1 //! Parsing and validation of builtin attributes
3 use rustc_ast::ast::{self, 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]),
24 MultipleStabilityLevels,
25 UnsupportedLiteral(&'static str, /* is_bytestr */ bool),
28 fn handle_errors(sess: &ParseSess, span: Span, error: AttrError) {
29 let diag = &sess.span_diagnostic;
31 AttrError::MultipleItem(item) => {
32 struct_span_err!(diag, span, E0538, "multiple '{}' items", item).emit();
34 AttrError::UnknownMetaItem(item, expected) => {
35 let expected = expected.iter().map(|name| format!("`{}`", name)).collect::<Vec<_>>();
36 struct_span_err!(diag, span, E0541, "unknown meta item '{}'", item)
37 .span_label(span, format!("expected one of {}", expected.join(", ")))
40 AttrError::MissingSince => {
41 struct_span_err!(diag, span, E0542, "missing 'since'").emit();
43 AttrError::MissingFeature => {
44 struct_span_err!(diag, span, E0546, "missing 'feature'").emit();
46 AttrError::MultipleStabilityLevels => {
47 struct_span_err!(diag, span, E0544, "multiple stability levels").emit();
49 AttrError::UnsupportedLiteral(msg, is_bytestr) => {
50 let mut err = struct_span_err!(diag, span, E0565, "{}", msg);
52 if let Ok(lint_str) = sess.source_map().span_to_snippet(span) {
55 "consider removing the prefix",
56 lint_str[1..].to_string(),
57 Applicability::MaybeIncorrect,
66 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable)]
74 #[derive(Clone, RustcEncodable, RustcDecodable)]
75 pub enum OptimizeAttr {
81 #[derive(Copy, Clone, PartialEq)]
87 /// Determine what `#[unwind]` attribute is present in `attrs`, if any.
88 pub fn find_unwind_attr(sess: &Session, attrs: &[Attribute]) -> Option<UnwindAttr> {
89 attrs.iter().fold(None, |ia, attr| {
90 if sess.check_name(attr, sym::unwind) {
91 if let Some(meta) = attr.meta() {
92 if let MetaItemKind::List(items) = meta.kind {
94 if items[0].has_name(sym::allowed) {
95 return Some(UnwindAttr::Allowed);
96 } else if items[0].has_name(sym::aborts) {
97 return Some(UnwindAttr::Aborts);
105 "malformed `unwind` attribute input"
107 .span_label(attr.span, "invalid argument")
110 "the allowed arguments are `allowed` and `aborts`",
111 (vec!["allowed", "aborts"])
113 .map(|s| format!("#[unwind({})]", s)),
114 Applicability::MachineApplicable,
125 /// Represents the following attributes:
129 #[derive(RustcEncodable, RustcDecodable, Copy, Clone, Debug, PartialEq, Eq, Hash)]
130 #[derive(HashStable_Generic)]
131 pub struct Stability {
132 pub level: StabilityLevel,
136 /// Represents the `#[rustc_const_unstable]` and `#[rustc_const_stable]` attributes.
137 #[derive(RustcEncodable, RustcDecodable, Copy, Clone, Debug, PartialEq, Eq, Hash)]
138 #[derive(HashStable_Generic)]
139 pub struct ConstStability {
140 pub level: StabilityLevel,
142 /// whether the function has a `#[rustc_promotable]` attribute
143 pub promotable: bool,
144 /// whether the function has a `#[rustc_allow_const_fn_ptr]` attribute
145 pub allow_const_fn_ptr: bool,
148 /// The available stability levels.
149 #[derive(RustcEncodable, RustcDecodable, PartialEq, PartialOrd, Copy, Clone, Debug, Eq, Hash)]
150 #[derive(HashStable_Generic)]
151 pub enum StabilityLevel {
152 // Reason for the current stability level and the relevant rust-lang issue
153 Unstable { reason: Option<Symbol>, issue: Option<NonZeroU32>, is_soft: bool },
154 Stable { since: Symbol },
157 impl StabilityLevel {
158 pub fn is_unstable(&self) -> bool {
159 if let StabilityLevel::Unstable { .. } = *self { true } else { false }
161 pub fn is_stable(&self) -> bool {
162 if let StabilityLevel::Stable { .. } = *self { true } else { false }
166 /// Collects stability info from all stability attributes in `attrs`.
167 /// Returns `None` if no stability attributes are found.
168 pub fn find_stability(
172 ) -> (Option<Stability>, Option<ConstStability>) {
173 find_stability_generic(sess, attrs.iter(), item_sp)
176 fn find_stability_generic<'a, I>(
180 ) -> (Option<Stability>, Option<ConstStability>)
182 I: Iterator<Item = &'a Attribute>,
184 use StabilityLevel::*;
186 let mut stab: Option<Stability> = None;
187 let mut const_stab: Option<ConstStability> = None;
188 let mut promotable = false;
189 let mut allow_const_fn_ptr = false;
190 let diagnostic = &sess.parse_sess.span_diagnostic;
192 'outer: for attr in attrs_iter {
194 sym::rustc_const_unstable,
195 sym::rustc_const_stable,
198 sym::rustc_promotable,
199 sym::rustc_allow_const_fn_ptr,
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 if attr.has_name(sym::rustc_allow_const_fn_ptr) {
215 allow_const_fn_ptr = true;
217 // attributes with data
218 else if let Some(MetaItem { kind: MetaItemKind::List(ref metas), .. }) = meta {
219 let meta = meta.as_ref().unwrap();
220 let get = |meta: &MetaItem, item: &mut Option<Symbol>| {
225 AttrError::MultipleItem(pprust::path_to_string(&meta.path)),
229 if let Some(v) = meta.value_str() {
233 struct_span_err!(diagnostic, meta.span, E0539, "incorrect meta item").emit();
238 let meta_name = meta.name_or_empty();
240 sym::rustc_const_unstable | sym::unstable => {
241 if meta_name == sym::unstable && stab.is_some() {
245 AttrError::MultipleStabilityLevels,
248 } else if meta_name == sym::rustc_const_unstable && const_stab.is_some() {
252 AttrError::MultipleStabilityLevels,
257 let mut feature = None;
258 let mut reason = None;
259 let mut issue = None;
260 let mut issue_num = None;
261 let mut is_soft = false;
263 if let Some(mi) = meta.meta_item() {
264 match mi.name_or_empty() {
266 if !get(mi, &mut feature) {
271 if !get(mi, &mut reason) {
276 if !get(mi, &mut issue) {
280 // These unwraps are safe because `get` ensures the meta item
281 // is a name/value pair string literal.
282 issue_num = match &*issue.unwrap().as_str() {
285 let emit_diag = |msg: &str| {
290 "`issue` must be a non-zero numeric string \
294 mi.name_value_literal().unwrap().span,
299 match issue.parse() {
300 Ok(num) if num == 0 => {
302 "`issue` must not be \"0\", \
303 use \"none\" instead",
307 Ok(num) => NonZeroU32::new(num),
309 emit_diag(&err.to_string());
318 let msg = "`soft` should not have any arguments";
319 sess.parse_sess.span_diagnostic.span_err(mi.span, msg);
327 AttrError::UnknownMetaItem(
328 pprust::path_to_string(&mi.path),
329 &["feature", "reason", "issue", "soft"],
339 AttrError::UnsupportedLiteral("unsupported literal", false),
345 match (feature, reason, issue) {
346 (Some(feature), reason, Some(_)) => {
347 let level = Unstable { reason, issue: issue_num, is_soft };
348 if sym::unstable == meta_name {
349 stab = Some(Stability { level, feature });
351 const_stab = Some(ConstStability {
355 allow_const_fn_ptr: false,
360 handle_errors(&sess.parse_sess, attr.span, AttrError::MissingFeature);
364 struct_span_err!(diagnostic, attr.span, E0547, "missing 'issue'")
370 sym::rustc_const_stable | sym::stable => {
371 if meta_name == sym::stable && stab.is_some() {
375 AttrError::MultipleStabilityLevels,
378 } else if meta_name == sym::rustc_const_stable && const_stab.is_some() {
382 AttrError::MultipleStabilityLevels,
387 let mut feature = None;
388 let mut since = None;
391 NestedMetaItem::MetaItem(mi) => match mi.name_or_empty() {
393 if !get(mi, &mut feature) {
398 if !get(mi, &mut since) {
406 AttrError::UnknownMetaItem(
407 pprust::path_to_string(&mi.path),
414 NestedMetaItem::Literal(lit) => {
418 AttrError::UnsupportedLiteral("unsupported literal", false),
425 match (feature, since) {
426 (Some(feature), Some(since)) => {
427 let level = Stable { since };
428 if sym::stable == meta_name {
429 stab = Some(Stability { level, feature });
431 const_stab = Some(ConstStability {
435 allow_const_fn_ptr: false,
440 handle_errors(&sess.parse_sess, attr.span, AttrError::MissingFeature);
444 handle_errors(&sess.parse_sess, attr.span, AttrError::MissingSince);
454 // Merge the const-unstable info into the stability info
455 if promotable || allow_const_fn_ptr {
456 if let Some(ref mut stab) = const_stab {
457 stab.promotable = promotable;
458 stab.allow_const_fn_ptr = allow_const_fn_ptr;
464 "rustc_promotable and rustc_allow_const_fn_ptr attributes \
465 must be paired with either a rustc_const_unstable or a rustc_const_stable \
475 pub fn find_crate_name(sess: &Session, attrs: &[Attribute]) -> Option<Symbol> {
476 sess.first_attr_value_str_by_name(attrs, sym::crate_name)
479 /// Tests if a cfg-pattern matches the cfg set
480 pub fn cfg_matches(cfg: &ast::MetaItem, sess: &ParseSess, features: Option<&Features>) -> bool {
481 eval_condition(cfg, sess, features, &mut |cfg| {
482 try_gate_cfg(cfg, sess, features);
483 let error = |span, msg| {
484 sess.span_diagnostic.span_err(span, msg);
487 if cfg.path.segments.len() != 1 {
488 return error(cfg.path.span, "`cfg` predicate key must be an identifier");
491 MetaItemKind::List(..) => {
492 error(cfg.span, "unexpected parentheses after `cfg` predicate key")
494 MetaItemKind::NameValue(lit) if !lit.kind.is_str() => {
498 AttrError::UnsupportedLiteral(
499 "literal in `cfg` predicate value must be a string",
500 lit.kind.is_bytestr(),
505 MetaItemKind::NameValue(..) | MetaItemKind::Word => {
506 let ident = cfg.ident().expect("multi-segment cfg predicate");
507 sess.config.contains(&(ident.name, cfg.value_str()))
513 fn try_gate_cfg(cfg: &ast::MetaItem, sess: &ParseSess, features: Option<&Features>) {
514 let gate = find_gated_cfg(|sym| cfg.has_name(sym));
515 if let (Some(feats), Some(gated_cfg)) = (features, gate) {
516 gate_cfg(&gated_cfg, cfg.span, sess, feats);
520 fn gate_cfg(gated_cfg: &GatedCfg, cfg_span: Span, sess: &ParseSess, features: &Features) {
521 let (cfg, feature, has_feature) = gated_cfg;
522 if !has_feature(features) && !cfg_span.allows_unstable(*feature) {
523 let explain = format!("`cfg({})` is experimental and subject to change", cfg);
524 feature_err(sess, *feature, cfg_span, &explain).emit();
528 /// Evaluate a cfg-like condition (with `any` and `all`), using `eval` to
529 /// evaluate individual items.
530 pub fn eval_condition(
533 features: Option<&Features>,
534 eval: &mut impl FnMut(&ast::MetaItem) -> bool,
537 ast::MetaItemKind::List(ref mis) if cfg.name_or_empty() == sym::version => {
538 try_gate_cfg(cfg, sess, features);
539 let (min_version, span) = match &mis[..] {
540 [NestedMetaItem::Literal(Lit { kind: LitKind::Str(sym, ..), span, .. })] => {
543 [NestedMetaItem::Literal(Lit { span, .. })
544 | NestedMetaItem::MetaItem(MetaItem { span, .. })] => {
546 .struct_span_err(*span, "expected a version literal")
552 .struct_span_err(cfg.span, "expected single version literal")
557 let min_version = match Version::parse(&min_version.as_str()) {
560 sess.span_diagnostic.struct_span_err(*span, "invalid version literal").emit();
564 let channel = env!("CFG_RELEASE_CHANNEL");
565 let nightly = channel == "nightly" || channel == "dev";
566 let rustc_version = Version::parse(env!("CFG_RELEASE")).unwrap();
568 // See https://github.com/rust-lang/rust/issues/64796#issuecomment-625474439 for details
569 if nightly { rustc_version > min_version } else { rustc_version >= min_version }
571 ast::MetaItemKind::List(ref mis) => {
572 for mi in mis.iter() {
573 if !mi.is_meta_item() {
577 AttrError::UnsupportedLiteral("unsupported literal", false),
583 // The unwraps below may look dangerous, but we've already asserted
584 // that they won't fail with the loop above.
585 match cfg.name_or_empty() {
588 .any(|mi| eval_condition(mi.meta_item().unwrap(), sess, features, eval)),
591 .all(|mi| eval_condition(mi.meta_item().unwrap(), sess, features, eval)),
595 sess.span_diagnostic,
598 "expected 1 cfg-pattern"
604 !eval_condition(mis[0].meta_item().unwrap(), sess, features, eval)
608 sess.span_diagnostic,
611 "invalid predicate `{}`",
612 pprust::path_to_string(&cfg.path)
619 ast::MetaItemKind::Word | ast::MetaItemKind::NameValue(..) => eval(cfg),
623 #[derive(RustcEncodable, RustcDecodable, Clone, HashStable_Generic)]
624 pub struct Deprecation {
625 pub since: Option<Symbol>,
626 /// The note to issue a reason.
627 pub note: Option<Symbol>,
628 /// A text snippet used to completely replace any use of the deprecated item in an expression.
630 /// This is currently unstable.
631 pub suggestion: Option<Symbol>,
633 /// Whether to treat the since attribute as being a Rust version identifier
634 /// (rather than an opaque string).
635 pub is_since_rustc_version: bool,
638 /// Finds the deprecation attribute. `None` if none exists.
639 pub fn find_deprecation(sess: &Session, attrs: &[Attribute], item_sp: Span) -> Option<Deprecation> {
640 find_deprecation_generic(sess, attrs.iter(), item_sp)
643 fn find_deprecation_generic<'a, I>(
647 ) -> Option<Deprecation>
649 I: Iterator<Item = &'a Attribute>,
651 let mut depr: Option<Deprecation> = None;
652 let diagnostic = &sess.parse_sess.span_diagnostic;
654 'outer: for attr in attrs_iter {
655 if !(sess.check_name(attr, sym::deprecated) || sess.check_name(attr, sym::rustc_deprecated))
661 struct_span_err!(diagnostic, item_sp, E0550, "multiple deprecated attributes").emit();
665 let meta = match attr.meta() {
669 let mut since = None;
671 let mut suggestion = None;
673 MetaItemKind::Word => {}
674 MetaItemKind::NameValue(..) => note = meta.value_str(),
675 MetaItemKind::List(list) => {
676 let get = |meta: &MetaItem, item: &mut Option<Symbol>| {
681 AttrError::MultipleItem(pprust::path_to_string(&meta.path)),
685 if let Some(v) = meta.value_str() {
689 if let Some(lit) = meta.name_value_literal() {
693 AttrError::UnsupportedLiteral(
694 "literal in `deprecated` \
695 value must be a string",
696 lit.kind.is_bytestr(),
700 struct_span_err!(diagnostic, meta.span, E0551, "incorrect meta item")
710 NestedMetaItem::MetaItem(mi) => match mi.name_or_empty() {
712 if !get(mi, &mut since) {
716 sym::note if sess.check_name(attr, sym::deprecated) => {
717 if !get(mi, &mut note) {
721 sym::reason if sess.check_name(attr, sym::rustc_deprecated) => {
722 if !get(mi, &mut note) {
726 sym::suggestion if sess.check_name(attr, sym::rustc_deprecated) => {
727 if !get(mi, &mut suggestion) {
735 AttrError::UnknownMetaItem(
736 pprust::path_to_string(&mi.path),
737 if sess.check_name(attr, sym::deprecated) {
740 &["since", "reason", "suggestion"]
747 NestedMetaItem::Literal(lit) => {
751 AttrError::UnsupportedLiteral(
752 "item in `deprecated` must be a key/value pair",
763 if suggestion.is_some() && sess.check_name(attr, sym::deprecated) {
764 unreachable!("only allowed on rustc_deprecated")
767 if sess.check_name(attr, sym::rustc_deprecated) {
769 handle_errors(&sess.parse_sess, attr.span, AttrError::MissingSince);
774 struct_span_err!(diagnostic, attr.span, E0543, "missing 'reason'").emit();
779 sess.mark_attr_used(&attr);
781 let is_since_rustc_version = sess.check_name(attr, sym::rustc_deprecated);
782 depr = Some(Deprecation { since, note, suggestion, is_since_rustc_version });
788 #[derive(PartialEq, Debug, RustcEncodable, RustcDecodable, Copy, Clone)]
799 #[derive(Eq, PartialEq, Debug, RustcEncodable, RustcDecodable, Copy, Clone, HashStable_Generic)]
801 SignedInt(ast::IntTy),
802 UnsignedInt(ast::UintTy),
807 pub fn is_signed(self) -> bool {
811 SignedInt(..) => true,
812 UnsignedInt(..) => false,
817 /// Parse #[repr(...)] forms.
819 /// Valid repr contents: any of the primitive integral type names (see
820 /// `int_type_of_word`, below) to specify enum discriminant type; `C`, to use
821 /// the same discriminant size that the corresponding C enum would or C
822 /// structure layout, `packed` to remove padding, and `transparent` to elegate representation
823 /// concerns to the only non-ZST field.
824 pub fn find_repr_attrs(sess: &Session, attr: &Attribute) -> Vec<ReprAttr> {
827 let mut acc = Vec::new();
828 let diagnostic = &sess.parse_sess.span_diagnostic;
829 if attr.has_name(sym::repr) {
830 if let Some(items) = attr.meta_item_list() {
831 sess.mark_attr_used(attr);
833 if !item.is_meta_item() {
837 AttrError::UnsupportedLiteral(
838 "meta item in `repr` must be an identifier",
845 let mut recognised = false;
847 let hint = match item.name_or_empty() {
848 sym::C => Some(ReprC),
849 sym::packed => Some(ReprPacked(1)),
850 sym::simd => Some(ReprSimd),
851 sym::transparent => Some(ReprTransparent),
852 sym::no_niche => Some(ReprNoNiche),
853 name => int_type_of_word(name).map(ReprInt),
856 if let Some(h) = hint {
860 } else if let Some((name, value)) = item.name_value_literal() {
861 let parse_alignment = |node: &ast::LitKind| -> Result<u32, &'static str> {
862 if let ast::LitKind::Int(literal, ast::LitIntType::Unsuffixed) = node {
863 if literal.is_power_of_two() {
864 // rustc_middle::ty::layout::Align restricts align to <= 2^29
865 if *literal <= 1 << 29 {
868 Err("larger than 2^29")
871 Err("not a power of two")
874 Err("not an unsuffixed integer")
878 let mut literal_error = None;
879 if name == sym::align {
881 match parse_alignment(&value.kind) {
882 Ok(literal) => acc.push(ReprAlign(literal)),
883 Err(message) => literal_error = Some(message),
885 } else if name == sym::packed {
887 match parse_alignment(&value.kind) {
888 Ok(literal) => acc.push(ReprPacked(literal)),
889 Err(message) => literal_error = Some(message),
892 if let Some(literal_error) = literal_error {
897 "invalid `repr(align)` attribute: {}",
903 if let Some(meta_item) = item.meta_item() {
904 if meta_item.has_name(sym::align) {
905 if let MetaItemKind::NameValue(ref value) = meta_item.kind {
907 let mut err = struct_span_err!(
911 "incorrect `repr(align)` attribute format"
914 ast::LitKind::Int(int, ast::LitIntType::Unsuffixed) => {
917 "use parentheses instead",
918 format!("align({})", int),
919 Applicability::MachineApplicable,
922 ast::LitKind::Str(s, _) => {
925 "use parentheses instead",
926 format!("align({})", s),
927 Applicability::MachineApplicable,
938 // Not a word we recognize
943 "unrecognized representation hint"
953 fn int_type_of_word(s: Symbol) -> Option<IntType> {
957 sym::i8 => Some(SignedInt(ast::IntTy::I8)),
958 sym::u8 => Some(UnsignedInt(ast::UintTy::U8)),
959 sym::i16 => Some(SignedInt(ast::IntTy::I16)),
960 sym::u16 => Some(UnsignedInt(ast::UintTy::U16)),
961 sym::i32 => Some(SignedInt(ast::IntTy::I32)),
962 sym::u32 => Some(UnsignedInt(ast::UintTy::U32)),
963 sym::i64 => Some(SignedInt(ast::IntTy::I64)),
964 sym::u64 => Some(UnsignedInt(ast::UintTy::U64)),
965 sym::i128 => Some(SignedInt(ast::IntTy::I128)),
966 sym::u128 => Some(UnsignedInt(ast::UintTy::U128)),
967 sym::isize => Some(SignedInt(ast::IntTy::Isize)),
968 sym::usize => Some(UnsignedInt(ast::UintTy::Usize)),
973 pub enum TransparencyError {
974 UnknownTransparency(Symbol, Span),
975 MultipleTransparencyAttrs(Span, Span),
978 pub fn find_transparency(
982 ) -> (Transparency, Option<TransparencyError>) {
983 let mut transparency = None;
984 let mut error = None;
986 if sess.check_name(attr, sym::rustc_macro_transparency) {
987 if let Some((_, old_span)) = transparency {
988 error = Some(TransparencyError::MultipleTransparencyAttrs(old_span, attr.span));
990 } else if let Some(value) = attr.value_str() {
991 transparency = Some((
993 sym::transparent => Transparency::Transparent,
994 sym::semitransparent => Transparency::SemiTransparent,
995 sym::opaque => Transparency::Opaque,
997 error = Some(TransparencyError::UnknownTransparency(value, attr.span));
1006 let fallback = if macro_rules { Transparency::SemiTransparent } else { Transparency::Opaque };
1007 (transparency.map_or(fallback, |t| t.0), error)
1010 pub fn allow_internal_unstable<'a>(
1012 attrs: &[Attribute],
1013 ) -> Option<impl Iterator<Item = Symbol> + 'a> {
1014 let attr = sess.find_by_name(attrs, sym::allow_internal_unstable)?;
1015 let list = attr.meta_item_list().or_else(|| {
1017 .span_err(attr.span, "allow_internal_unstable expects list of feature names");
1020 Some(list.into_iter().filter_map(move |it| {
1021 let name = it.ident().map(|ident| ident.name);
1024 .span_err(it.span(), "`allow_internal_unstable` expects feature names");