phplang 0.2.2

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
//! PHP standard-library `json` functions. Part of the `stdlib` chain; see
//! `src/stdlib/mod.rs`. `dispatch` returns `None` for names it does not handle.
//!
//! `json_encode` lives in `builtins.rs` (core); this module supplies the decoder
//! and the error-state accessors. `json_decode` is a hand-written recursive
//! descent parser over the byte stream, matching PHP 8's `ext/json` semantics:
//!
//! * A JSON array always decodes to a PHP array. A JSON **object** decodes to a
//!   `stdClass` unless `$associative` (or `JSON_OBJECT_AS_ARRAY`) asks for an
//!   array, exactly as `ext/json` does.
//! * Integral numbers become `int`, everything with a `.`/`e`/`E` (or that
//!   overflows `i64`) becomes `float`, matching PHP's default (no
//!   `JSON_BIGINT_AS_STRING`).
//! * `\uXXXX` escapes and UTF-16 surrogate pairs are decoded to UTF-8.
//! * `$depth` is honored (default 512): exceeding it yields `JSON_ERROR_DEPTH`.
//! * On any failure `json_decode` returns `null` and records the error code,
//!   readable via `json_last_error` / `json_last_error_msg`.
//!
//! LIMITATION: PHP tracks the last json error in a per-request global. phplang
//! has no persistent request/constant table, so the code is kept in a
//! thread-local `Cell` for the life of the thread instead. `json_encode` (core)
//! does not reset it; only `json_decode` writes it.

use crate::host::PhpHost;
use crate::stdlib::common::throws;
use fusevm::Value;
use std::cell::Cell;

// PHP `JSON_ERROR_*` codes (ext/json/php_json.h).
const JSON_ERROR_NONE: i64 = 0;
const JSON_ERROR_DEPTH: i64 = 1;
const JSON_ERROR_CTRL_CHAR: i64 = 3;
const JSON_ERROR_SYNTAX: i64 = 4;
const JSON_ERROR_UTF16: i64 = 10;
/// `JSON_ERROR_RECURSION` — `json_encode` found a structure that contains
/// itself. JSON has no way to spell a cycle, so the encode fails outright.
pub const JSON_ERROR_RECURSION: i64 = 6;
/// `JSON_ERROR_INF_OR_NAN` — `json_encode` refuses non-finite floats.
pub const JSON_ERROR_INF_OR_NAN: i64 = 7;
/// `JSON_ERROR_NON_BACKED_ENUM` — a pure `enum` case has no value to encode.
pub const JSON_ERROR_NON_BACKED_ENUM: i64 = 11;

thread_local! {
    /// Last `json_decode` error for this thread (see the module LIMITATION note).
    static LAST_ERROR: Cell<i64> = const { Cell::new(JSON_ERROR_NONE) };
}

pub fn set_last_error(code: i64) {
    LAST_ERROR.with(|c| c.set(code));
}

/// `JSON_THROW_ON_ERROR`. With it set, a failing `json_*` call throws
/// `JsonException` instead of returning `false`/`null`, and — importantly —
/// leaves `json_last_error()` at `JSON_ERROR_NONE`, because the failure was
/// reported by the throw rather than recorded for a later read.
pub const JSON_THROW_ON_ERROR: i64 = 4194304;

/// Turn a `JSON_ERROR_*` code into whichever failure `$flags` asked for: a
/// tagged `JsonException` carrying the code, or `None` after recording the code
/// for `json_last_error()`.
pub fn fail(code: i64, flags: i64) -> Option<String> {
    if flags & JSON_THROW_ON_ERROR != 0 {
        set_last_error(JSON_ERROR_NONE);
        return Some(crate::builtins::throws_code(
            "JsonException",
            code,
            error_msg(code),
        ));
    }
    set_last_error(code);
    None
}

fn get_last_error() -> i64 {
    LAST_ERROR.with(|c| c.get())
}

