diff --git a/shared/yeast-macros/src/ast.rs b/shared/yeast-macros/src/ast.rs index 0f341fcef29d..d9ca25ea1656 100644 --- a/shared/yeast-macros/src/ast.rs +++ b/shared/yeast-macros/src/ast.rs @@ -2,6 +2,21 @@ use std::collections::BTreeSet; use proc_macro2::{Ident, Literal}; +/// An imperative query match over one input or output AST node. +pub(crate) struct QueryMatch { + /// Rust expression yielding the node to match. + pub(crate) node: syn::Expr, + /// Ordered query arms. + pub(crate) arms: Vec, +} + +/// One query, optional guard, and Rust result body. +pub(crate) struct QueryMatchArm { + pub(crate) pattern: Pattern, + pub(crate) guard: Option, + pub(crate) body: syn::Block, +} + /// A complete rewrite rule such as `(input) where guard => (output)`. pub(crate) struct Rule { /// Input pattern before `where` or `=>`. diff --git a/shared/yeast-macros/src/lib.rs b/shared/yeast-macros/src/lib.rs index 682e60eda2b6..0206a585b437 100644 --- a/shared/yeast-macros/src/lib.rs +++ b/shared/yeast-macros/src/lib.rs @@ -50,6 +50,52 @@ pub fn query(input: TokenStream) -> TokenStream { } } +#[doc(hidden)] +#[proc_macro] +pub fn query_match_with_schema(input: TokenStream) -> TokenStream { + let input2: TokenStream2 = input.into(); + match parse::parse_query_match_with_schema_top(input2) { + Ok(output) => output.into(), + Err(err) => err.to_compile_error().into(), + } +} + +#[doc(hidden)] +#[proc_macro] +pub fn query_match_with_schema_and_context(input: TokenStream) -> TokenStream { + let input2: TokenStream2 = input.into(); + match parse::parse_query_match_with_schema_and_context_top(input2) { + Ok(output) => output.into(), + Err(err) => err.to_compile_error().into(), + } +} + +/// Declare a matcher namespace for one AST schema. +/// +/// ```ignore +/// yeast::query_match_schema! { +/// swift_input, +/// "swift_node_types.yml", +/// } +/// +/// use swift_input::{query_match, query_match_with_context}; +/// +/// yeast::query_match_schema! { +/// swift_output, +/// "ast_types.yml", +/// } +/// +/// use swift_output::query_match as output_query_match; +/// ``` +#[proc_macro] +pub fn query_match_schema(input: TokenStream) -> TokenStream { + let input2: TokenStream2 = input.into(); + match parse::parse_query_match_schema_top(input2) { + Ok(output) => output.into(), + Err(err) => err.to_compile_error().into(), + } +} + /// Build a single AST node from a template, returning its `OutputId`. /// /// A top-level choice returns `Option`. diff --git a/shared/yeast-macros/src/lower.rs b/shared/yeast-macros/src/lower.rs index 4b4b0c0a9be3..b4a27500ec92 100644 --- a/shared/yeast-macros/src/lower.rs +++ b/shared/yeast-macros/src/lower.rs @@ -1,10 +1,12 @@ use proc_macro2::{Ident, Span, TokenStream, TokenTree}; -use quote::{quote, ToTokens}; +use quote::{quote, quote_spanned, ToTokens}; use std::cell::RefCell; use std::sync::atomic::{AtomicUsize, Ordering}; +use syn::spanned::Spanned; use crate::ast::{ - Alternative, Cardinality, Content, Field, Node, Pattern, Replacement, Rule, Template, + Alternative, Cardinality, Content, Field, Node, Pattern, QueryMatch, QueryMatchArm, + Replacement, Rule, Template, }; #[derive(Clone, Copy)] @@ -46,6 +48,133 @@ struct CaptureBinding { cardinality: Cardinality, } +#[derive(Clone, Copy)] +struct QueryMatchLoweringContext<'a> { + build_ctx: &'a Ident, + ctx: &'a Ident, + ast: &'a Ident, + ast_expr: &'a TokenStream, +} + +impl QueryMatch { + pub(crate) fn lower(self, explicit_ctx: Option) -> TokenStream { + let node_span = self.node.span(); + let has_explicit_ctx = explicit_ctx.is_some(); + let hygiene_span = explicit_ctx.as_ref().map_or(node_span, Ident::span); + let ctx = Ident::new("ctx", hygiene_span); + let ast = Ident::new("ast", hygiene_span); + let build_ctx = explicit_ctx.unwrap_or_else(|| ctx.clone()); + let ast_expr = quote! { yeast::query::QueryTarget::query_ast(__node, &#build_ctx) }; + let context = QueryMatchLoweringContext { + build_ctx: &build_ctx, + ctx: &ctx, + ast: &ast, + ast_expr: &ast_expr, + }; + let fallback = if has_explicit_ctx { + quote! { ::core::panic!("no query arm matched") } + } else { + let node_ident = Ident::new("__node", Span::call_site()); + let matched_node_ident = Ident::new("__matched_node", Span::call_site()); + let panic = quote_spanned! {node_span=> + ::core::panic!( + "no query arm matched node of kind `{}` in {}:{}:{}", + #matched_node_ident.kind_name(), + ::core::file!(), + ::core::line!(), + ::core::column!(), + ) + }; + quote! { + { + let __ast = #ast_expr; + let #matched_node_ident = __ast + .get_node(#node_ident) + .expect("query_match! node must exist in its AST"); + #panic + } + } + }; + let matching = self + .arms + .into_iter() + .rev() + .fold(fallback, |fallback, arm| arm.lower(&fallback, context)); + + let node = self.node; + quote! { + { + let __node = #node; + #matching + } + } + } +} + +impl QueryMatchArm { + fn lower(self, fallback: &TokenStream, context: QueryMatchLoweringContext<'_>) -> TokenStream { + let Self { + pattern, + guard, + body, + } = self; + let query = pattern.lower(); + let captures_ident = Ident::new("__captures", Span::call_site()); + let captures = pattern.captures(); + let id_type = quote! { _ }; + // Give guards and bodies independent bindings so either can consume a + // repeated capture without affecting the other. + let body_bindings = capture_bindings(captures.iter(), &id_type, &captures_ident); + let QueryMatchLoweringContext { + build_ctx, + ctx, + ast, + ast_expr, + } = context; + let guard = guard.map_or_else( + || quote! { true }, + |guard| { + let guard_bindings = capture_bindings(captures.iter(), &id_type, &captures_ident); + let guard_values = Ident::new("__yeast_query_guard_values", Span::mixed_site()); + quote! { + { + let #guard_values = (#ast_expr, &*#build_ctx.user_ctx); + #(#guard_bindings)* + #[allow(unused_variables)] + let #ast = #guard_values.0; + #[allow(unused_variables)] + let #ctx = #guard_values.1; + let __guard: bool = #guard; + __guard + } + } + }, + ); + let statements = &body.stmts; + let body = quote!({ #(#statements)* }); + + quote! { + { + let __query = #query; + let mut __captures = yeast::captures::Captures::new(); + let __matched = { + let __ast = #ast_expr; + __query.do_match(__ast, __node, &mut __captures) + }; + if __matched && #guard { + #(#body_bindings)* + #[allow(unreachable_code)] + { + #body + } + } else { + #fallback + } + } + } + } +} + impl Rule { pub(crate) fn lower(&self) -> TokenStream { let query = self.pattern.lower(); @@ -285,20 +414,23 @@ fn capture_bindings<'a>( captures .map(|capture| { let name_string = capture.name.to_string(); - let name = Ident::new(&name_string, Span::call_site()); + let name = &capture.name; match (capture.cardinality.multiple, capture.cardinality.required) { (true, _) => { quote! { + #[allow(unused_variables)] let #name: Vec<#id_type> = #captures_ident.get_all(#name_string); } } (false, false) => { quote! { + #[allow(unused_variables)] let #name: Option<#id_type> = #captures_ident.get_opt(#name_string); } } (false, true) => { quote! { + #[allow(unused_variables)] let #name: #id_type = #captures_ident.get_var(#name_string).unwrap(); } } diff --git a/shared/yeast-macros/src/parse.rs b/shared/yeast-macros/src/parse.rs index 37b9ed156a17..016a1f062946 100644 --- a/shared/yeast-macros/src/parse.rs +++ b/shared/yeast-macros/src/parse.rs @@ -1,8 +1,84 @@ use proc_macro2::{Ident, Span, TokenStream, TokenTree}; use quote::quote; +use syn::parse::{Parse, ParseStream}; + +use crate::ast::{QueryMatch, QueryMatchArm}; type Result = std::result::Result; +impl Parse for QueryMatch { + fn parse(input: ParseStream<'_>) -> syn::Result { + let node = input.parse()?; + input.parse::()?; + let arm_tokens: TokenStream = input.parse()?; + let mut tokens = arm_tokens.into_iter().peekable(); + let mut arms = Vec::new(); + while tokens.peek().is_some() { + arms.push(QueryMatchArm::parse(&mut tokens)?); + } + if arms.is_empty() { + return Err(syn::Error::new( + Span::call_site(), + "query_match! requires at least one query arm", + )); + } + Ok(QueryMatch { node, arms }) + } +} + +impl QueryMatchArm { + fn parse(tokens: &mut Tokens) -> Result { + let mut pattern_and_guard = Vec::new(); + loop { + match tokens.next() { + Some(TokenTree::Punct(first)) + if first.as_char() == '=' + && first.spacing() == proc_macro2::Spacing::Joint + && matches!( + tokens.peek(), + Some(TokenTree::Punct(second)) if second.as_char() == '>' + ) => + { + tokens.next(); + break; + } + Some(token) => pattern_and_guard.push(token), + None => { + return Err(syn::Error::new( + Span::call_site(), + "expected `=>` in query_match! arm", + )); + } + } + } + + let body = tokens + .next() + .ok_or_else(|| syn::Error::new(Span::call_site(), "expected block after `=>`"))?; + let body = syn::parse2(TokenStream::from(body))?; + + match tokens.next() { + Some(TokenTree::Punct(comma)) if comma.as_char() == ',' => {} + Some(token) => { + return Err(syn::Error::new_spanned( + token, + "expected `,` after query_match! arm", + )); + } + None => {} + } + + let pattern_and_guard = pattern_and_guard.into_iter().collect(); + let (pattern, guard) = crate::rule_parse::split_guard(pattern_and_guard)?; + let pattern = crate::rule_parse::parse_pattern(pattern)?; + Ok(Self { + pattern, + guard, + body, + }) + } +} + pub fn parse_query_top(input: TokenStream) -> Result { let pattern = crate::rule_parse::parse_pattern(input)?.lower(); Ok(quote! { @@ -13,6 +89,73 @@ pub fn parse_query_top(input: TokenStream) -> Result { }) } +fn parse_query_match(input: TokenStream, explicit_ctx: Option) -> Result { + Ok(syn::parse2::(input)?.lower(explicit_ctx)) +} + +pub fn parse_query_match_with_schema_top(input: TokenStream) -> Result { + let mut tokens = input.into_iter().peekable(); + let _schema = parse_string_arg(&mut tokens, "schema")?; + expect_punct(&mut tokens, ',', "expected `,` after schema path")?; + parse_query_match(tokens.collect(), None) +} + +pub fn parse_query_match_with_schema_and_context_top(input: TokenStream) -> Result { + let mut tokens = input.into_iter().peekable(); + let _schema = parse_string_arg(&mut tokens, "schema")?; + expect_punct(&mut tokens, ',', "expected `,` after schema path")?; + let ctx = expect_ident(&mut tokens, "expected context identifier")?; + expect_punct(&mut tokens, ',', "expected `,` after context identifier")?; + parse_query_match(tokens.collect(), Some(ctx)) +} + +pub fn parse_query_match_schema_top(input: TokenStream) -> Result { + let mut tokens = input.into_iter().peekable(); + let module = expect_ident(&mut tokens, "expected schema module name")?; + expect_punct(&mut tokens, ',', "expected `,` after schema module name")?; + let schema = parse_string_arg(&mut tokens, "schema")?; + if tokens.peek().is_some() { + expect_punct(&mut tokens, ',', "expected trailing `,`")?; + } + if let Some(token) = tokens.next() { + return Err(syn::Error::new_spanned( + token, + "unexpected token after schema declaration", + )); + } + + let schema_abs = resolve_manifest_path(&schema, "query_match_schema")?; + let schema_lit = proc_macro2::Literal::string(&schema_abs.to_string_lossy()); + + Ok(quote! { + pub(crate) mod #module { + #[allow(dead_code)] + pub const SCHEMA: &str = ::core::include_str!(#schema_lit); + + macro_rules! query_match { + ($($tokens:tt)*) => { + yeast::__query_match_with_schema! { + #schema_lit, + $($tokens)* + } + }; + } + pub(crate) use query_match; + + macro_rules! query_match_with_context { + ($ctx:ident, $($tokens:tt)*) => { + yeast::__query_match_with_schema_and_context! { + #schema_lit, + $ctx, + $($tokens)* + } + }; + } + pub(crate) use query_match_with_context; + } + }) +} + pub fn parse_tree_with_schema_top(input: TokenStream) -> Result { let mut tokens = input.into_iter().peekable(); let output_path = parse_named_string_arg(&mut tokens, "output")?; diff --git a/shared/yeast-macros/src/rule_parse.rs b/shared/yeast-macros/src/rule_parse.rs index 7339a431134b..4230c61bbe2c 100644 --- a/shared/yeast-macros/src/rule_parse.rs +++ b/shared/yeast-macros/src/rule_parse.rs @@ -375,7 +375,7 @@ fn split_arrow(input: TokenStream) -> Result<(TokenStream, TokenStream)> { } } -fn split_guard(input: TokenStream) -> Result<(TokenStream, Option)> { +pub(crate) fn split_guard(input: TokenStream) -> Result<(TokenStream, Option)> { let tokens = input.into_iter().collect::>(); let guard_index = tokens .iter() diff --git a/shared/yeast/doc/yeast.md b/shared/yeast/doc/yeast.md index 306fe55a187a..6b48b9dc5928 100644 --- a/shared/yeast/doc/yeast.md +++ b/shared/yeast/doc/yeast.md @@ -113,6 +113,109 @@ Captures bind matched nodes to names for use in the transform. A capture _ @anything // capture any node, named or unnamed ``` +### `query_match!` schema namespaces + +Instantiate a matcher namespace for each AST schema being queried: + +```rust +yeast::query_match_schema! { + swift_input, + "swift_node_types.yml", +} + +yeast::query_match_schema! { + swift_output, + "ast_types.yml", +} + +use swift_input::{query_match, query_match_with_context}; +use swift_output::{query_match as output_query_match, SCHEMA as OUTPUT_SCHEMA}; +``` + +Use `query_match!` when matching a query imperatively and consuming its +captures immediately: + +```rust +let result = query_match!( + node, + (assignment + left: (_) @left + type: _? @annotation + right: (_) @right) + => { + (left, annotation, right) + }, + (call function: (_) @function) + => { + (function, None, function) + }, +); +``` + +Query arms are tried in order. The result is the expression from the first +matching arm, and the macro panics when none match. Add a catch-all arm such as +`_ => { None }` when an unmatched node is expected. Captures are bound as raw +input ids: a required capture is an `Id`, an optional capture is an +`Option`, and a repeated capture is a `Vec`. `@` and `@@` are +equivalent in `query_match!`; neither form eagerly translates the capture. +Like `tree!` and `trees!`, `query_match!` uses the ambient `BuildCtx` binding +named `ctx`. + +An arm may include a rule-style `where` guard: + +```rust +query_match!( + node, + (tuple element: _* @elements) + where elements.is_empty() + => { + // ... + }, +); +``` + +The guard receives raw captures, the input AST as `ast`, and the user context +as read-only `ctx`. Guard bindings are independent of body bindings, so the +guard may consume a repeated capture without affecting the body's `Vec`. +A false guard continues with the next arm. + +Passing an `OutputId` makes `query_match!` match against the current output +tree. Its captures are then raw `OutputId` values, and `ast` in a guard refers +to the output AST. The output-tree borrow used for matching and guard evaluation +ends before the body runs, so the body may construct or mutate output nodes. + +Each namespace exports a `query_match!` macro alongside its `SCHEMA` constant. +The node ID selects the input or output tree. Aliasing allows both macros to be +used together without repeating the paths: + +```rust +query_match!(node, (identifier) => { node }); +output_query_match!(output_node, (Name) => { output_node }); +``` + +Each generated namespace exposes its schema as the `SCHEMA` constant. Multiple +schema namespaces may coexist in one crate. `rules!` continues to specify both +of its schema paths explicitly. + +The default matcher infers the hygiene of the ambient `ctx` binding from the +matched node expression. A macro that forwards that expression must use +`query_match_with_context!` to pass its local context explicitly. Otherwise the +generated code may fail to resolve `ctx`, or silently use an unrelated `ctx` +from the scope where the node expression originated: + +```rust +macro_rules! match_node { + ($node:expr, $context:expr) => {{ + let ctx = $context; + query_match_with_context!( + ctx, + $node, + (identifier) => { $node }, + ) + }}; +} +``` + ### Named vs unnamed children The two wildcard forms `(_)` and bare `_` differ: diff --git a/shared/yeast/src/captures.rs b/shared/yeast/src/captures.rs index 167bbe57efa7..5ac88d478cd4 100644 --- a/shared/yeast/src/captures.rs +++ b/shared/yeast/src/captures.rs @@ -1,19 +1,19 @@ use std::collections::{BTreeMap, BTreeSet}; -use crate::{Id, OutputId}; +use crate::{OutputId, TreeId}; #[derive(Debug, Clone)] -pub struct Captures { +pub struct Captures { captures: BTreeMap<&'static str, Vec>, } -impl Default for Captures { +impl Default for Captures { fn default() -> Self { Self::new() } } -impl Captures { +impl Captures { pub fn new() -> Self { Captures { captures: BTreeMap::new(), @@ -54,26 +54,7 @@ impl Captures { self.captures.entry(key).or_default().push(id); } - pub(crate) fn translate_except( - &self, - skip: &[&str], - mut f: impl FnMut(Id) -> Vec, - ) -> TranslatedCaptures { - let mut translated = TranslatedCaptures::new(); - for (name, ids) in &self.captures { - if skip.contains(name) { - continue; - } - for &id in ids { - for translated_id in f(id) { - translated.insert(name, translated_id); - } - } - } - translated - } - - pub fn merge(&mut self, other: &Captures) { + pub fn merge(&mut self, other: &Captures) { for (key, ids) in &other.captures { self.captures.entry(key).or_default().extend(ids); } @@ -82,7 +63,7 @@ impl Captures { pub fn un_star<'a>( &'a self, children: &'a BTreeSet<&'static str>, - ) -> Result + 'a, String> { + ) -> Result> + 'a, String> { let mut id_iter = children.iter(); if let Some(fst) = id_iter.next() { @@ -109,6 +90,27 @@ impl Captures { } } +impl Captures { + pub(crate) fn translate_except( + &self, + skip: &[&str], + mut f: impl FnMut(crate::Id) -> Vec, + ) -> TranslatedCaptures { + let mut translated = TranslatedCaptures::new(); + for (name, ids) in &self.captures { + if skip.contains(name) { + continue; + } + for &id in ids { + for translated_id in f(id) { + translated.insert(name, translated_id); + } + } + } + translated + } +} + /// Output ids produced by eagerly translating non-raw query captures. #[derive(Debug, Clone, Default)] pub struct TranslatedCaptures { diff --git a/shared/yeast/src/lib.rs b/shared/yeast/src/lib.rs index d4f1e576c966..04c878f097a1 100644 --- a/shared/yeast/src/lib.rs +++ b/shared/yeast/src/lib.rs @@ -16,10 +16,14 @@ mod visitor; pub use range::{Point, Range}; #[doc(hidden)] +pub use yeast_macros::query_match_with_schema as __query_match_with_schema; +#[doc(hidden)] +pub use yeast_macros::query_match_with_schema_and_context as __query_match_with_schema_and_context; +#[doc(hidden)] pub use yeast_macros::tree_with_schema as __tree_with_schema; #[doc(hidden)] pub use yeast_macros::trees_with_schema as __trees_with_schema; -pub use yeast_macros::{query, rule, rules, tree_schema}; +pub use yeast_macros::{query, query_match_schema, rule, rules, tree_schema}; use captures::{Captures, TranslatedCaptures}; use query::QueryNode; diff --git a/shared/yeast/src/query.rs b/shared/yeast/src/query.rs index 37c9ced07e4e..9f438bb647a9 100644 --- a/shared/yeast/src/query.rs +++ b/shared/yeast/src/query.rs @@ -1,4 +1,21 @@ -use crate::{captures::Captures, Ast, Id}; +use crate::{build::BuildCtx, captures::Captures, Ast, TreeId}; + +#[doc(hidden)] +pub trait QueryTarget: TreeId { + fn query_ast<'a, C>(self, ctx: &'a BuildCtx<'_, C>) -> &'a Ast; +} + +impl QueryTarget for crate::Id { + fn query_ast<'a, C>(self, ctx: &'a BuildCtx<'_, C>) -> &'a Ast { + ctx.ast() + } +} + +impl QueryTarget for crate::OutputId { + fn query_ast<'a, C>(self, ctx: &'a BuildCtx<'_, C>) -> &'a Ast { + &*ctx.output + } +} #[derive(Debug, Clone)] pub enum QueryNode { @@ -64,7 +81,12 @@ impl QueryNode { } } - pub fn do_match(&self, ast: &Ast, node: Id, matches: &mut Captures) -> bool { + pub fn do_match( + &self, + ast: &Ast, + node: Id, + matches: &mut Captures, + ) -> bool { match self { QueryNode::Any { match_unnamed } => { // `(_)` only matches named nodes, matching tree-sitter @@ -116,21 +138,21 @@ impl QueryNode { } } -fn match_children<'a>( +fn match_children<'a, Id: TreeId>( mut child_matchers: impl Iterator, - ast: &Ast, + ast: &Ast, remaining_children: &mut (impl Iterator + Clone), - matches: &mut Captures, + matches: &mut Captures, ) -> bool { child_matchers.all(|child| child.do_match(ast, remaining_children, matches)) } impl QueryListElem { - fn do_match( + fn do_match( &self, - ast: &Ast, + ast: &Ast, remaining_children: &mut (impl Iterator + Clone), - matches: &mut Captures, + matches: &mut Captures, ) -> bool { match self { QueryListElem::Repeated { children, rep } => { diff --git a/shared/yeast/tests/test.rs b/shared/yeast/tests/test.rs index a64c3e83a302..d62338d177d5 100644 --- a/shared/yeast/tests/test.rs +++ b/shared/yeast/tests/test.rs @@ -35,6 +35,49 @@ macro_rules! build_tree_from_template { }}; } +yeast::query_match_schema! { + test_input, + "tests/input-types.yml", +} + +yeast::query_match_schema! { + test_output, + "tests/node-types.yml", +} + +use test_input::query_match as schema_query_match; +use test_input::query_match_with_context as schema_query_match_with_context; +use test_output::query_match as schema_output_query_match; + +macro_rules! match_forwarded_input_node { + ($node:ident, $context:expr) => {{ + let builder = $context; + schema_query_match_with_context!( + builder, + $node, + (program child: (assignment) @assignment) + where *ctx && ast.get_node(assignment).is_some() + => { + assignment + }, + ) + }}; +} + +macro_rules! match_forwarded_block { + ($node:ident, $context:expr, $body:block) => {{ + let ctx = $context; + schema_query_match_with_context!(ctx, $node, (program) => $body) + }}; +} + +macro_rules! match_forwarded_block_expr { + ($node:ident, $context:expr, $body:expr) => {{ + let ctx = $context; + schema_query_match_with_context!(ctx, $node, (program) => $body) + }}; +} + /// Helper: parse Ruby source with no rules, return dump. fn parse_and_dump(input: &str) -> String { let ast = parse_input(input); @@ -372,6 +415,339 @@ fn test_query_match() { assert!(captures.get_var("right").is_ok()); } +#[test] +fn test_query_match_binds_raw_captures() { + let ast = parse_input("x = 1"); + let mut output = empty_output_ast("x = 1"); + let mut user_ctx = (); + let ctx = yeast::build::BuildCtx::new(&ast, &mut output, &mut user_ctx); + + let assignment = schema_query_match!( + ast.get_root(), + (program child: (assignment) @assignment) + => { + assignment + } + ); + + let (left, right) = schema_query_match!( + assignment, + (assignment + left: (_) @left + right: (_) @@right) + => { + (left, right) + } + ); + assert_eq!(ast.get_node(left).unwrap().kind_name(), "identifier"); + assert_eq!(ast.get_node(right).unwrap().kind_name(), "integer"); + + let call = schema_query_match!( + ast.get_root(), + (program child: (call)? @call) + => { + call + } + ); + assert!(call.is_none()); + + let children = schema_query_match!( + ast.get_root(), + (program child: (_)* @children) + => { + children + } + ); + assert_eq!(children, vec![assignment]); +} + +#[test] +#[deny(unused_braces)] +fn test_query_match_tries_arms_in_order() { + let ast = parse_input("x = 1"); + let mut output = empty_output_ast("x = 1"); + let mut user_ctx = (); + let ctx = yeast::build::BuildCtx::new(&ast, &mut output, &mut user_ctx); + let assignment = schema_query_match!( + ast.get_root(), + (program child: (assignment) @assignment) => { + assignment + }, + ); + + let mut attempted_call = false; + let mut second_assignment_ran = false; + let left = schema_query_match!( + assignment, + (call) => { + attempted_call = true; + assignment + }, + (assignment left: (_) @left) => { + left + }, + (assignment) => { + second_assignment_ran = true; + assignment + }, + ); + assert!(!attempted_call); + assert!(!second_assignment_ran); + assert_eq!(ast.get_node(left).unwrap().kind_name(), "identifier"); + + let mut unmatched_body_ran = false; + let result = schema_query_match!( + assignment, + (call) => { + unmatched_body_ran = true; + Some(()) + }, + _ => { + None + }, + ); + assert!(result.is_none()); + assert!(!unmatched_body_ran); +} + +#[test] +fn test_query_match_guards() { + let ast = parse_input("x = 1"); + let mut output = empty_output_ast("x = 1"); + let mut enabled = true; + let ctx = yeast::build::BuildCtx::new(&ast, &mut output, &mut enabled); + + let children = schema_query_match!( + ast.get_root(), + (program child: (_)* @children) + where children + .into_iter() + .all(|child| ast.get_node(child).unwrap().is_named()) + => { + children + }, + ); + let assignment = children[0]; + + let mut guarded_body_ran = false; + let right = schema_query_match!( + assignment, + (assignment left: (_) @left) + where false + => { + guarded_body_ran = true; + left + }, + (assignment right: (_) @right) + where ast.get_node(right).is_some() + => { + right + }, + ); + assert!(!guarded_body_ran); + + let left = schema_query_match!( + assignment, + (assignment left: (_) @left) + where *ctx + => { + left + }, + ); + assert_eq!(ast.get_node(left).unwrap().kind_name(), "identifier"); + assert_eq!(ast.get_node(right).unwrap().kind_name(), "integer"); +} + +#[test] +fn test_query_match_allows_return_from_body() { + #[allow(clippy::needless_return)] + fn matched_left(ast: &Ast, assignment: Id) -> Id { + let mut output = empty_output_ast("x = 1"); + let mut user_ctx = (); + let ctx = yeast::build::BuildCtx::new(ast, &mut output, &mut user_ctx); + schema_query_match!( + assignment, + (assignment left: (_) @left) + => { + return left; + } + ); + } + + let ast = parse_input("x = 1"); + let mut output = empty_output_ast("x = 1"); + let mut user_ctx = (); + let ctx = yeast::build::BuildCtx::new(&ast, &mut output, &mut user_ctx); + let assignment = schema_query_match!( + ast.get_root(), + (program child: (assignment) @assignment) => { + assignment + }, + ); + assert_eq!( + ast.get_node(matched_left(&ast, assignment)) + .unwrap() + .kind_name(), + "identifier" + ); +} + +#[test] +#[allow(clippy::needless_continue)] +fn test_query_match_allows_continue_from_body() { + let ast = parse_input("x = 1"); + let mut output = empty_output_ast("x = 1"); + let mut user_ctx = (); + let ctx = yeast::build::BuildCtx::new(&ast, &mut output, &mut user_ctx); + let assignment = schema_query_match!( + ast.get_root(), + (program child: (assignment) @assignment) => { + assignment + }, + ); + + let mut continued = false; + for node in [assignment] { + schema_query_match!( + node, + (assignment) + => { + continued = true; + continue; + } + ); + } + assert!(continued); +} + +#[test] +#[should_panic(expected = "no query arm matched node of kind `program`")] +fn test_query_match_panics_when_no_arm_matches() { + let ast = parse_input("x = 1"); + let mut output = empty_output_ast("x = 1"); + let mut user_ctx = (); + let ctx = yeast::build::BuildCtx::new(&ast, &mut output, &mut user_ctx); + + schema_query_match!( + ast.get_root(), + (call) => {} + ); +} + +#[test] +fn test_query_match_binds_output_captures_and_releases_borrow() { + let ast = parse_input("x = 1"); + let mut output = empty_output_ast("x = 1"); + let mut user_ctx = (); + let mut ctx = yeast::build::BuildCtx::new(&ast, &mut output, &mut user_ctx); + let assignment = tree!((assignment + left: (identifier "x") + right: (integer "1"))); + + let (left, right, call) = schema_output_query_match!( + assignment, + (assignment + left: (identifier) @left + right: (integer) @right) + where ast.get_node(left).unwrap().kind_name() == "identifier" + => { + let call = tree!((call method: {left})); + (left, right, call) + }, + ); + + assert_eq!(ctx.output.get_node(left).unwrap().kind_name(), "identifier"); + assert_eq!(ctx.output.get_node(right).unwrap().kind_name(), "integer"); + assert_eq!(ctx.output.get_node(call).unwrap().kind_name(), "call"); +} + +#[test] +fn test_explicit_context_uses_selected_user_context() { + let input_ast = parse_input("x = 1"); + let mut output = empty_output_ast("x = 1"); + let mut enabled = true; + let root = input_ast.get_root(); + let ctx = &false; + + let assignment = match_forwarded_input_node!( + root, + yeast::build::BuildCtx::new(&input_ast, &mut output, &mut enabled) + ); + + assert_eq!( + input_ast.get_node(assignment).unwrap().kind_name(), + "assignment" + ); + assert!(!*ctx); +} + +#[test] +fn test_explicit_context_accepts_ast_identifier() { + let input_ast = parse_input("x = 1"); + let mut output = empty_output_ast("x = 1"); + let mut enabled = true; + let root = input_ast.get_root(); + let ast = yeast::build::BuildCtx::new(&input_ast, &mut output, &mut enabled); + + let assignment = schema_query_match_with_context!( + ast, + root, + (program child: (assignment) @assignment) + where *ctx && ast.get_node(assignment).is_some() + => { + assignment + }, + ); + + assert_eq!( + input_ast.get_node(assignment).unwrap().kind_name(), + "assignment" + ); +} + +#[test] +fn test_explicit_context_accepts_ctx_identifier() { + let input_ast = parse_input("x = 1"); + let mut output = empty_output_ast("x = 1"); + let mut enabled = true; + let root = input_ast.get_root(); + let ctx = yeast::build::BuildCtx::new(&input_ast, &mut output, &mut enabled); + + assert!(schema_query_match_with_context!( + ctx, + root, + (program) + where *ctx + => { + true + }, + )); +} + +#[test] +fn test_explicit_context_accepts_forwarded_bodies() { + let input_ast = parse_input("x = 1"); + + let mut output = empty_output_ast("x = 1"); + let mut user_ctx = (); + let root = input_ast.get_root(); + let value = match_forwarded_block!( + root, + yeast::build::BuildCtx::new(&input_ast, &mut output, &mut user_ctx), + { 41 } + ); + assert_eq!(value, 41); + + let mut output = empty_output_ast("x = 1"); + let mut user_ctx = (); + let value = match_forwarded_block_expr!( + root, + yeast::build::BuildCtx::new(&input_ast, &mut output, &mut user_ctx), + { 42 } + ); + assert_eq!(value, 42); +} + #[test] fn test_run_from_ast_desugars_hand_built_tree() { // Output schema for the desugared tree. Its kind/field names must become @@ -843,6 +1219,12 @@ fn test_tree_schema_namespace() { ); } +#[test] +fn test_query_match_schema_namespace() { + assert_eq!(test_input::SCHEMA, include_str!("input-types.yml")); + assert_eq!(test_output::SCHEMA, OUTPUT_SCHEMA_YAML); +} + #[test] fn test_explicit_context_builders_support_forwarded_templates() { let input_ast = parse_input("x = 1"); @@ -993,10 +1375,7 @@ fn test_choice_fallback_can_reuse_consumed_splice() { let mut user_ctx = (); let mut ctx = yeast::build::BuildCtx::new(&input_ast, &mut ast, &mut user_ctx); - let items = vec![ - tree!((identifier "x")), - tree!((identifier "y")), - ]; + let items = vec![tree!((identifier "x")), tree!((identifier "y"))]; let use_first = false; let root = tree!( (assignment @@ -1178,8 +1557,7 @@ fn test_location_interpolation_materializes_context_iterator() { let mut ast = empty_output_ast(input); let mut user_ctx = BorrowedInterpolationContext::default(); let mut ctx = yeast::build::BuildCtx::new(&input_ast, &mut ast, &mut user_ctx); - let location = - tree!((identifier "location" location: {input_ast.get_root()})); + let location = tree!((identifier "location" location: {input_ast.get_root()})); ctx.locations.push(location); let call = tree!((call location: {ctx.locations.drain(..)})); diff --git a/unified/extractor/src/languages/swift/swift.rs b/unified/extractor/src/languages/swift/swift.rs index 5b08e45ba96b..eb35a3ee7f03 100644 --- a/unified/extractor/src/languages/swift/swift.rs +++ b/unified/extractor/src/languages/swift/swift.rs @@ -8,6 +8,13 @@ yeast::tree_schema! { use swift_tree::tree; +yeast::query_match_schema! { + swift_output_query, + "ast_types.yml", +} + +use swift_output_query::query_match as output_query_match; + /// User context propagated from outer rules down to the inner rules that /// emit the corresponding output declarations, so that each emitted node /// is born with the outer information (name, type, modifiers, etc.) @@ -76,10 +83,12 @@ fn implicit_parameterless_initializer( ctx: &mut yeast::build::BuildCtx<'_, SwiftContext>, members: &[yeast::OutputId], ) -> Option { - let has_explicit_initializer = members.iter().any(|member| { - ctx.output - .get_node(*member) - .is_some_and(|node| node.kind_name() == "constructor_declaration") + let has_explicit_initializer = members.iter().copied().any(|member| { + output_query_match!( + member, + (constructor_declaration) => { true }, + _ => { false }, + ) }); (!has_explicit_initializer).then(|| { tree!((constructor_declaration