quiltlang 0.6.0

Quilt, a polyglot metaprogramming language: source code with arrow-bracket syntax for embedding and manipulating code fragments of other languages at code-generation time.
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
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
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
//! Integration tests for the `quilt` binary (issue #160).
//!
//! The CLI had essentially no coverage: `expand` / `check` / `run`, `-m`,
//! language-chain derivation from the file stem, shebang handling, exit codes
//! and the generated-file header were all untested — and **#136 lived exactly
//! there** (a Rust `//!` comment on every generated file, whatever the
//! language).
//!
//! These drive the real binary through `CARGO_BIN_EXE_quilt` rather than
//! calling into the library, because the things worth testing here are the
//! parts only the binary does: argument handling, what lands on stdout versus
//! stderr, and what the process exits with.

use std::path::{Path, PathBuf};
use std::process::{Command, Output};

fn quilt() -> Command {
    let mut c = Command::new(env!("CARGO_BIN_EXE_quilt"));
    // The dev shell exports `RUST_LOG=info` (see .envrc), which puts tracing's
    // `running: …` line on the CLI's stdout. Assertions about what a command
    // printed should not depend on the developer's environment.
    c.env_remove("RUST_LOG");
    c
}

/// A scratch directory that cleans itself up.
struct Dir(PathBuf);

impl Dir {
    fn new(tag: &str) -> Self {
        let p = std::env::temp_dir().join(format!(
            "quilt-cli-{tag}-{}-{:?}",
            std::process::id(),
            std::thread::current().id()
        ));
        let _ = std::fs::remove_dir_all(&p);
        std::fs::create_dir_all(&p).expect("scratch dir");
        Dir(p)
    }

    fn write(&self, name: &str, body: &str) -> PathBuf {
        let p = self.0.join(name);
        if let Some(parent) = p.parent() {
            std::fs::create_dir_all(parent).expect("parent dir");
        }
        std::fs::write(&p, body).expect("write fixture");
        p
    }
}

impl Drop for Dir {
    fn drop(&mut self) {
        let _ = std::fs::remove_dir_all(&self.0);
    }
}

fn run(args: &[&Path]) -> Output {
    quilt().args(args).output().expect("quilt runs")
}

fn stderr(o: &Output) -> String {
    String::from_utf8_lossy(&o.stderr).into_owned()
}

fn stdout(o: &Output) -> String {
    String::from_utf8_lossy(&o.stdout).into_owned()
}

/* ── check: exit codes ─────────────────────────────────────────────────── */

#[test]
fn check_valid_file_succeeds() {
    let d = Dir::new("ok");
    let f = d.write("ok.rs.quilt", "let x = ↖1 + 2↗;\n");
    let o = run(&[Path::new("check"), &f]);
    assert!(
        o.status.success(),
        "expected success, stderr:\n{}",
        stderr(&o)
    );
    assert!(stdout(&o).contains(": ok"), "stdout: {}", stdout(&o));
}

#[test]
fn check_invalid_file_exits_nonzero() {
    let d = Dir::new("bad");
    let f = d.write("bad.rs.quilt", "let x = ↙1 + 2↘;\n");
    let o = run(&[Path::new("check"), &f]);
    assert_eq!(o.status.code(), Some(1), "stderr:\n{}", stderr(&o));
}

#[test]
fn check_missing_file_exits_nonzero() {
    let d = Dir::new("missing");
    let f = d.0.join("nope.rs.quilt");
    let o = run(&[Path::new("check"), &f]);
    assert_eq!(o.status.code(), Some(1));
}

/// One broken file must not hide the rest: every file is checked, and the
/// summary counts them.
#[test]
fn check_reports_every_file_before_failing() {
    let d = Dir::new("multi");
    let ok = d.write("ok.rs.quilt", "let x = ↖1 + 2↗;\n");
    let bad = d.write("bad.rs.quilt", "let x = ↙1 + 2↘;\n");
    let o = run(&[Path::new("check"), &ok, &bad]);
    assert_eq!(o.status.code(), Some(1));
    assert!(
        stdout(&o).contains(": ok"),
        "the good file should still report ok"
    );
    assert!(
        stderr(&o).contains("1 of 2 file(s) failed"),
        "summary should count both files, got:\n{}",
        stderr(&o)
    );
}

/* ── check: diagnostics ────────────────────────────────────────────────── */

/// `check` is the CI and pre-commit path, so its diagnostics are the ones a
/// contributor actually reads. They used to be bare byte offsets
/// ("source bytes 8..19") while `expand` rendered a caret under the source.
#[test]
fn check_renders_a_source_snippet() {
    let d = Dir::new("snippet");
    let f = d.write("bad.rs.quilt", "let x = ↙1 + 2↘;\n");
    let e = stderr(&run(&[Path::new("check"), &f]));
    assert!(e.contains("unquote depth too high"), "{e}");
    assert!(
        e.contains("let x = ↙1 + 2↘;"),
        "the offending line should be shown, got:\n{e}"
    );
    assert!(e.contains(":1:9"), "expected a line:col, got:\n{e}");
}

/// A stripped shebang must not shift the line numbers of everything after it.
#[test]
fn check_shebang_does_not_shift_line_numbers() {
    let d = Dir::new("shebang");
    let f = d.write("sheb.rs.quilt", "#!/usr/bin/env quilt\nlet x = ↙1 + 2↘;\n");
    let e = stderr(&run(&[Path::new("check"), &f]));
    assert!(
        e.contains(":2:9"),
        "the error is on line 2 of the file; got:\n{e}"
    );
}

#[test]
fn check_accepts_a_valid_shebang_script() {
    let d = Dir::new("shebang-ok");
    let f = d.write("ok.rs.quilt", "#!/usr/bin/env quilt\nlet x = ↖1 + 2↗;\n");
    let o = run(&[Path::new("check"), &f]);
    assert!(o.status.success(), "stderr:\n{}", stderr(&o));
}

/// The other half of `run_resolves_a_symlinked_entry_point` (issue #188).
/// `check` used to require a literal `.quilt` suffix on the path it was handed,
/// so an extension-less entry point — `bin/issues` is a symlink to
/// `examples/issue_triage.html.py.quilt` — could be *run* and never validated
/// in CI. Both subcommands now derive the chain the same way, through
/// `resolve_stem`.
///
/// Python content is what proves the chain came from the resolved *target*:
/// under the link's own name there is no language at all, and under a Rust
/// default `x = ↖1 + 2↗` is a parse error. The dotted parent directory is the
/// second half of the rule — only the file *name* counts.
#[cfg(unix)]
#[test]
fn check_accepts_a_symlinked_extensionless_script() {
    let d = Dir::new("check-symlink");
    let target = d.write(
        "some.dir.v2/tool.py.quilt",
        "#!/usr/bin/env quilt\nx = ↖1 + 2↗\n",
    );
    let link = d.0.join("issues");
    std::os::unix::fs::symlink(&target, &link).expect("symlink");
    let o = run(&[Path::new("check"), &link]);
    assert!(o.status.success(), "stderr:\n{}", stderr(&o));
    assert!(stdout(&o).contains(": ok"), "stdout: {}", stdout(&o));
}

