bcgen-lang 0.2.0

Compiles HIR to LSB bytecode: the path from a forged language's meaning to code bvm-lang runs.
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
//! Assignment to places: variables, globals, and chains of index, property,
//! and append steps, with PHP's auto-vivification and copy-on-write
//! separation under [`ArraySemantics::Php`](crate::ArraySemantics::Php).

use alloc::vec::Vec;

use bytecode_lang::{Inst, Kind, Reg, ValType};
use hir_lang::{Expr, ExprId, ItemKind, Member, NodeRef, Op, Res, Symbol};
use intern_lang::Lookup;

use super::{Dst, Gen, Rel, Step, Task, Val};
use crate::error::{CompileError, Unsupported};
use crate::options::KeyCoercion;
use crate::unit::Slot;

/// One step of a place chain, from the root outward.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum PStep {
    /// `[key]`: the key is on the value stack (normalized).
    Index,
    /// `->$name`: the name is on the value stack (not normalized).
    DynProp,
    /// `.name`.
    Prop(Symbol),
    /// `.0`.
    Elem(u32),
    /// `[]`.
    Append,
}

/// Where a place chain starts.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Root {
    /// A variable or global (written back when a write creates the array).
    Slot(Slot),
    /// Any other expression, evaluated to a temporary (on the value stack).
    Value,
}

/// The continuation steps of assignments.
#[derive(Clone, Debug)]
pub(crate) enum PlaceStep {
    /// `x op= v` for a variable in a register: `old` holds its value from
    /// before `v` was evaluated.
    LocalCompound {
        op: Op,
        old: Reg,
        own_old: bool,
        reg: Reg,
        dst: Dst,
        node: NodeRef,
    },
    /// `x = v` / `x op= v` for a cell or global variable.
    Store {
        slot: Slot,
        op: Option<Op>,
        old: Option<Reg>,
        dup: bool,
        dst: Dst,
        node: NodeRef,
    },
    /// Reads the current value at the end of a chain (compound assignment).
    ChainRead {
        root: Root,
        steps: Vec<PStep>,
        node: NodeRef,
    },
    /// Combines the old value (below) with the assigned one (on top).
    Combine { op: Op, node: NodeRef },
    /// Writes the value on top of the stack through the chain.
    ChainWrite {
        root: Root,
        steps: Vec<PStep>,
        dup: bool,
        dst: Dst,
        node: NodeRef,
    },
}

impl<L: Lookup> Gen<'_, '_, L> {
    /// The slot a path names as an assignment target.
    fn place_slot(&self, e: ExprId) -> Result<Option<Slot>, CompileError> {
        let node = NodeRef::Expr(e);
        let hir = self.cx.hir;
        let Expr::Path(p) = *hir.expr(e) else {
            return Ok(None);
        };
        let path = *hir.path(p);
        if path.unresolved > 0 {
            return Err(self.cx.unsupported(Unsupported::TypeDirected, node));
        }
        match path.res {
            Res::Local(b) => Ok(self.cx.slot(b)),
            Res::Def(_) => {
                let item = self.cx.local_item(path.res, node)?;
                match item.map(|i| (i, hir.item(i).kind)) {
                    Some((i, ItemKind::Global { .. })) => Ok(self.cx.global_slot(i)),
                    _ => Err(CompileError::NotAssignable {
                        node,
                        span: self.cx.span(node),
                    }),
                }
            }
            Res::Unresolved | Res::Err => Err(CompileError::Unresolved {
                node,
                span: self.cx.span(node),
            }),
            _ => Err(CompileError::NotAssignable {
                node,
                span: self.cx.span(node),
            }),
        }
    }

