qua 0.74.0

Structure-aware query CLI for the Quarb engine
//! An operand that expects an integer takes a whole float as that
//! integer and refuses a float with a fraction (ruling 2026-11-24:
//! "commands that expect an integer operand should cast to int and
//! refuse in case of fractional floats").
//!
//! Until then a whole float was refused by its kind (`first(4 div
//! 2)`: "operand 1 must be an integer, not a number"), and two
//! commands cut a fraction off in silence: `indent(2.5)` indented by
//! two units, `stress(2.7)` stressed the second vowel.

use std::path::PathBuf;

fn fixture(tag: &str) -> PathBuf {
    let dir = std::env::temp_dir().join(format!("quarb-integers-{}-{tag}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    let file = dir.join("rows.json");
    std::fs::write(
        &file,
        r#"{"rows": [
            {"n": 1, "v": [10, 20, 30, 40]},
            {"n": 2, "v": [60, 70, 80, 90]},
            {"n": 3, "v": [1, 2, 3, 4]},
            {"n": 4, "v": []},
            {"n": 5, "v": [7]}]}"#,
    )
    .unwrap();
    file
}

/// Whether the run answered, its output, its diagnostics.
fn qua(q: &str, file: &str) -> (bool, String, String) {
    let out = std::process::Command::new(env!("CARGO_BIN_EXE_qua"))
        .env("QUARB_LOCALE", "C")
        .args([q, file])
        .stdin(std::process::Stdio::null())
        .output()
        .unwrap();
    (
        out.status.success(),
        String::from_utf8(out.stdout).unwrap(),
        String::from_utf8_lossy(&out.stderr).to_string(),
    )
}

/// The answer of a query that answers with nothing said beside it.
fn answer(q: &str, file: &str) -> String {
    let (ok, out, err) = qua(q, file);
    assert!(ok, "{q}: {err}");
    assert_eq!(err, "", "{q}");
    out
}

/// The diagnostics of a query that is refused.
fn refused(q: &str, file: &str) -> String {
    let (ok, out, err) = qua(q, file);
    assert!(!ok, "{q}: expected a refusal, got {out:?}");
    err
}

/// The calls of the commands that reduce, order or read a context,
/// each with a whole float and with the integer it is: written
/// (`2.0`) and computed (`4 div 2`, which is a float).
const STREAM: [(&str, &str); 21] = [
    ("first(2.0)", "first(2)"),
    ("first(4 div 2)", "first(2)"),
    ("last(2.0)", "last(2)"),
    ("top(2.0; $_)", "top(2; $_)"),
    ("top(4 div 2; $_)", "top(2; $_)"),
    ("bottom(2.0; $_)", "bottom(2; $_)"),
    ("shift(1.0)", "shift(1)"),
    ("shift(2 div 2)", "shift(1)"),
    ("frequencies(1.0)", "frequencies(1)"),
    ("bins(2.0)", "bins(2)"),
    ("histogram(2.0)", "histogram(2)"),
    ("histogram(--width=10 div 2)", "histogram(--width=5)"),
    ("ngrams(2.0)", "ngrams(2)"),
    ("combinations(2.0)", "combinations(2)"),
    ("permutations(4 div 2)", "permutations(2)"),
    ("flatten(1.0)", "flatten(1)"),
    ("skipgrams(2.0; 1.0)", "skipgrams(2; 1)"),
    ("sample(2.0; --seed=3)", "sample(2; --seed=3)"),
    ("sample(2; --seed=3.0)", "sample(2; --seed=3)"),
    ("sample(4 div 2; --seed=6 div 2)", "sample(2; --seed=3)"),
    ("shuffle(--seed=3.0)", "shuffle(--seed=3)"),
];

