]> git.lizzy.rs Git - rust.git/blob - src/libsyntax_pos/symbol.rs
Rollup merge of #65775 - matthewjasper:reempty, r=pnkfelix
[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_msp430_interrupt,
114         abi_ptx,
115         abi_sysv64,
116         abi_thiscall,
117         abi_unadjusted,
118         abi_vectorcall,
119         abi_x86_interrupt,
120         aborts,
121         advanced_slice_patterns,
122         adx_target_feature,
123         alias,
124         align,
125         alignstack,
126         all,
127         allocator,
128         allocator_internals,
129         alloc_error_handler,
130         allow,
131         allowed,
132         allow_fail,
133         allow_internal_unsafe,
134         allow_internal_unstable,
135         allow_internal_unstable_backcompat_hack,
136         always,
137         and,
138         any,
139         arbitrary_enum_discriminant,
140         arbitrary_self_types,
141         Arguments,
142         ArgumentV1,
143         arm_target_feature,
144         asm,
145         assert,
146         associated_consts,
147         associated_type_bounds,
148         associated_type_defaults,
149         associated_types,
150         async_await,
151         async_closure,
152         attr,
153         attributes,
154         attr_literals,
155         augmented_assignments,
156         automatically_derived,
157         avx512_target_feature,
158         await_macro,
159         begin_panic,
160         bench,
161         bin,
162         bind_by_move_pattern_guards,
163         block,
164         bool,
165         borrowck_graphviz_postflow,
166         borrowck_graphviz_preflow,
167         box_patterns,
168         box_syntax,
169         braced_empty_structs,
170         C,
171         cdylib,
172         cfg,
173         cfg_attr,
174         cfg_attr_multi,
175         cfg_doctest,
176         cfg_target_feature,
177         cfg_target_has_atomic,
178         cfg_target_thread_local,
179         cfg_target_vendor,
180         char,
181         clippy,
182         clone,
183         Clone,
184         clone_closures,
185         clone_from,
186         closure_to_fn_coercion,
187         cmp,
188         cmpxchg16b_target_feature,
189         cold,
190         column,
191         compile_error,
192         compiler_builtins,
193         concat,
194         concat_idents,
195         conservative_impl_trait,
196         console,
197         const_compare_raw_pointers,
198         const_constructor,
199         const_extern_fn,
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_ordinal,
393         link_section,
394         LintPass,
395         lint_reasons,
396         literal,
397         local_inner_macros,
398         log_syntax,
399         loop_break_value,
400         macro_at_most_once_rep,
401         macro_escape,
402         macro_export,
403         macro_lifetime_matcher,
404         macro_literal_matcher,
405         macro_reexport,
406         macro_rules,
407         macros_in_extern,
408         macro_use,
409         macro_vis_matcher,
410         main,
411         managed_boxes,
412         marker,
413         marker_trait_attr,
414         masked,
415         match_beginning_vert,
416         match_default_bindings,
417         may_dangle,
418         mem,
419         member_constraints,
420         message,
421         meta,
422         min_const_fn,
423         min_const_unsafe_fn,
424         mips_target_feature,
425         mmx_target_feature,
426         module,
427         module_path,
428         more_struct_aliases,
429         movbe_target_feature,
430         must_use,
431         naked,
432         naked_functions,
433         name,
434         needs_allocator,
435         needs_panic_runtime,
436         negate_unsigned,
437         never,
438         never_type,
439         new,
440         next,
441         __next,
442         nll,
443         no_builtins,
444         no_core,
445         no_crate_inject,
446         no_debug,
447         no_default_passes,
448         no_implicit_prelude,
449         no_inline,
450         no_link,
451         no_main,
452         no_mangle,
453         non_ascii_idents,
454         None,
455         non_exhaustive,
456         non_modrs_mods,
457         no_stack_check,
458         no_start,
459         no_std,
460         not,
461         note,
462         object_safe_for_dispatch,
463         Ok,
464         omit_gdb_pretty_printer_section,
465         on,
466         on_unimplemented,
467         oom,
468         ops,
469         optimize,
470         optimize_attribute,
471         optin_builtin_traits,
472         option,
473         Option,
474         option_env,
475         opt_out_copy,
476         or,
477         or_patterns,
478         Ord,
479         Ordering,
480         Output,
481         overlapping_marker_traits,
482         packed,
483         panic,
484         panic_handler,
485         panic_impl,
486         panic_implementation,
487         panic_runtime,
488         parent_trait,
489         partial_cmp,
490         param_attrs,
491         PartialEq,
492         PartialOrd,
493         passes,
494         pat,
495         path,
496         pattern_parentheses,
497         Pending,
498         pin,
499         Pin,
500         pinned,
501         platform_intrinsics,
502         plugin,
503         plugin_registrar,
504         plugins,
505         Poll,
506         poll_with_tls_context,
507         powerpc_target_feature,
508         precise_pointer_size_matching,
509         prelude,
510         prelude_import,
511         primitive,
512         proc_dash_macro: "proc-macro",
513         proc_macro,
514         proc_macro_attribute,
515         proc_macro_def_site,
516         proc_macro_derive,
517         proc_macro_expr,
518         proc_macro_gen,
519         proc_macro_hygiene,
520         proc_macro_internals,
521         proc_macro_mod,
522         proc_macro_non_items,
523         proc_macro_path_invoc,
524         profiler_runtime,
525         pub_restricted,
526         pushpop_unsafe,
527         quad_precision_float,
528         question_mark,
529         quote,
530         Range,
531         RangeFrom,
532         RangeFull,
533         RangeInclusive,
534         RangeTo,
535         RangeToInclusive,
536         raw_dylib,
537         raw_identifiers,
538         Ready,
539         reason,
540         recursion_limit,
541         reexport_test_harness_main,
542         reflect,
543         relaxed_adts,
544         repr,
545         repr128,
546         repr_align,
547         repr_align_enum,
548         repr_packed,
549         repr_simd,
550         repr_transparent,
551         re_rebalance_coherence,
552         result,
553         Result,
554         Return,
555         rhs,
556         rlib,
557         rt,
558         rtm_target_feature,
559         rust,
560         rust_2015_preview,
561         rust_2018_preview,
562         rust_begin_unwind,
563         rustc,
564         RustcDecodable,
565         RustcEncodable,
566         rustc_allocator,
567         rustc_allocator_nounwind,
568         rustc_allow_const_fn_ptr,
569         rustc_args_required_const,
570         rustc_attrs,
571         rustc_builtin_macro,
572         rustc_clean,
573         rustc_const_unstable,
574         rustc_conversion_suggestion,
575         rustc_def_path,
576         rustc_deprecated,
577         rustc_diagnostic_item,
578         rustc_diagnostic_macros,
579         rustc_dirty,
580         rustc_dummy,
581         rustc_dump_env_program_clauses,
582         rustc_dump_program_clauses,
583         rustc_dump_user_substs,
584         rustc_error,
585         rustc_expected_cgu_reuse,
586         rustc_if_this_changed,
587         rustc_inherit_overflow_checks,
588         rustc_layout,
589         rustc_layout_scalar_valid_range_end,
590         rustc_layout_scalar_valid_range_start,
591         rustc_macro_transparency,
592         rustc_mir,
593         rustc_nonnull_optimization_guaranteed,
594         rustc_object_lifetime_default,
595         rustc_on_unimplemented,
596         rustc_outlives,
597         rustc_paren_sugar,
598         rustc_partition_codegened,
599         rustc_partition_reused,
600         rustc_peek,
601         rustc_peek_definite_init,
602         rustc_peek_maybe_init,
603         rustc_peek_maybe_uninit,
604         rustc_peek_indirectly_mutable,
605         rustc_private,
606         rustc_proc_macro_decls,
607         rustc_promotable,
608         rustc_regions,
609         rustc_stable,
610         rustc_std_internal_symbol,
611         rustc_symbol_name,
612         rustc_synthetic,
613         rustc_reservation_impl,
614         rustc_test_marker,
615         rustc_then_this_would_need,
616         rustc_variance,
617         rustdoc,
618         rustfmt,
619         rust_eh_personality,
620         rust_eh_unwind_resume,
621         rust_oom,
622         rvalue_static_promotion,
623         sanitizer_runtime,
624         _Self,
625         self_in_typedefs,
626         self_struct_ctor,
627         should_panic,
628         simd,
629         simd_ffi,
630         since,
631         size,
632         slice_patterns,
633         slicing_syntax,
634         soft,
635         Some,
636         specialization,
637         speed,
638         spotlight,
639         sse4a_target_feature,
640         stable,
641         staged_api,
642         start,
643         static_in_const,
644         staticlib,
645         static_nobundle,
646         static_recursion,
647         std,
648         std_inject,
649         str,
650         stringify,
651         stmt,
652         stmt_expr_attributes,
653         stop_after_dataflow,
654         struct_field_attributes,
655         struct_inherit,
656         structural_match,
657         struct_variant,
658         sty,
659         suggestion,
660         target_feature,
661         target_has_atomic,
662         target_has_atomic_load_store,
663         target_thread_local,
664         task,
665         tbm_target_feature,
666         termination_trait,
667         termination_trait_test,
668         test,
669         test_2018_feature,
670         test_accepted_feature,
671         test_case,
672         test_removed_feature,
673         test_runner,
674         then_with,
675         thread_local,
676         tool_attributes,
677         tool_lints,
678         trace_macros,
679         track_caller,
680         trait_alias,
681         transmute,
682         transparent,
683         transparent_enums,
684         transparent_unions,
685         trivial_bounds,
686         Try,
687         try_blocks,
688         try_trait,
689         tt,
690         tuple_indexing,
691         Ty,
692         ty,
693         type_alias_impl_trait,
694         TyCtxt,
695         TyKind,
696         type_alias_enum_variants,
697         type_ascription,
698         type_length_limit,
699         type_macros,
700         u128,
701         u16,
702         u32,
703         u64,
704         u8,
705         unboxed_closures,
706         underscore_const_names,
707         underscore_imports,
708         underscore_lifetimes,
709         uniform_paths,
710         uninitialized,
711         universal_impl_trait,
712         unmarked_api,
713         unreachable_code,
714         unrestricted_attribute_tokens,
715         unsafe_no_drop_flag,
716         unsized_locals,
717         unsized_tuple_coercion,
718         unstable,
719         untagged_unions,
720         unwind,
721         unwind_attributes,
722         unwrap_or,
723         used,
724         use_extern_macros,
725         use_nested_groups,
726         usize,
727         v1,
728         val,
729         vec,
730         Vec,
731         vis,
732         visible_private_types,
733         volatile,
734         warn,
735         warn_directory_ownership,
736         wasm_import_module,
737         wasm_target_feature,
738         while_let,
739         windows,
740         windows_subsystem,
741         Yield,
742         zeroed,
743     }
744 }
745
746 #[derive(Copy, Clone, Eq)]
747 pub struct Ident {
748     pub name: Symbol,
749     pub span: Span,
750 }
751
752 impl Ident {
753     #[inline]
754     /// Constructs a new identifier from a symbol and a span.
755     pub const fn new(name: Symbol, span: Span) -> Ident {
756         Ident { name, span }
757     }
758
759     /// Constructs a new identifier with a dummy span.
760     #[inline]
761     pub const fn with_dummy_span(name: Symbol) -> Ident {
762         Ident::new(name, DUMMY_SP)
763     }
764
765     #[inline]
766     pub fn invalid() -> Ident {
767         Ident::with_dummy_span(kw::Invalid)
768     }
769
770     /// Maps a string to an identifier with a dummy span.
771     pub fn from_str(string: &str) -> Ident {
772         Ident::with_dummy_span(Symbol::intern(string))
773     }
774
775     /// Maps a string and a span to an identifier.
776     pub fn from_str_and_span(string: &str, span: Span) -> Ident {
777         Ident::new(Symbol::intern(string), span)
778     }
779
780     /// Replaces `lo` and `hi` with those from `span`, but keep hygiene context.
781     pub fn with_span_pos(self, span: Span) -> Ident {
782         Ident::new(self.name, span.with_ctxt(self.span.ctxt()))
783     }
784
785     pub fn without_first_quote(self) -> Ident {
786         Ident::new(Symbol::intern(self.as_str().trim_start_matches('\'')), self.span)
787     }
788
789     /// "Normalize" ident for use in comparisons using "item hygiene".
790     /// Identifiers with same string value become same if they came from the same "modern" macro
791     /// (e.g., `macro` item, but not `macro_rules` item) and stay different if they came from
792     /// different "modern" macros.
793     /// Technically, this operation strips all non-opaque marks from ident's syntactic context.
794     pub fn modern(self) -> Ident {
795         Ident::new(self.name, self.span.modern())
796     }
797
798     /// "Normalize" ident for use in comparisons using "local variable hygiene".
799     /// Identifiers with same string value become same if they came from the same non-transparent
800     /// macro (e.g., `macro` or `macro_rules!` items) and stay different if they came from different
801     /// non-transparent macros.
802     /// Technically, this operation strips all transparent marks from ident's syntactic context.
803     pub fn modern_and_legacy(self) -> Ident {
804         Ident::new(self.name, self.span.modern_and_legacy())
805     }
806
807     /// Convert the name to a `LocalInternedString`. This is a slowish
808     /// operation because it requires locking the symbol interner.
809     pub fn as_str(self) -> LocalInternedString {
810         self.name.as_str()
811     }
812 }
813
814 impl PartialEq for Ident {
815     fn eq(&self, rhs: &Self) -> bool {
816         self.name == rhs.name && self.span.ctxt() == rhs.span.ctxt()
817     }
818 }
819
820 impl Hash for Ident {
821     fn hash<H: Hasher>(&self, state: &mut H) {
822         self.name.hash(state);
823         self.span.ctxt().hash(state);
824     }
825 }
826
827 impl fmt::Debug for Ident {
828     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
829         write!(f, "{}{:?}", self.name, self.span.ctxt())
830     }
831 }
832
833 impl fmt::Display for Ident {
834     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
835         fmt::Display::fmt(&self.name, f)
836     }
837 }
838
839 impl UseSpecializedEncodable for Ident {
840     fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
841         s.emit_struct("Ident", 2, |s| {
842             s.emit_struct_field("name", 0, |s| {
843                 self.name.encode(s)
844             })?;
845             s.emit_struct_field("span", 1, |s| {
846                 self.span.encode(s)
847             })
848         })
849     }
850 }
851
852 impl UseSpecializedDecodable for Ident {
853     fn default_decode<D: Decoder>(d: &mut D) -> Result<Self, D::Error> {
854         d.read_struct("Ident", 2, |d| {
855             Ok(Ident {
856                 name: d.read_struct_field("name", 0, Decodable::decode)?,
857                 span: d.read_struct_field("span", 1, Decodable::decode)?,
858             })
859         })
860     }
861 }
862
863 /// An interned string.
864 ///
865 /// Internally, a `Symbol` is implemented as an index, and all operations
866 /// (including hashing, equality, and ordering) operate on that index. The use
867 /// of `rustc_index::newtype_index!` means that `Option<Symbol>` only takes up 4 bytes,
868 /// because `rustc_index::newtype_index!` reserves the last 256 values for tagging purposes.
869 ///
870 /// Note that `Symbol` cannot directly be a `rustc_index::newtype_index!` because it
871 /// implements `fmt::Debug`, `Encodable`, and `Decodable` in special ways.
872 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
873 pub struct Symbol(SymbolIndex);
874
875 rustc_index::newtype_index! {
876     pub struct SymbolIndex { .. }
877 }
878
879 impl Symbol {
880     const fn new(n: u32) -> Self {
881         Symbol(SymbolIndex::from_u32_const(n))
882     }
883
884     /// Maps a string to its interned representation.
885     pub fn intern(string: &str) -> Self {
886         with_interner(|interner| interner.intern(string))
887     }
888
889     /// Access the symbol's chars. This is a slowish operation because it
890     /// requires locking the symbol interner.
891     pub fn with<F: FnOnce(&str) -> R, R>(self, f: F) -> R {
892         with_interner(|interner| {
893             f(interner.get(self))
894         })
895     }
896
897     /// Convert to a `LocalInternedString`. This is a slowish operation because
898     /// it requires locking the symbol interner.
899     pub fn as_str(self) -> LocalInternedString {
900         with_interner(|interner| unsafe {
901             LocalInternedString {
902                 string: std::mem::transmute::<&str, &str>(interner.get(self))
903             }
904         })
905     }
906
907     pub fn as_u32(self) -> u32 {
908         self.0.as_u32()
909     }
910 }
911
912 impl fmt::Debug for Symbol {
913     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
914         self.with(|str| fmt::Debug::fmt(&str, f))
915     }
916 }
917
918 impl fmt::Display for Symbol {
919     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
920         self.with(|str| fmt::Display::fmt(&str, f))
921     }
922 }
923
924 impl Encodable for Symbol {
925     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
926         self.with(|string| s.emit_str(string))
927     }
928 }
929
930 impl Decodable for Symbol {
931     fn decode<D: Decoder>(d: &mut D) -> Result<Symbol, D::Error> {
932         Ok(Symbol::intern(&d.read_str()?))
933     }
934 }
935
936 // The `&'static str`s in this type actually point into the arena.
937 #[derive(Default)]
938 pub struct Interner {
939     arena: DroplessArena,
940     names: FxHashMap<&'static str, Symbol>,
941     strings: Vec<&'static str>,
942 }
943
944 impl Interner {
945     fn prefill(init: &[&'static str]) -> Self {
946         Interner {
947             strings: init.into(),
948             names: init.iter().copied().zip((0..).map(Symbol::new)).collect(),
949             ..Default::default()
950         }
951     }
952
953     pub fn intern(&mut self, string: &str) -> Symbol {
954         if let Some(&name) = self.names.get(string) {
955             return name;
956         }
957
958         let name = Symbol::new(self.strings.len() as u32);
959
960         // `from_utf8_unchecked` is safe since we just allocated a `&str` which is known to be
961         // UTF-8.
962         let string: &str = unsafe {
963             str::from_utf8_unchecked(self.arena.alloc_slice(string.as_bytes()))
964         };
965         // It is safe to extend the arena allocation to `'static` because we only access
966         // these while the arena is still alive.
967         let string: &'static str =  unsafe {
968             &*(string as *const str)
969         };
970         self.strings.push(string);
971         self.names.insert(string, name);
972         name
973     }
974     // Get the symbol as a string. `Symbol::as_str()` should be used in
975     // preference to this function.
976     pub fn get(&self, symbol: Symbol) -> &str {
977         self.strings[symbol.0.as_usize()]
978     }
979 }
980
981 // This module has a very short name because it's used a lot.
982 pub mod kw {
983     use super::Symbol;
984     keywords!();
985 }
986
987 // This module has a very short name because it's used a lot.
988 pub mod sym {
989     use std::convert::TryInto;
990     use super::Symbol;
991
992     symbols!();
993
994     // Get the symbol for an integer. The first few non-negative integers each
995     // have a static symbol and therefore are fast.
996     pub fn integer<N: TryInto<usize> + Copy + ToString>(n: N) -> Symbol {
997         if let Result::Ok(idx) = n.try_into() {
998             if let Option::Some(&sym) = digits_array.get(idx) {
999                 return sym;
1000             }
1001         }
1002         Symbol::intern(&n.to_string())
1003     }
1004 }
1005
1006 impl Symbol {
1007     fn is_used_keyword_2018(self) -> bool {
1008         self >= kw::Async && self <= kw::Dyn
1009     }
1010
1011     fn is_unused_keyword_2018(self) -> bool {
1012         self == kw::Try
1013     }
1014
1015     /// Used for sanity checking rustdoc keyword sections.
1016     pub fn is_doc_keyword(self) -> bool {
1017         self <= kw::Union
1018     }
1019
1020     /// A keyword or reserved identifier that can be used as a path segment.
1021     pub fn is_path_segment_keyword(self) -> bool {
1022         self == kw::Super ||
1023         self == kw::SelfLower ||
1024         self == kw::SelfUpper ||
1025         self == kw::Crate ||
1026         self == kw::PathRoot ||
1027         self == kw::DollarCrate
1028     }
1029
1030     /// Returns `true` if the symbol is `true` or `false`.
1031     pub fn is_bool_lit(self) -> bool {
1032         self == kw::True || self == kw::False
1033     }
1034
1035     /// This symbol can be a raw identifier.
1036     pub fn can_be_raw(self) -> bool {
1037         self != kw::Invalid && self != kw::Underscore && !self.is_path_segment_keyword()
1038     }
1039 }
1040
1041 impl Ident {
1042     // Returns `true` for reserved identifiers used internally for elided lifetimes,
1043     // unnamed method parameters, crate root module, error recovery etc.
1044     pub fn is_special(self) -> bool {
1045         self.name <= kw::Underscore
1046     }
1047
1048     /// Returns `true` if the token is a keyword used in the language.
1049     pub fn is_used_keyword(self) -> bool {
1050         // Note: `span.edition()` is relatively expensive, don't call it unless necessary.
1051         self.name >= kw::As && self.name <= kw::While ||
1052         self.name.is_used_keyword_2018() && self.span.rust_2018()
1053     }
1054
1055     /// Returns `true` if the token is a keyword reserved for possible future use.
1056     pub fn is_unused_keyword(self) -> bool {
1057         // Note: `span.edition()` is relatively expensive, don't call it unless necessary.
1058         self.name >= kw::Abstract && self.name <= kw::Yield ||
1059         self.name.is_unused_keyword_2018() && self.span.rust_2018()
1060     }
1061
1062     /// Returns `true` if the token is either a special identifier or a keyword.
1063     pub fn is_reserved(self) -> bool {
1064         self.is_special() || self.is_used_keyword() || self.is_unused_keyword()
1065     }
1066
1067     /// A keyword or reserved identifier that can be used as a path segment.
1068     pub fn is_path_segment_keyword(self) -> bool {
1069         self.name.is_path_segment_keyword()
1070     }
1071
1072     /// We see this identifier in a normal identifier position, like variable name or a type.
1073     /// How was it written originally? Did it use the raw form? Let's try to guess.
1074     pub fn is_raw_guess(self) -> bool {
1075         self.name.can_be_raw() && self.is_reserved()
1076     }
1077 }
1078
1079 // If an interner exists, return it. Otherwise, prepare a fresh one.
1080 #[inline]
1081 fn with_interner<T, F: FnOnce(&mut Interner) -> T>(f: F) -> T {
1082     GLOBALS.with(|globals| f(&mut *globals.symbol_interner.lock()))
1083 }
1084
1085 /// An alternative to `Symbol`, useful when the chars within the symbol need to
1086 /// be accessed. It deliberately has limited functionality and should only be
1087 /// used for temporary values.
1088 ///
1089 /// Because the interner outlives any thread which uses this type, we can
1090 /// safely treat `string` which points to interner data, as an immortal string,
1091 /// as long as this type never crosses between threads.
1092 //
1093 // FIXME: ensure that the interner outlives any thread which uses
1094 // `LocalInternedString`, by creating a new thread right after constructing the
1095 // interner.
1096 #[derive(Clone, Eq, PartialOrd, Ord)]
1097 pub struct LocalInternedString {
1098     string: &'static str,
1099 }
1100
1101 impl<U: ?Sized> std::convert::AsRef<U> for LocalInternedString
1102 where
1103     str: std::convert::AsRef<U>
1104 {
1105     #[inline]
1106     fn as_ref(&self) -> &U {
1107         self.string.as_ref()
1108     }
1109 }
1110
1111 impl<T: std::ops::Deref<Target = str>> std::cmp::PartialEq<T> for LocalInternedString {
1112     fn eq(&self, other: &T) -> bool {
1113         self.string == other.deref()
1114     }
1115 }
1116
1117 impl !Send for LocalInternedString {}
1118 impl !Sync for LocalInternedString {}
1119
1120 impl std::ops::Deref for LocalInternedString {
1121     type Target = str;
1122     #[inline]
1123     fn deref(&self) -> &str { self.string }
1124 }
1125
1126 impl fmt::Debug for LocalInternedString {
1127     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1128         fmt::Debug::fmt(self.string, f)
1129     }
1130 }
1131
1132 impl fmt::Display for LocalInternedString {
1133     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1134         fmt::Display::fmt(self.string, f)
1135     }
1136 }