phprs 0.1.13

A PHP interpreter with build/package manager written in Rust
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
//! Operator expression parsing (logical, comparison, arithmetic chains)

use super::helpers::*;
use crate::engine::compile::context::CompileContext;
use crate::engine::facade::{self, result_val};
use crate::engine::lexer::{Lexer, Token, TokenType};
use crate::engine::types::Val;
use crate::engine::vm::Opcode;

/// Parse ternary expression (condition ? true_expr : false_expr)
/// Also handles short ternary (expr ?: default)
pub(crate) fn parse_ternary_expr(
    lexer: &mut Lexer,
    context: &mut CompileContext,
) -> Result<(Val, Token), String> {
    let (condition, token) = parse_null_coalesce_expr(lexer, context)?;
    parse_ternary_tail(lexer, context, condition, token)
}

/// Parse a ternary/null-coalesce expression starting from a pre-consumed token.
pub(crate) fn parse_ternary_expr_with_initial(
    lexer: &mut Lexer,
    context: &mut CompileContext,
    initial: Token,
) -> Result<(Val, Token), String> {
    let (condition, token) = parse_null_coalesce_expr_with_initial(lexer, context, initial)?;
    parse_ternary_tail(lexer, context, condition, token)
}

fn parse_ternary_tail(
    lexer: &mut Lexer,
    context: &mut CompileContext,
    condition: Val,
    token: Token,
) -> Result<(Val, Token), String> {
    if !token_is_punct(&token, "?") {
        return Ok((condition, token));
    }

    // Peek at next token to distinguish short ternary (?:) from full ternary
    let peek = lexer.next_token()?;

    if token_is_punct(&peek, ":") {
        // Short ternary: expr ?: default
        let (fallback, after) = parse_ternary_expr(lexer, context)?;
        let slot = context.alloc_temp();
        // JmpNZ: if condition is truthy, jump to truthy path
        let jmp_idx = context.current_op_index();
        context.emit_opcode(
            Opcode::JmpNZ,
            facade::clone_val(&condition),
            facade::long_val(0), // jump offset; patched via update_jump_target
            facade::null_val(),
        );
        // Falsy path: store fallback in temp slot
        context.emit_opcode(
            Opcode::QmAssign,
            fallback,
            facade::null_val(),
            crate::engine::vm::temp_var_ref(slot),
        );
        let jmp_end_idx = context.current_op_index();
        context.emit_opcode(
            Opcode::Jmp,
            facade::long_val(0), // jump offset; patched via update_jump_target
            facade::null_val(),
            facade::null_val(),
        );
        // Truthy path: store condition in temp slot
        let truthy_idx = context.current_op_index();
        context.emit_opcode(
            Opcode::QmAssign,
            condition,
            facade::null_val(),
            crate::engine::vm::temp_var_ref(slot),
        );
        let after_idx = context.current_op_index();
        // Patch jumps (use extended_value, which is what the VM reads)
        context.update_jump_target(jmp_idx, truthy_idx as u32);
        context.update_jump_target(jmp_end_idx, after_idx as u32);
        return Ok((crate::engine::vm::temp_var_ref(slot), after));
    }

    // Full ternary: condition ? true_expr : false_expr
    // `peek` is the first token of the true expression — need to parse with it
    let (true_expr, colon_token) = parse_additive_expr_with_initial(lexer, context, peek)?;
    if !token_is_punct(&colon_token, ":") {
        return Err(format!(
            "Expected ':' in ternary expression, got {:?}",
            colon_token.token_type
        ));
    }
    let (false_expr, after) = parse_ternary_expr(lexer, context)?;

    let slot = context.alloc_temp();
    // JmpZ: if condition is falsy, jump to false path
    let jmp_idx = context.current_op_index();
    context.emit_opcode(
        Opcode::JmpZ,
        facade::clone_val(&condition),
        facade::long_val(0), // jump offset; patched via update_jump_target
        facade::null_val(),
    );
    // True path: store in temp slot
    context.emit_opcode(
        Opcode::QmAssign,
        true_expr,
        facade::null_val(),
        crate::engine::vm::temp_var_ref(slot),
    );
    let jmp_end_idx = context.current_op_index();
    context.emit_opcode(
        Opcode::Jmp,
        facade::long_val(0), // jump offset; patched via update_jump_target
        facade::null_val(),
        facade::null_val(),
    );
    // False path: store in temp slot
    let false_start = context.current_op_index();
    context.emit_opcode(
        Opcode::QmAssign,
        false_expr,
        facade::null_val(),
        crate::engine::vm::temp_var_ref(slot),
    );
    let after_idx = context.current_op_index();
    // Patch jumps (use extended_value, which is what the VM reads)
    context.update_jump_target(jmp_idx, false_start as u32);
    context.update_jump_target(jmp_end_idx, after_idx as u32);

    Ok((crate::engine::vm::temp_var_ref(slot), after))
}

