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
//! The PHP abstract syntax tree produced by `parser` and consumed by `compiler`.
//!
//! This is the scaffold subset: scalars, variables, arrays, the common operators,
//! `if`/`while`/`for`/`foreach`, function definition and call, and `echo`/`print`.
//! Classes, traits, namespaces, closures, and references are later waves.

/// The prefix that marks a function or constant name the parser could not settle:
/// an UNQUALIFIED name written inside a namespace. PHP resolves those at run time
/// (`ZEND_INIT_NS_FCALL_BY_NAME`, `IS_CONSTANT_UNQUALIFIED_IN_NAMESPACE`): the
/// namespaced name first, then the global one. No PHP identifier can contain the
/// byte, so a marked name never collides with a real one.
pub const NS_FALLBACK: char = '\u{1}';

/// `ns\name` marked as a run-time fallback to the global `name` — see
/// [`NS_FALLBACK`].
pub fn ns_fallback(qualified: &str) -> String {
    format!("{NS_FALLBACK}{qualified}")
}

/// The `(namespaced, global)` pair a [`ns_fallback`] name stands for, or `None`
/// for a name the parser settled.
pub fn split_ns_fallback(name: &str) -> Option<(&str, &str)> {
    let qualified = name.strip_prefix(NS_FALLBACK)?;
    let global = qualified.rsplit('\\').next().unwrap_or(qualified);
    Some((qualified, global))
}

/// A binary operator.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BinOp {
    Add,
    Sub,
    Mul,
    Div,
    Mod,
    Pow,
    Concat, // .
    // Comparison
    LooseEq,  // ==
    LooseNe,  // != / <>
    StrictEq, // ===
    StrictNe, // !==
    Lt,
    Gt,
    Le,
    Ge,
    Spaceship, // <=>
    // Bitwise
    BitAnd, // &
    BitOr,  // |
    BitXor, // ^
    Shl,    // <<
    Shr,    // >>
    // Logical (short-circuit handled in the compiler)
    And, // && / and
    Or,  // || / or
}

/// A unary prefix operator.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UnOp {
    Neg,    // -x
    Pos,    // +x
    Not,    // !x
    BitNot, // ~x
}

/// One segment of a double-quoted / interpolated string.
#[derive(Debug, Clone, PartialEq)]
pub enum StrPart {
    /// A literal run of text.
    Lit(String),
    /// An interpolated `$name` variable.
    Var(String),
    /// PHP source for an interpolation the lexer cannot resolve to a bare name:
    /// the complex form `{$expr}`, and the simple forms `$a->p` and `$a[k]`.
    /// The lexer only records the text — parsing it is the parser's job.
    Raw(String),
}

/// One segment of a *parsed* interpolated string. The parser turns the lexer's
/// [`StrPart`] list into this: a `Var` becomes the expression that reads it and a
/// `Raw` is parsed, so the compiler sees only literal text and expressions.
#[derive(Debug, Clone)]
pub enum InterpPart {
    Lit(String),
    Expr(Box<Expr>),
}

/// What stands to the left of a `::`.
///
/// PHP accepts both a name known at compile time and a value computed at run
/// time (`$cls::CONST`, `$obj::m()`, `$arr['k']::class`), and the two resolve
/// very differently: a name may be the relative `self`/`parent`/`static`, while
/// a value must turn out to be an object or a class-name string or the access
/// is an `Error`.
#[derive(Debug, Clone)]
pub enum ClassRef {
    /// A bareword class name, or one of `self` / `parent` / `static`. Also the
    /// string-literal form `"C"::K`, which PHP resolves the same way.
    Name(String),
    /// `$expr::` — the class is whatever the expression yields at run time.
    Expr(Box<Expr>),
}

impl ClassRef {
    /// The compile-time name, when there is one. `None` for the dynamic form,
    /// which nothing may resolve, forward or diagnose before it runs.
    pub fn name(&self) -> Option<&str> {
        match self {
            ClassRef::Name(n) => Some(n),
            ClassRef::Expr(_) => None,
        }
    }

    /// The operand expression, when the class is computed. Every walk over an
    /// expression tree has to descend through this — a `$cls::K` reads `$cls`
    /// like any other use of it.
    pub fn operand(&self) -> Option<&Expr> {
        match self {
            ClassRef::Name(_) => None,
            ClassRef::Expr(e) => Some(e),
        }
    }
}

/// How an [`Expr::Array`] was spelled — `ZEND_ARRAY_SYNTAX_SHORT` / `_LIST` /
/// `_LONG`. All three build the same value; the spelling matters only to a
/// destructuring target, where PHP refuses `array()` and a nested pattern
/// whose spelling differs from its parent's (`Cannot mix [] and list()`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ArraySyntax {
    /// `[...]`
    Short,
    /// `list(...)`
    List,
    /// `array(...)`
    Long,
}

/// One element of an [`Expr::Array`] — a literal entry, or one target of a
/// destructuring pattern, since both spellings parse to the same node.
///
/// `by_ref` is the `&` in `[&$x, $y] = $a`. It is meaningful only in a
/// destructuring TARGET, where it makes the target an alias of the source
/// element rather than a copy of it, so a later write through the target is
/// visible in the source array.
#[derive(Debug, Clone)]
pub struct ArrayElem {
    /// `None` means the next auto-increment integer index.
    pub key: Option<Expr>,
    pub value: Expr,
    pub by_ref: bool,
}