    pub(crate) fn assign(
        &mut self,
        e: ExprId,
        target: ExprId,
        op: Option<Op>,
        value: ExprId,
        dst: Dst,
    ) -> Result<(), CompileError> {
        let node = NodeRef::Expr(e);
        let tnode = NodeRef::Expr(target);
        let hir = self.cx.hir;
        let dup = self.needs_dup(value);
        match *hir.expr(target) {
            Expr::Path(_) => {
                let Some(slot) = self.place_slot(target)? else {
                    return Err(CompileError::Unresolved {
                        node: tnode,
                        span: self.cx.span(tnode),
                    });
                };
                match (slot, op) {
                    (Slot::Reg(r), None) => {
                        let t = self.store_expr_tasks(value, r);
                        self.sched([
                            t[0].clone(),
                            t[1].clone(),
                            Task::Push(Val {
                                reg: r,
                                rel: Rel::Keep,
                            }),
                            Task::Deliver { dst, dup: false },
                        ]);
                    }
                    (Slot::Reg(r), Some(op)) => {
                        // The old value is read before `value` runs.
                        let (old, own_old) = if self.simple(value) {
                            (r, false)
                        } else {
                            let t = self.fx.temp(ValType::Dyn);
                            self.emit(Inst::Mov { dst: t, src: r });
                            (t, true)
                        };
                        self.sched([
                            Task::Expr(value, Dst::Any),
                            Task::Step(Step::Place(PlaceStep::LocalCompound {
                                op,
                                old,
                                own_old,
                                reg: r,
                                dst,
                                node,
                            })),
                        ]);
                    }
                    (slot, op) => {
                        let old = op.map(|_| {
                            let t = self.fx.temp(ValType::Dyn);
                            self.read_slot(slot, t);
                            t
                        });
                        self.sched([
                            Task::Expr(value, Dst::Any),
                            Task::Step(Step::Place(PlaceStep::Store {
                                slot,
                                op,
                                old,
                                dup,
                                dst,
                                node,
                            })),
                        ]);
                    }
                }
            }
            Expr::Index { .. } | Expr::Field { .. } | Expr::DynField { .. } | Expr::Append(_) => {
                let (root, root_expr, steps, keys) = self.chain(target)?;
                if op.is_some() && steps.contains(&PStep::Append) {
                    return Err(CompileError::NotAssignable {
                        node: tnode,
                        span: self.cx.span(tnode),
                    });
                }
                let mut ts: Vec<Task> = Vec::new();
                if let Some(re) = root_expr {
                    ts.push(Task::Expr(re, Dst::Temp));
                }
                for (k, is_index) in keys {
                    ts.push(Task::Expr(k, Dst::Temp));
                    if is_index {
                        ts.push(Task::CoerceKey(node));
                    }
                }
                if let Some(op) = op {
                    ts.push(Task::Step(Step::Place(PlaceStep::ChainRead {
                        root,
                        steps: steps.clone(),
                        node,
                    })));
                    ts.push(Task::Expr(value, Dst::Any));
                    ts.push(Task::Step(Step::Place(PlaceStep::Combine { op, node })));
                } else {
                    ts.push(Task::Expr(value, Dst::Any));
                }
                ts.push(Task::Step(Step::Place(PlaceStep::ChainWrite {
                    root,
                    steps,
                    dup: dup && op.is_none(),
                    dst,
                    node,
                })));
                for t in ts.into_iter().rev() {
                    self.tasks.push(t);
                }
            }
            Expr::VarVar(_) => return Err(self.cx.unsupported(Unsupported::VarVar, tnode)),
            Expr::Deref(_) => return Err(self.cx.unsupported(Unsupported::Reference, tnode)),
            Expr::Err => {
                return Err(CompileError::ErrorNode {
                    node: tnode,
                    span: self.cx.span(tnode),
                });
            }
            _ => {
                return Err(CompileError::NotAssignable {
                    node: tnode,
                    span: self.cx.span(tnode),
                });
            }
        }
        Ok(())
    }

    /// Decomposes a place into its root and steps (root first), with the
    /// key expressions to evaluate in order (and whether each is an index
    /// key, which PHP normalizes).
    #[allow(clippy::type_complexity)]
    fn chain(
        &self,
        target: ExprId,
    ) -> Result<(Root, Option<ExprId>, Vec<PStep>, Vec<(ExprId, bool)>), CompileError> {
        let hir = self.cx.hir;
        let mut steps: Vec<PStep> = Vec::new();
        let mut keys: Vec<(ExprId, bool)> = Vec::new();
        let mut cur = target;
        let root = loop {
            match *hir.expr(cur) {
                Expr::Index { base, index } => {
                    steps.push(PStep::Index);
                    keys.push((index, true));
                    cur = base;
                }
                Expr::DynField { base, name } => {
                    steps.push(PStep::DynProp);
                    keys.push((name, false));
                    cur = base;
                }
                Expr::Field { base, member, .. } => {
                    steps.push(match member {
                        Member::Named(s) => PStep::Prop(s),
                        Member::Index(i) => PStep::Elem(i),
                    });
                    cur = base;
                }
                Expr::Append(base) => {
                    steps.push(PStep::Append);
                    cur = base;
                }
                Expr::Path(_) => match self.place_slot(cur) {
                    Ok(Some(s)) => break (Root::Slot(s), None),
                    Ok(None) => {
                        let node = NodeRef::Expr(cur);
                        return Err(CompileError::Unresolved {
                            node,
                            span: self.cx.span(node),
                        });
                    }
                    // A path that is not a variable (a function, a
                    // constant): an ordinary value root.
                    Err(CompileError::NotAssignable { .. }) => break (Root::Value, Some(cur)),
                    Err(e) => return Err(e),
                },
                _ => break (Root::Value, Some(cur)),
            }
        };
        steps.reverse();
        keys.reverse();
        Ok((root.0, root.1, steps, keys))
    }

