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,
255 extern_absolute_paths,
257 extern_crate_item_prelude,
268 field_init_shorthand,
286 generic_associated_types,
293 hexagon_target_feature,
295 homogeneous_aggregate,
309 if_while_or_patterns,
311 impl_header_lifetime_elision,
312 impl_trait_in_bindings,
318 inclusive_range_syntax,
319 infer_outlives_requirements,
320 infer_static_outlives_requirements,
327 irrefutable_let_patterns,
330 issue_5723_bootstrap,
331 issue_tracker_base_url,
346 link_llvm_intrinsics,
353 macro_at_most_once_rep,
356 macro_lifetime_matcher,
357 macro_literal_matcher,
368 match_beginning_vert,
369 match_default_bindings,
379 movbe_target_feature,
413 omit_gdb_pretty_printer_section,
420 optin_builtin_traits,
428 overlapping_marker_traits,
433 panic_implementation,
449 poll_with_tls_context,
450 powerpc_target_feature,
451 precise_pointer_size_matching,
455 proc_dash_macro: "proc-macro",
457 proc_macro_attribute,
464 proc_macro_non_items,
465 proc_macro_path_invoc,
469 quad_precision_float,
482 reexport_test_harness_main,
492 re_rebalance_coherence,
503 rustc_allocator_nounwind,
504 rustc_allow_const_fn_ptr,
505 rustc_args_required_const,
508 rustc_const_unstable,
509 rustc_conversion_suggestion,
510 rustc_copy_clone_marker,
513 rustc_diagnostic_macros,
515 rustc_doc_only_macro,
516 rustc_dump_env_program_clauses,
517 rustc_dump_program_clauses,
518 rustc_dump_user_substs,
520 rustc_expected_cgu_reuse,
521 rustc_if_this_changed,
522 rustc_inherit_overflow_checks,
524 rustc_layout_scalar_valid_range_end,
525 rustc_layout_scalar_valid_range_start,
527 rustc_nonnull_optimization_guaranteed,
528 rustc_object_lifetime_default,
529 rustc_on_unimplemented,
532 rustc_partition_codegened,
533 rustc_partition_reused,
535 rustc_peek_definite_init,
536 rustc_peek_maybe_init,
537 rustc_peek_maybe_uninit,
539 rustc_proc_macro_decls,
543 rustc_std_internal_symbol,
547 rustc_then_this_would_need,
548 rustc_transparent_macro,
552 rust_eh_unwind_resume,
554 __rust_unstable_column,
555 rvalue_static_promotion,
571 sse4a_target_feature,
581 stmt_expr_attributes,
583 struct_field_attributes,
594 termination_trait_test,
597 test_accepted_feature,
599 test_removed_feature,
615 type_alias_enum_variants,
625 underscore_const_names,
627 underscore_lifetimes,
629 universal_impl_trait,
632 unrestricted_attribute_tokens,
633 unsafe_destructor_blind_to_params,
636 unsized_tuple_coercion,
651 visible_private_types,
654 warn_directory_ownership,
664 #[derive(Copy, Clone, Eq)]
672 /// Constructs a new identifier from a symbol and a span.
673 pub const fn new(name: Symbol, span: Span) -> Ident {
677 /// Constructs a new identifier with an empty syntax context.
679 pub const fn with_empty_ctxt(name: Symbol) -> Ident {
680 Ident::new(name, DUMMY_SP)
684 pub fn invalid() -> Ident {
685 Ident::with_empty_ctxt(kw::Invalid)
688 /// Maps an interned string to an identifier with an empty syntax context.
689 pub fn from_interned_str(string: InternedString) -> Ident {
690 Ident::with_empty_ctxt(string.as_symbol())
693 /// Maps a string to an identifier with an empty span.
694 pub fn from_str(string: &str) -> Ident {
695 Ident::with_empty_ctxt(Symbol::intern(string))
698 /// Maps a string and a span to an identifier.
699 pub fn from_str_and_span(string: &str, span: Span) -> Ident {
700 Ident::new(Symbol::intern(string), span)
703 /// Replaces `lo` and `hi` with those from `span`, but keep hygiene context.
704 pub fn with_span_pos(self, span: Span) -> Ident {
705 Ident::new(self.name, span.with_ctxt(self.span.ctxt()))
708 pub fn without_first_quote(self) -> Ident {
709 Ident::new(Symbol::intern(self.as_str().trim_start_matches('\'')), self.span)
712 /// "Normalize" ident for use in comparisons using "item hygiene".
713 /// Identifiers with same string value become same if they came from the same "modern" macro
714 /// (e.g., `macro` item, but not `macro_rules` item) and stay different if they came from
715 /// different "modern" macros.
716 /// Technically, this operation strips all non-opaque marks from ident's syntactic context.
717 pub fn modern(self) -> Ident {
718 Ident::new(self.name, self.span.modern())
721 /// "Normalize" ident for use in comparisons using "local variable hygiene".
722 /// Identifiers with same string value become same if they came from the same non-transparent
723 /// macro (e.g., `macro` or `macro_rules!` items) and stay different if they came from different
724 /// non-transparent macros.
725 /// Technically, this operation strips all transparent marks from ident's syntactic context.
726 pub fn modern_and_legacy(self) -> Ident {
727 Ident::new(self.name, self.span.modern_and_legacy())
730 /// Transforms an identifier into one with the same name, but gensymed.
731 pub fn gensym(self) -> Ident {
732 let name = with_interner(|interner| interner.gensymed(self.name));
733 Ident::new(name, self.span)
736 /// Transforms an underscore identifier into one with the same name, but
737 /// gensymed. Leaves non-underscore identifiers unchanged.
738 pub fn gensym_if_underscore(self) -> Ident {
739 if self.name == kw::Underscore { self.gensym() } else { self }
742 // WARNING: this function is deprecated and will be removed in the future.
743 pub fn is_gensymed(self) -> bool {
744 with_interner(|interner| interner.is_gensymed(self.name))
747 pub fn as_str(self) -> LocalInternedString {
751 pub fn as_interned_str(self) -> InternedString {
752 self.name.as_interned_str()
756 impl PartialEq for Ident {
757 fn eq(&self, rhs: &Self) -> bool {
758 self.name == rhs.name && self.span.ctxt() == rhs.span.ctxt()
762 impl Hash for Ident {
763 fn hash<H: Hasher>(&self, state: &mut H) {
764 self.name.hash(state);
765 self.span.ctxt().hash(state);
769 impl fmt::Debug for Ident {
770 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
771 write!(f, "{}{:?}", self.name, self.span.ctxt())
775 impl fmt::Display for Ident {
776 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
777 fmt::Display::fmt(&self.name, f)
781 impl Encodable for Ident {
782 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
783 if self.span.ctxt().modern() == SyntaxContext::empty() {
784 s.emit_str(&self.as_str())
785 } else { // FIXME(jseyfried): intercrate hygiene
786 let mut string = "#".to_owned();
787 string.push_str(&self.as_str());
793 impl Decodable for Ident {
794 fn decode<D: Decoder>(d: &mut D) -> Result<Ident, D::Error> {
795 let string = d.read_str()?;
796 Ok(if !string.starts_with('#') {
797 Ident::from_str(&string)
798 } else { // FIXME(jseyfried): intercrate hygiene
799 Ident::from_str(&string[1..]).gensym()
804 /// A symbol is an interned or gensymed string. A gensym is a symbol that is
805 /// never equal to any other symbol.
807 /// Conceptually, a gensym can be thought of as a normal symbol with an
808 /// invisible unique suffix. Gensyms are useful when creating new identifiers
809 /// that must not match any existing identifiers, e.g. during macro expansion
810 /// and syntax desugaring. Because gensyms should always be identifiers, all
811 /// gensym operations are on `Ident` rather than `Symbol`. (Indeed, in the
812 /// future the gensym-ness may be moved from `Symbol` to hygiene data.)
816 /// assert_eq!(Ident::from_str("x"), Ident::from_str("x"))
817 /// assert_ne!(Ident::from_str("x").gensym(), Ident::from_str("x"))
818 /// assert_ne!(Ident::from_str("x").gensym(), Ident::from_str("x").gensym())
820 /// Internally, a symbol is implemented as an index, and all operations
821 /// (including hashing, equality, and ordering) operate on that index. The use
822 /// of `newtype_index!` means that `Option<Symbol>` only takes up 4 bytes,
823 /// because `newtype_index!` reserves the last 256 values for tagging purposes.
825 /// Note that `Symbol` cannot directly be a `newtype_index!` because it
826 /// implements `fmt::Debug`, `Encodable`, and `Decodable` in special ways.
827 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
828 pub struct Symbol(SymbolIndex);
831 pub struct SymbolIndex { .. }
835 const fn new(n: u32) -> Self {
836 Symbol(SymbolIndex::from_u32_const(n))
839 /// Maps a string to its interned representation.
840 pub fn intern(string: &str) -> Self {
841 with_interner(|interner| interner.intern(string))
844 pub fn as_str(self) -> LocalInternedString {
845 with_interner(|interner| unsafe {
846 LocalInternedString {
847 string: std::mem::transmute::<&str, &str>(interner.get(self))
852 pub fn as_interned_str(self) -> InternedString {
853 with_interner(|interner| InternedString {
854 symbol: interner.interned(self)
858 pub fn as_u32(self) -> u32 {
863 impl fmt::Debug for Symbol {
864 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
865 let is_gensymed = with_interner(|interner| interner.is_gensymed(*self));
867 write!(f, "{}({:?})", self, self.0)
869 write!(f, "{}", self)
874 impl fmt::Display for Symbol {
875 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
876 fmt::Display::fmt(&self.as_str(), f)
880 impl Encodable for Symbol {
881 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
882 s.emit_str(&self.as_str())
886 impl Decodable for Symbol {
887 fn decode<D: Decoder>(d: &mut D) -> Result<Symbol, D::Error> {
888 Ok(Symbol::intern(&d.read_str()?))
892 // The `&'static str`s in this type actually point into the arena.
894 // Note that normal symbols are indexed upward from 0, and gensyms are indexed
895 // downward from SymbolIndex::MAX_AS_U32.
897 pub struct Interner {
898 arena: DroplessArena,
899 names: FxHashMap<&'static str, Symbol>,
900 strings: Vec<&'static str>,
901 gensyms: Vec<Symbol>,
905 fn prefill(init: &[&'static str]) -> Self {
906 let symbols = (0 .. init.len() as u32).map(Symbol::new);
908 strings: init.to_vec(),
909 names: init.iter().copied().zip(symbols).collect(),
914 pub fn intern(&mut self, string: &str) -> Symbol {
915 if let Some(&name) = self.names.get(string) {
919 let name = Symbol::new(self.strings.len() as u32);
921 // `from_utf8_unchecked` is safe since we just allocated a `&str` which is known to be
923 let string: &str = unsafe {
924 str::from_utf8_unchecked(self.arena.alloc_slice(string.as_bytes()))
926 // It is safe to extend the arena allocation to `'static` because we only access
927 // these while the arena is still alive.
928 let string: &'static str = unsafe {
929 &*(string as *const str)
931 self.strings.push(string);
932 self.names.insert(string, name);
936 fn interned(&self, symbol: Symbol) -> Symbol {
937 if (symbol.0.as_usize()) < self.strings.len() {
940 self.gensyms[(SymbolIndex::MAX_AS_U32 - symbol.0.as_u32()) as usize]
944 fn gensymed(&mut self, symbol: Symbol) -> Symbol {
945 self.gensyms.push(symbol);
946 Symbol::new(SymbolIndex::MAX_AS_U32 - self.gensyms.len() as u32 + 1)
949 fn is_gensymed(&mut self, symbol: Symbol) -> bool {
950 symbol.0.as_usize() >= self.strings.len()
953 // Get the symbol as a string. `Symbol::as_str()` should be used in
954 // preference to this function.
955 pub fn get(&self, symbol: Symbol) -> &str {
956 match self.strings.get(symbol.0.as_usize()) {
957 Some(string) => string,
959 let symbol = self.gensyms[(SymbolIndex::MAX_AS_U32 - symbol.0.as_u32()) as usize];
960 self.strings[symbol.0.as_usize()]
966 // This module has a very short name because it's used a lot.
972 // This module has a very short name because it's used a lot.
974 use std::convert::TryInto;
979 // Get the symbol for an integer. The first few non-negative integers each
980 // have a static symbol and therefore are fast.
981 pub fn integer<N: TryInto<usize> + Copy + ToString>(n: N) -> Symbol {
982 if let Result::Ok(idx) = n.try_into() {
983 if let Option::Some(&sym) = digits_array.get(idx) {
987 Symbol::intern(&n.to_string())
992 fn is_used_keyword_2018(self) -> bool {
996 fn is_unused_keyword_2018(self) -> bool {
997 self >= kw::Async && self <= kw::Try
1000 /// Used for sanity checking rustdoc keyword sections.
1001 pub fn is_doc_keyword(self) -> bool {
1007 // Returns `true` for reserved identifiers used internally for elided lifetimes,
1008 // unnamed method parameters, crate root module, error recovery etc.
1009 pub fn is_special(self) -> bool {
1010 self.name <= kw::Underscore
1013 /// Returns `true` if the token is a keyword used in the language.
1014 pub fn is_used_keyword(self) -> bool {
1015 // Note: `span.edition()` is relatively expensive, don't call it unless necessary.
1016 self.name >= kw::As && self.name <= kw::While ||
1017 self.name.is_used_keyword_2018() && self.span.rust_2018()
1020 /// Returns `true` if the token is a keyword reserved for possible future use.
1021 pub fn is_unused_keyword(self) -> bool {
1022 // Note: `span.edition()` is relatively expensive, don't call it unless necessary.
1023 self.name >= kw::Abstract && self.name <= kw::Yield ||
1024 self.name.is_unused_keyword_2018() && self.span.rust_2018()
1027 /// Returns `true` if the token is either a special identifier or a keyword.
1028 pub fn is_reserved(self) -> bool {
1029 self.is_special() || self.is_used_keyword() || self.is_unused_keyword()
1032 /// A keyword or reserved identifier that can be used as a path segment.
1033 pub fn is_path_segment_keyword(self) -> bool {
1034 self.name == kw::Super ||
1035 self.name == kw::SelfLower ||
1036 self.name == kw::SelfUpper ||
1037 self.name == kw::Crate ||
1038 self.name == kw::PathRoot ||
1039 self.name == kw::DollarCrate
1042 /// This identifier can be a raw identifier.
1043 pub fn can_be_raw(self) -> bool {
1044 self.name != kw::Invalid && self.name != kw::Underscore &&
1045 !self.is_path_segment_keyword()
1048 /// We see this identifier in a normal identifier position, like variable name or a type.
1049 /// How was it written originally? Did it use the raw form? Let's try to guess.
1050 pub fn is_raw_guess(self) -> bool {
1051 self.can_be_raw() && self.is_reserved()
1055 // If an interner exists, return it. Otherwise, prepare a fresh one.
1057 fn with_interner<T, F: FnOnce(&mut Interner) -> T>(f: F) -> T {
1058 GLOBALS.with(|globals| f(&mut *globals.symbol_interner.lock()))
1061 /// An alternative to `Symbol` and `InternedString`, useful when the chars
1062 /// within the symbol need to be accessed. It is best used for temporary
1065 /// Because the interner outlives any thread which uses this type, we can
1066 /// safely treat `string` which points to interner data, as an immortal string,
1067 /// as long as this type never crosses between threads.
1069 // FIXME: ensure that the interner outlives any thread which uses
1070 // `LocalInternedString`, by creating a new thread right after constructing the
1072 #[derive(Clone, Copy, Hash, PartialOrd, Eq, Ord)]
1073 pub struct LocalInternedString {
1074 string: &'static str,
1077 impl LocalInternedString {
1078 /// Maps a string to its interned representation.
1079 pub fn intern(string: &str) -> Self {
1080 let string = with_interner(|interner| {
1081 let symbol = interner.intern(string);
1082 interner.strings[symbol.0.as_usize()]
1084 LocalInternedString {
1085 string: unsafe { std::mem::transmute::<&str, &str>(string) }
1089 pub fn as_interned_str(self) -> InternedString {
1091 symbol: Symbol::intern(self.string)
1095 pub fn get(&self) -> &str {
1096 // This returns a valid string since we ensure that `self` outlives the interner
1097 // by creating the interner on a thread which outlives threads which can access it.
1098 // This type cannot move to a thread which outlives the interner since it does
1099 // not implement Send.
1104 impl<U: ?Sized> std::convert::AsRef<U> for LocalInternedString
1106 str: std::convert::AsRef<U>
1108 fn as_ref(&self) -> &U {
1109 self.string.as_ref()
1113 impl<T: std::ops::Deref<Target = str>> std::cmp::PartialEq<T> for LocalInternedString {
1114 fn eq(&self, other: &T) -> bool {
1115 self.string == other.deref()
1119 impl std::cmp::PartialEq<LocalInternedString> for str {
1120 fn eq(&self, other: &LocalInternedString) -> bool {
1121 self == other.string
1125 impl<'a> std::cmp::PartialEq<LocalInternedString> for &'a str {
1126 fn eq(&self, other: &LocalInternedString) -> bool {
1127 *self == other.string
1131 impl std::cmp::PartialEq<LocalInternedString> for String {
1132 fn eq(&self, other: &LocalInternedString) -> bool {
1133 self == other.string
1137 impl<'a> std::cmp::PartialEq<LocalInternedString> for &'a String {
1138 fn eq(&self, other: &LocalInternedString) -> bool {
1139 *self == other.string
1143 impl !Send for LocalInternedString {}
1144 impl !Sync for LocalInternedString {}
1146 impl std::ops::Deref for LocalInternedString {
1148 fn deref(&self) -> &str { self.string }
1151 impl fmt::Debug for LocalInternedString {
1152 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1153 fmt::Debug::fmt(self.string, f)
1157 impl fmt::Display for LocalInternedString {
1158 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1159 fmt::Display::fmt(self.string, f)
1163 impl Decodable for LocalInternedString {
1164 fn decode<D: Decoder>(d: &mut D) -> Result<LocalInternedString, D::Error> {
1165 Ok(LocalInternedString::intern(&d.read_str()?))
1169 impl Encodable for LocalInternedString {
1170 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1171 s.emit_str(self.string)
1175 /// An alternative to `Symbol` that is focused on string contents. It has two
1176 /// main differences to `Symbol`.
1178 /// First, its implementations of `Hash`, `PartialOrd` and `Ord` work with the
1179 /// string chars rather than the symbol integer. This is useful when hash
1180 /// stability is required across compile sessions, or a guaranteed sort
1181 /// ordering is required.
1183 /// Second, gensym-ness is irrelevant. E.g.:
1185 /// assert_ne!(Symbol::gensym("x"), Symbol::gensym("x"))
1186 /// assert_eq!(Symbol::gensym("x").as_interned_str(), Symbol::gensym("x").as_interned_str())
1188 #[derive(Clone, Copy, PartialEq, Eq)]
1189 pub struct InternedString {
1193 impl InternedString {
1194 /// Maps a string to its interned representation.
1195 pub fn intern(string: &str) -> Self {
1197 symbol: Symbol::intern(string)
1201 pub fn with<F: FnOnce(&str) -> R, R>(self, f: F) -> R {
1202 let str = with_interner(|interner| {
1203 interner.get(self.symbol) as *const str
1205 // This is safe because the interner keeps string alive until it is dropped.
1206 // We can access it because we know the interner is still alive since we use a
1207 // scoped thread local to access it, and it was alive at the beginning of this scope
1211 fn with2<F: FnOnce(&str, &str) -> R, R>(self, other: &InternedString, f: F) -> R {
1212 let (self_str, other_str) = with_interner(|interner| {
1213 (interner.get(self.symbol) as *const str,
1214 interner.get(other.symbol) as *const str)
1216 // This is safe for the same reason that `with` is safe.
1217 unsafe { f(&*self_str, &*other_str) }
1220 pub fn as_symbol(self) -> Symbol {
1224 pub fn as_str(self) -> LocalInternedString {
1225 self.symbol.as_str()
1229 impl Hash for InternedString {
1230 fn hash<H: Hasher>(&self, state: &mut H) {
1231 self.with(|str| str.hash(state))
1235 impl PartialOrd<InternedString> for InternedString {
1236 fn partial_cmp(&self, other: &InternedString) -> Option<Ordering> {
1237 if self.symbol == other.symbol {
1238 return Some(Ordering::Equal);
1240 self.with2(other, |self_str, other_str| self_str.partial_cmp(other_str))
1244 impl Ord for InternedString {
1245 fn cmp(&self, other: &InternedString) -> Ordering {
1246 if self.symbol == other.symbol {
1247 return Ordering::Equal;
1249 self.with2(other, |self_str, other_str| self_str.cmp(other_str))
1253 impl fmt::Debug for InternedString {
1254 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1255 self.with(|str| fmt::Debug::fmt(&str, f))
1259 impl fmt::Display for InternedString {
1260 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1261 self.with(|str| fmt::Display::fmt(&str, f))
1265 impl Decodable for InternedString {
1266 fn decode<D: Decoder>(d: &mut D) -> Result<InternedString, D::Error> {
1267 Ok(InternedString::intern(&d.read_str()?))
1271 impl Encodable for InternedString {
1272 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1273 self.with(|string| s.emit_str(string))
1284 fn interner_tests() {
1285 let mut i: Interner = Interner::default();
1286 // first one is zero:
1287 assert_eq!(i.intern("dog"), Symbol::new(0));
1288 // re-use gets the same entry:
1289 assert_eq!(i.intern("dog"), Symbol::new(0));
1290 // different string gets a different #:
1291 assert_eq!(i.intern("cat"), Symbol::new(1));
1292 assert_eq!(i.intern("cat"), Symbol::new(1));
1293 // dog is still at zero
1294 assert_eq!(i.intern("dog"), Symbol::new(0));
1295 let z = i.intern("zebra");
1296 assert_eq!(i.gensymed(z), Symbol::new(SymbolIndex::MAX_AS_U32));
1297 // gensym of same string gets new number:
1298 assert_eq!(i.gensymed(z), Symbol::new(SymbolIndex::MAX_AS_U32 - 1));
1299 // gensym of *existing* string gets new number:
1300 let d = i.intern("dog");
1301 assert_eq!(i.gensymed(d), Symbol::new(SymbolIndex::MAX_AS_U32 - 2));
1305 fn without_first_quote_test() {
1306 GLOBALS.set(&Globals::new(edition::DEFAULT_EDITION), || {
1307 let i = Ident::from_str("'break");
1308 assert_eq!(i.without_first_quote().name, kw::Break);