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