/// The suffix is no longer the gate, but the *name* still has to resolve to a
/// registered language. A genuinely extension-less regular file has no chain to
/// derive, so it still fails — just later, and naming the language it could not
/// find rather than the suffix it did not have.
#[test]
fn check_rejects_a_name_that_resolves_to_no_language() {
    let d = Dir::new("nolang");
    let f = d.write("issues", "#!/usr/bin/env quilt\nlet x = ↖1 + 2↗;\n");
    let o = run(&[Path::new("check"), &f]);
    assert_eq!(o.status.code(), Some(1));
    let e = stderr(&o);
    assert!(
        e.contains("\"issues\"") && e.contains("can't be used as"),
        "the error should name the language it looked for, got:\n{e}"
    );
}

/// Resolution is now how `check` finds the file at all, so a dangling symlink
/// has to come out as a diagnostic like any other unreadable path.
#[cfg(unix)]
#[test]
fn check_reports_a_dangling_symlink() {
    let d = Dir::new("dangling");
    let link = d.0.join("gone");
    std::os::unix::fs::symlink(d.0.join("nowhere.rs.quilt"), &link).expect("symlink");
    let o = run(&[Path::new("check"), &link]);
    assert_eq!(o.status.code(), Some(1), "stderr:\n{}", stderr(&o));
    assert!(
        stderr(&o).contains("1 of 1 file(s) failed"),
        "stderr:\n{}",
        stderr(&o)
    );
}

/* ── expand ────────────────────────────────────────────────────────────── */

#[test]
fn expand_writes_the_sibling_file() {
    let d = Dir::new("expand");
    let f = d.write("e.rs.quilt", "let x = ↖1 + 2↗;\n");
    let o = run(&[Path::new("expand"), &f]);
    assert!(o.status.success(), "stderr:\n{}", stderr(&o));
    let out = d.0.join("e.rs");
    assert!(out.exists(), "expand should write {}", out.display());
    let body = std::fs::read_to_string(&out).unwrap();
    assert!(body.contains("tb(\"binary_expression\")"), "body:\n{body}");
}

/// The `DO NOT EDIT` header has to be a comment *in the language generated* —
/// issue #136, where every language got Rust's `//!`.
#[test]
fn expand_header_comment_matches_the_language() {
    for (name, src, prefix) in [
        ("h.rs.quilt", "let x = ↖1 + 2↗;\n", "//!"),
        ("h.py.quilt", "x = ↖1 + 2↗\n", "#"),
        ("h.nix.quilt", "nix↖1↗\n", "#"),
        ("h.ts.quilt", "let x = ↖1 + 2↗;\n", "//"),
    ] {
        let d = Dir::new(&format!("hdr-{}", name.replace('.', "-")));
        let f = d.write(name, src);
        let o = run(&[Path::new("expand"), &f]);
        assert!(o.status.success(), "{name}: stderr:\n{}", stderr(&o));
        let out = d.0.join(name.strip_suffix(".quilt").unwrap());
        let body = std::fs::read_to_string(&out).unwrap();
        let first = body.lines().next().unwrap_or_default();
        assert!(
            first.starts_with(&format!("{prefix} DO NOT EDIT")),
            "{name}: header should start with {prefix:?}, got {first:?}"
        );
    }
}

/// The header records the command, but not the path the file happened to be
/// named by: expanding the same source by a relative path, from its own
/// directory, and by an absolute one gives the same file, byte for byte. The
/// path used to be echoed as passed, so the output depended on the working
/// directory.
#[test]
fn expand_output_does_not_depend_on_the_path_given() {
    let d = Dir::new("hdr-path");
    let f = d.write("sub/p.rs.quilt", "let x = ↖1 + 2↗;\n");
    let out = d.0.join("sub/p.rs");
    let mut seen = Vec::new();
    for (cwd, arg) in [
        (d.0.clone(), PathBuf::from("sub/p.rs.quilt")),
        (d.0.join("sub"), PathBuf::from("p.rs.quilt")),
        (std::env::temp_dir(), f.clone()),
    ] {
        let o = quilt()
            .current_dir(&cwd)
            .args([Path::new("expand"), &arg])
            .output()
            .expect("quilt runs");
        assert!(
            o.status.success(),
            "{}: stderr:\n{}",
            arg.display(),
            stderr(&o)
        );
        seen.push(std::fs::read_to_string(&out).unwrap());
    }
    let first = seen[0].lines().next().unwrap_or_default();
    assert_eq!(
        first, "//! DO NOT EDIT. GENERATED BY `quilt expand p.rs.quilt`.",
        "the header should name the file, not the path"
    );
    assert!(
        seen.iter().all(|s| *s == seen[0]),
        "outputs differ:\n{seen:#?}"
    );
}

/// A dot in a parent directory is not an extension: the chain is read off the
/// file name only, as `check` and `run` already read it.
#[test]
fn expand_reads_the_chain_off_the_file_name_only() {
    let d = Dir::new("dotted-dir");
    let f = d.write("v1.rs/n.quilt", "x\n");
    let o = run(&[Path::new("expand"), &f]);
    assert!(!o.status.success(), "a file naming no language should fail");
    let err = stderr(&o);
    assert!(
        !err.contains("rs/n"),
        "a directory leaked into the chain:\n{err}"
    );
}

/// The file stem is the language chain: `shaders.wgsl.rs.quilt` is Rust on the
/// ground with bare quotes defaulting to WGSL.
#[test]
fn expand_derives_the_language_chain_from_the_stem() {
    let d = Dir::new("chain");
    let f = d.write("s.wgsl.rs.quilt", "let shader = ↖1u↗;\n");
    let o = run(&[Path::new("expand"), &f]);
    assert!(o.status.success(), "stderr:\n{}", stderr(&o));
    let body = std::fs::read_to_string(d.0.join("s.wgsl.rs")).unwrap();
    assert!(
        body.contains("int_literal"),
        "the bare quote should have parsed as WGSL, got:\n{body}"
    );
}

