1 //! Parsing and validation of builtin attributes
3 use rustc_ast::{self as ast, Attribute, Lit, LitKind, MetaItem, MetaItemKind, NestedMetaItem};
4 use rustc_ast_pretty::pprust;
5 use rustc_errors::{struct_span_err, Applicability};
6 use rustc_feature::{find_gated_cfg, is_builtin_attr_name, Features, GatedCfg};
7 use rustc_macros::HashStable_Generic;
8 use rustc_session::parse::{feature_err, ParseSess};
9 use rustc_session::Session;
10 use rustc_span::hygiene::Transparency;
11 use rustc_span::{symbol::sym, symbol::Symbol, Span};
12 use std::num::NonZeroU32;
13 use version_check::Version;
15 pub fn is_builtin_attr(attr: &Attribute) -> bool {
16 attr.is_doc_comment() || attr.ident().filter(|ident| is_builtin_attr_name(ident.name)).is_some()
21 UnknownMetaItem(String, &'static [&'static str]),
25 MultipleStabilityLevels,
26 UnsupportedLiteral(&'static str, /* is_bytestr */ bool),
29 fn handle_errors(sess: &ParseSess, span: Span, error: AttrError) {
30 let diag = &sess.span_diagnostic;
32 AttrError::MultipleItem(item) => {
33 struct_span_err!(diag, span, E0538, "multiple '{}' items", item).emit();
35 AttrError::UnknownMetaItem(item, expected) => {
36 let expected = expected.iter().map(|name| format!("`{}`", name)).collect::<Vec<_>>();
37 struct_span_err!(diag, span, E0541, "unknown meta item '{}'", item)
38 .span_label(span, format!("expected one of {}", expected.join(", ")))
41 AttrError::MissingSince => {
42 struct_span_err!(diag, span, E0542, "missing 'since'").emit();
44 AttrError::NonIdentFeature => {
45 struct_span_err!(diag, span, E0546, "'feature' is not an identifier").emit();
47 AttrError::MissingFeature => {
48 struct_span_err!(diag, span, E0546, "missing 'feature'").emit();
50 AttrError::MultipleStabilityLevels => {
51 struct_span_err!(diag, span, E0544, "multiple stability levels").emit();
53 AttrError::UnsupportedLiteral(msg, is_bytestr) => {
54 let mut err = struct_span_err!(diag, span, E0565, "{}", msg);
56 if let Ok(lint_str) = sess.source_map().span_to_snippet(span) {
59 "consider removing the prefix",
60 lint_str[1..].to_string(),
61 Applicability::MaybeIncorrect,
70 #[derive(Clone, PartialEq, Encodable, Decodable)]
78 #[derive(Clone, Encodable, Decodable)]
79 pub enum OptimizeAttr {
85 #[derive(Copy, Clone, PartialEq)]
91 /// Determine what `#[unwind]` attribute is present in `attrs`, if any.
92 pub fn find_unwind_attr(sess: &Session, attrs: &[Attribute]) -> Option<UnwindAttr> {
93 attrs.iter().fold(None, |ia, attr| {
94 if sess.check_name(attr, sym::unwind) {
95 if let Some(meta) = attr.meta() {
96 if let MetaItemKind::List(items) = meta.kind {
98 if items[0].has_name(sym::allowed) {
99 return Some(UnwindAttr::Allowed);
100 } else if items[0].has_name(sym::aborts) {
101 return Some(UnwindAttr::Aborts);
109 "malformed `unwind` attribute input"
111 .span_label(attr.span, "invalid argument")
114 "the allowed arguments are `allowed` and `aborts`",
115 (vec!["allowed", "aborts"])
117 .map(|s| format!("#[unwind({})]", s)),
118 Applicability::MachineApplicable,
129 /// Represents the following attributes:
133 #[derive(Encodable, Decodable, Copy, Clone, Debug, PartialEq, Eq, Hash)]
134 #[derive(HashStable_Generic)]
135 pub struct Stability {
136 pub level: StabilityLevel,
140 /// Represents the `#[rustc_const_unstable]` and `#[rustc_const_stable]` attributes.
141 #[derive(Encodable, Decodable, Copy, Clone, Debug, PartialEq, Eq, Hash)]
142 #[derive(HashStable_Generic)]
143 pub struct ConstStability {
144 pub level: StabilityLevel,
146 /// whether the function has a `#[rustc_promotable]` attribute
147 pub promotable: bool,
150 /// The available stability levels.
151 #[derive(Encodable, Decodable, PartialEq, PartialOrd, Copy, Clone, Debug, Eq, Hash)]
152 #[derive(HashStable_Generic)]
153 pub enum StabilityLevel {
154 // Reason for the current stability level and the relevant rust-lang issue
155 Unstable { reason: Option<Symbol>, issue: Option<NonZeroU32>, is_soft: bool },
156 Stable { since: Symbol },
159 impl StabilityLevel {
160 pub fn is_unstable(&self) -> bool {
161 matches!(self, StabilityLevel::Unstable { .. })
163 pub fn is_stable(&self) -> bool {
164 matches!(self, StabilityLevel::Stable { .. })
168 /// Collects stability info from all stability attributes in `attrs`.
169 /// Returns `None` if no stability attributes are found.
170 pub fn find_stability(
174 ) -> (Option<Stability>, Option<ConstStability>) {
175 find_stability_generic(sess, attrs.iter(), item_sp)
178 fn find_stability_generic<'a, I>(
182 ) -> (Option<Stability>, Option<ConstStability>)
184 I: Iterator<Item = &'a Attribute>,
186 use StabilityLevel::*;
188 let mut stab: Option<Stability> = None;
189 let mut const_stab: Option<ConstStability> = None;
190 let mut promotable = false;
191 let diagnostic = &sess.parse_sess.span_diagnostic;
193 'outer: for attr in attrs_iter {
195 sym::rustc_const_unstable,
196 sym::rustc_const_stable,
199 sym::rustc_promotable,
202 .any(|&s| attr.has_name(s))
204 continue; // not a stability level
207 sess.mark_attr_used(attr);
209 let meta = attr.meta();
211 if attr.has_name(sym::rustc_promotable) {
214 // attributes with data
215 else if let Some(MetaItem { kind: MetaItemKind::List(ref metas), .. }) = meta {
216 let meta = meta.as_ref().unwrap();
217 let get = |meta: &MetaItem, item: &mut Option<Symbol>| {
222 AttrError::MultipleItem(pprust::path_to_string(&meta.path)),
226 if let Some(v) = meta.value_str() {
230 struct_span_err!(diagnostic, meta.span, E0539, "incorrect meta item").emit();
235 let meta_name = meta.name_or_empty();
237 sym::rustc_const_unstable | sym::unstable => {
238 if meta_name == sym::unstable && stab.is_some() {
242 AttrError::MultipleStabilityLevels,
245 } else if meta_name == sym::rustc_const_unstable && const_stab.is_some() {
249 AttrError::MultipleStabilityLevels,
254 let mut feature = None;
255 let mut reason = None;
256 let mut issue = None;
257 let mut issue_num = None;
258 let mut is_soft = false;
260 if let Some(mi) = meta.meta_item() {
261 match mi.name_or_empty() {
263 if !get(mi, &mut feature) {
268 if !get(mi, &mut reason) {
273 if !get(mi, &mut issue) {
277 // These unwraps are safe because `get` ensures the meta item
278 // is a name/value pair string literal.
279 issue_num = match &*issue.unwrap().as_str() {
282 let emit_diag = |msg: &str| {
287 "`issue` must be a non-zero numeric string \
291 mi.name_value_literal().unwrap().span,
296 match issue.parse() {
299 "`issue` must not be \"0\", \
300 use \"none\" instead",
304 Ok(num) => NonZeroU32::new(num),
306 emit_diag(&err.to_string());
315 let msg = "`soft` should not have any arguments";
316 sess.parse_sess.span_diagnostic.span_err(mi.span, msg);
324 AttrError::UnknownMetaItem(
325 pprust::path_to_string(&mi.path),
326 &["feature", "reason", "issue", "soft"],
336 AttrError::UnsupportedLiteral("unsupported literal", false),
342 match (feature, reason, issue) {
343 (Some(feature), reason, Some(_)) => {
344 if !rustc_lexer::is_ident(&feature.as_str()) {
348 AttrError::NonIdentFeature,
352 let level = Unstable { reason, issue: issue_num, is_soft };
353 if sym::unstable == meta_name {
354 stab = Some(Stability { level, feature });
357 Some(ConstStability { level, feature, promotable: false });
361 handle_errors(&sess.parse_sess, attr.span, AttrError::MissingFeature);
365 struct_span_err!(diagnostic, attr.span, E0547, "missing 'issue'")
371 sym::rustc_const_stable | sym::stable => {
372 if meta_name == sym::stable && stab.is_some() {
376 AttrError::MultipleStabilityLevels,
379 } else if meta_name == sym::rustc_const_stable && const_stab.is_some() {
383 AttrError::MultipleStabilityLevels,
388 let mut feature = None;
389 let mut since = None;
392 NestedMetaItem::MetaItem(mi) => match mi.name_or_empty() {
394 if !get(mi, &mut feature) {
399 if !get(mi, &mut since) {
407 AttrError::UnknownMetaItem(
408 pprust::path_to_string(&mi.path),
415 NestedMetaItem::Literal(lit) => {
419 AttrError::UnsupportedLiteral("unsupported literal", false),
426 match (feature, since) {
427 (Some(feature), Some(since)) => {
428 let level = Stable { since };
429 if sym::stable == meta_name {
430 stab = Some(Stability { level, feature });
433 Some(ConstStability { level, feature, promotable: false });
437 handle_errors(&sess.parse_sess, attr.span, AttrError::MissingFeature);
441 handle_errors(&sess.parse_sess, attr.span, AttrError::MissingSince);
451 // Merge the const-unstable info into the stability info
453 if let Some(ref mut stab) = const_stab {
454 stab.promotable = promotable;
460 "`rustc_promotable` attribute must be paired with either a `rustc_const_unstable` \
461 or a `rustc_const_stable` attribute"
470 pub fn find_crate_name(sess: &Session, attrs: &[Attribute]) -> Option<Symbol> {
471 sess.first_attr_value_str_by_name(attrs, sym::crate_name)
474 /// Tests if a cfg-pattern matches the cfg set
475 pub fn cfg_matches(cfg: &ast::MetaItem, sess: &ParseSess, features: Option<&Features>) -> bool {
476 eval_condition(cfg, sess, features, &mut |cfg| {
477 try_gate_cfg(cfg, sess, features);
478 let error = |span, msg| {
479 sess.span_diagnostic.span_err(span, msg);
482 if cfg.path.segments.len() != 1 {
483 return error(cfg.path.span, "`cfg` predicate key must be an identifier");
486 MetaItemKind::List(..) => {
487 error(cfg.span, "unexpected parentheses after `cfg` predicate key")
489 MetaItemKind::NameValue(lit) if !lit.kind.is_str() => {
493 AttrError::UnsupportedLiteral(
494 "literal in `cfg` predicate value must be a string",
495 lit.kind.is_bytestr(),
500 MetaItemKind::NameValue(..) | MetaItemKind::Word => {
501 let ident = cfg.ident().expect("multi-segment cfg predicate");
502 sess.config.contains(&(ident.name, cfg.value_str()))
508 fn try_gate_cfg(cfg: &ast::MetaItem, sess: &ParseSess, features: Option<&Features>) {
509 let gate = find_gated_cfg(|sym| cfg.has_name(sym));
510 if let (Some(feats), Some(gated_cfg)) = (features, gate) {
511 gate_cfg(&gated_cfg, cfg.span, sess, feats);
515 fn gate_cfg(gated_cfg: &GatedCfg, cfg_span: Span, sess: &ParseSess, features: &Features) {
516 let (cfg, feature, has_feature) = gated_cfg;
517 if !has_feature(features) && !cfg_span.allows_unstable(*feature) {
518 let explain = format!("`cfg({})` is experimental and subject to change", cfg);
519 feature_err(sess, *feature, cfg_span, &explain).emit();
523 /// Evaluate a cfg-like condition (with `any` and `all`), using `eval` to
524 /// evaluate individual items.
525 pub fn eval_condition(
528 features: Option<&Features>,
529 eval: &mut impl FnMut(&ast::MetaItem) -> bool,
532 ast::MetaItemKind::List(ref mis) if cfg.name_or_empty() == sym::version => {
533 try_gate_cfg(cfg, sess, features);
534 let (min_version, span) = match &mis[..] {
535 [NestedMetaItem::Literal(Lit { kind: LitKind::Str(sym, ..), span, .. })] => {
538 [NestedMetaItem::Literal(Lit { span, .. })
539 | NestedMetaItem::MetaItem(MetaItem { span, .. })] => {
541 .struct_span_err(*span, "expected a version literal")
547 .struct_span_err(cfg.span, "expected single version literal")
552 let min_version = match Version::parse(&min_version.as_str()) {
555 sess.span_diagnostic.struct_span_err(*span, "invalid version literal").emit();
559 let channel = env!("CFG_RELEASE_CHANNEL");
560 let nightly = channel == "nightly" || channel == "dev";
561 let rustc_version = Version::parse(env!("CFG_RELEASE")).unwrap();
563 // See https://github.com/rust-lang/rust/issues/64796#issuecomment-625474439 for details
564 if nightly { rustc_version > min_version } else { rustc_version >= min_version }
566 ast::MetaItemKind::List(ref mis) => {
567 for mi in mis.iter() {
568 if !mi.is_meta_item() {
572 AttrError::UnsupportedLiteral("unsupported literal", false),
578 // The unwraps below may look dangerous, but we've already asserted
579 // that they won't fail with the loop above.
580 match cfg.name_or_empty() {
583 .any(|mi| eval_condition(mi.meta_item().unwrap(), sess, features, eval)),
586 .all(|mi| eval_condition(mi.meta_item().unwrap(), sess, features, eval)),
590 sess.span_diagnostic,
593 "expected 1 cfg-pattern"
599 !eval_condition(mis[0].meta_item().unwrap(), sess, features, eval)
603 sess.span_diagnostic,
606 "invalid predicate `{}`",
607 pprust::path_to_string(&cfg.path)
614 ast::MetaItemKind::Word | ast::MetaItemKind::NameValue(..) => eval(cfg),
618 #[derive(Encodable, Decodable, Clone, HashStable_Generic)]
619 pub struct Deprecation {
620 pub since: Option<Symbol>,
621 /// The note to issue a reason.
622 pub note: Option<Symbol>,
623 /// A text snippet used to completely replace any use of the deprecated item in an expression.
625 /// This is currently unstable.
626 pub suggestion: Option<Symbol>,
628 /// Whether to treat the since attribute as being a Rust version identifier
629 /// (rather than an opaque string).
630 pub is_since_rustc_version: bool,
633 /// Finds the deprecation attribute. `None` if none exists.
634 pub fn find_deprecation(sess: &Session, attrs: &[Attribute], item_sp: Span) -> Option<Deprecation> {
635 find_deprecation_generic(sess, attrs.iter(), item_sp)
638 fn find_deprecation_generic<'a, I>(
642 ) -> Option<Deprecation>
644 I: Iterator<Item = &'a Attribute>,
646 let mut depr: Option<Deprecation> = None;
647 let diagnostic = &sess.parse_sess.span_diagnostic;
649 'outer: for attr in attrs_iter {
650 if !(sess.check_name(attr, sym::deprecated) || sess.check_name(attr, sym::rustc_deprecated))
656 struct_span_err!(diagnostic, item_sp, E0550, "multiple deprecated attributes").emit();
660 let meta = match attr.meta() {
664 let mut since = None;
666 let mut suggestion = None;
668 MetaItemKind::Word => {}
669 MetaItemKind::NameValue(..) => note = meta.value_str(),
670 MetaItemKind::List(list) => {
671 let get = |meta: &MetaItem, item: &mut Option<Symbol>| {
676 AttrError::MultipleItem(pprust::path_to_string(&meta.path)),
680 if let Some(v) = meta.value_str() {
684 if let Some(lit) = meta.name_value_literal() {
688 AttrError::UnsupportedLiteral(
689 "literal in `deprecated` \
690 value must be a string",
691 lit.kind.is_bytestr(),
695 struct_span_err!(diagnostic, meta.span, E0551, "incorrect meta item")
705 NestedMetaItem::MetaItem(mi) => match mi.name_or_empty() {
707 if !get(mi, &mut since) {
711 sym::note if sess.check_name(attr, sym::deprecated) => {
712 if !get(mi, &mut note) {
716 sym::reason if sess.check_name(attr, sym::rustc_deprecated) => {
717 if !get(mi, &mut note) {
721 sym::suggestion if sess.check_name(attr, sym::rustc_deprecated) => {
722 if !get(mi, &mut suggestion) {
730 AttrError::UnknownMetaItem(
731 pprust::path_to_string(&mi.path),
732 if sess.check_name(attr, sym::deprecated) {
735 &["since", "reason", "suggestion"]
742 NestedMetaItem::Literal(lit) => {
746 AttrError::UnsupportedLiteral(
747 "item in `deprecated` must be a key/value pair",
758 if suggestion.is_some() && sess.check_name(attr, sym::deprecated) {
759 unreachable!("only allowed on rustc_deprecated")
762 if sess.check_name(attr, sym::rustc_deprecated) {
764 handle_errors(&sess.parse_sess, attr.span, AttrError::MissingSince);
769 struct_span_err!(diagnostic, attr.span, E0543, "missing 'reason'").emit();
774 sess.mark_attr_used(&attr);
776 let is_since_rustc_version = sess.check_name(attr, sym::rustc_deprecated);
777 depr = Some(Deprecation { since, note, suggestion, is_since_rustc_version });
783 #[derive(PartialEq, Debug, Encodable, Decodable, Copy, Clone)]
794 #[derive(Eq, PartialEq, Debug, Copy, Clone)]
795 #[derive(Encodable, Decodable, HashStable_Generic)]
797 SignedInt(ast::IntTy),
798 UnsignedInt(ast::UintTy),
803 pub fn is_signed(self) -> bool {
807 SignedInt(..) => true,
808 UnsignedInt(..) => false,
813 /// Parse #[repr(...)] forms.
815 /// Valid repr contents: any of the primitive integral type names (see
816 /// `int_type_of_word`, below) to specify enum discriminant type; `C`, to use
817 /// the same discriminant size that the corresponding C enum would or C
818 /// structure layout, `packed` to remove padding, and `transparent` to elegate representation
819 /// concerns to the only non-ZST field.
820 pub fn find_repr_attrs(sess: &Session, attr: &Attribute) -> Vec<ReprAttr> {
823 let mut acc = Vec::new();
824 let diagnostic = &sess.parse_sess.span_diagnostic;
825 if attr.has_name(sym::repr) {
826 if let Some(items) = attr.meta_item_list() {
827 sess.mark_attr_used(attr);
829 if !item.is_meta_item() {
833 AttrError::UnsupportedLiteral(
834 "meta item in `repr` must be an identifier",
841 let mut recognised = false;
843 let hint = match item.name_or_empty() {
844 sym::C => Some(ReprC),
845 sym::packed => Some(ReprPacked(1)),
846 sym::simd => Some(ReprSimd),
847 sym::transparent => Some(ReprTransparent),
848 sym::no_niche => Some(ReprNoNiche),
849 name => int_type_of_word(name).map(ReprInt),
852 if let Some(h) = hint {
856 } else if let Some((name, value)) = item.name_value_literal() {
857 let parse_alignment = |node: &ast::LitKind| -> Result<u32, &'static str> {
858 if let ast::LitKind::Int(literal, ast::LitIntType::Unsuffixed) = node {
859 if literal.is_power_of_two() {
860 // rustc_middle::ty::layout::Align restricts align to <= 2^29
861 if *literal <= 1 << 29 {
864 Err("larger than 2^29")
867 Err("not a power of two")
870 Err("not an unsuffixed integer")
874 let mut literal_error = None;
875 if name == sym::align {
877 match parse_alignment(&value.kind) {
878 Ok(literal) => acc.push(ReprAlign(literal)),
879 Err(message) => literal_error = Some(message),
881 } else if name == sym::packed {
883 match parse_alignment(&value.kind) {
884 Ok(literal) => acc.push(ReprPacked(literal)),
885 Err(message) => literal_error = Some(message),
888 if let Some(literal_error) = literal_error {
893 "invalid `repr(align)` attribute: {}",
899 if let Some(meta_item) = item.meta_item() {
900 if meta_item.has_name(sym::align) {
901 if let MetaItemKind::NameValue(ref value) = meta_item.kind {
903 let mut err = struct_span_err!(
907 "incorrect `repr(align)` attribute format"
910 ast::LitKind::Int(int, ast::LitIntType::Unsuffixed) => {
913 "use parentheses instead",
914 format!("align({})", int),
915 Applicability::MachineApplicable,
918 ast::LitKind::Str(s, _) => {
921 "use parentheses instead",
922 format!("align({})", s),
923 Applicability::MachineApplicable,
934 // Not a word we recognize
939 "unrecognized representation hint"
949 fn int_type_of_word(s: Symbol) -> Option<IntType> {
953 sym::i8 => Some(SignedInt(ast::IntTy::I8)),
954 sym::u8 => Some(UnsignedInt(ast::UintTy::U8)),
955 sym::i16 => Some(SignedInt(ast::IntTy::I16)),
956 sym::u16 => Some(UnsignedInt(ast::UintTy::U16)),
957 sym::i32 => Some(SignedInt(ast::IntTy::I32)),
958 sym::u32 => Some(UnsignedInt(ast::UintTy::U32)),
959 sym::i64 => Some(SignedInt(ast::IntTy::I64)),
960 sym::u64 => Some(UnsignedInt(ast::UintTy::U64)),
961 sym::i128 => Some(SignedInt(ast::IntTy::I128)),
962 sym::u128 => Some(UnsignedInt(ast::UintTy::U128)),
963 sym::isize => Some(SignedInt(ast::IntTy::Isize)),
964 sym::usize => Some(UnsignedInt(ast::UintTy::Usize)),
969 pub enum TransparencyError {
970 UnknownTransparency(Symbol, Span),
971 MultipleTransparencyAttrs(Span, Span),
974 pub fn find_transparency(
978 ) -> (Transparency, Option<TransparencyError>) {
979 let mut transparency = None;
980 let mut error = None;
982 if sess.check_name(attr, sym::rustc_macro_transparency) {
983 if let Some((_, old_span)) = transparency {
984 error = Some(TransparencyError::MultipleTransparencyAttrs(old_span, attr.span));
986 } else if let Some(value) = attr.value_str() {
987 transparency = Some((
989 sym::transparent => Transparency::Transparent,
990 sym::semitransparent => Transparency::SemiTransparent,
991 sym::opaque => Transparency::Opaque,
993 error = Some(TransparencyError::UnknownTransparency(value, attr.span));
1002 let fallback = if macro_rules { Transparency::SemiTransparent } else { Transparency::Opaque };
1003 (transparency.map_or(fallback, |t| t.0), error)
1006 pub fn allow_internal_unstable<'a>(
1008 attrs: &'a [Attribute],
1009 ) -> Option<impl Iterator<Item = Symbol> + 'a> {
1010 let attrs = sess.filter_by_name(attrs, sym::allow_internal_unstable);
1012 .filter_map(move |attr| {
1013 attr.meta_item_list().or_else(|| {
1014 sess.diagnostic().span_err(
1016 "`allow_internal_unstable` expects a list of feature names",
1023 Some(list.into_iter().filter_map(move |it| {
1024 let name = it.ident().map(|ident| ident.name);
1027 .span_err(it.span(), "`allow_internal_unstable` expects feature names");