impl ArrayElem {
    /// A plain `key => value` entry with no `&`, which is what every
    /// construction site that predates by-reference targets wants.
    pub fn new(key: Option<Expr>, value: Expr) -> Self {
        Self {
            key,
            value,
            by_ref: false,
        }
    }
}

/// The member named after `->` or `?->`.
///
/// `$o->p` and `$o->{"p"}` (a string literal between the braces) are the same
/// static name. `$o->$n` and `$o->{expr}` compute the name at run time: the
/// expression is evaluated after the receiver and converted to a string by the
/// access itself, as `ZEND_FETCH_OBJ_*` / `ZEND_INIT_METHOD_CALL` do with a
/// non-constant op2.
#[derive(Debug, Clone)]
pub enum Member {
    Name(String),
    Dyn(Box<Expr>),
}

impl Member {
    /// The name when it is spelled in the source, `None` when it is computed.
    pub fn name(&self) -> Option<&str> {
        match self {
            Member::Name(n) => Some(n),
            Member::Dyn(_) => None,
        }
    }

    /// The expression a computed name evaluates, for walkers that visit every
    /// subexpression.
    pub fn operand(&self) -> Option<&Expr> {
        match self {
            Member::Name(_) => None,
            Member::Dyn(e) => Some(e),
        }
    }
}

