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