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