Skip to content

Commit 139b5da

Browse files
committed
Auto merge of #60903 - nnethercote:mv-gensyms-from-Symbol-to-Ident, r=<try>
Move gensym operations from `Symbol` to `Ident` Gensyms are always at the `Ident` level, and long-term we probably want to record gensym-ness in hygiene data. r? @petrochenkov
2 parents 6afcb56 + ad5dd49 commit 139b5da

File tree

13 files changed

+68
-72
lines changed

13 files changed

+68
-72
lines changed

src/librustc/hir/lowering.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -856,7 +856,7 @@ impl<'a> LoweringContext<'a> {
856856
}
857857

858858
fn str_to_ident(&self, s: &'static str) -> Ident {
859-
Ident::with_empty_ctxt(Symbol::gensym(s))
859+
Ident::from_str(s).gensym()
860860
}
861861

862862
fn with_anonymous_lifetime_mode<R>(

src/librustc_allocator/expand.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -140,7 +140,7 @@ impl MutVisitor for ExpandAllocatorDirectives<'_> {
140140

141141
// Generate the submodule itself
142142
let name = f.kind.fn_name("allocator_abi");
143-
let allocator_abi = Ident::with_empty_ctxt(Symbol::gensym(&name));
143+
let allocator_abi = Ident::from_str(&name).gensym();
144144
let module = f.cx.item_mod(span, span, allocator_abi, Vec::new(), items);
145145
let module = f.cx.monotonic_expander().flat_map_item(module).pop().unwrap();
146146

src/librustc_resolve/build_reduced_graph.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -314,7 +314,7 @@ impl<'a> Resolver<'a> {
314314
Ident::new(keywords::SelfLower.name(), new_span)
315315
),
316316
kind: ast::UseTreeKind::Simple(
317-
Some(Ident::new(Name::gensym("__dummy"), new_span)),
317+
Some(Ident::from_str_and_span("__dummy", new_span).gensym()),
318318
ast::DUMMY_NODE_ID,
319319
ast::DUMMY_NODE_ID,
320320
),

src/librustc_resolve/lib.rs

+3-4
Original file line numberDiff line numberDiff line change
@@ -4225,7 +4225,7 @@ impl<'a> Resolver<'a> {
42254225
let add_module_candidates = |module: Module<'_>, names: &mut Vec<TypoSuggestion>| {
42264226
for (&(ident, _), resolution) in module.resolutions.borrow().iter() {
42274227
if let Some(binding) = resolution.borrow().binding {
4228-
if !ident.name.is_gensymed() && filter_fn(binding.res()) {
4228+
if !ident.is_gensymed() && filter_fn(binding.res()) {
42294229
names.push(TypoSuggestion {
42304230
candidate: ident.name,
42314231
article: binding.res().article(),
@@ -4243,7 +4243,7 @@ impl<'a> Resolver<'a> {
42434243
for rib in self.ribs[ns].iter().rev() {
42444244
// Locals and type parameters
42454245
for (ident, &res) in &rib.bindings {
4246-
if !ident.name.is_gensymed() && filter_fn(res) {
4246+
if !ident.is_gensymed() && filter_fn(res) {
42474247
names.push(TypoSuggestion {
42484248
candidate: ident.name,
42494249
article: res.article(),
@@ -4273,7 +4273,7 @@ impl<'a> Resolver<'a> {
42734273
},
42744274
);
42754275

4276-
if !ident.name.is_gensymed() && filter_fn(crate_mod) {
4276+
if !ident.is_gensymed() && filter_fn(crate_mod) {
42774277
Some(TypoSuggestion {
42784278
candidate: ident.name,
42794279
article: "a",
@@ -4298,7 +4298,6 @@ impl<'a> Resolver<'a> {
42984298
names.extend(
42994299
self.primitive_type_table.primitive_types
43004300
.iter()
4301-
.filter(|(name, _)| !name.is_gensymed())
43024301
.map(|(name, _)| {
43034302
TypoSuggestion {
43044303
candidate: *name,

src/librustc_resolve/resolve_imports.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -1395,7 +1395,7 @@ impl<'a, 'b:'a> ImportResolver<'a, 'b> {
13951395
// so they can cause name conflict errors downstream.
13961396
let is_good_import = binding.is_import() && !binding.is_ambiguity() &&
13971397
// Note that as_str() de-gensyms the Symbol
1398-
!(ident.name.is_gensymed() && ident.name.as_str() != "_");
1398+
!(ident.is_gensymed() && ident.name.as_str() != "_");
13991399
if is_good_import || binding.is_macro_def() {
14001400
let res = binding.res();
14011401
if res != Res::Err {

src/libsyntax/ast.rs

+1-5
Original file line numberDiff line numberDiff line change
@@ -72,11 +72,7 @@ pub struct Path {
7272
impl PartialEq<Symbol> for Path {
7373
fn eq(&self, symbol: &Symbol) -> bool {
7474
self.segments.len() == 1 && {
75-
let name = self.segments[0].ident.name;
76-
// Make sure these symbols are pure strings
77-
debug_assert!(!symbol.is_gensymed());
78-
debug_assert!(!name.is_gensymed());
79-
name == *symbol
75+
self.segments[0].ident.name == *symbol
8076
}
8177
}
8278
}

src/libsyntax/diagnostics/plugin.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ use crate::ext::base::{ExtCtxt, MacEager, MacResult};
77
use crate::ext::build::AstBuilder;
88
use crate::parse::token;
99
use crate::ptr::P;
10-
use crate::symbol::{keywords, Symbol};
10+
use crate::symbol::keywords;
1111
use crate::tokenstream::{TokenTree};
1212

1313
use smallvec::smallvec;
@@ -121,13 +121,13 @@ pub fn expand_register_diagnostic<'cx>(ecx: &'cx mut ExtCtxt<'_>,
121121

122122
let span = span.apply_mark(ecx.current_expansion.mark);
123123

124-
let sym = Ident::new(Symbol::gensym(&format!("__register_diagnostic_{}", code)), span);
124+
let name = Ident::from_str_and_span(&format!("__register_diagnostic_{}", code), span).gensym();
125125

126126
MacEager::items(smallvec![
127127
ecx.item_mod(
128128
span,
129129
span,
130-
sym,
130+
name,
131131
vec![],
132132
vec![],
133133
)

src/libsyntax/ext/tt/macro_rules.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -252,8 +252,8 @@ pub fn compile(
252252
def: &ast::Item,
253253
edition: Edition
254254
) -> SyntaxExtension {
255-
let lhs_nm = ast::Ident::with_empty_ctxt(Symbol::gensym("lhs"));
256-
let rhs_nm = ast::Ident::with_empty_ctxt(Symbol::gensym("rhs"));
255+
let lhs_nm = ast::Ident::from_str("lhs").gensym();
256+
let rhs_nm = ast::Ident::from_str("rhs").gensym();
257257

258258
// Parse the macro_rules! invocation
259259
let body = match def.node {

src/libsyntax/std_inject.rs

+8-11
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ use crate::ast;
22
use crate::attr;
33
use crate::edition::Edition;
44
use crate::ext::hygiene::{Mark, SyntaxContext};
5-
use crate::symbol::{Symbol, keywords, sym};
5+
use crate::symbol::{Ident, Symbol, keywords, sym};
66
use crate::source_map::{ExpnInfo, MacroAttribute, dummy_spanned, hygiene, respan};
77
use crate::ptr::P;
88
use crate::tokenstream::TokenStream;
@@ -63,18 +63,15 @@ pub fn maybe_inject_crates_ref(
6363

6464
// .rev() to preserve ordering above in combination with insert(0, ...)
6565
let alt_std_name = alt_std_name.map(Symbol::intern);
66-
for orig_name in names.iter().rev() {
67-
let orig_name = Symbol::intern(orig_name);
68-
let mut rename = orig_name;
66+
for orig_name_str in names.iter().rev() {
6967
// HACK(eddyb) gensym the injected crates on the Rust 2018 edition,
7068
// so they don't accidentally interfere with the new import paths.
71-
if rust_2018 {
72-
rename = orig_name.gensymed();
73-
}
74-
let orig_name = if rename != orig_name {
75-
Some(orig_name)
69+
let orig_name_sym = Symbol::intern(orig_name_str);
70+
let orig_name_ident = Ident::with_empty_ctxt(orig_name_sym);
71+
let (rename, orig_name) = if rust_2018 {
72+
(orig_name_ident.gensym(), Some(orig_name_sym))
7673
} else {
77-
None
74+
(orig_name_ident, None)
7875
};
7976
krate.module.items.insert(0, P(ast::Item {
8077
attrs: vec![attr::mk_attr_outer(
@@ -84,7 +81,7 @@ pub fn maybe_inject_crates_ref(
8481
)],
8582
vis: dummy_spanned(ast::VisibilityKind::Inherited),
8683
node: ast::ItemKind::ExternCrate(alt_std_name.or(orig_name)),
87-
ident: ast::Ident::with_empty_ctxt(rename),
84+
ident: rename,
8885
id: ast::DUMMY_NODE_ID,
8986
span: DUMMY_SP,
9087
tokens: None,

src/libsyntax/test.rs

+7-6
Original file line numberDiff line numberDiff line change
@@ -232,11 +232,11 @@ fn mk_reexport_mod(cx: &mut TestCtxt<'_>,
232232
items,
233233
};
234234

235-
let sym = Ident::with_empty_ctxt(Symbol::gensym("__test_reexports"));
235+
let name = Ident::from_str("__test_reexports").gensym();
236236
let parent = if parent == ast::DUMMY_NODE_ID { ast::CRATE_NODE_ID } else { parent };
237237
cx.ext_cx.current_expansion.mark = cx.ext_cx.resolver.get_module_scope(parent);
238238
let it = cx.ext_cx.monotonic_expander().flat_map_item(P(ast::Item {
239-
ident: sym,
239+
ident: name,
240240
attrs: Vec::new(),
241241
id: ast::DUMMY_NODE_ID,
242242
node: ast::ItemKind::Mod(reexport_mod),
@@ -245,7 +245,7 @@ fn mk_reexport_mod(cx: &mut TestCtxt<'_>,
245245
tokens: None,
246246
})).pop().unwrap();
247247

248-
(it, sym)
248+
(it, name)
249249
}
250250

251251
/// Crawl over the crate, inserting test reexports and the test main function
@@ -373,9 +373,10 @@ fn mk_main(cx: &mut TestCtxt<'_>) -> P<ast::Item> {
373373
main_body);
374374

375375
// Honor the reexport_test_harness_main attribute
376-
let main_id = Ident::new(
377-
cx.reexport_test_harness_main.unwrap_or(Symbol::gensym("main")),
378-
sp);
376+
let main_id = match cx.reexport_test_harness_main {
377+
Some(sym) => Ident::new(sym, sp),
378+
None => Ident::from_str_and_span("main", sp).gensym(),
379+
};
379380

380381
P(ast::Item {
381382
ident: main_id,

src/libsyntax_ext/proc_macro_decls.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -429,7 +429,7 @@ fn mk_decls(
429429
let module = cx.item_mod(
430430
span,
431431
span,
432-
ast::Ident::with_empty_ctxt(Symbol::gensym("decls")),
432+
ast::Ident::from_str("decls").gensym(),
433433
vec![doc_hidden],
434434
vec![krate, decls_static],
435435
).map(|mut i| {

src/libsyntax_ext/test.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -127,7 +127,7 @@ pub fn expand_test_or_bench(
127127
])
128128
};
129129

130-
let mut test_const = cx.item(sp, ast::Ident::new(item.ident.name.gensymed(), sp),
130+
let mut test_const = cx.item(sp, ast::Ident::new(item.ident.name, sp).gensym(),
131131
vec![
132132
// #[cfg(test)]
133133
cx.attribute(attr_sp, cx.meta_list(attr_sp, Symbol::intern("cfg"), vec![

src/libsyntax_pos/symbol.rs

+38-35
Original file line numberDiff line numberDiff line change
@@ -623,10 +623,12 @@ pub struct Ident {
623623

624624
impl Ident {
625625
#[inline]
626+
/// constructs a new identifier from a symbol and a span.
626627
pub const fn new(name: Symbol, span: Span) -> Ident {
627628
Ident { name, span }
628629
}
629630

631+
/// Constructs a new identifier with an empty syntax context.
630632
#[inline]
631633
pub const fn with_empty_ctxt(name: Symbol) -> Ident {
632634
Ident::new(name, DUMMY_SP)
@@ -637,11 +639,16 @@ impl Ident {
637639
Ident::with_empty_ctxt(string.as_symbol())
638640
}
639641

640-
/// Maps a string to an identifier with an empty syntax context.
642+
/// Maps a string to an identifier with an empty span.
641643
pub fn from_str(string: &str) -> Ident {
642644
Ident::with_empty_ctxt(Symbol::intern(string))
643645
}
644646

647+
/// Maps a string and a span to an identifier.
648+
pub fn from_str_and_span(string: &str, span: Span) -> Ident {
649+
Ident::new(Symbol::intern(string), span)
650+
}
651+
645652
/// Replaces `lo` and `hi` with those from `span`, but keep hygiene context.
646653
pub fn with_span_pos(self, span: Span) -> Ident {
647654
Ident::new(self.name, span.with_ctxt(self.span.ctxt()))
@@ -669,14 +676,23 @@ impl Ident {
669676
Ident::new(self.name, self.span.modern_and_legacy())
670677
}
671678

679+
/// Transforms an identifier into one with the same name, but gensymed.
672680
pub fn gensym(self) -> Ident {
673-
Ident::new(self.name.gensymed(), self.span)
681+
let name = with_interner(|interner| interner.gensymed(self.name));
682+
Ident::new(name, self.span)
674683
}
675684

685+
/// Transforms an underscore identifier into one with the same name, but
686+
/// gensymed. Leaves non-underscore identifiers unchanged.
676687
pub fn gensym_if_underscore(self) -> Ident {
677688
if self.name == keywords::Underscore.name() { self.gensym() } else { self }
678689
}
679690

691+
// WARNING: this function is deprecated and will be removed in the future.
692+
pub fn is_gensymed(self) -> bool {
693+
with_interner(|interner| interner.is_gensymed(self.name))
694+
}
695+
680696
pub fn as_str(self) -> LocalInternedString {
681697
self.name.as_str()
682698
}
@@ -729,30 +745,34 @@ impl Decodable for Ident {
729745
Ok(if !string.starts_with('#') {
730746
Ident::from_str(&string)
731747
} else { // FIXME(jseyfried): intercrate hygiene
732-
Ident::with_empty_ctxt(Symbol::gensym(&string[1..]))
748+
Ident::from_str(&string[1..]).gensym()
733749
})
734750
}
735751
}
736752

737753
/// A symbol is an interned or gensymed string. A gensym is a symbol that is
738-
/// never equal to any other symbol. E.g.:
739-
/// ```
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"))
743-
/// ```
754+
/// never equal to any other symbol.
755+
///
744756
/// Conceptually, a gensym can be thought of as a normal symbol with an
745757
/// invisible unique suffix. Gensyms are useful when creating new identifiers
746758
/// that must not match any existing identifiers, e.g. during macro expansion
747-
/// and syntax desugaring.
759+
/// and syntax desugaring. Because gensyms should always be identifiers, all
760+
/// gensym operations are on `Ident` rather than `Symbol`. (Indeed, in the
761+
/// future the gensym-ness may be moved from `Symbol` to hygiene data.)
748762
///
749-
/// Internally, a Symbol is implemented as an index, and all operations
763+
/// Examples:
764+
/// ```
765+
/// assert_eq!(Ident::from_str("x"), Ident::from_str("x"))
766+
/// assert_ne!(Ident::from_str("x").gensym(), Ident::from_str("x"))
767+
/// assert_ne!(Ident::from_str("x").gensym(), Ident::from_str("x").gensym())
768+
/// ```
769+
/// Internally, a symbol is implemented as an index, and all operations
750770
/// (including hashing, equality, and ordering) operate on that index. The use
751771
/// of `newtype_index!` means that `Option<Symbol>` only takes up 4 bytes,
752772
/// because `newtype_index!` reserves the last 256 values for tagging purposes.
753773
///
754-
/// Note that `Symbol` cannot directly be a `newtype_index!` because it implements
755-
/// `fmt::Debug`, `Encodable`, and `Decodable` in special ways.
774+
/// Note that `Symbol` cannot directly be a `newtype_index!` because it
775+
/// implements `fmt::Debug`, `Encodable`, and `Decodable` in special ways.
756776
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
757777
pub struct Symbol(SymbolIndex);
758778

@@ -770,20 +790,6 @@ impl Symbol {
770790
with_interner(|interner| interner.intern(string))
771791
}
772792

773-
/// Gensyms a new `usize`, using the current interner.
774-
pub fn gensym(string: &str) -> Self {
775-
with_interner(|interner| interner.gensym(string))
776-
}
777-
778-
pub fn gensymed(self) -> Self {
779-
with_interner(|interner| interner.gensymed(self))
780-
}
781-
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))
785-
}
786-
787793
pub fn as_str(self) -> LocalInternedString {
788794
with_interner(|interner| unsafe {
789795
LocalInternedString {
@@ -891,11 +897,6 @@ impl Interner {
891897
}
892898
}
893899

894-
fn gensym(&mut self, string: &str) -> Symbol {
895-
let symbol = self.intern(string);
896-
self.gensymed(symbol)
897-
}
898-
899900
fn gensymed(&mut self, symbol: Symbol) -> Symbol {
900901
self.gensyms.push(symbol);
901902
Symbol::new(SymbolIndex::MAX_AS_U32 - self.gensyms.len() as u32 + 1)
@@ -1263,11 +1264,13 @@ mod tests {
12631264
assert_eq!(i.intern("cat"), Symbol::new(1));
12641265
// dog is still at zero
12651266
assert_eq!(i.intern("dog"), Symbol::new(0));
1266-
assert_eq!(i.gensym("zebra"), Symbol::new(SymbolIndex::MAX_AS_U32));
1267+
let z = i.intern("zebra");
1268+
assert_eq!(i.gensymed(z), Symbol::new(SymbolIndex::MAX_AS_U32));
12671269
// gensym of same string gets new number:
1268-
assert_eq!(i.gensym("zebra"), Symbol::new(SymbolIndex::MAX_AS_U32 - 1));
1270+
assert_eq!(i.gensymed(z), Symbol::new(SymbolIndex::MAX_AS_U32 - 1));
12691271
// gensym of *existing* string gets new number:
1270-
assert_eq!(i.gensym("dog"), Symbol::new(SymbolIndex::MAX_AS_U32 - 2));
1272+
let d = i.intern("dog");
1273+
assert_eq!(i.gensymed(d), Symbol::new(SymbolIndex::MAX_AS_U32 - 2));
12711274
}
12721275

12731276
#[test]

0 commit comments

Comments
 (0)