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