about summary refs log tree commit diff
path: root/compiler/rustc_feature/src/builtin_attrs.rs
blob: 129ab7eccb577358df64335598352ae16fa36ea4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
//! Built-in attributes and `cfg` flag gating.

use std::sync::LazyLock;

use AttributeDuplicates::*;
use AttributeGate::*;
use AttributeType::*;
use rustc_data_structures::fx::FxHashMap;
use rustc_hir::AttrStyle;
use rustc_hir::attrs::EncodeCrossCrate;
use rustc_span::edition::Edition;
use rustc_span::{Symbol, sym};

use crate::Features;

type GateFn = fn(&Features) -> bool;

pub type GatedCfg = (Symbol, Symbol, GateFn);

/// `cfg(...)`'s that are feature gated.
const GATED_CFGS: &[GatedCfg] = &[
    // (name in cfg, feature, function to check if the feature is enabled)
    (sym::overflow_checks, sym::cfg_overflow_checks, Features::cfg_overflow_checks),
    (sym::ub_checks, sym::cfg_ub_checks, Features::cfg_ub_checks),
    (sym::contract_checks, sym::cfg_contract_checks, Features::cfg_contract_checks),
    (sym::target_thread_local, sym::cfg_target_thread_local, Features::cfg_target_thread_local),
    (
        sym::target_has_atomic_equal_alignment,
        sym::cfg_target_has_atomic_equal_alignment,
        Features::cfg_target_has_atomic_equal_alignment,
    ),
    (
        sym::target_has_atomic_load_store,
        sym::cfg_target_has_atomic,
        Features::cfg_target_has_atomic,
    ),
    (sym::sanitize, sym::cfg_sanitize, Features::cfg_sanitize),
    (sym::version, sym::cfg_version, Features::cfg_version),
    (sym::relocation_model, sym::cfg_relocation_model, Features::cfg_relocation_model),
    (sym::sanitizer_cfi_generalize_pointers, sym::cfg_sanitizer_cfi, Features::cfg_sanitizer_cfi),
    (sym::sanitizer_cfi_normalize_integers, sym::cfg_sanitizer_cfi, Features::cfg_sanitizer_cfi),
    // this is consistent with naming of the compiler flag it's for
    (sym::fmt_debug, sym::fmt_debug, Features::fmt_debug),
    (sym::emscripten_wasm_eh, sym::cfg_emscripten_wasm_eh, Features::cfg_emscripten_wasm_eh),
    (
        sym::target_has_reliable_f16,
        sym::cfg_target_has_reliable_f16_f128,
        Features::cfg_target_has_reliable_f16_f128,
    ),
    (
        sym::target_has_reliable_f16_math,
        sym::cfg_target_has_reliable_f16_f128,
        Features::cfg_target_has_reliable_f16_f128,
    ),
    (
        sym::target_has_reliable_f128,
        sym::cfg_target_has_reliable_f16_f128,
        Features::cfg_target_has_reliable_f16_f128,
    ),
    (
        sym::target_has_reliable_f128_math,
        sym::cfg_target_has_reliable_f16_f128,
        Features::cfg_target_has_reliable_f16_f128,
    ),
];

/// Find a gated cfg determined by the `pred`icate which is given the cfg's name.
pub fn find_gated_cfg(pred: impl Fn(Symbol) -> bool) -> Option<&'static GatedCfg> {
    GATED_CFGS.iter().find(|(cfg_sym, ..)| pred(*cfg_sym))
}

// If you change this, please modify `src/doc/unstable-book` as well. You must
// move that documentation into the relevant place in the other docs, and
// remove the chapter on the flag.

#[derive(Copy, Clone, PartialEq, Debug)]
pub enum AttributeType {
    /// Normal, builtin attribute that is consumed
    /// by the compiler before the unused_attribute check
    Normal,

    /// Builtin attribute that is only allowed at the crate level
    CrateLevel,
}

#[derive(Copy, Clone, PartialEq, Debug)]
pub enum AttributeSafety {
    /// Normal attribute that does not need `#[unsafe(...)]`
    Normal,

    /// Unsafe attribute that requires safety obligations to be discharged.
    ///
    /// An error is emitted when `#[unsafe(...)]` is omitted, except when the attribute's edition
    /// is less than the one stored in `unsafe_since`. This handles attributes that were safe in
    /// earlier editions, but become unsafe in later ones.
    Unsafe { unsafe_since: Option<Edition> },
}

#[derive(Clone, Debug, Copy)]
pub enum AttributeGate {
    /// A gated attribute which requires a feature gate to be enabled.
    Gated {
        /// The feature gate, for example `#![feature(rustc_attrs)]` for rustc_* attributes.
        feature: Symbol,
        /// The error message displayed when an attempt is made to use the attribute without its feature gate.
        message: &'static str,
        /// Check function to be called during the `PostExpansionVisitor` pass.
        check: fn(&Features) -> bool,
        /// Notes to be displayed when an attempt is made to use the attribute without its feature gate.
        notes: &'static [&'static str],
    },
    /// Ungated attribute, can be used on all release channels
    Ungated,
}

// FIXME(jdonszelmann): move to rustc_hir::attrs
/// A template that the attribute input must match.
/// Only top-level shape (`#[attr]` vs `#[attr(...)]` vs `#[attr = ...]`) is considered now.
#[derive(Clone, Copy, Default)]
pub struct AttributeTemplate {
    /// If `true`, the attribute is allowed to be a bare word like `#[test]`.
    pub word: bool,
    /// If `Some`, the attribute is allowed to take a list of items like `#[allow(..)]`.
    pub list: Option<&'static [&'static str]>,
    /// If non-empty, the attribute is allowed to take a list containing exactly
    /// one of the listed words, like `#[coverage(off)]`.
    pub one_of: &'static [Symbol],
    /// If `Some`, the attribute is allowed to be a name/value pair where the
    /// value is a string, like `#[must_use = "reason"]`.
    pub name_value_str: Option<&'static [&'static str]>,
    /// A link to the document for this attribute.
    pub docs: Option<&'static str>,
}

impl AttributeTemplate {
    pub fn suggestions(&self, style: AttrStyle, name: impl std::fmt::Display) -> Vec<String> {
        let mut suggestions = vec![];
        let inner = match style {
            AttrStyle::Outer => "",
            AttrStyle::Inner => "!",
        };
        if self.word {
            suggestions.push(format!("#{inner}[{name}]"));
        }
        if let Some(descr) = self.list {
            for descr in descr {
                suggestions.push(format!("#{inner}[{name}({descr})]"));
            }
        }
        suggestions.extend(self.one_of.iter().map(|&word| format!("#{inner}[{name}({word})]")));
        if let Some(descr) = self.name_value_str {
            for descr in descr {
                suggestions.push(format!("#{inner}[{name} = \"{descr}\"]"));
            }
        }
        suggestions.sort();

        suggestions
    }
}

/// How to handle multiple duplicate attributes on the same item.
#[derive(Clone, Copy, Default)]
pub enum AttributeDuplicates {
    /// Duplicates of this attribute are allowed.
    ///
    /// This should only be used with attributes where duplicates have semantic
    /// meaning, or some kind of "additive" behavior. For example, `#[warn(..)]`
    /// can be specified multiple times, and it combines all the entries. Or use
    /// this if there is validation done elsewhere.
    #[default]
    DuplicatesOk,
    /// Duplicates after the first attribute will be an unused_attribute warning.
    ///
    /// This is usually used for "word" attributes, where they are used as a
    /// boolean marker, like `#[used]`. It is not necessarily wrong that there
    /// are duplicates, but the others should probably be removed.
    WarnFollowing,
    /// Same as `WarnFollowing`, but only issues warnings for word-style attributes.
    ///
    /// This is only for special cases, for example multiple `#[macro_use]` can
    /// be warned, but multiple `#[macro_use(...)]` should not because the list
    /// form has different meaning from the word form.
    WarnFollowingWordOnly,
    /// Duplicates after the first attribute will be an error.
    ///
    /// This should be used where duplicates would be ignored, but carry extra
    /// meaning that could cause confusion. For example, `#[stable(since="1.0")]
    /// #[stable(since="2.0")]`, which version should be used for `stable`?
    ErrorFollowing,
    /// Duplicates preceding the last instance of the attribute will be an error.
    ///
    /// This is the same as `ErrorFollowing`, except the last attribute is the
    /// one that is "used". This is typically used in cases like codegen
    /// attributes which usually only honor the last attribute.
    ErrorPreceding,
    /// Duplicates after the first attribute will be an unused_attribute warning
    /// with a note that this will be an error in the future.
    ///
    /// This should be used for attributes that should be `ErrorFollowing`, but
    /// because older versions of rustc silently accepted (and ignored) the
    /// attributes, this is used to transition.
    FutureWarnFollowing,
    /// Duplicates preceding the last instance of the attribute will be a
    /// warning, with a note that this will be an error in the future.
    ///
    /// This is the same as `FutureWarnFollowing`, except the last attribute is
    /// the one that is "used". Ideally these can eventually migrate to
    /// `ErrorPreceding`.
    FutureWarnPreceding,
}