/// An expression.
#[derive(Debug, Clone)]
pub enum Expr {
    Null,
    Bool(bool),
    Int(i64),
    Float(f64),
    /// A single-quoted string (no interpolation).
    Str(String),
    /// A double-quoted / interpolated string.
    Interp(Vec<InterpPart>),
    /// A `$name` variable read.
    Var(String),
    /// A variable VARIABLE — `$$name` or `${expr}`. The inner expression is
    /// evaluated and its string value is the name of the variable to read or
    /// write, so the name is not known until the expression runs.
    VarVar(Box<Expr>),
    /// An array literal: `[k => v, v, ...]` / `array(...)`. Also every
    /// destructuring pattern — see [`ArrayElem`]. The [`ArraySyntax`] is the
    /// spelling, which only a destructuring target looks at.
    Array(Vec<ArrayElem>, ArraySyntax),
    /// An empty slot in an array literal — the gap in `[, $b]` / `list(, $b)`.
    /// A destructuring target skips it (it still consumes an index); anywhere
    /// else it is the compile error `Cannot use empty array elements in arrays`.
    /// Kept apart from [`Expr::Null`] because `[null] = $a` is a different
    /// error (`Assignments can only happen to writable values`).
    Hole,
    /// `recv[index]`.
    Index(Box<Expr>, Box<Expr>),
    /// One element read of a destructuring assignment — `[$a, $b] = $src` and
    /// the `foreach` patterns, never written by the parser.
    ///
    /// This is NOT `Index`. PHP reads a list element through a different
    /// operation, and the two disagree on every non-array subject: `"ab"[0]` is
    /// `'a'`, but `[$x] = "ab"` warns `Cannot use string as array` and assigns
    /// null. Reusing `Index` here silently turns a diagnostic into a character.
    ListElem(Box<Expr>, Box<Expr>),
    /// `recv[]` — append target, only valid as an assignment LHS.
    Append(Box<Expr>),
    Unary(UnOp, Box<Expr>),
    Binary(BinOp, Box<Expr>, Box<Expr>),
    /// Assignment. `op` is `None` for `=`, or the compound arithmetic/concat op
    /// for `+=`, `.=`, etc.
    Assign(Box<Expr>, Option<BinOp>, Box<Expr>),
    /// Pre/post increment/decrement: `++$x`, `$x--`.
    IncDec {
        target: Box<Expr>,
        inc: bool,
        prefix: bool,
    },
    /// A function call `name(args)`.
    Call(String, Vec<Expr>),
    /// Argument unpacking at a call site: `...$arr` splats an array's values as
    /// positional arguments. Only valid inside a `Call`'s argument list.
    Spread(Box<Expr>),
    /// A dynamic call of a callable value — `$f(args)`, `foo()(args)`,
    /// `(function(){...})(args)`. The callee evaluates to a closure handle or a
    /// callable string.
    CallValue(Box<Expr>, Vec<Expr>),
    /// PHP 8.1 first-class callable syntax, `callee(...)`: a real `Closure` over
    /// the callable, whose CALLEE is settled where the syntax is written rather
    /// than where the closure is later invoked.
    ///
    /// It carries the callable as a *value* expression — `"f"` for a bare name,
    /// `"C::m"` for a resolved static call, `[recv, "m"]` for the two member
    /// forms — plus whether it was spelled with `->`. That flag cannot be
    /// recovered at run time: `$s = "C"; $s->m(...)` and `$s::m(...)` both build
    /// `["C", "m"]`, and the reference refuses the first (`Call to a member
    /// function m() on string`) while accepting the second.
    Fcc {
        callable: Box<Expr>,
        instance: bool,
    },
    /// An anonymous function `function(params) use(vars) { body }`. `uses` names
    /// the enclosing variables captured at closure-creation time, each by value
    /// or — for `use (&$v)` — by reference.
    Closure {
        params: Vec<Param>,
        uses: Vec<Capture>,
        body: Vec<Stmt>,
        /// The declared return type (`function (): int { … }`), or `None`.
        ret: Option<TypeHint>,
        /// `static function (…)` — the closure is NOT bound to the `$this` of
        /// the method it was written in. It keeps that method's class SCOPE, so
        /// a private static is still reachable; only the instance is withheld,
        /// and `Closure::bind` refuses to supply one later.
        is_static: bool,
        /// The line the `function` keyword is on — which is what PHP 8.4 puts in
        /// a stack frame's `{closure:<where>:<line>}` name, NOT the line the
        /// enclosing statement started on. `$f =\n    function () {…}` is line 2
        /// there.
        line: u32,
        /// The line of its closing brace, for `getEndLine()`.
        end_line: u32,
        /// Its doc comment, for `getDocComment()`.
        doc: Option<String>,
        /// Its `#[…]` attributes.
        attrs: Vec<Attr>,
    },
    /// An arrow function `fn(params) => expr` — its body is a single expression
    /// and every free variable is captured by value automatically.
    ArrowFn {
        params: Vec<Param>,
        body: Box<Expr>,
        /// The declared return type (`fn (): int => …`), or `None`.
        ret: Option<TypeHint>,
        /// `static fn (…)` — withholds the enclosing `$this`, exactly as
        /// `Closure::is_static` does for `static function`.
        is_static: bool,
        /// The line the `fn` keyword is on — see `Closure::line`.
        line: u32,
        /// The line its body expression ends on.
        end_line: u32,
        /// Its doc comment, for `getDocComment()`.
        doc: Option<String>,
        /// Its `#[…]` attributes.
        attrs: Vec<Attr>,
    },
    /// `new Class(args)` — instantiate an object (class name literal, or the
    /// `self`/`parent`/`static` keyword resolved at compile time).
    New(String, Vec<Expr>),
    /// `new $c(args)`, `new ($expr)(args)`, `new $o->p[k]` — the class is
    /// named at run time by a string or by an object (whose class is used).
    NewDyn(Box<Expr>, Vec<Expr>),
    /// `new class(args) [extends P] [implements I] { members }` — an anonymous
    /// class. The declaration is compiled once, at the point the expression is
    /// lowered, under a generated name; every evaluation of the expression then
    /// instantiates that one class (PHP does the same — a `new class` in a loop
    /// produces instances of a single class, not one class per iteration).
    ///
    /// `line` is the source line of the `class` keyword, which the generated
    /// name embeds the way the reference does.
    NewAnon {
        decl: Box<ClassDecl>,
        args: Vec<Expr>,
        line: u32,
    },
    /// `$obj->prop` — instance property read.
    PropGet(Box<Expr>, Member),
    /// `$obj->method(args)` — instance method call.
    MethodCall(Box<Expr>, Member, Vec<Expr>),
    /// `$obj?->prop` — nullsafe property read: the receiver is evaluated once and,
    /// if it is null, the access short-circuits to null (the property is never
    /// read). Otherwise it behaves like `PropGet`.
    NullsafePropGet(Box<Expr>, Member),
    /// `$obj?->method(args)` — nullsafe method call: short-circuits to null when
    /// the receiver is null (the arguments are not evaluated), else like `MethodCall`.
    NullsafeMethodCall(Box<Expr>, Member, Vec<Expr>),
    /// A named call argument `name: value` (PHP 8.0). Only valid inside a call's
    /// argument list; the compiler binds it to the parameter of that name.
    NamedArg(String, Box<Expr>),
    /// `Class::CONST` / `Class::class` — class constant read (also `self::`/`parent::`).
    StaticGet(ClassRef, String),
    /// `Class::$prop` — static property access (`self::$n`, `C::$x`). A read, an
    /// assignment target, and an `++`/`--` target; storage is shared per declaring
    /// class, so all instances and scopes observe the same value. The name is
    /// computed in `C::$$n` and `C::${expr}`.
    StaticProp(ClassRef, Member),
    /// `Class::method(args)` — static / scope-resolution method call.
    StaticCall(ClassRef, String, Vec<Expr>),
    /// `clone $o` — a new instance of the same class carrying a copy of the
    /// properties, then `__clone()` if the class defines one. The copy is
    /// shallow in PHP's sense: a nested array is a value and is copied, a
    /// nested object is a handle and stays shared.
    Clone(Box<Expr>),
    /// Ternary `cond ? then : els`.
    Ternary(Box<Expr>, Box<Expr>, Box<Expr>),
    /// Short ternary / elvis `a ?: b` — `a` if truthy, else `b` (evaluates `a`
    /// once).
    Elvis(Box<Expr>, Box<Expr>),
    /// Null coalesce `a ?? b` — `a` unless it is null, then `b`.
    Coalesce(Box<Expr>, Box<Expr>),
    /// PHP 8 `match` expression: strict (`===`) comparison of the subject
    /// against each arm's conditions, returning the matching arm's value.
    Match {
        subj: Box<Expr>,
        arms: Vec<MatchArm>,
    },
    /// `throw e` as a PHP 8 expression (also reached from a `throw e;` statement).
    /// Evaluates `e` to an exception object, records it as the pending throw, and
    /// unwinds the current chunk.
    Throw(Box<Expr>),
    /// A bare constant reference (`PHP_EOL`, `M_PI`, a user `define`d name). At
    /// runtime it resolves against the constant table, falling back to the bare
    /// name as a string when undefined (PHP 7 leniency, minus the notice).
    ConstFetch(String),
    /// One of PHP's magic constants in the part of its answer the parse could not
    /// settle. See [`MagicConst`]; everything a parse CAN settle never reaches
    /// here, arriving as the [`Expr::Str`] or [`Expr::Int`] it resolved to.
    Magic(MagicConst),
    /// `unset($a, $b[$k], …)` — remove each variable or array element. Evaluates
    /// to null (a statement-level construct in PHP).
    Unset(Vec<Expr>),
    /// `$x instanceof ClassName` — true if `$x` is an instance of the class or one
    /// of its ancestors/interfaces.
    InstanceOf(Box<Expr>, String),
    /// `$x instanceof $c` — the class given by an expression (`new_variable` or
    /// `(expr)`): an object stands for its class, a string names one, and
    /// anything else is an `Error`.
    InstanceOfDyn(Box<Expr>, Box<Expr>),
    /// `$target = &$source` — bind `target` as a reference alias of `source`.
    RefAssign(Box<Expr>, Box<Expr>),
    /// A read in PHP's "isset mode": the operand of `empty()` and the left operand
    /// of `??`. A missing variable, array element or object property is the
    /// question being asked rather than a mistake, so the read raises no
    /// diagnostic. Evaluates exactly as the wrapped expression does.
    ///
    /// On an object property this is the `__isset`-then-`__get` pair: the class is
    /// asked whether the property is set, and only then for its value.
    Quiet(Box<Expr>),
    /// `@expr` — the error-suppression operator. NOT an isset-mode read, despite
    /// the family resemblance: the operand is evaluated exactly as it would be
    /// without the `@`, and only the DIAGNOSTICS it raises are dropped. The
    /// difference is visible wherever the two modes disagree — `@$o->p` on a class
    /// with `__get` calls `__get` (an isset-mode read would ask `__isset` first),
    /// and `@$o->p` on an unreachable private property still throws, because an
    /// `Error` is not a diagnostic.
    Suppress(Box<Expr>),
    /// One `isset()` argument. Narrower than [`Quiet`](Expr::Quiet): it asks only
    /// whether the target is set and never reads a value, so on an object property
    /// it consults `__isset` and stops there — `isset($o->p)` is true for a class
    /// whose `__isset` says so even when `__get` would return null.
    IssetOf(Box<Expr>),
    /// The `empty()` argument, whose value the `!` around it then tests. Sits
    /// between the other two on object properties: like [`Quiet`](Expr::Quiet) it
    /// wants a VALUE, but like [`IssetOf`](Expr::IssetOf) it will not read one
    /// from a property `__isset` has not vouched for. A class with `__get` and no
    /// `__isset` is therefore `empty()` without `__get` ever being called, while
    /// `$o->p ?? 'd'` on that same class does call it.
    EmptyOf(Box<Expr>),
    /// `yield`, `yield $v`, or `yield $k => $v` — suspend the enclosing generator,
    /// handing a value (and optional key) to the resumer. Evaluates to the value
    /// passed by the next `->send($x)` (null for `->next()`). A function whose body
    /// contains a `yield` is a generator: calling it builds a `Generator` object
    /// instead of running the body.
    Yield {
        key: Option<Box<Expr>>,
        value: Option<Box<Expr>>,
    },
    /// `yield from $iterable` — delegate: re-yield every key/value of `$iterable`
    /// (an array, `Traversable`, or another generator) from the enclosing
    /// generator. Evaluates to the delegated generator's `return` value (null for
    /// an array / a generator with no `return`).
    YieldFrom(Box<Expr>),
    /// `print EXPR` — writes the operand like `echo` does, but it is an
    /// EXPRESSION whose value is always the int `1`, so `$r = print "x"` and
    /// `$a ?: print "y"` are both legal. Its precedence sits between assignment
    /// and `yield`, which is why it is read where `yield` is.
    Print(Box<Expr>),
    /// `include`/`require`/`include_once`/`require_once EXPR` — load, compile
    /// and run another file in the CURRENT scope. An expression: its value is
    /// the file's `return` value, `1`, `true` for a repeated `_once`, or `false`
    /// for a failed `include`. Read where `print` is, taking everything to its
    /// right at assignment precedence.
    Include(IncludeKind, Box<Expr>),
    /// `eval(EXPR)` — compile and run a string of PHP in the current scope.
    Eval(Box<Expr>),
}

