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