kaish-kernel 0.7.0

Core kernel for kaish: lexer, parser, interpreter, and runtime
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
//! Spec tests for the newline-split rule in for-loop `$(cmd)` position.
//!
//! These tests describe the *intended* behavior outlined in
//! `docs/plan-for-loop-newline-split.md`. They are staged BEFORE the kernel
//! change lands — most of them should fail today and turn green when the
//! rule ships. Each test is a fact about the spec, not a description of
//! the implementation.
//!
//! The rule (one-line): when a `for` iteration item is `$(cmd)` and the
//! substitution returns `Value::String` containing `\n`, split on `\n`
//! after trimming trailing newlines. Everywhere else strings stay whole.
//!
//! Notes for the test author:
//! - `Kernel::transient()` exercises the full kernel; no special wiring
//!   needed.
//! - Builtins like `printf`, `cat`, `seq`, `echo` are sufficient for
//!   stdin/stdout fixtures; we don't need a portable external command.
//! - Tempfiles use `tempfile::NamedTempFile` per the established pattern
//!   in `shell_bugs_tests.rs`. No hardcoded system paths.

use kaish_kernel::Kernel;
use std::io::Write;

// ---------------------------------------------------------------------------
// Splits per line: the muscle-memory case the rule is built for.
// ---------------------------------------------------------------------------

#[tokio::test]
async fn for_subst_printf_multiline_iterates_per_line() {
    let kernel = Kernel::transient().unwrap();
    let result = kernel
        .execute(
            r#"
            N=0
            for line in $(printf 'a\nb\nc\n'); do
                N=$((N + 1))
                echo "got=$line"
            done
            echo "count=$N"
            "#,
        )
        .await
        .unwrap();
    assert!(result.ok(), "script should succeed: err={}", result.err);
    let text = result.text_out();
    assert!(text.contains("got=a"), "missing 'got=a' in:\n{text}");
    assert!(text.contains("got=b"), "missing 'got=b' in:\n{text}");
    assert!(text.contains("got=c"), "missing 'got=c' in:\n{text}");
    assert!(text.contains("count=3"), "expected 3 iterations:\n{text}");
}

#[tokio::test]
async fn for_subst_cat_file_iterates_per_line() {
    let kernel = Kernel::transient().unwrap();

    let mut tmp = tempfile::NamedTempFile::new().unwrap();
    writeln!(tmp, "alpha").unwrap();
    writeln!(tmp, "beta").unwrap();
    writeln!(tmp, "gamma").unwrap();
    tmp.flush().unwrap();
    let path = tmp.path().display();

    let script = format!(
        r#"
        N=0
        for word in $(cat {path}); do
            N=$((N + 1))
            echo "w=$word"
        done
        echo "count=$N"
        "#
    );
    let result = kernel.execute(&script).await.unwrap();
    assert!(result.ok(), "script should succeed: err={}", result.err);
    let text = result.text_out();
    assert!(text.contains("w=alpha"), "missing 'w=alpha':\n{text}");
    assert!(text.contains("w=beta"), "missing 'w=beta':\n{text}");
    assert!(text.contains("w=gamma"), "missing 'w=gamma':\n{text}");
    assert!(text.contains("count=3"), "expected 3 iterations:\n{text}");
}

// ---------------------------------------------------------------------------
// Whitespace within a line is NEVER split — the "$VAR with spaces just
// works" promise is preserved.
// ---------------------------------------------------------------------------

#[tokio::test]
async fn for_subst_echo_with_spaces_iterates_once() {
    let kernel = Kernel::transient().unwrap();
    let result = kernel
        .execute(
            r#"
            N=0
            for x in $(echo "a b c"); do
                N=$((N + 1))
                echo "got=[$x]"
            done
            echo "count=$N"
            "#,
        )
        .await
        .unwrap();
    assert!(result.ok(), "script should succeed: err={}", result.err);
    let text = result.text_out();
    assert!(text.contains("got=[a b c]"), "should preserve whole string:\n{text}");
    assert!(text.contains("count=1"), "expected 1 iteration, got:\n{text}");
}

