arblang 0.1.2

Visualize and modify Unix pipelines: pipe a stream in, arb spawns a dynamic TUI
Documentation
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
//! Native jq-syntax front-end for `source { … }` bodies. A body command whose
//! first token is a jq literal (starts with `.`, or is a `select(…)`/`map(…)`
//! stage) is handed here verbatim (verb + args, space-joined) and translated to
//! a `Vec<QueryOp>` over arb's existing ops. This is a PRACTICAL subset — path,
//! iterate, index, pipe, select, map, and the builtins arb already implements —
//! not Turing-complete jq. Anything outside the subset is a clean error, never a
//! silent mis-translation.

use crate::expr::Expr;
use crate::query::{FieldSel, QueryOp};

/// Translate a reconstructed jq command string into arb ops. Splits on top-level
/// `|` (jq pipe) and translates each stage in order.
pub fn translate(src: &str) -> Result<Vec<QueryOp>, String> {
    let mut ops = Vec::new();
    for stage in split_pipe(src)? {
        let stage = stage.trim();
        if stage.is_empty() {
            return Err(format!("jq: empty pipe stage in `{src}`"));
        }
        translate_stage(stage, &mut ops)?;
    }
    Ok(ops)
}

/// Split on `|` that is not inside `(` `)`, `[` `]`, or a double-quoted string.
fn split_pipe(src: &str) -> Result<Vec<String>, String> {
    let mut out = Vec::new();
    let mut cur = String::new();
    let mut depth = 0i32;
    let mut in_str = false;
    for c in src.chars() {
        match c {
            '"' => {
                in_str = !in_str;
                cur.push(c);
            }
            '(' | '[' if !in_str => {
                depth += 1;
                cur.push(c);
            }
            ')' | ']' if !in_str => {
                depth -= 1;
                cur.push(c);
            }
            '|' if !in_str && depth == 0 => {
                out.push(std::mem::take(&mut cur));
            }
            _ => cur.push(c),
        }
    }
    if in_str {
        return Err(format!("jq: unterminated string in `{src}`"));
    }
    out.push(cur);
    Ok(out)
}

/// Translate one pipe-free jq stage, appending its ops.
fn translate_stage(s: &str, ops: &mut Vec<QueryOp>) -> Result<(), String> {
    match s {
        "." => return Ok(()), // identity
        ".[]" => {
            ops.push(QueryOp::Each);
            return Ok(());
        }
        "keys" => {
            ops.push(QueryOp::Keys);
            return Ok(());
        }
        "values" => {
            ops.push(QueryOp::NonNull);
            return Ok(());
        }
        "length" => {
            ops.push(QueryOp::JsonLen);
            return Ok(());
        }
        "add" => {
            ops.push(QueryOp::Add);
            return Ok(());
        }
        "flatten" => {
            ops.push(QueryOp::Flatten);
            return Ok(());
        }
        "to_entries" => {
            ops.push(QueryOp::Entries);
            return Ok(());
        }
        _ => {}
    }
    if let Some(inner) = fn_call(s, "select") {
        ops.push(QueryOp::Where(parse_expr(inner)?));
        return Ok(());
    }
    if let Some(inner) = fn_call(s, "map") {
        // jq identity: `map(f)` == `[.[] | f]`. arb drops the array rewrap, so
        // `map(f)` == iterate-then-f over the elements.
        ops.push(QueryOp::Each);
        translate_stage(inner.trim(), ops)?;
        return Ok(());
    }
    if let Some(inner) = fn_call(s, "has") {
        let key = strip_quotes(inner.trim());
        if key.is_empty() {
            return Err(format!("jq: has() expects a key: `{s}`"));
        }
        ops.push(QueryOp::HasKey(key));
        return Ok(());
    }
    if s.starts_with('.') {
        if is_pure_path(s) {
            return translate_path(s, ops);
        }
        // A `.field`-bearing arithmetic body (typically inside `map(...)`), e.g.
        // `. * 2` or `.a + .b` -> a per-element Map.
        ops.push(QueryOp::Map(parse_expr(s)?));
        return Ok(());
    }
    Err(format!("jq: unsupported expression `{s}`"))
}

/// If `s` is exactly `name( … )`, return the inside; else None.
fn fn_call<'a>(s: &'a str, name: &str) -> Option<&'a str> {
    let rest = s.strip_prefix(name)?.trim_start();
    let inner = rest.strip_prefix('(')?.strip_suffix(')')?;
    Some(inner)
}

