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