jetro-core 0.5.2

jetro-core: parser, compiler, and VM for the Jetro JSON query language
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
//! Forward-flow static analyses over compiled `Program` IR.
//!
//! Analyses run on the flat `Arc<[Opcode]>` representation after compilation.
//! They are conservative (return the `Unknown` top element when uncertain)
//! and used by the compiler for peephole specialisation and by the planner
//! for CSE (`dedup_subprograms`). None affect runtime correctness.

use std::collections::HashMap;
use std::sync::Arc;

use crate::parse::ast::KindType;
use crate::vm::{CompiledPipeStep, Opcode, Program};
use crate::builtins::BuiltinMethod;


/// Type lattice element. Ordered: `Bottom` ⊑ concrete types ⊑ `Unknown`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum VType {
    /// Unreachable position; join with any type yields that type.
    Bottom,
    /// Definitely `Val::Null`.
    Null,
    /// Definitely `Val::Bool`.
    Bool,
    /// Definitely `Val::Int` (i64).
    Int,
    /// Definitely `Val::Float` (f64).
    Float,
    /// Either `Int` or `Float`; the join of both concrete numeric types.
    Num,
    /// Definitely a string value.
    Str,
    /// Definitely `Val::Arr`.
    Arr,
    /// Definitely `Val::Obj`.
    Obj,
    /// Any type possible — top element, used when analysis cannot determine the type.
    Unknown,
}

impl VType {
    /// Lattice join: return the least upper bound of `self` and `other`.
    /// `Int ⊔ Float = Num`; incompatible concrete types collapse to `Unknown`.
    pub fn join(self, other: VType) -> VType {
        if self == other {
            return self;
        }
        match (self, other) {
            (VType::Bottom, x) | (x, VType::Bottom) => x,
            (VType::Int, VType::Float)
            | (VType::Float, VType::Int)
            | (VType::Int, VType::Num)
            | (VType::Num, VType::Int)
            | (VType::Float, VType::Num)
            | (VType::Num, VType::Float) => VType::Num,
            _ => VType::Unknown,
        }
    }

    /// Return `true` only for `Arr`; used to guard array-specific optimisations.
    pub fn is_array_like(self) -> bool {
        matches!(self, VType::Arr)
    }
    /// Return `true` only for `Obj`; used to guard object-specific optimisations.
    pub fn is_object_like(self) -> bool {
        matches!(self, VType::Obj)
    }
    /// Return `true` for any numeric variant (`Int`, `Float`, or `Num`).
    pub fn is_numeric(self) -> bool {
        matches!(self, VType::Int | VType::Float | VType::Num)
    }
    /// Return `true` only when the type is definitely a string.
    pub fn is_string(self) -> bool {
        matches!(self, VType::Str)
    }
}


/// Nullness lattice element tracking whether a value can ever be `null`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Nullness {
    /// The value is always `Val::Null` at this program point.
    AlwaysNull,
    /// The value is never null at this program point.
    NonNull,
    /// The value may or may not be null; the conservative top element.
    MaybeNull,
}

impl Nullness {
    /// Lattice join: any disagreement between `AlwaysNull` and `NonNull` yields `MaybeNull`.
    pub fn join(self, other: Nullness) -> Nullness {
        if self == other {
            return self;
        }
        Nullness::MaybeNull
    }
}


/// Cardinality lattice element describing how many values a program position produces.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Cardinality {
    /// Produces no values (empty result / unreachable branch).
    Zero,
    /// Produces exactly one value.
    One,
    /// Produces zero or one values (e.g. optional field access).
    ZeroOrOne,
    /// Produces two or more values (array output).
    Many,
    /// The value is a scalar — not wrapped in an array.
    NotArray,
    /// Cardinality is indeterminate; conservative top element.
    Unknown,
}

impl Cardinality {
    /// Lattice join: `Zero ⊔ One = ZeroOrOne`; all other mixed pairs collapse to `Unknown`.
    pub fn join(self, other: Cardinality) -> Cardinality {
        if self == other {
            return self;
        }
        match (self, other) {
            (Cardinality::Zero, Cardinality::One) | (Cardinality::One, Cardinality::Zero) => {
                Cardinality::ZeroOrOne
            }
            _ => Cardinality::Unknown,
        }
    }
}


/// Product of all three lattice dimensions for a single program point.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AbstractVal {
    /// Inferred type of the value.
    pub ty: VType,
    /// Nullness of the value.
    pub null: Nullness,
    /// Cardinality (scalar vs. array, count) of the value.
    pub card: Cardinality,
}

impl AbstractVal {
    /// Fully conservative element; used as the initial stack value and when analysis fails.
    pub const UNKNOWN: Self = Self {
        ty: VType::Unknown,
        null: Nullness::MaybeNull,
        card: Cardinality::Unknown,
    };
    /// Abstract value for a definite null literal.
    pub const NULL: Self = Self {
        ty: VType::Null,
        null: Nullness::AlwaysNull,
        card: Cardinality::NotArray,
    };
    /// Construct an abstract scalar (non-null, non-array) with the given type.
    pub fn scalar(ty: VType) -> Self {
        Self {
            ty,
            null: Nullness::NonNull,
            card: Cardinality::NotArray,
        }
    }
    /// Construct the canonical abstract value for a non-null array result.
    pub fn array() -> Self {
        Self {
            ty: VType::Arr,
            null: Nullness::NonNull,
            card: Cardinality::Many,
        }
    }
    /// Construct the canonical abstract value for a non-null object result.
    pub fn object() -> Self {
        Self {
            ty: VType::Obj,
            null: Nullness::NonNull,
            card: Cardinality::NotArray,
        }
    }
    /// Component-wise lattice join over all three dimensions.
    pub fn join(self, other: AbstractVal) -> AbstractVal {
        AbstractVal {
            ty: self.ty.join(other.ty),
            null: self.null.join(other.null),
            card: self.card.join(other.card),
        }
    }
}


/// Run the forward-flow type analysis over `program` and return the abstract
/// value at the top of the stack after the last opcode.
pub fn infer_result_type(program: &Program) -> AbstractVal {
    let mut stack: Vec<AbstractVal> = Vec::with_capacity(16);
    let mut env: HashMap<Arc<str>, AbstractVal> = HashMap::new();
    for op in program.ops.iter() {
        apply_op_env(op, &mut stack, &mut env);
    }
    stack.pop().unwrap_or(AbstractVal::UNKNOWN)
}


