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