/// `expand` writes the input name with `.quilt` sliced off, so — unlike
/// `check`, which only ever discards its result — it is right to insist on the
/// suffix: there is no output name without one. It used to `unwrap()` that
/// slice, so `quilt expand bin/issues` was a panic rather than a diagnostic
/// (issue #188). A Rust panic exits 101, so the exit code alone pins this.
#[test]
fn expand_rejects_a_file_without_the_quilt_suffix() {
    let d = Dir::new("expand-nosuffix");
    let f = d.write("issues", "#!/usr/bin/env quilt\nlet x = ↖1 + 2↗;\n");
    let o = run(&[Path::new("expand"), &f]);
    assert_eq!(o.status.code(), Some(1), "stderr:\n{}", stderr(&o));
    let e = stderr(&o);
    assert!(e.contains("expected a .quilt file"), "stderr:\n{e}");
}

#[test]
fn expand_reports_errors_with_a_snippet() {
    let d = Dir::new("expand-bad");
    let f = d.write("bad.rs.quilt", "let x = ↙1 + 2↘;\n");
    let o = run(&[Path::new("expand"), &f]);
    assert!(!o.status.success());
    let e = stderr(&o);
    assert!(e.contains("let x = ↙1 + 2↘;"), "stderr:\n{e}");
}

/* ── expand: the injected runtime import (issue #274) ──────────────────── */

/// Expanded code *calls a runtime* — `tb(..)`, `qlift(..)`, `name(..)` — and
/// until #274 every author typed the import that brought those names into
/// scope. Each host now supplies it, so the source does not have to.
#[test]
fn expand_injects_the_hosts_runtime_import() {
    for (name, src, want) in [
        ("i.rs.quilt", "let x = ↖1 + 2↗;\n", "use quilt::prelude::*;"),
        ("i.py.quilt", "x = ↖1 + 2↗\n", "from quilt import *"),
        (
            "i.ts.quilt",
            "const x = ↖1 + 2↗;\n",
            "import { tb, leaf, sym, quote, unquote, cmd, write, push, name, qseq, qlift_str, qlift, NL, POP, \
             HOLE } from \"quilt\";",
        ),
    ] {
        let d = Dir::new(&format!("prelude-{}", name.replace('.', "-")));
        let f = d.write(name, src);
        let o = run(&[Path::new("expand"), &f]);
        assert!(o.status.success(), "{name}: stderr:\n{}", stderr(&o));
        let body = std::fs::read_to_string(d.0.join(name.strip_suffix(".quilt").unwrap())).unwrap();
        // Directly after the `DO NOT EDIT` header: nothing in the generated
        // file can precede the names it uses.
        let second = body.lines().nth(2).unwrap_or_default();
        assert_eq!(second, want, "{name}: body:\n{body}");
    }
}

/// A file that uses no construct expands to itself, so it must not be handed an
/// import it does not use. Rust tolerates an unused glob silently; a Python or
/// TypeScript linter does not.
#[test]
fn expand_leaves_a_construct_free_file_import_free() {
    let d = Dir::new("prelude-none");
    let f = d.write("plain.rs.quilt", "fn main() {\n    println!(\"hi\");\n}\n");
    let o = run(&[Path::new("expand"), &f]);
    assert!(o.status.success(), "stderr:\n{}", stderr(&o));
    let body = std::fs::read_to_string(d.0.join("plain.rs")).unwrap();
    assert!(!body.contains("use quilt::prelude"), "body:\n{body}");
    // A Quilt *comment* is not a construct either: it is deleted, not
    // translated into a runtime call.
    let f = d.write("cmt.rs.quilt", "⟨//⟩ note\nfn main() {}\n");
    assert!(run(&[Path::new("expand"), &f]).status.success());
    let body = std::fs::read_to_string(d.0.join("cmt.rs")).unwrap();
    assert!(!body.contains("use quilt::prelude"), "body:\n{body}");
}

/// Never twice. The import is skipped when the source already brings the
/// runtime in — two globs are harmless in Rust and Python, but a doubled
/// *named* import is a hard `Duplicate identifier` error in TypeScript, so the
/// rule has to hold for the host where it is not merely tidiness.
#[test]
fn expand_does_not_double_a_hand_written_import() {
    for (name, src, needle) in [
        (
            "d.rs.quilt",
            "use quilt::prelude::*;\nlet x = ↖1↗;\n",
            "quilt::prelude",
        ),
        (
            "d.py.quilt",
            "from quilt import *\nx = ↖1↗\n",
            "from quilt import",
        ),
        (
            "d.ts.quilt",
            "import { tb, leaf, qlift } from \"quilt\";\nconst x = ↖1↗;\n",
            "from \"quilt\"",
        ),
    ] {
        let d = Dir::new(&format!("dedupe-{}", name.replace('.', "-")));
        let f = d.write(name, src);
        let o = run(&[Path::new("expand"), &f]);
        assert!(o.status.success(), "{name}: stderr:\n{}", stderr(&o));
        let body = std::fs::read_to_string(d.0.join(name.strip_suffix(".quilt").unwrap())).unwrap();
        assert_eq!(
            body.matches(needle).count(),
            1,
            "{name}: the import should appear once, body:\n{body}"
        );
    }
}

/// TypeScript has no glob import, so its list names every runtime function the
/// expansion calls — and the lift spelling is target-directed, so *which*
/// languages the file quotes decides what is in it. This is the boilerplate a
/// human gets wrong: the list has to grow the day the file starts quoting HTML.
#[test]
fn expand_typescript_import_follows_the_quoted_targets() {
    let d = Dir::new("prelude-ts-targets");

    // Plain `.ts`: only the homogeneous `qlift`.
    let f = d.write("a.ts.quilt", "const x = ↖1 + 2↗;\n");
    assert!(run(&[Path::new("expand"), &f]).status.success());
    let body = std::fs::read_to_string(d.0.join("a.ts")).unwrap();
    assert!(body.contains(" qlift,"), "body:\n{body}");
    assert!(!body.contains("qlift_html"), "body:\n{body}");

    // The chain says HTML, so `qlift_html` — the spelling `↑` expands to
    // there — comes along.
    let f = d.write("b.html.ts.quilt", "const x = ↖<p>↙↑(\"hi\")↘</p>↗;\n");
    assert!(run(&[Path::new("expand"), &f]).status.success());
    let body = std::fs::read_to_string(d.0.join("b.html.ts")).unwrap();
    assert!(body.contains("qlift_html"), "body:\n{body}");

    // …and so does an *annotated* quote, which the chain never mentions.
    let f = d.write("c.ts.quilt", "const x = html↖<p>↙↑(\"hi\")↘</p>↗;\n");
    assert!(run(&[Path::new("expand"), &f]).status.success());
    let body = std::fs::read_to_string(d.0.join("c.ts")).unwrap();
    assert!(body.contains("qlift_html"), "body:\n{body}");
}

