qj 0.1.4

A fast, jq-compatible JSON processor powered by simdjson
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
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
use anyhow::{Context, Result};
use clap::Parser;
use mimalloc::MiMalloc;
use std::io::{self, BufWriter, IsTerminal, Read, Write};
use std::sync::Arc;
use std::time::{Duration, Instant};

// ---------------------------------------------------------------------------
// File I/O helpers (compression-aware)
// ---------------------------------------------------------------------------

/// Expand glob patterns in file arguments.
/// Literal paths are passed through unchanged. Arguments containing glob
/// metacharacters (*, ?, [) are expanded against the filesystem.
fn expand_globs(files: Vec<String>) -> Result<Vec<String>> {
    let mut result = Vec::new();
    for f in files {
        // Literal file — use as-is (also handles the case where the filename
        // happens to contain glob metacharacters, e.g. "file[1].json")
        if std::path::Path::new(&f).exists() {
            result.push(f);
            continue;
        }
        if f.contains('*') || f.contains('?') || f.contains('[') {
            let mut paths: Vec<String> = Vec::new();
            for entry in glob::glob(&f).with_context(|| format!("invalid glob pattern: {f}"))? {
                let path = entry.with_context(|| format!("failed to read glob match for: {f}"))?;
                paths.push(path.display().to_string());
            }
            if paths.is_empty() {
                anyhow::bail!("no files matched pattern: {f}");
            }
            paths.sort();
            result.extend(paths);
        } else {
            // Not a glob, not an existing file — pass through (will fail at open)
            result.push(f);
        }
    }
    Ok(result)
}

/// Collect parsed JSON values from a file, decompressing if needed.
/// Preserves mmap for uncompressed files via `read_padded_file`.
fn collect_file_values(
    path: &str,
    force_jsonl: bool,
    values: &mut Vec<qj::value::Value>,
) -> Result<()> {
    if qj::decompress::is_compressed(path) {
        let bytes = qj::decompress::decompress_file(path)?;
        qj::input::collect_values_from_buf(&bytes, force_jsonl, values)
    } else {
        let (padded, json_len) = qj::simdjson::read_padded_file(std::path::Path::new(path))
            .with_context(|| format!("failed to read file: {path}"))?;
        qj::input::collect_values_from_buf(&padded[..json_len], force_jsonl, values)
    }
}

/// Read a file as a UTF-8 string, decompressing if needed.
fn read_file_text(path: &str) -> Result<String> {
    if qj::decompress::is_compressed(path) {
        let bytes = qj::decompress::decompress_file(path)?;
        String::from_utf8(bytes).with_context(|| format!("file is not valid UTF-8: {path}"))
    } else {
        std::fs::read_to_string(path).with_context(|| format!("failed to read file: {path}"))
    }
}

/// Extract RS-delimited (RFC 7464) JSON values from a buffer.
/// Each segment after an RS byte (0x1E) up to the next RS or end of buffer
/// is parsed as a JSON value. Segments that fail to parse are silently skipped
/// (with a warning to stderr, matching jq behavior). Content before the first
/// RS byte is also silently skipped.
fn collect_seq_values(buf: &[u8], values: &mut Vec<qj::value::Value>) -> Result<()> {
    let segments: Vec<&[u8]> = buf.split(|&b| b == 0x1E).collect();
    // The first segment (before any RS) is skipped — jq ignores non-RS-prefixed content
    for seg in segments.iter().skip(1) {
        let trimmed: &[u8] =
            seg.iter()
                .position(|b| !b.is_ascii_whitespace())
                .map_or(&[], |start| {
                    let end = seg
                        .iter()
                        .rposition(|b| !b.is_ascii_whitespace())
                        .unwrap_or(start);
                    &seg[start..=end]
                });
        if trimmed.is_empty() {
            continue;
        }
        let padded = qj::simdjson::pad_buffer(trimmed);
        match qj::simdjson::dom_parse_to_value(&padded, trimmed.len()) {
            Ok(v) => values.push(v),
            Err(e) => {
                eprintln!("qj: ignoring parse error: {e}");
            }
        }
    }
    Ok(())
}

#[global_allocator]
static GLOBAL: MiMalloc = MiMalloc;

/// Detect P-core count on Apple Silicon via sysctlbyname(3), fall back to available_parallelism.
/// Only runs on aarch64 macOS — Intel Macs don't have P/E core distinction.
fn default_thread_count() -> usize {
    #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
    {
        let mut val: i32 = 0;
        let mut size = std::mem::size_of::<i32>();
        let name = b"hw.perflevel0.logicalcpu\0";
        let ret = unsafe {
            libc::sysctlbyname(
                name.as_ptr() as *const libc::c_char,
                &mut val as *mut i32 as *mut libc::c_void,
                &mut size,
                std::ptr::null_mut(),
                0,
            )
        };
        if ret == 0 && val > 0 {
            return val as usize;
        }
    }
    std::thread::available_parallelism()
        .map(|n| n.get())
        .unwrap_or(4)
}

#[derive(Parser)]
#[command(
    name = "qj",
    about = "qj - a faster jq",
    version,
    after_help = "Example:\n\n\t$ echo '{\"foo\": 0}' | qj .\n\t{\n\t  \"foo\": 0\n\t}"
)]
struct Cli {
    /// jq filter expression (not needed with --from-file/-f)
    filter: Option<String>,

    /// Input file(s); defaults to stdin
    files: Vec<String>,

    /// Compact output (no pretty-printing)
    #[arg(short = 'c', long = "compact-output")]
    compact: bool,

    /// Raw output (strings without quotes)
    #[arg(short = 'r', long = "raw-output")]
    raw: bool,

    /// Raw output with NUL separator instead of newline (implies -r)
    #[arg(long = "raw-output0")]
    raw_output0: bool,

    /// Escape non-ASCII characters to \uXXXX sequences
    #[arg(short = 'a', long = "ascii-output")]
    ascii_output: bool,

    /// Flush stdout after each output value
    #[arg(long = "unbuffered")]
    unbuffered: bool,

    /// Use tab for indentation
    #[arg(long)]
    tab: bool,

    /// Number of spaces for indentation (default: 2)
    #[arg(long, default_value_t = 2)]
    indent: u32,

    /// Set exit status based on output
    #[arg(short = 'e', long = "exit-status")]
    exit_status: bool,

    /// Null input — don't read any input, use `null` as the sole input
    #[arg(short = 'n', long = "null-input")]
    null_input: bool,

    /// Treat input as NDJSON (newline-delimited JSON)
    #[arg(long)]
    jsonl: bool,

    /// Slurp all inputs into an array
    #[arg(short = 's', long = "slurp")]
    slurp: bool,

    /// Parse input in streaming fashion, emitting [path, value] pairs
    #[arg(long = "stream")]
    stream: bool,

    /// Like --stream but emit parse errors as ["error", []] entries
    #[arg(long = "stream-errors")]
    stream_errors: bool,

    /// Use application/json-seq (RFC 7464) RS-delimited I/O
    #[arg(long = "seq")]
    seq: bool,

    /// Read each line as a raw string instead of parsing as JSON
    #[arg(short = 'R', long = "raw-input")]
    raw_input: bool,

