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