/// The run-time half of PHP's magic constants.
///
/// PHP resolves `__LINE__`, `__FILE__`, `__DIR__`, `__FUNCTION__`, `__CLASS__`,
/// `__METHOD__`, `__NAMESPACE__` and `__TRAIT__` at COMPILE time — they are
/// literals in the emitted opcodes, not table lookups, which is why they answer
/// from the declaration they were written in rather than from the running call.
/// The parser resolves each one the same way and hands back a plain literal; the
/// two cases below are the only ones a parse cannot answer, and they are the ones
/// that need the host.
/// Each variant is `{prefix}{X}{suffix}` for one run-time piece `X`. The affixes
/// are never idle decoration: PHP names a closure after the scope it was written
/// in (`{closure:<scope>:<line>}`), so when that scope is itself a run-time
/// answer the closure's `__FUNCTION__` wraps it rather than replacing it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MagicConst {
    /// `X` is `__FILE__`: the running script's name — its resolved path,
    /// `Command line code` for `php -r`, or `Standard input code` for a script on
    /// stdin. The parser cannot know which, because one source runs under all
    /// three.
    File { prefix: String, suffix: String },
    /// `X` is the running frame's class, for the two places a parse cannot name
    /// it: a TRAIT method (whose `__CLASS__` is the class that used the trait)
    /// and an anonymous class (whose `class@anonymous …` name the compiler mints).
    Class { prefix: String, suffix: String },
    /// `__DIR__` — the directory part of `__FILE__`, or the working directory when
    /// the script has no file to take a directory from.
    Dir,
}

