phplang 0.2.17

PHP as a fusevm frontend: lexer, parser, and compiler to fusevm::Chunk on a PhpHost heap — the first compiled standalone PHP runtime
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
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
//! PHP standard-library `arrays` functions. Part of the `stdlib` chain; see
//! `src/stdlib/mod.rs`. `dispatch` returns `None` for names it does not handle.
//!
//! The functions the language core already provides (`count`, `array_map`,
//! `sort`, …) are handled before this module is consulted, so only their close
//! siblings live here. Arrays are heap objects reached by a `Value::Obj` handle,
//! so the by-reference mutators (`usort`, `shuffle`, the internal-pointer family,
//! …) mutate the array behind the handle in place, exactly as `sort` does in the
//! core — the effect is visible through the caller's `$var`.

use crate::host;
use crate::stdlib::common::*;
use crate::stdlib::math::php_random_range;
use fusevm::Value;
use std::cell::RefCell;
use std::cmp::Ordering;
use std::collections::hash_map::DefaultHasher;
use std::collections::HashMap;
use std::hash::{Hash, Hasher};

/// Dispatch an `arrays`-category PHP function by lowercased name.
pub fn dispatch(name: &str, args: &[Value]) -> Option<Result<Value, String>> {
    let v = match name {
        "array_column" => host::with_host(|h| php_array_column(h, args)),
        "array_chunk" => match php_array_chunk(args) {
            Ok(v) => v,
            e => return Some(e),
        },
        "array_fill_keys" => host::with_host(|h| php_array_fill_keys(h, args)),
        "array_pad" => host::with_host(|h| php_array_pad(h, args)),
        "array_key_first" => host::with_host(|h| php_array_key_first(h, args)),
        "array_key_last" => host::with_host(|h| php_array_key_last(h, args)),
        "array_first" => host::with_host(|h| php_array_first_last(h, args, false)),
        "array_last" => host::with_host(|h| php_array_first_last(h, args, true)),
        "array_is_list" => host::with_host(|h| php_array_is_list(h, args)),
        "array_diff_key" => host::with_host(|h| php_diff_intersect_key(h, args, false)),
        "array_intersect_key" => host::with_host(|h| php_diff_intersect_key(h, args, true)),
        "array_diff_assoc" => host::with_host(|h| php_diff_intersect_assoc(h, args, false)),
        "array_intersect_assoc" => host::with_host(|h| php_diff_intersect_assoc(h, args, true)),
        "array_merge_recursive" => host::with_host(|h| php_array_merge_recursive(h, args)),
        "array_replace" => host::with_host(|h| php_array_replace(h, args)),
        "array_replace_recursive" => host::with_host(|h| php_array_replace_recursive(h, args)),
        "array_count_values" => host::with_host(|h| php_array_count_values(h, args)),
        "usort" => return Some(php_usort(args, SortKind::List)),
        "uasort" => return Some(php_usort(args, SortKind::Assoc)),
        "uksort" => return Some(php_usort(args, SortKind::Key)),
        "natsort" => host::with_host(|h| php_natsort(h, args, false)),
        "natcasesort" => host::with_host(|h| php_natsort(h, args, true)),
        "shuffle" => host::with_host(|h| php_shuffle(h, args)),
        "array_rand" => match host::with_host(|h| php_array_rand(h, args)) {
            Ok(v) => v,
            e => return Some(e),
        },
        "array_walk" => return Some(php_array_walk(args)),
        "compact" => host::with_host(|h| php_compact(h, args)),
        "extract" => match host::with_host(|h| php_extract(h, args)) {
            Ok(v) => v,
            e => return Some(e),
        },
        "end" => host::with_host(|h| ptr_end(h, args)),
        "reset" => host::with_host(|h| ptr_reset(h, args)),
        "current" | "pos" => host::with_host(|h| ptr_current(h, args)),
        "key" => host::with_host(|h| ptr_key(h, args)),
        "next" => host::with_host(|h| ptr_step(h, args, 1)),
        "prev" => host::with_host(|h| ptr_step(h, args, -1)),
        _ => return None,
    };
    Some(Ok(v))
}

// ── helpers ──────────────────────────────────────────────────────────────────

/// The heap handle of an array value, or `None` if `v` is not an object handle.
fn as_handle(v: &Value) -> Option<u32> {
    match v {
        Value::Obj(h) => Some(*h),
        _ => None,
    }
}

/// Deep-copy a value: arrays are cloned into fresh handles (recursively) so the
/// result never shares storage with the source. Scalars clone directly. Used by
/// `array_merge_recursive`, which — unlike `array_merge` — must own its nested
/// arrays to merge into them without mutating the inputs.
fn deep_copy(h: &mut host::PhpHost, v: &Value) -> Value {
    deep_copy_seen(h, v, &mut host::Visiting::default())
}

/// [`deep_copy`] with a cycle guard: a self-referential array is copied one
/// level and the repeat becomes `null`, instead of recursing until the native
/// stack is gone.
fn deep_copy_seen(h: &mut host::PhpHost, v: &Value, seen: &mut host::Visiting) -> Value {
    if h.is_array(v) {
        if !seen.enter(v) {
            return Value::Undef;
        }
        let pairs = h.array_pairs(v).unwrap_or_default();
        let out = h.new_array();
        for (k, val) in pairs {
            let cv = deep_copy_seen(h, &val, seen);
            h.arr_set_key(&out, &k, cv);
        }
        seen.leave();
        out
    } else {
        v.clone()
    }
}

// ── array_column ─────────────────────────────────────────────────────────────