    /// Sort object keys
    #[arg(short = 'S', long = "sort-keys")]
    sort_keys: bool,

    /// Don't print newline after each output value
    #[arg(short = 'j', long = "join-output")]
    join_output: bool,

    /// Force color output even when piped
    #[arg(short = 'C', long = "color-output")]
    color: bool,

    /// Monochrome output (no color)
    #[arg(short = 'M', long = "monochrome-output")]
    monochrome: bool,

    /// Bind $name to string value
    #[arg(long = "arg", num_args = 2, value_names = ["NAME", "VALUE"], action = clap::ArgAction::Append)]
    args: Vec<String>,

    /// Bind $name to parsed JSON value
    #[arg(long = "argjson", num_args = 2, value_names = ["NAME", "VALUE"], action = clap::ArgAction::Append)]
    argjson: Vec<String>,

    /// Bind $NAME to raw string contents of FILE
    #[arg(long = "rawfile", num_args = 2, value_names = ["NAME", "FILE"], action = clap::ArgAction::Append)]
    rawfile: Vec<String>,

    /// Bind $NAME to array of JSON values parsed from FILE
    #[arg(long = "slurpfile", num_args = 2, value_names = ["NAME", "FILE"], action = clap::ArgAction::Append)]
    slurpfile: Vec<String>,

    /// Read filter from file instead of first argument
    #[arg(short = 'f', long = "from-file", value_name = "FILE")]
    from_file: Option<String>,

    /// Print timing breakdown to stderr (for profiling)
    #[arg(long = "debug-timing", hide = true)]
    debug_timing: bool,

    /// Number of threads for parallel NDJSON processing
    #[arg(long, value_name = "N")]
    threads: Option<usize>,

    /// Library search path for jq modules (import/include)
    #[arg(short = 'L', value_name = "DIR")]
    library_paths: Vec<String>,
}

/// Check if a filter AST contains import/include/module statements.
fn has_module_stmts(filter: &qj::filter::Filter) -> bool {
    matches!(
        filter,
        qj::filter::Filter::Import { .. }
            | qj::filter::Filter::Include { .. }
            | qj::filter::Filter::ModuleDecl { .. }
    )
}

