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