summaryrefslogtreecommitdiffstats
path: root/compiler/rustc_builtin_macros/src/concat_idents.rs
blob: ee56d45c9c826eb85c79865d34ba3710ece3685f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
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, *};
use rustc_span::symbol::{Ident, Symbol};
use rustc_span::Span;

use crate::errors;

pub fn expand_concat_idents<'cx>(
    cx: &'cx mut ExtCtxt<'_>,
    sp: Span,
    tts: TokenStream,
) -> Box<dyn base::MacResult + 'cx> {
    if tts.is_empty() {
        cx.emit_err(errors::ConcatIdentsMissingArgs { span: sp });
        return DummyResult::any(sp);
    }

    let mut res_str = String::new();
    for (i, e) in tts.trees().enumerate() {
        if i & 1 == 1 {
            match e {
                TokenTree::Token(Token { kind: token::Comma, .. }, _) => {}
                _ => {
                    cx.emit_err(errors::ConcatIdentsMissingComma { span: sp });
                    return DummyResult::any(sp);
                }
            }
        } else {
            if let TokenTree::Token(token, _) = e {
                if let Some((ident, _)) = token.ident() {
                    res_str.push_str(ident.name.as_str());
                    continue;
                }
            }

            cx.emit_err(errors::ConcatIdentsIdentArgs { span: sp });
            return DummyResult::any(sp);
        }
    }

    let ident = Ident::new(Symbol::intern(&res_str), cx.with_call_site_ctxt(sp));

    struct ConcatIdentsResult {
        ident: Ident,
    }

    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)),
                span: self.ident.span,
                attrs: ast::AttrVec::new(),
                tokens: None,
            }))
        }

        fn make_ty(self: Box<Self>) -> Option<P<ast::Ty>> {
            Some(P(ast::Ty {
                id: ast::DUMMY_NODE_ID,
                kind: ast::TyKind::Path(None, ast::Path::from_ident(self.ident)),
                span: self.ident.span,
                tokens: None,
            }))
        }
    }

    Box::new(ConcatIdentsResult { ident })
}