/// Parse null coalescing expression (??)
fn parse_null_coalesce_expr(
    lexer: &mut Lexer,
    context: &mut CompileContext,
) -> Result<(Val, Token), String> {
    let (left, token) = parse_logical_or_expr(lexer, context)?;
    parse_null_coalesce_tail(lexer, context, left, token)
}

fn parse_null_coalesce_expr_with_initial(
    lexer: &mut Lexer,
    context: &mut CompileContext,
    initial: Token,
) -> Result<(Val, Token), String> {
    let (left, token) = parse_logical_or_expr_with_initial(lexer, context, initial)?;
    parse_null_coalesce_tail(lexer, context, left, token)
}

fn parse_null_coalesce_tail(
    lexer: &mut Lexer,
    context: &mut CompileContext,
    left: Val,
    token: Token,
) -> Result<(Val, Token), String> {
    if token.token_type == TokenType::T_COALESCE {
        // Right-associative: parse right side as another null coalesce
        let (right, next_token) = parse_null_coalesce_expr(lexer, context)?;
        let slot = context.alloc_temp();
        context.emit_opcode(
            Opcode::Coalesce,
            left,
            right,
            crate::engine::vm::temp_var_ref(slot),
        );
        return Ok((crate::engine::vm::temp_var_ref(slot), next_token));
    }

    Ok((left, token))
}

/// Parse logical OR expression (||)
pub(crate) fn parse_logical_or_expr(
    lexer: &mut Lexer,
    context: &mut CompileContext,
) -> Result<(Val, Token), String> {
    let (left, token) = parse_logical_and_expr(lexer, context)?;
    parse_logical_or_tail(lexer, context, left, token)
}

fn parse_logical_or_expr_with_initial(
    lexer: &mut Lexer,
    context: &mut CompileContext,
    initial: Token,
) -> Result<(Val, Token), String> {
    let (left, token) = parse_logical_and_expr_with_initial(lexer, context, initial)?;
    parse_logical_or_tail(lexer, context, left, token)
}

fn parse_logical_or_tail(
    lexer: &mut Lexer,
    context: &mut CompileContext,
    mut left: Val,
    mut token: Token,
) -> Result<(Val, Token), String> {
    while token.token_type == TokenType::T_BOOLEAN_OR {
        let (right, next_token) = parse_logical_and_expr(lexer, context)?;
        let or_result = result_val(crate::engine::types::PhpType::Bool);
        let or_result_dup = result_val(crate::engine::types::PhpType::Bool);
        context.emit_opcode(Opcode::BoolOr, left, right, or_result);
        left = or_result_dup;
        token = next_token;
    }

    Ok((left, token))
}

/// Parse logical AND expression (&&)
fn parse_logical_and_expr(
    lexer: &mut Lexer,
    context: &mut CompileContext,
) -> Result<(Val, Token), String> {
    let (left, token) = parse_logical_not_expr(lexer, context)?;
    parse_logical_and_tail(lexer, context, left, token)
}

fn parse_logical_and_expr_with_initial(
    lexer: &mut Lexer,
    context: &mut CompileContext,
    initial: Token,
) -> Result<(Val, Token), String> {
    let (left, token) = parse_logical_not_expr_with_initial(lexer, context, initial)?;
    parse_logical_and_tail(lexer, context, left, token)
}

