]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_span/src/symbol.rs
Rollup merge of #105904 - MarcusCalhoun-Lopez:darwin_arch_i386, r=bjorn3
[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         Continue,
168         Copy,
169         Count,
170         Cow,
171         Debug,
172         Decodable,
173         Decoder,
174         DecorateLint,
175         Default,
176         Deref,
177         DiagnosticMessage,
178         DirBuilder,
179         Display,
180         DoubleEndedIterator,
181         Duration,
182         Encodable,
183         Encoder,
184         Eq,
185         Equal,
186         Err,
187         Error,
188         File,
189         FileType,
190         FormatSpec,
191         Formatter,
192         From,
193         FromIterator,
194         FromResidual,
195         Future,
196         FxHashMap,
197         FxHashSet,
198         GlobalAlloc,
199         Hash,
200         HashMap,
201         HashMapEntry,
202         HashSet,
203         Hasher,
204         Implied,
205         Input,
206         Into,
207         IntoDiagnostic,
208         IntoIterator,
209         IoRead,
210         IoWrite,
211         IpAddr,
212         IrTyKind,
213         Is,
214         ItemContext,
215         Iterator,
216         Layout,
217         Left,
218         LinkedList,
219         LintPass,
220         LocalKey,
221         Mutex,
222         MutexGuard,
223         N,
224         NonZeroI128,
225         NonZeroI16,
226         NonZeroI32,
227         NonZeroI64,
228         NonZeroI8,
229         NonZeroU128,
230         NonZeroU16,
231         NonZeroU32,
232         NonZeroU64,
233         NonZeroU8,
234         None,
235         Ok,
236         Option,
237         Ord,
238         Ordering,
239         OsStr,
240         OsString,
241         Output,
242         Param,
243         PartialEq,
244         PartialOrd,
245         Path,
246         PathBuf,
247         Pending,
248         Pin,
249         Pointer,
250         Poll,
251         ProcMacro,
252         ProceduralMasqueradeDummyType,
253         Range,
254         RangeFrom,
255         RangeFull,
256         RangeInclusive,
257         RangeTo,
258         RangeToInclusive,
259         Rc,
260         Ready,
261         Receiver,
262         RefCell,
263         Relaxed,
264         Release,
265         Result,
266         ResumeTy,
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         get_context,
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         iterator_collect_fn,
832         kcfi,
833         keyword,
834         kind,
835         kreg,
836         kreg0,
837         label,
838         label_break_value,
839         lang,
840         lang_items,
841         large_assignments,
842         lateout,
843         lazy_normalization_consts,
844         le,
845         len,
846         let_chains,
847         let_else,
848         lhs,
849         lib,
850         libc,
851         lifetime,
852         lifetimes,
853         likely,
854         line,
855         link,
856         link_args,
857         link_cfg,
858         link_llvm_intrinsics,
859         link_name,
860         link_ordinal,
861         link_section,
862         linkage,
863         linker,
864         lint_reasons,
865         literal,
866         load,
867         loaded_from_disk,
868         local,
869         local_inner_macros,
870         log10f32,
871         log10f64,
872         log2f32,
873         log2f64,
874         log_syntax,
875         logf32,
876         logf64,
877         loop_break_value,
878         lt,
879         macro_at_most_once_rep,
880         macro_attributes_in_derive_output,
881         macro_escape,
882         macro_export,
883         macro_lifetime_matcher,
884         macro_literal_matcher,
885         macro_metavar_expr,
886         macro_reexport,
887         macro_use,
888         macro_vis_matcher,
889         macros_in_extern,
890         main,
891         managed_boxes,
892         manually_drop,
893         map,
894         marker,
895         marker_trait_attr,
896         masked,
897         match_beginning_vert,
898         match_default_bindings,
899         matches_macro,
900         maxnumf32,
901         maxnumf64,
902         may_dangle,
903         may_unwind,
904         maybe_uninit,
905         maybe_uninit_uninit,
906         maybe_uninit_zeroed,
907         mem_discriminant,
908         mem_drop,
909         mem_forget,
910         mem_replace,
911         mem_size_of,
912         mem_size_of_val,
913         mem_uninitialized,
914         mem_variant_count,
915         mem_zeroed,
916         member_constraints,
917         memory,
918         memtag,
919         message,
920         meta,
921         metadata_type,
922         min_align_of,
923         min_align_of_val,
924         min_const_fn,
925         min_const_generics,
926         min_const_unsafe_fn,
927         min_specialization,
928         min_type_alias_impl_trait,
929         minnumf32,
930         minnumf64,
931         mips_target_feature,
932         miri,
933         misc,
934         mmx_reg,
935         modifiers,
936         module,
937         module_path,
938         more_qualified_paths,
939         more_struct_aliases,
940         movbe_target_feature,
941         move_ref_pattern,
942         move_size_limit,
943         mul,
944         mul_assign,
945         mul_with_overflow,
946         must_not_suspend,
947         must_use,
948         naked,
949         naked_functions,
950         name,
951         names,
952         native_link_modifiers,
953         native_link_modifiers_as_needed,
954         native_link_modifiers_bundle,
955         native_link_modifiers_verbatim,
956         native_link_modifiers_whole_archive,
957         natvis_file,
958         ne,
959         nearbyintf32,
960         nearbyintf64,
961         needs_allocator,
962         needs_drop,
963         needs_panic_runtime,
964         neg,
965         negate_unsigned,
966         negative_impls,
967         neon,
968         never,
969         never_type,
970         never_type_fallback,
971         new,
972         new_binary,
973         new_debug,
974         new_display,
975         new_lower_exp,
976         new_lower_hex,
977         new_octal,
978         new_pointer,
979         new_unchecked,
980         new_upper_exp,
981         new_upper_hex,
982         new_v1,
983         new_v1_formatted,
984         next,
985         nll,
986         no,
987         no_builtins,
988         no_core,
989         no_coverage,
990         no_crate_inject,
991         no_debug,
992         no_default_passes,
993         no_implicit_prelude,
994         no_inline,
995         no_link,
996         no_main,
997         no_mangle,
998         no_sanitize,
999         no_stack_check,
1000         no_start,
1001         no_std,
1002         nomem,
1003         non_ascii_idents,
1004         non_exhaustive,
1005         non_exhaustive_omitted_patterns_lint,
1006         non_modrs_mods,
1007         nontemporal_store,
1008         noop_method_borrow,
1009         noop_method_clone,
1010         noop_method_deref,
1011         noreturn,
1012         nostack,
1013         not,
1014         notable_trait,
1015         note,
1016         object_safe_for_dispatch,
1017         of,
1018         offset,
1019         omit_gdb_pretty_printer_section,
1020         on,
1021         on_unimplemented,
1022         oom,
1023         opaque,
1024         ops,
1025         opt_out_copy,
1026         optimize,
1027         optimize_attribute,
1028         optin_builtin_traits,
1029         option,
1030         option_env,
1031         options,
1032         or,
1033         or_patterns,
1034         other,
1035         out,
1036         overlapping_marker_traits,
1037         owned_box,
1038         packed,
1039         panic,
1040         panic_2015,
1041         panic_2021,
1042         panic_abort,
1043         panic_bounds_check,
1044         panic_display,
1045         panic_fmt,
1046         panic_handler,
1047         panic_impl,
1048         panic_implementation,
1049         panic_info,
1050         panic_location,
1051         panic_no_unwind,
1052         panic_runtime,
1053         panic_str,
1054         panic_unwind,
1055         panicking,
1056         param_attrs,
1057         parent_label,
1058         partial_cmp,
1059         partial_ord,
1060         passes,
1061         pat,
1062         pat_param,
1063         path,
1064         pattern_parentheses,
1065         phantom_data,
1066         pin,
1067         platform_intrinsics,
1068         plugin,
1069         plugin_registrar,
1070         plugins,
1071         pointee_trait,
1072         pointer,
1073         pointer_sized,
1074         poll,
1075         position,
1076         post_dash_lto: "post-lto",
1077         powerpc_target_feature,
1078         powf32,
1079         powf64,
1080         powif32,
1081         powif64,
1082         pre_dash_lto: "pre-lto",
1083         precise_pointer_size_matching,
1084         precision,
1085         pref_align_of,
1086         prefetch_read_data,
1087         prefetch_read_instruction,
1088         prefetch_write_data,
1089         prefetch_write_instruction,
1090         preg,
1091         prelude,
1092         prelude_import,
1093         preserves_flags,
1094         primitive,
1095         print_macro,
1096         println_macro,
1097         proc_dash_macro: "proc-macro",
1098         proc_macro,
1099         proc_macro_attribute,
1100         proc_macro_derive,
1101         proc_macro_expr,
1102         proc_macro_gen,
1103         proc_macro_hygiene,
1104         proc_macro_internals,
1105         proc_macro_mod,
1106         proc_macro_non_items,
1107         proc_macro_path_invoc,
1108         profiler_builtins,
1109         profiler_runtime,
1110         ptr,
1111         ptr_guaranteed_cmp,
1112         ptr_mask,
1113         ptr_null,
1114         ptr_null_mut,
1115         ptr_offset_from,
1116         ptr_offset_from_unsigned,
1117         pub_macro_rules,
1118         pub_restricted,
1119         public,
1120         pure,
1121         pushpop_unsafe,
1122         qreg,
1123         qreg_low4,
1124         qreg_low8,
1125         quad_precision_float,
1126         question_mark,
1127         quote,
1128         range_inclusive_new,
1129         raw_dylib,
1130         raw_eq,
1131         raw_identifiers,
1132         raw_ref_op,
1133         re_rebalance_coherence,
1134         read_enum,
1135         read_enum_variant,
1136         read_enum_variant_arg,
1137         read_struct,
1138         read_struct_field,
1139         readonly,
1140         realloc,
1141         reason,
1142         receiver,
1143         recursion_limit,
1144         reexport_test_harness_main,
1145         ref_unwind_safe_trait,
1146         reference,
1147         reflect,
1148         reg,
1149         reg16,
1150         reg32,
1151         reg64,
1152         reg_abcd,
1153         reg_byte,
1154         reg_iw,
1155         reg_nonzero,
1156         reg_pair,
1157         reg_ptr,
1158         reg_upper,
1159         register_attr,
1160         register_tool,
1161         relaxed_adts,
1162         relaxed_struct_unsize,
1163         rem,
1164         rem_assign,
1165         repr,
1166         repr128,
1167         repr_align,
1168         repr_align_enum,
1169         repr_packed,
1170         repr_simd,
1171         repr_transparent,
1172         require,
1173         residual,
1174         result,
1175         return_position_impl_trait_in_trait,
1176         rhs,
1177         rintf32,
1178         rintf64,
1179         riscv_target_feature,
1180         rlib,
1181         rotate_left,
1182         rotate_right,
1183         roundf32,
1184         roundf64,
1185         rt,
1186         rtm_target_feature,
1187         rust,
1188         rust_2015,
1189         rust_2015_preview,
1190         rust_2018,
1191         rust_2018_preview,
1192         rust_2021,
1193         rust_2021_preview,
1194         rust_2024,
1195         rust_2024_preview,
1196         rust_begin_unwind,
1197         rust_cold_cc,
1198         rust_eh_catch_typeinfo,
1199         rust_eh_personality,
1200         rustc,
1201         rustc_allocator,
1202         rustc_allocator_zeroed,
1203         rustc_allow_const_fn_unstable,
1204         rustc_allow_incoherent_impl,
1205         rustc_allowed_through_unstable_modules,
1206         rustc_attrs,
1207         rustc_box,
1208         rustc_builtin_macro,
1209         rustc_capture_analysis,
1210         rustc_clean,
1211         rustc_coherence_is_core,
1212         rustc_const_stable,
1213         rustc_const_unstable,
1214         rustc_conversion_suggestion,
1215         rustc_deallocator,
1216         rustc_def_path,
1217         rustc_default_body_unstable,
1218         rustc_deny_explicit_impl,
1219         rustc_diagnostic_item,
1220         rustc_diagnostic_macros,
1221         rustc_dirty,
1222         rustc_do_not_const_check,
1223         rustc_dummy,
1224         rustc_dump_env_program_clauses,
1225         rustc_dump_program_clauses,
1226         rustc_dump_user_substs,
1227         rustc_dump_vtable,
1228         rustc_effective_visibility,
1229         rustc_error,
1230         rustc_evaluate_where_clauses,
1231         rustc_expected_cgu_reuse,
1232         rustc_has_incoherent_inherent_impls,
1233         rustc_if_this_changed,
1234         rustc_inherit_overflow_checks,
1235         rustc_insignificant_dtor,
1236         rustc_layout,
1237         rustc_layout_scalar_valid_range_end,
1238         rustc_layout_scalar_valid_range_start,
1239         rustc_legacy_const_generics,
1240         rustc_lint_diagnostics,
1241         rustc_lint_opt_deny_field_access,
1242         rustc_lint_opt_ty,
1243         rustc_lint_query_instability,
1244         rustc_macro_transparency,
1245         rustc_main,
1246         rustc_mir,
1247         rustc_must_implement_one_of,
1248         rustc_nonnull_optimization_guaranteed,
1249         rustc_nounwind,
1250         rustc_object_lifetime_default,
1251         rustc_on_unimplemented,
1252         rustc_outlives,
1253         rustc_paren_sugar,
1254         rustc_partition_codegened,
1255         rustc_partition_reused,
1256         rustc_pass_by_value,
1257         rustc_peek,
1258         rustc_peek_definite_init,
1259         rustc_peek_liveness,
1260         rustc_peek_maybe_init,
1261         rustc_peek_maybe_uninit,
1262         rustc_polymorphize_error,
1263         rustc_private,
1264         rustc_proc_macro_decls,
1265         rustc_promotable,
1266         rustc_reallocator,
1267         rustc_regions,
1268         rustc_reservation_impl,
1269         rustc_safe_intrinsic,
1270         rustc_serialize,
1271         rustc_skip_array_during_method_dispatch,
1272         rustc_specialization_trait,
1273         rustc_std_internal_symbol,
1274         rustc_strict_coherence,
1275         rustc_symbol_name,
1276         rustc_test_marker,
1277         rustc_then_this_would_need,
1278         rustc_trivial_field_reads,
1279         rustc_unsafe_specialization_marker,
1280         rustc_variance,
1281         rustdoc,
1282         rustdoc_internals,
1283         rustdoc_missing_doc_code_examples,
1284         rustfmt,
1285         rvalue_static_promotion,
1286         s,
1287         safety,
1288         sanitize,
1289         sanitizer_runtime,
1290         saturating_add,
1291         saturating_sub,
1292         self_in_typedefs,
1293         self_struct_ctor,
1294         semitransparent,
1295         shadow_call_stack,
1296         shl,
1297         shl_assign,
1298         should_panic,
1299         shr,
1300         shr_assign,
1301         sig_dfl,
1302         sig_ign,
1303         simd,
1304         simd_add,
1305         simd_and,
1306         simd_arith_offset,
1307         simd_as,
1308         simd_bitmask,
1309         simd_cast,
1310         simd_cast_ptr,
1311         simd_ceil,
1312         simd_div,
1313         simd_eq,
1314         simd_expose_addr,
1315         simd_extract,
1316         simd_fabs,
1317         simd_fcos,
1318         simd_fexp,
1319         simd_fexp2,
1320         simd_ffi,
1321         simd_flog,
1322         simd_flog10,
1323         simd_flog2,
1324         simd_floor,
1325         simd_fma,
1326         simd_fmax,
1327         simd_fmin,
1328         simd_fpow,
1329         simd_fpowi,
1330         simd_from_exposed_addr,
1331         simd_fsin,
1332         simd_fsqrt,
1333         simd_gather,
1334         simd_ge,
1335         simd_gt,
1336         simd_insert,
1337         simd_le,
1338         simd_lt,
1339         simd_mul,
1340         simd_ne,
1341         simd_neg,
1342         simd_or,
1343         simd_reduce_add_ordered,
1344         simd_reduce_add_unordered,
1345         simd_reduce_all,
1346         simd_reduce_and,
1347         simd_reduce_any,
1348         simd_reduce_max,
1349         simd_reduce_max_nanless,
1350         simd_reduce_min,
1351         simd_reduce_min_nanless,
1352         simd_reduce_mul_ordered,
1353         simd_reduce_mul_unordered,
1354         simd_reduce_or,
1355         simd_reduce_xor,
1356         simd_rem,
1357         simd_round,
1358         simd_saturating_add,
1359         simd_saturating_sub,
1360         simd_scatter,
1361         simd_select,
1362         simd_select_bitmask,
1363         simd_shl,
1364         simd_shr,
1365         simd_shuffle,
1366         simd_sub,
1367         simd_trunc,
1368         simd_xor,
1369         since,
1370         sinf32,
1371         sinf64,
1372         size,
1373         size_of,
1374         size_of_val,
1375         sized,
1376         skip,
1377         slice,
1378         slice_len_fn,
1379         slice_patterns,
1380         slicing_syntax,
1381         soft,
1382         specialization,
1383         speed,
1384         spotlight,
1385         sqrtf32,
1386         sqrtf64,
1387         sreg,
1388         sreg_low16,
1389         sse,
1390         sse4a_target_feature,
1391         stable,
1392         staged_api,
1393         start,
1394         state,
1395         static_in_const,
1396         static_nobundle,
1397         static_recursion,
1398         staticlib,
1399         std,
1400         std_panic,
1401         std_panic_2015_macro,
1402         std_panic_macro,
1403         stmt,
1404         stmt_expr_attributes,
1405         stop_after_dataflow,
1406         store,
1407         str,
1408         str_split_whitespace,
1409         str_trim,
1410         str_trim_end,
1411         str_trim_start,
1412         strict_provenance,
1413         string_deref_patterns,
1414         stringify,
1415         struct_field_attributes,
1416         struct_inherit,
1417         struct_variant,
1418         structural_match,
1419         structural_peq,
1420         structural_teq,
1421         sty,
1422         sub,
1423         sub_assign,
1424         sub_with_overflow,
1425         suggestion,
1426         sym,
1427         sync,
1428         t32,
1429         target,
1430         target_abi,
1431         target_arch,
1432         target_endian,
1433         target_env,
1434         target_family,
1435         target_feature,
1436         target_feature_11,
1437         target_has_atomic,
1438         target_has_atomic_equal_alignment,
1439         target_has_atomic_load_store,
1440         target_os,
1441         target_pointer_width,
1442         target_thread_local,
1443         target_vendor,
1444         tbm_target_feature,
1445         termination,
1446         termination_trait,
1447         termination_trait_test,
1448         test,
1449         test_2018_feature,
1450         test_accepted_feature,
1451         test_case,
1452         test_removed_feature,
1453         test_runner,
1454         test_unstable_lint,
1455         thread,
1456         thread_local,
1457         thread_local_macro,
1458         thumb2,
1459         thumb_mode: "thumb-mode",
1460         tmm_reg,
1461         to_string,
1462         to_vec,
1463         todo_macro,
1464         tool_attributes,
1465         tool_lints,
1466         trace_macros,
1467         track_caller,
1468         trait_alias,
1469         trait_upcasting,
1470         transmute,
1471         transmute_opts,
1472         transmute_trait,
1473         transparent,
1474         transparent_enums,
1475         transparent_unions,
1476         trivial_bounds,
1477         truncf32,
1478         truncf64,
1479         try_blocks,
1480         try_capture,
1481         try_from,
1482         try_into,
1483         try_trait_v2,
1484         tt,
1485         tuple,
1486         tuple_indexing,
1487         tuple_trait,
1488         two_phase,
1489         ty,
1490         type_alias_enum_variants,
1491         type_alias_impl_trait,
1492         type_ascribe,
1493         type_ascription,
1494         type_changing_struct_update,
1495         type_id,
1496         type_length_limit,
1497         type_macros,
1498         type_name,
1499         u128,
1500         u16,
1501         u32,
1502         u64,
1503         u8,
1504         unaligned_volatile_load,
1505         unaligned_volatile_store,
1506         unboxed_closures,
1507         unchecked_add,
1508         unchecked_div,
1509         unchecked_mul,
1510         unchecked_rem,
1511         unchecked_shl,
1512         unchecked_shr,
1513         unchecked_sub,
1514         underscore_const_names,
1515         underscore_imports,
1516         underscore_lifetimes,
1517         uniform_paths,
1518         unimplemented_macro,
1519         unit,
1520         universal_impl_trait,
1521         unix,
1522         unix_sigpipe,
1523         unlikely,
1524         unmarked_api,
1525         unpin,
1526         unreachable,
1527         unreachable_2015,
1528         unreachable_2015_macro,
1529         unreachable_2021,
1530         unreachable_code,
1531         unreachable_display,
1532         unreachable_macro,
1533         unrestricted_attribute_tokens,
1534         unsafe_block_in_unsafe_fn,
1535         unsafe_cell,
1536         unsafe_no_drop_flag,
1537         unsafe_pin_internals,
1538         unsize,
1539         unsized_fn_params,
1540         unsized_locals,
1541         unsized_tuple_coercion,
1542         unstable,
1543         unstable_location_reason_default: "this crate is being loaded from the sysroot, an \
1544                           unstable location; did you mean to load this crate \
1545                           from crates.io via `Cargo.toml` instead?",
1546         untagged_unions,
1547         unused_imports,
1548         unwind,
1549         unwind_attributes,
1550         unwind_safe_trait,
1551         unwrap,
1552         unwrap_or,
1553         use_extern_macros,
1554         use_nested_groups,
1555         used,
1556         used_with_arg,
1557         using,
1558         usize,
1559         v1,
1560         va_arg,
1561         va_copy,
1562         va_end,
1563         va_list,
1564         va_start,
1565         val,
1566         validity,
1567         values,
1568         var,
1569         variant_count,
1570         vec,
1571         vec_macro,
1572         version,
1573         vfp2,
1574         vis,
1575         visible_private_types,
1576         volatile,
1577         volatile_copy_memory,
1578         volatile_copy_nonoverlapping_memory,
1579         volatile_load,
1580         volatile_set_memory,
1581         volatile_store,
1582         vreg,
1583         vreg_low16,
1584         vtable_align,
1585         vtable_size,
1586         warn,
1587         wasm_abi,
1588         wasm_import_module,
1589         wasm_target_feature,
1590         while_let,
1591         width,
1592         windows,
1593         windows_subsystem,
1594         with_negative_coherence,
1595         wrapping_add,
1596         wrapping_mul,
1597         wrapping_sub,
1598         wreg,
1599         write_bytes,
1600         write_macro,
1601         write_str,
1602         writeln_macro,
1603         x87_reg,
1604         xer,
1605         xmm_reg,
1606         yeet_desugar_details,
1607         yeet_expr,
1608         ymm_reg,
1609         zmm_reg,
1610     }
1611 }
1612
1613 #[derive(Copy, Clone, Eq, HashStable_Generic, Encodable, Decodable)]
1614 pub struct Ident {
1615     pub name: Symbol,
1616     pub span: Span,
1617 }
1618
1619 impl Ident {
1620     #[inline]
1621     /// Constructs a new identifier from a symbol and a span.
1622     pub const fn new(name: Symbol, span: Span) -> Ident {
1623         Ident { name, span }
1624     }
1625
1626     /// Constructs a new identifier with a dummy span.
1627     #[inline]
1628     pub const fn with_dummy_span(name: Symbol) -> Ident {
1629         Ident::new(name, DUMMY_SP)
1630     }
1631
1632     #[inline]
1633     pub fn empty() -> Ident {
1634         Ident::with_dummy_span(kw::Empty)
1635     }
1636
1637     /// Maps a string to an identifier with a dummy span.
1638     pub fn from_str(string: &str) -> Ident {
1639         Ident::with_dummy_span(Symbol::intern(string))
1640     }
1641
1642     /// Maps a string and a span to an identifier.
1643     pub fn from_str_and_span(string: &str, span: Span) -> Ident {
1644         Ident::new(Symbol::intern(string), span)
1645     }
1646
1647     /// Replaces `lo` and `hi` with those from `span`, but keep hygiene context.
1648     pub fn with_span_pos(self, span: Span) -> Ident {
1649         Ident::new(self.name, span.with_ctxt(self.span.ctxt()))
1650     }
1651
1652     pub fn without_first_quote(self) -> Ident {
1653         Ident::new(Symbol::intern(self.as_str().trim_start_matches('\'')), self.span)
1654     }
1655
1656     /// "Normalize" ident for use in comparisons using "item hygiene".
1657     /// Identifiers with same string value become same if they came from the same macro 2.0 macro
1658     /// (e.g., `macro` item, but not `macro_rules` item) and stay different if they came from
1659     /// different macro 2.0 macros.
1660     /// Technically, this operation strips all non-opaque marks from ident's syntactic context.
1661     pub fn normalize_to_macros_2_0(self) -> Ident {
1662         Ident::new(self.name, self.span.normalize_to_macros_2_0())
1663     }
1664
1665     /// "Normalize" ident for use in comparisons using "local variable hygiene".
1666     /// Identifiers with same string value become same if they came from the same non-transparent
1667     /// macro (e.g., `macro` or `macro_rules!` items) and stay different if they came from different
1668     /// non-transparent macros.
1669     /// Technically, this operation strips all transparent marks from ident's syntactic context.
1670     #[inline]
1671     pub fn normalize_to_macro_rules(self) -> Ident {
1672         Ident::new(self.name, self.span.normalize_to_macro_rules())
1673     }
1674
1675     /// Access the underlying string. This is a slowish operation because it
1676     /// requires locking the symbol interner.
1677     ///
1678     /// Note that the lifetime of the return value is a lie. See
1679     /// `Symbol::as_str()` for details.
1680     pub fn as_str(&self) -> &str {
1681         self.name.as_str()
1682     }
1683 }
1684
1685 impl PartialEq for Ident {
1686     #[inline]
1687     fn eq(&self, rhs: &Self) -> bool {
1688         self.name == rhs.name && self.span.eq_ctxt(rhs.span)
1689     }
1690 }
1691
1692 impl Hash for Ident {
1693     fn hash<H: Hasher>(&self, state: &mut H) {
1694         self.name.hash(state);
1695         self.span.ctxt().hash(state);
1696     }
1697 }
1698
1699 impl fmt::Debug for Ident {
1700     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1701         fmt::Display::fmt(self, f)?;
1702         fmt::Debug::fmt(&self.span.ctxt(), f)
1703     }
1704 }
1705
1706 /// This implementation is supposed to be used in error messages, so it's expected to be identical
1707 /// to printing the original identifier token written in source code (`token_to_string`),
1708 /// except that AST identifiers don't keep the rawness flag, so we have to guess it.
1709 impl fmt::Display for Ident {
1710     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1711         fmt::Display::fmt(&IdentPrinter::new(self.name, self.is_raw_guess(), None), f)
1712     }
1713 }
1714
1715 /// The most general type to print identifiers.
1716 ///
1717 /// AST pretty-printer is used as a fallback for turning AST structures into token streams for
1718 /// proc macros. Additionally, proc macros may stringify their input and expect it survive the
1719 /// stringification (especially true for proc macro derives written between Rust 1.15 and 1.30).
1720 /// So we need to somehow pretty-print `$crate` in a way preserving at least some of its
1721 /// hygiene data, most importantly name of the crate it refers to.
1722 /// As a result we print `$crate` as `crate` if it refers to the local crate
1723 /// and as `::other_crate_name` if it refers to some other crate.
1724 /// Note, that this is only done if the ident token is printed from inside of AST pretty-printing,
1725 /// but not otherwise. Pretty-printing is the only way for proc macros to discover token contents,
1726 /// so we should not perform this lossy conversion if the top level call to the pretty-printer was
1727 /// done for a token stream or a single token.
1728 pub struct IdentPrinter {
1729     symbol: Symbol,
1730     is_raw: bool,
1731     /// Span used for retrieving the crate name to which `$crate` refers to,
1732     /// if this field is `None` then the `$crate` conversion doesn't happen.
1733     convert_dollar_crate: Option<Span>,
1734 }
1735
1736 impl IdentPrinter {
1737     /// The most general `IdentPrinter` constructor. Do not use this.
1738     pub fn new(symbol: Symbol, is_raw: bool, convert_dollar_crate: Option<Span>) -> IdentPrinter {
1739         IdentPrinter { symbol, is_raw, convert_dollar_crate }
1740     }
1741
1742     /// This implementation is supposed to be used when printing identifiers
1743     /// as a part of pretty-printing for larger AST pieces.
1744     /// Do not use this either.
1745     pub fn for_ast_ident(ident: Ident, is_raw: bool) -> IdentPrinter {
1746         IdentPrinter::new(ident.name, is_raw, Some(ident.span))
1747     }
1748 }
1749
1750 impl fmt::Display for IdentPrinter {
1751     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1752         if self.is_raw {
1753             f.write_str("r#")?;
1754         } else if self.symbol == kw::DollarCrate {
1755             if let Some(span) = self.convert_dollar_crate {
1756                 let converted = span.ctxt().dollar_crate_name();
1757                 if !converted.is_path_segment_keyword() {
1758                     f.write_str("::")?;
1759                 }
1760                 return fmt::Display::fmt(&converted, f);
1761             }
1762         }
1763         fmt::Display::fmt(&self.symbol, f)
1764     }
1765 }
1766
1767 /// An newtype around `Ident` that calls [Ident::normalize_to_macro_rules] on
1768 /// construction.
1769 // FIXME(matthewj, petrochenkov) Use this more often, add a similar
1770 // `ModernIdent` struct and use that as well.
1771 #[derive(Copy, Clone, Eq, PartialEq, Hash)]
1772 pub struct MacroRulesNormalizedIdent(Ident);
1773
1774 impl MacroRulesNormalizedIdent {
1775     pub fn new(ident: Ident) -> Self {
1776         Self(ident.normalize_to_macro_rules())
1777     }
1778 }
1779
1780 impl fmt::Debug for MacroRulesNormalizedIdent {
1781     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1782         fmt::Debug::fmt(&self.0, f)
1783     }
1784 }
1785
1786 impl fmt::Display for MacroRulesNormalizedIdent {
1787     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1788         fmt::Display::fmt(&self.0, f)
1789     }
1790 }
1791
1792 /// An interned string.
1793 ///
1794 /// Internally, a `Symbol` is implemented as an index, and all operations
1795 /// (including hashing, equality, and ordering) operate on that index. The use
1796 /// of `rustc_index::newtype_index!` means that `Option<Symbol>` only takes up 4 bytes,
1797 /// because `rustc_index::newtype_index!` reserves the last 256 values for tagging purposes.
1798 ///
1799 /// Note that `Symbol` cannot directly be a `rustc_index::newtype_index!` because it
1800 /// implements `fmt::Debug`, `Encodable`, and `Decodable` in special ways.
1801 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
1802 pub struct Symbol(SymbolIndex);
1803
1804 rustc_index::newtype_index! {
1805     struct SymbolIndex {}
1806 }
1807
1808 impl Symbol {
1809     const fn new(n: u32) -> Self {
1810         Symbol(SymbolIndex::from_u32(n))
1811     }
1812
1813     /// for use in Decoder only
1814     pub fn new_from_decoded(n: u32) -> Self {
1815         Self::new(n)
1816     }
1817
1818     /// Maps a string to its interned representation.
1819     pub fn intern(string: &str) -> Self {
1820         with_session_globals(|session_globals| session_globals.symbol_interner.intern(string))
1821     }
1822
1823     /// Access the underlying string. This is a slowish operation because it
1824     /// requires locking the symbol interner.
1825     ///
1826     /// Note that the lifetime of the return value is a lie. It's not the same
1827     /// as `&self`, but actually tied to the lifetime of the underlying
1828     /// interner. Interners are long-lived, and there are very few of them, and
1829     /// this function is typically used for short-lived things, so in practice
1830     /// it works out ok.
1831     pub fn as_str(&self) -> &str {
1832         with_session_globals(|session_globals| unsafe {
1833             std::mem::transmute::<&str, &str>(session_globals.symbol_interner.get(*self))
1834         })
1835     }
1836
1837     pub fn as_u32(self) -> u32 {
1838         self.0.as_u32()
1839     }
1840
1841     pub fn is_empty(self) -> bool {
1842         self == kw::Empty
1843     }
1844
1845     /// This method is supposed to be used in error messages, so it's expected to be
1846     /// identical to printing the original identifier token written in source code
1847     /// (`token_to_string`, `Ident::to_string`), except that symbols don't keep the rawness flag
1848     /// or edition, so we have to guess the rawness using the global edition.
1849     pub fn to_ident_string(self) -> String {
1850         Ident::with_dummy_span(self).to_string()
1851     }
1852 }
1853
1854 impl fmt::Debug for Symbol {
1855     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1856         fmt::Debug::fmt(self.as_str(), f)
1857     }
1858 }
1859
1860 impl fmt::Display for Symbol {
1861     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1862         fmt::Display::fmt(self.as_str(), f)
1863     }
1864 }
1865
1866 // takes advantage of `str::to_string` specialization
1867 impl ToString for Symbol {
1868     fn to_string(&self) -> String {
1869         self.as_str().to_string()
1870     }
1871 }
1872
1873 impl<S: Encoder> Encodable<S> for Symbol {
1874     default fn encode(&self, s: &mut S) {
1875         s.emit_str(self.as_str());
1876     }
1877 }
1878
1879 impl<D: Decoder> Decodable<D> for Symbol {
1880     #[inline]
1881     default fn decode(d: &mut D) -> Symbol {
1882         Symbol::intern(d.read_str())
1883     }
1884 }
1885
1886 impl<CTX> HashStable<CTX> for Symbol {
1887     #[inline]
1888     fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
1889         self.as_str().hash_stable(hcx, hasher);
1890     }
1891 }
1892
1893 impl<CTX> ToStableHashKey<CTX> for Symbol {
1894     type KeyType = String;
1895     #[inline]
1896     fn to_stable_hash_key(&self, _: &CTX) -> String {
1897         self.as_str().to_string()
1898     }
1899 }
1900
1901 #[derive(Default)]
1902 pub(crate) struct Interner(Lock<InternerInner>);
1903
1904 // The `&'static str`s in this type actually point into the arena.
1905 //
1906 // The `FxHashMap`+`Vec` pair could be replaced by `FxIndexSet`, but #75278
1907 // found that to regress performance up to 2% in some cases. This might be
1908 // revisited after further improvements to `indexmap`.
1909 //
1910 // This type is private to prevent accidentally constructing more than one
1911 // `Interner` on the same thread, which makes it easy to mix up `Symbol`s
1912 // between `Interner`s.
1913 #[derive(Default)]
1914 struct InternerInner {
1915     arena: DroplessArena,
1916     names: FxHashMap<&'static str, Symbol>,
1917     strings: Vec<&'static str>,
1918 }
1919
1920 impl Interner {
1921     fn prefill(init: &[&'static str]) -> Self {
1922         Interner(Lock::new(InternerInner {
1923             strings: init.into(),
1924             names: init.iter().copied().zip((0..).map(Symbol::new)).collect(),
1925             ..Default::default()
1926         }))
1927     }
1928
1929     #[inline]
1930     fn intern(&self, string: &str) -> Symbol {
1931         let mut inner = self.0.lock();
1932         if let Some(&name) = inner.names.get(string) {
1933             return name;
1934         }
1935
1936         let name = Symbol::new(inner.strings.len() as u32);
1937
1938         // SAFETY: we convert from `&str` to `&[u8]`, clone it into the arena,
1939         // and immediately convert the clone back to `&[u8], all because there
1940         // is no `inner.arena.alloc_str()` method. This is clearly safe.
1941         let string: &str =
1942             unsafe { str::from_utf8_unchecked(inner.arena.alloc_slice(string.as_bytes())) };
1943
1944         // SAFETY: we can extend the arena allocation to `'static` because we
1945         // only access these while the arena is still alive.
1946         let string: &'static str = unsafe { &*(string as *const str) };
1947         inner.strings.push(string);
1948
1949         // This second hash table lookup can be avoided by using `RawEntryMut`,
1950         // but this code path isn't hot enough for it to be worth it. See
1951         // #91445 for details.
1952         inner.names.insert(string, name);
1953         name
1954     }
1955
1956     // Get the symbol as a string. `Symbol::as_str()` should be used in
1957     // preference to this function.
1958     fn get(&self, symbol: Symbol) -> &str {
1959         self.0.lock().strings[symbol.0.as_usize()]
1960     }
1961 }
1962
1963 // This module has a very short name because it's used a lot.
1964 /// This module contains all the defined keyword `Symbol`s.
1965 ///
1966 /// Given that `kw` is imported, use them like `kw::keyword_name`.
1967 /// For example `kw::Loop` or `kw::Break`.
1968 pub mod kw {
1969     pub use super::kw_generated::*;
1970 }
1971
1972 // This module has a very short name because it's used a lot.
1973 /// This module contains all the defined non-keyword `Symbol`s.
1974 ///
1975 /// Given that `sym` is imported, use them like `sym::symbol_name`.
1976 /// For example `sym::rustfmt` or `sym::u8`.
1977 pub mod sym {
1978     use super::Symbol;
1979
1980     #[doc(inline)]
1981     pub use super::sym_generated::*;
1982
1983     // Used from a macro in `librustc_feature/accepted.rs`
1984     pub use super::kw::MacroRules as macro_rules;
1985
1986     /// Get the symbol for an integer.
1987     ///
1988     /// The first few non-negative integers each have a static symbol and therefore
1989     /// are fast.
1990     pub fn integer<N: TryInto<usize> + Copy + ToString>(n: N) -> Symbol {
1991         if let Result::Ok(idx) = n.try_into() {
1992             if idx < 10 {
1993                 return Symbol::new(super::SYMBOL_DIGITS_BASE + idx as u32);
1994             }
1995         }
1996         Symbol::intern(&n.to_string())
1997     }
1998 }
1999
2000 impl Symbol {
2001     fn is_special(self) -> bool {
2002         self <= kw::Underscore
2003     }
2004
2005     fn is_used_keyword_always(self) -> bool {
2006         self >= kw::As && self <= kw::While
2007     }
2008
2009     fn is_used_keyword_conditional(self, edition: impl FnOnce() -> Edition) -> bool {
2010         (self >= kw::Async && self <= kw::Dyn) && edition() >= Edition::Edition2018
2011     }
2012
2013     fn is_unused_keyword_always(self) -> bool {
2014         self >= kw::Abstract && self <= kw::Yield
2015     }
2016
2017     fn is_unused_keyword_conditional(self, edition: impl FnOnce() -> Edition) -> bool {
2018         self == kw::Try && edition() >= Edition::Edition2018
2019     }
2020
2021     pub fn is_reserved(self, edition: impl Copy + FnOnce() -> Edition) -> bool {
2022         self.is_special()
2023             || self.is_used_keyword_always()
2024             || self.is_unused_keyword_always()
2025             || self.is_used_keyword_conditional(edition)
2026             || self.is_unused_keyword_conditional(edition)
2027     }
2028
2029     /// A keyword or reserved identifier that can be used as a path segment.
2030     pub fn is_path_segment_keyword(self) -> bool {
2031         self == kw::Super
2032             || self == kw::SelfLower
2033             || self == kw::SelfUpper
2034             || self == kw::Crate
2035             || self == kw::PathRoot
2036             || self == kw::DollarCrate
2037     }
2038
2039     /// Returns `true` if the symbol is `true` or `false`.
2040     pub fn is_bool_lit(self) -> bool {
2041         self == kw::True || self == kw::False
2042     }
2043
2044     /// Returns `true` if this symbol can be a raw identifier.
2045     pub fn can_be_raw(self) -> bool {
2046         self != kw::Empty && self != kw::Underscore && !self.is_path_segment_keyword()
2047     }
2048
2049     /// Is this symbol was interned in compiler's `symbols!` macro
2050     pub fn is_preinterned(self) -> bool {
2051         self.as_u32() < PREINTERNED_SYMBOLS_COUNT
2052     }
2053 }
2054
2055 impl Ident {
2056     /// Returns `true` for reserved identifiers used internally for elided lifetimes,
2057     /// unnamed method parameters, crate root module, error recovery etc.
2058     pub fn is_special(self) -> bool {
2059         self.name.is_special()
2060     }
2061
2062     /// Returns `true` if the token is a keyword used in the language.
2063     pub fn is_used_keyword(self) -> bool {
2064         // Note: `span.edition()` is relatively expensive, don't call it unless necessary.
2065         self.name.is_used_keyword_always()
2066             || self.name.is_used_keyword_conditional(|| self.span.edition())
2067     }
2068
2069     /// Returns `true` if the token is a keyword reserved for possible future use.
2070     pub fn is_unused_keyword(self) -> bool {
2071         // Note: `span.edition()` is relatively expensive, don't call it unless necessary.
2072         self.name.is_unused_keyword_always()
2073             || self.name.is_unused_keyword_conditional(|| self.span.edition())
2074     }
2075
2076     /// Returns `true` if the token is either a special identifier or a keyword.
2077     pub fn is_reserved(self) -> bool {
2078         // Note: `span.edition()` is relatively expensive, don't call it unless necessary.
2079         self.name.is_reserved(|| self.span.edition())
2080     }
2081
2082     /// A keyword or reserved identifier that can be used as a path segment.
2083     pub fn is_path_segment_keyword(self) -> bool {
2084         self.name.is_path_segment_keyword()
2085     }
2086
2087     /// We see this identifier in a normal identifier position, like variable name or a type.
2088     /// How was it written originally? Did it use the raw form? Let's try to guess.
2089     pub fn is_raw_guess(self) -> bool {
2090         self.name.can_be_raw() && self.is_reserved()
2091     }
2092 }