    pub(crate) fn ref_assign(
        &mut self,
        e: ExprId,
        target: ExprId,
        source: ExprId,
        dst: Dst,
    ) -> Result<(), CompileError> {
        let node = NodeRef::Expr(e);
        let t = self.place_slot(target).ok().flatten();
        let s = self.place_slot(source).ok().flatten();
        match (t, s) {
            (Some(Slot::Cell(tc)), Some(s @ (Slot::Cell(_) | Slot::GlobalCell(_)))) => {
                // The target variable now names the source's cell.
                if let Some((sc, owned)) = self.cell_of(s) {
                    self.emit(Inst::Mov { dst: tc, src: sc });
                    if owned {
                        self.fx.release(sc);
                    }
                }
                if dst != Dst::Discard {
                    let r = self.result_reg(dst);
                    self.emit(Inst::CellGet { dst: r, cell: tc });
                    self.produced(r, dst);
                }
                Ok(())
            }
            _ => Err(self.cx.unsupported(Unsupported::RefPlace, node)),
        }
    }

    pub(crate) fn place_step(&mut self, p: PlaceStep) -> Result<(), CompileError> {
        match p {
            PlaceStep::LocalCompound {
                op,
                old,
                own_old,
                reg,
                dst,
                node,
            } => {
                self.at(node);
                let v = self.pop();
                super::ops::emit_op(self, op, &[old, v.reg], reg, node)?;
                self.release(v);
                if own_old {
                    self.fx.release(old);
                }
                self.deliver(
                    Val {
                        reg,
                        rel: Rel::Keep,
                    },
                    dst,
                    false,
                );
            }
            PlaceStep::Store {
                slot,
                op,
                old,
                dup,
                dst,
                node,
            } => {
                self.at(node);
                let v = self.pop();
                let v = match (op, old) {
                    (Some(op), Some(old)) => {
                        let r = self.fx.temp(ValType::Dyn);
                        super::ops::emit_op(self, op, &[old, v.reg], r, node)?;
                        self.release(v);
                        self.fx.release(old);
                        Val {
                            reg: r,
                            rel: Rel::Temp,
                        }
                    }
                    _ => self.transfer(v, dup),
                };
                self.write_slot(slot, v.reg);
                self.deliver(v, dst, false);
            }
            PlaceStep::ChainRead { root, steps, node } => {
                self.at(node);
                let nkeys = steps
                    .iter()
                    .filter(|s| matches!(s, PStep::Index | PStep::DynProp))
                    .count();
                let base = self.vals.len().saturating_sub(nkeys);
                let keys: Vec<Reg> = self
                    .vals
                    .get(base..)
                    .map_or(Vec::new(), |v| v.iter().map(|v| v.reg).collect());
                let root_val = match root {
                    Root::Value => self.vals.get(base.saturating_sub(1)).map(|v| v.reg),
                    Root::Slot(_) => None,
                };
                let cur = self.fx.temp(ValType::Dyn);
                match (root, root_val) {
                    (Root::Slot(s), _) => self.read_slot(s, cur),
                    (Root::Value, Some(r)) => self.emit(Inst::Mov { dst: cur, src: r }),
                    (Root::Value, None) => self.emit(Inst::LoadNil { dst: cur }),
                }
                let mut ki = 0usize;
                for s in &steps {
                    match *s {
                        PStep::Index | PStep::DynProp => {
                            let k = keys.get(ki).copied().unwrap_or(Reg(0));
                            ki += 1;
                            self.emit(Inst::DGetIndex {
                                dst: cur,
                                obj: cur,
                                key: k,
                            });
                        }
                        PStep::Elem(i) => {
                            let k = self.fx.temp(ValType::Dyn);
                            self.load_dyn_int(k, i64::from(i));
                            self.emit(Inst::DGetIndex {
                                dst: cur,
                                obj: cur,
                                key: k,
                            });
                            self.fx.release(k);
                        }
                        PStep::Prop(name) => {
                            let n = self.name_ref(name);
                            self.emit(Inst::GetProp {
                                dst: cur,
                                obj: cur,
                                name: n,
                            });
                        }
                        PStep::Append => {}
                    }
                }
                self.vals.push(Val {
                    reg: cur,
                    rel: Rel::Temp,
                });
            }
            PlaceStep::Combine { op, node } => {
                self.at(node);
                let v = self.pop();
                let old = self.pop();
                let r = self.fx.temp(ValType::Dyn);
                super::ops::emit_op(self, op, &[old.reg, v.reg], r, node)?;
                self.release(v);
                self.release(old);
                self.vals.push(Val {
                    reg: r,
                    rel: Rel::Temp,
                });
            }
            PlaceStep::ChainWrite {
                root,
                steps,
                dup,
                dst,
                node,
            } => {
                self.at(node);
                let v = self.pop();
                let v = self.transfer(v, dup);
                let nkeys = steps
                    .iter()
                    .filter(|s| matches!(s, PStep::Index | PStep::DynProp))
                    .count();
                let keys = self.pop_n(nkeys);
                let root_val = match root {
                    Root::Value => Some(self.pop()),
                    Root::Slot(_) => None,
                };
                self.chain_write(root, root_val.map(|r| r.reg), &steps, &keys, v.reg);
                for k in keys {
                    self.release(k);
                }
                if let Some(r) = root_val {
                    self.release(r);
                }
                self.deliver(v, dst, false);
            }
        }
        Ok(())
    }

