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