/// Like `infer_result_type` but also returns the variable environment so the
/// caller can inspect inferred types for named bindings.
pub fn infer_result_type_with_env(
    program: &Program,
) -> (AbstractVal, HashMap<Arc<str>, AbstractVal>) {
    let mut stack: Vec<AbstractVal> = Vec::with_capacity(16);
    let mut env: HashMap<Arc<str>, AbstractVal> = HashMap::new();
    for op in program.ops.iter() {
        apply_op_env(op, &mut stack, &mut env);
    }
    (stack.pop().unwrap_or(AbstractVal::UNKNOWN), env)
}

/// Apply a single opcode to the abstract stack, threading the variable environment
/// for `LetExpr` and `LoadIdent`; delegates to `apply_op` for all other opcodes.
fn apply_op_env(
    op: &Opcode,
    stack: &mut Vec<AbstractVal>,
    env: &mut HashMap<Arc<str>, AbstractVal>,
) {
    // Handle the two opcodes that read/write the variable environment.
    match op {
        Opcode::LoadIdent(name) => {
            let av = env.get(name).copied().unwrap_or(AbstractVal::UNKNOWN);
            stack.push(av);
        }
        Opcode::LetExpr { name, body } => {
            let init = stack.pop().unwrap_or(AbstractVal::UNKNOWN);
            let saved = env.get(name).copied();
            env.insert(name.clone(), init);
            let mut sub_stack: Vec<AbstractVal> = Vec::with_capacity(8);
            for op2 in body.ops.iter() {
                apply_op_env(op2, &mut sub_stack, env);
            }
            let res = sub_stack.pop().unwrap_or(AbstractVal::UNKNOWN);
            // Restore the variable environment to its state before the let binding.
            match saved {
                Some(v) => {
                    env.insert(name.clone(), v);
                }
                None => {
                    env.remove(name);
                }
            }
            stack.push(res);
        }
        _ => apply_op(op, stack),
    }
}

/// Apply a single opcode to the abstract stack, producing abstract output values
/// from abstract input values without touching the variable environment.
fn apply_op(op: &Opcode, stack: &mut Vec<AbstractVal>) {
    macro_rules! pop2 {
        () => {{
            let r = stack.pop().unwrap_or(AbstractVal::UNKNOWN);
            let l = stack.pop().unwrap_or(AbstractVal::UNKNOWN);
            (l, r)
        }};
    }
    macro_rules! pop1 {
        () => {
            stack.pop().unwrap_or(AbstractVal::UNKNOWN)
        };
    }
    match op {
        Opcode::PushNull => stack.push(AbstractVal::NULL),
        Opcode::PushBool(_) => stack.push(AbstractVal::scalar(VType::Bool)),
        Opcode::PushInt(_) => stack.push(AbstractVal::scalar(VType::Int)),
        Opcode::PushFloat(_) => stack.push(AbstractVal::scalar(VType::Float)),
        Opcode::PushStr(_) => stack.push(AbstractVal::scalar(VType::Str)),
        Opcode::PushRoot | Opcode::PushCurrent | Opcode::LoadIdent(_) => {
            stack.push(AbstractVal::UNKNOWN)
        }
        Opcode::GetField(_) | Opcode::OptField(_) | Opcode::FieldChain(_) => {
            pop1!();
            stack.push(AbstractVal::UNKNOWN);
        }
        Opcode::GetIndex(_) | Opcode::DynIndex(_) => {
            pop1!();
            stack.push(AbstractVal::UNKNOWN);
        }
        Opcode::GetSlice(_, _) => {
            pop1!();
            stack.push(AbstractVal::array());
        }
        Opcode::Descendant(_) | Opcode::DescendAll => {
            pop1!();
            stack.push(AbstractVal::array());
        }
        Opcode::InlineFilter(_) => {
            pop1!();
            stack.push(AbstractVal::array());
        }
        Opcode::Quantifier(kind) => {
            pop1!();
            use crate::parse::ast::QuantifierKind;
            let card = match kind {
                QuantifierKind::First => Cardinality::ZeroOrOne,
                QuantifierKind::One => Cardinality::One,
            };
            stack.push(AbstractVal {
                ty: VType::Unknown,
                null: Nullness::MaybeNull,
                card,
            });
        }
        Opcode::RootChain(_) => stack.push(AbstractVal::UNKNOWN),
        Opcode::Add | Opcode::Sub | Opcode::Mul | Opcode::Mod => {
            let (l, r) = pop2!();
            stack.push(AbstractVal::scalar(l.ty.join(r.ty)));
        }
        Opcode::Div => {
            pop2!();
            stack.push(AbstractVal::scalar(VType::Float));
        }
        Opcode::Eq
        | Opcode::Neq
        | Opcode::Lt
        | Opcode::Lte
        | Opcode::Gt
        | Opcode::Gte
        | Opcode::Fuzzy => {
            pop2!();
            stack.push(AbstractVal::scalar(VType::Bool));
        }
        Opcode::Not => {
            pop1!();
            stack.push(AbstractVal::scalar(VType::Bool));
        }
        Opcode::Neg => {
            let v = pop1!();
            stack.push(AbstractVal::scalar(v.ty));
        }
        Opcode::AndOp(_) | Opcode::OrOp(_) => {
            pop1!();
            stack.push(AbstractVal::scalar(VType::Bool));
        }
        Opcode::CoalesceOp(_) => {
            pop1!();
            stack.push(AbstractVal::UNKNOWN);
        }
        Opcode::IfElse { .. } => {
            pop1!();
            stack.push(AbstractVal::UNKNOWN);
        }
        Opcode::TryExpr { .. } => {
            stack.push(AbstractVal::UNKNOWN);
        }
        Opcode::CallMethod(call) | Opcode::CallOptMethod(call) => {
            pop1!();
            stack.push(method_result_type(call.method));
        }
        Opcode::MakeObj(_) => stack.push(AbstractVal::object()),
        Opcode::MakeArr(_) => stack.push(AbstractVal::array()),
        Opcode::FString(_) => stack.push(AbstractVal::scalar(VType::Str)),
        Opcode::KindCheck { .. } => {
            pop1!();
            stack.push(AbstractVal::scalar(VType::Bool));
        }
        Opcode::SetCurrent => {} // Side-effecting; does not push a value.
        Opcode::LetExpr { .. } => {
            pop1!();
            stack.push(AbstractVal::UNKNOWN);
        }
        Opcode::ListComp(_) | Opcode::SetComp(_) => stack.push(AbstractVal::array()),
        Opcode::DictComp(_) => stack.push(AbstractVal::object()),
        Opcode::PatchEval(_) => stack.push(AbstractVal::UNKNOWN),
        Opcode::CastOp(ty) => {
            pop1!();
            use crate::parse::ast::CastType;
            let av = match ty {
                CastType::Int => AbstractVal::scalar(VType::Int),
                CastType::Float => AbstractVal::scalar(VType::Float),
                CastType::Number => AbstractVal::scalar(VType::Num),
                CastType::Str => AbstractVal::scalar(VType::Str),
                CastType::Bool => AbstractVal::scalar(VType::Bool),
                CastType::Array => AbstractVal::array(),
                CastType::Object => AbstractVal::object(),
                CastType::Null => AbstractVal::NULL,
            };
            stack.push(av);
        }
        Opcode::PipelineRun { .. } => stack.push(AbstractVal::UNKNOWN),
        Opcode::DeleteMarkErr => stack.push(AbstractVal::UNKNOWN),
        Opcode::Match(_) => stack.push(AbstractVal::UNKNOWN),
        Opcode::DeepMatchAll(_) => stack.push(AbstractVal::UNKNOWN),
        Opcode::DeepMatchFirst(_) => stack.push(AbstractVal::UNKNOWN),
    }
}