#[tokio::test]
async fn for_subst_single_line_no_newline_iterates_once() {
    let kernel = Kernel::transient().unwrap();
    let result = kernel
        .execute(
            r#"
            N=0
            for x in $(printf 'lonely'); do
                N=$((N + 1))
                echo "got=[$x]"
            done
            echo "count=$N"
            "#,
        )
        .await
        .unwrap();
    assert!(result.ok(), "script should succeed: err={}", result.err);
    let text = result.text_out();
    assert!(text.contains("got=[lonely]"), "missing 'got=[lonely]':\n{text}");
    assert!(text.contains("count=1"), "expected 1 iteration:\n{text}");
}

// ---------------------------------------------------------------------------
// Trailing-newline handling.
// ---------------------------------------------------------------------------

#[tokio::test]
async fn for_subst_trailing_newline_does_not_create_phantom_item() {
    // printf 'a\nb\n' must yield exactly 2 iterations, not 3.
    let kernel = Kernel::transient().unwrap();
    let result = kernel
        .execute(
            r#"
            N=0
            for x in $(printf 'a\nb\n'); do
                N=$((N + 1))
                echo "got=[$x]"
            done
            echo "count=$N"
            "#,
        )
        .await
        .unwrap();
    assert!(result.ok(), "script should succeed: err={}", result.err);
    let text = result.text_out();
    assert!(text.contains("got=[a]"), "missing 'got=[a]':\n{text}");
    assert!(text.contains("got=[b]"), "missing 'got=[b]':\n{text}");
    assert!(text.contains("count=2"), "expected 2 iterations, got:\n{text}");
    assert!(!text.contains("got=[]"), "should not have a phantom empty item:\n{text}");
}

#[tokio::test]
async fn for_subst_interior_empty_line_preserved() {
    // printf 'a\n\nb\n' must yield ["a", "", "b"] — only trailing newlines
    // are trimmed; interior empty lines stay.
    let kernel = Kernel::transient().unwrap();
    let result = kernel
        .execute(
            r#"
            N=0
            for x in $(printf 'a\n\nb\n'); do
                N=$((N + 1))
                echo "got=[$x]"
            done
            echo "count=$N"
            "#,
        )
        .await
        .unwrap();
    assert!(result.ok(), "script should succeed: err={}", result.err);
    let text = result.text_out();
    assert!(text.contains("got=[a]"), "missing 'got=[a]':\n{text}");
    assert!(text.contains("got=[]"), "missing empty-line iteration:\n{text}");
    assert!(text.contains("got=[b]"), "missing 'got=[b]':\n{text}");
    assert!(text.contains("count=3"), "expected 3 iterations:\n{text}");
}

#[tokio::test]
async fn for_subst_empty_stdout_zero_iterations() {
    let kernel = Kernel::transient().unwrap();
    let result = kernel
        .execute(
            r#"
            N=0
            for x in $(printf ''); do
                N=$((N + 1))
                echo "should-not-print"
            done
            echo "count=$N"
            "#,
        )
        .await
        .unwrap();
    assert!(result.ok(), "script should succeed: err={}", result.err);
    let text = result.text_out();
    assert!(text.contains("count=0"), "expected 0 iterations:\n{text}");
    assert!(!text.contains("should-not-print"), "body should not run:\n{text}");
}

// ---------------------------------------------------------------------------
// `.data` precedence: structured-array iteration is untouched.
// ---------------------------------------------------------------------------