#[test]
fn a_whole_float_counts_as_its_integer() {
    let f = fixture("stream");
    let f = f.to_str().unwrap();
    for (float, integer) in STREAM {
        for before in ["/rows/*::n @| ", "/rows/1::v | "] {
            assert_eq!(
                answer(&format!("{before}{float}"), f),
                answer(&format!("{before}{integer}"), f),
                "{before}{float}"
            );
        }
    }
    // the options that hold a count
    for (float, integer) in [
        ("/rows/* @| tree(--depth=1.0)", "/rows/* @| tree(--depth=1)"),
        (
            "/rows/* @| tree(--depth=2 div 2)",
            "/rows/* @| tree(--depth=1)",
        ),
        (
            "/rows/*/v/* @| threads(--depth=1.0)",
            "/rows/*/v/* @| threads(--depth=1)",
        ),
    ] {
        assert_eq!(answer(float, f), answer(integer, f), "{float}");
    }
    // a command of one value
    for (float, integer) in [
        ("= \"ab\" | pad(4.0)", "= \"ab\" | pad(4)"),
        ("= \"ab\" | pad(8 div 2)", "= \"ab\" | pad(4)"),
        ("= \"ab\" | lpad(4.0; \"*\")", "= \"ab\" | lpad(4; \"*\")"),
        ("= \"ab\" | repeat(2.0)", "= \"ab\" | repeat(2)"),
        ("= \"ab\" | repeat(4 div 2)", "= \"ab\" | repeat(2)"),
        (
            "= \"ab\" | indent(2.0; \"-\")",
            "= \"ab\" | indent(2; \"-\")",
        ),
        ("= 2.345 | round(2.0)", "= 2.345 | round(2)"),
        ("= 2.345 | round(4 div 2)", "= 2.345 | round(2)"),
        ("= 5 | choose(2.0)", "= 5 | choose(2)"),
        ("= \"a b c d\" | ngrams(2.0)", "= \"a b c d\" | ngrams(2)"),
        (
            "= #(@(a; b); %(1; 2); %(3; 4)) | cell(2.0; 1.0)",
            "= #(@(a; b); %(1; 2); %(3; 4)) | cell(2; 1)",
        ),
    ] {
        assert_eq!(answer(float, f), answer(integer, f), "{float}");
    }
}

/// A float with a fraction is refused by its value, where it is
/// written (when the query is parsed) and where an expression comes
/// to it (when the command runs), in a command of the whole context
/// and in a command of one value. `indent` and `stress` cut the
/// fraction off in silence; the others refused the kind, "must be an
/// integer, not a number".
#[test]
fn a_fraction_is_refused_by_its_value() {
    let f = fixture("fractions");
    let f = f.to_str().unwrap();
    let operand =
        |name: &str, v: &str| format!("{name}: operand 1 takes a whole number: {v} has a fraction");
    for (q, what) in [
        ("/rows/*::n @| first(2.5)", operand("first", "2.5")),
        ("/rows/*::n @| first(5 div 2)", operand("first", "2.5")),
        ("/rows/1::v | first(5 div 2)", operand("first", "2.5")),
        ("/rows/*::n @| top(2.5; $_)", operand("top", "2.5")),
        ("/rows/*::n @| top(5 div 2; $_)", operand("top", "2.5")),
        ("/rows/*::n @| bins(2.5)", operand("bins", "2.5")),
        ("= \"ab\" | pad(2.5)", operand("pad", "2.5")),
        ("= \"ab\" | pad(5 div 2)", operand("pad", "2.5")),
        ("= \"ab\" | indent(2.5; \"-\")", operand("indent", "2.5")),
        (
            "= \"ab\" | indent(5 div 2; \"-\")",
            operand("indent", "2.5"),
        ),
        ("= \"молоко\" | stress(2.7)", operand("stress", "2.7")),
        ("= 2.345 | round(2.5)", operand("round", "2.5")),
        ("= 2.345 | round(5 div 2)", operand("round", "2.5")),
        ("= 5 | choose(2.5)", operand("choose", "2.5")),
        (
            "/rows/*::n @| sample(2; --seed=1.5)",
            "sample: --seed takes a whole number: 1.5 has a fraction".to_string(),
        ),
        (
            "/rows/*::n @| sample(2; --seed=3 div 2)",
            "sample: --seed takes a whole number: 1.5 has a fraction".to_string(),
        ),
        (
            "/rows/*/v/* @| threads(--depth=1.5)",
            "threads: --depth takes a whole number, zero or more: 1.5 has a fraction".to_string(),
        ),
        (
            "/rows/*/v/* @| threads(--depth=0 - 1)",
            "threads: --depth takes a whole number, zero or more: -1 is below zero".to_string(),
        ),
    ] {
        let e = refused(q, f);
        assert!(e.contains(&what), "{q}: {e}");
    }
}