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,
148 /// whether the function has a `#[rustc_allow_const_fn_ptr]` attribute
149 pub allow_const_fn_ptr: bool,
152 /// The available stability levels.
153 #[derive(Encodable, Decodable, PartialEq, PartialOrd, Copy, Clone, Debug, Eq, Hash)]
154 #[derive(HashStable_Generic)]
155 pub enum StabilityLevel {
156 // Reason for the current stability level and the relevant rust-lang issue
157 Unstable { reason: Option<Symbol>, issue: Option<NonZeroU32>, is_soft: bool },
158 Stable { since: Symbol },
161 impl StabilityLevel {
162 pub fn is_unstable(&self) -> bool {
163 matches!(self, StabilityLevel::Unstable { .. })
165 pub fn is_stable(&self) -> bool {
166 matches!(self, StabilityLevel::Stable { .. })
170 /// Collects stability info from all stability attributes in `attrs`.
171 /// Returns `None` if no stability attributes are found.
172 pub fn find_stability(
176 ) -> (Option<Stability>, Option<ConstStability>) {
177 find_stability_generic(sess, attrs.iter(), item_sp)
180 fn find_stability_generic<'a, I>(
184 ) -> (Option<Stability>, Option<ConstStability>)
186 I: Iterator<Item = &'a Attribute>,
188 use StabilityLevel::*;
190 let mut stab: Option<Stability> = None;
191 let mut const_stab: Option<ConstStability> = None;
192 let mut promotable = false;
193 let mut allow_const_fn_ptr = false;
194 let diagnostic = &sess.parse_sess.span_diagnostic;
196 'outer: for attr in attrs_iter {
198 sym::rustc_const_unstable,
199 sym::rustc_const_stable,
202 sym::rustc_promotable,
203 sym::rustc_allow_const_fn_ptr,
206 .any(|&s| attr.has_name(s))
208 continue; // not a stability level
211 sess.mark_attr_used(attr);
213 let meta = attr.meta();
215 if attr.has_name(sym::rustc_promotable) {
218 if attr.has_name(sym::rustc_allow_const_fn_ptr) {
219 allow_const_fn_ptr = true;
221 // attributes with data
222 else if let Some(MetaItem { kind: MetaItemKind::List(ref metas), .. }) = meta {
223 let meta = meta.as_ref().unwrap();
224 let get = |meta: &MetaItem, item: &mut Option<Symbol>| {
229 AttrError::MultipleItem(pprust::path_to_string(&meta.path)),
233 if let Some(v) = meta.value_str() {
237 struct_span_err!(diagnostic, meta.span, E0539, "incorrect meta item").emit();
242 let meta_name = meta.name_or_empty();
244 sym::rustc_const_unstable | sym::unstable => {
245 if meta_name == sym::unstable && stab.is_some() {
249 AttrError::MultipleStabilityLevels,
252 } else if meta_name == sym::rustc_const_unstable && const_stab.is_some() {
256 AttrError::MultipleStabilityLevels,
261 let mut feature = None;
262 let mut reason = None;
263 let mut issue = None;
264 let mut issue_num = None;
265 let mut is_soft = false;
267 if let Some(mi) = meta.meta_item() {
268 match mi.name_or_empty() {
270 if !get(mi, &mut feature) {
275 if !get(mi, &mut reason) {
280 if !get(mi, &mut issue) {
284 // These unwraps are safe because `get` ensures the meta item
285 // is a name/value pair string literal.
286 issue_num = match &*issue.unwrap().as_str() {
289 let emit_diag = |msg: &str| {
294 "`issue` must be a non-zero numeric string \
298 mi.name_value_literal().unwrap().span,
303 match issue.parse() {
304 Ok(num) if num == 0 => {
306 "`issue` must not be \"0\", \
307 use \"none\" instead",
311 Ok(num) => NonZeroU32::new(num),
313 emit_diag(&err.to_string());
322 let msg = "`soft` should not have any arguments";
323 sess.parse_sess.span_diagnostic.span_err(mi.span, msg);
331 AttrError::UnknownMetaItem(
332 pprust::path_to_string(&mi.path),
333 &["feature", "reason", "issue", "soft"],
343 AttrError::UnsupportedLiteral("unsupported literal", false),
349 match (feature, reason, issue) {
350 (Some(feature), reason, Some(_)) => {
351 if !rustc_lexer::is_ident(&feature.as_str()) {
355 AttrError::NonIdentFeature,
359 let level = Unstable { reason, issue: issue_num, is_soft };
360 if sym::unstable == meta_name {
361 stab = Some(Stability { level, feature });
363 const_stab = Some(ConstStability {
367 allow_const_fn_ptr: false,
372 handle_errors(&sess.parse_sess, attr.span, AttrError::MissingFeature);
376 struct_span_err!(diagnostic, attr.span, E0547, "missing 'issue'")
382 sym::rustc_const_stable | sym::stable => {
383 if meta_name == sym::stable && stab.is_some() {
387 AttrError::MultipleStabilityLevels,
390 } else if meta_name == sym::rustc_const_stable && const_stab.is_some() {
394 AttrError::MultipleStabilityLevels,
399 let mut feature = None;
400 let mut since = None;
403 NestedMetaItem::MetaItem(mi) => match mi.name_or_empty() {
405 if !get(mi, &mut feature) {
410 if !get(mi, &mut since) {
418 AttrError::UnknownMetaItem(
419 pprust::path_to_string(&mi.path),
426 NestedMetaItem::Literal(lit) => {
430 AttrError::UnsupportedLiteral("unsupported literal", false),
437 match (feature, since) {
438 (Some(feature), Some(since)) => {
439 let level = Stable { since };
440 if sym::stable == meta_name {
441 stab = Some(Stability { level, feature });
443 const_stab = Some(ConstStability {
447 allow_const_fn_ptr: false,
452 handle_errors(&sess.parse_sess, attr.span, AttrError::MissingFeature);
456 handle_errors(&sess.parse_sess, attr.span, AttrError::MissingSince);
466 // Merge the const-unstable info into the stability info
467 if promotable || allow_const_fn_ptr {
468 if let Some(ref mut stab) = const_stab {
469 stab.promotable = promotable;
470 stab.allow_const_fn_ptr = allow_const_fn_ptr;
476 "rustc_promotable and rustc_allow_const_fn_ptr attributes \
477 must be paired with either a rustc_const_unstable or a rustc_const_stable \
487 pub fn find_crate_name(sess: &Session, attrs: &[Attribute]) -> Option<Symbol> {
488 sess.first_attr_value_str_by_name(attrs, sym::crate_name)
491 /// Tests if a cfg-pattern matches the cfg set
492 pub fn cfg_matches(cfg: &ast::MetaItem, sess: &ParseSess, features: Option<&Features>) -> bool {
493 eval_condition(cfg, sess, features, &mut |cfg| {
494 try_gate_cfg(cfg, sess, features);
495 let error = |span, msg| {
496 sess.span_diagnostic.span_err(span, msg);
499 if cfg.path.segments.len() != 1 {
500 return error(cfg.path.span, "`cfg` predicate key must be an identifier");
503 MetaItemKind::List(..) => {
504 error(cfg.span, "unexpected parentheses after `cfg` predicate key")
506 MetaItemKind::NameValue(lit) if !lit.kind.is_str() => {
510 AttrError::UnsupportedLiteral(
511 "literal in `cfg` predicate value must be a string",
512 lit.kind.is_bytestr(),
517 MetaItemKind::NameValue(..) | MetaItemKind::Word => {
518 let ident = cfg.ident().expect("multi-segment cfg predicate");
519 sess.config.contains(&(ident.name, cfg.value_str()))
525 fn try_gate_cfg(cfg: &ast::MetaItem, sess: &ParseSess, features: Option<&Features>) {
526 let gate = find_gated_cfg(|sym| cfg.has_name(sym));
527 if let (Some(feats), Some(gated_cfg)) = (features, gate) {
528 gate_cfg(&gated_cfg, cfg.span, sess, feats);
532 fn gate_cfg(gated_cfg: &GatedCfg, cfg_span: Span, sess: &ParseSess, features: &Features) {
533 let (cfg, feature, has_feature) = gated_cfg;
534 if !has_feature(features) && !cfg_span.allows_unstable(*feature) {
535 let explain = format!("`cfg({})` is experimental and subject to change", cfg);
536 feature_err(sess, *feature, cfg_span, &explain).emit();
540 /// Evaluate a cfg-like condition (with `any` and `all`), using `eval` to
541 /// evaluate individual items.
542 pub fn eval_condition(
545 features: Option<&Features>,
546 eval: &mut impl FnMut(&ast::MetaItem) -> bool,
549 ast::MetaItemKind::List(ref mis) if cfg.name_or_empty() == sym::version => {
550 try_gate_cfg(cfg, sess, features);
551 let (min_version, span) = match &mis[..] {
552 [NestedMetaItem::Literal(Lit { kind: LitKind::Str(sym, ..), span, .. })] => {
555 [NestedMetaItem::Literal(Lit { span, .. })
556 | NestedMetaItem::MetaItem(MetaItem { span, .. })] => {
558 .struct_span_err(*span, "expected a version literal")
564 .struct_span_err(cfg.span, "expected single version literal")
569 let min_version = match Version::parse(&min_version.as_str()) {
572 sess.span_diagnostic.struct_span_err(*span, "invalid version literal").emit();
576 let channel = env!("CFG_RELEASE_CHANNEL");
577 let nightly = channel == "nightly" || channel == "dev";
578 let rustc_version = Version::parse(env!("CFG_RELEASE")).unwrap();
580 // See https://github.com/rust-lang/rust/issues/64796#issuecomment-625474439 for details
581 if nightly { rustc_version > min_version } else { rustc_version >= min_version }
583 ast::MetaItemKind::List(ref mis) => {
584 for mi in mis.iter() {
585 if !mi.is_meta_item() {
589 AttrError::UnsupportedLiteral("unsupported literal", false),
595 // The unwraps below may look dangerous, but we've already asserted
596 // that they won't fail with the loop above.
597 match cfg.name_or_empty() {
600 .any(|mi| eval_condition(mi.meta_item().unwrap(), sess, features, eval)),
603 .all(|mi| eval_condition(mi.meta_item().unwrap(), sess, features, eval)),
607 sess.span_diagnostic,
610 "expected 1 cfg-pattern"
616 !eval_condition(mis[0].meta_item().unwrap(), sess, features, eval)
620 sess.span_diagnostic,
623 "invalid predicate `{}`",
624 pprust::path_to_string(&cfg.path)
631 ast::MetaItemKind::Word | ast::MetaItemKind::NameValue(..) => eval(cfg),
635 #[derive(Encodable, Decodable, Clone, HashStable_Generic)]
636 pub struct Deprecation {
637 pub since: Option<Symbol>,
638 /// The note to issue a reason.
639 pub note: Option<Symbol>,
640 /// A text snippet used to completely replace any use of the deprecated item in an expression.
642 /// This is currently unstable.
643 pub suggestion: Option<Symbol>,
645 /// Whether to treat the since attribute as being a Rust version identifier
646 /// (rather than an opaque string).
647 pub is_since_rustc_version: bool,
650 /// Finds the deprecation attribute. `None` if none exists.
651 pub fn find_deprecation(sess: &Session, attrs: &[Attribute], item_sp: Span) -> Option<Deprecation> {
652 find_deprecation_generic(sess, attrs.iter(), item_sp)
655 fn find_deprecation_generic<'a, I>(
659 ) -> Option<Deprecation>
661 I: Iterator<Item = &'a Attribute>,
663 let mut depr: Option<Deprecation> = None;
664 let diagnostic = &sess.parse_sess.span_diagnostic;
666 'outer: for attr in attrs_iter {
667 if !(sess.check_name(attr, sym::deprecated) || sess.check_name(attr, sym::rustc_deprecated))
673 struct_span_err!(diagnostic, item_sp, E0550, "multiple deprecated attributes").emit();
677 let meta = match attr.meta() {
681 let mut since = None;
683 let mut suggestion = None;
685 MetaItemKind::Word => {}
686 MetaItemKind::NameValue(..) => note = meta.value_str(),
687 MetaItemKind::List(list) => {
688 let get = |meta: &MetaItem, item: &mut Option<Symbol>| {
693 AttrError::MultipleItem(pprust::path_to_string(&meta.path)),
697 if let Some(v) = meta.value_str() {
701 if let Some(lit) = meta.name_value_literal() {
705 AttrError::UnsupportedLiteral(
706 "literal in `deprecated` \
707 value must be a string",
708 lit.kind.is_bytestr(),
712 struct_span_err!(diagnostic, meta.span, E0551, "incorrect meta item")
722 NestedMetaItem::MetaItem(mi) => match mi.name_or_empty() {
724 if !get(mi, &mut since) {
728 sym::note if sess.check_name(attr, sym::deprecated) => {
729 if !get(mi, &mut note) {
733 sym::reason if sess.check_name(attr, sym::rustc_deprecated) => {
734 if !get(mi, &mut note) {
738 sym::suggestion if sess.check_name(attr, sym::rustc_deprecated) => {
739 if !get(mi, &mut suggestion) {
747 AttrError::UnknownMetaItem(
748 pprust::path_to_string(&mi.path),
749 if sess.check_name(attr, sym::deprecated) {
752 &["since", "reason", "suggestion"]
759 NestedMetaItem::Literal(lit) => {
763 AttrError::UnsupportedLiteral(
764 "item in `deprecated` must be a key/value pair",
775 if suggestion.is_some() && sess.check_name(attr, sym::deprecated) {
776 unreachable!("only allowed on rustc_deprecated")
779 if sess.check_name(attr, sym::rustc_deprecated) {
781 handle_errors(&sess.parse_sess, attr.span, AttrError::MissingSince);
786 struct_span_err!(diagnostic, attr.span, E0543, "missing 'reason'").emit();
791 sess.mark_attr_used(&attr);
793 let is_since_rustc_version = sess.check_name(attr, sym::rustc_deprecated);
794 depr = Some(Deprecation { since, note, suggestion, is_since_rustc_version });
800 #[derive(PartialEq, Debug, Encodable, Decodable, Copy, Clone)]
811 #[derive(Eq, PartialEq, Debug, Copy, Clone)]
812 #[derive(Encodable, Decodable, HashStable_Generic)]
814 SignedInt(ast::IntTy),
815 UnsignedInt(ast::UintTy),
820 pub fn is_signed(self) -> bool {
824 SignedInt(..) => true,
825 UnsignedInt(..) => false,
830 /// Parse #[repr(...)] forms.
832 /// Valid repr contents: any of the primitive integral type names (see
833 /// `int_type_of_word`, below) to specify enum discriminant type; `C`, to use
834 /// the same discriminant size that the corresponding C enum would or C
835 /// structure layout, `packed` to remove padding, and `transparent` to elegate representation
836 /// concerns to the only non-ZST field.
837 pub fn find_repr_attrs(sess: &Session, attr: &Attribute) -> Vec<ReprAttr> {
840 let mut acc = Vec::new();
841 let diagnostic = &sess.parse_sess.span_diagnostic;
842 if attr.has_name(sym::repr) {
843 if let Some(items) = attr.meta_item_list() {
844 sess.mark_attr_used(attr);
846 if !item.is_meta_item() {
850 AttrError::UnsupportedLiteral(
851 "meta item in `repr` must be an identifier",
858 let mut recognised = false;
860 let hint = match item.name_or_empty() {
861 sym::C => Some(ReprC),
862 sym::packed => Some(ReprPacked(1)),
863 sym::simd => Some(ReprSimd),
864 sym::transparent => Some(ReprTransparent),
865 sym::no_niche => Some(ReprNoNiche),
866 name => int_type_of_word(name).map(ReprInt),
869 if let Some(h) = hint {
873 } else if let Some((name, value)) = item.name_value_literal() {
874 let parse_alignment = |node: &ast::LitKind| -> Result<u32, &'static str> {
875 if let ast::LitKind::Int(literal, ast::LitIntType::Unsuffixed) = node {
876 if literal.is_power_of_two() {
877 // rustc_middle::ty::layout::Align restricts align to <= 2^29
878 if *literal <= 1 << 29 {
881 Err("larger than 2^29")
884 Err("not a power of two")
887 Err("not an unsuffixed integer")
891 let mut literal_error = None;
892 if name == sym::align {
894 match parse_alignment(&value.kind) {
895 Ok(literal) => acc.push(ReprAlign(literal)),
896 Err(message) => literal_error = Some(message),
898 } else if name == sym::packed {
900 match parse_alignment(&value.kind) {
901 Ok(literal) => acc.push(ReprPacked(literal)),
902 Err(message) => literal_error = Some(message),
905 if let Some(literal_error) = literal_error {
910 "invalid `repr(align)` attribute: {}",
916 if let Some(meta_item) = item.meta_item() {
917 if meta_item.has_name(sym::align) {
918 if let MetaItemKind::NameValue(ref value) = meta_item.kind {
920 let mut err = struct_span_err!(
924 "incorrect `repr(align)` attribute format"
927 ast::LitKind::Int(int, ast::LitIntType::Unsuffixed) => {
930 "use parentheses instead",
931 format!("align({})", int),
932 Applicability::MachineApplicable,
935 ast::LitKind::Str(s, _) => {
938 "use parentheses instead",
939 format!("align({})", s),
940 Applicability::MachineApplicable,
951 // Not a word we recognize
956 "unrecognized representation hint"
966 fn int_type_of_word(s: Symbol) -> Option<IntType> {
970 sym::i8 => Some(SignedInt(ast::IntTy::I8)),
971 sym::u8 => Some(UnsignedInt(ast::UintTy::U8)),
972 sym::i16 => Some(SignedInt(ast::IntTy::I16)),
973 sym::u16 => Some(UnsignedInt(ast::UintTy::U16)),
974 sym::i32 => Some(SignedInt(ast::IntTy::I32)),
975 sym::u32 => Some(UnsignedInt(ast::UintTy::U32)),
976 sym::i64 => Some(SignedInt(ast::IntTy::I64)),
977 sym::u64 => Some(UnsignedInt(ast::UintTy::U64)),
978 sym::i128 => Some(SignedInt(ast::IntTy::I128)),
979 sym::u128 => Some(UnsignedInt(ast::UintTy::U128)),
980 sym::isize => Some(SignedInt(ast::IntTy::Isize)),
981 sym::usize => Some(UnsignedInt(ast::UintTy::Usize)),
986 pub enum TransparencyError {
987 UnknownTransparency(Symbol, Span),
988 MultipleTransparencyAttrs(Span, Span),
991 pub fn find_transparency(
995 ) -> (Transparency, Option<TransparencyError>) {
996 let mut transparency = None;
997 let mut error = None;
999 if sess.check_name(attr, sym::rustc_macro_transparency) {
1000 if let Some((_, old_span)) = transparency {
1001 error = Some(TransparencyError::MultipleTransparencyAttrs(old_span, attr.span));
1003 } else if let Some(value) = attr.value_str() {
1004 transparency = Some((
1006 sym::transparent => Transparency::Transparent,
1007 sym::semitransparent => Transparency::SemiTransparent,
1008 sym::opaque => Transparency::Opaque,
1010 error = Some(TransparencyError::UnknownTransparency(value, attr.span));
1019 let fallback = if macro_rules { Transparency::SemiTransparent } else { Transparency::Opaque };
1020 (transparency.map_or(fallback, |t| t.0), error)
1023 pub fn allow_internal_unstable<'a>(
1025 attrs: &[Attribute],
1026 ) -> Option<impl Iterator<Item = Symbol> + 'a> {
1027 let attr = sess.find_by_name(attrs, sym::allow_internal_unstable)?;
1028 let list = attr.meta_item_list().or_else(|| {
1030 .span_err(attr.span, "allow_internal_unstable expects list of feature names");
1033 Some(list.into_iter().filter_map(move |it| {
1034 let name = it.ident().map(|ident| ident.name);
1037 .span_err(it.span(), "`allow_internal_unstable` expects feature names");