fn main() -> Result<()> {
    // Restore default SIGPIPE behavior so piping to `head` etc. exits cleanly
    // instead of producing BrokenPipe errors. Rust's runtime sets SIG_IGN by default.
    #[cfg(unix)]
    unsafe {
        libc::signal(libc::SIGPIPE, libc::SIG_DFL);
    }

    // Pre-scan for --args / --jsonargs: split argv before clap sees them.
    // Everything after --args or --jsonargs becomes positional string/JSON values.
    let raw_args: Vec<String> = std::env::args().collect();
    let (clap_args, positional_args, positional_json) = {
        let mut clap_part = raw_args.clone();
        let mut pos_str = Vec::new();
        let mut pos_json = false;
        if let Some(idx) = raw_args
            .iter()
            .position(|a| a == "--args" || a == "--jsonargs")
        {
            pos_json = raw_args[idx] == "--jsonargs";
            let tail: Vec<String> = raw_args[idx + 1..].to_vec();
            clap_part = raw_args[..idx].to_vec();
            pos_str = tail;
        }
        (clap_part, pos_str, pos_json)
    };

    let cli = Cli::parse_from(&clap_args);

    // Configure Rayon thread pool to use P-cores only on Apple Silicon.
    // E-cores add contention without throughput benefit for I/O-bound NDJSON work.
    rayon::ThreadPoolBuilder::new()
        .num_threads(cli.threads.unwrap_or_else(default_thread_count))
        .build_global()
        .ok(); // Ignore error if pool already initialized (e.g., in tests)

    // Resolve filter string and input files.
    // With --from-file, all positional args are input files.
    // Without it, the first positional is the filter expression.
    // If no filter given: default to "." (like jq). On TTY with no files, show usage hint.
    let (filter_str, input_files) = if let Some(ref path) = cli.from_file {
        let filter_str = std::fs::read_to_string(path)
            .with_context(|| format!("failed to read filter file: {path}"))?;
        let mut files = cli.files.clone();
        if let Some(ref f) = cli.filter {
            files.insert(0, f.clone());
        }
        (filter_str, files)
    } else {
        match cli.filter.clone() {
            Some(f) => (f, cli.files.clone()),
            None if !cli.null_input && cli.files.is_empty() && io::stdin().is_terminal() => {
                eprintln!("qj - a faster jq [version {}]", env!("CARGO_PKG_VERSION"));
                eprintln!("Usage: qj [OPTIONS] [FILTER] [FILES...]");
                eprintln!("       echo '{{}}' | qj '.'");
                eprintln!("For help: qj --help");
                std::process::exit(0);
            }
            None => (".".to_string(), cli.files.clone()),
        }
    };

    // Expand glob patterns in file arguments (e.g., '*.json.gz')
    let input_files = expand_globs(input_files)?;

    let filter = match qj::filter::parse(&filter_str) {
        Ok(f) => f,
        Err(e) => {
            eprintln!("qj: error: failed to parse filter: {filter_str}\n\nCaused by:\n    {e}");
            std::process::exit(3);
        }
    };

    // Resolve module imports (import/include) if the filter uses them.
    // The module loader resolves all imports into the Env and strips
    // the import/include nodes from the filter AST.
    let (filter, module_loader) = if !cli.library_paths.is_empty() || has_module_stmts(&filter) {
        let search_paths: Vec<std::path::PathBuf> = cli
            .library_paths
            .iter()
            .map(std::path::PathBuf::from)
            .collect();
        let mut loader = qj::filter::module::ModuleLoader::new(search_paths.clone());
        match loader.resolve(&filter, qj::filter::Env::empty()) {
            Ok((resolved_filter, module_env)) => {
                // Set module metadata cache for modulemeta builtin
                qj::filter::eval::set_module_metadata(
                    loader.export_metadata(),
                    search_paths.clone(),
                );
                (resolved_filter, Some((loader, module_env)))
            }
            Err(e) => {
                eprintln!("qj: error: {e:#}");
                std::process::exit(3);
            }
        }
    } else {
        (filter, None)
    };

    // --stream-errors implies --stream behavior
    let effective_stream = cli.stream || cli.stream_errors;

    // --stream: wrap filter with `tostream |` for the common case (non-slurp, non-null-input).
    // For slurp and null-input, the expansion happens later at the value level.
    // For --stream-errors, keep the unwrapped filter for error entries.
    let unwrapped_filter = if cli.stream_errors && !cli.slurp && !cli.null_input {
        Some(filter.clone())
    } else {
        None
    };
    let filter = if effective_stream && !cli.slurp && !cli.null_input {
        qj::filter::Filter::Pipe(
            Box::new(qj::filter::Filter::Builtin("tostream".to_string(), vec![])),
            Box::new(filter),
        )
    } else {
        filter
    };

    // Build environment from --arg / --argjson
    // Variable names in the AST include the '$' prefix (e.g., "$name"),
    // so we prepend '$' when binding.
    let mut env = if let Some((_, ref module_env)) = module_loader {
        module_env.clone()
    } else {
        qj::filter::Env::empty()
    };
    for pair in cli.args.chunks(2) {
        if pair.len() == 2 {
            env = env.bind_var(
                format!("${}", pair[0]),
                qj::value::Value::String(pair[1].clone()),
            );
        }
    }
    for pair in cli.argjson.chunks(2) {
        if pair.len() == 2 {
            let padded = qj::simdjson::pad_buffer(pair[1].as_bytes());
            let val = qj::simdjson::dom_parse_to_value(&padded, pair[1].len())
                .with_context(|| format!("invalid JSON for --argjson {}: {}", pair[0], pair[1]))?;
            env = env.bind_var(format!("${}", pair[0]), val);
        }
    }
    for pair in cli.rawfile.chunks(2) {
        if pair.len() == 2 {
            let content = std::fs::read_to_string(&pair[1])
                .with_context(|| format!("failed to read --rawfile {}: {}", pair[0], pair[1]))?;
            env = env.bind_var(format!("${}", pair[0]), qj::value::Value::String(content));
        }
    }
    for pair in cli.slurpfile.chunks(2) {
        if pair.len() == 2 {
            let buf = std::fs::read(&pair[1])
                .with_context(|| format!("failed to read --slurpfile {}: {}", pair[0], pair[1]))?;
            let mut values = Vec::new();
            qj::input::collect_values_from_buf(&buf, false, &mut values)
                .with_context(|| format!("failed to parse --slurpfile {}: {}", pair[0], pair[1]))?;
            env = env.bind_var(
                format!("${}", pair[0]),
                qj::value::Value::Array(Arc::new(values)),
            );
        }
    }

    // Build $ARGS: {positional: [...], named: {...}}
    {
        let pos_values: Vec<qj::value::Value> = if positional_json {
            let mut vals = Vec::new();
            for s in &positional_args {
                let padded = qj::simdjson::pad_buffer(s.as_bytes());
                match qj::simdjson::dom_parse_to_value(&padded, s.len()) {
                    Ok(v) => vals.push(v),
                    Err(e) => {
                        eprintln!(
                            "qj: invalid JSON text passed to --jsonargs: {s}\n\nCaused by:\n    {e}"
                        );
                        std::process::exit(2);
                    }
                }
            }
            vals
        } else {
            positional_args
                .iter()
                .map(|s| qj::value::Value::String(s.clone()))
                .collect()
        };

        let named_pairs: Vec<(String, qj::value::Value)> = {
            let mut pairs = Vec::new();
            for pair in cli.args.chunks(2) {
                if pair.len() == 2 {
                    pairs.push((pair[0].clone(), qj::value::Value::String(pair[1].clone())));
                }
            }
            for pair in cli.argjson.chunks(2) {
                if pair.len() == 2 {
                    let padded = qj::simdjson::pad_buffer(pair[1].as_bytes());
                    if let Ok(val) = qj::simdjson::dom_parse_to_value(&padded, pair[1].len()) {
                        pairs.push((pair[0].clone(), val));
                    }
                }
            }
            pairs
        };

        let args_obj = qj::value::Value::Object(Arc::new(vec![
            (
                "positional".to_string(),
                qj::value::Value::Array(Arc::new(pos_values)),
            ),
            (
                "named".to_string(),
                qj::value::Value::Object(Arc::new(named_pairs)),
            ),
        ]));
        env = env.bind_var("$ARGS".to_string(), args_obj);
    }

    // Color: on by default for TTY, overridden by -C (force on) or -M (force off).
    // NO_COLOR env var (https://no-color.org/) disables color by default,
    // but -C still overrides it (matches jq behavior).
    // Check before locking stdout.
    let no_color_env = std::env::var_os("NO_COLOR").is_some_and(|v| !v.is_empty());
    let use_color = if cli.monochrome {
        false
    } else if cli.color {
        true
    } else if no_color_env {
        false
    } else {
        io::stdout().is_terminal()
    };
    let color_scheme = if use_color {
        qj::output::ColorScheme::jq_default()
    } else {
        qj::output::ColorScheme::none()
    };

    let stdout = io::stdout().lock();
    let mut out = BufWriter::with_capacity(128 * 1024, stdout);

    // -j / --join-output implies raw output (matches jq behavior)
    let config = if cli.raw || cli.raw_output0 || cli.join_output {
        qj::output::OutputConfig {
            mode: qj::output::OutputMode::Raw,
            indent: String::new(),
            sort_keys: cli.sort_keys,
            join_output: cli.join_output,
            color: color_scheme,
            null_separator: cli.raw_output0,
            ascii_output: cli.ascii_output,
            unbuffered: cli.unbuffered,
            seq: cli.seq,
        }
    } else if cli.compact {
        qj::output::OutputConfig {
            mode: qj::output::OutputMode::Compact,
            indent: String::new(),
            sort_keys: cli.sort_keys,
            join_output: cli.join_output,
            color: color_scheme,
            null_separator: false,
            ascii_output: cli.ascii_output,
            unbuffered: cli.unbuffered,
            seq: cli.seq,
        }
    } else {
        qj::output::OutputConfig {
            mode: qj::output::OutputMode::Pretty,
            indent: if cli.tab {
                "\t".to_string()
            } else {
                " ".repeat(cli.indent as usize)
            },
            sort_keys: cli.sort_keys,
            join_output: cli.join_output,
            color: color_scheme,
            null_separator: false,
            ascii_output: cli.ascii_output,
            unbuffered: cli.unbuffered,
            seq: cli.seq,
        }
    };

    // Detect passthrough-eligible patterns. Disable when semantic-changing
    // flags are active (slurp, raw_input, sort_keys, join_output) or when
    // color is enabled (passthrough bypasses the output formatter).
    // Also disable when -e is active — we need full eval to inspect output values.
    let passthrough = if cli.slurp
        || cli.raw_input
        || cli.sort_keys
        || cli.join_output
        || use_color
        || cli.ascii_output
        || cli.raw
        || cli.raw_output0
        || cli.exit_status
        || effective_stream
        || cli.seq
    {
        None
    } else {
        qj::filter::passthrough_path(&filter).filter(|p| !p.requires_compact() || cli.compact)
    };

    let uses_input = filter.uses_input_builtins();
    let mut had_output = false;
    let mut had_error = false;
    let mut last_was_falsy = false;

    if cli.null_input {
        // With -n: collect all input values into the input queue (for input/inputs),
        // then eval with null input.
        if uses_input {
            let mut values = Vec::new();
            if !input_files.is_empty() {
                for path in &input_files {
                    if cli.raw_input {
                        let content = read_file_text(path)?;
                        for line in content.lines() {
                            values.push(qj::value::Value::String(line.to_string()));
                        }
                    } else if cli.seq {
                        let buf = if qj::decompress::is_compressed(path) {
                            qj::decompress::decompress_file(path)?
                        } else {
                            std::fs::read(path)
                                .with_context(|| format!("failed to read file: {path}"))?
                        };
                        collect_seq_values(&buf, &mut values)?;
                    } else {
                        collect_file_values(path, cli.jsonl, &mut values)?;
                    }
                }
            } else {
                let mut buf = Vec::new();
                io::stdin()
                    .read_to_end(&mut buf)
                    .context("failed to read stdin")?;
                if cli.raw_input {
                    let text = std::str::from_utf8(&buf).context("stdin is not valid UTF-8")?;
                    for line in text.lines() {
                        values.push(qj::value::Value::String(line.to_string()));
                    }
                } else if cli.seq {
                    collect_seq_values(&buf, &mut values)?;
                } else {
                    qj::input::strip_bom(&mut buf);
                    qj::input::collect_values_from_buf(&buf, cli.jsonl, &mut values)?;
                }
            }
            let values = if effective_stream {
                stream_expand_values(&values)
            } else {
                values
            };
            use std::collections::VecDeque;
            qj::filter::eval::set_input_queue(VecDeque::from(values));
        }
        let input = qj::value::Value::Null;
        eval_and_output(
            &filter,
            &input,
            &env,
            &mut out,
            &config,
            &mut had_output,
            &mut had_error,
            &mut last_was_falsy,
        );
    } else if cli.raw_input {
        // --raw-input: read lines as strings instead of parsing JSON
        if input_files.is_empty() {
            let mut buf = Vec::new();
            io::stdin()
                .read_to_end(&mut buf)
                .context("failed to read stdin")?;
            let text = std::str::from_utf8(&buf).context("stdin is not valid UTF-8")?;
            process_raw_input(
                text,
                cli.slurp,
                &filter,
                &env,
                &mut out,
                &config,
                &mut had_output,
                &mut had_error,
                &mut last_was_falsy,
            )?;
        } else if cli.slurp {
            // --raw-input --slurp with files: concatenate all file contents
            // into a single string (matches jq -Rs behavior)
            let mut all_text = String::new();
            for path in &input_files {
                let content = read_file_text(path)?;
                all_text.push_str(&content);
            }
            let input = qj::value::Value::String(all_text);
            eval_and_output(
                &filter,
                &input,
                &env,
                &mut out,
                &config,
                &mut had_output,
                &mut had_error,
                &mut last_was_falsy,
            );
        } else {
            for path in &input_files {
                let content = read_file_text(path)?;
                process_raw_input(
                    &content,
                    false,
                    &filter,
                    &env,
                    &mut out,
                    &config,
                    &mut had_output,
                    &mut had_error,
                    &mut last_was_falsy,
                )?;
            }
        }
    } else if cli.seq {
        // --seq: RS-delimited (RFC 7464) input
        let mut values = Vec::new();
        if input_files.is_empty() {
            let mut buf = Vec::new();
            io::stdin()
                .read_to_end(&mut buf)
                .context("failed to read stdin")?;
            collect_seq_values(&buf, &mut values)?;
        } else {
            for path in &input_files {
                let buf = if qj::decompress::is_compressed(path) {
                    qj::decompress::decompress_file(path)?
                } else {
                    std::fs::read(path).with_context(|| format!("failed to read file: {path}"))?
                };
                collect_seq_values(&buf, &mut values)?;
            }
        }
        if cli.slurp {
            let input = qj::value::Value::Array(Arc::new(values));
            eval_and_output(
                &filter,
                &input,
                &env,
                &mut out,
                &config,
                &mut had_output,
                &mut had_error,
                &mut last_was_falsy,
            );
        } else {
            for value in &values {
                eval_and_output(
                    &filter,
                    value,
                    &env,
                    &mut out,
                    &config,
                    &mut had_output,
                    &mut had_error,
                    &mut last_was_falsy,
                );
            }
        }
    } else if cli.stream_errors && !cli.slurp && !cli.null_input {
        // --stream-errors: like --stream but parse errors become ["error msg", []] entries
        let error_filter = unwrapped_filter.as_ref().unwrap();
        let mut bufs: Vec<Vec<u8>> = Vec::new();
        if input_files.is_empty() {
            let mut buf = Vec::new();
            io::stdin()
                .read_to_end(&mut buf)
                .context("failed to read stdin")?;
            qj::input::strip_bom(&mut buf);
            bufs.push(buf);
        } else {
            for path in &input_files {
                let buf = if qj::decompress::is_compressed(path) {
                    qj::decompress::decompress_file(path)?
                } else {
                    std::fs::read(path).with_context(|| format!("failed to read file: {path}"))?
                };
                bufs.push(buf);
            }
        }
        for buf in &bufs {
            if buf
                .iter()
                .all(|&b| matches!(b, b' ' | b'\t' | b'\r' | b'\n'))
            {
                continue;
            }
            for result in parse_docs_with_errors(buf) {
                match result {
                    Ok(value) => {
                        // Success: apply wrapped filter (tostream | user_filter)
                        eval_and_output(
                            &filter,
                            &value,
                            &env,
                            &mut out,
                            &config,
                            &mut had_output,
                            &mut had_error,
                            &mut last_was_falsy,
                        );
                    }
                    Err(msg) => {
                        // Parse error: create error entry and apply unwrapped filter
                        let error_entry = make_stream_error_entry(&msg);
                        eval_and_output(
                            error_filter,
                            &error_entry,
                            &env,
                            &mut out,
                            &config,
                            &mut had_output,
                            &mut had_error,
                            &mut last_was_falsy,
                        );
                    }
                }
            }
        }
    } else if cli.slurp {
        // --slurp: collect all values into an array, eval once
        let mut values = Vec::new();
        if input_files.is_empty() {
            let mut buf = Vec::new();
            io::stdin()
                .read_to_end(&mut buf)
                .context("failed to read stdin")?;
            qj::input::strip_bom(&mut buf);
            qj::input::collect_values_from_buf(&buf, cli.jsonl, &mut values)?;
        } else {
            for path in &input_files {
                collect_file_values(path, cli.jsonl, &mut values)?;
            }
        }
        let values = if effective_stream {
            stream_expand_values(&values)
        } else {
            values
        };
        let input = qj::value::Value::Array(Arc::new(values));
        eval_and_output(
            &filter,
            &input,
            &env,
            &mut out,
            &config,
            &mut had_output,
            &mut had_error,
            &mut last_was_falsy,
        );
    } else if input_files.is_empty() {
        // stdin
        let mut buf = Vec::new();
        io::stdin()
            .read_to_end(&mut buf)
            .context("failed to read stdin")?;
        qj::input::strip_bom(&mut buf);
        // Empty input produces no output (matches jq behavior)
        let is_empty = buf
            .iter()
            .all(|&b| matches!(b, b' ' | b'\t' | b'\r' | b'\n'));
        if !is_empty {
            if !uses_input
                && !cli.exit_status
                && (cli.jsonl || qj::parallel::ndjson::is_ndjson(&buf))
            {
                let (output, ho, errs) =
                    qj::parallel::ndjson::process_ndjson(&buf, &filter, &config, &env)
                        .context("failed to process NDJSON from stdin")?;
                out.write_all(&output)?;
                had_output |= ho;
                if !errs.is_empty() {
                    // Always surface per-line errors to stderr (matching jq).
                    // Only set had_error (exit 5) when no output was produced —
                    // jq exits 0 for mixed success/error NDJSON.
                    if !ho {
                        had_error = true;
                    }
                    std::io::Write::write_all(&mut std::io::stderr(), &errs)?;
                }
            } else if uses_input {
                // Collect all values; first becomes input, rest go to queue
                let mut values = Vec::new();
                qj::input::collect_values_from_buf(&buf, cli.jsonl, &mut values)?;
                let mut queue: std::collections::VecDeque<_> = values.into();
                let input = queue.pop_front().unwrap_or(qj::value::Value::Null);
                qj::filter::eval::set_input_queue(queue);
                eval_and_output(
                    &filter,
                    &input,
                    &env,
                    &mut out,
                    &config,
                    &mut had_output,
                    &mut had_error,
                    &mut last_was_falsy,
                );
            } else {
                let json_len = buf.len();
                let padded = qj::simdjson::pad_buffer(&buf);
                let mut handled = false;
                if let Some(pt) = &passthrough {
                    handled = try_passthrough(&padded, json_len, pt, &mut out, &mut had_output)
                        .context("passthrough failed")?;
                }
                if !handled {
                    process_padded(
                        &padded,
                        json_len,
                        &filter,
                        &env,
                        &mut out,
                        &config,
                        &mut had_output,
                        &mut had_error,
                        &mut last_was_falsy,
                    )?;
                }
            }
        }
    } else {
        // files
        if uses_input {
            // Collect all values from all files; first becomes input, rest go to queue
            let mut values = Vec::new();
            for path in &input_files {
                collect_file_values(path, cli.jsonl, &mut values)?;
            }
            let mut queue: std::collections::VecDeque<_> = values.into();
            let input = queue.pop_front().unwrap_or(qj::value::Value::Null);
            qj::filter::eval::set_input_queue(queue);
            eval_and_output(
                &filter,
                &input,
                &env,
                &mut out,
                &config,
                &mut had_output,
                &mut had_error,
                &mut last_was_falsy,
            );
        } else {
            let ctx = ProcessCtx {
                passthrough: &passthrough,
                force_jsonl: cli.jsonl,
                filter: &filter,
                env: &env,
                config: &config,
                debug_timing: cli.debug_timing,
            };
            let mut had_file_error = false;
            for path in &input_files {
                match process_file(
                    path,
                    &ctx,
                    &mut out,
                    &mut had_output,
                    &mut had_error,
                    &mut last_was_falsy,
                ) {
                    Ok(()) => {}
                    Err(e) => {
                        // Strip the redundant anyhow context wrapping — just show root cause
                        let root = e.root_cause();
                        eprintln!("qj: error: Could not open file {path}: {root}");
                        had_file_error = true;
                    }
                }
            }
            if had_file_error {
                // Flush buffered output from successfully processed files before exiting
                let _ = out.flush();
                std::process::exit(2);
            }
        }
    }

    out.flush()?;

    if had_error {
        std::process::exit(5);
    }

    if cli.exit_status {
        if !had_output {
            std::process::exit(4);
        }
        if last_was_falsy {
            std::process::exit(1);
        }
    }

    Ok(())
}