/// Return the statically known result type of a builtin method call.
/// Grouped by return-type family; methods whose return type is data-dependent
/// fall through to `AbstractVal::UNKNOWN`.
pub fn method_result_type(m: BuiltinMethod) -> AbstractVal {
    use BuiltinMethod::*;
    match m {
        // Integer-returning methods.
        Len | Count | Sum | ApproxCountDistinct | IndexOf | LastIndexOf | ByteLen | ParseInt
        | Ceil | Floor | Round => AbstractVal::scalar(VType::Int),
        // Boolean-returning methods.
        Any | All | Has | Missing | Includes | StartsWith | EndsWith | IsBlank | IsNumeric
        | IsAlpha | IsAscii | ParseBool | ReMatch | ContainsAny | ContainsAll => {
            AbstractVal::scalar(VType::Bool)
        }
        // String-returning methods.
        Upper | Lower | Capitalize | TitleCase | Trim | TrimLeft | TrimRight | ToString
        | ToJson | ToBase64 | FromBase64 | UrlEncode | UrlDecode | HtmlEscape | HtmlUnescape
        | Repeat | PadLeft | PadRight | Replace | ReplaceAll | StripPrefix | StripSuffix
        | Indent | Dedent | Join | ToCsv | ToTsv | Type | SnakeCase | KebabCase | CamelCase
        | PascalCase | ReverseStr | Center => AbstractVal::scalar(VType::Str),
        // Float-returning methods.
        Avg | ParseFloat => AbstractVal::scalar(VType::Float),
        // Polymorphic-numeric methods; exact type depends on input.
        Min | Max | ToNumber | Abs => AbstractVal::scalar(VType::Num),
        // Explicit bool coercion.
        ToBool => AbstractVal::scalar(VType::Bool),
        // Array-returning methods (includes collection, transform, and window operations).
        Keys | Values | Entries | ToPairs | Reverse | Unique | Collect | Flatten | Compact
        | Chars | CharsOf | Lines | Words | Split | Sort | Filter | Map | FlatMap | Find
        | FindAll | UniqueBy | DeepFind | DeepShape | DeepLike | IndicesWhere | Fanout
        | TracePath | Enumerate | Pairwise | Window | Chunk | TakeWhile | DropWhile | Take
        | Skip | Accumulate | Zip | ZipLongest | Diff | Intersect | Union | Append | Prepend
        | Remove | Matches | Scan | Slice | Bytes | IndicesOf | Explode | Implode | RollingSum
        | RollingAvg | RollingMin | RollingMax | Lag | Lead | DiffWindow | PctChange | CumMax
        | CumMin | Zscore => AbstractVal::array(),
        // Object-returning methods.
        FromPairs | Invert | Pick | Omit | Merge | DeepMerge | Defaults | Rename
        | TransformKeys | TransformValues | FilterKeys | FilterValues | Pivot | GroupBy
        | CountBy | IndexBy | GroupShape | ZipShape | Partition | FlattenKeys | UnflattenKeys
        | SetPath | DelPath | DelPaths | Update | Schema => AbstractVal::object(),
        // Scalar-returning methods whose type cannot be determined without runtime information.
        First | Last | Nth | FindFirst | FindOne | FindIndex | MaxBy | MinBy | Walk | WalkPre
        | Rec | GetPath | ReMatchFirst | ReCaptures => AbstractVal::UNKNOWN,
        HasPath => AbstractVal::scalar(VType::Bool),
        ReMatchAll | ReCapturesAll | ReSplit => AbstractVal::array(),
        ReReplace | ReReplaceAll => AbstractVal::scalar(VType::Str),
        FromJson | Or | Set | Index => AbstractVal::UNKNOWN,
        EquiJoin => AbstractVal::array(),
        Unknown => AbstractVal::UNKNOWN,
    }
}


/// Count how many times `name` is referenced as `Opcode::LoadIdent` across
/// `program` and all nested sub-programs; used for inlining decisions.
pub fn count_ident_uses(program: &Program, name: &str) -> usize {
    let mut n = 0;
    count_ident_uses_in_ops(&program.ops, name, &mut n);
    n
}

/// Recursive helper for `count_ident_uses`; descends into every embedded `Program`.
fn count_ident_uses_in_ops(ops: &[Opcode], name: &str, acc: &mut usize) {
    for op in ops {
        match op {
            Opcode::LoadIdent(s) if s.as_ref() == name => *acc += 1,
            Opcode::AndOp(p)
            | Opcode::OrOp(p)
            | Opcode::CoalesceOp(p)
            | Opcode::InlineFilter(p)
            | Opcode::DynIndex(p) => count_ident_uses_in_ops(&p.ops, name, acc),
            Opcode::IfElse { then_, else_ } => {
                count_ident_uses_in_ops(&then_.ops, name, acc);
                count_ident_uses_in_ops(&else_.ops, name, acc);
            }
            Opcode::CallMethod(c) | Opcode::CallOptMethod(c) => {
                for p in c.sub_progs.iter() {
                    count_ident_uses_in_ops(&p.ops, name, acc);
                }
            }
            Opcode::LetExpr { body, .. } => count_ident_uses_in_ops(&body.ops, name, acc),
            Opcode::ListComp(spec) | Opcode::SetComp(spec) => {
                count_ident_uses_in_ops(&spec.expr.ops, name, acc);
                count_ident_uses_in_ops(&spec.iter.ops, name, acc);
                if let Some(c) = &spec.cond {
                    count_ident_uses_in_ops(&c.ops, name, acc);
                }
            }
            Opcode::DictComp(spec) => {
                count_ident_uses_in_ops(&spec.key.ops, name, acc);
                count_ident_uses_in_ops(&spec.val.ops, name, acc);
                count_ident_uses_in_ops(&spec.iter.ops, name, acc);
                if let Some(c) = &spec.cond {
                    count_ident_uses_in_ops(&c.ops, name, acc);
                }
            }
            Opcode::MakeObj(entries) => {
                use crate::vm::CompiledObjEntry;
                for e in entries.iter() {
                    match e {
                        CompiledObjEntry::Short { .. } => {}
                        CompiledObjEntry::Kv { prog, cond, .. } => {
                            count_ident_uses_in_ops(&prog.ops, name, acc);
                            if let Some(c) = cond {
                                count_ident_uses_in_ops(&c.ops, name, acc);
                            }
                        }
                        CompiledObjEntry::KvPath { .. } => {}
                        CompiledObjEntry::Dynamic { key, val } => {
                            count_ident_uses_in_ops(&key.ops, name, acc);
                            count_ident_uses_in_ops(&val.ops, name, acc);
                        }
                        CompiledObjEntry::Spread(p) => count_ident_uses_in_ops(&p.ops, name, acc),
                        CompiledObjEntry::SpreadDeep(p) => {
                            count_ident_uses_in_ops(&p.ops, name, acc)
                        }
                    }
                }
            }
            Opcode::MakeArr(progs) => {
                for (p, _) in progs.iter() {
                    count_ident_uses_in_ops(&p.ops, name, acc);
                }
            }
            Opcode::FString(parts) => {
                use crate::vm::CompiledFSPart;
                for p in parts.iter() {
                    if let CompiledFSPart::Interp { prog, .. } = p {
                        count_ident_uses_in_ops(&prog.ops, name, acc);
                    }
                }
            }
            _ => {}
        }
    }
}


