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_data_structures::indexed_vec::Idx;
8 use rustc_data_structures::newtype_index;
9 use rustc_macros::symbols;
10 use serialize::{Decodable, Decoder, Encodable, Encoder};
12 use std::cmp::{PartialEq, Ordering, PartialOrd, Ord};
14 use std::hash::{Hash, Hasher};
17 use crate::hygiene::SyntaxContext;
18 use crate::{Span, DUMMY_SP, GLOBALS};
21 // After modifying this list adjust `is_special`, `is_used_keyword`/`is_unused_keyword`,
22 // this should be rarely necessary though if the keywords are kept in alphabetic order.
24 // Special reserved identifiers used internally for elided lifetimes,
25 // unnamed method parameters, crate root module, error recovery etc.
28 DollarCrate: "$crate",
31 // Keywords that are used in stable Rust.
68 // Keywords that are used in unstable Rust or reserved for future use.
82 // Edition-specific keywords that are used in stable Rust.
83 Dyn: "dyn", // >= 2018 Edition only
85 // Edition-specific keywords that are used in unstable Rust or reserved for future use.
86 Async: "async", // >= 2018 Edition only
87 Await: "await", // >= 2018 Edition only
88 Try: "try", // >= 2018 Edition only
90 // Special lifetime names
91 UnderscoreLifetime: "'_",
92 StaticLifetime: "'static",
94 // Weak keywords, have special meaning only in specific contexts.
98 Existential: "existential",
102 // Symbols that can be referred to with syntax_pos::sym::*. The symbol is
103 // the stringified identifier unless otherwise specified (e.g.
104 // `proc_dash_macro` represents "proc-macro").
106 // As well as the symbols listed, there are symbols for the the strings
107 // "0", "1", ..., "9", which are accessible via `sym::integer`.
109 aarch64_target_feature,
112 abi_msp430_interrupt,
120 advanced_slice_patterns,
132 allow_internal_unsafe,
133 allow_internal_unstable,
134 allow_internal_unstable_backcompat_hack,
138 arbitrary_enum_discriminant,
139 arbitrary_self_types,
146 associated_type_bounds,
147 associated_type_defaults,
154 augmented_assignments,
155 automatically_derived,
156 avx512_target_feature,
161 bind_by_move_pattern_guards,
164 borrowck_graphviz_postflow,
165 borrowck_graphviz_preflow,
168 braced_empty_structs,
176 cfg_target_has_atomic,
177 cfg_target_thread_local,
185 closure_to_fn_coercion,
187 cmpxchg16b_target_feature,
194 conservative_impl_trait,
196 const_compare_raw_pointers,
205 const_raw_ptr_to_usize_cast,
219 crate_visibility_modifier,
222 custom_inner_attributes,
223 custom_test_frameworks,
230 default_lib_allocator,
231 default_type_parameter_fallback,
246 document_private_items,
247 dotdoteq_in_patterns,
248 dotdot_in_tuple_patterns,
249 double_braced_crate: "{{crate}}",
250 double_braced_impl: "{{impl}}",
251 double_braced_misc: "{{misc}}",
252 double_braced_closure: "{{closure}}",
253 double_braced_constructor: "{{constructor}}",
254 double_braced_constant: "{{constant}}",
255 double_braced_opaque: "{{opaque}}",
257 dropck_parametricity,
272 exclusive_range_pattern,
273 exhaustive_integer_patterns,
279 extern_absolute_paths,
281 extern_crate_item_prelude,
292 field_init_shorthand,
315 generic_associated_types,
324 hexagon_target_feature,
326 homogeneous_aggregate,
340 if_while_or_patterns,
342 impl_header_lifetime_elision,
344 impl_trait_in_bindings,
352 inclusive_range_syntax,
353 infer_outlives_requirements,
354 infer_static_outlives_requirements,
361 irrefutable_let_patterns,
364 issue_5723_bootstrap,
365 issue_tracker_base_url,
385 link_llvm_intrinsics,
394 macro_at_most_once_rep,
397 macro_lifetime_matcher,
398 macro_literal_matcher,
409 match_beginning_vert,
410 match_default_bindings,
422 movbe_target_feature,
456 omit_gdb_pretty_printer_section,
463 optin_builtin_traits,
472 overlapping_marker_traits,
477 panic_implementation,
497 poll_with_tls_context,
498 powerpc_target_feature,
499 precise_pointer_size_matching,
503 proc_dash_macro: "proc-macro",
505 proc_macro_attribute,
512 proc_macro_non_items,
513 proc_macro_path_invoc,
517 quad_precision_float,
530 reexport_test_harness_main,
540 re_rebalance_coherence,
556 rustc_allocator_nounwind,
557 rustc_allow_const_fn_ptr,
558 rustc_args_required_const,
562 rustc_const_unstable,
563 rustc_conversion_suggestion,
564 rustc_copy_clone_marker,
567 rustc_diagnostic_macros,
570 rustc_dump_env_program_clauses,
571 rustc_dump_program_clauses,
572 rustc_dump_user_substs,
574 rustc_expected_cgu_reuse,
575 rustc_if_this_changed,
576 rustc_inherit_overflow_checks,
578 rustc_layout_scalar_valid_range_end,
579 rustc_layout_scalar_valid_range_start,
580 rustc_macro_transparency,
582 rustc_nonnull_optimization_guaranteed,
583 rustc_object_lifetime_default,
584 rustc_on_unimplemented,
587 rustc_partition_codegened,
588 rustc_partition_reused,
590 rustc_peek_definite_init,
591 rustc_peek_maybe_init,
592 rustc_peek_maybe_uninit,
594 rustc_proc_macro_decls,
598 rustc_std_internal_symbol,
602 rustc_then_this_would_need,
606 rust_eh_unwind_resume,
608 __rust_unstable_column,
609 rvalue_static_promotion,
625 sse4a_target_feature,
637 stmt_expr_attributes,
639 struct_field_attributes,
651 termination_trait_test,
654 test_accepted_feature,
656 test_removed_feature,
678 type_alias_enum_variants,
688 underscore_const_names,
690 underscore_lifetimes,
692 universal_impl_trait,
695 unrestricted_attribute_tokens,
696 unsafe_destructor_blind_to_params,
699 unsized_tuple_coercion,
714 visible_private_types,
717 warn_directory_ownership,
727 #[derive(Copy, Clone, Eq)]
735 /// Constructs a new identifier from a symbol and a span.
736 pub const fn new(name: Symbol, span: Span) -> Ident {
740 /// Constructs a new identifier with an empty syntax context.
742 pub const fn with_empty_ctxt(name: Symbol) -> Ident {
743 Ident::new(name, DUMMY_SP)
747 pub fn invalid() -> Ident {
748 Ident::with_empty_ctxt(kw::Invalid)
751 /// Maps an interned string to an identifier with an empty syntax context.
752 pub fn from_interned_str(string: InternedString) -> Ident {
753 Ident::with_empty_ctxt(string.as_symbol())
756 /// Maps a string to an identifier with an empty span.
757 pub fn from_str(string: &str) -> Ident {
758 Ident::with_empty_ctxt(Symbol::intern(string))
761 /// Maps a string and a span to an identifier.
762 pub fn from_str_and_span(string: &str, span: Span) -> Ident {
763 Ident::new(Symbol::intern(string), span)
766 /// Replaces `lo` and `hi` with those from `span`, but keep hygiene context.
767 pub fn with_span_pos(self, span: Span) -> Ident {
768 Ident::new(self.name, span.with_ctxt(self.span.ctxt()))
771 pub fn without_first_quote(self) -> Ident {
772 Ident::new(Symbol::intern(self.as_str().trim_start_matches('\'')), self.span)
775 /// "Normalize" ident for use in comparisons using "item hygiene".
776 /// Identifiers with same string value become same if they came from the same "modern" macro
777 /// (e.g., `macro` item, but not `macro_rules` item) and stay different if they came from
778 /// different "modern" macros.
779 /// Technically, this operation strips all non-opaque marks from ident's syntactic context.
780 pub fn modern(self) -> Ident {
781 Ident::new(self.name, self.span.modern())
784 /// "Normalize" ident for use in comparisons using "local variable hygiene".
785 /// Identifiers with same string value become same if they came from the same non-transparent
786 /// macro (e.g., `macro` or `macro_rules!` items) and stay different if they came from different
787 /// non-transparent macros.
788 /// Technically, this operation strips all transparent marks from ident's syntactic context.
789 pub fn modern_and_legacy(self) -> Ident {
790 Ident::new(self.name, self.span.modern_and_legacy())
793 /// Transforms an identifier into one with the same name, but gensymed.
794 pub fn gensym(self) -> Ident {
795 let name = with_interner(|interner| interner.gensymed(self.name));
796 Ident::new(name, self.span)
799 /// Transforms an underscore identifier into one with the same name, but
800 /// gensymed. Leaves non-underscore identifiers unchanged.
801 pub fn gensym_if_underscore(self) -> Ident {
802 if self.name == kw::Underscore { self.gensym() } else { self }
805 // WARNING: this function is deprecated and will be removed in the future.
806 pub fn is_gensymed(self) -> bool {
807 with_interner(|interner| interner.is_gensymed(self.name))
810 pub fn as_str(self) -> LocalInternedString {
814 pub fn as_interned_str(self) -> InternedString {
815 self.name.as_interned_str()
819 impl PartialEq for Ident {
820 fn eq(&self, rhs: &Self) -> bool {
821 self.name == rhs.name && self.span.ctxt() == rhs.span.ctxt()
825 impl Hash for Ident {
826 fn hash<H: Hasher>(&self, state: &mut H) {
827 self.name.hash(state);
828 self.span.ctxt().hash(state);
832 impl fmt::Debug for Ident {
833 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
834 write!(f, "{}{:?}", self.name, self.span.ctxt())
838 impl fmt::Display for Ident {
839 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
840 fmt::Display::fmt(&self.name, f)
844 impl Encodable for Ident {
845 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
846 if self.span.ctxt().modern() == SyntaxContext::empty() {
847 s.emit_str(&self.as_str())
848 } else { // FIXME(jseyfried): intercrate hygiene
849 let mut string = "#".to_owned();
850 string.push_str(&self.as_str());
856 impl Decodable for Ident {
857 fn decode<D: Decoder>(d: &mut D) -> Result<Ident, D::Error> {
858 let string = d.read_str()?;
859 Ok(if !string.starts_with('#') {
860 Ident::from_str(&string)
861 } else { // FIXME(jseyfried): intercrate hygiene
862 Ident::from_str(&string[1..]).gensym()
867 /// A symbol is an interned or gensymed string. A gensym is a symbol that is
868 /// never equal to any other symbol.
870 /// Conceptually, a gensym can be thought of as a normal symbol with an
871 /// invisible unique suffix. Gensyms are useful when creating new identifiers
872 /// that must not match any existing identifiers, e.g. during macro expansion
873 /// and syntax desugaring. Because gensyms should always be identifiers, all
874 /// gensym operations are on `Ident` rather than `Symbol`. (Indeed, in the
875 /// future the gensym-ness may be moved from `Symbol` to hygiene data.)
879 /// assert_eq!(Ident::from_str("x"), Ident::from_str("x"))
880 /// assert_ne!(Ident::from_str("x").gensym(), Ident::from_str("x"))
881 /// assert_ne!(Ident::from_str("x").gensym(), Ident::from_str("x").gensym())
883 /// Internally, a symbol is implemented as an index, and all operations
884 /// (including hashing, equality, and ordering) operate on that index. The use
885 /// of `newtype_index!` means that `Option<Symbol>` only takes up 4 bytes,
886 /// because `newtype_index!` reserves the last 256 values for tagging purposes.
888 /// Note that `Symbol` cannot directly be a `newtype_index!` because it
889 /// implements `fmt::Debug`, `Encodable`, and `Decodable` in special ways.
890 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
891 pub struct Symbol(SymbolIndex);
894 pub struct SymbolIndex { .. }
898 const fn new(n: u32) -> Self {
899 Symbol(SymbolIndex::from_u32_const(n))
902 /// Maps a string to its interned representation.
903 pub fn intern(string: &str) -> Self {
904 with_interner(|interner| interner.intern(string))
907 pub fn as_str(self) -> LocalInternedString {
908 with_interner(|interner| unsafe {
909 LocalInternedString {
910 string: std::mem::transmute::<&str, &str>(interner.get(self))
915 pub fn as_interned_str(self) -> InternedString {
916 with_interner(|interner| InternedString {
917 symbol: interner.interned(self)
921 pub fn as_u32(self) -> u32 {
926 impl fmt::Debug for Symbol {
927 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
928 let is_gensymed = with_interner(|interner| interner.is_gensymed(*self));
930 write!(f, "{}({:?})", self, self.0)
932 write!(f, "{}", self)
937 impl fmt::Display for Symbol {
938 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
939 fmt::Display::fmt(&self.as_str(), f)
943 impl Encodable for Symbol {
944 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
945 s.emit_str(&self.as_str())
949 impl Decodable for Symbol {
950 fn decode<D: Decoder>(d: &mut D) -> Result<Symbol, D::Error> {
951 Ok(Symbol::intern(&d.read_str()?))
955 // The `&'static str`s in this type actually point into the arena.
957 // Note that normal symbols are indexed upward from 0, and gensyms are indexed
958 // downward from SymbolIndex::MAX_AS_U32.
960 pub struct Interner {
961 arena: DroplessArena,
962 names: FxHashMap<&'static str, Symbol>,
963 strings: Vec<&'static str>,
964 gensyms: Vec<Symbol>,
968 fn prefill(init: &[&'static str]) -> Self {
970 strings: init.into(),
971 names: init.iter().copied().zip((0..).map(Symbol::new)).collect(),
976 pub fn intern(&mut self, string: &str) -> Symbol {
977 if let Some(&name) = self.names.get(string) {
981 let name = Symbol::new(self.strings.len() as u32);
983 // `from_utf8_unchecked` is safe since we just allocated a `&str` which is known to be
985 let string: &str = unsafe {
986 str::from_utf8_unchecked(self.arena.alloc_slice(string.as_bytes()))
988 // It is safe to extend the arena allocation to `'static` because we only access
989 // these while the arena is still alive.
990 let string: &'static str = unsafe {
991 &*(string as *const str)
993 self.strings.push(string);
994 self.names.insert(string, name);
998 fn interned(&self, symbol: Symbol) -> Symbol {
999 if (symbol.0.as_usize()) < self.strings.len() {
1002 self.gensyms[(SymbolIndex::MAX_AS_U32 - symbol.0.as_u32()) as usize]
1006 fn gensymed(&mut self, symbol: Symbol) -> Symbol {
1007 self.gensyms.push(symbol);
1008 Symbol::new(SymbolIndex::MAX_AS_U32 - self.gensyms.len() as u32 + 1)
1011 fn is_gensymed(&mut self, symbol: Symbol) -> bool {
1012 symbol.0.as_usize() >= self.strings.len()
1015 // Get the symbol as a string. `Symbol::as_str()` should be used in
1016 // preference to this function.
1017 pub fn get(&self, symbol: Symbol) -> &str {
1018 match self.strings.get(symbol.0.as_usize()) {
1019 Some(string) => string,
1021 let symbol = self.gensyms[(SymbolIndex::MAX_AS_U32 - symbol.0.as_u32()) as usize];
1022 self.strings[symbol.0.as_usize()]
1028 // This module has a very short name because it's used a lot.
1034 // This module has a very short name because it's used a lot.
1036 use std::convert::TryInto;
1041 // Get the symbol for an integer. The first few non-negative integers each
1042 // have a static symbol and therefore are fast.
1043 pub fn integer<N: TryInto<usize> + Copy + ToString>(n: N) -> Symbol {
1044 if let Result::Ok(idx) = n.try_into() {
1045 if let Option::Some(&sym) = digits_array.get(idx) {
1049 Symbol::intern(&n.to_string())
1054 fn is_used_keyword_2018(self) -> bool {
1058 fn is_unused_keyword_2018(self) -> bool {
1059 self >= kw::Async && self <= kw::Try
1062 /// Used for sanity checking rustdoc keyword sections.
1063 pub fn is_doc_keyword(self) -> bool {
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 == kw::Super ||
1070 self == kw::SelfLower ||
1071 self == kw::SelfUpper ||
1072 self == kw::Crate ||
1073 self == kw::PathRoot ||
1074 self == kw::DollarCrate
1077 /// This symbol can be a raw identifier.
1078 pub fn can_be_raw(self) -> bool {
1079 self != kw::Invalid && self != kw::Underscore && !self.is_path_segment_keyword()
1084 // Returns `true` for reserved identifiers used internally for elided lifetimes,
1085 // unnamed method parameters, crate root module, error recovery etc.
1086 pub fn is_special(self) -> bool {
1087 self.name <= kw::Underscore
1090 /// Returns `true` if the token is a keyword used in the language.
1091 pub fn is_used_keyword(self) -> bool {
1092 // Note: `span.edition()` is relatively expensive, don't call it unless necessary.
1093 self.name >= kw::As && self.name <= kw::While ||
1094 self.name.is_used_keyword_2018() && self.span.rust_2018()
1097 /// Returns `true` if the token is a keyword reserved for possible future use.
1098 pub fn is_unused_keyword(self) -> bool {
1099 // Note: `span.edition()` is relatively expensive, don't call it unless necessary.
1100 self.name >= kw::Abstract && self.name <= kw::Yield ||
1101 self.name.is_unused_keyword_2018() && self.span.rust_2018()
1104 /// Returns `true` if the token is either a special identifier or a keyword.
1105 pub fn is_reserved(self) -> bool {
1106 self.is_special() || self.is_used_keyword() || self.is_unused_keyword()
1109 /// A keyword or reserved identifier that can be used as a path segment.
1110 pub fn is_path_segment_keyword(self) -> bool {
1111 self.name.is_path_segment_keyword()
1114 /// We see this identifier in a normal identifier position, like variable name or a type.
1115 /// How was it written originally? Did it use the raw form? Let's try to guess.
1116 pub fn is_raw_guess(self) -> bool {
1117 self.name.can_be_raw() && self.is_reserved()
1121 // If an interner exists, return it. Otherwise, prepare a fresh one.
1123 fn with_interner<T, F: FnOnce(&mut Interner) -> T>(f: F) -> T {
1124 GLOBALS.with(|globals| f(&mut *globals.symbol_interner.lock()))
1127 /// An alternative to `Symbol` and `InternedString`, useful when the chars
1128 /// within the symbol need to be accessed. It is best used for temporary
1131 /// Because the interner outlives any thread which uses this type, we can
1132 /// safely treat `string` which points to interner data, as an immortal string,
1133 /// as long as this type never crosses between threads.
1135 // FIXME: ensure that the interner outlives any thread which uses
1136 // `LocalInternedString`, by creating a new thread right after constructing the
1138 #[derive(Clone, Copy, Hash, PartialOrd, Eq, Ord)]
1139 pub struct LocalInternedString {
1140 string: &'static str,
1143 impl LocalInternedString {
1144 /// Maps a string to its interned representation.
1145 pub fn intern(string: &str) -> Self {
1146 let string = with_interner(|interner| {
1147 let symbol = interner.intern(string);
1148 interner.strings[symbol.0.as_usize()]
1150 LocalInternedString {
1151 string: unsafe { std::mem::transmute::<&str, &str>(string) }
1155 pub fn as_interned_str(self) -> InternedString {
1157 symbol: Symbol::intern(self.string)
1162 pub fn get(&self) -> &str {
1163 // This returns a valid string since we ensure that `self` outlives the interner
1164 // by creating the interner on a thread which outlives threads which can access it.
1165 // This type cannot move to a thread which outlives the interner since it does
1166 // not implement Send.
1171 impl<U: ?Sized> std::convert::AsRef<U> for LocalInternedString
1173 str: std::convert::AsRef<U>
1176 fn as_ref(&self) -> &U {
1177 self.string.as_ref()
1181 impl<T: std::ops::Deref<Target = str>> std::cmp::PartialEq<T> for LocalInternedString {
1182 fn eq(&self, other: &T) -> bool {
1183 self.string == other.deref()
1187 impl std::cmp::PartialEq<LocalInternedString> for str {
1188 fn eq(&self, other: &LocalInternedString) -> bool {
1189 self == other.string
1193 impl<'a> std::cmp::PartialEq<LocalInternedString> for &'a str {
1194 fn eq(&self, other: &LocalInternedString) -> bool {
1195 *self == other.string
1199 impl std::cmp::PartialEq<LocalInternedString> for String {
1200 fn eq(&self, other: &LocalInternedString) -> bool {
1201 self == other.string
1205 impl<'a> std::cmp::PartialEq<LocalInternedString> for &'a String {
1206 fn eq(&self, other: &LocalInternedString) -> bool {
1207 *self == other.string
1211 impl !Send for LocalInternedString {}
1212 impl !Sync for LocalInternedString {}
1214 impl std::ops::Deref for LocalInternedString {
1217 fn deref(&self) -> &str { self.string }
1220 impl fmt::Debug for LocalInternedString {
1221 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1222 fmt::Debug::fmt(self.string, f)
1226 impl fmt::Display for LocalInternedString {
1227 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1228 fmt::Display::fmt(self.string, f)
1232 impl Decodable for LocalInternedString {
1233 fn decode<D: Decoder>(d: &mut D) -> Result<LocalInternedString, D::Error> {
1234 Ok(LocalInternedString::intern(&d.read_str()?))
1238 impl Encodable for LocalInternedString {
1239 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1240 s.emit_str(self.string)
1244 /// An alternative to `Symbol` that is focused on string contents. It has two
1245 /// main differences to `Symbol`.
1247 /// First, its implementations of `Hash`, `PartialOrd` and `Ord` work with the
1248 /// string chars rather than the symbol integer. This is useful when hash
1249 /// stability is required across compile sessions, or a guaranteed sort
1250 /// ordering is required.
1252 /// Second, gensym-ness is irrelevant. E.g.:
1254 /// assert_ne!(Symbol::gensym("x"), Symbol::gensym("x"))
1255 /// assert_eq!(Symbol::gensym("x").as_interned_str(), Symbol::gensym("x").as_interned_str())
1257 #[derive(Clone, Copy, PartialEq, Eq)]
1258 pub struct InternedString {
1262 impl InternedString {
1263 /// Maps a string to its interned representation.
1264 pub fn intern(string: &str) -> Self {
1266 symbol: Symbol::intern(string)
1270 pub fn with<F: FnOnce(&str) -> R, R>(self, f: F) -> R {
1271 let str = with_interner(|interner| {
1272 interner.get(self.symbol) as *const str
1274 // This is safe because the interner keeps string alive until it is dropped.
1275 // We can access it because we know the interner is still alive since we use a
1276 // scoped thread local to access it, and it was alive at the beginning of this scope
1280 fn with2<F: FnOnce(&str, &str) -> R, R>(self, other: &InternedString, f: F) -> R {
1281 let (self_str, other_str) = with_interner(|interner| {
1282 (interner.get(self.symbol) as *const str,
1283 interner.get(other.symbol) as *const str)
1285 // This is safe for the same reason that `with` is safe.
1286 unsafe { f(&*self_str, &*other_str) }
1289 pub fn as_symbol(self) -> Symbol {
1293 pub fn as_str(self) -> LocalInternedString {
1294 self.symbol.as_str()
1298 impl Hash for InternedString {
1299 fn hash<H: Hasher>(&self, state: &mut H) {
1300 self.with(|str| str.hash(state))
1304 impl PartialOrd<InternedString> for InternedString {
1305 fn partial_cmp(&self, other: &InternedString) -> Option<Ordering> {
1306 if self.symbol == other.symbol {
1307 return Some(Ordering::Equal);
1309 self.with2(other, |self_str, other_str| self_str.partial_cmp(other_str))
1313 impl Ord for InternedString {
1314 fn cmp(&self, other: &InternedString) -> Ordering {
1315 if self.symbol == other.symbol {
1316 return Ordering::Equal;
1318 self.with2(other, |self_str, other_str| self_str.cmp(other_str))
1322 impl fmt::Debug for InternedString {
1323 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1324 self.with(|str| fmt::Debug::fmt(&str, f))
1328 impl fmt::Display for InternedString {
1329 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1330 self.with(|str| fmt::Display::fmt(&str, f))
1334 impl Decodable for InternedString {
1335 fn decode<D: Decoder>(d: &mut D) -> Result<InternedString, D::Error> {
1336 Ok(InternedString::intern(&d.read_str()?))
1340 impl Encodable for InternedString {
1341 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1342 self.with(|string| s.emit_str(string))
1353 fn interner_tests() {
1354 let mut i: Interner = Interner::default();
1355 // first one is zero:
1356 assert_eq!(i.intern("dog"), Symbol::new(0));
1357 // re-use gets the same entry:
1358 assert_eq!(i.intern("dog"), Symbol::new(0));
1359 // different string gets a different #:
1360 assert_eq!(i.intern("cat"), Symbol::new(1));
1361 assert_eq!(i.intern("cat"), Symbol::new(1));
1362 // dog is still at zero
1363 assert_eq!(i.intern("dog"), Symbol::new(0));
1364 let z = i.intern("zebra");
1365 assert_eq!(i.gensymed(z), Symbol::new(SymbolIndex::MAX_AS_U32));
1366 // gensym of same string gets new number:
1367 assert_eq!(i.gensymed(z), Symbol::new(SymbolIndex::MAX_AS_U32 - 1));
1368 // gensym of *existing* string gets new number:
1369 let d = i.intern("dog");
1370 assert_eq!(i.gensymed(d), Symbol::new(SymbolIndex::MAX_AS_U32 - 2));
1374 fn without_first_quote_test() {
1375 GLOBALS.set(&Globals::new(edition::DEFAULT_EDITION), || {
1376 let i = Ident::from_str("'break");
1377 assert_eq!(i.without_first_quote().name, kw::Break);