//! Parser for `.synctest` files. See `README.md` for the format. use anyhow::{Result, anyhow, bail}; /// A parsed `.synctest` file. #[derive(Debug, Clone)] pub struct TestFile { /// `@skip-file` lines. pub skips: Vec, pub tests: Vec, /// The places that have a runner tag, in file order. pub runner_tags: Vec, } /// The program that runs the client steps. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Runner { /// `sync/sdk-kit`, in process. Rust, /// The driver of the JavaScript SDK. Js, /// The driver of the Go SDK. Go, } impl Runner { pub fn parse(name: &str) -> Option { match name { "rust" => Some(Runner::Rust), "js" => Some(Runner::Js), "go" => Some(Runner::Go), _ => None, } } pub fn name(self) -> &'static str { match self { Runner::Rust => "rust", Runner::Js => "js", Runner::Go => "go", } } } /// `@skip [runners] "reason"` or `@skip-file [runners] "reason"`. Without runners, the skip /// applies to all runners. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Skip { pub runners: Option>, pub reason: String, } /// Returns the reason of the last skip that applies to the runner. pub fn skip_reason(skips: &[Skip], runner: Runner) -> Option<&str> { skips .iter() .rev() .find(|skip| skip.runners.as_ref().is_none_or(|r| r.contains(&runner))) .map(|skip| skip.reason.as_str()) } /// A place in a file that has a runner tag. #[derive(Debug, Clone, PartialEq, Eq)] pub struct RunnerTag { pub line: usize, pub runners: Vec, /// The tagged item: `@skip`, `@skip-file`, `expect`, `or error` and so on. pub kind: String, } #[derive(Debug, Clone)] pub struct Test { pub name: String, /// Line of the `test` keyword (1-based). pub line: usize, /// `@skip` lines before the test. pub skips: Vec, pub items: Vec, } #[derive(Debug, Clone)] pub enum Item { Step(Step), /// `step [N]`: advance a task by N yields (default 1). Advance { line: usize, task: String, count: usize, }, /// `wait `: run a task to its end. An `expect` checks the result of the task. Wait { line: usize, task: String, expect: Option, }, /// `interleave { ... }`: start the tasks of the block, then run them to their ends in /// every order of their yields. The test runs once per order. Interleave { line: usize, steps: Vec, }, } #[derive(Debug, Clone)] pub struct Step { /// Line of the step (1-based). pub line: usize, pub target: Target, pub command: Command, /// ` &name`: run the step as a task with this name. pub task: Option, pub expect: Option, } /// The actor that runs a step. #[derive(Debug, Clone, PartialEq, Eq)] pub enum Target { /// The database on the sync server, reached through `/v2/pipeline`. Server, /// A connection of a sync client. `connection` is `main` when the step does not name one. Client { client: String, connection: String }, } pub const DEFAULT_CONNECTION: &str = "main"; #[derive(Debug, Clone, PartialEq, Eq)] pub enum Command { /// Open the client's local database and bootstrap it from the server. With `ungated`, /// the connections of the client do not check the sync busy gate of the SDK (as in the /// JavaScript binding), so they can run statements while a pull runs. Init { ungated: bool }, /// Run SQL. Exec(String), /// Pull changes from the server. The result is one row: `true` if changes were applied. Pull, /// Push local changes to the server. Push, /// Push, then pull. Sync, /// Run a sync checkpoint. Checkpoint, /// Close the client (all connections), then open it again from its local files. Reopen, /// Close one connection. An open transaction on it is rolled back. Close, } #[derive(Debug, Clone, PartialEq, Eq)] pub enum Expect { Rows { rows: Vec, unordered: bool, }, /// The step must fail. `None` accepts any error message. Error(Option), /// `expect ... or ...`: one of the expectations must hold. AnyOf(Vec), /// `expect [runners] ...`: the expectation applies only to these runners. Only { runners: Vec, expect: Box, }, } impl Expect { /// Removes the alternatives that do not apply to the runner. `None` when no alternative /// applies: then the step must succeed, as a step without `expect`. pub fn for_runner(&self, runner: Runner) -> Option { match self { Expect::Only { runners, expect } => { if runners.contains(&runner) { expect.for_runner(runner) } else { None } } Expect::AnyOf(all) => { let mut all: Vec = all.iter().filter_map(|e| e.for_runner(runner)).collect(); match all.len() { 0 => None, 1 => all.pop(), _ => Some(Expect::AnyOf(all)), } } other => Some(other.clone()), } } } pub fn parse(source: &str) -> Result { let lines: Vec<&str> = source.lines().collect(); let mut pos = 0; let mut file = TestFile { skips: Vec::new(), tests: Vec::new(), runner_tags: Vec::new(), }; let mut pending_skips = Vec::new(); while pos < lines.len() { let line_no = pos + 1; let line = lines[pos].trim(); pos += 1; if line.is_empty() || line.starts_with('#') { continue; } if let Some(rest) = line.strip_prefix("@skip-file") { let skip = parse_skip(rest, line_no, "@skip-file", &mut file.runner_tags)?; file.skips.push(skip); } else if let Some(rest) = line.strip_prefix("@skip") { let skip = parse_skip(rest, line_no, "@skip", &mut file.runner_tags)?; pending_skips.push(skip); } else if let Some(rest) = line.strip_prefix("test ") { let Some(name) = rest.trim().strip_suffix('{') else { bail!("line {line_no}: expected `test {{`"); }; let name = name.trim(); if !is_name(name) { bail!("line {line_no}: invalid test name `{name}`"); } if file.tests.iter().any(|test| test.name == name) { bail!("line {line_no}: duplicate test name `{name}`"); } let items = parse_items(&lines, &mut pos, None, &mut file.runner_tags)?; let interleaves = items .iter() .filter(|item| matches!(item, Item::Interleave { .. })) .count(); if interleaves > 1 { bail!("line {line_no}: a test can have only one `interleave` block"); } file.tests.push(Test { name: name.to_string(), line: line_no, skips: std::mem::take(&mut pending_skips), items, }); } else { bail!("line {line_no}: unexpected `{line}`"); } } if !pending_skips.is_empty() { bail!("`@skip` at the end of the file has no test"); } Ok(file) } fn parse_skip(rest: &str, line_no: usize, kind: &str, tags: &mut Vec) -> Result { let (rest, runners) = take_runner_tags(rest, line_no)?; let rest = rest.trim(); let Some(reason) = rest.strip_prefix('"').and_then(|r| r.strip_suffix('"')) else { bail!("line {line_no}: expected `{kind} [runners] \"reason\"`"); }; if let Some(runners) = &runners { tags.push(RunnerTag { line: line_no, runners: runners.clone(), kind: kind.to_string(), }); } Ok(Skip { runners, reason: reason.to_string(), }) } /// Parses the items of a test body (or of an `interleave` block, when `block_line` is set) /// up to and including its closing `}`. fn parse_items( lines: &[&str], pos: &mut usize, block_line: Option, tags: &mut Vec, ) -> Result> { let mut items: Vec = Vec::new(); while *pos < lines.len() { let line_no = *pos + 1; let line = lines[*pos].trim(); *pos += 1; if line.is_empty() || line.starts_with('#') { continue; } if line == "}" { return Ok(items); } if line.starts_with("or ") { bail!("line {line_no}: `or` must follow an `expect` block"); } if line.starts_with("expect") { let mut expect = parse_expect(line, line_no, lines, pos, "expect", tags)?; // `or ` blocks after it give alternatives. while let Some(next) = lines.get(*pos).map(|l| l.trim()) && let Some(alternative) = next.strip_prefix("or ") { let or_line = *pos + 1; *pos += 1; let alternative = parse_expect( &format!("expect {alternative}"), or_line, lines, pos, "or", tags, )?; expect = match expect { Expect::AnyOf(mut all) => { all.push(alternative); Expect::AnyOf(all) } first => Expect::AnyOf(vec![first, alternative]), }; } let slot = match items.last_mut() { Some(Item::Step(Step { task: None, expect, .. })) | Some(Item::Wait { expect, .. }) => expect, Some(Item::Step(Step { task: Some(task), .. })) => bail!( "line {line_no}: a task has no result yet; put `expect` after `wait {task}`" ), _ => bail!("line {line_no}: `expect` must follow a step or a `wait`"), }; if slot.is_some() { bail!("line {line_no}: the step before already has an `expect`"); } *slot = Some(expect); continue; } let (word, rest) = split_word(line); let item = match word { "step" => { let (task, count) = split_word(rest); if !is_name(task) { bail!("line {line_no}: expected `step [N]`"); } let count = match count { "" => 1, count => count .parse() .ok() .filter(|n| *n > 0) .ok_or_else(|| anyhow!("line {line_no}: invalid count `{count}`"))?, }; Item::Advance { line: line_no, task: task.to_string(), count, } } "wait" => { if !is_name(rest) { bail!("line {line_no}: expected `wait `"); } Item::Wait { line: line_no, task: rest.to_string(), expect: None, } } "interleave" => { if block_line.is_some() { bail!("line {line_no}: `interleave` blocks cannot nest"); } if rest != "{" { bail!("line {line_no}: expected `interleave {{`"); } let mut steps = Vec::new(); for item in parse_items(lines, pos, Some(line_no), tags)? { match item { Item::Step(step) if step.task.is_some() => steps.push(step), _ => bail!( "line {line_no}: an `interleave` block contains only tasks (` &name`)" ), } } if steps.len() < 2 { bail!("line {line_no}: an `interleave` block needs at least two tasks"); } Item::Interleave { line: line_no, steps, } } _ => Item::Step(parse_step(line, line_no, lines, pos)?), }; items.push(item); } match block_line { Some(line) => bail!("line {line}: `interleave` block is not closed with `}}`"), None => bail!("unexpected end of file: a test is not closed with `}}`"), } } fn parse_step(line: &str, line_no: usize, lines: &[&str], pos: &mut usize) -> Result { let (target, rest) = split_word(line); let (command, args) = split_word(rest); let target = parse_target(target, line_no)?; let (args, mut task) = split_task(args); let command = match command { "exec" => { let mut sql = args.to_string(); // SQL continues on the next lines until a line ends with `;` (or with `; &task`), // and on all next lines that are indented deeper than the step. let indent = |line: &str| line.len() - line.trim_start().len(); let step_indent = indent(lines[line_no - 1]); loop { let deeper = lines .get(*pos) .is_some_and(|l| !l.trim().is_empty() && indent(l) > step_indent); if task.is_some() || !deeper { if sql.trim_end().ends_with(';') { break; } if task.is_some() || *pos >= lines.len() || lines[*pos].trim() == "}" { bail!("line {line_no}: SQL must end with `;`"); } } let (next, next_task) = split_task(lines[*pos].trim()); sql.push('\n'); sql.push_str(next); task = next_task; *pos += 1; } Command::Exec(sql.trim().to_string()) } "init" => match args { "" => Command::Init { ungated: false }, "ungated" => Command::Init { ungated: true }, other => bail!("line {line_no}: unknown `init` option `{other}`: expected `ungated`"), }, "pull" => Command::Pull, "push" => Command::Push, "sync" => Command::Sync, "checkpoint" => Command::Checkpoint, "reopen" => Command::Reopen, "close" => Command::Close, "" => bail!("line {line_no}: missing command after `{}`", line.trim()), other => bail!("line {line_no}: unknown command `{other}`"), }; if !matches!(command, Command::Exec(_) | Command::Init { .. }) && !args.is_empty() { bail!( "line {line_no}: `{}` takes no arguments", command_name(&command) ); } match (&target, &command) { (Target::Server, Command::Exec(_)) => {} (Target::Server, other) => { bail!( "line {line_no}: `server` supports only `exec`, not `{}`", command_name(other) ) } (Target::Client { connection, .. }, command) if connection != DEFAULT_CONNECTION && !matches!(command, Command::Exec(_) | Command::Close) => { bail!( "line {line_no}: `{}` applies to the whole client; remove `.{connection}`", command_name(command) ) } _ => {} } if let Some(task) = &task { if !is_name(task) { bail!("line {line_no}: invalid task name `{task}`"); } let can_run_as_task = match (&target, &command) { (Target::Server, _) => false, (_, command) => !matches!( command, Command::Init { .. } | Command::Reopen | Command::Close ), }; if !can_run_as_task { bail!( "line {line_no}: `{}` cannot run as a task", command_name(&command) ); } } Ok(Step { line: line_no, target, command, task: task.map(str::to_string), expect: None, }) } fn parse_target(word: &str, line_no: usize) -> Result { if word == "server" { return Ok(Target::Server); } let (client, connection) = match word.split_once('.') { Some((client, connection)) => (client, connection), None => (word, DEFAULT_CONNECTION), }; if matches!(client, "step" | "wait" | "interleave" | "test" | "expect") { bail!("line {line_no}: `{client}` is a keyword and cannot name a client"); } if !is_name(client) || !is_name(connection) { bail!( "line {line_no}: invalid target `{word}`: expected `server`, `` or `.`" ); } Ok(Target::Client { client: client.to_string(), connection: connection.to_string(), }) } /// Parses an `expect` block. `word` is `expect`, or `or` for an alternative. fn parse_expect( line: &str, line_no: usize, lines: &[&str], pos: &mut usize, word: &str, tags: &mut Vec, ) -> Result { let Some(header) = line.strip_suffix('{') else { bail!("line {line_no}: expected `{word} [runners] [unordered|error] {{`"); }; let (header, runners) = take_runner_tags(header, line_no)?; let modifier = header .trim() .strip_prefix("expect") .unwrap_or_default() .trim(); let expect = parse_expect_body(modifier, line_no, lines, pos)?; let Some(runners) = runners else { return Ok(expect); }; tags.push(RunnerTag { line: line_no, runners: runners.clone(), kind: format!("{word} {modifier}").trim().to_string(), }); Ok(Expect::Only { runners, expect: Box::new(expect), }) } fn parse_expect_body( modifier: &str, line_no: usize, lines: &[&str], pos: &mut usize, ) -> Result { let mut body = Vec::new(); loop { if *pos >= lines.len() { bail!("line {line_no}: `expect` block is not closed with `}}`"); } let line = lines[*pos].trim(); *pos += 1; if line == "}" { break; } if !line.is_empty() { body.push(line.to_string()); } } match modifier { "" => Ok(Expect::Rows { rows: body, unordered: false, }), "unordered" => Ok(Expect::Rows { rows: body, unordered: true, }), "error" => Ok(Expect::Error((!body.is_empty()).then(|| body.join("\n")))), other => bail!("line {line_no}: unknown `expect` modifier `{other}`"), } } /// Removes a `[rust,js,go]` group from `text`. Returns the text without the group, and the /// runners of the group. fn take_runner_tags(text: &str, line_no: usize) -> Result<(String, Option>)> { let Some(start) = text.find('[') else { return Ok((text.to_string(), None)); }; // The group must come before the reason of a skip. if text.find('"').is_some_and(|quote| quote < start) { return Ok((text.to_string(), None)); } let Some(len) = text[start..].find(']') else { bail!("line {line_no}: runner tag is not closed with `]`"); }; let mut runners = Vec::new(); for name in text[start + 1..start + len].split(',') { let name = name.trim(); let Some(runner) = Runner::parse(name) else { bail!("line {line_no}: unknown runner `{name}` in tag: expected `rust`, `js` or `go`"); }; if !runners.contains(&runner) { runners.push(runner); } } let rest = format!("{} {}", &text[..start], &text[start + len + 1..]); Ok((rest, Some(runners))) } pub fn command_name(command: &Command) -> &'static str { match command { Command::Init { .. } => "init", Command::Exec(_) => "exec", Command::Pull => "pull", Command::Push => "push", Command::Sync => "sync", Command::Checkpoint => "checkpoint", Command::Reopen => "reopen", Command::Close => "close", } } /// Splits a trailing `&name` off a step. fn split_task(args: &str) -> (&str, Option<&str>) { match args.rsplit_once('&') { Some((before, name)) if is_name(name.trim_end()) => { (before.trim_end(), Some(name.trim_end())) } _ => (args, None), } } fn split_word(s: &str) -> (&str, &str) { let s = s.trim(); match s.split_once(char::is_whitespace) { Some((word, rest)) => (word, rest.trim()), None => (s, ""), } } fn is_name(s: &str) -> bool { let mut chars = s.chars(); chars.next().is_some_and(|c| c.is_ascii_alphabetic()) && chars.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-') } #[cfg(test)] mod tests { use super::*; fn steps(test: &Test) -> Vec<&Step> { test.items .iter() .filter_map(|item| match item { Item::Step(step) => Some(step), _ => None, }) .collect() } #[test] fn parses_steps_and_expectations() { let file = parse( r#" # comment @skip "not yet" test push-pull { server exec CREATE TABLE t(x); a init a.tx exec BEGIN; a exec INSERT INTO t VALUES (1); a pull expect error { busy } b exec SELECT x FROM t; expect unordered { 1 } } "#, ) .unwrap(); let test = &file.tests[0]; let steps = steps(test); assert_eq!(test.name, "push-pull"); assert_eq!(skip_reason(&test.skips, Runner::Rust), Some("not yet")); assert_eq!(steps.len(), 6); assert_eq!(steps[0].target, Target::Server); assert_eq!( steps[2].target, Target::Client { client: "a".into(), connection: "tx".into() } ); assert_eq!( steps[3].command, Command::Exec("INSERT INTO t\nVALUES (1);".into()) ); assert_eq!(steps[4].expect, Some(Expect::Error(Some("busy".into())))); assert_eq!( steps[5].expect, Some(Expect::Rows { rows: vec!["1".into()], unordered: true }) ); } #[test] fn parses_tasks() { let file = parse( r#" test t { a pull &p a.w exec BEGIN; INSERT INTO t VALUES (1 & 3); &w step p 2 wait p expect { true } interleave { a pull &p a.w exec COMMIT; &w } wait w } "#, ) .unwrap(); let items = &file.tests[0].items; let Item::Step(pull) = &items[0] else { panic!() }; assert_eq!(pull.task.as_deref(), Some("p")); let Item::Step(exec) = &items[1] else { panic!() }; assert_eq!(exec.task.as_deref(), Some("w")); assert_eq!( exec.command, Command::Exec("BEGIN;\nINSERT INTO t VALUES (1 & 3);".into()) ); assert!(matches!(&items[2], Item::Advance { task, count: 2, .. } if task == "p")); assert!(matches!( &items[3], Item::Wait { expect: Some(_), .. } )); assert!(matches!(&items[4], Item::Interleave { steps, .. } if steps.len() == 2)); } #[test] fn parses_runner_tags() { let file = parse( r#" @skip-file [js] "no js driver" @skip [go, js] "busy differs" test t { a pull expect { true } or [js] { false } or error [js,go] { busy } a push expect [go] unordered { } } "#, ) .unwrap(); assert_eq!(skip_reason(&file.skips, Runner::Js), Some("no js driver")); assert_eq!(skip_reason(&file.skips, Runner::Rust), None); let test = &file.tests[0]; assert_eq!(skip_reason(&test.skips, Runner::Go), Some("busy differs")); assert_eq!(skip_reason(&test.skips, Runner::Rust), None); let tags: Vec<(usize, &str)> = file .runner_tags .iter() .map(|tag| (tag.line, tag.kind.as_str())) .collect(); assert_eq!( tags, vec![ (2, "@skip-file"), (3, "@skip"), (9, "or"), (12, "or error"), (16, "expect unordered") ] ); assert_eq!(file.runner_tags[3].runners, vec![Runner::Js, Runner::Go]); let steps = steps(test); let pull = steps[0].expect.as_ref().unwrap(); let rows = |rows: &[&str]| Expect::Rows { rows: rows.iter().map(|r| r.to_string()).collect(), unordered: false, }; assert_eq!(pull.for_runner(Runner::Rust), Some(rows(&["true"]))); assert_eq!( pull.for_runner(Runner::Go), Some(Expect::AnyOf(vec![ rows(&["true"]), Expect::Error(Some("busy".into())) ])) ); let Some(Expect::AnyOf(js)) = pull.for_runner(Runner::Js) else { panic!() }; assert_eq!(js.len(), 3); let push = steps[1].expect.as_ref().unwrap(); assert_eq!(push.for_runner(Runner::Rust), None); assert!(push.for_runner(Runner::Go).is_some()); } #[test] fn rejects_bad_input() { for (source, message) in [ ("test t {\n a exec SELECT 1\n}", "must end with `;`"), ("test t {\n a frobnicate\n}", "unknown command"), ("test t {\n server pull\n}", "supports only `exec`"), ("test t {\n a.c pull\n}", "applies to the whole client"), ("test t {\n expect {\n }\n}", "must follow a step"), ("test t {\n a pull\n", "not closed"), ("test t {\n a pull &p\n expect {\n }\n}", "after `wait p`"), ("test t {\n a init &p\n}", "cannot run as a task"), ( "test t {\n interleave {\n a pull &p\n }\n}", "at least two tasks", ), ( "test t {\n interleave {\n a pull\n b pull &q\n }\n}", "contains only tasks", ), ( "test t {\n a pull\n expect [py] {\n }\n}", "unknown runner `py`", ), ("@skip [js \"x\"\ntest t {\n}", "not closed with `]`"), ] { let error = parse(source).unwrap_err().to_string(); assert!(error.contains(message), "{source:?}: {error}"); } } }