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