]> git.lizzy.rs Git - rust.git/blob - src/libsyntax_pos/symbol.rs
Auto merge of #61035 - nnethercote:avoid-more-symbol-interning, r=petrochenkov
[rust.git] / src / libsyntax_pos / 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::indexed_vec::Idx;
8 use rustc_data_structures::newtype_index;
9 use rustc_macros::symbols;
10 use serialize::{Decodable, Decoder, Encodable, Encoder};
11
12 use std::cmp::{PartialEq, Ordering, PartialOrd, Ord};
13 use std::fmt;
14 use std::hash::{Hash, Hasher};
15 use std::str;
16
17 use crate::hygiene::SyntaxContext;
18 use crate::{Span, DUMMY_SP, GLOBALS};
19
20 symbols! {
21     // After modifying this list adjust `is_special`, `is_used_keyword`/`is_unused_keyword`,
22     // this should be rarely necessary though if the keywords are kept in alphabetic order.
23     Keywords {
24         // Special reserved identifiers used internally for elided lifetimes,
25         // unnamed method parameters, crate root module, error recovery etc.
26         Invalid:            "",
27         PathRoot:           "{{root}}",
28         DollarCrate:        "$crate",
29         Underscore:         "_",
30
31         // Keywords that are used in stable Rust.
32         As:                 "as",
33         Break:              "break",
34         Const:              "const",
35         Continue:           "continue",
36         Crate:              "crate",
37         Else:               "else",
38         Enum:               "enum",
39         Extern:             "extern",
40         False:              "false",
41         Fn:                 "fn",
42         For:                "for",
43         If:                 "if",
44         Impl:               "impl",
45         In:                 "in",
46         Let:                "let",
47         Loop:               "loop",
48         Match:              "match",
49         Mod:                "mod",
50         Move:               "move",
51         Mut:                "mut",
52         Pub:                "pub",
53         Ref:                "ref",
54         Return:             "return",
55         SelfLower:          "self",
56         SelfUpper:          "Self",
57         Static:             "static",
58         Struct:             "struct",
59         Super:              "super",
60         Trait:              "trait",
61         True:               "true",
62         Type:               "type",
63         Unsafe:             "unsafe",
64         Use:                "use",
65         Where:              "where",
66         While:              "while",
67
68         // Keywords that are used in unstable Rust or reserved for future use.
69         Abstract:           "abstract",
70         Become:             "become",
71         Box:                "box",
72         Do:                 "do",
73         Final:              "final",
74         Macro:              "macro",
75         Override:           "override",
76         Priv:               "priv",
77         Typeof:             "typeof",
78         Unsized:            "unsized",
79         Virtual:            "virtual",
80         Yield:              "yield",
81
82         // Edition-specific keywords that are used in stable Rust.
83         Dyn:                "dyn", // >= 2018 Edition only
84
85         // Edition-specific keywords that are used in unstable Rust or reserved for future use.
86         Async:              "async", // >= 2018 Edition only
87         Await:              "await", // >= 2018 Edition only
88         Try:                "try", // >= 2018 Edition only
89
90         // Special lifetime names
91         UnderscoreLifetime: "'_",
92         StaticLifetime:     "'static",
93
94         // Weak keywords, have special meaning only in specific contexts.
95         Auto:               "auto",
96         Catch:              "catch",
97         Default:            "default",
98         Existential:        "existential",
99         Union:              "union",
100     }
101
102     // Symbols that can be referred to with syntax_pos::sym::*. The symbol is
103     // the stringified identifier unless otherwise specified (e.g.
104     // `proc_dash_macro` represents "proc-macro").
105     //
106     // As well as the symbols listed, there are symbols for the the strings
107     // "0", "1", ..., "9", which are accessible via `sym::integer`.
108     Symbols {
109         aarch64_target_feature,
110         abi,
111         abi_amdgpu_kernel,
112         abi_msp430_interrupt,
113         abi_ptx,
114         abi_sysv64,
115         abi_thiscall,
116         abi_unadjusted,
117         abi_vectorcall,
118         abi_x86_interrupt,
119         aborts,
120         advanced_slice_patterns,
121         adx_target_feature,
122         alias,
123         align,
124         alignstack,
125         all,
126         allocator,
127         allocator_internals,
128         alloc_error_handler,
129         allow,
130         allowed,
131         allow_fail,
132         allow_internal_unsafe,
133         allow_internal_unstable,
134         allow_internal_unstable_backcompat_hack,
135         always,
136         and,
137         any,
138         arbitrary_self_types,
139         Arguments,
140         ArgumentV1,
141         arm_target_feature,
142         asm,
143         associated_consts,
144         associated_type_defaults,
145         associated_types,
146         async_await,
147         attr,
148         attributes,
149         attr_literals,
150         augmented_assignments,
151         automatically_derived,
152         avx512_target_feature,
153         await_macro,
154         begin_panic,
155         bench,
156         bin,
157         bind_by_move_pattern_guards,
158         block,
159         borrowck_graphviz_postflow,
160         borrowck_graphviz_preflow,
161         box_patterns,
162         box_syntax,
163         braced_empty_structs,
164         C,
165         cdylib,
166         cfg,
167         cfg_attr,
168         cfg_attr_multi,
169         cfg_target_feature,
170         cfg_target_has_atomic,
171         cfg_target_thread_local,
172         cfg_target_vendor,
173         clone,
174         Clone,
175         clone_closures,
176         clone_from,
177         closure_to_fn_coercion,
178         cmp,
179         cmpxchg16b_target_feature,
180         cold,
181         compile_error,
182         compiler_builtins,
183         concat_idents,
184         conservative_impl_trait,
185         console,
186         const_compare_raw_pointers,
187         const_fn,
188         const_fn_union,
189         const_generics,
190         const_indexing,
191         const_let,
192         const_panic,
193         const_raw_ptr_deref,
194         const_raw_ptr_to_usize_cast,
195         const_transmute,
196         contents,
197         convert,
198         copy_closures,
199         core,
200         core_intrinsics,
201         crate_id,
202         crate_in_paths,
203         crate_name,
204         crate_type,
205         crate_visibility_modifier,
206         custom_attribute,
207         custom_derive,
208         custom_inner_attributes,
209         custom_test_frameworks,
210         c_variadic,
211         decl_macro,
212         Default,
213         default_lib_allocator,
214         default_type_parameter_fallback,
215         default_type_params,
216         deny,
217         deprecated,
218         deref,
219         deref_mut,
220         derive,
221         doc,
222         doc_alias,
223         doc_cfg,
224         doc_keyword,
225         doc_masked,
226         doc_spotlight,
227         document_private_items,
228         dotdoteq_in_patterns,
229         dotdot_in_tuple_patterns,
230         double_braced_crate: "{{crate}}",
231         double_braced_impl: "{{impl}}",
232         double_braced_misc: "{{misc}}",
233         double_braced_closure: "{{closure}}",
234         double_braced_constructor: "{{constructor}}",
235         double_braced_constant: "{{constant}}",
236         double_braced_opaque: "{{opaque}}",
237         dropck_eyepatch,
238         dropck_parametricity,
239         drop_types_in_const,
240         dylib,
241         dyn_trait,
242         eh_personality,
243         eh_unwind_resume,
244         enable,
245         err,
246         Err,
247         Equal,
248         except,
249         exclusive_range_pattern,
250         exhaustive_integer_patterns,
251         exhaustive_patterns,
252         existential_type,
253         expected,
254         export_name,
255         expr,
256         extern_absolute_paths,
257         external_doc,
258         extern_crate_item_prelude,
259         extern_crate_self,
260         extern_in_paths,
261         extern_prelude,
262         extern_types,
263         f16c_target_feature,
264         f32,
265         f64,
266         feature,
267         ffi_returns_twice,
268         field,
269         field_init_shorthand,
270         file,
271         fmt,
272         fmt_internals,
273         fn_must_use,
274         forbid,
275         format_args_nl,
276         from,
277         From,
278         from_error,
279         from_generator,
280         from_ok,
281         from_usize,
282         fundamental,
283         future,
284         Future,
285         gen_future,
286         generators,
287         generic_associated_types,
288         generic_param_attrs,
289         global_allocator,
290         global_asm,
291         globs,
292         hash,
293         Hash,
294         hexagon_target_feature,
295         hidden,
296         homogeneous_aggregate,
297         html_favicon_url,
298         html_logo_url,
299         html_no_source,
300         html_playground_url,
301         html_root_url,
302         i128,
303         i128_type,
304         i16,
305         i32,
306         i64,
307         i8,
308         ident,
309         if_let,
310         if_while_or_patterns,
311         ignore,
312         impl_header_lifetime_elision,
313         impl_trait_in_bindings,
314         import_shadowing,
315         index,
316         index_mut,
317         in_band_lifetimes,
318         include,
319         inclusive_range_syntax,
320         infer_outlives_requirements,
321         infer_static_outlives_requirements,
322         inline,
323         intel,
324         into_iter,
325         IntoIterator,
326         into_result,
327         intrinsics,
328         irrefutable_let_patterns,
329         isize,
330         issue,
331         issue_5723_bootstrap,
332         issue_tracker_base_url,
333         item,
334         item_like_imports,
335         iter,
336         Iterator,
337         keyword,
338         kind,
339         label,
340         label_break_value,
341         lang,
342         lang_items,
343         lib,
344         lifetime,
345         link,
346         linkage,
347         link_args,
348         link_cfg,
349         link_llvm_intrinsics,
350         link_name,
351         link_section,
352         lint_reasons,
353         literal,
354         local_inner_macros,
355         log_syntax,
356         loop_break_value,
357         macro_at_most_once_rep,
358         macro_escape,
359         macro_export,
360         macro_lifetime_matcher,
361         macro_literal_matcher,
362         macro_reexport,
363         macro_rules,
364         macros_in_extern,
365         macro_use,
366         macro_vis_matcher,
367         main,
368         managed_boxes,
369         marker,
370         marker_trait_attr,
371         masked,
372         match_beginning_vert,
373         match_default_bindings,
374         may_dangle,
375         message,
376         meta,
377         min_const_fn,
378         min_const_unsafe_fn,
379         mips_target_feature,
380         mmx_target_feature,
381         module,
382         more_struct_aliases,
383         movbe_target_feature,
384         must_use,
385         naked,
386         naked_functions,
387         name,
388         needs_allocator,
389         needs_panic_runtime,
390         negate_unsigned,
391         never,
392         never_type,
393         new,
394         next,
395         __next,
396         nll,
397         no_builtins,
398         no_core,
399         no_crate_inject,
400         no_debug,
401         no_default_passes,
402         no_implicit_prelude,
403         no_inline,
404         no_link,
405         no_main,
406         no_mangle,
407         non_ascii_idents,
408         None,
409         non_exhaustive,
410         non_modrs_mods,
411         no_stack_check,
412         no_start,
413         no_std,
414         not,
415         note,
416         Ok,
417         omit_gdb_pretty_printer_section,
418         on,
419         on_unimplemented,
420         oom,
421         ops,
422         optimize,
423         optimize_attribute,
424         optin_builtin_traits,
425         option,
426         Option,
427         opt_out_copy,
428         or,
429         Ord,
430         Ordering,
431         Output,
432         overlapping_marker_traits,
433         packed,
434         panic,
435         panic_handler,
436         panic_impl,
437         panic_implementation,
438         panic_runtime,
439         partial_cmp,
440         PartialOrd,
441         passes,
442         pat,
443         path,
444         pattern_parentheses,
445         Pending,
446         pin,
447         Pin,
448         pinned,
449         platform_intrinsics,
450         plugin,
451         plugin_registrar,
452         plugins,
453         Poll,
454         poll_with_tls_context,
455         powerpc_target_feature,
456         precise_pointer_size_matching,
457         prelude,
458         prelude_import,
459         primitive,
460         proc_dash_macro: "proc-macro",
461         proc_macro,
462         proc_macro_attribute,
463         proc_macro_def_site,
464         proc_macro_derive,
465         proc_macro_expr,
466         proc_macro_gen,
467         proc_macro_hygiene,
468         proc_macro_mod,
469         proc_macro_non_items,
470         proc_macro_path_invoc,
471         profiler_runtime,
472         pub_restricted,
473         pushpop_unsafe,
474         quad_precision_float,
475         question_mark,
476         quote,
477         Range,
478         RangeFrom,
479         RangeFull,
480         RangeInclusive,
481         RangeTo,
482         RangeToInclusive,
483         raw_identifiers,
484         Ready,
485         reason,
486         recursion_limit,
487         reexport_test_harness_main,
488         reflect,
489         relaxed_adts,
490         repr,
491         repr128,
492         repr_align,
493         repr_align_enum,
494         repr_packed,
495         repr_simd,
496         repr_transparent,
497         re_rebalance_coherence,
498         result,
499         Result,
500         Return,
501         rlib,
502         rt,
503         rtm_target_feature,
504         rust,
505         rust_2015_preview,
506         rust_2018_preview,
507         rust_begin_unwind,
508         rustc_allocator_nounwind,
509         rustc_allow_const_fn_ptr,
510         rustc_args_required_const,
511         rustc_attrs,
512         rustc_clean,
513         rustc_const_unstable,
514         rustc_conversion_suggestion,
515         rustc_copy_clone_marker,
516         rustc_def_path,
517         rustc_deprecated,
518         rustc_diagnostic_macros,
519         rustc_dirty,
520         rustc_doc_only_macro,
521         rustc_dump_env_program_clauses,
522         rustc_dump_program_clauses,
523         rustc_dump_user_substs,
524         rustc_error,
525         rustc_expected_cgu_reuse,
526         rustc_if_this_changed,
527         rustc_inherit_overflow_checks,
528         rustc_layout,
529         rustc_layout_scalar_valid_range_end,
530         rustc_layout_scalar_valid_range_start,
531         rustc_mir,
532         rustc_nonnull_optimization_guaranteed,
533         rustc_object_lifetime_default,
534         rustc_on_unimplemented,
535         rustc_outlives,
536         rustc_paren_sugar,
537         rustc_partition_codegened,
538         rustc_partition_reused,
539         rustc_peek,
540         rustc_peek_definite_init,
541         rustc_peek_maybe_init,
542         rustc_peek_maybe_uninit,
543         rustc_private,
544         rustc_proc_macro_decls,
545         rustc_promotable,
546         rustc_regions,
547         rustc_stable,
548         rustc_std_internal_symbol,
549         rustc_symbol_name,
550         rustc_synthetic,
551         rustc_test_marker,
552         rustc_then_this_would_need,
553         rustc_transparent_macro,
554         rustc_variance,
555         rustdoc,
556         rust_eh_personality,
557         rust_eh_unwind_resume,
558         rust_oom,
559         __rust_unstable_column,
560         rvalue_static_promotion,
561         sanitizer_runtime,
562         self_in_typedefs,
563         self_struct_ctor,
564         Send,
565         should_panic,
566         simd,
567         simd_ffi,
568         since,
569         size,
570         slice_patterns,
571         slicing_syntax,
572         Some,
573         specialization,
574         speed,
575         spotlight,
576         sse4a_target_feature,
577         stable,
578         staged_api,
579         start,
580         static_in_const,
581         staticlib,
582         static_nobundle,
583         static_recursion,
584         std,
585         str,
586         stmt,
587         stmt_expr_attributes,
588         stop_after_dataflow,
589         struct_field_attributes,
590         struct_inherit,
591         structural_match,
592         struct_variant,
593         suggestion,
594         target_feature,
595         target_has_atomic,
596         target_thread_local,
597         task,
598         tbm_target_feature,
599         termination_trait,
600         termination_trait_test,
601         test,
602         test_2018_feature,
603         test_accepted_feature,
604         test_case,
605         test_removed_feature,
606         test_runner,
607         then_with,
608         thread_local,
609         tool_attributes,
610         tool_lints,
611         trace_macros,
612         trait_alias,
613         transmute,
614         transparent,
615         trivial_bounds,
616         Try,
617         try_blocks,
618         try_trait,
619         tt,
620         tuple_indexing,
621         ty,
622         type_alias_enum_variants,
623         type_ascription,
624         type_length_limit,
625         type_macros,
626         u128,
627         u16,
628         u32,
629         u64,
630         u8,
631         unboxed_closures,
632         underscore_const_names,
633         underscore_imports,
634         underscore_lifetimes,
635         uniform_paths,
636         universal_impl_trait,
637         unmarked_api,
638         unreachable_code,
639         unrestricted_attribute_tokens,
640         unsafe_destructor_blind_to_params,
641         unsafe_no_drop_flag,
642         unsized_locals,
643         unsized_tuple_coercion,
644         unstable,
645         untagged_unions,
646         unwind,
647         unwind_attributes,
648         unwrap_or,
649         used,
650         use_extern_macros,
651         use_nested_groups,
652         usize,
653         v1,
654         val,
655         vec,
656         Vec,
657         vis,
658         visible_private_types,
659         volatile,
660         warn,
661         warn_directory_ownership,
662         wasm_import_module,
663         wasm_target_feature,
664         while_let,
665         windows,
666         windows_subsystem,
667         Yield,
668     }
669 }
670
671 #[derive(Copy, Clone, Eq)]
672 pub struct Ident {
673     pub name: Symbol,
674     pub span: Span,
675 }
676
677 impl Ident {
678     #[inline]
679     /// Constructs a new identifier from a symbol and a span.
680     pub const fn new(name: Symbol, span: Span) -> Ident {
681         Ident { name, span }
682     }
683
684     /// Constructs a new identifier with an empty syntax context.
685     #[inline]
686     pub const fn with_empty_ctxt(name: Symbol) -> Ident {
687         Ident::new(name, DUMMY_SP)
688     }
689
690     #[inline]
691     pub fn invalid() -> Ident {
692         Ident::with_empty_ctxt(kw::Invalid)
693     }
694
695     /// Maps an interned string to an identifier with an empty syntax context.
696     pub fn from_interned_str(string: InternedString) -> Ident {
697         Ident::with_empty_ctxt(string.as_symbol())
698     }
699
700     /// Maps a string to an identifier with an empty span.
701     pub fn from_str(string: &str) -> Ident {
702         Ident::with_empty_ctxt(Symbol::intern(string))
703     }
704
705     /// Maps a string and a span to an identifier.
706     pub fn from_str_and_span(string: &str, span: Span) -> Ident {
707         Ident::new(Symbol::intern(string), span)
708     }
709
710     /// Replaces `lo` and `hi` with those from `span`, but keep hygiene context.
711     pub fn with_span_pos(self, span: Span) -> Ident {
712         Ident::new(self.name, span.with_ctxt(self.span.ctxt()))
713     }
714
715     pub fn without_first_quote(self) -> Ident {
716         Ident::new(Symbol::intern(self.as_str().trim_start_matches('\'')), self.span)
717     }
718
719     /// "Normalize" ident for use in comparisons using "item hygiene".
720     /// Identifiers with same string value become same if they came from the same "modern" macro
721     /// (e.g., `macro` item, but not `macro_rules` item) and stay different if they came from
722     /// different "modern" macros.
723     /// Technically, this operation strips all non-opaque marks from ident's syntactic context.
724     pub fn modern(self) -> Ident {
725         Ident::new(self.name, self.span.modern())
726     }
727
728     /// "Normalize" ident for use in comparisons using "local variable hygiene".
729     /// Identifiers with same string value become same if they came from the same non-transparent
730     /// macro (e.g., `macro` or `macro_rules!` items) and stay different if they came from different
731     /// non-transparent macros.
732     /// Technically, this operation strips all transparent marks from ident's syntactic context.
733     pub fn modern_and_legacy(self) -> Ident {
734         Ident::new(self.name, self.span.modern_and_legacy())
735     }
736
737     /// Transforms an identifier into one with the same name, but gensymed.
738     pub fn gensym(self) -> Ident {
739         let name = with_interner(|interner| interner.gensymed(self.name));
740         Ident::new(name, self.span)
741     }
742
743     /// Transforms an underscore identifier into one with the same name, but
744     /// gensymed. Leaves non-underscore identifiers unchanged.
745     pub fn gensym_if_underscore(self) -> Ident {
746         if self.name == kw::Underscore { self.gensym() } else { self }
747     }
748
749     // WARNING: this function is deprecated and will be removed in the future.
750     pub fn is_gensymed(self) -> bool {
751         with_interner(|interner| interner.is_gensymed(self.name))
752     }
753
754     pub fn as_str(self) -> LocalInternedString {
755         self.name.as_str()
756     }
757
758     pub fn as_interned_str(self) -> InternedString {
759         self.name.as_interned_str()
760     }
761 }
762
763 impl PartialEq for Ident {
764     fn eq(&self, rhs: &Self) -> bool {
765         self.name == rhs.name && self.span.ctxt() == rhs.span.ctxt()
766     }
767 }
768
769 impl Hash for Ident {
770     fn hash<H: Hasher>(&self, state: &mut H) {
771         self.name.hash(state);
772         self.span.ctxt().hash(state);
773     }
774 }
775
776 impl fmt::Debug for Ident {
777     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
778         write!(f, "{}{:?}", self.name, self.span.ctxt())
779     }
780 }
781
782 impl fmt::Display for Ident {
783     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
784         fmt::Display::fmt(&self.name, f)
785     }
786 }
787
788 impl Encodable for Ident {
789     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
790         if self.span.ctxt().modern() == SyntaxContext::empty() {
791             s.emit_str(&self.as_str())
792         } else { // FIXME(jseyfried): intercrate hygiene
793             let mut string = "#".to_owned();
794             string.push_str(&self.as_str());
795             s.emit_str(&string)
796         }
797     }
798 }
799
800 impl Decodable for Ident {
801     fn decode<D: Decoder>(d: &mut D) -> Result<Ident, D::Error> {
802         let string = d.read_str()?;
803         Ok(if !string.starts_with('#') {
804             Ident::from_str(&string)
805         } else { // FIXME(jseyfried): intercrate hygiene
806             Ident::from_str(&string[1..]).gensym()
807         })
808     }
809 }
810
811 /// A symbol is an interned or gensymed string. A gensym is a symbol that is
812 /// never equal to any other symbol.
813 ///
814 /// Conceptually, a gensym can be thought of as a normal symbol with an
815 /// invisible unique suffix. Gensyms are useful when creating new identifiers
816 /// that must not match any existing identifiers, e.g. during macro expansion
817 /// and syntax desugaring. Because gensyms should always be identifiers, all
818 /// gensym operations are on `Ident` rather than `Symbol`. (Indeed, in the
819 /// future the gensym-ness may be moved from `Symbol` to hygiene data.)
820 ///
821 /// Examples:
822 /// ```
823 /// assert_eq!(Ident::from_str("x"), Ident::from_str("x"))
824 /// assert_ne!(Ident::from_str("x").gensym(), Ident::from_str("x"))
825 /// assert_ne!(Ident::from_str("x").gensym(), Ident::from_str("x").gensym())
826 /// ```
827 /// Internally, a symbol is implemented as an index, and all operations
828 /// (including hashing, equality, and ordering) operate on that index. The use
829 /// of `newtype_index!` means that `Option<Symbol>` only takes up 4 bytes,
830 /// because `newtype_index!` reserves the last 256 values for tagging purposes.
831 ///
832 /// Note that `Symbol` cannot directly be a `newtype_index!` because it
833 /// implements `fmt::Debug`, `Encodable`, and `Decodable` in special ways.
834 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
835 pub struct Symbol(SymbolIndex);
836
837 newtype_index! {
838     pub struct SymbolIndex { .. }
839 }
840
841 impl Symbol {
842     const fn new(n: u32) -> Self {
843         Symbol(SymbolIndex::from_u32_const(n))
844     }
845
846     /// Maps a string to its interned representation.
847     pub fn intern(string: &str) -> Self {
848         with_interner(|interner| interner.intern(string))
849     }
850
851     pub fn as_str(self) -> LocalInternedString {
852         with_interner(|interner| unsafe {
853             LocalInternedString {
854                 string: std::mem::transmute::<&str, &str>(interner.get(self))
855             }
856         })
857     }
858
859     pub fn as_interned_str(self) -> InternedString {
860         with_interner(|interner| InternedString {
861             symbol: interner.interned(self)
862         })
863     }
864
865     pub fn as_u32(self) -> u32 {
866         self.0.as_u32()
867     }
868 }
869
870 impl fmt::Debug for Symbol {
871     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
872         let is_gensymed = with_interner(|interner| interner.is_gensymed(*self));
873         if is_gensymed {
874             write!(f, "{}({:?})", self, self.0)
875         } else {
876             write!(f, "{}", self)
877         }
878     }
879 }
880
881 impl fmt::Display for Symbol {
882     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
883         fmt::Display::fmt(&self.as_str(), f)
884     }
885 }
886
887 impl Encodable for Symbol {
888     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
889         s.emit_str(&self.as_str())
890     }
891 }
892
893 impl Decodable for Symbol {
894     fn decode<D: Decoder>(d: &mut D) -> Result<Symbol, D::Error> {
895         Ok(Symbol::intern(&d.read_str()?))
896     }
897 }
898
899 // The `&'static str`s in this type actually point into the arena.
900 //
901 // Note that normal symbols are indexed upward from 0, and gensyms are indexed
902 // downward from SymbolIndex::MAX_AS_U32.
903 #[derive(Default)]
904 pub struct Interner {
905     arena: DroplessArena,
906     names: FxHashMap<&'static str, Symbol>,
907     strings: Vec<&'static str>,
908     gensyms: Vec<Symbol>,
909 }
910
911 impl Interner {
912     fn prefill(init: &[&'static str]) -> Self {
913         let symbols = (0 .. init.len() as u32).map(Symbol::new);
914         Interner {
915             strings: init.to_vec(),
916             names: init.iter().copied().zip(symbols).collect(),
917             ..Default::default()
918         }
919     }
920
921     pub fn intern(&mut self, string: &str) -> Symbol {
922         if let Some(&name) = self.names.get(string) {
923             return name;
924         }
925
926         let name = Symbol::new(self.strings.len() as u32);
927
928         // `from_utf8_unchecked` is safe since we just allocated a `&str` which is known to be
929         // UTF-8.
930         let string: &str = unsafe {
931             str::from_utf8_unchecked(self.arena.alloc_slice(string.as_bytes()))
932         };
933         // It is safe to extend the arena allocation to `'static` because we only access
934         // these while the arena is still alive.
935         let string: &'static str =  unsafe {
936             &*(string as *const str)
937         };
938         self.strings.push(string);
939         self.names.insert(string, name);
940         name
941     }
942
943     fn interned(&self, symbol: Symbol) -> Symbol {
944         if (symbol.0.as_usize()) < self.strings.len() {
945             symbol
946         } else {
947             self.gensyms[(SymbolIndex::MAX_AS_U32 - symbol.0.as_u32()) as usize]
948         }
949     }
950
951     fn gensymed(&mut self, symbol: Symbol) -> Symbol {
952         self.gensyms.push(symbol);
953         Symbol::new(SymbolIndex::MAX_AS_U32 - self.gensyms.len() as u32 + 1)
954     }
955
956     fn is_gensymed(&mut self, symbol: Symbol) -> bool {
957         symbol.0.as_usize() >= self.strings.len()
958     }
959
960     // Get the symbol as a string. `Symbol::as_str()` should be used in
961     // preference to this function.
962     pub fn get(&self, symbol: Symbol) -> &str {
963         match self.strings.get(symbol.0.as_usize()) {
964             Some(string) => string,
965             None => {
966                 let symbol = self.gensyms[(SymbolIndex::MAX_AS_U32 - symbol.0.as_u32()) as usize];
967                 self.strings[symbol.0.as_usize()]
968             }
969         }
970     }
971 }
972
973 // This module has a very short name because it's used a lot.
974 pub mod kw {
975     use super::Symbol;
976     keywords!();
977 }
978
979 // This module has a very short name because it's used a lot.
980 pub mod sym {
981     use std::convert::TryInto;
982     use super::Symbol;
983
984     symbols!();
985
986     // Get the symbol for an integer. The first few non-negative integers each
987     // have a static symbol and therefore are fast.
988     pub fn integer<N: TryInto<usize> + Copy + ToString>(n: N) -> Symbol {
989         if let Result::Ok(idx) = n.try_into() {
990             if let Option::Some(&sym) = digits_array.get(idx) {
991                 return sym;
992             }
993         }
994         Symbol::intern(&n.to_string())
995     }
996 }
997
998 impl Symbol {
999     fn is_used_keyword_2018(self) -> bool {
1000         self == kw::Dyn
1001     }
1002
1003     fn is_unused_keyword_2018(self) -> bool {
1004         self >= kw::Async && self <= kw::Try
1005     }
1006
1007     /// Used for sanity checking rustdoc keyword sections.
1008     pub fn is_doc_keyword(self) -> bool {
1009         self <= kw::Union
1010     }
1011 }
1012
1013 impl Ident {
1014     // Returns `true` for reserved identifiers used internally for elided lifetimes,
1015     // unnamed method parameters, crate root module, error recovery etc.
1016     pub fn is_special(self) -> bool {
1017         self.name <= kw::Underscore
1018     }
1019
1020     /// Returns `true` if the token is a keyword used in the language.
1021     pub fn is_used_keyword(self) -> bool {
1022         // Note: `span.edition()` is relatively expensive, don't call it unless necessary.
1023         self.name >= kw::As && self.name <= kw::While ||
1024         self.name.is_used_keyword_2018() && self.span.rust_2018()
1025     }
1026
1027     /// Returns `true` if the token is a keyword reserved for possible future use.
1028     pub fn is_unused_keyword(self) -> bool {
1029         // Note: `span.edition()` is relatively expensive, don't call it unless necessary.
1030         self.name >= kw::Abstract && self.name <= kw::Yield ||
1031         self.name.is_unused_keyword_2018() && self.span.rust_2018()
1032     }
1033
1034     /// Returns `true` if the token is either a special identifier or a keyword.
1035     pub fn is_reserved(self) -> bool {
1036         self.is_special() || self.is_used_keyword() || self.is_unused_keyword()
1037     }
1038
1039     /// A keyword or reserved identifier that can be used as a path segment.
1040     pub fn is_path_segment_keyword(self) -> bool {
1041         self.name == kw::Super ||
1042         self.name == kw::SelfLower ||
1043         self.name == kw::SelfUpper ||
1044         self.name == kw::Crate ||
1045         self.name == kw::PathRoot ||
1046         self.name == kw::DollarCrate
1047     }
1048
1049     /// This identifier can be a raw identifier.
1050     pub fn can_be_raw(self) -> bool {
1051         self.name != kw::Invalid && self.name != kw::Underscore &&
1052         !self.is_path_segment_keyword()
1053     }
1054
1055     /// We see this identifier in a normal identifier position, like variable name or a type.
1056     /// How was it written originally? Did it use the raw form? Let's try to guess.
1057     pub fn is_raw_guess(self) -> bool {
1058         self.can_be_raw() && self.is_reserved()
1059     }
1060 }
1061
1062 // If an interner exists, return it. Otherwise, prepare a fresh one.
1063 #[inline]
1064 fn with_interner<T, F: FnOnce(&mut Interner) -> T>(f: F) -> T {
1065     GLOBALS.with(|globals| f(&mut *globals.symbol_interner.lock()))
1066 }
1067
1068 /// An alternative to `Symbol` and `InternedString`, useful when the chars
1069 /// within the symbol need to be accessed. It is best used for temporary
1070 /// values.
1071 ///
1072 /// Because the interner outlives any thread which uses this type, we can
1073 /// safely treat `string` which points to interner data, as an immortal string,
1074 /// as long as this type never crosses between threads.
1075 //
1076 // FIXME: ensure that the interner outlives any thread which uses
1077 // `LocalInternedString`, by creating a new thread right after constructing the
1078 // interner.
1079 #[derive(Clone, Copy, Hash, PartialOrd, Eq, Ord)]
1080 pub struct LocalInternedString {
1081     string: &'static str,
1082 }
1083
1084 impl LocalInternedString {
1085     /// Maps a string to its interned representation.
1086     pub fn intern(string: &str) -> Self {
1087         let string = with_interner(|interner| {
1088             let symbol = interner.intern(string);
1089             interner.strings[symbol.0.as_usize()]
1090         });
1091         LocalInternedString {
1092             string: unsafe { std::mem::transmute::<&str, &str>(string) }
1093         }
1094     }
1095
1096     pub fn as_interned_str(self) -> InternedString {
1097         InternedString {
1098             symbol: Symbol::intern(self.string)
1099         }
1100     }
1101
1102     pub fn get(&self) -> &str {
1103         // This returns a valid string since we ensure that `self` outlives the interner
1104         // by creating the interner on a thread which outlives threads which can access it.
1105         // This type cannot move to a thread which outlives the interner since it does
1106         // not implement Send.
1107         self.string
1108     }
1109 }
1110
1111 impl<U: ?Sized> std::convert::AsRef<U> for LocalInternedString
1112 where
1113     str: std::convert::AsRef<U>
1114 {
1115     fn as_ref(&self) -> &U {
1116         self.string.as_ref()
1117     }
1118 }
1119
1120 impl<T: std::ops::Deref<Target = str>> std::cmp::PartialEq<T> for LocalInternedString {
1121     fn eq(&self, other: &T) -> bool {
1122         self.string == other.deref()
1123     }
1124 }
1125
1126 impl std::cmp::PartialEq<LocalInternedString> for str {
1127     fn eq(&self, other: &LocalInternedString) -> bool {
1128         self == other.string
1129     }
1130 }
1131
1132 impl<'a> std::cmp::PartialEq<LocalInternedString> for &'a str {
1133     fn eq(&self, other: &LocalInternedString) -> bool {
1134         *self == other.string
1135     }
1136 }
1137
1138 impl std::cmp::PartialEq<LocalInternedString> for String {
1139     fn eq(&self, other: &LocalInternedString) -> bool {
1140         self == other.string
1141     }
1142 }
1143
1144 impl<'a> std::cmp::PartialEq<LocalInternedString> for &'a String {
1145     fn eq(&self, other: &LocalInternedString) -> bool {
1146         *self == other.string
1147     }
1148 }
1149
1150 impl !Send for LocalInternedString {}
1151 impl !Sync for LocalInternedString {}
1152
1153 impl std::ops::Deref for LocalInternedString {
1154     type Target = str;
1155     fn deref(&self) -> &str { self.string }
1156 }
1157
1158 impl fmt::Debug for LocalInternedString {
1159     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1160         fmt::Debug::fmt(self.string, f)
1161     }
1162 }
1163
1164 impl fmt::Display for LocalInternedString {
1165     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1166         fmt::Display::fmt(self.string, f)
1167     }
1168 }
1169
1170 impl Decodable for LocalInternedString {
1171     fn decode<D: Decoder>(d: &mut D) -> Result<LocalInternedString, D::Error> {
1172         Ok(LocalInternedString::intern(&d.read_str()?))
1173     }
1174 }
1175
1176 impl Encodable for LocalInternedString {
1177     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1178         s.emit_str(self.string)
1179     }
1180 }
1181
1182 /// An alternative to `Symbol` that is focused on string contents. It has two
1183 /// main differences to `Symbol`.
1184 ///
1185 /// First, its implementations of `Hash`, `PartialOrd` and `Ord` work with the
1186 /// string chars rather than the symbol integer. This is useful when hash
1187 /// stability is required across compile sessions, or a guaranteed sort
1188 /// ordering is required.
1189 ///
1190 /// Second, gensym-ness is irrelevant. E.g.:
1191 /// ```
1192 /// assert_ne!(Symbol::gensym("x"), Symbol::gensym("x"))
1193 /// assert_eq!(Symbol::gensym("x").as_interned_str(), Symbol::gensym("x").as_interned_str())
1194 /// ```
1195 #[derive(Clone, Copy, PartialEq, Eq)]
1196 pub struct InternedString {
1197     symbol: Symbol,
1198 }
1199
1200 impl InternedString {
1201     /// Maps a string to its interned representation.
1202     pub fn intern(string: &str) -> Self {
1203         InternedString {
1204             symbol: Symbol::intern(string)
1205         }
1206     }
1207
1208     pub fn with<F: FnOnce(&str) -> R, R>(self, f: F) -> R {
1209         let str = with_interner(|interner| {
1210             interner.get(self.symbol) as *const str
1211         });
1212         // This is safe because the interner keeps string alive until it is dropped.
1213         // We can access it because we know the interner is still alive since we use a
1214         // scoped thread local to access it, and it was alive at the beginning of this scope
1215         unsafe { f(&*str) }
1216     }
1217
1218     fn with2<F: FnOnce(&str, &str) -> R, R>(self, other: &InternedString, f: F) -> R {
1219         let (self_str, other_str) = with_interner(|interner| {
1220             (interner.get(self.symbol) as *const str,
1221              interner.get(other.symbol) as *const str)
1222         });
1223         // This is safe for the same reason that `with` is safe.
1224         unsafe { f(&*self_str, &*other_str) }
1225     }
1226
1227     pub fn as_symbol(self) -> Symbol {
1228         self.symbol
1229     }
1230
1231     pub fn as_str(self) -> LocalInternedString {
1232         self.symbol.as_str()
1233     }
1234 }
1235
1236 impl Hash for InternedString {
1237     fn hash<H: Hasher>(&self, state: &mut H) {
1238         self.with(|str| str.hash(state))
1239     }
1240 }
1241
1242 impl PartialOrd<InternedString> for InternedString {
1243     fn partial_cmp(&self, other: &InternedString) -> Option<Ordering> {
1244         if self.symbol == other.symbol {
1245             return Some(Ordering::Equal);
1246         }
1247         self.with2(other, |self_str, other_str| self_str.partial_cmp(other_str))
1248     }
1249 }
1250
1251 impl Ord for InternedString {
1252     fn cmp(&self, other: &InternedString) -> Ordering {
1253         if self.symbol == other.symbol {
1254             return Ordering::Equal;
1255         }
1256         self.with2(other, |self_str, other_str| self_str.cmp(other_str))
1257     }
1258 }
1259
1260 impl fmt::Debug for InternedString {
1261     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1262         self.with(|str| fmt::Debug::fmt(&str, f))
1263     }
1264 }
1265
1266 impl fmt::Display for InternedString {
1267     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1268         self.with(|str| fmt::Display::fmt(&str, f))
1269     }
1270 }
1271
1272 impl Decodable for InternedString {
1273     fn decode<D: Decoder>(d: &mut D) -> Result<InternedString, D::Error> {
1274         Ok(InternedString::intern(&d.read_str()?))
1275     }
1276 }
1277
1278 impl Encodable for InternedString {
1279     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1280         self.with(|string| s.emit_str(string))
1281     }
1282 }
1283
1284 #[cfg(test)]
1285 mod tests {
1286     use super::*;
1287     use crate::Globals;
1288     use crate::edition;
1289
1290     #[test]
1291     fn interner_tests() {
1292         let mut i: Interner = Interner::default();
1293         // first one is zero:
1294         assert_eq!(i.intern("dog"), Symbol::new(0));
1295         // re-use gets the same entry:
1296         assert_eq!(i.intern("dog"), Symbol::new(0));
1297         // different string gets a different #:
1298         assert_eq!(i.intern("cat"), Symbol::new(1));
1299         assert_eq!(i.intern("cat"), Symbol::new(1));
1300         // dog is still at zero
1301         assert_eq!(i.intern("dog"), Symbol::new(0));
1302         let z = i.intern("zebra");
1303         assert_eq!(i.gensymed(z), Symbol::new(SymbolIndex::MAX_AS_U32));
1304         // gensym of same string gets new number:
1305         assert_eq!(i.gensymed(z), Symbol::new(SymbolIndex::MAX_AS_U32 - 1));
1306         // gensym of *existing* string gets new number:
1307         let d = i.intern("dog");
1308         assert_eq!(i.gensymed(d), Symbol::new(SymbolIndex::MAX_AS_U32 - 2));
1309     }
1310
1311     #[test]
1312     fn without_first_quote_test() {
1313         GLOBALS.set(&Globals::new(edition::DEFAULT_EDITION), || {
1314             let i = Ident::from_str("'break");
1315             assert_eq!(i.without_first_quote().name, kw::Break);
1316         });
1317     }
1318 }