/// The escape hatch. The import path is not universal — code generated inside
/// the quilt repo wants `use crate::prelude::*`, and a runtime re-expanding a
/// generated stage wants nothing at all.
#[test]
fn expand_prelude_flags_override_the_host() {
    let d = Dir::new("prelude-flags");
    let f = d.write("o.rs.quilt", "let x = ↖1↗;\n");

    let o = quilt()
        .args(["expand", "--no-prelude"])
        .arg(&f)
        .output()
        .unwrap();
    assert!(o.status.success(), "stderr:\n{}", stderr(&o));
    let body = std::fs::read_to_string(d.0.join("o.rs")).unwrap();
    assert!(!body.contains("use quilt::prelude"), "body:\n{body}");

    let o = quilt()
        .args(["expand", "--prelude", "use crate::prelude::*;"])
        .arg(&f)
        .output()
        .unwrap();
    assert!(o.status.success(), "stderr:\n{}", stderr(&o));
    let body = std::fs::read_to_string(d.0.join("o.rs")).unwrap();
    assert!(body.contains("use crate::prelude::*;"), "body:\n{body}");
    assert!(!body.contains("use quilt::prelude"), "body:\n{body}");

    // They are alternatives, not a pair.
    let o = quilt()
        .args(["expand", "--no-prelude", "--prelude", "x"])
        .arg(&f)
        .output()
        .unwrap();
    assert_eq!(o.status.code(), Some(2), "stderr:\n{}", stderr(&o));
}

/* ── expand: the script's shebang ──────────────────────────────────────── */

/// A `#!` line in a `.quilt` file says how to run *that file* — it is what
/// makes `./examples/countdown.rs.quilt` and `bin/issues` work — and it says
/// nothing about the artifact. `run` strips it before expanding and `check`
/// blanks it; `expand` used to copy it through, where the `DO NOT EDIT` header
/// had already taken line 1, so it was not a shebang at all. In Rust it was
/// worse than noise: `#!` there is inner-attribute syntax, so every generated
/// file that came from an executable script failed to parse (`error[E0753]`).
#[test]
fn expand_drops_the_scripts_shebang() {
    for (name, src) in [
        (
            "s.rs.quilt",
            "#!/usr/bin/env quilt\n\n//! A doc header, which is an *inner* comment.\n\
             fn main() { let _x = ↖1↗; }\n",
        ),
        ("s.py.quilt", "#!/usr/bin/env quilt\nx = ↖1↗\n"),
        ("s.ts.quilt", "#!/usr/bin/env quilt\nconst x = ↖1↗;\n"),
    ] {
        let d = Dir::new(&format!("shebang-{}", name.replace('.', "-")));
        let f = d.write(name, src);
        let o = run(&[Path::new("expand"), &f]);
        assert!(o.status.success(), "{name}: stderr:\n{}", stderr(&o));
        let body = std::fs::read_to_string(d.0.join(name.strip_suffix(".quilt").unwrap())).unwrap();
        assert!(!body.contains("#!"), "{name}: body:\n{body}");
    }
}

/// …but an inner attribute is not a shebang. `#!` is one only when the next
/// character is not `[`, exactly the rule rustc reads it by — and dropping an
/// `#![allow(..)]` would change what the generated file means.
#[test]
fn expand_keeps_an_inner_attribute() {
    let d = Dir::new("shebang-attr");
    let f = d.write(
        "a.rs.quilt",
        "#![allow(dead_code)]\nfn main() { let _x = ↖1↗; }\n",
    );
    let o = run(&[Path::new("expand"), &f]);
    assert!(o.status.success(), "stderr:\n{}", stderr(&o));
    let body = std::fs::read_to_string(d.0.join("a.rs")).unwrap();
    assert!(body.contains("#![allow(dead_code)]"), "body:\n{body}");
    // …and the runtime import lands *after* it, since an inner attribute may
    // only appear before items.
    let attr = body.find("#![allow").unwrap();
    let import = body.find("use quilt::prelude::*;").unwrap();
    assert!(attr < import, "body:\n{body}");
}

/* ── -m: choosing the multi ────────────────────────────────────────────── */

/// A file that reaches the two engines' one visible difference: `↑` spells
/// `qlift()` under Omni and `bs_lift()` under Bootstrap. Everything else about
/// the expansion is identical, which is the point — `expand_rust.rs` asserts
/// that agreement term by term.
const LIFTING: &str = "let n = 3;\nlet e = ↖↙n.↑↘ + 1↗;\n";

/// `-m bootstrap` picks a different *engine*, not a flag on the same one: the
/// `BootstrapMetaLanguage` that `bin/bootstrap0` expands `mk_meta.rs.quilt`
/// with, back when there is no generated `RustMetaLanguage` to use yet.
#[test]
fn expand_bootstrap_selects_the_other_engine() {
    let d = Dir::new("boot");
    let f = d.write("b.rs.quilt", LIFTING);

    let o = run(&[Path::new("expand"), &f]);
    assert!(o.status.success(), "stderr:\n{}", stderr(&o));
    let omni = std::fs::read_to_string(d.0.join("b.rs")).unwrap();
    assert!(omni.contains("n.qlift()"), "omni output:\n{omni}");

    let o = quilt()
        .args(["expand", "-m", "bootstrap"])
        .arg(&f)
        .output()
        .expect("runs");
    assert!(o.status.success(), "stderr:\n{}", stderr(&o));
    let boot = std::fs::read_to_string(d.0.join("b.rs")).unwrap();
    assert!(boot.contains("n.bs_lift()"), "bootstrap output:\n{boot}");

    // The two differ only in that spelling, so the rest of the generated code
    // is the same builder chain.
    assert_eq!(
        omni.replace("n.qlift()", "LIFT"),
        boot.replace("n.bs_lift()", "LIFT")
            // the header records the exact command, `-m bootstrap` included
            .replace("quilt expand -m bootstrap", "quilt expand"),
        "the engines should differ only in the lift spelling"
    );
}

/// The expand cache is keyed by the multi as well as by path and mtime — it has
/// to be, because the same unmodified file expands to different code under the
/// two engines. A key of (path, mtime) alone would serve Omni's output to a
/// `-m bootstrap` run, and the failure would be silent: valid Rust, wrong
/// runtime call, discovered by the bootstrap gate much later.
#[test]
fn expand_cache_is_keyed_by_the_multi() {
    let d = Dir::new("boot-cache");
    let f = d.write("c.rs.quilt", LIFTING);
    // Keep the run hermetic: a private cache dir, so the assertion doesn't
    // depend on (or pollute) the developer's `~/.cache/quilt`.
    let cache = d.0.join("cache");

    for (multi, want) in [("omni", "n.qlift()"), ("bootstrap", "n.bs_lift()")] {
        let o = quilt()
            .args(["expand", "-m", multi])
            .arg(&f)
            .env("XDG_CACHE_HOME", &cache)
            .output()
            .expect("runs");
        assert!(o.status.success(), "{multi}: stderr:\n{}", stderr(&o));
        let body = std::fs::read_to_string(d.0.join("c.rs")).unwrap();
        assert!(
            body.contains(want),
            "-m {multi} on an unmodified file should not reuse the other engine's \
             cached expansion; got:\n{body}"
        );
    }
}

