wikioxide 0.1.0

MediaWiki wikitext parser producing typed domain models (templates, links, categories, warnings) with template expansion — no HTML, no network
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
//! `{{#expr:}}` — the MediaWiki arithmetic expression evaluator.
//!
//! A faithful port of the ParserFunctions extension's `ExprParser.php`
//! (`MediaWiki\Extension\ParserFunctions\ExprParser`). The goal is byte-exact
//! agreement with the live parser: same operator set, same precedence table,
//! same PHP-double arithmetic quirks, same `precision = 14` number formatting,
//! and the same error strings the wiki renders inline.
//!
//! Evaluation is an iterative shunting-yard (infix → RPN) walk with two explicit
//! stacks, exactly like the reference. There is **no** input-controlled recursion,
//! so pathological input such as `((((…))))` or `ln(ln(ln(…)))` cannot overflow
//! the Rust stack — it hits the `MAX_STACK_SIZE` guard and returns an error, just
//! as MediaWiki does.
//!
//! ## Quirks replicated from PHP / ExprParser
//! - Unary `-`/`+` have precedence 10, higher than `^` (`EXPR_POW` = 8). Because
//!   the shunting loop pops on `<=`, this makes `-2^2` == `4` (the minus binds
//!   first) and makes `^` **left**-associative (`2^3^2` == `64`, not `512`).
//!   Verified against the live API.
//! - `e` is dual: a constant (`exp(1)`) when a value is expected, or a `×10^`
//!   operator when an operator is expected — so `1e4` == `10000` but a bare `e4`
//!   is an "Unexpected number" error.
//! - `mod` casts both operands to integer first (PHP `(int)`), so `5.7 mod 1.3`
//!   == `0`; the result carries the sign of the dividend (`-7 mod 3` == `-1`).
//! - `round` is PHP's `round()` with `HALF_UP` (half away from zero) plus PHP's
//!   pre-rounding correction, so `0.15 round 1` == `0.2` and `2.675 round 2`
//!   == `2.68` (a naive `*10^n` scale would give `0.1` / `2.67`).
//! - Non-finite results stringify like PHP: `INF`, `-INF`, `NAN`; negative zero
//!   prints `-0` (e.g. `0*-1`).
//!
//! ## Approximations (documented deviations)
//! - `Validator::cleanUp` (UTF-8 sanitisation) is a no-op here: a Rust `&str` is
//!   already valid UTF-8, so there is nothing to clean.
//! - PHP's `(int)` cast wraps to a 64-bit integer with platform-defined overflow;
//!   `trunc` uses `f64::trunc` and `mod` uses `f64 as i64` (saturating). These
//!   agree with PHP for every value inside `i64` range; only astronomically large
//!   operands differ.

use std::f64::consts::{E, PI};

/// An expression error whose text matches MediaWiki's exact wording (e.g.
/// `"Expression error: Unrecognized punctuation character \"@\""`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct ExprError {
    /// The fully-substituted, content-language message string.
    message: String,
}

impl ExprError {
    /// Wraps an already-formatted MediaWiki message string.
    fn new(message: String) -> Self {
        ExprError { message }
    }

    /// The MediaWiki-formatted error message (also what `{{#expr:}}` renders inline).
    pub(crate) fn message(&self) -> &str {
        &self.message
    }
}

/// Upper bound on either stack; mirrors `ExprParser::MAX_STACK_SIZE`. Reaching
/// 101 entries on the operand or operator stack aborts with "Stack exhausted."
const MAX_STACK_SIZE: usize = 100;

/// Every token that can sit on the operator stack (plus the two constants and the
/// brackets, which never reach [`do_operation`]). Variant order is irrelevant;
/// semantics come from [`precedence`] and [`op_name`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Op {
    /// Unary minus (`-x`).
    Negative,
    /// Unary plus (`+x`), a no-op that still requires an operand.
    Positive,
    /// Logical `not`.
    Not,
    /// Multiplication `*`.
    Times,
    /// Floating division `/` (also the `div` word).
    Divide,
    /// Integer modulo `mod` (PHP `%` on truncated operands).
    Mod,
    /// Floating remainder `fmod`.
    Fmod,
    /// Binary addition `+`.
    Plus,
    /// Binary subtraction `-`.
    Minus,
    /// `X round Y` — round `X` to `Y` decimal places.
    Round,
    /// Equality `=` (numeric).
    Equality,
    /// Less-than `<`.
    Less,
    /// Greater-than `>`.
    Greater,
    /// Less-or-equal `<=`.
    LessEq,
    /// Greater-or-equal `>=`.
    GreaterEq,
    /// Not-equal `<>` / `!=`.
    NotEq,
    /// Logical `and`.
    And,
    /// Logical `or`.
    Or,
    /// `X e Y` — scientific `×10^Y` operator (the `e` word used as an operator).
    Exponent,
    /// `sin`.
    Sine,
    /// `cos`.
    Cosine,
    /// `tan`.
    Tangens,
    /// `asin`.
    Arcsine,
    /// `acos`.
    Arccos,
    /// `atan`.
    Arctan,
    /// `ln` (natural log).
    Ln,
    /// `exp`.
    Exp,
    /// `abs`.
    Abs,
    /// `floor`.
    Floor,
    /// `trunc` (truncate toward zero).
    Trunc,
    /// `ceil`.
    Ceil,
    /// Exponentiation `^`.
    Pow,
    /// The constant `pi` (never an operator; here only for a complete table).
    Pi,
    /// `sqrt`.
    Sqrt,
    /// Opening bracket `(` — a precedence barrier on the operator stack.
    Open,
    /// Closing bracket `)` — never stored; present for completeness.
    Close,
}

/// The binding strength of each operator, copied verbatim from
/// `ExprParser::PRECEDENCE`. The shunting loop pops while
/// `precedence(incoming) <= precedence(top)`, which makes equal-precedence
/// operators left-associative and makes unary `-`/`+` (10) outrank `^` (8).
fn precedence(op: Op) -> i32 {
    match op {
        Op::Negative | Op::Positive | Op::Exponent => 10,
        Op::Sine
        | Op::Cosine
        | Op::Tangens
        | Op::Arcsine
        | Op::Arccos
        | Op::Arctan
        | Op::Exp
        | Op::Ln
        | Op::Abs
        | Op::Floor
        | Op::Trunc
        | Op::Ceil
        | Op::Not
        | Op::Sqrt => 9,
        Op::Pow => 8,
        Op::Times | Op::Divide | Op::Mod | Op::Fmod => 7,
        Op::Plus | Op::Minus => 6,
        Op::Round => 5,
        Op::Equality | Op::Less | Op::Greater | Op::LessEq | Op::GreaterEq | Op::NotEq => 4,
        Op::And => 3,
        Op::Or => 2,
        Op::Pi => 0,
        Op::Open | Op::Close => -1,
    }
}

