]> git.lizzy.rs Git - rust.git/blob - src/libsyntax_ext/concat.rs
Auto merge of #60840 - tmandry:preserve-scope-in-generator-mir, r=cramertj
[rust.git] / src / libsyntax_ext / concat.rs
1 use syntax::ast;
2 use syntax::ext::base;
3 use syntax::ext::build::AstBuilder;
4 use syntax::symbol::Symbol;
5 use syntax::tokenstream;
6
7 use std::string::String;
8
9 pub fn expand_syntax_ext(
10     cx: &mut base::ExtCtxt<'_>,
11     sp: syntax_pos::Span,
12     tts: &[tokenstream::TokenTree],
13 ) -> Box<dyn base::MacResult + 'static> {
14     let es = match base::get_exprs_from_tts(cx, sp, tts) {
15         Some(e) => e,
16         None => return base::DummyResult::expr(sp),
17     };
18     let mut accumulator = String::new();
19     let mut missing_literal = vec![];
20     let mut has_errors = false;
21     for e in es {
22         match e.node {
23             ast::ExprKind::Lit(ref lit) => match lit.node {
24                 ast::LitKind::Str(ref s, _)
25                 | ast::LitKind::Err(ref s)
26                 | ast::LitKind::Float(ref s, _)
27                 | ast::LitKind::FloatUnsuffixed(ref s) => {
28                     accumulator.push_str(&s.as_str());
29                 }
30                 ast::LitKind::Char(c) => {
31                     accumulator.push(c);
32                 }
33                 ast::LitKind::Int(i, ast::LitIntType::Unsigned(_))
34                 | ast::LitKind::Int(i, ast::LitIntType::Signed(_))
35                 | ast::LitKind::Int(i, ast::LitIntType::Unsuffixed) => {
36                     accumulator.push_str(&i.to_string());
37                 }
38                 ast::LitKind::Bool(b) => {
39                     accumulator.push_str(&b.to_string());
40                 }
41                 ast::LitKind::Byte(..) | ast::LitKind::ByteStr(..) => {
42                     cx.span_err(e.span, "cannot concatenate a byte string literal");
43                 }
44             },
45             ast::ExprKind::Err => {
46                 has_errors = true;
47             }
48             _ => {
49                 missing_literal.push(e.span);
50             }
51         }
52     }
53     if missing_literal.len() > 0 {
54         let mut err = cx.struct_span_err(missing_literal, "expected a literal");
55         err.note("only literals (like `\"foo\"`, `42` and `3.14`) can be passed to `concat!()`");
56         err.emit();
57         return base::DummyResult::expr(sp);
58     } else if has_errors {
59         return base::DummyResult::expr(sp);
60     }
61     let sp = sp.apply_mark(cx.current_expansion.mark);
62     base::MacEager::expr(cx.expr_str(sp, Symbol::intern(&accumulator)))
63 }