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_self_types,
144 associated_type_defaults,
150 augmented_assignments,
151 automatically_derived,
152 avx512_target_feature,
157 bind_by_move_pattern_guards,
159 borrowck_graphviz_postflow,
160 borrowck_graphviz_preflow,
163 braced_empty_structs,
170 cfg_target_has_atomic,
171 cfg_target_thread_local,
177 closure_to_fn_coercion,
179 cmpxchg16b_target_feature,
184 conservative_impl_trait,
186 const_compare_raw_pointers,
194 const_raw_ptr_to_usize_cast,
205 crate_visibility_modifier,
208 custom_inner_attributes,
209 custom_test_frameworks,
213 default_lib_allocator,
214 default_type_parameter_fallback,
227 document_private_items,
228 dotdoteq_in_patterns,
229 dotdot_in_tuple_patterns,
230 double_braced_crate: "{{crate}}",
231 double_braced_impl: "{{impl}}",
232 double_braced_misc: "{{misc}}",
233 double_braced_closure: "{{closure}}",
234 double_braced_constructor: "{{constructor}}",
235 double_braced_constant: "{{constant}}",
236 double_braced_opaque: "{{opaque}}",
238 dropck_parametricity,
249 exclusive_range_pattern,
250 exhaustive_integer_patterns,
256 extern_absolute_paths,
258 extern_crate_item_prelude,
269 field_init_shorthand,
287 generic_associated_types,
294 hexagon_target_feature,
296 homogeneous_aggregate,
310 if_while_or_patterns,
312 impl_header_lifetime_elision,
313 impl_trait_in_bindings,
319 inclusive_range_syntax,
320 infer_outlives_requirements,
321 infer_static_outlives_requirements,
328 irrefutable_let_patterns,
331 issue_5723_bootstrap,
332 issue_tracker_base_url,
349 link_llvm_intrinsics,
357 macro_at_most_once_rep,
360 macro_lifetime_matcher,
361 macro_literal_matcher,
372 match_beginning_vert,
373 match_default_bindings,
383 movbe_target_feature,
417 omit_gdb_pretty_printer_section,
424 optin_builtin_traits,
432 overlapping_marker_traits,
437 panic_implementation,
454 poll_with_tls_context,
455 powerpc_target_feature,
456 precise_pointer_size_matching,
460 proc_dash_macro: "proc-macro",
462 proc_macro_attribute,
469 proc_macro_non_items,
470 proc_macro_path_invoc,
474 quad_precision_float,
487 reexport_test_harness_main,
497 re_rebalance_coherence,
508 rustc_allocator_nounwind,
509 rustc_allow_const_fn_ptr,
510 rustc_args_required_const,
513 rustc_const_unstable,
514 rustc_conversion_suggestion,
515 rustc_copy_clone_marker,
518 rustc_diagnostic_macros,
520 rustc_doc_only_macro,
521 rustc_dump_env_program_clauses,
522 rustc_dump_program_clauses,
523 rustc_dump_user_substs,
525 rustc_expected_cgu_reuse,
526 rustc_if_this_changed,
527 rustc_inherit_overflow_checks,
529 rustc_layout_scalar_valid_range_end,
530 rustc_layout_scalar_valid_range_start,
532 rustc_nonnull_optimization_guaranteed,
533 rustc_object_lifetime_default,
534 rustc_on_unimplemented,
537 rustc_partition_codegened,
538 rustc_partition_reused,
540 rustc_peek_definite_init,
541 rustc_peek_maybe_init,
542 rustc_peek_maybe_uninit,
544 rustc_proc_macro_decls,
548 rustc_std_internal_symbol,
552 rustc_then_this_would_need,
553 rustc_transparent_macro,
557 rust_eh_unwind_resume,
559 __rust_unstable_column,
560 rvalue_static_promotion,
576 sse4a_target_feature,
587 stmt_expr_attributes,
589 struct_field_attributes,
600 termination_trait_test,
603 test_accepted_feature,
605 test_removed_feature,
622 type_alias_enum_variants,
632 underscore_const_names,
634 underscore_lifetimes,
636 universal_impl_trait,
639 unrestricted_attribute_tokens,
640 unsafe_destructor_blind_to_params,
643 unsized_tuple_coercion,
658 visible_private_types,
661 warn_directory_ownership,
671 #[derive(Copy, Clone, Eq)]
679 /// Constructs a new identifier from a symbol and a span.
680 pub const fn new(name: Symbol, span: Span) -> Ident {
684 /// Constructs a new identifier with an empty syntax context.
686 pub const fn with_empty_ctxt(name: Symbol) -> Ident {
687 Ident::new(name, DUMMY_SP)
691 pub fn invalid() -> Ident {
692 Ident::with_empty_ctxt(kw::Invalid)
695 /// Maps an interned string to an identifier with an empty syntax context.
696 pub fn from_interned_str(string: InternedString) -> Ident {
697 Ident::with_empty_ctxt(string.as_symbol())
700 /// Maps a string to an identifier with an empty span.
701 pub fn from_str(string: &str) -> Ident {
702 Ident::with_empty_ctxt(Symbol::intern(string))
705 /// Maps a string and a span to an identifier.
706 pub fn from_str_and_span(string: &str, span: Span) -> Ident {
707 Ident::new(Symbol::intern(string), span)
710 /// Replaces `lo` and `hi` with those from `span`, but keep hygiene context.
711 pub fn with_span_pos(self, span: Span) -> Ident {
712 Ident::new(self.name, span.with_ctxt(self.span.ctxt()))
715 pub fn without_first_quote(self) -> Ident {
716 Ident::new(Symbol::intern(self.as_str().trim_start_matches('\'')), self.span)
719 /// "Normalize" ident for use in comparisons using "item hygiene".
720 /// Identifiers with same string value become same if they came from the same "modern" macro
721 /// (e.g., `macro` item, but not `macro_rules` item) and stay different if they came from
722 /// different "modern" macros.
723 /// Technically, this operation strips all non-opaque marks from ident's syntactic context.
724 pub fn modern(self) -> Ident {
725 Ident::new(self.name, self.span.modern())
728 /// "Normalize" ident for use in comparisons using "local variable hygiene".
729 /// Identifiers with same string value become same if they came from the same non-transparent
730 /// macro (e.g., `macro` or `macro_rules!` items) and stay different if they came from different
731 /// non-transparent macros.
732 /// Technically, this operation strips all transparent marks from ident's syntactic context.
733 pub fn modern_and_legacy(self) -> Ident {
734 Ident::new(self.name, self.span.modern_and_legacy())
737 /// Transforms an identifier into one with the same name, but gensymed.
738 pub fn gensym(self) -> Ident {
739 let name = with_interner(|interner| interner.gensymed(self.name));
740 Ident::new(name, self.span)
743 /// Transforms an underscore identifier into one with the same name, but
744 /// gensymed. Leaves non-underscore identifiers unchanged.
745 pub fn gensym_if_underscore(self) -> Ident {
746 if self.name == kw::Underscore { self.gensym() } else { self }
749 // WARNING: this function is deprecated and will be removed in the future.
750 pub fn is_gensymed(self) -> bool {
751 with_interner(|interner| interner.is_gensymed(self.name))
754 pub fn as_str(self) -> LocalInternedString {
758 pub fn as_interned_str(self) -> InternedString {
759 self.name.as_interned_str()
763 impl PartialEq for Ident {
764 fn eq(&self, rhs: &Self) -> bool {
765 self.name == rhs.name && self.span.ctxt() == rhs.span.ctxt()
769 impl Hash for Ident {
770 fn hash<H: Hasher>(&self, state: &mut H) {
771 self.name.hash(state);
772 self.span.ctxt().hash(state);
776 impl fmt::Debug for Ident {
777 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
778 write!(f, "{}{:?}", self.name, self.span.ctxt())
782 impl fmt::Display for Ident {
783 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
784 fmt::Display::fmt(&self.name, f)
788 impl Encodable for Ident {
789 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
790 if self.span.ctxt().modern() == SyntaxContext::empty() {
791 s.emit_str(&self.as_str())
792 } else { // FIXME(jseyfried): intercrate hygiene
793 let mut string = "#".to_owned();
794 string.push_str(&self.as_str());
800 impl Decodable for Ident {
801 fn decode<D: Decoder>(d: &mut D) -> Result<Ident, D::Error> {
802 let string = d.read_str()?;
803 Ok(if !string.starts_with('#') {
804 Ident::from_str(&string)
805 } else { // FIXME(jseyfried): intercrate hygiene
806 Ident::from_str(&string[1..]).gensym()
811 /// A symbol is an interned or gensymed string. A gensym is a symbol that is
812 /// never equal to any other symbol.
814 /// Conceptually, a gensym can be thought of as a normal symbol with an
815 /// invisible unique suffix. Gensyms are useful when creating new identifiers
816 /// that must not match any existing identifiers, e.g. during macro expansion
817 /// and syntax desugaring. Because gensyms should always be identifiers, all
818 /// gensym operations are on `Ident` rather than `Symbol`. (Indeed, in the
819 /// future the gensym-ness may be moved from `Symbol` to hygiene data.)
823 /// assert_eq!(Ident::from_str("x"), Ident::from_str("x"))
824 /// assert_ne!(Ident::from_str("x").gensym(), Ident::from_str("x"))
825 /// assert_ne!(Ident::from_str("x").gensym(), Ident::from_str("x").gensym())
827 /// Internally, a symbol is implemented as an index, and all operations
828 /// (including hashing, equality, and ordering) operate on that index. The use
829 /// of `newtype_index!` means that `Option<Symbol>` only takes up 4 bytes,
830 /// because `newtype_index!` reserves the last 256 values for tagging purposes.
832 /// Note that `Symbol` cannot directly be a `newtype_index!` because it
833 /// implements `fmt::Debug`, `Encodable`, and `Decodable` in special ways.
834 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
835 pub struct Symbol(SymbolIndex);
838 pub struct SymbolIndex { .. }
842 const fn new(n: u32) -> Self {
843 Symbol(SymbolIndex::from_u32_const(n))
846 /// Maps a string to its interned representation.
847 pub fn intern(string: &str) -> Self {
848 with_interner(|interner| interner.intern(string))
851 pub fn as_str(self) -> LocalInternedString {
852 with_interner(|interner| unsafe {
853 LocalInternedString {
854 string: std::mem::transmute::<&str, &str>(interner.get(self))
859 pub fn as_interned_str(self) -> InternedString {
860 with_interner(|interner| InternedString {
861 symbol: interner.interned(self)
865 pub fn as_u32(self) -> u32 {
870 impl fmt::Debug for Symbol {
871 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
872 let is_gensymed = with_interner(|interner| interner.is_gensymed(*self));
874 write!(f, "{}({:?})", self, self.0)
876 write!(f, "{}", self)
881 impl fmt::Display for Symbol {
882 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
883 fmt::Display::fmt(&self.as_str(), f)
887 impl Encodable for Symbol {
888 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
889 s.emit_str(&self.as_str())
893 impl Decodable for Symbol {
894 fn decode<D: Decoder>(d: &mut D) -> Result<Symbol, D::Error> {
895 Ok(Symbol::intern(&d.read_str()?))
899 // The `&'static str`s in this type actually point into the arena.
901 // Note that normal symbols are indexed upward from 0, and gensyms are indexed
902 // downward from SymbolIndex::MAX_AS_U32.
904 pub struct Interner {
905 arena: DroplessArena,
906 names: FxHashMap<&'static str, Symbol>,
907 strings: Vec<&'static str>,
908 gensyms: Vec<Symbol>,
912 fn prefill(init: &[&'static str]) -> Self {
913 let symbols = (0 .. init.len() as u32).map(Symbol::new);
915 strings: init.to_vec(),
916 names: init.iter().copied().zip(symbols).collect(),
921 pub fn intern(&mut self, string: &str) -> Symbol {
922 if let Some(&name) = self.names.get(string) {
926 let name = Symbol::new(self.strings.len() as u32);
928 // `from_utf8_unchecked` is safe since we just allocated a `&str` which is known to be
930 let string: &str = unsafe {
931 str::from_utf8_unchecked(self.arena.alloc_slice(string.as_bytes()))
933 // It is safe to extend the arena allocation to `'static` because we only access
934 // these while the arena is still alive.
935 let string: &'static str = unsafe {
936 &*(string as *const str)
938 self.strings.push(string);
939 self.names.insert(string, name);
943 fn interned(&self, symbol: Symbol) -> Symbol {
944 if (symbol.0.as_usize()) < self.strings.len() {
947 self.gensyms[(SymbolIndex::MAX_AS_U32 - symbol.0.as_u32()) as usize]
951 fn gensymed(&mut self, symbol: Symbol) -> Symbol {
952 self.gensyms.push(symbol);
953 Symbol::new(SymbolIndex::MAX_AS_U32 - self.gensyms.len() as u32 + 1)
956 fn is_gensymed(&mut self, symbol: Symbol) -> bool {
957 symbol.0.as_usize() >= self.strings.len()
960 // Get the symbol as a string. `Symbol::as_str()` should be used in
961 // preference to this function.
962 pub fn get(&self, symbol: Symbol) -> &str {
963 match self.strings.get(symbol.0.as_usize()) {
964 Some(string) => string,
966 let symbol = self.gensyms[(SymbolIndex::MAX_AS_U32 - symbol.0.as_u32()) as usize];
967 self.strings[symbol.0.as_usize()]
973 // This module has a very short name because it's used a lot.
979 // This module has a very short name because it's used a lot.
981 use std::convert::TryInto;
986 // Get the symbol for an integer. The first few non-negative integers each
987 // have a static symbol and therefore are fast.
988 pub fn integer<N: TryInto<usize> + Copy + ToString>(n: N) -> Symbol {
989 if let Result::Ok(idx) = n.try_into() {
990 if let Option::Some(&sym) = digits_array.get(idx) {
994 Symbol::intern(&n.to_string())
999 fn is_used_keyword_2018(self) -> bool {
1003 fn is_unused_keyword_2018(self) -> bool {
1004 self >= kw::Async && self <= kw::Try
1007 /// Used for sanity checking rustdoc keyword sections.
1008 pub fn is_doc_keyword(self) -> bool {
1014 // Returns `true` for reserved identifiers used internally for elided lifetimes,
1015 // unnamed method parameters, crate root module, error recovery etc.
1016 pub fn is_special(self) -> bool {
1017 self.name <= kw::Underscore
1020 /// Returns `true` if the token is a keyword used in the language.
1021 pub fn is_used_keyword(self) -> bool {
1022 // Note: `span.edition()` is relatively expensive, don't call it unless necessary.
1023 self.name >= kw::As && self.name <= kw::While ||
1024 self.name.is_used_keyword_2018() && self.span.rust_2018()
1027 /// Returns `true` if the token is a keyword reserved for possible future use.
1028 pub fn is_unused_keyword(self) -> bool {
1029 // Note: `span.edition()` is relatively expensive, don't call it unless necessary.
1030 self.name >= kw::Abstract && self.name <= kw::Yield ||
1031 self.name.is_unused_keyword_2018() && self.span.rust_2018()
1034 /// Returns `true` if the token is either a special identifier or a keyword.
1035 pub fn is_reserved(self) -> bool {
1036 self.is_special() || self.is_used_keyword() || self.is_unused_keyword()
1039 /// A keyword or reserved identifier that can be used as a path segment.
1040 pub fn is_path_segment_keyword(self) -> bool {
1041 self.name == kw::Super ||
1042 self.name == kw::SelfLower ||
1043 self.name == kw::SelfUpper ||
1044 self.name == kw::Crate ||
1045 self.name == kw::PathRoot ||
1046 self.name == kw::DollarCrate
1049 /// This identifier can be a raw identifier.
1050 pub fn can_be_raw(self) -> bool {
1051 self.name != kw::Invalid && self.name != kw::Underscore &&
1052 !self.is_path_segment_keyword()
1055 /// We see this identifier in a normal identifier position, like variable name or a type.
1056 /// How was it written originally? Did it use the raw form? Let's try to guess.
1057 pub fn is_raw_guess(self) -> bool {
1058 self.can_be_raw() && self.is_reserved()
1062 // If an interner exists, return it. Otherwise, prepare a fresh one.
1064 fn with_interner<T, F: FnOnce(&mut Interner) -> T>(f: F) -> T {
1065 GLOBALS.with(|globals| f(&mut *globals.symbol_interner.lock()))
1068 /// An alternative to `Symbol` and `InternedString`, useful when the chars
1069 /// within the symbol need to be accessed. It is best used for temporary
1072 /// Because the interner outlives any thread which uses this type, we can
1073 /// safely treat `string` which points to interner data, as an immortal string,
1074 /// as long as this type never crosses between threads.
1076 // FIXME: ensure that the interner outlives any thread which uses
1077 // `LocalInternedString`, by creating a new thread right after constructing the
1079 #[derive(Clone, Copy, Hash, PartialOrd, Eq, Ord)]
1080 pub struct LocalInternedString {
1081 string: &'static str,
1084 impl LocalInternedString {
1085 /// Maps a string to its interned representation.
1086 pub fn intern(string: &str) -> Self {
1087 let string = with_interner(|interner| {
1088 let symbol = interner.intern(string);
1089 interner.strings[symbol.0.as_usize()]
1091 LocalInternedString {
1092 string: unsafe { std::mem::transmute::<&str, &str>(string) }
1096 pub fn as_interned_str(self) -> InternedString {
1098 symbol: Symbol::intern(self.string)
1102 pub fn get(&self) -> &str {
1103 // This returns a valid string since we ensure that `self` outlives the interner
1104 // by creating the interner on a thread which outlives threads which can access it.
1105 // This type cannot move to a thread which outlives the interner since it does
1106 // not implement Send.
1111 impl<U: ?Sized> std::convert::AsRef<U> for LocalInternedString
1113 str: std::convert::AsRef<U>
1115 fn as_ref(&self) -> &U {
1116 self.string.as_ref()
1120 impl<T: std::ops::Deref<Target = str>> std::cmp::PartialEq<T> for LocalInternedString {
1121 fn eq(&self, other: &T) -> bool {
1122 self.string == other.deref()
1126 impl std::cmp::PartialEq<LocalInternedString> for str {
1127 fn eq(&self, other: &LocalInternedString) -> bool {
1128 self == other.string
1132 impl<'a> std::cmp::PartialEq<LocalInternedString> for &'a str {
1133 fn eq(&self, other: &LocalInternedString) -> bool {
1134 *self == other.string
1138 impl std::cmp::PartialEq<LocalInternedString> for String {
1139 fn eq(&self, other: &LocalInternedString) -> bool {
1140 self == other.string
1144 impl<'a> std::cmp::PartialEq<LocalInternedString> for &'a String {
1145 fn eq(&self, other: &LocalInternedString) -> bool {
1146 *self == other.string
1150 impl !Send for LocalInternedString {}
1151 impl !Sync for LocalInternedString {}
1153 impl std::ops::Deref for LocalInternedString {
1155 fn deref(&self) -> &str { self.string }
1158 impl fmt::Debug for LocalInternedString {
1159 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1160 fmt::Debug::fmt(self.string, f)
1164 impl fmt::Display for LocalInternedString {
1165 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1166 fmt::Display::fmt(self.string, f)
1170 impl Decodable for LocalInternedString {
1171 fn decode<D: Decoder>(d: &mut D) -> Result<LocalInternedString, D::Error> {
1172 Ok(LocalInternedString::intern(&d.read_str()?))
1176 impl Encodable for LocalInternedString {
1177 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1178 s.emit_str(self.string)
1182 /// An alternative to `Symbol` that is focused on string contents. It has two
1183 /// main differences to `Symbol`.
1185 /// First, its implementations of `Hash`, `PartialOrd` and `Ord` work with the
1186 /// string chars rather than the symbol integer. This is useful when hash
1187 /// stability is required across compile sessions, or a guaranteed sort
1188 /// ordering is required.
1190 /// Second, gensym-ness is irrelevant. E.g.:
1192 /// assert_ne!(Symbol::gensym("x"), Symbol::gensym("x"))
1193 /// assert_eq!(Symbol::gensym("x").as_interned_str(), Symbol::gensym("x").as_interned_str())
1195 #[derive(Clone, Copy, PartialEq, Eq)]
1196 pub struct InternedString {
1200 impl InternedString {
1201 /// Maps a string to its interned representation.
1202 pub fn intern(string: &str) -> Self {
1204 symbol: Symbol::intern(string)
1208 pub fn with<F: FnOnce(&str) -> R, R>(self, f: F) -> R {
1209 let str = with_interner(|interner| {
1210 interner.get(self.symbol) as *const str
1212 // This is safe because the interner keeps string alive until it is dropped.
1213 // We can access it because we know the interner is still alive since we use a
1214 // scoped thread local to access it, and it was alive at the beginning of this scope
1218 fn with2<F: FnOnce(&str, &str) -> R, R>(self, other: &InternedString, f: F) -> R {
1219 let (self_str, other_str) = with_interner(|interner| {
1220 (interner.get(self.symbol) as *const str,
1221 interner.get(other.symbol) as *const str)
1223 // This is safe for the same reason that `with` is safe.
1224 unsafe { f(&*self_str, &*other_str) }
1227 pub fn as_symbol(self) -> Symbol {
1231 pub fn as_str(self) -> LocalInternedString {
1232 self.symbol.as_str()
1236 impl Hash for InternedString {
1237 fn hash<H: Hasher>(&self, state: &mut H) {
1238 self.with(|str| str.hash(state))
1242 impl PartialOrd<InternedString> for InternedString {
1243 fn partial_cmp(&self, other: &InternedString) -> Option<Ordering> {
1244 if self.symbol == other.symbol {
1245 return Some(Ordering::Equal);
1247 self.with2(other, |self_str, other_str| self_str.partial_cmp(other_str))
1251 impl Ord for InternedString {
1252 fn cmp(&self, other: &InternedString) -> Ordering {
1253 if self.symbol == other.symbol {
1254 return Ordering::Equal;
1256 self.with2(other, |self_str, other_str| self_str.cmp(other_str))
1260 impl fmt::Debug for InternedString {
1261 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1262 self.with(|str| fmt::Debug::fmt(&str, f))
1266 impl fmt::Display for InternedString {
1267 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1268 self.with(|str| fmt::Display::fmt(&str, f))
1272 impl Decodable for InternedString {
1273 fn decode<D: Decoder>(d: &mut D) -> Result<InternedString, D::Error> {
1274 Ok(InternedString::intern(&d.read_str()?))
1278 impl Encodable for InternedString {
1279 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1280 self.with(|string| s.emit_str(string))
1291 fn interner_tests() {
1292 let mut i: Interner = Interner::default();
1293 // first one is zero:
1294 assert_eq!(i.intern("dog"), Symbol::new(0));
1295 // re-use gets the same entry:
1296 assert_eq!(i.intern("dog"), Symbol::new(0));
1297 // different string gets a different #:
1298 assert_eq!(i.intern("cat"), Symbol::new(1));
1299 assert_eq!(i.intern("cat"), Symbol::new(1));
1300 // dog is still at zero
1301 assert_eq!(i.intern("dog"), Symbol::new(0));
1302 let z = i.intern("zebra");
1303 assert_eq!(i.gensymed(z), Symbol::new(SymbolIndex::MAX_AS_U32));
1304 // gensym of same string gets new number:
1305 assert_eq!(i.gensymed(z), Symbol::new(SymbolIndex::MAX_AS_U32 - 1));
1306 // gensym of *existing* string gets new number:
1307 let d = i.intern("dog");
1308 assert_eq!(i.gensymed(d), Symbol::new(SymbolIndex::MAX_AS_U32 - 2));
1312 fn without_first_quote_test() {
1313 GLOBALS.set(&Globals::new(edition::DEFAULT_EDITION), || {
1314 let i = Ident::from_str("'break");
1315 assert_eq!(i.without_first_quote().name, kw::Break);