Skip to content

Commit 0b90e4e

Browse files
committed
Auto merge of #46551 - jseyfried:improve_legacy_modern_macro_interaction, r=nrc
macros: improve 1.0/2.0 interaction This PR supports using unhygienic macros from hygienic macros without breaking the latter's hygiene. ```rust // crate A: #[macro_export] macro_rules! m1 { () => { f(); // unhygienic: this macro needs `f` in its environment fn g() {} // (1) unhygienic: `g` is usable outside the macro definition } } // crate B: #![feature(decl_macro)] extern crate A; use A::m1; macro m2() { fn f() {} // (2) m1!(); // After this PR, `f()` in the expansion resolves to (2), not (3) g(); // After this PR, this resolves to `fn g() {}` from the above expansion. // Today, it is a resolution error. } fn test() { fn f() {} // (3) m2!(); // Today, `m2!()` can see (3) even though it should be hygienic. fn g() {} // Today, this conflicts with `fn g() {}` from the expansion, even though it should be hygienic. } ``` Once this PR lands, you can make an existing unhygienic macro hygienic by wrapping it in a hygienic macro. There is an [example](b766fa8) of this in the tests. r? @nrc
2 parents 73ac5d6 + b766fa8 commit 0b90e4e

File tree

11 files changed

+217
-9
lines changed

11 files changed

+217
-9
lines changed

src/libproc_macro/lib.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -95,7 +95,7 @@ impl FromStr for TokenStream {
9595
// notify the expansion info that it is unhygienic
9696
let mark = Mark::fresh(mark);
9797
mark.set_expn_info(expn_info);
98-
let span = call_site.with_ctxt(call_site.ctxt().apply_mark(mark));
98+
let span = call_site.with_ctxt(SyntaxContext::empty().apply_mark(mark));
9999
let stream = parse::parse_stream_from_source_str(name, src, sess, Some(span));
100100
Ok(__internal::token_stream_wrap(stream))
101101
})