/// Collect every field name statically accessed by `program` (via `GetField`,
/// `OptField`, `Descendant`, or `RootChain`). De-duplicated; order is discovery order.
pub fn collect_accessed_fields(program: &Program) -> Vec<Arc<str>> {
    let mut set = Vec::new();
    collect_fields_in_ops(&program.ops, &mut set);
    set
}

/// Recursive helper for `collect_accessed_fields`.
fn collect_fields_in_ops(ops: &[Opcode], acc: &mut Vec<Arc<str>>) {
    for op in ops {
        match op {
            Opcode::GetField(k) | Opcode::OptField(k) | Opcode::Descendant(k) => {
                if !acc.iter().any(|a: &Arc<str>| a == k) {
                    acc.push(k.clone());
                }
            }
            Opcode::RootChain(chain) => {
                for k in chain.iter() {
                    if !acc.iter().any(|a: &Arc<str>| a == k) {
                        acc.push(k.clone());
                    }
                }
            }
            Opcode::AndOp(p)
            | Opcode::OrOp(p)
            | Opcode::CoalesceOp(p)
            | Opcode::InlineFilter(p)
            | Opcode::DynIndex(p) => collect_fields_in_ops(&p.ops, acc),
            Opcode::IfElse { then_, else_ } => {
                collect_fields_in_ops(&then_.ops, acc);
                collect_fields_in_ops(&else_.ops, acc);
            }
            Opcode::CallMethod(c) | Opcode::CallOptMethod(c) => {
                for p in c.sub_progs.iter() {
                    collect_fields_in_ops(&p.ops, acc);
                }
            }
            Opcode::LetExpr { body, .. } => collect_fields_in_ops(&body.ops, acc),
            _ => {}
        }
    }
}


/// Compute a structural hash of `program` that identifies its opcode sequence.
/// Used as a key for CSE deduplication and the compiled-program cache.
pub fn program_signature(program: &Program) -> u64 {
    use std::collections::hash_map::DefaultHasher;
    use std::hash::Hasher;
    let mut h = DefaultHasher::new();
    hash_ops(&program.ops, &mut h);
    h.finish()
}

/// Recursively hash an opcode slice; only structurally significant fields are hashed
/// (discriminant + key literals + sub-program signatures).
fn hash_ops(ops: &[Opcode], h: &mut impl std::hash::Hasher) {
    use std::hash::Hash;
    for op in ops {
        // Always hash the variant discriminant so different opcodes don't collide.
        std::mem::discriminant(op).hash(h);
        match op {
            Opcode::PushInt(n) => n.hash(h),
            Opcode::PushStr(s) => s.as_bytes().hash(h),
            Opcode::PushBool(b) => b.hash(h),
            Opcode::GetField(k)
            | Opcode::OptField(k)
            | Opcode::Descendant(k)
            | Opcode::LoadIdent(k) => k.as_bytes().hash(h),
            Opcode::GetIndex(i) => i.hash(h),
            Opcode::CallMethod(c) | Opcode::CallOptMethod(c) => {
                (c.method as u8).hash(h);
                for p in c.sub_progs.iter() {
                    hash_ops(&p.ops, h);
                }
            }
            Opcode::AndOp(p)
            | Opcode::OrOp(p)
            | Opcode::CoalesceOp(p)
            | Opcode::InlineFilter(p)
            | Opcode::DynIndex(p) => hash_ops(&p.ops, h),
            Opcode::IfElse { then_, else_ } => {
                hash_ops(&then_.ops, h);
                hash_ops(&else_.ops, h);
            }
            Opcode::RootChain(chain) => {
                for k in chain.iter() {
                    k.as_bytes().hash(h);
                }
            }
            Opcode::MakeObj(entries) => {
                use crate::vm::CompiledObjEntry;
                for e in entries.iter() {
                    match e {
                        CompiledObjEntry::Short { name, .. } => {
                            0u8.hash(h);
                            name.as_bytes().hash(h);
                        }
                        CompiledObjEntry::Kv {
                            key,
                            prog,
                            optional,
                            cond,
                        } => {
                            1u8.hash(h);
                            key.as_bytes().hash(h);
                            optional.hash(h);
                            hash_ops(&prog.ops, h);
                            if let Some(c) = cond {
                                hash_ops(&c.ops, h);
                            }
                        }
                        CompiledObjEntry::KvPath {
                            key,
                            steps,
                            optional,
                            ..
                        } => {
                            2u8.hash(h);
                            key.as_bytes().hash(h);
                            optional.hash(h);
                            for st in steps.iter() {
                                use crate::vm::KvStep;
                                match st {
                                    KvStep::Field(f) => {
                                        0u8.hash(h);
                                        f.as_bytes().hash(h);
                                    }
                                    KvStep::Index(i) => {
                                        1u8.hash(h);
                                        i.hash(h);
                                    }
                                }
                            }
                        }
                        CompiledObjEntry::Dynamic { key, val } => {
                            3u8.hash(h);
                            hash_ops(&key.ops, h);
                            hash_ops(&val.ops, h);
                        }
                        CompiledObjEntry::Spread(p) => {
                            4u8.hash(h);
                            hash_ops(&p.ops, h);
                        }
                        CompiledObjEntry::SpreadDeep(p) => {
                            5u8.hash(h);
                            hash_ops(&p.ops, h);
                        }
                    }
                }
            }
            Opcode::MakeArr(entries) => {
                for (p, sp) in entries.iter() {
                    sp.hash(h);
                    hash_ops(&p.ops, h);
                }
            }
            _ => {}
        }
    }
}