fn parse_logical_and_tail(
    lexer: &mut Lexer,
    context: &mut CompileContext,
    mut left: Val,
    mut token: Token,
) -> Result<(Val, Token), String> {
    while token.token_type == TokenType::T_BOOLEAN_AND {
        let (right, next_token) = parse_logical_not_expr(lexer, context)?;
        let and_result = result_val(crate::engine::types::PhpType::Bool);
        let and_result_dup = result_val(crate::engine::types::PhpType::Bool);
        context.emit_opcode(Opcode::BoolAnd, left, right, and_result);
        left = and_result_dup;
        token = next_token;
    }

    Ok((left, token))
}

/// Parse logical NOT expression (!)
fn parse_logical_not_expr(
    lexer: &mut Lexer,
    context: &mut CompileContext,
) -> Result<(Val, Token), String> {
    let token = lexer.next_token()?;
    parse_logical_not_expr_with_initial(lexer, context, token)
}

fn parse_logical_not_expr_with_initial(
    lexer: &mut Lexer,
    context: &mut CompileContext,
    token: Token,
) -> Result<(Val, Token), String> {
    if token.token_type == TokenType::T_BOOLEAN_NOT {
        let (expr, next_token) = parse_logical_not_expr(lexer, context)?;
        let bool_result = result_val(crate::engine::types::PhpType::Bool);
        let bool_result_dup = result_val(crate::engine::types::PhpType::Bool);
        let zero = facade::zero_val();
        context.emit_opcode(Opcode::BoolNot, expr, zero, bool_result);
        return Ok((bool_result_dup, next_token));
    }

    // Not a logical NOT — parse comparison with pre-consumed token
    parse_comparison_expr_with_token(lexer, context, Some(token))
}

/// Parse comparison expression with optional pre-consumed token
pub(crate) fn parse_comparison_expr_with_token(
    lexer: &mut Lexer,
    context: &mut CompileContext,
    initial_token: Option<Token>,
) -> Result<(Val, Token), String> {
    let (mut left, mut token) = if let Some(tok) = initial_token {
        parse_additive_expr_with_initial(lexer, context, tok)?
    } else {
        parse_additive_expr(lexer, context)?
    };

    loop {
        // Check for comparison operators
        let is_lt = token_is_punct(&token, "<");
        let is_gt = token_is_punct(&token, ">");
        let is_cmp = matches!(
            token.token_type,
            TokenType::T_IS_EQUAL
                | TokenType::T_IS_NOT_EQUAL
                | TokenType::T_IS_SMALLER_OR_EQUAL
                | TokenType::T_IS_GREATER_OR_EQUAL
                | TokenType::T_IS_IDENTICAL
                | TokenType::T_IS_NOT_IDENTICAL
        ) || is_lt
            || is_gt;
        if !is_cmp {
            break;
        }

        let (right, next_token) = parse_additive_expr(lexer, context)?;
        let (opcode, swap) = if is_lt {
            (Opcode::IsSmaller, false)
        } else if is_gt {
            (Opcode::IsSmaller, true) // swap operands
        } else {
            match token.token_type {
                TokenType::T_IS_EQUAL => (Opcode::IsEqual, false),
                TokenType::T_IS_NOT_EQUAL => (Opcode::IsNotEqual, false),
                TokenType::T_IS_SMALLER_OR_EQUAL => (Opcode::IsSmallerOrEqual, false),
                TokenType::T_IS_GREATER_OR_EQUAL => (Opcode::IsSmallerOrEqual, true),
                TokenType::T_IS_IDENTICAL => (Opcode::IsIdentical, false),
                TokenType::T_IS_NOT_IDENTICAL => (Opcode::IsNotIdentical, false),
                _ => unreachable!(),
            }
        };
        let (l, r) = if swap { (right, left) } else { (left, right) };
        left = emit_binary_op(context, opcode, l, r);
        token = next_token;
    }

    Ok((left, token))
}

/// Parse additive expression with a pre-consumed initial token
pub fn parse_additive_expr_with_initial(
    lexer: &mut Lexer,
    context: &mut CompileContext,
    initial_token: Token,
) -> Result<(Val, Token), String> {
    let (left, token) = parse_multiplicative_expr_with_initial(lexer, context, initial_token)?;
    additive_loop(lexer, context, left, token)
}

/// Parse additive expression (+, -, .)
fn parse_additive_expr(
    lexer: &mut Lexer,
    context: &mut CompileContext,
) -> Result<(Val, Token), String> {
    let (left, token) = parse_multiplicative_expr(lexer, context)?;
    additive_loop(lexer, context, left, token)
}

