Skip to content

fix: Pass the correct per-token (not global) edition when expanding macro_rules #20164

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 2 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

52 changes: 30 additions & 22 deletions crates/hir-def/src/macro_expansion_tests/mbe.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1958,28 +1958,6 @@ fn f() {
);
}

#[test]
fn test_edition_handling_in() {
check(
r#"
//- /main.rs crate:main deps:old edition:2021
fn f() {
old::parse_try_old!(try!{});
}
//- /old.rs crate:old edition:2015
#[macro_export]
macro_rules! parse_try_old {
($it:expr) => {};
}
"#,
expect![[r#"
fn f() {
;
}
"#]],
);
}

#[test]
fn semicolon_does_not_glue() {
check(
Expand Down Expand Up @@ -2051,3 +2029,33 @@ fn f() {
"#]],
);
}

#[test]
fn per_token_edition() {
check(
r#"
//- /foo.rs crate:foo edition:2024
#[macro_export]
macro_rules! m {
($e:expr) => {};
}
//- /bar.rs crate:bar deps:foo edition:2021
fn gen() -> usize {
0
}

fn foo() {
foo::m!(gen());
}
"#,
expect![[r#"
fn gen() -> usize {
0
}

fn foo() {
;
}
"#]],
);
}
4 changes: 2 additions & 2 deletions crates/hir-expand/src/builtin/fn_macro.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ use syntax::{
use syntax_bridge::syntax_node_to_token_tree;

use crate::{
EditionedFileId, ExpandError, ExpandResult, Lookup as _, MacroCallId,
EditionedFileId, ExpandError, ExpandResult, MacroCallId,
builtin::quote::{WithDelimiter, dollar_crate, quote},
db::ExpandDatabase,
hygiene::{span_with_call_site_ctxt, span_with_def_site_ctxt},
Expand Down Expand Up @@ -229,9 +229,9 @@ fn assert_expand(
let mut iter = tt.iter();

let cond = expect_fragment(
db,
&mut iter,
parser::PrefixEntryPoint::Expr,
id.lookup(db).krate.data(db).edition,
tt.top_subtree().delimiter.delim_span(),
);
_ = iter.expect_char(',');
Expand Down
2 changes: 1 addition & 1 deletion crates/hir-expand/src/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -298,7 +298,7 @@ pub fn expand_speculative(
pseudo_derive_attr_expansion(&tt, attr_arg.as_ref()?, span)
}
MacroDefKind::Declarative(it) => {
db.decl_macro_expander(loc.krate, it).expand_unhygienic(tt, span, loc.def.edition)
db.decl_macro_expander(loc.krate, it).expand_unhygienic(db, tt, span)
}
MacroDefKind::BuiltIn(_, it) => {
it.expand(db, actual_macro_call, &tt, span).map_err(Into::into)
Expand Down
13 changes: 5 additions & 8 deletions crates/hir-expand/src/declarative.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@ impl DeclarativeMacroExpander {
call_id: MacroCallId,
span: Span,
) -> ExpandResult<(tt::TopSubtree, Option<u32>)> {
let loc = db.lookup_intern_macro_call(call_id);
match self.mac.err() {
Some(_) => ExpandResult::new(
(tt::TopSubtree::empty(tt::DelimSpan { open: span, close: span }), None),
Expand All @@ -41,34 +40,32 @@ impl DeclarativeMacroExpander {
None => self
.mac
.expand(
db,
&tt,
|s| {
s.ctx =
apply_mark(db, s.ctx, call_id.into(), self.transparency, self.edition)
},
span,
loc.def.edition,
)
.map_err(Into::into),
}
}

pub fn expand_unhygienic(
&self,
db: &dyn ExpandDatabase,
tt: tt::TopSubtree,
call_site: Span,
def_site_edition: Edition,
) -> ExpandResult<tt::TopSubtree> {
match self.mac.err() {
Some(_) => ExpandResult::new(
tt::TopSubtree::empty(tt::DelimSpan { open: call_site, close: call_site }),
ExpandError::new(call_site, ExpandErrorKind::MacroDefinition),
),
None => self
.mac
.expand(&tt, |_| (), call_site, def_site_edition)
.map(TupleExt::head)
.map_err(Into::into),
None => {
self.mac.expand(db, &tt, |_| (), call_site).map(TupleExt::head).map_err(Into::into)
}
}
}

Expand Down
1 change: 1 addition & 0 deletions crates/mbe/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ rustc-hash.workspace = true
smallvec.workspace = true
arrayvec.workspace = true
ra-ap-rustc_lexer.workspace = true
salsa.workspace = true

# local deps
parser.workspace = true
Expand Down
10 changes: 6 additions & 4 deletions crates/mbe/src/benchmark.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

use intern::Symbol;
use rustc_hash::FxHashMap;
use span::{Edition, Span};
use span::Span;
use stdx::itertools::Itertools;
use syntax::{
AstNode,
Expand Down Expand Up @@ -44,15 +44,16 @@ fn benchmark_expand_macro_rules() {
if skip_slow_tests() {
return;
}
let db = salsa::DatabaseImpl::default();
let rules = macro_rules_fixtures();
let invocations = invocation_fixtures(&rules);
let invocations = invocation_fixtures(&db, &rules);

let hash: usize = {
let _pt = bench("mbe expand macro rules");
invocations
.into_iter()
.map(|(id, tt)| {
let res = rules[&id].expand(&tt, |_| (), DUMMY, Edition::CURRENT);
let res = rules[&id].expand(&db, &tt, |_| (), DUMMY);
assert!(res.err.is_none());
res.value.0.0.len()
})
Expand Down Expand Up @@ -92,6 +93,7 @@ fn macro_rules_fixtures_tt() -> FxHashMap<String, tt::TopSubtree<Span>> {

/// Generate random invocation fixtures from rules
fn invocation_fixtures(
db: &dyn salsa::Database,
rules: &FxHashMap<String, DeclarativeMacro>,
) -> Vec<(String, tt::TopSubtree<Span>)> {
let mut seed = 123456789;
Expand Down Expand Up @@ -123,7 +125,7 @@ fn invocation_fixtures(
}
let subtree = builder.build();

if it.expand(&subtree, |_| (), DUMMY, Edition::CURRENT).err.is_none() {
if it.expand(db, &subtree, |_| (), DUMMY).err.is_none() {
res.push((name.clone(), subtree));
break;
}
Expand Down
6 changes: 3 additions & 3 deletions crates/mbe/src/expander.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,20 +7,20 @@ mod transcriber;

use intern::Symbol;
use rustc_hash::FxHashMap;
use span::{Edition, Span};
use span::Span;

use crate::{ExpandError, ExpandErrorKind, ExpandResult, MatchedArmIndex, parser::MetaVarKind};

pub(crate) fn expand_rules(
db: &dyn salsa::Database,
rules: &[crate::Rule],
input: &tt::TopSubtree<Span>,
marker: impl Fn(&mut Span) + Copy,
call_site: Span,
def_site_edition: Edition,
) -> ExpandResult<(tt::TopSubtree<Span>, MatchedArmIndex)> {
let mut match_: Option<(matcher::Match<'_>, &crate::Rule, usize)> = None;
for (idx, rule) in rules.iter().enumerate() {
let new_match = matcher::match_(&rule.lhs, input, def_site_edition);
let new_match = matcher::match_(db, &rule.lhs, input);

if new_match.err.is_none() {
// If we find a rule that applies without errors, we're done.
Expand Down
22 changes: 11 additions & 11 deletions crates/mbe/src/expander/matcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ use std::{rc::Rc, sync::Arc};

use intern::{Symbol, sym};
use smallvec::{SmallVec, smallvec};
use span::{Edition, Span};
use span::Span;
use tt::{
DelimSpan,
iter::{TtElement, TtIter},
Expand Down Expand Up @@ -112,11 +112,11 @@ impl Match<'_> {

/// Matching errors are added to the `Match`.
pub(super) fn match_<'t>(
db: &dyn salsa::Database,
pattern: &'t MetaTemplate,
input: &'t tt::TopSubtree<Span>,
edition: Edition,
) -> Match<'t> {
let mut res = match_loop(pattern, input, edition);
let mut res = match_loop(db, pattern, input);
res.bound_count = count(res.bindings.bindings());
return res;

Expand Down Expand Up @@ -365,6 +365,7 @@ struct MatchState<'t> {
/// - `error_items`: the set of items in errors, used for error-resilient parsing
#[inline]
fn match_loop_inner<'t>(
db: &dyn salsa::Database,
src: TtIter<'t, Span>,
stack: &[TtIter<'t, Span>],
res: &mut Match<'t>,
Expand All @@ -375,7 +376,6 @@ fn match_loop_inner<'t>(
eof_items: &mut SmallVec<[MatchState<'t>; 1]>,
error_items: &mut SmallVec<[MatchState<'t>; 1]>,
delim_span: tt::DelimSpan<Span>,
edition: Edition,
) {
macro_rules! try_push {
($items: expr, $it:expr) => {
Expand Down Expand Up @@ -486,7 +486,7 @@ fn match_loop_inner<'t>(
OpDelimited::Op(Op::Var { kind, name, .. }) => {
if let &Some(kind) = kind {
let mut fork = src.clone();
let match_res = match_meta_var(kind, &mut fork, delim_span, edition);
let match_res = match_meta_var(db, kind, &mut fork, delim_span);
match match_res.err {
None => {
// Some meta variables are optional (e.g. vis)
Expand Down Expand Up @@ -621,9 +621,9 @@ fn match_loop_inner<'t>(
}

fn match_loop<'t>(
db: &dyn salsa::Database,
pattern: &'t MetaTemplate,
src: &'t tt::TopSubtree<Span>,
edition: Edition,
) -> Match<'t> {
let span = src.top_subtree().delimiter.delim_span();
let mut src = src.iter();
Expand Down Expand Up @@ -655,6 +655,7 @@ fn match_loop<'t>(
stdx::always!(next_items.is_empty());

match_loop_inner(
db,
src.clone(),
&stack,
&mut res,
Expand All @@ -665,7 +666,6 @@ fn match_loop<'t>(
&mut eof_items,
&mut error_items,
span,
edition,
);
stdx::always!(cur_items.is_empty());

Expand Down Expand Up @@ -772,14 +772,14 @@ fn match_loop<'t>(
}

fn match_meta_var<'t>(
db: &dyn salsa::Database,
kind: MetaVarKind,
input: &mut TtIter<'t, Span>,
delim_span: DelimSpan<Span>,
edition: Edition,
) -> ExpandResult<Fragment<'t>> {
let fragment = match kind {
MetaVarKind::Path => {
return expect_fragment(input, parser::PrefixEntryPoint::Path, edition, delim_span)
return expect_fragment(db, input, parser::PrefixEntryPoint::Path, delim_span)
.map(Fragment::Path);
}
MetaVarKind::Expr(expr) => {
Expand Down Expand Up @@ -807,7 +807,7 @@ fn match_meta_var<'t>(
}
_ => {}
};
return expect_fragment(input, parser::PrefixEntryPoint::Expr, edition, delim_span)
return expect_fragment(db, input, parser::PrefixEntryPoint::Expr, delim_span)
.map(Fragment::Expr);
}
MetaVarKind::Ident | MetaVarKind::Tt | MetaVarKind::Lifetime | MetaVarKind::Literal => {
Expand Down Expand Up @@ -853,7 +853,7 @@ fn match_meta_var<'t>(
MetaVarKind::Item => parser::PrefixEntryPoint::Item,
MetaVarKind::Vis => parser::PrefixEntryPoint::Vis,
};
expect_fragment(input, fragment, edition, delim_span).map(Fragment::Tokens)
expect_fragment(db, input, fragment, delim_span).map(Fragment::Tokens)
}

fn collect_vars(collector_fun: &mut impl FnMut(Symbol), pattern: &MetaTemplate) {
Expand Down
11 changes: 5 additions & 6 deletions crates/mbe/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -251,12 +251,12 @@ impl DeclarativeMacro {

pub fn expand(
&self,
db: &dyn salsa::Database,
tt: &tt::TopSubtree<Span>,
marker: impl Fn(&mut Span) + Copy,
call_site: Span,
def_site_edition: Edition,
) -> ExpandResult<(tt::TopSubtree<Span>, MatchedArmIndex)> {
expander::expand_rules(&self.rules, tt, marker, call_site, def_site_edition)
expander::expand_rules(db, &self.rules, tt, marker, call_site)
}
}

Expand Down Expand Up @@ -362,16 +362,15 @@ impl<T: Default, E> From<Result<T, E>> for ValueResult<T, E> {
}

pub fn expect_fragment<'t>(
db: &dyn salsa::Database,
tt_iter: &mut TtIter<'t, Span>,
entry_point: ::parser::PrefixEntryPoint,
edition: ::parser::Edition,
delim_span: DelimSpan<Span>,
) -> ExpandResult<tt::TokenTreesView<'t, Span>> {
use ::parser;
let buffer = tt_iter.remaining();
// FIXME: Pass the correct edition per token. Due to the split between mbe and hir-expand it's complicated.
let parser_input = to_parser_input(buffer, &mut |_ctx| edition);
let tree_traversal = entry_point.parse(&parser_input, edition);
let parser_input = to_parser_input(buffer, &mut |ctx| ctx.edition(db));
let tree_traversal = entry_point.parse(&parser_input, Edition::CURRENT_FIXME);
let mut cursor = buffer.cursor();
let mut error = false;
for step in tree_traversal.iter() {
Expand Down
3 changes: 2 additions & 1 deletion crates/mbe/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ fn check_(
expect: expect_test::Expect,
parse: parser::TopEntryPoint,
) {
let db = salsa::DatabaseImpl::default();
let decl_tt = &syntax_bridge::parse_to_token_tree(
def_edition,
SpanAnchor {
Expand Down Expand Up @@ -49,14 +50,14 @@ fn check_(
)
.unwrap();
let res = mac.expand(
&db,
&arg_tt,
|_| (),
Span {
range: TextRange::up_to(TextSize::of(arg)),
anchor: call_anchor,
ctx: SyntaxContext::root(Edition::CURRENT),
},
def_edition,
);
let mut expect_res = String::new();
if let Some(err) = res.err {
Expand Down