/// Human-readable message for a `JSON_ERROR_*` code (ext/json/json.c).
fn error_msg(code: i64) -> &'static str {
    match code {
        JSON_ERROR_NONE => "No error",
        JSON_ERROR_DEPTH => "Maximum stack depth exceeded",
        2 => "State mismatch (invalid or malformed JSON)",
        JSON_ERROR_CTRL_CHAR => "Control character error, possibly incorrectly encoded",
        JSON_ERROR_SYNTAX => "Syntax error",
        5 => "Malformed UTF-8 characters, possibly incorrectly encoded",
        JSON_ERROR_RECURSION => "Recursion detected",
        JSON_ERROR_UTF16 => "Single unpaired UTF-16 surrogate in unicode escape",
        JSON_ERROR_INF_OR_NAN => "Inf and NaN cannot be JSON encoded",
        JSON_ERROR_NON_BACKED_ENUM => "Non-backed enums have no default serialization",
        _ => "Unknown error",
    }
}

/// Dispatch a `json`-category PHP function by lowercased name. Returns `None` for
/// names this module does not implement so the stdlib chain can continue.
pub fn dispatch(name: &str, args: &[Value]) -> Option<Result<Value, String>> {
    let v = match name {
        "json_decode" => return Some(json_decode(args)),
        "json_validate" => return Some(json_validate(args)),
        "json_last_error" => Value::int(get_last_error()),
        "json_last_error_msg" => Value::str(error_msg(get_last_error()).to_string()),
        _ => return None,
    };
    Some(Ok(v))
}

/// Resolve the `$depth` argument at `idx` (default 512), rejecting a
/// non-positive one the way the reference does.
///
/// `$depth` counts the document's NESTING LEVELS, not its containers, so it is
/// always one more than the number of `[`/`{` that may be open at once: `"[1]"`
/// needs 2 and only a scalar document fits in 1. Clamping a bad depth to 1
/// (which is what this used to do) therefore admitted exactly the documents PHP
/// rejects at that depth.
///
/// `func`/`pos` name the caller in the message — `$depth` is argument #3 of
/// `json_decode` but argument #2 of `json_validate`.
fn decode_depth(args: &[Value], idx: usize, func: &str, pos: usize) -> Result<usize, String> {
    match args.get(idx) {
        Some(v) if !matches!(v, Value::Undef) => {
            let d = crate::host::with_host(|h| h.to_number(v).to_int());
            if d < 1 {
                return Err(throws(
                    "ValueError",
                    format!("{func}(): Argument #{pos} ($depth) must be greater than 0"),
                ));
            }
            // The reference stores the depth in an `int`, so anything PAST `INT_MAX`
            // is rejected up front — the message says "less than" but the check
            // admits `INT_MAX` itself. Without this ceiling the parser simply
            // recursed until the native stack was gone.
            if d > i64::from(i32::MAX) {
                return Err(throws(
                    "ValueError",
                    format!(
                        "{func}(): Argument #{pos} ($depth) must be less than {}",
                        i32::MAX
                    ),
                ));
            }
            Ok((d as usize).min(NATIVE_DEPTH_CEILING))
        }
        _ => Ok(512),
    }
}

/// The deepest nesting this parser will descend, whatever `$depth` asks for.
///
/// The decoder is recursive descent on the NATIVE stack, so an unbounded
/// `$depth` is an unbounded stack walk: `json_decode(str_repeat("[", 10000),
/// true, PHP_INT_MAX)` aborted the process outright.
///
/// The ceiling is sized against the SMALLEST stack phplang runs on, not the
/// largest. Measured by bisection: on the 8 MiB main thread 5000 levels survive
/// and 10000 do not; on a 2 MiB worker thread (what `cargo test` gives a test
/// function, and what an embedder that spawns a thread gets by default) 1536
/// survive and 2048 do not. 1024 sits inside the smaller of those and is still
/// double the 512 the reference defaults to, which is what real documents are
/// written against.
///
/// DIVERGENCE: a document nested deeper than this reports `JSON_ERROR_DEPTH`
/// where the reference, given a large enough `$depth`, would keep going. Only
/// programs that explicitly raise `$depth` past 1024 can observe it.
const NATIVE_DEPTH_CEILING: usize = 1024;

/// `JSON_OBJECT_AS_ARRAY` — decode JSON objects as PHP arrays. Only consulted
/// when `$associative` is left `null`, which is `ext/json`'s own precedence
/// (`php_json_decode_ex` ORs the flag in only for a null `$assoc`).
const JSON_OBJECT_AS_ARRAY: i64 = 1;

