]> git.lizzy.rs Git - rust.git/blob - src/libsyntax_pos/symbol.rs
add basic lint testing for misuse of mem::zeroed and mem::uninitialized
[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         mem,
416         member_constraints,
417         message,
418         meta,
419         min_const_fn,
420         min_const_unsafe_fn,
421         mips_target_feature,
422         mmx_target_feature,
423         module,
424         module_path,
425         more_struct_aliases,
426         movbe_target_feature,
427         must_use,
428         naked,
429         naked_functions,
430         name,
431         needs_allocator,
432         needs_panic_runtime,
433         negate_unsigned,
434         never,
435         never_type,
436         new,
437         next,
438         __next,
439         nll,
440         no_builtins,
441         no_core,
442         no_crate_inject,
443         no_debug,
444         no_default_passes,
445         no_implicit_prelude,
446         no_inline,
447         no_link,
448         no_main,
449         no_mangle,
450         non_ascii_idents,
451         None,
452         non_exhaustive,
453         non_modrs_mods,
454         no_stack_check,
455         no_start,
456         no_std,
457         not,
458         note,
459         Ok,
460         omit_gdb_pretty_printer_section,
461         on,
462         on_unimplemented,
463         oom,
464         ops,
465         optimize,
466         optimize_attribute,
467         optin_builtin_traits,
468         option,
469         Option,
470         option_env,
471         opt_out_copy,
472         or,
473         Ord,
474         Ordering,
475         Output,
476         overlapping_marker_traits,
477         packed,
478         panic,
479         panic_handler,
480         panic_impl,
481         panic_implementation,
482         panic_runtime,
483         parent_trait,
484         partial_cmp,
485         param_attrs,
486         PartialEq,
487         PartialOrd,
488         passes,
489         pat,
490         path,
491         pattern_parentheses,
492         Pending,
493         pin,
494         Pin,
495         pinned,
496         platform_intrinsics,
497         plugin,
498         plugin_registrar,
499         plugins,
500         Poll,
501         poll_with_tls_context,
502         powerpc_target_feature,
503         precise_pointer_size_matching,
504         prelude,
505         prelude_import,
506         primitive,
507         proc_dash_macro: "proc-macro",
508         proc_macro,
509         proc_macro_attribute,
510         proc_macro_def_site,
511         proc_macro_derive,
512         proc_macro_expr,
513         proc_macro_gen,
514         proc_macro_hygiene,
515         proc_macro_internals,
516         proc_macro_mod,
517         proc_macro_non_items,
518         proc_macro_path_invoc,
519         profiler_runtime,
520         pub_restricted,
521         pushpop_unsafe,
522         quad_precision_float,
523         question_mark,
524         quote,
525         Range,
526         RangeFrom,
527         RangeFull,
528         RangeInclusive,
529         RangeTo,
530         RangeToInclusive,
531         raw_identifiers,
532         Ready,
533         reason,
534         recursion_limit,
535         reexport_test_harness_main,
536         reflect,
537         relaxed_adts,
538         repr,
539         repr128,
540         repr_align,
541         repr_align_enum,
542         repr_packed,
543         repr_simd,
544         repr_transparent,
545         re_rebalance_coherence,
546         result,
547         Result,
548         Return,
549         rhs,
550         rlib,
551         rt,
552         rtm_target_feature,
553         rust,
554         rust_2015_preview,
555         rust_2018_preview,
556         rust_begin_unwind,
557         rustc,
558         RustcDecodable,
559         RustcEncodable,
560         rustc_allocator,
561         rustc_allocator_nounwind,
562         rustc_allow_const_fn_ptr,
563         rustc_args_required_const,
564         rustc_attrs,
565         rustc_builtin_macro,
566         rustc_clean,
567         rustc_const_unstable,
568         rustc_conversion_suggestion,
569         rustc_def_path,
570         rustc_deprecated,
571         rustc_diagnostic_macros,
572         rustc_dirty,
573         rustc_dummy,
574         rustc_dump_env_program_clauses,
575         rustc_dump_program_clauses,
576         rustc_dump_user_substs,
577         rustc_error,
578         rustc_expected_cgu_reuse,
579         rustc_if_this_changed,
580         rustc_inherit_overflow_checks,
581         rustc_layout,
582         rustc_layout_scalar_valid_range_end,
583         rustc_layout_scalar_valid_range_start,
584         rustc_macro_transparency,
585         rustc_mir,
586         rustc_nonnull_optimization_guaranteed,
587         rustc_object_lifetime_default,
588         rustc_on_unimplemented,
589         rustc_outlives,
590         rustc_paren_sugar,
591         rustc_partition_codegened,
592         rustc_partition_reused,
593         rustc_peek,
594         rustc_peek_definite_init,
595         rustc_peek_maybe_init,
596         rustc_peek_maybe_uninit,
597         rustc_private,
598         rustc_proc_macro_decls,
599         rustc_promotable,
600         rustc_regions,
601         rustc_stable,
602         rustc_std_internal_symbol,
603         rustc_symbol_name,
604         rustc_synthetic,
605         rustc_test_marker,
606         rustc_then_this_would_need,
607         rustc_variance,
608         rustdoc,
609         rustfmt,
610         rust_eh_personality,
611         rust_eh_unwind_resume,
612         rust_oom,
613         __rust_unstable_column,
614         rvalue_static_promotion,
615         sanitizer_runtime,
616         _Self,
617         self_in_typedefs,
618         self_struct_ctor,
619         should_panic,
620         simd,
621         simd_ffi,
622         since,
623         size,
624         slice_patterns,
625         slicing_syntax,
626         Some,
627         specialization,
628         speed,
629         spotlight,
630         sse4a_target_feature,
631         stable,
632         staged_api,
633         start,
634         static_in_const,
635         staticlib,
636         static_nobundle,
637         static_recursion,
638         std,
639         std_inject,
640         str,
641         stringify,
642         stmt,
643         stmt_expr_attributes,
644         stop_after_dataflow,
645         struct_field_attributes,
646         struct_inherit,
647         structural_match,
648         struct_variant,
649         sty,
650         suggestion,
651         target_feature,
652         target_has_atomic,
653         target_thread_local,
654         task,
655         tbm_target_feature,
656         termination_trait,
657         termination_trait_test,
658         test,
659         test_2018_feature,
660         test_accepted_feature,
661         test_case,
662         test_removed_feature,
663         test_runner,
664         then_with,
665         thread_local,
666         tool_attributes,
667         tool_lints,
668         trace_macros,
669         trait_alias,
670         transmute,
671         transparent,
672         transparent_enums,
673         transparent_unions,
674         trivial_bounds,
675         Try,
676         try_blocks,
677         try_trait,
678         tt,
679         tuple_indexing,
680         Ty,
681         ty,
682         type_alias_impl_trait,
683         TyCtxt,
684         TyKind,
685         type_alias_enum_variants,
686         type_ascription,
687         type_length_limit,
688         type_macros,
689         u128,
690         u16,
691         u32,
692         u64,
693         u8,
694         unboxed_closures,
695         underscore_const_names,
696         underscore_imports,
697         underscore_lifetimes,
698         uniform_paths,
699         uninitialized,
700         universal_impl_trait,
701         unmarked_api,
702         unreachable_code,
703         unrestricted_attribute_tokens,
704         unsafe_no_drop_flag,
705         unsized_locals,
706         unsized_tuple_coercion,
707         unstable,
708         untagged_unions,
709         unwind,
710         unwind_attributes,
711         unwrap_or,
712         used,
713         use_extern_macros,
714         use_nested_groups,
715         usize,
716         v1,
717         val,
718         vec,
719         Vec,
720         vis,
721         visible_private_types,
722         volatile,
723         warn,
724         warn_directory_ownership,
725         wasm_import_module,
726         wasm_target_feature,
727         while_let,
728         windows,
729         windows_subsystem,
730         Yield,
731         zeroed,
732     }
733 }
734
735 #[derive(Copy, Clone, Eq)]
736 pub struct Ident {
737     pub name: Symbol,
738     pub span: Span,
739 }
740
741 impl Ident {
742     #[inline]
743     /// Constructs a new identifier from a symbol and a span.
744     pub const fn new(name: Symbol, span: Span) -> Ident {
745         Ident { name, span }
746     }
747
748     /// Constructs a new identifier with an empty syntax context.
749     #[inline]
750     pub const fn with_empty_ctxt(name: Symbol) -> Ident {
751         Ident::new(name, DUMMY_SP)
752     }
753
754     #[inline]
755     pub fn invalid() -> Ident {
756         Ident::with_empty_ctxt(kw::Invalid)
757     }
758
759     /// Maps an interned string to an identifier with an empty syntax context.
760     pub fn from_interned_str(string: InternedString) -> Ident {
761         Ident::with_empty_ctxt(string.as_symbol())
762     }
763
764     /// Maps a string to an identifier with an empty span.
765     pub fn from_str(string: &str) -> Ident {
766         Ident::with_empty_ctxt(Symbol::intern(string))
767     }
768
769     /// Maps a string and a span to an identifier.
770     pub fn from_str_and_span(string: &str, span: Span) -> Ident {
771         Ident::new(Symbol::intern(string), span)
772     }
773
774     /// Replaces `lo` and `hi` with those from `span`, but keep hygiene context.
775     pub fn with_span_pos(self, span: Span) -> Ident {
776         Ident::new(self.name, span.with_ctxt(self.span.ctxt()))
777     }
778
779     pub fn without_first_quote(self) -> Ident {
780         Ident::new(Symbol::intern(self.as_str().trim_start_matches('\'')), self.span)
781     }
782
783     /// "Normalize" ident for use in comparisons using "item hygiene".
784     /// Identifiers with same string value become same if they came from the same "modern" macro
785     /// (e.g., `macro` item, but not `macro_rules` item) and stay different if they came from
786     /// different "modern" macros.
787     /// Technically, this operation strips all non-opaque marks from ident's syntactic context.
788     pub fn modern(self) -> Ident {
789         Ident::new(self.name, self.span.modern())
790     }
791
792     /// "Normalize" ident for use in comparisons using "local variable hygiene".
793     /// Identifiers with same string value become same if they came from the same non-transparent
794     /// macro (e.g., `macro` or `macro_rules!` items) and stay different if they came from different
795     /// non-transparent macros.
796     /// Technically, this operation strips all transparent marks from ident's syntactic context.
797     pub fn modern_and_legacy(self) -> Ident {
798         Ident::new(self.name, self.span.modern_and_legacy())
799     }
800
801     /// Transforms an identifier into one with the same name, but gensymed.
802     pub fn gensym(self) -> Ident {
803         let name = with_interner(|interner| interner.gensymed(self.name));
804         Ident::new(name, self.span)
805     }
806
807     /// Transforms an underscore identifier into one with the same name, but
808     /// gensymed. Leaves non-underscore identifiers unchanged.
809     pub fn gensym_if_underscore(self) -> Ident {
810         if self.name == kw::Underscore { self.gensym() } else { self }
811     }
812
813     // WARNING: this function is deprecated and will be removed in the future.
814     pub fn is_gensymed(self) -> bool {
815         with_interner(|interner| interner.is_gensymed(self.name))
816     }
817
818     pub fn as_str(self) -> LocalInternedString {
819         self.name.as_str()
820     }
821
822     pub fn as_interned_str(self) -> InternedString {
823         self.name.as_interned_str()
824     }
825 }
826
827 impl PartialEq for Ident {
828     fn eq(&self, rhs: &Self) -> bool {
829         self.name == rhs.name && self.span.ctxt() == rhs.span.ctxt()
830     }
831 }
832
833 impl Hash for Ident {
834     fn hash<H: Hasher>(&self, state: &mut H) {
835         self.name.hash(state);
836         self.span.ctxt().hash(state);
837     }
838 }
839
840 impl fmt::Debug for Ident {
841     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
842         write!(f, "{}{:?}", self.name, self.span.ctxt())
843     }
844 }
845
846 impl fmt::Display for Ident {
847     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
848         fmt::Display::fmt(&self.name, f)
849     }
850 }
851
852 impl Encodable for Ident {
853     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
854         if self.span.ctxt().modern() == SyntaxContext::empty() {
855             s.emit_str(&self.as_str())
856         } else { // FIXME(jseyfried): intercrate hygiene
857             let mut string = "#".to_owned();
858             string.push_str(&self.as_str());
859             s.emit_str(&string)
860         }
861     }
862 }
863
864 impl Decodable for Ident {
865     fn decode<D: Decoder>(d: &mut D) -> Result<Ident, D::Error> {
866         let string = d.read_str()?;
867         Ok(if !string.starts_with('#') {
868             Ident::from_str(&string)
869         } else { // FIXME(jseyfried): intercrate hygiene
870             Ident::from_str(&string[1..]).gensym()
871         })
872     }
873 }
874
875 /// A symbol is an interned or gensymed string. A gensym is a symbol that is
876 /// never equal to any other symbol.
877 ///
878 /// Conceptually, a gensym can be thought of as a normal symbol with an
879 /// invisible unique suffix. Gensyms are useful when creating new identifiers
880 /// that must not match any existing identifiers, e.g. during macro expansion
881 /// and syntax desugaring. Because gensyms should always be identifiers, all
882 /// gensym operations are on `Ident` rather than `Symbol`. (Indeed, in the
883 /// future the gensym-ness may be moved from `Symbol` to hygiene data.)
884 ///
885 /// Examples:
886 /// ```
887 /// assert_eq!(Ident::from_str("x"), Ident::from_str("x"))
888 /// assert_ne!(Ident::from_str("x").gensym(), Ident::from_str("x"))
889 /// assert_ne!(Ident::from_str("x").gensym(), Ident::from_str("x").gensym())
890 /// ```
891 /// Internally, a symbol is implemented as an index, and all operations
892 /// (including hashing, equality, and ordering) operate on that index. The use
893 /// of `newtype_index!` means that `Option<Symbol>` only takes up 4 bytes,
894 /// because `newtype_index!` reserves the last 256 values for tagging purposes.
895 ///
896 /// Note that `Symbol` cannot directly be a `newtype_index!` because it
897 /// implements `fmt::Debug`, `Encodable`, and `Decodable` in special ways.
898 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
899 pub struct Symbol(SymbolIndex);
900
901 newtype_index! {
902     pub struct SymbolIndex { .. }
903 }
904
905 impl Symbol {
906     const fn new(n: u32) -> Self {
907         Symbol(SymbolIndex::from_u32_const(n))
908     }
909
910     /// Maps a string to its interned representation.
911     pub fn intern(string: &str) -> Self {
912         with_interner(|interner| interner.intern(string))
913     }
914
915     pub fn as_str(self) -> LocalInternedString {
916         with_interner(|interner| unsafe {
917             LocalInternedString {
918                 string: std::mem::transmute::<&str, &str>(interner.get(self))
919             }
920         })
921     }
922
923     pub fn as_interned_str(self) -> InternedString {
924         with_interner(|interner| InternedString {
925             symbol: interner.interned(self)
926         })
927     }
928
929     pub fn as_u32(self) -> u32 {
930         self.0.as_u32()
931     }
932 }
933
934 impl fmt::Debug for Symbol {
935     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
936         let is_gensymed = with_interner(|interner| interner.is_gensymed(*self));
937         if is_gensymed {
938             write!(f, "{}({:?})", self, self.0)
939         } else {
940             write!(f, "{}", self)
941         }
942     }
943 }
944
945 impl fmt::Display for Symbol {
946     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
947         fmt::Display::fmt(&self.as_str(), f)
948     }
949 }
950
951 impl Encodable for Symbol {
952     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
953         s.emit_str(&self.as_str())
954     }
955 }
956
957 impl Decodable for Symbol {
958     fn decode<D: Decoder>(d: &mut D) -> Result<Symbol, D::Error> {
959         Ok(Symbol::intern(&d.read_str()?))
960     }
961 }
962
963 // The `&'static str`s in this type actually point into the arena.
964 //
965 // Note that normal symbols are indexed upward from 0, and gensyms are indexed
966 // downward from SymbolIndex::MAX_AS_U32.
967 #[derive(Default)]
968 pub struct Interner {
969     arena: DroplessArena,
970     names: FxHashMap<&'static str, Symbol>,
971     strings: Vec<&'static str>,
972     gensyms: Vec<Symbol>,
973 }
974
975 impl Interner {
976     fn prefill(init: &[&'static str]) -> Self {
977         Interner {
978             strings: init.into(),
979             names: init.iter().copied().zip((0..).map(Symbol::new)).collect(),
980             ..Default::default()
981         }
982     }
983
984     pub fn intern(&mut self, string: &str) -> Symbol {
985         if let Some(&name) = self.names.get(string) {
986             return name;
987         }
988
989         let name = Symbol::new(self.strings.len() as u32);
990
991         // `from_utf8_unchecked` is safe since we just allocated a `&str` which is known to be
992         // UTF-8.
993         let string: &str = unsafe {
994             str::from_utf8_unchecked(self.arena.alloc_slice(string.as_bytes()))
995         };
996         // It is safe to extend the arena allocation to `'static` because we only access
997         // these while the arena is still alive.
998         let string: &'static str =  unsafe {
999             &*(string as *const str)
1000         };
1001         self.strings.push(string);
1002         self.names.insert(string, name);
1003         name
1004     }
1005
1006     fn interned(&self, symbol: Symbol) -> Symbol {
1007         if (symbol.0.as_usize()) < self.strings.len() {
1008             symbol
1009         } else {
1010             self.gensyms[(SymbolIndex::MAX_AS_U32 - symbol.0.as_u32()) as usize]
1011         }
1012     }
1013
1014     fn gensymed(&mut self, symbol: Symbol) -> Symbol {
1015         self.gensyms.push(symbol);
1016         Symbol::new(SymbolIndex::MAX_AS_U32 - self.gensyms.len() as u32 + 1)
1017     }
1018
1019     fn is_gensymed(&mut self, symbol: Symbol) -> bool {
1020         symbol.0.as_usize() >= self.strings.len()
1021     }
1022
1023     // Get the symbol as a string. `Symbol::as_str()` should be used in
1024     // preference to this function.
1025     pub fn get(&self, symbol: Symbol) -> &str {
1026         match self.strings.get(symbol.0.as_usize()) {
1027             Some(string) => string,
1028             None => {
1029                 let symbol = self.gensyms[(SymbolIndex::MAX_AS_U32 - symbol.0.as_u32()) as usize];
1030                 self.strings[symbol.0.as_usize()]
1031             }
1032         }
1033     }
1034 }
1035
1036 // This module has a very short name because it's used a lot.
1037 pub mod kw {
1038     use super::Symbol;
1039     keywords!();
1040 }
1041
1042 // This module has a very short name because it's used a lot.
1043 pub mod sym {
1044     use std::convert::TryInto;
1045     use super::Symbol;
1046
1047     symbols!();
1048
1049     // Get the symbol for an integer. The first few non-negative integers each
1050     // have a static symbol and therefore are fast.
1051     pub fn integer<N: TryInto<usize> + Copy + ToString>(n: N) -> Symbol {
1052         if let Result::Ok(idx) = n.try_into() {
1053             if let Option::Some(&sym) = digits_array.get(idx) {
1054                 return sym;
1055             }
1056         }
1057         Symbol::intern(&n.to_string())
1058     }
1059 }
1060
1061 impl Symbol {
1062     fn is_used_keyword_2018(self) -> bool {
1063         self == kw::Dyn
1064     }
1065
1066     fn is_unused_keyword_2018(self) -> bool {
1067         self >= kw::Async && self <= kw::Try
1068     }
1069
1070     /// Used for sanity checking rustdoc keyword sections.
1071     pub fn is_doc_keyword(self) -> bool {
1072         self <= kw::Union
1073     }
1074
1075     /// A keyword or reserved identifier that can be used as a path segment.
1076     pub fn is_path_segment_keyword(self) -> bool {
1077         self == kw::Super ||
1078         self == kw::SelfLower ||
1079         self == kw::SelfUpper ||
1080         self == kw::Crate ||
1081         self == kw::PathRoot ||
1082         self == kw::DollarCrate
1083     }
1084
1085     /// This symbol can be a raw identifier.
1086     pub fn can_be_raw(self) -> bool {
1087         self != kw::Invalid && self != kw::Underscore && !self.is_path_segment_keyword()
1088     }
1089 }
1090
1091 impl Ident {
1092     // Returns `true` for reserved identifiers used internally for elided lifetimes,
1093     // unnamed method parameters, crate root module, error recovery etc.
1094     pub fn is_special(self) -> bool {
1095         self.name <= kw::Underscore
1096     }
1097
1098     /// Returns `true` if the token is a keyword used in the language.
1099     pub fn is_used_keyword(self) -> bool {
1100         // Note: `span.edition()` is relatively expensive, don't call it unless necessary.
1101         self.name >= kw::As && self.name <= kw::While ||
1102         self.name.is_used_keyword_2018() && self.span.rust_2018()
1103     }
1104
1105     /// Returns `true` if the token is a keyword reserved for possible future use.
1106     pub fn is_unused_keyword(self) -> bool {
1107         // Note: `span.edition()` is relatively expensive, don't call it unless necessary.
1108         self.name >= kw::Abstract && self.name <= kw::Yield ||
1109         self.name.is_unused_keyword_2018() && self.span.rust_2018()
1110     }
1111
1112     /// Returns `true` if the token is either a special identifier or a keyword.
1113     pub fn is_reserved(self) -> bool {
1114         self.is_special() || self.is_used_keyword() || self.is_unused_keyword()
1115     }
1116
1117     /// A keyword or reserved identifier that can be used as a path segment.
1118     pub fn is_path_segment_keyword(self) -> bool {
1119         self.name.is_path_segment_keyword()
1120     }
1121
1122     /// We see this identifier in a normal identifier position, like variable name or a type.
1123     /// How was it written originally? Did it use the raw form? Let's try to guess.
1124     pub fn is_raw_guess(self) -> bool {
1125         self.name.can_be_raw() && self.is_reserved()
1126     }
1127 }
1128
1129 // If an interner exists, return it. Otherwise, prepare a fresh one.
1130 #[inline]
1131 fn with_interner<T, F: FnOnce(&mut Interner) -> T>(f: F) -> T {
1132     GLOBALS.with(|globals| f(&mut *globals.symbol_interner.lock()))
1133 }
1134
1135 /// An alternative to `Symbol` and `InternedString`, useful when the chars
1136 /// within the symbol need to be accessed. It is best used for temporary
1137 /// values.
1138 ///
1139 /// Because the interner outlives any thread which uses this type, we can
1140 /// safely treat `string` which points to interner data, as an immortal string,
1141 /// as long as this type never crosses between threads.
1142 //
1143 // FIXME: ensure that the interner outlives any thread which uses
1144 // `LocalInternedString`, by creating a new thread right after constructing the
1145 // interner.
1146 #[derive(Clone, Copy, Hash, PartialOrd, Eq, Ord)]
1147 pub struct LocalInternedString {
1148     string: &'static str,
1149 }
1150
1151 impl LocalInternedString {
1152     /// Maps a string to its interned representation.
1153     pub fn intern(string: &str) -> Self {
1154         let string = with_interner(|interner| {
1155             let symbol = interner.intern(string);
1156             interner.strings[symbol.0.as_usize()]
1157         });
1158         LocalInternedString {
1159             string: unsafe { std::mem::transmute::<&str, &str>(string) }
1160         }
1161     }
1162
1163     pub fn as_interned_str(self) -> InternedString {
1164         InternedString {
1165             symbol: Symbol::intern(self.string)
1166         }
1167     }
1168
1169     #[inline]
1170     pub fn get(&self) -> &str {
1171         // This returns a valid string since we ensure that `self` outlives the interner
1172         // by creating the interner on a thread which outlives threads which can access it.
1173         // This type cannot move to a thread which outlives the interner since it does
1174         // not implement Send.
1175         self.string
1176     }
1177 }
1178
1179 impl<U: ?Sized> std::convert::AsRef<U> for LocalInternedString
1180 where
1181     str: std::convert::AsRef<U>
1182 {
1183     #[inline]
1184     fn as_ref(&self) -> &U {
1185         self.string.as_ref()
1186     }
1187 }
1188
1189 impl<T: std::ops::Deref<Target = str>> std::cmp::PartialEq<T> for LocalInternedString {
1190     fn eq(&self, other: &T) -> bool {
1191         self.string == other.deref()
1192     }
1193 }
1194
1195 impl std::cmp::PartialEq<LocalInternedString> for str {
1196     fn eq(&self, other: &LocalInternedString) -> bool {
1197         self == other.string
1198     }
1199 }
1200
1201 impl<'a> std::cmp::PartialEq<LocalInternedString> for &'a str {
1202     fn eq(&self, other: &LocalInternedString) -> bool {
1203         *self == other.string
1204     }
1205 }
1206
1207 impl std::cmp::PartialEq<LocalInternedString> for String {
1208     fn eq(&self, other: &LocalInternedString) -> bool {
1209         self == other.string
1210     }
1211 }
1212
1213 impl<'a> std::cmp::PartialEq<LocalInternedString> for &'a String {
1214     fn eq(&self, other: &LocalInternedString) -> bool {
1215         *self == other.string
1216     }
1217 }
1218
1219 impl !Send for LocalInternedString {}
1220 impl !Sync for LocalInternedString {}
1221
1222 impl std::ops::Deref for LocalInternedString {
1223     type Target = str;
1224     #[inline]
1225     fn deref(&self) -> &str { self.string }
1226 }
1227
1228 impl fmt::Debug for LocalInternedString {
1229     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1230         fmt::Debug::fmt(self.string, f)
1231     }
1232 }
1233
1234 impl fmt::Display for LocalInternedString {
1235     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1236         fmt::Display::fmt(self.string, f)
1237     }
1238 }
1239
1240 impl Decodable for LocalInternedString {
1241     fn decode<D: Decoder>(d: &mut D) -> Result<LocalInternedString, D::Error> {
1242         Ok(LocalInternedString::intern(&d.read_str()?))
1243     }
1244 }
1245
1246 impl Encodable for LocalInternedString {
1247     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1248         s.emit_str(self.string)
1249     }
1250 }
1251
1252 /// An alternative to `Symbol` that is focused on string contents. It has two
1253 /// main differences to `Symbol`.
1254 ///
1255 /// First, its implementations of `Hash`, `PartialOrd` and `Ord` work with the
1256 /// string chars rather than the symbol integer. This is useful when hash
1257 /// stability is required across compile sessions, or a guaranteed sort
1258 /// ordering is required.
1259 ///
1260 /// Second, gensym-ness is irrelevant. E.g.:
1261 /// ```
1262 /// assert_ne!(Symbol::gensym("x"), Symbol::gensym("x"))
1263 /// assert_eq!(Symbol::gensym("x").as_interned_str(), Symbol::gensym("x").as_interned_str())
1264 /// ```
1265 #[derive(Clone, Copy, PartialEq, Eq)]
1266 pub struct InternedString {
1267     symbol: Symbol,
1268 }
1269
1270 impl InternedString {
1271     /// Maps a string to its interned representation.
1272     pub fn intern(string: &str) -> Self {
1273         InternedString {
1274             symbol: Symbol::intern(string)
1275         }
1276     }
1277
1278     pub fn with<F: FnOnce(&str) -> R, R>(self, f: F) -> R {
1279         let str = with_interner(|interner| {
1280             interner.get(self.symbol) as *const str
1281         });
1282         // This is safe because the interner keeps string alive until it is dropped.
1283         // We can access it because we know the interner is still alive since we use a
1284         // scoped thread local to access it, and it was alive at the beginning of this scope
1285         unsafe { f(&*str) }
1286     }
1287
1288     fn with2<F: FnOnce(&str, &str) -> R, R>(self, other: &InternedString, f: F) -> R {
1289         let (self_str, other_str) = with_interner(|interner| {
1290             (interner.get(self.symbol) as *const str,
1291              interner.get(other.symbol) as *const str)
1292         });
1293         // This is safe for the same reason that `with` is safe.
1294         unsafe { f(&*self_str, &*other_str) }
1295     }
1296
1297     pub fn as_symbol(self) -> Symbol {
1298         self.symbol
1299     }
1300
1301     pub fn as_str(self) -> LocalInternedString {
1302         self.symbol.as_str()
1303     }
1304 }
1305
1306 impl Hash for InternedString {
1307     fn hash<H: Hasher>(&self, state: &mut H) {
1308         self.with(|str| str.hash(state))
1309     }
1310 }
1311
1312 impl PartialOrd<InternedString> for InternedString {
1313     fn partial_cmp(&self, other: &InternedString) -> Option<Ordering> {
1314         if self.symbol == other.symbol {
1315             return Some(Ordering::Equal);
1316         }
1317         self.with2(other, |self_str, other_str| self_str.partial_cmp(other_str))
1318     }
1319 }
1320
1321 impl Ord for InternedString {
1322     fn cmp(&self, other: &InternedString) -> Ordering {
1323         if self.symbol == other.symbol {
1324             return Ordering::Equal;
1325         }
1326         self.with2(other, |self_str, other_str| self_str.cmp(other_str))
1327     }
1328 }
1329
1330 impl fmt::Debug for InternedString {
1331     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1332         self.with(|str| fmt::Debug::fmt(&str, f))
1333     }
1334 }
1335
1336 impl fmt::Display for InternedString {
1337     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1338         self.with(|str| fmt::Display::fmt(&str, f))
1339     }
1340 }
1341
1342 impl Decodable for InternedString {
1343     fn decode<D: Decoder>(d: &mut D) -> Result<InternedString, D::Error> {
1344         Ok(InternedString::intern(&d.read_str()?))
1345     }
1346 }
1347
1348 impl Encodable for InternedString {
1349     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1350         self.with(|string| s.emit_str(string))
1351     }
1352 }