qua 0.75.0

Structure-aware query CLI for the Quarb engine
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
//! A notation the query asserts (spec: Grafting; the user's rulings
//! of 2026-11-29, "1, harmonize" and "Agreed on \"the engine moves
//! on the three\""). A named step that carries a notation trait
//! alone, `/plays/*/meta<json>`, reads what it names wherever the
//! text lies, a database's cell, a field of a document, a file of a
//! folder, a member of an archive, a cell of a CSV row, and the path
//! walks on into it; a text that is not written in the notation
//! grafts nothing and is told, NOT_IN_NOTATION, once for the step
//! with the count and the first. `graft` answers null for such a
//! text under the same warning, and reads the text of the node a
//! thread stands on. Every answer and line here is taken from the
//! tool.

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

const STORE: &str = r#"{"plays": [
 {"title": "Antigone", "meta": "{\"author\": {\"name\": \"Sophocles\"}}"},
 {"title": "Medea", "meta": "by Euripides"},
 {"title": "Electra", "meta": null},
 {"title": "Ajax", "meta": "{\"author\": {\"name\": \"Sophocles\"}}"},
 {"title": "Ion", "meta": "<author>Euripides</author>"}
]}"#;

fn fixture(tag: &str) -> PathBuf {
    let dir = std::env::temp_dir().join(format!("quarb-notation-{}-{tag}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(dir.join("shelf")).unwrap();
    std::fs::write(dir.join("store.json"), STORE).unwrap();
    std::fs::write(dir.join("shelf/lines.dat"), "[1353, 1419, 1510]\n").unwrap();
    std::fs::write(dir.join("shelf/note.dat"), "three plays\n").unwrap();
    std::fs::write(dir.join("shelf/play.json"), "{\"lines\": 1353}\n").unwrap();
    std::fs::write(
        dir.join("plays.csv"),
        "id,payload\n1,\"{\"\"lines\"\": 1353}\"\n2,unknown\n3,\"{\"\"lines\"\": 1510}\"\n",
    )
    .unwrap();
    let db = rusqlite::Connection::open(dir.join("plays.db")).unwrap();
    db.execute_batch(
        "CREATE TABLE plays (id INTEGER PRIMARY KEY, meta TEXT);
         INSERT INTO plays VALUES
           (1,'{\"author\": {\"name\": \"Sophocles\"}}'),
           (2,'by Euripides'),
           (3,NULL),
           (4,'{\"author\": {\"name\": \"Sophocles\"}}');",
    )
    .unwrap();
    let mut z = zip::ZipWriter::new(std::fs::File::create(dir.join("shelf.zip")).unwrap());
    let o = zip::write::SimpleFileOptions::default();
    z.start_file("lines.dat", o).unwrap();
    z.write_all(b"[1353, 1419, 1510]\n").unwrap();
    z.start_file("note.dat", o).unwrap();
    z.write_all(b"three plays\n").unwrap();
    z.finish().unwrap();
    std::fs::write(dir.join("roles.model"), "trait <late>: row[::id > 1];\n").unwrap();
    std::fs::write(dir.join("taken.model"), "trait <json>: meta;\n").unwrap();
    dir
}

/// The answer on one line, the diagnostics, and whether the run
/// answered.
fn run(dir: &Path, args: &[&str]) -> (String, String, bool) {
    let out = std::process::Command::new(env!("CARGO_BIN_EXE_qua"))
        .env("QUARB_LOCALE", "C")
        .env("QUARB_OFFLINE", "localhost")
        .current_dir(dir)
        .args(args)
        .stdin(std::process::Stdio::null())
        .output()
        .unwrap();
    (
        String::from_utf8_lossy(&out.stdout)
            .trim()
            .replace('\n', " "),
        String::from_utf8_lossy(&out.stderr).trim().to_string(),
        out.status.success(),
    )
}

/// The answer of a run that answers and says nothing beside it.
fn quiet(dir: &Path, args: &[&str]) -> String {
    let (out, err, ok) = run(dir, args);
    assert!(ok, "{args:?}: {err}");
    assert_eq!(err, "", "{args:?}");
    out
}

/// The answer and the one line of a run that answers and is told one
/// thing.
fn told(dir: &Path, args: &[&str]) -> (String, String) {
    let (out, err, ok) = run(dir, args);
    assert!(ok, "{args:?}: {err}");
    assert_eq!(err.lines().count(), 1, "{args:?}: {err}");
    (out, err)
}

#[test]
fn a_named_step_under_a_notation_tells_the_texts_it_does_not_read() {
    let d = fixture("told");
    // the step matched nothing there in silence
    let (out, line) = told(&d, &["/plays/*/meta<json>/author/name::", "store.json"]);
    assert_eq!(out, "Sophocles Sophocles");
    assert_eq!(
        line,
        "warning NOT_IN_NOTATION (/meta<json>): '<json>' reads a text as json: 2 texts are not \
         written in it (the first: \"by Euripides\"), and the step matches nothing there. Spell \
         it another way: qua man NOT_IN_NOTATION"
    );
    // one text, and the null is no text
    let (out, line) = told(&d, &["/plays/*/meta<json> @| count", "plays.db"]);
    assert_eq!(out, "2");
    assert_eq!(
        line,
        "warning NOT_IN_NOTATION (/meta<json>): '<json>' reads a text as json: 1 text is not \
         written in it (\"by Euripides\"), and the step matches nothing there. Spell it another \
         way: qua man NOT_IN_NOTATION"
    );
    // a step that selects tells nothing of what it leaves out: a
    // wildcard, a negation, an expression of the algebra
    assert_eq!(quiet(&d, &["//*<json> @| count", "store.json"]), "2");
    // (the two other texts and the null)
    assert_eq!(
        quiet(&d, &["/plays/*/meta<!json> @| count", "store.json"]),
        "3"
    );
    assert_eq!(
        quiet(&d, &["/plays/*/meta<json || xml> @| count", "store.json"]),
        "3"
    );
    // the brackets that pick among what the step matched are not the
    // step's spelling
    let (out, line) = told(&d, &["/plays/*/meta<json>[1]/author/name::", "store.json"]);
    assert_eq!(out, "Sophocles Sophocles");
    assert!(
        line.starts_with("warning NOT_IN_NOTATION (/meta<json>): "),
        "{line}"
    );
}

#[test]
fn the_step_walks_into_what_it_read_wherever_the_text_lies() {
    let d = fixture("walks");
    // a database's cell, as before
    let (out, _) = told(&d, &["/plays/*/meta<json>/author/name::", "plays.db"]);
    assert_eq!(out, "Sophocles Sophocles");
    // a text field of a document: the leaf was read and its children
    // could not be reached
    assert_eq!(
        quiet(&d, &["/plays/1/meta<json>/author/name::", "store.json"]),
        "Sophocles"
    );
    // a file of a folder that no `--graft` opens
    assert_eq!(
        quiet(&d, &["/lines.dat<json>/*::", "shelf"]),
        "1353 1419 1510"
    );
    let (out, line) = told(&d, &["/note.dat<json>/*::", "shelf"]);
    assert_eq!(out, "");
    assert_eq!(
        line,
        "warning NOT_IN_NOTATION (/note.dat<json>): '<json>' reads a text as json: 1 text is \
         not written in it (\"three plays\"), and the step matches nothing there. Spell it \
         another way: qua man NOT_IN_NOTATION"
    );
    // a member of an archive
    assert_eq!(
        quiet(&d, &["/lines.dat<json>/*::", "shelf.zip"]),
        "1353 1419 1510"
    );
    // a cell of a CSV row, named by its column: a property, which no
    // step reached
    let (out, line) = told(&d, &["/row/payload<json>/lines::", "plays.csv"]);
    assert_eq!(out, "1353 1510");
    assert_eq!(
        line,
        "warning NOT_IN_NOTATION (/payload<json>): '<json>' reads a text as json: 1 text is not \
         written in it (\"unknown\"), and the step matches nothing there. Spell it another way: \
         qua man NOT_IN_NOTATION"
    );
    // a name that is no column is nothing, and nothing is told
    assert_eq!(quiet(&d, &["/row/nosuch<json>/lines::", "plays.csv"]), "");
}

#[test]
fn a_cell_named_by_its_column_stands_under_its_row() {
    let d = fixture("cell");
    // the document answers to the column's name under the row, so
    // the way up, the path and the name cross the boundary
    assert_eq!(
        quiet(&d, &["/row[1]/payload<json>/lines", "plays.csv"]),
        "/row[1]/payload!/lines"
    );
    assert_eq!(
        quiet(&d, &["/row[3]/payload<json> | :name", "plays.csv"]),
        "payload"
    );
    assert_eq!(
        quiet(
            &d,
            &["/row[3]/payload<json>/lines | \\\\row::id", "plays.csv"]
        ),
        "3"
    );
    // without the notation the column is the property it was
    assert_eq!(quiet(&d, &["/row/payload", "plays.csv"]), "");
    assert_eq!(quiet(&d, &["/row/* @| count", "plays.csv"]), "0");
}

#[test]
fn graft_answers_null_for_a_text_that_is_not_in_the_notation() {
    let d = fixture("graft");
    // one such cell of a column ended the run
    let (out, line) = told(
        &d,
        &[
            "/plays/*/meta:: | graft(json) | /author/name::",
            "store.json",
        ],
    );
    assert_eq!(out, "Sophocles Sophocles");
    assert_eq!(
        line,
        "warning NOT_IN_NOTATION (graft(json)): 'graft(json)' reads a text as json: 2 texts are \
         not written in it (the first: \"by Euripides\"), and the command answers null for \
         each. Spell it another way: qua man NOT_IN_NOTATION"
    );
    let (out, line) = told(&d, &["/row[2]::payload | graft(json)", "plays.csv"]);
    assert_eq!(out, "null");
    assert_eq!(
        line,
        "warning NOT_IN_NOTATION (graft(json)): 'graft(json)' reads a text as json: 1 text is \
         not written in it (\"unknown\"), and the command answers null. Spell it another way: \
         qua man NOT_IN_NOTATION"
    );
    // a word that names no notation is still the query's refusal
    let (_, err, ok) = run(&d, &["/plays/*/meta:: | graft(nosuch)", "store.json"]);
    assert!(!ok);
    assert!(
        err.starts_with(
            "error REFUSED (query): refused: graft(nosuch): 'nosuch' names no notation"
        ),
        "{err}"
    );
}

#[test]
fn graft_reads_the_text_of_the_node_it_stands_on() {
    let d = fixture("node");
    // a leaf grafts where it lies and the thread stays on it: the
    // command read the node's value, which a file does not have
    assert_eq!(
        quiet(&d, &["//lines.dat | graft(json) | /*::", "shelf"]),
        "1353 1419 1510"
    );
    assert_eq!(
        quiet(&d, &["//play.json | graft(json) | /lines::", "shelf"]),
        "1353"
    );
    // with no operand, what the leaf declares, its name here
    assert_eq!(
        quiet(&d, &["//play.json | graft | /lines::", "shelf"]),
        "1353"
    );
    // a property reading reads the leaf's text as a text topic's
    assert_eq!(
        quiet(&d, &["//play.json | graft(json2) | ::lines", "shelf"]),
        "1353"
    );
    // a database's cell, a node there
    let (out, _, ok) = run(
        &d,
        &["/plays/1/meta | graft(json) | /author/name::", "plays.db"],
    );
    assert!(ok);
    assert_eq!(out, "Sophocles");
    // a leaf that is not in the notation: null, and told
    let (out, line) = told(&d, &["//note.dat | graft(json)", "shelf"]);
    assert_eq!(out, "null");
    assert_eq!(
        line,
        "warning NOT_IN_NOTATION (graft(json)): 'graft(json)' reads a text as json: 1 text is \
         not written in it (\"three plays\"), and the command answers null. Spell it another \
         way: qua man NOT_IN_NOTATION"
    );
    // a leaf that declares nothing, under no operand, is refused as
    // such a text is
    let (_, err, ok) = run(&d, &["//note.dat | graft", "shelf"]);
    assert!(!ok);
    assert!(
        err.starts_with("error REFUSED (query): refused: graft: the text declares no notation"),
        "{err}"
    );
}

#[test]
fn a_model_keeps_the_notation_and_declares_no_trait_under_its_name() {
    let d = fixture("model");
    // under a model the step matched nothing in silence
    assert_eq!(
        quiet(
            &d,
            &[
                "--model",
                "roles.model",
                "/plays/1/meta<json>/author/name::",
                "store.json"
            ]
        ),
        "Sophocles"
    );
    assert_eq!(
        quiet(
            &d,
            &["--model", "roles.model", "/lines.dat<json>/*::", "shelf"]
        ),
        "1353 1419 1510"
    );
    let (out, line) = told(
        &d,
        &[
            "--model",
            "roles.model",
            "/row<late>/payload<json>/lines::",
            "plays.csv",
        ],
    );
    assert_eq!(out, "1510");
    assert!(
        line.starts_with("warning NOT_IN_NOTATION (/payload<json>): "),
        "{line}"
    );
    // a notation's name is the notation's
    let (_, err, ok) = run(&d, &["--model", "taken.model", "/plays/*", "store.json"]);
    assert!(!ok);
    assert!(
        err.contains(
            "trait <json>: 'json' is a notation's name, and '<json>' at a step reads what the \
             step names in that notation; a model's trait takes another name"
        ),
        "{err}"
    );
}

/// A source language's word is a notation's name too (`<rs>` at a
/// step, `?format=py`), and no model declares a trait under it, on
/// every build, with the source reading or without: the model's
/// parser holds the words the syntax adapter reads, each of them a
/// notation at a step here.
///
/// A language's long name is its word's synonym wherever a notation
/// is named as an operand or an option, `graft(rust)`,
/// `?format=python` on a mount, `--format javascript` on standard
/// input, and no model declares a trait under it either (the user's
/// ruling of 2026-11-29, relayed by lang: "no notation word is open
/// to a model: <c>, <h>, <rust> alike"; they were refused, the
/// refusal listing the words). At a step the long name is the trait
/// a source file bears by its extension, with nothing read, as it
/// was: whether it asserts there too waits for his word.
#[test]
fn a_source_languages_word_is_a_notations_name() {
    let d = fixture("source");
    std::fs::write(d.join("shelf/code.dat"), "x = 1\n").unwrap();
    std::fs::write(d.join("shelf/lib.rs"), "fn main() {}\n").unwrap();
    for word in quarb_tree_sitter::EXTENSIONS {
        assert_eq!(
            quiet(&d, &[&format!("/code.dat<{word}> @| count"), "shelf"]),
            "1",
            "{word}"
        );
        let err = quarb_model::parse_model(&format!("trait <{word}>: row;")).unwrap_err();
        assert!(
            err.starts_with(&format!("trait <{word}>: '{word}' is a notation's name")),
            "{word}: {err}"
        );
    }
    for (long, word) in quarb_tree_sitter::LONG_NAMES {
        // the composing layer holds the same pairs, for a build
        // that reads no source
        assert!(
            quarb_compose::LONG_NAMES.contains(&(*long, *word)),
            "{long}"
        );
        assert_eq!(quarb_compose::canonical_notation(long), *word);
        // an operand of `graft` and a mount's option: as the word
        for (a, b) in [
            (
                format!(r#"= "x = 1" | graft({long}) | //* @| count"#),
                format!(r#"= "x = 1" | graft({word}) | //* @| count"#),
            ),
            (
                "/code.dat//* @| count".to_string(),
                "/code.dat//* @| count".to_string(),
            ),
        ] {
            let with_long = if a.starts_with('=') {
                quiet(&d, &[&a])
            } else {
                quiet(&d, &[&a, &format!("shelf?format={long}")])
            };
            let with_word = if b.starts_with('=') {
                quiet(&d, &[&b])
            } else {
                quiet(&d, &[&b, &format!("shelf?format={word}")])
            };
            assert_eq!(with_long, with_word, "{long}: {a}");
            assert_ne!(with_long, "0", "{long}: {a}");
        }
        // closed to a model, as its word is
        let err = quarb_model::parse_model(&format!("trait <{long}>: row;")).unwrap_err();
        assert!(
            err.starts_with(&format!("trait <{long}>: '{long}' is a notation's name")),
            "{long}: {err}"
        );
    }
    // standard input's `--format` takes the long name (it is asked
    // once a document is on the pipe)
    let piped = |format: &str, text: &[u8]| {
        let mut child = std::process::Command::new(env!("CARGO_BIN_EXE_qua"))
            .current_dir(&d)
            .args(["--format", format, "//* @| count"])
            .stdin(std::process::Stdio::piped())
            .stdout(std::process::Stdio::piped())
            .stderr(std::process::Stdio::piped())
            .spawn()
            .unwrap();
        child.stdin.take().unwrap().write_all(text).unwrap();
        let out = child.wait_with_output().unwrap();
        (
            String::from_utf8_lossy(&out.stdout).trim().to_string(),
            String::from_utf8_lossy(&out.stderr).to_string(),
            out.status.success(),
        )
    };
    let (by_long, err, ok) = piped("rust", b"fn main() {}\n");
    assert!(ok, "{err}");
    assert_eq!(by_long, piped("rs", b"fn main() {}\n").0);
    assert_eq!(by_long, "4");
    // at a step the long name is the trait a source file bears by
    // its extension, and reads nothing: the file named `.rs`, and
    // no assertion on a file that is not
    assert_eq!(quiet(&d, &["/*<rust> | :name", "shelf"]), "lib.rs");
    assert_eq!(quiet(&d, &["/code.dat<rust> @| count", "shelf"]), "0");
    // a word no reader takes is a model's to declare
    assert!(quarb_model::parse_model("trait <pascal>: row;").is_ok());
    // and a refusal that lists the notations names the languages'
    // words, each with its long name
    let listed = format!(
        "or a source language's word ({})",
        quarb_compose::source_words_listed()
    );
    assert!(listed.contains("rs or rust, py or python, js or javascript, mjs"));
    for args in [
        &[r#"= "fn main() {}" | graft(pascal)"#][..],
        &["--graft", "/* @| count", "shelf?format=pascal"][..],
    ] {
        let (_, err, ok) = run(&d, args);
        assert!(!ok, "{args:?}");
        assert!(err.contains(&listed), "{args:?}: {err}");
    }
    let (_, err, ok) = piped("pascal", b"begin end.\n");
    assert!(!ok);
    assert!(err.contains(&listed), "--format pascal: {err}");
    // a file's own `?format=` takes no source language, and says so
    // of the word as it was written
    let (_, err, ok) = run(&d, &["/* @| count", "shelf/code.dat?format=rust"]);
    assert!(!ok);
    assert!(
        err.contains(
            "format=rust names a source language, which a file is read as by its extension"
        ),
        "{err}"
    );
    assert_eq!(
        quiet(&d, &[r#"= "fn main() {}" | graft(rs) | //* @| count"#]),
        "4"
    );
}
/// `?format=NOTATION` on a mount opens the leaves it covers, with or
/// without `--graft` (the user's ruling of 2026-11-29, relayed by
/// lang). On a directory without the flag the option was accepted
/// and the files stayed leaves, in silence; on an archive, whose
/// members graft by what they declare, it declared nothing.
#[test]
fn a_mounts_format_opens_its_leaves_with_or_without_the_flag() {
    let d = fixture("mount-format");
    // a directory's files are leaves until something opens them
    assert_eq!(quiet(&d, &["/lines.dat/* @| count", "shelf"]), "0");
    // the option opens every file as the notation, the flag or no
    for args in [
        &["/lines.dat/* @| count", "shelf?format=json"][..],
        &["--graft", "/lines.dat/* @| count", "shelf?format=json"],
    ] {
        assert_eq!(quiet(&d, args), "3", "{args:?}");
    }
    assert_eq!(
        quiet(&d, &["/s/lines.dat/*:: @| sum", "s=shelf?format=json"]),
        "4282"
    );
    assert_eq!(
        quiet(&d, &["/play.json/lines::", "shelf?format=json"]),
        "1353"
    );
    // a file that is not written in it stays the leaf it was
    assert_eq!(
        quiet(&d, &["/* | [:is-leaf] | :name", "shelf?format=json"]),
        "note.dat"
    );
    // an archive's members the same
    assert_eq!(quiet(&d, &["/lines.dat/* @| count", "shelf.zip"]), "0");
    assert_eq!(
        quiet(&d, &["/lines.dat/* @| count", "shelf.zip?format=json"]),
        "3"
    );
    assert_eq!(
        quiet(&d, &["/z/lines.dat/*:: @| sum", "z=shelf.zip?format=json"]),
        "4282"
    );
    // (`--no-graft` keeps an archive's members closed, as it says)
    assert_eq!(
        quiet(
            &d,
            &[
                "--no-graft",
                "/lines.dat/* @| count",
                "shelf.zip?format=json"
            ]
        ),
        "0"
    );
}