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};
14 use std::cmp::{PartialEq, Ordering, PartialOrd, Ord};
15 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 aarch64_target_feature,
109 abi_msp430_interrupt,
117 advanced_slice_patterns,
129 allow_internal_unsafe,
130 allow_internal_unstable,
131 allow_internal_unstable_backcompat_hack,
134 arbitrary_self_types,
138 associated_type_defaults,
144 augmented_assignments,
145 automatically_derived,
146 avx512_target_feature,
149 bind_by_move_pattern_guards,
151 borrowck_graphviz_postflow,
152 borrowck_graphviz_preflow,
155 braced_empty_structs,
162 cfg_target_has_atomic,
163 cfg_target_thread_local,
168 closure_to_fn_coercion,
169 cmpxchg16b_target_feature,
174 conservative_impl_trait,
176 const_compare_raw_pointers,
184 const_raw_ptr_to_usize_cast,
195 crate_visibility_modifier,
198 custom_inner_attributes,
199 custom_test_frameworks,
202 default_lib_allocator,
203 default_type_parameter_fallback,
214 document_private_items,
215 dotdoteq_in_patterns,
216 dotdot_in_tuple_patterns,
217 double_braced_crate: "{{crate}}",
218 double_braced_impl: "{{impl}}",
219 double_braced_misc: "{{misc}}",
220 double_braced_closure: "{{closure}}",
221 double_braced_constructor: "{{constructor}}",
222 double_braced_constant: "{{constant}}",
223 double_braced_opaque: "{{opaque}}",
225 dropck_parametricity,
234 exclusive_range_pattern,
235 exhaustive_integer_patterns,
240 extern_absolute_paths,
242 extern_crate_item_prelude,
250 field_init_shorthand,
264 generic_associated_types,
269 hexagon_target_feature,
271 homogeneous_aggregate,
285 if_while_or_patterns,
287 impl_header_lifetime_elision,
288 impl_trait_in_bindings,
292 inclusive_range_syntax,
293 infer_outlives_requirements,
294 infer_static_outlives_requirements,
301 irrefutable_let_patterns,
304 issue_5723_bootstrap,
305 issue_tracker_base_url,
320 link_llvm_intrinsics,
327 macro_at_most_once_rep,
330 macro_lifetime_matcher,
331 macro_literal_matcher,
342 match_beginning_vert,
343 match_default_bindings,
353 movbe_target_feature,
385 omit_gdb_pretty_printer_section,
392 optin_builtin_traits,
397 overlapping_marker_traits,
401 panic_implementation,
414 poll_with_tls_context,
415 powerpc_target_feature,
416 precise_pointer_size_matching,
420 proc_dash_macro: "proc-macro",
422 proc_macro_attribute,
428 proc_macro_non_items,
429 proc_macro_path_invoc,
433 quad_precision_float,
446 reexport_test_harness_main,
456 re_rebalance_coherence,
466 rustc_allocator_nounwind,
467 rustc_allow_const_fn_ptr,
468 rustc_args_required_const,
471 rustc_const_unstable,
472 rustc_conversion_suggestion,
473 rustc_copy_clone_marker,
476 rustc_diagnostic_macros,
478 rustc_doc_only_macro,
479 rustc_dump_env_program_clauses,
480 rustc_dump_program_clauses,
481 rustc_dump_user_substs,
483 rustc_expected_cgu_reuse,
484 rustc_if_this_changed,
485 rustc_inherit_overflow_checks,
487 rustc_layout_scalar_valid_range_end,
488 rustc_layout_scalar_valid_range_start,
490 rustc_object_lifetime_default,
491 rustc_on_unimplemented,
494 rustc_partition_codegened,
495 rustc_partition_reused,
497 rustc_peek_definite_init,
498 rustc_peek_maybe_init,
499 rustc_peek_maybe_uninit,
501 rustc_proc_macro_decls,
505 rustc_std_internal_symbol,
509 rustc_then_this_would_need,
510 rustc_transparent_macro,
514 rust_eh_unwind_resume,
516 __rust_unstable_column,
517 rvalue_static_promotion,
533 sse4a_target_feature,
543 stmt_expr_attributes,
545 struct_field_attributes,
556 termination_trait_test,
559 test_accepted_feature,
560 test_removed_feature,
574 type_alias_enum_variants,
584 underscore_const_names,
586 underscore_lifetimes,
588 universal_impl_trait,
590 unrestricted_attribute_tokens,
591 unsafe_destructor_blind_to_params,
594 unsized_tuple_coercion,
605 visible_private_types,
608 warn_directory_ownership,
618 #[derive(Copy, Clone, Eq)]
626 pub const fn new(name: Symbol, span: Span) -> Ident {
631 pub const fn with_empty_ctxt(name: Symbol) -> Ident {
632 Ident::new(name, DUMMY_SP)
635 /// Maps an interned string to an identifier with an empty syntax context.
636 pub fn from_interned_str(string: InternedString) -> Ident {
637 Ident::with_empty_ctxt(string.as_symbol())
640 /// Maps a string to an identifier with an empty syntax context.
641 pub fn from_str(string: &str) -> Ident {
642 Ident::with_empty_ctxt(Symbol::intern(string))
645 /// Replaces `lo` and `hi` with those from `span`, but keep hygiene context.
646 pub fn with_span_pos(self, span: Span) -> Ident {
647 Ident::new(self.name, span.with_ctxt(self.span.ctxt()))
650 pub fn without_first_quote(self) -> Ident {
651 Ident::new(Symbol::intern(self.as_str().trim_start_matches('\'')), self.span)
654 /// "Normalize" ident for use in comparisons using "item hygiene".
655 /// Identifiers with same string value become same if they came from the same "modern" macro
656 /// (e.g., `macro` item, but not `macro_rules` item) and stay different if they came from
657 /// different "modern" macros.
658 /// Technically, this operation strips all non-opaque marks from ident's syntactic context.
659 pub fn modern(self) -> Ident {
660 Ident::new(self.name, self.span.modern())
663 /// "Normalize" ident for use in comparisons using "local variable hygiene".
664 /// Identifiers with same string value become same if they came from the same non-transparent
665 /// macro (e.g., `macro` or `macro_rules!` items) and stay different if they came from different
666 /// non-transparent macros.
667 /// Technically, this operation strips all transparent marks from ident's syntactic context.
668 pub fn modern_and_legacy(self) -> Ident {
669 Ident::new(self.name, self.span.modern_and_legacy())
672 pub fn gensym(self) -> Ident {
673 Ident::new(self.name.gensymed(), self.span)
676 pub fn gensym_if_underscore(self) -> Ident {
677 if self.name == keywords::Underscore.name() { self.gensym() } else { self }
680 pub fn as_str(self) -> LocalInternedString {
684 pub fn as_interned_str(self) -> InternedString {
685 self.name.as_interned_str()
689 impl PartialEq for Ident {
690 fn eq(&self, rhs: &Self) -> bool {
691 self.name == rhs.name && self.span.ctxt() == rhs.span.ctxt()
695 impl Hash for Ident {
696 fn hash<H: Hasher>(&self, state: &mut H) {
697 self.name.hash(state);
698 self.span.ctxt().hash(state);
702 impl fmt::Debug for Ident {
703 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
704 write!(f, "{}{:?}", self.name, self.span.ctxt())
708 impl fmt::Display for Ident {
709 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
710 fmt::Display::fmt(&self.name, f)
714 impl Encodable for Ident {
715 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
716 if self.span.ctxt().modern() == SyntaxContext::empty() {
717 s.emit_str(&self.as_str())
718 } else { // FIXME(jseyfried): intercrate hygiene
719 let mut string = "#".to_owned();
720 string.push_str(&self.as_str());
726 impl Decodable for Ident {
727 fn decode<D: Decoder>(d: &mut D) -> Result<Ident, D::Error> {
728 let string = d.read_str()?;
729 Ok(if !string.starts_with('#') {
730 Ident::from_str(&string)
731 } else { // FIXME(jseyfried): intercrate hygiene
732 Ident::with_empty_ctxt(Symbol::gensym(&string[1..]))
737 /// A symbol is an interned or gensymed string. A gensym is a symbol that is
738 /// never equal to any other symbol. E.g.:
740 /// assert_eq!(Symbol::intern("x"), Symbol::intern("x"))
741 /// assert_ne!(Symbol::gensym("x"), Symbol::intern("x"))
742 /// assert_ne!(Symbol::gensym("x"), Symbol::gensym("x"))
744 /// Conceptually, a gensym can be thought of as a normal symbol with an
745 /// invisible unique suffix. Gensyms are useful when creating new identifiers
746 /// that must not match any existing identifiers, e.g. during macro expansion
747 /// and syntax desugaring.
749 /// Internally, a Symbol is implemented as an index, and all operations
750 /// (including hashing, equality, and ordering) operate on that index. The use
751 /// of `newtype_index!` means that `Option<Symbol>` only takes up 4 bytes,
752 /// because `newtype_index!` reserves the last 256 values for tagging purposes.
754 /// Note that `Symbol` cannot directly be a `newtype_index!` because it implements
755 /// `fmt::Debug`, `Encodable`, and `Decodable` in special ways.
756 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
757 pub struct Symbol(SymbolIndex);
760 pub struct SymbolIndex { .. }
764 const fn new(n: u32) -> Self {
765 Symbol(SymbolIndex::from_u32_const(n))
768 /// Maps a string to its interned representation.
769 pub fn intern(string: &str) -> Self {
770 with_interner(|interner| interner.intern(string))
773 /// Gensyms a new `usize`, using the current interner.
774 pub fn gensym(string: &str) -> Self {
775 with_interner(|interner| interner.gensym(string))
778 pub fn gensymed(self) -> Self {
779 with_interner(|interner| interner.gensymed(self))
782 // WARNING: this function is deprecated and will be removed in the future.
783 pub fn is_gensymed(self) -> bool {
784 with_interner(|interner| interner.is_gensymed(self))
787 pub fn as_str(self) -> LocalInternedString {
788 with_interner(|interner| unsafe {
789 LocalInternedString {
790 string: std::mem::transmute::<&str, &str>(interner.get(self))
795 pub fn as_interned_str(self) -> InternedString {
796 with_interner(|interner| InternedString {
797 symbol: interner.interned(self)
801 pub fn as_u32(self) -> u32 {
806 impl fmt::Debug for Symbol {
807 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
808 let is_gensymed = with_interner(|interner| interner.is_gensymed(*self));
810 write!(f, "{}({:?})", self, self.0)
812 write!(f, "{}", self)
817 impl fmt::Display for Symbol {
818 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
819 fmt::Display::fmt(&self.as_str(), f)
823 impl Encodable for Symbol {
824 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
825 s.emit_str(&self.as_str())
829 impl Decodable for Symbol {
830 fn decode<D: Decoder>(d: &mut D) -> Result<Symbol, D::Error> {
831 Ok(Symbol::intern(&d.read_str()?))
835 // The `&'static str`s in this type actually point into the arena.
837 // Note that normal symbols are indexed upward from 0, and gensyms are indexed
838 // downward from SymbolIndex::MAX_AS_U32.
840 pub struct Interner {
841 arena: DroplessArena,
842 names: FxHashMap<&'static str, Symbol>,
843 strings: Vec<&'static str>,
844 gensyms: Vec<Symbol>,
848 fn prefill(init: &[&str]) -> Self {
849 let mut this = Interner::default();
850 this.names.reserve(init.len());
851 this.strings.reserve(init.len());
853 // We can't allocate empty strings in the arena, so handle this here.
854 assert!(keywords::Invalid.name().as_u32() == 0 && init[0].is_empty());
855 this.names.insert("", keywords::Invalid.name());
856 this.strings.push("");
858 for string in &init[1..] {
864 pub fn intern(&mut self, string: &str) -> Symbol {
865 if let Some(&name) = self.names.get(string) {
869 let name = Symbol::new(self.strings.len() as u32);
871 // `from_utf8_unchecked` is safe since we just allocated a `&str` which is known to be
873 let string: &str = unsafe {
874 str::from_utf8_unchecked(self.arena.alloc_slice(string.as_bytes()))
876 // It is safe to extend the arena allocation to `'static` because we only access
877 // these while the arena is still alive.
878 let string: &'static str = unsafe {
879 &*(string as *const str)
881 self.strings.push(string);
882 self.names.insert(string, name);
886 fn interned(&self, symbol: Symbol) -> Symbol {
887 if (symbol.0.as_usize()) < self.strings.len() {
890 self.gensyms[(SymbolIndex::MAX_AS_U32 - symbol.0.as_u32()) as usize]
894 fn gensym(&mut self, string: &str) -> Symbol {
895 let symbol = self.intern(string);
896 self.gensymed(symbol)
899 fn gensymed(&mut self, symbol: Symbol) -> Symbol {
900 self.gensyms.push(symbol);
901 Symbol::new(SymbolIndex::MAX_AS_U32 - self.gensyms.len() as u32 + 1)
904 fn is_gensymed(&mut self, symbol: Symbol) -> bool {
905 symbol.0.as_usize() >= self.strings.len()
908 // Get the symbol as a string. `Symbol::as_str()` should be used in
909 // preference to this function.
910 pub fn get(&self, symbol: Symbol) -> &str {
911 match self.strings.get(symbol.0.as_usize()) {
912 Some(string) => string,
914 let symbol = self.gensyms[(SymbolIndex::MAX_AS_U32 - symbol.0.as_u32()) as usize];
915 self.strings[symbol.0.as_usize()]
922 use super::{Symbol, Ident};
924 #[derive(Clone, Copy, PartialEq, Eq)]
931 pub fn ident(self) -> Ident {
936 pub fn name(self) -> Symbol {
944 // This module has a very short name because it's used a lot.
951 fn is_used_keyword_2018(self) -> bool {
952 self == keywords::Dyn.name()
955 fn is_unused_keyword_2018(self) -> bool {
956 self >= keywords::Async.name() && self <= keywords::Try.name()
961 // Returns `true` for reserved identifiers used internally for elided lifetimes,
962 // unnamed method parameters, crate root module, error recovery etc.
963 pub fn is_special(self) -> bool {
964 self.name <= keywords::Underscore.name()
967 /// Returns `true` if the token is a keyword used in the language.
968 pub fn is_used_keyword(self) -> bool {
969 // Note: `span.edition()` is relatively expensive, don't call it unless necessary.
970 self.name >= keywords::As.name() && self.name <= keywords::While.name() ||
971 self.name.is_used_keyword_2018() && self.span.rust_2018()
974 /// Returns `true` if the token is a keyword reserved for possible future use.
975 pub fn is_unused_keyword(self) -> bool {
976 // Note: `span.edition()` is relatively expensive, don't call it unless necessary.
977 self.name >= keywords::Abstract.name() && self.name <= keywords::Yield.name() ||
978 self.name.is_unused_keyword_2018() && self.span.rust_2018()
981 /// Returns `true` if the token is either a special identifier or a keyword.
982 pub fn is_reserved(self) -> bool {
983 self.is_special() || self.is_used_keyword() || self.is_unused_keyword()
986 /// A keyword or reserved identifier that can be used as a path segment.
987 pub fn is_path_segment_keyword(self) -> bool {
988 self.name == keywords::Super.name() ||
989 self.name == keywords::SelfLower.name() ||
990 self.name == keywords::SelfUpper.name() ||
991 self.name == keywords::Crate.name() ||
992 self.name == keywords::PathRoot.name() ||
993 self.name == keywords::DollarCrate.name()
996 /// This identifier can be a raw identifier.
997 pub fn can_be_raw(self) -> bool {
998 self.name != keywords::Invalid.name() && self.name != keywords::Underscore.name() &&
999 !self.is_path_segment_keyword()
1002 /// We see this identifier in a normal identifier position, like variable name or a type.
1003 /// How was it written originally? Did it use the raw form? Let's try to guess.
1004 pub fn is_raw_guess(self) -> bool {
1005 self.can_be_raw() && self.is_reserved()
1009 // If an interner exists, return it. Otherwise, prepare a fresh one.
1011 fn with_interner<T, F: FnOnce(&mut Interner) -> T>(f: F) -> T {
1012 GLOBALS.with(|globals| f(&mut *globals.symbol_interner.lock()))
1015 /// An alternative to `Symbol` and `InternedString`, useful when the chars
1016 /// within the symbol need to be accessed. It is best used for temporary
1019 /// Because the interner outlives any thread which uses this type, we can
1020 /// safely treat `string` which points to interner data, as an immortal string,
1021 /// as long as this type never crosses between threads.
1023 // FIXME: ensure that the interner outlives any thread which uses
1024 // `LocalInternedString`, by creating a new thread right after constructing the
1026 #[derive(Clone, Copy, Hash, PartialOrd, Eq, Ord)]
1027 pub struct LocalInternedString {
1028 string: &'static str,
1031 impl LocalInternedString {
1032 pub fn as_interned_str(self) -> InternedString {
1034 symbol: Symbol::intern(self.string)
1038 pub fn get(&self) -> &str {
1039 // This returns a valid string since we ensure that `self` outlives the interner
1040 // by creating the interner on a thread which outlives threads which can access it.
1041 // This type cannot move to a thread which outlives the interner since it does
1042 // not implement Send.
1047 impl<U: ?Sized> std::convert::AsRef<U> for LocalInternedString
1049 str: std::convert::AsRef<U>
1051 fn as_ref(&self) -> &U {
1052 self.string.as_ref()
1056 impl<T: std::ops::Deref<Target = str>> std::cmp::PartialEq<T> for LocalInternedString {
1057 fn eq(&self, other: &T) -> bool {
1058 self.string == other.deref()
1062 impl std::cmp::PartialEq<LocalInternedString> for str {
1063 fn eq(&self, other: &LocalInternedString) -> bool {
1064 self == other.string
1068 impl<'a> std::cmp::PartialEq<LocalInternedString> for &'a str {
1069 fn eq(&self, other: &LocalInternedString) -> bool {
1070 *self == other.string
1074 impl std::cmp::PartialEq<LocalInternedString> for String {
1075 fn eq(&self, other: &LocalInternedString) -> bool {
1076 self == other.string
1080 impl<'a> std::cmp::PartialEq<LocalInternedString> for &'a String {
1081 fn eq(&self, other: &LocalInternedString) -> bool {
1082 *self == other.string
1086 impl !Send for LocalInternedString {}
1087 impl !Sync for LocalInternedString {}
1089 impl std::ops::Deref for LocalInternedString {
1091 fn deref(&self) -> &str { self.string }
1094 impl fmt::Debug for LocalInternedString {
1095 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1096 fmt::Debug::fmt(self.string, f)
1100 impl fmt::Display for LocalInternedString {
1101 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1102 fmt::Display::fmt(self.string, f)
1106 impl Decodable for LocalInternedString {
1107 fn decode<D: Decoder>(d: &mut D) -> Result<LocalInternedString, D::Error> {
1108 Ok(Symbol::intern(&d.read_str()?).as_str())
1112 impl Encodable for LocalInternedString {
1113 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1114 s.emit_str(self.string)
1118 /// An alternative to `Symbol` that is focused on string contents. It has two
1119 /// main differences to `Symbol`.
1121 /// First, its implementations of `Hash`, `PartialOrd` and `Ord` work with the
1122 /// string chars rather than the symbol integer. This is useful when hash
1123 /// stability is required across compile sessions, or a guaranteed sort
1124 /// ordering is required.
1126 /// Second, gensym-ness is irrelevant. E.g.:
1128 /// assert_ne!(Symbol::gensym("x"), Symbol::gensym("x"))
1129 /// assert_eq!(Symbol::gensym("x").as_interned_str(), Symbol::gensym("x").as_interned_str())
1131 #[derive(Clone, Copy, Eq)]
1132 pub struct InternedString {
1136 impl InternedString {
1137 pub fn with<F: FnOnce(&str) -> R, R>(self, f: F) -> R {
1138 let str = with_interner(|interner| {
1139 interner.get(self.symbol) as *const str
1141 // This is safe because the interner keeps string alive until it is dropped.
1142 // We can access it because we know the interner is still alive since we use a
1143 // scoped thread local to access it, and it was alive at the beginning of this scope
1147 fn with2<F: FnOnce(&str, &str) -> R, R>(self, other: &InternedString, f: F) -> R {
1148 let (self_str, other_str) = with_interner(|interner| {
1149 (interner.get(self.symbol) as *const str,
1150 interner.get(other.symbol) as *const str)
1152 // This is safe for the same reason that `with` is safe.
1153 unsafe { f(&*self_str, &*other_str) }
1156 pub fn as_symbol(self) -> Symbol {
1160 pub fn as_str(self) -> LocalInternedString {
1161 self.symbol.as_str()
1165 impl Hash for InternedString {
1166 fn hash<H: Hasher>(&self, state: &mut H) {
1167 self.with(|str| str.hash(state))
1171 impl PartialOrd<InternedString> for InternedString {
1172 fn partial_cmp(&self, other: &InternedString) -> Option<Ordering> {
1173 if self.symbol == other.symbol {
1174 return Some(Ordering::Equal);
1176 self.with2(other, |self_str, other_str| self_str.partial_cmp(other_str))
1180 impl Ord for InternedString {
1181 fn cmp(&self, other: &InternedString) -> Ordering {
1182 if self.symbol == other.symbol {
1183 return Ordering::Equal;
1185 self.with2(other, |self_str, other_str| self_str.cmp(other_str))
1189 impl<T: std::ops::Deref<Target = str>> PartialEq<T> for InternedString {
1190 fn eq(&self, other: &T) -> bool {
1191 self.with(|string| string == other.deref())
1195 impl PartialEq<InternedString> for InternedString {
1196 fn eq(&self, other: &InternedString) -> bool {
1197 self.symbol == other.symbol
1201 impl PartialEq<InternedString> for str {
1202 fn eq(&self, other: &InternedString) -> bool {
1203 other.with(|string| self == string)
1207 impl<'a> PartialEq<InternedString> for &'a str {
1208 fn eq(&self, other: &InternedString) -> bool {
1209 other.with(|string| *self == string)
1213 impl PartialEq<InternedString> for String {
1214 fn eq(&self, other: &InternedString) -> bool {
1215 other.with(|string| self == string)
1219 impl<'a> PartialEq<InternedString> for &'a String {
1220 fn eq(&self, other: &InternedString) -> bool {
1221 other.with(|string| *self == string)
1225 impl fmt::Debug for InternedString {
1226 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1227 self.with(|str| fmt::Debug::fmt(&str, f))
1231 impl fmt::Display for InternedString {
1232 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1233 self.with(|str| fmt::Display::fmt(&str, f))
1237 impl Decodable for InternedString {
1238 fn decode<D: Decoder>(d: &mut D) -> Result<InternedString, D::Error> {
1239 Ok(Symbol::intern(&d.read_str()?).as_interned_str())
1243 impl Encodable for InternedString {
1244 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1245 self.with(|string| s.emit_str(string))
1255 fn interner_tests() {
1256 let mut i: Interner = Interner::default();
1257 // first one is zero:
1258 assert_eq!(i.intern("dog"), Symbol::new(0));
1259 // re-use gets the same entry:
1260 assert_eq!(i.intern("dog"), Symbol::new(0));
1261 // different string gets a different #:
1262 assert_eq!(i.intern("cat"), Symbol::new(1));
1263 assert_eq!(i.intern("cat"), Symbol::new(1));
1264 // dog is still at zero
1265 assert_eq!(i.intern("dog"), Symbol::new(0));
1266 assert_eq!(i.gensym("zebra"), Symbol::new(SymbolIndex::MAX_AS_U32));
1267 // gensym of same string gets new number:
1268 assert_eq!(i.gensym("zebra"), Symbol::new(SymbolIndex::MAX_AS_U32 - 1));
1269 // gensym of *existing* string gets new number:
1270 assert_eq!(i.gensym("dog"), Symbol::new(SymbolIndex::MAX_AS_U32 - 2));
1274 fn without_first_quote_test() {
1275 GLOBALS.set(&Globals::new(), || {
1276 let i = Ident::from_str("'break");
1277 assert_eq!(i.without_first_quote().name, keywords::Break.name());