Skip to main content

rustc_builtin_macros/
util.rs

1use rustc_ast::tokenstream::TokenStream;
2use rustc_ast::{
3    self as ast, AttrStyle, Attribute, GenericArg, GenericParam, GenericParamKind, MetaItem, attr,
4    token,
5};
6use rustc_attr_parsing::{AttributeTemplate, DuplicateAttribute, validate_attr};
7use rustc_errors::{Applicability, Diag, ErrorGuaranteed};
8use rustc_expand::base::{Annotatable, ExpandResult, ExtCtxt};
9use rustc_expand::expand::AstFragment;
10use rustc_lint_defs::builtin::DUPLICATE_MACRO_ATTRIBUTES;
11use rustc_parse::{exp, parser};
12use rustc_session::diagnostics::report_lit_error;
13use rustc_span::{BytePos, Span, Symbol};
14
15use crate::diagnostics;
16
17pub(crate) fn check_builtin_macro_attribute(ecx: &ExtCtxt<'_>, meta_item: &MetaItem, name: Symbol) {
18    // All the built-in macro attributes are "words" at the moment.
19    let template = AttributeTemplate { word: true, ..Default::default() };
20    validate_attr::check_builtin_meta_item(
21        &ecx.sess.psess,
22        meta_item,
23        AttrStyle::Outer,
24        name,
25        template,
26        true,
27    );
28}
29
30/// Emit a warning if the item is annotated with the given attribute. This is used to diagnose when
31/// an attribute may have been mistakenly duplicated.
32pub(crate) fn warn_on_duplicate_attribute(
33    ecx: &ExtCtxt<'_>,
34    item: &Annotatable,
35    span: Span,
36    name: Symbol,
37) {
38    let attrs: &[Attribute] = match item {
39        Annotatable::Item(item) => &item.attrs,
40        Annotatable::AssocItem(item, _) => &item.attrs,
41        Annotatable::ForeignItem(item) => &item.attrs,
42        Annotatable::Expr(expr) => &expr.attrs,
43        Annotatable::Arm(arm) => &arm.attrs,
44        Annotatable::ExprField(field) => &field.attrs,
45        Annotatable::PatField(field) => &field.attrs,
46        Annotatable::GenericParam(param) => &param.attrs,
47        Annotatable::Param(param) => &param.attrs,
48        Annotatable::FieldDef(def) => &def.attrs,
49        Annotatable::Variant(variant) => &variant.attrs,
50        _ => return,
51    };
52    if let Some(attr) = attr::find_by_name(attrs, name) {
53        ecx.psess().buffer_lint(
54            DUPLICATE_MACRO_ATTRIBUTES,
55            attr.span,
56            ecx.current_expansion.lint_node_id,
57            DuplicateAttribute { this: attr.span, other: span, name, warning: false },
58        );
59    }
60}
61
62/// `Ok` represents successfully retrieving the string literal at the correct
63/// position, e.g., `println("abc")`.
64pub(crate) type ExprToSpannedStringResult<'a> = Result<ExprToSpannedString, UnexpectedExprKind<'a>>;
65
66pub(crate) struct ExprToSpannedString {
67    pub symbol: Symbol,
68    pub style: ast::StrStyle,
69    pub span: Span,
70    /// The raw string literal, with no escaping or processing.
71    ///
72    /// Generally only useful for lints that care about the raw bytes the user wrote.
73    pub uncooked_symbol: (ast::token::LitKind, Symbol),
74}
75
76/// - `Ok` is returned when the conversion to a string literal is unsuccessful,
77/// but another type of expression is obtained instead.
78/// - `Err` is returned when the conversion process fails.
79type UnexpectedExprKind<'a> = Result<(Diag<'a>, bool /* has_suggestions */), ErrorGuaranteed>;
80
81/// Extracts a string literal from the macro expanded version of `expr`,
82/// returning a diagnostic error of `err_msg` if `expr` is not a string literal.
83/// The returned bool indicates whether an applicable suggestion has already been
84/// added to the diagnostic to avoid emitting multiple suggestions. `Err(Err(ErrorGuaranteed))`
85/// indicates that an ast error was encountered.
86pub(crate) fn expr_to_spanned_string<'a>(
87    cx: &'a mut ExtCtxt<'_>,
88    expr: Box<ast::Expr>,
89    err_msg: &'static str,
90) -> ExpandResult<ExprToSpannedStringResult<'a>, ()> {
91    if !cx.force_mode
92        && let ast::ExprKind::MacCall(m) = &expr.kind
93        && cx.resolver.macro_accessible(cx.current_expansion.id, &m.path).is_err()
94    {
95        return ExpandResult::Retry(());
96    }
97
98    // Perform eager expansion on the expression.
99    // We want to be able to handle e.g., `concat!("foo", "bar")`.
100    let expr = cx.expander().fully_expand_fragment(AstFragment::Expr(expr)).make_expr();
101
102    ExpandResult::Ready(Err(match expr.kind {
103        ast::ExprKind::Lit(token_lit) => match ast::LitKind::from_token_lit(token_lit) {
104            Ok(ast::LitKind::Str(s, style)) => {
105                return ExpandResult::Ready(Ok(ExprToSpannedString {
106                    symbol: s,
107                    style,
108                    span: expr.span,
109                    uncooked_symbol: (token_lit.kind, token_lit.symbol),
110                }));
111            }
112            Ok(ast::LitKind::ByteStr(..)) => {
113                let mut err = cx.dcx().struct_span_err(expr.span, err_msg);
114                let span = expr.span.shrink_to_lo();
115                err.span_suggestion_short(
116                    span.with_hi(span.lo() + BytePos(1)),
117                    "consider removing the leading `b`",
118                    "",
119                    Applicability::MaybeIncorrect,
120                );
121                Ok((err, true))
122            }
123            Ok(ast::LitKind::Err(guar)) => Err(guar),
124            Err(err) => Err(report_lit_error(&cx.sess.psess, err, token_lit, expr.span)),
125            _ => Ok((cx.dcx().struct_span_err(expr.span, err_msg), false)),
126        },
127        ast::ExprKind::Err(guar) => Err(guar),
128        ast::ExprKind::Dummy => {
129            cx.dcx().span_bug(expr.span, "tried to get a string literal from `ExprKind::Dummy`")
130        }
131        _ => Ok((cx.dcx().struct_span_err(expr.span, err_msg), false)),
132    }))
133}
134
135/// Extracts a string literal from the macro expanded version of `expr`,
136/// emitting `err_msg` if `expr` is not a string literal. This does not stop
137/// compilation on error, merely emits a non-fatal error and returns `Err`.
138pub(crate) fn expr_to_string(
139    cx: &mut ExtCtxt<'_>,
140    expr: Box<ast::Expr>,
141    err_msg: &'static str,
142) -> ExpandResult<Result<(Symbol, ast::StrStyle), ErrorGuaranteed>, ()> {
143    expr_to_spanned_string(cx, expr, err_msg).map(|res| {
144        res.map_err(|err| match err {
145            Ok((err, _)) => err.emit_err(),
146            Err(guar) => guar,
147        })
148        .map(|ExprToSpannedString { symbol, style, .. }| (symbol, style))
149    })
150}
151
152/// Non-fatally assert that `tts` is empty. Note that this function
153/// returns even when `tts` is non-empty, macros that *need* to stop
154/// compilation should call `cx.diagnostic().abort_if_errors()`
155/// (this should be done as rarely as possible).
156pub(crate) fn check_zero_tts(cx: &ExtCtxt<'_>, span: Span, tts: TokenStream, name: &str) {
157    if !tts.is_empty() {
158        cx.dcx().emit_err(diagnostics::TakesNoArguments { span, name });
159    }
160}
161
162/// Parse an expression. On error, emit it, advancing to `Eof`, and return `Err`.
163pub(crate) fn parse_expr(p: &mut parser::Parser<'_>) -> Result<Box<ast::Expr>, ErrorGuaranteed> {
164    let guar = match p.parse_expr() {
165        Ok(expr) => return Ok(expr),
166        Err(err) => err.emit_err(),
167    };
168    while p.token != token::Eof {
169        p.bump();
170    }
171    Err(guar)
172}
173
174/// Interpreting `tts` as a comma-separated sequence of expressions,
175/// expect exactly one string literal, or emit an error and return `Err`.
176pub(crate) fn get_single_str_from_tts(
177    cx: &mut ExtCtxt<'_>,
178    span: Span,
179    tts: TokenStream,
180    name: &str,
181) -> ExpandResult<Result<Symbol, ErrorGuaranteed>, ()> {
182    get_single_str_spanned_from_tts(cx, span, tts, name).map(|res| res.map(|(s, _)| s))
183}
184
185pub(crate) fn get_single_str_spanned_from_tts(
186    cx: &mut ExtCtxt<'_>,
187    span: Span,
188    tts: TokenStream,
189    name: &str,
190) -> ExpandResult<Result<(Symbol, Span), ErrorGuaranteed>, ()> {
191    let ExpandResult::Ready(ret) = get_single_expr_from_tts(cx, span, tts, name) else {
192        return ExpandResult::Retry(());
193    };
194    let ret = match ret {
195        Ok(ret) => ret,
196        Err(e) => return ExpandResult::Ready(Err(e)),
197    };
198    expr_to_spanned_string(cx, ret, "argument must be a string literal").map(|res| {
199        res.map_err(|err| match err {
200            Ok((err, _)) => err.emit_err(),
201            Err(guar) => guar,
202        })
203        .map(|ExprToSpannedString { symbol, span, .. }| (symbol, span))
204    })
205}
206
207/// Interpreting `tts` as a comma-separated sequence of expressions,
208/// expect exactly one expression, or emit an error and return `Err`.
209pub(crate) fn get_single_expr_from_tts(
210    cx: &mut ExtCtxt<'_>,
211    span: Span,
212    tts: TokenStream,
213    name: &str,
214) -> ExpandResult<Result<Box<ast::Expr>, ErrorGuaranteed>, ()> {
215    let mut p = cx.new_parser_from_tts(tts);
216    if p.token == token::Eof {
217        let guar = cx.dcx().emit_err(diagnostics::OnlyOneArgument { span, name });
218        return ExpandResult::Ready(Err(guar));
219    }
220    let ret = match parse_expr(&mut p) {
221        Ok(ret) => ret,
222        Err(guar) => return ExpandResult::Ready(Err(guar)),
223    };
224    let _ = p.eat(::rustc_parse::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Comma,
    token_type: ::rustc_parse::parser::token_type::TokenType::Comma,
}exp!(Comma));
225
226    if p.token != token::Eof {
227        cx.dcx().emit_err(diagnostics::OnlyOneArgument { span, name });
228    }
229    ExpandResult::Ready(Ok(ret))
230}
231
232/// Extracts comma-separated expressions from `tts`.
233/// On error, emit it, and return `Err`.
234pub(crate) fn get_exprs_from_tts(
235    cx: &mut ExtCtxt<'_>,
236    tts: TokenStream,
237) -> ExpandResult<Result<Vec<Box<ast::Expr>>, ErrorGuaranteed>, ()> {
238    let mut p = cx.new_parser_from_tts(tts);
239    let mut es = Vec::new();
240    while p.token != token::Eof {
241        let expr = match parse_expr(&mut p) {
242            Ok(expr) => expr,
243            Err(guar) => return ExpandResult::Ready(Err(guar)),
244        };
245        if !cx.force_mode
246            && let ast::ExprKind::MacCall(m) = &expr.kind
247            && cx.resolver.macro_accessible(cx.current_expansion.id, &m.path).is_err()
248        {
249            return ExpandResult::Retry(());
250        }
251
252        // Perform eager expansion on the expression.
253        // We want to be able to handle e.g., `concat!("foo", "bar")`.
254        let expr = cx.expander().fully_expand_fragment(AstFragment::Expr(expr)).make_expr();
255
256        es.push(expr);
257        if p.eat(::rustc_parse::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Comma,
    token_type: ::rustc_parse::parser::token_type::TokenType::Comma,
}exp!(Comma)) {
258            continue;
259        }
260        if p.token != token::Eof {
261            let guar = cx.dcx().emit_err(diagnostics::ExpectedCommaInList { span: p.token.span });
262            return ExpandResult::Ready(Err(guar));
263        }
264    }
265    ExpandResult::Ready(Ok(es))
266}
267
268pub(crate) fn generic_param_to_arg(cx: &ExtCtxt<'_>, p: &GenericParam, span: Span) -> GenericArg {
269    match p.kind {
270        GenericParamKind::Lifetime => GenericArg::Lifetime(cx.lifetime(span, p.ident)),
271        GenericParamKind::Type { .. } => GenericArg::Type(cx.ty_ident(span, p.ident)),
272        GenericParamKind::Const { .. } => GenericArg::Const(cx.const_ident(span, p.ident)),
273    }
274}