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,
235 exclusive_range_pattern,
236 exhaustive_integer_patterns,
241 extern_absolute_paths,
243 extern_crate_item_prelude,
251 field_init_shorthand,
266 generic_associated_types,
271 hexagon_target_feature,
273 homogeneous_aggregate,
287 if_while_or_patterns,
289 impl_header_lifetime_elision,
290 impl_trait_in_bindings,
294 inclusive_range_syntax,
295 infer_outlives_requirements,
296 infer_static_outlives_requirements,
303 irrefutable_let_patterns,
306 issue_5723_bootstrap,
307 issue_tracker_base_url,
322 link_llvm_intrinsics,
329 macro_at_most_once_rep,
332 macro_lifetime_matcher,
333 macro_literal_matcher,
344 match_beginning_vert,
345 match_default_bindings,
355 movbe_target_feature,
388 omit_gdb_pretty_printer_section,
395 optin_builtin_traits,
400 overlapping_marker_traits,
404 panic_implementation,
418 poll_with_tls_context,
419 powerpc_target_feature,
420 precise_pointer_size_matching,
424 proc_dash_macro: "proc-macro",
426 proc_macro_attribute,
432 proc_macro_non_items,
433 proc_macro_path_invoc,
437 quad_precision_float,
450 reexport_test_harness_main,
460 re_rebalance_coherence,
470 rustc_allocator_nounwind,
471 rustc_allow_const_fn_ptr,
472 rustc_args_required_const,
475 rustc_const_unstable,
476 rustc_conversion_suggestion,
477 rustc_copy_clone_marker,
480 rustc_diagnostic_macros,
482 rustc_doc_only_macro,
483 rustc_dump_env_program_clauses,
484 rustc_dump_program_clauses,
485 rustc_dump_user_substs,
487 rustc_expected_cgu_reuse,
488 rustc_if_this_changed,
489 rustc_inherit_overflow_checks,
491 rustc_layout_scalar_valid_range_end,
492 rustc_layout_scalar_valid_range_start,
494 rustc_object_lifetime_default,
495 rustc_on_unimplemented,
498 rustc_partition_codegened,
499 rustc_partition_reused,
501 rustc_peek_definite_init,
502 rustc_peek_maybe_init,
503 rustc_peek_maybe_uninit,
505 rustc_proc_macro_decls,
509 rustc_std_internal_symbol,
513 rustc_then_this_would_need,
514 rustc_transparent_macro,
518 rust_eh_unwind_resume,
520 __rust_unstable_column,
521 rvalue_static_promotion,
537 sse4a_target_feature,
547 stmt_expr_attributes,
549 struct_field_attributes,
560 termination_trait_test,
563 test_accepted_feature,
564 test_removed_feature,
579 type_alias_enum_variants,
589 underscore_const_names,
591 underscore_lifetimes,
593 universal_impl_trait,
596 unrestricted_attribute_tokens,
597 unsafe_destructor_blind_to_params,
600 unsized_tuple_coercion,
612 visible_private_types,
615 warn_directory_ownership,
625 #[derive(Copy, Clone, Eq)]
633 pub const fn new(name: Symbol, span: Span) -> Ident {
638 pub const fn with_empty_ctxt(name: Symbol) -> Ident {
639 Ident::new(name, DUMMY_SP)
642 /// Maps an interned string to an identifier with an empty syntax context.
643 pub fn from_interned_str(string: InternedString) -> Ident {
644 Ident::with_empty_ctxt(string.as_symbol())
647 /// Maps a string to an identifier with an empty syntax context.
648 pub fn from_str(string: &str) -> Ident {
649 Ident::with_empty_ctxt(Symbol::intern(string))
652 /// Replaces `lo` and `hi` with those from `span`, but keep hygiene context.
653 pub fn with_span_pos(self, span: Span) -> Ident {
654 Ident::new(self.name, span.with_ctxt(self.span.ctxt()))
657 pub fn without_first_quote(self) -> Ident {
658 Ident::new(Symbol::intern(self.as_str().trim_start_matches('\'')), self.span)
661 /// "Normalize" ident for use in comparisons using "item hygiene".
662 /// Identifiers with same string value become same if they came from the same "modern" macro
663 /// (e.g., `macro` item, but not `macro_rules` item) and stay different if they came from
664 /// different "modern" macros.
665 /// Technically, this operation strips all non-opaque marks from ident's syntactic context.
666 pub fn modern(self) -> Ident {
667 Ident::new(self.name, self.span.modern())
670 /// "Normalize" ident for use in comparisons using "local variable hygiene".
671 /// Identifiers with same string value become same if they came from the same non-transparent
672 /// macro (e.g., `macro` or `macro_rules!` items) and stay different if they came from different
673 /// non-transparent macros.
674 /// Technically, this operation strips all transparent marks from ident's syntactic context.
675 pub fn modern_and_legacy(self) -> Ident {
676 Ident::new(self.name, self.span.modern_and_legacy())
679 pub fn gensym(self) -> Ident {
680 Ident::new(self.name.gensymed(), self.span)
683 pub fn gensym_if_underscore(self) -> Ident {
684 if self.name == keywords::Underscore.name() { self.gensym() } else { self }
687 pub fn as_str(self) -> LocalInternedString {
691 pub fn as_interned_str(self) -> InternedString {
692 self.name.as_interned_str()
696 impl PartialEq for Ident {
697 fn eq(&self, rhs: &Self) -> bool {
698 self.name == rhs.name && self.span.ctxt() == rhs.span.ctxt()
702 impl Hash for Ident {
703 fn hash<H: Hasher>(&self, state: &mut H) {
704 self.name.hash(state);
705 self.span.ctxt().hash(state);
709 impl fmt::Debug for Ident {
710 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
711 write!(f, "{}{:?}", self.name, self.span.ctxt())
715 impl fmt::Display for Ident {
716 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
717 fmt::Display::fmt(&self.name, f)
721 impl Encodable for Ident {
722 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
723 if self.span.ctxt().modern() == SyntaxContext::empty() {
724 s.emit_str(&self.as_str())
725 } else { // FIXME(jseyfried): intercrate hygiene
726 let mut string = "#".to_owned();
727 string.push_str(&self.as_str());
733 impl Decodable for Ident {
734 fn decode<D: Decoder>(d: &mut D) -> Result<Ident, D::Error> {
735 let string = d.read_str()?;
736 Ok(if !string.starts_with('#') {
737 Ident::from_str(&string)
738 } else { // FIXME(jseyfried): intercrate hygiene
739 Ident::with_empty_ctxt(Symbol::gensym(&string[1..]))
744 /// A symbol is an interned or gensymed string. A gensym is a symbol that is
745 /// never equal to any other symbol. E.g.:
747 /// assert_eq!(Symbol::intern("x"), Symbol::intern("x"))
748 /// assert_ne!(Symbol::gensym("x"), Symbol::intern("x"))
749 /// assert_ne!(Symbol::gensym("x"), Symbol::gensym("x"))
751 /// Conceptually, a gensym can be thought of as a normal symbol with an
752 /// invisible unique suffix. Gensyms are useful when creating new identifiers
753 /// that must not match any existing identifiers, e.g. during macro expansion
754 /// and syntax desugaring.
756 /// Internally, a Symbol is implemented as an index, and all operations
757 /// (including hashing, equality, and ordering) operate on that index. The use
758 /// of `newtype_index!` means that `Option<Symbol>` only takes up 4 bytes,
759 /// because `newtype_index!` reserves the last 256 values for tagging purposes.
761 /// Note that `Symbol` cannot directly be a `newtype_index!` because it implements
762 /// `fmt::Debug`, `Encodable`, and `Decodable` in special ways.
763 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
764 pub struct Symbol(SymbolIndex);
767 pub struct SymbolIndex { .. }
771 const fn new(n: u32) -> Self {
772 Symbol(SymbolIndex::from_u32_const(n))
775 /// Maps a string to its interned representation.
776 pub fn intern(string: &str) -> Self {
777 with_interner(|interner| interner.intern(string))
780 /// Gensyms a new `usize`, using the current interner.
781 pub fn gensym(string: &str) -> Self {
782 with_interner(|interner| interner.gensym(string))
785 pub fn gensymed(self) -> Self {
786 with_interner(|interner| interner.gensymed(self))
789 // WARNING: this function is deprecated and will be removed in the future.
790 pub fn is_gensymed(self) -> bool {
791 with_interner(|interner| interner.is_gensymed(self))
794 pub fn as_str(self) -> LocalInternedString {
795 with_interner(|interner| unsafe {
796 LocalInternedString {
797 string: std::mem::transmute::<&str, &str>(interner.get(self))
802 pub fn as_interned_str(self) -> InternedString {
803 with_interner(|interner| InternedString {
804 symbol: interner.interned(self)
808 pub fn as_u32(self) -> u32 {
813 impl fmt::Debug for Symbol {
814 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
815 let is_gensymed = with_interner(|interner| interner.is_gensymed(*self));
817 write!(f, "{}({:?})", self, self.0)
819 write!(f, "{}", self)
824 impl fmt::Display for Symbol {
825 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
826 fmt::Display::fmt(&self.as_str(), f)
830 impl Encodable for Symbol {
831 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
832 s.emit_str(&self.as_str())
836 impl Decodable for Symbol {
837 fn decode<D: Decoder>(d: &mut D) -> Result<Symbol, D::Error> {
838 Ok(Symbol::intern(&d.read_str()?))
842 // The `&'static str`s in this type actually point into the arena.
844 // Note that normal symbols are indexed upward from 0, and gensyms are indexed
845 // downward from SymbolIndex::MAX_AS_U32.
847 pub struct Interner {
848 arena: DroplessArena,
849 names: FxHashMap<&'static str, Symbol>,
850 strings: Vec<&'static str>,
851 gensyms: Vec<Symbol>,
855 fn prefill(init: &[&str]) -> Self {
856 let mut this = Interner::default();
857 this.names.reserve(init.len());
858 this.strings.reserve(init.len());
860 // We can't allocate empty strings in the arena, so handle this here.
861 assert!(keywords::Invalid.name().as_u32() == 0 && init[0].is_empty());
862 this.names.insert("", keywords::Invalid.name());
863 this.strings.push("");
865 for string in &init[1..] {
871 pub fn intern(&mut self, string: &str) -> Symbol {
872 if let Some(&name) = self.names.get(string) {
876 let name = Symbol::new(self.strings.len() as u32);
878 // `from_utf8_unchecked` is safe since we just allocated a `&str` which is known to be
880 let string: &str = unsafe {
881 str::from_utf8_unchecked(self.arena.alloc_slice(string.as_bytes()))
883 // It is safe to extend the arena allocation to `'static` because we only access
884 // these while the arena is still alive.
885 let string: &'static str = unsafe {
886 &*(string as *const str)
888 self.strings.push(string);
889 self.names.insert(string, name);
893 fn interned(&self, symbol: Symbol) -> Symbol {
894 if (symbol.0.as_usize()) < self.strings.len() {
897 self.gensyms[(SymbolIndex::MAX_AS_U32 - symbol.0.as_u32()) as usize]
901 fn gensym(&mut self, string: &str) -> Symbol {
902 let symbol = self.intern(string);
903 self.gensymed(symbol)
906 fn gensymed(&mut self, symbol: Symbol) -> Symbol {
907 self.gensyms.push(symbol);
908 Symbol::new(SymbolIndex::MAX_AS_U32 - self.gensyms.len() as u32 + 1)
911 fn is_gensymed(&mut self, symbol: Symbol) -> bool {
912 symbol.0.as_usize() >= self.strings.len()
915 // Get the symbol as a string. `Symbol::as_str()` should be used in
916 // preference to this function.
917 pub fn get(&self, symbol: Symbol) -> &str {
918 match self.strings.get(symbol.0.as_usize()) {
919 Some(string) => string,
921 let symbol = self.gensyms[(SymbolIndex::MAX_AS_U32 - symbol.0.as_u32()) as usize];
922 self.strings[symbol.0.as_usize()]
929 use super::{Symbol, Ident};
931 #[derive(Clone, Copy, PartialEq, Eq)]
938 pub fn ident(self) -> Ident {
943 pub fn name(self) -> Symbol {
951 // This module has a very short name because it's used a lot.
958 fn is_used_keyword_2018(self) -> bool {
959 self == keywords::Dyn.name()
962 fn is_unused_keyword_2018(self) -> bool {
963 self >= keywords::Async.name() && self <= keywords::Try.name()
968 // Returns `true` for reserved identifiers used internally for elided lifetimes,
969 // unnamed method parameters, crate root module, error recovery etc.
970 pub fn is_special(self) -> bool {
971 self.name <= keywords::Underscore.name()
974 /// Returns `true` if the token is a keyword used in the language.
975 pub fn is_used_keyword(self) -> bool {
976 // Note: `span.edition()` is relatively expensive, don't call it unless necessary.
977 self.name >= keywords::As.name() && self.name <= keywords::While.name() ||
978 self.name.is_used_keyword_2018() && self.span.rust_2018()
981 /// Returns `true` if the token is a keyword reserved for possible future use.
982 pub fn is_unused_keyword(self) -> bool {
983 // Note: `span.edition()` is relatively expensive, don't call it unless necessary.
984 self.name >= keywords::Abstract.name() && self.name <= keywords::Yield.name() ||
985 self.name.is_unused_keyword_2018() && self.span.rust_2018()
988 /// Returns `true` if the token is either a special identifier or a keyword.
989 pub fn is_reserved(self) -> bool {
990 self.is_special() || self.is_used_keyword() || self.is_unused_keyword()
993 /// A keyword or reserved identifier that can be used as a path segment.
994 pub fn is_path_segment_keyword(self) -> bool {
995 self.name == keywords::Super.name() ||
996 self.name == keywords::SelfLower.name() ||
997 self.name == keywords::SelfUpper.name() ||
998 self.name == keywords::Crate.name() ||
999 self.name == keywords::PathRoot.name() ||
1000 self.name == keywords::DollarCrate.name()
1003 /// This identifier can be a raw identifier.
1004 pub fn can_be_raw(self) -> bool {
1005 self.name != keywords::Invalid.name() && self.name != keywords::Underscore.name() &&
1006 !self.is_path_segment_keyword()
1009 /// We see this identifier in a normal identifier position, like variable name or a type.
1010 /// How was it written originally? Did it use the raw form? Let's try to guess.
1011 pub fn is_raw_guess(self) -> bool {
1012 self.can_be_raw() && self.is_reserved()
1016 // If an interner exists, return it. Otherwise, prepare a fresh one.
1018 fn with_interner<T, F: FnOnce(&mut Interner) -> T>(f: F) -> T {
1019 GLOBALS.with(|globals| f(&mut *globals.symbol_interner.lock()))
1022 /// An alternative to `Symbol` and `InternedString`, useful when the chars
1023 /// within the symbol need to be accessed. It is best used for temporary
1026 /// Because the interner outlives any thread which uses this type, we can
1027 /// safely treat `string` which points to interner data, as an immortal string,
1028 /// as long as this type never crosses between threads.
1030 // FIXME: ensure that the interner outlives any thread which uses
1031 // `LocalInternedString`, by creating a new thread right after constructing the
1033 #[derive(Clone, Copy, Hash, PartialOrd, Eq, Ord)]
1034 pub struct LocalInternedString {
1035 string: &'static str,
1038 impl LocalInternedString {
1039 pub fn as_interned_str(self) -> InternedString {
1041 symbol: Symbol::intern(self.string)
1045 pub fn get(&self) -> &str {
1046 // This returns a valid string since we ensure that `self` outlives the interner
1047 // by creating the interner on a thread which outlives threads which can access it.
1048 // This type cannot move to a thread which outlives the interner since it does
1049 // not implement Send.
1054 impl<U: ?Sized> std::convert::AsRef<U> for LocalInternedString
1056 str: std::convert::AsRef<U>
1058 fn as_ref(&self) -> &U {
1059 self.string.as_ref()
1063 impl<T: std::ops::Deref<Target = str>> std::cmp::PartialEq<T> for LocalInternedString {
1064 fn eq(&self, other: &T) -> bool {
1065 self.string == other.deref()
1069 impl std::cmp::PartialEq<LocalInternedString> for str {
1070 fn eq(&self, other: &LocalInternedString) -> bool {
1071 self == other.string
1075 impl<'a> std::cmp::PartialEq<LocalInternedString> for &'a str {
1076 fn eq(&self, other: &LocalInternedString) -> bool {
1077 *self == other.string
1081 impl std::cmp::PartialEq<LocalInternedString> for String {
1082 fn eq(&self, other: &LocalInternedString) -> bool {
1083 self == other.string
1087 impl<'a> std::cmp::PartialEq<LocalInternedString> for &'a String {
1088 fn eq(&self, other: &LocalInternedString) -> bool {
1089 *self == other.string
1093 impl !Send for LocalInternedString {}
1094 impl !Sync for LocalInternedString {}
1096 impl std::ops::Deref for LocalInternedString {
1098 fn deref(&self) -> &str { self.string }
1101 impl fmt::Debug for LocalInternedString {
1102 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1103 fmt::Debug::fmt(self.string, f)
1107 impl fmt::Display for LocalInternedString {
1108 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1109 fmt::Display::fmt(self.string, f)
1113 impl Decodable for LocalInternedString {
1114 fn decode<D: Decoder>(d: &mut D) -> Result<LocalInternedString, D::Error> {
1115 Ok(Symbol::intern(&d.read_str()?).as_str())
1119 impl Encodable for LocalInternedString {
1120 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1121 s.emit_str(self.string)
1125 /// An alternative to `Symbol` that is focused on string contents. It has two
1126 /// main differences to `Symbol`.
1128 /// First, its implementations of `Hash`, `PartialOrd` and `Ord` work with the
1129 /// string chars rather than the symbol integer. This is useful when hash
1130 /// stability is required across compile sessions, or a guaranteed sort
1131 /// ordering is required.
1133 /// Second, gensym-ness is irrelevant. E.g.:
1135 /// assert_ne!(Symbol::gensym("x"), Symbol::gensym("x"))
1136 /// assert_eq!(Symbol::gensym("x").as_interned_str(), Symbol::gensym("x").as_interned_str())
1138 #[derive(Clone, Copy, Eq)]
1139 pub struct InternedString {
1143 impl InternedString {
1144 pub fn with<F: FnOnce(&str) -> R, R>(self, f: F) -> R {
1145 let str = with_interner(|interner| {
1146 interner.get(self.symbol) as *const str
1148 // This is safe because the interner keeps string alive until it is dropped.
1149 // We can access it because we know the interner is still alive since we use a
1150 // scoped thread local to access it, and it was alive at the beginning of this scope
1154 fn with2<F: FnOnce(&str, &str) -> R, R>(self, other: &InternedString, f: F) -> R {
1155 let (self_str, other_str) = with_interner(|interner| {
1156 (interner.get(self.symbol) as *const str,
1157 interner.get(other.symbol) as *const str)
1159 // This is safe for the same reason that `with` is safe.
1160 unsafe { f(&*self_str, &*other_str) }
1163 pub fn as_symbol(self) -> Symbol {
1167 pub fn as_str(self) -> LocalInternedString {
1168 self.symbol.as_str()
1172 impl Hash for InternedString {
1173 fn hash<H: Hasher>(&self, state: &mut H) {
1174 self.with(|str| str.hash(state))
1178 impl PartialOrd<InternedString> for InternedString {
1179 fn partial_cmp(&self, other: &InternedString) -> Option<Ordering> {
1180 if self.symbol == other.symbol {
1181 return Some(Ordering::Equal);
1183 self.with2(other, |self_str, other_str| self_str.partial_cmp(other_str))
1187 impl Ord for InternedString {
1188 fn cmp(&self, other: &InternedString) -> Ordering {
1189 if self.symbol == other.symbol {
1190 return Ordering::Equal;
1192 self.with2(other, |self_str, other_str| self_str.cmp(other_str))
1196 impl<T: std::ops::Deref<Target = str>> PartialEq<T> for InternedString {
1197 fn eq(&self, other: &T) -> bool {
1198 self.with(|string| string == other.deref())
1202 impl PartialEq<InternedString> for InternedString {
1203 fn eq(&self, other: &InternedString) -> bool {
1204 self.symbol == other.symbol
1208 impl PartialEq<InternedString> for str {
1209 fn eq(&self, other: &InternedString) -> bool {
1210 other.with(|string| self == string)
1214 impl<'a> PartialEq<InternedString> for &'a str {
1215 fn eq(&self, other: &InternedString) -> bool {
1216 other.with(|string| *self == string)
1220 impl PartialEq<InternedString> for String {
1221 fn eq(&self, other: &InternedString) -> bool {
1222 other.with(|string| self == string)
1226 impl<'a> PartialEq<InternedString> for &'a String {
1227 fn eq(&self, other: &InternedString) -> bool {
1228 other.with(|string| *self == string)
1232 impl fmt::Debug for InternedString {
1233 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1234 self.with(|str| fmt::Debug::fmt(&str, f))
1238 impl fmt::Display for InternedString {
1239 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1240 self.with(|str| fmt::Display::fmt(&str, f))
1244 impl Decodable for InternedString {
1245 fn decode<D: Decoder>(d: &mut D) -> Result<InternedString, D::Error> {
1246 Ok(Symbol::intern(&d.read_str()?).as_interned_str())
1250 impl Encodable for InternedString {
1251 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1252 self.with(|string| s.emit_str(string))
1262 fn interner_tests() {
1263 let mut i: Interner = Interner::default();
1264 // first one is zero:
1265 assert_eq!(i.intern("dog"), Symbol::new(0));
1266 // re-use gets the same entry:
1267 assert_eq!(i.intern("dog"), Symbol::new(0));
1268 // different string gets a different #:
1269 assert_eq!(i.intern("cat"), Symbol::new(1));
1270 assert_eq!(i.intern("cat"), Symbol::new(1));
1271 // dog is still at zero
1272 assert_eq!(i.intern("dog"), Symbol::new(0));
1273 assert_eq!(i.gensym("zebra"), Symbol::new(SymbolIndex::MAX_AS_U32));
1274 // gensym of same string gets new number:
1275 assert_eq!(i.gensym("zebra"), Symbol::new(SymbolIndex::MAX_AS_U32 - 1));
1276 // gensym of *existing* string gets new number:
1277 assert_eq!(i.gensym("dog"), Symbol::new(SymbolIndex::MAX_AS_U32 - 2));
1281 fn without_first_quote_test() {
1282 GLOBALS.set(&Globals::new(), || {
1283 let i = Ident::from_str("'break");
1284 assert_eq!(i.without_first_quote().name, keywords::Break.name());