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