/// `array_column($rows, $column_key, $index_key = null)` — pluck one column out
/// of a list of rows, optionally re-keying by another column. A `null` column key
/// keeps the whole row (PHP 7+). Rows missing the column are skipped.
fn php_array_column(h: &mut host::PhpHost, args: &[Value]) -> Value {
    let rows = arg(args, 0);
    let col = arg(args, 1);
    let idx = arg(args, 2);
    let col_all = matches!(col, Value::Undef);
    let has_idx = args.len() > 2 && !matches!(idx, Value::Undef);
    let out = h.new_array();
    for (_, row) in h.array_pairs(&rows).unwrap_or_default() {
        // The plucked value: the whole row for a null column, else the element at
        // `col` — skipping any row that lacks that column.
        let value = if col_all {
            row.clone()
        } else if let Some(v) = row_get(h, &row, &col) {
            v
        } else {
            continue;
        };
        match if has_idx {
            row_get(h, &row, &idx)
        } else {
            None
        } {
            Some(k) => h.arr_set_key(&out, &k, value),
            None => h.arr_push_auto(&out, value),
        }
    }
    out
}

/// Read `field` out of a row (an array or an object), returning `None` when the
/// field is absent so the caller can skip the row.
fn row_get(h: &host::PhpHost, row: &Value, field: &Value) -> Option<Value> {
    if h.is_array(row) {
        let want = h.to_str(field);
        for (k, v) in h.array_pairs(row).unwrap_or_default() {
            if h.to_str(&k) == want {
                return Some(v);
            }
        }
        return None;
    }
    if h.is_object(row) {
        let v = h.prop_get(row, &h.to_str(field));
        if !matches!(v, Value::Undef) {
            return Some(v);
        }
    }
    None
}

// ── array_chunk ──────────────────────────────────────────────────────────────

/// `array_chunk($array, $size, $preserve_keys = false)` — split into a list of
/// sub-arrays of at most `$size` elements. `$size < 1` is a fatal error in PHP.
fn php_array_chunk(args: &[Value]) -> Result<Value, String> {
    let arr = arg(args, 0);
    let size = int_arg(args, 1);
    if size < 1 {
        return Err(throws(
            "ValueError",
            "array_chunk(): Argument #2 ($length) must be greater than 0",
        ));
    }
    let preserve = args.get(2).map(|v| host::with_host(|h| h.is_truthy(v)));
    let preserve = preserve.unwrap_or(false);
    Ok(host::with_host(|h| {
        let pairs = h.array_pairs(&arr).unwrap_or_default();
        let out = h.new_array();
        for chunk in pairs.chunks(size as usize) {
            let sub = h.new_array();
            for (k, v) in chunk {
                if preserve {
                    h.arr_set_key(&sub, k, v.clone());
                } else {
                    h.arr_push_auto(&sub, v.clone());
                }
            }
            h.arr_push_auto(&out, sub);
        }
        out
    }))
}

// ── array_fill_keys ──────────────────────────────────────────────────────────

/// `array_fill_keys($keys, $value)` — a new array using each element of `$keys`
/// as a key, every entry set to `$value`.
fn php_array_fill_keys(h: &mut host::PhpHost, args: &[Value]) -> Value {
    let keys = arg(args, 0);
    let value = arg(args, 1);
    let out = h.new_array();
    for (_, k) in h.array_pairs(&keys).unwrap_or_default() {
        let k = crate::builtins::string_key(h, k);
        h.arr_set_key(&out, &k, value.clone());
    }
    out
}

// ── array_pad ────────────────────────────────────────────────────────────────

/// `array_pad($array, $size, $value)` — pad to `abs($size)` elements with
/// `$value`; a positive size pads on the right, a negative one on the left. The
/// result renumbers integer keys and preserves string keys (as `array_merge`).
fn php_array_pad(h: &mut host::PhpHost, args: &[Value]) -> Value {
    let arr = arg(args, 0);
    let size = h.to_number(&arg(args, 1)).to_int();
    let value = arg(args, 2);
    let pairs = h.array_pairs(&arr).unwrap_or_default();
    let need = size.unsigned_abs() as usize;
    let pad = need.saturating_sub(pairs.len());
    let out = h.new_array();
    let emit = |h: &mut host::PhpHost, out: &Value, pairs: &[(Value, Value)]| {
        for (k, v) in pairs {
            match k {
                Value::Int(_) => h.arr_push_auto(out, v.clone()),
                _ => h.arr_set_key(out, k, v.clone()),
            }
        }
    };
    if size < 0 {
        for _ in 0..pad {
            h.arr_push_auto(&out, value.clone());
        }
        emit(h, &out, &pairs);
    } else {
        emit(h, &out, &pairs);
        for _ in 0..pad {
            h.arr_push_auto(&out, value.clone());
        }
    }
    out
}

// ── array_key_first / array_key_last / array_is_list ─────────────────────────

fn php_array_key_first(h: &mut host::PhpHost, args: &[Value]) -> Value {
    h.array_pairs(&arg(args, 0))
        .and_then(|p| p.into_iter().next())
        .map(|(k, _)| k)
        .unwrap_or(Value::Undef)
}

fn php_array_key_last(h: &mut host::PhpHost, args: &[Value]) -> Value {
    h.array_pairs(&arg(args, 0))
        .and_then(|p| p.into_iter().next_back())
        .map(|(k, _)| k)
        .unwrap_or(Value::Undef)
}

/// `array_first` / `array_last` (PHP 8.5) — the first or last VALUE in insertion
/// order, or null for an empty array. Port of `PHP_FUNCTION(array_first)` /
/// `PHP_FUNCTION(array_last)` in `ext/standard/array.c`, which dereference the
/// slot and copy the value out.
fn php_array_first_last(h: &mut host::PhpHost, args: &[Value], last: bool) -> Value {
    let pairs = h.array_pairs(&arg(args, 0)).unwrap_or_default();
    let slot = if last {
        pairs.into_iter().next_back()
    } else {
        pairs.into_iter().next()
    };
    slot.map(|(_, v)| v).unwrap_or(Value::Undef)
}