/// The canonical operator name used in error messages, mirroring
/// `ExprParser::NAMES` (e.g. `Op::Divide` → `"/"` even when written `div`).
fn op_name(op: Op) -> &'static str {
    match op {
        Op::Negative | Op::Minus => "-",
        Op::Positive | Op::Plus => "+",
        Op::Not => "not",
        Op::Times => "*",
        Op::Divide => "/",
        Op::Mod => "mod",
        Op::Fmod => "fmod",
        Op::Round => "round",
        Op::Equality => "=",
        Op::Less => "<",
        Op::Greater => ">",
        Op::LessEq => "<=",
        Op::GreaterEq => ">=",
        Op::NotEq => "<>",
        Op::And => "and",
        Op::Or => "or",
        Op::Exponent => "e",
        Op::Sine => "sin",
        Op::Cosine => "cos",
        Op::Tangens => "tan",
        Op::Arcsine => "asin",
        Op::Arccos => "acos",
        Op::Arctan => "atan",
        Op::Ln => "ln",
        Op::Exp => "exp",
        Op::Abs => "abs",
        Op::Floor => "floor",
        Op::Trunc => "trunc",
        Op::Ceil => "ceil",
        Op::Pow => "^",
        Op::Pi => "pi",
        Op::Sqrt => "sqrt",
        Op::Open | Op::Close => "(",
    }
}

/// True for a byte in `ExprParser::EXPR_WHITE_CLASS` (space, tab, CR, LF).
fn is_white(b: u8) -> bool {
    matches!(b, b' ' | b'\t' | b'\r' | b'\n')
}

/// True for a byte in `ExprParser::EXPR_NUMBER_CLASS` (`0-9` and `.`).
fn is_number_byte(b: u8) -> bool {
    b.is_ascii_digit() || b == b'.'
}

/// Maps a lowercased alphabetic word to its operator/constant, mirroring
/// `ExprParser::WORDS`. Returns `None` for unrecognised words.
fn word_to_op(word: &str) -> Option<Op> {
    let op = match word {
        "mod" => Op::Mod,
        "fmod" => Op::Fmod,
        "and" => Op::And,
        "or" => Op::Or,
        "not" => Op::Not,
        "round" => Op::Round,
        "div" => Op::Divide,
        "e" => Op::Exponent,
        "sin" => Op::Sine,
        "cos" => Op::Cosine,
        "tan" => Op::Tangens,
        "asin" => Op::Arcsine,
        "acos" => Op::Arccos,
        "atan" => Op::Arctan,
        "exp" => Op::Exp,
        "ln" => Op::Ln,
        "abs" => Op::Abs,
        "trunc" => Op::Trunc,
        "floor" => Op::Floor,
        "ceil" => Op::Ceil,
        "pi" => Op::Pi,
        "sqrt" => Op::Sqrt,
        _ => return None,
    };
    Some(op)
}