    /// Writes `v` through the chain.
    fn chain_write(
        &mut self,
        root: Root,
        root_val: Option<Reg>,
        steps: &[PStep],
        keys: &[Val],
        v: Reg,
    ) {
        let php = self.php();
        let map_ty = self.map_ty();
        let tr = self.map_ref();
        let cur = self.fx.temp(ValType::Dyn);
        let b = self.fx.temp(ValType::Bool);
        match (root, root_val) {
            (Root::Slot(s), _) => self.read_slot(s, cur),
            (Root::Value, Some(r)) => self.emit(Inst::Mov { dst: cur, src: r }),
            (Root::Value, None) => self.emit(Inst::LoadNil { dst: cur }),
        }
        if php {
            // Writing into null creates the array (auto-vivification).
            let have = self.label();
            self.emit(Inst::IsKind {
                dst: b,
                src: cur,
                kind: Kind::Nil,
            });
            self.jump_on(b, have, false);
            let m = self.new_map();
            self.emit(Inst::Mov { dst: cur, src: m });
            self.fx.release(m);
            if let Root::Slot(s) = root {
                self.write_slot(s, cur);
            }
            self.bind(have);
        }
        let mut ki = 0usize;
        let last = steps.len().saturating_sub(1);
        for (i, s) in steps.iter().enumerate() {
            // The key of a keyed step, as a `dyn` value.
            let (key, own) = match *s {
                PStep::Index | PStep::DynProp => {
                    let k = keys.get(ki).map_or(Reg(0), |v| v.reg);
                    ki += 1;
                    (Some(k), false)
                }
                PStep::Elem(n) => {
                    let k = self.fx.temp(ValType::Dyn);
                    self.load_dyn_int(k, i64::from(n));
                    (Some(k), true)
                }
                PStep::Prop(name) => (Some(self.load_name(name)), true),
                PStep::Append => (None, false),
            };
            if i == last {
                match (*s, key) {
                    (PStep::Prop(name), _) => {
                        let n = self.name_ref(name);
                        self.emit(Inst::SetProp {
                            obj: cur,
                            name: n,
                            src: v,
                        });
                    }
                    (PStep::Append, _) => {
                        let bad = self.label();
                        let done = self.label();
                        self.emit(Inst::IsType {
                            dst: b,
                            src: cur,
                            ty: tr,
                        });
                        self.jump_on(b, bad, false);
                        let m = self.fx.temp(map_ty);
                        self.emit(Inst::Cast {
                            dst: m,
                            src: cur,
                            ty: tr,
                        });
                        self.emit(Inst::MapPush { map: m, src: v });
                        self.fx.release(m);
                        self.jmp(done);
                        self.bind(bad);
                        self.raise_type_error();
                        self.bind(done);
                    }
                    (_, Some(k)) => self.emit(Inst::DSetIndex {
                        obj: cur,
                        key: k,
                        src: v,
                    }),
                    (_, None) => {}
                }
            } else {
                self.chain_step(*s, cur, key, b, php);
            }
            if own {
                if let Some(k) = key {
                    self.fx.release(k);
                }
            }
        }
        self.fx.release(b);
        self.fx.release(cur);
    }

