rust/src/test/run-pass-fulldeps/auxiliary/cond_plugin.rs

48 lines
1.5 KiB
Rust
Raw Normal View History

2016-08-04 14:20:01 -05:00
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// no-prefer-dynamic
2016-08-04 14:20:01 -05:00
#![crate_type = "proc-macro"]
2017-06-21 14:42:44 -05:00
#![feature(proc_macro)]
2016-08-04 14:20:01 -05:00
extern crate proc_macro;
2016-08-04 14:20:01 -05:00
2017-06-04 20:41:33 -05:00
use proc_macro::{TokenStream, TokenNode, quote};
2016-08-04 14:20:01 -05:00
#[proc_macro]
pub fn cond(input: TokenStream) -> TokenStream {
2017-01-17 21:27:09 -06:00
let mut conds = Vec::new();
let mut input = input.into_iter().peekable();
2017-01-17 21:27:09 -06:00
while let Some(tree) = input.next() {
let cond = match tree.kind {
2017-06-21 14:42:44 -05:00
TokenNode::Group(_, cond) => cond,
2017-01-17 21:27:09 -06:00
_ => panic!("Invalid input"),
};
let mut cond_trees = cond.clone().into_iter();
let test = cond_trees.next().expect("Unexpected empty condition in `cond!`");
let rhs = cond_trees.collect::<TokenStream>();
2017-01-17 21:27:09 -06:00
if rhs.is_empty() {
panic!("Invalid macro usage in cond: {}", cond);
}
let is_else = match test.kind {
2017-06-21 14:42:44 -05:00
TokenNode::Term(word) => word.as_str() == "else",
2017-01-17 21:27:09 -06:00
_ => false,
};
conds.push(if is_else || input.peek().is_none() {
2017-03-14 17:04:46 -05:00
quote!({ $rhs })
2017-01-17 21:27:09 -06:00
} else {
2017-03-14 17:04:46 -05:00
quote!(if $test { $rhs } else)
2017-01-17 21:27:09 -06:00
});
}
conds.into_iter().collect()
2016-08-04 14:20:01 -05:00
}