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 rustc_arena::DroplessArena;
6 use rustc_data_structures::fx::FxHashMap;
7 use rustc_data_structures::stable_hasher::{HashStable, StableHasher, ToStableHashKey};
8 use rustc_macros::{symbols, HashStable_Generic};
9 use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
10 use rustc_serialize::{UseSpecializedDecodable, UseSpecializedEncodable};
12 use std::cmp::{Ord, PartialEq, PartialOrd};
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.
100 MacroRules: "macro_rules",
105 // Symbols that can be referred to with rustc_span::sym::*. The symbol is
106 // the stringified identifier unless otherwise specified (e.g.
107 // `proc_dash_macro` represents "proc-macro").
109 // As well as the symbols listed, there are symbols for the the strings
110 // "0", "1", ..., "9", which are accessible via `sym::integer`.
112 aarch64_target_feature,
116 abi_msp430_interrupt,
128 advanced_slice_patterns,
140 allow_internal_unsafe,
141 allow_internal_unstable,
142 allow_internal_unstable_backcompat_hack,
146 arbitrary_enum_discriminant,
147 arbitrary_self_types,
156 associated_type_bounds,
157 associated_type_defaults,
166 augmented_assignments,
167 automatically_derived,
168 avx512_target_feature,
173 bind_by_move_pattern_guards,
177 borrowck_graphviz_format,
178 borrowck_graphviz_postflow,
179 borrowck_graphviz_preflow,
182 braced_empty_structs,
195 cfg_target_has_atomic,
196 cfg_target_thread_local,
205 closure_to_fn_coercion,
207 cmpxchg16b_target_feature,
214 conservative_impl_trait,
216 const_compare_raw_pointers,
225 const_in_array_repeat_expressions,
230 const_precise_live_drops,
232 const_raw_ptr_to_usize_cast,
234 const_trait_bound_opt_out,
249 crate_visibility_modifier,
257 custom_inner_attributes,
258 custom_test_frameworks,
267 default_lib_allocator,
268 default_type_parameter_fallback,
270 delay_span_bug_from_inside_query,
285 document_private_items,
286 dotdoteq_in_patterns,
287 dotdot_in_tuple_patterns,
288 double_braced_crate: "{{crate}}",
289 double_braced_impl: "{{impl}}",
290 double_braced_misc: "{{misc}}",
291 double_braced_closure: "{{closure}}",
292 double_braced_constructor: "{{constructor}}",
293 double_braced_constant: "{{constant}}",
294 double_braced_opaque: "{{opaque}}",
296 dropck_parametricity,
311 exclusive_range_pattern,
312 exhaustive_integer_patterns,
318 extern_absolute_paths,
320 extern_crate_item_prelude,
333 field_init_shorthand,
358 generic_associated_types,
364 half_open_range_patterns,
369 hexagon_target_feature,
371 homogeneous_aggregate,
385 if_while_or_patterns,
389 impl_header_lifetime_elision,
391 impl_trait_in_bindings,
399 inclusive_range_syntax,
400 infer_outlives_requirements,
401 infer_static_outlives_requirements,
408 irrefutable_let_patterns,
411 issue_5723_bootstrap,
412 issue_tracker_base_url,
414 item_context: "ItemContext",
434 link_llvm_intrinsics,
445 macro_at_most_once_rep,
448 macro_lifetime_matcher,
449 macro_literal_matcher,
459 match_beginning_vert,
460 match_default_bindings,
481 movbe_target_feature,
523 object_safe_for_dispatch,
526 omit_gdb_pretty_printer_section,
533 optin_builtin_traits,
545 overlapping_marker_traits,
550 panic_implementation,
571 powerpc_target_feature,
572 precise_pointer_size_matching,
578 proc_dash_macro: "proc-macro",
580 proc_macro_attribute,
586 proc_macro_internals,
588 proc_macro_non_items,
589 proc_macro_path_invoc,
595 quad_precision_float,
612 reexport_test_harness_main,
625 re_rebalance_coherence,
630 riscv_target_feature,
644 rustc_allocator_nounwind,
645 rustc_allow_const_fn_ptr,
646 rustc_args_required_const,
650 rustc_const_unstable,
652 rustc_conversion_suggestion,
655 rustc_diagnostic_item,
656 rustc_diagnostic_macros,
659 rustc_dump_env_program_clauses,
660 rustc_dump_program_clauses,
661 rustc_dump_user_substs,
663 rustc_expected_cgu_reuse,
664 rustc_if_this_changed,
665 rustc_inherit_overflow_checks,
667 rustc_layout_scalar_valid_range_end,
668 rustc_layout_scalar_valid_range_start,
669 rustc_macro_transparency,
671 rustc_nonnull_optimization_guaranteed,
672 rustc_object_lifetime_default,
673 rustc_on_unimplemented,
676 rustc_partition_codegened,
677 rustc_partition_reused,
679 rustc_peek_definite_init,
681 rustc_peek_maybe_init,
682 rustc_peek_maybe_uninit,
683 rustc_peek_indirectly_mutable,
685 rustc_proc_macro_decls,
688 rustc_unsafe_specialization_marker,
689 rustc_specialization_trait,
691 rustc_std_internal_symbol,
694 rustc_reservation_impl,
696 rustc_then_this_would_need,
701 rvalue_static_promotion,
724 sse4a_target_feature,
737 stmt_expr_attributes,
739 struct_field_attributes,
751 target_has_atomic_load_store,
757 termination_trait_test,
760 test_accepted_feature,
762 test_removed_feature,
785 type_alias_impl_trait,
790 type_alias_enum_variants,
807 underscore_const_names,
809 underscore_lifetimes,
811 universal_impl_trait,
814 unrestricted_attribute_tokens,
815 unsafe_block_in_unsafe_fn,
818 unsized_tuple_coercion,
835 visible_private_types,
850 #[derive(Copy, Clone, Eq, HashStable_Generic)]
858 /// Constructs a new identifier from a symbol and a span.
859 pub const fn new(name: Symbol, span: Span) -> Ident {
863 /// Constructs a new identifier with a dummy span.
865 pub const fn with_dummy_span(name: Symbol) -> Ident {
866 Ident::new(name, DUMMY_SP)
870 pub fn invalid() -> Ident {
871 Ident::with_dummy_span(kw::Invalid)
874 /// Maps a string to an identifier with a dummy span.
875 pub fn from_str(string: &str) -> Ident {
876 Ident::with_dummy_span(Symbol::intern(string))
879 /// Maps a string and a span to an identifier.
880 pub fn from_str_and_span(string: &str, span: Span) -> Ident {
881 Ident::new(Symbol::intern(string), span)
884 /// Replaces `lo` and `hi` with those from `span`, but keep hygiene context.
885 pub fn with_span_pos(self, span: Span) -> Ident {
886 Ident::new(self.name, span.with_ctxt(self.span.ctxt()))
889 pub fn without_first_quote(self) -> Ident {
890 Ident::new(Symbol::intern(self.as_str().trim_start_matches('\'')), self.span)
893 /// "Normalize" ident for use in comparisons using "item hygiene".
894 /// Identifiers with same string value become same if they came from the same macro 2.0 macro
895 /// (e.g., `macro` item, but not `macro_rules` item) and stay different if they came from
896 /// different macro 2.0 macros.
897 /// Technically, this operation strips all non-opaque marks from ident's syntactic context.
898 pub fn normalize_to_macros_2_0(self) -> Ident {
899 Ident::new(self.name, self.span.normalize_to_macros_2_0())
902 /// "Normalize" ident for use in comparisons using "local variable hygiene".
903 /// Identifiers with same string value become same if they came from the same non-transparent
904 /// macro (e.g., `macro` or `macro_rules!` items) and stay different if they came from different
905 /// non-transparent macros.
906 /// Technically, this operation strips all transparent marks from ident's syntactic context.
907 pub fn normalize_to_macro_rules(self) -> Ident {
908 Ident::new(self.name, self.span.normalize_to_macro_rules())
911 /// Convert the name to a `SymbolStr`. This is a slowish operation because
912 /// it requires locking the symbol interner.
913 pub fn as_str(self) -> SymbolStr {
918 impl PartialEq for Ident {
919 fn eq(&self, rhs: &Self) -> bool {
920 self.name == rhs.name && self.span.ctxt() == rhs.span.ctxt()
924 impl Hash for Ident {
925 fn hash<H: Hasher>(&self, state: &mut H) {
926 self.name.hash(state);
927 self.span.ctxt().hash(state);
931 impl fmt::Debug for Ident {
932 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
933 fmt::Display::fmt(self, f)?;
934 fmt::Debug::fmt(&self.span.ctxt(), f)
938 /// This implementation is supposed to be used in error messages, so it's expected to be identical
939 /// to printing the original identifier token written in source code (`token_to_string`),
940 /// except that AST identifiers don't keep the rawness flag, so we have to guess it.
941 impl fmt::Display for Ident {
942 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
943 fmt::Display::fmt(&IdentPrinter::new(self.name, self.is_raw_guess(), None), f)
947 impl UseSpecializedEncodable for Ident {
948 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
949 s.emit_struct("Ident", 2, |s| {
950 s.emit_struct_field("name", 0, |s| self.name.encode(s))?;
951 s.emit_struct_field("span", 1, |s| self.span.encode(s))
956 impl UseSpecializedDecodable for Ident {
957 fn default_decode<D: Decoder>(d: &mut D) -> Result<Self, D::Error> {
958 d.read_struct("Ident", 2, |d| {
960 name: d.read_struct_field("name", 0, Decodable::decode)?,
961 span: d.read_struct_field("span", 1, Decodable::decode)?,
967 /// This is the most general way to print identifiers.
968 /// AST pretty-printer is used as a fallback for turning AST structures into token streams for
969 /// proc macros. Additionally, proc macros may stringify their input and expect it survive the
970 /// stringification (especially true for proc macro derives written between Rust 1.15 and 1.30).
971 /// So we need to somehow pretty-print `$crate` in a way preserving at least some of its
972 /// hygiene data, most importantly name of the crate it refers to.
973 /// As a result we print `$crate` as `crate` if it refers to the local crate
974 /// and as `::other_crate_name` if it refers to some other crate.
975 /// Note, that this is only done if the ident token is printed from inside of AST pretty-pringing,
976 /// but not otherwise. Pretty-printing is the only way for proc macros to discover token contents,
977 /// so we should not perform this lossy conversion if the top level call to the pretty-printer was
978 /// done for a token stream or a single token.
979 pub struct IdentPrinter {
982 /// Span used for retrieving the crate name to which `$crate` refers to,
983 /// if this field is `None` then the `$crate` conversion doesn't happen.
984 convert_dollar_crate: Option<Span>,
988 /// The most general `IdentPrinter` constructor. Do not use this.
989 pub fn new(symbol: Symbol, is_raw: bool, convert_dollar_crate: Option<Span>) -> IdentPrinter {
990 IdentPrinter { symbol, is_raw, convert_dollar_crate }
993 /// This implementation is supposed to be used when printing identifiers
994 /// as a part of pretty-printing for larger AST pieces.
995 /// Do not use this either.
996 pub fn for_ast_ident(ident: Ident, is_raw: bool) -> IdentPrinter {
997 IdentPrinter::new(ident.name, is_raw, Some(ident.span))
1001 impl fmt::Display for IdentPrinter {
1002 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1006 if self.symbol == kw::DollarCrate {
1007 if let Some(span) = self.convert_dollar_crate {
1008 let converted = span.ctxt().dollar_crate_name();
1009 if !converted.is_path_segment_keyword() {
1012 return fmt::Display::fmt(&converted, f);
1016 fmt::Display::fmt(&self.symbol, f)
1020 /// An newtype around `Ident` that calls [Ident::normalize_to_macro_rules] on
1022 // FIXME(matthewj, petrochenkov) Use this more often, add a similar
1023 // `ModernIdent` struct and use that as well.
1024 #[derive(Copy, Clone, Eq, PartialEq, Hash)]
1025 pub struct MacroRulesNormalizedIdent(Ident);
1027 impl MacroRulesNormalizedIdent {
1028 pub fn new(ident: Ident) -> Self {
1029 Self(ident.normalize_to_macro_rules())
1033 impl fmt::Debug for MacroRulesNormalizedIdent {
1034 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1035 fmt::Debug::fmt(&self.0, f)
1039 impl fmt::Display for MacroRulesNormalizedIdent {
1040 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1041 fmt::Display::fmt(&self.0, f)
1045 /// An interned string.
1047 /// Internally, a `Symbol` is implemented as an index, and all operations
1048 /// (including hashing, equality, and ordering) operate on that index. The use
1049 /// of `rustc_index::newtype_index!` means that `Option<Symbol>` only takes up 4 bytes,
1050 /// because `rustc_index::newtype_index!` reserves the last 256 values for tagging purposes.
1052 /// Note that `Symbol` cannot directly be a `rustc_index::newtype_index!` because it
1053 /// implements `fmt::Debug`, `Encodable`, and `Decodable` in special ways.
1054 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
1055 pub struct Symbol(SymbolIndex);
1057 rustc_index::newtype_index! {
1058 pub struct SymbolIndex { .. }
1062 const fn new(n: u32) -> Self {
1063 Symbol(SymbolIndex::from_u32(n))
1066 /// Maps a string to its interned representation.
1067 pub fn intern(string: &str) -> Self {
1068 with_interner(|interner| interner.intern(string))
1071 /// Access the symbol's chars. This is a slowish operation because it
1072 /// requires locking the symbol interner.
1073 pub fn with<F: FnOnce(&str) -> R, R>(self, f: F) -> R {
1074 with_interner(|interner| f(interner.get(self)))
1077 /// Convert to a `SymbolStr`. This is a slowish operation because it
1078 /// requires locking the symbol interner.
1079 pub fn as_str(self) -> SymbolStr {
1080 with_interner(|interner| unsafe {
1081 SymbolStr { string: std::mem::transmute::<&str, &str>(interner.get(self)) }
1085 pub fn as_u32(self) -> u32 {
1089 /// This method is supposed to be used in error messages, so it's expected to be
1090 /// identical to printing the original identifier token written in source code
1091 /// (`token_to_string`, `Ident::to_string`), except that symbols don't keep the rawness flag
1092 /// or edition, so we have to guess the rawness using the global edition.
1093 pub fn to_ident_string(self) -> String {
1094 Ident::with_dummy_span(self).to_string()
1098 impl fmt::Debug for Symbol {
1099 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1100 self.with(|str| fmt::Debug::fmt(&str, f))
1104 impl fmt::Display for Symbol {
1105 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1106 self.with(|str| fmt::Display::fmt(&str, f))
1110 impl Encodable for Symbol {
1111 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1112 self.with(|string| s.emit_str(string))
1116 impl Decodable for Symbol {
1118 fn decode<D: Decoder>(d: &mut D) -> Result<Symbol, D::Error> {
1119 Ok(Symbol::intern(&d.read_str()?))
1123 impl<CTX> HashStable<CTX> for Symbol {
1125 fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
1126 self.as_str().hash_stable(hcx, hasher);
1130 impl<CTX> ToStableHashKey<CTX> for Symbol {
1131 type KeyType = SymbolStr;
1134 fn to_stable_hash_key(&self, _: &CTX) -> SymbolStr {
1139 // The `&'static str`s in this type actually point into the arena.
1141 pub struct Interner {
1142 arena: DroplessArena,
1143 names: FxHashMap<&'static str, Symbol>,
1144 strings: Vec<&'static str>,
1148 fn prefill(init: &[&'static str]) -> Self {
1150 strings: init.into(),
1151 names: init.iter().copied().zip((0..).map(Symbol::new)).collect(),
1152 ..Default::default()
1157 pub fn intern(&mut self, string: &str) -> Symbol {
1158 if let Some(&name) = self.names.get(string) {
1162 let name = Symbol::new(self.strings.len() as u32);
1164 // `from_utf8_unchecked` is safe since we just allocated a `&str` which is known to be
1167 unsafe { str::from_utf8_unchecked(self.arena.alloc_slice(string.as_bytes())) };
1168 // It is safe to extend the arena allocation to `'static` because we only access
1169 // these while the arena is still alive.
1170 let string: &'static str = unsafe { &*(string as *const str) };
1171 self.strings.push(string);
1172 self.names.insert(string, name);
1176 // Get the symbol as a string. `Symbol::as_str()` should be used in
1177 // preference to this function.
1178 pub fn get(&self, symbol: Symbol) -> &str {
1179 self.strings[symbol.0.as_usize()]
1183 // This module has a very short name because it's used a lot.
1184 /// This module contains all the defined keyword `Symbol`s.
1186 /// Given that `kw` is imported, use them like `kw::keyword_name`.
1187 /// For example `kw::Loop` or `kw::Break`.
1193 // This module has a very short name because it's used a lot.
1194 /// This module contains all the defined non-keyword `Symbol`s.
1196 /// Given that `sym` is imported, use them like `sym::symbol_name`.
1197 /// For example `sym::rustfmt` or `sym::u8`.
1198 #[allow(rustc::default_hash_types)]
1201 use std::convert::TryInto;
1205 // Used from a macro in `librustc_feature/accepted.rs`
1206 pub use super::kw::MacroRules as macro_rules;
1208 // Get the symbol for an integer. The first few non-negative integers each
1209 // have a static symbol and therefore are fast.
1210 pub fn integer<N: TryInto<usize> + Copy + ToString>(n: N) -> Symbol {
1211 if let Result::Ok(idx) = n.try_into() {
1212 if let Option::Some(&sym_) = digits_array.get(idx) {
1216 Symbol::intern(&n.to_string())
1221 fn is_used_keyword_2018(self) -> bool {
1222 self >= kw::Async && self <= kw::Dyn
1225 fn is_unused_keyword_2018(self) -> bool {
1229 /// Used for sanity checking rustdoc keyword sections.
1230 pub fn is_doc_keyword(self) -> bool {
1234 /// A keyword or reserved identifier that can be used as a path segment.
1235 pub fn is_path_segment_keyword(self) -> bool {
1237 || self == kw::SelfLower
1238 || self == kw::SelfUpper
1239 || self == kw::Crate
1240 || self == kw::PathRoot
1241 || self == kw::DollarCrate
1244 /// Returns `true` if the symbol is `true` or `false`.
1245 pub fn is_bool_lit(self) -> bool {
1246 self == kw::True || self == kw::False
1249 /// This symbol can be a raw identifier.
1250 pub fn can_be_raw(self) -> bool {
1251 self != kw::Invalid && self != kw::Underscore && !self.is_path_segment_keyword()
1256 // Returns `true` for reserved identifiers used internally for elided lifetimes,
1257 // unnamed method parameters, crate root module, error recovery etc.
1258 pub fn is_special(self) -> bool {
1259 self.name <= kw::Underscore
1262 /// Returns `true` if the token is a keyword used in the language.
1263 pub fn is_used_keyword(self) -> bool {
1264 // Note: `span.edition()` is relatively expensive, don't call it unless necessary.
1265 self.name >= kw::As && self.name <= kw::While
1266 || self.name.is_used_keyword_2018() && self.span.rust_2018()
1269 /// Returns `true` if the token is a keyword reserved for possible future use.
1270 pub fn is_unused_keyword(self) -> bool {
1271 // Note: `span.edition()` is relatively expensive, don't call it unless necessary.
1272 self.name >= kw::Abstract && self.name <= kw::Yield
1273 || self.name.is_unused_keyword_2018() && self.span.rust_2018()
1276 /// Returns `true` if the token is either a special identifier or a keyword.
1277 pub fn is_reserved(self) -> bool {
1278 self.is_special() || self.is_used_keyword() || self.is_unused_keyword()
1281 /// A keyword or reserved identifier that can be used as a path segment.
1282 pub fn is_path_segment_keyword(self) -> bool {
1283 self.name.is_path_segment_keyword()
1286 /// We see this identifier in a normal identifier position, like variable name or a type.
1287 /// How was it written originally? Did it use the raw form? Let's try to guess.
1288 pub fn is_raw_guess(self) -> bool {
1289 self.name.can_be_raw() && self.is_reserved()
1294 fn with_interner<T, F: FnOnce(&mut Interner) -> T>(f: F) -> T {
1295 GLOBALS.with(|globals| f(&mut *globals.symbol_interner.lock()))
1298 /// An alternative to `Symbol`, useful when the chars within the symbol need to
1299 /// be accessed. It deliberately has limited functionality and should only be
1300 /// used for temporary values.
1302 /// Because the interner outlives any thread which uses this type, we can
1303 /// safely treat `string` which points to interner data, as an immortal string,
1304 /// as long as this type never crosses between threads.
1306 // FIXME: ensure that the interner outlives any thread which uses `SymbolStr`,
1307 // by creating a new thread right after constructing the interner.
1308 #[derive(Clone, Eq, PartialOrd, Ord)]
1309 pub struct SymbolStr {
1310 string: &'static str,
1313 // This impl allows a `SymbolStr` to be directly equated with a `String` or
1315 impl<T: std::ops::Deref<Target = str>> std::cmp::PartialEq<T> for SymbolStr {
1316 fn eq(&self, other: &T) -> bool {
1317 self.string == other.deref()
1321 impl !Send for SymbolStr {}
1322 impl !Sync for SymbolStr {}
1324 /// This impl means that if `ss` is a `SymbolStr`:
1325 /// - `*ss` is a `str`;
1326 /// - `&*ss` is a `&str`;
1327 /// - `&ss as &str` is a `&str`, which means that `&ss` can be passed to a
1328 /// function expecting a `&str`.
1329 impl std::ops::Deref for SymbolStr {
1332 fn deref(&self) -> &str {
1337 impl fmt::Debug for SymbolStr {
1338 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1339 fmt::Debug::fmt(self.string, f)
1343 impl fmt::Display for SymbolStr {
1344 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1345 fmt::Display::fmt(self.string, f)
1349 impl<CTX> HashStable<CTX> for SymbolStr {
1351 fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
1352 self.string.hash_stable(hcx, hasher)
1356 impl<CTX> ToStableHashKey<CTX> for SymbolStr {
1357 type KeyType = SymbolStr;
1360 fn to_stable_hash_key(&self, _: &CTX) -> SymbolStr {