/// `array_is_list` — true when the keys are exactly `0,1,…,n-1` in order.
fn php_array_is_list(h: &mut host::PhpHost, args: &[Value]) -> Value {
    let v = arg(args, 0);
    if !h.is_array(&v) {
        return Value::bool(false);
    }
    let is_list = h
        .array_pairs(&v)
        .unwrap_or_default()
        .iter()
        .enumerate()
        .all(|(i, (k, _))| matches!(k, Value::Int(n) if *n == i as i64));
    Value::bool(is_list)
}

// ── key/assoc diff & intersect ───────────────────────────────────────────────

/// `array_diff_key` (`intersect=false`) / `array_intersect_key` (`intersect=true`)
/// — filter the first array by whether each key is absent from every other array
/// (diff) or present in all of them (intersect). Keys compare by string form.
fn php_diff_intersect_key(h: &mut host::PhpHost, args: &[Value], intersect: bool) -> Value {
    let first = h.array_pairs(&arg(args, 0)).unwrap_or_default();
    let others: Vec<std::collections::HashSet<String>> = args
        .iter()
        .skip(1)
        .map(|a| {
            h.array_pairs(a)
                .unwrap_or_default()
                .into_iter()
                .map(|(k, _)| h.to_str(&k))
                .collect()
        })
        .collect();
    let out = h.new_array();
    for (k, v) in first {
        let ks = h.to_str(&k);
        let keep = if intersect {
            others.iter().all(|s| s.contains(&ks))
        } else {
            others.iter().all(|s| !s.contains(&ks))
        };
        if keep {
            h.arr_set_key(&out, &k, v);
        }
    }
    out
}

/// `array_diff_assoc` (`intersect=false`) / `array_intersect_assoc`
/// (`intersect=true`) — like the key variants but matching on key *and* value
/// (both compared by string form).
fn php_diff_intersect_assoc(h: &mut host::PhpHost, args: &[Value], intersect: bool) -> Value {
    let first = h.array_pairs(&arg(args, 0)).unwrap_or_default();
    let others: Vec<HashMap<String, String>> = args
        .iter()
        .skip(1)
        .map(|a| {
            h.array_pairs(a)
                .unwrap_or_default()
                .into_iter()
                .map(|(k, v)| (h.to_str(&k), h.to_str(&v)))
                .collect()
        })
        .collect();
    let out = h.new_array();
    for (k, v) in first {
        let ks = h.to_str(&k);
        let vs = h.to_str(&v);
        let matches_other = |m: &HashMap<String, String>| m.get(&ks) == Some(&vs);
        let keep = if intersect {
            others.iter().all(matches_other)
        } else {
            others.iter().all(|m| !matches_other(m))
        };
        if keep {
            h.arr_set_key(&out, &k, v);
        }
    }
    out
}

// ── array_merge_recursive ────────────────────────────────────────────────────

/// `array_merge_recursive(...)` — merge arrays, recursing into shared string
/// keys: two arrays under one key merge; anything else under a duplicate string
/// key is gathered into a flat list. Integer keys always append.
fn php_array_merge_recursive(h: &mut host::PhpHost, args: &[Value]) -> Value {
    let acc = h.new_array();
    for a in args {
        if h.is_array(a) {
            merge_recursive_into(h, &acc, a);
        }
    }
    acc
}

/// Merge every entry of `src` into the owned accumulator `acc` (see
/// `array_merge_recursive`). `acc`'s array values are always deep copies, so
/// recursing into them never touches the caller's inputs.
fn merge_recursive_into(h: &mut host::PhpHost, acc: &Value, src: &Value) {
    for (k, v) in h.array_pairs(src).unwrap_or_default() {
        match k {
            Value::Int(_) => {
                let cv = deep_copy(h, &v);
                h.arr_push_auto(acc, cv);
            }
            _ => {
                let existing = existing_by_key(h, acc, &k);
                match existing {
                    None => {
                        let cv = deep_copy(h, &v);
                        h.arr_set_key(acc, &k, cv);
                    }
                    Some(ev) if h.is_array(&ev) && h.is_array(&v) => {
                        // Guard the mutual walk the same way: `$a[] = &$a` makes
                        // `ev` and `v` the same handle, and the merge would
                        // otherwise descend into itself forever.
                        if ev != v {
                            merge_recursive_into(h, &ev, &v);
                        }
                    }
                    Some(ev) => {
                        // Not both arrays: flatten the existing value and the new
                        // one into a single fresh list.
                        let combined = h.new_array();
                        for item in as_value_list(h, &ev) {
                            let ci = deep_copy(h, &item);
                            h.arr_push_auto(&combined, ci);
                        }
                        for item in as_value_list(h, &v) {
                            let ci = deep_copy(h, &item);
                            h.arr_push_auto(&combined, ci);
                        }
                        h.arr_set_key(acc, &k, combined);
                    }
                }
            }
        }
    }
}

/// The value already stored under `key` in `acc` (by string-form key match), or
/// `None` if that key is absent.
fn existing_by_key(h: &host::PhpHost, acc: &Value, key: &Value) -> Option<Value> {
    let want = h.to_str(key);
    h.array_pairs(acc)
        .unwrap_or_default()
        .into_iter()
        .find(|(k, _)| h.to_str(k) == want)
        .map(|(_, v)| v)
}

/// A value seen as a list of values: an array's values, or a one-element list
/// holding the scalar itself.
fn as_value_list(h: &host::PhpHost, v: &Value) -> Vec<Value> {
    if h.is_array(v) {
        h.array_pairs(v)
            .unwrap_or_default()
            .into_iter()
            .map(|(_, x)| x)
            .collect()
    } else {
        vec![v.clone()]
    }
}

// ── array_replace ────────────────────────────────────────────────────────────