/// Walk `program` and its nested sub-programs, recording every sub-program
/// signature and how many times it appears; entries with count ≥ 2 are CSE candidates.
pub fn find_common_subexprs(program: &Program) -> HashMap<u64, usize> {
    let mut map: HashMap<u64, usize> = HashMap::new();
    walk_subprograms(&program.ops, &mut map);
    map.retain(|_, &mut n| n >= 2);
    map
}

/// Recursive helper for `find_common_subexprs`; increments a counter for each
/// sub-program encountered and recurses into its opcodes.
fn walk_subprograms(ops: &[Opcode], map: &mut HashMap<u64, usize>) {
    for op in ops {
        let sub_progs: Vec<&Arc<Program>> = match op {
            Opcode::AndOp(p)
            | Opcode::OrOp(p)
            | Opcode::CoalesceOp(p)
            | Opcode::InlineFilter(p)
            | Opcode::DynIndex(p) => vec![p],
            Opcode::IfElse { then_, else_ } => vec![then_, else_],
            Opcode::CallMethod(c) | Opcode::CallOptMethod(c) => c.sub_progs.iter().collect(),
            Opcode::LetExpr { body, .. } => vec![body],
            Opcode::MakeArr(progs) => progs.iter().map(|(p, _)| p).collect(),
            Opcode::MakeObj(entries) => {
                use crate::vm::CompiledObjEntry;
                let mut v = Vec::new();
                for e in entries.iter() {
                    match e {
                        CompiledObjEntry::Short { .. } => {}
                        CompiledObjEntry::Kv { prog, cond, .. } => {
                            v.push(prog);
                            if let Some(c) = cond {
                                v.push(c);
                            }
                        }
                        CompiledObjEntry::KvPath { .. } => {}
                        CompiledObjEntry::Dynamic { key, val } => {
                            v.push(key);
                            v.push(val);
                        }
                        CompiledObjEntry::Spread(p) => v.push(p),
                        CompiledObjEntry::SpreadDeep(p) => v.push(p),
                    }
                }
                v
            }
            _ => continue,
        };
        for p in sub_progs {
            let sig = program_signature(p);
            *map.entry(sig).or_insert(0) += 1;
            walk_subprograms(&p.ops, map);
        }
    }
}


/// Return `true` when `expr` contains a free reference to the variable `name`,
/// respecting lexical scope (bindings introduced inside comprehensions / lambdas / let shadow `name`).
pub fn expr_uses_ident(expr: &crate::parse::ast::Expr, name: &str) -> bool {
    use crate::parse::ast::{Arg, ArrayElem, BindTarget, Expr, FStringPart, ObjField, PipeStep, Step};
    match expr {
        Expr::Ident(n) => n == name,
        Expr::Null
        | Expr::Bool(_)
        | Expr::Int(_)
        | Expr::Float(_)
        | Expr::Str(_)
        | Expr::Root
        | Expr::Current => false,
        Expr::FString(parts) => parts.iter().any(|p| match p {
            FStringPart::Lit(_) => false,
            FStringPart::Interp { expr, .. } => expr_uses_ident(expr, name),
        }),
        Expr::Chain(base, steps) => {
            if expr_uses_ident(base, name) {
                return true;
            }
            steps.iter().any(|s| match s {
                Step::DynIndex(e) | Step::InlineFilter(e) => expr_uses_ident(e, name),
                Step::Method(_, args) | Step::OptMethod(_, args) => args.iter().any(|a| match a {
                    Arg::Pos(e) | Arg::Named(_, e) => expr_uses_ident(e, name),
                }),
                _ => false,
            })
        }
        Expr::BinOp(l, _, r) => expr_uses_ident(l, name) || expr_uses_ident(r, name),
        Expr::UnaryNeg(e) | Expr::Not(e) => expr_uses_ident(e, name),
        Expr::Kind { expr, .. } => expr_uses_ident(expr, name),
        Expr::Coalesce(l, r) => expr_uses_ident(l, name) || expr_uses_ident(r, name),
        Expr::Object(fields) => fields.iter().any(|f| match f {
            ObjField::Kv { val, cond, .. } => {
                expr_uses_ident(val, name)
                    || cond.as_ref().map_or(false, |c| expr_uses_ident(c, name))
            }
            ObjField::Short(n) => n == name,
            ObjField::Dynamic { key, val } => {
                expr_uses_ident(key, name) || expr_uses_ident(val, name)
            }
            ObjField::Spread(e) => expr_uses_ident(e, name),
            ObjField::SpreadDeep(e) => expr_uses_ident(e, name),
        }),
        Expr::Array(elems) => elems.iter().any(|e| match e {
            ArrayElem::Expr(e) | ArrayElem::Spread(e) => expr_uses_ident(e, name),
        }),
        Expr::Pipeline { base, steps } => {
            if expr_uses_ident(base, name) {
                return true;
            }
            steps.iter().any(|s| match s {
                PipeStep::Forward(e) => expr_uses_ident(e, name),
                PipeStep::Bind(bt) => match bt {
                    BindTarget::Name(n) => n == name,
                    BindTarget::Obj { fields, rest } => {
                        fields.iter().any(|f| f == name)
                            || rest.as_ref().map_or(false, |r| r == name)
                    }
                    BindTarget::Arr(ns) => ns.iter().any(|n| n == name),
                },
            })
        }
        Expr::ListComp {
            expr,
            vars,
            iter,
            cond,
        }
        | Expr::SetComp {
            expr,
            vars,
            iter,
            cond,
        }
        | Expr::GenComp {
            expr,
            vars,
            iter,
            cond,
        } => {
            if expr_uses_ident(iter, name) {
                return true;
            }
            if vars.iter().any(|v| v == name) {
                return false; // `name` is shadowed by the comprehension binding.
            }
            expr_uses_ident(expr, name) || cond.as_ref().map_or(false, |c| expr_uses_ident(c, name))
        }
        Expr::DictComp {
            key,
            val,
            vars,
            iter,
            cond,
        } => {
            if expr_uses_ident(iter, name) {
                return true;
            }
            if vars.iter().any(|v| v == name) {
                return false; // `name` is shadowed by the comprehension binding.
            }
            expr_uses_ident(key, name)
                || expr_uses_ident(val, name)
                || cond.as_ref().map_or(false, |c| expr_uses_ident(c, name))
        }
        Expr::Lambda { params, body } => {
            if params.iter().any(|p| p == name) {
                return false; // Parameter shadows the outer binding.
            }
            expr_uses_ident(body, name)
        }
        Expr::Let {
            name: n,
            init,
            body,
        } => {
            if expr_uses_ident(init, name) {
                return true;
            }
            if n == name {
                return false; // The let binding itself shadows `name` in `body`.
            }
            expr_uses_ident(body, name)
        }
        Expr::IfElse { cond, then_, else_ } => {
            expr_uses_ident(cond, name)
                || expr_uses_ident(then_, name)
                || expr_uses_ident(else_, name)
        }
        Expr::Try { body, default } => {
            expr_uses_ident(body, name) || expr_uses_ident(default, name)
        }
        Expr::GlobalCall { args, .. } => args.iter().any(|a| match a {
            Arg::Pos(e) | Arg::Named(_, e) => expr_uses_ident(e, name),
        }),
        Expr::Cast { expr, .. } => expr_uses_ident(expr, name),
        Expr::Patch { root, ops } => {
            use crate::parse::ast::PathStep;
            if expr_uses_ident(root, name) {
                return true;
            }
            ops.iter().any(|op| {
                op.path.iter().any(|s| match s {
                    PathStep::WildcardFilter(e) => expr_uses_ident(e, name),
                    _ => false,
                }) || expr_uses_ident(&op.val, name)
                    || op.cond.as_ref().map_or(false, |c| expr_uses_ident(c, name))
            })
        }
        Expr::DeleteMark => false,
        Expr::Match { scrutinee, arms } => {
            expr_uses_ident(scrutinee, name)
                || arms.iter().any(|a| {
                    a.guard.as_ref().is_some_and(|g| expr_uses_ident(g, name))
                        || expr_uses_ident(&a.body, name)
                })
        }
    }
}


