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_bounds,
145 associated_type_defaults,
151 augmented_assignments,
152 automatically_derived,
153 avx512_target_feature,
158 bind_by_move_pattern_guards,
160 borrowck_graphviz_postflow,
161 borrowck_graphviz_preflow,
164 braced_empty_structs,
171 cfg_target_has_atomic,
172 cfg_target_thread_local,
178 closure_to_fn_coercion,
180 cmpxchg16b_target_feature,
185 conservative_impl_trait,
187 const_compare_raw_pointers,
196 const_raw_ptr_to_usize_cast,
208 crate_visibility_modifier,
211 custom_inner_attributes,
212 custom_test_frameworks,
216 default_lib_allocator,
217 default_type_parameter_fallback,
230 document_private_items,
231 dotdoteq_in_patterns,
232 dotdot_in_tuple_patterns,
233 double_braced_crate: "{{crate}}",
234 double_braced_impl: "{{impl}}",
235 double_braced_misc: "{{misc}}",
236 double_braced_closure: "{{closure}}",
237 double_braced_constructor: "{{constructor}}",
238 double_braced_constant: "{{constant}}",
239 double_braced_opaque: "{{opaque}}",
241 dropck_parametricity,
252 exclusive_range_pattern,
253 exhaustive_integer_patterns,
259 extern_absolute_paths,
261 extern_crate_item_prelude,
272 field_init_shorthand,
292 generic_associated_types,
301 hexagon_target_feature,
303 homogeneous_aggregate,
317 if_while_or_patterns,
319 impl_header_lifetime_elision,
320 impl_trait_in_bindings,
326 inclusive_range_syntax,
327 infer_outlives_requirements,
328 infer_static_outlives_requirements,
335 irrefutable_let_patterns,
338 issue_5723_bootstrap,
339 issue_tracker_base_url,
356 link_llvm_intrinsics,
364 macro_at_most_once_rep,
367 macro_lifetime_matcher,
368 macro_literal_matcher,
379 match_beginning_vert,
380 match_default_bindings,
390 movbe_target_feature,
424 omit_gdb_pretty_printer_section,
431 optin_builtin_traits,
439 overlapping_marker_traits,
444 panic_implementation,
461 poll_with_tls_context,
462 powerpc_target_feature,
463 precise_pointer_size_matching,
467 proc_dash_macro: "proc-macro",
469 proc_macro_attribute,
476 proc_macro_non_items,
477 proc_macro_path_invoc,
481 quad_precision_float,
494 reexport_test_harness_main,
504 re_rebalance_coherence,
517 rustc_allocator_nounwind,
518 rustc_allow_const_fn_ptr,
519 rustc_args_required_const,
522 rustc_const_unstable,
523 rustc_conversion_suggestion,
524 rustc_copy_clone_marker,
527 rustc_diagnostic_macros,
529 rustc_doc_only_macro,
530 rustc_dump_env_program_clauses,
531 rustc_dump_program_clauses,
532 rustc_dump_user_substs,
534 rustc_expected_cgu_reuse,
535 rustc_if_this_changed,
536 rustc_inherit_overflow_checks,
538 rustc_layout_scalar_valid_range_end,
539 rustc_layout_scalar_valid_range_start,
541 rustc_nonnull_optimization_guaranteed,
542 rustc_object_lifetime_default,
543 rustc_on_unimplemented,
546 rustc_partition_codegened,
547 rustc_partition_reused,
549 rustc_peek_definite_init,
550 rustc_peek_maybe_init,
551 rustc_peek_maybe_uninit,
553 rustc_proc_macro_decls,
557 rustc_std_internal_symbol,
561 rustc_then_this_would_need,
562 rustc_transparent_macro,
566 rust_eh_unwind_resume,
568 __rust_unstable_column,
569 rvalue_static_promotion,
585 sse4a_target_feature,
596 stmt_expr_attributes,
598 struct_field_attributes,
610 termination_trait_test,
613 test_accepted_feature,
615 test_removed_feature,
635 type_alias_enum_variants,
645 underscore_const_names,
647 underscore_lifetimes,
649 universal_impl_trait,
652 unrestricted_attribute_tokens,
653 unsafe_destructor_blind_to_params,
656 unsized_tuple_coercion,
671 visible_private_types,
674 warn_directory_ownership,
684 #[derive(Copy, Clone, Eq)]
692 /// Constructs a new identifier from a symbol and a span.
693 pub const fn new(name: Symbol, span: Span) -> Ident {
697 /// Constructs a new identifier with an empty syntax context.
699 pub const fn with_empty_ctxt(name: Symbol) -> Ident {
700 Ident::new(name, DUMMY_SP)
704 pub fn invalid() -> Ident {
705 Ident::with_empty_ctxt(kw::Invalid)
708 /// Maps an interned string to an identifier with an empty syntax context.
709 pub fn from_interned_str(string: InternedString) -> Ident {
710 Ident::with_empty_ctxt(string.as_symbol())
713 /// Maps a string to an identifier with an empty span.
714 pub fn from_str(string: &str) -> Ident {
715 Ident::with_empty_ctxt(Symbol::intern(string))
718 /// Maps a string and a span to an identifier.
719 pub fn from_str_and_span(string: &str, span: Span) -> Ident {
720 Ident::new(Symbol::intern(string), span)
723 /// Replaces `lo` and `hi` with those from `span`, but keep hygiene context.
724 pub fn with_span_pos(self, span: Span) -> Ident {
725 Ident::new(self.name, span.with_ctxt(self.span.ctxt()))
728 pub fn without_first_quote(self) -> Ident {
729 Ident::new(Symbol::intern(self.as_str().trim_start_matches('\'')), self.span)
732 /// "Normalize" ident for use in comparisons using "item hygiene".
733 /// Identifiers with same string value become same if they came from the same "modern" macro
734 /// (e.g., `macro` item, but not `macro_rules` item) and stay different if they came from
735 /// different "modern" macros.
736 /// Technically, this operation strips all non-opaque marks from ident's syntactic context.
737 pub fn modern(self) -> Ident {
738 Ident::new(self.name, self.span.modern())
741 /// "Normalize" ident for use in comparisons using "local variable hygiene".
742 /// Identifiers with same string value become same if they came from the same non-transparent
743 /// macro (e.g., `macro` or `macro_rules!` items) and stay different if they came from different
744 /// non-transparent macros.
745 /// Technically, this operation strips all transparent marks from ident's syntactic context.
746 pub fn modern_and_legacy(self) -> Ident {
747 Ident::new(self.name, self.span.modern_and_legacy())
750 /// Transforms an identifier into one with the same name, but gensymed.
751 pub fn gensym(self) -> Ident {
752 let name = with_interner(|interner| interner.gensymed(self.name));
753 Ident::new(name, self.span)
756 /// Transforms an underscore identifier into one with the same name, but
757 /// gensymed. Leaves non-underscore identifiers unchanged.
758 pub fn gensym_if_underscore(self) -> Ident {
759 if self.name == kw::Underscore { self.gensym() } else { self }
762 // WARNING: this function is deprecated and will be removed in the future.
763 pub fn is_gensymed(self) -> bool {
764 with_interner(|interner| interner.is_gensymed(self.name))
767 pub fn as_str(self) -> LocalInternedString {
771 pub fn as_interned_str(self) -> InternedString {
772 self.name.as_interned_str()
776 impl PartialEq for Ident {
777 fn eq(&self, rhs: &Self) -> bool {
778 self.name == rhs.name && self.span.ctxt() == rhs.span.ctxt()
782 impl Hash for Ident {
783 fn hash<H: Hasher>(&self, state: &mut H) {
784 self.name.hash(state);
785 self.span.ctxt().hash(state);
789 impl fmt::Debug for Ident {
790 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
791 write!(f, "{}{:?}", self.name, self.span.ctxt())
795 impl fmt::Display for Ident {
796 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
797 fmt::Display::fmt(&self.name, f)
801 impl Encodable for Ident {
802 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
803 if self.span.ctxt().modern() == SyntaxContext::empty() {
804 s.emit_str(&self.as_str())
805 } else { // FIXME(jseyfried): intercrate hygiene
806 let mut string = "#".to_owned();
807 string.push_str(&self.as_str());
813 impl Decodable for Ident {
814 fn decode<D: Decoder>(d: &mut D) -> Result<Ident, D::Error> {
815 let string = d.read_str()?;
816 Ok(if !string.starts_with('#') {
817 Ident::from_str(&string)
818 } else { // FIXME(jseyfried): intercrate hygiene
819 Ident::from_str(&string[1..]).gensym()
824 /// A symbol is an interned or gensymed string. A gensym is a symbol that is
825 /// never equal to any other symbol.
827 /// Conceptually, a gensym can be thought of as a normal symbol with an
828 /// invisible unique suffix. Gensyms are useful when creating new identifiers
829 /// that must not match any existing identifiers, e.g. during macro expansion
830 /// and syntax desugaring. Because gensyms should always be identifiers, all
831 /// gensym operations are on `Ident` rather than `Symbol`. (Indeed, in the
832 /// future the gensym-ness may be moved from `Symbol` to hygiene data.)
836 /// assert_eq!(Ident::from_str("x"), Ident::from_str("x"))
837 /// assert_ne!(Ident::from_str("x").gensym(), Ident::from_str("x"))
838 /// assert_ne!(Ident::from_str("x").gensym(), Ident::from_str("x").gensym())
840 /// Internally, a symbol is implemented as an index, and all operations
841 /// (including hashing, equality, and ordering) operate on that index. The use
842 /// of `newtype_index!` means that `Option<Symbol>` only takes up 4 bytes,
843 /// because `newtype_index!` reserves the last 256 values for tagging purposes.
845 /// Note that `Symbol` cannot directly be a `newtype_index!` because it
846 /// implements `fmt::Debug`, `Encodable`, and `Decodable` in special ways.
847 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
848 pub struct Symbol(SymbolIndex);
851 pub struct SymbolIndex { .. }
855 const fn new(n: u32) -> Self {
856 Symbol(SymbolIndex::from_u32_const(n))
859 /// Maps a string to its interned representation.
860 pub fn intern(string: &str) -> Self {
861 with_interner(|interner| interner.intern(string))
864 pub fn as_str(self) -> LocalInternedString {
865 with_interner(|interner| unsafe {
866 LocalInternedString {
867 string: std::mem::transmute::<&str, &str>(interner.get(self))
872 pub fn as_interned_str(self) -> InternedString {
873 with_interner(|interner| InternedString {
874 symbol: interner.interned(self)
878 pub fn as_u32(self) -> u32 {
883 impl fmt::Debug for Symbol {
884 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
885 let is_gensymed = with_interner(|interner| interner.is_gensymed(*self));
887 write!(f, "{}({:?})", self, self.0)
889 write!(f, "{}", self)
894 impl fmt::Display for Symbol {
895 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
896 fmt::Display::fmt(&self.as_str(), f)
900 impl Encodable for Symbol {
901 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
902 s.emit_str(&self.as_str())
906 impl Decodable for Symbol {
907 fn decode<D: Decoder>(d: &mut D) -> Result<Symbol, D::Error> {
908 Ok(Symbol::intern(&d.read_str()?))
912 // The `&'static str`s in this type actually point into the arena.
914 // Note that normal symbols are indexed upward from 0, and gensyms are indexed
915 // downward from SymbolIndex::MAX_AS_U32.
917 pub struct Interner {
918 arena: DroplessArena,
919 names: FxHashMap<&'static str, Symbol>,
920 strings: Vec<&'static str>,
921 gensyms: Vec<Symbol>,
925 fn prefill(init: &[&'static str]) -> Self {
927 strings: init.into(),
928 names: init.iter().copied().zip((0..).map(Symbol::new)).collect(),
933 pub fn intern(&mut self, string: &str) -> Symbol {
934 if let Some(&name) = self.names.get(string) {
938 let name = Symbol::new(self.strings.len() as u32);
940 // `from_utf8_unchecked` is safe since we just allocated a `&str` which is known to be
942 let string: &str = unsafe {
943 str::from_utf8_unchecked(self.arena.alloc_slice(string.as_bytes()))
945 // It is safe to extend the arena allocation to `'static` because we only access
946 // these while the arena is still alive.
947 let string: &'static str = unsafe {
948 &*(string as *const str)
950 self.strings.push(string);
951 self.names.insert(string, name);
955 fn interned(&self, symbol: Symbol) -> Symbol {
956 if (symbol.0.as_usize()) < self.strings.len() {
959 self.gensyms[(SymbolIndex::MAX_AS_U32 - symbol.0.as_u32()) as usize]
963 fn gensymed(&mut self, symbol: Symbol) -> Symbol {
964 self.gensyms.push(symbol);
965 Symbol::new(SymbolIndex::MAX_AS_U32 - self.gensyms.len() as u32 + 1)
968 fn is_gensymed(&mut self, symbol: Symbol) -> bool {
969 symbol.0.as_usize() >= self.strings.len()
972 // Get the symbol as a string. `Symbol::as_str()` should be used in
973 // preference to this function.
974 pub fn get(&self, symbol: Symbol) -> &str {
975 match self.strings.get(symbol.0.as_usize()) {
976 Some(string) => string,
978 let symbol = self.gensyms[(SymbolIndex::MAX_AS_U32 - symbol.0.as_u32()) as usize];
979 self.strings[symbol.0.as_usize()]
985 // This module has a very short name because it's used a lot.
991 // This module has a very short name because it's used a lot.
993 use std::convert::TryInto;
998 // Get the symbol for an integer. The first few non-negative integers each
999 // have a static symbol and therefore are fast.
1000 pub fn integer<N: TryInto<usize> + Copy + ToString>(n: N) -> Symbol {
1001 if let Result::Ok(idx) = n.try_into() {
1002 if let Option::Some(&sym) = digits_array.get(idx) {
1006 Symbol::intern(&n.to_string())
1011 fn is_used_keyword_2018(self) -> bool {
1015 fn is_unused_keyword_2018(self) -> bool {
1016 self >= kw::Async && self <= kw::Try
1019 /// Used for sanity checking rustdoc keyword sections.
1020 pub fn is_doc_keyword(self) -> bool {
1024 /// A keyword or reserved identifier that can be used as a path segment.
1025 pub fn is_path_segment_keyword(self) -> bool {
1026 self == kw::Super ||
1027 self == kw::SelfLower ||
1028 self == kw::SelfUpper ||
1029 self == kw::Crate ||
1030 self == kw::PathRoot ||
1031 self == kw::DollarCrate
1034 /// This symbol can be a raw identifier.
1035 pub fn can_be_raw(self) -> bool {
1036 self != kw::Invalid && self != kw::Underscore && !self.is_path_segment_keyword()
1041 // Returns `true` for reserved identifiers used internally for elided lifetimes,
1042 // unnamed method parameters, crate root module, error recovery etc.
1043 pub fn is_special(self) -> bool {
1044 self.name <= kw::Underscore
1047 /// Returns `true` if the token is a keyword used in the language.
1048 pub fn is_used_keyword(self) -> bool {
1049 // Note: `span.edition()` is relatively expensive, don't call it unless necessary.
1050 self.name >= kw::As && self.name <= kw::While ||
1051 self.name.is_used_keyword_2018() && self.span.rust_2018()
1054 /// Returns `true` if the token is a keyword reserved for possible future use.
1055 pub fn is_unused_keyword(self) -> bool {
1056 // Note: `span.edition()` is relatively expensive, don't call it unless necessary.
1057 self.name >= kw::Abstract && self.name <= kw::Yield ||
1058 self.name.is_unused_keyword_2018() && self.span.rust_2018()
1061 /// Returns `true` if the token is either a special identifier or a keyword.
1062 pub fn is_reserved(self) -> bool {
1063 self.is_special() || self.is_used_keyword() || self.is_unused_keyword()
1066 /// A keyword or reserved identifier that can be used as a path segment.
1067 pub fn is_path_segment_keyword(self) -> bool {
1068 self.name.is_path_segment_keyword()
1071 /// We see this identifier in a normal identifier position, like variable name or a type.
1072 /// How was it written originally? Did it use the raw form? Let's try to guess.
1073 pub fn is_raw_guess(self) -> bool {
1074 self.name.can_be_raw() && self.is_reserved()
1078 // If an interner exists, return it. Otherwise, prepare a fresh one.
1080 fn with_interner<T, F: FnOnce(&mut Interner) -> T>(f: F) -> T {
1081 GLOBALS.with(|globals| f(&mut *globals.symbol_interner.lock()))
1084 /// An alternative to `Symbol` and `InternedString`, useful when the chars
1085 /// within the symbol need to be accessed. It is best used for temporary
1088 /// Because the interner outlives any thread which uses this type, we can
1089 /// safely treat `string` which points to interner data, as an immortal string,
1090 /// as long as this type never crosses between threads.
1092 // FIXME: ensure that the interner outlives any thread which uses
1093 // `LocalInternedString`, by creating a new thread right after constructing the
1095 #[derive(Clone, Copy, Hash, PartialOrd, Eq, Ord)]
1096 pub struct LocalInternedString {
1097 string: &'static str,
1100 impl LocalInternedString {
1101 /// Maps a string to its interned representation.
1102 pub fn intern(string: &str) -> Self {
1103 let string = with_interner(|interner| {
1104 let symbol = interner.intern(string);
1105 interner.strings[symbol.0.as_usize()]
1107 LocalInternedString {
1108 string: unsafe { std::mem::transmute::<&str, &str>(string) }
1112 pub fn as_interned_str(self) -> InternedString {
1114 symbol: Symbol::intern(self.string)
1118 pub fn get(&self) -> &str {
1119 // This returns a valid string since we ensure that `self` outlives the interner
1120 // by creating the interner on a thread which outlives threads which can access it.
1121 // This type cannot move to a thread which outlives the interner since it does
1122 // not implement Send.
1127 impl<U: ?Sized> std::convert::AsRef<U> for LocalInternedString
1129 str: std::convert::AsRef<U>
1131 fn as_ref(&self) -> &U {
1132 self.string.as_ref()
1136 impl<T: std::ops::Deref<Target = str>> std::cmp::PartialEq<T> for LocalInternedString {
1137 fn eq(&self, other: &T) -> bool {
1138 self.string == other.deref()
1142 impl std::cmp::PartialEq<LocalInternedString> for str {
1143 fn eq(&self, other: &LocalInternedString) -> bool {
1144 self == other.string
1148 impl<'a> std::cmp::PartialEq<LocalInternedString> for &'a str {
1149 fn eq(&self, other: &LocalInternedString) -> bool {
1150 *self == other.string
1154 impl std::cmp::PartialEq<LocalInternedString> for String {
1155 fn eq(&self, other: &LocalInternedString) -> bool {
1156 self == other.string
1160 impl<'a> std::cmp::PartialEq<LocalInternedString> for &'a String {
1161 fn eq(&self, other: &LocalInternedString) -> bool {
1162 *self == other.string
1166 impl !Send for LocalInternedString {}
1167 impl !Sync for LocalInternedString {}
1169 impl std::ops::Deref for LocalInternedString {
1171 fn deref(&self) -> &str { self.string }
1174 impl fmt::Debug for LocalInternedString {
1175 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1176 fmt::Debug::fmt(self.string, f)
1180 impl fmt::Display for LocalInternedString {
1181 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1182 fmt::Display::fmt(self.string, f)
1186 impl Decodable for LocalInternedString {
1187 fn decode<D: Decoder>(d: &mut D) -> Result<LocalInternedString, D::Error> {
1188 Ok(LocalInternedString::intern(&d.read_str()?))
1192 impl Encodable for LocalInternedString {
1193 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1194 s.emit_str(self.string)
1198 /// An alternative to `Symbol` that is focused on string contents. It has two
1199 /// main differences to `Symbol`.
1201 /// First, its implementations of `Hash`, `PartialOrd` and `Ord` work with the
1202 /// string chars rather than the symbol integer. This is useful when hash
1203 /// stability is required across compile sessions, or a guaranteed sort
1204 /// ordering is required.
1206 /// Second, gensym-ness is irrelevant. E.g.:
1208 /// assert_ne!(Symbol::gensym("x"), Symbol::gensym("x"))
1209 /// assert_eq!(Symbol::gensym("x").as_interned_str(), Symbol::gensym("x").as_interned_str())
1211 #[derive(Clone, Copy, PartialEq, Eq)]
1212 pub struct InternedString {
1216 impl InternedString {
1217 /// Maps a string to its interned representation.
1218 pub fn intern(string: &str) -> Self {
1220 symbol: Symbol::intern(string)
1224 pub fn with<F: FnOnce(&str) -> R, R>(self, f: F) -> R {
1225 let str = with_interner(|interner| {
1226 interner.get(self.symbol) as *const str
1228 // This is safe because the interner keeps string alive until it is dropped.
1229 // We can access it because we know the interner is still alive since we use a
1230 // scoped thread local to access it, and it was alive at the beginning of this scope
1234 fn with2<F: FnOnce(&str, &str) -> R, R>(self, other: &InternedString, f: F) -> R {
1235 let (self_str, other_str) = with_interner(|interner| {
1236 (interner.get(self.symbol) as *const str,
1237 interner.get(other.symbol) as *const str)
1239 // This is safe for the same reason that `with` is safe.
1240 unsafe { f(&*self_str, &*other_str) }
1243 pub fn as_symbol(self) -> Symbol {
1247 pub fn as_str(self) -> LocalInternedString {
1248 self.symbol.as_str()
1252 impl Hash for InternedString {
1253 fn hash<H: Hasher>(&self, state: &mut H) {
1254 self.with(|str| str.hash(state))
1258 impl PartialOrd<InternedString> for InternedString {
1259 fn partial_cmp(&self, other: &InternedString) -> Option<Ordering> {
1260 if self.symbol == other.symbol {
1261 return Some(Ordering::Equal);
1263 self.with2(other, |self_str, other_str| self_str.partial_cmp(other_str))
1267 impl Ord for InternedString {
1268 fn cmp(&self, other: &InternedString) -> Ordering {
1269 if self.symbol == other.symbol {
1270 return Ordering::Equal;
1272 self.with2(other, |self_str, other_str| self_str.cmp(other_str))
1276 impl fmt::Debug for InternedString {
1277 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1278 self.with(|str| fmt::Debug::fmt(&str, f))
1282 impl fmt::Display for InternedString {
1283 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1284 self.with(|str| fmt::Display::fmt(&str, f))
1288 impl Decodable for InternedString {
1289 fn decode<D: Decoder>(d: &mut D) -> Result<InternedString, D::Error> {
1290 Ok(InternedString::intern(&d.read_str()?))
1294 impl Encodable for InternedString {
1295 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1296 self.with(|string| s.emit_str(string))
1307 fn interner_tests() {
1308 let mut i: Interner = Interner::default();
1309 // first one is zero:
1310 assert_eq!(i.intern("dog"), Symbol::new(0));
1311 // re-use gets the same entry:
1312 assert_eq!(i.intern("dog"), Symbol::new(0));
1313 // different string gets a different #:
1314 assert_eq!(i.intern("cat"), Symbol::new(1));
1315 assert_eq!(i.intern("cat"), Symbol::new(1));
1316 // dog is still at zero
1317 assert_eq!(i.intern("dog"), Symbol::new(0));
1318 let z = i.intern("zebra");
1319 assert_eq!(i.gensymed(z), Symbol::new(SymbolIndex::MAX_AS_U32));
1320 // gensym of same string gets new number:
1321 assert_eq!(i.gensymed(z), Symbol::new(SymbolIndex::MAX_AS_U32 - 1));
1322 // gensym of *existing* string gets new number:
1323 let d = i.intern("dog");
1324 assert_eq!(i.gensymed(d), Symbol::new(SymbolIndex::MAX_AS_U32 - 2));
1328 fn without_first_quote_test() {
1329 GLOBALS.set(&Globals::new(edition::DEFAULT_EDITION), || {
1330 let i = Ident::from_str("'break");
1331 assert_eq!(i.without_first_quote().name, kw::Break);