    /// Moves `cur` one intermediate step down a write chain: to the child
    /// array, creating it when absent or null (PHP), separating it from any
    /// copy that shares it (PHP), and storing it back into its container.
    fn chain_step(&mut self, s: PStep, cur: Reg, key: Option<Reg>, b: Reg, php: bool) {
        let map_ty = self.map_ty();
        let tr = self.map_ref();
        if !php {
            // Shared references: read the child as an expression would.
            match (s, key) {
                (PStep::Prop(name), _) => {
                    let n = self.name_ref(name);
                    self.emit(Inst::GetProp {
                        dst: cur,
                        obj: cur,
                        name: n,
                    });
                    return;
                }
                (PStep::Append, _) => {}
                (_, Some(k)) => {
                    self.emit(Inst::DGetIndex {
                        dst: cur,
                        obj: cur,
                        key: k,
                    });
                    return;
                }
                (_, None) => return,
            }
        }
        let other = self.label();
        let done = self.label();
        self.emit(Inst::IsType {
            dst: b,
            src: cur,
            ty: tr,
        });
        self.jump_on(b, other, false);
        let m = self.fx.temp(map_ty);
        self.emit(Inst::Cast {
            dst: m,
            src: cur,
            ty: tr,
        });
        match (s, key) {
            (PStep::Append, _) => {
                // `$a[][...] = v`: a new array appended.
                let n = self.new_map();
                self.emit(Inst::MapPush { map: m, src: n });
                self.emit(Inst::Mov { dst: cur, src: n });
                self.fx.release(n);
            }
            (_, Some(k)) if php => {
                let sep = self.label();
                let child = self.fx.temp(ValType::Dyn);
                self.emit(Inst::MapFind {
                    dst: child,
                    map: m,
                    key: k,
                });
                self.emit(Inst::IsKind {
                    dst: b,
                    src: child,
                    kind: Kind::Nil,
                });
                self.jump_on(b, sep, false);
                let n = self.new_map();
                self.emit(Inst::Mov { dst: child, src: n });
                self.fx.release(n);
                self.emit(Inst::MapSet {
                    map: m,
                    key: k,
                    src: child,
                });
                self.emit(Inst::Mov {
                    dst: cur,
                    src: child,
                });
                self.jmp(done);
                self.bind(sep);
                let keep = self.label();
                self.emit(Inst::IsKind {
                    dst: b,
                    src: child,
                    kind: Kind::Map,
                });
                self.jump_on(b, keep, false);
                self.emit(Inst::Dup {
                    dst: child,
                    src: child,
                });
                self.emit(Inst::MapSet {
                    map: m,
                    key: k,
                    src: child,
                });
                self.bind(keep);
                self.emit(Inst::Mov {
                    dst: cur,
                    src: child,
                });
                self.fx.release(child);
            }
            (_, _) => {}
        }
        self.fx.release(m);
        self.jmp(done);
        // Not a map: the dynamic instructions (and their hooks) decide.
        self.bind(other);
        match (s, key) {
            (PStep::Prop(name), _) => {
                let n = self.name_ref(name);
                self.emit(Inst::GetProp {
                    dst: cur,
                    obj: cur,
                    name: n,
                });
            }
            (PStep::Append, _) => self.raise_type_error(),
            (_, Some(k)) => self.emit(Inst::DGetIndex {
                dst: cur,
                obj: cur,
                key: k,
            }),
            (_, None) => {}
        }
        self.bind(done);
    }

    /// Normalizes a map key (PHP key coercion): integers pass; anything else
    /// goes through the module's `<php_key>` function.
    pub(crate) fn coerce_key(&mut self, k: Val) -> Val {
        if self.cx.opts.keys() != KeyCoercion::Php {
            return k;
        }
        let out = self.fx.temp(ValType::Dyn);
        let b = self.fx.temp(ValType::Bool);
        let done = self.label();
        self.emit(Inst::Mov {
            dst: out,
            src: k.reg,
        });
        self.emit(Inst::IsKind {
            dst: b,
            src: k.reg,
            kind: Kind::Int,
        });
        self.jump_on(b, done, true);
        let f = self.cx.php_key();
        let win = self.fx.window(&[ValType::Dyn, ValType::Dyn]);
        self.emit(Inst::Mov {
            dst: crate::func::FnCx::slot(win.1, 1),
            src: k.reg,
        });
        self.emit(Inst::Call {
            dst: win.1,
            func: f,
            argc: 1,
        });
        self.emit(Inst::Mov {
            dst: out,
            src: win.1,
        });
        self.fx.release_window(win.0, win.1);
        self.bind(done);
        self.fx.release(b);
        self.release(k);
        Val {
            reg: out,
            rel: Rel::Temp,
        }
    }
}