/// `json_decode($json, $associative = null, $depth = 512, $flags = 0)`.
///
/// `$associative` selects the container a JSON **object** decodes into: `true`
/// gives a PHP array, `false` a `stdClass`. Left `null` (the default) the
/// `JSON_OBJECT_AS_ARRAY` bit of `$flags` decides, defaulting to `stdClass`.
/// `$flags` beyond that and `JSON_THROW_ON_ERROR` are ignored.
fn json_decode(args: &[Value]) -> Result<Value, String> {
    let json = crate::host::with_host(|h| h.to_str(&args.first().cloned().unwrap_or(Value::Undef)));
    // 3rd argument is depth; default 512 (see `decode_depth`).
    let depth = decode_depth(args, 2, "json_decode", 3)?;
    let flags = args.get(3).map(|v| v.to_int()).unwrap_or(0);
    let assoc = match args.get(1) {
        // Absent or an explicit `null`: the flag bit is the tie-breaker.
        None | Some(Value::Undef) => flags & JSON_OBJECT_AS_ARRAY != 0,
        Some(v) => crate::host::with_host(|h| h.is_truthy(v)),
    };

    set_last_error(JSON_ERROR_NONE);
    let parsed = crate::host::with_host(|h| {
        let mut p = Parser::new(json.as_bytes(), depth, h);
        p.assoc = assoc;
        p.parse_document()
    });
    match parsed {
        Ok(v) => Ok(v),
        Err(code) => match fail(code, flags) {
            Some(e) => Err(e),
            None => Ok(Value::Undef),
        },
    }
}

/// `json_validate($json, $depth = 512, $flags = 0)` (PHP 8.3). Returns `true`
/// when `$json` is syntactically valid JSON, `false` otherwise. Like
/// `json_decode` it records the result in `json_last_error` /
/// `json_last_error_msg` (reset to `JSON_ERROR_NONE` on success).
///
/// The `$depth` argument is honored; `$flags` (only `JSON_INVALID_UTF8_IGNORE`
/// in PHP) is accepted and ignored — phplang strings are already valid UTF-8.
///
/// PHP validates without materializing the value; phplang runs the same parser
/// in a non-building mode (`Parser::new_validate`) so no PHP array is allocated,
/// matching that property while sharing the decoder's exact grammar.
fn json_validate(args: &[Value]) -> Result<Value, String> {
    let json = crate::host::with_host(|h| h.to_str(&args.first().cloned().unwrap_or(Value::Undef)));
    let depth = decode_depth(args, 1, "json_validate", 2)?;

    set_last_error(JSON_ERROR_NONE);
    let ok = crate::host::with_host(|h| {
        let mut p = Parser::new_validate(json.as_bytes(), depth, h);
        match p.parse_document() {
            Ok(_) => true,
            Err(code) => {
                set_last_error(code);
                false
            }
        }
    });
    Ok(Value::bool(ok))
}

// ── recursive-descent parser ────────────────────────────────────────────────

/// A single-pass JSON reader over a byte slice. Errors carry a `JSON_ERROR_*`
/// code so `json_decode` can record it for `json_last_error`.
struct Parser<'a, 'h> {
    b: &'a [u8],
    pos: usize,
    max_depth: usize,
    depth: usize,
    /// When `false` (validate mode) the parser walks the grammar without
    /// allocating PHP arrays; container values are placeholder `Undef`s and the
    /// only observable result is `Ok`/`Err`.
    build: bool,
    /// `json_decode`'s resolved `$associative`: a JSON object becomes a PHP array
    /// when set, a `stdClass` when clear. `json_validate` never reads it.
    assoc: bool,
    h: &'h mut PhpHost,
}

impl<'a, 'h> Parser<'a, 'h> {
    fn new(b: &'a [u8], max_depth: usize, h: &'h mut PhpHost) -> Self {
        Parser {
            b,
            pos: 0,
            max_depth,
            depth: 0,
            build: true,
            assoc: true,
            h,
        }
    }

    /// Non-building parser for `json_validate`: same grammar, no array allocation.
    fn new_validate(b: &'a [u8], max_depth: usize, h: &'h mut PhpHost) -> Self {
        Parser {
            b,
            pos: 0,
            max_depth,
            depth: 0,
            build: false,
            assoc: true,
            h,
        }
    }

