]> git.lizzy.rs Git - rust.git/blob - src/librustc_span/symbol.rs
Rollup merge of #73588 - Amanieu:thumb-fp, r=nagisa
[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         line,
431         link,
432         linkage,
433         link_args,
434         link_cfg,
435         link_llvm_intrinsics,
436         link_name,
437         link_ordinal,
438         link_section,
439         LintPass,
440         lint_reasons,
441         literal,
442         llvm_asm,
443         local_inner_macros,
444         log_syntax,
445         loop_break_value,
446         macro_at_most_once_rep,
447         macro_escape,
448         macro_export,
449         macro_lifetime_matcher,
450         macro_literal_matcher,
451         macro_reexport,
452         macros_in_extern,
453         macro_use,
454         macro_vis_matcher,
455         main,
456         managed_boxes,
457         marker,
458         marker_trait_attr,
459         masked,
460         match_beginning_vert,
461         match_default_bindings,
462         may_dangle,
463         maybe_uninit_uninit,
464         maybe_uninit_zeroed,
465         mem_uninitialized,
466         mem_zeroed,
467         member_constraints,
468         memory,
469         message,
470         meta,
471         min_align_of,
472         min_const_fn,
473         min_const_unsafe_fn,
474         min_specialization,
475         mips_target_feature,
476         mmx_target_feature,
477         module,
478         module_path,
479         more_struct_aliases,
480         move_ref_pattern,
481         move_val_init,
482         movbe_target_feature,
483         mul_with_overflow,
484         must_use,
485         naked,
486         naked_functions,
487         name,
488         needs_allocator,
489         needs_drop,
490         needs_panic_runtime,
491         negate_unsigned,
492         negative_impls,
493         never,
494         never_type,
495         never_type_fallback,
496         new,
497         next,
498         __next,
499         nll,
500         no_builtins,
501         no_core,
502         no_crate_inject,
503         no_debug,
504         no_default_passes,
505         no_implicit_prelude,
506         no_inline,
507         no_link,
508         no_main,
509         no_mangle,
510         nomem,
511         non_ascii_idents,
512         None,
513         non_exhaustive,
514         non_modrs_mods,
515         noreturn,
516         no_niche,
517         no_sanitize,
518         nostack,
519         no_stack_check,
520         no_start,
521         no_std,
522         not,
523         note,
524         object_safe_for_dispatch,
525         offset,
526         Ok,
527         omit_gdb_pretty_printer_section,
528         on,
529         on_unimplemented,
530         oom,
531         ops,
532         optimize,
533         optimize_attribute,
534         optin_builtin_traits,
535         option,
536         Option,
537         option_env,
538         options,
539         opt_out_copy,
540         or,
541         or_patterns,
542         Ord,
543         Ordering,
544         out,
545         Output,
546         overlapping_marker_traits,
547         packed,
548         panic,
549         panic_handler,
550         panic_impl,
551         panic_implementation,
552         panic_runtime,
553         parent_trait,
554         partial_cmp,
555         param_attrs,
556         PartialEq,
557         PartialOrd,
558         passes,
559         pat,
560         path,
561         pattern_parentheses,
562         Pending,
563         pin,
564         Pin,
565         pinned,
566         platform_intrinsics,
567         plugin,
568         plugin_registrar,
569         plugins,
570         poll,
571         Poll,
572         powerpc_target_feature,
573         precise_pointer_size_matching,
574         pref_align_of,
575         prelude,
576         prelude_import,
577         preserves_flags,
578         primitive,
579         proc_dash_macro: "proc-macro",
580         proc_macro,
581         proc_macro_attribute,
582         proc_macro_def_site,
583         proc_macro_derive,
584         proc_macro_expr,
585         proc_macro_gen,
586         proc_macro_hygiene,
587         proc_macro_internals,
588         proc_macro_mod,
589         proc_macro_non_items,
590         proc_macro_path_invoc,
591         profiler_builtins,
592         profiler_runtime,
593         ptr_guaranteed_eq,
594         ptr_guaranteed_ne,
595         ptr_offset_from,
596         pub_restricted,
597         pure,
598         pushpop_unsafe,
599         quad_precision_float,
600         question_mark,
601         quote,
602         Range,
603         RangeFrom,
604         RangeFull,
605         RangeInclusive,
606         RangeTo,
607         RangeToInclusive,
608         raw_dylib,
609         raw_identifiers,
610         raw_ref_op,
611         Rc,
612         readonly,
613         Ready,
614         reason,
615         recursion_limit,
616         reexport_test_harness_main,
617         reflect,
618         register_attr,
619         register_tool,
620         relaxed_adts,
621         repr,
622         repr128,
623         repr_align,
624         repr_align_enum,
625         repr_no_niche,
626         repr_packed,
627         repr_simd,
628         repr_transparent,
629         re_rebalance_coherence,
630         result,
631         Result,
632         Return,
633         rhs,
634         riscv_target_feature,
635         rlib,
636         rotate_left,
637         rotate_right,
638         rt,
639         rtm_target_feature,
640         rust,
641         rust_2015_preview,
642         rust_2018_preview,
643         rust_begin_unwind,
644         rustc,
645         RustcDecodable,
646         RustcEncodable,
647         rustc_allocator,
648         rustc_allocator_nounwind,
649         rustc_allow_const_fn_ptr,
650         rustc_args_required_const,
651         rustc_attrs,
652         rustc_builtin_macro,
653         rustc_clean,
654         rustc_const_unstable,
655         rustc_const_stable,
656         rustc_conversion_suggestion,
657         rustc_def_path,
658         rustc_deprecated,
659         rustc_diagnostic_item,
660         rustc_diagnostic_macros,
661         rustc_dirty,
662         rustc_dummy,
663         rustc_dump_env_program_clauses,
664         rustc_dump_program_clauses,
665         rustc_dump_user_substs,
666         rustc_error,
667         rustc_expected_cgu_reuse,
668         rustc_if_this_changed,
669         rustc_inherit_overflow_checks,
670         rustc_layout,
671         rustc_layout_scalar_valid_range_end,
672         rustc_layout_scalar_valid_range_start,
673         rustc_macro_transparency,
674         rustc_mir,
675         rustc_nonnull_optimization_guaranteed,
676         rustc_object_lifetime_default,
677         rustc_on_unimplemented,
678         rustc_outlives,
679         rustc_paren_sugar,
680         rustc_partition_codegened,
681         rustc_partition_reused,
682         rustc_peek,
683         rustc_peek_definite_init,
684         rustc_peek_liveness,
685         rustc_peek_maybe_init,
686         rustc_peek_maybe_uninit,
687         rustc_peek_indirectly_mutable,
688         rustc_private,
689         rustc_proc_macro_decls,
690         rustc_promotable,
691         rustc_regions,
692         rustc_unsafe_specialization_marker,
693         rustc_specialization_trait,
694         rustc_stable,
695         rustc_std_internal_symbol,
696         rustc_symbol_name,
697         rustc_synthetic,
698         rustc_reservation_impl,
699         rustc_test_marker,
700         rustc_then_this_would_need,
701         rustc_variance,
702         rustfmt,
703         rust_eh_personality,
704         rust_oom,
705         rvalue_static_promotion,
706         sanitize,
707         sanitizer_runtime,
708         saturating_add,
709         saturating_sub,
710         _Self,
711         self_in_typedefs,
712         self_struct_ctor,
713         send_trait,
714         should_panic,
715         simd,
716         simd_extract,
717         simd_ffi,
718         simd_insert,
719         since,
720         size,
721         size_of,
722         slice_patterns,
723         slicing_syntax,
724         soft,
725         Some,
726         specialization,
727         speed,
728         sse4a_target_feature,
729         stable,
730         staged_api,
731         start,
732         static_in_const,
733         staticlib,
734         static_nobundle,
735         static_recursion,
736         std,
737         std_inject,
738         str,
739         stringify,
740         stmt,
741         stmt_expr_attributes,
742         stop_after_dataflow,
743         struct_field_attributes,
744         struct_inherit,
745         structural_match,
746         struct_variant,
747         sty,
748         sub_with_overflow,
749         suggestion,
750         sym,
751         sync_trait,
752         target_feature,
753         target_feature_11,
754         target_has_atomic,
755         target_has_atomic_load_store,
756         target_thread_local,
757         task,
758         _task_context,
759         tbm_target_feature,
760         termination_trait,
761         termination_trait_test,
762         test,
763         test_2018_feature,
764         test_accepted_feature,
765         test_case,
766         test_removed_feature,
767         test_runner,
768         then_with,
769         thread,
770         thread_local,
771         tool_attributes,
772         tool_lints,
773         trace_macros,
774         track_caller,
775         trait_alias,
776         transmute,
777         transparent,
778         transparent_enums,
779         transparent_unions,
780         trivial_bounds,
781         Try,
782         try_blocks,
783         try_trait,
784         tt,
785         tuple_indexing,
786         two_phase,
787         Ty,
788         ty,
789         type_alias_impl_trait,
790         type_id,
791         type_name,
792         TyCtxt,
793         TyKind,
794         type_alias_enum_variants,
795         type_ascription,
796         type_length_limit,
797         type_macros,
798         u128,
799         u16,
800         u32,
801         u64,
802         u8,
803         unboxed_closures,
804         unchecked_add,
805         unchecked_div,
806         unchecked_mul,
807         unchecked_rem,
808         unchecked_shl,
809         unchecked_shr,
810         unchecked_sub,
811         underscore_const_names,
812         underscore_imports,
813         underscore_lifetimes,
814         uniform_paths,
815         universal_impl_trait,
816         unmarked_api,
817         unreachable_code,
818         unrestricted_attribute_tokens,
819         unsafe_block_in_unsafe_fn,
820         unsafe_no_drop_flag,
821         unsized_locals,
822         unsized_tuple_coercion,
823         unstable,
824         untagged_unions,
825         unwind,
826         unwind_attributes,
827         unwrap_or,
828         used,
829         use_extern_macros,
830         use_nested_groups,
831         usize,
832         v1,
833         val,
834         var,
835         variant_count,
836         vec,
837         Vec,
838         version,
839         vis,
840         visible_private_types,
841         volatile,
842         warn,
843         wasm_import_module,
844         wasm_target_feature,
845         while_let,
846         windows,
847         windows_subsystem,
848         wrapping_add,
849         wrapping_sub,
850         wrapping_mul,
851         Yield,
852     }
853 }
854
855 #[derive(Copy, Clone, Eq, HashStable_Generic)]
856 pub struct Ident {
857     pub name: Symbol,
858     pub span: Span,
859 }
860
861 impl Ident {
862     #[inline]
863     /// Constructs a new identifier from a symbol and a span.
864     pub const fn new(name: Symbol, span: Span) -> Ident {
865         Ident { name, span }
866     }
867
868     /// Constructs a new identifier with a dummy span.
869     #[inline]
870     pub const fn with_dummy_span(name: Symbol) -> Ident {
871         Ident::new(name, DUMMY_SP)
872     }
873
874     #[inline]
875     pub fn invalid() -> Ident {
876         Ident::with_dummy_span(kw::Invalid)
877     }
878
879     /// Maps a string to an identifier with a dummy span.
880     pub fn from_str(string: &str) -> Ident {
881         Ident::with_dummy_span(Symbol::intern(string))
882     }
883
884     /// Maps a string and a span to an identifier.
885     pub fn from_str_and_span(string: &str, span: Span) -> Ident {
886         Ident::new(Symbol::intern(string), span)
887     }
888
889     /// Replaces `lo` and `hi` with those from `span`, but keep hygiene context.
890     pub fn with_span_pos(self, span: Span) -> Ident {
891         Ident::new(self.name, span.with_ctxt(self.span.ctxt()))
892     }
893
894     pub fn without_first_quote(self) -> Ident {
895         Ident::new(Symbol::intern(self.as_str().trim_start_matches('\'')), self.span)
896     }
897
898     /// "Normalize" ident for use in comparisons using "item hygiene".
899     /// Identifiers with same string value become same if they came from the same macro 2.0 macro
900     /// (e.g., `macro` item, but not `macro_rules` item) and stay different if they came from
901     /// different macro 2.0 macros.
902     /// Technically, this operation strips all non-opaque marks from ident's syntactic context.
903     pub fn normalize_to_macros_2_0(self) -> Ident {
904         Ident::new(self.name, self.span.normalize_to_macros_2_0())
905     }
906
907     /// "Normalize" ident for use in comparisons using "local variable hygiene".
908     /// Identifiers with same string value become same if they came from the same non-transparent
909     /// macro (e.g., `macro` or `macro_rules!` items) and stay different if they came from different
910     /// non-transparent macros.
911     /// Technically, this operation strips all transparent marks from ident's syntactic context.
912     pub fn normalize_to_macro_rules(self) -> Ident {
913         Ident::new(self.name, self.span.normalize_to_macro_rules())
914     }
915
916     /// Convert the name to a `SymbolStr`. This is a slowish operation because
917     /// it requires locking the symbol interner.
918     pub fn as_str(self) -> SymbolStr {
919         self.name.as_str()
920     }
921 }
922
923 impl PartialEq for Ident {
924     fn eq(&self, rhs: &Self) -> bool {
925         self.name == rhs.name && self.span.ctxt() == rhs.span.ctxt()
926     }
927 }
928
929 impl Hash for Ident {
930     fn hash<H: Hasher>(&self, state: &mut H) {
931         self.name.hash(state);
932         self.span.ctxt().hash(state);
933     }
934 }
935
936 impl fmt::Debug for Ident {
937     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
938         fmt::Display::fmt(self, f)?;
939         fmt::Debug::fmt(&self.span.ctxt(), f)
940     }
941 }
942
943 /// This implementation is supposed to be used in error messages, so it's expected to be identical
944 /// to printing the original identifier token written in source code (`token_to_string`),
945 /// except that AST identifiers don't keep the rawness flag, so we have to guess it.
946 impl fmt::Display for Ident {
947     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
948         fmt::Display::fmt(&IdentPrinter::new(self.name, self.is_raw_guess(), None), f)
949     }
950 }
951
952 impl UseSpecializedEncodable for Ident {
953     fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
954         s.emit_struct("Ident", 2, |s| {
955             s.emit_struct_field("name", 0, |s| self.name.encode(s))?;
956             s.emit_struct_field("span", 1, |s| self.span.encode(s))
957         })
958     }
959 }
960
961 impl UseSpecializedDecodable for Ident {
962     fn default_decode<D: Decoder>(d: &mut D) -> Result<Self, D::Error> {
963         d.read_struct("Ident", 2, |d| {
964             Ok(Ident {
965                 name: d.read_struct_field("name", 0, Decodable::decode)?,
966                 span: d.read_struct_field("span", 1, Decodable::decode)?,
967             })
968         })
969     }
970 }
971
972 /// This is the most general way to print identifiers.
973 /// AST pretty-printer is used as a fallback for turning AST structures into token streams for
974 /// proc macros. Additionally, proc macros may stringify their input and expect it survive the
975 /// stringification (especially true for proc macro derives written between Rust 1.15 and 1.30).
976 /// So we need to somehow pretty-print `$crate` in a way preserving at least some of its
977 /// hygiene data, most importantly name of the crate it refers to.
978 /// As a result we print `$crate` as `crate` if it refers to the local crate
979 /// and as `::other_crate_name` if it refers to some other crate.
980 /// Note, that this is only done if the ident token is printed from inside of AST pretty-pringing,
981 /// but not otherwise. Pretty-printing is the only way for proc macros to discover token contents,
982 /// so we should not perform this lossy conversion if the top level call to the pretty-printer was
983 /// done for a token stream or a single token.
984 pub struct IdentPrinter {
985     symbol: Symbol,
986     is_raw: bool,
987     /// Span used for retrieving the crate name to which `$crate` refers to,
988     /// if this field is `None` then the `$crate` conversion doesn't happen.
989     convert_dollar_crate: Option<Span>,
990 }
991
992 impl IdentPrinter {
993     /// The most general `IdentPrinter` constructor. Do not use this.
994     pub fn new(symbol: Symbol, is_raw: bool, convert_dollar_crate: Option<Span>) -> IdentPrinter {
995         IdentPrinter { symbol, is_raw, convert_dollar_crate }
996     }
997
998     /// This implementation is supposed to be used when printing identifiers
999     /// as a part of pretty-printing for larger AST pieces.
1000     /// Do not use this either.
1001     pub fn for_ast_ident(ident: Ident, is_raw: bool) -> IdentPrinter {
1002         IdentPrinter::new(ident.name, is_raw, Some(ident.span))
1003     }
1004 }
1005
1006 impl fmt::Display for IdentPrinter {
1007     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1008         if self.is_raw {
1009             f.write_str("r#")?;
1010         } else {
1011             if self.symbol == kw::DollarCrate {
1012                 if let Some(span) = self.convert_dollar_crate {
1013                     let converted = span.ctxt().dollar_crate_name();
1014                     if !converted.is_path_segment_keyword() {
1015                         f.write_str("::")?;
1016                     }
1017                     return fmt::Display::fmt(&converted, f);
1018                 }
1019             }
1020         }
1021         fmt::Display::fmt(&self.symbol, f)
1022     }
1023 }
1024
1025 /// An newtype around `Ident` that calls [Ident::normalize_to_macro_rules] on
1026 /// construction.
1027 // FIXME(matthewj, petrochenkov) Use this more often, add a similar
1028 // `ModernIdent` struct and use that as well.
1029 #[derive(Copy, Clone, Eq, PartialEq, Hash)]
1030 pub struct MacroRulesNormalizedIdent(Ident);
1031
1032 impl MacroRulesNormalizedIdent {
1033     pub fn new(ident: Ident) -> Self {
1034         Self(ident.normalize_to_macro_rules())
1035     }
1036 }
1037
1038 impl fmt::Debug for MacroRulesNormalizedIdent {
1039     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1040         fmt::Debug::fmt(&self.0, f)
1041     }
1042 }
1043
1044 impl fmt::Display for MacroRulesNormalizedIdent {
1045     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1046         fmt::Display::fmt(&self.0, f)
1047     }
1048 }
1049
1050 /// An interned string.
1051 ///
1052 /// Internally, a `Symbol` is implemented as an index, and all operations
1053 /// (including hashing, equality, and ordering) operate on that index. The use
1054 /// of `rustc_index::newtype_index!` means that `Option<Symbol>` only takes up 4 bytes,
1055 /// because `rustc_index::newtype_index!` reserves the last 256 values for tagging purposes.
1056 ///
1057 /// Note that `Symbol` cannot directly be a `rustc_index::newtype_index!` because it
1058 /// implements `fmt::Debug`, `Encodable`, and `Decodable` in special ways.
1059 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
1060 pub struct Symbol(SymbolIndex);
1061
1062 rustc_index::newtype_index! {
1063     pub struct SymbolIndex { .. }
1064 }
1065
1066 impl Symbol {
1067     const fn new(n: u32) -> Self {
1068         Symbol(SymbolIndex::from_u32(n))
1069     }
1070
1071     /// Maps a string to its interned representation.
1072     pub fn intern(string: &str) -> Self {
1073         with_interner(|interner| interner.intern(string))
1074     }
1075
1076     /// Access the symbol's chars. This is a slowish operation because it
1077     /// requires locking the symbol interner.
1078     pub fn with<F: FnOnce(&str) -> R, R>(self, f: F) -> R {
1079         with_interner(|interner| f(interner.get(self)))
1080     }
1081
1082     /// Convert to a `SymbolStr`. This is a slowish operation because it
1083     /// requires locking the symbol interner.
1084     pub fn as_str(self) -> SymbolStr {
1085         with_interner(|interner| unsafe {
1086             SymbolStr { string: std::mem::transmute::<&str, &str>(interner.get(self)) }
1087         })
1088     }
1089
1090     pub fn as_u32(self) -> u32 {
1091         self.0.as_u32()
1092     }
1093
1094     /// This method is supposed to be used in error messages, so it's expected to be
1095     /// identical to printing the original identifier token written in source code
1096     /// (`token_to_string`, `Ident::to_string`), except that symbols don't keep the rawness flag
1097     /// or edition, so we have to guess the rawness using the global edition.
1098     pub fn to_ident_string(self) -> String {
1099         Ident::with_dummy_span(self).to_string()
1100     }
1101 }
1102
1103 impl fmt::Debug for Symbol {
1104     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1105         self.with(|str| fmt::Debug::fmt(&str, f))
1106     }
1107 }
1108
1109 impl fmt::Display for Symbol {
1110     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1111         self.with(|str| fmt::Display::fmt(&str, f))
1112     }
1113 }
1114
1115 impl Encodable for Symbol {
1116     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1117         self.with(|string| s.emit_str(string))
1118     }
1119 }
1120
1121 impl Decodable for Symbol {
1122     #[inline]
1123     fn decode<D: Decoder>(d: &mut D) -> Result<Symbol, D::Error> {
1124         Ok(Symbol::intern(&d.read_str()?))
1125     }
1126 }
1127
1128 impl<CTX> HashStable<CTX> for Symbol {
1129     #[inline]
1130     fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
1131         self.as_str().hash_stable(hcx, hasher);
1132     }
1133 }
1134
1135 impl<CTX> ToStableHashKey<CTX> for Symbol {
1136     type KeyType = SymbolStr;
1137
1138     #[inline]
1139     fn to_stable_hash_key(&self, _: &CTX) -> SymbolStr {
1140         self.as_str()
1141     }
1142 }
1143
1144 // The `&'static str`s in this type actually point into the arena.
1145 #[derive(Default)]
1146 pub struct Interner {
1147     arena: DroplessArena,
1148     names: FxHashMap<&'static str, Symbol>,
1149     strings: Vec<&'static str>,
1150 }
1151
1152 impl Interner {
1153     fn prefill(init: &[&'static str]) -> Self {
1154         Interner {
1155             strings: init.into(),
1156             names: init.iter().copied().zip((0..).map(Symbol::new)).collect(),
1157             ..Default::default()
1158         }
1159     }
1160
1161     #[inline]
1162     pub fn intern(&mut self, string: &str) -> Symbol {
1163         if let Some(&name) = self.names.get(string) {
1164             return name;
1165         }
1166
1167         let name = Symbol::new(self.strings.len() as u32);
1168
1169         // `from_utf8_unchecked` is safe since we just allocated a `&str` which is known to be
1170         // UTF-8.
1171         let string: &str =
1172             unsafe { str::from_utf8_unchecked(self.arena.alloc_slice(string.as_bytes())) };
1173         // It is safe to extend the arena allocation to `'static` because we only access
1174         // these while the arena is still alive.
1175         let string: &'static str = unsafe { &*(string as *const str) };
1176         self.strings.push(string);
1177         self.names.insert(string, name);
1178         name
1179     }
1180
1181     // Get the symbol as a string. `Symbol::as_str()` should be used in
1182     // preference to this function.
1183     pub fn get(&self, symbol: Symbol) -> &str {
1184         self.strings[symbol.0.as_usize()]
1185     }
1186 }
1187
1188 // This module has a very short name because it's used a lot.
1189 /// This module contains all the defined keyword `Symbol`s.
1190 ///
1191 /// Given that `kw` is imported, use them like `kw::keyword_name`.
1192 /// For example `kw::Loop` or `kw::Break`.
1193 pub mod kw {
1194     use super::Symbol;
1195     keywords!();
1196 }
1197
1198 // This module has a very short name because it's used a lot.
1199 /// This module contains all the defined non-keyword `Symbol`s.
1200 ///
1201 /// Given that `sym` is imported, use them like `sym::symbol_name`.
1202 /// For example `sym::rustfmt` or `sym::u8`.
1203 #[allow(rustc::default_hash_types)]
1204 pub mod sym {
1205     use super::Symbol;
1206     use std::convert::TryInto;
1207
1208     symbols!();
1209
1210     // Used from a macro in `librustc_feature/accepted.rs`
1211     pub use super::kw::MacroRules as macro_rules;
1212
1213     // Get the symbol for an integer. The first few non-negative integers each
1214     // have a static symbol and therefore are fast.
1215     pub fn integer<N: TryInto<usize> + Copy + ToString>(n: N) -> Symbol {
1216         if let Result::Ok(idx) = n.try_into() {
1217             if let Option::Some(&sym_) = digits_array.get(idx) {
1218                 return sym_;
1219             }
1220         }
1221         Symbol::intern(&n.to_string())
1222     }
1223 }
1224
1225 impl Symbol {
1226     fn is_used_keyword_2018(self) -> bool {
1227         self >= kw::Async && self <= kw::Dyn
1228     }
1229
1230     fn is_unused_keyword_2018(self) -> bool {
1231         self == kw::Try
1232     }
1233
1234     /// Used for sanity checking rustdoc keyword sections.
1235     pub fn is_doc_keyword(self) -> bool {
1236         self <= kw::Union
1237     }
1238
1239     /// A keyword or reserved identifier that can be used as a path segment.
1240     pub fn is_path_segment_keyword(self) -> bool {
1241         self == kw::Super
1242             || self == kw::SelfLower
1243             || self == kw::SelfUpper
1244             || self == kw::Crate
1245             || self == kw::PathRoot
1246             || self == kw::DollarCrate
1247     }
1248
1249     /// Returns `true` if the symbol is `true` or `false`.
1250     pub fn is_bool_lit(self) -> bool {
1251         self == kw::True || self == kw::False
1252     }
1253
1254     /// This symbol can be a raw identifier.
1255     pub fn can_be_raw(self) -> bool {
1256         self != kw::Invalid && self != kw::Underscore && !self.is_path_segment_keyword()
1257     }
1258 }
1259
1260 impl Ident {
1261     // Returns `true` for reserved identifiers used internally for elided lifetimes,
1262     // unnamed method parameters, crate root module, error recovery etc.
1263     pub fn is_special(self) -> bool {
1264         self.name <= kw::Underscore
1265     }
1266
1267     /// Returns `true` if the token is a keyword used in the language.
1268     pub fn is_used_keyword(self) -> bool {
1269         // Note: `span.edition()` is relatively expensive, don't call it unless necessary.
1270         self.name >= kw::As && self.name <= kw::While
1271             || self.name.is_used_keyword_2018() && self.span.rust_2018()
1272     }
1273
1274     /// Returns `true` if the token is a keyword reserved for possible future use.
1275     pub fn is_unused_keyword(self) -> bool {
1276         // Note: `span.edition()` is relatively expensive, don't call it unless necessary.
1277         self.name >= kw::Abstract && self.name <= kw::Yield
1278             || self.name.is_unused_keyword_2018() && self.span.rust_2018()
1279     }
1280
1281     /// Returns `true` if the token is either a special identifier or a keyword.
1282     pub fn is_reserved(self) -> bool {
1283         self.is_special() || self.is_used_keyword() || self.is_unused_keyword()
1284     }
1285
1286     /// A keyword or reserved identifier that can be used as a path segment.
1287     pub fn is_path_segment_keyword(self) -> bool {
1288         self.name.is_path_segment_keyword()
1289     }
1290
1291     /// We see this identifier in a normal identifier position, like variable name or a type.
1292     /// How was it written originally? Did it use the raw form? Let's try to guess.
1293     pub fn is_raw_guess(self) -> bool {
1294         self.name.can_be_raw() && self.is_reserved()
1295     }
1296 }
1297
1298 #[inline]
1299 fn with_interner<T, F: FnOnce(&mut Interner) -> T>(f: F) -> T {
1300     GLOBALS.with(|globals| f(&mut *globals.symbol_interner.lock()))
1301 }
1302
1303 /// An alternative to `Symbol`, useful when the chars within the symbol need to
1304 /// be accessed. It deliberately has limited functionality and should only be
1305 /// used for temporary values.
1306 ///
1307 /// Because the interner outlives any thread which uses this type, we can
1308 /// safely treat `string` which points to interner data, as an immortal string,
1309 /// as long as this type never crosses between threads.
1310 //
1311 // FIXME: ensure that the interner outlives any thread which uses `SymbolStr`,
1312 // by creating a new thread right after constructing the interner.
1313 #[derive(Clone, Eq, PartialOrd, Ord)]
1314 pub struct SymbolStr {
1315     string: &'static str,
1316 }
1317
1318 // This impl allows a `SymbolStr` to be directly equated with a `String` or
1319 // `&str`.
1320 impl<T: std::ops::Deref<Target = str>> std::cmp::PartialEq<T> for SymbolStr {
1321     fn eq(&self, other: &T) -> bool {
1322         self.string == other.deref()
1323     }
1324 }
1325
1326 impl !Send for SymbolStr {}
1327 impl !Sync for SymbolStr {}
1328
1329 /// This impl means that if `ss` is a `SymbolStr`:
1330 /// - `*ss` is a `str`;
1331 /// - `&*ss` is a `&str`;
1332 /// - `&ss as &str` is a `&str`, which means that `&ss` can be passed to a
1333 ///   function expecting a `&str`.
1334 impl std::ops::Deref for SymbolStr {
1335     type Target = str;
1336     #[inline]
1337     fn deref(&self) -> &str {
1338         self.string
1339     }
1340 }
1341
1342 impl fmt::Debug for SymbolStr {
1343     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1344         fmt::Debug::fmt(self.string, f)
1345     }
1346 }
1347
1348 impl fmt::Display for SymbolStr {
1349     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1350         fmt::Display::fmt(self.string, f)
1351     }
1352 }
1353
1354 impl<CTX> HashStable<CTX> for SymbolStr {
1355     #[inline]
1356     fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
1357         self.string.hash_stable(hcx, hasher)
1358     }
1359 }
1360
1361 impl<CTX> ToStableHashKey<CTX> for SymbolStr {
1362     type KeyType = SymbolStr;
1363
1364     #[inline]
1365     fn to_stable_hash_key(&self, _: &CTX) -> SymbolStr {
1366         self.clone()
1367     }
1368 }