/// Strip one layer of surrounding double quotes.
fn strip_quotes(s: &str) -> String {
    s.strip_prefix('"')
        .and_then(|x| x.strip_suffix('"'))
        .unwrap_or(s)
        .to_string()
}

/// A stage is a pure path if every char is a path char (no spaces/operators
/// outside brackets). `:` and `-` are allowed so slices `.[1:3]` and negative
/// indices `.[-1]` route here; a bare `-`/`: ` outside a bracket still errors in
/// `translate_path` (fail-closed), never mis-handles.
fn is_pure_path(s: &str) -> bool {
    s.chars()
        .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '[' | ']' | '"' | '_' | ':' | '-'))
}

/// Translate a pure path (`.a.b`, `.foo[]`, `.[0]`, `.["k"]`) into ops.
fn translate_path(s: &str, ops: &mut Vec<QueryOp>) -> Result<(), String> {
    let cs: Vec<char> = s.chars().collect();
    let mut i = 0usize;
    let mut key: Vec<String> = Vec::new();
    if cs.first() != Some(&'.') {
        return Err(format!("jq: path must start with `.`: `{s}`"));
    }
    let flush = |key: &mut Vec<String>, ops: &mut Vec<QueryOp>| {
        if !key.is_empty() {
            ops.push(QueryOp::Field(FieldSel::Key(std::mem::take(key))));
        }
    };
    while i < cs.len() {
        match cs[i] {
            '.' => {
                i += 1;
                if cs.get(i) == Some(&'[') {
                    parse_bracket(&cs, &mut i, &mut key, ops, &flush, s)?;
                } else {
                    let id = take_ident(&cs, &mut i);
                    if id.is_empty() {
                        return Err(format!("jq: expected a key after `.` in `{s}`"));
                    }
                    key.push(id);
                }
            }
            '[' => parse_bracket(&cs, &mut i, &mut key, ops, &flush, s)?,
            other => return Err(format!("jq: unexpected `{other}` in path `{s}`")),
        }
    }
    flush(&mut key, ops);
    Ok(())
}

/// Parse a subscript at `cs[i] == '['`: `[]` (iterate), `["k"]` (string key),
/// `[N]`/`[-N]` (array index, negative from the end), or `[a:b]` (slice, either
/// bound optional/negative).
fn parse_bracket(
    cs: &[char],
    i: &mut usize,
    key: &mut Vec<String>,
    ops: &mut Vec<QueryOp>,
    flush: &dyn Fn(&mut Vec<String>, &mut Vec<QueryOp>),
    s: &str,
) -> Result<(), String> {
    *i += 1; // consume '['
    let start = *i;
    while *i < cs.len() && cs[*i] != ']' {
        *i += 1;
    }
    if cs.get(*i) != Some(&']') {
        return Err(format!("jq: unterminated `[` in `{s}`"));
    }
    let content: String = cs[start..*i].iter().collect();
    *i += 1; // consume ']'
    let c = content.trim();
    // `[]` — iterate the array/object.
    if c.is_empty() {
        flush(key, ops);
        ops.push(QueryOp::Each);
        return Ok(());
    }
    // `["key"]` — a quoted object key (checked before `:` so `["a:b"]` is a key).
    if let Some(k) = c.strip_prefix('"').and_then(|x| x.strip_suffix('"')) {
        key.push(k.to_string());
        return Ok(());
    }
    // `[a:b]` — a slice; it applies to the value the pending path points at.
    if let Some((a, b)) = c.split_once(':') {
        flush(key, ops);
        ops.push(QueryOp::JsonSlice(
            parse_opt_int(a, s)?,
            parse_opt_int(b, s)?,
        ));
        return Ok(());
    }
    // `[N]` / `[-N]` — an array index (`walk` handles the negative case).
    if c.parse::<i64>().is_ok() {
        key.push(c.to_string());
        Ok(())
    } else {
        Err(format!("jq: unsupported subscript `[{content}]` in `{s}`"))
    }
}

/// Parse an optional slice bound: empty → `None`, else an `i64` (may be negative).
fn parse_opt_int(s: &str, whole: &str) -> Result<Option<i64>, String> {
    let s = s.trim();
    if s.is_empty() {
        Ok(None)
    } else {
        s.parse::<i64>()
            .map(Some)
            .map_err(|_| format!("jq: bad slice bound `{s}` in `{whole}`"))
    }
}