/// Return `true` when `expr` is side-effect-free and may be safely eliminated
/// or reordered. Conservatively returns `true` for most compound forms.
pub fn expr_is_pure(expr: &crate::parse::ast::Expr) -> bool {
    use crate::parse::ast::{Arg, Expr, Step};
    match expr {
        Expr::Null
        | Expr::Bool(_)
        | Expr::Int(_)
        | Expr::Float(_)
        | Expr::Str(_)
        | Expr::Root
        | Expr::Current
        | Expr::Ident(_) => true,
        Expr::FString(_) => true,
        Expr::Chain(base, steps) => {
            if !expr_is_pure(base) {
                return false;
            }
            steps.iter().all(|s| match s {
                Step::DynIndex(e) | Step::InlineFilter(e) => expr_is_pure(e),
                Step::Method(_, args) | Step::OptMethod(_, args) => args.iter().all(|a| match a {
                    Arg::Pos(e) | Arg::Named(_, e) => expr_is_pure(e),
                }),
                _ => true,
            })
        }
        Expr::BinOp(l, _, r) | Expr::Coalesce(l, r) => expr_is_pure(l) && expr_is_pure(r),
        Expr::UnaryNeg(e) | Expr::Not(e) | Expr::Kind { expr: e, .. } => expr_is_pure(e),
        // Conservatively treat all other forms (lambdas, patches, comprehensions) as pure
        // since they don't mutate shared state in the current runtime.
        _ => true,
    }
}


/// CSE pass over `program`: replace duplicate sub-programs (identified by
/// `program_signature`) with shared `Arc` pointers, reducing re-compilation and
/// memory pressure in programs with repeated sub-expressions.
pub fn dedup_subprograms(program: &Program) -> Arc<Program> {
    let mut cache: HashMap<u64, Arc<Program>> = HashMap::new();
    dedup_rec(program, &mut cache)
}

/// Recursive implementation of `dedup_subprograms`; returns a cached `Arc<Program>`
/// if one with the same signature already exists, otherwise rebuilds with deduped children.
fn dedup_rec(program: &Program, cache: &mut HashMap<u64, Arc<Program>>) -> Arc<Program> {
    let sig = program_signature(program);
    if let Some(a) = cache.get(&sig) {
        return Arc::clone(a);
    }
    let new_ops: Vec<Opcode> = program.ops.iter().map(|op| rewrite_op(op, cache)).collect();
    let ics = crate::vm::fresh_ics(new_ops.len());
    let out = Arc::new(Program {
        ops: new_ops.into(),
        source: program.source.clone(),
        id: program.id,
        is_structural: program.is_structural,
        ics,
    });
    cache.insert(sig, Arc::clone(&out));
    out
}