// ---------------------------------------------------------------------------
// Core processing helpers
// ---------------------------------------------------------------------------

/// Evaluate a filter against an input value and write all outputs.
/// After evaluation, checks for uncaught runtime errors and reports them
/// to stderr (like jq's exit-code-5 behavior).
#[allow(clippy::too_many_arguments)]
fn eval_and_output(
    filter: &qj::filter::Filter,
    input: &qj::value::Value,
    env: &qj::filter::Env,
    out: &mut impl Write,
    config: &qj::output::OutputConfig,
    had_output: &mut bool,
    had_error: &mut bool,
    last_was_falsy: &mut bool,
) {
    let mut nul_error = false;
    let mut write_failed = false;
    qj::filter::eval::eval_filter_with_env(filter, input, env, &mut |v| {
        if nul_error || write_failed {
            return;
        }
        // Check for embedded NUL in --raw-output0 mode
        if config.null_separator
            && let qj::value::Value::String(s) = &v
            && s.contains('\0')
        {
            nul_error = true;
            return;
        }
        *last_was_falsy = matches!(v, qj::value::Value::Null | qj::value::Value::Bool(false));
        *had_output = true;
        if qj::output::write_value(out, &v, config).is_err() {
            write_failed = true;
        }
    });
    if nul_error {
        *had_error = true;
        eprintln!("qj: error: Cannot dump a string containing NUL with --raw-output0 option");
    }
    // Check for uncaught runtime errors
    if let Some(err) = qj::filter::eval::take_last_error() {
        *had_error = true;
        let msg = format_error(&err);
        eprintln!("qj: error: {msg}");
    }
}