/// `array_replace($base, ...$rest)` — start from `$base`, then overwrite/insert
/// every entry of each later array by key (no recursion).
fn php_array_replace(h: &mut host::PhpHost, args: &[Value]) -> Value {
    let out = h.new_array();
    for a in args {
        for (k, v) in h.array_pairs(a).unwrap_or_default() {
            h.arr_set_key(&out, &k, v);
        }
    }
    out
}

/// `array_replace_recursive($base, ...$rest)` — as `array_replace`, except that
/// when BOTH sides hold an array under the same key the two are merged
/// recursively instead of the later one replacing the earlier wholesale. Any
/// other type pairing (or a key present on only one side) replaces.
fn php_array_replace_recursive(h: &mut host::PhpHost, args: &[Value]) -> Value {
    let out = h.new_array();
    for a in args {
        replace_recursive_into(h, &out, a);
    }
    out
}

/// Merge every entry of `src` into the existing array `dst`, descending wherever
/// both sides already hold an array. `dst` is a heap handle, so the descent
/// writes through to the copy `array_replace_recursive` is building.
fn replace_recursive_into(h: &mut host::PhpHost, dst: &Value, src: &Value) {
    for (k, v) in h.array_pairs(src).unwrap_or_default() {
        let existing = h.index_get(dst, &k);
        if h.is_array(&existing) && h.is_array(&v) {
            // Copy the destination subtree first: PHP arrays are value types, so
            // merging must not write through into an array the caller still holds.
            let sub = h.new_array();
            for (ek, ev) in h.array_pairs(&existing).unwrap_or_default() {
                h.arr_set_key(&sub, &ek, ev);
            }
            replace_recursive_into(h, &sub, &v);
            h.arr_set_key(dst, &k, sub);
        } else {
            h.arr_set_key(dst, &k, v);
        }
    }
}

// ── array_count_values ───────────────────────────────────────────────────────

/// `array_count_values($array)` — tally occurrences of the values (only int and
/// string values are counted, matching PHP; others are skipped).
fn php_array_count_values(h: &mut host::PhpHost, args: &[Value]) -> Value {
    let pairs = h.array_pairs(&arg(args, 0)).unwrap_or_default();
    let out = h.new_array();
    for (_, v) in pairs {
        if !matches!(v, Value::Int(_) | Value::Str(_)) {
            h.warn("array_count_values(): Can only count string and integer values, entry skipped");
            continue;
        }
        let prev = h.index_get(&out, &v);
        let n = match prev {
            Value::Undef => 1,
            other => other.to_int() + 1,
        };
        h.arr_set_key(&out, &v, Value::int(n));
    }
    out
}

// ── usort / uasort / uksort ──────────────────────────────────────────────────

enum SortKind {
    /// `usort` — sort by value, then reindex 0..n.
    List,
    /// `uasort` — sort by value, preserve keys.
    Assoc,
    /// `uksort` — sort by key, preserve keys.
    Key,
}

/// One call's worth of user-comparator state: the function name its
/// diagnostics carry, PHP's `ARRAYG(compare_deprecation_thrown)` (the bool
/// deprecation is raised once per call, `PHP_ARRAY_CMP_FUNC_BACKUP` resets it),
/// and the first engine error a callback raised.
pub(crate) struct UserCmp<'a> {
    func: &'a str,
    deprecation_thrown: bool,
    pub(crate) err: Option<String>,
}

impl<'a> UserCmp<'a> {
    pub(crate) fn new(func: &'a str) -> Self {
        UserCmp {
            func,
            deprecation_thrown: false,
            err: None,
        }
    }

    /// Run the callback once. With an exception pending `zend_call_function`
    /// returns at once and leaves the result UNDEF, so no further callback runs
    /// and the comparison reads as `0`.
    fn invoke(&mut self, cb: &Value, a: &Value, b: &Value) -> Option<Value> {
        if self.err.is_some() || host::unwinding() {
            return None;
        }
        match host::call_value(cb.clone(), vec![a.clone(), b.clone()]) {
            Ok(r) if !host::unwinding() => Some(r),
            Ok(_) => None,
            Err(e) => {
                self.err = Some(e);
                None
            }
        }
    }

    /// `php_get_long` + `ZEND_NORMALIZE_BOOL`.
    fn normalized(r: Option<Value>) -> i32 {
        let n = r.map_or(0, |r| host::with_host(|h| h.to_number(&r).to_int()));
        n.signum() as i32
    }

    /// `zval_user_compare`: the plain form the key-matched `array_udiff_assoc`
    /// / `array_uintersect_assoc` use — no bool handling.
    pub(crate) fn plain(&mut self, cb: &Value, a: &Value, b: &Value) -> i32 {
        Self::normalized(self.invoke(cb, a, b))
    }

    /// `php_array_user_compare_unstable` (and its key twin): a bool result is
    /// deprecated, and `false` is retried with the operands swapped, its answer
    /// negated — so `fn($a, $b) => $a > $b` still sorts.
    pub(crate) fn sorting(&mut self, cb: &Value, a: &Value, b: &Value) -> i32 {
        let r = self.invoke(cb, a, b);
        if let Some(Value::Bool(truth)) = r {
            if !self.deprecation_thrown {
                let func = self.func;
                host::with_host(|h| {
                    h.deprecated(format!(
                        "{func}(): Returning bool from comparison function is deprecated, \
                         return an integer less than, equal to, or greater than zero"
                    ))
                });
                self.deprecation_thrown = true;
            }
            if !truth {
                return -Self::normalized(self.invoke(cb, b, a));
            }
        }
        Self::normalized(r)
    }
}

