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