/// Format an error value for display on stderr.
fn format_error(err: &qj::value::Value) -> String {
    match err {
        qj::value::Value::String(s) => s.clone(),
        other => other.short_desc(),
    }
}

/// Create a `--stream-errors` error entry: `["error message", []]`.
fn make_stream_error_entry(msg: &str) -> qj::value::Value {
    qj::value::Value::Array(Arc::new(vec![
        qj::value::Value::String(msg.to_string()),
        qj::value::Value::Array(Arc::new(vec![])),
    ]))
}

/// Parse a buffer as one or more JSON documents for `--stream-errors`.
/// Each successfully parsed document is wrapped in `Ok(value)`.
/// Parse failures produce `Err(error_message)`.
/// For NDJSON, each line is tried independently.
/// Try to parse a single JSON document, validating first to catch malformed input.
fn parse_single_doc(trimmed: &[u8]) -> std::result::Result<qj::value::Value, String> {
    let padded = qj::simdjson::pad_buffer(trimmed);
    // Validate first — dom_parse_to_value may silently accept non-JSON tokens
    if let Err(e) = qj::simdjson::dom_validate(&padded, trimmed.len()) {
        return Err(format!("{e}"));
    }
    qj::simdjson::dom_parse_to_value(&padded, trimmed.len()).map_err(|e| format!("{e}"))
}

fn parse_docs_with_errors(buf: &[u8]) -> Vec<std::result::Result<qj::value::Value, String>> {
    let mut results = Vec::new();
    // Count non-empty lines to determine if this is multi-doc input
    let non_empty_lines = buf
        .split(|&b| b == b'\n')
        .filter(|line| line.iter().any(|b| !b.is_ascii_whitespace()))
        .count();

    if non_empty_lines > 1 {
        // Multi-doc: parse each line independently (error recovery per line)
        for line in buf.split(|&b| b == b'\n') {
            let trimmed =
                line.iter()
                    .position(|b| !b.is_ascii_whitespace())
                    .map_or(&[] as &[u8], |start| {
                        let end = line
                            .iter()
                            .rposition(|b| !b.is_ascii_whitespace())
                            .unwrap_or(start);
                        &line[start..=end]
                    });
            if trimmed.is_empty() {
                continue;
            }
            results.push(parse_single_doc(trimmed));
        }
    } else {
        // Single document
        let trimmed = buf
            .iter()
            .position(|b| !b.is_ascii_whitespace())
            .map_or(buf, |start| {
                let end = buf
                    .iter()
                    .rposition(|b| !b.is_ascii_whitespace())
                    .unwrap_or(start);
                &buf[start..=end]
            });
        if !trimmed.is_empty() {
            results.push(parse_single_doc(trimmed));
        }
    }
    results
}

