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