/// Evaluates a `{{#expr:}}` expression to its MediaWiki string form.
///
/// Returns `Ok("")` for empty/whitespace input and otherwise the imploded
/// operand list (a single value in practice). Errors carry MediaWiki's exact
/// message text via [`ExprError::message`].
// COV-EXEMPT(the `if let Some((op, name)) = binary` tail has an unreachable else-arm:
// `binary` is definitely assigned `Some(..)` on every path that reaches it (all others
// `continue`/`return`), so llvm emits a 0-count region on that arm's closing brace that no
// input can exercise. The attribute is function-granular, the only granularity available.)
#[cfg_attr(coverage_nightly, coverage(off))]
pub(crate) fn eval(input: &str) -> Result<String, ExprError> {
    // `strtr` unescaping from the reference: HTML entities for the inequality
    // operators, plus the Unicode minus sign U+2212. These patterns do not
    // overlap, so sequential replacement matches PHP's simultaneous `strtr`.
    let expr = input
        .replace("&lt;", "<")
        .replace("&gt;", ">")
        .replace("&minus;", "-")
        .replace('\u{2212}', "-");

    let bytes = expr.as_bytes();
    let end = bytes.len();

    let mut operands: Vec<f64> = Vec::new();
    let mut operators: Vec<Op> = Vec::new();
    // `true` while a value (or prefix operator) is expected; `false` while a
    // binary operator is expected. Mirrors ExprParser's `$expecting`.
    let mut expecting_expression = true;
    let mut p = 0usize;

    while p < end {
        if operands.len() > MAX_STACK_SIZE || operators.len() > MAX_STACK_SIZE {
            return Err(ExprError::new(
                "Expression error: Stack exhausted.".to_owned(),
            ));
        }

        let b = bytes[p];
        let b1 = if p + 1 < end { bytes[p + 1] } else { 0 };

        // A pending binary operator, resolved by the shared block at the bottom.
        // Left uninitialised: every path either assigns it or diverges
        // (`continue`/`return`) before the shared block reads it.
        let binary: Option<(Op, String)>;

        if is_white(b) {
            while p < end && is_white(bytes[p]) {
                p += 1;
            }
            continue;
        } else if is_number_byte(b) {
            if !expecting_expression {
                return Err(ExprError::new(
                    "Expression error: Unexpected number.".to_owned(),
                ));
            }
            let start = p;
            while p < end && is_number_byte(bytes[p]) {
                p += 1;
            }
            // The whole `[0-9.]` run is consumed even though only the valid
            // float prefix contributes a value (PHP `(float)` of `"1.2.3"`
            // is `1.2`, yet `strspn` advanced past all of it).
            operands.push(parse_php_float(&expr[start..p]));
            expecting_expression = false;
            continue;
        } else if b.is_ascii_alphabetic() {
            let start = p;
            while p < end && bytes[p].is_ascii_alphabetic() {
                p += 1;
            }
            let word = expr[start..p].to_ascii_lowercase();
            let Some(op) = word_to_op(&word) else {
                return Err(ExprError::new(format!(
                    "Expression error: Unrecognized word \"{word}\"."
                )));
            };
            match op {
                Op::Exponent => {
                    if expecting_expression {
                        // Bare `e` used as a value → Euler's number.
                        operands.push(E);
                        expecting_expression = false;
                        continue;
                    }
                    // Otherwise it is the `×10^` binary operator.
                    binary = Some((Op::Exponent, word));
                }
                Op::Pi => {
                    if !expecting_expression {
                        return Err(ExprError::new(
                            "Expression error: Unexpected number.".to_owned(),
                        ));
                    }
                    operands.push(PI);
                    expecting_expression = false;
                    continue;
                }
                Op::Not
                | Op::Sine
                | Op::Cosine
                | Op::Tangens
                | Op::Arcsine
                | Op::Arccos
                | Op::Arctan
                | Op::Exp
                | Op::Ln
                | Op::Abs
                | Op::Floor
                | Op::Trunc
                | Op::Ceil
                | Op::Sqrt => {
                    if !expecting_expression {
                        return Err(ExprError::new(format!(
                            "Expression error: Unexpected {word} operator."
                        )));
                    }
                    operators.push(op);
                    continue;
                }
                // Binary words: mod, fmod, and, or, round, div.
                _ => binary = Some((op, word)),
            }
        } else if b == b'<' && b1 == b'=' {
            p += 2;
            binary = Some((Op::LessEq, "<=".to_owned()));
        } else if b == b'>' && b1 == b'=' {
            p += 2;
            binary = Some((Op::GreaterEq, ">=".to_owned()));
        } else if (b == b'<' && b1 == b'>') || (b == b'!' && b1 == b'=') {
            // Preserve the literal spelling for the "Unexpected … operator" text.
            let name = if b == b'!' { "!=" } else { "<>" };
            p += 2;
            binary = Some((Op::NotEq, name.to_owned()));
        } else if b == b'+' {
            p += 1;
            if expecting_expression {
                operators.push(Op::Positive);
                continue;
            }
            binary = Some((Op::Plus, "+".to_owned()));
        } else if b == b'-' {
            p += 1;
            if expecting_expression {
                operators.push(Op::Negative);
                continue;
            }
            binary = Some((Op::Minus, "-".to_owned()));
        } else if b == b'*' {
            p += 1;
            binary = Some((Op::Times, "*".to_owned()));
        } else if b == b'/' {
            p += 1;
            binary = Some((Op::Divide, "/".to_owned()));
        } else if b == b'^' {
            p += 1;
            binary = Some((Op::Pow, "^".to_owned()));
        } else if b == b'(' {
            if !expecting_expression {
                return Err(ExprError::new(
                    "Expression error: Unexpected ( operator.".to_owned(),
                ));
            }
            operators.push(Op::Open);
            p += 1;
            continue;
        } else if b == b')' {
            // Collapse everything back to the matching open bracket.
            loop {
                match operators.last().copied() {
                    Some(Op::Open) => {
                        operators.pop();
                        break;
                    }
                    Some(top) => {
                        operators.pop();
                        do_operation(top, &mut operands)?;
                    }
                    None => {
                        return Err(ExprError::new(
                            "Expression error: Unexpected closing bracket.".to_owned(),
                        ));
                    }
                }
            }
            expecting_expression = false;
            p += 1;
            continue;
        } else if b == b'=' {
            p += 1;
            binary = Some((Op::Equality, "=".to_owned()));
        } else if b == b'<' {
            p += 1;
            binary = Some((Op::Less, "<".to_owned()));
        } else if b == b'>' {
            p += 1;
            binary = Some((Op::Greater, ">".to_owned()));
        } else {
            // Any other byte: report the first *Unicode* character, like
            // `mb_substr(Validator::cleanUp(...), 0, 1)`.
            let ch = expr.get(p..).and_then(|s| s.chars().next()).unwrap_or('?');
            return Err(ExprError::new(format!(
                "Expression error: Unrecognized punctuation character \"{ch}\"."
            )));
        }

        // Shared binary-operator handling (the fall-through path of ExprParser).
        if let Some((op, name)) = binary {
            if expecting_expression {
                return Err(ExprError::new(format!(
                    "Expression error: Unexpected {name} operator."
                )));
            }
            // Shunting yard: pop while the stack top binds at least as tightly.
            while let Some(top) = operators.last().copied() {
                if precedence(op) <= precedence(top) {
                    operators.pop();
                    do_operation(top, &mut operands)?;
                } else {
                    break;
                }
            }
            operators.push(op);
            expecting_expression = true;
        }
    }

    // Drain the remaining operators; a leftover open bracket is unbalanced.
    while let Some(op) = operators.pop() {
        if op == Op::Open {
            return Err(ExprError::new(
                "Expression error: Unclosed bracket.".to_owned(),
            ));
        }
        do_operation(op, &mut operands)?;
    }

    Ok(operands
        .iter()
        .map(|v| format_double(*v))
        .collect::<Vec<_>>()
        .join("<br />\n"))
}

