Skip to content
Closed
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
8 changes: 8 additions & 0 deletions Cargo.lock

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

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ repository = "https://github.com/storytold/gridcraft"
gridcraft-core = { path = "crates/core" }
gridcraft-numfmt = { path = "crates/numfmt" }
gridcraft-formula = { path = "crates/formula" }
gridcraft-dax = { path = "crates/dax" }
gridcraft-functions = { path = "crates/functions" }
gridcraft-model = { path = "crates/model" }
gridcraft-calc = { path = "crates/calc" }
Expand Down
1 change: 1 addition & 0 deletions apps/gridcraft-cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ name = "gridcraft-cli"
path = "src/main.rs"

[dependencies]
gridcraft-dax = { workspace = true }
gridcraft-engine = { workspace = true }
gridcraft-mcp = { workspace = true }
serde_json = { workspace = true }
Expand Down
76 changes: 76 additions & 0 deletions apps/gridcraft-cli/src/dax.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
//! `gridcraft-cli dax`: format or dump the syntax tree of DAX text.

use std::io::Read;

use gridcraft_dax::{Expr, Query, TokenKind, parse_expression, parse_query, print_expression, print_query, tokenize};

use super::{Args, USAGE};

pub fn main(args: &[String]) -> Result<(), String> {
let action = args.first().map(String::as_str).ok_or_else(|| format!("missing dax action\n{USAGE}"))?;
let rest = args.get(1..).unwrap_or_default();
match action {
"format" => format(rest),
"parse" => parse(rest),
other => Err(format!("unknown dax action `{other}`\n{USAGE}")),
}
}

fn format(args: &[String]) -> Result<(), String> {
let text = read_input(args)?;
match parse_any(&text)? {
Parsed::Query(query) => outln!("{}", print_query(&query)),
Parsed::Expression(expr) => outln!("{}", print_expression(&expr)),
}
Ok(())
}

fn parse(args: &[String]) -> Result<(), String> {
let text = read_input(args)?;
match parse_any(&text)? {
Parsed::Query(query) => outln!("{query:#?}"),
Parsed::Expression(expr) => outln!("{expr:#?}"),
}
Ok(())
}

enum Parsed {
Query(Query),
Expression(Expr),
}

/// Reads `TEXT`, `--file PATH`, or stdin (in that order of preference). Multiple positionals
/// are joined with spaces, so an unquoted `dax format 1 + 2` works.
fn read_input(args: &[String]) -> Result<String, String> {
let parsed = Args::parse(args, &["file"], &[])?;
if let Some(path) = parsed.opt("file") {
if !parsed.positional.is_empty() {
return Err("give either TEXT or --file, not both".into());
}
return std::fs::read_to_string(path).map_err(|e| format!("can't read {path}: {e}"));
}
if !parsed.positional.is_empty() {
return Ok(parsed.positional.join(" "));
}
let mut text = String::new();
std::io::stdin().read_to_string(&mut text).map_err(|e| format!("can't read stdin: {e}"))?;
Ok(text)
}

/// Queries are tried first; a malformed `EVALUATE` reports its query error instead of a
/// misleading expression error.
fn parse_any(text: &str) -> Result<Parsed, String> {
match parse_query(text) {
Ok(query) => Ok(Parsed::Query(query)),
Err(query_error) => {
if starts_with_evaluate(text) {
return Err(query_error.to_string());
}
parse_expression(text).map(Parsed::Expression).map_err(|e| e.to_string())
}
}
}

fn starts_with_evaluate(text: &str) -> bool {
tokenize(text).is_ok_and(|tokens| matches!(tokens.first().map(|token| &token.kind), Some(TokenKind::Evaluate)))
}
5 changes: 5 additions & 0 deletions apps/gridcraft-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
//! gridcraft-cli run [--in FILE | --sample NAME] [--cmd 'id={json}']... [--script FILE.jsonl] [--out FILE] [--print RANGE] [--quiet]
//! gridcraft-cli commands [--json] [--search X]
//! gridcraft-cli functions [--json] [--search X] [--category C]
//! gridcraft-cli dax format|parse [TEXT] [--file PATH]
//! gridcraft-cli mcp [--connect PORT] [--in FILE | --sample NAME]
//! gridcraft-cli send <port> <method> [json]
//! gridcraft-cli version | --version
Expand All @@ -30,6 +31,7 @@ macro_rules! outln {
}