/// Parse multiplicative expression with a pre-consumed initial token
fn parse_multiplicative_expr_with_initial(
    lexer: &mut Lexer,
    context: &mut CompileContext,
    initial_token: Token,
) -> Result<(Val, Token), String> {
    // Handle interpolated strings
    if initial_token.token_type == TokenType::T_CONSTANT_ENCAPSED_STRING {
        if let Some(ref val) = initial_token.value {
            let s = val.as_str();
            if s.contains('$') {
                let result = compile_interpolated_string(s, context)?;
                let next = lexer.next_token()?;
                return multiplicative_loop(lexer, context, result, next);
            }
        }
    }

    // Handle T_NEW
    if initial_token.token_type == TokenType::T_NEW {
        let (result, next) = compile_new_obj(lexer, context)?;
        return multiplicative_loop(lexer, context, result, next);
    }

    // Handle T_CLONE
    if initial_token.token_type == TokenType::T_CLONE {
        let (result, next) = compile_clone_obj(lexer, context)?;
        return multiplicative_loop(lexer, context, result, next);
    }

    if initial_token.token_type == TokenType::T_MATCH {
        let (result, next) = parse_match_expression(lexer, context)?;
        return multiplicative_loop(lexer, context, result, next);
    }

    if initial_token.token_type == TokenType::T_YIELD {
        let (result, next) = super::parse_expression(lexer, context)?;
        return multiplicative_loop(lexer, context, result, next);
    }

    // Handle T_FUNCTION (closure in expression position)
    if initial_token.token_type == TokenType::T_FUNCTION {
        let (result, next) = crate::engine::compile::function::compile_closure(lexer, context)?;
        return multiplicative_loop(lexer, context, result, next);
    }

    // Handle T_STATIC
    if initial_token.token_type == TokenType::T_STATIC {
        let static_val = crate::engine::facade::string_val("static");
        let next = lexer.next_token()?;
        let (result, next_token) = parse_access_chain(lexer, context, static_val, next)?;
        return multiplicative_loop(lexer, context, result, next_token);
    }

    if initial_token.token_type == TokenType::T_ARRAY {
        let result = parse_long_array_literal(lexer, context)?;
        let next = lexer.next_token()?;
        return multiplicative_loop(lexer, context, result, next);
    }

    // Convert token to primary Val
    let initial_zval = token_to_primary(&initial_token, context)?;

    // Handle special cases based on token type
    let (left, token) = if initial_token.token_type == TokenType::T_STRING {
        let val = initial_token
            .value
            .as_ref()
            .map(|s| s.as_str())
            .unwrap_or("");
        if val == "(" {
            let (inner, close_token) = super::parse_expression(lexer, context)?;
            if token_is_punct(&close_token, ")") {
                (inner, lexer.next_token()?)
            } else {
                return Err("Expected ')' after parenthesized expression".to_string());
            }
        } else if val == "[" {
            let result = parse_array_literal(lexer, context)?;
            (result, lexer.next_token()?)
        } else {
            let next = lexer.next_token()?;
            if token_is_punct(&next, "(") {
                let fname = initial_token.value.as_ref().unwrap().as_str();
                parse_function_call(lexer, context, fname)?
            } else if next.token_type == TokenType::T_PAAMAYIM_NEKUDOTAYIM {
                let class_val = crate::engine::facade::string_val(val);
                let (result, next_token) = parse_access_chain(lexer, context, class_val, next)?;
                return multiplicative_loop(lexer, context, result, next_token);
            } else {
                (initial_zval, next)
            }
        }
    } else if initial_token.token_type == TokenType::T_VARIABLE {
        let next = lexer.next_token()?;
        parse_access_chain(lexer, context, initial_zval, next)?
    } else {
        (initial_zval, lexer.next_token()?)
    };

    multiplicative_loop(lexer, context, left, token)
}

/// Parse multiplicative expression (*, /, %)
pub(crate) fn parse_multiplicative_expr(
    lexer: &mut Lexer,
    context: &mut CompileContext,
) -> Result<(Val, Token), String> {
    let (left, token) = super::primary::parse_primary_expr(lexer, context)?;
    multiplicative_loop(lexer, context, left, token)
}