#[test]
fn check_accepts_the_bootstrap_multi() {
    let d = Dir::new("boot-check");
    let ok = d.write("ok.rs.quilt", LIFTING);
    let o = quilt()
        .args(["check", "-m", "bootstrap"])
        .arg(&ok)
        .output()
        .expect("runs");
    assert!(o.status.success(), "stderr:\n{}", stderr(&o));

    let bad = d.write("bad.rs.quilt", "let x = ↙1 + 2↘;\n");
    let o = quilt()
        .args(["check", "-m", "bootstrap"])
        .arg(&bad)
        .output()
        .expect("runs");
    assert_eq!(o.status.code(), Some(1), "stderr:\n{}", stderr(&o));
    assert!(
        stderr(&o).contains("unquote depth too high"),
        "the bootstrap engine should report the same error, got:\n{}",
        stderr(&o)
    );
}

/// Documents a rough edge rather than asserting it is right. The bootstrap
/// multi is a `Single`, and `Singleton::get` ignores the language key it is
/// handed — so `-m bootstrap` parses *every* file as Rust, whatever the stem
/// says. `lang_chain` in `bin.rs` peels extensions with
/// `multi.get_lang(part).is_ok()`, which under Bootstrap succeeds for every
/// extension, so chain derivation is meaningless there too. A `.py.quilt` file
/// therefore fails with a Rust parse error naming Rust node kinds, rather than
/// "the bootstrap multi only has rust".
///
/// It fails, which is the important half — `-m omni` accepts the same file. If
/// `-m bootstrap` ever learns to refuse a non-Rust stem outright, this test is
/// the one to rewrite.
#[test]
fn bootstrap_multi_parses_every_file_as_rust() {
    let d = Dir::new("boot-py");
    let f = d.write("p.py.quilt", "def f():\n    return ↖1 + 2↗\n");

    let o = quilt()
        .args(["check", "-m", "bootstrap"])
        .arg(&f)
        .output()
        .expect("runs");
    assert_eq!(o.status.code(), Some(1), "stdout:\n{}", stdout(&o));
    assert!(
        stderr(&o).contains("Parsed with errors"),
        "expected a Rust parse error, got:\n{}",
        stderr(&o)
    );

    let o = quilt()
        .args(["check", "-m", "omni"])
        .arg(&f)
        .output()
        .expect("runs");
    assert!(
        o.status.success(),
        "omni should read the same file as Python; stderr:\n{}",
        stderr(&o)
    );
}

/// An unknown `-m` value is a clap error (exit 2), not a quilt one — so it is
/// reported before any file is opened, and it lists what is available.
#[test]
fn unknown_multi_is_rejected() {
    let d = Dir::new("multi-bad");
    let f = d.write("m.rs.quilt", "let x = ↖1 + 2↗;\n");
    let o = quilt()
        .args(["check", "-m", "klingon"])
        .arg(&f)
        .output()
        .expect("runs");
    assert_eq!(o.status.code(), Some(2), "stderr:\n{}", stderr(&o));
    let e = stderr(&o);
    assert!(
        e.contains("omni") && e.contains("bootstrap"),
        "stderr:\n{e}"
    );
}

/* ── run: dispatch and the error paths ─────────────────────────────────── */

/// Not every language has an interpreter. Nix and Lean are hosts — a
/// `.nix.quilt` file expands fine — but they are *generators*: the expansion is
/// a Nix program you evaluate, not a script `quilt` can hand to a runner. The
/// refusal has to name the language, because the file expanded successfully and
/// nothing else in the output says why it stopped.
#[test]
fn run_rejects_a_language_with_no_interpreter() {
    let d = Dir::new("run-nix");
    let f = d.write("n.nix.quilt", "let gen = nix↖1↗; in gen\n");
    let o = run(&[Path::new("run"), &f]);
    assert_eq!(o.status.code(), Some(1));
    assert!(
        stderr(&o).contains("language 'nix' is not runnable via 'quilt'"),
        "stderr:\n{}",
        stderr(&o)
    );
}

/// `run` is the *default* subcommand, and that is load-bearing: a
/// `#!/usr/bin/env quilt` shebang invokes `quilt <script> <args>…` with no
/// subcommand at all. If the bare form ever stopped meaning `run`, every
/// shebang script in the repo would break at once.
#[test]
fn run_is_the_default_subcommand() {
    let d = Dir::new("run-default");
    let f = d.write("n.nix.quilt", "let gen = nix↖1↗; in gen\n");
    let bare = run(&[&f]);
    let explicit = run(&[Path::new("run"), &f]);
    assert_eq!(bare.status.code(), explicit.status.code());
    assert_eq!(
        stderr(&bare),
        stderr(&explicit),
        "`quilt <file>` should be `quilt run <file>`"
    );
}

#[test]
fn run_missing_file_exits_nonzero() {
    let d = Dir::new("run-missing");
    let f = d.0.join("nope.rs.quilt");
    let o = run(&[Path::new("run"), &f]);
    assert_eq!(o.status.code(), Some(1));
}

/* ── run: the rust-script backend ──────────────────────────────────────── */

/// The Rust runner end to end — the one backend that needs nothing built first,
/// and so the only `run` test that never skips: shebang stripped, the expanded
/// program handed to `rust-script` with a cargo manifest pointing at *this*
/// quilt crate, and the script's stdout passed through.
///
/// `rust-script` comes from the flake devShell and `quilt/tests/bootstrap.rs`
/// already shells out to it, so this adds a runner rather than a dependency.
#[test]
fn run_rust_script_executes_the_program() {
    let d = Dir::new("run-rs");
    let f = d.write(
        "hello.rs.quilt",
        "#!/usr/bin/env quilt\n\
         use quilt::prelude::*;\n\
         fn main() {\n\
         \x20   let frag = ↖1 + 2↗;\n\
         \x20   println!(\"{}\", frag.coparse());\n\
         }\n",
    );
    let o = run(&[Path::new("run"), &f]);
    assert!(o.status.success(), "stderr:\n{}", stderr(&o));
    assert_eq!(stdout(&o).trim(), "1 + 2");
}

/// The same program with no hand-written import (issue #274). This is the
/// injection that matters most: `run` hands its temp file straight to
/// `rust-script`, so a missing runtime import is a failed run rather than a
/// stale artifact someone notices later.
#[test]
fn run_rust_script_needs_no_hand_written_import() {
    let d = Dir::new("run-rs-prelude");
    let f = d.write(
        "hello.rs.quilt",
        "#!/usr/bin/env quilt\n\
         fn main() {\n\
         \x20   let frag = ↖1 + 2↗;\n\
         \x20   println!(\"{}\", frag.coparse());\n\
         }\n",
    );
    let o = run(&[Path::new("run"), &f]);
    assert!(o.status.success(), "stderr:\n{}", stderr(&o));
    assert_eq!(stdout(&o).trim(), "1 + 2");
}