/// Expand each value through `tostream`, collecting all stream entries.
/// Used for `--stream` in slurp and null-input modes where we can't wrap the filter.
fn stream_expand_values(values: &[qj::value::Value]) -> Vec<qj::value::Value> {
    let tostream = qj::filter::Filter::Builtin("tostream".to_string(), vec![]);
    let mut expanded = Vec::new();
    for value in values {
        qj::filter::eval::eval_filter(&tostream, value, &mut |v| expanded.push(v));
    }
    expanded
}

/// Try the passthrough fast path on a padded buffer.
/// Returns `Ok(true)` if handled, `Ok(false)` if the caller should fall back.
fn try_passthrough(
    padded: &[u8],
    json_len: usize,
    passthrough: &qj::filter::PassthroughPath,
    out: &mut impl Write,
    had_output: &mut bool,
) -> Result<bool> {
    match passthrough {
        qj::filter::PassthroughPath::Identity => {
            // Validate that this is a single JSON document before minifying.
            // simdjson's minify doesn't reject multi-doc input (e.g., {"a":1}{"b":2}),
            // so we must verify with a parse first to avoid incorrect passthrough.
            if qj::simdjson::dom_validate(padded, json_len).is_err() {
                return Ok(false);
            }
            let minified = match qj::simdjson::minify(padded, json_len) {
                Ok(m) => m,
                Err(_) => return Ok(false),
            };
            out.write_all(&minified)?;
            out.write_all(b"\n")?;
            *had_output = true;
            Ok(true)
        }
        qj::filter::PassthroughPath::FieldLength(fields) => {
            let field_refs: Vec<&str> = fields.iter().map(|s| s.as_str()).collect();
            match qj::simdjson::dom_field_length(padded, json_len, &field_refs)? {
                Some(result) => {
                    out.write_all(&result)?;
                    out.write_all(b"\n")?;
                    *had_output = true;
                    Ok(true)
                }
                None => Ok(false),
            }
        }
        qj::filter::PassthroughPath::FieldKeys { fields, sorted } => {
            let field_refs: Vec<&str> = fields.iter().map(|s| s.as_str()).collect();
            match qj::simdjson::dom_field_keys(padded, json_len, &field_refs, *sorted)? {
                Some(result) => {
                    out.write_all(&result)?;
                    out.write_all(b"\n")?;
                    *had_output = true;
                    Ok(true)
                }
                None => Ok(false),
            }
        }
        qj::filter::PassthroughPath::FieldType(fields) => {
            let field_refs: Vec<&str> = fields.iter().map(|s| s.as_str()).collect();
            // Get the raw JSON of the target, then check first byte for type
            let raw = if field_refs.is_empty() {
                // Bare `type` — check the input directly
                // Skip leading whitespace
                let first_byte = padded[..json_len]
                    .iter()
                    .find(|&&b| !matches!(b, b' ' | b'\t' | b'\n' | b'\r'));
                match first_byte {
                    Some(b'{') => "\"object\"",
                    Some(b'[') => "\"array\"",
                    Some(b'"') => "\"string\"",
                    Some(b't') | Some(b'f') => "\"boolean\"",
                    Some(b'n') => "\"null\"",
                    Some(b'0'..=b'9') | Some(b'-') => "\"number\"",
                    _ => return Ok(false),
                }
            } else {
                let raw = qj::simdjson::dom_find_field_raw(padded, json_len, &field_refs)?;
                let first_byte = raw.first();
                match first_byte {
                    Some(b'{') => "\"object\"",
                    Some(b'[') => "\"array\"",
                    Some(b'"') => "\"string\"",
                    Some(b't') | Some(b'f') => "\"boolean\"",
                    // "null" as raw result means field missing OR actual null value
                    // jq returns "null" for both, so this is correct
                    Some(b'n') => "\"null\"",
                    Some(b'0'..=b'9') | Some(b'-') => "\"number\"",
                    _ => return Ok(false),
                }
            };
            out.write_all(raw.as_bytes())?;
            out.write_all(b"\n")?;
            *had_output = true;
            Ok(true)
        }
        qj::filter::PassthroughPath::FieldHas { fields, key } => {
            let field_refs: Vec<&str> = fields.iter().map(|s| s.as_str()).collect();
            match qj::simdjson::dom_field_has(padded, json_len, &field_refs, key)? {
                Some(result) => {
                    out.write_all(if result { b"true" } else { b"false" })?;
                    out.write_all(b"\n")?;
                    *had_output = true;
                    Ok(true)
                }
                None => Ok(false),
            }
        }
        qj::filter::PassthroughPath::ArrayMapField {
            prefix,
            fields,
            wrap_array,
        } => {
            let prefix_refs: Vec<&str> = prefix.iter().map(|s| s.as_str()).collect();
            let field_refs: Vec<&str> = fields.iter().map(|s| s.as_str()).collect();
            match qj::simdjson::dom_array_map_field(
                padded,
                json_len,
                &prefix_refs,
                &field_refs,
                *wrap_array,
            )? {
                Some(result) => {
                    out.write_all(&result)?;
                    out.write_all(b"\n")?;
                    *had_output = true;
                    Ok(true)
                }
                None => Ok(false),
            }
        }
        qj::filter::PassthroughPath::ArrayMapFieldsObj {
            prefix,
            entries,
            wrap_array,
        } => {
            let prefix_refs: Vec<&str> = prefix.iter().map(|s| s.as_str()).collect();
            let field_refs: Vec<&str> = entries.iter().map(|s| s.as_str()).collect();
            // Pre-encode JSON keys: "fieldname" (with quotes)
            let json_keys: Vec<Vec<u8>> = entries
                .iter()
                .map(|s| {
                    let mut k = Vec::with_capacity(s.len() + 2);
                    k.push(b'"');
                    k.extend_from_slice(s.as_bytes());
                    k.push(b'"');
                    k
                })
                .collect();
            let key_refs: Vec<&[u8]> = json_keys.iter().map(|k| k.as_slice()).collect();
            match qj::simdjson::dom_array_map_fields_obj(
                padded,
                json_len,
                &prefix_refs,
                &key_refs,
                &field_refs,
                *wrap_array,
            )? {
                Some(result) => {
                    out.write_all(&result)?;
                    out.write_all(b"\n")?;
                    *had_output = true;
                    Ok(true)
                }
                None => Ok(false),
            }
        }
        qj::filter::PassthroughPath::ArrayMapBuiltin {
            prefix,
            op,
            wrap_array,
        } => {
            let prefix_refs: Vec<&str> = prefix.iter().map(|s| s.as_str()).collect();
            let (op_code, sorted, arg) = match op {
                qj::filter::PassthroughBuiltin::Length => (0, true, ""),
                qj::filter::PassthroughBuiltin::Keys => (1, true, ""),
                qj::filter::PassthroughBuiltin::KeysUnsorted => (1, false, ""),
                qj::filter::PassthroughBuiltin::Type => (2, false, ""),
                qj::filter::PassthroughBuiltin::Has(key) => (3, false, key.as_str()),
            };
            match qj::simdjson::dom_array_map_builtin(
                padded,
                json_len,
                &prefix_refs,
                op_code,
                sorted,
                arg,
                *wrap_array,
            )? {
                Some(result) => {
                    out.write_all(&result)?;
                    out.write_all(b"\n")?;
                    *had_output = true;
                    Ok(true)
                }
                None => Ok(false),
            }
        }
    }
}