    /// A fresh empty PHP array, or `Undef` in validate mode.
    fn make_container(&mut self) -> Value {
        if self.build {
            self.h.new_array()
        } else {
            Value::Undef
        }
    }

    /// The container a JSON `{…}` decodes into: a PHP array under
    /// `$associative`, otherwise an empty `stdClass`.
    ///
    /// WHEN this runs is observable, because `var_dump` prints an object's
    /// creation-order handle as `#N`. `ext/json`'s grammar allocates the object
    /// in `php_json_parser_object_init`, which the `members` rule reduces AFTER
    /// the first member's value has been parsed (or immediately for `{}`), so a
    /// nested object is numbered BEFORE the object holding it:
    /// `json_decode('{"a":{"b":1}}')` gives the inner `#1` and the outer `#2`.
    /// [`parse_object`] therefore calls this at the same point, not on `{`.
    fn make_object_container(&mut self) -> Value {
        if !self.build {
            return Value::Undef;
        }
        if self.assoc {
            self.h.new_array()
        } else {
            self.h.new_object_bare("stdClass", Vec::new())
        }
    }

    /// Parse a whole document: one value with only whitespace around it.
    fn parse_document(&mut self) -> Result<Value, i64> {
        self.skip_ws();
        if self.pos >= self.b.len() {
            return Err(JSON_ERROR_SYNTAX);
        }
        let v = self.parse_value()?;
        self.skip_ws();
        if self.pos != self.b.len() {
            return Err(JSON_ERROR_SYNTAX);
        }
        Ok(v)
    }

    fn skip_ws(&mut self) {
        while let Some(&c) = self.b.get(self.pos) {
            match c {
                b' ' | b'\t' | b'\n' | b'\r' => self.pos += 1,
                _ => break,
            }
        }
    }

    fn peek(&self) -> Option<u8> {
        self.b.get(self.pos).copied()
    }

    /// Consume a value: object, array, string, number, or a literal keyword.
    fn parse_value(&mut self) -> Result<Value, i64> {
        match self.peek() {
            Some(b'{') => self.parse_object(),
            Some(b'[') => self.parse_array(),
            Some(b'"') => Ok(Value::str(self.parse_string()?)),
            Some(b't') => self.parse_literal(b"true", Value::bool(true)),
            Some(b'f') => self.parse_literal(b"false", Value::bool(false)),
            Some(b'n') => self.parse_literal(b"null", Value::Undef),
            Some(c) if c == b'-' || c.is_ascii_digit() => self.parse_number(),
            _ => Err(JSON_ERROR_SYNTAX),
        }
    }

    fn parse_literal(&mut self, word: &[u8], val: Value) -> Result<Value, i64> {
        if self.b[self.pos..].starts_with(word) {
            self.pos += word.len();
            Ok(val)
        } else {
            Err(JSON_ERROR_SYNTAX)
        }
    }

    fn enter(&mut self) -> Result<(), i64> {
        // Matches ext/json PHP_JSON_DEPTH_INC: check before descending.
        //
        // `max_depth` is PHP's `$depth`, which counts NESTING LEVELS — the
        // scalar at the bottom is a level of its own. Opening a container costs
        // the level it sits at plus the one its contents need, so the guard is
        // `depth + 1`, not `depth`: at `$depth = 1` no container fits at all.
        if self.depth + 1 >= self.max_depth {
            return Err(JSON_ERROR_DEPTH);
        }
        self.depth += 1;
        Ok(())
    }

    fn parse_array(&mut self) -> Result<Value, i64> {
        self.enter()?;
        self.pos += 1; // '['
        let arr = self.make_container();
        self.skip_ws();
        if self.peek() == Some(b']') {
            self.pos += 1;
            self.depth -= 1;
            return Ok(arr);
        }
        loop {
            self.skip_ws();
            let v = self.parse_value()?;
            if self.build {
                self.h.arr_push_auto(&arr, v);
            }
            self.skip_ws();
            match self.peek() {
                Some(b',') => {
                    self.pos += 1;
                }
                Some(b']') => {
                    self.pos += 1;
                    break;
                }
                _ => return Err(JSON_ERROR_SYNTAX),
            }
        }
        self.depth -= 1;
        Ok(arr)
    }