/* ── run: the shell backends (issue #151) ──────────────────────────────── */

/// The whole point of #151, end to end: bash declared `#!/usr/bin/env bash` and
/// could never reach it, because a language with no `MetaLanguage` can never be
/// the ground language. Now it can, so the shebang resolves to a real
/// interpreter and the expanded script runs.
///
/// A string host needs no per-runner setup at all — no cargo manifest, no
/// `PYTHONPATH`, no `node_modules` — because the generated code is shell words
/// rather than calls into a `QTerm` runtime. So this test, like the Rust one,
/// never skips: `bash` is on `PATH` everywhere this suite runs.
#[test]
fn run_bash_host_executes_the_generated_script() {
    let d = Dir::new("run-bash");
    let f = d.write(
        "gen.bash.quilt",
        "#!/usr/bin/env quilt\n\
         units=(nginx redis)\n\
         for u in \"${units[@]}\"; do\n\
         \x20 echo ↖systemctl start ↙$u↘↗\n\
         done\n",
    );
    let o = run(&[Path::new("run"), &f]);
    assert!(o.status.success(), "stderr:\n{}", stderr(&o));
    assert_eq!(stdout(&o), "systemctl start nginx\nsystemctl start redis\n");
}

/// The zsh half of the same claim. Unlike bash, zsh is not guaranteed to be
/// installed, so this skips rather than fails where it is absent.
#[test]
fn run_zsh_host_executes_the_generated_script() {
    if Command::new("zsh")
        .arg("--version")
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status()
        .is_err()
    {
        eprintln!("skipping run_zsh_host_executes_the_generated_script: no `zsh` on PATH");
        return;
    }
    let d = Dir::new("run-zsh");
    let f = d.write(
        "gen.zsh.quilt",
        "#!/usr/bin/env quilt\n\
         n=3\n\
         echo rs↖const N: u32 = ↙$n↘;↗\n",
    );
    let o = run(&[Path::new("run"), &f]);
    assert!(o.status.success(), "stderr:\n{}", stderr(&o));
    assert_eq!(stdout(&o), "const N: u32 = 3;\n");
}

/* ── run: the Python backend ───────────────────────────────────────────── */

/// The `quilt_python` extension module a `.py.quilt` program imports. Absent
/// until `bin/build-py` has run, so these tests skip rather than fail — as the
/// Node ones below do. `bin/test-py` builds it and then runs this file, which
/// is where they execute for real.
fn python_runtime_built() -> bool {
    Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("../quilt-python/quilt/_quilt.abi3.so")
        .exists()
}

fn skip_without_python_runtime(test: &str) -> bool {
    if python_runtime_built() {
        return false;
    }
    eprintln!("skipping {test}: quilt_python is not built — run `bin/build-py`");
    true
}

/// The `.py.quilt` end of `run`: the expanded program imports the runtime by
/// bare name, which only resolves because `run` injects `PYTHONPATH`. The
/// shebang is stripped before parsing, so an executable script runs as itself.
#[test]
fn run_python_resolves_the_runtime_import() {
    if skip_without_python_runtime("run_python_resolves_the_runtime_import") {
        return;
    }
    let d = Dir::new("run-py");
    let f = d.write(
        "hello.py.quilt",
        "#!/usr/bin/env quilt\n\
         from quilt import *\n\
         frag = py↖1 + 2↗\n\
         print(frag.coparse())\n",
    );
    let o = run(&[Path::new("run"), &f]);
    assert!(o.status.success(), "stderr:\n{}", stderr(&o));
    assert_eq!(stdout(&o).trim(), "1 + 2");
}

/// The injection *prepends*: a caller's own `PYTHONPATH` survives, and quilt's
/// entry wins over it. Replacing it outright would silently break a script that
/// imports anything else, and appending would let a stale checkout on the
/// caller's path shadow the runtime `run` just built.
///
/// Asserted on the variable the child actually sees, not on the run merely
/// succeeding — a run with the inherited value dropped succeeds too, so that
/// would pin nothing.
#[test]
fn run_python_prepends_to_an_inherited_pythonpath() {
    if skip_without_python_runtime("run_python_prepends_to_an_inherited_pythonpath") {
        return;
    }
    let d = Dir::new("run-py-path");
    let f = d.write(
        "path.py.quilt",
        "import os\nprint(os.environ[\"PYTHONPATH\"])\n",
    );
    let o = quilt()
        .env("PYTHONPATH", "/inherited-and-preserved")
        .args([Path::new("run"), f.as_path()])
        .output()
        .expect("runs");
    assert!(o.status.success(), "stderr:\n{}", stderr(&o));

    let seen = stdout(&o);
    let seen = seen.trim();
    let (first, rest) = seen
        .split_once(':')
        .unwrap_or_else(|| panic!("expected quilt's entry *and* the inherited one, got {seen:?}"));
    assert!(
        first.ends_with("/quilt-python"),
        "quilt's runtime should come first, got {seen:?}"
    );
    assert_eq!(
        rest, "/inherited-and-preserved",
        "the inherited PYTHONPATH should be kept verbatim after quilt's entry"
    );
}

/// Everything after the filename belongs to the script, not to `quilt` — the
/// other half of what makes a shebang script a real program. Untested until
/// now, and the flags are hyphen-friendly on purpose (`allow_hyphen_values`),
/// so a script can take its own `--flag` without `quilt` claiming it.
#[test]
fn run_python_forwards_script_arguments() {
    if skip_without_python_runtime("run_python_forwards_script_arguments") {
        return;
    }
    let d = Dir::new("run-py-args");
    let f = d.write(
        "args.py.quilt",
        "import sys\nprint(\" \".join(sys.argv[1:]))\n",
    );
    let o = quilt()
        .arg("run")
        .arg(&f)
        .args(["--verbose", "two"])
        .output()
        .expect("runs");
    assert!(o.status.success(), "stderr:\n{}", stderr(&o));
    assert_eq!(stdout(&o).trim(), "--verbose two");
}

#[test]
fn run_python_propagates_the_exit_code() {
    if skip_without_python_runtime("run_python_propagates_the_exit_code") {
        return;
    }
    let d = Dir::new("run-py-exit");
    let f = d.write("boom.py.quilt", "import sys\nsys.exit(3)\n");
    let o = run(&[Path::new("run"), &f]);
    assert_eq!(o.status.code(), Some(3), "stderr:\n{}", stderr(&o));
}

