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