    fn parse_object(&mut self) -> Result<Value, i64> {
        self.enter()?;
        self.pos += 1; // '{'
        self.skip_ws();
        if self.peek() == Some(b'}') {
            self.pos += 1;
            self.depth -= 1;
            return Ok(self.make_object_container());
        }
        // Deliberately not allocated yet — see `make_object_container` for why the
        // first member's value has to be parsed first.
        let mut arr: Option<Value> = None;
        loop {
            self.skip_ws();
            if self.peek() != Some(b'"') {
                return Err(JSON_ERROR_SYNTAX);
            }
            let key = self.parse_string()?;
            self.skip_ws();
            if self.peek() != Some(b':') {
                return Err(JSON_ERROR_SYNTAX);
            }
            self.pos += 1; // ':'
            self.skip_ws();
            let v = self.parse_value()?;
            let container = match &arr {
                Some(c) => c.clone(),
                None => {
                    let c = self.make_object_container();
                    arr = Some(c.clone());
                    c
                }
            };
            if self.build {
                if self.assoc {
                    // arr_set_key normalizes canonical integer string keys to int
                    // keys, matching PHP array-key coercion for objects like
                    // {"0":...}.
                    self.h.arr_set_key(&container, &Value::str(key), v);
                } else {
                    // A property name is NOT array-key coerced: `{"0":1}` decodes
                    // to a stdClass whose property is the string "0".
                    self.h.prop_set(&container, &key, v);
                }
            }
            self.skip_ws();
            match self.peek() {
                Some(b',') => {
                    self.pos += 1;
                }
                Some(b'}') => {
                    self.pos += 1;
                    break;
                }
                _ => return Err(JSON_ERROR_SYNTAX),
            }
        }
        self.depth -= 1;
        Ok(arr.unwrap_or(Value::Undef))
    }

    /// Parse a `"..."` string starting at the opening quote. Handles the JSON
    /// escapes, `\uXXXX`, and high/low surrogate pairs; rejects raw control
    /// characters (`JSON_ERROR_CTRL_CHAR`) and unpaired surrogates
    /// (`JSON_ERROR_UTF16`).
    fn parse_string(&mut self) -> Result<String, i64> {
        self.pos += 1; // opening quote
        let mut out = String::new();
        loop {
            let c = self.peek().ok_or(JSON_ERROR_SYNTAX)?;
            match c {
                b'"' => {
                    self.pos += 1;
                    return Ok(out);
                }
                b'\\' => {
                    self.pos += 1;
                    let esc = self.peek().ok_or(JSON_ERROR_SYNTAX)?;
                    self.pos += 1;
                    match esc {
                        b'"' => out.push('"'),
                        b'\\' => out.push('\\'),
                        b'/' => out.push('/'),
                        b'b' => out.push('\u{0008}'),
                        b'f' => out.push('\u{000C}'),
                        b'n' => out.push('\n'),
                        b'r' => out.push('\r'),
                        b't' => out.push('\t'),
                        b'u' => {
                            let cp = self.parse_hex4()?;
                            self.push_unicode(cp, &mut out)?;
                        }
                        _ => return Err(JSON_ERROR_SYNTAX),
                    }
                }
                c if c < 0x20 => return Err(JSON_ERROR_CTRL_CHAR),
                _ => {
                    // Copy one UTF-8 code point verbatim. The input is valid UTF-8
                    // (a Rust String), so a lead byte always has its continuation
                    // bytes present.
                    let len = utf8_len(c);
                    let end = (self.pos + len).min(self.b.len());
                    out.push_str(&String::from_utf8_lossy(&self.b[self.pos..end]));
                    self.pos = end;
                }
            }
        }
    }

    /// Read exactly four hex digits (the caller has consumed the `\u`).
    fn parse_hex4(&mut self) -> Result<u32, i64> {
        if self.pos + 4 > self.b.len() {
            return Err(JSON_ERROR_SYNTAX);
        }
        let mut val: u32 = 0;
        for _ in 0..4 {
            let d = hex_digit(self.b[self.pos]).ok_or(JSON_ERROR_SYNTAX)?;
            val = (val << 4) | d as u32;
            self.pos += 1;
        }
        Ok(val)
    }

