qua 0.75.0

Structure-aware query CLI for the Quarb engine
//! "Two references are equal when they name the same node, whatever
//! path reached it" (spec: Node references), in every command that
//! compares values. `=` and a fold's key went by the node; `unique`,
//! `unique_by`, `frequencies` and every other command that keys by
//! the value comparison went by the reference's TEXT, and a
//! reference's text is not always one node's: every row of a CSV is
//! `/row`, same-named siblings of an XML document `/shelf/book`. So
//! the references of different nodes merged, in silence (lang's
//! finding of 2026-11-26; 0.74.0 answered the same).

use std::path::{Path, PathBuf};

fn dir(tag: &str) -> PathBuf {
    let dir = std::env::temp_dir().join(format!("quarb-node-refs-{}-{tag}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(
        dir.join("shelf.csv"),
        "title,author,pages\n\
         Iliad,Homer,704\n\
         Emma,Austen,474\n\
         Histories,Herodotus,716\n\
         Odyssey,Homer,541\n",
    )
    .unwrap();
    std::fs::write(
        dir.join("refs.xml"),
        "<shelf><book>Iliad</book><book>Emma</book><note>n</note></shelf>",
    )
    .unwrap();
    let twelve: Vec<String> = (1..=12).map(|n| format!(r#"{{"n": {n}}}"#)).collect();
    std::fs::write(
        dir.join("twelve.json"),
        format!(r#"{{"items": [{}]}}"#, twelve.join(", ")),
    )
    .unwrap();
    std::fs::write(
        dir.join("books.json"),
        r#"{"books": [{"title": "Iliad"}, {"title": "Emma"}, {"title": "Histories"}]}"#,
    )
    .unwrap();
    dir
}

/// The answer of a run that answers and says nothing beside it, on
/// one line.
fn quiet(dir: &Path, query: &str, source: &str) -> String {
    let out = std::process::Command::new(env!("CARGO_BIN_EXE_qua"))
        .env("QUARB_LOCALE", "C")
        .env("QUARB_OFFLINE", "localhost")
        .current_dir(dir)
        .args([query, source])
        .stdin(std::process::Stdio::null())
        .output()
        .unwrap();
    let err = String::from_utf8_lossy(&out.stderr).trim().to_string();
    assert!(out.status.success(), "{query}: {err}");
    assert_eq!(err, "", "{query}");
    String::from_utf8_lossy(&out.stdout)
        .trim()
        .replace('\n', " ")
}

/// References that print alike and name different nodes are
/// different values to every command that compares values.
#[test]
fn references_of_different_nodes_are_different_values() {
    let d = dir("apart");
    for (query, source, answer) in [
        // (each was 1, 1 and 2: the rows of a CSV, and two of the
        // three children of the XML root, merged)
        ("/row[..3] | $$_ @| unique @| count", "shelf.csv", "3"),
        (
            "/row[..3] | %(r = $$_; ::title) @| unique_by(:r) @| count",
            "shelf.csv",
            "3",
        ),
        ("/shelf/* | $$_ @| unique @| count", "refs.xml", "3"),
        // where the texts differ they never merged
        ("/books/*[..3] | $$_ @| unique @| count", "books.json", "3"),
        // a list's own `unique`, a key that is the reference itself
        ("/row | $$_ @| @ | unique | count", "shelf.csv", "4"),
        ("/row | $$_ @| unique_by($_) @| count", "shelf.csv", "4"),
        // a count of each: four nodes, once each (it was one row,
        // `/row` four times)
        ("/row | $$_ @| frequencies | :n", "shelf.csv", "1 1 1 1"),
        // a record and a list that hold a reference are told apart
        // by it, where they print alike
        ("/row | %(r = $$_) @| unique @| count", "shelf.csv", "4"),
        ("/row | @($$_) @| unique @| count", "shelf.csv", "4"),
        (
            "/row | %(r = $$_; ::author) @| unique @| count",
            "shelf.csv",
            "4",
        ),
    ] {
        assert_eq!(quiet(&d, query, source), answer, "{query}");
    }
}

/// The same node reached twice is one value, as it was; and what
/// already went by the node is as it was: `=`, a fold's key, a
/// membership test.
#[test]
fn references_of_one_node_are_one_value() {
    let d = dir("one");
    for (query, answer) in [
        (
            "/row[1] | .a | ^/row[1] | @($$_; $.a) | unique | count",
            "1",
        ),
        ("/row[..2] | $$_ @| @ | ($_ ++ $_) | unique | count", "2"),
        (
            "/row[1] | .a | ^/row[2] | %(same = ($$_ = $.a))",
            "%(same = false)",
        ),
        (
            "/row[1] | .a | ^/row[1] | %(same = ($$_ = $.a))",
            "%(same = true)",
        ),
        (
            r#"/row[..3] | .n($$_) @|{.n} %(k = "$.n"; rows = count)"#,
            r#"%(k = "/row"; rows = 1) %(k = "/row"; rows = 1) %(k = "/row"; rows = 1)"#,
        ),
        (
            "/row[..2] | $$_ @| @ | .l | ^/row[2] | ($$_ <<= $.l)",
            "true",
        ),
        (
            "/row[..2] | $$_ @| @ | .l | ^/row[3] | ($$_ <<= $.l)",
            "false",
        ),
        // nodes themselves, with no reference made, were never
        // merged
        ("/row[..3] @| collapse @| count", "3"),
    ] {
        assert_eq!(quiet(&d, query, "shelf.csv"), answer, "{query}");
    }
}

/// "Without a collation sort orders by class, null first, then
/// booleans, numbers, instants, quantities, text and lists, each
/// class in its own order, and nodes in document order" (spec:
/// Lists). References ordered as their locators READ, `/items/10`
/// before `/items/2`, and those that print alike not at all; threads
/// standing on bare nodes were keyed by a null topic and stayed as
/// they came (lang's finding of 2026-11-26). A node's place is read
/// through the adapter: the ordinals from the root down.
#[test]
fn nodes_and_references_order_in_document_order() {
    let d = dir("order");
    let up = "1 2 3 4 5 6 7 8 9 10 11 12";
    let down = "12 11 10 9 8 7 6 5 4 3 2 1";
    for (query, source, answer) in [
        // references whose locators differ: by the node's place, not
        // by the locator's text (it was 1 10 11 12 2 3 …)
        (
            "/items/* | %(r = $$_; ::n) @| reverse @| sort_by(:r) | :n",
            "twelve.json",
            up,
        ),
        (
            "/items/* @| reverse @| sort_by($$_) | ::n",
            "twelve.json",
            up,
        ),
        (
            "/items/* | %(r = $$_; ::n) @| sort_by(:r; -d) | :n",
            "twelve.json",
            down,
        ),
        (
            "/items/* | %(r = $$_; ::n) @| top(3; :r) | :n",
            "twelve.json",
            "12 11 10",
        ),
        // threads on bare nodes: ordered as the nodes, their topics
        // left as they are (they stayed as they came: 12 … 1)
        ("/items/* @| reverse @| sort | ::n", "twelve.json", up),
        (
            "/items/* @| reverse @| sort(--desc) | ::n",
            "twelve.json",
            down,
        ),
        (
            "/items/*[::n > 9] || /items/*[::n < 3] @| sort | ::n",
            "twelve.json",
            "1 2 10 11 12",
        ),
        // a node before what is under it
        (
            "/items/3/n || /items/3 || /items/2 || /items @| sort | :name",
            "twelve.json",
            "items 2 3 n",
        ),
        // a mix: the values first, in their order, then the nodes
        (
            "/items/*[..3] | (::n > 1 ? ::n : $$_) @| reverse @| sort",
            "twelve.json",
            "2 3 /items/1",
        ),
        // references that print alike: the rows of a CSV, the
        // same-named children of an XML root, in the file's order
        (
            "/row | %(r = $$_; ::title) @| reverse @| sort_by(:r) | :title",
            "shelf.csv",
            "Iliad Emma Histories Odyssey",
        ),
        (
            "/shelf/* @| reverse @| sort | ::",
            "refs.xml",
            "Iliad Emma n",
        ),
    ] {
        assert_eq!(quiet(&d, query, source), answer, "{query}");
    }
    // two sources under one root: the arbor's own order, the first
    // mount before the second
    let out = std::process::Command::new(env!("CARGO_BIN_EXE_qua"))
        .env("QUARB_LOCALE", "C")
        .current_dir(&d)
        .args([
            "/b/row[1] || /a/items/2 || /a/items/1 @| sort | :path",
            "a=twelve.json",
            "b=shelf.csv",
        ])
        .stdin(std::process::Stdio::null())
        .output()
        .unwrap();
    assert!(
        out.status.success(),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );
    assert_eq!(
        String::from_utf8_lossy(&out.stdout)
            .trim()
            .replace('\n', " "),
        "/items/1 /items/2 /row"
    );
}