rustc_attr_parsing/
interface.rs

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