/// Applies one operator to the operand stack, reproducing `ExprParser::doOperation`
/// including its PHP double semantics and exact error strings.
fn do_operation(op: Op, stack: &mut Vec<f64>) -> Result<(), ExprError> {
    /// Builds the "Missing operand for X" error for `op`.
    fn missing(op: Op) -> ExprError {
        ExprError::new(format!(
            "Expression error: Missing operand for {}.",
            op_name(op)
        ))
    }
    /// The literal "Division by zero." message (parameter is ignored by MediaWiki).
    fn div_zero() -> ExprError {
        ExprError::new("Division by zero.".to_owned())
    }

    match op {
        Op::Negative => {
            if stack.is_empty() {
                return Err(missing(op));
            }
            let a = stack.pop().unwrap_or(0.0);
            stack.push(-a);
        }
        Op::Positive => {
            if stack.is_empty() {
                return Err(missing(op));
            }
            // Unary plus leaves the operand untouched.
        }
        Op::Times => {
            if stack.len() < 2 {
                return Err(missing(op));
            }
            let r = stack.pop().unwrap_or(0.0);
            let l = stack.pop().unwrap_or(0.0);
            stack.push(l * r);
        }
        Op::Divide => {
            if stack.len() < 2 {
                return Err(missing(op));
            }
            let r = stack.pop().unwrap_or(0.0);
            let l = stack.pop().unwrap_or(0.0);
            if r == 0.0 {
                return Err(div_zero());
            }
            stack.push(l / r);
        }
        Op::Mod => {
            if stack.len() < 2 {
                return Err(missing(op));
            }
            // PHP casts both operands to int before `%`; the result carries the
            // sign of the dividend, matching Rust's `%` on integers.
            let r = stack.pop().unwrap_or(0.0) as i64;
            let l = stack.pop().unwrap_or(0.0) as i64;
            if r == 0 {
                return Err(div_zero());
            }
            stack.push((l % r) as f64);
        }
        Op::Fmod => {
            if stack.len() < 2 {
                return Err(missing(op));
            }
            let r = stack.pop().unwrap_or(0.0);
            let l = stack.pop().unwrap_or(0.0);
            if r == 0.0 {
                return Err(div_zero());
            }
            // Rust's `%` on f64 is C `fmod` (remainder with sign of dividend).
            stack.push(l % r);
        }
        Op::Plus => {
            if stack.len() < 2 {
                return Err(missing(op));
            }
            let r = stack.pop().unwrap_or(0.0);
            let l = stack.pop().unwrap_or(0.0);
            stack.push(l + r);
        }
        Op::Minus => {
            if stack.len() < 2 {
                return Err(missing(op));
            }
            let r = stack.pop().unwrap_or(0.0);
            let l = stack.pop().unwrap_or(0.0);
            stack.push(l - r);
        }
        Op::And => {
            if stack.len() < 2 {
                return Err(missing(op));
            }
            let r = stack.pop().unwrap_or(0.0);
            let l = stack.pop().unwrap_or(0.0);
            stack.push(if l != 0.0 && r != 0.0 { 1.0 } else { 0.0 });
        }
        Op::Or => {
            if stack.len() < 2 {
                return Err(missing(op));
            }
            let r = stack.pop().unwrap_or(0.0);
            let l = stack.pop().unwrap_or(0.0);
            stack.push(if l != 0.0 || r != 0.0 { 1.0 } else { 0.0 });
        }
        Op::Equality => {
            if stack.len() < 2 {
                return Err(missing(op));
            }
            let r = stack.pop().unwrap_or(0.0);
            let l = stack.pop().unwrap_or(0.0);
            stack.push(if l == r { 1.0 } else { 0.0 });
        }
        Op::Not => {
            if stack.is_empty() {
                return Err(missing(op));
            }
            let a = stack.pop().unwrap_or(0.0);
            stack.push(if a == 0.0 { 1.0 } else { 0.0 });
        }
        Op::Round => {
            if stack.len() < 2 {
                return Err(missing(op));
            }
            let digits = stack.pop().unwrap_or(0.0) as i32;
            let value = stack.pop().unwrap_or(0.0);
            stack.push(php_round(value, digits));
        }
        Op::Less => {
            if stack.len() < 2 {
                return Err(missing(op));
            }
            let r = stack.pop().unwrap_or(0.0);
            let l = stack.pop().unwrap_or(0.0);
            stack.push(if l < r { 1.0 } else { 0.0 });
        }
        Op::Greater => {
            if stack.len() < 2 {
                return Err(missing(op));
            }
            let r = stack.pop().unwrap_or(0.0);
            let l = stack.pop().unwrap_or(0.0);
            stack.push(if l > r { 1.0 } else { 0.0 });
        }
        Op::LessEq => {
            if stack.len() < 2 {
                return Err(missing(op));
            }
            let r = stack.pop().unwrap_or(0.0);
            let l = stack.pop().unwrap_or(0.0);
            stack.push(if l <= r { 1.0 } else { 0.0 });
        }
        Op::GreaterEq => {
            if stack.len() < 2 {
                return Err(missing(op));
            }
            let r = stack.pop().unwrap_or(0.0);
            let l = stack.pop().unwrap_or(0.0);
            stack.push(if l >= r { 1.0 } else { 0.0 });
        }
        Op::NotEq => {
            if stack.len() < 2 {
                return Err(missing(op));
            }
            let r = stack.pop().unwrap_or(0.0);
            let l = stack.pop().unwrap_or(0.0);
            stack.push(if l != r { 1.0 } else { 0.0 });
        }
        Op::Exponent => {
            if stack.len() < 2 {
                return Err(missing(op));
            }
            let r = stack.pop().unwrap_or(0.0);
            let l = stack.pop().unwrap_or(0.0);
            stack.push(l * 10f64.powf(r));
        }
        Op::Sine => {
            if stack.is_empty() {
                return Err(missing(op));
            }
            let a = stack.pop().unwrap_or(0.0);
            stack.push(a.sin());
        }
        Op::Cosine => {
            if stack.is_empty() {
                return Err(missing(op));
            }
            let a = stack.pop().unwrap_or(0.0);
            stack.push(a.cos());
        }
        Op::Tangens => {
            if stack.is_empty() {
                return Err(missing(op));
            }
            let a = stack.pop().unwrap_or(0.0);
            stack.push(a.tan());
        }
        Op::Arcsine => {
            if stack.is_empty() {
                return Err(missing(op));
            }
            let a = stack.pop().unwrap_or(0.0);
            if !(-1.0..=1.0).contains(&a) {
                return Err(ExprError::new(format!(
                    "Invalid argument for {}: less than -1 or greater than 1.",
                    op_name(op)
                )));
            }
            stack.push(a.asin());
        }
        Op::Arccos => {
            if stack.is_empty() {
                return Err(missing(op));
            }
            let a = stack.pop().unwrap_or(0.0);
            if !(-1.0..=1.0).contains(&a) {
                return Err(ExprError::new(format!(
                    "Invalid argument for {}: less than -1 or greater than 1.",
                    op_name(op)
                )));
            }
            stack.push(a.acos());
        }
        Op::Arctan => {
            if stack.is_empty() {
                return Err(missing(op));
            }
            let a = stack.pop().unwrap_or(0.0);
            stack.push(a.atan());
        }
        Op::Exp => {
            if stack.is_empty() {
                return Err(missing(op));
            }
            let a = stack.pop().unwrap_or(0.0);
            stack.push(a.exp());
        }
        Op::Ln => {
            if stack.is_empty() {
                return Err(missing(op));
            }
            let a = stack.pop().unwrap_or(0.0);
            if a <= 0.0 {
                return Err(ExprError::new(
                    "Invalid argument for ln: less than or equal to 0.".to_owned(),
                ));
            }
            stack.push(a.ln());
        }
        Op::Abs => {
            if stack.is_empty() {
                return Err(missing(op));
            }
            let a = stack.pop().unwrap_or(0.0);
            stack.push(a.abs());
        }
        Op::Floor => {
            if stack.is_empty() {
                return Err(missing(op));
            }
            let a = stack.pop().unwrap_or(0.0);
            stack.push(a.floor());
        }
        Op::Trunc => {
            if stack.is_empty() {
                return Err(missing(op));
            }
            // PHP `(int)$arg` truncates toward zero; `f64::trunc` matches for all
            // values within `i64` range (see module approximation note).
            let a = stack.pop().unwrap_or(0.0);
            stack.push(a.trunc());
        }
        Op::Ceil => {
            if stack.is_empty() {
                return Err(missing(op));
            }
            let a = stack.pop().unwrap_or(0.0);
            stack.push(a.ceil());
        }
        Op::Pow => {
            if stack.len() < 2 {
                return Err(missing(op));
            }
            let r = stack.pop().unwrap_or(0.0);
            let l = stack.pop().unwrap_or(0.0);
            stack.push(l.powf(r));
        }
        Op::Sqrt => {
            if stack.is_empty() {
                return Err(missing(op));
            }
            let a = stack.pop().unwrap_or(0.0);
            let result = a.sqrt();
            if result.is_nan() {
                return Err(ExprError::new(format!(
                    "In {}: Result is not a number.",
                    op_name(op)
                )));
            }
            stack.push(result);
        }
        // Constants and brackets never reach doOperation in a real parse; the
        // reference throws "Unknown error" here. Exercised directly by a test.
        Op::Pi | Op::Open | Op::Close => {
            return Err(ExprError::new(
                "Expression error: Unknown error ().".to_owned(),
            ));
        }
    }
    Ok(())
}