    /// Append a decoded `\uXXXX` code unit, combining a high surrogate with a
    /// following `\uXXXX` low surrogate into one code point.
    fn push_unicode(&mut self, first: u32, out: &mut String) -> Result<(), i64> {
        if (0xD800..=0xDBFF).contains(&first) {
            // High surrogate: require a following \uDC00-\uDFFF low surrogate.
            if self.b.get(self.pos) == Some(&b'\\') && self.b.get(self.pos + 1) == Some(&b'u') {
                self.pos += 2;
                let low = self.parse_hex4()?;
                if (0xDC00..=0xDFFF).contains(&low) {
                    let cp = 0x10000 + ((first - 0xD800) << 10) + (low - 0xDC00);
                    out.push(char::from_u32(cp).ok_or(JSON_ERROR_UTF16)?);
                    return Ok(());
                }
                return Err(JSON_ERROR_UTF16);
            }
            return Err(JSON_ERROR_UTF16);
        }
        if (0xDC00..=0xDFFF).contains(&first) {
            // Unpaired low surrogate.
            return Err(JSON_ERROR_UTF16);
        }
        out.push(char::from_u32(first).ok_or(JSON_ERROR_UTF16)?);
        Ok(())
    }

    /// Parse a JSON number: `-?(0|[1-9]\d*)(\.\d+)?([eE][+-]?\d+)?`. Integral
    /// values that fit `i64` become `int`; anything with a fraction/exponent, or
    /// that overflows `i64`, becomes `float`.
    fn parse_number(&mut self) -> Result<Value, i64> {
        let start = self.pos;
        let mut is_float = false;

        if self.peek() == Some(b'-') {
            self.pos += 1;
        }
        match self.peek() {
            Some(b'0') => self.pos += 1,
            Some(c) if c.is_ascii_digit() => {
                while self.peek().is_some_and(|d| d.is_ascii_digit()) {
                    self.pos += 1;
                }
            }
            _ => return Err(JSON_ERROR_SYNTAX),
        }
        // Fraction.
        if self.peek() == Some(b'.') {
            is_float = true;
            self.pos += 1;
            if !self.peek().is_some_and(|d| d.is_ascii_digit()) {
                return Err(JSON_ERROR_SYNTAX);
            }
            while self.peek().is_some_and(|d| d.is_ascii_digit()) {
                self.pos += 1;
            }
        }
        // Exponent.
        if matches!(self.peek(), Some(b'e' | b'E')) {
            is_float = true;
            self.pos += 1;
            if matches!(self.peek(), Some(b'+' | b'-')) {
                self.pos += 1;
            }
            if !self.peek().is_some_and(|d| d.is_ascii_digit()) {
                return Err(JSON_ERROR_SYNTAX);
            }
            while self.peek().is_some_and(|d| d.is_ascii_digit()) {
                self.pos += 1;
            }
        }

        let text = std::str::from_utf8(&self.b[start..self.pos]).map_err(|_| JSON_ERROR_SYNTAX)?;
        if is_float {
            text.parse::<f64>()
                .map(Value::float)
                .map_err(|_| JSON_ERROR_SYNTAX)
        } else {
            match text.parse::<i64>() {
                Ok(n) => Ok(Value::int(n)),
                // Integer literal too large for i64: PHP returns a float here.
                Err(_) => text
                    .parse::<f64>()
                    .map(Value::float)
                    .map_err(|_| JSON_ERROR_SYNTAX),
            }
        }
    }
}

/// UTF-8 sequence length from a lead byte (defaults to 1 for continuation/junk).
fn utf8_len(lead: u8) -> usize {
    match lead {
        0x00..=0x7F => 1,
        0xC0..=0xDF => 2,
        0xE0..=0xEF => 3,
        0xF0..=0xF7 => 4,
        _ => 1,
    }
}

/// Value of one ASCII hex digit, or `None`.
fn hex_digit(b: u8) -> Option<u8> {
    match b {
        b'0'..=b'9' => Some(b - b'0'),
        b'a'..=b'f' => Some(b - b'a' + 10),
        b'A'..=b'F' => Some(b - b'A' + 10),
        _ => None,
    }
}