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