/// The user-comparator sorts, ported from `php_usort`: `zend_hash_sort` over a
/// copy of the array with `php_array_user_compare` (`uksort`: the key form),
/// whose ties fall back to original position. The comparator runs the VM, so
/// it is invoked outside any `with_host` borrow; the first error it raises
/// stops further callbacks.
fn php_usort(args: &[Value], kind: SortKind) -> Result<Value, String> {
    let arr = arg(args, 0);
    let cb = arg(args, 1);
    let func = match kind {
        SortKind::List => "usort",
        SortKind::Assoc => "uasort",
        SortKind::Key => "uksort",
    };
    let mut pairs = host::with_host(|h| h.array_pairs(&arr)).unwrap_or_default();
    let mut ucmp = UserCmp::new(func);
    crate::stdlib::zsort::zend_sort_stable(&mut pairs, |(ka, va), (kb, vb)| match kind {
        SortKind::Key => ucmp.sorting(&cb, ka, kb),
        _ => ucmp.sorting(&cb, va, vb),
    });
    if let Some(e) = ucmp.err {
        return Err(e);
    }
    if host::unwinding() {
        return Ok(Value::Undef);
    }
    host::with_host(|h| match kind {
        SortKind::List => {
            let vals = pairs.into_iter().map(|(_, v)| v).collect();
            h.arr_set_reindexed(&arr, vals);
        }
        _ => h.arr_set_pairs(&arr, pairs),
    });
    Ok(Value::bool(true))
}

// ── natsort / natcasesort ────────────────────────────────────────────────────

/// `natsort` / `natcasesort` — natural-order sort by value, preserving keys.
fn php_natsort(h: &mut host::PhpHost, args: &[Value], fold_case: bool) -> Value {
    let arr = arg(args, 0);
    let mut pairs = h.array_pairs(&arr).unwrap_or_default();
    let keyed: Vec<(String, (Value, Value))> = pairs
        .drain(..)
        .map(|(k, v)| (h.to_str(&v), (k, v)))
        .collect();
    let mut keyed = keyed;
    keyed.sort_by(|(a, _), (b, _)| nat_cmp(a, b, fold_case));
    let sorted: Vec<(Value, Value)> = keyed.into_iter().map(|(_, kv)| kv).collect();
    h.arr_set_pairs(&arr, sorted);
    Value::bool(true)
}

/// Natural-order string comparison (PHP `strnatcmp`): digit runs compare
/// numerically, everything else by code point; leading whitespace is skipped.
pub fn nat_cmp(a: &str, b: &str, fold_case: bool) -> Ordering {
    let owned_a;
    let owned_b;
    let (a, b) = if fold_case {
        owned_a = a.to_lowercase();
        owned_b = b.to_lowercase();
        (owned_a.as_str(), owned_b.as_str())
    } else {
        (a, b)
    };
    let ca: Vec<char> = a.chars().collect();
    let cb: Vec<char> = b.chars().collect();
    let (mut i, mut j) = (0usize, 0usize);
    loop {
        while i < ca.len() && ca[i].is_whitespace() {
            i += 1;
        }
        while j < cb.len() && cb[j].is_whitespace() {
            j += 1;
        }
        if i >= ca.len() || j >= cb.len() {
            break;
        }
        if ca[i].is_ascii_digit() && cb[j].is_ascii_digit() {
            let mut i2 = i;
            while i2 < ca.len() && ca[i2].is_ascii_digit() {
                i2 += 1;
            }
            let mut j2 = j;
            while j2 < cb.len() && cb[j2].is_ascii_digit() {
                j2 += 1;
            }
            // Compare the digit runs the way PHP `strnatcmp` does (Martin Pool's
            // algorithm). If either run has a leading zero the comparison is
            // "fractional": the runs are compared left-aligned, character by
            // character, so the first differing digit decides and a shorter run
            // that is a prefix of the other sorts first. That makes "010" < "10"
            // ('0' < '1') instead of folding both to 10. Otherwise (neither run
            // has a leading zero) the runs compare by magnitude: the longer run
            // wins, and at equal length the lexical order of the digits decides.
            let na: &[char] = &ca[i..i2];
            let nb: &[char] = &cb[j..j2];
            let fractional = na.first() == Some(&'0') || nb.first() == Some(&'0');
            let cmp = if fractional {
                na.cmp(nb)
            } else if na.len() != nb.len() {
                na.len().cmp(&nb.len())
            } else {
                na.cmp(nb)
            };
            if cmp != Ordering::Equal {
                return cmp;
            }
            i = i2;
            j = j2;
            continue;
        }
        if ca[i] != cb[j] {
            return ca[i].cmp(&cb[j]);
        }
        i += 1;
        j += 1;
    }
    (ca.len() - i).cmp(&(cb.len() - j))
}

// ── shuffle / array_rand ─────────────────────────────────────────────────────
// Both draw from the default Mt19937 engine that `mt_srand` seeds, through the
// reference's own range reduction — so a seeded program sees the reference's
// order. See `crate::stdlib::math::php_random_range`.

/// `shuffle($array)` — randomize order and reindex 0..n in place; returns `true`.
///
/// Port of `php_array_data_shuffle`: walk `n_left` down from the last index,
/// swapping it with a uniform pick from `0..=n_left`.
fn php_shuffle(h: &mut host::PhpHost, args: &[Value]) -> Value {
    let arr = arg(args, 0);
    let mut vals: Vec<Value> = h
        .array_pairs(&arr)
        .unwrap_or_default()
        .into_iter()
        .map(|(_, v)| v)
        .collect();
    for n_left in (1..vals.len()).rev() {
        let j = php_random_range(0, n_left as i64) as usize;
        vals.swap(n_left, j);
    }
    h.arr_set_reindexed(&arr, vals);
    Value::bool(true)
}