/// A convenience macro for constructing attribute templates.
/// E.g., `template!(Word, List: "description")` means that the attribute
/// supports forms `#[attr]` and `#[attr(description)]`.
#[macro_export]
macro_rules! template {
    (Word) => { $crate::template!(@ true, None, &[], None, None) };
    (Word, $link: literal) => { $crate::template!(@ true, None, &[], None, Some($link)) };
    (List: $descr: expr) => { $crate::template!(@ false, Some($descr), &[], None, None) };
    (List: $descr: expr, $link: literal) => { $crate::template!(@ false, Some($descr), &[], None, Some($link)) };
    (OneOf: $one_of: expr) => { $crate::template!(@ false, None, $one_of, None, None) };
    (NameValueStr: [$($descr: literal),* $(,)?]) => { $crate::template!(@ false, None, &[], Some(&[$($descr,)*]), None) };
    (NameValueStr: [$($descr: literal),* $(,)?], $link: literal) => { $crate::template!(@ false, None, &[], Some(&[$($descr,)*]), Some($link)) };
    (NameValueStr: $descr: literal) => { $crate::template!(@ false, None, &[], Some(&[$descr]), None) };
    (NameValueStr: $descr: literal, $link: literal) => { $crate::template!(@ false, None, &[], Some(&[$descr]), Some($link)) };
    (Word, List: $descr: expr) => { $crate::template!(@ true, Some($descr), &[], None, None) };
    (Word, List: $descr: expr, $link: literal) => { $crate::template!(@ true, Some($descr), &[], None, Some($link)) };
    (Word, NameValueStr: $descr: expr) => { $crate::template!(@ true, None, &[], Some(&[$descr]), None) };
    (Word, NameValueStr: $descr: expr, $link: literal) => { $crate::template!(@ true, None, &[], Some(&[$descr]), Some($link)) };
    (List: $descr1: expr, NameValueStr: $descr2: expr) => {
        $crate::template!(@ false, Some($descr1), &[], Some(&[$descr2]), None)
    };
    (List: $descr1: expr, NameValueStr: $descr2: expr, $link: literal) => {
        $crate::template!(@ false, Some($descr1), &[], Some(&[$descr2]), Some($link))
    };
    (Word, List: $descr1: expr, NameValueStr: $descr2: expr) => {
        $crate::template!(@ true, Some($descr1), &[], Some(&[$descr2]), None)
    };
    (Word, List: $descr1: expr, NameValueStr: $descr2: expr, $link: literal) => {
        $crate::template!(@ true, Some($descr1), &[], Some(&[$descr2]), Some($link))
    };
    (@ $word: expr, $list: expr, $one_of: expr, $name_value_str: expr, $link: expr) => { $crate::AttributeTemplate {
        word: $word, list: $list, one_of: $one_of, name_value_str: $name_value_str, docs: $link,
    } };
}

macro_rules! ungated {
    (unsafe($edition:ident) $attr:ident, $typ:expr, $tpl:expr, $duplicates:expr, $encode_cross_crate:expr $(,)?) => {
        BuiltinAttribute {
            name: sym::$attr,
            encode_cross_crate: $encode_cross_crate,
            type_: $typ,
            safety: AttributeSafety::Unsafe { unsafe_since: Some(Edition::$edition) },
            template: $tpl,
            gate: Ungated,
            duplicates: $duplicates,
        }
    };
    (unsafe $attr:ident, $typ:expr, $tpl:expr, $duplicates:expr, $encode_cross_crate:expr $(,)?) => {
        BuiltinAttribute {
            name: sym::$attr,
            encode_cross_crate: $encode_cross_crate,
            type_: $typ,
            safety: AttributeSafety::Unsafe { unsafe_since: None },
            template: $tpl,
            gate: Ungated,
            duplicates: $duplicates,
        }
    };
    ($attr:ident, $typ:expr, $tpl:expr, $duplicates:expr, $encode_cross_crate:expr $(,)?) => {
        BuiltinAttribute {
            name: sym::$attr,
            encode_cross_crate: $encode_cross_crate,
            type_: $typ,
            safety: AttributeSafety::Normal,
            template: $tpl,
            gate: Ungated,
            duplicates: $duplicates,
        }
    };
}

macro_rules! gated {
    (unsafe $attr:ident, $typ:expr, $tpl:expr, $duplicates:expr, $encode_cross_crate:expr, $gate:ident, $message:expr $(,)?) => {
        BuiltinAttribute {
            name: sym::$attr,
            encode_cross_crate: $encode_cross_crate,
            type_: $typ,
            safety: AttributeSafety::Unsafe { unsafe_since: None },
            template: $tpl,
            duplicates: $duplicates,
            gate: Gated {
                feature: sym::$gate,
                message: $message,
                check: Features::$gate,
                notes: &[],
            },
        }
    };
    (unsafe $attr:ident, $typ:expr, $tpl:expr, $duplicates:expr, $encode_cross_crate:expr, $message:expr $(,)?) => {
        BuiltinAttribute {
            name: sym::$attr,
            encode_cross_crate: $encode_cross_crate,
            type_: $typ,
            safety: AttributeSafety::Unsafe { unsafe_since: None },
            template: $tpl,
            duplicates: $duplicates,
            gate: Gated {
                feature: sym::$attr,
                message: $message,
                check: Features::$attr,
                notes: &[],
            },
        }
    };
    ($attr:ident, $typ:expr, $tpl:expr, $duplicates:expr, $encode_cross_crate:expr, $gate:ident, $message:expr $(,)?) => {
        BuiltinAttribute {
            name: sym::$attr,
            encode_cross_crate: $encode_cross_crate,
            type_: $typ,
            safety: AttributeSafety::Normal,
            template: $tpl,
            duplicates: $duplicates,
            gate: Gated {
                feature: sym::$gate,
                message: $message,
                check: Features::$gate,
                notes: &[],
            },
        }
    };
    ($attr:ident, $typ:expr, $tpl:expr, $duplicates:expr, $encode_cross_crate:expr, $message:expr $(,)?) => {
        BuiltinAttribute {
            name: sym::$attr,
            encode_cross_crate: $encode_cross_crate,
            type_: $typ,
            safety: AttributeSafety::Normal,
            template: $tpl,
            duplicates: $duplicates,
            gate: Gated {
                feature: sym::$attr,
                message: $message,
                check: Features::$attr,
                notes: &[],
            },
        }
    };
}

macro_rules! rustc_attr {
    (TEST, $attr:ident, $typ:expr, $tpl:expr, $duplicate:expr, $encode_cross_crate:expr $(,)?) => {
        rustc_attr!(
            $attr,
            $typ,
            $tpl,
            $duplicate,
            $encode_cross_crate,
            concat!(
                "the `#[",
                stringify!($attr),
                "]` attribute is used for rustc unit tests"
            ),
        )
    };
    ($attr:ident, $typ:expr, $tpl:expr, $duplicates:expr, $encode_cross_crate:expr, $($notes:expr),* $(,)?) => {
        BuiltinAttribute {
            name: sym::$attr,
            encode_cross_crate: $encode_cross_crate,
            type_: $typ,
            safety: AttributeSafety::Normal,
            template: $tpl,
            duplicates: $duplicates,
            gate: Gated {
                feature: sym::rustc_attrs,
                message: "use of an internal attribute",
                check: Features::rustc_attrs,
                notes: &[
                    concat!("the `#[",
                    stringify!($attr),
                    "]` attribute is an internal implementation detail that will never be stable"),
                    $($notes),*
                    ]
            },
        }
    };
}

