]> git.lizzy.rs Git - rust.git/blob - src/librustc_span/symbol.rs
Rollup merge of #73806 - Aaron1011:feature/approx-universal-upper, r=estebank
[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         variant_count,
838         vec,
839         Vec,
840         version,
841         vis,
842         visible_private_types,
843         volatile,
844         warn,
845         wasm_import_module,
846         wasm_target_feature,
847         while_let,
848         windows,
849         windows_subsystem,
850         wrapping_add,
851         wrapping_sub,
852         wrapping_mul,
853         Yield,
854     }
855 }
856
857 #[derive(Copy, Clone, Eq, HashStable_Generic)]
858 pub struct Ident {
859     pub name: Symbol,
860     pub span: Span,
861 }
862
863 impl Ident {
864     #[inline]
865     /// Constructs a new identifier from a symbol and a span.
866     pub const fn new(name: Symbol, span: Span) -> Ident {
867         Ident { name, span }
868     }
869
870     /// Constructs a new identifier with a dummy span.
871     #[inline]
872     pub const fn with_dummy_span(name: Symbol) -> Ident {
873         Ident::new(name, DUMMY_SP)
874     }
875
876     #[inline]
877     pub fn invalid() -> Ident {
878         Ident::with_dummy_span(kw::Invalid)
879     }
880
881     /// Maps a string to an identifier with a dummy span.
882     pub fn from_str(string: &str) -> Ident {
883         Ident::with_dummy_span(Symbol::intern(string))
884     }
885
886     /// Maps a string and a span to an identifier.
887     pub fn from_str_and_span(string: &str, span: Span) -> Ident {
888         Ident::new(Symbol::intern(string), span)
889     }
890
891     /// Replaces `lo` and `hi` with those from `span`, but keep hygiene context.
892     pub fn with_span_pos(self, span: Span) -> Ident {
893         Ident::new(self.name, span.with_ctxt(self.span.ctxt()))
894     }
895
896     pub fn without_first_quote(self) -> Ident {
897         Ident::new(Symbol::intern(self.as_str().trim_start_matches('\'')), self.span)
898     }
899
900     /// "Normalize" ident for use in comparisons using "item hygiene".
901     /// Identifiers with same string value become same if they came from the same macro 2.0 macro
902     /// (e.g., `macro` item, but not `macro_rules` item) and stay different if they came from
903     /// different macro 2.0 macros.
904     /// Technically, this operation strips all non-opaque marks from ident's syntactic context.
905     pub fn normalize_to_macros_2_0(self) -> Ident {
906         Ident::new(self.name, self.span.normalize_to_macros_2_0())
907     }
908
909     /// "Normalize" ident for use in comparisons using "local variable hygiene".
910     /// Identifiers with same string value become same if they came from the same non-transparent
911     /// macro (e.g., `macro` or `macro_rules!` items) and stay different if they came from different
912     /// non-transparent macros.
913     /// Technically, this operation strips all transparent marks from ident's syntactic context.
914     pub fn normalize_to_macro_rules(self) -> Ident {
915         Ident::new(self.name, self.span.normalize_to_macro_rules())
916     }
917
918     /// Convert the name to a `SymbolStr`. This is a slowish operation because
919     /// it requires locking the symbol interner.
920     pub fn as_str(self) -> SymbolStr {
921         self.name.as_str()
922     }
923 }
924
925 impl PartialEq for Ident {
926     fn eq(&self, rhs: &Self) -> bool {
927         self.name == rhs.name && self.span.ctxt() == rhs.span.ctxt()
928     }
929 }
930
931 impl Hash for Ident {
932     fn hash<H: Hasher>(&self, state: &mut H) {
933         self.name.hash(state);
934         self.span.ctxt().hash(state);
935     }
936 }
937
938 impl fmt::Debug for Ident {
939     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
940         fmt::Display::fmt(self, f)?;
941         fmt::Debug::fmt(&self.span.ctxt(), f)
942     }
943 }
944
945 /// This implementation is supposed to be used in error messages, so it's expected to be identical
946 /// to printing the original identifier token written in source code (`token_to_string`),
947 /// except that AST identifiers don't keep the rawness flag, so we have to guess it.
948 impl fmt::Display for Ident {
949     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
950         fmt::Display::fmt(&IdentPrinter::new(self.name, self.is_raw_guess(), None), f)
951     }
952 }
953
954 impl UseSpecializedEncodable for Ident {
955     fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
956         s.emit_struct("Ident", 2, |s| {
957             s.emit_struct_field("name", 0, |s| self.name.encode(s))?;
958             s.emit_struct_field("span", 1, |s| self.span.encode(s))
959         })
960     }
961 }
962
963 impl UseSpecializedDecodable for Ident {
964     fn default_decode<D: Decoder>(d: &mut D) -> Result<Self, D::Error> {
965         d.read_struct("Ident", 2, |d| {
966             Ok(Ident {
967                 name: d.read_struct_field("name", 0, Decodable::decode)?,
968                 span: d.read_struct_field("span", 1, Decodable::decode)?,
969             })
970         })
971     }
972 }
973
974 /// This is the most general way to print identifiers.
975 /// AST pretty-printer is used as a fallback for turning AST structures into token streams for
976 /// proc macros. Additionally, proc macros may stringify their input and expect it survive the
977 /// stringification (especially true for proc macro derives written between Rust 1.15 and 1.30).
978 /// So we need to somehow pretty-print `$crate` in a way preserving at least some of its
979 /// hygiene data, most importantly name of the crate it refers to.
980 /// As a result we print `$crate` as `crate` if it refers to the local crate
981 /// and as `::other_crate_name` if it refers to some other crate.
982 /// Note, that this is only done if the ident token is printed from inside of AST pretty-pringing,
983 /// but not otherwise. Pretty-printing is the only way for proc macros to discover token contents,
984 /// so we should not perform this lossy conversion if the top level call to the pretty-printer was
985 /// done for a token stream or a single token.
986 pub struct IdentPrinter {
987     symbol: Symbol,
988     is_raw: bool,
989     /// Span used for retrieving the crate name to which `$crate` refers to,
990     /// if this field is `None` then the `$crate` conversion doesn't happen.
991     convert_dollar_crate: Option<Span>,
992 }
993
994 impl IdentPrinter {
995     /// The most general `IdentPrinter` constructor. Do not use this.
996     pub fn new(symbol: Symbol, is_raw: bool, convert_dollar_crate: Option<Span>) -> IdentPrinter {
997         IdentPrinter { symbol, is_raw, convert_dollar_crate }
998     }
999
1000     /// This implementation is supposed to be used when printing identifiers
1001     /// as a part of pretty-printing for larger AST pieces.
1002     /// Do not use this either.
1003     pub fn for_ast_ident(ident: Ident, is_raw: bool) -> IdentPrinter {
1004         IdentPrinter::new(ident.name, is_raw, Some(ident.span))
1005     }
1006 }
1007
1008 impl fmt::Display for IdentPrinter {
1009     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1010         if self.is_raw {
1011             f.write_str("r#")?;
1012         } else {
1013             if self.symbol == kw::DollarCrate {
1014                 if let Some(span) = self.convert_dollar_crate {
1015                     let converted = span.ctxt().dollar_crate_name();
1016                     if !converted.is_path_segment_keyword() {
1017                         f.write_str("::")?;
1018                     }
1019                     return fmt::Display::fmt(&converted, f);
1020                 }
1021             }
1022         }
1023         fmt::Display::fmt(&self.symbol, f)
1024     }
1025 }
1026
1027 /// An newtype around `Ident` that calls [Ident::normalize_to_macro_rules] on
1028 /// construction.
1029 // FIXME(matthewj, petrochenkov) Use this more often, add a similar
1030 // `ModernIdent` struct and use that as well.
1031 #[derive(Copy, Clone, Eq, PartialEq, Hash)]
1032 pub struct MacroRulesNormalizedIdent(Ident);
1033
1034 impl MacroRulesNormalizedIdent {
1035     pub fn new(ident: Ident) -> Self {
1036         Self(ident.normalize_to_macro_rules())
1037     }
1038 }
1039
1040 impl fmt::Debug for MacroRulesNormalizedIdent {
1041     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1042         fmt::Debug::fmt(&self.0, f)
1043     }
1044 }
1045
1046 impl fmt::Display for MacroRulesNormalizedIdent {
1047     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1048         fmt::Display::fmt(&self.0, f)
1049     }
1050 }
1051
1052 /// An interned string.
1053 ///
1054 /// Internally, a `Symbol` is implemented as an index, and all operations
1055 /// (including hashing, equality, and ordering) operate on that index. The use
1056 /// of `rustc_index::newtype_index!` means that `Option<Symbol>` only takes up 4 bytes,
1057 /// because `rustc_index::newtype_index!` reserves the last 256 values for tagging purposes.
1058 ///
1059 /// Note that `Symbol` cannot directly be a `rustc_index::newtype_index!` because it
1060 /// implements `fmt::Debug`, `Encodable`, and `Decodable` in special ways.
1061 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
1062 pub struct Symbol(SymbolIndex);
1063
1064 rustc_index::newtype_index! {
1065     pub struct SymbolIndex { .. }
1066 }
1067
1068 impl Symbol {
1069     const fn new(n: u32) -> Self {
1070         Symbol(SymbolIndex::from_u32(n))
1071     }
1072
1073     /// Maps a string to its interned representation.
1074     pub fn intern(string: &str) -> Self {
1075         with_interner(|interner| interner.intern(string))
1076     }
1077
1078     /// Access the symbol's chars. This is a slowish operation because it
1079     /// requires locking the symbol interner.
1080     pub fn with<F: FnOnce(&str) -> R, R>(self, f: F) -> R {
1081         with_interner(|interner| f(interner.get(self)))
1082     }
1083
1084     /// Convert to a `SymbolStr`. This is a slowish operation because it
1085     /// requires locking the symbol interner.
1086     pub fn as_str(self) -> SymbolStr {
1087         with_interner(|interner| unsafe {
1088             SymbolStr { string: std::mem::transmute::<&str, &str>(interner.get(self)) }
1089         })
1090     }
1091
1092     pub fn as_u32(self) -> u32 {
1093         self.0.as_u32()
1094     }
1095
1096     /// This method is supposed to be used in error messages, so it's expected to be
1097     /// identical to printing the original identifier token written in source code
1098     /// (`token_to_string`, `Ident::to_string`), except that symbols don't keep the rawness flag
1099     /// or edition, so we have to guess the rawness using the global edition.
1100     pub fn to_ident_string(self) -> String {
1101         Ident::with_dummy_span(self).to_string()
1102     }
1103 }
1104
1105 impl fmt::Debug for Symbol {
1106     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1107         self.with(|str| fmt::Debug::fmt(&str, f))
1108     }
1109 }
1110
1111 impl fmt::Display for Symbol {
1112     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1113         self.with(|str| fmt::Display::fmt(&str, f))
1114     }
1115 }
1116
1117 impl Encodable for Symbol {
1118     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1119         self.with(|string| s.emit_str(string))
1120     }
1121 }
1122
1123 impl Decodable for Symbol {
1124     #[inline]
1125     fn decode<D: Decoder>(d: &mut D) -> Result<Symbol, D::Error> {
1126         Ok(Symbol::intern(&d.read_str()?))
1127     }
1128 }
1129
1130 impl<CTX> HashStable<CTX> for Symbol {
1131     #[inline]
1132     fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
1133         self.as_str().hash_stable(hcx, hasher);
1134     }
1135 }
1136
1137 impl<CTX> ToStableHashKey<CTX> for Symbol {
1138     type KeyType = SymbolStr;
1139
1140     #[inline]
1141     fn to_stable_hash_key(&self, _: &CTX) -> SymbolStr {
1142         self.as_str()
1143     }
1144 }
1145
1146 // The `&'static str`s in this type actually point into the arena.
1147 #[derive(Default)]
1148 pub struct Interner {
1149     arena: DroplessArena,
1150     names: FxHashMap<&'static str, Symbol>,
1151     strings: Vec<&'static str>,
1152 }
1153
1154 impl Interner {
1155     fn prefill(init: &[&'static str]) -> Self {
1156         Interner {
1157             strings: init.into(),
1158             names: init.iter().copied().zip((0..).map(Symbol::new)).collect(),
1159             ..Default::default()
1160         }
1161     }
1162
1163     #[inline]
1164     pub fn intern(&mut self, string: &str) -> Symbol {
1165         if let Some(&name) = self.names.get(string) {
1166             return name;
1167         }
1168
1169         let name = Symbol::new(self.strings.len() as u32);
1170
1171         // `from_utf8_unchecked` is safe since we just allocated a `&str` which is known to be
1172         // UTF-8.
1173         let string: &str =
1174             unsafe { str::from_utf8_unchecked(self.arena.alloc_slice(string.as_bytes())) };
1175         // It is safe to extend the arena allocation to `'static` because we only access
1176         // these while the arena is still alive.
1177         let string: &'static str = unsafe { &*(string as *const str) };
1178         self.strings.push(string);
1179         self.names.insert(string, name);
1180         name
1181     }
1182
1183     // Get the symbol as a string. `Symbol::as_str()` should be used in
1184     // preference to this function.
1185     pub fn get(&self, symbol: Symbol) -> &str {
1186         self.strings[symbol.0.as_usize()]
1187     }
1188 }
1189
1190 // This module has a very short name because it's used a lot.
1191 /// This module contains all the defined keyword `Symbol`s.
1192 ///
1193 /// Given that `kw` is imported, use them like `kw::keyword_name`.
1194 /// For example `kw::Loop` or `kw::Break`.
1195 pub mod kw {
1196     use super::Symbol;
1197     keywords!();
1198 }
1199
1200 // This module has a very short name because it's used a lot.
1201 /// This module contains all the defined non-keyword `Symbol`s.
1202 ///
1203 /// Given that `sym` is imported, use them like `sym::symbol_name`.
1204 /// For example `sym::rustfmt` or `sym::u8`.
1205 #[allow(rustc::default_hash_types)]
1206 pub mod sym {
1207     use super::Symbol;
1208     use std::convert::TryInto;
1209
1210     symbols!();
1211
1212     // Used from a macro in `librustc_feature/accepted.rs`
1213     pub use super::kw::MacroRules as macro_rules;
1214
1215     // Get the symbol for an integer. The first few non-negative integers each
1216     // have a static symbol and therefore are fast.
1217     pub fn integer<N: TryInto<usize> + Copy + ToString>(n: N) -> Symbol {
1218         if let Result::Ok(idx) = n.try_into() {
1219             if let Option::Some(&sym_) = digits_array.get(idx) {
1220                 return sym_;
1221             }
1222         }
1223         Symbol::intern(&n.to_string())
1224     }
1225 }
1226
1227 impl Symbol {
1228     fn is_used_keyword_2018(self) -> bool {
1229         self >= kw::Async && self <= kw::Dyn
1230     }
1231
1232     fn is_unused_keyword_2018(self) -> bool {
1233         self == kw::Try
1234     }
1235
1236     /// Used for sanity checking rustdoc keyword sections.
1237     pub fn is_doc_keyword(self) -> bool {
1238         self <= kw::Union
1239     }
1240
1241     /// A keyword or reserved identifier that can be used as a path segment.
1242     pub fn is_path_segment_keyword(self) -> bool {
1243         self == kw::Super
1244             || self == kw::SelfLower
1245             || self == kw::SelfUpper
1246             || self == kw::Crate
1247             || self == kw::PathRoot
1248             || self == kw::DollarCrate
1249     }
1250
1251     /// Returns `true` if the symbol is `true` or `false`.
1252     pub fn is_bool_lit(self) -> bool {
1253         self == kw::True || self == kw::False
1254     }
1255
1256     /// This symbol can be a raw identifier.
1257     pub fn can_be_raw(self) -> bool {
1258         self != kw::Invalid && self != kw::Underscore && !self.is_path_segment_keyword()
1259     }
1260 }
1261
1262 impl Ident {
1263     // Returns `true` for reserved identifiers used internally for elided lifetimes,
1264     // unnamed method parameters, crate root module, error recovery etc.
1265     pub fn is_special(self) -> bool {
1266         self.name <= kw::Underscore
1267     }
1268
1269     /// Returns `true` if the token is a keyword used in the language.
1270     pub fn is_used_keyword(self) -> bool {
1271         // Note: `span.edition()` is relatively expensive, don't call it unless necessary.
1272         self.name >= kw::As && self.name <= kw::While
1273             || self.name.is_used_keyword_2018() && self.span.rust_2018()
1274     }
1275
1276     /// Returns `true` if the token is a keyword reserved for possible future use.
1277     pub fn is_unused_keyword(self) -> bool {
1278         // Note: `span.edition()` is relatively expensive, don't call it unless necessary.
1279         self.name >= kw::Abstract && self.name <= kw::Yield
1280             || self.name.is_unused_keyword_2018() && self.span.rust_2018()
1281     }
1282
1283     /// Returns `true` if the token is either a special identifier or a keyword.
1284     pub fn is_reserved(self) -> bool {
1285         self.is_special() || self.is_used_keyword() || self.is_unused_keyword()
1286     }
1287
1288     /// A keyword or reserved identifier that can be used as a path segment.
1289     pub fn is_path_segment_keyword(self) -> bool {
1290         self.name.is_path_segment_keyword()
1291     }
1292
1293     /// We see this identifier in a normal identifier position, like variable name or a type.
1294     /// How was it written originally? Did it use the raw form? Let's try to guess.
1295     pub fn is_raw_guess(self) -> bool {
1296         self.name.can_be_raw() && self.is_reserved()
1297     }
1298 }
1299
1300 #[inline]
1301 fn with_interner<T, F: FnOnce(&mut Interner) -> T>(f: F) -> T {
1302     GLOBALS.with(|globals| f(&mut *globals.symbol_interner.lock()))
1303 }
1304
1305 /// An alternative to `Symbol`, useful when the chars within the symbol need to
1306 /// be accessed. It deliberately has limited functionality and should only be
1307 /// used for temporary values.
1308 ///
1309 /// Because the interner outlives any thread which uses this type, we can
1310 /// safely treat `string` which points to interner data, as an immortal string,
1311 /// as long as this type never crosses between threads.
1312 //
1313 // FIXME: ensure that the interner outlives any thread which uses `SymbolStr`,
1314 // by creating a new thread right after constructing the interner.
1315 #[derive(Clone, Eq, PartialOrd, Ord)]
1316 pub struct SymbolStr {
1317     string: &'static str,
1318 }
1319
1320 // This impl allows a `SymbolStr` to be directly equated with a `String` or
1321 // `&str`.
1322 impl<T: std::ops::Deref<Target = str>> std::cmp::PartialEq<T> for SymbolStr {
1323     fn eq(&self, other: &T) -> bool {
1324         self.string == other.deref()
1325     }
1326 }
1327
1328 impl !Send for SymbolStr {}
1329 impl !Sync for SymbolStr {}
1330
1331 /// This impl means that if `ss` is a `SymbolStr`:
1332 /// - `*ss` is a `str`;
1333 /// - `&*ss` is a `&str`;
1334 /// - `&ss as &str` is a `&str`, which means that `&ss` can be passed to a
1335 ///   function expecting a `&str`.
1336 impl std::ops::Deref for SymbolStr {
1337     type Target = str;
1338     #[inline]
1339     fn deref(&self) -> &str {
1340         self.string
1341     }
1342 }
1343
1344 impl fmt::Debug for SymbolStr {
1345     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1346         fmt::Debug::fmt(self.string, f)
1347     }
1348 }
1349
1350 impl fmt::Display for SymbolStr {
1351     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1352         fmt::Display::fmt(self.string, f)
1353     }
1354 }
1355
1356 impl<CTX> HashStable<CTX> for SymbolStr {
1357     #[inline]
1358     fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
1359         self.string.hash_stable(hcx, hasher)
1360     }
1361 }
1362
1363 impl<CTX> ToStableHashKey<CTX> for SymbolStr {
1364     type KeyType = SymbolStr;
1365
1366     #[inline]
1367     fn to_stable_hash_key(&self, _: &CTX) -> SymbolStr {
1368         self.clone()
1369     }
1370 }