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