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};
12 use std::cmp::{PartialEq, PartialOrd, Ord};
14 use std::hash::{Hash, Hasher};
17 use crate::{Span, DUMMY_SP, GLOBALS};
23 // After modifying this list adjust `is_special`, `is_used_keyword`/`is_unused_keyword`,
24 // this should be rarely necessary though if the keywords are kept in alphabetic order.
26 // Special reserved identifiers used internally for elided lifetimes,
27 // unnamed method parameters, crate root module, error recovery etc.
30 DollarCrate: "$crate",
33 // Keywords that are used in stable Rust.
70 // Keywords that are used in unstable Rust or reserved for future use.
84 // Edition-specific keywords that are used in stable Rust.
85 Async: "async", // >= 2018 Edition only
86 Await: "await", // >= 2018 Edition only
87 Dyn: "dyn", // >= 2018 Edition only
89 // Edition-specific keywords that are used in unstable Rust or reserved for future use.
90 Try: "try", // >= 2018 Edition only
92 // Special lifetime names
93 UnderscoreLifetime: "'_",
94 StaticLifetime: "'static",
96 // Weak keywords, have special meaning only in specific contexts.
103 // Symbols that can be referred to with syntax_pos::sym::*. The symbol is
104 // the stringified identifier unless otherwise specified (e.g.
105 // `proc_dash_macro` represents "proc-macro").
107 // As well as the symbols listed, there are symbols for the the strings
108 // "0", "1", ..., "9", which are accessible via `sym::integer`.
110 aarch64_target_feature,
113 abi_msp430_interrupt,
121 advanced_slice_patterns,
133 allow_internal_unsafe,
134 allow_internal_unstable,
135 allow_internal_unstable_backcompat_hack,
139 arbitrary_enum_discriminant,
140 arbitrary_self_types,
147 associated_type_bounds,
148 associated_type_defaults,
155 augmented_assignments,
156 automatically_derived,
157 avx512_target_feature,
162 bind_by_move_pattern_guards,
165 borrowck_graphviz_postflow,
166 borrowck_graphviz_preflow,
169 braced_empty_structs,
177 cfg_target_has_atomic,
178 cfg_target_thread_local,
186 closure_to_fn_coercion,
188 cmpxchg16b_target_feature,
195 conservative_impl_trait,
197 const_compare_raw_pointers,
204 const_in_array_repeat_expressions,
208 const_raw_ptr_to_usize_cast,
222 crate_visibility_modifier,
225 custom_inner_attributes,
226 custom_test_frameworks,
234 default_lib_allocator,
235 default_type_parameter_fallback,
251 document_private_items,
252 dotdoteq_in_patterns,
253 dotdot_in_tuple_patterns,
254 double_braced_crate: "{{crate}}",
255 double_braced_impl: "{{impl}}",
256 double_braced_misc: "{{misc}}",
257 double_braced_closure: "{{closure}}",
258 double_braced_constructor: "{{constructor}}",
259 double_braced_constant: "{{constant}}",
260 double_braced_opaque: "{{opaque}}",
262 dropck_parametricity,
277 exclusive_range_pattern,
278 exhaustive_integer_patterns,
284 extern_absolute_paths,
286 extern_crate_item_prelude,
297 field_init_shorthand,
320 generic_associated_types,
329 hexagon_target_feature,
331 homogeneous_aggregate,
345 if_while_or_patterns,
347 impl_header_lifetime_elision,
349 impl_trait_in_bindings,
357 inclusive_range_syntax,
358 infer_outlives_requirements,
359 infer_static_outlives_requirements,
366 irrefutable_let_patterns,
369 issue_5723_bootstrap,
370 issue_tracker_base_url,
390 link_llvm_intrinsics,
400 macro_at_most_once_rep,
403 macro_lifetime_matcher,
404 macro_literal_matcher,
415 match_beginning_vert,
416 match_default_bindings,
429 movbe_target_feature,
462 object_safe_for_dispatch,
464 omit_gdb_pretty_printer_section,
471 optin_builtin_traits,
481 overlapping_marker_traits,
486 panic_implementation,
506 poll_with_tls_context,
507 powerpc_target_feature,
508 precise_pointer_size_matching,
512 proc_dash_macro: "proc-macro",
514 proc_macro_attribute,
520 proc_macro_internals,
522 proc_macro_non_items,
523 proc_macro_path_invoc,
527 quad_precision_float,
541 reexport_test_harness_main,
551 re_rebalance_coherence,
567 rustc_allocator_nounwind,
568 rustc_allow_const_fn_ptr,
569 rustc_args_required_const,
573 rustc_const_unstable,
574 rustc_conversion_suggestion,
577 rustc_diagnostic_item,
578 rustc_diagnostic_macros,
581 rustc_dump_env_program_clauses,
582 rustc_dump_program_clauses,
583 rustc_dump_user_substs,
585 rustc_expected_cgu_reuse,
586 rustc_if_this_changed,
587 rustc_inherit_overflow_checks,
589 rustc_layout_scalar_valid_range_end,
590 rustc_layout_scalar_valid_range_start,
591 rustc_macro_transparency,
593 rustc_nonnull_optimization_guaranteed,
594 rustc_object_lifetime_default,
595 rustc_on_unimplemented,
598 rustc_partition_codegened,
599 rustc_partition_reused,
601 rustc_peek_definite_init,
602 rustc_peek_maybe_init,
603 rustc_peek_maybe_uninit,
604 rustc_peek_indirectly_mutable,
606 rustc_proc_macro_decls,
610 rustc_std_internal_symbol,
613 rustc_reservation_impl,
615 rustc_then_this_would_need,
620 rust_eh_unwind_resume,
622 rvalue_static_promotion,
639 sse4a_target_feature,
652 stmt_expr_attributes,
654 struct_field_attributes,
662 target_has_atomic_load_store,
667 termination_trait_test,
670 test_accepted_feature,
672 test_removed_feature,
693 type_alias_impl_trait,
696 type_alias_enum_variants,
706 underscore_const_names,
708 underscore_lifetimes,
711 universal_impl_trait,
714 unrestricted_attribute_tokens,
717 unsized_tuple_coercion,
732 visible_private_types,
735 warn_directory_ownership,
746 #[derive(Copy, Clone, Eq)]
754 /// Constructs a new identifier from a symbol and a span.
755 pub const fn new(name: Symbol, span: Span) -> Ident {
759 /// Constructs a new identifier with a dummy span.
761 pub const fn with_dummy_span(name: Symbol) -> Ident {
762 Ident::new(name, DUMMY_SP)
766 pub fn invalid() -> Ident {
767 Ident::with_dummy_span(kw::Invalid)
770 /// Maps a string to an identifier with a dummy span.
771 pub fn from_str(string: &str) -> Ident {
772 Ident::with_dummy_span(Symbol::intern(string))
775 /// Maps a string and a span to an identifier.
776 pub fn from_str_and_span(string: &str, span: Span) -> Ident {
777 Ident::new(Symbol::intern(string), span)
780 /// Replaces `lo` and `hi` with those from `span`, but keep hygiene context.
781 pub fn with_span_pos(self, span: Span) -> Ident {
782 Ident::new(self.name, span.with_ctxt(self.span.ctxt()))
785 pub fn without_first_quote(self) -> Ident {
786 Ident::new(Symbol::intern(self.as_str().trim_start_matches('\'')), self.span)
789 /// "Normalize" ident for use in comparisons using "item hygiene".
790 /// Identifiers with same string value become same if they came from the same "modern" macro
791 /// (e.g., `macro` item, but not `macro_rules` item) and stay different if they came from
792 /// different "modern" macros.
793 /// Technically, this operation strips all non-opaque marks from ident's syntactic context.
794 pub fn modern(self) -> Ident {
795 Ident::new(self.name, self.span.modern())
798 /// "Normalize" ident for use in comparisons using "local variable hygiene".
799 /// Identifiers with same string value become same if they came from the same non-transparent
800 /// macro (e.g., `macro` or `macro_rules!` items) and stay different if they came from different
801 /// non-transparent macros.
802 /// Technically, this operation strips all transparent marks from ident's syntactic context.
803 pub fn modern_and_legacy(self) -> Ident {
804 Ident::new(self.name, self.span.modern_and_legacy())
807 /// Convert the name to a `LocalInternedString`. This is a slowish
808 /// operation because it requires locking the symbol interner.
809 pub fn as_str(self) -> LocalInternedString {
814 impl PartialEq for Ident {
815 fn eq(&self, rhs: &Self) -> bool {
816 self.name == rhs.name && self.span.ctxt() == rhs.span.ctxt()
820 impl Hash for Ident {
821 fn hash<H: Hasher>(&self, state: &mut H) {
822 self.name.hash(state);
823 self.span.ctxt().hash(state);
827 impl fmt::Debug for Ident {
828 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
829 write!(f, "{}{:?}", self.name, self.span.ctxt())
833 impl fmt::Display for Ident {
834 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
835 fmt::Display::fmt(&self.name, f)
839 impl UseSpecializedEncodable for Ident {
840 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
841 s.emit_struct("Ident", 2, |s| {
842 s.emit_struct_field("name", 0, |s| {
845 s.emit_struct_field("span", 1, |s| {
852 impl UseSpecializedDecodable for Ident {
853 fn default_decode<D: Decoder>(d: &mut D) -> Result<Self, D::Error> {
854 d.read_struct("Ident", 2, |d| {
856 name: d.read_struct_field("name", 0, Decodable::decode)?,
857 span: d.read_struct_field("span", 1, Decodable::decode)?,
863 /// An interned string.
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 `rustc_index::newtype_index!` means that `Option<Symbol>` only takes up 4 bytes,
868 /// because `rustc_index::newtype_index!` reserves the last 256 values for tagging purposes.
870 /// Note that `Symbol` cannot directly be a `rustc_index::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);
875 rustc_index::newtype_index! {
876 pub struct SymbolIndex { .. }
880 const fn new(n: u32) -> Self {
881 Symbol(SymbolIndex::from_u32_const(n))
884 /// Maps a string to its interned representation.
885 pub fn intern(string: &str) -> Self {
886 with_interner(|interner| interner.intern(string))
889 /// Access the symbol's chars. This is a slowish operation because it
890 /// requires locking the symbol interner.
891 pub fn with<F: FnOnce(&str) -> R, R>(self, f: F) -> R {
892 with_interner(|interner| {
893 f(interner.get(self))
897 /// Convert to a `LocalInternedString`. This is a slowish operation because
898 /// it requires locking the symbol interner.
899 pub fn as_str(self) -> LocalInternedString {
900 with_interner(|interner| unsafe {
901 LocalInternedString {
902 string: std::mem::transmute::<&str, &str>(interner.get(self))
907 pub fn as_u32(self) -> u32 {
912 impl fmt::Debug for Symbol {
913 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
914 self.with(|str| fmt::Debug::fmt(&str, f))
918 impl fmt::Display for Symbol {
919 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
920 self.with(|str| fmt::Display::fmt(&str, f))
924 impl Encodable for Symbol {
925 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
926 self.with(|string| s.emit_str(string))
930 impl Decodable for Symbol {
931 fn decode<D: Decoder>(d: &mut D) -> Result<Symbol, D::Error> {
932 Ok(Symbol::intern(&d.read_str()?))
936 // The `&'static str`s in this type actually point into the arena.
938 pub struct Interner {
939 arena: DroplessArena,
940 names: FxHashMap<&'static str, Symbol>,
941 strings: Vec<&'static str>,
945 fn prefill(init: &[&'static str]) -> Self {
947 strings: init.into(),
948 names: init.iter().copied().zip((0..).map(Symbol::new)).collect(),
953 pub fn intern(&mut self, string: &str) -> Symbol {
954 if let Some(&name) = self.names.get(string) {
958 let name = Symbol::new(self.strings.len() as u32);
960 // `from_utf8_unchecked` is safe since we just allocated a `&str` which is known to be
962 let string: &str = unsafe {
963 str::from_utf8_unchecked(self.arena.alloc_slice(string.as_bytes()))
965 // It is safe to extend the arena allocation to `'static` because we only access
966 // these while the arena is still alive.
967 let string: &'static str = unsafe {
968 &*(string as *const str)
970 self.strings.push(string);
971 self.names.insert(string, name);
974 // Get the symbol as a string. `Symbol::as_str()` should be used in
975 // preference to this function.
976 pub fn get(&self, symbol: Symbol) -> &str {
977 self.strings[symbol.0.as_usize()]
981 // This module has a very short name because it's used a lot.
987 // This module has a very short name because it's used a lot.
989 use std::convert::TryInto;
994 // Get the symbol for an integer. The first few non-negative integers each
995 // have a static symbol and therefore are fast.
996 pub fn integer<N: TryInto<usize> + Copy + ToString>(n: N) -> Symbol {
997 if let Result::Ok(idx) = n.try_into() {
998 if let Option::Some(&sym) = digits_array.get(idx) {
1002 Symbol::intern(&n.to_string())
1007 fn is_used_keyword_2018(self) -> bool {
1008 self >= kw::Async && self <= kw::Dyn
1011 fn is_unused_keyword_2018(self) -> bool {
1015 /// Used for sanity checking rustdoc keyword sections.
1016 pub fn is_doc_keyword(self) -> bool {
1020 /// A keyword or reserved identifier that can be used as a path segment.
1021 pub fn is_path_segment_keyword(self) -> bool {
1022 self == kw::Super ||
1023 self == kw::SelfLower ||
1024 self == kw::SelfUpper ||
1025 self == kw::Crate ||
1026 self == kw::PathRoot ||
1027 self == kw::DollarCrate
1030 /// Returns `true` if the symbol is `true` or `false`.
1031 pub fn is_bool_lit(self) -> bool {
1032 self == kw::True || self == kw::False
1035 /// This symbol can be a raw identifier.
1036 pub fn can_be_raw(self) -> bool {
1037 self != kw::Invalid && self != kw::Underscore && !self.is_path_segment_keyword()
1042 // Returns `true` for reserved identifiers used internally for elided lifetimes,
1043 // unnamed method parameters, crate root module, error recovery etc.
1044 pub fn is_special(self) -> bool {
1045 self.name <= kw::Underscore
1048 /// Returns `true` if the token is a keyword used in the language.
1049 pub fn is_used_keyword(self) -> bool {
1050 // Note: `span.edition()` is relatively expensive, don't call it unless necessary.
1051 self.name >= kw::As && self.name <= kw::While ||
1052 self.name.is_used_keyword_2018() && self.span.rust_2018()
1055 /// Returns `true` if the token is a keyword reserved for possible future use.
1056 pub fn is_unused_keyword(self) -> bool {
1057 // Note: `span.edition()` is relatively expensive, don't call it unless necessary.
1058 self.name >= kw::Abstract && self.name <= kw::Yield ||
1059 self.name.is_unused_keyword_2018() && self.span.rust_2018()
1062 /// Returns `true` if the token is either a special identifier or a keyword.
1063 pub fn is_reserved(self) -> bool {
1064 self.is_special() || self.is_used_keyword() || self.is_unused_keyword()
1067 /// A keyword or reserved identifier that can be used as a path segment.
1068 pub fn is_path_segment_keyword(self) -> bool {
1069 self.name.is_path_segment_keyword()
1072 /// We see this identifier in a normal identifier position, like variable name or a type.
1073 /// How was it written originally? Did it use the raw form? Let's try to guess.
1074 pub fn is_raw_guess(self) -> bool {
1075 self.name.can_be_raw() && self.is_reserved()
1079 // If an interner exists, return it. Otherwise, prepare a fresh one.
1081 fn with_interner<T, F: FnOnce(&mut Interner) -> T>(f: F) -> T {
1082 GLOBALS.with(|globals| f(&mut *globals.symbol_interner.lock()))
1085 /// An alternative to `Symbol`, useful when the chars within the symbol need to
1086 /// be accessed. It deliberately has limited functionality and should only be
1087 /// used for temporary values.
1089 /// Because the interner outlives any thread which uses this type, we can
1090 /// safely treat `string` which points to interner data, as an immortal string,
1091 /// as long as this type never crosses between threads.
1093 // FIXME: ensure that the interner outlives any thread which uses
1094 // `LocalInternedString`, by creating a new thread right after constructing the
1096 #[derive(Clone, Eq, PartialOrd, Ord)]
1097 pub struct LocalInternedString {
1098 string: &'static str,
1101 impl<U: ?Sized> std::convert::AsRef<U> for LocalInternedString
1103 str: std::convert::AsRef<U>
1106 fn as_ref(&self) -> &U {
1107 self.string.as_ref()
1111 impl<T: std::ops::Deref<Target = str>> std::cmp::PartialEq<T> for LocalInternedString {
1112 fn eq(&self, other: &T) -> bool {
1113 self.string == other.deref()
1117 impl !Send for LocalInternedString {}
1118 impl !Sync for LocalInternedString {}
1120 impl std::ops::Deref for LocalInternedString {
1123 fn deref(&self) -> &str { self.string }
1126 impl fmt::Debug for LocalInternedString {
1127 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1128 fmt::Debug::fmt(self.string, f)
1132 impl fmt::Display for LocalInternedString {
1133 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1134 fmt::Display::fmt(self.string, f)