]> git.lizzy.rs Git - rust.git/blob - src/libsyntax_pos/symbol.rs
Add hooks for Miri panic unwinding
[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_uninit,
422         maybe_uninit_zeroed,
423         mem_uninitialized,
424         mem_zeroed,
425         member_constraints,
426         message,
427         meta,
428         min_const_fn,
429         min_const_unsafe_fn,
430         mips_target_feature,
431         mmx_target_feature,
432         module,
433         module_path,
434         more_struct_aliases,
435         movbe_target_feature,
436         must_use,
437         naked,
438         naked_functions,
439         name,
440         needs_allocator,
441         needs_panic_runtime,
442         negate_unsigned,
443         never,
444         never_type,
445         new,
446         next,
447         __next,
448         nll,
449         no_builtins,
450         no_core,
451         no_crate_inject,
452         no_debug,
453         no_default_passes,
454         no_implicit_prelude,
455         no_inline,
456         no_link,
457         no_main,
458         no_mangle,
459         non_ascii_idents,
460         None,
461         non_exhaustive,
462         non_modrs_mods,
463         no_stack_check,
464         no_start,
465         no_std,
466         not,
467         note,
468         object_safe_for_dispatch,
469         Ok,
470         omit_gdb_pretty_printer_section,
471         on,
472         on_unimplemented,
473         oom,
474         ops,
475         optimize,
476         optimize_attribute,
477         optin_builtin_traits,
478         option,
479         Option,
480         option_env,
481         opt_out_copy,
482         or,
483         or_patterns,
484         Ord,
485         Ordering,
486         Output,
487         overlapping_marker_traits,
488         packed,
489         panic,
490         panic_handler,
491         panic_impl,
492         panic_implementation,
493         panic_runtime,
494         parent_trait,
495         partial_cmp,
496         param_attrs,
497         PartialEq,
498         PartialOrd,
499         passes,
500         pat,
501         path,
502         pattern_parentheses,
503         Pending,
504         pin,
505         Pin,
506         pinned,
507         platform_intrinsics,
508         plugin,
509         plugin_registrar,
510         plugins,
511         Poll,
512         poll_with_tls_context,
513         powerpc_target_feature,
514         precise_pointer_size_matching,
515         prelude,
516         prelude_import,
517         primitive,
518         proc_dash_macro: "proc-macro",
519         proc_macro,
520         proc_macro_attribute,
521         proc_macro_def_site,
522         proc_macro_derive,
523         proc_macro_expr,
524         proc_macro_gen,
525         proc_macro_hygiene,
526         proc_macro_internals,
527         proc_macro_mod,
528         proc_macro_non_items,
529         proc_macro_path_invoc,
530         profiler_runtime,
531         pub_restricted,
532         pushpop_unsafe,
533         quad_precision_float,
534         question_mark,
535         quote,
536         Range,
537         RangeFrom,
538         RangeFull,
539         RangeInclusive,
540         RangeTo,
541         RangeToInclusive,
542         raw_dylib,
543         raw_identifiers,
544         Ready,
545         reason,
546         recursion_limit,
547         reexport_test_harness_main,
548         reflect,
549         register_attr,
550         register_tool,
551         relaxed_adts,
552         repr,
553         repr128,
554         repr_align,
555         repr_align_enum,
556         repr_packed,
557         repr_simd,
558         repr_transparent,
559         re_rebalance_coherence,
560         result,
561         Result,
562         Return,
563         rhs,
564         rlib,
565         rt,
566         rtm_target_feature,
567         rust,
568         rust_2015_preview,
569         rust_2018_preview,
570         rust_begin_unwind,
571         rustc,
572         Rust,
573         RustcDecodable,
574         RustcEncodable,
575         rustc_allocator,
576         rustc_allocator_nounwind,
577         rustc_allow_const_fn_ptr,
578         rustc_args_required_const,
579         rustc_attrs,
580         rustc_builtin_macro,
581         rustc_clean,
582         rustc_const_unstable,
583         rustc_conversion_suggestion,
584         rustc_def_path,
585         rustc_deprecated,
586         rustc_diagnostic_item,
587         rustc_diagnostic_macros,
588         rustc_dirty,
589         rustc_dummy,
590         rustc_dump_env_program_clauses,
591         rustc_dump_program_clauses,
592         rustc_dump_user_substs,
593         rustc_error,
594         rustc_expected_cgu_reuse,
595         rustc_if_this_changed,
596         rustc_inherit_overflow_checks,
597         rustc_layout,
598         rustc_layout_scalar_valid_range_end,
599         rustc_layout_scalar_valid_range_start,
600         rustc_macro_transparency,
601         rustc_mir,
602         rustc_nonnull_optimization_guaranteed,
603         rustc_object_lifetime_default,
604         rustc_on_unimplemented,
605         rustc_outlives,
606         rustc_paren_sugar,
607         rustc_partition_codegened,
608         rustc_partition_reused,
609         rustc_peek,
610         rustc_peek_definite_init,
611         rustc_peek_maybe_init,
612         rustc_peek_maybe_uninit,
613         rustc_peek_indirectly_mutable,
614         rustc_private,
615         rustc_proc_macro_decls,
616         rustc_promotable,
617         rustc_regions,
618         rustc_stable,
619         rustc_std_internal_symbol,
620         rustc_symbol_name,
621         rustc_synthetic,
622         rustc_reservation_impl,
623         rustc_test_marker,
624         rustc_then_this_would_need,
625         rustc_variance,
626         rustdoc,
627         rustfmt,
628         rust_eh_personality,
629         rust_eh_unwind_resume,
630         rust_oom,
631         rvalue_static_promotion,
632         sanitizer_runtime,
633         _Self,
634         self_in_typedefs,
635         self_struct_ctor,
636         should_panic,
637         simd,
638         simd_ffi,
639         since,
640         size,
641         slice_patterns,
642         slicing_syntax,
643         soft,
644         Some,
645         specialization,
646         speed,
647         spotlight,
648         sse4a_target_feature,
649         stable,
650         staged_api,
651         start,
652         static_in_const,
653         staticlib,
654         static_nobundle,
655         static_recursion,
656         std,
657         std_inject,
658         str,
659         stringify,
660         stmt,
661         stmt_expr_attributes,
662         stop_after_dataflow,
663         struct_field_attributes,
664         struct_inherit,
665         structural_match,
666         struct_variant,
667         sty,
668         suggestion,
669         target_feature,
670         target_has_atomic,
671         target_has_atomic_load_store,
672         target_thread_local,
673         task,
674         tbm_target_feature,
675         termination_trait,
676         termination_trait_test,
677         test,
678         test_2018_feature,
679         test_accepted_feature,
680         test_case,
681         test_removed_feature,
682         test_runner,
683         then_with,
684         thread_local,
685         tool_attributes,
686         tool_lints,
687         trace_macros,
688         track_caller,
689         trait_alias,
690         transmute,
691         transparent,
692         transparent_enums,
693         transparent_unions,
694         trivial_bounds,
695         Try,
696         try_blocks,
697         try_trait,
698         tt,
699         tuple_indexing,
700         Ty,
701         ty,
702         type_alias_impl_trait,
703         TyCtxt,
704         TyKind,
705         type_alias_enum_variants,
706         type_ascription,
707         type_length_limit,
708         type_macros,
709         u128,
710         u16,
711         u32,
712         u64,
713         u8,
714         unboxed_closures,
715         underscore_const_names,
716         underscore_imports,
717         underscore_lifetimes,
718         uniform_paths,
719         universal_impl_trait,
720         unmarked_api,
721         unreachable_code,
722         unrestricted_attribute_tokens,
723         unsafe_no_drop_flag,
724         unsized_locals,
725         unsized_tuple_coercion,
726         unstable,
727         untagged_unions,
728         unwind,
729         unwind_attributes,
730         unwrap_or,
731         used,
732         use_extern_macros,
733         use_nested_groups,
734         usize,
735         v1,
736         val,
737         vec,
738         Vec,
739         vis,
740         visible_private_types,
741         volatile,
742         warn,
743         wasm_import_module,
744         wasm_target_feature,
745         while_let,
746         windows,
747         windows_subsystem,
748         Yield,
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 }