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