/// `array_rand($array, $num = 1)` — a random key (num == 1) or an array of `num`
/// distinct keys (in original order). `$num` outside `1..=count` is a fatal error.
///
/// Port of `php_array_pick_keys`. One key is a single draw over the positions.
/// Several are chosen by drawing positions into a bitset until `num` distinct
/// ones are in — or, when `num` is more than half the array, the `count - num`
/// positions to LEAVE OUT — and the keys are then read off in array order.
fn php_array_rand(h: &mut host::PhpHost, args: &[Value]) -> Result<Value, String> {
    let arr = arg(args, 0);
    let keys: Vec<Value> = h
        .array_pairs(&arr)
        .unwrap_or_default()
        .into_iter()
        .map(|(k, _)| k)
        .collect();
    let len = keys.len();
    let num = if args.len() > 1 {
        h.to_number(&arg(args, 1)).to_int()
    } else {
        1
    };
    // An EMPTY array is reported against argument #1, not #2: there is no
    // `$num` that would work, so the reference names the array instead.
    if len == 0 {
        return Err(throws(
            "ValueError",
            "array_rand(): Argument #1 ($array) must not be empty",
        ));
    }
    if num == 1 {
        return Ok(keys[php_random_range(0, len as i64 - 1) as usize].clone());
    }
    if num < 1 || num as usize > len {
        return Err(throws(
            "ValueError",
            "array_rand(): Argument #2 ($num) must be between 1 and the number of elements in \
             argument #1 ($array)",
        ));
    }
    let mut want = num as usize;
    let negative = want > len >> 1;
    if negative {
        want = len - want;
    }
    let mut picked = vec![false; len];
    while want > 0 {
        let i = php_random_range(0, len as i64 - 1) as usize;
        if !picked[i] {
            picked[i] = true;
            want -= 1;
        }
    }
    let out = h.new_array();
    for (key, hit) in keys.into_iter().zip(picked) {
        if hit != negative {
            h.arr_push_auto(&out, key);
        }
    }
    Ok(out)
}

// ── array_walk ───────────────────────────────────────────────────────────────

/// `array_walk($array, $callback, $extra = null)` — call `$callback($value, $key
/// [, $extra])` for every element; always returns `true`.
///
/// LIMITATION (documented, not a bug we can fix here): in PHP the callback's
/// first parameter is by-reference (`function(&$value, $key)`), so the callback
/// can modify each element in place. phplang has **no by-reference parameters** —
/// every argument is passed by value — so a *scalar* mutated inside the callback
/// does NOT propagate back into the array, unlike PHP. Fixing this faithfully
/// would require VM-level by-reference OUT-parameters, which the VM does not
/// provide and which live outside this module. Array/object elements still
/// reflect mutations, because those are shared heap handles rather than scalars.
fn php_array_walk(args: &[Value]) -> Result<Value, String> {
    let arr = arg(args, 0);
    let cb = arg(args, 1);
    let extra = arg(args, 2);
    let has_extra = args.len() > 2;
    let pairs = host::with_host(|h| h.array_pairs(&arr)).unwrap_or_default();
    for (k, v) in pairs {
        // The value goes in through a reference cell so a `function (&$v)`
        // callback can write to it; anything it stores is copied back into the
        // array under the same key.
        let (cell, slot) = host::with_host(|h| h.new_ref_cell(v));
        let mut call_args = vec![cell, k.clone()];
        if has_extra {
            call_args.push(extra.clone());
        }
        host::call_value(cb.clone(), call_args)?;
        if host::unwinding() {
            return Ok(Value::Undef);
        }
        host::with_host(|h| {
            let updated = h.ref_cell_value(slot);
            h.arr_set_key(&arr, &k, updated);
        });
    }
    Ok(Value::bool(true))
}

// ── compact / extract ────────────────────────────────────────────────────────

/// `compact(...)` — build an array from the given variable names, pulling each
/// bound value out of the current scope. A name may itself be an array of names
/// (recursively). A name that is not bound is skipped WITH a warning, and an
/// argument that is neither a string nor an array is skipped with a different
/// one — `compact()` is diagnostic-heavy and silently dropping either is how a
/// misspelled name goes unnoticed.
fn php_compact(h: &mut host::PhpHost, args: &[Value]) -> Value {
    let out = h.new_array();
    for (i, a) in args.iter().enumerate() {
        // `php_compact_var` carries the TOP-LEVEL argument number into the
        // recursion, so a bad entry nested inside an array of names is still
        // reported against the argument that array was passed as.
        compact_add(h, &out, a, i + 1);
    }
    out
}

fn compact_add(h: &mut host::PhpHost, out: &Value, name: &Value, pos: usize) {
    if h.is_array(name) {
        for (_, n) in h.array_pairs(name).unwrap_or_default() {
            compact_add(h, out, &n, pos);
        }
        return;
    }
    let Value::Str(n) = name else {
        let given = h.type_name_for_error(name);
        h.warn(format_args!(
            "compact(): Argument #{pos} must be string or array of strings, {given} given"
        ));
        return;
    };
    let n = n.to_string();
    // `var_defined`, not a non-`Undef` read: a variable holding `null` IS
    // captured, and only a name that was never bound warns.
    if h.var_defined(&n) {
        let val = h.get_var(&n);
        h.arr_set_key(out, &Value::str(n), val);
    } else {
        h.warn(format_args!("compact(): Undefined variable ${n}"));
    }
}

/// `extract($array)` — import each string-keyed entry as a variable in the
/// current scope; returns the number of variables set. Integer keys are skipped
/// (they are not valid variable names), matching PHP's default behavior.
/// `EXTR_*`, the `$flags` argument of [`php_extract`]. The low bits pick ONE
/// behaviour; `EXTR_REFS` is a separate bit that may be OR'd onto any of them.
mod extr {
    pub const OVERWRITE: i64 = 0;
    pub const SKIP: i64 = 1;
    pub const PREFIX_SAME: i64 = 2;
    pub const PREFIX_ALL: i64 = 3;
    pub const PREFIX_INVALID: i64 = 4;
    pub const PREFIX_IF_EXISTS: i64 = 5;
    pub const IF_EXISTS: i64 = 6;
    pub const REFS: i64 = 256;
}