mod check;
mod dax;

use gridcraft_engine::Session;
use serde_json::{Value, json};
Expand All @@ -47,6 +49,8 @@ const USAGE: &str = "usage:
blank lines and lines starting with # or // are skipped
gridcraft-cli commands [--json] [--search X]
gridcraft-cli functions [--json] [--search X] [--category C]
gridcraft-cli dax format [TEXT] [--file PATH] canonical DAX text (expression or EVALUATE query)
gridcraft-cli dax parse [TEXT] [--file PATH] DAX syntax tree
gridcraft-cli mcp [--connect PORT] [--in FILE | --sample NAME]
gridcraft-cli send <port> <method> [json]
gridcraft-cli version";
Expand Down Expand Up @@ -81,6 +85,7 @@ fn main() -> ExitCode {
Some("check") => return check::main(rest),
Some("commands") => commands(rest),
Some("functions") => functions(rest),
Some("dax") => dax::main(rest),
Some("mcp") => mcp(rest),
Some("send") => send(rest),
Some(other) => Err(format!("unknown subcommand `{other}`\n{USAGE}")),
Expand Down
34 changes: 34 additions & 0 deletions apps/gridcraft-cli/tests/it/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -242,3 +242,37 @@ fn a_script_line_with_an_unknown_key_stops_the_run() {

let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn dax_format_parse_and_errors() {
assert_eq!(ok(&["dax", "format", "1 + 2 * 3"]).trim(), "1 + 2 * 3");
assert_eq!(ok(&["dax", "format", "(1 + 2) * 3"]).trim(), "(1 + 2) * 3");
assert_eq!(ok(&["dax", "format", "-2 ^ 2"]).trim(), "-2 ^ 2");
assert!(ok(&["dax", "parse", "1 + 2 * 3"]).contains("Binary"));

assert_eq!(ok(&["dax", "format", "'Sales'[Amount] + 1"]).trim(), "'Sales'[Amount] + 1");
assert!(ok(&["dax", "parse", "'It''s'[A]]B]"]).contains("It's"));

let query = ok(&["dax", "format", "EVALUATE SUM('Sales'[Amount])"]);
assert_eq!(query.trim(), "EVALUATE SUM('Sales'[Amount])");
assert!(ok(&["dax", "parse", "EVALUATE 1"]).contains("Query"));

let o = run(&["dax", "parse", "1 +"]);
assert_eq!(o.status.code(), Some(1));
assert!(String::from_utf8_lossy(&o.stderr).contains("expected expression"));
let o = run(&["dax", "format", "EVALUATE 1 +"]);
assert_eq!(o.status.code(), Some(1));
assert!(String::from_utf8_lossy(&o.stderr).contains("end of input"));

let dir = tmpdir("dax");
let file = dir.join("expr.dax");
std::fs::write(&file, "1 + 2 * 3").unwrap();
assert_eq!(ok(&["dax", "format", "--file", file.to_str().unwrap()]).trim(), "1 + 2 * 3");
let _ = std::fs::remove_dir_all(dir);

let mut child = bin().args(["dax", "format"]).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap();
child.stdin.as_mut().unwrap().write_all(b"1 + 2 * 3").unwrap();
let out = child.wait_with_output().unwrap();
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
assert_eq!(String::from_utf8(out.stdout).unwrap().trim(), "1 + 2 * 3");
}
12 changes: 12 additions & 0 deletions crates/dax/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
[package]
name = "gridcraft-dax"
version.workspace = true
edition.workspace = true
license.workspace = true
description = "GridCraft DAX language: lexer, Pratt parser, syntax tree and canonical printer"

[lints]
workspace = true

[dependencies]
thiserror = { workspace = true }
Loading
Loading