src/librustc_resolve/build_reduced_graph.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -156,7 +156,7 @@ impl<'a> Resolver<'a> {
156156

157157
// Disallow `use $crate;`
158158
if source.name == keywords::DollarCrate.name() && path.segments.len() == 1 {
159-
let crate_root = self.resolve_crate_root(source.ctxt);
159+
let crate_root = self.resolve_crate_root(source.ctxt, true);
160160
let crate_name = match crate_root.kind {
161161
ModuleKind::Def(_, name) => name,
162162
ModuleKind::Block(..) => unreachable!(),

src/librustc_resolve/lib.rs

+14-5
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ use rustc::hir::{Freevar, FreevarMap, TraitCandidate, TraitMap, GlobMap};
4242
use rustc::util::nodemap::{NodeMap, NodeSet, FxHashMap, FxHashSet, DefIdMap};
4343

4444
use syntax::codemap::{dummy_spanned, respan};
45-
use syntax::ext::hygiene::{Mark, SyntaxContext};
45+
use syntax::ext::hygiene::{Mark, MarkKind, SyntaxContext};
4646
use syntax::ast::{self, Name, NodeId, Ident, SpannedIdent, FloatTy, IntTy, UintTy};
4747
use syntax::ext::base::SyntaxExtension;
4848
use syntax::ext::base::Determinacy::{self, Determined, Undetermined};
@@ -1789,8 +1789,17 @@ impl<'a> Resolver<'a> {
17891789
result
17901790
}
17911791

1792-
fn resolve_crate_root(&mut self, mut ctxt: SyntaxContext) -> Module<'a> {
1793-
let module = match ctxt.adjust(Mark::root()) {
1792+
fn resolve_crate_root(&mut self, mut ctxt: SyntaxContext, legacy: bool) -> Module<'a> {
1793+
let mark = if legacy {
1794+
// When resolving `$crate` from a `macro_rules!` invoked in a `macro`,
1795+
// we don't want to pretend that the `macro_rules!` definition is in the `macro`
1796+
// as described in `SyntaxContext::apply_mark`, so we ignore prepended modern marks.
1797+
ctxt.marks().into_iter().find(|&mark| mark.kind() != MarkKind::Modern)
1798+
} else {
1799+
ctxt = ctxt.modern();
1800+
ctxt.adjust(Mark::root())
1801+
};
1802+
let module = match mark {
17941803
Some(def) => self.macro_def_scope(def),
17951804
None => return self.graph_root,
17961805
};
@@ -2992,11 +3001,11 @@ impl<'a> Resolver<'a> {
29923001
(i == 1 && name == keywords::Crate.name() &&
29933002
path[0].node.name == keywords::CrateRoot.name()) {
29943003
// `::a::b` or `::crate::a::b`
2995-
module = Some(self.resolve_crate_root(ident.node.ctxt.modern()));
3004+
module = Some(self.resolve_crate_root(ident.node.ctxt, false));
29963005
continue
29973006
} else if i == 0 && name == keywords::DollarCrate.name() {
29983007
// `$crate::a::b`
2999-
module = Some(self.resolve_crate_root(ident.node.ctxt));
3008+
module = Some(self.resolve_crate_root(ident.node.ctxt, true));
30003009
continue
30013010
} else if i == 1 && !token::Ident(ident.node).is_path_segment_keyword() {
30023011
let prev_name = path[0].node.name;

src/librustc_resolve/macros.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -140,7 +140,7 @@ impl<'a> base::Resolver for Resolver<'a> {
140140
let ident = path.segments[0].identifier;
141141
if ident.name == keywords::DollarCrate.name() {
142142
path.segments[0].identifier.name = keywords::CrateRoot.name();
143-
let module = self.0.resolve_crate_root(ident.ctxt);
143+
let module = self.0.resolve_crate_root(ident.ctxt, true);
144144
if !module.is_local() {
145145
let span = path.segments[0].span;
146146
path.segments.insert(1, match module.kind {

src/librustc_resolve/resolve_imports.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -623,7 +623,7 @@ impl<'a, 'b:'a> ImportResolver<'a, 'b> {
623623
"crate root imports need to be explicitly named: \
624624
`use crate as name;`".to_string()));
625625
} else {
626-
Some(self.resolve_crate_root(source.ctxt.modern()))
626+
Some(self.resolve_crate_root(source.ctxt.modern(), false))
627627
}
628628
} else if is_extern && !token::Ident(source).is_path_segment_keyword() {
629629
let crate_id =

src/libsyntax_pos/hygiene.rs

+39
Original file line numberDiff line numberDiff line change
@@ -188,6 +188,33 @@ impl SyntaxContext {
188188

189189
/// Extend a syntax context with a given mark
190190
pub fn apply_mark(self, mark: Mark) -> SyntaxContext {
191+
if mark.kind() == MarkKind::Modern {
192+
return self.apply_mark_internal(mark);
193+
}
194+
195+
let call_site_ctxt =
196+
mark.expn_info().map_or(SyntaxContext::empty(), |info| info.call_site.ctxt()).modern();
197+
if call_site_ctxt == SyntaxContext::empty() {
198+
return self.apply_mark_internal(mark);
199+
}
200+
201+
// Otherwise, `mark` is a macros 1.0 definition and the call site is in a
202+
// macros 2.0 expansion, i.e. a macros 1.0 invocation is in a macros 2.0 definition.
203+
//
204+
// In this case, the tokens from the macros 1.0 definition inherit the hygiene
205+
// at their invocation. That is, we pretend that the macros 1.0 definition
206+
// was defined at its invocation (i.e. inside the macros 2.0 definition)
207+
// so that the macros 2.0 definition remains hygienic.
208+
//
209+
// See the example at `test/run-pass/hygiene/legacy_interaction.rs`.
210+
let mut ctxt = call_site_ctxt;
211+
for mark in self.marks() {
212+
ctxt = ctxt.apply_mark_internal(mark);
213+
}
214+
ctxt.apply_mark_internal(mark)
215+
}
216+
217+
fn apply_mark_internal(self, mark: Mark) -> SyntaxContext {
191218
HygieneData::with(|data| {
192219
let syntax_contexts = &mut data.syntax_contexts;
193220
let mut modern = syntax_contexts[self.0 as usize].modern;
@@ -222,6 +249,18 @@ impl SyntaxContext {
222249
})
223250
}
224251

252+
pub fn marks(mut self) -> Vec<Mark> {
253+
HygieneData::with(|data| {
254+
let mut marks = Vec::new();
255+
while self != SyntaxContext::empty() {
256+
marks.push(data.syntax_contexts[self.0 as usize].outer_mark);
257+
self = data.syntax_contexts[self.0 as usize].prev_ctxt;
258+
}
259+
marks.reverse();
260+
marks
261+
})
262+
}
263+
225264
/// Adjust this context for resolution in a scope created by the given expansion.
226265
/// For example, consider the following three resolutions of `f`:
227266
///
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
2+
// file at the top-level directory of this distribution and at
3+
// http://rust-lang.org/COPYRIGHT.
4+
//
5+
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6+
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7+
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8+
// option. This file may not be copied, modified, or distributed
9+
// except according to those terms.
10+
11+
// ignore-pretty pretty-printing is unhygienic
12+
13+
#[macro_export]
14+
macro_rules! m {
15+
() => {
16+
fn f() {} // (2)
17+
g(); // (1)
18+
}
19+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
2+
// file at the top-level directory of this distribution and at
3+
// http://rust-lang.org/COPYRIGHT.
4+
//
5+
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6+
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7+
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8+
// option. This file may not be copied, modified, or distributed
9+
// except according to those terms.
10+
11+
pub fn f() {}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
2+
// file at the top-level directory of this distribution and at
3+
// http://rust-lang.org/COPYRIGHT.
4+
//
5+
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6+
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7+
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8+
// option. This file may not be copied, modified, or distributed
9+
// except according to those terms.
10+
11+
#![crate_type = "lib"]
12+
13+
extern crate my_crate;
14+
15+
pub fn g() {} // (a)
16+
17+
#[macro_export]
18+
macro_rules! unhygienic_macro {
19+
() => {
20+
// (1) unhygienic: depends on `my_crate` in the crate root at the invocation site.
21+
::my_crate::f();
22+
23+
// (2) unhygienic: defines `f` at the invocation site (in addition to the above point).
24+
use my_crate::f;
25+
f();
26+
27+
g(); // (3) unhygienic: `g` needs to be in scope at use site.
28+
29+
$crate::g(); // (4) hygienic: this always resolves to (a)
30+
}
31+
}
32+
33+
#[allow(unused)]
34+
fn test_unhygienic() {
35+
unhygienic_macro!();
36+
f(); // `f` was defined at the use site
37+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
2+
// file at the top-level directory of this distribution and at
3+
// http://rust-lang.org/COPYRIGHT.
4+
//
5+
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6+
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7+
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8+
// option. This file may not be copied, modified, or distributed
9+
// except according to those terms.
10+
11+
// ignore-pretty pretty-printing is unhygienic
12+
13+
// aux-build:legacy_interaction.rs
14+
15+
#![feature(decl_macro)]
16+
#[allow(unused)]
17+
18+
extern crate legacy_interaction;
19+
// ^ defines
20+
// ```rust
21+
// macro_rules! m {
22+
// () => {
23+
// fn f() // (1)
24+
// g() // (2)
25+
// }
26+
// }
27+
// ```rust
28+
29+
mod def_site {
30+
// Unless this macro opts out of hygiene, it should resolve the same wherever it is invoked.
31+
pub macro m2() {
32+
::legacy_interaction::m!();
33+
f(); // This should resolve to (1)
34+
fn g() {} // We want (2) resolve to this, not to (4)
35+
}
36+
}
37+
38+
mod use_site {
39+
fn test() {
40+
fn f() -> bool { true } // (3)
41+
fn g() -> bool { true } // (4)
42+
43+
::def_site::m2!();
44+
45+
let _: bool = f(); // This should resolve to (3)
46+
let _: bool = g(); // This should resolve to (4)
47+
}
48+
}
49+
50+
fn main() {}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
2+
// file at the top-level directory of this distribution and at
3+
// http://rust-lang.org/COPYRIGHT.
4+
//
5+
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6+
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7+
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8+
// option. This file may not be copied, modified, or distributed
9+
// except according to those terms.
10+
11+
// ignore-pretty pretty-printing is unhygienic
12+
13+
// aux-build:my_crate.rs
14+
// aux-build:unhygienic_example.rs
15+
16+
#![feature(decl_macro)]
17+
18+
extern crate unhygienic_example;
19+
extern crate my_crate; // (b)
20+
21+
// Hygienic version of `unhygienic_macro`.
22+
pub macro hygienic_macro() {
23+
fn g() {} // (c)
24+
::unhygienic_example::unhygienic_macro!();
25+
// ^ Even though we invoke an unhygienic macro, `hygienic_macro` remains hygienic.
26+
// In the above expansion:
27+
// (1) `my_crate` always resolves to (b) regardless of invocation site.
28+
// (2) The defined function `f` is only usable inside this macro definition.
29+
// (3) `g` always resolves to (c) regardless of invocation site.
30+
// (4) `$crate::g` remains hygienic and continues to resolve to (a).
31+
32+
f();
33+
}
34+
35+
#[allow(unused)]
36+
fn test_hygienic_macro() {
37+
hygienic_macro!();
38+
39+
fn f() {} // (d) no conflict
40+
f(); // resolves to (d)
41+
}
42+
43+
fn main() {}

0 commit comments

Comments
 (0)