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