/// Parses the valid float prefix of a `[0-9.]` run using PHP `(float)`/`strtod`
/// rules: digits, at most one `.`, then digits; a lone `"."` or empty string is
/// `0.0`; a second `.` (as in `"1.2.3"`) terminates the number at `1.2`.
fn parse_php_float(token: &str) -> f64 {
    let mut prefix = String::new();
    let mut seen_dot = false;
    for c in token.chars() {
        if c == '.' {
            if seen_dot {
                break;
            }
            seen_dot = true;
        }
        prefix.push(c);
    }
    if prefix.is_empty() || prefix == "." {
        return 0.0;
    }
    // Rust's parser dislikes leading/trailing dots; pad them.
    if prefix.starts_with('.') {
        prefix.insert(0, '0');
    }
    if prefix.ends_with('.') {
        prefix.push('0');
    }
    prefix.parse::<f64>().unwrap_or(0.0)
}

/// Formats a double exactly like PHP's `(string)` cast with `precision = 14`,
/// i.e. `zend_gcvt(value, 14, '.', 'E', …)` over `zend_dtoa` mode 2.
///
/// Returns `"INF"`/`"-INF"`/`"NAN"` for non-finite values, integral results with
/// no decimal point, and switches to `E` notation on the same thresholds PHP uses
/// (decimal exponent `> 14` or `< -3`).
fn format_double(v: f64) -> String {
    if v.is_nan() {
        return "NAN".to_owned();
    }
    if v.is_infinite() {
        return if v < 0.0 { "-INF" } else { "INF" }.to_owned();
    }

    let sign = v.is_sign_negative();
    let (digits, decpt) = dtoa14(v.abs());
    let ndigit: i32 = 14;

    let mut out = String::new();
    if sign {
        out.push('-');
    }

    if (decpt >= 0 && decpt > ndigit) || decpt < -3 {
        // E-style: `d.dddE±xx`.
        let mut e = decpt - 1;
        let neg_exp = e < 0;
        if neg_exp {
            e = -e;
        }
        let mut it = digits.chars();
        out.push(it.next().unwrap_or('0'));
        out.push('.');
        let rest: String = it.collect();
        if rest.is_empty() {
            out.push('0');
        } else {
            out.push_str(&rest);
        }
        out.push('E');
        out.push(if neg_exp { '-' } else { '+' });
        out.push_str(&e.to_string());
    } else if decpt < 0 {
        // Pure fraction: `0.00…digits`, with `-decpt` leading zeros.
        out.push('0');
        out.push('.');
        for _ in 0..(-decpt) {
            out.push('0');
        }
        out.push_str(&digits);
    } else {
        // Standard fixed notation.
        let d: Vec<char> = digits.chars().collect();
        let dp = decpt as usize;
        let mut i = 0usize;
        while i < dp {
            out.push(if i < d.len() { d[i] } else { '0' });
            i += 1;
        }
        if dp < d.len() {
            // A zero before the point when there is no integer part at all.
            if dp == 0 {
                out.push('0');
            }
            out.push('.');
            for &ch in &d[dp..] {
                out.push(ch);
            }
        }
    }

    out
}

/// Emulates `zend_dtoa(value, mode 2, ndigit 14)`: returns the significant
/// digits (trailing zeros stripped) and `decpt`, the position of the decimal
/// point relative to the start of the digit string. `value` must be finite and
/// non-negative.
// COV-EXEMPT(the `trimmed.is_empty()` guard is unreachable: `value == 0.0` returns early,
// and any normalized nonzero mantissa from `{:.13e}` has a nonzero leading digit that
// `trim_end_matches('0')` cannot remove).
#[cfg_attr(coverage_nightly, coverage(off))]
fn dtoa14(value: f64) -> (String, i32) {
    if value == 0.0 {
        return ("0".to_owned(), 1);
    }
    // `{:.13e}` yields 14 significant digits, correctly rounded ties-to-even —
    // the same rounding zend_dtoa mode 2 performs.
    let s = format!("{value:.13e}");
    let (mantissa, exp) = s.split_once('e').unwrap_or((s.as_str(), "0"));
    let exp: i32 = exp.parse().unwrap_or(0);
    let all_digits: String = mantissa.chars().filter(|c| *c != '.').collect();
    let decpt = exp + 1;
    let trimmed = all_digits.trim_end_matches('0');
    let digits = if trimmed.is_empty() {
        "0".to_owned()
    } else {
        trimmed.to_owned()
    };
    (digits, decpt)
}

/// `10^power` via PHP's exact-power lookup table for `0..=22`, falling back to
/// `powi` outside that range. Matches `php_intpow10`.
fn intpow10(power: i32) -> f64 {
    const P: [f64; 23] = [
        1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16,
        1e17, 1e18, 1e19, 1e20, 1e21, 1e22,
    ];
    if (0..=22).contains(&power) {
        P[power as usize]
    } else {
        10f64.powi(power)
    }
}

/// `floor(log10(|value|))` computed robustly against the power table so exact
/// powers of ten do not slip a rank. Matches `php_intlog10abs`.
// COV-EXEMPT(the `e += 1` correction loop is unreachable: `f64::log10().floor()` never
// underestimates the decade for any input, so `intpow10(e + 1) <= value` is false on entry;
// verified by exhaustive decade-boundary and randomized f64 search).
#[cfg_attr(coverage_nightly, coverage(off))]
fn intlog10abs(value: f64) -> i32 {
    let value = value.abs();
    if value == 0.0 {
        return 0;
    }
    let mut e = value.log10().floor() as i32;
    while intpow10(e) > value {
        e -= 1;
    }
    while intpow10(e + 1) <= value {
        e += 1;
    }
    e
}