/// Bundled processing context to avoid too-many-arguments in process_file.
struct ProcessCtx<'a> {
    passthrough: &'a Option<qj::filter::PassthroughPath>,
    force_jsonl: bool,
    filter: &'a qj::filter::Filter,
    env: &'a qj::filter::Env,
    config: &'a qj::output::OutputConfig,
    debug_timing: bool,
}

/// Process a single file: read, detect NDJSON, try passthrough, or run the
/// normal DOM parse → eval → output pipeline. Optionally prints timing.
fn process_file(
    path: &str,
    ctx: &ProcessCtx,
    out: &mut impl Write,
    had_output: &mut bool,
    had_error: &mut bool,
    last_was_falsy: &mut bool,
) -> Result<()> {
    // ---- Compressed file handling ----
    // Decompress to memory, then process the decompressed buffer.
    // Can't use mmap or streaming NDJSON directly on compressed data.
    if qj::decompress::is_compressed(path) {
        let decompressed = qj::decompress::decompress_file(path)?;
        if decompressed.is_empty() {
            return Ok(());
        }

        // NDJSON: use Cursor as a Read+Seek source for the streaming processor
        if !ctx.debug_timing && (ctx.force_jsonl || qj::parallel::ndjson::is_ndjson(&decompressed))
        {
            let mut cursor = std::io::Cursor::new(decompressed);
            let ho = qj::parallel::ndjson::process_ndjson_streaming(
                &mut cursor,
                ctx.filter,
                ctx.config,
                ctx.env,
                out,
            )
            .with_context(|| format!("failed to process NDJSON: {path}"))?;
            *had_output |= ho;
            return Ok(());
        }

        // Single doc: pad and process
        let json_len = decompressed.len();
        let padded = qj::simdjson::pad_buffer(&decompressed);

        std::str::from_utf8(&padded[..json_len])
            .with_context(|| format!("file is not valid UTF-8: {path}"))?;

        if let Some(pt) = ctx.passthrough {
            let handled = try_passthrough(&padded, json_len, pt, out, had_output)
                .with_context(|| format!("passthrough failed: {path}"))?;
            if handled {
                return Ok(());
            }
        }

        process_padded(
            &padded,
            json_len,
            ctx.filter,
            ctx.env,
            out,
            ctx.config,
            had_output,
            had_error,
            last_was_falsy,
        )?;
        return Ok(());
    }

    // ---- Uncompressed file handling ----

    // NDJSON: mmap the file directly (no simdjson padding needed) and process
    // in parallel windows. Falls back to streaming read() if mmap is unavailable.
    // Works for files larger than physical RAM — kernel pages in on demand.
    if !ctx.debug_timing
        && let Some(ho) = qj::parallel::ndjson::process_ndjson_file(
            std::path::Path::new(path),
            ctx.filter,
            ctx.config,
            ctx.env,
            ctx.force_jsonl,
            out,
        )
        .with_context(|| format!("failed to process NDJSON: {path}"))?
    {
        *had_output |= ho;
        return Ok(());
    }

    // Non-NDJSON: load via read_padded_file (mmap with simdjson padding).
    let t0 = Instant::now();
    let (padded, json_len) = qj::simdjson::read_padded_file(std::path::Path::new(path))
        .with_context(|| format!("failed to read file: {path}"))?;
    let t_read = t0.elapsed();

    // Empty file produces no output (matches jq behavior)
    if json_len == 0 {
        return Ok(());
    }

    // Passthrough fast path
    if let Some(pt) = ctx.passthrough {
        let t1 = Instant::now();
        let handled = try_passthrough(&padded, json_len, pt, out, had_output)
            .with_context(|| format!("passthrough failed: {path}"))?;
        if handled {
            if ctx.debug_timing {
                let t_op = t1.elapsed();
                let total = t_read + t_op;
                let mb = json_len as f64 / (1024.0 * 1024.0);
                let label = match pt {
                    qj::filter::PassthroughPath::Identity => "minify",
                    qj::filter::PassthroughPath::FieldLength(_) => "length",
                    qj::filter::PassthroughPath::FieldKeys { .. } => "keys",
                    qj::filter::PassthroughPath::FieldType(_) => "type",
                    qj::filter::PassthroughPath::FieldHas { .. } => "has",
                    qj::filter::PassthroughPath::ArrayMapField { .. } => "map_field",
                    qj::filter::PassthroughPath::ArrayMapFieldsObj { .. } => "map_fields_obj",
                    qj::filter::PassthroughPath::ArrayMapBuiltin { .. } => "map_builtin",
                };
                eprintln!("--- debug-timing ({label} passthrough): {path} ({mb:.1} MB) ---");
                print_timing_line("read", t_read, total);
                print_timing_line(label, t_op, total);
                print_timing_total(total, mb);
            }
            return Ok(());
        }
        // Passthrough returned None (unsupported type) — fall through to normal pipeline
    }

    // Normal pipeline: DOM parse → eval → output
    std::str::from_utf8(&padded[..json_len])
        .with_context(|| format!("file is not valid UTF-8: {path}"))?;

    if ctx.debug_timing {
        let t1 = Instant::now();
        let input = match qj::simdjson::dom_parse_to_value(&padded, json_len) {
            Ok(v) => v,
            Err(e)
                if e.to_string().contains(&format!(
                    "simdjson error code {}",
                    qj::simdjson::SIMDJSON_CAPACITY
                )) =>
            {
                let text = std::str::from_utf8(&padded[..json_len])
                    .context("file is not valid UTF-8 (serde_json fallback)")?;
                let serde_val: serde_json::Value = serde_json::from_str(text)
                    .context("failed to parse JSON (serde_json fallback for >4GB file)")?;
                qj::value::Value::from(serde_val)
            }
            Err(e) => return Err(e).context("failed to parse JSON"),
        };
        let t_parse = t1.elapsed();

        let t2 = Instant::now();
        let mut values = Vec::new();
        qj::filter::eval::eval_filter(ctx.filter, &input, &mut |v| {
            values.push(v);
        });
        let t_eval = t2.elapsed();

        // Check for uncaught runtime errors from the debug-timing eval path
        if let Some(err) = qj::filter::eval::take_last_error() {
            *had_error = true;
            let msg = format_error(&err);
            eprintln!("qj: error: {msg}");
        }

        let t3 = Instant::now();
        for v in &values {
            *had_output = true;
            if qj::output::write_value(out, v, ctx.config).is_err() {
                break;
            }
        }
        out.flush()?;
        let t_output = t3.elapsed();

        let total = t_read + t_parse + t_eval + t_output;
        let mb = json_len as f64 / (1024.0 * 1024.0);
        eprintln!("--- debug-timing: {path} ({mb:.1} MB) ---");
        print_timing_line("read", t_read, total);
        print_timing_line("parse", t_parse, total);
        print_timing_line("eval", t_eval, total);
        print_timing_line("output", t_output, total);
        print_timing_total(total, mb);
    } else {
        process_padded(
            &padded,
            json_len,
            ctx.filter,
            ctx.env,
            out,
            ctx.config,
            had_output,
            had_error,
            last_was_falsy,
        )?;
    }

    Ok(())
}