/// Rewrite a single opcode so that all embedded sub-programs are replaced with
/// their deduplicated equivalents from `cache`.
fn rewrite_op(op: &Opcode, cache: &mut HashMap<u64, Arc<Program>>) -> Opcode {
    use crate::vm::{CompSpec, CompiledFSPart, CompiledObjEntry, DictCompSpec};
    match op {
        Opcode::AndOp(p) => Opcode::AndOp(dedup_rec(p, cache)),
        Opcode::OrOp(p) => Opcode::OrOp(dedup_rec(p, cache)),
        Opcode::CoalesceOp(p) => Opcode::CoalesceOp(dedup_rec(p, cache)),
        Opcode::IfElse { then_, else_ } => Opcode::IfElse {
            then_: dedup_rec(then_, cache),
            else_: dedup_rec(else_, cache),
        },
        Opcode::InlineFilter(p) => Opcode::InlineFilter(dedup_rec(p, cache)),
        Opcode::DynIndex(p) => Opcode::DynIndex(dedup_rec(p, cache)),
        Opcode::LetExpr { name, body } => Opcode::LetExpr {
            name: name.clone(),
            body: dedup_rec(body, cache),
        },
        Opcode::CallMethod(c) => Opcode::CallMethod(rewrite_call(c, cache)),
        Opcode::CallOptMethod(c) => Opcode::CallOptMethod(rewrite_call(c, cache)),
        Opcode::MakeArr(progs) => {
            let new_progs: Vec<(Arc<Program>, bool)> = progs
                .iter()
                .map(|(p, sp)| (dedup_rec(p, cache), *sp))
                .collect();
            Opcode::MakeArr(new_progs.into())
        }
        Opcode::MakeObj(entries) => {
            let new_entries: Vec<CompiledObjEntry> = entries
                .iter()
                .map(|e| match e {
                    CompiledObjEntry::Short { name, ic } => CompiledObjEntry::Short {
                        name: name.clone(),
                        ic: ic.clone(),
                    },
                    CompiledObjEntry::Kv {
                        key,
                        prog,
                        optional,
                        cond,
                    } => CompiledObjEntry::Kv {
                        key: key.clone(),
                        prog: dedup_rec(prog, cache),
                        optional: *optional,
                        cond: cond.as_ref().map(|c| dedup_rec(c, cache)),
                    },
                    CompiledObjEntry::KvPath {
                        key,
                        steps,
                        optional,
                        ics,
                    } => CompiledObjEntry::KvPath {
                        key: key.clone(),
                        steps: steps.clone(),
                        optional: *optional,
                        ics: ics.clone(),
                    },
                    CompiledObjEntry::Dynamic { key, val } => CompiledObjEntry::Dynamic {
                        key: dedup_rec(key, cache),
                        val: dedup_rec(val, cache),
                    },
                    CompiledObjEntry::Spread(p) => CompiledObjEntry::Spread(dedup_rec(p, cache)),
                    CompiledObjEntry::SpreadDeep(p) => {
                        CompiledObjEntry::SpreadDeep(dedup_rec(p, cache))
                    }
                })
                .collect();
            Opcode::MakeObj(new_entries.into())
        }
        Opcode::FString(parts) => {
            let new_parts: Vec<CompiledFSPart> = parts
                .iter()
                .map(|p| match p {
                    CompiledFSPart::Lit(s) => CompiledFSPart::Lit(s.clone()),
                    CompiledFSPart::Interp { prog, fmt } => CompiledFSPart::Interp {
                        prog: dedup_rec(prog, cache),
                        fmt: fmt.clone(),
                    },
                })
                .collect();
            Opcode::FString(new_parts.into())
        }
        Opcode::ListComp(spec) => {
            let new_spec = CompSpec {
                expr: dedup_rec(&spec.expr, cache),
                iter: dedup_rec(&spec.iter, cache),
                cond: spec.cond.as_ref().map(|c| dedup_rec(c, cache)),
                vars: spec.vars.clone(),
            };
            Opcode::ListComp(Arc::new(new_spec))
        }
        Opcode::SetComp(spec) => {
            let new_spec = CompSpec {
                expr: dedup_rec(&spec.expr, cache),
                iter: dedup_rec(&spec.iter, cache),
                cond: spec.cond.as_ref().map(|c| dedup_rec(c, cache)),
                vars: spec.vars.clone(),
            };
            Opcode::SetComp(Arc::new(new_spec))
        }
        Opcode::DictComp(spec) => {
            let new_spec = DictCompSpec {
                key: dedup_rec(&spec.key, cache),
                val: dedup_rec(&spec.val, cache),
                iter: dedup_rec(&spec.iter, cache),
                cond: spec.cond.as_ref().map(|c| dedup_rec(c, cache)),
                vars: spec.vars.clone(),
            };
            Opcode::DictComp(Arc::new(new_spec))
        }
        _ => op.clone(),
    }
}

/// Rebuild a `CompiledCall` with all sub-programs replaced by their deduplicated equivalents.
fn rewrite_call(
    c: &Arc<crate::vm::CompiledCall>,
    cache: &mut HashMap<u64, Arc<Program>>,
) -> Arc<crate::vm::CompiledCall> {
    use crate::vm::CompiledCall;
    let new_subs: Vec<Arc<Program>> = c.sub_progs.iter().map(|p| dedup_rec(p, cache)).collect();
    let new_kernels = crate::compile::compiler::classify_sub_kernels(&new_subs);
    Arc::new(CompiledCall {
        method: c.method,
        name: c.name.clone(),
        sub_progs: new_subs.into(),
        sub_kernels: new_kernels,
        orig_args: c.orig_args.clone(),
        demand_max_keep: c.demand_max_keep,
    })
}


/// Return an estimated execution cost for a single opcode, used by the planner
/// to order filter predicates cheapest-first and to guide inlining decisions.
pub fn opcode_cost(op: &Opcode) -> u32 {
    match op {
        Opcode::PushNull
        | Opcode::PushBool(_)
        | Opcode::PushInt(_)
        | Opcode::PushFloat(_)
        | Opcode::PushStr(_)
        | Opcode::PushRoot
        | Opcode::PushCurrent
        | Opcode::LoadIdent(_) => 1,
        Opcode::GetField(_)
        | Opcode::OptField(_)
        | Opcode::GetIndex(_)
        | Opcode::RootChain(_)
        | Opcode::FieldChain(_) => 2,
        Opcode::GetSlice(..) | Opcode::Descendant(_) => 5,
        Opcode::DescendAll => 20,
        Opcode::Not | Opcode::Neg | Opcode::SetCurrent => 1,
        Opcode::Add
        | Opcode::Sub
        | Opcode::Mul
        | Opcode::Div
        | Opcode::Mod
        | Opcode::Eq
        | Opcode::Neq
        | Opcode::Lt
        | Opcode::Lte
        | Opcode::Gt
        | Opcode::Gte
        | Opcode::Fuzzy => 2,
        Opcode::KindCheck { .. } => 2,
        Opcode::AndOp(p) | Opcode::OrOp(p) | Opcode::CoalesceOp(p) => 2 + program_cost(p),
        Opcode::IfElse { then_, else_ } => 2 + program_cost(then_) + program_cost(else_),
        Opcode::TryExpr { body, default } => 2 + program_cost(body) + program_cost(default),
        Opcode::InlineFilter(p) | Opcode::DynIndex(p) => 10 + program_cost(p),
        Opcode::CallMethod(c) | Opcode::CallOptMethod(c) => {
            let base = match c.method {
                BuiltinMethod::Filter | BuiltinMethod::Map | BuiltinMethod::FlatMap => 10,
                BuiltinMethod::Sort => 30,
                BuiltinMethod::GroupBy | BuiltinMethod::IndexBy => 25,
                BuiltinMethod::Len | BuiltinMethod::Count => 2,
                _ => 8,
            };
            base + c.sub_progs.iter().map(|p| program_cost(p)).sum::<u32>()
        }
        Opcode::MakeObj(entries) => {
            use crate::vm::CompiledObjEntry;
            entries
                .iter()
                .map(|e| match e {
                    CompiledObjEntry::Short { .. } => 2,
                    CompiledObjEntry::Kv { prog, cond, .. } => {
                        2 + program_cost(prog) + cond.as_ref().map_or(0, |c| program_cost(c))
                    }
                    CompiledObjEntry::KvPath { steps, .. } => 2 + steps.len() as u32,
                    CompiledObjEntry::Dynamic { key, val } => {
                        3 + program_cost(key) + program_cost(val)
                    }
                    CompiledObjEntry::Spread(p) => 5 + program_cost(p),
                    CompiledObjEntry::SpreadDeep(p) => 8 + program_cost(p),
                })
                .sum()
        }
        Opcode::MakeArr(progs) => progs.iter().map(|(p, _)| 1 + program_cost(p)).sum(),
        Opcode::FString(parts) => {
            use crate::vm::CompiledFSPart;
            parts
                .iter()
                .map(|p| match p {
                    CompiledFSPart::Lit(_) => 1,
                    CompiledFSPart::Interp { prog, .. } => 3 + program_cost(prog),
                })
                .sum()
        }
        Opcode::ListComp(s) | Opcode::SetComp(s) => {
            15 + program_cost(&s.expr)
                + program_cost(&s.iter)
                + s.cond.as_ref().map_or(0, |c| program_cost(c))
        }
        Opcode::DictComp(s) => {
            15 + program_cost(&s.key)
                + program_cost(&s.val)
                + program_cost(&s.iter)
                + s.cond.as_ref().map_or(0, |c| program_cost(c))
        }
        Opcode::LetExpr { body, .. } => 2 + program_cost(body),
        Opcode::Quantifier(_) => 2,
        Opcode::CastOp(_) => 2,
        Opcode::PatchEval(_) => 50,
        Opcode::DeleteMarkErr => 1,
        Opcode::Match(_) => 1,
        Opcode::DeepMatchAll(_) => 1,
        Opcode::DeepMatchFirst(_) => 1,
        Opcode::PipelineRun { base, steps } => {
            program_cost(base)
                + steps
                    .iter()
                    .map(|s| match s {
                        CompiledPipeStep::Forward(p) => program_cost(p),
                        _ => 1,
                    })
                    .sum::<u32>()
        }
    }
}