/// PHP `round($value, $places, PHP_ROUND_HALF_UP)` including the pre-rounding
/// correction that makes `0.15 round 1 == 0.2` and `2.675 round 2 == 2.68`.
/// A direct port of pre-8.4 `_php_math_round`.
fn php_round(value: f64, places: i32) -> f64 {
    if !value.is_finite() || value == 0.0 {
        return value;
    }

    let f1 = intpow10(places.abs());
    let precision_places = 14 - intlog10abs(value);
    let tmp_value;

    if precision_places > places && precision_places - 15 < places {
        // Pre-round at full precision, then shift to the requested scale.
        let mut use_precision = precision_places.max(-60);
        let f2 = intpow10(use_precision.abs());
        let mut t = if use_precision >= 0 {
            value * f2
        } else {
            value / f2
        };
        t = round_helper(t);

        use_precision = (places - use_precision).clamp(-60, 60);
        let f2b = intpow10(use_precision.abs());
        t = if use_precision >= 0 { t * f2b } else { t / f2b };
        tmp_value = round_helper(t);
    } else {
        let t = if places >= 0 { value * f1 } else { value / f1 };
        if t.abs() >= 1e15 {
            return value;
        }
        tmp_value = round_helper(t);
    }

    if places.abs() < 23 {
        if places > 0 {
            tmp_value / f1
        } else {
            tmp_value * f1
        }
    } else {
        // Extreme scale: reconstruct through a decimal string, as PHP does.
        let reparsed = format!("{tmp_value:.6}e{}", -places).parse::<f64>();
        match reparsed {
            Ok(x) if x.is_finite() && x != 0.0 => x,
            _ => value,
        }
    }
}

