]> git.lizzy.rs Git - rust.git/blob - src/librustc_span/symbol.rs
introduce `#![feature(move_ref_pattern)]`
[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_ref_pattern,
459         move_val_init,
460         movbe_target_feature,
461         mul_with_overflow,
462         must_use,
463         naked,
464         naked_functions,
465         name,
466         needs_allocator,
467         needs_drop,
468         needs_panic_runtime,
469         negate_unsigned,
470         never,
471         never_type,
472         never_type_fallback,
473         new,
474         next,
475         __next,
476         nll,
477         no_builtins,
478         no_core,
479         no_crate_inject,
480         no_debug,
481         no_default_passes,
482         no_implicit_prelude,
483         no_inline,
484         no_link,
485         no_main,
486         no_mangle,
487         non_ascii_idents,
488         None,
489         non_exhaustive,
490         non_modrs_mods,
491         no_stack_check,
492         no_start,
493         no_std,
494         not,
495         note,
496         object_safe_for_dispatch,
497         Ok,
498         omit_gdb_pretty_printer_section,
499         on,
500         on_unimplemented,
501         oom,
502         ops,
503         optimize,
504         optimize_attribute,
505         optin_builtin_traits,
506         option,
507         Option,
508         option_env,
509         opt_out_copy,
510         or,
511         or_patterns,
512         Ord,
513         Ordering,
514         Output,
515         overlapping_marker_traits,
516         packed,
517         panic,
518         panic_handler,
519         panic_impl,
520         panic_implementation,
521         panic_runtime,
522         parent_trait,
523         partial_cmp,
524         param_attrs,
525         PartialEq,
526         PartialOrd,
527         passes,
528         pat,
529         path,
530         pattern_parentheses,
531         Pending,
532         pin,
533         Pin,
534         pinned,
535         platform_intrinsics,
536         plugin,
537         plugin_registrar,
538         plugins,
539         Poll,
540         poll_with_tls_context,
541         powerpc_target_feature,
542         precise_pointer_size_matching,
543         pref_align_of,
544         prelude,
545         prelude_import,
546         primitive,
547         proc_dash_macro: "proc-macro",
548         proc_macro,
549         proc_macro_attribute,
550         proc_macro_def_site,
551         proc_macro_derive,
552         proc_macro_expr,
553         proc_macro_gen,
554         proc_macro_hygiene,
555         proc_macro_internals,
556         proc_macro_mod,
557         proc_macro_non_items,
558         proc_macro_path_invoc,
559         profiler_runtime,
560         ptr_offset_from,
561         pub_restricted,
562         pushpop_unsafe,
563         quad_precision_float,
564         question_mark,
565         quote,
566         Range,
567         RangeFrom,
568         RangeFull,
569         RangeInclusive,
570         RangeTo,
571         RangeToInclusive,
572         raw_dylib,
573         raw_identifiers,
574         raw_ref_op,
575         Ready,
576         reason,
577         recursion_limit,
578         reexport_test_harness_main,
579         reflect,
580         register_attr,
581         register_tool,
582         relaxed_adts,
583         repr,
584         repr128,
585         repr_align,
586         repr_align_enum,
587         repr_packed,
588         repr_simd,
589         repr_transparent,
590         re_rebalance_coherence,
591         result,
592         Result,
593         Return,
594         rhs,
595         rlib,
596         rotate_left,
597         rotate_right,
598         rt,
599         rtm_target_feature,
600         rust,
601         rust_2015_preview,
602         rust_2018_preview,
603         rust_begin_unwind,
604         rustc,
605         RustcDecodable,
606         RustcEncodable,
607         rustc_allocator,
608         rustc_allocator_nounwind,
609         rustc_allow_const_fn_ptr,
610         rustc_args_required_const,
611         rustc_attrs,
612         rustc_builtin_macro,
613         rustc_clean,
614         rustc_const_unstable,
615         rustc_const_stable,
616         rustc_conversion_suggestion,
617         rustc_def_path,
618         rustc_deprecated,
619         rustc_diagnostic_item,
620         rustc_diagnostic_macros,
621         rustc_dirty,
622         rustc_dummy,
623         rustc_dump_env_program_clauses,
624         rustc_dump_program_clauses,
625         rustc_dump_user_substs,
626         rustc_error,
627         rustc_expected_cgu_reuse,
628         rustc_if_this_changed,
629         rustc_inherit_overflow_checks,
630         rustc_layout,
631         rustc_layout_scalar_valid_range_end,
632         rustc_layout_scalar_valid_range_start,
633         rustc_macro_transparency,
634         rustc_mir,
635         rustc_nonnull_optimization_guaranteed,
636         rustc_object_lifetime_default,
637         rustc_on_unimplemented,
638         rustc_outlives,
639         rustc_paren_sugar,
640         rustc_partition_codegened,
641         rustc_partition_reused,
642         rustc_peek,
643         rustc_peek_definite_init,
644         rustc_peek_maybe_init,
645         rustc_peek_maybe_uninit,
646         rustc_peek_indirectly_mutable,
647         rustc_private,
648         rustc_proc_macro_decls,
649         rustc_promotable,
650         rustc_regions,
651         rustc_stable,
652         rustc_std_internal_symbol,
653         rustc_symbol_name,
654         rustc_synthetic,
655         rustc_reservation_impl,
656         rustc_test_marker,
657         rustc_then_this_would_need,
658         rustc_variance,
659         rustfmt,
660         rust_eh_personality,
661         rust_eh_unwind_resume,
662         rust_oom,
663         rvalue_static_promotion,
664         sanitize,
665         sanitizer_runtime,
666         saturating_add,
667         saturating_sub,
668         _Self,
669         self_in_typedefs,
670         self_struct_ctor,
671         send_trait,
672         should_panic,
673         simd,
674         simd_extract,
675         simd_ffi,
676         simd_insert,
677         since,
678         size,
679         size_of,
680         slice_patterns,
681         slicing_syntax,
682         soft,
683         Some,
684         specialization,
685         speed,
686         spotlight,
687         sse4a_target_feature,
688         stable,
689         staged_api,
690         start,
691         static_in_const,
692         staticlib,
693         static_nobundle,
694         static_recursion,
695         std,
696         std_inject,
697         str,
698         stringify,
699         stmt,
700         stmt_expr_attributes,
701         stop_after_dataflow,
702         struct_field_attributes,
703         struct_inherit,
704         structural_match,
705         struct_variant,
706         sty,
707         sub_with_overflow,
708         suggestion,
709         sync_trait,
710         target_feature,
711         target_has_atomic,
712         target_has_atomic_load_store,
713         target_thread_local,
714         task,
715         tbm_target_feature,
716         termination_trait,
717         termination_trait_test,
718         test,
719         test_2018_feature,
720         test_accepted_feature,
721         test_case,
722         test_removed_feature,
723         test_runner,
724         then_with,
725         thread_local,
726         tool_attributes,
727         tool_lints,
728         trace_macros,
729         track_caller,
730         trait_alias,
731         transmute,
732         transparent,
733         transparent_enums,
734         transparent_unions,
735         trivial_bounds,
736         Try,
737         try_blocks,
738         try_trait,
739         tt,
740         tuple_indexing,
741         two_phase,
742         Ty,
743         ty,
744         type_alias_impl_trait,
745         type_id,
746         type_name,
747         TyCtxt,
748         TyKind,
749         type_alias_enum_variants,
750         type_ascription,
751         type_length_limit,
752         type_macros,
753         u128,
754         u16,
755         u32,
756         u64,
757         u8,
758         unboxed_closures,
759         unchecked_shl,
760         unchecked_shr,
761         underscore_const_names,
762         underscore_imports,
763         underscore_lifetimes,
764         uniform_paths,
765         universal_impl_trait,
766         unmarked_api,
767         unreachable_code,
768         unrestricted_attribute_tokens,
769         unsafe_no_drop_flag,
770         unsized_locals,
771         unsized_tuple_coercion,
772         unstable,
773         untagged_unions,
774         unwind,
775         unwind_attributes,
776         unwrap_or,
777         used,
778         use_extern_macros,
779         use_nested_groups,
780         usize,
781         v1,
782         val,
783         var,
784         vec,
785         Vec,
786         vis,
787         visible_private_types,
788         volatile,
789         warn,
790         wasm_import_module,
791         wasm_target_feature,
792         while_let,
793         windows,
794         windows_subsystem,
795         wrapping_add,
796         wrapping_sub,
797         wrapping_mul,
798         Yield,
799     }
800 }
801
802 #[derive(Copy, Clone, Eq, HashStable_Generic)]
803 pub struct Ident {
804     pub name: Symbol,
805     pub span: Span,
806 }
807
808 impl Ident {
809     #[inline]
810     /// Constructs a new identifier from a symbol and a span.
811     pub const fn new(name: Symbol, span: Span) -> Ident {
812         Ident { name, span }
813     }
814
815     /// Constructs a new identifier with a dummy span.
816     #[inline]
817     pub const fn with_dummy_span(name: Symbol) -> Ident {
818         Ident::new(name, DUMMY_SP)
819     }
820
821     #[inline]
822     pub fn invalid() -> Ident {
823         Ident::with_dummy_span(kw::Invalid)
824     }
825
826     /// Maps a string to an identifier with a dummy span.
827     pub fn from_str(string: &str) -> Ident {
828         Ident::with_dummy_span(Symbol::intern(string))
829     }
830
831     /// Maps a string and a span to an identifier.
832     pub fn from_str_and_span(string: &str, span: Span) -> Ident {
833         Ident::new(Symbol::intern(string), span)
834     }
835
836     /// Replaces `lo` and `hi` with those from `span`, but keep hygiene context.
837     pub fn with_span_pos(self, span: Span) -> Ident {
838         Ident::new(self.name, span.with_ctxt(self.span.ctxt()))
839     }
840
841     pub fn without_first_quote(self) -> Ident {
842         Ident::new(Symbol::intern(self.as_str().trim_start_matches('\'')), self.span)
843     }
844
845     /// "Normalize" ident for use in comparisons using "item hygiene".
846     /// Identifiers with same string value become same if they came from the same "modern" macro
847     /// (e.g., `macro` item, but not `macro_rules` item) and stay different if they came from
848     /// different "modern" macros.
849     /// Technically, this operation strips all non-opaque marks from ident's syntactic context.
850     pub fn modern(self) -> Ident {
851         Ident::new(self.name, self.span.modern())
852     }
853
854     /// "Normalize" ident for use in comparisons using "local variable hygiene".
855     /// Identifiers with same string value become same if they came from the same non-transparent
856     /// macro (e.g., `macro` or `macro_rules!` items) and stay different if they came from different
857     /// non-transparent macros.
858     /// Technically, this operation strips all transparent marks from ident's syntactic context.
859     pub fn modern_and_legacy(self) -> Ident {
860         Ident::new(self.name, self.span.modern_and_legacy())
861     }
862
863     /// Convert the name to a `SymbolStr`. This is a slowish operation because
864     /// it requires locking the symbol interner.
865     pub fn as_str(self) -> SymbolStr {
866         self.name.as_str()
867     }
868 }
869
870 impl PartialEq for Ident {
871     fn eq(&self, rhs: &Self) -> bool {
872         self.name == rhs.name && self.span.ctxt() == rhs.span.ctxt()
873     }
874 }
875
876 impl Hash for Ident {
877     fn hash<H: Hasher>(&self, state: &mut H) {
878         self.name.hash(state);
879         self.span.ctxt().hash(state);
880     }
881 }
882
883 impl fmt::Debug for Ident {
884     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
885         if self.is_raw_guess() {
886             write!(f, "r#")?;
887         }
888         write!(f, "{}{:?}", self.name, self.span.ctxt())
889     }
890 }
891
892 impl fmt::Display for Ident {
893     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
894         if self.is_raw_guess() {
895             write!(f, "r#")?;
896         }
897         fmt::Display::fmt(&self.name, f)
898     }
899 }
900
901 impl UseSpecializedEncodable for Ident {
902     fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
903         s.emit_struct("Ident", 2, |s| {
904             s.emit_struct_field("name", 0, |s| self.name.encode(s))?;
905             s.emit_struct_field("span", 1, |s| self.span.encode(s))
906         })
907     }
908 }
909
910 impl UseSpecializedDecodable for Ident {
911     fn default_decode<D: Decoder>(d: &mut D) -> Result<Self, D::Error> {
912         d.read_struct("Ident", 2, |d| {
913             Ok(Ident {
914                 name: d.read_struct_field("name", 0, Decodable::decode)?,
915                 span: d.read_struct_field("span", 1, Decodable::decode)?,
916             })
917         })
918     }
919 }
920
921 /// An interned string.
922 ///
923 /// Internally, a `Symbol` is implemented as an index, and all operations
924 /// (including hashing, equality, and ordering) operate on that index. The use
925 /// of `rustc_index::newtype_index!` means that `Option<Symbol>` only takes up 4 bytes,
926 /// because `rustc_index::newtype_index!` reserves the last 256 values for tagging purposes.
927 ///
928 /// Note that `Symbol` cannot directly be a `rustc_index::newtype_index!` because it
929 /// implements `fmt::Debug`, `Encodable`, and `Decodable` in special ways.
930 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
931 pub struct Symbol(SymbolIndex);
932
933 rustc_index::newtype_index! {
934     pub struct SymbolIndex { .. }
935 }
936
937 impl Symbol {
938     const fn new(n: u32) -> Self {
939         Symbol(SymbolIndex::from_u32_const(n))
940     }
941
942     /// Maps a string to its interned representation.
943     pub fn intern(string: &str) -> Self {
944         with_interner(|interner| interner.intern(string))
945     }
946
947     /// Access the symbol's chars. This is a slowish operation because it
948     /// requires locking the symbol interner.
949     pub fn with<F: FnOnce(&str) -> R, R>(self, f: F) -> R {
950         with_interner(|interner| f(interner.get(self)))
951     }
952
953     /// Convert to a `SymbolStr`. This is a slowish operation because it
954     /// requires locking the symbol interner.
955     pub fn as_str(self) -> SymbolStr {
956         with_interner(|interner| unsafe {
957             SymbolStr { string: std::mem::transmute::<&str, &str>(interner.get(self)) }
958         })
959     }
960
961     pub fn as_u32(self) -> u32 {
962         self.0.as_u32()
963     }
964 }
965
966 impl fmt::Debug for Symbol {
967     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
968         self.with(|str| fmt::Debug::fmt(&str, f))
969     }
970 }
971
972 impl fmt::Display for Symbol {
973     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
974         self.with(|str| fmt::Display::fmt(&str, f))
975     }
976 }
977
978 impl Encodable for Symbol {
979     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
980         self.with(|string| s.emit_str(string))
981     }
982 }
983
984 impl Decodable for Symbol {
985     fn decode<D: Decoder>(d: &mut D) -> Result<Symbol, D::Error> {
986         Ok(Symbol::intern(&d.read_str()?))
987     }
988 }
989
990 impl<CTX> HashStable<CTX> for Symbol {
991     #[inline]
992     fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
993         self.as_str().hash_stable(hcx, hasher);
994     }
995 }
996
997 impl<CTX> ToStableHashKey<CTX> for Symbol {
998     type KeyType = SymbolStr;
999
1000     #[inline]
1001     fn to_stable_hash_key(&self, _: &CTX) -> SymbolStr {
1002         self.as_str()
1003     }
1004 }
1005
1006 // The `&'static str`s in this type actually point into the arena.
1007 #[derive(Default)]
1008 pub struct Interner {
1009     arena: DroplessArena,
1010     names: FxHashMap<&'static str, Symbol>,
1011     strings: Vec<&'static str>,
1012 }
1013
1014 impl Interner {
1015     fn prefill(init: &[&'static str]) -> Self {
1016         Interner {
1017             strings: init.into(),
1018             names: init.iter().copied().zip((0..).map(Symbol::new)).collect(),
1019             ..Default::default()
1020         }
1021     }
1022
1023     pub fn intern(&mut self, string: &str) -> Symbol {
1024         if let Some(&name) = self.names.get(string) {
1025             return name;
1026         }
1027
1028         let name = Symbol::new(self.strings.len() as u32);
1029
1030         // `from_utf8_unchecked` is safe since we just allocated a `&str` which is known to be
1031         // UTF-8.
1032         let string: &str =
1033             unsafe { str::from_utf8_unchecked(self.arena.alloc_slice(string.as_bytes())) };
1034         // It is safe to extend the arena allocation to `'static` because we only access
1035         // these while the arena is still alive.
1036         let string: &'static str = unsafe { &*(string as *const str) };
1037         self.strings.push(string);
1038         self.names.insert(string, name);
1039         name
1040     }
1041
1042     // Get the symbol as a string. `Symbol::as_str()` should be used in
1043     // preference to this function.
1044     pub fn get(&self, symbol: Symbol) -> &str {
1045         self.strings[symbol.0.as_usize()]
1046     }
1047 }
1048
1049 // This module has a very short name because it's used a lot.
1050 pub mod kw {
1051     use super::Symbol;
1052     keywords!();
1053 }
1054
1055 // This module has a very short name because it's used a lot.
1056 #[allow(rustc::default_hash_types)]
1057 pub mod sym {
1058     use super::Symbol;
1059     use std::convert::TryInto;
1060
1061     symbols!();
1062
1063     // Get the symbol for an integer. The first few non-negative integers each
1064     // have a static symbol and therefore are fast.
1065     pub fn integer<N: TryInto<usize> + Copy + ToString>(n: N) -> Symbol {
1066         if let Result::Ok(idx) = n.try_into() {
1067             if let Option::Some(&sym) = digits_array.get(idx) {
1068                 return sym;
1069             }
1070         }
1071         Symbol::intern(&n.to_string())
1072     }
1073 }
1074
1075 impl Symbol {
1076     fn is_used_keyword_2018(self) -> bool {
1077         self >= kw::Async && self <= kw::Dyn
1078     }
1079
1080     fn is_unused_keyword_2018(self) -> bool {
1081         self == kw::Try
1082     }
1083
1084     /// Used for sanity checking rustdoc keyword sections.
1085     pub fn is_doc_keyword(self) -> bool {
1086         self <= kw::Union
1087     }
1088
1089     /// A keyword or reserved identifier that can be used as a path segment.
1090     pub fn is_path_segment_keyword(self) -> bool {
1091         self == kw::Super
1092             || self == kw::SelfLower
1093             || self == kw::SelfUpper
1094             || self == kw::Crate
1095             || self == kw::PathRoot
1096             || self == kw::DollarCrate
1097     }
1098
1099     /// Returns `true` if the symbol is `true` or `false`.
1100     pub fn is_bool_lit(self) -> bool {
1101         self == kw::True || self == kw::False
1102     }
1103
1104     /// This symbol can be a raw identifier.
1105     pub fn can_be_raw(self) -> bool {
1106         self != kw::Invalid && self != kw::Underscore && !self.is_path_segment_keyword()
1107     }
1108 }
1109
1110 impl Ident {
1111     // Returns `true` for reserved identifiers used internally for elided lifetimes,
1112     // unnamed method parameters, crate root module, error recovery etc.
1113     pub fn is_special(self) -> bool {
1114         self.name <= kw::Underscore
1115     }
1116
1117     /// Returns `true` if the token is a keyword used in the language.
1118     pub fn is_used_keyword(self) -> bool {
1119         // Note: `span.edition()` is relatively expensive, don't call it unless necessary.
1120         self.name >= kw::As && self.name <= kw::While
1121             || self.name.is_used_keyword_2018() && self.span.rust_2018()
1122     }
1123
1124     /// Returns `true` if the token is a keyword reserved for possible future use.
1125     pub fn is_unused_keyword(self) -> bool {
1126         // Note: `span.edition()` is relatively expensive, don't call it unless necessary.
1127         self.name >= kw::Abstract && self.name <= kw::Yield
1128             || self.name.is_unused_keyword_2018() && self.span.rust_2018()
1129     }
1130
1131     /// Returns `true` if the token is either a special identifier or a keyword.
1132     pub fn is_reserved(self) -> bool {
1133         self.is_special() || self.is_used_keyword() || self.is_unused_keyword()
1134     }
1135
1136     /// A keyword or reserved identifier that can be used as a path segment.
1137     pub fn is_path_segment_keyword(self) -> bool {
1138         self.name.is_path_segment_keyword()
1139     }
1140
1141     /// We see this identifier in a normal identifier position, like variable name or a type.
1142     /// How was it written originally? Did it use the raw form? Let's try to guess.
1143     pub fn is_raw_guess(self) -> bool {
1144         self.name.can_be_raw() && self.is_reserved()
1145     }
1146 }
1147
1148 #[inline]
1149 fn with_interner<T, F: FnOnce(&mut Interner) -> T>(f: F) -> T {
1150     GLOBALS.with(|globals| f(&mut *globals.symbol_interner.lock()))
1151 }
1152
1153 /// An alternative to `Symbol`, useful when the chars within the symbol need to
1154 /// be accessed. It deliberately has limited functionality and should only be
1155 /// used for temporary values.
1156 ///
1157 /// Because the interner outlives any thread which uses this type, we can
1158 /// safely treat `string` which points to interner data, as an immortal string,
1159 /// as long as this type never crosses between threads.
1160 //
1161 // FIXME: ensure that the interner outlives any thread which uses `SymbolStr`,
1162 // by creating a new thread right after constructing the interner.
1163 #[derive(Clone, Eq, PartialOrd, Ord)]
1164 pub struct SymbolStr {
1165     string: &'static str,
1166 }
1167
1168 // This impl allows a `SymbolStr` to be directly equated with a `String` or
1169 // `&str`.
1170 impl<T: std::ops::Deref<Target = str>> std::cmp::PartialEq<T> for SymbolStr {
1171     fn eq(&self, other: &T) -> bool {
1172         self.string == other.deref()
1173     }
1174 }
1175
1176 impl !Send for SymbolStr {}
1177 impl !Sync for SymbolStr {}
1178
1179 /// This impl means that if `ss` is a `SymbolStr`:
1180 /// - `*ss` is a `str`;
1181 /// - `&*ss` is a `&str`;
1182 /// - `&ss as &str` is a `&str`, which means that `&ss` can be passed to a
1183 ///   function expecting a `&str`.
1184 impl std::ops::Deref for SymbolStr {
1185     type Target = str;
1186     #[inline]
1187     fn deref(&self) -> &str {
1188         self.string
1189     }
1190 }
1191
1192 impl fmt::Debug for SymbolStr {
1193     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1194         fmt::Debug::fmt(self.string, f)
1195     }
1196 }
1197
1198 impl fmt::Display for SymbolStr {
1199     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1200         fmt::Display::fmt(self.string, f)
1201     }
1202 }
1203
1204 impl<CTX> HashStable<CTX> for SymbolStr {
1205     #[inline]
1206     fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
1207         self.string.hash_stable(hcx, hasher)
1208     }
1209 }
1210
1211 impl<CTX> ToStableHashKey<CTX> for SymbolStr {
1212     type KeyType = SymbolStr;
1213
1214     #[inline]
1215     fn to_stable_hash_key(&self, _: &CTX) -> SymbolStr {
1216         self.clone()
1217     }
1218 }