Skip to main content

rustc_attr_parsing/attributes/
codegen_attrs.rs

1use rustc_hir::attrs::{CoverageAttrKind, OptimizeAttr, RtsanSetting, SanitizerSet, UsedBy};
2use rustc_session::parse::feature_err;
3
4use super::prelude::*;
5use crate::session_diagnostics::{
6    NakedFunctionIncompatibleAttribute, NullOnExport, NullOnObjcClass, NullOnObjcSelector,
7    ObjcClassExpectedStringLiteral, ObjcSelectorExpectedStringLiteral,
8};
9use crate::target_checking::Policy::AllowSilent;
10
11pub(crate) struct OptimizeParser;
12
13impl<S: Stage> SingleAttributeParser<S> for OptimizeParser {
14    const PATH: &[Symbol] = &[sym::optimize];
15    const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::WarnButFutureError;
16    const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[
17        Allow(Target::Fn),
18        Allow(Target::Closure),
19        Allow(Target::Method(MethodKind::Trait { body: true })),
20        Allow(Target::Method(MethodKind::TraitImpl)),
21        Allow(Target::Method(MethodKind::Inherent)),
22    ]);
23    const TEMPLATE: AttributeTemplate = ::rustc_feature::AttributeTemplate {
    word: false,
    list: Some(&["size", "speed", "none"]),
    one_of: &[],
    name_value_str: None,
    docs: None,
}template!(List: &["size", "speed", "none"]);
24
25    fn convert(cx: &mut AcceptContext<'_, '_, S>, args: &ArgParser) -> Option<AttributeKind> {
26        let Some(list) = args.list() else {
27            let attr_span = cx.attr_span;
28            cx.adcx().expected_list(attr_span, args);
29            return None;
30        };
31
32        let Some(single) = list.single() else {
33            cx.adcx().expected_single_argument(list.span);
34            return None;
35        };
36
37        let res = match single.meta_item().and_then(|i| i.path().word().map(|i| i.name)) {
38            Some(sym::size) => OptimizeAttr::Size,
39            Some(sym::speed) => OptimizeAttr::Speed,
40            Some(sym::none) => OptimizeAttr::DoNotOptimize,
41            _ => {
42                cx.adcx()
43                    .expected_specific_argument(single.span(), &[sym::size, sym::speed, sym::none]);
44                OptimizeAttr::Default
45            }
46        };
47
48        Some(AttributeKind::Optimize(res, cx.attr_span))
49    }
50}
51
52pub(crate) struct ColdParser;
53
54impl<S: Stage> NoArgsAttributeParser<S> for ColdParser {
55    const PATH: &[Symbol] = &[sym::cold];
56    const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Warn;
57    const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowListWarnRest(&[
58        Allow(Target::Fn),
59        Allow(Target::Method(MethodKind::Trait { body: true })),
60        Allow(Target::Method(MethodKind::TraitImpl)),
61        Allow(Target::Method(MethodKind::Inherent)),
62        Allow(Target::ForeignFn),
63        Allow(Target::Closure),
64    ]);
65    const CREATE: fn(Span) -> AttributeKind = AttributeKind::Cold;
66}
67
68pub(crate) struct CoverageParser;
69
70impl<S: Stage> SingleAttributeParser<S> for CoverageParser {
71    const PATH: &[Symbol] = &[sym::coverage];
72    const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
73    const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[
74        Allow(Target::Fn),
75        Allow(Target::Closure),
76        Allow(Target::Method(MethodKind::Trait { body: true })),
77        Allow(Target::Method(MethodKind::TraitImpl)),
78        Allow(Target::Method(MethodKind::Inherent)),
79        Allow(Target::Impl { of_trait: true }),
80        Allow(Target::Impl { of_trait: false }),
81        Allow(Target::Mod),
82        Allow(Target::Crate),
83    ]);
84    const TEMPLATE: AttributeTemplate = ::rustc_feature::AttributeTemplate {
    word: false,
    list: None,
    one_of: &[sym::off, sym::on],
    name_value_str: None,
    docs: None,
}template!(OneOf: &[sym::off, sym::on]);
85
86    fn convert(cx: &mut AcceptContext<'_, '_, S>, args: &ArgParser) -> Option<AttributeKind> {
87        let Some(args) = args.list() else {
88            let attr_span = cx.attr_span;
89            cx.adcx().expected_specific_argument_and_list(attr_span, &[sym::on, sym::off]);
90            return None;
91        };
92
93        let Some(arg) = args.single() else {
94            cx.adcx().expected_single_argument(args.span);
95            return None;
96        };
97
98        let mut fail_incorrect_argument =
99            |span| cx.adcx().expected_specific_argument(span, &[sym::on, sym::off]);
100
101        let Some(arg) = arg.meta_item() else {
102            fail_incorrect_argument(args.span);
103            return None;
104        };
105
106        let kind = match arg.path().word_sym() {
107            Some(sym::off) => CoverageAttrKind::Off,
108            Some(sym::on) => CoverageAttrKind::On,
109            None | Some(_) => {
110                fail_incorrect_argument(arg.span());
111                return None;
112            }
113        };
114
115        Some(AttributeKind::Coverage(cx.attr_span, kind))
116    }
117}
118
119pub(crate) struct ExportNameParser;
120
121impl<S: Stage> SingleAttributeParser<S> for ExportNameParser {
122    const PATH: &[rustc_span::Symbol] = &[sym::export_name];
123    const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::WarnButFutureError;
124    const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[
125        Allow(Target::Static),
126        Allow(Target::Fn),
127        Allow(Target::Method(MethodKind::Inherent)),
128        Allow(Target::Method(MethodKind::Trait { body: true })),
129        Allow(Target::Method(MethodKind::TraitImpl)),
130        Warn(Target::Field),
131        Warn(Target::Arm),
132        Warn(Target::MacroDef),
133        Warn(Target::MacroCall),
134    ]);
135    const TEMPLATE: AttributeTemplate = ::rustc_feature::AttributeTemplate {
    word: false,
    list: None,
    one_of: &[],
    name_value_str: Some(&["name"]),
    docs: None,
}template!(NameValueStr: "name");
136
137    fn convert(cx: &mut AcceptContext<'_, '_, S>, args: &ArgParser) -> Option<AttributeKind> {
138        let Some(nv) = args.name_value() else {
139            let attr_span = cx.attr_span;
140            cx.adcx().expected_name_value(attr_span, None);
141            return None;
142        };
143        let Some(name) = nv.value_as_str() else {
144            cx.adcx().expected_string_literal(nv.value_span, Some(nv.value_as_lit()));
145            return None;
146        };
147        if name.as_str().contains('\0') {
148            // `#[export_name = ...]` will be converted to a null-terminated string,
149            // so it may not contain any null characters.
150            cx.emit_err(NullOnExport { span: cx.attr_span });
151            return None;
152        }
153        Some(AttributeKind::ExportName { name, span: cx.attr_span })
154    }
155}
156
157pub(crate) struct RustcObjcClassParser;
158
159impl<S: Stage> SingleAttributeParser<S> for RustcObjcClassParser {
160    const PATH: &[rustc_span::Symbol] = &[sym::rustc_objc_class];
161    const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
162    const ALLOWED_TARGETS: AllowedTargets =
163        AllowedTargets::AllowList(&[Allow(Target::ForeignStatic)]);
164    const TEMPLATE: AttributeTemplate = ::rustc_feature::AttributeTemplate {
    word: false,
    list: None,
    one_of: &[],
    name_value_str: Some(&["ClassName"]),
    docs: None,
}template!(NameValueStr: "ClassName");
165
166    fn convert(cx: &mut AcceptContext<'_, '_, S>, args: &ArgParser) -> Option<AttributeKind> {
167        let Some(nv) = args.name_value() else {
168            let attr_span = cx.attr_span;
169            cx.adcx().expected_name_value(attr_span, None);
170            return None;
171        };
172        let Some(classname) = nv.value_as_str() else {
173            // `#[rustc_objc_class = ...]` is expected to be used as an implementation detail
174            // inside a standard library macro, but `cx.expected_string_literal` exposes too much.
175            // Use a custom error message instead.
176            cx.emit_err(ObjcClassExpectedStringLiteral { span: nv.value_span });
177            return None;
178        };
179        if classname.as_str().contains('\0') {
180            // `#[rustc_objc_class = ...]` will be converted to a null-terminated string,
181            // so it may not contain any null characters.
182            cx.emit_err(NullOnObjcClass { span: nv.value_span });
183            return None;
184        }
185        Some(AttributeKind::RustcObjcClass { classname, span: cx.attr_span })
186    }
187}
188
189pub(crate) struct RustcObjcSelectorParser;
190
191impl<S: Stage> SingleAttributeParser<S> for RustcObjcSelectorParser {
192    const PATH: &[rustc_span::Symbol] = &[sym::rustc_objc_selector];
193    const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
194    const ALLOWED_TARGETS: AllowedTargets =
195        AllowedTargets::AllowList(&[Allow(Target::ForeignStatic)]);
196    const TEMPLATE: AttributeTemplate = ::rustc_feature::AttributeTemplate {
    word: false,
    list: None,
    one_of: &[],
    name_value_str: Some(&["methodName"]),
    docs: None,
}template!(NameValueStr: "methodName");
197
198    fn convert(cx: &mut AcceptContext<'_, '_, S>, args: &ArgParser) -> Option<AttributeKind> {
199        let Some(nv) = args.name_value() else {
200            let attr_span = cx.attr_span;
201            cx.adcx().expected_name_value(attr_span, None);
202            return None;
203        };
204        let Some(methname) = nv.value_as_str() else {
205            // `#[rustc_objc_selector = ...]` is expected to be used as an implementation detail
206            // inside a standard library macro, but `cx.expected_string_literal` exposes too much.
207            // Use a custom error message instead.
208            cx.emit_err(ObjcSelectorExpectedStringLiteral { span: nv.value_span });
209            return None;
210        };
211        if methname.as_str().contains('\0') {
212            // `#[rustc_objc_selector = ...]` will be converted to a null-terminated string,
213            // so it may not contain any null characters.
214            cx.emit_err(NullOnObjcSelector { span: nv.value_span });
215            return None;
216        }
217        Some(AttributeKind::RustcObjcSelector { methname, span: cx.attr_span })
218    }
219}
220
221#[derive(#[automatically_derived]
impl ::core::default::Default for NakedParser {
    #[inline]
    fn default() -> NakedParser {
        NakedParser { span: ::core::default::Default::default() }
    }
}Default)]
222pub(crate) struct NakedParser {
223    span: Option<Span>,
224}
225
226impl<S: Stage> AttributeParser<S> for NakedParser {
227    const ATTRIBUTES: AcceptMapping<Self, S> =
228        &[(&[sym::naked], ::rustc_feature::AttributeTemplate {
    word: true,
    list: None,
    one_of: &[],
    name_value_str: None,
    docs: None,
}template!(Word), |this, cx, args| {
229            if let Err(span) = args.no_args() {
230                cx.adcx().expected_no_args(span);
231                return;
232            }
233
234            if let Some(earlier) = this.span {
235                let span = cx.attr_span;
236                cx.warn_unused_duplicate(earlier, span);
237            } else {
238                this.span = Some(cx.attr_span);
239            }
240        })];
241    const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[
242        Allow(Target::Fn),
243        Allow(Target::Method(MethodKind::Inherent)),
244        Allow(Target::Method(MethodKind::Trait { body: true })),
245        Allow(Target::Method(MethodKind::TraitImpl)),
246        Warn(Target::MacroCall),
247    ]);
248
249    fn finalize(self, cx: &FinalizeContext<'_, '_, S>) -> Option<AttributeKind> {
250        // FIXME(jdonszelmann): upgrade this list to *parsed* attributes
251        // once all of these have parsed forms. That'd make the check much nicer...
252        //
253        // many attributes don't make sense in combination with #[naked].
254        // Notable attributes that are incompatible with `#[naked]` are:
255        //
256        // * `#[inline]`
257        // * `#[track_caller]`
258        // * `#[test]`, `#[ignore]`, `#[should_panic]`
259        //
260        // NOTE: when making changes to this list, check that `error_codes/E0736.md` remains
261        // accurate.
262        const ALLOW_LIST: &[rustc_span::Symbol] = &[
263            // conditional compilation
264            sym::cfg_trace,
265            sym::cfg_attr_trace,
266            // testing (allowed here so better errors can be generated in `rustc_builtin_macros::test`)
267            sym::test,
268            sym::ignore,
269            sym::should_panic,
270            sym::bench,
271            // diagnostics
272            sym::allow,
273            sym::warn,
274            sym::deny,
275            sym::forbid,
276            sym::deprecated,
277            sym::must_use,
278            // abi, linking and FFI
279            sym::cold,
280            sym::export_name,
281            sym::link_section,
282            sym::linkage,
283            sym::no_mangle,
284            sym::instruction_set,
285            sym::repr,
286            sym::rustc_std_internal_symbol,
287            // FIXME(#82232, #143834): temporarily renamed to mitigate `#[align]` nameres ambiguity
288            sym::rustc_align,
289            sym::rustc_align_static,
290            // obviously compatible with self
291            sym::naked,
292            // documentation
293            sym::doc,
294        ];
295
296        let span = self.span?;
297
298        // only if we found a naked attribute do we do the somewhat expensive check
299        'outer: for other_attr in cx.all_attrs {
300            for allowed_attr in ALLOW_LIST {
301                if other_attr.segments().next().is_some_and(|i| cx.tools.contains(&i.name)) {
302                    // effectively skips the error message  being emitted below
303                    // if it's a tool attribute
304                    continue 'outer;
305                }
306                if other_attr.word_is(*allowed_attr) {
307                    // effectively skips the error message  being emitted below
308                    // if its an allowed attribute
309                    continue 'outer;
310                }
311
312                if other_attr.word_is(sym::target_feature) {
313                    if !cx.features().naked_functions_target_feature() {
314                        feature_err(
315                            &cx.sess(),
316                            sym::naked_functions_target_feature,
317                            other_attr.span(),
318                            "`#[target_feature(/* ... */)]` is currently unstable on `#[naked]` functions",
319                        ).emit();
320                    }
321
322                    continue 'outer;
323                }
324            }
325
326            cx.emit_err(NakedFunctionIncompatibleAttribute {
327                span: other_attr.span(),
328                naked_span: span,
329                attr: other_attr.get_attribute_path().to_string(),
330            });
331        }
332
333        Some(AttributeKind::Naked(span))
334    }
335}
336
337pub(crate) struct TrackCallerParser;
338impl<S: Stage> NoArgsAttributeParser<S> for TrackCallerParser {
339    const PATH: &[Symbol] = &[sym::track_caller];
340    const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Warn;
341    const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[
342        Allow(Target::Fn),
343        Allow(Target::Method(MethodKind::Inherent)),
344        Allow(Target::Method(MethodKind::Trait { body: true })),
345        Allow(Target::Method(MethodKind::TraitImpl)),
346        Allow(Target::Method(MethodKind::Trait { body: false })), // `#[track_caller]` is inherited from trait methods
347        Allow(Target::ForeignFn),
348        Allow(Target::Closure),
349        Warn(Target::MacroDef),
350        Warn(Target::Arm),
351        Warn(Target::Field),
352        Warn(Target::MacroCall),
353    ]);
354    const CREATE: fn(Span) -> AttributeKind = AttributeKind::TrackCaller;
355}
356
357pub(crate) struct NoMangleParser;
358impl<S: Stage> NoArgsAttributeParser<S> for NoMangleParser {
359    const PATH: &[Symbol] = &[sym::no_mangle];
360    const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Warn;
361    const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowListWarnRest(&[
362        Allow(Target::Fn),
363        Allow(Target::Static),
364        Allow(Target::Method(MethodKind::Inherent)),
365        Allow(Target::Method(MethodKind::TraitImpl)),
366        AllowSilent(Target::Const), // Handled in the `InvalidNoMangleItems` pass
367        Error(Target::Closure),
368    ]);
369    const CREATE: fn(Span) -> AttributeKind = AttributeKind::NoMangle;
370}
371
372#[derive(#[automatically_derived]
impl ::core::default::Default for UsedParser {
    #[inline]
    fn default() -> UsedParser {
        UsedParser {
            first_compiler: ::core::default::Default::default(),
            first_linker: ::core::default::Default::default(),
            first_default: ::core::default::Default::default(),
        }
    }
}Default)]
373pub(crate) struct UsedParser {
374    first_compiler: Option<Span>,
375    first_linker: Option<Span>,
376    first_default: Option<Span>,
377}
378
379// A custom `AttributeParser` is used rather than a Simple attribute parser because
380// - Specifying two `#[used]` attributes is a warning (but will be an error in the future)
381// - But specifying two conflicting attributes: `#[used(compiler)]` and `#[used(linker)]` is already an error today
382// We can change this to a Simple parser once the warning becomes an error
383impl<S: Stage> AttributeParser<S> for UsedParser {
384    const ATTRIBUTES: AcceptMapping<Self, S> = &[(
385        &[sym::used],
386        ::rustc_feature::AttributeTemplate {
    word: true,
    list: Some(&["compiler", "linker"]),
    one_of: &[],
    name_value_str: None,
    docs: None,
}template!(Word, List: &["compiler", "linker"]),
387        |group: &mut Self, cx, args| {
388            let used_by = match args {
389                ArgParser::NoArgs => UsedBy::Default,
390                ArgParser::List(list) => {
391                    let Some(l) = list.single() else {
392                        cx.adcx().expected_single_argument(list.span);
393                        return;
394                    };
395
396                    match l.meta_item().and_then(|i| i.path().word_sym()) {
397                        Some(sym::compiler) => {
398                            if !cx.features().used_with_arg() {
399                                feature_err(
400                                    &cx.sess(),
401                                    sym::used_with_arg,
402                                    cx.attr_span,
403                                    "`#[used(compiler)]` is currently unstable",
404                                )
405                                .emit();
406                            }
407                            UsedBy::Compiler
408                        }
409                        Some(sym::linker) => {
410                            if !cx.features().used_with_arg() {
411                                feature_err(
412                                    &cx.sess(),
413                                    sym::used_with_arg,
414                                    cx.attr_span,
415                                    "`#[used(linker)]` is currently unstable",
416                                )
417                                .emit();
418                            }
419                            UsedBy::Linker
420                        }
421                        _ => {
422                            cx.adcx().expected_specific_argument(
423                                l.span(),
424                                &[sym::compiler, sym::linker],
425                            );
426                            return;
427                        }
428                    }
429                }
430                ArgParser::NameValue(_) => return,
431            };
432
433            let attr_span = cx.attr_span;
434
435            // `#[used]` is interpreted as `#[used(linker)]` (though depending on target OS the
436            // circumstances are more complicated). While we're checking `used_by`, also report
437            // these cross-`UsedBy` duplicates to warn.
438            let target = match used_by {
439                UsedBy::Compiler => &mut group.first_compiler,
440                UsedBy::Linker => {
441                    if let Some(prev) = group.first_default {
442                        cx.warn_unused_duplicate(prev, attr_span);
443                        return;
444                    }
445                    &mut group.first_linker
446                }
447                UsedBy::Default => {
448                    if let Some(prev) = group.first_linker {
449                        cx.warn_unused_duplicate(prev, attr_span);
450                        return;
451                    }
452                    &mut group.first_default
453                }
454            };
455
456            if let Some(prev) = *target {
457                cx.warn_unused_duplicate(prev, attr_span);
458            } else {
459                *target = Some(attr_span);
460            }
461        },
462    )];
463    const ALLOWED_TARGETS: AllowedTargets =
464        AllowedTargets::AllowList(&[Allow(Target::Static), Warn(Target::MacroCall)]);
465
466    fn finalize(self, _cx: &FinalizeContext<'_, '_, S>) -> Option<AttributeKind> {
467        // If a specific form of `used` is specified, it takes precedence over generic `#[used]`.
468        // If both `linker` and `compiler` are specified, use `linker`.
469        Some(match (self.first_compiler, self.first_linker, self.first_default) {
470            (_, Some(span), _) => AttributeKind::Used { used_by: UsedBy::Linker, span },
471            (Some(span), _, _) => AttributeKind::Used { used_by: UsedBy::Compiler, span },
472            (_, _, Some(span)) => AttributeKind::Used { used_by: UsedBy::Default, span },
473            (None, None, None) => return None,
474        })
475    }
476}
477
478fn parse_tf_attribute<S: Stage>(
479    cx: &mut AcceptContext<'_, '_, S>,
480    args: &ArgParser,
481) -> impl IntoIterator<Item = (Symbol, Span)> {
482    let mut features = Vec::new();
483    let ArgParser::List(list) = args else {
484        let attr_span = cx.attr_span;
485        cx.adcx().expected_list(attr_span, args);
486        return features;
487    };
488    if list.is_empty() {
489        let attr_span = cx.attr_span;
490        cx.adcx().warn_empty_attribute(attr_span);
491        return features;
492    }
493    for item in list.mixed() {
494        let Some(name_value) = item.meta_item() else {
495            cx.adcx().expected_name_value(item.span(), Some(sym::enable));
496            return features;
497        };
498
499        // Validate name
500        let Some(name) = name_value.path().word_sym() else {
501            cx.adcx().expected_name_value(name_value.path().span(), Some(sym::enable));
502            return features;
503        };
504        if name != sym::enable {
505            cx.adcx().expected_name_value(name_value.path().span(), Some(sym::enable));
506            return features;
507        }
508
509        // Use value
510        let Some(name_value) = name_value.args().name_value() else {
511            cx.adcx().expected_name_value(item.span(), Some(sym::enable));
512            return features;
513        };
514        let Some(value_str) = name_value.value_as_str() else {
515            cx.adcx()
516                .expected_string_literal(name_value.value_span, Some(name_value.value_as_lit()));
517            return features;
518        };
519        for feature in value_str.as_str().split(",") {
520            features.push((Symbol::intern(feature), item.span()));
521        }
522    }
523    features
524}
525
526pub(crate) struct TargetFeatureParser;
527
528impl<S: Stage> CombineAttributeParser<S> for TargetFeatureParser {
529    type Item = (Symbol, Span);
530    const PATH: &[Symbol] = &[sym::target_feature];
531    const CONVERT: ConvertFn<Self::Item> = |items, span| AttributeKind::TargetFeature {
532        features: items,
533        attr_span: span,
534        was_forced: false,
535    };
536    const TEMPLATE: AttributeTemplate = ::rustc_feature::AttributeTemplate {
    word: false,
    list: Some(&["enable = \"feat1, feat2\""]),
    one_of: &[],
    name_value_str: None,
    docs: None,
}template!(List: &["enable = \"feat1, feat2\""]);
537
538    fn extend(
539        cx: &mut AcceptContext<'_, '_, S>,
540        args: &ArgParser,
541    ) -> impl IntoIterator<Item = Self::Item> {
542        parse_tf_attribute(cx, args)
543    }
544
545    const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[
546        Allow(Target::Fn),
547        Allow(Target::Method(MethodKind::Inherent)),
548        Allow(Target::Method(MethodKind::Trait { body: true })),
549        Allow(Target::Method(MethodKind::TraitImpl)),
550        Warn(Target::Statement),
551        Warn(Target::Field),
552        Warn(Target::Arm),
553        Warn(Target::MacroDef),
554        Warn(Target::MacroCall),
555    ]);
556}
557
558pub(crate) struct ForceTargetFeatureParser;
559
560impl<S: Stage> CombineAttributeParser<S> for ForceTargetFeatureParser {
561    type Item = (Symbol, Span);
562    const PATH: &[Symbol] = &[sym::force_target_feature];
563    const CONVERT: ConvertFn<Self::Item> = |items, span| AttributeKind::TargetFeature {
564        features: items,
565        attr_span: span,
566        was_forced: true,
567    };
568    const TEMPLATE: AttributeTemplate = ::rustc_feature::AttributeTemplate {
    word: false,
    list: Some(&["enable = \"feat1, feat2\""]),
    one_of: &[],
    name_value_str: None,
    docs: None,
}template!(List: &["enable = \"feat1, feat2\""]);
569    const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[
570        Allow(Target::Fn),
571        Allow(Target::Method(MethodKind::Inherent)),
572        Allow(Target::Method(MethodKind::Trait { body: true })),
573        Allow(Target::Method(MethodKind::TraitImpl)),
574    ]);
575
576    fn extend(
577        cx: &mut AcceptContext<'_, '_, S>,
578        args: &ArgParser,
579    ) -> impl IntoIterator<Item = Self::Item> {
580        parse_tf_attribute(cx, args)
581    }
582}
583
584pub(crate) struct SanitizeParser;
585
586impl<S: Stage> SingleAttributeParser<S> for SanitizeParser {
587    const PATH: &[Symbol] = &[sym::sanitize];
588
589    // FIXME: still checked in check_attrs.rs
590    const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(ALL_TARGETS);
591
592    const TEMPLATE: AttributeTemplate = ::rustc_feature::AttributeTemplate {
    word: false,
    list: Some(&[r#"address = "on|off""#, r#"kernel_address = "on|off""#,
                    r#"cfi = "on|off""#, r#"hwaddress = "on|off""#,
                    r#"kernel_hwaddress = "on|off""#, r#"kcfi = "on|off""#,
                    r#"memory = "on|off""#, r#"memtag = "on|off""#,
                    r#"shadow_call_stack = "on|off""#, r#"thread = "on|off""#,
                    r#"realtime = "nonblocking|blocking|caller""#]),
    one_of: &[],
    name_value_str: None,
    docs: None,
}template!(List: &[
593        r#"address = "on|off""#,
594        r#"kernel_address = "on|off""#,
595        r#"cfi = "on|off""#,
596        r#"hwaddress = "on|off""#,
597        r#"kernel_hwaddress = "on|off""#,
598        r#"kcfi = "on|off""#,
599        r#"memory = "on|off""#,
600        r#"memtag = "on|off""#,
601        r#"shadow_call_stack = "on|off""#,
602        r#"thread = "on|off""#,
603        r#"realtime = "nonblocking|blocking|caller""#,
604    ]);
605
606    const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
607
608    fn convert(cx: &mut AcceptContext<'_, '_, S>, args: &ArgParser) -> Option<AttributeKind> {
609        let Some(list) = args.list() else {
610            let attr_span = cx.attr_span;
611            cx.adcx().expected_list(attr_span, args);
612            return None;
613        };
614
615        let mut on_set = SanitizerSet::empty();
616        let mut off_set = SanitizerSet::empty();
617        let mut rtsan = None;
618
619        for item in list.mixed() {
620            let Some(item) = item.meta_item() else {
621                cx.adcx().expected_name_value(item.span(), None);
622                continue;
623            };
624
625            let path = item.path().word_sym();
626            let Some(value) = item.args().name_value() else {
627                cx.adcx().expected_name_value(item.span(), path);
628                continue;
629            };
630
631            let mut apply = |s: SanitizerSet| {
632                let is_on = match value.value_as_str() {
633                    Some(sym::on) => true,
634                    Some(sym::off) => false,
635                    Some(_) => {
636                        cx.adcx().expected_specific_argument_strings(
637                            value.value_span,
638                            &[sym::on, sym::off],
639                        );
640                        return;
641                    }
642                    None => {
643                        cx.adcx()
644                            .expected_string_literal(value.value_span, Some(value.value_as_lit()));
645                        return;
646                    }
647                };
648
649                if is_on {
650                    on_set |= s;
651                } else {
652                    off_set |= s;
653                }
654            };
655
656            match path {
657                Some(sym::address) | Some(sym::kernel_address) => {
658                    apply(SanitizerSet::ADDRESS | SanitizerSet::KERNELADDRESS)
659                }
660                Some(sym::cfi) => apply(SanitizerSet::CFI),
661                Some(sym::kcfi) => apply(SanitizerSet::KCFI),
662                Some(sym::memory) => apply(SanitizerSet::MEMORY),
663                Some(sym::memtag) => apply(SanitizerSet::MEMTAG),
664                Some(sym::shadow_call_stack) => apply(SanitizerSet::SHADOWCALLSTACK),
665                Some(sym::thread) => apply(SanitizerSet::THREAD),
666                Some(sym::hwaddress) | Some(sym::kernel_hwaddress) => {
667                    apply(SanitizerSet::HWADDRESS | SanitizerSet::KERNELHWADDRESS)
668                }
669                Some(sym::realtime) => match value.value_as_str() {
670                    Some(sym::nonblocking) => rtsan = Some(RtsanSetting::Nonblocking),
671                    Some(sym::blocking) => rtsan = Some(RtsanSetting::Blocking),
672                    Some(sym::caller) => rtsan = Some(RtsanSetting::Caller),
673                    _ => {
674                        cx.adcx().expected_specific_argument_strings(
675                            value.value_span,
676                            &[sym::nonblocking, sym::blocking, sym::caller],
677                        );
678                    }
679                },
680                _ => {
681                    cx.adcx().expected_specific_argument_strings(
682                        item.path().span(),
683                        &[
684                            sym::address,
685                            sym::kernel_address,
686                            sym::cfi,
687                            sym::kcfi,
688                            sym::memory,
689                            sym::memtag,
690                            sym::shadow_call_stack,
691                            sym::thread,
692                            sym::hwaddress,
693                            sym::kernel_hwaddress,
694                            sym::realtime,
695                        ],
696                    );
697                    continue;
698                }
699            }
700        }
701
702        Some(AttributeKind::Sanitize { on_set, off_set, rtsan, span: cx.attr_span })
703    }
704}
705
706pub(crate) struct ThreadLocalParser;
707
708impl<S: Stage> NoArgsAttributeParser<S> for ThreadLocalParser {
709    const PATH: &[Symbol] = &[sym::thread_local];
710    const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::WarnButFutureError;
711    const ALLOWED_TARGETS: AllowedTargets =
712        AllowedTargets::AllowList(&[Allow(Target::Static), Allow(Target::ForeignStatic)]);
713    const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::ThreadLocal;
714}
715
716pub(crate) struct RustcPassIndirectlyInNonRusticAbisParser;
717
718impl<S: Stage> NoArgsAttributeParser<S> for RustcPassIndirectlyInNonRusticAbisParser {
719    const PATH: &[Symbol] = &[sym::rustc_pass_indirectly_in_non_rustic_abis];
720    const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
721    const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::Struct)]);
722    const CREATE: fn(Span) -> AttributeKind = AttributeKind::RustcPassIndirectlyInNonRusticAbis;
723}
724
725pub(crate) struct RustcEiiForeignItemParser;
726
727impl<S: Stage> NoArgsAttributeParser<S> for RustcEiiForeignItemParser {
728    const PATH: &[Symbol] = &[sym::rustc_eii_foreign_item];
729    const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
730    const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::ForeignFn)]);
731    const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::RustcEiiForeignItem;
732}
733
734pub(crate) struct PatchableFunctionEntryParser;
735
736impl<S: Stage> SingleAttributeParser<S> for PatchableFunctionEntryParser {
737    const PATH: &[Symbol] = &[sym::patchable_function_entry];
738    const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
739    const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::Fn)]);
740    const TEMPLATE: AttributeTemplate = ::rustc_feature::AttributeTemplate {
    word: false,
    list: Some(&["prefix_nops = m, entry_nops = n"]),
    one_of: &[],
    name_value_str: None,
    docs: None,
}template!(List: &["prefix_nops = m, entry_nops = n"]);
741
742    fn convert(cx: &mut AcceptContext<'_, '_, S>, args: &ArgParser) -> Option<AttributeKind> {
743        let Some(meta_item_list) = args.list() else {
744            let attr_span = cx.attr_span;
745            cx.adcx().expected_list(attr_span, args);
746            return None;
747        };
748
749        let mut prefix = None;
750        let mut entry = None;
751
752        if meta_item_list.len() == 0 {
753            cx.adcx().expected_list(meta_item_list.span, args);
754            return None;
755        }
756
757        let mut errored = false;
758
759        for item in meta_item_list.mixed() {
760            let Some(meta_item) = item.meta_item() else {
761                errored = true;
762                cx.adcx().expected_name_value(item.span(), None);
763                continue;
764            };
765
766            let Some(name_value_lit) = meta_item.args().name_value() else {
767                errored = true;
768                cx.adcx().expected_name_value(item.span(), None);
769                continue;
770            };
771
772            let attrib_to_write = match meta_item.ident().map(|ident| ident.name) {
773                Some(sym::prefix_nops) => {
774                    // Duplicate prefixes are not allowed
775                    if prefix.is_some() {
776                        errored = true;
777                        cx.adcx().duplicate_key(meta_item.path().span(), sym::prefix_nops);
778                        continue;
779                    }
780                    &mut prefix
781                }
782                Some(sym::entry_nops) => {
783                    // Duplicate entries are not allowed
784                    if entry.is_some() {
785                        errored = true;
786                        cx.adcx().duplicate_key(meta_item.path().span(), sym::entry_nops);
787                        continue;
788                    }
789                    &mut entry
790                }
791                _ => {
792                    errored = true;
793                    cx.adcx().expected_specific_argument(
794                        meta_item.path().span(),
795                        &[sym::prefix_nops, sym::entry_nops],
796                    );
797                    continue;
798                }
799            };
800
801            let rustc_ast::LitKind::Int(val, _) = name_value_lit.value_as_lit().kind else {
802                errored = true;
803                cx.adcx().expected_integer_literal(name_value_lit.value_span);
804                continue;
805            };
806
807            let Ok(val) = val.get().try_into() else {
808                errored = true;
809                cx.adcx().expected_integer_literal_in_range(
810                    name_value_lit.value_span,
811                    u8::MIN as isize,
812                    u8::MAX as isize,
813                );
814                continue;
815            };
816
817            *attrib_to_write = Some(val);
818        }
819
820        if errored {
821            None
822        } else {
823            Some(AttributeKind::PatchableFunctionEntry {
824                prefix: prefix.unwrap_or(0),
825                entry: entry.unwrap_or(0),
826            })
827        }
828    }
829}