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