impl MagicConst {
    /// The same constant with more text around it. Used to build a closure's name
    /// out of the enclosing scope's, which composes: a closure inside a closure
    /// inside a trait method wraps twice.
    pub fn wrap(&self, before: &str, after: &str) -> MagicConst {
        let wrapped = |prefix: &String, suffix: &String| {
            (format!("{before}{prefix}"), format!("{suffix}{after}"))
        };
        match self {
            MagicConst::File { prefix, suffix } => {
                let (prefix, suffix) = wrapped(prefix, suffix);
                MagicConst::File { prefix, suffix }
            }
            MagicConst::Class { prefix, suffix } => {
                let (prefix, suffix) = wrapped(prefix, suffix);
                MagicConst::Class { prefix, suffix }
            }
            // `__DIR__` names no scope, so nothing is ever built around it.
            MagicConst::Dir => MagicConst::Dir,
        }
    }
}

/// One arm of a `match` expression. `conds` is `None` for the `default` arm;
/// otherwise the subject is compared (`===`) against each condition, and the arm
/// fires if any matches.
#[derive(Debug, Clone)]
pub struct MatchArm {
    pub conds: Option<Vec<Expr>>,
    pub body: Box<Expr>,
}

/// A statement. `line` is the 1-based source line, used for the bytecode dump.
#[derive(Debug, Clone)]
pub struct Stmt {
    pub line: u32,
    pub kind: StmtKind,
}

/// The value target of a `foreach`.
///
/// The destructuring spellings all carry an [`Expr::Array`] — the very node the
/// standalone `[$a, $b] = …` assignment uses as its target — so `foreach` gets
/// keyed elements, holes, and nesting from the one destructuring implementation
/// rather than a parallel copy of it. That shared path is also what makes a
/// too-short element warn before binding null, instead of binding null silently.
#[derive(Debug, Clone)]
pub enum ForeachVal {
    /// `foreach ($a as $v)`.
    Var(String),
    /// `foreach ($a as [$x, $y])` or the equivalent `as list($x, $y)`.
    Pattern(Expr),
}

#[derive(Debug, Clone)]
pub enum StmtKind {
    /// A run of literal text outside `<?php ... ?>` — echoed verbatim.
    InlineHtml(String),
    /// `echo e1, e2, ...;`
    Echo(Vec<Expr>),
    /// An expression evaluated for its side effects.
    Expr(Expr),
    /// `if (cond) { then } elseif ... else { els }`.
    If {
        cond: Expr,
        then: Vec<Stmt>,
        /// `(cond, body)` pairs for each `elseif`.
        elifs: Vec<(Expr, Vec<Stmt>)>,
        els: Option<Vec<Stmt>>,
    },
    While {
        cond: Expr,
        body: Vec<Stmt>,
    },
    /// `do { body } while (cond);` — the body always runs at least once.
    DoWhile {
        cond: Expr,
        body: Vec<Stmt>,
    },
    /// `switch ($subj) { case A: ...; default: ... }`. Cases compare with loose
    /// (`==`) equality and fall through unless a `break` is hit.
    Switch {
        subj: Expr,
        cases: Vec<SwitchCase>,
    },
    For {
        init: Vec<Expr>,
        cond: Option<Expr>,
        step: Vec<Expr>,
        body: Vec<Stmt>,
    },
    /// `foreach ($arr as [$k =>] [&]$v) { body }`. `by_ref` marks `as &$v`, where
    /// mutating `$v` writes back into the array element.
    Foreach {
        arr: Expr,
        key_var: Option<String>,
        val: ForeachVal,
        by_ref: bool,
        body: Vec<Stmt>,
    },
    /// `function name($a, $b) { body }`.
    Function {
        name: String,
        params: Vec<Param>,
        body: Vec<Stmt>,
        /// The declared return type (`function f(): int`), or `None`.
        ret: Option<TypeHint>,
        /// `function &f()` — the function returns by reference, so `$r = &f()`
        /// aliases the storage its `return` names rather than copying its value.
        by_ref_return: bool,
        /// The namespace the declaration was written in (`""` at global scope)
        /// — see [`ClassDecl::namespace`] for why a flat resolver keeps it.
        namespace: String,
        /// Its `#[\Deprecated]` attribute, if it has one.
        deprecated: Option<Deprecation>,
        /// Its doc comment, for `getDocComment()`.
        doc: Option<String>,
        /// The lines of its `function` keyword and its closing brace, for
        /// `getStartLine()` / `getEndLine()`.
        lines: (u32, u32),
        /// Its `#[…]` attributes.
        attrs: Vec<Attr>,
    },
    /// `class Name [extends Parent] { ... }`.
    Class(ClassDecl),
    Return(Option<Expr>),
    /// `break [n];` — `n` is how many enclosing loop/switch levels to leave
    /// (1 = the innermost, PHP's default).
    /// `goto label;`
    Goto(String),
    /// `label:` — a `goto` target.
    Label(String),
    Break(u32),
    /// `continue [n];` — see [`StmtKind::Break`] for the level.
    Continue(u32),
    /// `try { body } catch (T1 | T2 $e) { ... } ... [finally { ... }]`.
    Try {
        body: Vec<Stmt>,
        catches: Vec<CatchArm>,
        finally: Option<Vec<Stmt>>,
    },
    /// An empty `;` or a `{ }` block.
    Block(Vec<Stmt>),
    /// `static $a = 1, $b;` inside a function — each name is bound to a persistent
    /// per-declaration slot whose value survives across calls; the optional
    /// initializer runs only on the first entry.
    StaticLocal(Vec<(String, Option<Expr>)>),
    /// `global $a, $b;` inside a function — each name becomes an ALIAS of the
    /// global variable of that name, so a write through it is visible outside
    /// and a later write to the global is visible here. It is a reference
    /// binding, not a copy: `unset()` on the local breaks the alias and leaves
    /// the global alone.
    Global(Vec<String>),
    /// `const NAME = expr, NAME2 = expr2;` at statement level — the declaration
    /// spelling of a global constant, as opposed to the `define()` call.
    ///
    /// It is NOT hoisted: the constant comes into being where the statement
    /// stands, so a `defined()` earlier in the same script answers false. That
    /// makes this a runtime statement rather than a load-time declaration, and
    /// it is why the entries keep their source order.
    ///
    /// Distinct from [`ClassDecl::consts`], which is the class-body `const`.
    ConstDecl(Vec<(String, Expr)>),
}

