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