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,
253 field_init_shorthand,
268 generic_associated_types,
273 hexagon_target_feature,
275 homogeneous_aggregate,
289 if_while_or_patterns,
291 impl_header_lifetime_elision,
292 impl_trait_in_bindings,
296 inclusive_range_syntax,
297 infer_outlives_requirements,
298 infer_static_outlives_requirements,
305 irrefutable_let_patterns,
308 issue_5723_bootstrap,
309 issue_tracker_base_url,
324 link_llvm_intrinsics,
331 macro_at_most_once_rep,
334 macro_lifetime_matcher,
335 macro_literal_matcher,
346 match_beginning_vert,
347 match_default_bindings,
357 movbe_target_feature,
390 omit_gdb_pretty_printer_section,
397 optin_builtin_traits,
402 overlapping_marker_traits,
406 panic_implementation,
420 poll_with_tls_context,
421 powerpc_target_feature,
422 precise_pointer_size_matching,
426 proc_dash_macro: "proc-macro",
428 proc_macro_attribute,
434 proc_macro_non_items,
435 proc_macro_path_invoc,
439 quad_precision_float,
452 reexport_test_harness_main,
462 re_rebalance_coherence,
472 rustc_allocator_nounwind,
473 rustc_allow_const_fn_ptr,
474 rustc_args_required_const,
477 rustc_const_unstable,
478 rustc_conversion_suggestion,
479 rustc_copy_clone_marker,
482 rustc_diagnostic_macros,
484 rustc_doc_only_macro,
485 rustc_dump_env_program_clauses,
486 rustc_dump_program_clauses,
487 rustc_dump_user_substs,
489 rustc_expected_cgu_reuse,
490 rustc_if_this_changed,
491 rustc_inherit_overflow_checks,
493 rustc_layout_scalar_valid_range_end,
494 rustc_layout_scalar_valid_range_start,
496 rustc_nonnull_optimization_guaranteed,
497 rustc_object_lifetime_default,
498 rustc_on_unimplemented,
501 rustc_partition_codegened,
502 rustc_partition_reused,
504 rustc_peek_definite_init,
505 rustc_peek_maybe_init,
506 rustc_peek_maybe_uninit,
508 rustc_proc_macro_decls,
512 rustc_std_internal_symbol,
516 rustc_then_this_would_need,
517 rustc_transparent_macro,
521 rust_eh_unwind_resume,
523 __rust_unstable_column,
524 rvalue_static_promotion,
540 sse4a_target_feature,
550 stmt_expr_attributes,
552 struct_field_attributes,
563 termination_trait_test,
566 test_accepted_feature,
567 test_removed_feature,
582 type_alias_enum_variants,
592 underscore_const_names,
594 underscore_lifetimes,
596 universal_impl_trait,
599 unrestricted_attribute_tokens,
600 unsafe_destructor_blind_to_params,
603 unsized_tuple_coercion,
615 visible_private_types,
618 warn_directory_ownership,
628 #[derive(Copy, Clone, Eq)]
636 /// Constructs a new identifier from a symbol and a span.
637 pub const fn new(name: Symbol, span: Span) -> Ident {
641 /// Constructs a new identifier with an empty syntax context.
643 pub const fn with_empty_ctxt(name: Symbol) -> Ident {
644 Ident::new(name, DUMMY_SP)
648 pub fn invalid() -> Ident {
649 Ident::with_empty_ctxt(kw::Invalid)
652 /// Maps an interned string to an identifier with an empty syntax context.
653 pub fn from_interned_str(string: InternedString) -> Ident {
654 Ident::with_empty_ctxt(string.as_symbol())
657 /// Maps a string to an identifier with an empty span.
658 pub fn from_str(string: &str) -> Ident {
659 Ident::with_empty_ctxt(Symbol::intern(string))
662 /// Maps a string and a span to an identifier.
663 pub fn from_str_and_span(string: &str, span: Span) -> Ident {
664 Ident::new(Symbol::intern(string), span)
667 /// Replaces `lo` and `hi` with those from `span`, but keep hygiene context.
668 pub fn with_span_pos(self, span: Span) -> Ident {
669 Ident::new(self.name, span.with_ctxt(self.span.ctxt()))
672 pub fn without_first_quote(self) -> Ident {
673 Ident::new(Symbol::intern(self.as_str().trim_start_matches('\'')), self.span)
676 /// "Normalize" ident for use in comparisons using "item hygiene".
677 /// Identifiers with same string value become same if they came from the same "modern" macro
678 /// (e.g., `macro` item, but not `macro_rules` item) and stay different if they came from
679 /// different "modern" macros.
680 /// Technically, this operation strips all non-opaque marks from ident's syntactic context.
681 pub fn modern(self) -> Ident {
682 Ident::new(self.name, self.span.modern())
685 /// "Normalize" ident for use in comparisons using "local variable hygiene".
686 /// Identifiers with same string value become same if they came from the same non-transparent
687 /// macro (e.g., `macro` or `macro_rules!` items) and stay different if they came from different
688 /// non-transparent macros.
689 /// Technically, this operation strips all transparent marks from ident's syntactic context.
690 pub fn modern_and_legacy(self) -> Ident {
691 Ident::new(self.name, self.span.modern_and_legacy())
694 /// Transforms an identifier into one with the same name, but gensymed.
695 pub fn gensym(self) -> Ident {
696 let name = with_interner(|interner| interner.gensymed(self.name));
697 Ident::new(name, self.span)
700 /// Transforms an underscore identifier into one with the same name, but
701 /// gensymed. Leaves non-underscore identifiers unchanged.
702 pub fn gensym_if_underscore(self) -> Ident {
703 if self.name == kw::Underscore { self.gensym() } else { self }
706 // WARNING: this function is deprecated and will be removed in the future.
707 pub fn is_gensymed(self) -> bool {
708 with_interner(|interner| interner.is_gensymed(self.name))
711 pub fn as_str(self) -> LocalInternedString {
715 pub fn as_interned_str(self) -> InternedString {
716 self.name.as_interned_str()
720 impl PartialEq for Ident {
721 fn eq(&self, rhs: &Self) -> bool {
722 self.name == rhs.name && self.span.ctxt() == rhs.span.ctxt()
726 impl Hash for Ident {
727 fn hash<H: Hasher>(&self, state: &mut H) {
728 self.name.hash(state);
729 self.span.ctxt().hash(state);
733 impl fmt::Debug for Ident {
734 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
735 write!(f, "{}{:?}", self.name, self.span.ctxt())
739 impl fmt::Display for Ident {
740 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
741 fmt::Display::fmt(&self.name, f)
745 impl Encodable for Ident {
746 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
747 if self.span.ctxt().modern() == SyntaxContext::empty() {
748 s.emit_str(&self.as_str())
749 } else { // FIXME(jseyfried): intercrate hygiene
750 let mut string = "#".to_owned();
751 string.push_str(&self.as_str());
757 impl Decodable for Ident {
758 fn decode<D: Decoder>(d: &mut D) -> Result<Ident, D::Error> {
759 let string = d.read_str()?;
760 Ok(if !string.starts_with('#') {
761 Ident::from_str(&string)
762 } else { // FIXME(jseyfried): intercrate hygiene
763 Ident::from_str(&string[1..]).gensym()
768 /// A symbol is an interned or gensymed string. A gensym is a symbol that is
769 /// never equal to any other symbol.
771 /// Conceptually, a gensym can be thought of as a normal symbol with an
772 /// invisible unique suffix. Gensyms are useful when creating new identifiers
773 /// that must not match any existing identifiers, e.g. during macro expansion
774 /// and syntax desugaring. Because gensyms should always be identifiers, all
775 /// gensym operations are on `Ident` rather than `Symbol`. (Indeed, in the
776 /// future the gensym-ness may be moved from `Symbol` to hygiene data.)
780 /// assert_eq!(Ident::from_str("x"), Ident::from_str("x"))
781 /// assert_ne!(Ident::from_str("x").gensym(), Ident::from_str("x"))
782 /// assert_ne!(Ident::from_str("x").gensym(), Ident::from_str("x").gensym())
784 /// Internally, a symbol is implemented as an index, and all operations
785 /// (including hashing, equality, and ordering) operate on that index. The use
786 /// of `newtype_index!` means that `Option<Symbol>` only takes up 4 bytes,
787 /// because `newtype_index!` reserves the last 256 values for tagging purposes.
789 /// Note that `Symbol` cannot directly be a `newtype_index!` because it
790 /// implements `fmt::Debug`, `Encodable`, and `Decodable` in special ways.
791 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
792 pub struct Symbol(SymbolIndex);
795 pub struct SymbolIndex { .. }
799 const fn new(n: u32) -> Self {
800 Symbol(SymbolIndex::from_u32_const(n))
803 /// Maps a string to its interned representation.
804 pub fn intern(string: &str) -> Self {
805 with_interner(|interner| interner.intern(string))
808 pub fn as_str(self) -> LocalInternedString {
809 with_interner(|interner| unsafe {
810 LocalInternedString {
811 string: std::mem::transmute::<&str, &str>(interner.get(self))
816 pub fn as_interned_str(self) -> InternedString {
817 with_interner(|interner| InternedString {
818 symbol: interner.interned(self)
822 pub fn as_u32(self) -> u32 {
827 impl fmt::Debug for Symbol {
828 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
829 let is_gensymed = with_interner(|interner| interner.is_gensymed(*self));
831 write!(f, "{}({:?})", self, self.0)
833 write!(f, "{}", self)
838 impl fmt::Display for Symbol {
839 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
840 fmt::Display::fmt(&self.as_str(), f)
844 impl Encodable for Symbol {
845 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
846 s.emit_str(&self.as_str())
850 impl Decodable for Symbol {
851 fn decode<D: Decoder>(d: &mut D) -> Result<Symbol, D::Error> {
852 Ok(Symbol::intern(&d.read_str()?))
856 // The `&'static str`s in this type actually point into the arena.
858 // Note that normal symbols are indexed upward from 0, and gensyms are indexed
859 // downward from SymbolIndex::MAX_AS_U32.
861 pub struct Interner {
862 arena: DroplessArena,
863 names: FxHashMap<&'static str, Symbol>,
864 strings: Vec<&'static str>,
865 gensyms: Vec<Symbol>,
869 fn prefill(init: &[&str]) -> Self {
870 let mut this = Interner::default();
871 this.names.reserve(init.len());
872 this.strings.reserve(init.len());
874 // We can't allocate empty strings in the arena, so handle this here.
875 assert!(kw::Invalid.as_u32() == 0 && init[0].is_empty());
876 this.names.insert("", kw::Invalid);
877 this.strings.push("");
879 for string in &init[1..] {
885 pub fn intern(&mut self, string: &str) -> Symbol {
886 if let Some(&name) = self.names.get(string) {
890 let name = Symbol::new(self.strings.len() as u32);
892 // `from_utf8_unchecked` is safe since we just allocated a `&str` which is known to be
894 let string: &str = unsafe {
895 str::from_utf8_unchecked(self.arena.alloc_slice(string.as_bytes()))
897 // It is safe to extend the arena allocation to `'static` because we only access
898 // these while the arena is still alive.
899 let string: &'static str = unsafe {
900 &*(string as *const str)
902 self.strings.push(string);
903 self.names.insert(string, name);
907 fn interned(&self, symbol: Symbol) -> Symbol {
908 if (symbol.0.as_usize()) < self.strings.len() {
911 self.gensyms[(SymbolIndex::MAX_AS_U32 - symbol.0.as_u32()) as usize]
915 fn gensymed(&mut self, symbol: Symbol) -> Symbol {
916 self.gensyms.push(symbol);
917 Symbol::new(SymbolIndex::MAX_AS_U32 - self.gensyms.len() as u32 + 1)
920 fn is_gensymed(&mut self, symbol: Symbol) -> bool {
921 symbol.0.as_usize() >= self.strings.len()
924 // Get the symbol as a string. `Symbol::as_str()` should be used in
925 // preference to this function.
926 pub fn get(&self, symbol: Symbol) -> &str {
927 match self.strings.get(symbol.0.as_usize()) {
928 Some(string) => string,
930 let symbol = self.gensyms[(SymbolIndex::MAX_AS_U32 - symbol.0.as_u32()) as usize];
931 self.strings[symbol.0.as_usize()]
937 // This module has a very short name because it's used a lot.
943 // This module has a very short name because it's used a lot.
950 fn is_used_keyword_2018(self) -> bool {
954 fn is_unused_keyword_2018(self) -> bool {
955 self >= kw::Async && self <= kw::Try
958 /// Used for sanity checking rustdoc keyword sections.
959 pub fn is_doc_keyword(self) -> bool {
965 // Returns `true` for reserved identifiers used internally for elided lifetimes,
966 // unnamed method parameters, crate root module, error recovery etc.
967 pub fn is_special(self) -> bool {
968 self.name <= kw::Underscore
971 /// Returns `true` if the token is a keyword used in the language.
972 pub fn is_used_keyword(self) -> bool {
973 // Note: `span.edition()` is relatively expensive, don't call it unless necessary.
974 self.name >= kw::As && self.name <= kw::While ||
975 self.name.is_used_keyword_2018() && self.span.rust_2018()
978 /// Returns `true` if the token is a keyword reserved for possible future use.
979 pub fn is_unused_keyword(self) -> bool {
980 // Note: `span.edition()` is relatively expensive, don't call it unless necessary.
981 self.name >= kw::Abstract && self.name <= kw::Yield ||
982 self.name.is_unused_keyword_2018() && self.span.rust_2018()
985 /// Returns `true` if the token is either a special identifier or a keyword.
986 pub fn is_reserved(self) -> bool {
987 self.is_special() || self.is_used_keyword() || self.is_unused_keyword()
990 /// A keyword or reserved identifier that can be used as a path segment.
991 pub fn is_path_segment_keyword(self) -> bool {
992 self.name == kw::Super ||
993 self.name == kw::SelfLower ||
994 self.name == kw::SelfUpper ||
995 self.name == kw::Crate ||
996 self.name == kw::PathRoot ||
997 self.name == kw::DollarCrate
1000 /// This identifier can be a raw identifier.
1001 pub fn can_be_raw(self) -> bool {
1002 self.name != kw::Invalid && self.name != kw::Underscore &&
1003 !self.is_path_segment_keyword()
1006 /// We see this identifier in a normal identifier position, like variable name or a type.
1007 /// How was it written originally? Did it use the raw form? Let's try to guess.
1008 pub fn is_raw_guess(self) -> bool {
1009 self.can_be_raw() && self.is_reserved()
1013 // If an interner exists, return it. Otherwise, prepare a fresh one.
1015 fn with_interner<T, F: FnOnce(&mut Interner) -> T>(f: F) -> T {
1016 GLOBALS.with(|globals| f(&mut *globals.symbol_interner.lock()))
1019 /// An alternative to `Symbol` and `InternedString`, useful when the chars
1020 /// within the symbol need to be accessed. It is best used for temporary
1023 /// Because the interner outlives any thread which uses this type, we can
1024 /// safely treat `string` which points to interner data, as an immortal string,
1025 /// as long as this type never crosses between threads.
1027 // FIXME: ensure that the interner outlives any thread which uses
1028 // `LocalInternedString`, by creating a new thread right after constructing the
1030 #[derive(Clone, Copy, Hash, PartialOrd, Eq, Ord)]
1031 pub struct LocalInternedString {
1032 string: &'static str,
1035 impl LocalInternedString {
1036 /// Maps a string to its interned representation.
1037 pub fn intern(string: &str) -> Self {
1038 let string = with_interner(|interner| {
1039 let symbol = interner.intern(string);
1040 interner.strings[symbol.0.as_usize()]
1042 LocalInternedString {
1043 string: unsafe { std::mem::transmute::<&str, &str>(string) }
1047 pub fn as_interned_str(self) -> InternedString {
1049 symbol: Symbol::intern(self.string)
1053 pub fn get(&self) -> &str {
1054 // This returns a valid string since we ensure that `self` outlives the interner
1055 // by creating the interner on a thread which outlives threads which can access it.
1056 // This type cannot move to a thread which outlives the interner since it does
1057 // not implement Send.
1062 impl<U: ?Sized> std::convert::AsRef<U> for LocalInternedString
1064 str: std::convert::AsRef<U>
1066 fn as_ref(&self) -> &U {
1067 self.string.as_ref()
1071 impl<T: std::ops::Deref<Target = str>> std::cmp::PartialEq<T> for LocalInternedString {
1072 fn eq(&self, other: &T) -> bool {
1073 self.string == other.deref()
1077 impl std::cmp::PartialEq<LocalInternedString> for str {
1078 fn eq(&self, other: &LocalInternedString) -> bool {
1079 self == other.string
1083 impl<'a> std::cmp::PartialEq<LocalInternedString> for &'a str {
1084 fn eq(&self, other: &LocalInternedString) -> bool {
1085 *self == other.string
1089 impl std::cmp::PartialEq<LocalInternedString> for String {
1090 fn eq(&self, other: &LocalInternedString) -> bool {
1091 self == other.string
1095 impl<'a> std::cmp::PartialEq<LocalInternedString> for &'a String {
1096 fn eq(&self, other: &LocalInternedString) -> bool {
1097 *self == other.string
1101 impl !Send for LocalInternedString {}
1102 impl !Sync for LocalInternedString {}
1104 impl std::ops::Deref for LocalInternedString {
1106 fn deref(&self) -> &str { self.string }
1109 impl fmt::Debug for LocalInternedString {
1110 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1111 fmt::Debug::fmt(self.string, f)
1115 impl fmt::Display for LocalInternedString {
1116 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1117 fmt::Display::fmt(self.string, f)
1121 impl Decodable for LocalInternedString {
1122 fn decode<D: Decoder>(d: &mut D) -> Result<LocalInternedString, D::Error> {
1123 Ok(LocalInternedString::intern(&d.read_str()?))
1127 impl Encodable for LocalInternedString {
1128 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1129 s.emit_str(self.string)
1133 /// An alternative to `Symbol` that is focused on string contents. It has two
1134 /// main differences to `Symbol`.
1136 /// First, its implementations of `Hash`, `PartialOrd` and `Ord` work with the
1137 /// string chars rather than the symbol integer. This is useful when hash
1138 /// stability is required across compile sessions, or a guaranteed sort
1139 /// ordering is required.
1141 /// Second, gensym-ness is irrelevant. E.g.:
1143 /// assert_ne!(Symbol::gensym("x"), Symbol::gensym("x"))
1144 /// assert_eq!(Symbol::gensym("x").as_interned_str(), Symbol::gensym("x").as_interned_str())
1146 #[derive(Clone, Copy, PartialEq, Eq)]
1147 pub struct InternedString {
1151 impl InternedString {
1152 /// Maps a string to its interned representation.
1153 pub fn intern(string: &str) -> Self {
1155 symbol: Symbol::intern(string)
1159 pub fn with<F: FnOnce(&str) -> R, R>(self, f: F) -> R {
1160 let str = with_interner(|interner| {
1161 interner.get(self.symbol) as *const str
1163 // This is safe because the interner keeps string alive until it is dropped.
1164 // We can access it because we know the interner is still alive since we use a
1165 // scoped thread local to access it, and it was alive at the beginning of this scope
1169 fn with2<F: FnOnce(&str, &str) -> R, R>(self, other: &InternedString, f: F) -> R {
1170 let (self_str, other_str) = with_interner(|interner| {
1171 (interner.get(self.symbol) as *const str,
1172 interner.get(other.symbol) as *const str)
1174 // This is safe for the same reason that `with` is safe.
1175 unsafe { f(&*self_str, &*other_str) }
1178 pub fn as_symbol(self) -> Symbol {
1182 pub fn as_str(self) -> LocalInternedString {
1183 self.symbol.as_str()
1187 impl Hash for InternedString {
1188 fn hash<H: Hasher>(&self, state: &mut H) {
1189 self.with(|str| str.hash(state))
1193 impl PartialOrd<InternedString> for InternedString {
1194 fn partial_cmp(&self, other: &InternedString) -> Option<Ordering> {
1195 if self.symbol == other.symbol {
1196 return Some(Ordering::Equal);
1198 self.with2(other, |self_str, other_str| self_str.partial_cmp(other_str))
1202 impl Ord for InternedString {
1203 fn cmp(&self, other: &InternedString) -> Ordering {
1204 if self.symbol == other.symbol {
1205 return Ordering::Equal;
1207 self.with2(other, |self_str, other_str| self_str.cmp(other_str))
1211 impl fmt::Debug for InternedString {
1212 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1213 self.with(|str| fmt::Debug::fmt(&str, f))
1217 impl fmt::Display for InternedString {
1218 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1219 self.with(|str| fmt::Display::fmt(&str, f))
1223 impl Decodable for InternedString {
1224 fn decode<D: Decoder>(d: &mut D) -> Result<InternedString, D::Error> {
1225 Ok(InternedString::intern(&d.read_str()?))
1229 impl Encodable for InternedString {
1230 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1231 self.with(|string| s.emit_str(string))
1242 fn interner_tests() {
1243 let mut i: Interner = Interner::default();
1244 // first one is zero:
1245 assert_eq!(i.intern("dog"), Symbol::new(0));
1246 // re-use gets the same entry:
1247 assert_eq!(i.intern("dog"), Symbol::new(0));
1248 // different string gets a different #:
1249 assert_eq!(i.intern("cat"), Symbol::new(1));
1250 assert_eq!(i.intern("cat"), Symbol::new(1));
1251 // dog is still at zero
1252 assert_eq!(i.intern("dog"), Symbol::new(0));
1253 let z = i.intern("zebra");
1254 assert_eq!(i.gensymed(z), Symbol::new(SymbolIndex::MAX_AS_U32));
1255 // gensym of same string gets new number:
1256 assert_eq!(i.gensymed(z), Symbol::new(SymbolIndex::MAX_AS_U32 - 1));
1257 // gensym of *existing* string gets new number:
1258 let d = i.intern("dog");
1259 assert_eq!(i.gensymed(d), Symbol::new(SymbolIndex::MAX_AS_U32 - 2));
1263 fn without_first_quote_test() {
1264 GLOBALS.set(&Globals::new(edition::DEFAULT_EDITION), || {
1265 let i = Ident::from_str("'break");
1266 assert_eq!(i.without_first_quote().name, kw::Break);