Thanks to visit codestin.com
Credit goes to doc.rust-lang.org

rustc_span/
symbol.rs

1//! An "interner" is a data structure that associates values with usize tags and
2//! allows bidirectional lookup; i.e., given a value, one can easily find the
3//! type, and vice versa.
4
5use std::hash::{Hash, Hasher};
6use std::ops::Deref;
7use std::{fmt, str};
8
9use rustc_arena::DroplessArena;
10use rustc_data_structures::fx::{FxHashSet, FxIndexSet};
11use rustc_data_structures::stable_hasher::{
12    HashStable, StableCompare, StableHasher, ToStableHashKey,
13};
14use rustc_data_structures::sync::Lock;
15use rustc_macros::{Decodable, Encodable, HashStable_Generic, symbols};
16
17use crate::{DUMMY_SP, Edition, Span, with_session_globals};
18
19#[cfg(test)]
20mod tests;
21
22// The proc macro code for this is in `compiler/rustc_macros/src/symbols.rs`.
23symbols! {
24    // This list includes things that are definitely keywords (e.g. `if`), a
25    // few things that are definitely not keywords (e.g. `{{root}}`) and things
26    // where there is disagreement between people and/or documents (such as the
27    // Rust Reference) about whether it is a keyword (e.g. `_`).
28    //
29    // If you modify this list, adjust any relevant `Symbol::{is,can_be}_*`
30    // predicates and `used_keywords`. Also consider adding new keywords to the
31    // `ui/parser/raw/raw-idents.rs` test.
32    Keywords {
33        // Special reserved identifiers used internally for unnamed method
34        // parameters, crate root module, etc.
35        // Matching predicates: `is_special`/`is_reserved`
36        //
37        // tidy-alphabetical-start
38        DollarCrate:        "$crate",
39        PathRoot:           "{{root}}",
40        Underscore:         "_",
41        // tidy-alphabetical-end
42
43        // Keywords that are used in stable Rust.
44        // Matching predicates: `is_used_keyword_always`/`is_reserved`
45        // tidy-alphabetical-start
46        As:                 "as",
47        Break:              "break",
48        Const:              "const",
49        Continue:           "continue",
50        Crate:              "crate",
51        Else:               "else",
52        Enum:               "enum",
53        Extern:             "extern",
54        False:              "false",
55        Fn:                 "fn",
56        For:                "for",
57        If:                 "if",
58        Impl:               "impl",
59        In:                 "in",
60        Let:                "let",
61        Loop:               "loop",
62        Match:              "match",
63        Mod:                "mod",
64        Move:               "move",
65        Mut:                "mut",
66        Pub:                "pub",
67        Ref:                "ref",
68        Return:             "return",
69        SelfLower:          "self",
70        SelfUpper:          "Self",
71        Static:             "static",
72        Struct:             "struct",
73        Super:              "super",
74        Trait:              "trait",
75        True:               "true",
76        Type:               "type",
77        Unsafe:             "unsafe",
78        Use:                "use",
79        Where:              "where",
80        While:              "while",
81        // tidy-alphabetical-end
82
83        // Keywords that are used in unstable Rust or reserved for future use.
84        // Matching predicates: `is_unused_keyword_always`/`is_reserved`
85        // tidy-alphabetical-start
86        Abstract:           "abstract",
87        Become:             "become",
88        Box:                "box",
89        Do:                 "do",
90        Final:              "final",
91        Macro:              "macro",
92        Override:           "override",
93        Priv:               "priv",
94        Typeof:             "typeof",
95        Unsized:            "unsized",
96        Virtual:            "virtual",
97        Yield:              "yield",
98        // tidy-alphabetical-end
99
100        // Edition-specific keywords that are used in stable Rust.
101        // Matching predicates: `is_used_keyword_conditional`/`is_reserved` (if
102        // the edition suffices)
103        // tidy-alphabetical-start
104        Async:              "async", // >= 2018 Edition only
105        Await:              "await", // >= 2018 Edition only
106        Dyn:                "dyn", // >= 2018 Edition only
107        // tidy-alphabetical-end
108
109        // Edition-specific keywords that are used in unstable Rust or reserved for future use.
110        // Matching predicates: `is_unused_keyword_conditional`/`is_reserved` (if
111        // the edition suffices)
112        // tidy-alphabetical-start
113        Gen:                "gen", // >= 2024 Edition only
114        Try:                "try", // >= 2018 Edition only
115        // tidy-alphabetical-end
116
117        // "Lifetime keywords": regular keywords with a leading `'`.
118        // Matching predicates: none
119        // tidy-alphabetical-start
120        StaticLifetime:     "'static",
121        UnderscoreLifetime: "'_",
122        // tidy-alphabetical-end
123
124        // Weak keywords, have special meaning only in specific contexts.
125        // Matching predicates: `is_weak`
126        // tidy-alphabetical-start
127        Auto:               "auto",
128        Builtin:            "builtin",
129        Catch:              "catch",
130        ContractEnsures:    "contract_ensures",
131        ContractRequires:   "contract_requires",
132        Default:            "default",
133        MacroRules:         "macro_rules",
134        Raw:                "raw",
135        Reuse:              "reuse",
136        Safe:               "safe",
137        Union:              "union",
138        Yeet:               "yeet",
139        // tidy-alphabetical-end
140    }
141
142    // Pre-interned symbols that can be referred to with `rustc_span::sym::*`.
143    //
144    // The symbol is the stringified identifier unless otherwise specified, in
145    // which case the name should mention the non-identifier punctuation.
146    // E.g. `sym::proc_dash_macro` represents "proc-macro", and it shouldn't be
147    // called `sym::proc_macro` because then it's easy to mistakenly think it
148    // represents "proc_macro".
149    //
150    // As well as the symbols listed, there are symbols for the strings
151    // "0", "1", ..., "9", which are accessible via `sym::integer`.
152    //
153    // There is currently no checking that all symbols are used; that would be
154    // nice to have.
155    Symbols {
156        // tidy-alphabetical-start
157        Abi,
158        AcqRel,
159        Acquire,
160        Any,
161        Arc,
162        ArcWeak,
163        Argument,
164        ArrayIntoIter,
165        AsMut,
166        AsRef,
167        AssertParamIsClone,
168        AssertParamIsCopy,
169        AssertParamIsEq,
170        AsyncGenFinished,
171        AsyncGenPending,
172        AsyncGenReady,
173        AtomicBool,
174        AtomicI8,
175        AtomicI16,
176        AtomicI32,
177        AtomicI64,
178        AtomicI128,
179        AtomicIsize,
180        AtomicPtr,
181        AtomicU8,
182        AtomicU16,
183        AtomicU32,
184        AtomicU64,
185        AtomicU128,
186        AtomicUsize,
187        BTreeEntry,
188        BTreeMap,
189        BTreeSet,
190        BinaryHeap,
191        Borrow,
192        BorrowMut,
193        Break,
194        C,
195        CStr,
196        C_dash_unwind: "C-unwind",
197        CallOnceFuture,
198        CallRefFuture,
199        Capture,
200        Cell,
201        Center,
202        Child,
203        Cleanup,
204        Clone,
205        CoercePointee,
206        CoercePointeeValidated,
207        CoerceUnsized,
208        Command,
209        ConstParamTy,
210        ConstParamTy_,
211        Context,
212        Continue,
213        ControlFlow,
214        Copy,
215        Cow,
216        Debug,
217        DebugStruct,
218        Decodable,
219        Decoder,
220        Default,
221        Deref,
222        DiagMessage,
223        Diagnostic,
224        DirBuilder,
225        DispatchFromDyn,
226        Display,
227        DoubleEndedIterator,
228        Duration,
229        Encodable,
230        Encoder,
231        Enumerate,
232        Eq,
233        Equal,
234        Err,
235        Error,
236        File,
237        FileType,
238        FmtArgumentsNew,
239        Fn,
240        FnMut,
241        FnOnce,
242        Formatter,
243        Forward,
244        From,
245        FromIterator,
246        FromResidual,
247        FsOpenOptions,
248        FsPermissions,
249        FusedIterator,
250        Future,
251        GlobalAlloc,
252        Hash,
253        HashMap,
254        HashMapEntry,
255        HashSet,
256        Hasher,
257        Implied,
258        InCleanup,
259        IndexOutput,
260        Input,
261        Instant,
262        Into,
263        IntoFuture,
264        IntoIterator,
265        IoBufRead,
266        IoLines,
267        IoRead,
268        IoSeek,
269        IoWrite,
270        IpAddr,
271        Ipv4Addr,
272        Ipv6Addr,
273        IrTyKind,
274        Is,
275        Item,
276        ItemContext,
277        IterEmpty,
278        IterOnce,
279        IterPeekable,
280        Iterator,
281        IteratorItem,
282        IteratorMap,
283        Layout,
284        Left,
285        LinkedList,
286        LintDiagnostic,
287        LintPass,
288        LocalKey,
289        Mutex,
290        MutexGuard,
291        N,
292        NonNull,
293        NonZero,
294        None,
295        Normal,
296        Ok,
297        Option,
298        Ord,
299        Ordering,
300        OsStr,
301        OsString,
302        Output,
303        Param,
304        ParamSet,
305        PartialEq,
306        PartialOrd,
307        Path,
308        PathBuf,
309        Pending,
310        PinCoerceUnsized,
311        Pointer,
312        Poll,
313        ProcMacro,
314        ProceduralMasqueradeDummyType,
315        Range,
316        RangeBounds,
317        RangeCopy,
318        RangeFrom,
319        RangeFromCopy,
320        RangeFull,
321        RangeInclusive,
322        RangeInclusiveCopy,
323        RangeMax,
324        RangeMin,
325        RangeSub,
326        RangeTo,
327        RangeToInclusive,
328        RangeToInclusiveCopy,
329        Rc,
330        RcWeak,
331        Ready,
332        Receiver,
333        RefCell,
334        RefCellRef,
335        RefCellRefMut,
336        Relaxed,
337        Release,
338        Result,
339        ResumeTy,
340        Return,
341        Reverse,
342        Right,
343        Rust,
344        RustaceansAreAwesome,
345        RwLock,
346        RwLockReadGuard,
347        RwLockWriteGuard,
348        Saturating,
349        SeekFrom,
350        SelfTy,
351        Send,
352        SeqCst,
353        Sized,
354        SliceIndex,
355        SliceIter,
356        Some,
357        SpanCtxt,
358        Stdin,
359        String,
360        StructuralPartialEq,
361        SubdiagMessage,
362        Subdiagnostic,
363        SymbolIntern,
364        Sync,
365        SyncUnsafeCell,
366        T,
367        Target,
368        This,
369        ToOwned,
370        ToString,
371        TokenStream,
372        Trait,
373        Try,
374        TryCaptureGeneric,
375        TryCapturePrintable,
376        TryFrom,
377        TryInto,
378        Ty,
379        TyCtxt,
380        TyKind,
381        Unknown,
382        Unsize,
383        UnsizedConstParamTy,
384        Upvars,
385        Vec,
386        VecDeque,
387        Waker,
388        Wrapper,
389        Wrapping,
390        Yield,
391        _DECLS,
392        __D,
393        __H,
394        __S,
395        __T,
396        __awaitee,
397        __try_var,
398        _t,
399        _task_context,
400        a32,
401        aarch64_target_feature,
402        aarch64_unstable_target_feature,
403        aarch64_ver_target_feature,
404        abi,
405        abi_amdgpu_kernel,
406        abi_avr_interrupt,
407        abi_c_cmse_nonsecure_call,
408        abi_cmse_nonsecure_call,
409        abi_custom,
410        abi_efiapi,
411        abi_gpu_kernel,
412        abi_msp430_interrupt,
413        abi_ptx,
414        abi_riscv_interrupt,
415        abi_sysv64,
416        abi_thiscall,
417        abi_unadjusted,
418        abi_vectorcall,
419        abi_x86_interrupt,
420        abort,
421        add,
422        add_assign,
423        add_with_overflow,
424        address,
425        adt_const_params,
426        advanced_slice_patterns,
427        adx_target_feature,
428        aes,
429        aggregate_raw_ptr,
430        alias,
431        align,
432        align_of,
433        align_of_val,
434        alignment,
435        all,
436        alloc,
437        alloc_error_handler,
438        alloc_layout,
439        alloc_zeroed,
440        allocator,
441        allocator_api,
442        allocator_internals,
443        allow,
444        allow_fail,
445        allow_internal_unsafe,
446        allow_internal_unstable,
447        altivec,
448        alu32,
449        always,
450        analysis,
451        and,
452        and_then,
453        anon,
454        anon_adt,
455        anon_assoc,
456        anonymous_lifetime_in_impl_trait,
457        any,
458        append_const_msg,
459        apx_target_feature,
460        arbitrary_enum_discriminant,
461        arbitrary_self_types,
462        arbitrary_self_types_pointers,
463        areg,
464        args,
465        arith_offset,
466        arm,
467        arm_target_feature,
468        array,
469        as_dash_needed: "as-needed",
470        as_ptr,
471        as_ref,
472        as_str,
473        asm,
474        asm_cfg,
475        asm_const,
476        asm_experimental_arch,
477        asm_experimental_reg,
478        asm_goto,
479        asm_goto_with_outputs,
480        asm_sym,
481        asm_unwind,
482        assert,
483        assert_eq,
484        assert_eq_macro,
485        assert_inhabited,
486        assert_macro,
487        assert_mem_uninitialized_valid,
488        assert_ne_macro,
489        assert_receiver_is_total_eq,
490        assert_zero_valid,
491        asserting,
492        associated_const_equality,
493        associated_consts,
494        associated_type_bounds,
495        associated_type_defaults,
496        associated_types,
497        assume,
498        assume_init,
499        asterisk: "*",
500        async_await,
501        async_call,
502        async_call_mut,
503        async_call_once,
504        async_closure,
505        async_drop,
506        async_drop_in_place,
507        async_fn,
508        async_fn_in_dyn_trait,
509        async_fn_in_trait,
510        async_fn_kind_helper,
511        async_fn_kind_upvars,
512        async_fn_mut,
513        async_fn_once,
514        async_fn_once_output,
515        async_fn_track_caller,
516        async_fn_traits,
517        async_for_loop,
518        async_iterator,
519        async_iterator_poll_next,
520        async_trait_bounds,
521        atomic,
522        atomic_and,
523        atomic_cxchg,
524        atomic_cxchgweak,
525        atomic_fence,
526        atomic_load,
527        atomic_max,
528        atomic_min,
529        atomic_mod,
530        atomic_nand,
531        atomic_or,
532        atomic_singlethreadfence,
533        atomic_store,
534        atomic_umax,
535        atomic_umin,
536        atomic_xadd,
537        atomic_xchg,
538        atomic_xor,
539        atomic_xsub,
540        atomics,
541        att_syntax,
542        attr,
543        attr_literals,
544        attribute,
545        attributes,
546        audit_that,
547        augmented_assignments,
548        auto_traits,
549        autodiff,
550        autodiff_forward,
551        autodiff_reverse,
552        automatically_derived,
553        available_externally,
554        avx,
555        avx10_target_feature,
556        avx512_target_feature,
557        avx512bw,
558        avx512f,
559        await_macro,
560        bang,
561        begin_panic,
562        bench,
563        bevy_ecs,
564        bikeshed_guaranteed_no_drop,
565        bin,
566        binaryheap_iter,
567        bind_by_move_pattern_guards,
568        bindings_after_at,
569        bitand,
570        bitand_assign,
571        bitor,
572        bitor_assign,
573        bitreverse,
574        bitxor,
575        bitxor_assign,
576        black_box,
577        block,
578        bool,
579        bool_then,
580        borrowck_graphviz_format,
581        borrowck_graphviz_postflow,
582        box_new,
583        box_patterns,
584        box_syntax,
585        boxed_slice,
586        bpf_target_feature,
587        braced_empty_structs,
588        branch,
589        breakpoint,
590        bridge,
591        bswap,
592        btreemap_contains_key,
593        btreemap_insert,
594        btreeset_iter,
595        built,
596        builtin_syntax,
597        bundle,
598        c,
599        c_dash_variadic,
600        c_str,
601        c_str_literals,
602        c_unwind,
603        c_variadic,
604        c_void,
605        call,
606        call_mut,
607        call_once,
608        call_once_future,
609        call_ref_future,
610        caller_location,
611        capture_disjoint_fields,
612        carrying_mul_add,
613        catch_unwind,
614        cause,
615        cdylib,
616        ceilf16,
617        ceilf32,
618        ceilf64,
619        ceilf128,
620        cfg,
621        cfg_accessible,
622        cfg_attr,
623        cfg_attr_multi,
624        cfg_attr_trace: "<cfg_attr>", // must not be a valid identifier
625        cfg_boolean_literals,
626        cfg_contract_checks,
627        cfg_doctest,
628        cfg_emscripten_wasm_eh,
629        cfg_eval,
630        cfg_fmt_debug,
631        cfg_hide,
632        cfg_overflow_checks,
633        cfg_panic,
634        cfg_relocation_model,
635        cfg_sanitize,
636        cfg_sanitizer_cfi,
637        cfg_select,
638        cfg_target_abi,
639        cfg_target_compact,
640        cfg_target_feature,
641        cfg_target_has_atomic,
642        cfg_target_has_atomic_equal_alignment,
643        cfg_target_has_reliable_f16_f128,
644        cfg_target_thread_local,
645        cfg_target_vendor,
646        cfg_trace: "<cfg>", // must not be a valid identifier
647        cfg_ub_checks,
648        cfg_version,
649        cfi,
650        cfi_encoding,
651        char,
652        char_is_ascii,
653        char_to_digit,
654        child_id,
655        child_kill,
656        client,
657        clippy,
658        clobber_abi,
659        clone,
660        clone_closures,
661        clone_fn,
662        clone_from,
663        closure,
664        closure_lifetime_binder,
665        closure_to_fn_coercion,
666        closure_track_caller,
667        cmp,
668        cmp_max,
669        cmp_min,
670        cmp_ord_max,
671        cmp_ord_min,
672        cmp_partialeq_eq,
673        cmp_partialeq_ne,
674        cmp_partialord_cmp,
675        cmp_partialord_ge,
676        cmp_partialord_gt,
677        cmp_partialord_le,
678        cmp_partialord_lt,
679        cmpxchg16b_target_feature,
680        cmse_nonsecure_entry,
681        coerce_pointee_validated,
682        coerce_unsized,
683        cold,
684        cold_path,
685        collapse_debuginfo,
686        column,
687        common,
688        compare_bytes,
689        compare_exchange,
690        compare_exchange_weak,
691        compile_error,
692        compiler,
693        compiler_builtins,
694        compiler_fence,
695        concat,
696        concat_bytes,
697        concat_idents,
698        conservative_impl_trait,
699        console,
700        const_allocate,
701        const_async_blocks,
702        const_closures,
703        const_compare_raw_pointers,
704        const_constructor,
705        const_continue,
706        const_deallocate,
707        const_destruct,
708        const_eval_limit,
709        const_eval_select,
710        const_evaluatable_checked,
711        const_extern_fn,
712        const_fn,
713        const_fn_floating_point_arithmetic,
714        const_fn_fn_ptr_basics,
715        const_fn_trait_bound,
716        const_fn_transmute,
717        const_fn_union,
718        const_fn_unsize,
719        const_for,
720        const_format_args,
721        const_generics,
722        const_generics_defaults,
723        const_if_match,
724        const_impl_trait,
725        const_in_array_repeat_expressions,
726        const_indexing,
727        const_let,
728        const_loop,
729        const_make_global,
730        const_mut_refs,
731        const_panic,
732        const_panic_fmt,
733        const_param_ty,
734        const_precise_live_drops,
735        const_ptr_cast,
736        const_raw_ptr_deref,
737        const_raw_ptr_to_usize_cast,
738        const_refs_to_cell,
739        const_refs_to_static,
740        const_trait,
741        const_trait_bound_opt_out,
742        const_trait_impl,
743        const_try,
744        const_ty_placeholder: "<const_ty>",
745        constant,
746        constructor,
747        contract_build_check_ensures,
748        contract_check_ensures,
749        contract_check_requires,
750        contract_checks,
751        contracts,
752        contracts_ensures,
753        contracts_internals,
754        contracts_requires,
755        convert,
756        convert_identity,
757        copy,
758        copy_closures,
759        copy_nonoverlapping,
760        copysignf16,
761        copysignf32,
762        copysignf64,
763        copysignf128,
764        core,
765        core_panic,
766        core_panic_2015_macro,
767        core_panic_2021_macro,
768        core_panic_macro,
769        coroutine,
770        coroutine_clone,
771        coroutine_resume,
772        coroutine_return,
773        coroutine_state,
774        coroutine_yield,
775        coroutines,
776        cosf16,
777        cosf32,
778        cosf64,
779        cosf128,
780        count,
781        coverage,
782        coverage_attribute,
783        cr,
784        crate_in_paths,
785        crate_local,
786        crate_name,
787        crate_type,
788        crate_visibility_modifier,
789        crt_dash_static: "crt-static",
790        csky_target_feature,
791        cstr_type,
792        cstring_as_c_str,
793        cstring_type,
794        ctlz,
795        ctlz_nonzero,
796        ctpop,
797        cttz,
798        cttz_nonzero,
799        custom_attribute,
800        custom_code_classes_in_docs,
801        custom_derive,
802        custom_inner_attributes,
803        custom_mir,
804        custom_test_frameworks,
805        d,
806        d32,
807        dbg_macro,
808        dead_code,
809        dealloc,
810        debug,
811        debug_assert_eq_macro,
812        debug_assert_macro,
813        debug_assert_ne_macro,
814        debug_assertions,
815        debug_struct,
816        debug_struct_fields_finish,
817        debug_tuple,
818        debug_tuple_fields_finish,
819        debugger_visualizer,
820        decl_macro,
821        declare_lint_pass,
822        decode,
823        decorated,
824        default_alloc_error_handler,
825        default_field_values,
826        default_fn,
827        default_lib_allocator,
828        default_method_body_is_const,
829        // --------------------------
830        // Lang items which are used only for experiments with auto traits with default bounds.
831        // These lang items are not actually defined in core/std. Experiment is a part of
832        // `MCP: Low level components for async drop`(https://github.com/rust-lang/compiler-team/issues/727)
833        default_trait1,
834        default_trait2,
835        default_trait3,
836        default_trait4,
837        // --------------------------
838        default_type_parameter_fallback,
839        default_type_params,
840        define_opaque,
841        delayed_bug_from_inside_query,
842        deny,
843        deprecated,
844        deprecated_safe,
845        deprecated_suggestion,
846        deref,
847        deref_method,
848        deref_mut,
849        deref_mut_method,
850        deref_patterns,
851        deref_pure,
852        deref_target,
853        derive,
854        derive_coerce_pointee,
855        derive_const,
856        derive_const_issue: "118304",
857        derive_default_enum,
858        derive_from,
859        derive_smart_pointer,
860        destruct,
861        destructuring_assignment,
862        diagnostic,
863        diagnostic_namespace,
864        dialect,
865        direct,
866        discriminant_kind,
867        discriminant_type,
868        discriminant_value,
869        disjoint_bitor,
870        dispatch_from_dyn,
871        div,
872        div_assign,
873        diverging_block_default,
874        do_not_recommend,
875        doc,
876        doc_alias,
877        doc_auto_cfg,
878        doc_cfg,
879        doc_cfg_hide,
880        doc_keyword,
881        doc_masked,
882        doc_notable_trait,
883        doc_primitive,
884        doc_spotlight,
885        doctest,
886        document_private_items,
887        dotdot: "..",
888        dotdot_in_tuple_patterns,
889        dotdoteq_in_patterns,
890        dreg,
891        dreg_low8,
892        dreg_low16,
893        drop,
894        drop_in_place,
895        drop_types_in_const,
896        dropck_eyepatch,
897        dropck_parametricity,
898        dummy: "<!dummy!>", // use this instead of `sym::empty` for symbols that won't be used
899        dummy_cgu_name,
900        dylib,
901        dyn_compatible_for_dispatch,
902        dyn_metadata,
903        dyn_star,
904        dyn_trait,
905        dynamic_no_pic: "dynamic-no-pic",
906        e,
907        edition_panic,
908        effective_target_features,
909        effects,
910        eh_catch_typeinfo,
911        eh_personality,
912        emit,
913        emit_enum,
914        emit_enum_variant,
915        emit_enum_variant_arg,
916        emit_struct,
917        emit_struct_field,
918        // Notes about `sym::empty`:
919        // - It should only be used when it genuinely means "empty symbol". Use
920        //   `Option<Symbol>` when "no symbol" is a possibility.
921        // - For dummy symbols that are never used and absolutely must be
922        //   present, it's better to use `sym::dummy` than `sym::empty`, because
923        //   it's clearer that it's intended as a dummy value, and more likely
924        //   to be detected if it accidentally does get used.
925        empty: "",
926        emscripten_wasm_eh,
927        enable,
928        encode,
929        end,
930        entry_nops,
931        enumerate_method,
932        env,
933        env_CFG_RELEASE: env!("CFG_RELEASE"),
934        eprint_macro,
935        eprintln_macro,
936        eq,
937        ergonomic_clones,
938        ermsb_target_feature,
939        exact_div,
940        except,
941        exchange_malloc,
942        exclusive_range_pattern,
943        exhaustive_integer_patterns,
944        exhaustive_patterns,
945        existential_type,
946        exp2f16,
947        exp2f32,
948        exp2f64,
949        exp2f128,
950        expect,
951        expected,
952        expf16,
953        expf32,
954        expf64,
955        expf128,
956        explicit_extern_abis,
957        explicit_generic_args_with_impl_trait,
958        explicit_tail_calls,
959        export_name,
960        export_stable,
961        expr,
962        expr_2021,
963        expr_fragment_specifier_2024,
964        extended_key_value_attributes,
965        extended_varargs_abi_support,
966        extern_absolute_paths,
967        extern_crate_item_prelude,
968        extern_crate_self,
969        extern_in_paths,
970        extern_prelude,
971        extern_system_varargs,
972        extern_types,
973        extern_weak,
974        external,
975        external_doc,
976        f,
977        f16,
978        f16_epsilon,
979        f16_nan,
980        f16c_target_feature,
981        f32,
982        f32_epsilon,
983        f32_legacy_const_digits,
984        f32_legacy_const_epsilon,
985        f32_legacy_const_infinity,
986        f32_legacy_const_mantissa_dig,
987        f32_legacy_const_max,
988        f32_legacy_const_max_10_exp,
989        f32_legacy_const_max_exp,
990        f32_legacy_const_min,
991        f32_legacy_const_min_10_exp,
992        f32_legacy_const_min_exp,
993        f32_legacy_const_min_positive,
994        f32_legacy_const_nan,
995        f32_legacy_const_neg_infinity,
996        f32_legacy_const_radix,
997        f32_nan,
998        f64,
999        f64_epsilon,
1000        f64_legacy_const_digits,
1001        f64_legacy_const_epsilon,
1002        f64_legacy_const_infinity,
1003        f64_legacy_const_mantissa_dig,
1004        f64_legacy_const_max,
1005        f64_legacy_const_max_10_exp,
1006        f64_legacy_const_max_exp,
1007        f64_legacy_const_min,
1008        f64_legacy_const_min_10_exp,
1009        f64_legacy_const_min_exp,
1010        f64_legacy_const_min_positive,
1011        f64_legacy_const_nan,
1012        f64_legacy_const_neg_infinity,
1013        f64_legacy_const_radix,
1014        f64_nan,
1015        f128,
1016        f128_epsilon,
1017        f128_nan,
1018        fabsf16,
1019        fabsf32,
1020        fabsf64,
1021        fabsf128,
1022        fadd_algebraic,
1023        fadd_fast,
1024        fake_variadic,
1025        fallback,
1026        fdiv_algebraic,
1027        fdiv_fast,
1028        feature,
1029        fence,
1030        ferris: "🦀",
1031        fetch_update,
1032        ffi,
1033        ffi_const,
1034        ffi_pure,
1035        ffi_returns_twice,
1036        field,
1037        field_init_shorthand,
1038        file,
1039        file_options,
1040        flags,
1041        float,
1042        float_to_int_unchecked,
1043        floorf16,
1044        floorf32,
1045        floorf64,
1046        floorf128,
1047        fmaf16,
1048        fmaf32,
1049        fmaf64,
1050        fmaf128,
1051        fmt,
1052        fmt_debug,
1053        fmul_algebraic,
1054        fmul_fast,
1055        fmuladdf16,
1056        fmuladdf32,
1057        fmuladdf64,
1058        fmuladdf128,
1059        fn_align,
1060        fn_body,
1061        fn_delegation,
1062        fn_must_use,
1063        fn_mut,
1064        fn_once,
1065        fn_once_output,
1066        fn_ptr_addr,
1067        fn_ptr_trait,
1068        forbid,
1069        force_target_feature,
1070        forget,
1071        format,
1072        format_args,
1073        format_args_capture,
1074        format_args_macro,
1075        format_args_nl,
1076        format_argument,
1077        format_arguments,
1078        format_count,
1079        format_macro,
1080        format_placeholder,
1081        format_unsafe_arg,
1082        framework,
1083        freeze,
1084        freeze_impls,
1085        freg,
1086        frem_algebraic,
1087        frem_fast,
1088        from,
1089        from_desugaring,
1090        from_fn,
1091        from_iter,
1092        from_iter_fn,
1093        from_output,
1094        from_residual,
1095        from_size_align_unchecked,
1096        from_str_method,
1097        from_u16,
1098        from_usize,
1099        from_yeet,
1100        frontmatter,
1101        fs_create_dir,
1102        fsub_algebraic,
1103        fsub_fast,
1104        full,
1105        fundamental,
1106        fused_iterator,
1107        future,
1108        future_drop_poll,
1109        future_output,
1110        future_trait,
1111        fxsr,
1112        gdb_script_file,
1113        ge,
1114        gen_blocks,
1115        gen_future,
1116        generator_clone,
1117        generators,
1118        generic_arg_infer,
1119        generic_assert,
1120        generic_associated_types,
1121        generic_associated_types_extended,
1122        generic_const_exprs,
1123        generic_const_items,
1124        generic_const_parameter_types,
1125        generic_param_attrs,
1126        generic_pattern_types,
1127        get_context,
1128        global_alloc_ty,
1129        global_allocator,
1130        global_asm,
1131        global_registration,
1132        globs,
1133        gt,
1134        guard_patterns,
1135        half_open_range_patterns,
1136        half_open_range_patterns_in_slices,
1137        hash,
1138        hashmap_contains_key,
1139        hashmap_drain_ty,
1140        hashmap_insert,
1141        hashmap_iter_mut_ty,
1142        hashmap_iter_ty,
1143        hashmap_keys_ty,
1144        hashmap_values_mut_ty,
1145        hashmap_values_ty,
1146        hashset_drain_ty,
1147        hashset_iter,
1148        hashset_iter_ty,
1149        hexagon_target_feature,
1150        hidden,
1151        hint,
1152        homogeneous_aggregate,
1153        host,
1154        html_favicon_url,
1155        html_logo_url,
1156        html_no_source,
1157        html_playground_url,
1158        html_root_url,
1159        hwaddress,
1160        i,
1161        i8,
1162        i8_legacy_const_max,
1163        i8_legacy_const_min,
1164        i8_legacy_fn_max_value,
1165        i8_legacy_fn_min_value,
1166        i8_legacy_mod,
1167        i16,
1168        i16_legacy_const_max,
1169        i16_legacy_const_min,
1170        i16_legacy_fn_max_value,
1171        i16_legacy_fn_min_value,
1172        i16_legacy_mod,
1173        i32,
1174        i32_legacy_const_max,
1175        i32_legacy_const_min,
1176        i32_legacy_fn_max_value,
1177        i32_legacy_fn_min_value,
1178        i32_legacy_mod,
1179        i64,
1180        i64_legacy_const_max,
1181        i64_legacy_const_min,
1182        i64_legacy_fn_max_value,
1183        i64_legacy_fn_min_value,
1184        i64_legacy_mod,
1185        i128,
1186        i128_legacy_const_max,
1187        i128_legacy_const_min,
1188        i128_legacy_fn_max_value,
1189        i128_legacy_fn_min_value,
1190        i128_legacy_mod,
1191        i128_type,
1192        ident,
1193        if_let,
1194        if_let_guard,
1195        if_let_rescope,
1196        if_while_or_patterns,
1197        ignore,
1198        impl_header_lifetime_elision,
1199        impl_lint_pass,
1200        impl_trait_in_assoc_type,
1201        impl_trait_in_bindings,
1202        impl_trait_in_fn_trait_return,
1203        impl_trait_projections,
1204        implement_via_object,
1205        implied_by,
1206        import,
1207        import_name_type,
1208        import_shadowing,
1209        import_trait_associated_functions,
1210        imported_main,
1211        in_band_lifetimes,
1212        include,
1213        include_bytes,
1214        include_bytes_macro,
1215        include_str,
1216        include_str_macro,
1217        inclusive_range_syntax,
1218        index,
1219        index_mut,
1220        infer_outlives_requirements,
1221        infer_static_outlives_requirements,
1222        inherent_associated_types,
1223        inherit,
1224        initial,
1225        inlateout,
1226        inline,
1227        inline_const,
1228        inline_const_pat,
1229        inout,
1230        instant_now,
1231        instruction_set,
1232        integer_: "integer", // underscore to avoid clashing with the function `sym::integer` below
1233        integral,
1234        internal,
1235        internal_features,
1236        into_async_iter_into_iter,
1237        into_future,
1238        into_iter,
1239        intra_doc_pointers,
1240        intrinsics,
1241        intrinsics_unaligned_volatile_load,
1242        intrinsics_unaligned_volatile_store,
1243        io_error_new,
1244        io_errorkind,
1245        io_stderr,
1246        io_stdout,
1247        irrefutable_let_patterns,
1248        is,
1249        is_val_statically_known,
1250        isa_attribute,
1251        isize,
1252        isize_legacy_const_max,
1253        isize_legacy_const_min,
1254        isize_legacy_fn_max_value,
1255        isize_legacy_fn_min_value,
1256        isize_legacy_mod,
1257        issue,
1258        issue_5723_bootstrap,
1259        issue_tracker_base_url,
1260        item,
1261        item_like_imports,
1262        iter,
1263        iter_cloned,
1264        iter_copied,
1265        iter_filter,
1266        iter_mut,
1267        iter_repeat,
1268        iterator,
1269        iterator_collect_fn,
1270        kcfi,
1271        kernel_address,
1272        keylocker_x86,
1273        keyword,
1274        kind,
1275        kreg,
1276        kreg0,
1277        label,
1278        label_break_value,
1279        lahfsahf_target_feature,
1280        lang,
1281        lang_items,
1282        large_assignments,
1283        last,
1284        lateout,
1285        lazy_normalization_consts,
1286        lazy_type_alias,
1287        le,
1288        legacy_receiver,
1289        len,
1290        let_chains,
1291        let_else,
1292        lhs,
1293        lib,
1294        libc,
1295        lifetime,
1296        lifetime_capture_rules_2024,
1297        lifetimes,
1298        likely,
1299        line,
1300        link,
1301        link_arg_attribute,
1302        link_args,
1303        link_cfg,
1304        link_dash_arg: "link-arg",
1305        link_llvm_intrinsics,
1306        link_name,
1307        link_ordinal,
1308        link_section,
1309        linkage,
1310        linker,
1311        linker_messages,
1312        linkonce,
1313        linkonce_odr,
1314        lint_reasons,
1315        literal,
1316        load,
1317        loaded_from_disk,
1318        local,
1319        local_inner_macros,
1320        log2f16,
1321        log2f32,
1322        log2f64,
1323        log2f128,
1324        log10f16,
1325        log10f32,
1326        log10f64,
1327        log10f128,
1328        log_syntax,
1329        logf16,
1330        logf32,
1331        logf64,
1332        logf128,
1333        loongarch_target_feature,
1334        loop_break_value,
1335        loop_match,
1336        lt,
1337        m68k_target_feature,
1338        macro_at_most_once_rep,
1339        macro_attr,
1340        macro_attributes_in_derive_output,
1341        macro_concat,
1342        macro_derive,
1343        macro_escape,
1344        macro_export,
1345        macro_lifetime_matcher,
1346        macro_literal_matcher,
1347        macro_metavar_expr,
1348        macro_metavar_expr_concat,
1349        macro_reexport,
1350        macro_use,
1351        macro_vis_matcher,
1352        macros_in_extern,
1353        main,
1354        managed_boxes,
1355        manually_drop,
1356        map,
1357        map_err,
1358        marker,
1359        marker_trait_attr,
1360        masked,
1361        match_beginning_vert,
1362        match_default_bindings,
1363        matches_macro,
1364        maximumf16,
1365        maximumf32,
1366        maximumf64,
1367        maximumf128,
1368        maxnumf16,
1369        maxnumf32,
1370        maxnumf64,
1371        maxnumf128,
1372        may_dangle,
1373        may_unwind,
1374        maybe_uninit,
1375        maybe_uninit_uninit,
1376        maybe_uninit_zeroed,
1377        mem_align_of,
1378        mem_discriminant,
1379        mem_drop,
1380        mem_forget,
1381        mem_replace,
1382        mem_size_of,
1383        mem_size_of_val,
1384        mem_swap,
1385        mem_uninitialized,
1386        mem_variant_count,
1387        mem_zeroed,
1388        member_constraints,
1389        memory,
1390        memtag,
1391        message,
1392        meta,
1393        meta_sized,
1394        metadata_type,
1395        min_const_fn,
1396        min_const_generics,
1397        min_const_unsafe_fn,
1398        min_exhaustive_patterns,
1399        min_generic_const_args,
1400        min_specialization,
1401        min_type_alias_impl_trait,
1402        minimumf16,
1403        minimumf32,
1404        minimumf64,
1405        minimumf128,
1406        minnumf16,
1407        minnumf32,
1408        minnumf64,
1409        minnumf128,
1410        mips_target_feature,
1411        mir_assume,
1412        mir_basic_block,
1413        mir_call,
1414        mir_cast_ptr_to_ptr,
1415        mir_cast_transmute,
1416        mir_checked,
1417        mir_copy_for_deref,
1418        mir_debuginfo,
1419        mir_deinit,
1420        mir_discriminant,
1421        mir_drop,
1422        mir_field,
1423        mir_goto,
1424        mir_len,
1425        mir_make_place,
1426        mir_move,
1427        mir_offset,
1428        mir_ptr_metadata,
1429        mir_retag,
1430        mir_return,
1431        mir_return_to,
1432        mir_set_discriminant,
1433        mir_static,
1434        mir_static_mut,
1435        mir_storage_dead,
1436        mir_storage_live,
1437        mir_tail_call,
1438        mir_unreachable,
1439        mir_unwind_cleanup,
1440        mir_unwind_continue,
1441        mir_unwind_resume,
1442        mir_unwind_terminate,
1443        mir_unwind_terminate_reason,
1444        mir_unwind_unreachable,
1445        mir_variant,
1446        miri,
1447        mmx_reg,
1448        modifiers,
1449        module,
1450        module_path,
1451        more_maybe_bounds,
1452        more_qualified_paths,
1453        more_struct_aliases,
1454        movbe_target_feature,
1455        move_ref_pattern,
1456        move_size_limit,
1457        movrs_target_feature,
1458        mul,
1459        mul_assign,
1460        mul_with_overflow,
1461        multiple_supertrait_upcastable,
1462        must_not_suspend,
1463        must_use,
1464        mut_preserve_binding_mode_2024,
1465        mut_ref,
1466        naked,
1467        naked_asm,
1468        naked_functions,
1469        naked_functions_rustic_abi,
1470        naked_functions_target_feature,
1471        name,
1472        names,
1473        native_link_modifiers,
1474        native_link_modifiers_as_needed,
1475        native_link_modifiers_bundle,
1476        native_link_modifiers_verbatim,
1477        native_link_modifiers_whole_archive,
1478        natvis_file,
1479        ne,
1480        needs_allocator,
1481        needs_drop,
1482        needs_panic_runtime,
1483        neg,
1484        negate_unsigned,
1485        negative_bounds,
1486        negative_impls,
1487        neon,
1488        nested,
1489        never,
1490        never_patterns,
1491        never_type,
1492        never_type_fallback,
1493        new,
1494        new_binary,
1495        new_const,
1496        new_debug,
1497        new_debug_noop,
1498        new_display,
1499        new_lower_exp,
1500        new_lower_hex,
1501        new_octal,
1502        new_pointer,
1503        new_range,
1504        new_unchecked,
1505        new_upper_exp,
1506        new_upper_hex,
1507        new_v1,
1508        new_v1_formatted,
1509        next,
1510        niko,
1511        nll,
1512        no,
1513        no_builtins,
1514        no_core,
1515        no_coverage,
1516        no_crate_inject,
1517        no_debug,
1518        no_default_passes,
1519        no_implicit_prelude,
1520        no_inline,
1521        no_link,
1522        no_main,
1523        no_mangle,
1524        no_sanitize,
1525        no_stack_check,
1526        no_std,
1527        nomem,
1528        non_ascii_idents,
1529        non_exhaustive,
1530        non_exhaustive_omitted_patterns_lint,
1531        non_lifetime_binders,
1532        non_modrs_mods,
1533        none,
1534        nontemporal_store,
1535        noop_method_borrow,
1536        noop_method_clone,
1537        noop_method_deref,
1538        noprefix,
1539        noreturn,
1540        nostack,
1541        not,
1542        notable_trait,
1543        note,
1544        nvptx_target_feature,
1545        object_safe_for_dispatch,
1546        of,
1547        off,
1548        offset,
1549        offset_of,
1550        offset_of_enum,
1551        offset_of_nested,
1552        offset_of_slice,
1553        ok_or_else,
1554        old_name,
1555        omit_gdb_pretty_printer_section,
1556        on,
1557        on_unimplemented,
1558        opaque,
1559        opaque_module_name_placeholder: "<opaque>",
1560        open_options_new,
1561        ops,
1562        opt_out_copy,
1563        optimize,
1564        optimize_attribute,
1565        optimized,
1566        optin_builtin_traits,
1567        option,
1568        option_env,
1569        option_expect,
1570        option_unwrap,
1571        options,
1572        or,
1573        or_patterns,
1574        ord_cmp_method,
1575        os_str_to_os_string,
1576        os_string_as_os_str,
1577        other,
1578        out,
1579        overflow_checks,
1580        overlapping_marker_traits,
1581        owned_box,
1582        packed,
1583        packed_bundled_libs,
1584        panic,
1585        panic_2015,
1586        panic_2021,
1587        panic_abort,
1588        panic_any,
1589        panic_bounds_check,
1590        panic_cannot_unwind,
1591        panic_const_add_overflow,
1592        panic_const_async_fn_resumed,
1593        panic_const_async_fn_resumed_drop,
1594        panic_const_async_fn_resumed_panic,
1595        panic_const_async_gen_fn_resumed,
1596        panic_const_async_gen_fn_resumed_drop,
1597        panic_const_async_gen_fn_resumed_panic,
1598        panic_const_coroutine_resumed,
1599        panic_const_coroutine_resumed_drop,
1600        panic_const_coroutine_resumed_panic,
1601        panic_const_div_by_zero,
1602        panic_const_div_overflow,
1603        panic_const_gen_fn_none,
1604        panic_const_gen_fn_none_drop,
1605        panic_const_gen_fn_none_panic,
1606        panic_const_mul_overflow,
1607        panic_const_neg_overflow,
1608        panic_const_rem_by_zero,
1609        panic_const_rem_overflow,
1610        panic_const_shl_overflow,
1611        panic_const_shr_overflow,
1612        panic_const_sub_overflow,
1613        panic_display,
1614        panic_fmt,
1615        panic_handler,
1616        panic_impl,
1617        panic_implementation,
1618        panic_in_cleanup,
1619        panic_info,
1620        panic_invalid_enum_construction,
1621        panic_location,
1622        panic_misaligned_pointer_dereference,
1623        panic_nounwind,
1624        panic_null_pointer_dereference,
1625        panic_runtime,
1626        panic_str_2015,
1627        panic_unwind,
1628        panicking,
1629        param_attrs,
1630        parent_label,
1631        partial_cmp,
1632        partial_ord,
1633        passes,
1634        pat,
1635        pat_param,
1636        patchable_function_entry,
1637        path,
1638        path_main_separator,
1639        path_to_pathbuf,
1640        pathbuf_as_path,
1641        pattern_complexity_limit,
1642        pattern_parentheses,
1643        pattern_type,
1644        pattern_type_range_trait,
1645        pattern_types,
1646        permissions_from_mode,
1647        phantom_data,
1648        phase,
1649        pic,
1650        pie,
1651        pin,
1652        pin_ergonomics,
1653        pin_macro,
1654        platform_intrinsics,
1655        plugin,
1656        plugin_registrar,
1657        plugins,
1658        pointee,
1659        pointee_sized,
1660        pointee_trait,
1661        pointer,
1662        poll,
1663        poll_next,
1664        position,
1665        post_cleanup: "post-cleanup",
1666        post_dash_lto: "post-lto",
1667        postfix_match,
1668        powerpc_target_feature,
1669        powf16,
1670        powf32,
1671        powf64,
1672        powf128,
1673        powif16,
1674        powif32,
1675        powif64,
1676        powif128,
1677        pre_dash_lto: "pre-lto",
1678        precise_capturing,
1679        precise_capturing_in_traits,
1680        precise_pointer_size_matching,
1681        precision,
1682        pref_align_of,
1683        prefetch_read_data,
1684        prefetch_read_instruction,
1685        prefetch_write_data,
1686        prefetch_write_instruction,
1687        prefix_nops,
1688        preg,
1689        prelude,
1690        prelude_import,
1691        preserves_flags,
1692        prfchw_target_feature,
1693        print_macro,
1694        println_macro,
1695        proc_dash_macro: "proc-macro",
1696        proc_macro,
1697        proc_macro_attribute,
1698        proc_macro_derive,
1699        proc_macro_expr,
1700        proc_macro_gen,
1701        proc_macro_hygiene,
1702        proc_macro_internals,
1703        proc_macro_mod,
1704        proc_macro_non_items,
1705        proc_macro_path_invoc,
1706        process_abort,
1707        process_exit,
1708        profiler_builtins,
1709        profiler_runtime,
1710        ptr,
1711        ptr_cast,
1712        ptr_cast_const,
1713        ptr_cast_mut,
1714        ptr_const_is_null,
1715        ptr_copy,
1716        ptr_copy_nonoverlapping,
1717        ptr_eq,
1718        ptr_from_ref,
1719        ptr_guaranteed_cmp,
1720        ptr_is_null,
1721        ptr_mask,
1722        ptr_metadata,
1723        ptr_null,
1724        ptr_null_mut,
1725        ptr_offset_from,
1726        ptr_offset_from_unsigned,
1727        ptr_read,
1728        ptr_read_unaligned,
1729        ptr_read_volatile,
1730        ptr_replace,
1731        ptr_slice_from_raw_parts,
1732        ptr_slice_from_raw_parts_mut,
1733        ptr_swap,
1734        ptr_swap_nonoverlapping,
1735        ptr_write,
1736        ptr_write_bytes,
1737        ptr_write_unaligned,
1738        ptr_write_volatile,
1739        pub_macro_rules,
1740        pub_restricted,
1741        public,
1742        pure,
1743        pushpop_unsafe,
1744        qreg,
1745        qreg_low4,
1746        qreg_low8,
1747        quad_precision_float,
1748        question_mark,
1749        quote,
1750        range_inclusive_new,
1751        range_step,
1752        raw_dash_dylib: "raw-dylib",
1753        raw_dylib,
1754        raw_dylib_elf,
1755        raw_eq,
1756        raw_identifiers,
1757        raw_ref_op,
1758        re_rebalance_coherence,
1759        read_enum,
1760        read_enum_variant,
1761        read_enum_variant_arg,
1762        read_struct,
1763        read_struct_field,
1764        read_via_copy,
1765        readonly,
1766        realloc,
1767        reason,
1768        reborrow,
1769        receiver,
1770        receiver_target,
1771        recursion_limit,
1772        reexport_test_harness_main,
1773        ref_pat_eat_one_layer_2024,
1774        ref_pat_eat_one_layer_2024_structural,
1775        ref_pat_everywhere,
1776        ref_unwind_safe_trait,
1777        reference,
1778        reflect,
1779        reg,
1780        reg16,
1781        reg32,
1782        reg64,
1783        reg_abcd,
1784        reg_addr,
1785        reg_byte,
1786        reg_data,
1787        reg_iw,
1788        reg_nonzero,
1789        reg_pair,
1790        reg_ptr,
1791        reg_upper,
1792        register_attr,
1793        register_tool,
1794        relaxed_adts,
1795        relaxed_struct_unsize,
1796        relocation_model,
1797        rem,
1798        rem_assign,
1799        repr,
1800        repr128,
1801        repr_align,
1802        repr_align_enum,
1803        repr_packed,
1804        repr_simd,
1805        repr_transparent,
1806        require,
1807        reserve_x18: "reserve-x18",
1808        residual,
1809        result,
1810        result_ffi_guarantees,
1811        result_ok_method,
1812        resume,
1813        return_position_impl_trait_in_trait,
1814        return_type_notation,
1815        riscv_target_feature,
1816        rlib,
1817        ropi,
1818        ropi_rwpi: "ropi-rwpi",
1819        rotate_left,
1820        rotate_right,
1821        round_ties_even_f16,
1822        round_ties_even_f32,
1823        round_ties_even_f64,
1824        round_ties_even_f128,
1825        roundf16,
1826        roundf32,
1827        roundf64,
1828        roundf128,
1829        rt,
1830        rtm_target_feature,
1831        runtime,
1832        rust,
1833        rust_2015,
1834        rust_2018,
1835        rust_2018_preview,
1836        rust_2021,
1837        rust_2024,
1838        rust_analyzer,
1839        rust_begin_unwind,
1840        rust_cold_cc,
1841        rust_eh_catch_typeinfo,
1842        rust_eh_personality,
1843        rust_future,
1844        rust_logo,
1845        rust_out,
1846        rustc,
1847        rustc_abi,
1848        // FIXME(#82232, #143834): temporary name to mitigate `#[align]` nameres ambiguity
1849        rustc_align,
1850        rustc_align_static,
1851        rustc_allocator,
1852        rustc_allocator_zeroed,
1853        rustc_allow_const_fn_unstable,
1854        rustc_allow_incoherent_impl,
1855        rustc_allowed_through_unstable_modules,
1856        rustc_as_ptr,
1857        rustc_attrs,
1858        rustc_autodiff,
1859        rustc_builtin_macro,
1860        rustc_capture_analysis,
1861        rustc_clean,
1862        rustc_coherence_is_core,
1863        rustc_coinductive,
1864        rustc_confusables,
1865        rustc_const_stable,
1866        rustc_const_stable_indirect,
1867        rustc_const_unstable,
1868        rustc_conversion_suggestion,
1869        rustc_deallocator,
1870        rustc_def_path,
1871        rustc_default_body_unstable,
1872        rustc_delayed_bug_from_inside_query,
1873        rustc_deny_explicit_impl,
1874        rustc_deprecated_safe_2024,
1875        rustc_diagnostic_item,
1876        rustc_diagnostic_macros,
1877        rustc_dirty,
1878        rustc_do_not_const_check,
1879        rustc_do_not_implement_via_object,
1880        rustc_doc_primitive,
1881        rustc_driver,
1882        rustc_dummy,
1883        rustc_dump_def_parents,
1884        rustc_dump_item_bounds,
1885        rustc_dump_predicates,
1886        rustc_dump_user_args,
1887        rustc_dump_vtable,
1888        rustc_effective_visibility,
1889        rustc_evaluate_where_clauses,
1890        rustc_expected_cgu_reuse,
1891        rustc_force_inline,
1892        rustc_has_incoherent_inherent_impls,
1893        rustc_hidden_type_of_opaques,
1894        rustc_if_this_changed,
1895        rustc_inherit_overflow_checks,
1896        rustc_insignificant_dtor,
1897        rustc_intrinsic,
1898        rustc_intrinsic_const_stable_indirect,
1899        rustc_layout,
1900        rustc_layout_scalar_valid_range_end,
1901        rustc_layout_scalar_valid_range_start,
1902        rustc_legacy_const_generics,
1903        rustc_lint_diagnostics,
1904        rustc_lint_opt_deny_field_access,
1905        rustc_lint_opt_ty,
1906        rustc_lint_query_instability,
1907        rustc_lint_untracked_query_information,
1908        rustc_macro_transparency,
1909        rustc_main,
1910        rustc_mir,
1911        rustc_must_implement_one_of,
1912        rustc_never_returns_null_ptr,
1913        rustc_never_type_options,
1914        rustc_no_implicit_autorefs,
1915        rustc_no_implicit_bounds,
1916        rustc_no_mir_inline,
1917        rustc_nonnull_optimization_guaranteed,
1918        rustc_nounwind,
1919        rustc_object_lifetime_default,
1920        rustc_on_unimplemented,
1921        rustc_outlives,
1922        rustc_paren_sugar,
1923        rustc_partition_codegened,
1924        rustc_partition_reused,
1925        rustc_pass_by_value,
1926        rustc_peek,
1927        rustc_peek_liveness,
1928        rustc_peek_maybe_init,
1929        rustc_peek_maybe_uninit,
1930        rustc_preserve_ub_checks,
1931        rustc_private,
1932        rustc_proc_macro_decls,
1933        rustc_promotable,
1934        rustc_pub_transparent,
1935        rustc_reallocator,
1936        rustc_regions,
1937        rustc_reservation_impl,
1938        rustc_serialize,
1939        rustc_skip_during_method_dispatch,
1940        rustc_specialization_trait,
1941        rustc_std_internal_symbol,
1942        rustc_strict_coherence,
1943        rustc_symbol_name,
1944        rustc_test_marker,
1945        rustc_then_this_would_need,
1946        rustc_trivial_field_reads,
1947        rustc_unsafe_specialization_marker,
1948        rustc_variance,
1949        rustc_variance_of_opaques,
1950        rustdoc,
1951        rustdoc_internals,
1952        rustdoc_missing_doc_code_examples,
1953        rustfmt,
1954        rvalue_static_promotion,
1955        rwpi,
1956        s,
1957        s390x_target_feature,
1958        safety,
1959        sanitize,
1960        sanitizer_cfi_generalize_pointers,
1961        sanitizer_cfi_normalize_integers,
1962        sanitizer_runtime,
1963        saturating_add,
1964        saturating_div,
1965        saturating_sub,
1966        sdylib,
1967        search_unbox,
1968        select_unpredictable,
1969        self_in_typedefs,
1970        self_struct_ctor,
1971        semiopaque,
1972        semitransparent,
1973        sha2,
1974        sha3,
1975        sha512_sm_x86,
1976        shadow_call_stack,
1977        shallow,
1978        shl,
1979        shl_assign,
1980        shorter_tail_lifetimes,
1981        should_panic,
1982        shr,
1983        shr_assign,
1984        sig_dfl,
1985        sig_ign,
1986        simd,
1987        simd_add,
1988        simd_and,
1989        simd_arith_offset,
1990        simd_as,
1991        simd_bitmask,
1992        simd_bitreverse,
1993        simd_bswap,
1994        simd_cast,
1995        simd_cast_ptr,
1996        simd_ceil,
1997        simd_ctlz,
1998        simd_ctpop,
1999        simd_cttz,
2000        simd_div,
2001        simd_eq,
2002        simd_expose_provenance,
2003        simd_extract,
2004        simd_extract_dyn,
2005        simd_fabs,
2006        simd_fcos,
2007        simd_fexp,
2008        simd_fexp2,
2009        simd_ffi,
2010        simd_flog,
2011        simd_flog2,
2012        simd_flog10,
2013        simd_floor,
2014        simd_fma,
2015        simd_fmax,
2016        simd_fmin,
2017        simd_fsin,
2018        simd_fsqrt,
2019        simd_funnel_shl,
2020        simd_funnel_shr,
2021        simd_gather,
2022        simd_ge,
2023        simd_gt,
2024        simd_insert,
2025        simd_insert_dyn,
2026        simd_le,
2027        simd_lt,
2028        simd_masked_load,
2029        simd_masked_store,
2030        simd_mul,
2031        simd_ne,
2032        simd_neg,
2033        simd_or,
2034        simd_reduce_add_ordered,
2035        simd_reduce_add_unordered,
2036        simd_reduce_all,
2037        simd_reduce_and,
2038        simd_reduce_any,
2039        simd_reduce_max,
2040        simd_reduce_min,
2041        simd_reduce_mul_ordered,
2042        simd_reduce_mul_unordered,
2043        simd_reduce_or,
2044        simd_reduce_xor,
2045        simd_relaxed_fma,
2046        simd_rem,
2047        simd_round,
2048        simd_round_ties_even,
2049        simd_saturating_add,
2050        simd_saturating_sub,
2051        simd_scatter,
2052        simd_select,
2053        simd_select_bitmask,
2054        simd_shl,
2055        simd_shr,
2056        simd_shuffle,
2057        simd_shuffle_const_generic,
2058        simd_sub,
2059        simd_trunc,
2060        simd_with_exposed_provenance,
2061        simd_xor,
2062        since,
2063        sinf16,
2064        sinf32,
2065        sinf64,
2066        sinf128,
2067        size,
2068        size_of,
2069        size_of_val,
2070        sized,
2071        sized_hierarchy,
2072        skip,
2073        slice,
2074        slice_from_raw_parts,
2075        slice_from_raw_parts_mut,
2076        slice_from_ref,
2077        slice_get_unchecked,
2078        slice_into_vec,
2079        slice_iter,
2080        slice_len_fn,
2081        slice_patterns,
2082        slicing_syntax,
2083        soft,
2084        sparc_target_feature,
2085        specialization,
2086        speed,
2087        spotlight,
2088        sqrtf16,
2089        sqrtf32,
2090        sqrtf64,
2091        sqrtf128,
2092        sreg,
2093        sreg_low16,
2094        sse,
2095        sse2,
2096        sse4a_target_feature,
2097        stable,
2098        staged_api,
2099        start,
2100        state,
2101        static_align,
2102        static_in_const,
2103        static_nobundle,
2104        static_recursion,
2105        staticlib,
2106        std,
2107        std_lib_injection,
2108        std_panic,
2109        std_panic_2015_macro,
2110        std_panic_macro,
2111        stmt,
2112        stmt_expr_attributes,
2113        stop_after_dataflow,
2114        store,
2115        str,
2116        str_chars,
2117        str_ends_with,
2118        str_from_utf8,
2119        str_from_utf8_mut,
2120        str_from_utf8_unchecked,
2121        str_from_utf8_unchecked_mut,
2122        str_inherent_from_utf8,
2123        str_inherent_from_utf8_mut,
2124        str_inherent_from_utf8_unchecked,
2125        str_inherent_from_utf8_unchecked_mut,
2126        str_len,
2127        str_split_whitespace,
2128        str_starts_with,
2129        str_trim,
2130        str_trim_end,
2131        str_trim_start,
2132        strict_provenance_lints,
2133        string_as_mut_str,
2134        string_as_str,
2135        string_deref_patterns,
2136        string_from_utf8,
2137        string_insert_str,
2138        string_new,
2139        string_push_str,
2140        stringify,
2141        struct_field_attributes,
2142        struct_inherit,
2143        struct_variant,
2144        structural_match,
2145        structural_peq,
2146        sub,
2147        sub_assign,
2148        sub_with_overflow,
2149        suggestion,
2150        super_let,
2151        supertrait_item_shadowing,
2152        sym,
2153        sync,
2154        synthetic,
2155        sys_mutex_lock,
2156        sys_mutex_try_lock,
2157        sys_mutex_unlock,
2158        t32,
2159        target,
2160        target_abi,
2161        target_arch,
2162        target_endian,
2163        target_env,
2164        target_family,
2165        target_feature,
2166        target_feature_11,
2167        target_feature_inline_always,
2168        target_has_atomic,
2169        target_has_atomic_equal_alignment,
2170        target_has_atomic_load_store,
2171        target_has_reliable_f16,
2172        target_has_reliable_f16_math,
2173        target_has_reliable_f128,
2174        target_has_reliable_f128_math,
2175        target_os,
2176        target_pointer_width,
2177        target_thread_local,
2178        target_vendor,
2179        tbm_target_feature,
2180        termination,
2181        termination_trait,
2182        termination_trait_test,
2183        test,
2184        test_2018_feature,
2185        test_accepted_feature,
2186        test_case,
2187        test_removed_feature,
2188        test_runner,
2189        test_unstable_lint,
2190        thread,
2191        thread_local,
2192        thread_local_macro,
2193        three_way_compare,
2194        thumb2,
2195        thumb_mode: "thumb-mode",
2196        tmm_reg,
2197        to_owned_method,
2198        to_string,
2199        to_string_method,
2200        to_vec,
2201        todo_macro,
2202        tool_attributes,
2203        tool_lints,
2204        trace_macros,
2205        track_caller,
2206        trait_alias,
2207        trait_upcasting,
2208        transmute,
2209        transmute_generic_consts,
2210        transmute_opts,
2211        transmute_trait,
2212        transmute_unchecked,
2213        transparent,
2214        transparent_enums,
2215        transparent_unions,
2216        trivial_bounds,
2217        truncf16,
2218        truncf32,
2219        truncf64,
2220        truncf128,
2221        try_blocks,
2222        try_capture,
2223        try_from,
2224        try_from_fn,
2225        try_into,
2226        try_trait_v2,
2227        tt,
2228        tuple,
2229        tuple_indexing,
2230        tuple_trait,
2231        two_phase,
2232        ty,
2233        type_alias_enum_variants,
2234        type_alias_impl_trait,
2235        type_ascribe,
2236        type_ascription,
2237        type_changing_struct_update,
2238        type_const,
2239        type_id,
2240        type_id_eq,
2241        type_ir,
2242        type_ir_infer_ctxt_like,
2243        type_ir_inherent,
2244        type_ir_interner,
2245        type_length_limit,
2246        type_macros,
2247        type_name,
2248        type_privacy_lints,
2249        typed_swap_nonoverlapping,
2250        u8,
2251        u8_legacy_const_max,
2252        u8_legacy_const_min,
2253        u8_legacy_fn_max_value,
2254        u8_legacy_fn_min_value,
2255        u8_legacy_mod,
2256        u16,
2257        u16_legacy_const_max,
2258        u16_legacy_const_min,
2259        u16_legacy_fn_max_value,
2260        u16_legacy_fn_min_value,
2261        u16_legacy_mod,
2262        u32,
2263        u32_legacy_const_max,
2264        u32_legacy_const_min,
2265        u32_legacy_fn_max_value,
2266        u32_legacy_fn_min_value,
2267        u32_legacy_mod,
2268        u64,
2269        u64_legacy_const_max,
2270        u64_legacy_const_min,
2271        u64_legacy_fn_max_value,
2272        u64_legacy_fn_min_value,
2273        u64_legacy_mod,
2274        u128,
2275        u128_legacy_const_max,
2276        u128_legacy_const_min,
2277        u128_legacy_fn_max_value,
2278        u128_legacy_fn_min_value,
2279        u128_legacy_mod,
2280        ub_checks,
2281        unaligned_volatile_load,
2282        unaligned_volatile_store,
2283        unboxed_closures,
2284        unchecked_add,
2285        unchecked_div,
2286        unchecked_funnel_shl,
2287        unchecked_funnel_shr,
2288        unchecked_mul,
2289        unchecked_rem,
2290        unchecked_shl,
2291        unchecked_shr,
2292        unchecked_sub,
2293        undecorated,
2294        underscore_const_names,
2295        underscore_imports,
2296        underscore_lifetimes,
2297        uniform_paths,
2298        unimplemented_macro,
2299        unit,
2300        universal_impl_trait,
2301        unix,
2302        unlikely,
2303        unmarked_api,
2304        unnamed_fields,
2305        unpin,
2306        unqualified_local_imports,
2307        unreachable,
2308        unreachable_2015,
2309        unreachable_2015_macro,
2310        unreachable_2021,
2311        unreachable_code,
2312        unreachable_display,
2313        unreachable_macro,
2314        unrestricted_attribute_tokens,
2315        unsafe_attributes,
2316        unsafe_binders,
2317        unsafe_block_in_unsafe_fn,
2318        unsafe_cell,
2319        unsafe_cell_raw_get,
2320        unsafe_extern_blocks,
2321        unsafe_fields,
2322        unsafe_no_drop_flag,
2323        unsafe_pinned,
2324        unsafe_unpin,
2325        unsize,
2326        unsized_const_param_ty,
2327        unsized_const_params,
2328        unsized_fn_params,
2329        unsized_locals,
2330        unsized_tuple_coercion,
2331        unstable,
2332        unstable_feature_bound,
2333        unstable_location_reason_default: "this crate is being loaded from the sysroot, an \
2334                          unstable location; did you mean to load this crate \
2335                          from crates.io via `Cargo.toml` instead?",
2336        untagged_unions,
2337        unused_imports,
2338        unwind,
2339        unwind_attributes,
2340        unwind_safe_trait,
2341        unwrap,
2342        unwrap_binder,
2343        unwrap_or,
2344        use_cloned,
2345        use_extern_macros,
2346        use_nested_groups,
2347        used,
2348        used_with_arg,
2349        using,
2350        usize,
2351        usize_legacy_const_max,
2352        usize_legacy_const_min,
2353        usize_legacy_fn_max_value,
2354        usize_legacy_fn_min_value,
2355        usize_legacy_mod,
2356        v1,
2357        v8plus,
2358        va_arg,
2359        va_copy,
2360        va_end,
2361        va_list,
2362        va_start,
2363        val,
2364        validity,
2365        value,
2366        values,
2367        var,
2368        variant_count,
2369        vec,
2370        vec_as_mut_slice,
2371        vec_as_slice,
2372        vec_from_elem,
2373        vec_is_empty,
2374        vec_macro,
2375        vec_new,
2376        vec_pop,
2377        vec_reserve,
2378        vec_with_capacity,
2379        vecdeque_iter,
2380        vecdeque_reserve,
2381        vector,
2382        verbatim,
2383        version,
2384        vfp2,
2385        vis,
2386        visible_private_types,
2387        volatile,
2388        volatile_copy_memory,
2389        volatile_copy_nonoverlapping_memory,
2390        volatile_load,
2391        volatile_set_memory,
2392        volatile_store,
2393        vreg,
2394        vreg_low16,
2395        vsx,
2396        vtable_align,
2397        vtable_size,
2398        warn,
2399        wasip2,
2400        wasm_abi,
2401        wasm_import_module,
2402        wasm_target_feature,
2403        weak,
2404        weak_odr,
2405        where_clause_attrs,
2406        while_let,
2407        whole_dash_archive: "whole-archive",
2408        width,
2409        windows,
2410        windows_subsystem,
2411        with_negative_coherence,
2412        wrap_binder,
2413        wrapping_add,
2414        wrapping_div,
2415        wrapping_mul,
2416        wrapping_rem,
2417        wrapping_rem_euclid,
2418        wrapping_sub,
2419        wreg,
2420        write_bytes,
2421        write_fmt,
2422        write_macro,
2423        write_str,
2424        write_via_move,
2425        writeln_macro,
2426        x86_amx_intrinsics,
2427        x87_reg,
2428        x87_target_feature,
2429        xer,
2430        xmm_reg,
2431        xop_target_feature,
2432        yeet_desugar_details,
2433        yeet_expr,
2434        yes,
2435        yield_expr,
2436        ymm_reg,
2437        yreg,
2438        zca,
2439        zfh,
2440        zfhmin,
2441        zmm_reg,
2442        ztso,
2443        // tidy-alphabetical-end
2444    }
2445}
2446
2447/// Symbols for crates that are part of the stable standard library: `std`, `core`, `alloc`, and
2448/// `proc_macro`.
2449pub const STDLIB_STABLE_CRATES: &[Symbol] = &[sym::std, sym::core, sym::alloc, sym::proc_macro];
2450
2451#[derive(Copy, Clone, Eq, HashStable_Generic, Encodable, Decodable)]
2452pub struct Ident {
2453    // `name` should never be the empty symbol. If you are considering that,
2454    // you are probably conflating "empty identifier with "no identifier" and
2455    // you should use `Option<Ident>` instead.
2456    pub name: Symbol,
2457    pub span: Span,
2458}
2459
2460impl Ident {
2461    #[inline]
2462    /// Constructs a new identifier from a symbol and a span.
2463    pub fn new(name: Symbol, span: Span) -> Ident {
2464        debug_assert_ne!(name, sym::empty);
2465        Ident { name, span }
2466    }
2467
2468    /// Constructs a new identifier with a dummy span.
2469    #[inline]
2470    pub fn with_dummy_span(name: Symbol) -> Ident {
2471        Ident::new(name, DUMMY_SP)
2472    }
2473
2474    // For dummy identifiers that are never used and absolutely must be
2475    // present. Note that this does *not* use the empty symbol; `sym::dummy`
2476    // makes it clear that it's intended as a dummy value, and is more likely
2477    // to be detected if it accidentally does get used.
2478    #[inline]
2479    pub fn dummy() -> Ident {
2480        Ident::with_dummy_span(sym::dummy)
2481    }
2482
2483    /// Maps a string to an identifier with a dummy span.
2484    pub fn from_str(string: &str) -> Ident {
2485        Ident::with_dummy_span(Symbol::intern(string))
2486    }
2487
2488    /// Maps a string and a span to an identifier.
2489    pub fn from_str_and_span(string: &str, span: Span) -> Ident {
2490        Ident::new(Symbol::intern(string), span)
2491    }
2492
2493    /// Replaces `lo` and `hi` with those from `span`, but keep hygiene context.
2494    pub fn with_span_pos(self, span: Span) -> Ident {
2495        Ident::new(self.name, span.with_ctxt(self.span.ctxt()))
2496    }
2497
2498    pub fn without_first_quote(self) -> Ident {
2499        Ident::new(Symbol::intern(self.as_str().trim_start_matches('\'')), self.span)
2500    }
2501
2502    /// "Normalize" ident for use in comparisons using "item hygiene".
2503    /// Identifiers with same string value become same if they came from the same macro 2.0 macro
2504    /// (e.g., `macro` item, but not `macro_rules` item) and stay different if they came from
2505    /// different macro 2.0 macros.
2506    /// Technically, this operation strips all non-opaque marks from ident's syntactic context.
2507    pub fn normalize_to_macros_2_0(self) -> Ident {
2508        Ident::new(self.name, self.span.normalize_to_macros_2_0())
2509    }
2510
2511    /// "Normalize" ident for use in comparisons using "local variable hygiene".
2512    /// Identifiers with same string value become same if they came from the same non-transparent
2513    /// macro (e.g., `macro` or `macro_rules!` items) and stay different if they came from different
2514    /// non-transparent macros.
2515    /// Technically, this operation strips all transparent marks from ident's syntactic context.
2516    #[inline]
2517    pub fn normalize_to_macro_rules(self) -> Ident {
2518        Ident::new(self.name, self.span.normalize_to_macro_rules())
2519    }
2520
2521    /// Access the underlying string. This is a slowish operation because it
2522    /// requires locking the symbol interner.
2523    ///
2524    /// Note that the lifetime of the return value is a lie. See
2525    /// `Symbol::as_str()` for details.
2526    pub fn as_str(&self) -> &str {
2527        self.name.as_str()
2528    }
2529}
2530
2531impl PartialEq for Ident {
2532    #[inline]
2533    fn eq(&self, rhs: &Self) -> bool {
2534        self.name == rhs.name && self.span.eq_ctxt(rhs.span)
2535    }
2536}
2537
2538impl Hash for Ident {
2539    fn hash<H: Hasher>(&self, state: &mut H) {
2540        self.name.hash(state);
2541        self.span.ctxt().hash(state);
2542    }
2543}
2544
2545impl fmt::Debug for Ident {
2546    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2547        fmt::Display::fmt(self, f)?;
2548        fmt::Debug::fmt(&self.span.ctxt(), f)
2549    }
2550}
2551
2552/// This implementation is supposed to be used in error messages, so it's expected to be identical
2553/// to printing the original identifier token written in source code (`token_to_string`),
2554/// except that AST identifiers don't keep the rawness flag, so we have to guess it.
2555impl fmt::Display for Ident {
2556    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2557        fmt::Display::fmt(&IdentPrinter::new(self.name, self.guess_print_mode(), None), f)
2558    }
2559}
2560
2561pub enum IdentPrintMode {
2562    Normal,
2563    RawIdent,
2564    RawLifetime,
2565}
2566
2567/// The most general type to print identifiers.
2568///
2569/// AST pretty-printer is used as a fallback for turning AST structures into token streams for
2570/// proc macros. Additionally, proc macros may stringify their input and expect it survive the
2571/// stringification (especially true for proc macro derives written between Rust 1.15 and 1.30).
2572/// So we need to somehow pretty-print `$crate` in a way preserving at least some of its
2573/// hygiene data, most importantly name of the crate it refers to.
2574/// As a result we print `$crate` as `crate` if it refers to the local crate
2575/// and as `::other_crate_name` if it refers to some other crate.
2576/// Note, that this is only done if the ident token is printed from inside of AST pretty-printing,
2577/// but not otherwise. Pretty-printing is the only way for proc macros to discover token contents,
2578/// so we should not perform this lossy conversion if the top level call to the pretty-printer was
2579/// done for a token stream or a single token.
2580pub struct IdentPrinter {
2581    symbol: Symbol,
2582    mode: IdentPrintMode,
2583    /// Span used for retrieving the crate name to which `$crate` refers to,
2584    /// if this field is `None` then the `$crate` conversion doesn't happen.
2585    convert_dollar_crate: Option<Span>,
2586}
2587
2588impl IdentPrinter {
2589    /// The most general `IdentPrinter` constructor. Do not use this.
2590    pub fn new(
2591        symbol: Symbol,
2592        mode: IdentPrintMode,
2593        convert_dollar_crate: Option<Span>,
2594    ) -> IdentPrinter {
2595        IdentPrinter { symbol, mode, convert_dollar_crate }
2596    }
2597
2598    /// This implementation is supposed to be used when printing identifiers
2599    /// as a part of pretty-printing for larger AST pieces.
2600    /// Do not use this either.
2601    pub fn for_ast_ident(ident: Ident, mode: IdentPrintMode) -> IdentPrinter {
2602        IdentPrinter::new(ident.name, mode, Some(ident.span))
2603    }
2604}
2605
2606impl fmt::Display for IdentPrinter {
2607    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2608        let s = match self.mode {
2609            IdentPrintMode::Normal
2610                if self.symbol == kw::DollarCrate
2611                    && let Some(span) = self.convert_dollar_crate =>
2612            {
2613                let converted = span.ctxt().dollar_crate_name();
2614                if !converted.is_path_segment_keyword() {
2615                    f.write_str("::")?;
2616                }
2617                converted
2618            }
2619            IdentPrintMode::Normal => self.symbol,
2620            IdentPrintMode::RawIdent => {
2621                f.write_str("r#")?;
2622                self.symbol
2623            }
2624            IdentPrintMode::RawLifetime => {
2625                f.write_str("'r#")?;
2626                let s = self
2627                    .symbol
2628                    .as_str()
2629                    .strip_prefix("'")
2630                    .expect("only lifetime idents should be passed with RawLifetime mode");
2631                Symbol::intern(s)
2632            }
2633        };
2634        s.fmt(f)
2635    }
2636}
2637
2638/// An newtype around `Ident` that calls [Ident::normalize_to_macro_rules] on
2639/// construction for "local variable hygiene" comparisons.
2640///
2641/// Use this type when you need to compare identifiers according to macro_rules hygiene.
2642/// This ensures compile-time safety and avoids manual normalization calls.
2643#[derive(Copy, Clone, Eq, PartialEq, Hash)]
2644pub struct MacroRulesNormalizedIdent(Ident);
2645
2646impl MacroRulesNormalizedIdent {
2647    #[inline]
2648    pub fn new(ident: Ident) -> Self {
2649        MacroRulesNormalizedIdent(ident.normalize_to_macro_rules())
2650    }
2651}
2652
2653impl fmt::Debug for MacroRulesNormalizedIdent {
2654    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2655        fmt::Debug::fmt(&self.0, f)
2656    }
2657}
2658
2659impl fmt::Display for MacroRulesNormalizedIdent {
2660    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2661        fmt::Display::fmt(&self.0, f)
2662    }
2663}
2664
2665/// An newtype around `Ident` that calls [Ident::normalize_to_macros_2_0] on
2666/// construction for "item hygiene" comparisons.
2667///
2668/// Identifiers with same string value become same if they came from the same macro 2.0 macro
2669/// (e.g., `macro` item, but not `macro_rules` item) and stay different if they came from
2670/// different macro 2.0 macros.
2671#[derive(Copy, Clone, Eq, PartialEq, Hash)]
2672pub struct Macros20NormalizedIdent(pub Ident);
2673
2674impl Macros20NormalizedIdent {
2675    #[inline]
2676    pub fn new(ident: Ident) -> Self {
2677        Macros20NormalizedIdent(ident.normalize_to_macros_2_0())
2678    }
2679
2680    // dummy_span does not need to be normalized, so we can use `Ident` directly
2681    pub fn with_dummy_span(name: Symbol) -> Self {
2682        Macros20NormalizedIdent(Ident::with_dummy_span(name))
2683    }
2684}
2685
2686impl fmt::Debug for Macros20NormalizedIdent {
2687    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2688        fmt::Debug::fmt(&self.0, f)
2689    }
2690}
2691
2692impl fmt::Display for Macros20NormalizedIdent {
2693    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2694        fmt::Display::fmt(&self.0, f)
2695    }
2696}
2697
2698/// By impl Deref, we can access the wrapped Ident as if it were a normal Ident
2699/// such as `norm_ident.name` instead of `norm_ident.0.name`.
2700impl Deref for Macros20NormalizedIdent {
2701    type Target = Ident;
2702    fn deref(&self) -> &Self::Target {
2703        &self.0
2704    }
2705}
2706
2707/// An interned UTF-8 string.
2708///
2709/// Internally, a `Symbol` is implemented as an index, and all operations
2710/// (including hashing, equality, and ordering) operate on that index. The use
2711/// of `rustc_index::newtype_index!` means that `Option<Symbol>` only takes up 4 bytes,
2712/// because `rustc_index::newtype_index!` reserves the last 256 values for tagging purposes.
2713///
2714/// Note that `Symbol` cannot directly be a `rustc_index::newtype_index!` because it
2715/// implements `fmt::Debug`, `Encodable`, and `Decodable` in special ways.
2716#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
2717pub struct Symbol(SymbolIndex);
2718
2719// Used within both `Symbol` and `ByteSymbol`.
2720rustc_index::newtype_index! {
2721    #[orderable]
2722    struct SymbolIndex {}
2723}
2724
2725impl Symbol {
2726    /// Avoid this except for things like deserialization of previously
2727    /// serialized symbols, and testing. Use `intern` instead.
2728    pub const fn new(n: u32) -> Self {
2729        Symbol(SymbolIndex::from_u32(n))
2730    }
2731
2732    /// Maps a string to its interned representation.
2733    #[rustc_diagnostic_item = "SymbolIntern"]
2734    pub fn intern(str: &str) -> Self {
2735        with_session_globals(|session_globals| session_globals.symbol_interner.intern_str(str))
2736    }
2737
2738    /// Access the underlying string. This is a slowish operation because it
2739    /// requires locking the symbol interner.
2740    ///
2741    /// Note that the lifetime of the return value is a lie. It's not the same
2742    /// as `&self`, but actually tied to the lifetime of the underlying
2743    /// interner. Interners are long-lived, and there are very few of them, and
2744    /// this function is typically used for short-lived things, so in practice
2745    /// it works out ok.
2746    pub fn as_str(&self) -> &str {
2747        with_session_globals(|session_globals| unsafe {
2748            std::mem::transmute::<&str, &str>(session_globals.symbol_interner.get_str(*self))
2749        })
2750    }
2751
2752    pub fn as_u32(self) -> u32 {
2753        self.0.as_u32()
2754    }
2755
2756    pub fn is_empty(self) -> bool {
2757        self == sym::empty
2758    }
2759
2760    /// This method is supposed to be used in error messages, so it's expected to be
2761    /// identical to printing the original identifier token written in source code
2762    /// (`token_to_string`, `Ident::to_string`), except that symbols don't keep the rawness flag
2763    /// or edition, so we have to guess the rawness using the global edition.
2764    pub fn to_ident_string(self) -> String {
2765        // Avoid creating an empty identifier, because that asserts in debug builds.
2766        if self == sym::empty { String::new() } else { Ident::with_dummy_span(self).to_string() }
2767    }
2768}
2769
2770impl fmt::Debug for Symbol {
2771    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2772        fmt::Debug::fmt(self.as_str(), f)
2773    }
2774}
2775
2776impl fmt::Display for Symbol {
2777    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2778        fmt::Display::fmt(self.as_str(), f)
2779    }
2780}
2781
2782impl<CTX> HashStable<CTX> for Symbol {
2783    #[inline]
2784    fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
2785        self.as_str().hash_stable(hcx, hasher);
2786    }
2787}
2788
2789impl<CTX> ToStableHashKey<CTX> for Symbol {
2790    type KeyType = String;
2791    #[inline]
2792    fn to_stable_hash_key(&self, _: &CTX) -> String {
2793        self.as_str().to_string()
2794    }
2795}
2796
2797impl StableCompare for Symbol {
2798    const CAN_USE_UNSTABLE_SORT: bool = true;
2799
2800    fn stable_cmp(&self, other: &Self) -> std::cmp::Ordering {
2801        self.as_str().cmp(other.as_str())
2802    }
2803}
2804
2805/// Like `Symbol`, but for byte strings. `ByteSymbol` is used less widely, so
2806/// it has fewer operations defined than `Symbol`.
2807#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
2808pub struct ByteSymbol(SymbolIndex);
2809
2810impl ByteSymbol {
2811    /// Avoid this except for things like deserialization of previously
2812    /// serialized symbols, and testing. Use `intern` instead.
2813    pub const fn new(n: u32) -> Self {
2814        ByteSymbol(SymbolIndex::from_u32(n))
2815    }
2816
2817    /// Maps a string to its interned representation.
2818    pub fn intern(byte_str: &[u8]) -> Self {
2819        with_session_globals(|session_globals| {
2820            session_globals.symbol_interner.intern_byte_str(byte_str)
2821        })
2822    }
2823
2824    /// Like `Symbol::as_str`.
2825    pub fn as_byte_str(&self) -> &[u8] {
2826        with_session_globals(|session_globals| unsafe {
2827            std::mem::transmute::<&[u8], &[u8]>(session_globals.symbol_interner.get_byte_str(*self))
2828        })
2829    }
2830
2831    pub fn as_u32(self) -> u32 {
2832        self.0.as_u32()
2833    }
2834}
2835
2836impl fmt::Debug for ByteSymbol {
2837    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2838        fmt::Debug::fmt(self.as_byte_str(), f)
2839    }
2840}
2841
2842impl<CTX> HashStable<CTX> for ByteSymbol {
2843    #[inline]
2844    fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
2845        self.as_byte_str().hash_stable(hcx, hasher);
2846    }
2847}
2848
2849// Interner used for both `Symbol`s and `ByteSymbol`s. If a string and a byte
2850// string with identical contents (e.g. "foo" and b"foo") are both interned,
2851// only one copy will be stored and the resulting `Symbol` and `ByteSymbol`
2852// will have the same index.
2853pub(crate) struct Interner(Lock<InternerInner>);
2854
2855// The `&'static [u8]`s in this type actually point into the arena.
2856//
2857// This type is private to prevent accidentally constructing more than one
2858// `Interner` on the same thread, which makes it easy to mix up `Symbol`s
2859// between `Interner`s.
2860struct InternerInner {
2861    arena: DroplessArena,
2862    byte_strs: FxIndexSet<&'static [u8]>,
2863}
2864
2865impl Interner {
2866    // These arguments are `&str`, but because of the sharing, we are
2867    // effectively pre-interning all these strings for both `Symbol` and
2868    // `ByteSymbol`.
2869    fn prefill(init: &[&'static str], extra: &[&'static str]) -> Self {
2870        let byte_strs = FxIndexSet::from_iter(
2871            init.iter().copied().chain(extra.iter().copied()).map(|str| str.as_bytes()),
2872        );
2873
2874        // The order in which duplicates are reported is irrelevant.
2875        #[expect(rustc::potential_query_instability)]
2876        if byte_strs.len() != init.len() + extra.len() {
2877            panic!(
2878                "duplicate symbols in the rustc symbol list and the extra symbols added by the driver: {:?}",
2879                FxHashSet::intersection(
2880                    &init.iter().copied().collect(),
2881                    &extra.iter().copied().collect(),
2882                )
2883                .collect::<Vec<_>>()
2884            )
2885        }
2886
2887        Interner(Lock::new(InternerInner { arena: Default::default(), byte_strs }))
2888    }
2889
2890    fn intern_str(&self, str: &str) -> Symbol {
2891        Symbol::new(self.intern_inner(str.as_bytes()))
2892    }
2893
2894    fn intern_byte_str(&self, byte_str: &[u8]) -> ByteSymbol {
2895        ByteSymbol::new(self.intern_inner(byte_str))
2896    }
2897
2898    #[inline]
2899    fn intern_inner(&self, byte_str: &[u8]) -> u32 {
2900        let mut inner = self.0.lock();
2901        if let Some(idx) = inner.byte_strs.get_index_of(byte_str) {
2902            return idx as u32;
2903        }
2904
2905        let byte_str: &[u8] = inner.arena.alloc_slice(byte_str);
2906
2907        // SAFETY: we can extend the arena allocation to `'static` because we
2908        // only access these while the arena is still alive.
2909        let byte_str: &'static [u8] = unsafe { &*(byte_str as *const [u8]) };
2910
2911        // This second hash table lookup can be avoided by using `RawEntryMut`,
2912        // but this code path isn't hot enough for it to be worth it. See
2913        // #91445 for details.
2914        let (idx, is_new) = inner.byte_strs.insert_full(byte_str);
2915        debug_assert!(is_new); // due to the get_index_of check above
2916
2917        idx as u32
2918    }
2919
2920    /// Get the symbol as a string.
2921    ///
2922    /// [`Symbol::as_str()`] should be used in preference to this function.
2923    fn get_str(&self, symbol: Symbol) -> &str {
2924        let byte_str = self.get_inner(symbol.0.as_usize());
2925        // SAFETY: known to be a UTF8 string because it's a `Symbol`.
2926        unsafe { str::from_utf8_unchecked(byte_str) }
2927    }
2928
2929    /// Get the symbol as a string.
2930    ///
2931    /// [`ByteSymbol::as_byte_str()`] should be used in preference to this function.
2932    fn get_byte_str(&self, symbol: ByteSymbol) -> &[u8] {
2933        self.get_inner(symbol.0.as_usize())
2934    }
2935
2936    fn get_inner(&self, index: usize) -> &[u8] {
2937        self.0.lock().byte_strs.get_index(index).unwrap()
2938    }
2939}
2940
2941// This module has a very short name because it's used a lot.
2942/// This module contains all the defined keyword `Symbol`s.
2943///
2944/// Given that `kw` is imported, use them like `kw::keyword_name`.
2945/// For example `kw::Loop` or `kw::Break`.
2946pub mod kw {
2947    pub use super::kw_generated::*;
2948}
2949
2950// This module has a very short name because it's used a lot.
2951/// This module contains all the defined non-keyword `Symbol`s.
2952///
2953/// Given that `sym` is imported, use them like `sym::symbol_name`.
2954/// For example `sym::rustfmt` or `sym::u8`.
2955pub mod sym {
2956    // Used from a macro in `librustc_feature/accepted.rs`
2957    use super::Symbol;
2958    pub use super::kw::MacroRules as macro_rules;
2959    #[doc(inline)]
2960    pub use super::sym_generated::*;
2961
2962    /// Get the symbol for an integer.
2963    ///
2964    /// The first few non-negative integers each have a static symbol and therefore
2965    /// are fast.
2966    pub fn integer<N: TryInto<usize> + Copy + itoa::Integer>(n: N) -> Symbol {
2967        if let Result::Ok(idx) = n.try_into() {
2968            if idx < 10 {
2969                return Symbol::new(super::SYMBOL_DIGITS_BASE + idx as u32);
2970            }
2971        }
2972        let mut buffer = itoa::Buffer::new();
2973        let printed = buffer.format(n);
2974        Symbol::intern(printed)
2975    }
2976}
2977
2978impl Symbol {
2979    fn is_special(self) -> bool {
2980        self <= kw::Underscore
2981    }
2982
2983    fn is_used_keyword_always(self) -> bool {
2984        self >= kw::As && self <= kw::While
2985    }
2986
2987    fn is_unused_keyword_always(self) -> bool {
2988        self >= kw::Abstract && self <= kw::Yield
2989    }
2990
2991    fn is_used_keyword_conditional(self, edition: impl FnOnce() -> Edition) -> bool {
2992        (self >= kw::Async && self <= kw::Dyn) && edition() >= Edition::Edition2018
2993    }
2994
2995    fn is_unused_keyword_conditional(self, edition: impl Copy + FnOnce() -> Edition) -> bool {
2996        self == kw::Gen && edition().at_least_rust_2024()
2997            || self == kw::Try && edition().at_least_rust_2018()
2998    }
2999
3000    pub fn is_reserved(self, edition: impl Copy + FnOnce() -> Edition) -> bool {
3001        self.is_special()
3002            || self.is_used_keyword_always()
3003            || self.is_unused_keyword_always()
3004            || self.is_used_keyword_conditional(edition)
3005            || self.is_unused_keyword_conditional(edition)
3006    }
3007
3008    pub fn is_weak(self) -> bool {
3009        self >= kw::Auto && self <= kw::Yeet
3010    }
3011
3012    /// A keyword or reserved identifier that can be used as a path segment.
3013    pub fn is_path_segment_keyword(self) -> bool {
3014        self == kw::Super
3015            || self == kw::SelfLower
3016            || self == kw::SelfUpper
3017            || self == kw::Crate
3018            || self == kw::PathRoot
3019            || self == kw::DollarCrate
3020    }
3021
3022    /// Returns `true` if the symbol is `true` or `false`.
3023    pub fn is_bool_lit(self) -> bool {
3024        self == kw::True || self == kw::False
3025    }
3026
3027    /// Returns `true` if this symbol can be a raw identifier.
3028    pub fn can_be_raw(self) -> bool {
3029        self != sym::empty && self != kw::Underscore && !self.is_path_segment_keyword()
3030    }
3031
3032    /// Was this symbol index predefined in the compiler's `symbols!` macro?
3033    /// Note: this applies to both `Symbol`s and `ByteSymbol`s, which is why it
3034    /// takes a `u32` argument instead of a `&self` argument. Use with care.
3035    pub fn is_predefined(index: u32) -> bool {
3036        index < PREDEFINED_SYMBOLS_COUNT
3037    }
3038}
3039
3040impl Ident {
3041    /// Returns `true` for reserved identifiers used internally for elided lifetimes,
3042    /// unnamed method parameters, crate root module, error recovery etc.
3043    pub fn is_special(self) -> bool {
3044        self.name.is_special()
3045    }
3046
3047    /// Returns `true` if the token is a keyword used in the language.
3048    pub fn is_used_keyword(self) -> bool {
3049        // Note: `span.edition()` is relatively expensive, don't call it unless necessary.
3050        self.name.is_used_keyword_always()
3051            || self.name.is_used_keyword_conditional(|| self.span.edition())
3052    }
3053
3054    /// Returns `true` if the token is a keyword reserved for possible future use.
3055    pub fn is_unused_keyword(self) -> bool {
3056        // Note: `span.edition()` is relatively expensive, don't call it unless necessary.
3057        self.name.is_unused_keyword_always()
3058            || self.name.is_unused_keyword_conditional(|| self.span.edition())
3059    }
3060
3061    /// Returns `true` if the token is either a special identifier or a keyword.
3062    pub fn is_reserved(self) -> bool {
3063        // Note: `span.edition()` is relatively expensive, don't call it unless necessary.
3064        self.name.is_reserved(|| self.span.edition())
3065    }
3066
3067    /// A keyword or reserved identifier that can be used as a path segment.
3068    pub fn is_path_segment_keyword(self) -> bool {
3069        self.name.is_path_segment_keyword()
3070    }
3071
3072    /// We see this identifier in a normal identifier position, like variable name or a type.
3073    /// How was it written originally? Did it use the raw form? Let's try to guess.
3074    pub fn is_raw_guess(self) -> bool {
3075        self.name.can_be_raw() && self.is_reserved()
3076    }
3077
3078    /// Given the name of a lifetime without the first quote (`'`),
3079    /// returns whether the lifetime name is reserved (therefore invalid)
3080    pub fn is_reserved_lifetime(self) -> bool {
3081        self.is_reserved() && ![kw::Underscore, kw::Static].contains(&self.name)
3082    }
3083
3084    pub fn is_raw_lifetime_guess(self) -> bool {
3085        let name_without_apostrophe = self.without_first_quote();
3086        name_without_apostrophe.name != self.name
3087            && name_without_apostrophe.name.can_be_raw()
3088            && name_without_apostrophe.is_reserved_lifetime()
3089    }
3090
3091    pub fn guess_print_mode(self) -> IdentPrintMode {
3092        if self.is_raw_lifetime_guess() {
3093            IdentPrintMode::RawLifetime
3094        } else if self.is_raw_guess() {
3095            IdentPrintMode::RawIdent
3096        } else {
3097            IdentPrintMode::Normal
3098        }
3099    }
3100
3101    /// Whether this would be the identifier for a tuple field like `self.0`, as
3102    /// opposed to a named field like `self.thing`.
3103    pub fn is_numeric(self) -> bool {
3104        self.as_str().bytes().all(|b| b.is_ascii_digit())
3105    }
3106}
3107
3108/// Collect all the keywords in a given edition into a vector.
3109///
3110/// *Note:* Please update this if a new keyword is added beyond the current
3111/// range.
3112pub fn used_keywords(edition: impl Copy + FnOnce() -> Edition) -> Vec<Symbol> {
3113    (kw::DollarCrate.as_u32()..kw::Yeet.as_u32())
3114        .filter_map(|kw| {
3115            let kw = Symbol::new(kw);
3116            if kw.is_used_keyword_always() || kw.is_used_keyword_conditional(edition) {
3117                Some(kw)
3118            } else {
3119                None
3120            }
3121        })
3122        .collect()
3123}