/// An extension-less entry point — `bin/issues` is a symlink to
/// `examples/issue_triage.html.py.quilt` — has no chain in its own name, so
/// `run` resolves the symlink and derives the chain from the target's. Only the
/// file *name* counts: a dot in a parent directory must not leak into it.
#[cfg(unix)]
#[test]
fn run_resolves_a_symlinked_entry_point() {
    if skip_without_python_runtime("run_resolves_a_symlinked_entry_point") {
        return;
    }
    let d = Dir::new("run-py-symlink");
    let target = d.write(
        "some.dir.v2/tool.py.quilt",
        "#!/usr/bin/env quilt\n\
         from quilt import *\n\
         print(py↖40 + 2↗.coparse())\n",
    );
    let link = d.0.join("tool");
    std::os::unix::fs::symlink(&target, &link).expect("symlink");
    let o = run(&[Path::new("run"), &link]);
    assert!(o.status.success(), "stderr:\n{}", stderr(&o));
    assert_eq!(stdout(&o).trim(), "40 + 2");
}

/* ── run: the TypeScript/Node backend ──────────────────────────────────── */

/// The Node runtime `quilt run` binds the bare `quilt` import to, and the
/// wasm-pack build it needs. Absent in a checkout that has not run
/// `bin/build-ts`, so the tests below skip rather than fail there — the CI
/// `typescript` job builds it, as the `python` job does for `quilt_python`.
fn node_runtime_built() -> bool {
    Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("../quilt-wasm/pkg/quilt_wasm.js")
        .exists()
}

fn skip_without_node_runtime(test: &str) -> bool {
    if node_runtime_built() {
        return false;
    }
    eprintln!("skipping {test}: quilt-wasm is not built for Node — run `bin/build-ts`");
    true
}

/// A `.ts.quilt` file has to actually run: the expanded program imports the
/// runtime by bare specifier, and Node's ESM resolver ignores `NODE_PATH`, so
/// before #153 `quilt run` died at the import.
#[test]
fn run_typescript_resolves_the_runtime_import() {
    if skip_without_node_runtime("run_typescript_resolves_the_runtime_import") {
        return;
    }
    let d = Dir::new("run-ts");
    let f = d.write(
        "hello.ts.quilt",
        "import { tb, leaf, sym } from \"quilt\";\n\
         const frag = ts↖1 + 2↗;\n\
         console.log(frag.coparse());\n",
    );
    let o = run(&[Path::new("run"), &f]);
    assert!(o.status.success(), "stderr:\n{}", stderr(&o));
    assert_eq!(stdout(&o).trim(), "1 + 2");
}

/// `↓` on the CLI — the whole point of #153. The first reduce is plain
/// TypeScript; the second is a *generated stage* whose source still holds
/// glyphs, so it only works if the runtime re-invokes the expander.
#[test]
fn run_typescript_reduces() {
    if skip_without_node_runtime("run_typescript_reduces") {
        return;
    }
    let d = Dir::new("run-ts-reduce");
    // Everything printed is a string: `console.log` inspects non-string
    // arguments, which adds ANSI colour whenever $FORCE_COLOR is set.
    let f = d.write(
        "reduce.ts.quilt",
        "import { tb, leaf, sym, quote, unquote, cmd, write, qlift, HOLE } from \"quilt\";\n\
         console.log(`plain: ${(ts↖6 * 7↗).↓}`);\n\
         const stage2 = ts↖(a) => ts↖(x) => ↙↑(a)↘ * x↗↗;\n\
         const gen = stage2.↓;\n\
         console.log(`staged: ${gen(7).coparse()}`);\n\
         console.log(`value: ${gen(7).↓(6)}`);\n",
    );
    let o = run(&[Path::new("run"), &f]);
    assert!(o.status.success(), "stderr:\n{}", stderr(&o));
    let out = stdout(&o);
    assert!(out.contains("plain: 42"), "stdout:\n{out}");
    assert!(out.contains("staged: (x) => 7 * x"), "stdout:\n{out}");
    assert!(out.contains("value: 42"), "stdout:\n{out}");
}

/// Reduce has to re-expand a generated stage under the right language chain, or
/// the stage's own quotes resolve to the wrong language. `quilt run` passes the
/// running chain as `$QUILT_CHAIN` and the runtime reads the stage's chain off
/// it: one entry along, since the chain is indexed by quote depth — but never
/// dropping the ground, or the stage would stop being a TypeScript program.
#[test]
fn run_typescript_reduces_under_the_language_chain() {
    if skip_without_node_runtime("run_typescript_reduces_under_the_language_chain") {
        return;
    }
    let imports = "import { tb, leaf, sym, quote, unquote, cmd, write, push, \
                   name, qlift, qlift_html, NL, POP, HOLE } from \"quilt\";\n";
    for (name, body) in [
        // [ts, ts, html]: the stage is the un-annotated depth-1 quote, and its
        // own un-annotated quote is HTML — so the stage's chain is [ts, html].
        (
            "gen.html.ts.ts.quilt",
            "const s = ↖(t) => ↖<li>↙↑(t)↘</li>↗↗;\n",
        ),
        // [ts, html]: the stage has to be written `ts↖…↗`, and dropping the
        // ground would re-expand it as an HTML program.
        (
            "gen.html.ts.quilt",
            "const s = ts↖(t) => html↖<li>↙↑(t)↘</li>↗↗;\n",
        ),
    ] {
        let d = Dir::new(&format!("run-ts-chain-{}", name.replace('.', "-")));
        let f = d.write(
            name,
            &format!("{imports}{body}console.log(s.↓(\"Fix <bug>\").coparse());\n"),
        );
        let o = run(&[Path::new("run"), &f]);
        assert!(o.status.success(), "{name}: stderr:\n{}", stderr(&o));
        // The HTML lift escapes, which also proves the fragment was built by the
        // HTML side of the runtime rather than spliced as TypeScript text.
        assert_eq!(stdout(&o).trim(), "<li>Fix &lt;bug&gt;</li>", "{name}");
    }
}

/// The script's exit code is the CLI's exit code, so a failing `.ts.quilt`
/// program is not reported as a success.
#[test]
fn run_typescript_propagates_the_exit_code() {
    if skip_without_node_runtime("run_typescript_propagates_the_exit_code") {
        return;
    }
    let d = Dir::new("run-ts-exit");
    let f = d.write("boom.ts.quilt", "process.exit(3);\n");
    let o = run(&[Path::new("run"), &f]);
    assert_eq!(o.status.code(), Some(3), "stderr:\n{}", stderr(&o));
}

/* ── notebook: an .html.quilt page whose cells run on machines ─────────── */