/// `extract($array, $flags = EXTR_OVERWRITE, $prefix = "")` — bind each element
/// of `$array` to a variable of its key's name, answering how many were bound.
///
/// `$flags` chooses what happens when the name is already taken or is not a
/// legal variable name; four of the seven modes rewrite the name to
/// `"{$prefix}_{$key}"`, and `EXTR_REFS` (a bit, not a mode) binds by REFERENCE
/// so a later write to the variable is visible through the array.
fn php_extract(h: &mut host::PhpHost, args: &[Value]) -> Result<Value, String> {
    let arr = arg(args, 0);
    let raw = if args.len() > 1 {
        h.to_number(&args[1]).to_int()
    } else {
        extr::OVERWRITE
    };
    let by_ref = raw & extr::REFS != 0;
    let mode = raw & !extr::REFS;
    if !(extr::OVERWRITE..=extr::IF_EXISTS).contains(&mode) {
        return Err(throws(
            "ValueError",
            "extract(): Argument #2 ($flags) must be a valid extract type",
        ));
    }
    let prefixed = matches!(
        mode,
        extr::PREFIX_SAME | extr::PREFIX_ALL | extr::PREFIX_INVALID | extr::PREFIX_IF_EXISTS
    );
    let prefix = if args.len() > 2 {
        h.to_str(&args[2])
    } else {
        if prefixed {
            return Err(throws(
                "ValueError",
                "extract(): Argument #3 ($prefix) is required when using this extract type",
            ));
        }
        String::new()
    };
    // An EMPTY prefix is accepted and yields the `_key` names; anything else has
    // to be a legal identifier, since it becomes the head of one.
    if prefixed && !prefix.is_empty() && !is_var_name(&prefix) {
        return Err(throws(
            "ValueError",
            "extract(): Argument #3 ($prefix) must be a valid identifier",
        ));
    }

    let mut count = 0i64;
    for (k, v) in h.array_pairs(&arr).unwrap_or_default() {
        // An integer key is a legal ARRAY key but never a legal variable name,
        // so it is only ever reached through one of the prefixing modes.
        let key = match &k {
            Value::Str(s) => s.to_string(),
            other => h.to_str(other),
        };
        // `this` is spelled like a legal name but can never be assigned, so it is
        // not `plain` either. What the reference then does with it is a MEASURED
        // table rather than one rule — verified flag by flag:
        //   OVERWRITE  refuses outright, PREFIX_SAME/ALL/INVALID all prefix it,
        //   and SKIP, PREFIX_IF_EXISTS and IF_EXISTS pass over it silently.
        // PREFIX_INVALID prefixing it is the tell that the engine counts it among
        // the unusable names, not among the taken ones.
        let reserved = key == "this";
        let plain = is_var_name(&key) && !reserved;
        let exists = plain && h.var_defined(&key);
        let with_prefix = || format!("{prefix}_{key}");
        let target = match mode {
            // The one name `extract()` stops on rather than skipping.
            extr::OVERWRITE if reserved => return Err(throws("Error", "Cannot re-assign $this")),
            extr::OVERWRITE if plain => key.clone(),
            extr::SKIP if plain && !exists => key.clone(),
            // PREFIX_SAME prefixes a name that is TAKEN. A key that is not a
            // spellable name at all is skipped here, not prefixed — only the two
            // modes below rescue one.
            extr::PREFIX_SAME if plain && !exists => key.clone(),
            extr::PREFIX_SAME if plain || reserved => with_prefix(),
            extr::PREFIX_ALL => with_prefix(),
            extr::PREFIX_INVALID if plain => key.clone(),
            extr::PREFIX_INVALID => with_prefix(),
            extr::PREFIX_IF_EXISTS if exists => with_prefix(),
            // `php_extract_prefix_if_exists`: a name the symbol table holds as an
            // UNDEF compiled variable is assigned as itself, unprefixed, and counted.
            extr::PREFIX_IF_EXISTS if plain && h.var_has_slot(&key) => key.clone(),
            extr::IF_EXISTS if exists => key.clone(),
            _ => continue,
        };
        // A prefixing mode can still produce an illegal name — a prefix of `""`
        // in front of a key that starts with a digit, say.
        if !is_var_name(&target) {
            continue;
        }
        if by_ref {
            let slot = h.arr_elem_ref_slot(&arr, &k);
            h.bind_ref_slot(&target, slot);
        } else {
            h.set_var(&target, v);
        }
        count += 1;
    }
    Ok(Value::int(count))
}

/// Whether `s` is a valid PHP variable name (`[A-Za-z_][A-Za-z0-9_]*`).
fn is_var_name(s: &str) -> bool {
    let mut cs = s.chars();
    match cs.next() {
        Some(c) if c == '_' || c.is_ascii_alphabetic() => {}
        _ => return false,
    }
    cs.all(|c| c == '_' || c.is_ascii_alphanumeric())
}

