]> git.lizzy.rs Git - rust.git/blob - src/librustc_span/symbol.rs
Rollup merge of #73613 - oli-obk:const_prop_miscompile, r=wesleywiser
[rust.git] / src / librustc_span / 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 rustc_arena::DroplessArena;
6 use rustc_data_structures::fx::FxHashMap;
7 use rustc_data_structures::stable_hasher::{HashStable, StableHasher, ToStableHashKey};
8 use rustc_macros::{symbols, HashStable_Generic};
9 use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
10 use rustc_serialize::{UseSpecializedDecodable, UseSpecializedEncodable};
11
12 use std::cmp::{Ord, PartialEq, PartialOrd};
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         MacroRules:         "macro_rules",
101         Raw:                "raw",
102         Union:              "union",
103     }
104
105     // Symbols that can be referred to with rustc_span::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         abi_avr_interrupt,
124         abort,
125         aborts,
126         address,
127         add_with_overflow,
128         advanced_slice_patterns,
129         adx_target_feature,
130         alias,
131         align,
132         alignstack,
133         all,
134         allocator,
135         allocator_internals,
136         alloc_error_handler,
137         allow,
138         allowed,
139         allow_fail,
140         allow_internal_unsafe,
141         allow_internal_unstable,
142         allow_internal_unstable_backcompat_hack,
143         always,
144         and,
145         any,
146         arbitrary_enum_discriminant,
147         arbitrary_self_types,
148         Arc,
149         Arguments,
150         ArgumentV1,
151         arith_offset,
152         arm_target_feature,
153         asm,
154         assert,
155         associated_consts,
156         associated_type_bounds,
157         associated_type_defaults,
158         associated_types,
159         assume_init,
160         async_await,
161         async_closure,
162         attr,
163         attributes,
164         attr_literals,
165         att_syntax,
166         augmented_assignments,
167         automatically_derived,
168         avx512_target_feature,
169         await_macro,
170         begin_panic,
171         bench,
172         bin,
173         bind_by_move_pattern_guards,
174         bindings_after_at,
175         block,
176         bool,
177         borrowck_graphviz_format,
178         borrowck_graphviz_postflow,
179         borrowck_graphviz_preflow,
180         box_patterns,
181         box_syntax,
182         braced_empty_structs,
183         bswap,
184         bitreverse,
185         C,
186         caller_location,
187         cdylib,
188         cfg,
189         cfg_accessible,
190         cfg_attr,
191         cfg_attr_multi,
192         cfg_doctest,
193         cfg_sanitize,
194         cfg_target_feature,
195         cfg_target_has_atomic,
196         cfg_target_thread_local,
197         cfg_target_vendor,
198         cfg_version,
199         char,
200         clippy,
201         clone,
202         Clone,
203         clone_closures,
204         clone_from,
205         closure_to_fn_coercion,
206         cmp,
207         cmpxchg16b_target_feature,
208         cold,
209         column,
210         compile_error,
211         compiler_builtins,
212         concat,
213         concat_idents,
214         conservative_impl_trait,
215         console,
216         const_compare_raw_pointers,
217         const_constructor,
218         const_eval_limit,
219         const_extern_fn,
220         const_fn,
221         const_fn_union,
222         const_generics,
223         const_if_match,
224         const_indexing,
225         const_in_array_repeat_expressions,
226         const_let,
227         const_loop,
228         const_mut_refs,
229         const_panic,
230         const_precise_live_drops,
231         const_raw_ptr_deref,
232         const_raw_ptr_to_usize_cast,
233         const_transmute,
234         const_trait_bound_opt_out,
235         const_trait_impl,
236         contents,
237         context,
238         convert,
239         Copy,
240         copy_closures,
241         core,
242         core_intrinsics,
243         count_code_region,
244         crate_id,
245         crate_in_paths,
246         crate_local,
247         crate_name,
248         crate_type,
249         crate_visibility_modifier,
250         ctpop,
251         cttz,
252         cttz_nonzero,
253         ctlz,
254         ctlz_nonzero,
255         custom_attribute,
256         custom_derive,
257         custom_inner_attributes,
258         custom_test_frameworks,
259         c_variadic,
260         debug_trait,
261         declare_lint_pass,
262         decl_macro,
263         debug,
264         Debug,
265         Decodable,
266         Default,
267         default_lib_allocator,
268         default_type_parameter_fallback,
269         default_type_params,
270         delay_span_bug_from_inside_query,
271         deny,
272         deprecated,
273         deref,
274         deref_mut,
275         derive,
276         diagnostic,
277         direct,
278         discriminant_value,
279         doc,
280         doc_alias,
281         doc_cfg,
282         doc_keyword,
283         doc_masked,
284         doctest,
285         document_private_items,
286         dotdoteq_in_patterns,
287         dotdot_in_tuple_patterns,
288         double_braced_crate: "{{crate}}",
289         double_braced_impl: "{{impl}}",
290         double_braced_misc: "{{misc}}",
291         double_braced_closure: "{{closure}}",
292         double_braced_constructor: "{{constructor}}",
293         double_braced_constant: "{{constant}}",
294         double_braced_opaque: "{{opaque}}",
295         dropck_eyepatch,
296         dropck_parametricity,
297         drop_types_in_const,
298         dylib,
299         dyn_trait,
300         eh_personality,
301         enable,
302         Encodable,
303         env,
304         eq,
305         err,
306         Err,
307         Eq,
308         Equal,
309         enclosing_scope,
310         except,
311         exclusive_range_pattern,
312         exhaustive_integer_patterns,
313         exhaustive_patterns,
314         existential_type,
315         expected,
316         export_name,
317         expr,
318         extern_absolute_paths,
319         external_doc,
320         extern_crate_item_prelude,
321         extern_crate_self,
322         extern_in_paths,
323         extern_prelude,
324         extern_types,
325         f16c_target_feature,
326         f32,
327         f64,
328         feature,
329         ffi_const,
330         ffi_pure,
331         ffi_returns_twice,
332         field,
333         field_init_shorthand,
334         file,
335         fmt,
336         fmt_internals,
337         fn_must_use,
338         forbid,
339         format_args,
340         format_args_nl,
341         from,
342         From,
343         from_desugaring,
344         from_error,
345         from_generator,
346         from_method,
347         from_ok,
348         from_usize,
349         from_trait,
350         fundamental,
351         future,
352         Future,
353         FxHashSet,
354         FxHashMap,
355         gen_future,
356         gen_kill,
357         generators,
358         generic_associated_types,
359         generic_param_attrs,
360         get_context,
361         global_allocator,
362         global_asm,
363         globs,
364         half_open_range_patterns,
365         hash,
366         Hash,
367         HashSet,
368         HashMap,
369         hexagon_target_feature,
370         hidden,
371         homogeneous_aggregate,
372         html_favicon_url,
373         html_logo_url,
374         html_no_source,
375         html_playground_url,
376         html_root_url,
377         i128,
378         i128_type,
379         i16,
380         i32,
381         i64,
382         i8,
383         ident,
384         if_let,
385         if_while_or_patterns,
386         ignore,
387         inlateout,
388         inout,
389         impl_header_lifetime_elision,
390         impl_lint_pass,
391         impl_trait_in_bindings,
392         import_shadowing,
393         index,
394         index_mut,
395         in_band_lifetimes,
396         include,
397         include_bytes,
398         include_str,
399         inclusive_range_syntax,
400         infer_outlives_requirements,
401         infer_static_outlives_requirements,
402         inline,
403         intel,
404         into_iter,
405         IntoIterator,
406         into_result,
407         intrinsics,
408         irrefutable_let_patterns,
409         isize,
410         issue,
411         issue_5723_bootstrap,
412         issue_tracker_base_url,
413         item,
414         item_context: "ItemContext",
415         item_like_imports,
416         iter,
417         Iterator,
418         keyword,
419         kind,
420         label,
421         label_break_value,
422         lang,
423         lang_items,
424         lateout,
425         let_chains,
426         lhs,
427         lib,
428         lifetime,
429         line,
430         link,
431         linkage,
432         link_args,
433         link_cfg,
434         link_llvm_intrinsics,
435         link_name,
436         link_ordinal,
437         link_section,
438         LintPass,
439         lint_reasons,
440         literal,
441         llvm_asm,
442         local_inner_macros,
443         log_syntax,
444         loop_break_value,
445         macro_at_most_once_rep,
446         macro_escape,
447         macro_export,
448         macro_lifetime_matcher,
449         macro_literal_matcher,
450         macro_reexport,
451         macros_in_extern,
452         macro_use,
453         macro_vis_matcher,
454         main,
455         managed_boxes,
456         marker,
457         marker_trait_attr,
458         masked,
459         match_beginning_vert,
460         match_default_bindings,
461         may_dangle,
462         maybe_uninit_uninit,
463         maybe_uninit_zeroed,
464         mem_uninitialized,
465         mem_zeroed,
466         member_constraints,
467         memory,
468         message,
469         meta,
470         min_align_of,
471         min_const_fn,
472         min_const_unsafe_fn,
473         min_specialization,
474         mips_target_feature,
475         mmx_target_feature,
476         module,
477         module_path,
478         more_struct_aliases,
479         move_ref_pattern,
480         move_val_init,
481         movbe_target_feature,
482         mul_with_overflow,
483         must_use,
484         naked,
485         naked_functions,
486         name,
487         needs_allocator,
488         needs_drop,
489         needs_panic_runtime,
490         negate_unsigned,
491         negative_impls,
492         never,
493         never_type,
494         never_type_fallback,
495         new,
496         next,
497         __next,
498         nll,
499         no_builtins,
500         no_core,
501         no_crate_inject,
502         no_debug,
503         no_default_passes,
504         no_implicit_prelude,
505         no_inline,
506         no_link,
507         no_main,
508         no_mangle,
509         nomem,
510         non_ascii_idents,
511         None,
512         non_exhaustive,
513         non_modrs_mods,
514         noreturn,
515         no_niche,
516         no_sanitize,
517         nostack,
518         no_stack_check,
519         no_start,
520         no_std,
521         not,
522         note,
523         object_safe_for_dispatch,
524         offset,
525         Ok,
526         omit_gdb_pretty_printer_section,
527         on,
528         on_unimplemented,
529         oom,
530         ops,
531         optimize,
532         optimize_attribute,
533         optin_builtin_traits,
534         option,
535         Option,
536         option_env,
537         options,
538         opt_out_copy,
539         or,
540         or_patterns,
541         Ord,
542         Ordering,
543         out,
544         Output,
545         overlapping_marker_traits,
546         packed,
547         panic,
548         panic_handler,
549         panic_impl,
550         panic_implementation,
551         panic_runtime,
552         parent_trait,
553         partial_cmp,
554         param_attrs,
555         PartialEq,
556         PartialOrd,
557         passes,
558         pat,
559         path,
560         pattern_parentheses,
561         Pending,
562         pin,
563         Pin,
564         pinned,
565         platform_intrinsics,
566         plugin,
567         plugin_registrar,
568         plugins,
569         poll,
570         Poll,
571         powerpc_target_feature,
572         precise_pointer_size_matching,
573         pref_align_of,
574         prelude,
575         prelude_import,
576         preserves_flags,
577         primitive,
578         proc_dash_macro: "proc-macro",
579         proc_macro,
580         proc_macro_attribute,
581         proc_macro_def_site,
582         proc_macro_derive,
583         proc_macro_expr,
584         proc_macro_gen,
585         proc_macro_hygiene,
586         proc_macro_internals,
587         proc_macro_mod,
588         proc_macro_non_items,
589         proc_macro_path_invoc,
590         profiler_builtins,
591         profiler_runtime,
592         ptr_guaranteed_eq,
593         ptr_guaranteed_ne,
594         ptr_offset_from,
595         pub_restricted,
596         pure,
597         pushpop_unsafe,
598         quad_precision_float,
599         question_mark,
600         quote,
601         Range,
602         RangeFrom,
603         RangeFull,
604         RangeInclusive,
605         RangeTo,
606         RangeToInclusive,
607         raw_dylib,
608         raw_identifiers,
609         raw_ref_op,
610         Rc,
611         readonly,
612         Ready,
613         reason,
614         recursion_limit,
615         reexport_test_harness_main,
616         reflect,
617         register_attr,
618         register_tool,
619         relaxed_adts,
620         repr,
621         repr128,
622         repr_align,
623         repr_align_enum,
624         repr_no_niche,
625         repr_packed,
626         repr_simd,
627         repr_transparent,
628         re_rebalance_coherence,
629         result,
630         Result,
631         Return,
632         rhs,
633         riscv_target_feature,
634         rlib,
635         rotate_left,
636         rotate_right,
637         rt,
638         rtm_target_feature,
639         rust,
640         rust_2015_preview,
641         rust_2018_preview,
642         rust_begin_unwind,
643         rustc,
644         RustcDecodable,
645         RustcEncodable,
646         rustc_allocator,
647         rustc_allocator_nounwind,
648         rustc_allow_const_fn_ptr,
649         rustc_args_required_const,
650         rustc_attrs,
651         rustc_builtin_macro,
652         rustc_clean,
653         rustc_const_unstable,
654         rustc_const_stable,
655         rustc_conversion_suggestion,
656         rustc_def_path,
657         rustc_deprecated,
658         rustc_diagnostic_item,
659         rustc_diagnostic_macros,
660         rustc_dirty,
661         rustc_dummy,
662         rustc_dump_env_program_clauses,
663         rustc_dump_program_clauses,
664         rustc_dump_user_substs,
665         rustc_error,
666         rustc_expected_cgu_reuse,
667         rustc_if_this_changed,
668         rustc_inherit_overflow_checks,
669         rustc_layout,
670         rustc_layout_scalar_valid_range_end,
671         rustc_layout_scalar_valid_range_start,
672         rustc_macro_transparency,
673         rustc_mir,
674         rustc_nonnull_optimization_guaranteed,
675         rustc_object_lifetime_default,
676         rustc_on_unimplemented,
677         rustc_outlives,
678         rustc_paren_sugar,
679         rustc_partition_codegened,
680         rustc_partition_reused,
681         rustc_peek,
682         rustc_peek_definite_init,
683         rustc_peek_liveness,
684         rustc_peek_maybe_init,
685         rustc_peek_maybe_uninit,
686         rustc_peek_indirectly_mutable,
687         rustc_private,
688         rustc_proc_macro_decls,
689         rustc_promotable,
690         rustc_regions,
691         rustc_unsafe_specialization_marker,
692         rustc_specialization_trait,
693         rustc_stable,
694         rustc_std_internal_symbol,
695         rustc_symbol_name,
696         rustc_synthetic,
697         rustc_reservation_impl,
698         rustc_test_marker,
699         rustc_then_this_would_need,
700         rustc_variance,
701         rustfmt,
702         rust_eh_personality,
703         rust_oom,
704         rvalue_static_promotion,
705         sanitize,
706         sanitizer_runtime,
707         saturating_add,
708         saturating_sub,
709         _Self,
710         self_in_typedefs,
711         self_struct_ctor,
712         send_trait,
713         should_panic,
714         simd,
715         simd_extract,
716         simd_ffi,
717         simd_insert,
718         since,
719         size,
720         size_of,
721         slice_patterns,
722         slicing_syntax,
723         soft,
724         Some,
725         specialization,
726         speed,
727         sse4a_target_feature,
728         stable,
729         staged_api,
730         start,
731         static_in_const,
732         staticlib,
733         static_nobundle,
734         static_recursion,
735         std,
736         std_inject,
737         str,
738         stringify,
739         stmt,
740         stmt_expr_attributes,
741         stop_after_dataflow,
742         struct_field_attributes,
743         struct_inherit,
744         structural_match,
745         struct_variant,
746         sty,
747         sub_with_overflow,
748         suggestion,
749         sym,
750         sync_trait,
751         target_feature,
752         target_feature_11,
753         target_has_atomic,
754         target_has_atomic_load_store,
755         target_thread_local,
756         task,
757         _task_context,
758         tbm_target_feature,
759         termination_trait,
760         termination_trait_test,
761         test,
762         test_2018_feature,
763         test_accepted_feature,
764         test_case,
765         test_removed_feature,
766         test_runner,
767         then_with,
768         thread,
769         thread_local,
770         tool_attributes,
771         tool_lints,
772         trace_macros,
773         track_caller,
774         trait_alias,
775         transmute,
776         transparent,
777         transparent_enums,
778         transparent_unions,
779         trivial_bounds,
780         Try,
781         try_blocks,
782         try_trait,
783         tt,
784         tuple_indexing,
785         two_phase,
786         Ty,
787         ty,
788         type_alias_impl_trait,
789         type_id,
790         type_name,
791         TyCtxt,
792         TyKind,
793         type_alias_enum_variants,
794         type_ascription,
795         type_length_limit,
796         type_macros,
797         u128,
798         u16,
799         u32,
800         u64,
801         u8,
802         unboxed_closures,
803         unchecked_add,
804         unchecked_div,
805         unchecked_mul,
806         unchecked_rem,
807         unchecked_shl,
808         unchecked_shr,
809         unchecked_sub,
810         underscore_const_names,
811         underscore_imports,
812         underscore_lifetimes,
813         uniform_paths,
814         universal_impl_trait,
815         unmarked_api,
816         unreachable_code,
817         unrestricted_attribute_tokens,
818         unsafe_block_in_unsafe_fn,
819         unsafe_no_drop_flag,
820         unsized_locals,
821         unsized_tuple_coercion,
822         unstable,
823         untagged_unions,
824         unwind,
825         unwind_attributes,
826         unwrap_or,
827         used,
828         use_extern_macros,
829         use_nested_groups,
830         usize,
831         v1,
832         val,
833         var,
834         vec,
835         Vec,
836         version,
837         vis,
838         visible_private_types,
839         volatile,
840         warn,
841         wasm_import_module,
842         wasm_target_feature,
843         while_let,
844         windows,
845         windows_subsystem,
846         wrapping_add,
847         wrapping_sub,
848         wrapping_mul,
849         Yield,
850     }
851 }
852
853 #[derive(Copy, Clone, Eq, HashStable_Generic)]
854 pub struct Ident {
855     pub name: Symbol,
856     pub span: Span,
857 }
858
859 impl Ident {
860     #[inline]
861     /// Constructs a new identifier from a symbol and a span.
862     pub const fn new(name: Symbol, span: Span) -> Ident {
863         Ident { name, span }
864     }
865
866     /// Constructs a new identifier with a dummy span.
867     #[inline]
868     pub const fn with_dummy_span(name: Symbol) -> Ident {
869         Ident::new(name, DUMMY_SP)
870     }
871
872     #[inline]
873     pub fn invalid() -> Ident {
874         Ident::with_dummy_span(kw::Invalid)
875     }
876
877     /// Maps a string to an identifier with a dummy span.
878     pub fn from_str(string: &str) -> Ident {
879         Ident::with_dummy_span(Symbol::intern(string))
880     }
881
882     /// Maps a string and a span to an identifier.
883     pub fn from_str_and_span(string: &str, span: Span) -> Ident {
884         Ident::new(Symbol::intern(string), span)
885     }
886
887     /// Replaces `lo` and `hi` with those from `span`, but keep hygiene context.
888     pub fn with_span_pos(self, span: Span) -> Ident {
889         Ident::new(self.name, span.with_ctxt(self.span.ctxt()))
890     }
891
892     pub fn without_first_quote(self) -> Ident {
893         Ident::new(Symbol::intern(self.as_str().trim_start_matches('\'')), self.span)
894     }
895
896     /// "Normalize" ident for use in comparisons using "item hygiene".
897     /// Identifiers with same string value become same if they came from the same macro 2.0 macro
898     /// (e.g., `macro` item, but not `macro_rules` item) and stay different if they came from
899     /// different macro 2.0 macros.
900     /// Technically, this operation strips all non-opaque marks from ident's syntactic context.
901     pub fn normalize_to_macros_2_0(self) -> Ident {
902         Ident::new(self.name, self.span.normalize_to_macros_2_0())
903     }
904
905     /// "Normalize" ident for use in comparisons using "local variable hygiene".
906     /// Identifiers with same string value become same if they came from the same non-transparent
907     /// macro (e.g., `macro` or `macro_rules!` items) and stay different if they came from different
908     /// non-transparent macros.
909     /// Technically, this operation strips all transparent marks from ident's syntactic context.
910     pub fn normalize_to_macro_rules(self) -> Ident {
911         Ident::new(self.name, self.span.normalize_to_macro_rules())
912     }
913
914     /// Convert the name to a `SymbolStr`. This is a slowish operation because
915     /// it requires locking the symbol interner.
916     pub fn as_str(self) -> SymbolStr {
917         self.name.as_str()
918     }
919 }
920
921 impl PartialEq for Ident {
922     fn eq(&self, rhs: &Self) -> bool {
923         self.name == rhs.name && self.span.ctxt() == rhs.span.ctxt()
924     }
925 }
926
927 impl Hash for Ident {
928     fn hash<H: Hasher>(&self, state: &mut H) {
929         self.name.hash(state);
930         self.span.ctxt().hash(state);
931     }
932 }
933
934 impl fmt::Debug for Ident {
935     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
936         fmt::Display::fmt(self, f)?;
937         fmt::Debug::fmt(&self.span.ctxt(), f)
938     }
939 }
940
941 /// This implementation is supposed to be used in error messages, so it's expected to be identical
942 /// to printing the original identifier token written in source code (`token_to_string`),
943 /// except that AST identifiers don't keep the rawness flag, so we have to guess it.
944 impl fmt::Display for Ident {
945     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
946         fmt::Display::fmt(&IdentPrinter::new(self.name, self.is_raw_guess(), None), f)
947     }
948 }
949
950 impl UseSpecializedEncodable for Ident {
951     fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
952         s.emit_struct("Ident", 2, |s| {
953             s.emit_struct_field("name", 0, |s| self.name.encode(s))?;
954             s.emit_struct_field("span", 1, |s| self.span.encode(s))
955         })
956     }
957 }
958
959 impl UseSpecializedDecodable for Ident {
960     fn default_decode<D: Decoder>(d: &mut D) -> Result<Self, D::Error> {
961         d.read_struct("Ident", 2, |d| {
962             Ok(Ident {
963                 name: d.read_struct_field("name", 0, Decodable::decode)?,
964                 span: d.read_struct_field("span", 1, Decodable::decode)?,
965             })
966         })
967     }
968 }
969
970 /// This is the most general way to print identifiers.
971 /// AST pretty-printer is used as a fallback for turning AST structures into token streams for
972 /// proc macros. Additionally, proc macros may stringify their input and expect it survive the
973 /// stringification (especially true for proc macro derives written between Rust 1.15 and 1.30).
974 /// So we need to somehow pretty-print `$crate` in a way preserving at least some of its
975 /// hygiene data, most importantly name of the crate it refers to.
976 /// As a result we print `$crate` as `crate` if it refers to the local crate
977 /// and as `::other_crate_name` if it refers to some other crate.
978 /// Note, that this is only done if the ident token is printed from inside of AST pretty-pringing,
979 /// but not otherwise. Pretty-printing is the only way for proc macros to discover token contents,
980 /// so we should not perform this lossy conversion if the top level call to the pretty-printer was
981 /// done for a token stream or a single token.
982 pub struct IdentPrinter {
983     symbol: Symbol,
984     is_raw: bool,
985     /// Span used for retrieving the crate name to which `$crate` refers to,
986     /// if this field is `None` then the `$crate` conversion doesn't happen.
987     convert_dollar_crate: Option<Span>,
988 }
989
990 impl IdentPrinter {
991     /// The most general `IdentPrinter` constructor. Do not use this.
992     pub fn new(symbol: Symbol, is_raw: bool, convert_dollar_crate: Option<Span>) -> IdentPrinter {
993         IdentPrinter { symbol, is_raw, convert_dollar_crate }
994     }
995
996     /// This implementation is supposed to be used when printing identifiers
997     /// as a part of pretty-printing for larger AST pieces.
998     /// Do not use this either.
999     pub fn for_ast_ident(ident: Ident, is_raw: bool) -> IdentPrinter {
1000         IdentPrinter::new(ident.name, is_raw, Some(ident.span))
1001     }
1002 }
1003
1004 impl fmt::Display for IdentPrinter {
1005     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1006         if self.is_raw {
1007             f.write_str("r#")?;
1008         } else {
1009             if self.symbol == kw::DollarCrate {
1010                 if let Some(span) = self.convert_dollar_crate {
1011                     let converted = span.ctxt().dollar_crate_name();
1012                     if !converted.is_path_segment_keyword() {
1013                         f.write_str("::")?;
1014                     }
1015                     return fmt::Display::fmt(&converted, f);
1016                 }
1017             }
1018         }
1019         fmt::Display::fmt(&self.symbol, f)
1020     }
1021 }
1022
1023 /// An newtype around `Ident` that calls [Ident::normalize_to_macro_rules] on
1024 /// construction.
1025 // FIXME(matthewj, petrochenkov) Use this more often, add a similar
1026 // `ModernIdent` struct and use that as well.
1027 #[derive(Copy, Clone, Eq, PartialEq, Hash)]
1028 pub struct MacroRulesNormalizedIdent(Ident);
1029
1030 impl MacroRulesNormalizedIdent {
1031     pub fn new(ident: Ident) -> Self {
1032         Self(ident.normalize_to_macro_rules())
1033     }
1034 }
1035
1036 impl fmt::Debug for MacroRulesNormalizedIdent {
1037     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1038         fmt::Debug::fmt(&self.0, f)
1039     }
1040 }
1041
1042 impl fmt::Display for MacroRulesNormalizedIdent {
1043     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1044         fmt::Display::fmt(&self.0, f)
1045     }
1046 }
1047
1048 /// An interned string.
1049 ///
1050 /// Internally, a `Symbol` is implemented as an index, and all operations
1051 /// (including hashing, equality, and ordering) operate on that index. The use
1052 /// of `rustc_index::newtype_index!` means that `Option<Symbol>` only takes up 4 bytes,
1053 /// because `rustc_index::newtype_index!` reserves the last 256 values for tagging purposes.
1054 ///
1055 /// Note that `Symbol` cannot directly be a `rustc_index::newtype_index!` because it
1056 /// implements `fmt::Debug`, `Encodable`, and `Decodable` in special ways.
1057 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
1058 pub struct Symbol(SymbolIndex);
1059
1060 rustc_index::newtype_index! {
1061     pub struct SymbolIndex { .. }
1062 }
1063
1064 impl Symbol {
1065     const fn new(n: u32) -> Self {
1066         Symbol(SymbolIndex::from_u32(n))
1067     }
1068
1069     /// Maps a string to its interned representation.
1070     pub fn intern(string: &str) -> Self {
1071         with_interner(|interner| interner.intern(string))
1072     }
1073
1074     /// Access the symbol's chars. This is a slowish operation because it
1075     /// requires locking the symbol interner.
1076     pub fn with<F: FnOnce(&str) -> R, R>(self, f: F) -> R {
1077         with_interner(|interner| f(interner.get(self)))
1078     }
1079
1080     /// Convert to a `SymbolStr`. This is a slowish operation because it
1081     /// requires locking the symbol interner.
1082     pub fn as_str(self) -> SymbolStr {
1083         with_interner(|interner| unsafe {
1084             SymbolStr { string: std::mem::transmute::<&str, &str>(interner.get(self)) }
1085         })
1086     }
1087
1088     pub fn as_u32(self) -> u32 {
1089         self.0.as_u32()
1090     }
1091
1092     /// This method is supposed to be used in error messages, so it's expected to be
1093     /// identical to printing the original identifier token written in source code
1094     /// (`token_to_string`, `Ident::to_string`), except that symbols don't keep the rawness flag
1095     /// or edition, so we have to guess the rawness using the global edition.
1096     pub fn to_ident_string(self) -> String {
1097         Ident::with_dummy_span(self).to_string()
1098     }
1099 }
1100
1101 impl fmt::Debug for Symbol {
1102     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1103         self.with(|str| fmt::Debug::fmt(&str, f))
1104     }
1105 }
1106
1107 impl fmt::Display for Symbol {
1108     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1109         self.with(|str| fmt::Display::fmt(&str, f))
1110     }
1111 }
1112
1113 impl Encodable for Symbol {
1114     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1115         self.with(|string| s.emit_str(string))
1116     }
1117 }
1118
1119 impl Decodable for Symbol {
1120     #[inline]
1121     fn decode<D: Decoder>(d: &mut D) -> Result<Symbol, D::Error> {
1122         Ok(Symbol::intern(&d.read_str()?))
1123     }
1124 }
1125
1126 impl<CTX> HashStable<CTX> for Symbol {
1127     #[inline]
1128     fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
1129         self.as_str().hash_stable(hcx, hasher);
1130     }
1131 }
1132
1133 impl<CTX> ToStableHashKey<CTX> for Symbol {
1134     type KeyType = SymbolStr;
1135
1136     #[inline]
1137     fn to_stable_hash_key(&self, _: &CTX) -> SymbolStr {
1138         self.as_str()
1139     }
1140 }
1141
1142 // The `&'static str`s in this type actually point into the arena.
1143 #[derive(Default)]
1144 pub struct Interner {
1145     arena: DroplessArena,
1146     names: FxHashMap<&'static str, Symbol>,
1147     strings: Vec<&'static str>,
1148 }
1149
1150 impl Interner {
1151     fn prefill(init: &[&'static str]) -> Self {
1152         Interner {
1153             strings: init.into(),
1154             names: init.iter().copied().zip((0..).map(Symbol::new)).collect(),
1155             ..Default::default()
1156         }
1157     }
1158
1159     #[inline]
1160     pub fn intern(&mut self, string: &str) -> Symbol {
1161         if let Some(&name) = self.names.get(string) {
1162             return name;
1163         }
1164
1165         let name = Symbol::new(self.strings.len() as u32);
1166
1167         // `from_utf8_unchecked` is safe since we just allocated a `&str` which is known to be
1168         // UTF-8.
1169         let string: &str =
1170             unsafe { str::from_utf8_unchecked(self.arena.alloc_slice(string.as_bytes())) };
1171         // It is safe to extend the arena allocation to `'static` because we only access
1172         // these while the arena is still alive.
1173         let string: &'static str = unsafe { &*(string as *const str) };
1174         self.strings.push(string);
1175         self.names.insert(string, name);
1176         name
1177     }
1178
1179     // Get the symbol as a string. `Symbol::as_str()` should be used in
1180     // preference to this function.
1181     pub fn get(&self, symbol: Symbol) -> &str {
1182         self.strings[symbol.0.as_usize()]
1183     }
1184 }
1185
1186 // This module has a very short name because it's used a lot.
1187 /// This module contains all the defined keyword `Symbol`s.
1188 ///
1189 /// Given that `kw` is imported, use them like `kw::keyword_name`.
1190 /// For example `kw::Loop` or `kw::Break`.
1191 pub mod kw {
1192     use super::Symbol;
1193     keywords!();
1194 }
1195
1196 // This module has a very short name because it's used a lot.
1197 /// This module contains all the defined non-keyword `Symbol`s.
1198 ///
1199 /// Given that `sym` is imported, use them like `sym::symbol_name`.
1200 /// For example `sym::rustfmt` or `sym::u8`.
1201 #[allow(rustc::default_hash_types)]
1202 pub mod sym {
1203     use super::Symbol;
1204     use std::convert::TryInto;
1205
1206     symbols!();
1207
1208     // Used from a macro in `librustc_feature/accepted.rs`
1209     pub use super::kw::MacroRules as macro_rules;
1210
1211     // Get the symbol for an integer. The first few non-negative integers each
1212     // have a static symbol and therefore are fast.
1213     pub fn integer<N: TryInto<usize> + Copy + ToString>(n: N) -> Symbol {
1214         if let Result::Ok(idx) = n.try_into() {
1215             if let Option::Some(&sym_) = digits_array.get(idx) {
1216                 return sym_;
1217             }
1218         }
1219         Symbol::intern(&n.to_string())
1220     }
1221 }
1222
1223 impl Symbol {
1224     fn is_used_keyword_2018(self) -> bool {
1225         self >= kw::Async && self <= kw::Dyn
1226     }
1227
1228     fn is_unused_keyword_2018(self) -> bool {
1229         self == kw::Try
1230     }
1231
1232     /// Used for sanity checking rustdoc keyword sections.
1233     pub fn is_doc_keyword(self) -> bool {
1234         self <= kw::Union
1235     }
1236
1237     /// A keyword or reserved identifier that can be used as a path segment.
1238     pub fn is_path_segment_keyword(self) -> bool {
1239         self == kw::Super
1240             || self == kw::SelfLower
1241             || self == kw::SelfUpper
1242             || self == kw::Crate
1243             || self == kw::PathRoot
1244             || self == kw::DollarCrate
1245     }
1246
1247     /// Returns `true` if the symbol is `true` or `false`.
1248     pub fn is_bool_lit(self) -> bool {
1249         self == kw::True || self == kw::False
1250     }
1251
1252     /// This symbol can be a raw identifier.
1253     pub fn can_be_raw(self) -> bool {
1254         self != kw::Invalid && self != kw::Underscore && !self.is_path_segment_keyword()
1255     }
1256 }
1257
1258 impl Ident {
1259     // Returns `true` for reserved identifiers used internally for elided lifetimes,
1260     // unnamed method parameters, crate root module, error recovery etc.
1261     pub fn is_special(self) -> bool {
1262         self.name <= kw::Underscore
1263     }
1264
1265     /// Returns `true` if the token is a keyword used in the language.
1266     pub fn is_used_keyword(self) -> bool {
1267         // Note: `span.edition()` is relatively expensive, don't call it unless necessary.
1268         self.name >= kw::As && self.name <= kw::While
1269             || self.name.is_used_keyword_2018() && self.span.rust_2018()
1270     }
1271
1272     /// Returns `true` if the token is a keyword reserved for possible future use.
1273     pub fn is_unused_keyword(self) -> bool {
1274         // Note: `span.edition()` is relatively expensive, don't call it unless necessary.
1275         self.name >= kw::Abstract && self.name <= kw::Yield
1276             || self.name.is_unused_keyword_2018() && self.span.rust_2018()
1277     }
1278
1279     /// Returns `true` if the token is either a special identifier or a keyword.
1280     pub fn is_reserved(self) -> bool {
1281         self.is_special() || self.is_used_keyword() || self.is_unused_keyword()
1282     }
1283
1284     /// A keyword or reserved identifier that can be used as a path segment.
1285     pub fn is_path_segment_keyword(self) -> bool {
1286         self.name.is_path_segment_keyword()
1287     }
1288
1289     /// We see this identifier in a normal identifier position, like variable name or a type.
1290     /// How was it written originally? Did it use the raw form? Let's try to guess.
1291     pub fn is_raw_guess(self) -> bool {
1292         self.name.can_be_raw() && self.is_reserved()
1293     }
1294 }
1295
1296 #[inline]
1297 fn with_interner<T, F: FnOnce(&mut Interner) -> T>(f: F) -> T {
1298     GLOBALS.with(|globals| f(&mut *globals.symbol_interner.lock()))
1299 }
1300
1301 /// An alternative to `Symbol`, useful when the chars within the symbol need to
1302 /// be accessed. It deliberately has limited functionality and should only be
1303 /// used for temporary values.
1304 ///
1305 /// Because the interner outlives any thread which uses this type, we can
1306 /// safely treat `string` which points to interner data, as an immortal string,
1307 /// as long as this type never crosses between threads.
1308 //
1309 // FIXME: ensure that the interner outlives any thread which uses `SymbolStr`,
1310 // by creating a new thread right after constructing the interner.
1311 #[derive(Clone, Eq, PartialOrd, Ord)]
1312 pub struct SymbolStr {
1313     string: &'static str,
1314 }
1315
1316 // This impl allows a `SymbolStr` to be directly equated with a `String` or
1317 // `&str`.
1318 impl<T: std::ops::Deref<Target = str>> std::cmp::PartialEq<T> for SymbolStr {
1319     fn eq(&self, other: &T) -> bool {
1320         self.string == other.deref()
1321     }
1322 }
1323
1324 impl !Send for SymbolStr {}
1325 impl !Sync for SymbolStr {}
1326
1327 /// This impl means that if `ss` is a `SymbolStr`:
1328 /// - `*ss` is a `str`;
1329 /// - `&*ss` is a `&str`;
1330 /// - `&ss as &str` is a `&str`, which means that `&ss` can be passed to a
1331 ///   function expecting a `&str`.
1332 impl std::ops::Deref for SymbolStr {
1333     type Target = str;
1334     #[inline]
1335     fn deref(&self) -> &str {
1336         self.string
1337     }
1338 }
1339
1340 impl fmt::Debug for SymbolStr {
1341     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1342         fmt::Debug::fmt(self.string, f)
1343     }
1344 }
1345
1346 impl fmt::Display for SymbolStr {
1347     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1348         fmt::Display::fmt(self.string, f)
1349     }
1350 }
1351
1352 impl<CTX> HashStable<CTX> for SymbolStr {
1353     #[inline]
1354     fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
1355         self.string.hash_stable(hcx, hasher)
1356     }
1357 }
1358
1359 impl<CTX> ToStableHashKey<CTX> for SymbolStr {
1360     type KeyType = SymbolStr;
1361
1362     #[inline]
1363     fn to_stable_hash_key(&self, _: &CTX) -> SymbolStr {
1364         self.clone()
1365     }
1366 }