// ---------------------------------------------------------------------------
// Input parsing helpers
// ---------------------------------------------------------------------------

/// Process --raw-input text: each line becomes a Value::String.
/// If slurp is true, concatenate all input into a single string (matches jq -Rs).
#[allow(clippy::too_many_arguments)]
fn process_raw_input(
    text: &str,
    slurp: bool,
    filter: &qj::filter::Filter,
    env: &qj::filter::Env,
    out: &mut impl Write,
    config: &qj::output::OutputConfig,
    had_output: &mut bool,
    had_error: &mut bool,
    last_was_falsy: &mut bool,
) -> Result<()> {
    if slurp {
        // jq's -Rs concatenates all input into a single string value (not an array)
        let input = qj::value::Value::String(text.to_string());
        eval_and_output(
            filter,
            &input,
            env,
            out,
            config,
            had_output,
            had_error,
            last_was_falsy,
        );
    } else {
        for line in text.lines() {
            let input = qj::value::Value::String(line.to_string());
            eval_and_output(
                filter,
                &input,
                env,
                out,
                config,
                had_output,
                had_error,
                last_was_falsy,
            );
        }
    }
    Ok(())
}

#[allow(clippy::too_many_arguments)]
fn process_padded(
    padded: &[u8],
    json_len: usize,
    filter: &qj::filter::Filter,
    env: &qj::filter::Env,
    out: &mut impl Write,
    config: &qj::output::OutputConfig,
    had_output: &mut bool,
    had_error: &mut bool,
    last_was_falsy: &mut bool,
) -> Result<()> {
    // Use flat evaluation (lazy, zero-copy) when the filter is safe for it.
    // Flat eval was designed for NDJSON and silently ignores type errors,
    // so we only use it when the filter won't produce errors that need reporting.
    if let Ok(flat_buf) = qj::simdjson::dom_parse_to_flat_buf_tape(padded, json_len) {
        let mut nul_error = false;
        let mut write_failed = false;
        qj::flat_eval::eval_flat(filter, flat_buf.root(), env, &mut |v| {
            if nul_error || write_failed {
                return;
            }
            if config.null_separator
                && let qj::value::Value::String(s) = &v
                && s.contains('\0')
            {
                nul_error = true;
                return;
            }
            *last_was_falsy = matches!(v, qj::value::Value::Null | qj::value::Value::Bool(false));
            *had_output = true;
            if qj::output::write_value(out, &v, config).is_err() {
                write_failed = true;
            }
        });
        if nul_error {
            *had_error = true;
            eprintln!("qj: error: Cannot dump a string containing NUL with --raw-output0 option");
        }
        if let Some(err) = qj::filter::eval::take_last_error() {
            *had_error = true;
            let msg = format_error(&err);
            eprintln!("qj: error: {msg}");
        }
        return Ok(());
    }

    // Regular pipeline: DOM tape walk → flat buffer → Value tree → eval → output
    let input = match qj::simdjson::dom_parse_to_value_fast(padded, json_len) {
        Ok(v) => v,
        Err(e)
            if e.to_string()
                == format!("simdjson error code {}", qj::simdjson::SIMDJSON_CAPACITY) =>
        {
            // simdjson CAPACITY limit (~4GB) — fall back to serde_json
            let text = std::str::from_utf8(&padded[..json_len])
                .context("file is not valid UTF-8 (serde_json fallback)")?;
            let serde_val: serde_json::Value = serde_json::from_str(text)
                .context("failed to parse JSON (serde_json fallback for >4GB file)")?;
            qj::value::Value::from(serde_val)
        }
        Err(e) => {
            // Try special float preprocessing (NaN, Infinity, nan, inf)
            let raw = &padded[..json_len];
            if qj::input::has_special_float_tokens_pub(raw) {
                let pp = qj::input::preprocess_special_floats_pub(raw);
                let pp_padded = qj::simdjson::pad_buffer(&pp);
                if let Ok(val) = qj::simdjson::dom_parse_to_value_fast(&pp_padded, pp.len()) {
                    let input = qj::input::fixup_special_float_sentinels_pub(val);
                    eval_and_output(
                        filter,
                        &input,
                        env,
                        out,
                        config,
                        had_output,
                        had_error,
                        last_was_falsy,
                    );
                    return Ok(());
                }
            }
            // Try multi-doc fallback: serde_json's StreamDeserializer handles
            // concatenated JSON like {"a":1}{"b":2} and whitespace-separated values.
            let text = match std::str::from_utf8(&padded[..json_len]) {
                Ok(t) => t,
                Err(_) => {
                    eprintln!("qj: error (at <stdin>): {e:#}");
                    *had_error = true;
                    return Ok(());
                }
            };
            let mut stream =
                serde_json::Deserializer::from_str(text).into_iter::<serde_json::Value>();
            let mut count = 0usize;
            let mut last_stream_err = None;
            for result in &mut stream {
                match result {
                    Ok(serde_val) => {
                        count += 1;
                        let input = qj::value::Value::from(serde_val);
                        eval_and_output(
                            filter,
                            &input,
                            env,
                            out,
                            config,
                            had_output,
                            had_error,
                            last_was_falsy,
                        );
                    }
                    Err(se) => {
                        last_stream_err = Some(se);
                        break;
                    }
                }
            }
            if count == 0 {
                // Stream produced nothing — report the original simdjson error
                eprintln!("qj: error (at <stdin>): {e:#}");
                *had_error = true;
            } else if let Some(se) = last_stream_err {
                // Partial parse — some docs succeeded, then an error
                eprintln!("qj: error (at <stdin>): {se}");
                *had_error = true;
            }
            return Ok(());
        }
    };
    eval_and_output(
        filter,
        &input,
        env,
        out,
        config,
        had_output,
        had_error,
        last_was_falsy,
    );
    Ok(())
}

// ---------------------------------------------------------------------------
// Debug timing helpers
// ---------------------------------------------------------------------------

fn print_timing_line(label: &str, dur: Duration, total: Duration) {
    let pct = if total.as_nanos() > 0 {
        dur.as_secs_f64() / total.as_secs_f64() * 100.0
    } else {
        0.0
    };
    eprintln!(
        "  {label:<7} {:>8.2}ms  ({pct:.0}%)",
        dur.as_secs_f64() * 1000.0,
    );
}

fn print_timing_total(total: Duration, mb: f64) {
    eprintln!(
        "  total:  {:>8.2}ms  ({:.0} MB/s)",
        total.as_secs_f64() * 1000.0,
        mb / total.as_secs_f64()
    );
}