#[tokio::test]
async fn for_subst_seq_still_uses_data_array() {
    let kernel = Kernel::transient().unwrap();
    let result = kernel
        .execute(
            r#"
            N=0
            for i in $(seq 1 3); do
                N=$((N + 1))
                echo "i=$i"
            done
            echo "count=$N"
            "#,
        )
        .await
        .unwrap();
    assert!(result.ok(), "script should succeed: err={}", result.err);
    let text = result.text_out();
    assert!(text.contains("i=1"), "missing i=1:\n{text}");
    assert!(text.contains("i=2"), "missing i=2:\n{text}");
    assert!(text.contains("i=3"), "missing i=3:\n{text}");
    assert!(text.contains("count=3"), "expected 3 iterations:\n{text}");
}

#[tokio::test]
async fn for_subst_jq_extract_still_uses_data_array() {
    // jq emits .data; structured iteration should win over newline split.
    let kernel = Kernel::transient().unwrap();
    let result = kernel
        .execute(
            r#"
            N=0
            for name in $(echo '["alice","bob","carol"]' | jq -r '.[]'); do
                N=$((N + 1))
                echo "hello-$name"
            done
            echo "count=$N"
            "#,
        )
        .await
        .unwrap();
    assert!(result.ok(), "script should succeed: err={}", result.err);
    let text = result.text_out();
    assert!(text.contains("hello-alice"), "missing alice:\n{text}");
    assert!(text.contains("hello-bob"), "missing bob:\n{text}");
    assert!(text.contains("hello-carol"), "missing carol:\n{text}");
    assert!(text.contains("count=3"), "expected 3 iterations:\n{text}");
}

// ---------------------------------------------------------------------------
// Quoting suppresses the new behavior — same as bash's IFS= discipline.
// ---------------------------------------------------------------------------

#[tokio::test]
async fn for_subst_quoted_iterates_once_with_embedded_newlines() {
    let kernel = Kernel::transient().unwrap();
    let result = kernel
        .execute(
            r#"
            N=0
            for x in "$(printf 'a\nb\nc')"; do
                N=$((N + 1))
            done
            echo "count=$N"
            "#,
        )
        .await
        .unwrap();
    assert!(result.ok(), "script should succeed: err={}", result.err);
    let text = result.text_out();
    assert!(text.contains("count=1"), "quoted subst should iterate once:\n{text}");
}

// ---------------------------------------------------------------------------
// Newline-split is for-iteration-position only — assignment, argv, and
// string interpolation keep the whole string.
// ---------------------------------------------------------------------------

#[tokio::test]
async fn assignment_does_not_split_multiline_subst() {
    let kernel = Kernel::transient().unwrap();
    let result = kernel
        .execute(
            r#"
            R=$(printf 'a\nb\nc')
            echo "len=${#R}"
            echo "value=[$R]"
            "#,
        )
        .await
        .unwrap();
    assert!(result.ok(), "script should succeed: err={}", result.err);
    let text = result.text_out();
    // "a\nb\nc" is 5 chars (a, \n, b, \n, c). If anyone broke
    // assignment by accidentally splitting, the length would change.
    assert!(text.contains("len=5"), "assignment should preserve full string:\n{text}");
    // The literal newlines should survive in the captured variable.
    assert!(text.contains("value=[a\nb\nc]"), "newlines should be preserved:\n{text}");
}

#[tokio::test]
async fn string_interpolation_does_not_split_multiline_subst() {
    let kernel = Kernel::transient().unwrap();
    let result = kernel
        .execute(
            r#"
            echo "before|$(printf 'a\nb')|after"
            "#,
        )
        .await
        .unwrap();
    assert!(result.ok(), "script should succeed: err={}", result.err);
    let text = result.text_out();
    // The substituted multi-line value sits inside a single string;
    // the result should still be one logical echo with embedded newline.
    assert!(text.contains("before|a\nb|after"), "interpolation should preserve newlines:\n{text}");
}

