]> git.lizzy.rs Git - rust.git/blob - src/librustc_span/symbol.rs
Rollup merge of #68388 - varkor:toogeneric-wf, r=eddyb
[rust.git] / src / librustc_span / symbol.rs
1 //! An "interner" is a data structure that associates values with usize tags and
2 //! allows bidirectional lookup; i.e., given a value, one can easily find the
3 //! type, and vice versa.
4
5 use arena::DroplessArena;
6 use rustc_data_structures::fx::FxHashMap;
7 use rustc_data_structures::stable_hasher::{HashStable, StableHasher, ToStableHashKey};
8 use rustc_macros::{symbols, HashStable_Generic};
9 use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
10 use rustc_serialize::{UseSpecializedDecodable, UseSpecializedEncodable};
11
12 use std::cmp::{Ord, PartialEq, PartialOrd};
13 use std::fmt;
14 use std::hash::{Hash, Hasher};
15 use std::str;
16
17 use crate::{Span, DUMMY_SP, GLOBALS};
18
19 #[cfg(test)]
20 mod tests;
21
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         Invalid:            "",
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         Raw:                "raw",
101         Union:              "union",
102     }
103
104     // Symbols that can be referred to with rustc_span::sym::*. The symbol is
105     // the stringified identifier unless otherwise specified (e.g.
106     // `proc_dash_macro` represents "proc-macro").
107     //
108     // As well as the symbols listed, there are symbols for the the strings
109     // "0", "1", ..., "9", which are accessible via `sym::integer`.
110     Symbols {
111         aarch64_target_feature,
112         abi,
113         abi_amdgpu_kernel,
114         abi_efiapi,
115         abi_msp430_interrupt,
116         abi_ptx,
117         abi_sysv64,
118         abi_thiscall,
119         abi_unadjusted,
120         abi_vectorcall,
121         abi_x86_interrupt,
122         aborts,
123         add_with_overflow,
124         advanced_slice_patterns,
125         adx_target_feature,
126         alias,
127         align,
128         alignstack,
129         all,
130         allocator,
131         allocator_internals,
132         alloc_error_handler,
133         allow,
134         allowed,
135         allow_fail,
136         allow_internal_unsafe,
137         allow_internal_unstable,
138         allow_internal_unstable_backcompat_hack,
139         always,
140         and,
141         any,
142         arbitrary_enum_discriminant,
143         arbitrary_self_types,
144         Arguments,
145         ArgumentV1,
146         arm_target_feature,
147         asm,
148         assert,
149         associated_consts,
150         associated_type_bounds,
151         associated_type_defaults,
152         associated_types,
153         assume_init,
154         async_await,
155         async_closure,
156         attr,
157         attributes,
158         attr_literals,
159         augmented_assignments,
160         automatically_derived,
161         avx512_target_feature,
162         await_macro,
163         begin_panic,
164         bench,
165         bin,
166         bind_by_move_pattern_guards,
167         bindings_after_at,
168         block,
169         bool,
170         borrowck_graphviz_format,
171         borrowck_graphviz_postflow,
172         borrowck_graphviz_preflow,
173         box_patterns,
174         box_syntax,
175         braced_empty_structs,
176         bswap,
177         bitreverse,
178         C,
179         caller_location,
180         cdylib,
181         cfg,
182         cfg_attr,
183         cfg_attr_multi,
184         cfg_doctest,
185         cfg_sanitize,
186         cfg_target_feature,
187         cfg_target_has_atomic,
188         cfg_target_thread_local,
189         cfg_target_vendor,
190         char,
191         clippy,
192         clone,
193         Clone,
194         clone_closures,
195         clone_from,
196         closure_to_fn_coercion,
197         cmp,
198         cmpxchg16b_target_feature,
199         cold,
200         column,
201         compile_error,
202         compiler_builtins,
203         concat,
204         concat_idents,
205         conservative_impl_trait,
206         console,
207         const_compare_raw_pointers,
208         const_constructor,
209         const_extern_fn,
210         const_fn,
211         const_fn_union,
212         const_generics,
213         const_if_match,
214         const_indexing,
215         const_in_array_repeat_expressions,
216         const_let,
217         const_loop,
218         const_mut_refs,
219         const_panic,
220         const_raw_ptr_deref,
221         const_raw_ptr_to_usize_cast,
222         const_transmute,
223         const_trait_bound_opt_out,
224         const_trait_impl,
225         contents,
226         context,
227         convert,
228         Copy,
229         copy_closures,
230         core,
231         core_intrinsics,
232         crate_id,
233         crate_in_paths,
234         crate_local,
235         crate_name,
236         crate_type,
237         crate_visibility_modifier,
238         ctpop,
239         cttz,
240         cttz_nonzero,
241         ctlz,
242         ctlz_nonzero,
243         custom_attribute,
244         custom_derive,
245         custom_inner_attributes,
246         custom_test_frameworks,
247         c_variadic,
248         debug_trait,
249         declare_lint_pass,
250         decl_macro,
251         Debug,
252         Decodable,
253         Default,
254         default_lib_allocator,
255         default_type_parameter_fallback,
256         default_type_params,
257         delay_span_bug_from_inside_query,
258         deny,
259         deprecated,
260         deref,
261         deref_mut,
262         derive,
263         diagnostic,
264         direct,
265         doc,
266         doc_alias,
267         doc_cfg,
268         doc_keyword,
269         doc_masked,
270         doc_spotlight,
271         doctest,
272         document_private_items,
273         dotdoteq_in_patterns,
274         dotdot_in_tuple_patterns,
275         double_braced_crate: "{{crate}}",
276         double_braced_impl: "{{impl}}",
277         double_braced_misc: "{{misc}}",
278         double_braced_closure: "{{closure}}",
279         double_braced_constructor: "{{constructor}}",
280         double_braced_constant: "{{constant}}",
281         double_braced_opaque: "{{opaque}}",
282         dropck_eyepatch,
283         dropck_parametricity,
284         drop_types_in_const,
285         dylib,
286         dyn_trait,
287         eh_personality,
288         eh_unwind_resume,
289         enable,
290         Encodable,
291         env,
292         eq,
293         err,
294         Err,
295         Eq,
296         Equal,
297         enclosing_scope,
298         except,
299         exclusive_range_pattern,
300         exhaustive_integer_patterns,
301         exhaustive_patterns,
302         existential_type,
303         expected,
304         export_name,
305         expr,
306         extern_absolute_paths,
307         external_doc,
308         extern_crate_item_prelude,
309         extern_crate_self,
310         extern_in_paths,
311         extern_prelude,
312         extern_types,
313         f16c_target_feature,
314         f32,
315         f64,
316         feature,
317         ffi_returns_twice,
318         field,
319         field_init_shorthand,
320         file,
321         fmt,
322         fmt_internals,
323         fn_must_use,
324         forbid,
325         format_args,
326         format_args_nl,
327         from,
328         From,
329         from_desugaring,
330         from_error,
331         from_generator,
332         from_method,
333         from_ok,
334         from_usize,
335         fundamental,
336         future,
337         Future,
338         FxHashSet,
339         FxHashMap,
340         gen_future,
341         gen_kill,
342         generators,
343         generic_associated_types,
344         generic_param_attrs,
345         global_allocator,
346         global_asm,
347         globs,
348         half_open_range_patterns,
349         hash,
350         Hash,
351         HashSet,
352         HashMap,
353         hexagon_target_feature,
354         hidden,
355         homogeneous_aggregate,
356         html_favicon_url,
357         html_logo_url,
358         html_no_source,
359         html_playground_url,
360         html_root_url,
361         i128,
362         i128_type,
363         i16,
364         i32,
365         i64,
366         i8,
367         ident,
368         if_let,
369         if_while_or_patterns,
370         ignore,
371         impl_header_lifetime_elision,
372         impl_lint_pass,
373         impl_trait_in_bindings,
374         import_shadowing,
375         index,
376         index_mut,
377         in_band_lifetimes,
378         include,
379         include_bytes,
380         include_str,
381         inclusive_range_syntax,
382         infer_outlives_requirements,
383         infer_static_outlives_requirements,
384         inline,
385         intel,
386         into_iter,
387         IntoIterator,
388         into_result,
389         intrinsics,
390         irrefutable_let_patterns,
391         isize,
392         issue,
393         issue_5723_bootstrap,
394         issue_tracker_base_url,
395         item,
396         item_context: "ItemContext",
397         item_like_imports,
398         iter,
399         Iterator,
400         keyword,
401         kind,
402         label,
403         label_break_value,
404         lang,
405         lang_items,
406         let_chains,
407         lhs,
408         lib,
409         lifetime,
410         line,
411         link,
412         linkage,
413         link_args,
414         link_cfg,
415         link_llvm_intrinsics,
416         link_name,
417         link_ordinal,
418         link_section,
419         LintPass,
420         lint_reasons,
421         literal,
422         local_inner_macros,
423         log_syntax,
424         loop_break_value,
425         macro_at_most_once_rep,
426         macro_escape,
427         macro_export,
428         macro_lifetime_matcher,
429         macro_literal_matcher,
430         macro_reexport,
431         macro_rules,
432         macros_in_extern,
433         macro_use,
434         macro_vis_matcher,
435         main,
436         managed_boxes,
437         marker,
438         marker_trait_attr,
439         masked,
440         match_beginning_vert,
441         match_default_bindings,
442         may_dangle,
443         maybe_uninit_uninit,
444         maybe_uninit_zeroed,
445         mem_uninitialized,
446         mem_zeroed,
447         member_constraints,
448         message,
449         meta,
450         min_align_of,
451         min_const_fn,
452         min_const_unsafe_fn,
453         mips_target_feature,
454         mmx_target_feature,
455         module,
456         module_path,
457         more_struct_aliases,
458         move_val_init,
459         movbe_target_feature,
460         mul_with_overflow,
461         must_use,
462         naked,
463         naked_functions,
464         name,
465         needs_allocator,
466         needs_drop,
467         needs_panic_runtime,
468         negate_unsigned,
469         never,
470         never_type,
471         never_type_fallback,
472         new,
473         next,
474         __next,
475         nll,
476         no_builtins,
477         no_core,
478         no_crate_inject,
479         no_debug,
480         no_default_passes,
481         no_implicit_prelude,
482         no_inline,
483         no_link,
484         no_main,
485         no_mangle,
486         non_ascii_idents,
487         None,
488         non_exhaustive,
489         non_modrs_mods,
490         no_stack_check,
491         no_start,
492         no_std,
493         not,
494         note,
495         object_safe_for_dispatch,
496         Ok,
497         omit_gdb_pretty_printer_section,
498         on,
499         on_unimplemented,
500         oom,
501         ops,
502         optimize,
503         optimize_attribute,
504         optin_builtin_traits,
505         option,
506         Option,
507         option_env,
508         opt_out_copy,
509         or,
510         or_patterns,
511         Ord,
512         Ordering,
513         Output,
514         overlapping_marker_traits,
515         packed,
516         panic,
517         panic_handler,
518         panic_impl,
519         panic_implementation,
520         panic_runtime,
521         parent_trait,
522         partial_cmp,
523         param_attrs,
524         PartialEq,
525         PartialOrd,
526         passes,
527         pat,
528         path,
529         pattern_parentheses,
530         Pending,
531         pin,
532         Pin,
533         pinned,
534         platform_intrinsics,
535         plugin,
536         plugin_registrar,
537         plugins,
538         Poll,
539         poll_with_tls_context,
540         powerpc_target_feature,
541         precise_pointer_size_matching,
542         pref_align_of,
543         prelude,
544         prelude_import,
545         primitive,
546         proc_dash_macro: "proc-macro",
547         proc_macro,
548         proc_macro_attribute,
549         proc_macro_def_site,
550         proc_macro_derive,
551         proc_macro_expr,
552         proc_macro_gen,
553         proc_macro_hygiene,
554         proc_macro_internals,
555         proc_macro_mod,
556         proc_macro_non_items,
557         proc_macro_path_invoc,
558         profiler_runtime,
559         ptr_offset_from,
560         pub_restricted,
561         pushpop_unsafe,
562         quad_precision_float,
563         question_mark,
564         quote,
565         Range,
566         RangeFrom,
567         RangeFull,
568         RangeInclusive,
569         RangeTo,
570         RangeToInclusive,
571         raw_dylib,
572         raw_identifiers,
573         raw_ref_op,
574         Ready,
575         reason,
576         recursion_limit,
577         reexport_test_harness_main,
578         reflect,
579         register_attr,
580         register_tool,
581         relaxed_adts,
582         repr,
583         repr128,
584         repr_align,
585         repr_align_enum,
586         repr_packed,
587         repr_simd,
588         repr_transparent,
589         re_rebalance_coherence,
590         result,
591         Result,
592         Return,
593         rhs,
594         rlib,
595         rotate_left,
596         rotate_right,
597         rt,
598         rtm_target_feature,
599         rust,
600         rust_2015_preview,
601         rust_2018_preview,
602         rust_begin_unwind,
603         rustc,
604         RustcDecodable,
605         RustcEncodable,
606         rustc_allocator,
607         rustc_allocator_nounwind,
608         rustc_allow_const_fn_ptr,
609         rustc_args_required_const,
610         rustc_attrs,
611         rustc_builtin_macro,
612         rustc_clean,
613         rustc_const_unstable,
614         rustc_const_stable,
615         rustc_conversion_suggestion,
616         rustc_def_path,
617         rustc_deprecated,
618         rustc_diagnostic_item,
619         rustc_diagnostic_macros,
620         rustc_dirty,
621         rustc_dummy,
622         rustc_dump_env_program_clauses,
623         rustc_dump_program_clauses,
624         rustc_dump_user_substs,
625         rustc_error,
626         rustc_expected_cgu_reuse,
627         rustc_if_this_changed,
628         rustc_inherit_overflow_checks,
629         rustc_layout,
630         rustc_layout_scalar_valid_range_end,
631         rustc_layout_scalar_valid_range_start,
632         rustc_macro_transparency,
633         rustc_mir,
634         rustc_nonnull_optimization_guaranteed,
635         rustc_object_lifetime_default,
636         rustc_on_unimplemented,
637         rustc_outlives,
638         rustc_paren_sugar,
639         rustc_partition_codegened,
640         rustc_partition_reused,
641         rustc_peek,
642         rustc_peek_definite_init,
643         rustc_peek_maybe_init,
644         rustc_peek_maybe_uninit,
645         rustc_peek_indirectly_mutable,
646         rustc_private,
647         rustc_proc_macro_decls,
648         rustc_promotable,
649         rustc_regions,
650         rustc_stable,
651         rustc_std_internal_symbol,
652         rustc_symbol_name,
653         rustc_synthetic,
654         rustc_reservation_impl,
655         rustc_test_marker,
656         rustc_then_this_would_need,
657         rustc_variance,
658         rustfmt,
659         rust_eh_personality,
660         rust_eh_unwind_resume,
661         rust_oom,
662         rvalue_static_promotion,
663         sanitize,
664         sanitizer_runtime,
665         saturating_add,
666         saturating_sub,
667         _Self,
668         self_in_typedefs,
669         self_struct_ctor,
670         send_trait,
671         should_panic,
672         simd,
673         simd_extract,
674         simd_ffi,
675         simd_insert,
676         since,
677         size,
678         size_of,
679         slice_patterns,
680         slicing_syntax,
681         soft,
682         Some,
683         specialization,
684         speed,
685         spotlight,
686         sse4a_target_feature,
687         stable,
688         staged_api,
689         start,
690         static_in_const,
691         staticlib,
692         static_nobundle,
693         static_recursion,
694         std,
695         std_inject,
696         str,
697         stringify,
698         stmt,
699         stmt_expr_attributes,
700         stop_after_dataflow,
701         struct_field_attributes,
702         struct_inherit,
703         structural_match,
704         struct_variant,
705         sty,
706         sub_with_overflow,
707         suggestion,
708         sync_trait,
709         target_feature,
710         target_has_atomic,
711         target_has_atomic_load_store,
712         target_thread_local,
713         task,
714         tbm_target_feature,
715         termination_trait,
716         termination_trait_test,
717         test,
718         test_2018_feature,
719         test_accepted_feature,
720         test_case,
721         test_removed_feature,
722         test_runner,
723         then_with,
724         thread_local,
725         tool_attributes,
726         tool_lints,
727         trace_macros,
728         track_caller,
729         trait_alias,
730         transmute,
731         transparent,
732         transparent_enums,
733         transparent_unions,
734         trivial_bounds,
735         Try,
736         try_blocks,
737         try_trait,
738         tt,
739         tuple_indexing,
740         two_phase,
741         Ty,
742         ty,
743         type_alias_impl_trait,
744         type_id,
745         type_name,
746         TyCtxt,
747         TyKind,
748         type_alias_enum_variants,
749         type_ascription,
750         type_length_limit,
751         type_macros,
752         u128,
753         u16,
754         u32,
755         u64,
756         u8,
757         unboxed_closures,
758         unchecked_shl,
759         unchecked_shr,
760         underscore_const_names,
761         underscore_imports,
762         underscore_lifetimes,
763         uniform_paths,
764         universal_impl_trait,
765         unmarked_api,
766         unreachable_code,
767         unrestricted_attribute_tokens,
768         unsafe_no_drop_flag,
769         unsized_locals,
770         unsized_tuple_coercion,
771         unstable,
772         untagged_unions,
773         unwind,
774         unwind_attributes,
775         unwrap_or,
776         used,
777         use_extern_macros,
778         use_nested_groups,
779         usize,
780         v1,
781         val,
782         var,
783         vec,
784         Vec,
785         vis,
786         visible_private_types,
787         volatile,
788         warn,
789         wasm_import_module,
790         wasm_target_feature,
791         while_let,
792         windows,
793         windows_subsystem,
794         wrapping_add,
795         wrapping_sub,
796         wrapping_mul,
797         Yield,
798     }
799 }
800
801 #[derive(Copy, Clone, Eq, HashStable_Generic)]
802 pub struct Ident {
803     pub name: Symbol,
804     pub span: Span,
805 }
806
807 impl Ident {
808     #[inline]
809     /// Constructs a new identifier from a symbol and a span.
810     pub const fn new(name: Symbol, span: Span) -> Ident {
811         Ident { name, span }
812     }
813
814     /// Constructs a new identifier with a dummy span.
815     #[inline]
816     pub const fn with_dummy_span(name: Symbol) -> Ident {
817         Ident::new(name, DUMMY_SP)
818     }
819
820     #[inline]
821     pub fn invalid() -> Ident {
822         Ident::with_dummy_span(kw::Invalid)
823     }
824
825     /// Maps a string to an identifier with a dummy span.
826     pub fn from_str(string: &str) -> Ident {
827         Ident::with_dummy_span(Symbol::intern(string))
828     }
829
830     /// Maps a string and a span to an identifier.
831     pub fn from_str_and_span(string: &str, span: Span) -> Ident {
832         Ident::new(Symbol::intern(string), span)
833     }
834
835     /// Replaces `lo` and `hi` with those from `span`, but keep hygiene context.
836     pub fn with_span_pos(self, span: Span) -> Ident {
837         Ident::new(self.name, span.with_ctxt(self.span.ctxt()))
838     }
839
840     pub fn without_first_quote(self) -> Ident {
841         Ident::new(Symbol::intern(self.as_str().trim_start_matches('\'')), self.span)
842     }
843
844     /// "Normalize" ident for use in comparisons using "item hygiene".
845     /// Identifiers with same string value become same if they came from the same "modern" macro
846     /// (e.g., `macro` item, but not `macro_rules` item) and stay different if they came from
847     /// different "modern" macros.
848     /// Technically, this operation strips all non-opaque marks from ident's syntactic context.
849     pub fn modern(self) -> Ident {
850         Ident::new(self.name, self.span.modern())
851     }
852
853     /// "Normalize" ident for use in comparisons using "local variable hygiene".
854     /// Identifiers with same string value become same if they came from the same non-transparent
855     /// macro (e.g., `macro` or `macro_rules!` items) and stay different if they came from different
856     /// non-transparent macros.
857     /// Technically, this operation strips all transparent marks from ident's syntactic context.
858     pub fn modern_and_legacy(self) -> Ident {
859         Ident::new(self.name, self.span.modern_and_legacy())
860     }
861
862     /// Convert the name to a `SymbolStr`. This is a slowish operation because
863     /// it requires locking the symbol interner.
864     pub fn as_str(self) -> SymbolStr {
865         self.name.as_str()
866     }
867 }
868
869 impl PartialEq for Ident {
870     fn eq(&self, rhs: &Self) -> bool {
871         self.name == rhs.name && self.span.ctxt() == rhs.span.ctxt()
872     }
873 }
874
875 impl Hash for Ident {
876     fn hash<H: Hasher>(&self, state: &mut H) {
877         self.name.hash(state);
878         self.span.ctxt().hash(state);
879     }
880 }
881
882 impl fmt::Debug for Ident {
883     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
884         if self.is_raw_guess() {
885             write!(f, "r#")?;
886         }
887         write!(f, "{}{:?}", self.name, self.span.ctxt())
888     }
889 }
890
891 impl fmt::Display for Ident {
892     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
893         if self.is_raw_guess() {
894             write!(f, "r#")?;
895         }
896         fmt::Display::fmt(&self.name, f)
897     }
898 }
899
900 impl UseSpecializedEncodable for Ident {
901     fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
902         s.emit_struct("Ident", 2, |s| {
903             s.emit_struct_field("name", 0, |s| self.name.encode(s))?;
904             s.emit_struct_field("span", 1, |s| self.span.encode(s))
905         })
906     }
907 }
908
909 impl UseSpecializedDecodable for Ident {
910     fn default_decode<D: Decoder>(d: &mut D) -> Result<Self, D::Error> {
911         d.read_struct("Ident", 2, |d| {
912             Ok(Ident {
913                 name: d.read_struct_field("name", 0, Decodable::decode)?,
914                 span: d.read_struct_field("span", 1, Decodable::decode)?,
915             })
916         })
917     }
918 }
919
920 /// An interned string.
921 ///
922 /// Internally, a `Symbol` is implemented as an index, and all operations
923 /// (including hashing, equality, and ordering) operate on that index. The use
924 /// of `rustc_index::newtype_index!` means that `Option<Symbol>` only takes up 4 bytes,
925 /// because `rustc_index::newtype_index!` reserves the last 256 values for tagging purposes.
926 ///
927 /// Note that `Symbol` cannot directly be a `rustc_index::newtype_index!` because it
928 /// implements `fmt::Debug`, `Encodable`, and `Decodable` in special ways.
929 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
930 pub struct Symbol(SymbolIndex);
931
932 rustc_index::newtype_index! {
933     pub struct SymbolIndex { .. }
934 }
935
936 impl Symbol {
937     const fn new(n: u32) -> Self {
938         Symbol(SymbolIndex::from_u32_const(n))
939     }
940
941     /// Maps a string to its interned representation.
942     pub fn intern(string: &str) -> Self {
943         with_interner(|interner| interner.intern(string))
944     }
945
946     /// Access the symbol's chars. This is a slowish operation because it
947     /// requires locking the symbol interner.
948     pub fn with<F: FnOnce(&str) -> R, R>(self, f: F) -> R {
949         with_interner(|interner| f(interner.get(self)))
950     }
951
952     /// Convert to a `SymbolStr`. This is a slowish operation because it
953     /// requires locking the symbol interner.
954     pub fn as_str(self) -> SymbolStr {
955         with_interner(|interner| unsafe {
956             SymbolStr { string: std::mem::transmute::<&str, &str>(interner.get(self)) }
957         })
958     }
959
960     pub fn as_u32(self) -> u32 {
961         self.0.as_u32()
962     }
963 }
964
965 impl fmt::Debug for Symbol {
966     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
967         self.with(|str| fmt::Debug::fmt(&str, f))
968     }
969 }
970
971 impl fmt::Display for Symbol {
972     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
973         self.with(|str| fmt::Display::fmt(&str, f))
974     }
975 }
976
977 impl Encodable for Symbol {
978     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
979         self.with(|string| s.emit_str(string))
980     }
981 }
982
983 impl Decodable for Symbol {
984     fn decode<D: Decoder>(d: &mut D) -> Result<Symbol, D::Error> {
985         Ok(Symbol::intern(&d.read_str()?))
986     }
987 }
988
989 impl<CTX> HashStable<CTX> for Symbol {
990     #[inline]
991     fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
992         self.as_str().hash_stable(hcx, hasher);
993     }
994 }
995
996 impl<CTX> ToStableHashKey<CTX> for Symbol {
997     type KeyType = SymbolStr;
998
999     #[inline]
1000     fn to_stable_hash_key(&self, _: &CTX) -> SymbolStr {
1001         self.as_str()
1002     }
1003 }
1004
1005 // The `&'static str`s in this type actually point into the arena.
1006 #[derive(Default)]
1007 pub struct Interner {
1008     arena: DroplessArena,
1009     names: FxHashMap<&'static str, Symbol>,
1010     strings: Vec<&'static str>,
1011 }
1012
1013 impl Interner {
1014     fn prefill(init: &[&'static str]) -> Self {
1015         Interner {
1016             strings: init.into(),
1017             names: init.iter().copied().zip((0..).map(Symbol::new)).collect(),
1018             ..Default::default()
1019         }
1020     }
1021
1022     pub fn intern(&mut self, string: &str) -> Symbol {
1023         if let Some(&name) = self.names.get(string) {
1024             return name;
1025         }
1026
1027         let name = Symbol::new(self.strings.len() as u32);
1028
1029         // `from_utf8_unchecked` is safe since we just allocated a `&str` which is known to be
1030         // UTF-8.
1031         let string: &str =
1032             unsafe { str::from_utf8_unchecked(self.arena.alloc_slice(string.as_bytes())) };
1033         // It is safe to extend the arena allocation to `'static` because we only access
1034         // these while the arena is still alive.
1035         let string: &'static str = unsafe { &*(string as *const str) };
1036         self.strings.push(string);
1037         self.names.insert(string, name);
1038         name
1039     }
1040
1041     // Get the symbol as a string. `Symbol::as_str()` should be used in
1042     // preference to this function.
1043     pub fn get(&self, symbol: Symbol) -> &str {
1044         self.strings[symbol.0.as_usize()]
1045     }
1046 }
1047
1048 // This module has a very short name because it's used a lot.
1049 pub mod kw {
1050     use super::Symbol;
1051     keywords!();
1052 }
1053
1054 // This module has a very short name because it's used a lot.
1055 #[allow(rustc::default_hash_types)]
1056 pub mod sym {
1057     use super::Symbol;
1058     use std::convert::TryInto;
1059
1060     symbols!();
1061
1062     // Get the symbol for an integer. The first few non-negative integers each
1063     // have a static symbol and therefore are fast.
1064     pub fn integer<N: TryInto<usize> + Copy + ToString>(n: N) -> Symbol {
1065         if let Result::Ok(idx) = n.try_into() {
1066             if let Option::Some(&sym) = digits_array.get(idx) {
1067                 return sym;
1068             }
1069         }
1070         Symbol::intern(&n.to_string())
1071     }
1072 }
1073
1074 impl Symbol {
1075     fn is_used_keyword_2018(self) -> bool {
1076         self >= kw::Async && self <= kw::Dyn
1077     }
1078
1079     fn is_unused_keyword_2018(self) -> bool {
1080         self == kw::Try
1081     }
1082
1083     /// Used for sanity checking rustdoc keyword sections.
1084     pub fn is_doc_keyword(self) -> bool {
1085         self <= kw::Union
1086     }
1087
1088     /// A keyword or reserved identifier that can be used as a path segment.
1089     pub fn is_path_segment_keyword(self) -> bool {
1090         self == kw::Super
1091             || self == kw::SelfLower
1092             || self == kw::SelfUpper
1093             || self == kw::Crate
1094             || self == kw::PathRoot
1095             || self == kw::DollarCrate
1096     }
1097
1098     /// Returns `true` if the symbol is `true` or `false`.
1099     pub fn is_bool_lit(self) -> bool {
1100         self == kw::True || self == kw::False
1101     }
1102
1103     /// This symbol can be a raw identifier.
1104     pub fn can_be_raw(self) -> bool {
1105         self != kw::Invalid && self != kw::Underscore && !self.is_path_segment_keyword()
1106     }
1107 }
1108
1109 impl Ident {
1110     // Returns `true` for reserved identifiers used internally for elided lifetimes,
1111     // unnamed method parameters, crate root module, error recovery etc.
1112     pub fn is_special(self) -> bool {
1113         self.name <= kw::Underscore
1114     }
1115
1116     /// Returns `true` if the token is a keyword used in the language.
1117     pub fn is_used_keyword(self) -> bool {
1118         // Note: `span.edition()` is relatively expensive, don't call it unless necessary.
1119         self.name >= kw::As && self.name <= kw::While
1120             || self.name.is_used_keyword_2018() && self.span.rust_2018()
1121     }
1122
1123     /// Returns `true` if the token is a keyword reserved for possible future use.
1124     pub fn is_unused_keyword(self) -> bool {
1125         // Note: `span.edition()` is relatively expensive, don't call it unless necessary.
1126         self.name >= kw::Abstract && self.name <= kw::Yield
1127             || self.name.is_unused_keyword_2018() && self.span.rust_2018()
1128     }
1129
1130     /// Returns `true` if the token is either a special identifier or a keyword.
1131     pub fn is_reserved(self) -> bool {
1132         self.is_special() || self.is_used_keyword() || self.is_unused_keyword()
1133     }
1134
1135     /// A keyword or reserved identifier that can be used as a path segment.
1136     pub fn is_path_segment_keyword(self) -> bool {
1137         self.name.is_path_segment_keyword()
1138     }
1139
1140     /// We see this identifier in a normal identifier position, like variable name or a type.
1141     /// How was it written originally? Did it use the raw form? Let's try to guess.
1142     pub fn is_raw_guess(self) -> bool {
1143         self.name.can_be_raw() && self.is_reserved()
1144     }
1145 }
1146
1147 #[inline]
1148 fn with_interner<T, F: FnOnce(&mut Interner) -> T>(f: F) -> T {
1149     GLOBALS.with(|globals| f(&mut *globals.symbol_interner.lock()))
1150 }
1151
1152 /// An alternative to `Symbol`, useful when the chars within the symbol need to
1153 /// be accessed. It deliberately has limited functionality and should only be
1154 /// used for temporary values.
1155 ///
1156 /// Because the interner outlives any thread which uses this type, we can
1157 /// safely treat `string` which points to interner data, as an immortal string,
1158 /// as long as this type never crosses between threads.
1159 //
1160 // FIXME: ensure that the interner outlives any thread which uses `SymbolStr`,
1161 // by creating a new thread right after constructing the interner.
1162 #[derive(Clone, Eq, PartialOrd, Ord)]
1163 pub struct SymbolStr {
1164     string: &'static str,
1165 }
1166
1167 // This impl allows a `SymbolStr` to be directly equated with a `String` or
1168 // `&str`.
1169 impl<T: std::ops::Deref<Target = str>> std::cmp::PartialEq<T> for SymbolStr {
1170     fn eq(&self, other: &T) -> bool {
1171         self.string == other.deref()
1172     }
1173 }
1174
1175 impl !Send for SymbolStr {}
1176 impl !Sync for SymbolStr {}
1177
1178 /// This impl means that if `ss` is a `SymbolStr`:
1179 /// - `*ss` is a `str`;
1180 /// - `&*ss` is a `&str`;
1181 /// - `&ss as &str` is a `&str`, which means that `&ss` can be passed to a
1182 ///   function expecting a `&str`.
1183 impl std::ops::Deref for SymbolStr {
1184     type Target = str;
1185     #[inline]
1186     fn deref(&self) -> &str {
1187         self.string
1188     }
1189 }
1190
1191 impl fmt::Debug for SymbolStr {
1192     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1193         fmt::Debug::fmt(self.string, f)
1194     }
1195 }
1196
1197 impl fmt::Display for SymbolStr {
1198     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1199         fmt::Display::fmt(self.string, f)
1200     }
1201 }
1202
1203 impl<CTX> HashStable<CTX> for SymbolStr {
1204     #[inline]
1205     fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
1206         self.string.hash_stable(hcx, hasher)
1207     }
1208 }
1209
1210 impl<CTX> ToStableHashKey<CTX> for SymbolStr {
1211     type KeyType = SymbolStr;
1212
1213     #[inline]
1214     fn to_stable_hash_key(&self, _: &CTX) -> SymbolStr {
1215         self.clone()
1216     }
1217 }