/// One `catch (T1 | T2 [$var]) { body }` clause. `types` is the union of caught
/// class names; `var` is the optional bound variable (PHP 8 allows `catch (T)`).
#[derive(Debug, Clone)]
pub struct CatchArm {
    pub types: Vec<String>,
    pub var: Option<String>,
    pub body: Vec<Stmt>,
}

/// A type as written in a declaration: `int`, `?string`, `int|float`, `Foo\Bar`.
///
/// `?T` is normalised on the way in to the two-part union `T|null`, so nullability
/// has one spelling here rather than two. The parts keep their SOURCE order and
/// spelling; [`TypeHint::declared`] renders them in the order PHP's own
/// `zend_type_to_string` does.
///
/// Every part is enforced — on a parameter, a return and a typed property — by
/// `host::verify_type`, the port of `zend_check_type`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TypeHint {
    /// The alternatives of a union type. A plain type is a one-entry union.
    pub parts: Vec<String>,
}

impl TypeHint {
    /// Whether `null` is one of the accepted alternatives (`?T`, or `T|null`).
    pub fn nullable(&self) -> bool {
        self.parts.iter().any(|p| p.eq_ignore_ascii_case("null"))
    }

    /// The type as the engine spells a DECLARED type back — what `var_dump`
    /// prints inside `uninitialized(…)`. A port of `zend_type_to_string`
    /// (Zend/zend_compile.c): class names first in declared order (an
    /// intersection parenthesized when it is one member of a union), then the
    /// builtin types in the engine's fixed order, whatever order they were
    /// written in; `null` with exactly one other simple type becomes `?T`.
    /// `self` and `parent` resolve to the classes they name, `iterable` to
    /// `Traversable|array`, and a type covering everything is `mixed`.
    pub fn declared(&self, self_class: &str, parent: Option<&str>) -> String {
        const BUILTIN: [&str; 14] = [
            "mixed", "static", "callable", "object", "array", "string", "int", "float", "bool",
            "false", "true", "void", "never", "null",
        ];
        let mut classes: Vec<String> = Vec::new();
        let mut builtin = [false; BUILTIN.len()];
        for p in &self.parts {
            let lower = p.to_ascii_lowercase();
            match lower.as_str() {
                "self" => classes.push(self_class.to_string()),
                "parent" => classes.push(parent.unwrap_or("parent").to_string()),
                "iterable" => {
                    classes.push("Traversable".to_string());
                    builtin[4] = true;
                }
                b => match BUILTIN.iter().position(|n| *n == b) {
                    Some(i) => builtin[i] = true,
                    None => classes.push(p.clone()),
                },
            }
        }
        if builtin[0] {
            return "mixed".to_string();
        }
        let nullable = builtin[13];
        let mut out: Vec<String> = Vec::new();
        let members = classes.len() + builtin[..13].iter().filter(|b| **b).count();
        for c in classes {
            if c.contains('&') && members + usize::from(nullable) > 1 {
                out.push(format!("({c})"));
            } else {
                out.push(c);
            }
        }
        for (i, name) in BUILTIN.iter().enumerate().take(13) {
            if builtin[i] {
                out.push((*name).to_string());
            }
        }
        if nullable {
            if out.len() == 1 && !out[0].contains('&') {
                return format!("?{}", out[0]);
            }
            out.push("null".to_string());
        }
        out.join("|")
    }
}

/// One formal parameter of a function definition: its name, an optional default
/// value expression (used when the caller omits the argument), whether it is
/// variadic (`...$rest`, collecting all trailing arguments into an array), and
/// whether it is a promoted constructor property (`public int $x`), which makes
/// `__construct` also assign `$this->name = $name`.
#[derive(Debug, Clone)]
pub struct Param {
    pub name: String,
    /// The line the parameter is DECLARED on. PHP attributes an implicit-
    /// conversion `Deprecated` to the declaration, not to the call, so the check
    /// has to know where the parameter was written.
    pub line: u32,
    /// The declared type (`int $x`, `?string $s`, `int|float $n`), or `None` for
    /// an untyped parameter.
    pub ty: Option<TypeHint>,
    pub default: Option<Expr>,
    pub variadic: bool,
    pub promoted: bool,
    /// The visibility a promoted parameter declares its property with
    /// (`public` when only `readonly` promoted it).
    pub promoted_vis: Visibility,
    /// The write visibility a promoted parameter was given, as in
    /// `public private(set) int $x` (PHP 8.4); `None` when it names none.
    pub promoted_set_vis: Option<Visibility>,
    /// `readonly` on a promoted constructor parameter, which declares the
    /// property readonly exactly as a `readonly` member declaration would.
    pub readonly: bool,
    /// `&$x` — a by-reference parameter; the caller's variable is updated to the
    /// parameter's final value when the call returns.
    pub by_ref: bool,
    /// Its `#[…]` attributes.
    pub attrs: Vec<Attr>,
}

