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