1 //! Parsing and validation of builtin attributes
4 use rustc_ast::{Attribute, Lit, LitKind, MetaItem, MetaItemKind, NestedMetaItem, NodeId};
5 use rustc_ast_pretty::pprust;
6 use rustc_errors::{struct_span_err, Applicability};
7 use rustc_feature::{find_gated_cfg, is_builtin_attr_name, Features, GatedCfg};
8 use rustc_macros::HashStable_Generic;
9 use rustc_session::lint::builtin::UNEXPECTED_CFGS;
10 use rustc_session::lint::BuiltinLintDiagnostics;
11 use rustc_session::parse::{feature_err, ParseSess};
12 use rustc_session::Session;
13 use rustc_span::hygiene::Transparency;
14 use rustc_span::{symbol::sym, symbol::Symbol, Span};
15 use std::num::NonZeroU32;
17 pub fn is_builtin_attr(attr: &Attribute) -> bool {
18 attr.is_doc_comment() || attr.ident().filter(|ident| is_builtin_attr_name(ident.name)).is_some()
23 UnknownMetaItem(String, &'static [&'static str]),
27 MultipleStabilityLevels,
28 UnsupportedLiteral(&'static str, /* is_bytestr */ bool),
31 fn handle_errors(sess: &ParseSess, span: Span, error: AttrError) {
32 let diag = &sess.span_diagnostic;
34 AttrError::MultipleItem(item) => {
35 struct_span_err!(diag, span, E0538, "multiple '{}' items", item).emit();
37 AttrError::UnknownMetaItem(item, expected) => {
38 let expected = expected.iter().map(|name| format!("`{}`", name)).collect::<Vec<_>>();
39 struct_span_err!(diag, span, E0541, "unknown meta item '{}'", item)
40 .span_label(span, format!("expected one of {}", expected.join(", ")))
43 AttrError::MissingSince => {
44 struct_span_err!(diag, span, E0542, "missing 'since'").emit();
46 AttrError::NonIdentFeature => {
47 struct_span_err!(diag, span, E0546, "'feature' is not an identifier").emit();
49 AttrError::MissingFeature => {
50 struct_span_err!(diag, span, E0546, "missing 'feature'").emit();
52 AttrError::MultipleStabilityLevels => {
53 struct_span_err!(diag, span, E0544, "multiple stability levels").emit();
55 AttrError::UnsupportedLiteral(msg, is_bytestr) => {
56 let mut err = struct_span_err!(diag, span, E0565, "{}", msg);
58 if let Ok(lint_str) = sess.source_map().span_to_snippet(span) {
61 "consider removing the prefix",
63 Applicability::MaybeIncorrect,
72 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
80 #[derive(Clone, Encodable, Decodable, Debug, PartialEq, Eq, HashStable_Generic)]
81 pub enum InstructionSetAttr {
86 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
87 pub enum OptimizeAttr {
93 /// Represents the following attributes:
97 #[derive(Encodable, Decodable, Copy, Clone, Debug, PartialEq, Eq, Hash)]
98 #[derive(HashStable_Generic)]
99 pub struct Stability {
100 pub level: StabilityLevel,
105 pub fn is_unstable(&self) -> bool {
106 self.level.is_unstable()
109 pub fn is_stable(&self) -> bool {
110 self.level.is_stable()
114 /// Represents the `#[rustc_const_unstable]` and `#[rustc_const_stable]` attributes.
115 #[derive(Encodable, Decodable, Copy, Clone, Debug, PartialEq, Eq, Hash)]
116 #[derive(HashStable_Generic)]
117 pub struct ConstStability {
118 pub level: StabilityLevel,
120 /// whether the function has a `#[rustc_promotable]` attribute
121 pub promotable: bool,
124 impl ConstStability {
125 pub fn is_const_unstable(&self) -> bool {
126 self.level.is_unstable()
129 pub fn is_const_stable(&self) -> bool {
130 self.level.is_stable()
134 /// The available stability levels.
135 #[derive(Encodable, Decodable, PartialEq, Copy, Clone, Debug, Eq, Hash)]
136 #[derive(HashStable_Generic)]
137 pub enum StabilityLevel {
140 /// Reason for the current stability level.
141 reason: Option<Symbol>,
142 /// Relevant `rust-lang/rust` issue.
143 issue: Option<NonZeroU32>,
145 /// If part of a feature is stabilized and a new feature is added for the remaining parts,
146 /// then the `implied_by` attribute is used to indicate which now-stable feature previously
147 /// contained a item.
150 /// #[unstable(feature = "foo", issue = "...")]
152 /// #[unstable(feature = "foo", issue = "...")]
159 /// #[stable(feature = "foo", since = "1.XX.X")]
161 /// #[unstable(feature = "foobar", issue = "...", implied_by = "foo")]
164 implied_by: Option<Symbol>,
168 /// Rust release which stabilized this feature.
170 /// Is this item allowed to be referred to on stable, despite being contained in unstable
172 allowed_through_unstable_modules: bool,
176 impl StabilityLevel {
177 pub fn is_unstable(&self) -> bool {
178 matches!(self, StabilityLevel::Unstable { .. })
180 pub fn is_stable(&self) -> bool {
181 matches!(self, StabilityLevel::Stable { .. })
185 /// Collects stability info from all stability attributes in `attrs`.
186 /// Returns `None` if no stability attributes are found.
187 pub fn find_stability(
191 ) -> (Option<(Stability, Span)>, Option<(ConstStability, Span)>) {
192 find_stability_generic(sess, attrs.iter(), item_sp)
195 fn find_stability_generic<'a, I>(
199 ) -> (Option<(Stability, Span)>, Option<(ConstStability, Span)>)
201 I: Iterator<Item = &'a Attribute>,
203 use StabilityLevel::*;
205 let mut stab: Option<(Stability, Span)> = None;
206 let mut const_stab: Option<(ConstStability, Span)> = None;
207 let mut promotable = false;
208 let mut allowed_through_unstable_modules = false;
210 let diagnostic = &sess.parse_sess.span_diagnostic;
212 'outer: for attr in attrs_iter {
214 sym::rustc_const_unstable,
215 sym::rustc_const_stable,
218 sym::rustc_promotable,
219 sym::rustc_allowed_through_unstable_modules,
222 .any(|&s| attr.has_name(s))
224 continue; // not a stability level
227 let meta = attr.meta();
229 if attr.has_name(sym::rustc_promotable) {
231 } else if attr.has_name(sym::rustc_allowed_through_unstable_modules) {
232 allowed_through_unstable_modules = true;
234 // attributes with data
235 else if let Some(MetaItem { kind: MetaItemKind::List(ref metas), .. }) = meta {
236 let meta = meta.as_ref().unwrap();
237 let get = |meta: &MetaItem, item: &mut Option<Symbol>| {
242 AttrError::MultipleItem(pprust::path_to_string(&meta.path)),
246 if let Some(v) = meta.value_str() {
250 struct_span_err!(diagnostic, meta.span, E0539, "incorrect meta item").emit();
255 let meta_name = meta.name_or_empty();
257 sym::rustc_const_unstable | sym::unstable => {
258 if meta_name == sym::unstable && stab.is_some() {
262 AttrError::MultipleStabilityLevels,
265 } else if meta_name == sym::rustc_const_unstable && const_stab.is_some() {
269 AttrError::MultipleStabilityLevels,
274 let mut feature = None;
275 let mut reason = None;
276 let mut issue = None;
277 let mut issue_num = None;
278 let mut is_soft = false;
279 let mut implied_by = None;
281 let Some(mi) = meta.meta_item() else {
285 AttrError::UnsupportedLiteral("unsupported literal", false),
289 match mi.name_or_empty() {
291 if !get(mi, &mut feature) {
296 if !get(mi, &mut reason) {
301 if !get(mi, &mut issue) {
305 // These unwraps are safe because `get` ensures the meta item
306 // is a name/value pair string literal.
307 issue_num = match issue.unwrap().as_str() {
310 let emit_diag = |msg: &str| {
315 "`issue` must be a non-zero numeric string \
318 .span_label(mi.name_value_literal_span().unwrap(), msg)
321 match issue.parse() {
324 "`issue` must not be \"0\", \
325 use \"none\" instead",
329 Ok(num) => NonZeroU32::new(num),
331 emit_diag(&err.to_string());
340 let msg = "`soft` should not have any arguments";
341 sess.parse_sess.span_diagnostic.span_err(mi.span, msg);
346 if !get(mi, &mut implied_by) {
354 AttrError::UnknownMetaItem(
355 pprust::path_to_string(&mi.path),
356 &["feature", "reason", "issue", "soft"],
364 match (feature, reason, issue) {
365 (Some(feature), reason, Some(_)) => {
366 if !rustc_lexer::is_ident(feature.as_str()) {
370 AttrError::NonIdentFeature,
374 let level = Unstable { reason, issue: issue_num, is_soft, implied_by };
375 if sym::unstable == meta_name {
376 stab = Some((Stability { level, feature }, attr.span));
379 ConstStability { level, feature, promotable: false },
385 handle_errors(&sess.parse_sess, attr.span, AttrError::MissingFeature);
389 struct_span_err!(diagnostic, attr.span, E0547, "missing 'issue'")
395 sym::rustc_const_stable | sym::stable => {
396 if meta_name == sym::stable && stab.is_some() {
400 AttrError::MultipleStabilityLevels,
403 } else if meta_name == sym::rustc_const_stable && const_stab.is_some() {
407 AttrError::MultipleStabilityLevels,
412 let mut feature = None;
413 let mut since = None;
416 NestedMetaItem::MetaItem(mi) => match mi.name_or_empty() {
418 if !get(mi, &mut feature) {
423 if !get(mi, &mut since) {
431 AttrError::UnknownMetaItem(
432 pprust::path_to_string(&mi.path),
433 &["feature", "since"],
439 NestedMetaItem::Literal(lit) => {
443 AttrError::UnsupportedLiteral("unsupported literal", false),
450 match (feature, since) {
451 (Some(feature), Some(since)) => {
452 let level = Stable { since, allowed_through_unstable_modules: false };
453 if sym::stable == meta_name {
454 stab = Some((Stability { level, feature }, attr.span));
457 ConstStability { level, feature, promotable: false },
463 handle_errors(&sess.parse_sess, attr.span, AttrError::MissingFeature);
467 handle_errors(&sess.parse_sess, attr.span, AttrError::MissingSince);
477 // Merge the const-unstable info into the stability info
479 if let Some((ref mut stab, _)) = const_stab {
480 stab.promotable = promotable;
486 "`rustc_promotable` attribute must be paired with either a `rustc_const_unstable` \
487 or a `rustc_const_stable` attribute"
493 if allowed_through_unstable_modules {
496 level: StabilityLevel::Stable { ref mut allowed_through_unstable_modules, .. },
502 *allowed_through_unstable_modules = true;
508 "`rustc_allowed_through_unstable_modules` attribute must be paired with a `stable` attribute"
517 pub fn find_crate_name(sess: &Session, attrs: &[Attribute]) -> Option<Symbol> {
518 sess.first_attr_value_str_by_name(attrs, sym::crate_name)
521 #[derive(Clone, Debug)]
522 pub struct Condition {
525 pub value: Option<Symbol>,
526 pub value_span: Option<Span>,
530 /// Tests if a cfg-pattern matches the cfg set
534 lint_node_id: NodeId,
535 features: Option<&Features>,
537 eval_condition(cfg, sess, features, &mut |cfg| {
538 try_gate_cfg(cfg.name, cfg.span, sess, features);
539 if let Some(names_valid) = &sess.check_config.names_valid {
540 if !names_valid.contains(&cfg.name) {
541 sess.buffer_lint_with_diagnostic(
545 "unexpected `cfg` condition name",
546 BuiltinLintDiagnostics::UnexpectedCfg((cfg.name, cfg.name_span), None),
550 if let Some(value) = cfg.value {
551 if let Some(values) = &sess.check_config.values_valid.get(&cfg.name) {
552 if !values.contains(&value) {
553 sess.buffer_lint_with_diagnostic(
557 "unexpected `cfg` condition value",
558 BuiltinLintDiagnostics::UnexpectedCfg(
559 (cfg.name, cfg.name_span),
560 cfg.value_span.map(|vs| (value, vs)),
566 sess.config.contains(&(cfg.name, cfg.value))
570 fn try_gate_cfg(name: Symbol, span: Span, sess: &ParseSess, features: Option<&Features>) {
571 let gate = find_gated_cfg(|sym| sym == name);
572 if let (Some(feats), Some(gated_cfg)) = (features, gate) {
573 gate_cfg(&gated_cfg, span, sess, feats);
577 fn gate_cfg(gated_cfg: &GatedCfg, cfg_span: Span, sess: &ParseSess, features: &Features) {
578 let (cfg, feature, has_feature) = gated_cfg;
579 if !has_feature(features) && !cfg_span.allows_unstable(*feature) {
580 let explain = format!("`cfg({})` is experimental and subject to change", cfg);
581 feature_err(sess, *feature, cfg_span, &explain).emit();
585 #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
592 fn parse_version(s: &str, allow_appendix: bool) -> Option<Version> {
593 let mut components = s.split('-');
594 let d = components.next()?;
595 if !allow_appendix && components.next().is_some() {
598 let mut digits = d.splitn(3, '.');
599 let major = digits.next()?.parse().ok()?;
600 let minor = digits.next()?.parse().ok()?;
601 let patch = digits.next().unwrap_or("0").parse().ok()?;
602 Some(Version { major, minor, patch })
605 /// Evaluate a cfg-like condition (with `any` and `all`), using `eval` to
606 /// evaluate individual items.
607 pub fn eval_condition(
610 features: Option<&Features>,
611 eval: &mut impl FnMut(Condition) -> bool,
614 ast::MetaItemKind::List(ref mis) if cfg.name_or_empty() == sym::version => {
615 try_gate_cfg(sym::version, cfg.span, sess, features);
616 let (min_version, span) = match &mis[..] {
617 [NestedMetaItem::Literal(Lit { kind: LitKind::Str(sym, ..), span, .. })] => {
621 NestedMetaItem::Literal(Lit { span, .. })
622 | NestedMetaItem::MetaItem(MetaItem { span, .. }),
625 .struct_span_err(*span, "expected a version literal")
631 .struct_span_err(cfg.span, "expected single version literal")
636 let Some(min_version) = parse_version(min_version.as_str(), false) else {
640 "unknown version literal format, assuming it refers to a future version",
645 let rustc_version = parse_version(env!("CFG_RELEASE"), true).unwrap();
647 // See https://github.com/rust-lang/rust/issues/64796#issuecomment-640851454 for details
648 if sess.assume_incomplete_release {
649 rustc_version > min_version
651 rustc_version >= min_version
654 ast::MetaItemKind::List(ref mis) => {
655 for mi in mis.iter() {
656 if !mi.is_meta_item() {
660 AttrError::UnsupportedLiteral("unsupported literal", false),
666 // The unwraps below may look dangerous, but we've already asserted
667 // that they won't fail with the loop above.
668 match cfg.name_or_empty() {
671 // We don't use any() here, because we want to evaluate all cfg condition
672 // as eval_condition can (and does) extra checks
673 .fold(false, |res, mi| {
674 res | eval_condition(mi.meta_item().unwrap(), sess, features, eval)
678 // We don't use all() here, because we want to evaluate all cfg condition
679 // as eval_condition can (and does) extra checks
680 .fold(true, |res, mi| {
681 res & eval_condition(mi.meta_item().unwrap(), sess, features, eval)
686 sess.span_diagnostic,
689 "expected 1 cfg-pattern"
695 !eval_condition(mis[0].meta_item().unwrap(), sess, features, eval)
698 if let Some(features) = features && !features.cfg_target_compact {
701 sym::cfg_target_compact,
703 &"compact `cfg(target(..))` is experimental and subject to change"
707 mis.iter().fold(true, |res, mi| {
708 let mut mi = mi.meta_item().unwrap().clone();
709 if let [seg, ..] = &mut mi.path.segments[..] {
710 seg.ident.name = Symbol::intern(&format!("target_{}", seg.ident.name));
713 res & eval_condition(&mi, sess, features, eval)
718 sess.span_diagnostic,
721 "invalid predicate `{}`",
722 pprust::path_to_string(&cfg.path)
729 ast::MetaItemKind::Word | MetaItemKind::NameValue(..) if cfg.path.segments.len() != 1 => {
731 .span_err(cfg.path.span, "`cfg` predicate key must be an identifier");
734 MetaItemKind::NameValue(ref lit) if !lit.kind.is_str() => {
738 AttrError::UnsupportedLiteral(
739 "literal in `cfg` predicate value must be a string",
740 lit.kind.is_bytestr(),
745 ast::MetaItemKind::Word | ast::MetaItemKind::NameValue(..) => {
746 let ident = cfg.ident().expect("multi-segment cfg predicate");
749 name_span: ident.span,
750 value: cfg.value_str(),
751 value_span: cfg.name_value_literal_span(),
758 #[derive(Copy, Debug, Encodable, Decodable, Clone, HashStable_Generic)]
759 pub struct Deprecation {
760 pub since: Option<Symbol>,
761 /// The note to issue a reason.
762 pub note: Option<Symbol>,
763 /// A text snippet used to completely replace any use of the deprecated item in an expression.
765 /// This is currently unstable.
766 pub suggestion: Option<Symbol>,
768 /// Whether to treat the since attribute as being a Rust version identifier
769 /// (rather than an opaque string).
770 pub is_since_rustc_version: bool,
773 /// Finds the deprecation attribute. `None` if none exists.
774 pub fn find_deprecation(sess: &Session, attrs: &[Attribute]) -> Option<(Deprecation, Span)> {
775 find_deprecation_generic(sess, attrs.iter())
778 fn find_deprecation_generic<'a, I>(sess: &Session, attrs_iter: I) -> Option<(Deprecation, Span)>
780 I: Iterator<Item = &'a Attribute>,
782 let mut depr: Option<(Deprecation, Span)> = None;
783 let diagnostic = &sess.parse_sess.span_diagnostic;
784 let is_rustc = sess.features_untracked().staged_api;
786 'outer: for attr in attrs_iter {
787 if !attr.has_name(sym::deprecated) {
791 let Some(meta) = attr.meta() else {
794 let mut since = None;
796 let mut suggestion = None;
798 MetaItemKind::Word => {}
799 MetaItemKind::NameValue(..) => note = meta.value_str(),
800 MetaItemKind::List(list) => {
801 let get = |meta: &MetaItem, item: &mut Option<Symbol>| {
806 AttrError::MultipleItem(pprust::path_to_string(&meta.path)),
810 if let Some(v) = meta.value_str() {
814 if let Some(lit) = meta.name_value_literal() {
818 AttrError::UnsupportedLiteral(
819 "literal in `deprecated` \
820 value must be a string",
821 lit.kind.is_bytestr(),
825 struct_span_err!(diagnostic, meta.span, E0551, "incorrect meta item")
835 NestedMetaItem::MetaItem(mi) => match mi.name_or_empty() {
837 if !get(mi, &mut since) {
842 if !get(mi, &mut note) {
847 if !sess.features_untracked().deprecated_suggestion {
848 let mut diag = sess.struct_span_err(
850 "suggestions on deprecated items are unstable",
852 if sess.is_nightly_build() {
853 diag.help("add `#![feature(deprecated_suggestion)]` to the crate root");
855 diag.note("see #94785 for more details").emit();
858 if !get(mi, &mut suggestion) {
866 AttrError::UnknownMetaItem(
867 pprust::path_to_string(&mi.path),
868 if sess.features_untracked().deprecated_suggestion {
869 &["since", "note", "suggestion"]
878 NestedMetaItem::Literal(lit) => {
882 AttrError::UnsupportedLiteral(
883 "item in `deprecated` must be a key/value pair",
896 handle_errors(&sess.parse_sess, attr.span, AttrError::MissingSince);
901 struct_span_err!(diagnostic, attr.span, E0543, "missing 'note'").emit();
907 Deprecation { since, note, suggestion, is_since_rustc_version: is_rustc },
915 #[derive(PartialEq, Debug, Encodable, Decodable, Copy, Clone)]
925 #[derive(Eq, PartialEq, Debug, Copy, Clone)]
926 #[derive(Encodable, Decodable, HashStable_Generic)]
928 SignedInt(ast::IntTy),
929 UnsignedInt(ast::UintTy),
934 pub fn is_signed(self) -> bool {
938 SignedInt(..) => true,
939 UnsignedInt(..) => false,
944 /// Parse #[repr(...)] forms.
946 /// Valid repr contents: any of the primitive integral type names (see
947 /// `int_type_of_word`, below) to specify enum discriminant type; `C`, to use
948 /// the same discriminant size that the corresponding C enum would or C
949 /// structure layout, `packed` to remove padding, and `transparent` to delegate representation
950 /// concerns to the only non-ZST field.
951 pub fn find_repr_attrs(sess: &Session, attr: &Attribute) -> Vec<ReprAttr> {
952 if attr.has_name(sym::repr) { parse_repr_attr(sess, attr) } else { Vec::new() }
955 pub fn parse_repr_attr(sess: &Session, attr: &Attribute) -> Vec<ReprAttr> {
956 assert!(attr.has_name(sym::repr), "expected `#[repr(..)]`, found: {:?}", attr);
958 let mut acc = Vec::new();
959 let diagnostic = &sess.parse_sess.span_diagnostic;
961 if let Some(items) = attr.meta_item_list() {
963 let mut recognised = false;
965 let hint = match item.name_or_empty() {
966 sym::C => Some(ReprC),
967 sym::packed => Some(ReprPacked(1)),
968 sym::simd => Some(ReprSimd),
969 sym::transparent => Some(ReprTransparent),
971 let mut err = struct_span_err!(
975 "invalid `repr(align)` attribute: `align` needs an argument"
979 "supply an argument here",
981 Applicability::HasPlaceholders,
987 name => int_type_of_word(name).map(ReprInt),
990 if let Some(h) = hint {
994 } else if let Some((name, value)) = item.name_value_literal() {
995 let mut literal_error = None;
996 if name == sym::align {
998 match parse_alignment(&value.kind) {
999 Ok(literal) => acc.push(ReprAlign(literal)),
1000 Err(message) => literal_error = Some(message),
1002 } else if name == sym::packed {
1004 match parse_alignment(&value.kind) {
1005 Ok(literal) => acc.push(ReprPacked(literal)),
1006 Err(message) => literal_error = Some(message),
1008 } else if matches!(name, sym::C | sym::simd | sym::transparent)
1009 || int_type_of_word(name).is_some()
1016 "invalid representation hint: `{}` does not take a parenthesized argument list",
1017 name.to_ident_string(),
1020 if let Some(literal_error) = literal_error {
1025 "invalid `repr({})` attribute: {}",
1026 name.to_ident_string(),
1031 } else if let Some(meta_item) = item.meta_item() {
1032 if let MetaItemKind::NameValue(ref value) = meta_item.kind {
1033 if meta_item.has_name(sym::align) || meta_item.has_name(sym::packed) {
1034 let name = meta_item.name_or_empty().to_ident_string();
1036 let mut err = struct_span_err!(
1040 "incorrect `repr({})` attribute format",
1044 ast::LitKind::Int(int, ast::LitIntType::Unsuffixed) => {
1045 err.span_suggestion(
1047 "use parentheses instead",
1048 format!("{}({})", name, int),
1049 Applicability::MachineApplicable,
1052 ast::LitKind::Str(s, _) => {
1053 err.span_suggestion(
1055 "use parentheses instead",
1056 format!("{}({})", name, s),
1057 Applicability::MachineApplicable,
1065 meta_item.name_or_empty(),
1066 sym::C | sym::simd | sym::transparent
1067 ) || int_type_of_word(meta_item.name_or_empty()).is_some()
1074 "invalid representation hint: `{}` does not take a value",
1075 meta_item.name_or_empty().to_ident_string(),
1080 } else if let MetaItemKind::List(_) = meta_item.kind {
1081 if meta_item.has_name(sym::align) {
1087 "incorrect `repr(align)` attribute format: \
1088 `align` takes exactly one argument in parentheses"
1091 } else if meta_item.has_name(sym::packed) {
1097 "incorrect `repr(packed)` attribute format: \
1098 `packed` takes exactly one parenthesized argument, \
1099 or no parentheses at all"
1103 meta_item.name_or_empty(),
1104 sym::C | sym::simd | sym::transparent
1105 ) || int_type_of_word(meta_item.name_or_empty()).is_some()
1112 "invalid representation hint: `{}` does not take a parenthesized argument list",
1113 meta_item.name_or_empty().to_ident_string(),
1119 // Not a word we recognize. This will be caught and reported by
1120 // the `check_mod_attrs` pass, but this pass doesn't always run
1121 // (e.g. if we only pretty-print the source), so we have to gate
1122 // the `delay_span_bug` call as follows:
1123 if sess.opts.pretty.map_or(true, |pp| pp.needs_analysis()) {
1124 diagnostic.delay_span_bug(item.span(), "unrecognized representation hint");
1132 fn int_type_of_word(s: Symbol) -> Option<IntType> {
1136 sym::i8 => Some(SignedInt(ast::IntTy::I8)),
1137 sym::u8 => Some(UnsignedInt(ast::UintTy::U8)),
1138 sym::i16 => Some(SignedInt(ast::IntTy::I16)),
1139 sym::u16 => Some(UnsignedInt(ast::UintTy::U16)),
1140 sym::i32 => Some(SignedInt(ast::IntTy::I32)),
1141 sym::u32 => Some(UnsignedInt(ast::UintTy::U32)),
1142 sym::i64 => Some(SignedInt(ast::IntTy::I64)),
1143 sym::u64 => Some(UnsignedInt(ast::UintTy::U64)),
1144 sym::i128 => Some(SignedInt(ast::IntTy::I128)),
1145 sym::u128 => Some(UnsignedInt(ast::UintTy::U128)),
1146 sym::isize => Some(SignedInt(ast::IntTy::Isize)),
1147 sym::usize => Some(UnsignedInt(ast::UintTy::Usize)),
1152 pub enum TransparencyError {
1153 UnknownTransparency(Symbol, Span),
1154 MultipleTransparencyAttrs(Span, Span),
1157 pub fn find_transparency(
1158 attrs: &[Attribute],
1160 ) -> (Transparency, Option<TransparencyError>) {
1161 let mut transparency = None;
1162 let mut error = None;
1164 if attr.has_name(sym::rustc_macro_transparency) {
1165 if let Some((_, old_span)) = transparency {
1166 error = Some(TransparencyError::MultipleTransparencyAttrs(old_span, attr.span));
1168 } else if let Some(value) = attr.value_str() {
1169 transparency = Some((
1171 sym::transparent => Transparency::Transparent,
1172 sym::semitransparent => Transparency::SemiTransparent,
1173 sym::opaque => Transparency::Opaque,
1175 error = Some(TransparencyError::UnknownTransparency(value, attr.span));
1184 let fallback = if macro_rules { Transparency::SemiTransparent } else { Transparency::Opaque };
1185 (transparency.map_or(fallback, |t| t.0), error)
1188 pub fn allow_internal_unstable<'a>(
1190 attrs: &'a [Attribute],
1191 ) -> impl Iterator<Item = Symbol> + 'a {
1192 allow_unstable(sess, attrs, sym::allow_internal_unstable)
1195 pub fn rustc_allow_const_fn_unstable<'a>(
1197 attrs: &'a [Attribute],
1198 ) -> impl Iterator<Item = Symbol> + 'a {
1199 allow_unstable(sess, attrs, sym::rustc_allow_const_fn_unstable)
1202 fn allow_unstable<'a>(
1204 attrs: &'a [Attribute],
1206 ) -> impl Iterator<Item = Symbol> + 'a {
1207 let attrs = sess.filter_by_name(attrs, symbol);
1209 .filter_map(move |attr| {
1210 attr.meta_item_list().or_else(|| {
1211 sess.diagnostic().span_err(
1213 &format!("`{}` expects a list of feature names", symbol.to_ident_string()),
1220 list.into_iter().filter_map(move |it| {
1221 let name = it.ident().map(|ident| ident.name);
1223 sess.diagnostic().span_err(
1225 &format!("`{}` expects feature names", symbol.to_ident_string()),
1232 pub fn parse_alignment(node: &ast::LitKind) -> Result<u32, &'static str> {
1233 if let ast::LitKind::Int(literal, ast::LitIntType::Unsuffixed) = node {
1234 if literal.is_power_of_two() {
1235 // rustc_middle::ty::layout::Align restricts align to <= 2^29
1236 if *literal <= 1 << 29 { Ok(*literal as u32) } else { Err("larger than 2^29") }
1238 Err("not a power of two")
1241 Err("not an unsuffixed integer")