#[tokio::test]
async fn argv_does_not_split_multiline_subst() {
    // `echo $(printf 'a\nb')` — kaish treats $() in argv position as one
    // Value, so echo sees a single argument containing the embedded newline.
    let kernel = Kernel::transient().unwrap();
    let result = kernel
        .execute(
            r#"
            echo "[" $(printf 'a\nb') "]"
            "#,
        )
        .await
        .unwrap();
    assert!(result.ok(), "script should succeed: err={}", result.err);
    let text = result.text_out();
    // The exact rendering of `echo` with an embedded newline is
    // intentionally not over-specified — what matters is that echo
    // received the multi-line blob, not two separate args.
    assert!(text.contains("a\nb"), "argv should pass multi-line string:\n{text}");
}

// ---------------------------------------------------------------------------
// CRLF handling: per-line iteration trims trailing \r so Windows-origin
// files don't leak carriage returns.
// ---------------------------------------------------------------------------

#[tokio::test]
async fn for_subst_crlf_trims_carriage_returns() {
    let kernel = Kernel::transient().unwrap();
    let result = kernel
        .execute(
            r#"
            N=0
            for x in $(printf 'a\r\nb\r\nc\r\n'); do
                N=$((N + 1))
                echo "len=${#x}"
                echo "got=[$x]"
            done
            echo "count=$N"
            "#,
        )
        .await
        .unwrap();
    assert!(result.ok(), "script should succeed: err={}", result.err);
    let text = result.text_out();
    assert!(text.contains("count=3"), "expected 3 iterations:\n{text}");
    // Each line is one char ('a', 'b', 'c') — if \r leaked in, length
    // would be 2 instead of 1.
    assert!(text.contains("len=1"), "each line should be 1 char (no \\r):\n{text}");
    assert!(!text.contains("len=2"), "stray \\r leaked into a line:\n{text}");
}

// ---------------------------------------------------------------------------
// Regression guards: things the rule must NOT change.
// ---------------------------------------------------------------------------

#[tokio::test]
async fn regression_for_bare_var_still_validator_error() {
    // E012 should remain a hard error — the bareword scalar case has no
    // \n-list-stdout signal to lean on. This guards the validator path.
    let kernel = Kernel::transient().unwrap();
    let result = kernel
        .execute(
            r#"
            ITEMS="a b c"
            for i in $ITEMS; do echo $i; done
            "#,
        )
        .await;
    assert!(result.is_err(), "bare $VAR in for should still error");
    let err = result.unwrap_err().to_string();
    assert!(
        err.contains("word splitting") || err.contains("iterate once") || err.contains("E012"),
        "error should still mention E012/word splitting: {err}"
    );
}

#[tokio::test]
async fn regression_while_condition_unchanged() {
    // `while` has no iteration list; the change must not touch it.
    let kernel = Kernel::transient().unwrap();
    let result = kernel
        .execute(
            r#"
            N=0
            while [[ $N -lt 3 ]]; do
                N=$((N + 1))
                echo "n=$N"
            done
            "#,
        )
        .await
        .unwrap();
    assert!(result.ok(), "while loop should run: err={}", result.err);
    let text = result.text_out();
    assert!(text.contains("n=1"), "missing n=1:\n{text}");
    assert!(text.contains("n=2"), "missing n=2:\n{text}");
    assert!(text.contains("n=3"), "missing n=3:\n{text}");
}

#[tokio::test]
async fn regression_explicit_split_still_works() {
    // Users who already wrote `for x in $(split "$VAR")` should not see
    // a change in semantics or count.
    let kernel = Kernel::transient().unwrap();
    let result = kernel
        .execute(
            r#"
            N=0
            for x in $(split "alpha beta gamma"); do
                N=$((N + 1))
                echo "x=$x"
            done
            echo "count=$N"
            "#,
        )
        .await
        .unwrap();
    assert!(result.ok(), "script should succeed: err={}", result.err);
    let text = result.text_out();
    assert!(text.contains("x=alpha"), "missing alpha:\n{text}");
    assert!(text.contains("x=beta"), "missing beta:\n{text}");
    assert!(text.contains("x=gamma"), "missing gamma:\n{text}");
    assert!(text.contains("count=3"), "split should still produce 3:\n{text}");
}