rustc_attr_parsing/
interface.rs

1use std::borrow::Cow;
2
3use rustc_ast as ast;
4use rustc_ast::NodeId;
5use rustc_errors::DiagCtxtHandle;
6use rustc_feature::{AttributeTemplate, Features};
7use rustc_hir::attrs::AttributeKind;
8use rustc_hir::lints::AttributeLint;
9use rustc_hir::{AttrArgs, AttrItem, AttrPath, Attribute, HashIgnoredAttrId, Target};
10use rustc_session::Session;
11use rustc_span::{DUMMY_SP, Span, Symbol, sym};
12
13use crate::context::{AcceptContext, FinalizeContext, SharedContext, Stage};
14use crate::parser::{ArgParser, MetaItemParser, PathParser};
15use crate::{Early, Late, OmitDoc, ShouldEmit};
16
17/// Context created once, for example as part of the ast lowering
18/// context, through which all attributes can be lowered.
19pub struct AttributeParser<'sess, S: Stage = Late> {
20    pub(crate) tools: Vec<Symbol>,
21    pub(crate) features: Option<&'sess Features>,
22    pub(crate) sess: &'sess Session,
23    pub(crate) stage: S,
24
25    /// *Only* parse attributes with this symbol.
26    ///
27    /// Used in cases where we want the lowering infrastructure for parse just a single attribute.
28    parse_only: Option<Symbol>,
29}
30
31impl<'sess> AttributeParser<'sess, Early> {
32    /// This method allows you to parse attributes *before* you have access to features or tools.
33    /// One example where this is necessary, is to parse `feature` attributes themselves for
34    /// example.
35    ///
36    /// Try to use this as little as possible. Attributes *should* be lowered during
37    /// `rustc_ast_lowering`. Some attributes require access to features to parse, which would
38    /// crash if you tried to do so through [`parse_limited`](Self::parse_limited).
39    ///
40    /// To make sure use is limited, supply a `Symbol` you'd like to parse. Only attributes with
41    /// that symbol are picked out of the list of instructions and parsed. Those are returned.
42    ///
43    /// No diagnostics will be emitted when parsing limited. Lints are not emitted at all, while
44    /// errors will be emitted as a delayed bugs. in other words, we *expect* attributes parsed
45    /// with `parse_limited` to be reparsed later during ast lowering where we *do* emit the errors
46    pub fn parse_limited(
47        sess: &'sess Session,
48        attrs: &[ast::Attribute],
49        sym: Symbol,
50        target_span: Span,
51        target_node_id: NodeId,
52        features: Option<&'sess Features>,
53    ) -> Option<Attribute> {
54        let mut parsed = Self::parse_limited_all(
55            sess,
56            attrs,
57            Some(sym),
58            Target::Crate, // Does not matter, we're not going to emit errors anyways
59            target_span,
60            target_node_id,
61            features,
62            ShouldEmit::Nothing,
63        );
64        assert!(parsed.len() <= 1);
65        parsed.pop()
66    }
67
68    pub fn parse_limited_all(
69        sess: &'sess Session,
70        attrs: &[ast::Attribute],
71        parse_only: Option<Symbol>,
72        target: Target,
73        target_span: Span,
74        target_node_id: NodeId,
75        features: Option<&'sess Features>,
76        emit_errors: ShouldEmit,
77    ) -> Vec<Attribute> {
78        let mut p =
79            Self { features, tools: Vec::new(), parse_only, sess, stage: Early { emit_errors } };
80        p.parse_attribute_list(
81            attrs,
82            target_span,
83            target_node_id,
84            target,
85            OmitDoc::Skip,
86            std::convert::identity,
87            |_lint| {
88                // FIXME: Can't emit lints here for now
89                // This branch can be hit when an attribute produces a warning during early parsing (such as attributes on macro calls)
90            },
91        )
92    }
93
94    pub fn parse_single<T>(
95        sess: &'sess Session,
96        attr: &ast::Attribute,
97        target_span: Span,
98        target_node_id: NodeId,
99        features: Option<&'sess Features>,
100        emit_errors: ShouldEmit,
101        parse_fn: fn(cx: &mut AcceptContext<'_, '_, Early>, item: &ArgParser<'_>) -> Option<T>,
102        template: &AttributeTemplate,
103    ) -> Option<T> {
104        let mut parser = Self {
105            features,
106            tools: Vec::new(),
107            parse_only: None,
108            sess,
109            stage: Early { emit_errors },
110        };
111        let ast::AttrKind::Normal(normal_attr) = &attr.kind else {
112            panic!("parse_single called on a doc attr")
113        };
114        let parts =
115            normal_attr.item.path.segments.iter().map(|seg| seg.ident.name).collect::<Vec<_>>();
116        let meta_parser = MetaItemParser::from_attr(normal_attr, &parts, &sess.psess, emit_errors)?;
117        let path = meta_parser.path();
118        let args = meta_parser.args();
119        let mut cx: AcceptContext<'_, 'sess, Early> = AcceptContext {
120            shared: SharedContext {
121                cx: &mut parser,
122                target_span,
123                target_id: target_node_id,
124                emit_lint: &mut |_lint| {
125                    panic!("can't emit lints here for now (nothing uses this atm)");
126                },
127            },
128            attr_span: attr.span,
129            attr_style: attr.style,
130            template,
131            attr_path: path.get_attribute_path(),
132        };
133        parse_fn(&mut cx, args)
134    }
135}
136
137impl<'sess, S: Stage> AttributeParser<'sess, S> {
138    pub fn new(
139        sess: &'sess Session,
140        features: &'sess Features,
141        tools: Vec<Symbol>,
142        stage: S,
143    ) -> Self {
144        Self { features: Some(features), tools, parse_only: None, sess, stage }
145    }
146
147    pub(crate) fn sess(&self) -> &'sess Session {
148        &self.sess
149    }
150
151    pub(crate) fn features(&self) -> &'sess Features {
152        self.features.expect("features not available at this point in the compiler")
153    }
154
155    pub(crate) fn features_option(&self) -> Option<&'sess Features> {
156        self.features
157    }
158
159    pub(crate) fn dcx(&self) -> DiagCtxtHandle<'sess> {
160        self.sess().dcx()
161    }
162
163    /// Parse a list of attributes.
164    ///
165    /// `target_span` is the span of the thing this list of attributes is applied to,
166    /// and when `omit_doc` is set, doc attributes are filtered out.
167    pub fn parse_attribute_list(
168        &mut self,
169        attrs: &[ast::Attribute],
170        target_span: Span,
171        target_id: S::Id,
172        target: Target,
173        omit_doc: OmitDoc,
174
175        lower_span: impl Copy + Fn(Span) -> Span,
176        mut emit_lint: impl FnMut(AttributeLint<S::Id>),
177    ) -> Vec<Attribute> {
178        let mut attributes = Vec::new();
179        let mut attr_paths = Vec::new();
180
181        for attr in attrs {
182            // If we're only looking for a single attribute, skip all the ones we don't care about.
183            if let Some(expected) = self.parse_only {
184                if !attr.has_name(expected) {
185                    continue;
186                }
187            }
188
189            // Sometimes, for example for `#![doc = include_str!("readme.md")]`,
190            // doc still contains a non-literal. You might say, when we're lowering attributes
191            // that's expanded right? But no, sometimes, when parsing attributes on macros,
192            // we already use the lowering logic and these are still there. So, when `omit_doc`
193            // is set we *also* want to ignore these.
194            if omit_doc == OmitDoc::Skip && attr.has_name(sym::doc) {
195                continue;
196            }
197
198            match &attr.kind {
199                ast::AttrKind::DocComment(comment_kind, symbol) => {
200                    if omit_doc == OmitDoc::Skip {
201                        continue;
202                    }
203
204                    attributes.push(Attribute::Parsed(AttributeKind::DocComment {
205                        style: attr.style,
206                        kind: *comment_kind,
207                        span: lower_span(attr.span),
208                        comment: *symbol,
209                    }))
210                }
211                // // FIXME: make doc attributes go through a proper attribute parser
212                // ast::AttrKind::Normal(n) if n.has_name(sym::doc) => {
213                //     let p = GenericMetaItemParser::from_attr(&n, self.dcx());
214                //
215                //     attributes.push(Attribute::Parsed(AttributeKind::DocComment {
216                //         style: attr.style,
217                //         kind: CommentKind::Line,
218                //         span: attr.span,
219                //         comment: p.args().name_value(),
220                //     }))
221                // }
222                ast::AttrKind::Normal(n) => {
223                    attr_paths.push(PathParser(Cow::Borrowed(&n.item.path)));
224
225                    let parts =
226                        n.item.path.segments.iter().map(|seg| seg.ident.name).collect::<Vec<_>>();
227
228                    if let Some(accepts) = S::parsers().accepters.get(parts.as_slice()) {
229                        let Some(parser) = MetaItemParser::from_attr(
230                            n,
231                            &parts,
232                            &self.sess.psess,
233                            self.stage.should_emit(),
234                        ) else {
235                            continue;
236                        };
237                        let path = parser.path();
238                        let args = parser.args();
239                        for accept in accepts {
240                            let mut cx: AcceptContext<'_, 'sess, S> = AcceptContext {
241                                shared: SharedContext {
242                                    cx: self,
243                                    target_span,
244                                    target_id,
245                                    emit_lint: &mut emit_lint,
246                                },
247                                attr_span: lower_span(attr.span),
248                                attr_style: attr.style,
249                                template: &accept.template,
250                                attr_path: path.get_attribute_path(),
251                            };
252
253                            (accept.accept_fn)(&mut cx, args);
254
255                            if self.stage.should_emit().should_emit() {
256                                self.check_target(
257                                    path.get_attribute_path(),
258                                    attr.span,
259                                    &accept.allowed_targets,
260                                    target,
261                                    target_id,
262                                    &mut emit_lint,
263                                );
264                            }
265                        }
266                    } else {
267                        // If we're here, we must be compiling a tool attribute... Or someone
268                        // forgot to parse their fancy new attribute. Let's warn them in any case.
269                        // If you are that person, and you really think your attribute should
270                        // remain unparsed, carefully read the documentation in this module and if
271                        // you still think so you can add an exception to this assertion.
272
273                        // FIXME(jdonszelmann): convert other attributes, and check with this that
274                        // we caught em all
275                        // const FIXME_TEMPORARY_ATTR_ALLOWLIST: &[Symbol] = &[sym::cfg];
276                        // assert!(
277                        //     self.tools.contains(&parts[0]) || true,
278                        //     // || FIXME_TEMPORARY_ATTR_ALLOWLIST.contains(&parts[0]),
279                        //     "attribute {path} wasn't parsed and isn't a know tool attribute",
280                        // );
281
282                        attributes.push(Attribute::Unparsed(Box::new(AttrItem {
283                            path: AttrPath::from_ast(&n.item.path),
284                            args: self.lower_attr_args(&n.item.args, lower_span),
285                            id: HashIgnoredAttrId { attr_id: attr.id },
286                            style: attr.style,
287                            span: lower_span(attr.span),
288                        })));
289                    }
290                }
291            }
292        }
293
294        let mut parsed_attributes = Vec::new();
295        for f in &S::parsers().finalizers {
296            if let Some(attr) = f(&mut FinalizeContext {
297                shared: SharedContext {
298                    cx: self,
299                    target_span,
300                    target_id,
301                    emit_lint: &mut emit_lint,
302                },
303                all_attrs: &attr_paths,
304            }) {
305                parsed_attributes.push(Attribute::Parsed(attr));
306            }
307        }
308
309        attributes.extend(parsed_attributes);
310
311        attributes
312    }
313
314    /// Returns whether there is a parser for an attribute with this name
315    pub fn is_parsed_attribute(path: &[Symbol]) -> bool {
316        Late::parsers().accepters.contains_key(path)
317    }
318
319    fn lower_attr_args(&self, args: &ast::AttrArgs, lower_span: impl Fn(Span) -> Span) -> AttrArgs {
320        match args {
321            ast::AttrArgs::Empty => AttrArgs::Empty,
322            ast::AttrArgs::Delimited(args) => AttrArgs::Delimited(args.clone()),
323            // This is an inert key-value attribute - it will never be visible to macros
324            // after it gets lowered to HIR. Therefore, we can extract literals to handle
325            // nonterminals in `#[doc]` (e.g. `#[doc = $e]`).
326            ast::AttrArgs::Eq { eq_span, expr } => {
327                // In valid code the value always ends up as a single literal. Otherwise, a dummy
328                // literal suffices because the error is handled elsewhere.
329                let lit = if let ast::ExprKind::Lit(token_lit) = expr.kind
330                    && let Ok(lit) =
331                        ast::MetaItemLit::from_token_lit(token_lit, lower_span(expr.span))
332                {
333                    lit
334                } else {
335                    let guar = self.dcx().span_delayed_bug(
336                        args.span().unwrap_or(DUMMY_SP),
337                        "expr in place where literal is expected (builtin attr parsing)",
338                    );
339                    ast::MetaItemLit {
340                        symbol: sym::dummy,
341                        suffix: None,
342                        kind: ast::LitKind::Err(guar),
343                        span: DUMMY_SP,
344                    }
345                };
346                AttrArgs::Eq { eq_span: lower_span(*eq_span), expr: lit }
347            }
348        }
349    }
350}