/// Sum `opcode_cost` over all opcodes in `program`; used as a proxy for execution
/// time when comparing alternative sub-expressions for predicate reordering.
pub fn program_cost(program: &Program) -> u32 {
    program.ops.iter().map(opcode_cost).sum()
}


/// Monotonicity of an array-valued program with respect to its natural order.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Monotonicity {
    /// Order is unknown or has been disrupted by a non-monotone operation.
    Unknown,
    /// The array is in ascending order (e.g. after `.sort()`).
    Asc,
    /// The array is in descending order (e.g. after `.sort().reverse()`).
    Desc,
    /// The value is not an array; monotonicity is not applicable.
    NotArray,
}

impl Monotonicity {
    /// Compute the monotonicity that results from applying `op` to a value
    /// with the current monotonicity. Used to track sort order through pipelines.
    pub fn after(self, op: &Opcode) -> Monotonicity {
        match op {
            Opcode::CallMethod(c) if c.sub_progs.is_empty() => match c.method {
                BuiltinMethod::Sort => Monotonicity::Asc,
                BuiltinMethod::Reverse => match self {
                    Monotonicity::Asc => Monotonicity::Desc,
                    Monotonicity::Desc => Monotonicity::Asc,
                    x => x,
                },
                BuiltinMethod::Filter => self, // Filter preserves order.
                BuiltinMethod::Map => Monotonicity::Unknown, // Map may reorder.
                _ => Monotonicity::Unknown,
            },
            Opcode::MakeArr(_) | Opcode::ListComp(_) => Monotonicity::Unknown,
            _ => self,
        }
    }
}


/// Infer the output monotonicity of `program` by stepping through each opcode
/// sequentially from `Unknown`, updating the state with `Monotonicity::after`.
pub fn infer_monotonicity(program: &Program) -> Monotonicity {
    let mut m = Monotonicity::Unknown;
    for op in program.ops.iter() {
        m = m.after(op);
    }
    m
}


/// Return `true` when `program` reads from the input document (`PushRoot`,
/// `PushCurrent`, field/index accesses, descendants). Used to detect programs
/// that are fully constant and need not be re-evaluated per document.
pub fn escapes_doc(program: &Program) -> bool {
    for op in program.ops.iter() {
        match op {
            Opcode::PushRoot
            | Opcode::PushCurrent
            | Opcode::RootChain(_)
            | Opcode::GetField(_)
            | Opcode::GetIndex(_)
            | Opcode::GetSlice(..)
            | Opcode::Descendant(_)
            | Opcode::DescendAll
            | Opcode::OptField(_) => return true,
            Opcode::CallMethod(c) | Opcode::CallOptMethod(c)
                if c.sub_progs.iter().any(|p| escapes_doc(p)) =>
            {
                return true
            }
            _ => {}
        }
    }
    false
}


/// Estimate the selectivity of a filter predicate expression; lower scores mean
/// the predicate eliminates more candidates and should be tested first.
/// The planner uses this to reorder `And` operands cheapest/most-selective first.
pub fn selectivity_score(expr: &crate::parse::ast::Expr) -> u32 {
    use crate::parse::ast::{BinOp, Expr};
    match expr {
        Expr::Bool(true) => 1000, // Always passes — effectively no filter.
        Expr::Bool(false) => 0,   // Never passes — maximally selective.
        Expr::BinOp(_, BinOp::Eq, _) => 1,
        Expr::BinOp(_, BinOp::Neq, _) => 5,
        Expr::BinOp(_, BinOp::Lt, _)
        | Expr::BinOp(_, BinOp::Gt, _)
        | Expr::BinOp(_, BinOp::Lte, _)
        | Expr::BinOp(_, BinOp::Gte, _) => 3,
        Expr::BinOp(_, BinOp::Fuzzy, _) => 2,
        Expr::BinOp(l, BinOp::And, r) => selectivity_score(l).min(selectivity_score(r)),
        Expr::BinOp(l, BinOp::Or, r) => selectivity_score(l) + selectivity_score(r),
        Expr::Not(e) => 10u32.saturating_sub(selectivity_score(e)),
        Expr::Kind { .. } => 2,
        _ => 5,
    }
}


/// Attempt to evaluate a kind-check at compile time given a statically known
/// `VType`. Returns `Some(bool)` when the result is certain, `None` when
/// `val_ty` is `Unknown` and the check must be deferred to runtime.
pub fn fold_kind_check(val_ty: VType, target: KindType, negate: bool) -> Option<bool> {
    let matches = match (val_ty, target) {
        (VType::Null, KindType::Null) => true,
        (VType::Bool, KindType::Bool) => true,
        (VType::Int | VType::Float | VType::Num, KindType::Number) => true,
        (VType::Str, KindType::Str) => true,
        (VType::Arr, KindType::Array) => true,
        (VType::Obj, KindType::Object) => true,
        (VType::Unknown, _) => return None,
        _ => false,
    };
    Some(if negate { !matches } else { matches })
}