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