]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_span/src/symbol.rs
Auto merge of #99667 - ouz-a:some_branch, r=oli-obk
[rust.git] / compiler / rustc_span / src / 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
5 use rustc_arena::DroplessArena;
6 use rustc_data_structures::fx::FxHashMap;
7 use rustc_data_structures::stable_hasher::{HashStable, StableHasher, ToStableHashKey};
8 use rustc_data_structures::sync::Lock;
9 use rustc_macros::HashStable_Generic;
10 use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
11
12 use std::cmp::{Ord, PartialEq, PartialOrd};
13 use std::fmt;
14 use std::hash::{Hash, Hasher};
15 use std::str;
16
17 use crate::{with_session_globals, Edition, Span, DUMMY_SP};
18
19 #[cfg(test)]
20 mod tests;
21
22 // The proc macro code for this is in `compiler/rustc_macros/src/symbols.rs`.
23 symbols! {
24     // After modifying this list adjust `is_special`, `is_used_keyword`/`is_unused_keyword`,
25     // this should be rarely necessary though if the keywords are kept in alphabetic order.
26     Keywords {
27         // Special reserved identifiers used internally for elided lifetimes,
28         // unnamed method parameters, crate root module, error recovery etc.
29         Empty:              "",
30         PathRoot:           "{{root}}",
31         DollarCrate:        "$crate",
32         Underscore:         "_",
33
34         // Keywords that are used in stable Rust.
35         As:                 "as",
36         Break:              "break",
37         Const:              "const",
38         Continue:           "continue",
39         Crate:              "crate",
40         Else:               "else",
41         Enum:               "enum",
42         Extern:             "extern",
43         False:              "false",
44         Fn:                 "fn",
45         For:                "for",
46         If:                 "if",
47         Impl:               "impl",
48         In:                 "in",
49         Let:                "let",
50         Loop:               "loop",
51         Match:              "match",
52         Mod:                "mod",
53         Move:               "move",
54         Mut:                "mut",
55         Pub:                "pub",
56         Ref:                "ref",
57         Return:             "return",
58         SelfLower:          "self",
59         SelfUpper:          "Self",
60         Static:             "static",
61         Struct:             "struct",
62         Super:              "super",
63         Trait:              "trait",
64         True:               "true",
65         Type:               "type",
66         Unsafe:             "unsafe",
67         Use:                "use",
68         Where:              "where",
69         While:              "while",
70
71         // Keywords that are used in unstable Rust or reserved for future use.
72         Abstract:           "abstract",
73         Become:             "become",
74         Box:                "box",
75         Do:                 "do",
76         Final:              "final",
77         Macro:              "macro",
78         Override:           "override",
79         Priv:               "priv",
80         Typeof:             "typeof",
81         Unsized:            "unsized",
82         Virtual:            "virtual",
83         Yield:              "yield",
84
85         // Edition-specific keywords that are used in stable Rust.
86         Async:              "async", // >= 2018 Edition only
87         Await:              "await", // >= 2018 Edition only
88         Dyn:                "dyn", // >= 2018 Edition only
89
90         // Edition-specific keywords that are used in unstable Rust or reserved for future use.
91         Try:                "try", // >= 2018 Edition only
92
93         // Special lifetime names
94         UnderscoreLifetime: "'_",
95         StaticLifetime:     "'static",
96
97         // Weak keywords, have special meaning only in specific contexts.
98         Auto:               "auto",
99         Catch:              "catch",
100         Default:            "default",
101         MacroRules:         "macro_rules",
102         Raw:                "raw",
103         Union:              "union",
104         Yeet:               "yeet",
105     }
106
107     // Pre-interned symbols that can be referred to with `rustc_span::sym::*`.
108     //
109     // The symbol is the stringified identifier unless otherwise specified, in
110     // which case the name should mention the non-identifier punctuation.
111     // E.g. `sym::proc_dash_macro` represents "proc-macro", and it shouldn't be
112     // called `sym::proc_macro` because then it's easy to mistakenly think it
113     // represents "proc_macro".
114     //
115     // As well as the symbols listed, there are symbols for the strings
116     // "0", "1", ..., "9", which are accessible via `sym::integer`.
117     //
118     // The proc macro will abort if symbols are not in alphabetical order (as
119     // defined by `impl Ord for str`) or if any symbols are duplicated. Vim
120     // users can sort the list by selecting it and executing the command
121     // `:'<,'>!LC_ALL=C sort`.
122     //
123     // There is currently no checking that all symbols are used; that would be
124     // nice to have.
125     Symbols {
126         AcqRel,
127         Acquire,
128         AddSubdiagnostic,
129         Alignment,
130         Any,
131         Arc,
132         Argument,
133         ArgumentV1,
134         ArgumentV1Methods,
135         Arguments,
136         AsMut,
137         AsRef,
138         AssertParamIsClone,
139         AssertParamIsCopy,
140         AssertParamIsEq,
141         AtomicBool,
142         AtomicI128,
143         AtomicI16,
144         AtomicI32,
145         AtomicI64,
146         AtomicI8,
147         AtomicIsize,
148         AtomicPtr,
149         AtomicU128,
150         AtomicU16,
151         AtomicU32,
152         AtomicU64,
153         AtomicU8,
154         AtomicUsize,
155         BTreeEntry,
156         BTreeMap,
157         BTreeSet,
158         BinaryHeap,
159         Borrow,
160         Break,
161         C,
162         CStr,
163         CString,
164         Capture,
165         Center,
166         Clone,
167         Continue,
168         Copy,
169         Count,
170         Cow,
171         Debug,
172         DebugStruct,
173         DebugTuple,
174         Decodable,
175         Decoder,
176         DecorateLint,
177         Default,
178         Deref,
179         DiagnosticMessage,
180         DirBuilder,
181         Display,
182         DoubleEndedIterator,
183         Duration,
184         Encodable,
185         Encoder,
186         Eq,
187         Equal,
188         Err,
189         Error,
190         File,
191         FileType,
192         Fn,
193         FnMut,
194         FnOnce,
195         FormatSpec,
196         Formatter,
197         From,
198         FromIterator,
199         FromResidual,
200         Future,
201         FxHashMap,
202         FxHashSet,
203         GlobalAlloc,
204         Hash,
205         HashMap,
206         HashMapEntry,
207         HashSet,
208         Hasher,
209         Implied,
210         Input,
211         Into,
212         IntoFuture,
213         IntoIterator,
214         IoRead,
215         IoWrite,
216         IrTyKind,
217         Is,
218         ItemContext,
219         Iterator,
220         Layout,
221         Left,
222         LinkedList,
223         LintPass,
224         Mutex,
225         N,
226         NonZeroI128,
227         NonZeroI16,
228         NonZeroI32,
229         NonZeroI64,
230         NonZeroI8,
231         NonZeroU128,
232         NonZeroU16,
233         NonZeroU32,
234         NonZeroU64,
235         NonZeroU8,
236         None,
237         Ok,
238         Option,
239         Ord,
240         Ordering,
241         OsStr,
242         OsString,
243         Output,
244         Param,
245         PartialEq,
246         PartialOrd,
247         Path,
248         PathBuf,
249         Pending,
250         Pin,
251         Pointer,
252         Poll,
253         ProcMacro,
254         ProcMacroHack,
255         ProceduralMasqueradeDummyType,
256         Range,
257         RangeFrom,
258         RangeFull,
259         RangeInclusive,
260         RangeTo,
261         RangeToInclusive,
262         Rc,
263         Ready,
264         Receiver,
265         Relaxed,
266         Release,
267         Result,
268         Return,
269         Right,
270         Rust,
271         RustcDecodable,
272         RustcEncodable,
273         Send,
274         SeqCst,
275         SessionDiagnostic,
276         SliceIndex,
277         Some,
278         String,
279         StructuralEq,
280         StructuralPartialEq,
281         SubdiagnosticMessage,
282         Sync,
283         Target,
284         ToOwned,
285         ToString,
286         Try,
287         TryCaptureGeneric,
288         TryCapturePrintable,
289         TryFrom,
290         TryInto,
291         Ty,
292         TyCtxt,
293         TyKind,
294         Unknown,
295         UnsafeArg,
296         Vec,
297         VecDeque,
298         Wrapper,
299         Yield,
300         _DECLS,
301         _Self,
302         __D,
303         __H,
304         __S,
305         __awaitee,
306         __try_var,
307         _d,
308         _e,
309         _task_context,
310         a32,
311         aarch64_target_feature,
312         aarch64_ver_target_feature,
313         abi,
314         abi_amdgpu_kernel,
315         abi_avr_interrupt,
316         abi_c_cmse_nonsecure_call,
317         abi_efiapi,
318         abi_msp430_interrupt,
319         abi_ptx,
320         abi_sysv64,
321         abi_thiscall,
322         abi_unadjusted,
323         abi_vectorcall,
324         abi_x86_interrupt,
325         abort,
326         aborts,
327         add,
328         add_assign,
329         add_with_overflow,
330         address,
331         adt_const_params,
332         advanced_slice_patterns,
333         adx_target_feature,
334         alias,
335         align,
336         align_offset,
337         alignstack,
338         all,
339         alloc,
340         alloc_error_handler,
341         alloc_layout,
342         alloc_zeroed,
343         allocator,
344         allocator_api,
345         allocator_internals,
346         allow,
347         allow_fail,
348         allow_internal_unsafe,
349         allow_internal_unstable,
350         allowed,
351         alu32,
352         always,
353         and,
354         and_then,
355         anonymous_lifetime_in_impl_trait,
356         any,
357         append_const_msg,
358         arbitrary_enum_discriminant,
359         arbitrary_self_types,
360         args,
361         arith_offset,
362         arm,
363         arm_target_feature,
364         array,
365         arrays,
366         as_ptr,
367         as_ref,
368         as_str,
369         asm,
370         asm_const,
371         asm_experimental_arch,
372         asm_sym,
373         asm_unwind,
374         assert,
375         assert_eq_macro,
376         assert_inhabited,
377         assert_macro,
378         assert_ne_macro,
379         assert_receiver_is_total_eq,
380         assert_uninit_valid,
381         assert_zero_valid,
382         asserting,
383         associated_const_equality,
384         associated_consts,
385         associated_type_bounds,
386         associated_type_defaults,
387         associated_types,
388         assume,
389         assume_init,
390         async_await,
391         async_closure,
392         atomic,
393         atomic_mod,
394         atomics,
395         att_syntax,
396         attr,
397         attr_literals,
398         attributes,
399         augmented_assignments,
400         auto_traits,
401         automatically_derived,
402         avx,
403         avx512_target_feature,
404         avx512bw,
405         avx512f,
406         await_macro,
407         bang,
408         begin_panic,
409         bench,
410         bin,
411         bind_by_move_pattern_guards,
412         bindings_after_at,
413         bitand,
414         bitand_assign,
415         bitor,
416         bitor_assign,
417         bitreverse,
418         bitxor,
419         bitxor_assign,
420         black_box,
421         block,
422         bool,
423         borrowck_graphviz_format,
424         borrowck_graphviz_postflow,
425         borrowck_graphviz_preflow,
426         box_free,
427         box_patterns,
428         box_syntax,
429         bpf_target_feature,
430         braced_empty_structs,
431         branch,
432         breakpoint,
433         bridge,
434         bswap,
435         c_str,
436         c_unwind,
437         c_variadic,
438         call,
439         call_mut,
440         call_once,
441         caller_location,
442         capture_disjoint_fields,
443         cdylib,
444         ceilf32,
445         ceilf64,
446         cfg,
447         cfg_accessible,
448         cfg_attr,
449         cfg_attr_multi,
450         cfg_doctest,
451         cfg_eval,
452         cfg_hide,
453         cfg_macro,
454         cfg_panic,
455         cfg_sanitize,
456         cfg_target_abi,
457         cfg_target_compact,
458         cfg_target_feature,
459         cfg_target_has_atomic,
460         cfg_target_has_atomic_equal_alignment,
461         cfg_target_has_atomic_load_store,
462         cfg_target_thread_local,
463         cfg_target_vendor,
464         cfg_version,
465         cfi,
466         char,
467         client,
468         clippy,
469         clobber_abi,
470         clone,
471         clone_closures,
472         clone_from,
473         closure,
474         closure_lifetime_binder,
475         closure_to_fn_coercion,
476         closure_track_caller,
477         cmp,
478         cmp_max,
479         cmp_min,
480         cmpxchg16b_target_feature,
481         cmse_nonsecure_entry,
482         coerce_unsized,
483         cold,
484         column,
485         column_macro,
486         compare_and_swap,
487         compare_exchange,
488         compare_exchange_weak,
489         compile_error,
490         compile_error_macro,
491         compiler,
492         compiler_builtins,
493         compiler_fence,
494         concat,
495         concat_bytes,
496         concat_idents,
497         concat_macro,
498         conservative_impl_trait,
499         console,
500         const_allocate,
501         const_async_blocks,
502         const_compare_raw_pointers,
503         const_constructor,
504         const_deallocate,
505         const_eval_limit,
506         const_eval_select,
507         const_eval_select_ct,
508         const_evaluatable_checked,
509         const_extern_fn,
510         const_fn,
511         const_fn_floating_point_arithmetic,
512         const_fn_fn_ptr_basics,
513         const_fn_trait_bound,
514         const_fn_transmute,
515         const_fn_union,
516         const_fn_unsize,
517         const_for,
518         const_format_args,
519         const_generic_defaults,
520         const_generics,
521         const_generics_defaults,
522         const_if_match,
523         const_impl_trait,
524         const_in_array_repeat_expressions,
525         const_indexing,
526         const_let,
527         const_loop,
528         const_mut_refs,
529         const_panic,
530         const_panic_fmt,
531         const_precise_live_drops,
532         const_raw_ptr_deref,
533         const_raw_ptr_to_usize_cast,
534         const_refs_to_cell,
535         const_trait,
536         const_trait_bound_opt_out,
537         const_trait_impl,
538         const_transmute,
539         const_try,
540         constant,
541         constructor,
542         contents,
543         context,
544         convert,
545         copy,
546         copy_closures,
547         copy_nonoverlapping,
548         copysignf32,
549         copysignf64,
550         core,
551         core_intrinsics,
552         core_panic,
553         core_panic_2015_macro,
554         core_panic_macro,
555         cosf32,
556         cosf64,
557         count,
558         cr,
559         crate_id,
560         crate_in_paths,
561         crate_local,
562         crate_name,
563         crate_type,
564         crate_visibility_modifier,
565         crt_dash_static: "crt-static",
566         cstring_type,
567         ctlz,
568         ctlz_nonzero,
569         ctpop,
570         cttz,
571         cttz_nonzero,
572         custom_attribute,
573         custom_derive,
574         custom_inner_attributes,
575         custom_test_frameworks,
576         d,
577         d32,
578         dbg_macro,
579         dead_code,
580         dealloc,
581         debug,
582         debug_assert_eq_macro,
583         debug_assert_macro,
584         debug_assert_ne_macro,
585         debug_assertions,
586         debug_struct,
587         debug_struct_fields_finish,
588         debug_trait_builder,
589         debug_tuple,
590         debug_tuple_fields_finish,
591         debugger_visualizer,
592         decl_macro,
593         declare_lint_pass,
594         decode,
595         default_alloc_error_handler,
596         default_lib_allocator,
597         default_method_body_is_const,
598         default_type_parameter_fallback,
599         default_type_params,
600         delay_span_bug_from_inside_query,
601         deny,
602         deprecated,
603         deprecated_safe,
604         deprecated_suggestion,
605         deref,
606         deref_method,
607         deref_mut,
608         deref_target,
609         derive,
610         derive_default_enum,
611         destruct,
612         destructuring_assignment,
613         diagnostic,
614         direct,
615         discriminant_kind,
616         discriminant_type,
617         discriminant_value,
618         dispatch_from_dyn,
619         display_trait,
620         div,
621         div_assign,
622         doc,
623         doc_alias,
624         doc_auto_cfg,
625         doc_cfg,
626         doc_cfg_hide,
627         doc_keyword,
628         doc_masked,
629         doc_notable_trait,
630         doc_primitive,
631         doc_spotlight,
632         doctest,
633         document_private_items,
634         dotdot: "..",
635         dotdot_in_tuple_patterns,
636         dotdoteq_in_patterns,
637         dreg,
638         dreg_low16,
639         dreg_low8,
640         drop,
641         drop_in_place,
642         drop_types_in_const,
643         dropck_eyepatch,
644         dropck_parametricity,
645         dylib,
646         dyn_metadata,
647         dyn_trait,
648         e,
649         edition_macro_pats,
650         edition_panic,
651         eh_catch_typeinfo,
652         eh_personality,
653         emit_enum,
654         emit_enum_variant,
655         emit_enum_variant_arg,
656         emit_struct,
657         emit_struct_field,
658         enable,
659         enclosing_scope,
660         encode,
661         end,
662         env,
663         env_macro,
664         eprint_macro,
665         eprintln_macro,
666         eq,
667         ermsb_target_feature,
668         exact_div,
669         except,
670         exchange_malloc,
671         exclusive_range_pattern,
672         exhaustive_integer_patterns,
673         exhaustive_patterns,
674         existential_type,
675         exp2f32,
676         exp2f64,
677         expect,
678         expected,
679         expf32,
680         expf64,
681         explicit_generic_args_with_impl_trait,
682         export_name,
683         expr,
684         extended_key_value_attributes,
685         extern_absolute_paths,
686         extern_crate_item_prelude,
687         extern_crate_self,
688         extern_in_paths,
689         extern_prelude,
690         extern_types,
691         external_doc,
692         f,
693         f16c_target_feature,
694         f32,
695         f64,
696         fabsf32,
697         fabsf64,
698         fadd_fast,
699         fake_variadic,
700         fdiv_fast,
701         feature,
702         fence,
703         ferris: "🦀",
704         fetch_update,
705         ffi,
706         ffi_const,
707         ffi_pure,
708         ffi_returns_twice,
709         field,
710         field_init_shorthand,
711         file,
712         file_macro,
713         fill,
714         finish,
715         flags,
716         float,
717         float_to_int_unchecked,
718         floorf32,
719         floorf64,
720         fmaf32,
721         fmaf64,
722         fmt,
723         fmt_as_str,
724         fmt_internals,
725         fmul_fast,
726         fn_align,
727         fn_must_use,
728         fn_mut,
729         fn_once,
730         fn_once_output,
731         forbid,
732         forget,
733         format,
734         format_args,
735         format_args_capture,
736         format_args_macro,
737         format_args_nl,
738         format_macro,
739         fp,
740         freeze,
741         freg,
742         frem_fast,
743         from,
744         from_desugaring,
745         from_generator,
746         from_iter,
747         from_method,
748         from_output,
749         from_residual,
750         from_size_align_unchecked,
751         from_usize,
752         from_yeet,
753         fsub_fast,
754         fundamental,
755         future,
756         future_trait,
757         gdb_script_file,
758         ge,
759         gen_future,
760         gen_kill,
761         generator,
762         generator_return,
763         generator_state,
764         generators,
765         generic_arg_infer,
766         generic_assert,
767         generic_associated_types,
768         generic_associated_types_extended,
769         generic_const_exprs,
770         generic_param_attrs,
771         get_context,
772         global_allocator,
773         global_asm,
774         globs,
775         gt,
776         half_open_range_patterns,
777         hash,
778         hexagon_target_feature,
779         hidden,
780         homogeneous_aggregate,
781         html_favicon_url,
782         html_logo_url,
783         html_no_source,
784         html_playground_url,
785         html_root_url,
786         hwaddress,
787         i,
788         i128,
789         i128_type,
790         i16,
791         i32,
792         i64,
793         i8,
794         ident,
795         if_let,
796         if_let_guard,
797         if_while_or_patterns,
798         ignore,
799         impl_header_lifetime_elision,
800         impl_lint_pass,
801         impl_macros,
802         impl_trait_in_bindings,
803         implied_by,
804         import,
805         import_shadowing,
806         imported_main,
807         in_band_lifetimes,
808         include,
809         include_bytes,
810         include_bytes_macro,
811         include_macro,
812         include_str,
813         include_str_macro,
814         inclusive_range_syntax,
815         index,
816         index_mut,
817         infer_outlives_requirements,
818         infer_static_outlives_requirements,
819         inherent_associated_types,
820         inlateout,
821         inline,
822         inline_const,
823         inline_const_pat,
824         inout,
825         instruction_set,
826         integer_: "integer",
827         integral,
828         intel,
829         into_future,
830         into_iter,
831         intra_doc_pointers,
832         intrinsics,
833         irrefutable_let_patterns,
834         isa_attribute,
835         isize,
836         issue,
837         issue_5723_bootstrap,
838         issue_tracker_base_url,
839         item,
840         item_like_imports,
841         iter,
842         iter_repeat,
843         keyword,
844         kind,
845         kreg,
846         kreg0,
847         label,
848         label_break_value,
849         lang,
850         lang_items,
851         large_assignments,
852         lateout,
853         lazy_normalization_consts,
854         le,
855         len,
856         let_chains,
857         let_else,
858         lhs,
859         lib,
860         libc,
861         lifetime,
862         likely,
863         line,
864         line_macro,
865         link,
866         link_args,
867         link_cfg,
868         link_llvm_intrinsics,
869         link_name,
870         link_ordinal,
871         link_section,
872         linkage,
873         linker,
874         lint_reasons,
875         literal,
876         load,
877         loaded_from_disk,
878         local,
879         local_inner_macros,
880         log10f32,
881         log10f64,
882         log2f32,
883         log2f64,
884         log_syntax,
885         logf32,
886         logf64,
887         loop_break_value,
888         lt,
889         macro_at_most_once_rep,
890         macro_attributes_in_derive_output,
891         macro_escape,
892         macro_export,
893         macro_lifetime_matcher,
894         macro_literal_matcher,
895         macro_metavar_expr,
896         macro_reexport,
897         macro_use,
898         macro_vis_matcher,
899         macros_in_extern,
900         main,
901         managed_boxes,
902         manually_drop,
903         map,
904         marker,
905         marker_trait_attr,
906         masked,
907         match_beginning_vert,
908         match_default_bindings,
909         matches_macro,
910         maxnumf32,
911         maxnumf64,
912         may_dangle,
913         may_unwind,
914         maybe_uninit,
915         maybe_uninit_uninit,
916         maybe_uninit_zeroed,
917         mem_discriminant,
918         mem_drop,
919         mem_forget,
920         mem_replace,
921         mem_size_of,
922         mem_size_of_val,
923         mem_uninitialized,
924         mem_variant_count,
925         mem_zeroed,
926         member_constraints,
927         memory,
928         memtag,
929         message,
930         meta,
931         metadata_type,
932         min_align_of,
933         min_align_of_val,
934         min_const_fn,
935         min_const_generics,
936         min_const_unsafe_fn,
937         min_specialization,
938         min_type_alias_impl_trait,
939         minnumf32,
940         minnumf64,
941         mips_target_feature,
942         miri,
943         misc,
944         mmx_reg,
945         modifiers,
946         module,
947         module_path,
948         module_path_macro,
949         more_qualified_paths,
950         more_struct_aliases,
951         movbe_target_feature,
952         move_ref_pattern,
953         move_size_limit,
954         mul,
955         mul_assign,
956         mul_with_overflow,
957         must_not_suspend,
958         must_use,
959         naked,
960         naked_functions,
961         name,
962         names,
963         native_link_modifiers,
964         native_link_modifiers_as_needed,
965         native_link_modifiers_bundle,
966         native_link_modifiers_verbatim,
967         native_link_modifiers_whole_archive,
968         natvis_file,
969         ne,
970         nearbyintf32,
971         nearbyintf64,
972         needs_allocator,
973         needs_drop,
974         needs_panic_runtime,
975         neg,
976         negate_unsigned,
977         negative_impls,
978         neon,
979         never,
980         never_type,
981         never_type_fallback,
982         new,
983         new_unchecked,
984         next,
985         nll,
986         no,
987         no_builtins,
988         no_core,
989         no_coverage,
990         no_crate_inject,
991         no_debug,
992         no_default_passes,
993         no_implicit_prelude,
994         no_inline,
995         no_link,
996         no_main,
997         no_mangle,
998         no_sanitize,
999         no_stack_check,
1000         no_start,
1001         no_std,
1002         nomem,
1003         non_ascii_idents,
1004         non_exhaustive,
1005         non_exhaustive_omitted_patterns_lint,
1006         non_modrs_mods,
1007         none_error,
1008         nontemporal_store,
1009         noop_method_borrow,
1010         noop_method_clone,
1011         noop_method_deref,
1012         noreturn,
1013         nostack,
1014         not,
1015         notable_trait,
1016         note,
1017         object_safe_for_dispatch,
1018         of,
1019         offset,
1020         omit_gdb_pretty_printer_section,
1021         on,
1022         on_unimplemented,
1023         oom,
1024         opaque,
1025         ops,
1026         opt_out_copy,
1027         optimize,
1028         optimize_attribute,
1029         optin_builtin_traits,
1030         option,
1031         option_env,
1032         option_env_macro,
1033         options,
1034         or,
1035         or_patterns,
1036         other,
1037         out,
1038         overlapping_marker_traits,
1039         owned_box,
1040         packed,
1041         panic,
1042         panic_2015,
1043         panic_2021,
1044         panic_abort,
1045         panic_bounds_check,
1046         panic_display,
1047         panic_fmt,
1048         panic_handler,
1049         panic_impl,
1050         panic_implementation,
1051         panic_info,
1052         panic_location,
1053         panic_no_unwind,
1054         panic_runtime,
1055         panic_str,
1056         panic_unwind,
1057         panicking,
1058         param_attrs,
1059         partial_cmp,
1060         partial_ord,
1061         passes,
1062         pat,
1063         pat_param,
1064         path,
1065         pattern_parentheses,
1066         phantom_data,
1067         pin,
1068         platform_intrinsics,
1069         plugin,
1070         plugin_registrar,
1071         plugins,
1072         pointee_trait,
1073         pointer,
1074         pointer_trait_fmt,
1075         poll,
1076         position,
1077         post_dash_lto: "post-lto",
1078         powerpc_target_feature,
1079         powf32,
1080         powf64,
1081         powif32,
1082         powif64,
1083         pre_dash_lto: "pre-lto",
1084         precise_pointer_size_matching,
1085         precision,
1086         pref_align_of,
1087         prefetch_read_data,
1088         prefetch_read_instruction,
1089         prefetch_write_data,
1090         prefetch_write_instruction,
1091         preg,
1092         prelude,
1093         prelude_import,
1094         preserves_flags,
1095         primitive,
1096         print_macro,
1097         println_macro,
1098         proc_dash_macro: "proc-macro",
1099         proc_macro,
1100         proc_macro_attribute,
1101         proc_macro_def_site,
1102         proc_macro_derive,
1103         proc_macro_expr,
1104         proc_macro_gen,
1105         proc_macro_hygiene,
1106         proc_macro_internals,
1107         proc_macro_mod,
1108         proc_macro_non_items,
1109         proc_macro_path_invoc,
1110         profiler_builtins,
1111         profiler_runtime,
1112         ptr,
1113         ptr_guaranteed_eq,
1114         ptr_guaranteed_ne,
1115         ptr_null,
1116         ptr_null_mut,
1117         ptr_offset_from,
1118         ptr_offset_from_unsigned,
1119         pub_macro_rules,
1120         pub_restricted,
1121         pure,
1122         pushpop_unsafe,
1123         qreg,
1124         qreg_low4,
1125         qreg_low8,
1126         quad_precision_float,
1127         question_mark,
1128         quote,
1129         range_inclusive_new,
1130         raw_dylib,
1131         raw_eq,
1132         raw_identifiers,
1133         raw_ref_op,
1134         re_rebalance_coherence,
1135         read_enum,
1136         read_enum_variant,
1137         read_enum_variant_arg,
1138         read_struct,
1139         read_struct_field,
1140         readonly,
1141         realloc,
1142         reason,
1143         receiver,
1144         recursion_limit,
1145         reexport_test_harness_main,
1146         ref_unwind_safe_trait,
1147         reference,
1148         reflect,
1149         reg,
1150         reg16,
1151         reg32,
1152         reg64,
1153         reg_abcd,
1154         reg_byte,
1155         reg_iw,
1156         reg_nonzero,
1157         reg_pair,
1158         reg_ptr,
1159         reg_upper,
1160         register_attr,
1161         register_tool,
1162         relaxed_adts,
1163         relaxed_struct_unsize,
1164         rem,
1165         rem_assign,
1166         repr,
1167         repr128,
1168         repr_align,
1169         repr_align_enum,
1170         repr_packed,
1171         repr_simd,
1172         repr_transparent,
1173         residual,
1174         result,
1175         rhs,
1176         rintf32,
1177         rintf64,
1178         riscv_target_feature,
1179         rlib,
1180         rotate_left,
1181         rotate_right,
1182         roundf32,
1183         roundf64,
1184         rt,
1185         rtm_target_feature,
1186         rust,
1187         rust_2015,
1188         rust_2015_preview,
1189         rust_2018,
1190         rust_2018_preview,
1191         rust_2021,
1192         rust_2021_preview,
1193         rust_2024,
1194         rust_2024_preview,
1195         rust_begin_unwind,
1196         rust_cold_cc,
1197         rust_eh_catch_typeinfo,
1198         rust_eh_personality,
1199         rust_eh_register_frames,
1200         rust_eh_unregister_frames,
1201         rust_oom,
1202         rustc,
1203         rustc_allocator,
1204         rustc_allocator_nounwind,
1205         rustc_allocator_zeroed,
1206         rustc_allow_const_fn_unstable,
1207         rustc_allow_incoherent_impl,
1208         rustc_allowed_through_unstable_modules,
1209         rustc_attrs,
1210         rustc_box,
1211         rustc_builtin_macro,
1212         rustc_capture_analysis,
1213         rustc_clean,
1214         rustc_coherence_is_core,
1215         rustc_const_stable,
1216         rustc_const_unstable,
1217         rustc_conversion_suggestion,
1218         rustc_deallocator,
1219         rustc_def_path,
1220         rustc_diagnostic_item,
1221         rustc_diagnostic_macros,
1222         rustc_dirty,
1223         rustc_do_not_const_check,
1224         rustc_dummy,
1225         rustc_dump_env_program_clauses,
1226         rustc_dump_program_clauses,
1227         rustc_dump_user_substs,
1228         rustc_dump_vtable,
1229         rustc_error,
1230         rustc_evaluate_where_clauses,
1231         rustc_expected_cgu_reuse,
1232         rustc_has_incoherent_inherent_impls,
1233         rustc_if_this_changed,
1234         rustc_inherit_overflow_checks,
1235         rustc_insignificant_dtor,
1236         rustc_layout,
1237         rustc_layout_scalar_valid_range_end,
1238         rustc_layout_scalar_valid_range_start,
1239         rustc_legacy_const_generics,
1240         rustc_lint_diagnostics,
1241         rustc_lint_opt_deny_field_access,
1242         rustc_lint_opt_ty,
1243         rustc_lint_query_instability,
1244         rustc_macro_transparency,
1245         rustc_main,
1246         rustc_mir,
1247         rustc_must_implement_one_of,
1248         rustc_nonnull_optimization_guaranteed,
1249         rustc_object_lifetime_default,
1250         rustc_on_unimplemented,
1251         rustc_outlives,
1252         rustc_paren_sugar,
1253         rustc_partition_codegened,
1254         rustc_partition_reused,
1255         rustc_pass_by_value,
1256         rustc_peek,
1257         rustc_peek_definite_init,
1258         rustc_peek_liveness,
1259         rustc_peek_maybe_init,
1260         rustc_peek_maybe_uninit,
1261         rustc_polymorphize_error,
1262         rustc_private,
1263         rustc_proc_macro_decls,
1264         rustc_promotable,
1265         rustc_reallocator,
1266         rustc_regions,
1267         rustc_reservation_impl,
1268         rustc_serialize,
1269         rustc_skip_array_during_method_dispatch,
1270         rustc_specialization_trait,
1271         rustc_stable,
1272         rustc_std_internal_symbol,
1273         rustc_strict_coherence,
1274         rustc_symbol_name,
1275         rustc_test_marker,
1276         rustc_then_this_would_need,
1277         rustc_trivial_field_reads,
1278         rustc_unsafe_specialization_marker,
1279         rustc_variance,
1280         rustdoc,
1281         rustdoc_internals,
1282         rustfmt,
1283         rvalue_static_promotion,
1284         s,
1285         sanitize,
1286         sanitizer_runtime,
1287         saturating_add,
1288         saturating_sub,
1289         self_in_typedefs,
1290         self_struct_ctor,
1291         semitransparent,
1292         shadow_call_stack,
1293         shl,
1294         shl_assign,
1295         should_panic,
1296         shr,
1297         shr_assign,
1298         simd,
1299         simd_add,
1300         simd_and,
1301         simd_arith_offset,
1302         simd_as,
1303         simd_bitmask,
1304         simd_cast,
1305         simd_ceil,
1306         simd_div,
1307         simd_eq,
1308         simd_extract,
1309         simd_fabs,
1310         simd_fcos,
1311         simd_fexp,
1312         simd_fexp2,
1313         simd_ffi,
1314         simd_flog,
1315         simd_flog10,
1316         simd_flog2,
1317         simd_floor,
1318         simd_fma,
1319         simd_fmax,
1320         simd_fmin,
1321         simd_fpow,
1322         simd_fpowi,
1323         simd_fsin,
1324         simd_fsqrt,
1325         simd_gather,
1326         simd_ge,
1327         simd_gt,
1328         simd_insert,
1329         simd_le,
1330         simd_lt,
1331         simd_mul,
1332         simd_ne,
1333         simd_neg,
1334         simd_or,
1335         simd_reduce_add_ordered,
1336         simd_reduce_add_unordered,
1337         simd_reduce_all,
1338         simd_reduce_and,
1339         simd_reduce_any,
1340         simd_reduce_max,
1341         simd_reduce_max_nanless,
1342         simd_reduce_min,
1343         simd_reduce_min_nanless,
1344         simd_reduce_mul_ordered,
1345         simd_reduce_mul_unordered,
1346         simd_reduce_or,
1347         simd_reduce_xor,
1348         simd_rem,
1349         simd_round,
1350         simd_saturating_add,
1351         simd_saturating_sub,
1352         simd_scatter,
1353         simd_select,
1354         simd_select_bitmask,
1355         simd_shl,
1356         simd_shr,
1357         simd_shuffle,
1358         simd_sub,
1359         simd_trunc,
1360         simd_xor,
1361         since,
1362         sinf32,
1363         sinf64,
1364         size,
1365         size_of,
1366         size_of_val,
1367         sized,
1368         skip,
1369         slice,
1370         slice_len_fn,
1371         slice_patterns,
1372         slicing_syntax,
1373         soft,
1374         specialization,
1375         speed,
1376         spotlight,
1377         sqrtf32,
1378         sqrtf64,
1379         sreg,
1380         sreg_low16,
1381         sse,
1382         sse4a_target_feature,
1383         stable,
1384         staged_api,
1385         start,
1386         state,
1387         static_in_const,
1388         static_nobundle,
1389         static_recursion,
1390         staticlib,
1391         std,
1392         std_inject,
1393         std_panic,
1394         std_panic_2015_macro,
1395         std_panic_macro,
1396         stmt,
1397         stmt_expr_attributes,
1398         stop_after_dataflow,
1399         store,
1400         str,
1401         str_split_whitespace,
1402         str_trim,
1403         str_trim_end,
1404         str_trim_start,
1405         strict_provenance,
1406         stringify,
1407         stringify_macro,
1408         struct_field_attributes,
1409         struct_inherit,
1410         struct_variant,
1411         structural_match,
1412         structural_peq,
1413         structural_teq,
1414         sty,
1415         sub,
1416         sub_assign,
1417         sub_with_overflow,
1418         suggestion,
1419         sym,
1420         sync,
1421         t32,
1422         target,
1423         target_abi,
1424         target_arch,
1425         target_endian,
1426         target_env,
1427         target_family,
1428         target_feature,
1429         target_feature_11,
1430         target_has_atomic,
1431         target_has_atomic_equal_alignment,
1432         target_has_atomic_load_store,
1433         target_os,
1434         target_pointer_width,
1435         target_target_vendor,
1436         target_thread_local,
1437         target_vendor,
1438         task,
1439         tbm_target_feature,
1440         termination,
1441         termination_trait,
1442         termination_trait_test,
1443         test,
1444         test_2018_feature,
1445         test_accepted_feature,
1446         test_case,
1447         test_removed_feature,
1448         test_runner,
1449         test_unstable_lint,
1450         then_with,
1451         thread,
1452         thread_local,
1453         thread_local_macro,
1454         thumb2,
1455         thumb_mode: "thumb-mode",
1456         tmm_reg,
1457         to_string,
1458         to_vec,
1459         todo_macro,
1460         tool_attributes,
1461         tool_lints,
1462         trace_macros,
1463         track_caller,
1464         trait_alias,
1465         trait_upcasting,
1466         transmute,
1467         transparent,
1468         transparent_enums,
1469         transparent_unions,
1470         trivial_bounds,
1471         truncf32,
1472         truncf64,
1473         try_blocks,
1474         try_capture,
1475         try_from,
1476         try_into,
1477         try_trait_v2,
1478         tt,
1479         tuple,
1480         tuple_from_req,
1481         tuple_indexing,
1482         two_phase,
1483         ty,
1484         type_alias_enum_variants,
1485         type_alias_impl_trait,
1486         type_ascription,
1487         type_changing_struct_update,
1488         type_id,
1489         type_length_limit,
1490         type_macros,
1491         type_name,
1492         u128,
1493         u16,
1494         u32,
1495         u64,
1496         u8,
1497         unaligned_volatile_load,
1498         unaligned_volatile_store,
1499         unboxed_closures,
1500         unchecked_add,
1501         unchecked_div,
1502         unchecked_mul,
1503         unchecked_rem,
1504         unchecked_shl,
1505         unchecked_shr,
1506         unchecked_sub,
1507         underscore_const_names,
1508         underscore_imports,
1509         underscore_lifetimes,
1510         uniform_paths,
1511         unimplemented_macro,
1512         unit,
1513         universal_impl_trait,
1514         unix,
1515         unlikely,
1516         unmarked_api,
1517         unpin,
1518         unreachable,
1519         unreachable_2015,
1520         unreachable_2015_macro,
1521         unreachable_2021,
1522         unreachable_2021_macro,
1523         unreachable_code,
1524         unreachable_display,
1525         unreachable_macro,
1526         unrestricted_attribute_tokens,
1527         unsafe_block_in_unsafe_fn,
1528         unsafe_cell,
1529         unsafe_no_drop_flag,
1530         unsafe_pin_internals,
1531         unsize,
1532         unsized_fn_params,
1533         unsized_locals,
1534         unsized_tuple_coercion,
1535         unstable,
1536         unstable_location_reason_default: "this crate is being loaded from the sysroot, an \
1537                           unstable location; did you mean to load this crate \
1538                           from crates.io via `Cargo.toml` instead?",
1539         untagged_unions,
1540         unused_imports,
1541         unused_qualifications,
1542         unwind,
1543         unwind_attributes,
1544         unwind_safe_trait,
1545         unwrap,
1546         unwrap_or,
1547         use_extern_macros,
1548         use_nested_groups,
1549         used,
1550         used_with_arg,
1551         using,
1552         usize,
1553         v1,
1554         va_arg,
1555         va_copy,
1556         va_end,
1557         va_list,
1558         va_start,
1559         val,
1560         values,
1561         var,
1562         variant_count,
1563         vec,
1564         vec_macro,
1565         version,
1566         vfp2,
1567         vis,
1568         visible_private_types,
1569         volatile,
1570         volatile_copy_memory,
1571         volatile_copy_nonoverlapping_memory,
1572         volatile_load,
1573         volatile_set_memory,
1574         volatile_store,
1575         vreg,
1576         vreg_low16,
1577         vtable_align,
1578         vtable_size,
1579         warn,
1580         wasm_abi,
1581         wasm_import_module,
1582         wasm_target_feature,
1583         while_let,
1584         width,
1585         windows,
1586         windows_subsystem,
1587         with_negative_coherence,
1588         wrapping_add,
1589         wrapping_mul,
1590         wrapping_sub,
1591         wreg,
1592         write_bytes,
1593         write_macro,
1594         write_str,
1595         writeln_macro,
1596         x87_reg,
1597         xer,
1598         xmm_reg,
1599         yeet_desugar_details,
1600         yeet_expr,
1601         ymm_reg,
1602         zmm_reg,
1603     }
1604 }
1605
1606 #[derive(Copy, Clone, Eq, HashStable_Generic, Encodable, Decodable)]
1607 pub struct Ident {
1608     pub name: Symbol,
1609     pub span: Span,
1610 }
1611
1612 impl Ident {
1613     #[inline]
1614     /// Constructs a new identifier from a symbol and a span.
1615     pub const fn new(name: Symbol, span: Span) -> Ident {
1616         Ident { name, span }
1617     }
1618
1619     /// Constructs a new identifier with a dummy span.
1620     #[inline]
1621     pub const fn with_dummy_span(name: Symbol) -> Ident {
1622         Ident::new(name, DUMMY_SP)
1623     }
1624
1625     #[inline]
1626     pub fn empty() -> Ident {
1627         Ident::with_dummy_span(kw::Empty)
1628     }
1629
1630     /// Maps a string to an identifier with a dummy span.
1631     pub fn from_str(string: &str) -> Ident {
1632         Ident::with_dummy_span(Symbol::intern(string))
1633     }
1634
1635     /// Maps a string and a span to an identifier.
1636     pub fn from_str_and_span(string: &str, span: Span) -> Ident {
1637         Ident::new(Symbol::intern(string), span)
1638     }
1639
1640     /// Replaces `lo` and `hi` with those from `span`, but keep hygiene context.
1641     pub fn with_span_pos(self, span: Span) -> Ident {
1642         Ident::new(self.name, span.with_ctxt(self.span.ctxt()))
1643     }
1644
1645     pub fn without_first_quote(self) -> Ident {
1646         Ident::new(Symbol::intern(self.as_str().trim_start_matches('\'')), self.span)
1647     }
1648
1649     /// "Normalize" ident for use in comparisons using "item hygiene".
1650     /// Identifiers with same string value become same if they came from the same macro 2.0 macro
1651     /// (e.g., `macro` item, but not `macro_rules` item) and stay different if they came from
1652     /// different macro 2.0 macros.
1653     /// Technically, this operation strips all non-opaque marks from ident's syntactic context.
1654     pub fn normalize_to_macros_2_0(self) -> Ident {
1655         Ident::new(self.name, self.span.normalize_to_macros_2_0())
1656     }
1657
1658     /// "Normalize" ident for use in comparisons using "local variable hygiene".
1659     /// Identifiers with same string value become same if they came from the same non-transparent
1660     /// macro (e.g., `macro` or `macro_rules!` items) and stay different if they came from different
1661     /// non-transparent macros.
1662     /// Technically, this operation strips all transparent marks from ident's syntactic context.
1663     pub fn normalize_to_macro_rules(self) -> Ident {
1664         Ident::new(self.name, self.span.normalize_to_macro_rules())
1665     }
1666
1667     /// Access the underlying string. This is a slowish operation because it
1668     /// requires locking the symbol interner.
1669     ///
1670     /// Note that the lifetime of the return value is a lie. See
1671     /// `Symbol::as_str()` for details.
1672     pub fn as_str(&self) -> &str {
1673         self.name.as_str()
1674     }
1675 }
1676
1677 impl PartialEq for Ident {
1678     fn eq(&self, rhs: &Self) -> bool {
1679         self.name == rhs.name && self.span.eq_ctxt(rhs.span)
1680     }
1681 }
1682
1683 impl Hash for Ident {
1684     fn hash<H: Hasher>(&self, state: &mut H) {
1685         self.name.hash(state);
1686         self.span.ctxt().hash(state);
1687     }
1688 }
1689
1690 impl fmt::Debug for Ident {
1691     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1692         fmt::Display::fmt(self, f)?;
1693         fmt::Debug::fmt(&self.span.ctxt(), f)
1694     }
1695 }
1696
1697 /// This implementation is supposed to be used in error messages, so it's expected to be identical
1698 /// to printing the original identifier token written in source code (`token_to_string`),
1699 /// except that AST identifiers don't keep the rawness flag, so we have to guess it.
1700 impl fmt::Display for Ident {
1701     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1702         fmt::Display::fmt(&IdentPrinter::new(self.name, self.is_raw_guess(), None), f)
1703     }
1704 }
1705
1706 /// This is the most general way to print identifiers.
1707 /// AST pretty-printer is used as a fallback for turning AST structures into token streams for
1708 /// proc macros. Additionally, proc macros may stringify their input and expect it survive the
1709 /// stringification (especially true for proc macro derives written between Rust 1.15 and 1.30).
1710 /// So we need to somehow pretty-print `$crate` in a way preserving at least some of its
1711 /// hygiene data, most importantly name of the crate it refers to.
1712 /// As a result we print `$crate` as `crate` if it refers to the local crate
1713 /// and as `::other_crate_name` if it refers to some other crate.
1714 /// Note, that this is only done if the ident token is printed from inside of AST pretty-printing,
1715 /// but not otherwise. Pretty-printing is the only way for proc macros to discover token contents,
1716 /// so we should not perform this lossy conversion if the top level call to the pretty-printer was
1717 /// done for a token stream or a single token.
1718 pub struct IdentPrinter {
1719     symbol: Symbol,
1720     is_raw: bool,
1721     /// Span used for retrieving the crate name to which `$crate` refers to,
1722     /// if this field is `None` then the `$crate` conversion doesn't happen.
1723     convert_dollar_crate: Option<Span>,
1724 }
1725
1726 impl IdentPrinter {
1727     /// The most general `IdentPrinter` constructor. Do not use this.
1728     pub fn new(symbol: Symbol, is_raw: bool, convert_dollar_crate: Option<Span>) -> IdentPrinter {
1729         IdentPrinter { symbol, is_raw, convert_dollar_crate }
1730     }
1731
1732     /// This implementation is supposed to be used when printing identifiers
1733     /// as a part of pretty-printing for larger AST pieces.
1734     /// Do not use this either.
1735     pub fn for_ast_ident(ident: Ident, is_raw: bool) -> IdentPrinter {
1736         IdentPrinter::new(ident.name, is_raw, Some(ident.span))
1737     }
1738 }
1739
1740 impl fmt::Display for IdentPrinter {
1741     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1742         if self.is_raw {
1743             f.write_str("r#")?;
1744         } else if self.symbol == kw::DollarCrate {
1745             if let Some(span) = self.convert_dollar_crate {
1746                 let converted = span.ctxt().dollar_crate_name();
1747                 if !converted.is_path_segment_keyword() {
1748                     f.write_str("::")?;
1749                 }
1750                 return fmt::Display::fmt(&converted, f);
1751             }
1752         }
1753         fmt::Display::fmt(&self.symbol, f)
1754     }
1755 }
1756
1757 /// An newtype around `Ident` that calls [Ident::normalize_to_macro_rules] on
1758 /// construction.
1759 // FIXME(matthewj, petrochenkov) Use this more often, add a similar
1760 // `ModernIdent` struct and use that as well.
1761 #[derive(Copy, Clone, Eq, PartialEq, Hash)]
1762 pub struct MacroRulesNormalizedIdent(Ident);
1763
1764 impl MacroRulesNormalizedIdent {
1765     pub fn new(ident: Ident) -> Self {
1766         Self(ident.normalize_to_macro_rules())
1767     }
1768 }
1769
1770 impl fmt::Debug for MacroRulesNormalizedIdent {
1771     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1772         fmt::Debug::fmt(&self.0, f)
1773     }
1774 }
1775
1776 impl fmt::Display for MacroRulesNormalizedIdent {
1777     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1778         fmt::Display::fmt(&self.0, f)
1779     }
1780 }
1781
1782 /// An interned string.
1783 ///
1784 /// Internally, a `Symbol` is implemented as an index, and all operations
1785 /// (including hashing, equality, and ordering) operate on that index. The use
1786 /// of `rustc_index::newtype_index!` means that `Option<Symbol>` only takes up 4 bytes,
1787 /// because `rustc_index::newtype_index!` reserves the last 256 values for tagging purposes.
1788 ///
1789 /// Note that `Symbol` cannot directly be a `rustc_index::newtype_index!` because it
1790 /// implements `fmt::Debug`, `Encodable`, and `Decodable` in special ways.
1791 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
1792 pub struct Symbol(SymbolIndex);
1793
1794 rustc_index::newtype_index! {
1795     struct SymbolIndex { .. }
1796 }
1797
1798 impl Symbol {
1799     const fn new(n: u32) -> Self {
1800         Symbol(SymbolIndex::from_u32(n))
1801     }
1802
1803     /// Maps a string to its interned representation.
1804     pub fn intern(string: &str) -> Self {
1805         with_session_globals(|session_globals| session_globals.symbol_interner.intern(string))
1806     }
1807
1808     /// Access the underlying string. This is a slowish operation because it
1809     /// requires locking the symbol interner.
1810     ///
1811     /// Note that the lifetime of the return value is a lie. It's not the same
1812     /// as `&self`, but actually tied to the lifetime of the underlying
1813     /// interner. Interners are long-lived, and there are very few of them, and
1814     /// this function is typically used for short-lived things, so in practice
1815     /// it works out ok.
1816     pub fn as_str(&self) -> &str {
1817         with_session_globals(|session_globals| unsafe {
1818             std::mem::transmute::<&str, &str>(session_globals.symbol_interner.get(*self))
1819         })
1820     }
1821
1822     pub fn as_u32(self) -> u32 {
1823         self.0.as_u32()
1824     }
1825
1826     pub fn is_empty(self) -> bool {
1827         self == kw::Empty
1828     }
1829
1830     /// This method is supposed to be used in error messages, so it's expected to be
1831     /// identical to printing the original identifier token written in source code
1832     /// (`token_to_string`, `Ident::to_string`), except that symbols don't keep the rawness flag
1833     /// or edition, so we have to guess the rawness using the global edition.
1834     pub fn to_ident_string(self) -> String {
1835         Ident::with_dummy_span(self).to_string()
1836     }
1837 }
1838
1839 impl fmt::Debug for Symbol {
1840     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1841         fmt::Debug::fmt(self.as_str(), f)
1842     }
1843 }
1844
1845 impl fmt::Display for Symbol {
1846     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1847         fmt::Display::fmt(self.as_str(), f)
1848     }
1849 }
1850
1851 impl<S: Encoder> Encodable<S> for Symbol {
1852     fn encode(&self, s: &mut S) {
1853         s.emit_str(self.as_str());
1854     }
1855 }
1856
1857 impl<D: Decoder> Decodable<D> for Symbol {
1858     #[inline]
1859     fn decode(d: &mut D) -> Symbol {
1860         Symbol::intern(&d.read_str())
1861     }
1862 }
1863
1864 impl<CTX> HashStable<CTX> for Symbol {
1865     #[inline]
1866     fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
1867         self.as_str().hash_stable(hcx, hasher);
1868     }
1869 }
1870
1871 impl<CTX> ToStableHashKey<CTX> for Symbol {
1872     type KeyType = String;
1873     #[inline]
1874     fn to_stable_hash_key(&self, _: &CTX) -> String {
1875         self.as_str().to_string()
1876     }
1877 }
1878
1879 #[derive(Default)]
1880 pub(crate) struct Interner(Lock<InternerInner>);
1881
1882 // The `&'static str`s in this type actually point into the arena.
1883 //
1884 // The `FxHashMap`+`Vec` pair could be replaced by `FxIndexSet`, but #75278
1885 // found that to regress performance up to 2% in some cases. This might be
1886 // revisited after further improvements to `indexmap`.
1887 //
1888 // This type is private to prevent accidentally constructing more than one
1889 // `Interner` on the same thread, which makes it easy to mix up `Symbol`s
1890 // between `Interner`s.
1891 #[derive(Default)]
1892 struct InternerInner {
1893     arena: DroplessArena,
1894     names: FxHashMap<&'static str, Symbol>,
1895     strings: Vec<&'static str>,
1896 }
1897
1898 impl Interner {
1899     fn prefill(init: &[&'static str]) -> Self {
1900         Interner(Lock::new(InternerInner {
1901             strings: init.into(),
1902             names: init.iter().copied().zip((0..).map(Symbol::new)).collect(),
1903             ..Default::default()
1904         }))
1905     }
1906
1907     #[inline]
1908     fn intern(&self, string: &str) -> Symbol {
1909         let mut inner = self.0.lock();
1910         if let Some(&name) = inner.names.get(string) {
1911             return name;
1912         }
1913
1914         let name = Symbol::new(inner.strings.len() as u32);
1915
1916         // SAFETY: we convert from `&str` to `&[u8]`, clone it into the arena,
1917         // and immediately convert the clone back to `&[u8], all because there
1918         // is no `inner.arena.alloc_str()` method. This is clearly safe.
1919         let string: &str =
1920             unsafe { str::from_utf8_unchecked(inner.arena.alloc_slice(string.as_bytes())) };
1921
1922         // SAFETY: we can extend the arena allocation to `'static` because we
1923         // only access these while the arena is still alive.
1924         let string: &'static str = unsafe { &*(string as *const str) };
1925         inner.strings.push(string);
1926
1927         // This second hash table lookup can be avoided by using `RawEntryMut`,
1928         // but this code path isn't hot enough for it to be worth it. See
1929         // #91445 for details.
1930         inner.names.insert(string, name);
1931         name
1932     }
1933
1934     // Get the symbol as a string. `Symbol::as_str()` should be used in
1935     // preference to this function.
1936     fn get(&self, symbol: Symbol) -> &str {
1937         self.0.lock().strings[symbol.0.as_usize()]
1938     }
1939 }
1940
1941 // This module has a very short name because it's used a lot.
1942 /// This module contains all the defined keyword `Symbol`s.
1943 ///
1944 /// Given that `kw` is imported, use them like `kw::keyword_name`.
1945 /// For example `kw::Loop` or `kw::Break`.
1946 pub mod kw {
1947     pub use super::kw_generated::*;
1948 }
1949
1950 // This module has a very short name because it's used a lot.
1951 /// This module contains all the defined non-keyword `Symbol`s.
1952 ///
1953 /// Given that `sym` is imported, use them like `sym::symbol_name`.
1954 /// For example `sym::rustfmt` or `sym::u8`.
1955 pub mod sym {
1956     use super::Symbol;
1957     use std::convert::TryInto;
1958
1959     #[doc(inline)]
1960     pub use super::sym_generated::*;
1961
1962     // Used from a macro in `librustc_feature/accepted.rs`
1963     pub use super::kw::MacroRules as macro_rules;
1964
1965     /// Get the symbol for an integer.
1966     ///
1967     /// The first few non-negative integers each have a static symbol and therefore
1968     /// are fast.
1969     pub fn integer<N: TryInto<usize> + Copy + ToString>(n: N) -> Symbol {
1970         if let Result::Ok(idx) = n.try_into() {
1971             if idx < 10 {
1972                 return Symbol::new(super::SYMBOL_DIGITS_BASE + idx as u32);
1973             }
1974         }
1975         Symbol::intern(&n.to_string())
1976     }
1977 }
1978
1979 impl Symbol {
1980     fn is_special(self) -> bool {
1981         self <= kw::Underscore
1982     }
1983
1984     fn is_used_keyword_always(self) -> bool {
1985         self >= kw::As && self <= kw::While
1986     }
1987
1988     fn is_used_keyword_conditional(self, edition: impl FnOnce() -> Edition) -> bool {
1989         (self >= kw::Async && self <= kw::Dyn) && edition() >= Edition::Edition2018
1990     }
1991
1992     fn is_unused_keyword_always(self) -> bool {
1993         self >= kw::Abstract && self <= kw::Yield
1994     }
1995
1996     fn is_unused_keyword_conditional(self, edition: impl FnOnce() -> Edition) -> bool {
1997         self == kw::Try && edition() >= Edition::Edition2018
1998     }
1999
2000     pub fn is_reserved(self, edition: impl Copy + FnOnce() -> Edition) -> bool {
2001         self.is_special()
2002             || self.is_used_keyword_always()
2003             || self.is_unused_keyword_always()
2004             || self.is_used_keyword_conditional(edition)
2005             || self.is_unused_keyword_conditional(edition)
2006     }
2007
2008     /// A keyword or reserved identifier that can be used as a path segment.
2009     pub fn is_path_segment_keyword(self) -> bool {
2010         self == kw::Super
2011             || self == kw::SelfLower
2012             || self == kw::SelfUpper
2013             || self == kw::Crate
2014             || self == kw::PathRoot
2015             || self == kw::DollarCrate
2016     }
2017
2018     /// Returns `true` if the symbol is `true` or `false`.
2019     pub fn is_bool_lit(self) -> bool {
2020         self == kw::True || self == kw::False
2021     }
2022
2023     /// Returns `true` if this symbol can be a raw identifier.
2024     pub fn can_be_raw(self) -> bool {
2025         self != kw::Empty && self != kw::Underscore && !self.is_path_segment_keyword()
2026     }
2027 }
2028
2029 impl Ident {
2030     // Returns `true` for reserved identifiers used internally for elided lifetimes,
2031     // unnamed method parameters, crate root module, error recovery etc.
2032     pub fn is_special(self) -> bool {
2033         self.name.is_special()
2034     }
2035
2036     /// Returns `true` if the token is a keyword used in the language.
2037     pub fn is_used_keyword(self) -> bool {
2038         // Note: `span.edition()` is relatively expensive, don't call it unless necessary.
2039         self.name.is_used_keyword_always()
2040             || self.name.is_used_keyword_conditional(|| self.span.edition())
2041     }
2042
2043     /// Returns `true` if the token is a keyword reserved for possible future use.
2044     pub fn is_unused_keyword(self) -> bool {
2045         // Note: `span.edition()` is relatively expensive, don't call it unless necessary.
2046         self.name.is_unused_keyword_always()
2047             || self.name.is_unused_keyword_conditional(|| self.span.edition())
2048     }
2049
2050     /// Returns `true` if the token is either a special identifier or a keyword.
2051     pub fn is_reserved(self) -> bool {
2052         // Note: `span.edition()` is relatively expensive, don't call it unless necessary.
2053         self.name.is_reserved(|| self.span.edition())
2054     }
2055
2056     /// A keyword or reserved identifier that can be used as a path segment.
2057     pub fn is_path_segment_keyword(self) -> bool {
2058         self.name.is_path_segment_keyword()
2059     }
2060
2061     /// We see this identifier in a normal identifier position, like variable name or a type.
2062     /// How was it written originally? Did it use the raw form? Let's try to guess.
2063     pub fn is_raw_guess(self) -> bool {
2064         self.name.can_be_raw() && self.is_reserved()
2065     }
2066 }