Skip to content

Commit 2e84acc

Browse files
authored
Merge pull request #22964 from github/tausbn/yeast-isolate-interpolation-contexts
yeast: Isolate interpolation contexts from each other
2 parents 5313f23 + e6205e0 commit 2e84acc

3 files changed

Lines changed: 252 additions & 63 deletions

File tree

‎shared/yeast-macros/src/lower.rs‎

Lines changed: 94 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
use proc_macro2::{Ident, Span, TokenStream};
2-
use quote::quote;
1+
use proc_macro2::{Ident, Span, TokenStream, TokenTree};
2+
use quote::{quote, ToTokens};
33
use std::cell::RefCell;
44
use std::sync::atomic::{AtomicUsize, Ordering};
55

@@ -324,12 +324,16 @@ impl Template {
324324
quote! { __nodes.push(#node); }
325325
}
326326
Template::Splice(block) => {
327+
let uses_ctx = block_uses_ctx(block);
327328
let block = rust_block(block);
328-
quote! {
329-
let __value = ::std::iter::IntoIterator::into_iter(#block)
330-
.collect::<Vec<_>>();
331-
ctx.extend_field_ids(__value, &mut __nodes);
332-
}
329+
isolated_interpolation(
330+
uses_ctx,
331+
quote! {
332+
let __value = ::std::iter::IntoIterator::into_iter(#block)
333+
.collect::<Vec<_>>();
334+
ctx.extend_field_ids(__value, &mut __nodes);
335+
},
336+
)
333337
}
334338
Template::Choice(alternatives) => {
335339
let pick = Self::lower_choice(alternatives);
@@ -355,8 +359,14 @@ impl Template {
355359
match self {
356360
Template::Node(node) => node.lower(context),
357361
Template::Splice(block) => {
362+
let uses_ctx = block_uses_ctx(block);
358363
let block = rust_block(block);
359-
quote! { ::std::convert::Into::<yeast::OutputId>::into(#block) }
364+
isolated_interpolation(
365+
uses_ctx,
366+
quote! {
367+
::std::convert::Into::<yeast::OutputId>::into(#block)
368+
},
369+
)
360370
}
361371
Template::Choice(_) => {
362372
unreachable!("choices are lowered through Template::lower_choice")
@@ -453,35 +463,38 @@ impl Node {
453463
let node = match content {
454464
Content::Static(lit) => quote! { #ctx.literal(#kind_str, #lit) },
455465
Content::Computed(block) => {
466+
let uses_ctx = block_uses_ctx(block);
456467
let block = rust_block(block);
457468
if let Some(scope) = context.choice_alternative_scope {
458469
let value = fresh_prepared_ident("value");
459470
let source_range = fresh_prepared_ident("source_range");
471+
let expression = isolated_interpolation(
472+
uses_ctx,
473+
quote! {
474+
let __expr = #block;
475+
yeast::MaybeYeastValue::maybe_yeast_value(&__expr).map(
476+
|__value_ref| {
477+
(
478+
yeast::YeastDisplay::yeast_to_string(
479+
__value_ref,
480+
&#ctx,
481+
),
482+
yeast::YeastSourceRange::yeast_source_range(
483+
__value_ref,
484+
&#ctx,
485+
),
486+
)
487+
},
488+
)
489+
},
490+
);
460491
scope
461492
.interpolations
462493
.borrow_mut()
463494
.push(GuardingInterpolation {
464495
value: value.clone(),
465496
source_range: source_range.clone(),
466-
expression: quote! {
467-
{
468-
let __expr = #block;
469-
yeast::MaybeYeastValue::maybe_yeast_value(&__expr).map(
470-
|__value_ref| {
471-
(
472-
yeast::YeastDisplay::yeast_to_string(
473-
__value_ref,
474-
&#ctx,
475-
),
476-
yeast::YeastSourceRange::yeast_source_range(
477-
__value_ref,
478-
&#ctx,
479-
),
480-
)
481-
},
482-
)
483-
}
484-
},
497+
expression,
485498
});
486499
quote! {
487500
#ctx.literal_with_source_range(
@@ -491,8 +504,9 @@ impl Node {
491504
)
492505
}
493506
} else {
494-
quote! {
495-
{
507+
isolated_interpolation(
508+
uses_ctx,
509+
quote! {
496510
let __expr = #block;
497511
let __value =
498512
yeast::YeastDisplay::yeast_to_string(&__expr, &#ctx);
@@ -503,8 +517,8 @@ impl Node {
503517
&__value,
504518
__source_range,
505519
)
506-
}
507-
}
520+
},
521+
)
508522
}
509523
}
510524
Content::Inherited => quote! { #ctx.inherited_literal(#kind_str) },
@@ -524,12 +538,16 @@ impl Node {
524538
for (field_counter, field) in self.fields.iter().enumerate() {
525539
match field {
526540
Field::Location { block } => {
541+
let uses_ctx = block_uses_ctx(block);
527542
let block = rust_block(block);
528-
stmts.push(quote! {
529-
let __value = ::std::iter::IntoIterator::into_iter(#block)
530-
.collect::<Vec<_>>();
531-
#ctx.extend_location_ranges(__value, &mut __location_ranges);
532-
});
543+
stmts.push(isolated_interpolation(
544+
uses_ctx,
545+
quote! {
546+
let __value = ::std::iter::IntoIterator::into_iter(#block)
547+
.collect::<Vec<_>>();
548+
#ctx.extend_location_ranges(__value, &mut __location_ranges);
549+
},
550+
));
533551
}
534552
Field::LocationNone => {}
535553
Field::Named { name, value } => {
@@ -544,12 +562,19 @@ impl Node {
544562
);
545563
match value {
546564
Template::Splice(block) => {
565+
let uses_ctx = block_uses_ctx(block);
547566
let block = rust_block(block);
567+
let interpolation = isolated_interpolation(
568+
uses_ctx,
569+
quote! {
570+
let __value = ::std::iter::IntoIterator::into_iter(#block)
571+
.collect::<Vec<_>>();
572+
#ctx.extend_field_ids(__value, &mut #temp);
573+
},
574+
);
548575
stmts.push(quote! {
549576
let mut #temp: Vec<yeast::OutputId> = Vec::new();
550-
let __value = ::std::iter::IntoIterator::into_iter(#block)
551-
.collect::<Vec<_>>();
552-
#ctx.extend_field_ids(__value, &mut #temp);
577+
#interpolation
553578
});
554579
field_args.push(quote! {
555580
if !#temp.is_empty() {
@@ -612,3 +637,33 @@ fn rust_block(block: &syn::Block) -> TokenStream {
612637
let statements = &block.stmts;
613638
quote!({ #(#statements)* })
614639
}
640+
641+
fn isolated_interpolation(uses_ctx: bool, body: TokenStream) -> TokenStream {
642+
if uses_ctx {
643+
quote! {{
644+
let __saved_user_ctx = (*ctx.user_ctx).clone();
645+
let __result = { #body };
646+
*ctx.user_ctx = __saved_user_ctx;
647+
__result
648+
}}
649+
} else {
650+
quote! {{ #body }}
651+
}
652+
}
653+
654+
/// Returns whether `block` directly mentions `ctx`.
655+
///
656+
/// This lexical check cannot see context access hidden behind a helper or
657+
/// macro. Such an interpolation can opt into isolation by explicitly
658+
/// mentioning `ctx`, for example with `let _ = &ctx;`.
659+
fn block_uses_ctx(block: &syn::Block) -> bool {
660+
fn uses_ctx(tokens: TokenStream) -> bool {
661+
tokens.into_iter().any(|token| match token {
662+
TokenTree::Ident(ident) => ident == "ctx",
663+
TokenTree::Group(group) => uses_ctx(group.stream()),
664+
TokenTree::Punct(_) | TokenTree::Literal(_) => false,
665+
})
666+
}
667+
668+
uses_ctx(block.to_token_stream())
669+
}

‎shared/yeast/tests/test.rs‎

Lines changed: 147 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -943,6 +943,153 @@ fn test_choice_fallback_can_reuse_consumed_splice() {
943943
);
944944
}
945945

946+
#[derive(Clone, Default)]
947+
struct InterpolationContext {
948+
counter: u64,
949+
}
950+
951+
#[test]
952+
fn test_output_template_interpolations_clone_user_context() {
953+
let input = "x = 1";
954+
let input_ast = parse_input(input);
955+
let mut ast = empty_output_ast(input);
956+
let mut user_ctx = InterpolationContext::default();
957+
let mut ctx = yeast::build::BuildCtx::new(&input_ast, &mut ast, &mut user_ctx);
958+
let source = yeast::tree!((identifier "source"));
959+
960+
let nodes = yeast::trees!(
961+
(call
962+
location: {
963+
ctx.counter += 1;
964+
source
965+
}
966+
method: {
967+
ctx.counter += 1;
968+
let value = ctx.counter.to_string();
969+
ctx.literal("identifier", &value)
970+
}
971+
receiver: (identifier #{
972+
ctx.counter += 1;
973+
ctx.counter
974+
})
975+
)
976+
{
977+
ctx.counter += 1;
978+
let value = ctx.counter.to_string();
979+
[ctx.literal("identifier", &value)]
980+
}
981+
);
982+
983+
assert_eq!(ctx.counter, 0);
984+
assert_eq!(nodes.len(), 2);
985+
assert_dump_eq(
986+
&dump_ast(ctx.output, nodes[0], input),
987+
r#"
988+
call
989+
method: identifier "1"
990+
receiver: identifier "1"
991+
"#,
992+
);
993+
assert_dump_eq(
994+
&dump_ast(ctx.output, nodes[1], input),
995+
r#"
996+
identifier "1"
997+
"#,
998+
);
999+
}
1000+
1001+
#[test]
1002+
fn test_interpolation_preserves_build_ctx_method_borrowing() {
1003+
let input = "x = 1";
1004+
let input_ast = parse_input(input);
1005+
let mut ast = empty_output_ast(input);
1006+
let mut user_ctx = InterpolationContext::default();
1007+
let mut ctx = yeast::build::BuildCtx::new(&input_ast, &mut ast, &mut user_ctx);
1008+
let source = yeast::tree!((identifier "source"));
1009+
1010+
let node = yeast::tree!((call
1011+
method: {
1012+
ctx.literal("identifier", &ctx.source_text(source))
1013+
}
1014+
));
1015+
1016+
assert_dump_eq(
1017+
&dump_ast(ctx.output, node, input),
1018+
r#"
1019+
call
1020+
method: identifier "source"
1021+
"#,
1022+
);
1023+
}
1024+
1025+
#[test]
1026+
fn test_interpolation_preserves_user_context_assignment() {
1027+
let input = "x = 1";
1028+
let input_ast = parse_input(input);
1029+
let mut ast = empty_output_ast(input);
1030+
let mut user_ctx = InterpolationContext::default();
1031+
let mut ctx = yeast::build::BuildCtx::new(&input_ast, &mut ast, &mut user_ctx);
1032+
1033+
let node = yeast::tree!((identifier #{
1034+
*ctx = InterpolationContext { counter: 1 };
1035+
ctx.counter
1036+
}));
1037+
1038+
assert_eq!(ctx.counter, 0);
1039+
assert_dump_eq(
1040+
&dump_ast(ctx.output, node, input),
1041+
r#"
1042+
identifier "1"
1043+
"#,
1044+
);
1045+
}
1046+
1047+
#[test]
1048+
fn test_interpolation_accepts_borrowed_build_ctx() {
1049+
fn build_identifier(
1050+
ctx: &mut yeast::build::BuildCtx<'_, InterpolationContext>,
1051+
) -> yeast::OutputId {
1052+
yeast::tree!((identifier #{
1053+
ctx.counter += 1;
1054+
ctx.counter
1055+
}))
1056+
}
1057+
1058+
let input = "x = 1";
1059+
let input_ast = parse_input(input);
1060+
let mut ast = empty_output_ast(input);
1061+
let mut user_ctx = InterpolationContext::default();
1062+
let mut ctx = yeast::build::BuildCtx::new(&input_ast, &mut ast, &mut user_ctx);
1063+
1064+
let node = build_identifier(&mut ctx);
1065+
assert_eq!(ctx.counter, 0);
1066+
assert_dump_eq(
1067+
&dump_ast(ctx.output, node, input),
1068+
r#"
1069+
identifier "1"
1070+
"#,
1071+
);
1072+
}
1073+
1074+
#[derive(Clone, Default)]
1075+
struct BorrowedInterpolationContext {
1076+
locations: Vec<yeast::OutputId>,
1077+
}
1078+
1079+
#[test]
1080+
fn test_interpolation_accepts_value_borrowed_from_context() {
1081+
let input = "x = 1";
1082+
let input_ast = parse_input(input);
1083+
let mut ast = empty_output_ast(input);
1084+
let mut user_ctx = BorrowedInterpolationContext::default();
1085+
let mut ctx = yeast::build::BuildCtx::new(&input_ast, &mut ast, &mut user_ctx);
1086+
let location = yeast::tree!((identifier "location"));
1087+
ctx.locations.push(location);
1088+
let locations = ctx.locations.iter();
1089+
1090+
yeast::tree!((call location: {locations}));
1091+
}
1092+
9461093
#[test]
9471094
fn test_root_choice_returns_an_optional_node() {
9481095
let input = "x = 1";

0 commit comments

Comments
 (0)