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