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