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