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.
5 use arena::DroplessArena;
6 use rustc_data_structures::fx::FxHashMap;
7 use rustc_index::vec::Idx;
8 use rustc_macros::symbols;
9 use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
10 use rustc_serialize::{UseSpecializedDecodable, UseSpecializedEncodable};
11 use rustc_data_structures::stable_hasher::{HashStable, ToStableHashKey, StableHasher};
13 use std::cmp::{PartialEq, PartialOrd, Ord};
15 use std::hash::{Hash, Hasher};
18 use crate::{Span, DUMMY_SP, GLOBALS};
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.
27 // Special reserved identifiers used internally for elided lifetimes,
28 // unnamed method parameters, crate root module, error recovery etc.
31 DollarCrate: "$crate",
34 // Keywords that are used in stable Rust.
71 // Keywords that are used in unstable Rust or reserved for future use.
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
90 // Edition-specific keywords that are used in unstable Rust or reserved for future use.
91 Try: "try", // >= 2018 Edition only
93 // Special lifetime names
94 UnderscoreLifetime: "'_",
95 StaticLifetime: "'static",
97 // Weak keywords, have special meaning only in specific contexts.
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").
108 // As well as the symbols listed, there are symbols for the the strings
109 // "0", "1", ..., "9", which are accessible via `sym::integer`.
111 aarch64_target_feature,
115 abi_msp430_interrupt,
123 advanced_slice_patterns,
135 allow_internal_unsafe,
136 allow_internal_unstable,
137 allow_internal_unstable_backcompat_hack,
141 arbitrary_enum_discriminant,
142 arbitrary_self_types,
149 associated_type_bounds,
150 associated_type_defaults,
158 augmented_assignments,
159 automatically_derived,
160 avx512_target_feature,
165 bind_by_move_pattern_guards,
168 borrowck_graphviz_postflow,
169 borrowck_graphviz_preflow,
172 braced_empty_structs,
180 cfg_target_has_atomic,
181 cfg_target_thread_local,
189 closure_to_fn_coercion,
191 cmpxchg16b_target_feature,
198 conservative_impl_trait,
200 const_compare_raw_pointers,
208 const_in_array_repeat_expressions,
212 const_raw_ptr_to_usize_cast,
226 crate_visibility_modifier,
229 custom_inner_attributes,
230 custom_test_frameworks,
238 default_lib_allocator,
239 default_type_parameter_fallback,
241 delay_span_bug_from_inside_query,
256 document_private_items,
257 dotdoteq_in_patterns,
258 dotdot_in_tuple_patterns,
259 double_braced_crate: "{{crate}}",
260 double_braced_impl: "{{impl}}",
261 double_braced_misc: "{{misc}}",
262 double_braced_closure: "{{closure}}",
263 double_braced_constructor: "{{constructor}}",
264 double_braced_constant: "{{constant}}",
265 double_braced_opaque: "{{opaque}}",
267 dropck_parametricity,
282 exclusive_range_pattern,
283 exhaustive_integer_patterns,
289 extern_absolute_paths,
291 extern_crate_item_prelude,
302 field_init_shorthand,
325 generic_associated_types,
334 hexagon_target_feature,
336 homogeneous_aggregate,
350 if_while_or_patterns,
352 impl_header_lifetime_elision,
354 impl_trait_in_bindings,
362 inclusive_range_syntax,
363 infer_outlives_requirements,
364 infer_static_outlives_requirements,
371 irrefutable_let_patterns,
374 issue_5723_bootstrap,
375 issue_tracker_base_url,
377 item_context: "ItemContext",
396 link_llvm_intrinsics,
406 macro_at_most_once_rep,
409 macro_lifetime_matcher,
410 macro_literal_matcher,
421 match_beginning_vert,
422 match_default_bindings,
439 movbe_target_feature,
473 object_safe_for_dispatch,
475 omit_gdb_pretty_printer_section,
482 optin_builtin_traits,
492 overlapping_marker_traits,
497 panic_implementation,
517 poll_with_tls_context,
518 powerpc_target_feature,
519 precise_pointer_size_matching,
523 proc_dash_macro: "proc-macro",
525 proc_macro_attribute,
531 proc_macro_internals,
533 proc_macro_non_items,
534 proc_macro_path_invoc,
538 quad_precision_float,
552 reexport_test_harness_main,
564 re_rebalance_coherence,
580 rustc_allocator_nounwind,
581 rustc_allow_const_fn_ptr,
582 rustc_args_required_const,
586 rustc_const_unstable,
587 rustc_conversion_suggestion,
590 rustc_diagnostic_item,
591 rustc_diagnostic_macros,
594 rustc_dump_env_program_clauses,
595 rustc_dump_program_clauses,
596 rustc_dump_user_substs,
598 rustc_expected_cgu_reuse,
599 rustc_if_this_changed,
600 rustc_inherit_overflow_checks,
602 rustc_layout_scalar_valid_range_end,
603 rustc_layout_scalar_valid_range_start,
604 rustc_macro_transparency,
606 rustc_nonnull_optimization_guaranteed,
607 rustc_object_lifetime_default,
608 rustc_on_unimplemented,
611 rustc_partition_codegened,
612 rustc_partition_reused,
614 rustc_peek_definite_init,
615 rustc_peek_maybe_init,
616 rustc_peek_maybe_uninit,
617 rustc_peek_indirectly_mutable,
619 rustc_proc_macro_decls,
623 rustc_std_internal_symbol,
626 rustc_reservation_impl,
628 rustc_then_this_would_need,
633 rust_eh_unwind_resume,
635 rvalue_static_promotion,
652 sse4a_target_feature,
665 stmt_expr_attributes,
667 struct_field_attributes,
675 target_has_atomic_load_store,
680 termination_trait_test,
683 test_accepted_feature,
685 test_removed_feature,
706 type_alias_impl_trait,
709 type_alias_enum_variants,
719 underscore_const_names,
721 underscore_lifetimes,
723 universal_impl_trait,
726 unrestricted_attribute_tokens,
729 unsized_tuple_coercion,
744 visible_private_types,
756 #[derive(Copy, Clone, Eq)]
764 /// Constructs a new identifier from a symbol and a span.
765 pub const fn new(name: Symbol, span: Span) -> Ident {
769 /// Constructs a new identifier with a dummy span.
771 pub const fn with_dummy_span(name: Symbol) -> Ident {
772 Ident::new(name, DUMMY_SP)
776 pub fn invalid() -> Ident {
777 Ident::with_dummy_span(kw::Invalid)
780 /// Maps a string to an identifier with a dummy span.
781 pub fn from_str(string: &str) -> Ident {
782 Ident::with_dummy_span(Symbol::intern(string))
785 /// Maps a string and a span to an identifier.
786 pub fn from_str_and_span(string: &str, span: Span) -> Ident {
787 Ident::new(Symbol::intern(string), span)
790 /// Replaces `lo` and `hi` with those from `span`, but keep hygiene context.
791 pub fn with_span_pos(self, span: Span) -> Ident {
792 Ident::new(self.name, span.with_ctxt(self.span.ctxt()))
795 pub fn without_first_quote(self) -> Ident {
796 Ident::new(Symbol::intern(self.as_str().trim_start_matches('\'')), self.span)
799 /// "Normalize" ident for use in comparisons using "item hygiene".
800 /// Identifiers with same string value become same if they came from the same "modern" macro
801 /// (e.g., `macro` item, but not `macro_rules` item) and stay different if they came from
802 /// different "modern" macros.
803 /// Technically, this operation strips all non-opaque marks from ident's syntactic context.
804 pub fn modern(self) -> Ident {
805 Ident::new(self.name, self.span.modern())
808 /// "Normalize" ident for use in comparisons using "local variable hygiene".
809 /// Identifiers with same string value become same if they came from the same non-transparent
810 /// macro (e.g., `macro` or `macro_rules!` items) and stay different if they came from different
811 /// non-transparent macros.
812 /// Technically, this operation strips all transparent marks from ident's syntactic context.
813 pub fn modern_and_legacy(self) -> Ident {
814 Ident::new(self.name, self.span.modern_and_legacy())
817 /// Convert the name to a `SymbolStr`. This is a slowish operation because
818 /// it requires locking the symbol interner.
819 pub fn as_str(self) -> SymbolStr {
824 impl PartialEq for Ident {
825 fn eq(&self, rhs: &Self) -> bool {
826 self.name == rhs.name && self.span.ctxt() == rhs.span.ctxt()
830 impl Hash for Ident {
831 fn hash<H: Hasher>(&self, state: &mut H) {
832 self.name.hash(state);
833 self.span.ctxt().hash(state);
837 impl fmt::Debug for Ident {
838 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
839 write!(f, "{}{:?}", self.name, self.span.ctxt())
843 impl fmt::Display for Ident {
844 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
845 fmt::Display::fmt(&self.name, f)
849 impl UseSpecializedEncodable for Ident {
850 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
851 s.emit_struct("Ident", 2, |s| {
852 s.emit_struct_field("name", 0, |s| {
855 s.emit_struct_field("span", 1, |s| {
862 impl UseSpecializedDecodable for Ident {
863 fn default_decode<D: Decoder>(d: &mut D) -> Result<Self, D::Error> {
864 d.read_struct("Ident", 2, |d| {
866 name: d.read_struct_field("name", 0, Decodable::decode)?,
867 span: d.read_struct_field("span", 1, Decodable::decode)?,
873 /// An interned string.
875 /// Internally, a `Symbol` is implemented as an index, and all operations
876 /// (including hashing, equality, and ordering) operate on that index. The use
877 /// of `rustc_index::newtype_index!` means that `Option<Symbol>` only takes up 4 bytes,
878 /// because `rustc_index::newtype_index!` reserves the last 256 values for tagging purposes.
880 /// Note that `Symbol` cannot directly be a `rustc_index::newtype_index!` because it
881 /// implements `fmt::Debug`, `Encodable`, and `Decodable` in special ways.
882 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
883 pub struct Symbol(SymbolIndex);
885 rustc_index::newtype_index! {
886 pub struct SymbolIndex { .. }
890 const fn new(n: u32) -> Self {
891 Symbol(SymbolIndex::from_u32_const(n))
894 /// Maps a string to its interned representation.
895 pub fn intern(string: &str) -> Self {
896 with_interner(|interner| interner.intern(string))
899 /// Access the symbol's chars. This is a slowish operation because it
900 /// requires locking the symbol interner.
901 pub fn with<F: FnOnce(&str) -> R, R>(self, f: F) -> R {
902 with_interner(|interner| {
903 f(interner.get(self))
907 /// Convert to a `SymbolStr`. This is a slowish operation because it
908 /// requires locking the symbol interner.
909 pub fn as_str(self) -> SymbolStr {
910 with_interner(|interner| unsafe {
912 string: std::mem::transmute::<&str, &str>(interner.get(self))
917 pub fn as_u32(self) -> u32 {
922 impl fmt::Debug for Symbol {
923 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
924 self.with(|str| fmt::Debug::fmt(&str, f))
928 impl fmt::Display for Symbol {
929 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
930 self.with(|str| fmt::Display::fmt(&str, f))
934 impl Encodable for Symbol {
935 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
936 self.with(|string| s.emit_str(string))
940 impl Decodable for Symbol {
941 fn decode<D: Decoder>(d: &mut D) -> Result<Symbol, D::Error> {
942 Ok(Symbol::intern(&d.read_str()?))
946 impl<CTX> HashStable<CTX> for Symbol {
948 fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
949 self.as_str().hash_stable(hcx, hasher);
953 impl<CTX> ToStableHashKey<CTX> for Symbol {
954 type KeyType = SymbolStr;
957 fn to_stable_hash_key(&self, _: &CTX) -> SymbolStr {
962 // The `&'static str`s in this type actually point into the arena.
964 pub struct Interner {
965 arena: DroplessArena,
966 names: FxHashMap<&'static str, Symbol>,
967 strings: Vec<&'static str>,
971 fn prefill(init: &[&'static str]) -> Self {
973 strings: init.into(),
974 names: init.iter().copied().zip((0..).map(Symbol::new)).collect(),
979 pub fn intern(&mut self, string: &str) -> Symbol {
980 if let Some(&name) = self.names.get(string) {
984 let name = Symbol::new(self.strings.len() as u32);
986 // `from_utf8_unchecked` is safe since we just allocated a `&str` which is known to be
988 let string: &str = unsafe {
989 str::from_utf8_unchecked(self.arena.alloc_slice(string.as_bytes()))
991 // It is safe to extend the arena allocation to `'static` because we only access
992 // these while the arena is still alive.
993 let string: &'static str = unsafe {
994 &*(string as *const str)
996 self.strings.push(string);
997 self.names.insert(string, name);
1001 // Get the symbol as a string. `Symbol::as_str()` should be used in
1002 // preference to this function.
1003 pub fn get(&self, symbol: Symbol) -> &str {
1004 self.strings[symbol.0.as_usize()]
1008 // This module has a very short name because it's used a lot.
1014 // This module has a very short name because it's used a lot.
1016 use std::convert::TryInto;
1021 // Get the symbol for an integer. The first few non-negative integers each
1022 // have a static symbol and therefore are fast.
1023 pub fn integer<N: TryInto<usize> + Copy + ToString>(n: N) -> Symbol {
1024 if let Result::Ok(idx) = n.try_into() {
1025 if let Option::Some(&sym) = digits_array.get(idx) {
1029 Symbol::intern(&n.to_string())
1034 fn is_used_keyword_2018(self) -> bool {
1035 self >= kw::Async && self <= kw::Dyn
1038 fn is_unused_keyword_2018(self) -> bool {
1042 /// Used for sanity checking rustdoc keyword sections.
1043 pub fn is_doc_keyword(self) -> bool {
1047 /// A keyword or reserved identifier that can be used as a path segment.
1048 pub fn is_path_segment_keyword(self) -> bool {
1049 self == kw::Super ||
1050 self == kw::SelfLower ||
1051 self == kw::SelfUpper ||
1052 self == kw::Crate ||
1053 self == kw::PathRoot ||
1054 self == kw::DollarCrate
1057 /// Returns `true` if the symbol is `true` or `false`.
1058 pub fn is_bool_lit(self) -> bool {
1059 self == kw::True || self == kw::False
1062 /// This symbol can be a raw identifier.
1063 pub fn can_be_raw(self) -> bool {
1064 self != kw::Invalid && self != kw::Underscore && !self.is_path_segment_keyword()
1069 // Returns `true` for reserved identifiers used internally for elided lifetimes,
1070 // unnamed method parameters, crate root module, error recovery etc.
1071 pub fn is_special(self) -> bool {
1072 self.name <= kw::Underscore
1075 /// Returns `true` if the token is a keyword used in the language.
1076 pub fn is_used_keyword(self) -> bool {
1077 // Note: `span.edition()` is relatively expensive, don't call it unless necessary.
1078 self.name >= kw::As && self.name <= kw::While ||
1079 self.name.is_used_keyword_2018() && self.span.rust_2018()
1082 /// Returns `true` if the token is a keyword reserved for possible future use.
1083 pub fn is_unused_keyword(self) -> bool {
1084 // Note: `span.edition()` is relatively expensive, don't call it unless necessary.
1085 self.name >= kw::Abstract && self.name <= kw::Yield ||
1086 self.name.is_unused_keyword_2018() && self.span.rust_2018()
1089 /// Returns `true` if the token is either a special identifier or a keyword.
1090 pub fn is_reserved(self) -> bool {
1091 self.is_special() || self.is_used_keyword() || self.is_unused_keyword()
1094 /// A keyword or reserved identifier that can be used as a path segment.
1095 pub fn is_path_segment_keyword(self) -> bool {
1096 self.name.is_path_segment_keyword()
1099 /// We see this identifier in a normal identifier position, like variable name or a type.
1100 /// How was it written originally? Did it use the raw form? Let's try to guess.
1101 pub fn is_raw_guess(self) -> bool {
1102 self.name.can_be_raw() && self.is_reserved()
1107 fn with_interner<T, F: FnOnce(&mut Interner) -> T>(f: F) -> T {
1108 GLOBALS.with(|globals| f(&mut *globals.symbol_interner.lock()))
1111 /// An alternative to `Symbol`, useful when the chars within the symbol need to
1112 /// be accessed. It deliberately has limited functionality and should only be
1113 /// used for temporary values.
1115 /// Because the interner outlives any thread which uses this type, we can
1116 /// safely treat `string` which points to interner data, as an immortal string,
1117 /// as long as this type never crosses between threads.
1119 // FIXME: ensure that the interner outlives any thread which uses `SymbolStr`,
1120 // by creating a new thread right after constructing the interner.
1121 #[derive(Clone, Eq, PartialOrd, Ord)]
1122 pub struct SymbolStr {
1123 string: &'static str,
1126 // This impl allows a `SymbolStr` to be directly equated with a `String` or
1128 impl<T: std::ops::Deref<Target = str>> std::cmp::PartialEq<T> for SymbolStr {
1129 fn eq(&self, other: &T) -> bool {
1130 self.string == other.deref()
1134 impl !Send for SymbolStr {}
1135 impl !Sync for SymbolStr {}
1137 /// This impl means that if `ss` is a `SymbolStr`:
1138 /// - `*ss` is a `str`;
1139 /// - `&*ss` is a `&str`;
1140 /// - `&ss as &str` is a `&str`, which means that `&ss` can be passed to a
1141 /// function expecting a `&str`.
1142 impl std::ops::Deref for SymbolStr {
1145 fn deref(&self) -> &str { self.string }
1148 impl fmt::Debug for SymbolStr {
1149 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1150 fmt::Debug::fmt(self.string, f)
1154 impl fmt::Display for SymbolStr {
1155 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1156 fmt::Display::fmt(self.string, f)
1160 impl<CTX> HashStable<CTX> for SymbolStr {
1162 fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
1163 self.string.hash_stable(hcx, hasher)
1167 impl<CTX> ToStableHashKey<CTX> for SymbolStr {
1168 type KeyType = SymbolStr;
1171 fn to_stable_hash_key(&self, _: &CTX) -> SymbolStr {