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