/// The `PHP_ROUND_HALF_UP` kernel (`php_round_helper`): round to the nearest
/// integer, ties away from zero, with the small ±0.5 boundary corrections PHP
/// applies to counter floating error.
// COV-EXEMPT(the ±0.5 boundary corrections are unreachable from `php_round`: the else path
// returns before calling this whenever |t| >= 1e15, and the pre-round path normalizes to
// ~1e14 (< 2^52), where `value + 0.5` is exact so `t - value` stays in (-0.5, 0.5]; verified
// by randomized f64 search — the corrections only fire for |value| > 2^52, never fed here).
#[cfg_attr(coverage_nightly, coverage(off))]
fn round_helper(value: f64) -> f64 {
    if value >= 0.0 {
        let mut t = (value + 0.5).floor();
        if t - value > 0.5 {
            t -= 1.0;
        } else if t - value <= -0.5 {
            t += 1.0;
        }
        t
    } else {
        let mut t = (value - 0.5).ceil();
        if t - value < -0.5 {
            t += 1.0;
        } else if t - value >= 0.5 {
            t -= 1.0;
        }
        t
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Convenience: evaluate and unwrap to the rendered string.
    fn ev(s: &str) -> String {
        eval(s).unwrap()
    }

    /// Convenience: evaluate and unwrap the error message.
    fn err(s: &str) -> String {
        eval(s).unwrap_err().message().to_owned()
    }

    #[test]
    fn empty_expression_is_empty() {
        assert_eq!(eval("   "), Ok(String::new()));
        assert_eq!(eval(""), Ok(String::new()));
    }

    #[test]
    fn reference_test_suite_values() {
        // The exact table from ParserFunctions' ExpressionTest::provideExpressions.
        let cases: &[(&str, &str)] = &[
            ("1 or 0", "1"),
            ("not (1 and 0)", "1"),
            ("not 0", "1"),
            ("4 < 5", "1"),
            ("-5 < 2", "1"),
            ("-2 <= -2", "1"),
            ("4 > 3", "1"),
            ("4 > -3", "1"),
            ("5 >= 2", "1"),
            ("2 >= 2", "1"),
            ("1 != 2", "1"),
            ("-4 * -4 = 4 * 4", "1"),
            ("not (1 != 1)", "1"),
            ("1 + 1", "2"),
            ("-1 + 1", "0"),
            ("+1 + 1", "2"),
            ("4 * 4", "16"),
            ("(1/3) * 3", "1"),
            ("3 / 1.5", "2"),
            ("3 / 0.2", "15"),
            ("3 / ( 2.0 * 0.1 )", "15"),
            ("3 / ( 2.0 / 10 )", "15"),
            ("3 / (- 0.2 )", "-15"),
            ("3 / abs( 0.2 )", "15"),
            ("3 mod 2", "1"),
            ("1e4", "10000"),
            ("1e-2", "0.01"),
            ("4.0 round 0", "4"),
            ("ceil 4", "4"),
            ("floor 4", "4"),
            ("4.5 round 0", "5"),
            ("4.2 round 0", "4"),
            ("-4.2 round 0", "-4"),
            ("-4.5 round 0", "-5"),
            ("-2.0 round 0", "-2"),
            ("ceil -3", "-3"),
            ("floor -6.0", "-6"),
            ("ceil 4.2", "5"),
            ("ceil -4.5", "-4"),
            ("floor -4.5", "-5"),
            ("abs(-2)", "2"),
            ("ln(exp(1))", "1"),
            ("trunc(4.5)", "4"),
            ("trunc(-4.5)", "-4"),
            ("123 fmod (2^64-1)", "123"),
            ("5.7 mod 1.3", "0"),
            ("5.7 fmod 1.3", "0.5"),
            ("pi + 1", "4.1415926535898"),
            ("sin(0)", "0"),
            ("cos(0)", "1"),
            ("tan(0)", "0"),
            ("asin(0)", "0"),
            ("acos(1)", "0"),
            ("atan(0)", "0"),
            ("sqrt(4)", "2"),
        ];
        for (input, expected) in cases {
            assert_eq!(ev(input), *expected, "input: {input}");
        }
    }

    #[test]
    fn values_verified_against_live_api() {
        // Each pair was checked against the English Wikipedia parse API.
        let cases: &[(&str, &str)] = &[
            ("10/3", "3.3333333333333"),
            ("2^10", "1024"),
            ("7 mod 3", "1"),
            ("-7 mod 3", "-1"),
            ("7 mod -3", "1"),
            ("2.5 round 0", "3"),
            ("8.5 round 0", "9"),
            ("5.5 round 0", "6"),
            ("0.15 round 1", "0.2"),
            ("-0.15 round 1", "-0.2"),
            ("2.675 round 2", "2.68"),
            ("1234.5678 round -2", "1200"),
            ("1234.5678 round 2", "1234.57"),
            ("-2^2", "4"),
            ("2^-2", "0.25"),
            ("2^0.5", "1.4142135623731"),
            ("1/3", "0.33333333333333"),
            ("1000000*1000000", "1000000000000"),
            ("sin(1)", "0.8414709848079"),
            ("ln(2)", "0.69314718055995"),
            ("0.1+0.2", "0.3"),
            ("1e20", "1.0E+20"),
            ("1e15", "1.0E+15"),
            ("1e14", "1.0E+14"),
            ("1e13", "10000000000000"),
            ("1e-4", "0.0001"),
            ("1e-5", "1.0E-5"),
            ("0*-1", "-0"),
            ("1.5e300*1e300", "INF"),
        ];
        for (input, expected) in cases {
            assert_eq!(ev(input), *expected, "input: {input}");
        }
    }

    #[test]
    fn power_is_left_associative() {
        // `<=` shunting makes `^` left-associative: (2^3)^2 = 64, not 2^(3^2)=512.
        assert_eq!(ev("2^3^2"), "64");
    }

    #[test]
    fn euler_constant_and_exponent_operator() {
        assert_eq!(ev("e = exp(1)"), "1");
        assert_eq!(ev("2 e 3"), "2000");
    }

    #[test]
    fn logical_operators() {
        assert_eq!(ev("0 and 1"), "0");
        assert_eq!(ev("0 or 0"), "0");
        assert_eq!(ev("5 and 3"), "1");
        assert_eq!(ev("not 5"), "0");
        assert_eq!(ev("1 = 1"), "1");
        assert_eq!(ev("1 <> 2"), "1");
        assert_eq!(ev("1 != 1"), "0");
        assert_eq!(ev("2 <= 1"), "0");
        assert_eq!(ev("2 >= 3"), "0");
    }

    #[test]
    fn unary_and_div_mod_fmod() {
        assert_eq!(ev("+5"), "5");
        assert_eq!(ev("- -5"), "5");
        assert_eq!(ev("10 div 4"), "2.5");
        assert_eq!(ev("10 mod 4"), "2");
        assert_eq!(ev("10 fmod 4"), "2");
        assert_eq!(ev("trunc 9.99"), "9");
    }

    #[test]
    fn entity_unescaping() {
        assert_eq!(ev("1 &lt; 2"), "1");
        assert_eq!(ev("2 &gt; 1"), "1");
        assert_eq!(ev("5 &minus; 3"), "2");
        assert_eq!(ev("5 \u{2212} 3"), "2");
    }

    #[test]
    fn nan_result_stringifies() {
        // inf - inf produces NaN without triggering a domain error.
        assert_eq!(ev("(1e300*1e300) - (1e300*1e300)"), "NAN");
        assert_eq!(ev("-1e300*1e300"), "-INF");
    }

    #[test]
    fn number_parsing_quirks() {
        assert_eq!(ev(".5"), "0.5");
        assert_eq!(ev("5."), "5");
        assert_eq!(ev("1.2.3"), "1.2");
        assert_eq!(ev("."), "0");
    }

    #[test]
    fn multi_digit_exponent_formatting() {
        assert_eq!(ev("1e100"), "1.0E+100");
        assert_eq!(ev("1e-100"), "1.0E-100");
    }

    #[test]
    fn trig_and_sqrt() {
        assert_eq!(ev("cos(0) + sin(0)"), "1");
        assert_eq!(ev("atan(0)"), "0");
        assert_eq!(ev("acos(1)"), "0");
        assert_eq!(ev("asin(1) = pi/2"), "1");
        assert_eq!(ev("sqrt(9)"), "3");
    }

    #[test]
    fn all_error_strings() {
        assert_eq!(err("1 2"), "Expression error: Unexpected number.");
        assert_eq!(err("1 pi"), "Expression error: Unexpected number.");
        assert_eq!(err("foo"), "Expression error: Unrecognized word \"foo\".");
        assert_eq!(err("FOO"), "Expression error: Unrecognized word \"foo\".");
        assert_eq!(err("1 sin"), "Expression error: Unexpected sin operator.");
        assert_eq!(err("1 ("), "Expression error: Unexpected ( operator.");
        assert_eq!(err("<1"), "Expression error: Unexpected < operator.");
        assert_eq!(err("!=1"), "Expression error: Unexpected != operator.");
        assert_eq!(err("<>1"), "Expression error: Unexpected <> operator.");
        assert_eq!(
            err("1 + 1)"),
            "Expression error: Unexpected closing bracket."
        );
        assert_eq!(err("(1"), "Expression error: Unclosed bracket.");
        assert_eq!(
            err("1, 2"),
            "Expression error: Unrecognized punctuation character \",\"."
        );
        assert_eq!(
            err("1 @ 2"),
            "Expression error: Unrecognized punctuation character \"@\"."
        );
        assert_eq!(
            err("1 \u{00d7} 2"),
            "Expression error: Unrecognized punctuation character \"\u{00d7}\"."
        );
        assert_eq!(err("-"), "Expression error: Missing operand for -.");
        assert_eq!(err("+"), "Expression error: Missing operand for +.");
        assert_eq!(err("1*"), "Expression error: Missing operand for *.");
        assert_eq!(err("1/"), "Expression error: Missing operand for /.");
        assert_eq!(err("1 mod"), "Expression error: Missing operand for mod.");
        assert_eq!(err("1 fmod"), "Expression error: Missing operand for fmod.");
        assert_eq!(err("1+"), "Expression error: Missing operand for +.");
        assert_eq!(err("1-"), "Expression error: Missing operand for -.");
        assert_eq!(err("1 and"), "Expression error: Missing operand for and.");
        assert_eq!(err("1 or"), "Expression error: Missing operand for or.");
        assert_eq!(err("1 ="), "Expression error: Missing operand for =.");
        // `not` after a value is an unexpected unary operator, not a missing
        // operand (the reference's test label "Missing operand: not" is
        // misleading — `testExpressionThrows` only asserts *some* error).
        assert_eq!(err("1 not"), "Expression error: Unexpected not operator.");
        assert_eq!(
            err("1 round"),
            "Expression error: Missing operand for round."
        );
        assert_eq!(err("1<"), "Expression error: Missing operand for <.");
        assert_eq!(err("1>"), "Expression error: Missing operand for >.");
        assert_eq!(err("1<="), "Expression error: Missing operand for <=.");
        assert_eq!(err("1>="), "Expression error: Missing operand for >=.");
        assert_eq!(err("1<>"), "Expression error: Missing operand for <>.");
        assert_eq!(err("sin()"), "Expression error: Missing operand for sin.");
        assert_eq!(err("cos()"), "Expression error: Missing operand for cos.");
        assert_eq!(err("tan()"), "Expression error: Missing operand for tan.");
        assert_eq!(err("asin()"), "Expression error: Missing operand for asin.");
        assert_eq!(err("acos()"), "Expression error: Missing operand for acos.");
        assert_eq!(err("atan()"), "Expression error: Missing operand for atan.");
        assert_eq!(err("exp()"), "Expression error: Missing operand for exp.");
        assert_eq!(err("ln()"), "Expression error: Missing operand for ln.");
        assert_eq!(err("abs()"), "Expression error: Missing operand for abs.");
        assert_eq!(err("floor"), "Expression error: Missing operand for floor.");
        assert_eq!(err("trunc"), "Expression error: Missing operand for trunc.");
        assert_eq!(err("ceil"), "Expression error: Missing operand for ceil.");
        assert_eq!(err("1 ^"), "Expression error: Missing operand for ^.");
        assert_eq!(err("sqrt"), "Expression error: Missing operand for sqrt.");
        assert_eq!(err("1 e"), "Expression error: Missing operand for e.");
        assert_eq!(err("1/0"), "Division by zero.");
        assert_eq!(err("1 mod 0"), "Division by zero.");
        assert_eq!(err("1 fmod 0"), "Division by zero.");
        assert_eq!(err("1 mod 0.5"), "Division by zero.");
        assert_eq!(
            err("asin(3)"),
            "Invalid argument for asin: less than -1 or greater than 1."
        );
        assert_eq!(
            err("acos(-1.1)"),
            "Invalid argument for acos: less than -1 or greater than 1."
        );
        assert_eq!(
            err("ln(-1)"),
            "Invalid argument for ln: less than or equal to 0."
        );
        assert_eq!(
            err("ln(0)"),
            "Invalid argument for ln: less than or equal to 0."
        );
        assert_eq!(err("sqrt(-1)"), "In sqrt: Result is not a number.");
    }

    #[test]
    fn stack_exhaustion_does_not_overflow() {
        let deep_parens = format!("{}1{}", "(".repeat(1001), ")".repeat(1001));
        assert_eq!(err(&deep_parens), "Expression error: Stack exhausted.");
        let deep_calls = format!("{}1{}", "ln(".repeat(1001), ")".repeat(1001));
        assert_eq!(err(&deep_calls), "Expression error: Stack exhausted.");
    }

    #[test]
    fn do_operation_unreachable_ops_error() {
        // The constant/bracket arms of doOperation are unreachable in a real
        // parse; drive them directly for coverage.
        let mut stack = vec![1.0];
        assert_eq!(
            do_operation(Op::Pi, &mut stack).unwrap_err().message(),
            "Expression error: Unknown error ()."
        );
        assert_eq!(
            do_operation(Op::Open, &mut stack).unwrap_err().message(),
            "Expression error: Unknown error ()."
        );
        assert_eq!(
            do_operation(Op::Close, &mut stack).unwrap_err().message(),
            "Expression error: Unknown error ()."
        );
    }

    #[test]
    fn helper_edge_cases() {
        // Formatting specials directly.
        assert_eq!(format_double(f64::NAN), "NAN");
        assert_eq!(format_double(f64::INFINITY), "INF");
        assert_eq!(format_double(f64::NEG_INFINITY), "-INF");
        assert_eq!(format_double(0.0), "0");
        // Power table bounds and out-of-range fallback.
        assert_eq!(intpow10(0), 1.0);
        assert_eq!(intpow10(22), 1e22);
        // Out-of-table power falls back to `powi` (its rounding differs from the
        // `1e23` literal, so compare against the same expression).
        assert_eq!(intpow10(23), 10f64.powi(23));
        assert_eq!(intpow10(-1), 0.1);
        // intlog10abs on an exact power of ten and on zero.
        assert_eq!(intlog10abs(1000.0), 3);
        assert_eq!(intlog10abs(0.0), 0);
        // round early-return paths.
        assert_eq!(php_round(0.0, 2), 0.0);
        assert!(php_round(f64::INFINITY, 2).is_infinite());
        // Very large scale hits the >= 1e15 guard (returns value unchanged).
        assert_eq!(php_round(5.0, 100), 5.0);
        // Negative-half rounding kernel.
        assert_eq!(round_helper(-2.5), -3.0);
        assert_eq!(round_helper(2.5), 3.0);
    }

    #[test]
    fn round_extreme_scale_branch() {
        // Exercises the |places| >= 23 string-reparse branch of php_round: a tiny
        // value with a large positive scale takes the pre-round path and then
        // reconstructs through a decimal string.
        assert_eq!(php_round(1e-10, 23), 1e-10);
        // A value whose magnitude is too large for the scale returns unchanged.
        assert_eq!(php_round(5.0, 100), 5.0);
    }

    #[test]
    fn whitespace_and_bare_number() {
        assert_eq!(ev("\t 42 \n"), "42");
        assert_eq!(ev("3"), "3");
    }

    #[test]
    fn not_missing_operand_and_left_assoc_or() {
        // A dangling `not` drains with an empty stack (covers Op::Not missing).
        assert_eq!(err("not"), "Expression error: Missing operand for not.");
        // A second `or` forces the first off the stack, exercising precedence(Or).
        assert_eq!(ev("1 or 0 or 1"), "1");
    }

    #[test]
    fn e_style_multi_digit_mantissa() {
        // Non-empty fractional part of an E-style mantissa.
        assert_eq!(ev("1.5e20"), "1.5E+20");
        assert_eq!(ev("1.25e-10"), "1.25E-10");
    }

    #[test]
    fn precedence_and_name_tables_are_total() {
        // Constants/brackets never flow through the shunting or doOperation name
        // paths, so cover their table entries directly.
        assert_eq!(precedence(Op::Pi), 0);
        assert_eq!(precedence(Op::Close), -1);
        assert_eq!(op_name(Op::Pi), "pi");
        assert_eq!(op_name(Op::Open), "(");
        assert_eq!(op_name(Op::Close), "(");
    }

    #[test]
    fn php_round_branch_coverage() {
        // else-branch without early return (precision_places <= places).
        assert_eq!(php_round(1e14, 0), 1e14);
        // precision branch with a negative use_precision (value / f2 path).
        assert_eq!(php_round(1e15, -3), 1e15);
        // |places| >= 23 string path whose reparse underflows to 0 → value kept.
        assert_eq!(php_round(1e10, -25), 1e10);
        // intlog10abs adjustment loop on an exact power of ten.
        assert_eq!(intlog10abs(1e16), 16);
        assert_eq!(intlog10abs(0.1), -1);
    }
}