/// Member visibility, captured on properties and methods. `Public` is the
/// default when no `public`/`protected`/`private` modifier is written.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Visibility {
    Public,
    Protected,
    Private,
}

/// A declared class property: its name, optional default initializer, whether it
/// is `static` (class-level, shared storage) and its declared visibility.
#[derive(Debug, Clone)]
pub struct PropDecl {
    pub name: String,
    pub default: Option<Expr>,
    /// The declared type, `None` for an untyped property. A typed property with
    /// no default starts UNINITIALIZED: absent from the object until written,
    /// and an error to read before that.
    pub ty: Option<TypeHint>,
    pub is_static: bool,
    pub visibility: Visibility,
    /// The write visibility of an asymmetric declaration, `private(set)`,
    /// `protected(set)` or `public(set)` (PHP 8.4); `None` when none is written.
    pub set_visibility: Option<Visibility>,
    /// `readonly` — writable exactly once, from inside the declaring class or a
    /// subclass, and never again. See [`PhpHost::readonly_write_error`].
    ///
    /// [`PhpHost::readonly_write_error`]: crate::host::PhpHost::readonly_write_error
    pub readonly: bool,
    /// Declared `final` (PHP 8.4): a subclass may not redeclare it.
    pub is_final: bool,
    /// The line of its `$name`, which is where a redeclaration is reported.
    pub line: u32,
    /// The token position of its `$name` (see `ClassDecl::const_pos`).
    pub pos: usize,
}

/// A parsed class declaration. Single inheritance only; interfaces/traits are
/// parsed-and-discarded in the scaffold.
#[derive(Debug, Clone)]
pub struct ClassDecl {
    pub name: String,
    /// The lines of its `class` (`interface`, `trait`, `enum`) keyword and its
    /// closing brace, for `getStartLine()` / `getEndLine()`.
    pub lines: (u32, u32),
    pub parent: Option<String>,
    /// Interfaces this class implements (or, for an `interface`, the interfaces it
    /// extends). Used by `instanceof`/`is_a`/`catch`.
    pub implements: Vec<String>,
    /// Traits pulled in via `use Trait;` inside the class body; their methods and
    /// properties are merged into the class at compile time.
    pub uses: Vec<String>,
    /// `A::m insteadof B, C;` entries of the `use` adaptation block — the trait
    /// whose `m` wins, and the traits whose `m` is dropped.
    pub trait_insteadof: Vec<TraitInsteadof>,
    /// `A::m as [visibility] [alias];` entries of the `use` adaptation block.
    pub trait_aliases: Vec<TraitAlias>,
    /// Whether this is an `interface` (vs a `class`/`trait`).
    pub is_interface: bool,
    /// Whether this is a `trait`. A trait's methods are compiled ONCE and copied
    /// into every class that uses them, so the class `self` and `parent` name is
    /// not known while the body is being lowered — it is whichever class ends up
    /// running the method, exactly as for `__CLASS__`.
    pub is_trait: bool,
    /// `readonly class` (PHP 8.2) — every property the class declares is
    /// readonly, promoted constructor parameters included.
    pub is_readonly: bool,
    /// Whether the class is declared `abstract` (cannot be instantiated directly).
    pub is_abstract: bool,
    /// Whether the class is declared `final` (cannot be extended).
    pub is_final: bool,
    /// Whether this is an `enum` (PHP 8.1). An enum compiles like a class whose
    /// `cases` are singleton instances; `implements` gains `UnitEnum` (plus
    /// `BackedEnum` when `enum_backing` is set).
    pub is_enum: bool,
    /// The scalar backing type of a backed enum (`enum E: string`) — `"int"` or
    /// `"string"`. `None` for a pure enum.
    pub enum_backing: Option<String>,
    /// `case Name [= value];` entries of an `enum`, in source order.
    pub cases: Vec<EnumCase>,
    /// `const NAME = expr;` entries, in source order.
    pub consts: Vec<(String, Expr)>,
    /// The line of each entry of `consts`' name, index for index.
    pub const_lines: Vec<u32>,
    /// The token position of each entry of `consts`, index for index — what
    /// decides whether a property default declared later can see it.
    pub const_pos: Vec<usize>,
    /// The declared visibility of each `private`/`protected` constant, by name.
    /// A constant absent from this list is `public`.
    pub const_vis: Vec<(String, Visibility)>,
    /// The constants declared `final`, by name: no subclass or implementing
    /// class may redefine them.
    pub final_consts: Vec<String>,
    /// Property declarations, in source order (instance and static).
    pub props: Vec<PropDecl>,
    /// How many of `props` precede the constructor: a promoted parameter
    /// declares its property at the constructor's place in the slot order
    /// (`zend_compile_params` declares it as the method is compiled).
    pub ctor_prop_slot: usize,
    pub methods: Vec<Method>,
    /// Names of the `#[…]` attributes written before the declaration, unqualified.
    /// Only `AllowDynamicProperties` changes behaviour today; the rest are carried
    /// so the declaration parses and so reflection has something to report.
    pub attributes: Vec<String>,
    /// The namespace the declaration was written in (`""` at global scope).
    /// phplang resolves class names flat, so this is consulted only where the
    /// reference's answer depends on it: two same-named declarations in
    /// DIFFERENT namespaces are not a redeclaration, and a namespaced class may
    /// share a built-in class's short name.
    pub namespace: String,
    /// The doc comments of the declaration and its members, for
    /// `getDocComment()`: keyed `class`, `method:<lowercased name>`,
    /// `prop:<name>`, `const:<name>` and `case:<name>`.
    pub docs: Vec<(String, String)>,
    /// The `#[…]` attributes of the declaration and its members, keyed as
    /// `docs` is.
    pub attrs: Vec<(String, Vec<Attr>)>,
}