/// A small notebook whose cells need only `python3` and `bash`: a page
/// element, a Python cell reading it, a bash cell reading it.
const NOTEBOOK: &str = "<h1 id=\"n\">20</h1>\n\
    <div class=\"row\">\n  py↖int(↙#n↘) + 1↗\n  bash↖echo \"n is ↙#n↘\"↗\n</div>\n";

/// `quilt notebook` writes the rendered page beside the source — the input
/// name without `.quilt` — with a generated-file header, the cells' results
/// in it, and a summary on stderr.
#[test]
fn notebook_writes_the_sibling_page() {
    let d = Dir::new("notebook");
    let f = d.write("nb.html.quilt", NOTEBOOK);
    let o = run(&[Path::new("notebook"), &f]);
    assert!(o.status.success(), "stderr:\n{}", stderr(&o));
    let page = std::fs::read_to_string(d.0.join("nb.html")).expect("nb.html written");
    assert!(
        page.starts_with("<!-- DO NOT EDIT. GENERATED BY `quilt notebook"),
        "{page}"
    );
    assert!(
        page.contains("<pre class=\"quilt-value\">21</pre>"),
        "{page}"
    );
    assert!(
        page.contains("<pre class=\"quilt-stdout\">n is 20</pre>"),
        "{page}"
    );
    assert!(stderr(&o).contains("2 cell(s), 0 failed"), "{}", stderr(&o));
}

/// `-o` picks the output; `--stdout` prints the page instead of writing.
#[test]
fn notebook_output_options() {
    let d = Dir::new("notebook-out");
    let f = d.write("nb.html.quilt", NOTEBOOK);
    let out = d.0.join("elsewhere.html");
    let o = run(&[Path::new("notebook"), &f, Path::new("-o"), &out]);
    assert!(o.status.success(), "stderr:\n{}", stderr(&o));
    assert!(out.exists());
    assert!(!d.0.join("nb.html").exists());

    let o = run(&[Path::new("notebook"), &f, Path::new("--stdout")]);
    assert!(o.status.success(), "stderr:\n{}", stderr(&o));
    assert!(stdout(&o).contains("<pre class=\"quilt-value\">21</pre>"));
    assert!(!d.0.join("nb.html").exists());
}

/// `expand` on an HTML-ground file renders the notebook (the identity
/// expansion is nothing anyone wants written), and `run` prints it — so a
/// `#!/usr/bin/env quilt` notebook is a script whose output is its page.
#[test]
fn expand_and_run_render_a_notebook() {
    let d = Dir::new("notebook-expand");
    let f = d.write("nb.html.quilt", NOTEBOOK);
    let o = run(&[Path::new("expand"), &f]);
    assert!(o.status.success(), "stderr:\n{}", stderr(&o));
    let page = std::fs::read_to_string(d.0.join("nb.html")).expect("nb.html written");
    assert!(
        page.contains("<pre class=\"quilt-value\">21</pre>"),
        "{page}"
    );

    let script = d.write(
        "script.html.quilt",
        &format!("#!/usr/bin/env quilt\n{NOTEBOOK}"),
    );
    let o = run(&[Path::new("run"), &script]);
    assert!(o.status.success(), "stderr:\n{}", stderr(&o));
    assert!(
        stdout(&o).contains("<pre class=\"quilt-value\">21</pre>"),
        "{}",
        stdout(&o)
    );
    assert!(!d.0.join("script.html").exists(), "run writes nothing");
}

/// `check` validates every cell with its own grammar and runs none of them.
#[test]
fn check_validates_a_notebook_without_running_it() {
    let d = Dir::new("notebook-check");
    let marker = d.0.join("ran");
    let f = d.write(
        "nb.html.quilt",
        &format!("<p>bash↖touch \"{}\"↗ py↖x = 1↗</p>\n", marker.display()),
    );
    let o = run(&[Path::new("check"), &f]);
    assert!(o.status.success(), "stderr:\n{}", stderr(&o));
    assert!(!marker.exists(), "check must not run cells");

    let bad = d.write("bad.html.quilt", "<p>py↖def oops(:↗</p>\n");
    let o = run(&[Path::new("check"), &bad]);
    assert!(!o.status.success(), "a cell's syntax error fails check");
}

/// A failed cell is rendered, not fatal; `--strict` makes it the exit code.
#[test]
fn notebook_strict_reports_failed_cells() {
    let d = Dir::new("notebook-strict");
    let f = d.write("nb.html.quilt", "<p>py↖undefined_name↗ py↖2 + 2↗</p>\n");
    let o = run(&[Path::new("notebook"), &f, Path::new("--stdout")]);
    assert!(o.status.success(), "stderr:\n{}", stderr(&o));
    assert!(stdout(&o).contains("quilt-failed"));
    assert!(stdout(&o).contains("<pre class=\"quilt-value\">4</pre>"));
    assert!(stderr(&o).contains("cell 1 [py] failed"), "{}", stderr(&o));

    let o = run(&[
        Path::new("notebook"),
        &f,
        Path::new("--stdout"),
        Path::new("--strict"),
    ]);
    assert!(!o.status.success());
    assert!(stderr(&o).contains("1 cell(s) failed"), "{}", stderr(&o));
}

/// A notebook is an HTML-ground file; anything else is refused by name.
#[test]
fn notebook_rejects_another_ground_language() {
    let d = Dir::new("notebook-ground");
    let f = d.write("prog.py.quilt", "print(1)\n");
    let o = run(&[Path::new("notebook"), &f]);
    assert!(!o.status.success());
    assert!(stderr(&o).contains("ground language"), "{}", stderr(&o));
}

/// `quilt repl html` is a notebook session: markup defines, quotes run,
/// `#id` reads, and the page is printed at the end.
#[test]
fn repl_html_is_a_notebook_session() {
    use std::io::Write as _;
    use std::process::Stdio;
    let mut child = quilt()
        .args(["repl", "html"])
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .expect("spawns");
    child
        .stdin
        .take()
        .unwrap()
        .write_all(b"<p id=\"x\">5</p>\npy\xe2\x86\x96int(\xe2\x86\x99#x\xe2\x86\x98) * 2\xe2\x86\x97\n#x\n")
        .unwrap();
    let o = child.wait_with_output().expect("runs");
    assert!(o.status.success(), "stderr:\n{}", stderr(&o));
    let s = stdout(&o);
    assert!(s.starts_with("10\n<p id=\"x\">5</p>\n"), "{s}");
    assert!(s.contains("<figure class=\"quilt-cell quilt-py\""), "{s}");
}

/* ── general ───────────────────────────────────────────────────────────── */

#[test]
fn help_lists_the_subcommands() {
    let o = quilt().arg("--help").output().expect("runs");
    assert!(o.status.success());
    let s = stdout(&o);
    for sub in ["expand", "check", "run", "notebook"] {
        assert!(s.contains(sub), "--help should mention {sub}, got:\n{s}");
    }
}