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