// ── internal pointer (end/reset/current/key/next/prev) ───────────────────────
//
// PHP arrays carry an internal cursor. The heap array here has no cursor field
// and `host.rs` is off-limits, so the cursor lives in a side table keyed by the
// array's handle. A per-handle content fingerprint guards the entry: when the
// array behind a handle changes (a fresh program after `reset_host` reuses the
// same low handles), the fingerprint no longer matches and the cursor resets to
// the first element — so no stale cursor leaks across independent runs.
//
// The fingerprint is deliberately **append-invariant**: it hashes only the first
// element (its key and value), NOT the length or the last key. PHP keeps the
// internal pointer where it is when you append (`$a[] = x`), so a fingerprint
// that changed on append would wrongly rewind the cursor to the start after
// every push. Hashing the first element leaves the cursor untouched across
// appends (they never alter element 0) while still distinguishing an unrelated
// array that reuses the same handle after `reset_host`, as long as that array's
// first element differs.
//
// LIMITATION (documented, not fully fixable here): because the fingerprint is
// content-based, two *different* arrays that happen to share an identical first
// element and land on the same reused handle across a `reset_host` boundary
// could inherit a stale cursor. A fully correct fix needs a real per-array
// cursor field stored in the VM heap alongside the array (so identity is by the
// handle's lifetime, not by content) — that lives in `host.rs`, which is off
// limits for this change. The heuristic below is the closest correct-for-PHP
// behavior (append preserves the pointer) achievable without a VM change.
//
// Positions: `0..len` index the elements; `-1` is the single "invalid" state PHP
// uses once the pointer falls off either end (sticky — `prev`/`next` from it stay
// invalid and return false until `reset`/`end` re-anchors it).

thread_local! {
    static CURSORS: RefCell<HashMap<u32, (u64, i64)>> = RefCell::new(HashMap::new());
}

/// An append-invariant identity fingerprint for an array: it hashes only the
/// first element's key and value (plus whether the array is empty). Appending to
/// the array never touches element 0, so the fingerprint — and therefore the
/// stored cursor — survives an append, matching PHP (the internal pointer stays
/// put across `$a[] = x`). It still changes when an unrelated array reuses the
/// same handle after `reset_host`, provided that array's first element differs.
/// See the module-level LIMITATION note for the residual same-first-element case.
fn fingerprint(h: &host::PhpHost, pairs: &[(Value, Value)]) -> u64 {
    let mut hasher = DefaultHasher::new();
    match pairs.first() {
        Some((k, v)) => {
            1u8.hash(&mut hasher);
            h.to_str(k).hash(&mut hasher);
            h.to_str(v).hash(&mut hasher);
        }
        None => 0u8.hash(&mut hasher),
    }
    hasher.finish()
}

/// The stored cursor position for `handle`, or `0` (the fresh default) when there
/// is no entry or the array's fingerprint has changed under it.
fn cursor_pos(handle: u32, fp: u64) -> i64 {
    CURSORS.with(|c| match c.borrow().get(&handle) {
        Some((f, pos)) if *f == fp => *pos,
        _ => 0,
    })
}

fn cursor_set(handle: u32, fp: u64, pos: i64) {
    CURSORS.with(|c| {
        c.borrow_mut().insert(handle, (fp, pos));
    });
}

/// The array's handle, its `(key, value)` pairs, and its identity fingerprint.
type PtrCtx = (u32, Vec<(Value, Value)>, u64);

/// Common preamble for the pointer builtins — or `None` if the argument is not
/// an array.
fn ptr_ctx(h: &host::PhpHost, args: &[Value]) -> Option<PtrCtx> {
    let v = arg(args, 0);
    let handle = as_handle(&v)?;
    if !h.is_array(&v) {
        return None;
    }
    let pairs = h.array_pairs(&v).unwrap_or_default();
    let fp = fingerprint(h, &pairs);
    Some((handle, pairs, fp))
}

fn ptr_reset(h: &mut host::PhpHost, args: &[Value]) -> Value {
    let Some((handle, pairs, fp)) = ptr_ctx(h, args) else {
        return Value::bool(false);
    };
    if pairs.is_empty() {
        cursor_set(handle, fp, -1);
        return Value::bool(false);
    }
    cursor_set(handle, fp, 0);
    pairs[0].1.clone()
}

fn ptr_end(h: &mut host::PhpHost, args: &[Value]) -> Value {
    let Some((handle, pairs, fp)) = ptr_ctx(h, args) else {
        return Value::bool(false);
    };
    if pairs.is_empty() {
        cursor_set(handle, fp, -1);
        return Value::bool(false);
    }
    let last = pairs.len() - 1;
    cursor_set(handle, fp, last as i64);
    pairs[last].1.clone()
}

fn ptr_current(h: &mut host::PhpHost, args: &[Value]) -> Value {
    let Some((handle, pairs, fp)) = ptr_ctx(h, args) else {
        return Value::bool(false);
    };
    let pos = cursor_pos(handle, fp);
    if pos >= 0 && (pos as usize) < pairs.len() {
        pairs[pos as usize].1.clone()
    } else {
        Value::bool(false)
    }
}

fn ptr_key(h: &mut host::PhpHost, args: &[Value]) -> Value {
    let Some((handle, pairs, fp)) = ptr_ctx(h, args) else {
        return Value::Undef;
    };
    let pos = cursor_pos(handle, fp);
    if pos >= 0 && (pos as usize) < pairs.len() {
        pairs[pos as usize].0.clone()
    } else {
        Value::Undef
    }
}

/// `next` (`delta = 1`) / `prev` (`delta = -1`): step the cursor and return the
/// value at the new position, or `false` once it falls off the end (staying in
/// the sticky invalid state).
fn ptr_step(h: &mut host::PhpHost, args: &[Value], delta: i64) -> Value {
    let Some((handle, pairs, fp)) = ptr_ctx(h, args) else {
        return Value::bool(false);
    };
    let pos = cursor_pos(handle, fp);
    // Already invalid: stay invalid (PHP's off-the-end pointer is sticky).
    if pos < 0 {
        cursor_set(handle, fp, -1);
        return Value::bool(false);
    }
    let np = pos + delta;
    if np >= 0 && (np as usize) < pairs.len() {
        cursor_set(handle, fp, np);
        pairs[np as usize].1.clone()
    } else {
        cursor_set(handle, fp, -1);
        Value::bool(false)
    }
}