fn take_ident(cs: &[char], i: &mut usize) -> String {
    let start = *i;
    while *i < cs.len() && (cs[*i].is_ascii_alphanumeric() || cs[*i] == '_') {
        *i += 1;
    }
    cs[start..*i].iter().collect()
}

/// Parse a jq expression body (a `select(...)` predicate or a `map(...)` /
/// arithmetic stage) into an arb `Expr`: rewrite each leading `.field` to an arb
/// field bareword, then defer to arb's expression parser. Nested field paths
/// (`.a.b`) inside an expression are unsupported and error.
fn parse_expr(src: &str) -> Result<Expr, String> {
    let rewritten = rewrite_fields(src)?;
    crate::expr::parse(&rewritten).map_err(|e| format!("jq: {e}"))
}

/// Rewrite jq `.field` refs to arb barewords. `.` followed by an identifier and
/// NOT preceded by an alphanumeric is a field ref (drop the dot). `.` before a
/// digit stays (decimal / range). `.a.b` (nested) errors.
fn rewrite_fields(src: &str) -> Result<String, String> {
    let cs: Vec<char> = src.chars().collect();
    let mut out = String::new();
    let mut i = 0;
    while i < cs.len() {
        let c = cs[i];
        if c == '.' {
            let next = cs.get(i + 1).copied();
            let prev_alnum = out
                .chars()
                .last()
                .map(|p| p.is_alphanumeric() || p == '_')
                .unwrap_or(false);
            if matches!(next, Some(d) if d.is_ascii_alphabetic() || d == '_') {
                if prev_alnum {
                    return Err(format!(
                        "jq: nested field path (.a.b) inside select/map is unsupported: `{src}`"
                    ));
                }
                i += 1; // drop the '.'
                while i < cs.len() && (cs[i].is_alphanumeric() || cs[i] == '_') {
                    out.push(cs[i]);
                    i += 1;
                }
                if cs.get(i) == Some(&'.')
                    && matches!(cs.get(i + 1), Some(d) if d.is_ascii_alphabetic() || *d == '_')
                {
                    return Err(format!(
                        "jq: nested field path (.a.b) inside select/map is unsupported: `{src}`"
                    ));
                }
                continue;
            }
            // `.` before a digit is a decimal (`.5`); `..` is a range; a bare `.`
            // (identity of the current element) becomes arb's line scalar `x`.
            if matches!(next, Some(d) if d.is_ascii_digit()) || next == Some('.') {
                out.push('.');
            } else {
                out.push('x');
            }
            i += 1;
            continue;
        }
        out.push(c);
        i += 1;
    }
    Ok(out)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::query::{eval, QueryResult};

    fn run(jq: &str, lines: &[&str]) -> Vec<String> {
        let ops = translate(jq).unwrap();
        match eval(
            &ops,
            &lines.iter().map(|s| s.to_string()).collect::<Vec<_>>(),
            1.0,
        ) {
            QueryResult::Lines(v) => v,
            other => panic!("expected lines, got {other:?}"),
        }
    }

    #[test]
    fn identity() {
        assert_eq!(run(".", &["a", "b"]), vec!["a", "b"]);
    }

    #[test]
    fn key_path() {
        assert_eq!(run(".foo.bar", &[r#"{"foo":{"bar":7}}"#]), vec!["7"]);
    }

    #[test]
    fn iterate_root() {
        assert_eq!(run(".[]", &["[1,2,3]"]), vec!["1", "2", "3"]);
    }

    #[test]
    fn iterate_object_yields_values() {
        // jq `.[]` over an object iterates its VALUES (not passes it through).
        assert_eq!(run(".[]", &[r#"{"a":1,"b":2}"#]), vec!["1", "2"]);
        // `map(f)` over an object applies f to each value.
        assert_eq!(run("map(.+1)", &[r#"{"a":1,"b":2}"#]), vec!["2", "3"]);
    }

    #[test]
    fn field_then_iterate() {
        assert_eq!(run(".items[]", &[r#"{"items":[1,2]}"#]), vec!["1", "2"]);
    }

    #[test]
    fn array_index() {
        assert_eq!(run(".[1]", &[r#"["a","b","c"]"#]), vec!["b"]);
        assert_eq!(run(".foo[0]", &[r#"{"foo":["x","y"]}"#]), vec!["x"]);
    }

    #[test]
    fn bracket_string_key() {
        assert_eq!(run(r#".["foo"]"#, &[r#"{"foo":9}"#]), vec!["9"]);
    }

    #[test]
    fn pipe_two_ops() {
        assert_eq!(run(".foo | .bar", &[r#"{"foo":{"bar":5}}"#]), vec!["5"]);
    }

    #[test]
    fn select_numeric() {
        let out = run(
            "select(.amount > 100)",
            &[r#"{"amount":50}"#, r#"{"amount":150}"#],
        );
        assert_eq!(out, vec![r#"{"amount":150}"#]);
    }

    #[test]
    fn iterate_then_select() {
        let out = run(".[] | select(.n >= 2)", &[r#"[{"n":1},{"n":2},{"n":3}]"#]);
        assert_eq!(out, vec![r#"{"n":2}"#, r#"{"n":3}"#]);
    }

    #[test]
    fn map_field() {
        // map(.price) == .[] | .price
        assert_eq!(
            run("map(.price)", &[r#"[{"price":3},{"price":4}]"#]),
            vec!["3", "4"]
        );
    }

    #[test]
    fn map_arith() {
        assert_eq!(run("map(. * 2)", &["[1,2,3]"]), vec!["2", "4", "6"]);
    }

    #[test]
    fn has_key() {
        // jq `has(k)` is a per-input BOOLEAN test, not a filter (real jq prints
        // `true` then `false` for these two inputs).
        let out = run(r#"has("id")"#, &[r#"{"id":1}"#, r#"{"x":2}"#]);
        assert_eq!(out, vec!["true", "false"]);
    }

    #[test]
    fn values_is_select_non_null() {
        // jq `values` == `select(. != null)`: drop nulls, pass the rest through
        // unchanged — NOT object-value iteration.
        let out = run("values", &[r#"{"a":1,"b":2}"#, "null", "5"]);
        assert_eq!(out, vec![r#"{"a":1,"b":2}"#, "5"]);
    }

    #[test]
    fn flatten_is_recursive() {
        // jq `flatten` flattens ALL nesting levels (real jq: [1,2,3,4]).
        assert_eq!(
            run("flatten", &["[1,[2,[3,[4]]]]"]),
            vec!["1", "2", "3", "4"]
        );
    }

    #[test]
    fn builtins() {
        assert_eq!(run("keys", &[r#"{"a":1,"b":2}"#]), vec!["a", "b"]);
        assert_eq!(run("add", &["[1,2,3]"]), vec!["6"]);
        assert_eq!(run(".[] | length", &[r#"["ab","cde"]"#]), vec!["2", "3"]);
    }

    #[test]
    fn slices_and_negative_indices() {
        // Array slice, either bound optional or negative.
        assert_eq!(run(".[1:3]", &["[10,20,30,40,50]"]), vec!["[20,30]"]);
        assert_eq!(run(".[:2]", &["[10,20,30]"]), vec!["[10,20]"]);
        assert_eq!(run(".[2:]", &["[10,20,30,40]"]), vec!["[30,40]"]);
        assert_eq!(run(".[-2:]", &["[10,20,30,40]"]), vec!["[30,40]"]);
        assert_eq!(run(".foo[1:3]", &[r#"{"foo":[1,2,3,4]}"#]), vec!["[2,3]"]);
        // String slice.
        assert_eq!(run(".[1:3]", &[r#""hello""#]), vec!["el"]);
        // Negative index → element from the end.
        assert_eq!(run(".[-1]", &[r#"["a","b","c"]"#]), vec!["c"]);
        assert_eq!(run(".foo[-1]", &[r#"{"foo":[1,2,3]}"#]), vec!["3"]);
    }

    #[test]
    fn length_is_json_aware() {
        assert_eq!(run("length", &["[1,2,3]"]), vec!["3"]); // array elements
        assert_eq!(run("length", &[r#"{"a":1,"b":2}"#]), vec!["2"]); // object keys
        assert_eq!(run("length", &[r#""hello""#]), vec!["5"]); // string chars
        assert_eq!(run("length", &["-7"]), vec!["7"]); // |number|
        assert_eq!(run("length", &["null"]), vec!["0"]);
    }

    #[test]
    fn unsupported_errors_cleanly() {
        assert!(translate(".a.b as $x").is_err());
        assert!(translate(".[1:x]").is_err()); // bad slice bound
        assert!(translate(".foo // 0").is_err()); // alternative
        assert!(translate(".foo?").is_err()); // optional
        assert!(translate("reduce .[] as $x (0; . + $x)").is_err());
        assert!(translate(r#"select(.status == "ok")"#).is_err()); // string compare
        assert!(translate("select(.a.b > 1)").is_err()); // nested in expr
    }
}