1use std::convert::identity;
3#[cfg(debug_assertions)]
4use std::sync::atomic::{AtomicBool, Ordering};
5
6use rustc_ast::token::DocFragmentKind;
7use rustc_ast::{self as ast, AttrStyle, CRATE_NODE_ID, NodeId, Safety};
8use rustc_attr_ir::target::{AstTarget, Target};
9use rustc_attr_ir::{AttrArgs, AttrItem, AttrPath, Attribute, AttributeKind, HashIgnoredAttrId};
10use rustc_data_structures::sync::{DynSend, DynSync};
11use rustc_errors::{Diag, DiagCtxtHandle, Diagnostic, Level, MultiSpan};
12use rustc_feature::{BUILTIN_ATTRIBUTE_SET, Features};
13use rustc_lint_defs::Reflectiveness::NonReflective;
14use rustc_lint_defs::{LintId, RegisteredTools, ToolOptions};
15use rustc_session::Session;
16use rustc_span::{DUMMY_SP, ErrorGuaranteed, Ident, Span, Symbol, sym};
17
18use crate::attributes::AttributeSafety;
19use crate::attributes::doc_comment::target_check_doc_comment;
20use crate::context::{
21 ATTRIBUTE_PARSERS, AcceptContext, FinalizeCheckContext, FinalizeCheckFn, FinalizeContext,
22 FinalizeFn, FinalizeOutput, SharedContext,
23};
24use crate::diagnostics::ParsedDescription;
25use crate::generated::GeneratedAttrState;
26use crate::parser::{AllowExprMetavar, ArgParser, PathParser, RefPathParser};
27use crate::synthetic::SyntheticAttrState;
28use crate::validate_attr::parse_meta;
29use crate::{AttributeTemplate, ShouldEmit, diagnostics};
30
31pub struct EmitAttribute(
32 pub Box<
33 dyn for<'a> FnOnce(DiagCtxtHandle<'a>, Level, &Session) -> Diag<'a>
34 + DynSend
35 + DynSync
36 + 'static,
37 >,
38);
39
40pub struct AttributeParser<'sess> {
43 pub(crate) attr_tools: Option<&'sess RegisteredTools>,
44 pub(crate) features: Option<&'sess Features>,
45 pub(crate) sess: &'sess Session,
46 pub(crate) should_emit: ShouldEmit,
47
48 pub(crate) parse_filter: Option<&'sess dyn Fn(&ast::Attribute) -> bool>,
52}
53
54impl<'sess> AttributeParser<'sess> {
55 pub fn parse_limited(
72 sess: &'sess Session,
73 attrs: &[ast::Attribute],
74 parse_filter: &dyn Fn(&ast::Attribute) -> bool,
75 ) -> Option<Attribute> {
76 Self::parse_limited_should_emit(
77 sess,
78 attrs,
79 parse_filter,
80 DUMMY_SP,
82 None,
83 ShouldEmit::Nothing,
84 )
85 }
86
87 pub fn parse_limited_sym(
90 sess: &'sess Session,
91 attrs: &[ast::Attribute],
92 sym: &'static [Symbol],
93 ) -> Option<Attribute> {
94 Self::parse_limited(sess, attrs, &|attr| attr.path_matches(sym))
95 }
96
97 pub fn parse_limited_should_emit(
102 sess: &'sess Session,
103 attrs: &[ast::Attribute],
104 parse_filter: &dyn Fn(&ast::Attribute) -> bool,
105 target_span: Span,
106 features: Option<&'sess Features>,
107 should_emit: ShouldEmit,
108 ) -> Option<Attribute> {
109 let mut parsed = Self::parse_limited_all(
110 sess,
111 attrs,
112 Some(parse_filter),
113 AstTarget::None(Target::Crate),
114 target_span,
115 CRATE_NODE_ID,
116 features,
117 should_emit,
118 None,
119 );
120 if !(parsed.len() <= 1) {
::core::panicking::panic("assertion failed: parsed.len() <= 1")
};assert!(parsed.len() <= 1);
121 parsed.pop()
122 }
123
124 pub fn parse_limited_sym_should_emit(
127 sess: &'sess Session,
128 attrs: &[ast::Attribute],
129 sym: &'static [Symbol],
130 target_span: Span,
131 features: Option<&'sess Features>,
132 should_emit: ShouldEmit,
133 ) -> Option<Attribute> {
134 Self::parse_limited_should_emit(
135 sess,
136 attrs,
137 &|attr| attr.path_matches(sym),
138 target_span,
139 features,
140 should_emit,
141 )
142 }
143
144 pub fn parse_limited_all(
152 sess: &'sess Session,
153 attrs: &[ast::Attribute],
154 parse_filter: Option<&dyn Fn(&ast::Attribute) -> bool>,
155 ast_target: AstTarget<'_>,
156 target_span: Span,
157 target_node_id: NodeId,
158 features: Option<&'sess Features>,
159 should_emit: ShouldEmit,
160 attr_tools: Option<&'sess RegisteredTools>,
161 ) -> Vec<Attribute> {
162 let mut p = AttributeParser { features, attr_tools, parse_filter, sess, should_emit };
163 p.parse_attribute_list(
164 attrs,
165 target_span,
166 ast_target,
167 std::convert::identity,
168 |lint_id, span, kind| {
169 sess.psess.dyn_buffer_lint_sess(lint_id.lint, span, target_node_id, kind.0)
170 },
171 )
172 }
173
174 pub fn parse_single<T>(
177 sess: &'sess Session,
178 attr: &ast::Attribute,
179 target_span: Span,
180 target_node_id: NodeId,
181 ast_target: AstTarget<'_>,
182 features: Option<&'sess Features>,
183 emit_errors: ShouldEmit,
184 parse_fn: fn(cx: &mut AcceptContext<'_, '_>, item: &ArgParser) -> Option<T>,
185 template: &AttributeTemplate,
186 allow_expr_metavar: AllowExprMetavar,
187 expected_safety: AttributeSafety,
188 ) -> Option<T> {
189 let attr_item = attr.get_normal_item();
190 let parts = attr_item.path.segments.iter().map(|seg| seg.ident.name).collect::<Vec<_>>();
191
192 let path = AttrPath::from_ast(&attr_item.path, identity);
193 let args = ArgParser::from_attr_args(
194 &attr_item.args,
195 &parts,
196 &sess.psess,
197 emit_errors,
198 allow_expr_metavar,
199 )?;
200 Self::parse_single_args(
201 sess,
202 attr.span,
203 attr_item.span,
204 attr.style,
205 path,
206 Some(attr_item.unsafety),
207 expected_safety,
208 ParsedDescription::Attribute,
209 target_span,
210 target_node_id,
211 ast_target,
212 features,
213 emit_errors,
214 &args,
215 parse_fn,
216 template,
217 )
218 }
219
220 pub fn parse_single_args<T, I>(
223 sess: &'sess Session,
224 attr_span: Span,
225 inner_span: Span,
226 attr_style: AttrStyle,
227 attr_path: AttrPath,
228 attr_safety: Option<Safety>,
229 expected_safety: AttributeSafety,
230 parsed_description: ParsedDescription,
231 target_span: Span,
232 target_node_id: NodeId,
233 ast_target: AstTarget<'_>,
234 features: Option<&'sess Features>,
235 should_emit: ShouldEmit,
236 args: &I,
237 parse_fn: fn(cx: &mut AcceptContext<'_, '_>, item: &I) -> T,
238 template: &AttributeTemplate,
239 ) -> T {
240 let mut parser = Self { features, attr_tools: None, parse_filter: None, sess, should_emit };
241 let mut emit_lint = |lint_id: LintId, span: MultiSpan, kind: EmitAttribute| {
242 sess.psess.dyn_buffer_lint_sess(lint_id.lint, span, target_node_id, kind.0)
243 };
244 if let Some(safety) = attr_safety {
245 parser.check_attribute_safety(
246 &attr_path,
247 inner_span,
248 safety,
249 expected_safety,
250 &mut emit_lint,
251 );
252 }
253 let mut cx: AcceptContext<'_, 'sess> = AcceptContext {
254 shared: SharedContext {
255 cx: &mut parser,
256 target_span,
257 target: Target::from_ast_target(&ast_target),
258 emit_lint: &mut emit_lint,
259 #[cfg(debug_assertions)]
260 has_lint_been_emitted: AtomicBool::new(false),
261 ast_target,
262 },
263 attr_span,
264 inner_span,
265 attr_style,
266 parsed_description,
267 template,
268 attr_safety: attr_safety.unwrap_or(Safety::Default),
269 attr_path,
270 #[cfg(debug_assertions)]
271 has_target_been_checked: false,
272 attr_id: None,
273 };
274 parse_fn(&mut cx, args)
275 }
276}
277
278impl<'sess> AttributeParser<'sess> {
279 pub fn new(
280 sess: &'sess Session,
281 features: &'sess Features,
282 attr_tools: &'sess RegisteredTools,
283 should_emit: ShouldEmit,
284 ) -> Self {
285 Self {
286 features: Some(features),
287 attr_tools: Some(attr_tools),
288 parse_filter: None,
289 sess,
290 should_emit,
291 }
292 }
293
294 pub(crate) fn sess(&self) -> &'sess Session {
295 self.sess
296 }
297
298 #[track_caller]
299 pub(crate) fn features(&self) -> &'sess Features {
300 self.features.expect("features not available at this point in the compiler")
301 }
302
303 pub(crate) fn features_option(&self) -> Option<&'sess Features> {
304 self.features
305 }
306
307 pub(crate) fn dcx(&self) -> DiagCtxtHandle<'sess> {
308 self.sess().dcx()
309 }
310
311 #[track_caller]
312 pub(crate) fn emit_err(&self, diag: impl for<'x> Diagnostic<'x>) -> ErrorGuaranteed {
313 self.should_emit.emit_err(self.sess.dcx().create_err(diag))
314 }
315
316 pub fn parse_attribute_list(
320 &mut self,
321 attrs: &[ast::Attribute],
322 target_span: Span,
323 ast_target: AstTarget<'_>,
324 lower_span: impl Copy + Fn(Span) -> Span,
325 mut emit_lint: impl FnMut(LintId, MultiSpan, EmitAttribute),
326 ) -> Vec<Attribute> {
327 let mut attributes = Vec::new();
328 let mut attr_paths: Vec<RefPathParser<'_>> = Vec::new();
329 let mut synthetic_attr_state = SyntheticAttrState::default();
330 let mut generated_attr_state = GeneratedAttrState::default();
331 let mut has_target_checked_doc_comment = false;
332
333 let mut finalizers: Vec<FinalizeFn> = Vec::with_capacity(attrs.len());
334
335 for attr in attrs {
336 if let Some(filter) = self.parse_filter {
338 if !filter(attr) {
339 continue;
340 }
341 }
342
343 let attr_span = lower_span(attr.span);
344 match &attr.kind {
345 ast::AttrKind::DocComment(comment_kind, symbol) => {
346 target_check_doc_comment(
347 &self,
348 attr,
349 &ast_target,
350 target_span,
351 &mut emit_lint,
352 &mut has_target_checked_doc_comment,
353 );
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::Generated(generated) => {
365 generated_attr_state.accept_generated_attr(attr_span, generated)
366 }
367 ast::AttrKind::Normal(n) => {
368 attr_paths.push(PathParser(&n.item.path));
369 let attr_path = AttrPath::from_ast(&n.item.path, lower_span);
370 let parts =
371 n.item.path.segments.iter().map(|seg| seg.ident.name).collect::<Vec<_>>();
372 let inner_span = lower_span(n.item.span);
373
374 let accepter = ATTRIBUTE_PARSERS.accepters.get(parts.as_slice());
375 if let Some(accept) = accepter {
376 self.check_attribute_safety(
377 &attr_path,
378 inner_span,
379 n.item.unsafety,
380 accept.safety,
381 &mut emit_lint,
382 );
383 self.check_attribute_stability(&attr_path, attr_span, accept.stability);
384 if let [part] = parts.as_slice() {
385 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));
386 }
387
388 let Some(args) = ArgParser::from_attr_args(
389 &n.item.args,
390 &parts,
391 &self.sess.psess,
392 self.should_emit,
393 AllowExprMetavar::No,
394 ) else {
395 continue;
396 };
397
398 if attr.has_name(sym::doc)
414 && let ArgParser::NameValue(nv) = &args
415 && let Some(comment) = nv.value_as_str()
419 {
420 target_check_doc_comment(
421 &self,
422 attr,
423 &ast_target,
424 target_span,
425 &mut emit_lint,
426 &mut false, );
428 attributes.push(Attribute::Parsed(AttributeKind::DocComment {
429 style: attr.style,
430 kind: DocFragmentKind::Raw(nv.value_span),
431 span: attr_span,
432 comment,
433 }));
434 continue;
435 }
436
437 let mut cx: AcceptContext<'_, 'sess> = AcceptContext {
438 shared: SharedContext {
439 cx: self,
440 target_span,
441 target: Target::from_ast_target(&ast_target),
442 emit_lint: &mut emit_lint,
443 #[cfg(debug_assertions)]
444 has_lint_been_emitted: AtomicBool::new(false),
445 ast_target,
446 },
447 attr_span,
448 inner_span,
449 attr_style: attr.style,
450 parsed_description: ParsedDescription::Attribute,
451 template: &accept.template,
452 attr_safety: n.item.unsafety,
453 attr_path: attr_path.clone(),
454 #[cfg(debug_assertions)]
455 has_target_been_checked: false,
456 attr_id: Some(HashIgnoredAttrId { attr_id: attr.id }),
457 };
458
459 (accept.accept_fn)(&mut cx, &args);
460 finalizers.push(accept.finalizer);
461
462 Self::check_target(&accept.allowed_targets, "", &mut cx);
463 #[cfg(debug_assertions)]
464 if !cx.shared.has_lint_been_emitted.load(Ordering::Relaxed) {
465 cx.shared.cx.check_args_used(attr, &args)
466 }
467 } else if let [sym::diagnostic, _unknown, ..] = &*parts {
468 self.unknown_diagnostic_attr(&n.item.path.segments[1], &mut emit_lint);
469 } else if let [sym::lint, unknown, ..] = &*parts {
470 if let Some(tools) = self.attr_tools
474 && tools.iter().any(|(i, _)| i.name == sym::lint)
475 {
476 self.emit_err(diagnostics::UnknownLintHelper {
477 span: n.item.span,
478 unknown: *unknown,
479 });
480 } else {
481 self.dcx().span_delayed_bug(
482 n.item.span,
483 "encountered `lint` tool attribute but error not reported",
484 );
485 }
486 } else {
487 let attr = AttrItem {
488 path: attr_path.clone(),
489 args: self.lower_attr_args(&n.item.args, lower_span),
490 style: attr.style,
491 span: attr_span,
492 };
493
494 self.check_attribute_safety(
495 &attr_path,
496 inner_span,
497 n.item.unsafety,
498 AttributeSafety::Normal,
499 &mut emit_lint,
500 );
501
502 if !#[allow(non_exhaustive_omitted_patterns)] match self.should_emit {
ShouldEmit::Nothing => true,
_ => false,
}matches!(self.should_emit, ShouldEmit::Nothing)
503 && Target::from_ast_target(&ast_target) == Target::Crate
504 {
505 self.check_invalid_crate_level_attr_item(&attr, inner_span);
506 }
507
508 let attr = match attr_path.segments.len() {
509 0 => {
::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
format_args!("no path for {0:?}", attr)));
}unreachable!("no path for {attr:?}"),
510 1 => Attribute::DeriveHelper(Box::new(attr)),
511 _ => {
512 if let Some(tools) = self.attr_tools
513 && let Some(opts) =
514 tools.get(&Ident::with_dummy_span(attr_path.segments[0]))
515 {
516 Attribute::Tool { item: Box::new(attr), opts: opts.clone() }
517 } else {
518 Attribute::Tool {
519 item: Box::new(attr),
520 opts: ToolOptions { reflectiveness: NonReflective },
521 }
522 }
523 }
524 };
525
526 attributes.push(attr);
527 };
528
529 if accepter.is_none()
530 && let rustc_ast::AttrArgs::Eq { .. } = n.item.args
531 {
532 match parse_meta(&self.sess.psess, &attr) {
534 Ok(_) => {}
535 Err(err) => {
536 err.emit();
537 }
538 }
539 }
540 }
541 }
542 }
543
544 synthetic_attr_state.finalize_synthetic_attrs(&mut attributes);
545 generated_attr_state.finalize_generated_attrs(&mut attributes);
546
547 let mut deferred_checks: Vec<(FinalizeCheckFn, Span)> = Vec::new();
552 for f in &finalizers {
553 let FinalizeOutput { attr, deferred_check } = f(&mut FinalizeContext {
554 shared: SharedContext {
555 cx: self,
556 target_span,
557 target: Target::from_ast_target(&ast_target),
558 ast_target,
559 emit_lint: &mut emit_lint,
560 #[cfg(debug_assertions)]
561 has_lint_been_emitted: AtomicBool::new(false),
562 },
563 all_attrs: &attr_paths,
564 });
565 if let Some(attr) = attr {
566 attributes.push(Attribute::Parsed(attr));
567 }
568 if let Some(deferred_check) = deferred_check {
569 deferred_checks.push(deferred_check);
570 }
571 }
572
573 if !#[allow(non_exhaustive_omitted_patterns)] match self.should_emit {
ShouldEmit::Nothing => true,
_ => false,
}matches!(self.should_emit, ShouldEmit::Nothing) {
576 for (check, attr_span) in deferred_checks {
577 check(
578 &mut FinalizeCheckContext {
579 shared: SharedContext {
580 cx: self,
581 target_span,
582 target: Target::from_ast_target(&ast_target),
583 ast_target,
584 emit_lint: &mut emit_lint,
585 #[cfg(debug_assertions)]
586 has_lint_been_emitted: AtomicBool::new(false),
587 },
588 all_attrs: &attr_paths,
589 parsed_attrs: &attributes,
590 },
591 attr_span,
592 );
593 }
594 }
595
596 if !#[allow(non_exhaustive_omitted_patterns)] match self.should_emit {
ShouldEmit::Nothing => true,
_ => false,
}matches!(self.should_emit, ShouldEmit::Nothing)
597 && Target::from_ast_target(&ast_target) == Target::WherePredicate
598 {
599 self.check_invalid_where_predicate_attrs(attributes.iter());
600 }
601
602 attributes
603 }
604
605 #[cfg(debug_assertions)]
606 fn check_args_used(&self, attr: &ast::Attribute, args: &ArgParser) {
609 if let ArgParser::List(items) = args {
610 for item in items.mixed() {
611 if let crate::parser::MetaItemOrLitParser::MetaItemParser(item) = item {
612 if !item.are_args_checked() {
613 self.dcx().span_delayed_bug(
614 item.span(),
615 "attribute args were not properly checked",
616 );
617 return;
618 }
619 self.check_args_used(attr, item.args());
620 }
621 }
622 }
623 }
624
625 pub fn is_parsed_attribute(path: &[Symbol]) -> bool {
627 const SPECIAL_ATTRIBUTES: &[&[Symbol]] = &[
630 &[sym::cfg],
633 &[sym::cfg_attr],
634 ];
635
636 ATTRIBUTE_PARSERS.accepters.contains_key(path) || SPECIAL_ATTRIBUTES.contains(&path)
637 }
638
639 fn lower_attr_args(&self, args: &ast::AttrArgs, lower_span: impl Fn(Span) -> Span) -> AttrArgs {
640 match args {
641 ast::AttrArgs::Empty => AttrArgs::Empty,
642 ast::AttrArgs::Delimited(args) => AttrArgs::Delimited(args.clone()),
643 ast::AttrArgs::Eq { eq_span, expr } => {
647 if let Err(diag) =
650 crate::validate_attr::check_attrs_on_rhs_expr(&self.sess.psess, expr)
651 {
652 diag.delay_as_bug();
653 }
654
655 let lit = if let ast::ExprKind::Lit(token_lit) = expr.kind
656 && let Ok(lit) =
657 ast::MetaItemLit::from_token_lit(token_lit, lower_span(expr.span))
658 {
659 lit
660 } else {
661 let span = args.span().unwrap_or(DUMMY_SP);
662 let guar =
663 self.dcx().span_delayed_bug(span, "non-literal expr in key-value attr");
664 ast::MetaItemLit {
665 symbol: sym::dummy,
666 suffix: None,
667 kind: ast::LitKind::Err(guar),
668 span: DUMMY_SP,
669 }
670 };
671 AttrArgs::Eq { eq_span: lower_span(*eq_span), expr: lit }
672 }
673 }
674 }
675}