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