rustc_attr_parsing/
interface.rs

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