]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_builtin_macros/src/concat.rs
Insert whitespace to avoid ident concatenation in suggestion
[rust.git] / compiler / rustc_builtin_macros / src / concat.rs
1 use rustc_ast as ast;
2 use rustc_ast::tokenstream::TokenStream;
3 use rustc_expand::base::{self, DummyResult};
4 use rustc_session::errors::report_lit_error;
5 use rustc_span::symbol::Symbol;
6
7 pub fn expand_concat(
8     cx: &mut base::ExtCtxt<'_>,
9     sp: rustc_span::Span,
10     tts: TokenStream,
11 ) -> Box<dyn base::MacResult + 'static> {
12     let Some(es) = base::get_exprs_from_tts(cx, tts) else {
13         return DummyResult::any(sp);
14     };
15     let mut accumulator = String::new();
16     let mut missing_literal = vec![];
17     let mut has_errors = false;
18     for e in es {
19         match e.kind {
20             ast::ExprKind::Lit(token_lit) => match ast::LitKind::from_token_lit(token_lit) {
21                 Ok(ast::LitKind::Str(s, _) | ast::LitKind::Float(s, _)) => {
22                     accumulator.push_str(s.as_str());
23                 }
24                 Ok(ast::LitKind::Char(c)) => {
25                     accumulator.push(c);
26                 }
27                 Ok(ast::LitKind::Int(i, _)) => {
28                     accumulator.push_str(&i.to_string());
29                 }
30                 Ok(ast::LitKind::Bool(b)) => {
31                     accumulator.push_str(&b.to_string());
32                 }
33                 Ok(ast::LitKind::Byte(..) | ast::LitKind::ByteStr(..)) => {
34                     cx.span_err(e.span, "cannot concatenate a byte string literal");
35                     has_errors = true;
36                 }
37                 Ok(ast::LitKind::Err) => {
38                     has_errors = true;
39                 }
40                 Err(err) => {
41                     report_lit_error(&cx.sess.parse_sess, err, token_lit, e.span);
42                     has_errors = true;
43                 }
44             },
45             ast::ExprKind::IncludedBytes(..) => {
46                 cx.span_err(e.span, "cannot concatenate a byte string literal")
47             }
48             ast::ExprKind::Err => {
49                 has_errors = true;
50             }
51             _ => {
52                 missing_literal.push(e.span);
53             }
54         }
55     }
56     if !missing_literal.is_empty() {
57         let mut err = cx.struct_span_err(missing_literal, "expected a literal");
58         err.note("only literals (like `\"foo\"`, `42` and `3.14`) can be passed to `concat!()`");
59         err.emit();
60         return DummyResult::any(sp);
61     } else if has_errors {
62         return DummyResult::any(sp);
63     }
64     let sp = cx.with_def_site_ctxt(sp);
65     base::MacEager::expr(cx.expr_str(sp, Symbol::intern(&accumulator)))
66 }