/// One `A::m insteadof B, C;` conflict resolution inside a `use` block. Without
/// it, two used traits declaring the same method is a fatal error.
#[derive(Debug, Clone)]
pub struct TraitInsteadof {
    /// The trait whose method is kept.
    pub winner: String,
    pub method: String,
    /// The traits whose method of that name is dropped.
    pub losers: Vec<String>,
}

/// One `[A::]m as [visibility] [alias];` adaptation inside a `use` block.
///
/// With an `alias`, the method is *additionally* bound under the new name (the
/// original binding stays); without one, only the visibility of the existing
/// binding changes. `from` is the qualifying trait, or `None` for the
/// unqualified `m as …` form, which is an error when more than one used trait
/// declares `m`.
#[derive(Debug, Clone)]
pub struct TraitAlias {
    pub from: Option<String>,
    pub method: String,
    pub alias: Option<String>,
    pub visibility: Option<Visibility>,
}

/// One `case Name [= value];` of an `enum`. `value` is the backing-value
/// expression for a backed enum, `None` for a pure enum.
#[derive(Debug, Clone)]
pub struct EnumCase {
    pub name: String,
    pub value: Option<Expr>,
    /// The line of its name.
    pub line: u32,
}

/// One `#[Name(args)]` attribute: its name, resolved as a class name, and its
/// arguments as written (positional, then `name: value` as `Expr::NamedArg`).
/// Reflection evaluates them when asked, as the reference does.
#[derive(Debug, Clone)]
pub struct Attr {
    pub name: String,
    pub args: Vec<Expr>,
    pub line: u32,
}

/// A `#[\Deprecated]` attribute on a function or method (PHP 8.4): calling it
/// raises `Function f() is deprecated[ since S][, M]`. Only literal string
/// arguments are read; `message` and `since` are the attribute's two parameters.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Deprecation {
    pub message: Option<String>,
    pub since: Option<String>,
}

/// A method of a class. `is_static` is retained but not enforced (a static call
/// still binds `$this` when made from an object context, as PHP does).
#[derive(Debug, Clone)]
pub struct Method {
    pub name: String,
    pub params: Vec<Param>,
    pub body: Vec<Stmt>,
    /// The declared return type (`function m(): int`), or `None`.
    pub ret: Option<TypeHint>,
    pub is_static: bool,
    pub visibility: Visibility,
    /// `function &m()` — see `StmtKind::Function::by_ref_return`.
    pub by_ref_return: bool,
    /// Declared `abstract` (or, in an interface, implicitly so).
    pub is_abstract: bool,
    /// Declared `final`.
    pub is_final: bool,
    /// Whether a `{ … }` body was written, as opposed to a bare `;`. Only an
    /// abstract or interface method may omit it, and only they must.
    pub has_body: bool,
    /// The line the declaration starts on.
    pub line: u32,
    /// The line its body (or the `;` of a bodiless one) ends on.
    pub end_line: u32,
    /// Its `#[\Deprecated]` attribute, if it has one.
    pub deprecated: Option<Deprecation>,
}

/// One `case`/`default` label of a `switch` plus its (fall-through) body. `test`
/// is `None` for the `default` label.
#[derive(Debug, Clone)]
pub struct SwitchCase {
    pub test: Option<Expr>,
    pub body: Vec<Stmt>,
}

/// One `use (...)` entry of an anonymous function. A by-value capture copies the
/// variable's value when the closure is created; a by-reference one (`use (&$v)`)
/// shares the enclosing variable itself, so the closure's writes are visible
/// outside it and later writes outside are visible in it.
#[derive(Debug, Clone, PartialEq)]
pub struct Capture {
    pub name: String,
    pub by_ref: bool,
    /// An arrow function's capture rather than a `use` clause's: bound only
    /// when the enclosing variable is, and without a diagnostic when it is not
    /// (`ZEND_BIND_IMPLICIT`).
    pub implicit: bool,
}

/// Which of the four file-inclusion constructs an [`Expr::Include`] is.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IncludeKind {
    Include,
    IncludeOnce,
    Require,
    RequireOnce,
}

impl IncludeKind {
    /// The construct as the reference names it in diagnostics and traces.
    pub fn name(self) -> &'static str {
        match self {
            IncludeKind::Include => "include",
            IncludeKind::IncludeOnce => "include_once",
            IncludeKind::Require => "require",
            IncludeKind::RequireOnce => "require_once",
        }
    }

    /// The number the compiler bakes into the `INCLUDE` call.
    pub fn code(self) -> i64 {
        self as i64
    }

    pub fn from_code(n: i64) -> Self {
        match n {
            1 => IncludeKind::IncludeOnce,
            2 => IncludeKind::Require,
            3 => IncludeKind::RequireOnce,
            _ => IncludeKind::Include,
        }
    }

    pub fn once(self) -> bool {
        matches!(self, IncludeKind::IncludeOnce | IncludeKind::RequireOnce)
    }

    pub fn required(self) -> bool {
        matches!(self, IncludeKind::Require | IncludeKind::RequireOnce)
    }
}