rust/compiler/rustc_builtin_macros/src/concat_idents.rs

70 lines
2.1 KiB
Rust
Raw Normal View History

2020-04-27 17:56:11 +00:00
use rustc_ast as ast;
use rustc_ast::ptr::P;
use rustc_ast::token::{self, Token};
use rustc_ast::tokenstream::{TokenStream, TokenTree};
use rustc_expand::base::{self, *};
2020-04-19 11:00:18 +00:00
use rustc_span::symbol::{Ident, Symbol};
use rustc_span::Span;
2019-12-22 22:42:04 +00:00
pub fn expand_concat_idents<'cx>(
cx: &'cx mut ExtCtxt<'_>,
sp: Span,
tts: TokenStream,
) -> Box<dyn base::MacResult + 'cx> {
if tts.is_empty() {
cx.span_err(sp, "concat_idents! takes 1 or more arguments.");
return DummyResult::any(sp);
}
let mut res_str = String::new();
for (i, e) in tts.into_trees().enumerate() {
if i & 1 == 1 {
match e {
TokenTree::Token(Token { kind: token::Comma, .. }) => {}
_ => {
cx.span_err(sp, "concat_idents! expecting comma.");
return DummyResult::any(sp);
2016-06-06 14:52:48 +00:00
}
}
} else {
match e {
2019-12-22 22:42:04 +00:00
TokenTree::Token(Token { kind: token::Ident(name, _), .. }) => {
res_str.push_str(&name.as_str())
}
_ => {
cx.span_err(sp, "concat_idents! requires ident args.");
return DummyResult::any(sp);
2016-06-06 14:52:48 +00:00
}
}
}
}
2020-04-19 11:00:18 +00:00
let ident = Ident::new(Symbol::intern(&res_str), cx.with_call_site_ctxt(sp));
2018-03-18 13:47:09 +00:00
2019-12-22 22:42:04 +00:00
struct ConcatIdentsResult {
2020-04-19 11:00:18 +00:00
ident: Ident,
2019-12-22 22:42:04 +00:00
}
2018-03-18 13:47:09 +00:00
impl base::MacResult for ConcatIdentsResult {
fn make_expr(self: Box<Self>) -> Option<P<ast::Expr>> {
Some(P(ast::Expr {
id: ast::DUMMY_NODE_ID,
kind: ast::ExprKind::Path(None, ast::Path::from_ident(self.ident)),
2018-03-18 13:47:09 +00:00
span: self.ident.span,
2019-12-03 15:38:34 +00:00
attrs: ast::AttrVec::new(),
2020-05-19 20:56:20 +00:00
tokens: None,
}))
}
fn make_ty(self: Box<Self>) -> Option<P<ast::Ty>> {
Some(P(ast::Ty {
id: ast::DUMMY_NODE_ID,
2019-09-26 16:25:31 +00:00
kind: ast::TyKind::Path(None, ast::Path::from_ident(self.ident)),
2018-03-18 13:47:09 +00:00
span: self.ident.span,
}))
}
}
2018-03-18 13:47:09 +00:00
Box::new(ConcatIdentsResult { ident })
}