Skip to main content

rustc_attr_parsing/
interface.rs

1//! API for other crates to parse attributes themselves.
2use std::convert::identity;
3#[cfg(debug_assertions)]
4use std::sync::atomic::{AtomicBool, Ordering};
5
6use rustc_ast as ast;
7use rustc_ast::token::DocFragmentKind;
8use rustc_ast::{AttrStyle, CRATE_NODE_ID, NodeId, Safety};
9use rustc_data_structures::sync::{DynSend, DynSync};
10use rustc_errors::{Diag, DiagCtxtHandle, Diagnostic, Level, MultiSpan};
11use rustc_feature::{BUILTIN_ATTRIBUTE_MAP, Features};
12use rustc_hir::attrs::AttributeKind;
13use rustc_hir::{AttrArgs, AttrItem, AttrPath, Attribute, HashIgnoredAttrId, Target};
14use rustc_lint_defs::RegisteredTools;
15use rustc_session::Session;
16use rustc_session::lint::LintId;
17use rustc_span::{DUMMY_SP, ErrorGuaranteed, Span, Symbol, sym};
18
19use crate::attributes::AttributeSafety;
20use crate::context::{
21    ATTRIBUTE_PARSERS, AcceptContext, FinalizeContext, FinalizeFn, SharedContext,
22};
23use crate::parser::{AllowExprMetavar, ArgParser, PathParser, RefPathParser};
24use crate::session_diagnostics::ParsedDescription;
25use crate::synthetic::SyntheticAttrState;
26use crate::{AttributeTemplate, OmitDoc, ShouldEmit};
27
28pub struct EmitAttribute(
29    pub  Box<
30        dyn for<'a> FnOnce(DiagCtxtHandle<'a>, Level, &Session) -> Diag<'a, ()>
31            + DynSend
32            + DynSync
33            + 'static,
34    >,
35);
36
37/// Context created once, for example as part of the ast lowering
38/// context, through which all attributes can be lowered.
39pub struct AttributeParser<'sess> {
40    pub(crate) tools: Option<&'sess RegisteredTools>,
41    pub(crate) features: Option<&'sess Features>,
42    pub(crate) sess: &'sess Session,
43    pub(crate) should_emit: ShouldEmit,
44
45    /// *Only* parse attributes with this symbol.
46    ///
47    /// Used in cases where we want the lowering infrastructure for parse just a single attribute.
48    parse_only: Option<&'static [Symbol]>,
49}
50
51impl<'sess> AttributeParser<'sess> {
52    /// This method allows you to parse attributes *before* you have access to features or tools.
53    /// One example where this is necessary, is to parse `feature` attributes themselves for
54    /// example.
55    ///
56    /// Try to use this as little as possible. Attributes *should* be lowered during
57    /// `rustc_ast_lowering`. Some attributes require access to features to parse, which would
58    /// crash if you tried to do so through [`parse_limited`](Self::parse_limited).
59    ///
60    /// To make sure use is limited, supply a `Symbol` you'd like to parse. Only attributes with
61    /// that symbol are picked out of the list of instructions and parsed. Those are returned.
62    ///
63    /// No diagnostics will be emitted when parsing limited. Lints are not emitted at all, while
64    /// errors will be emitted as a delayed bugs. in other words, we *expect* attributes parsed
65    /// with `parse_limited` to be reparsed later during ast lowering where we *do* emit the errors
66    ///
67    /// Due to this function not taking in `RegisteredTools`, *do not* use this for parsing any lint attributes
68    pub fn parse_limited(
69        sess: &'sess Session,
70        attrs: &[ast::Attribute],
71        sym: &'static [Symbol],
72    ) -> Option<Attribute> {
73        Self::parse_limited_should_emit(
74            sess,
75            attrs,
76            sym,
77            // Because we're not emitting warnings/errors, the target should not matter
78            DUMMY_SP,
79            CRATE_NODE_ID,
80            Target::Crate,
81            None,
82            ShouldEmit::Nothing,
83        )
84    }
85
86    /// This does the same as `parse_limited`, except it has a `should_emit` parameter which allows it to emit errors.
87    /// Usually you want `parse_limited`, which emits no errors.
88    ///
89    /// Due to this function not taking in `RegisteredTools`, *do not* use this for parsing any lint attributes
90    pub fn parse_limited_should_emit(
91        sess: &'sess Session,
92        attrs: &[ast::Attribute],
93        sym: &'static [Symbol],
94        target_span: Span,
95        target_node_id: NodeId,
96        target: Target,
97        features: Option<&'sess Features>,
98        should_emit: ShouldEmit,
99    ) -> Option<Attribute> {
100        let mut parsed = Self::parse_limited_all(
101            sess,
102            attrs,
103            Some(sym),
104            target,
105            target_span,
106            target_node_id,
107            features,
108            should_emit,
109            None,
110        );
111        if !(parsed.len() <= 1) {
    ::core::panicking::panic("assertion failed: parsed.len() <= 1")
};assert!(parsed.len() <= 1);
112        parsed.pop()
113    }
114
115    /// This method allows you to parse a list of attributes *before* `rustc_ast_lowering`.
116    /// This can be used for attributes that would be removed before `rustc_ast_lowering`, such as attributes on macro calls.
117    ///
118    /// Try to use this as little as possible. Attributes *should* be lowered during
119    /// `rustc_ast_lowering`. Some attributes require access to features to parse, which would
120    /// crash if you tried to do so through [`parse_limited_all`](Self::parse_limited_all).
121    /// Therefore, if `parse_only` is None, then features *must* be provided.
122    pub fn parse_limited_all(
123        sess: &'sess Session,
124        attrs: &[ast::Attribute],
125        parse_only: Option<&'static [Symbol]>,
126        target: Target,
127        target_span: Span,
128        target_node_id: NodeId,
129        features: Option<&'sess Features>,
130        should_emit: ShouldEmit,
131        tools: Option<&'sess RegisteredTools>,
132    ) -> Vec<Attribute> {
133        let mut p = Self { features, tools, parse_only, sess, should_emit };
134        p.parse_attribute_list(
135            attrs,
136            target_span,
137            target,
138            OmitDoc::Skip,
139            std::convert::identity,
140            |lint_id, span, kind| {
141                sess.psess.dyn_buffer_lint_sess(lint_id.lint, span, target_node_id, kind.0)
142            },
143        )
144    }
145
146    /// This method parses a single attribute, using `parse_fn`.
147    /// This is useful if you already know what exact attribute this is, and want to parse it.
148    pub fn parse_single<T>(
149        sess: &'sess Session,
150        attr: &ast::Attribute,
151        target_span: Span,
152        target_node_id: NodeId,
153        target: Target,
154        features: Option<&'sess Features>,
155        emit_errors: ShouldEmit,
156        parse_fn: fn(cx: &mut AcceptContext<'_, '_>, item: &ArgParser) -> Option<T>,
157        template: &AttributeTemplate,
158        allow_expr_metavar: AllowExprMetavar,
159        expected_safety: AttributeSafety,
160    ) -> Option<T> {
161        let attr_item = attr.get_normal_item();
162        let parts = attr_item.path.segments.iter().map(|seg| seg.ident.name).collect::<Vec<_>>();
163
164        let path = AttrPath::from_ast(&attr_item.path, identity);
165        let args = ArgParser::from_attr_args(
166            &attr_item.args,
167            &parts,
168            &sess.psess,
169            emit_errors,
170            allow_expr_metavar,
171        )?;
172        Self::parse_single_args(
173            sess,
174            attr.span,
175            attr_item.span,
176            attr.style,
177            path,
178            Some(attr_item.unsafety),
179            expected_safety,
180            ParsedDescription::Attribute,
181            target_span,
182            target_node_id,
183            target,
184            features,
185            emit_errors,
186            &args,
187            parse_fn,
188            template,
189        )
190    }
191
192    /// This method is equivalent to `parse_single`, but parses arguments using `parse_fn` using manually created `args`.
193    /// This is useful when you want to parse other things than attributes using attribute parsers.
194    pub fn parse_single_args<T, I>(
195        sess: &'sess Session,
196        attr_span: Span,
197        inner_span: Span,
198        attr_style: AttrStyle,
199        attr_path: AttrPath,
200        attr_safety: Option<Safety>,
201        expected_safety: AttributeSafety,
202        parsed_description: ParsedDescription,
203        target_span: Span,
204        target_node_id: NodeId,
205        target: Target,
206        features: Option<&'sess Features>,
207        should_emit: ShouldEmit,
208        args: &I,
209        parse_fn: fn(cx: &mut AcceptContext<'_, '_>, item: &I) -> T,
210        template: &AttributeTemplate,
211    ) -> T {
212        let mut parser = Self { features, tools: None, parse_only: None, sess, should_emit };
213        let mut emit_lint = |lint_id: LintId, span: MultiSpan, kind: EmitAttribute| {
214            sess.psess.dyn_buffer_lint_sess(lint_id.lint, span, target_node_id, kind.0)
215        };
216        if let Some(safety) = attr_safety {
217            parser.check_attribute_safety(
218                &attr_path,
219                inner_span,
220                safety,
221                expected_safety,
222                &mut emit_lint,
223            );
224        }
225        let mut cx: AcceptContext<'_, 'sess> = AcceptContext {
226            shared: SharedContext {
227                cx: &mut parser,
228                target_span,
229                target,
230                emit_lint: &mut emit_lint,
231                #[cfg(debug_assertions)]
232                has_lint_been_emitted: AtomicBool::new(false),
233            },
234            attr_span,
235            inner_span,
236            attr_style,
237            parsed_description,
238            template,
239            attr_safety: attr_safety.unwrap_or(Safety::Default),
240            attr_path,
241            #[cfg(debug_assertions)]
242            has_target_been_checked: false,
243        };
244        parse_fn(&mut cx, args)
245    }
246}
247
248impl<'sess> AttributeParser<'sess> {
249    pub fn new(
250        sess: &'sess Session,
251        features: &'sess Features,
252        tools: &'sess RegisteredTools,
253        should_emit: ShouldEmit,
254    ) -> Self {
255        Self { features: Some(features), tools: Some(tools), parse_only: None, sess, should_emit }
256    }
257
258    pub(crate) fn sess(&self) -> &'sess Session {
259        self.sess
260    }
261
262    pub(crate) fn features(&self) -> &'sess Features {
263        self.features.expect("features not available at this point in the compiler")
264    }
265
266    pub(crate) fn features_option(&self) -> Option<&'sess Features> {
267        self.features
268    }
269
270    pub(crate) fn dcx(&self) -> DiagCtxtHandle<'sess> {
271        self.sess().dcx()
272    }
273
274    pub(crate) fn emit_err(&self, diag: impl for<'x> Diagnostic<'x>) -> ErrorGuaranteed {
275        self.should_emit.emit_err(self.sess.dcx().create_err(diag))
276    }
277
278    /// Parse a list of attributes.
279    ///
280    /// `target_span` is the span of the thing this list of attributes is applied to,
281    /// and when `omit_doc` is set, doc attributes are filtered out.
282    pub fn parse_attribute_list(
283        &mut self,
284        attrs: &[ast::Attribute],
285        target_span: Span,
286        target: Target,
287        omit_doc: OmitDoc,
288        lower_span: impl Copy + Fn(Span) -> Span,
289        mut emit_lint: impl FnMut(LintId, MultiSpan, EmitAttribute),
290    ) -> Vec<Attribute> {
291        let mut attributes = Vec::new();
292        let mut attr_paths: Vec<RefPathParser<'_>> = Vec::new();
293        let mut synthetic_attr_state = SyntheticAttrState::default();
294
295        let mut finalizers: Vec<FinalizeFn> = Vec::with_capacity(attrs.len());
296
297        for attr in attrs {
298            // If we're only looking for a single attribute, skip all the ones we don't care about.
299            if let Some(expected) = self.parse_only {
300                if !attr.path_matches(expected) {
301                    continue;
302                }
303            }
304
305            // Sometimes, for example for `#![doc = include_str!("readme.md")]`,
306            // doc still contains a non-literal. You might say, when we're lowering attributes
307            // that's expanded right? But no, sometimes, when parsing attributes on macros,
308            // we already use the lowering logic and these are still there. So, when `omit_doc`
309            // is set we *also* want to ignore these.
310            let is_doc_attribute = attr.has_name(sym::doc);
311            if omit_doc == OmitDoc::Skip && is_doc_attribute {
312                continue;
313            }
314
315            let attr_span = lower_span(attr.span);
316            match &attr.kind {
317                ast::AttrKind::DocComment(comment_kind, symbol) => {
318                    if omit_doc == OmitDoc::Skip {
319                        continue;
320                    }
321
322                    attributes.push(Attribute::Parsed(AttributeKind::DocComment {
323                        style: attr.style,
324                        kind: DocFragmentKind::Sugared(*comment_kind),
325                        span: attr_span,
326                        comment: *symbol,
327                    }));
328                }
329                ast::AttrKind::Synthetic(synthetic) => {
330                    synthetic_attr_state.accept_synthetic_attr(attr_span, lower_span, synthetic);
331                }
332                ast::AttrKind::Normal(n) => {
333                    attr_paths.push(PathParser(&n.item.path));
334                    let attr_path = AttrPath::from_ast(&n.item.path, lower_span);
335                    let parts =
336                        n.item.path.segments.iter().map(|seg| seg.ident.name).collect::<Vec<_>>();
337                    let inner_span = lower_span(n.item.span);
338
339                    if let Some(accept) = ATTRIBUTE_PARSERS.accepters.get(parts.as_slice()) {
340                        self.check_attribute_safety(
341                            &attr_path,
342                            inner_span,
343                            n.item.unsafety,
344                            accept.safety,
345                            &mut emit_lint,
346                        );
347                        self.check_attribute_stability(&attr_path, attr_span, accept.stability);
348                        if let [part] = parts.as_slice() {
349                            if true {
    if !BUILTIN_ATTRIBUTE_MAP.contains(part) {
        ::core::panicking::panic("assertion failed: BUILTIN_ATTRIBUTE_MAP.contains(part)")
    };
};debug_assert!(BUILTIN_ATTRIBUTE_MAP.contains(part));
350                        }
351
352                        let Some(args) = ArgParser::from_attr_args(
353                            &n.item.args,
354                            &parts,
355                            &self.sess.psess,
356                            self.should_emit,
357                            AllowExprMetavar::No,
358                        ) else {
359                            continue;
360                        };
361
362                        // Special-case handling for `#[doc = "..."]`: if we go through with
363                        // `DocParser`, the order of doc comments will be messed up because `///`
364                        // doc comments are added into `attributes` whereas attributes parsed with
365                        // `DocParser` are added into `parsed_attributes` which are then appended
366                        // to `attributes`. So if you have:
367                        //
368                        // /// bla
369                        // #[doc = "a"]
370                        // /// blob
371                        //
372                        // You would get:
373                        //
374                        // bla
375                        // blob
376                        // a
377                        if is_doc_attribute
378                            && let ArgParser::NameValue(nv) = &args
379                            // If not a string key/value, it should emit an error, but to make
380                            // things simpler, it's handled in `DocParser` because it's simpler to
381                            // emit an error with `AcceptContext`.
382                            && let Some(comment) = nv.value_as_str()
383                        {
384                            attributes.push(Attribute::Parsed(AttributeKind::DocComment {
385                                style: attr.style,
386                                kind: DocFragmentKind::Raw(nv.value_span),
387                                span: attr_span,
388                                comment,
389                            }));
390                            continue;
391                        }
392
393                        let mut cx: AcceptContext<'_, 'sess> = AcceptContext {
394                            shared: SharedContext {
395                                cx: self,
396                                target_span,
397                                target,
398                                emit_lint: &mut emit_lint,
399                                #[cfg(debug_assertions)]
400                                has_lint_been_emitted: AtomicBool::new(false),
401                            },
402                            attr_span,
403                            inner_span,
404                            attr_style: attr.style,
405                            parsed_description: ParsedDescription::Attribute,
406                            template: &accept.template,
407                            attr_safety: n.item.unsafety,
408                            attr_path: attr_path.clone(),
409                            #[cfg(debug_assertions)]
410                            has_target_been_checked: false,
411                        };
412
413                        (accept.accept_fn)(&mut cx, &args);
414                        finalizers.push(accept.finalizer);
415
416                        Self::check_target(&accept.allowed_targets, "", &mut cx);
417                        #[cfg(debug_assertions)]
418                        if !cx.shared.has_lint_been_emitted.load(Ordering::Relaxed) {
419                            cx.shared.cx.check_args_used(attr, &args)
420                        }
421                    } else {
422                        let attr = AttrItem {
423                            path: attr_path.clone(),
424                            args: self.lower_attr_args(&n.item.args, lower_span),
425                            id: HashIgnoredAttrId { attr_id: attr.id },
426                            style: attr.style,
427                            span: attr_span,
428                        };
429
430                        self.check_attribute_safety(
431                            &attr_path,
432                            inner_span,
433                            n.item.unsafety,
434                            AttributeSafety::Normal,
435                            &mut emit_lint,
436                        );
437
438                        if !#[allow(non_exhaustive_omitted_patterns)] match self.should_emit {
    ShouldEmit::Nothing => true,
    _ => false,
}matches!(self.should_emit, ShouldEmit::Nothing)
439                            && target == Target::Crate
440                        {
441                            self.check_invalid_crate_level_attr_item(&attr, inner_span);
442                        }
443
444                        attributes.push(Attribute::Unparsed(Box::new(attr)));
445                    };
446                }
447            }
448        }
449
450        synthetic_attr_state.finalize_synthetic_attrs(&mut attributes);
451        for f in &finalizers {
452            if let Some(attr) = f(&mut FinalizeContext {
453                shared: SharedContext {
454                    cx: self,
455                    target_span,
456                    target,
457                    emit_lint: &mut emit_lint,
458                    #[cfg(debug_assertions)]
459                    has_lint_been_emitted: AtomicBool::new(false),
460                },
461                all_attrs: &attr_paths,
462            }) {
463                attributes.push(Attribute::Parsed(attr));
464            }
465        }
466
467        if !#[allow(non_exhaustive_omitted_patterns)] match self.should_emit {
    ShouldEmit::Nothing => true,
    _ => false,
}matches!(self.should_emit, ShouldEmit::Nothing) && target == Target::WherePredicate {
468            self.check_invalid_where_predicate_attrs(attributes.iter());
469        }
470
471        attributes
472    }
473
474    #[cfg(debug_assertions)]
475    /// Checks whether all `ArgParser`s were observed by an attribute parser at least once
476    /// This check exists because otherwise it is too easy to accidentally ignore the arguments of an attribute
477    fn check_args_used(&self, attr: &ast::Attribute, args: &ArgParser) {
478        if let ArgParser::List(items) = args {
479            for item in items.mixed() {
480                if let crate::parser::MetaItemOrLitParser::MetaItemParser(item) = item {
481                    if !item.are_args_checked() {
482                        self.dcx().span_delayed_bug(
483                            item.span(),
484                            "attribute args were not properly checked",
485                        );
486                        return;
487                    }
488                    self.check_args_used(attr, item.args());
489                }
490            }
491        }
492    }
493
494    /// Returns whether there is a parser for an attribute with this name
495    pub fn is_parsed_attribute(path: &[Symbol]) -> bool {
496        /// The list of attributes that are parsed attributes,
497        /// even though they don't have a parser in `Late::parsers()`
498        const SPECIAL_ATTRIBUTES: &[&[Symbol]] = &[
499            // Cfg attrs are removed after being converted into synthetic attrs and don't need to
500            // be in the parser list.
501            &[sym::cfg],
502            &[sym::cfg_attr],
503        ];
504
505        ATTRIBUTE_PARSERS.accepters.contains_key(path) || SPECIAL_ATTRIBUTES.contains(&path)
506    }
507
508    fn lower_attr_args(&self, args: &ast::AttrArgs, lower_span: impl Fn(Span) -> Span) -> AttrArgs {
509        match args {
510            ast::AttrArgs::Empty => AttrArgs::Empty,
511            ast::AttrArgs::Delimited(args) => AttrArgs::Delimited(args.clone()),
512            // This is an inert key-value attribute - it will never be visible to macros
513            // after it gets lowered to HIR. Therefore, we can extract literals to handle
514            // nonterminals in `#[doc]` (e.g. `#[doc = $e]`).
515            ast::AttrArgs::Eq { eq_span, expr } => {
516                // In valid code the value always ends up as a single literal. Otherwise, a dummy
517                // literal suffices because the error is handled elsewhere.
518                let lit = if let ast::ExprKind::Lit(token_lit) = expr.kind
519                    && let Ok(lit) =
520                        ast::MetaItemLit::from_token_lit(token_lit, lower_span(expr.span))
521                {
522                    lit
523                } else {
524                    let guar = self.dcx().span_delayed_bug(
525                        args.span().unwrap_or(DUMMY_SP),
526                        "expr in place where literal is expected (builtin attr parsing)",
527                    );
528                    ast::MetaItemLit {
529                        symbol: sym::dummy,
530                        suffix: None,
531                        kind: ast::LitKind::Err(guar),
532                        span: DUMMY_SP,
533                    }
534                };
535                AttrArgs::Eq { eq_span: lower_span(*eq_span), expr: lit }
536            }
537        }
538    }
539}