macro_rules! experimental {
    ($attr:ident) => {
        concat!("the `#[", stringify!($attr), "]` attribute is an experimental feature")
    };
}

pub struct BuiltinAttribute {
    pub name: Symbol,
    /// Whether this attribute is encode cross crate.
    ///
    /// If so, it is encoded in the crate metadata.
    /// Otherwise, it can only be used in the local crate.
    pub encode_cross_crate: EncodeCrossCrate,
    pub type_: AttributeType,
    pub safety: AttributeSafety,
    pub template: AttributeTemplate,
    pub duplicates: AttributeDuplicates,
    pub gate: AttributeGate,
}

/// Attributes that have a special meaning to rustc or rustdoc.
#[rustfmt::skip]
pub static BUILTIN_ATTRIBUTES: &[BuiltinAttribute] = &[
    // ==========================================================================
    // Stable attributes:
    // ==========================================================================

    // Conditional compilation:
    ungated!(
        cfg, Normal,
        template!(
            List: &["predicate"],
            "https://doc.rust-lang.org/reference/conditional-compilation.html#the-cfg-attribute"
        ),
        DuplicatesOk, EncodeCrossCrate::Yes
    ),
    ungated!(
        cfg_attr, Normal,
        template!(
            List: &["predicate, attr1, attr2, ..."],
            "https://doc.rust-lang.org/reference/conditional-compilation.html#the-cfg_attr-attribute"
        ),
        DuplicatesOk, EncodeCrossCrate::Yes
    ),

    // Testing:
    ungated!(
        ignore, Normal,
        template!(
            Word,
            NameValueStr: "reason",
            "https://doc.rust-lang.org/reference/attributes/testing.html#the-ignore-attribute"
        ),
        WarnFollowing, EncodeCrossCrate::No,
    ),
    ungated!(
        should_panic, Normal,
        template!(
            Word,
            List: &[r#"expected = "reason""#],
            NameValueStr: "reason",
            "https://doc.rust-lang.org/reference/attributes/testing.html#the-should_panic-attribute"
        ),
        FutureWarnFollowing, EncodeCrossCrate::No,
    ),
    // FIXME(Centril): This can be used on stable but shouldn't.
    ungated!(
        reexport_test_harness_main, CrateLevel, template!(NameValueStr: "name"), ErrorFollowing,
        EncodeCrossCrate::No,
    ),

    // Macros:
    ungated!(
        automatically_derived, Normal,
        template!(
            Word,
            "https://doc.rust-lang.org/reference/attributes/derive.html#the-automatically_derived-attribute"
        ),
        WarnFollowing, EncodeCrossCrate::Yes
    ),
    ungated!(
        macro_use, Normal,
        template!(
            Word,
            List: &["name1, name2, ..."],
            "https://doc.rust-lang.org/reference/macros-by-example.html#the-macro_use-attribute"
        ),
        WarnFollowingWordOnly, EncodeCrossCrate::No,
    ),
    ungated!(macro_escape, Normal, template!(Word), WarnFollowing, EncodeCrossCrate::No), // Deprecated synonym for `macro_use`.
    ungated!(
        macro_export, Normal,
        template!(
            Word,
            List: &["local_inner_macros"],
            "https://doc.rust-lang.org/reference/macros-by-example.html#path-based-scope"
        ),
        WarnFollowing, EncodeCrossCrate::Yes
    ),
    ungated!(
        proc_macro, Normal,
        template!(
            Word,
            "https://doc.rust-lang.org/reference/procedural-macros.html#function-like-procedural-macros"),
        ErrorFollowing, EncodeCrossCrate::No
    ),
    ungated!(
        proc_macro_derive, Normal,
        template!(
            List: &["TraitName", "TraitName, attributes(name1, name2, ...)"],
            "https://doc.rust-lang.org/reference/procedural-macros.html#derive-macros"
        ),
        ErrorFollowing, EncodeCrossCrate::No,
    ),
    ungated!(
        proc_macro_attribute, Normal,
        template!(Word, "https://doc.rust-lang.org/reference/procedural-macros.html#attribute-macros"),
        ErrorFollowing, EncodeCrossCrate::No
    ),

    // Lints:
    ungated!(
        warn, Normal,
        template!(
            List: &["lint1", "lint1, lint2, ...", r#"lint1, lint2, lint3, reason = "...""#],
            "https://doc.rust-lang.org/reference/attributes/diagnostics.html#lint-check-attributes"
        ),
        DuplicatesOk, EncodeCrossCrate::No,
    ),
    ungated!(
        allow, Normal,
        template!(
            List: &["lint1", "lint1, lint2, ...", r#"lint1, lint2, lint3, reason = "...""#],
            "https://doc.rust-lang.org/reference/attributes/diagnostics.html#lint-check-attributes"
        ),
        DuplicatesOk, EncodeCrossCrate::No,
    ),
    ungated!(
        expect, Normal,
        template!(
            List: &["lint1", "lint1, lint2, ...", r#"lint1, lint2, lint3, reason = "...""#],
            "https://doc.rust-lang.org/reference/attributes/diagnostics.html#lint-check-attributes"
        ),
        DuplicatesOk, EncodeCrossCrate::No,
    ),
    ungated!(
        forbid, Normal,
        template!(
            List: &["lint1", "lint1, lint2, ...", r#"lint1, lint2, lint3, reason = "...""#],
            "https://doc.rust-lang.org/reference/attributes/diagnostics.html#lint-check-attributes"
        ),
        DuplicatesOk, EncodeCrossCrate::No
    ),
    ungated!(
        deny, Normal,
        template!(
            List: &["lint1", "lint1, lint2, ...", r#"lint1, lint2, lint3, reason = "...""#],
            "https://doc.rust-lang.org/reference/attributes/diagnostics.html#lint-check-attributes"
        ),
        DuplicatesOk, EncodeCrossCrate::No
    ),
    ungated!(
        must_use, Normal,
        template!(
            Word,
            NameValueStr: "reason",
            "https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-must_use-attribute"
        ),
        FutureWarnFollowing, EncodeCrossCrate::Yes
    ),
    gated!(
        must_not_suspend, Normal, template!(Word, NameValueStr: "reason"), WarnFollowing,
        EncodeCrossCrate::Yes, experimental!(must_not_suspend)
    ),
    ungated!(
        deprecated, Normal,
        template!(
            Word,
            List: &[r#"/*opt*/ since = "version", /*opt*/ note = "reason""#],
            NameValueStr: "reason",
            "https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-deprecated-attribute"
        ),
        ErrorFollowing, EncodeCrossCrate::Yes
    ),

    // Crate properties:
    ungated!(
        crate_name, CrateLevel,
        template!(
            NameValueStr: "name",
            "https://doc.rust-lang.org/reference/crates-and-source-files.html#the-crate_name-attribute"
        ),
        FutureWarnFollowing, EncodeCrossCrate::No,
    ),
    ungated!(
        crate_type, CrateLevel,
        template!(
            NameValueStr: ["bin", "lib", "dylib", "cdylib", "rlib", "staticlib", "sdylib", "proc-macro"],
            "https://doc.rust-lang.org/reference/linkage.html"
        ),
        DuplicatesOk, EncodeCrossCrate::No,
    ),

    // ABI, linking, symbols, and FFI
    ungated!(
        link, Normal,
        template!(List: &[
            r#"name = "...""#,
            r#"name = "...", kind = "dylib|static|...""#,
            r#"name = "...", wasm_import_module = "...""#,
            r#"name = "...", import_name_type = "decorated|noprefix|undecorated""#,
            r#"name = "...", kind = "dylib|static|...", wasm_import_module = "...", import_name_type = "decorated|noprefix|undecorated""#,
        ], "https://doc.rust-lang.org/reference/items/external-blocks.html#the-link-attribute"),
        DuplicatesOk, EncodeCrossCrate::No,
    ),
    ungated!(
        link_name, Normal,
        template!(NameValueStr: "name", "https://doc.rust-lang.org/reference/items/external-blocks.html#the-link_name-attribute"),
        FutureWarnPreceding, EncodeCrossCrate::Yes
    ),
    ungated!(
        no_link, Normal,
        template!(Word, "https://doc.rust-lang.org/reference/items/extern-crates.html#the-no_link-attribute"),
        WarnFollowing, EncodeCrossCrate::No
    ),
    ungated!(
        repr, Normal,
        template!(
            List: &["C", "Rust", "transparent", "align(...)", "packed(...)", "<integer type>"],
            "https://doc.rust-lang.org/reference/type-layout.html#representations"
        ),
        DuplicatesOk, EncodeCrossCrate::No
    ),
    // FIXME(#82232, #143834): temporarily renamed to mitigate `#[align]` nameres ambiguity
    gated!(rustc_align, Normal, template!(List: &["alignment"]), DuplicatesOk, EncodeCrossCrate::No, fn_align, experimental!(rustc_align)),
    gated!(rustc_align_static, Normal, template!(List: &["alignment"]), DuplicatesOk, EncodeCrossCrate::No, static_align, experimental!(rustc_align_static)),
    ungated!(
        unsafe(Edition2024) export_name, Normal,
        template!(NameValueStr: "name", "https://doc.rust-lang.org/reference/abi.html#the-export_name-attribute"),
        FutureWarnPreceding, EncodeCrossCrate::No
    ),
    ungated!(
        unsafe(Edition2024) link_section, Normal,
        template!(NameValueStr: "name", "https://doc.rust-lang.org/reference/abi.html#the-link_section-attribute"),
        FutureWarnPreceding, EncodeCrossCrate::No
    ),
    ungated!(
        unsafe(Edition2024) no_mangle, Normal,
        template!(Word, "https://doc.rust-lang.org/reference/abi.html#the-no_mangle-attribute"),
        WarnFollowing, EncodeCrossCrate::No
    ),
    ungated!(
        used, Normal,
        template!(Word, List: &["compiler", "linker"], "https://doc.rust-lang.org/reference/abi.html#the-used-attribute"),
        WarnFollowing, EncodeCrossCrate::No
    ),
    ungated!(
        link_ordinal, Normal,
        template!(List: &["ordinal"], "https://doc.rust-lang.org/reference/items/external-blocks.html#the-link_ordinal-attribute"),
        ErrorPreceding, EncodeCrossCrate::Yes
    ),
    ungated!(
        unsafe naked, Normal,
        template!(Word, "https://doc.rust-lang.org/reference/attributes/codegen.html#the-naked-attribute"),
        WarnFollowing, EncodeCrossCrate::No
    ),

    // Limits:
    ungated!(
        recursion_limit, CrateLevel,
        template!(NameValueStr: "N", "https://doc.rust-lang.org/reference/attributes/limits.html#the-recursion_limit-attribute"),
        FutureWarnFollowing, EncodeCrossCrate::No
    ),
    ungated!(
        type_length_limit, CrateLevel,
        template!(NameValueStr: "N", "https://doc.rust-lang.org/reference/attributes/limits.html#the-type_length_limit-attribute"),
        FutureWarnFollowing, EncodeCrossCrate::No
    ),
    gated!(
        move_size_limit, CrateLevel, template!(NameValueStr: "N"), ErrorFollowing,
        EncodeCrossCrate::No, large_assignments, experimental!(move_size_limit)
    ),

    // Entry point:
    ungated!(
        no_main, CrateLevel,
        template!(Word, "https://doc.rust-lang.org/reference/crates-and-source-files.html#the-no_main-attribute"),
        WarnFollowing, EncodeCrossCrate::No
    ),

    // Modules, prelude, and resolution:
    ungated!(
        path, Normal,
        template!(NameValueStr: "file", "https://doc.rust-lang.org/reference/items/modules.html#the-path-attribute"),
        FutureWarnFollowing, EncodeCrossCrate::No
    ),
    ungated!(
        no_std, CrateLevel,
        template!(Word, "https://doc.rust-lang.org/reference/names/preludes.html#the-no_std-attribute"),
        WarnFollowing, EncodeCrossCrate::No
    ),
    ungated!(
        no_implicit_prelude, Normal,
        template!(Word, "https://doc.rust-lang.org/reference/names/preludes.html#the-no_implicit_prelude-attribute"),
        WarnFollowing, EncodeCrossCrate::No
    ),
    ungated!(
        non_exhaustive, Normal,
        template!(Word, "https://doc.rust-lang.org/reference/attributes/type_system.html#the-non_exhaustive-attribute"),
        WarnFollowing, EncodeCrossCrate::Yes
    ),

    // Runtime
    ungated!(
        windows_subsystem, CrateLevel,
        template!(NameValueStr: ["windows", "console"], "https://doc.rust-lang.org/reference/runtime.html#the-windows_subsystem-attribute"),
        FutureWarnFollowing, EncodeCrossCrate::No
    ),
    ungated!( // RFC 2070
        panic_handler, Normal,
        template!(Word, "https://doc.rust-lang.org/reference/panic.html#the-panic_handler-attribute"),
        WarnFollowing, EncodeCrossCrate::Yes
    ),

    // Code generation:
    ungated!(
        inline, Normal,
        template!(
            Word,
            List: &["always", "never"],
            "https://doc.rust-lang.org/reference/attributes/codegen.html#the-inline-attribute"
        ),
        FutureWarnFollowing, EncodeCrossCrate::No
    ),
    ungated!(
        cold, Normal,
        template!(Word, "https://doc.rust-lang.org/reference/attributes/codegen.html#the-cold-attribute"),
        WarnFollowing, EncodeCrossCrate::No
    ),
    ungated!(
        no_builtins, CrateLevel,
        template!(Word, "https://doc.rust-lang.org/reference/attributes/codegen.html#the-no_builtins-attribute"),
        WarnFollowing, EncodeCrossCrate::Yes
    ),
    ungated!(
        target_feature, Normal,
        template!(List: &[r#"enable = "name""#], "https://doc.rust-lang.org/reference/attributes/codegen.html#the-target_feature-attribute"),
        DuplicatesOk, EncodeCrossCrate::No,
    ),
    ungated!(
        track_caller, Normal,
        template!(Word, "https://doc.rust-lang.org/reference/attributes/codegen.html#the-track_caller-attribute"),
        WarnFollowing, EncodeCrossCrate::Yes
    ),
    ungated!(
        instruction_set, Normal,
        template!(List: &["set"], "https://doc.rust-lang.org/reference/attributes/codegen.html#the-instruction_set-attribute"),
        ErrorPreceding, EncodeCrossCrate::No
    ),
    gated!(
        unsafe force_target_feature, Normal, template!(List: &[r#"enable = "name""#]),
        DuplicatesOk, EncodeCrossCrate::No, effective_target_features, experimental!(force_target_feature)
    ),
    gated!(
        sanitize, Normal, template!(List: &[r#"address = "on|off""#, r#"kernel_address = "on|off""#, r#"cfi = "on|off""#, r#"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""#]), ErrorPreceding,
        EncodeCrossCrate::No, sanitize, experimental!(sanitize),
    ),
    gated!(
        coverage, Normal, template!(OneOf: &[sym::off, sym::on]),
        ErrorPreceding, EncodeCrossCrate::No,
        coverage_attribute, experimental!(coverage)
    ),

    ungated!(
        doc, Normal,
        template!(
            List: &["hidden", "inline"],
            NameValueStr: "string",
            "https://doc.rust-lang.org/rustdoc/write-documentation/the-doc-attribute.html"
        ),
        DuplicatesOk, EncodeCrossCrate::Yes
    ),

    // Debugging
    ungated!(
        debugger_visualizer, Normal,
        template!(
            List: &[r#"natvis_file = "...", gdb_script_file = "...""#],
            "https://doc.rust-lang.org/reference/attributes/debugger.html#the-debugger_visualizer-attribute"
        ),
        DuplicatesOk, EncodeCrossCrate::No
    ),
    ungated!(
        collapse_debuginfo, Normal,
        template!(
            List: &["no", "external", "yes"],
            "https://doc.rust-lang.org/reference/attributes/debugger.html#the-collapse_debuginfo-attribute"
        ),
        ErrorFollowing, EncodeCrossCrate::Yes
    ),

    // ==========================================================================
    // Unstable attributes:
    // ==========================================================================

    // Linking:
    gated!(
        export_stable, Normal, template!(Word), WarnFollowing,
        EncodeCrossCrate::No, experimental!(export_stable)
    ),

    // Testing:
    gated!(
        test_runner, CrateLevel, template!(List: &["path"]), ErrorFollowing,
        EncodeCrossCrate::Yes, custom_test_frameworks,
        "custom test frameworks are an unstable feature",
    ),
    // RFC #1268
    gated!(
        marker, Normal, template!(Word), WarnFollowing, EncodeCrossCrate::No,
        marker_trait_attr, experimental!(marker)
    ),
    gated!(
        thread_local, Normal, template!(Word), WarnFollowing, EncodeCrossCrate::No,
        "`#[thread_local]` is an experimental feature, and does not currently handle destructors",
    ),
    gated!(
        no_core, CrateLevel, template!(Word), WarnFollowing,
        EncodeCrossCrate::No, experimental!(no_core)
    ),
    // RFC 2412
    gated!(
        optimize, Normal, template!(List: &["none", "size", "speed"]), ErrorPreceding,
        EncodeCrossCrate::No, optimize_attribute, experimental!(optimize)
    ),

    gated!(
        unsafe ffi_pure, Normal, template!(Word), WarnFollowing,
        EncodeCrossCrate::No, experimental!(ffi_pure)
    ),
    gated!(
        unsafe ffi_const, Normal, template!(Word), WarnFollowing,
        EncodeCrossCrate::No, experimental!(ffi_const)
    ),
    gated!(
        register_tool, CrateLevel, template!(List: &["tool1, tool2, ..."]), DuplicatesOk,
        EncodeCrossCrate::No, experimental!(register_tool),
    ),

    // RFC 2632
    // FIXME(const_trait_impl) remove this
    gated!(
        const_trait, Normal, template!(Word), WarnFollowing, EncodeCrossCrate::No, const_trait_impl,
        "`const_trait` is a temporary placeholder for marking a trait that is suitable for `const` \
        `impls` and all default bodies as `const`, which may be removed or renamed in the \
        future."
    ),
    // lang-team MCP 147
    gated!(
        deprecated_safe, Normal, template!(List: &[r#"since = "version", note = "...""#]), ErrorFollowing,
        EncodeCrossCrate::Yes, experimental!(deprecated_safe),
    ),

    // `#[cfi_encoding = ""]`
    gated!(
        cfi_encoding, Normal, template!(NameValueStr: "encoding"), ErrorPreceding,
        EncodeCrossCrate::Yes, experimental!(cfi_encoding)
    ),

    // `#[coroutine]` attribute to be applied to closures to make them coroutines instead
    gated!(
        coroutine, Normal, template!(Word), ErrorFollowing,
        EncodeCrossCrate::No, coroutines, experimental!(coroutine)
    ),

    // RFC 3543
    // `#[patchable_function_entry(prefix_nops = m, entry_nops = n)]`
    gated!(
        patchable_function_entry, Normal, template!(List: &["prefix_nops = m, entry_nops = n"]), ErrorPreceding,
        EncodeCrossCrate::Yes, experimental!(patchable_function_entry)
    ),

    // Probably temporary component of min_generic_const_args.
    // `#[type_const] const ASSOC: usize;`
    gated!(
        type_const, Normal, template!(Word), ErrorFollowing,
        EncodeCrossCrate::Yes, min_generic_const_args, experimental!(type_const),
    ),

    // The `#[loop_match]` and `#[const_continue]` attributes are part of the
    // lang experiment for RFC 3720 tracked in:
    //
    // - https://github.com/rust-lang/rust/issues/132306
    gated!(
        const_continue, Normal, template!(Word), ErrorFollowing,
        EncodeCrossCrate::No, loop_match, experimental!(const_continue)
    ),
    gated!(
        loop_match, Normal, template!(Word), ErrorFollowing,
        EncodeCrossCrate::No, loop_match, experimental!(loop_match)
    ),

    // ==========================================================================
    // Internal attributes: Stability, deprecation, and unsafe:
    // ==========================================================================

    ungated!(
        feature, CrateLevel,
        template!(List: &["name1, name2, ..."]), DuplicatesOk, EncodeCrossCrate::No,
    ),
    // DuplicatesOk since it has its own validation
    ungated!(
        stable, Normal,
        template!(List: &[r#"feature = "name", since = "version""#]), DuplicatesOk, EncodeCrossCrate::No,
    ),
    ungated!(
        unstable, Normal,
        template!(List: &[r#"feature = "name", reason = "...", issue = "N""#]), DuplicatesOk,
        EncodeCrossCrate::Yes
    ),
    ungated!(
        unstable_feature_bound, Normal, template!(Word, List: &["feat1, feat2, ..."]),
        DuplicatesOk, EncodeCrossCrate::No,
    ),
    ungated!(
        rustc_const_unstable, Normal, template!(List: &[r#"feature = "name""#]),
        DuplicatesOk, EncodeCrossCrate::Yes
    ),
    ungated!(
        rustc_const_stable, Normal,
        template!(List: &[r#"feature = "name""#]), DuplicatesOk, EncodeCrossCrate::No,
    ),
    ungated!(
        rustc_default_body_unstable, Normal,
        template!(List: &[r#"feature = "name", reason = "...", issue = "N""#]),
        DuplicatesOk, EncodeCrossCrate::No
    ),
    gated!(
        allow_internal_unstable, Normal, template!(Word, List: &["feat1, feat2, ..."]),
        DuplicatesOk, EncodeCrossCrate::Yes,
        "allow_internal_unstable side-steps feature gating and stability checks",
    ),
    gated!(
        allow_internal_unsafe, Normal, template!(Word), WarnFollowing,
        EncodeCrossCrate::No, "allow_internal_unsafe side-steps the unsafe_code lint",
    ),
    rustc_attr!(
        rustc_allowed_through_unstable_modules, Normal, template!(NameValueStr: "deprecation message"),
        WarnFollowing, EncodeCrossCrate::No,
        "rustc_allowed_through_unstable_modules special cases accidental stabilizations of stable items \
        through unstable paths"
    ),
    rustc_attr!(
        rustc_deprecated_safe_2024, Normal, template!(List: &[r#"audit_that = "...""#]),
        ErrorFollowing, EncodeCrossCrate::Yes,
        "`#[rustc_deprecated_safe_2024]` is used to declare functions unsafe across the edition 2024 boundary",
    ),
    rustc_attr!(
        rustc_pub_transparent, Normal, template!(Word),
        ErrorFollowing, EncodeCrossCrate::Yes,
        "used internally to mark types with a `transparent` representation when it is guaranteed by the documentation",
    ),


    // ==========================================================================
    // Internal attributes: Type system related:
    // ==========================================================================

    gated!(fundamental, Normal, template!(Word), WarnFollowing, EncodeCrossCrate::Yes, experimental!(fundamental)),
    gated!(
        may_dangle, Normal, template!(Word), WarnFollowing,
        EncodeCrossCrate::No, dropck_eyepatch,
        "`may_dangle` has unstable semantics and may be removed in the future",
    ),

    rustc_attr!(
        rustc_never_type_options,
        Normal,
        template!(List: &[
            "",
            r#"fallback = "unit""#,
            r#"fallback = "niko""#,
            r#"fallback = "never""#,
            r#"fallback = "no""#,
        ]),
        ErrorFollowing,
        EncodeCrossCrate::No,
        "`rustc_never_type_options` is used to experiment with never type fallback and work on \
         never type stabilization"
    ),

    // ==========================================================================
    // Internal attributes: Runtime related:
    // ==========================================================================

    rustc_attr!(
        rustc_allocator, Normal, template!(Word), WarnFollowing,
        EncodeCrossCrate::No,
    ),
    rustc_attr!(
        rustc_nounwind, Normal, template!(Word), WarnFollowing,
        EncodeCrossCrate::No,
    ),
    rustc_attr!(
        rustc_reallocator, Normal, template!(Word), WarnFollowing,
        EncodeCrossCrate::No,
    ),
    rustc_attr!(
        rustc_deallocator, Normal, template!(Word), WarnFollowing,
        EncodeCrossCrate::No,
    ),
    rustc_attr!(
        rustc_allocator_zeroed, Normal, template!(Word), WarnFollowing,
        EncodeCrossCrate::No,
    ),
    rustc_attr!(
        rustc_allocator_zeroed_variant, Normal, template!(NameValueStr: "function"), ErrorPreceding,
        EncodeCrossCrate::Yes,
    ),
    gated!(
        default_lib_allocator, Normal, template!(Word), WarnFollowing,
        EncodeCrossCrate::No, allocator_internals, experimental!(default_lib_allocator),
    ),
    gated!(
        needs_allocator, Normal, template!(Word), WarnFollowing,
        EncodeCrossCrate::No, allocator_internals, experimental!(needs_allocator),
    ),
    gated!(
        panic_runtime, CrateLevel, template!(Word), WarnFollowing,
        EncodeCrossCrate::No, experimental!(panic_runtime)
    ),
    gated!(
        needs_panic_runtime, CrateLevel, template!(Word), WarnFollowing,
        EncodeCrossCrate::No, experimental!(needs_panic_runtime)
    ),
    gated!(
        compiler_builtins, CrateLevel, template!(Word), WarnFollowing,
        EncodeCrossCrate::No,
        "the `#[compiler_builtins]` attribute is used to identify the `compiler_builtins` crate \
        which contains compiler-rt intrinsics and will never be stable",
    ),
    gated!(
        profiler_runtime, CrateLevel, template!(Word), WarnFollowing,
        EncodeCrossCrate::No,
        "the `#[profiler_runtime]` attribute is used to identify the `profiler_builtins` crate \
        which contains the profiler runtime and will never be stable",
    ),

    // ==========================================================================
    // Internal attributes, Linkage:
    // ==========================================================================

    gated!(
        linkage, Normal, template!(NameValueStr: [
            "available_externally",
            "common",
            "extern_weak",
            "external",
            "internal",
            "linkonce",
            "linkonce_odr",
            "weak",
            "weak_odr",
        ], "https://doc.rust-lang.org/reference/linkage.html"),
        ErrorPreceding, EncodeCrossCrate::No,
        "the `linkage` attribute is experimental and not portable across platforms",
    ),
    rustc_attr!(
        rustc_std_internal_symbol, Normal, template!(Word), WarnFollowing,
        EncodeCrossCrate::No,
    ),

    // ==========================================================================
    // Internal attributes, Macro related:
    // ==========================================================================

    rustc_attr!(
        rustc_builtin_macro, Normal,
        template!(Word, List: &["name", "name, /*opt*/ attributes(name1, name2, ...)"]), ErrorFollowing,
        EncodeCrossCrate::Yes,
    ),
    rustc_attr!(
        rustc_proc_macro_decls, Normal, template!(Word), WarnFollowing,
        EncodeCrossCrate::No,
    ),
    rustc_attr!(
        rustc_macro_transparency, Normal,
        template!(NameValueStr: ["transparent", "semiopaque", "opaque"]), ErrorFollowing,
        EncodeCrossCrate::Yes, "used internally for testing macro hygiene",
    ),
    rustc_attr!(
        rustc_autodiff, Normal,
        template!(Word, List: &[r#""...""#]), DuplicatesOk,
        EncodeCrossCrate::Yes,
    ),
    // Traces that are left when `cfg` and `cfg_attr` attributes are expanded.
    // The attributes are not gated, to avoid stability errors, but they cannot be used in stable
    // or unstable code directly because `sym::cfg_(attr_)trace` are not valid identifiers, they
    // can only be generated by the compiler.
    ungated!(
        cfg_trace, Normal, template!(Word /* irrelevant */), DuplicatesOk,
        EncodeCrossCrate::No
    ),
    ungated!(
        cfg_attr_trace, Normal, template!(Word /* irrelevant */), DuplicatesOk,
        EncodeCrossCrate::No
    ),

    // ==========================================================================
    // Internal attributes, Diagnostics related:
    // ==========================================================================

    rustc_attr!(
        rustc_on_unimplemented, Normal,
        template!(
            List: &[r#"/*opt*/ message = "...", /*opt*/ label = "...", /*opt*/ note = "...""#],
            NameValueStr: "message"
        ),
        ErrorFollowing, EncodeCrossCrate::Yes,
        "see `#[diagnostic::on_unimplemented]` for the stable equivalent of this attribute"
    ),
    rustc_attr!(
        rustc_confusables, Normal,
        template!(List: &[r#""name1", "name2", ..."#]),
        ErrorFollowing, EncodeCrossCrate::Yes,
    ),
    // Enumerates "identity-like" conversion methods to suggest on type mismatch.
    rustc_attr!(
        rustc_conversion_suggestion, Normal, template!(Word),
        WarnFollowing, EncodeCrossCrate::Yes,
    ),
    // Prevents field reads in the marked trait or method to be considered
    // during dead code analysis.
    rustc_attr!(
        rustc_trivial_field_reads, Normal, template!(Word),
        WarnFollowing, EncodeCrossCrate::Yes,
    ),
    // Used by the `rustc::potential_query_instability` lint to warn methods which
    // might not be stable during incremental compilation.
    rustc_attr!(
        rustc_lint_query_instability, Normal, template!(Word),
        WarnFollowing, EncodeCrossCrate::Yes,
    ),
    // Used by the `rustc::untracked_query_information` lint to warn methods which
    // might not be stable during incremental compilation.
    rustc_attr!(
        rustc_lint_untracked_query_information, Normal, template!(Word),
        WarnFollowing, EncodeCrossCrate::Yes,
    ),
    // Used by the `rustc::diagnostic_outside_of_impl` lints to assist in changes to diagnostic
    // APIs. Any function with this attribute will be checked by that lint.
    rustc_attr!(
        rustc_lint_diagnostics, Normal, template!(Word),
        WarnFollowing, EncodeCrossCrate::Yes,
    ),
    // Used by the `rustc::bad_opt_access` lint to identify `DebuggingOptions` and `CodegenOptions`
    // types (as well as any others in future).
    rustc_attr!(
        rustc_lint_opt_ty, Normal, template!(Word),
        WarnFollowing, EncodeCrossCrate::Yes,
    ),
    // Used by the `rustc::bad_opt_access` lint on fields
    // types (as well as any others in future).
    rustc_attr!(
        rustc_lint_opt_deny_field_access, Normal, template!(List: &["message"]),
        WarnFollowing, EncodeCrossCrate::Yes,
    ),

    // ==========================================================================
    // Internal attributes, Const related:
    // ==========================================================================

    rustc_attr!(
        rustc_promotable, Normal, template!(Word), WarnFollowing,
        EncodeCrossCrate::No, ),
    rustc_attr!(
        rustc_legacy_const_generics, Normal, template!(List: &["N"]), ErrorFollowing,
        EncodeCrossCrate::Yes,
    ),
    // Do not const-check this function's body. It will always get replaced during CTFE via `hook_special_const_fn`.
    rustc_attr!(
        rustc_do_not_const_check, Normal, template!(Word), WarnFollowing,
        EncodeCrossCrate::Yes, "`#[rustc_do_not_const_check]` skips const-check for this function's body",
    ),
    rustc_attr!(
        rustc_const_stable_indirect, Normal,
        template!(Word),
        WarnFollowing,
        EncodeCrossCrate::No,
        "this is an internal implementation detail",
    ),
    rustc_attr!(
        rustc_intrinsic_const_stable_indirect, Normal,
        template!(Word), WarnFollowing, EncodeCrossCrate::No,  "this is an internal implementation detail",
    ),
    gated!(
        rustc_allow_const_fn_unstable, Normal,
        template!(Word, List: &["feat1, feat2, ..."]), DuplicatesOk, EncodeCrossCrate::No,
        "rustc_allow_const_fn_unstable side-steps feature gating and stability checks"
    ),

    // ==========================================================================
    // Internal attributes, Layout related:
    // ==========================================================================

    rustc_attr!(
        rustc_layout_scalar_valid_range_start, Normal, template!(List: &["value"]), ErrorFollowing,
        EncodeCrossCrate::Yes,
        "the `#[rustc_layout_scalar_valid_range_start]` attribute is just used to enable \
        niche optimizations in the standard library",
    ),
    rustc_attr!(
        rustc_layout_scalar_valid_range_end, Normal, template!(List: &["value"]), ErrorFollowing,
        EncodeCrossCrate::Yes,
        "the `#[rustc_layout_scalar_valid_range_end]` attribute is just used to enable \
        niche optimizations in the standard library",
    ),
    rustc_attr!(
        rustc_nonnull_optimization_guaranteed, Normal, template!(Word), WarnFollowing,
        EncodeCrossCrate::Yes,
        "the `#[rustc_nonnull_optimization_guaranteed]` attribute is just used to document \
        guaranteed niche optimizations in the standard library",
        "the compiler does not even check whether the type indeed is being non-null-optimized; \
        it is your responsibility to ensure that the attribute is only used on types that are optimized",
    ),

    // ==========================================================================
    // Internal attributes, Misc:
    // ==========================================================================
    gated!(
        lang, Normal, template!(NameValueStr: "name"), DuplicatesOk, EncodeCrossCrate::No, lang_items,
        "lang items are subject to change",
    ),
    rustc_attr!(
        rustc_as_ptr, Normal, template!(Word), ErrorFollowing,
        EncodeCrossCrate::Yes,
        "`#[rustc_as_ptr]` is used to mark functions returning pointers to their inner allocations."
    ),
    rustc_attr!(
        rustc_pass_by_value, Normal, template!(Word), ErrorFollowing,
        EncodeCrossCrate::Yes,
        "`#[rustc_pass_by_value]` is used to mark types that must be passed by value instead of reference."
    ),
    rustc_attr!(
        rustc_never_returns_null_ptr, Normal, template!(Word), ErrorFollowing,
        EncodeCrossCrate::Yes,
        "`#[rustc_never_returns_null_ptr]` is used to mark functions returning non-null pointers."
    ),
    rustc_attr!(
        rustc_no_implicit_autorefs, AttributeType::Normal, template!(Word), ErrorFollowing, EncodeCrossCrate::Yes,
        "`#[rustc_no_implicit_autorefs]` is used to mark functions for which an autoref to the dereference of a raw pointer should not be used as an argument."
    ),
    rustc_attr!(
        rustc_coherence_is_core, AttributeType::CrateLevel, template!(Word), ErrorFollowing, EncodeCrossCrate::No,
        "`#![rustc_coherence_is_core]` allows inherent methods on builtin types, only intended to be used in `core`."
    ),
    rustc_attr!(
        rustc_coinductive, AttributeType::Normal, template!(Word), WarnFollowing, EncodeCrossCrate::No,
        "`#[rustc_coinductive]` changes a trait to be coinductive, allowing cycles in the trait solver."
    ),
    rustc_attr!(
        rustc_allow_incoherent_impl, AttributeType::Normal, template!(Word), ErrorFollowing, EncodeCrossCrate::No,
        "`#[rustc_allow_incoherent_impl]` has to be added to all impl items of an incoherent inherent impl."
    ),
    rustc_attr!(
        rustc_preserve_ub_checks, AttributeType::CrateLevel, template!(Word), ErrorFollowing, EncodeCrossCrate::No,
        "`#![rustc_preserve_ub_checks]` prevents the designated crate from evaluating whether UB checks are enabled when optimizing MIR",
    ),
    rustc_attr!(
        rustc_deny_explicit_impl,
        AttributeType::Normal,
        template!(Word),
        ErrorFollowing,
        EncodeCrossCrate::No,
        "`#[rustc_deny_explicit_impl]` enforces that a trait can have no user-provided impls"
    ),
    rustc_attr!(
        rustc_do_not_implement_via_object,
        AttributeType::Normal,
        template!(Word),
        ErrorFollowing,
        EncodeCrossCrate::No,
        "`#[rustc_do_not_implement_via_object]` opts out of the automatic trait impl for trait objects \
        (`impl Trait for dyn Trait`)"
    ),
    rustc_attr!(
        rustc_has_incoherent_inherent_impls, AttributeType::Normal, template!(Word),
        ErrorFollowing, EncodeCrossCrate::Yes,
        "`#[rustc_has_incoherent_inherent_impls]` allows the addition of incoherent inherent impls for \
         the given type by annotating all impl items with `#[rustc_allow_incoherent_impl]`."
    ),

    BuiltinAttribute {
        name: sym::rustc_diagnostic_item,
        // FIXME: This can be `true` once we always use `tcx.is_diagnostic_item`.
        encode_cross_crate: EncodeCrossCrate::Yes,
        type_: Normal,
        safety: AttributeSafety::Normal,
        template: template!(NameValueStr: "name"),
        duplicates: ErrorFollowing,
        gate: Gated{
            feature: sym::rustc_attrs,
            message: "use of an internal attribute",
            check: Features::rustc_attrs,
            notes: &["the `#[rustc_diagnostic_item]` attribute allows the compiler to reference types \
            from the standard library for diagnostic purposes"],
        },
    },
    gated!(
        // Used in resolve:
        prelude_import, Normal, template!(Word), WarnFollowing,
        EncodeCrossCrate::No, "`#[prelude_import]` is for use by rustc only",
    ),
    gated!(
        rustc_paren_sugar, Normal, template!(Word), WarnFollowing, EncodeCrossCrate::No,
        unboxed_closures, "unboxed_closures are still evolving",
    ),
    rustc_attr!(
        rustc_inherit_overflow_checks, Normal, template!(Word), WarnFollowing, EncodeCrossCrate::No,
        "the `#[rustc_inherit_overflow_checks]` attribute is just used to control \
        overflow checking behavior of several functions in the standard library that are inlined \
        across crates",
    ),
    rustc_attr!(
        rustc_reservation_impl, Normal,
        template!(NameValueStr: "reservation message"), ErrorFollowing, EncodeCrossCrate::Yes,
        "the `#[rustc_reservation_impl]` attribute is internally used \
        for reserving `impl<T> From<!> for T` as part of the effort to stabilize `!`"
    ),
    rustc_attr!(
        rustc_test_marker, Normal, template!(NameValueStr: "name"), WarnFollowing,
        EncodeCrossCrate::No, "the `#[rustc_test_marker]` attribute is used internally to track tests",
    ),
    rustc_attr!(
        rustc_unsafe_specialization_marker, Normal, template!(Word),
        WarnFollowing, EncodeCrossCrate::No,
        "the `#[rustc_unsafe_specialization_marker]` attribute is used to check specializations"
    ),
    rustc_attr!(
        rustc_specialization_trait, Normal, template!(Word),
        WarnFollowing, EncodeCrossCrate::No,
        "the `#[rustc_specialization_trait]` attribute is used to check specializations"
    ),
    rustc_attr!(
        rustc_main, Normal, template!(Word), WarnFollowing, EncodeCrossCrate::No,
        "the `#[rustc_main]` attribute is used internally to specify test entry point function",
    ),
    rustc_attr!(
        rustc_skip_during_method_dispatch, Normal, template!(List: &["array, boxed_slice"]), ErrorFollowing,
        EncodeCrossCrate::No,
        "the `#[rustc_skip_during_method_dispatch]` attribute is used to exclude a trait \
        from method dispatch when the receiver is of the following type, for compatibility in \
        editions < 2021 (array) or editions < 2024 (boxed_slice)."
    ),
    rustc_attr!(
        rustc_must_implement_one_of, Normal, template!(List: &["function1, function2, ..."]),
        ErrorFollowing, EncodeCrossCrate::No,
        "the `#[rustc_must_implement_one_of]` attribute is used to change minimal complete \
        definition of a trait. Its syntax and semantics are highly experimental and will be \
        subject to change before stabilization",
    ),
    rustc_attr!(
        rustc_doc_primitive, Normal, template!(NameValueStr: "primitive name"), ErrorFollowing,
        EncodeCrossCrate::Yes, "the `#[rustc_doc_primitive]` attribute is used by the standard library \
        to provide a way to generate documentation for primitive types",
    ),
    gated!(
        rustc_intrinsic, Normal, template!(Word), ErrorFollowing, EncodeCrossCrate::Yes, intrinsics,
        "the `#[rustc_intrinsic]` attribute is used to declare intrinsics as function items",
    ),
    rustc_attr!(
        rustc_no_mir_inline, Normal, template!(Word), WarnFollowing, EncodeCrossCrate::Yes,
        "`#[rustc_no_mir_inline]` prevents the MIR inliner from inlining a function while not affecting codegen"
    ),
    rustc_attr!(
        rustc_force_inline, Normal, template!(Word, NameValueStr: "reason"), WarnFollowing, EncodeCrossCrate::Yes,
        "`#[rustc_force_inline]` forces a free function to be inlined"
    ),

    // ==========================================================================
    // Internal attributes, Testing:
    // ==========================================================================

    rustc_attr!(TEST, rustc_effective_visibility, Normal, template!(Word), WarnFollowing, EncodeCrossCrate::Yes),
    rustc_attr!(
        TEST, rustc_outlives, Normal, template!(Word),
        WarnFollowing, EncodeCrossCrate::No
    ),
    rustc_attr!(
        TEST, rustc_capture_analysis, Normal, template!(Word),
        WarnFollowing, EncodeCrossCrate::No
    ),
    rustc_attr!(
        TEST, rustc_insignificant_dtor, Normal, template!(Word),
        WarnFollowing, EncodeCrossCrate::Yes
    ),
    rustc_attr!(
        TEST, rustc_no_implicit_bounds, CrateLevel, template!(Word),
        WarnFollowing, EncodeCrossCrate::No
    ),
    rustc_attr!(
        TEST, rustc_strict_coherence, Normal, template!(Word),
        WarnFollowing, EncodeCrossCrate::Yes
    ),
    rustc_attr!(
        TEST, rustc_variance, Normal, template!(Word),
        WarnFollowing, EncodeCrossCrate::No
    ),
    rustc_attr!(
        TEST, rustc_variance_of_opaques, Normal, template!(Word),
        WarnFollowing, EncodeCrossCrate::No
    ),
    rustc_attr!(
        TEST, rustc_hidden_type_of_opaques, Normal, template!(Word),
        WarnFollowing, EncodeCrossCrate::No
    ),
    rustc_attr!(
        TEST, rustc_layout, Normal, template!(List: &["field1, field2, ..."]),
        WarnFollowing, EncodeCrossCrate::Yes
    ),
    rustc_attr!(
        TEST, rustc_abi, Normal, template!(List: &["field1, field2, ..."]),
        WarnFollowing, EncodeCrossCrate::No
    ),
    rustc_attr!(
        TEST, rustc_regions, Normal, template!(Word),
        WarnFollowing, EncodeCrossCrate::No
    ),
    rustc_attr!(
        TEST, rustc_delayed_bug_from_inside_query, Normal,
        template!(Word),
        WarnFollowing, EncodeCrossCrate::No
    ),
    rustc_attr!(
        TEST, rustc_dump_user_args, Normal, template!(Word),
        WarnFollowing, EncodeCrossCrate::No
    ),
    rustc_attr!(
        TEST, rustc_evaluate_where_clauses, Normal, template!(Word), WarnFollowing,
        EncodeCrossCrate::Yes
    ),
    rustc_attr!(
        TEST, rustc_if_this_changed, Normal, template!(Word, List: &["DepNode"]), DuplicatesOk,
        EncodeCrossCrate::No
    ),
    rustc_attr!(
        TEST, rustc_then_this_would_need, Normal, template!(List: &["DepNode"]), DuplicatesOk,
        EncodeCrossCrate::No
    ),
    rustc_attr!(
        TEST, rustc_clean, Normal,
        template!(List: &[r#"cfg = "...", /*opt*/ label = "...", /*opt*/ except = "...""#]),
        DuplicatesOk, EncodeCrossCrate::No
    ),
    rustc_attr!(
        TEST, rustc_partition_reused, Normal,
        template!(List: &[r#"cfg = "...", module = "...""#]), DuplicatesOk, EncodeCrossCrate::No
    ),
    rustc_attr!(
        TEST, rustc_partition_codegened, Normal,
        template!(List: &[r#"cfg = "...", module = "...""#]), DuplicatesOk, EncodeCrossCrate::No
    ),
    rustc_attr!(
        TEST, rustc_expected_cgu_reuse, Normal,
        template!(List: &[r#"cfg = "...", module = "...", kind = "...""#]), DuplicatesOk,
        EncodeCrossCrate::No
    ),
    rustc_attr!(
        TEST, rustc_symbol_name, Normal, template!(Word),
        WarnFollowing, EncodeCrossCrate::No
    ),
    rustc_attr!(
        TEST, rustc_def_path, Normal, template!(Word),
        WarnFollowing, EncodeCrossCrate::No
    ),
    rustc_attr!(
        TEST, rustc_mir, Normal, template!(List: &["arg1, arg2, ..."]),
        DuplicatesOk, EncodeCrossCrate::Yes
    ),
    gated!(
        custom_mir, Normal, template!(List: &[r#"dialect = "...", phase = "...""#]),
        ErrorFollowing, EncodeCrossCrate::No,
        "the `#[custom_mir]` attribute is just used for the Rust test suite",
    ),
    rustc_attr!(
        TEST, rustc_dump_item_bounds, Normal, template!(Word),
        WarnFollowing, EncodeCrossCrate::No
    ),
    rustc_attr!(
        TEST, rustc_dump_predicates, Normal, template!(Word),
        WarnFollowing, EncodeCrossCrate::No
    ),
    rustc_attr!(
        TEST, rustc_dump_def_parents, Normal, template!(Word),
        WarnFollowing, EncodeCrossCrate::No
    ),
    rustc_attr!(
        TEST, rustc_object_lifetime_default, Normal, template!(Word),
        WarnFollowing, EncodeCrossCrate::No
    ),
    rustc_attr!(
        TEST, rustc_dump_vtable, Normal, template!(Word),
        WarnFollowing, EncodeCrossCrate::No
    ),
    rustc_attr!(
        TEST, rustc_dummy, Normal, template!(Word /* doesn't matter*/),
        DuplicatesOk, EncodeCrossCrate::No
    ),
    rustc_attr!(
        TEST, pattern_complexity_limit, CrateLevel, template!(NameValueStr: "N"),
        ErrorFollowing, EncodeCrossCrate::No,
    ),
];

pub fn is_builtin_attr_name(name: Symbol) -> bool {
    BUILTIN_ATTRIBUTE_MAP.get(&name).is_some()
}

/// Whether this builtin attribute is encoded cross crate.
/// This means it can be used cross crate.
pub fn encode_cross_crate(name: Symbol) -> bool {
    if let Some(attr) = BUILTIN_ATTRIBUTE_MAP.get(&name) {
        attr.encode_cross_crate == EncodeCrossCrate::Yes
    } else {
        true
    }
}

pub fn is_valid_for_get_attr(name: Symbol) -> bool {
    BUILTIN_ATTRIBUTE_MAP.get(&name).is_some_and(|attr| match attr.duplicates {
        WarnFollowing | ErrorFollowing | ErrorPreceding | FutureWarnFollowing
        | FutureWarnPreceding => true,
        DuplicatesOk | WarnFollowingWordOnly => false,
    })
}

pub static BUILTIN_ATTRIBUTE_MAP: LazyLock<FxHashMap<Symbol, &BuiltinAttribute>> =
    LazyLock::new(|| {
        let mut map = FxHashMap::default();
        for attr in BUILTIN_ATTRIBUTES.iter() {
            if map.insert(attr.name, attr).is_some() {
                panic!("duplicate builtin attribute `{}`", attr.name);
            }
        }
        map
    });

pub fn is_stable_diagnostic_attribute(sym: Symbol, _features: &Features) -> bool {
    match sym {
        sym::on_unimplemented | sym::do_not_recommend => true,
        _ => false,
    }
}