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