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