javars 0.1.14

Java as a fusevm frontend: lexer, parser, and compiler to fusevm::Chunk, run on the shared three-tier Cranelift JIT — no bespoke VM or JVM
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
//! The implicit `java.lang` / `java.util.function` prelude.
//!
//! javars has no JDK to link against, so the exception classes a `throw`/`catch`
//! program names (`RuntimeException`, `IllegalStateException`, …) do not exist
//! until javars supplies them. Rather than special-case them in the compiler,
//! this module *writes them in Java* and parses them with the ordinary parser:
//! they become ordinary [`crate::ast::Class`] nodes with real fields, real
//! constructors, and real `toString()` bodies, so every existing mechanism —
//! `extends` chains, `super(m)` chaining, virtual dispatch, `instanceof` through
//! [`crate::host`]'s supertype table — applies to them unchanged. `catch
//! (Exception e)` catching a `NumberFormatException` is then just the
//! `instanceof` walk javars already had.
//!
//! The `java.util.function` interfaces (`Runnable`, `Function`, `Predicate`, …)
//! are supplied the same way, and for the same reason: a lambda target is just
//! an interface with one abstract method, so declaring them in Java means the
//! compiler needs no table of built-in functional types — a user's own
//! `interface Calc { int of(int a); }` reaches the identical code path.
//!
//! Each half of the prelude is injected only into programs that actually use it
//! (see [`inject`]), so a program that never throws and never writes a lambda
//! carries none of these types and emits exactly the bytecode it did before.

use crate::ast::Program;

/// The modeled `java.lang` throwable hierarchy: `(class, superclass)`, ordered
/// so a superclass is always declared before its subclasses. `Throwable` has no
/// superclass and carries the `detailMessage` field the whole tree inherits.
///
/// This is the subset a hand-written program throws and catches; the JDK's full
/// hierarchy is far larger, and an unlisted name is an unknown class (a compile
/// error) rather than a silently-accepted one.
pub const THROWABLES: &[(&str, &str)] = &[
    ("Throwable", ""),
    ("Error", "Throwable"),
    ("Exception", "Throwable"),
    ("RuntimeException", "Exception"),
    ("IllegalArgumentException", "RuntimeException"),
    ("NumberFormatException", "IllegalArgumentException"),
    ("IllegalStateException", "RuntimeException"),
    ("ArithmeticException", "RuntimeException"),
    ("NullPointerException", "RuntimeException"),
    ("ClassCastException", "RuntimeException"),
    ("UnsupportedOperationException", "RuntimeException"),
    ("NegativeArraySizeException", "RuntimeException"),
    ("IndexOutOfBoundsException", "RuntimeException"),
    (
        "ArrayIndexOutOfBoundsException",
        "IndexOutOfBoundsException",
    ),
    (
        "StringIndexOutOfBoundsException",
        "IndexOutOfBoundsException",
    ),
    // The modeled throwables that do not live in `java.lang` — see
    // [`qualified_throwable`].
    ("PatternSyntaxException", "IllegalArgumentException"),
    ("ConcurrentModificationException", "RuntimeException"),
    ("NoSuchElementException", "RuntimeException"),
    ("EmptyStackException", "RuntimeException"),
    ("InputMismatchException", "NoSuchElementException"),
    ("IOException", "Exception"),
    ("ArrayStoreException", "RuntimeException"),
    // The `assert`-style failure a program throws by hand
    // (`throw new AssertionError()` in an unreachable branch).
    ("AssertionError", "Error"),
    // A static initializer that completes abruptly (JLS 12.4.2): the
    // exception wrapped, and every later use of the erroneous class.
    ("LinkageError", "Error"),
    ("ExceptionInInitializerError", "LinkageError"),
    ("NoClassDefFoundError", "LinkageError"),
    // What `Object.clone()` throws for a class that is not `Cloneable`.
    ("CloneNotSupportedException", "Exception"),
    ("IllegalFormatException", "IllegalArgumentException"),
    ("IllegalFormatConversionException", "IllegalFormatException"),
    // The rest of `java.util`'s format family. Each is a *catchable*
    // `IllegalFormatException` in Java, and javars reported all four as internal
    // `javars:` errors that abort the run — two of them only after a `panic!` or
    // a hang first. Superclasses read off `getSuperclass()` on openjdk 21.0.12,
    // not assumed from the names: all four sit directly under
    // `IllegalFormatException`, siblings of `IllegalFormatConversionException`.
    ("IllegalFormatWidthException", "IllegalFormatException"),
    ("IllegalFormatPrecisionException", "IllegalFormatException"),
    ("MissingFormatArgumentException", "IllegalFormatException"),
    ("UnknownFormatConversionException", "IllegalFormatException"),
    // The two the flag validator raises. A flag the conversion does not accept
    // (`%,x`) and a pair that contradict each other (`%+ d`) were both accepted
    // and ignored before it existed, so the format string said something the
    // program could not have meant and nothing reported it.
    (
        "FormatFlagsConversionMismatchException",
        "IllegalFormatException",
    ),
    ("IllegalFormatFlagsException", "IllegalFormatException"),
    ("MissingFormatWidthException", "IllegalFormatException"),
    // `%c` of an `int` that is no code point.
    ("IllegalFormatCodePointException", "IllegalFormatException"),
];

/// The modeled throwables below `Throwable` that also declare Java's two
/// cause-chaining constructors, `(String, Throwable)` and `(Throwable)`. Read off
/// `javap -public` on openjdk 27: `NumberFormatException`,
/// `ArithmeticException`, `NullPointerException`, `ClassCastException`,
/// `IndexOutOfBoundsException` and the rest declare only `()` and `(String)`,
/// so `new ArithmeticException("x", e)` stays the compile error `javac` makes
/// it.
const CAUSE_CTORS: &[&str] = &[
    "Error",
    "Exception",
    "RuntimeException",
    "IllegalArgumentException",
    "IllegalStateException",
    "UnsupportedOperationException",
    "ConcurrentModificationException",
    "NoSuchElementException",
    "IOException",
];

/// True when `name` is one of the modeled JDK throwables.
pub fn is_throwable(name: &str) -> bool {
    THROWABLES.iter().any(|(n, _)| *n == name)
}

/// The fully-qualified name of a modeled throwable, which is what
/// `getClass().getName()`, `Throwable.toString()`, and the uncaught-exception
/// report print. Most live in `java.lang`; `PatternSyntaxException` is
/// `java.util.regex` and `ConcurrentModificationException` is `java.util`, and
/// printing either under the wrong package would be a visible difference from
/// Java for a program that ever prints a caught one.
pub fn qualified_throwable(name: &str) -> Option<String> {
    if !is_throwable(name) {
        return None;
    }
    Some(match name {
        "PatternSyntaxException" => format!("java.util.regex.{name}"),
        "IOException" => format!("java.io.{name}"),
        "ConcurrentModificationException"
        | "NoSuchElementException"
        | "EmptyStackException"
        | "InputMismatchException"
        | "IllegalFormatException"
        | "IllegalFormatConversionException"
        | "IllegalFormatWidthException"
        | "IllegalFormatPrecisionException"
        | "MissingFormatArgumentException"
        | "UnknownFormatConversionException"
        | "FormatFlagsConversionMismatchException"
        | "IllegalFormatFlagsException"
        | "MissingFormatWidthException"
        | "IllegalFormatCodePointException" => format!("java.util.{name}"),
        _ => format!("java.lang.{name}"),
    })
}

/// The fully-qualified name of a modeled JDK class, or `None` for a user class
/// (whose simple name *is* its qualified one — a single-file program declares no
/// package). This is what `getClass().getName()` prints and what Java's
/// `Object.toString()` puts before the `@`.
///
/// `Object` is the root of the hierarchy rather than a modeled type: javars
/// keeps it out of the class table on purpose (it is also the erasure of every
/// type variable), so it is named here directly.
pub fn qualified_class(name: &str) -> Option<String> {
    if matches!(name, "Object" | "StringBuilder" | "StringBuffer") {
        return Some(format!("java.lang.{name}"));
    }
    qualified_throwable(name)
}

/// The package a modeled functional interface lives in: `java.lang.Runnable`,
/// `java.util.concurrent.Callable`, `java.util.Comparator`, and everything else
/// in `java.util.function`.
pub fn qualified_functional(name: &str) -> Option<String> {
    if !FUNCTIONAL.iter().any(|(n, _, _)| *n == name) {
        return None;
    }
    Some(match name {
        "Runnable" => format!("java.lang.{name}"),
        "Callable" => format!("java.util.concurrent.{name}"),
        "Comparator" => format!("java.util.{name}"),
        _ => format!("java.util.function.{name}"),
    })
}

/// The modeled functional interfaces: `(name, declared single abstract method,
/// the interface's other members)`.
///
/// Each is declared to javars as an ordinary `interface`, whose one *abstract*
/// method is all a lambda target needs — the compiler recognises *any*
/// single-abstract-method interface (user-declared ones included) as a lambda
/// target, so these entries buy no special case, only the declarations the JDK
/// would have supplied. Type parameters are erased, so the parameter and return
/// types below are the erasure Java itself uses (`Object`), except where the
/// JDK's own signature is primitive (`Predicate.test` → `boolean`,
/// `Comparator.compare` → `int`), which javars keeps so a call participates in
/// numeric typing.
///
/// The third column is the JDK's `default` and `static` members, transliterated
/// from the bodies `java.util.function` declares. They are ordinary Java, so
/// they compile through the same paths a user's own `default` method does, and a
/// *lambda* receiver reaches them because a closure gets its own arm in the
/// dispatch chain. The JDK's leading `Objects.requireNonNull(after)` is the one
/// thing dropped: it would pull the whole throwable prelude into every program
/// that writes a lambda, and composing with `null` still raises the same
/// `NullPointerException` — at the composed function's first call rather than at
/// composition (named in `BUGS.md`).
pub const FUNCTIONAL: &[(&str, &str, &str)] = &[
    ("Runnable", "void run()", ""),
    ("Callable", "Object call()", ""),
    ("Supplier", "Object get()", ""),
    (
        "Consumer",
        "void accept(Object t)",
        "default Consumer andThen(Consumer after) { return t -> { this.accept(t); after.accept(t); }; }",
    ),
    (
        "BiConsumer",
        "void accept(Object t, Object u)",
        "default BiConsumer andThen(BiConsumer after) { return (t, u) -> { this.accept(t, u); after.accept(t, u); }; } \
         static Function mapMulti$(BiConsumer mapper) { return t -> { ArrayList buf = new ArrayList(); mapper.accept(t, buf::add); return buf; }; }",
    ),
    (
        "Function",
        "Object apply(Object t)",
        "default Function andThen(Function after) { return t -> after.apply(this.apply(t)); } \
         default Function compose(Function before) { return v -> this.apply(before.apply(v)); } \
         static Function identity() { return t -> t; }",
    ),
    (
        "BiFunction",
        "Object apply(Object t, Object u)",
        "default BiFunction andThen(Function after) { return (t, u) -> after.apply(this.apply(t, u)); }",
    ),
    (
        "UnaryOperator",
        "Object apply(Object t)",
        // `UnaryOperator extends Function`, so it inherits `andThen`/`compose`
        // (but not the `static identity`, which it redeclares).
        "default Function andThen(Function after) { return t -> after.apply(this.apply(t)); } \
         default Function compose(Function before) { return v -> this.apply(before.apply(v)); } \
         static UnaryOperator identity() { return t -> t; }",
    ),
    (
        "BinaryOperator",
        "Object apply(Object t, Object u)",
        // `BinaryOperator extends BiFunction`, whose `andThen` it inherits.
        "default BiFunction andThen(Function after) { return (t, u) -> after.apply(this.apply(t, u)); } \
         static BinaryOperator minBy(Comparator comparator) { return (a, b) -> comparator.compare(a, b) <= 0 ? a : b; } \
         static BinaryOperator maxBy(Comparator comparator) { return (a, b) -> comparator.compare(a, b) >= 0 ? a : b; }",
    ),
    (
        "Predicate",
        "boolean test(Object t)",
        "default Predicate and(Predicate other) { return t -> this.test(t) && other.test(t); } \
         default Predicate negate() { return t -> !this.test(t); } \
         default Predicate or(Predicate other) { return t -> this.test(t) || other.test(t); } \
         static Predicate not(Predicate target) { return target.negate(); } \
         static Predicate isEqual(Object targetRef) { return t -> targetRef == null ? t == null : targetRef.equals(t); }",
    ),
    (
        "BiPredicate",
        "boolean test(Object t, Object u)",
        "default BiPredicate and(BiPredicate other) { return (t, u) -> this.test(t, u) && other.test(t, u); } \
         default BiPredicate negate() { return (t, u) -> !this.test(t, u); } \
         default BiPredicate or(BiPredicate other) { return (t, u) -> this.test(t, u) || other.test(t, u); }",
    ),
    (
        "Comparator",
        "int compare(Object a, Object b)",
        // `thenComparing` is overloaded in Java on `Comparator` *and* on a key
        // extractor, and the two are told apart by the target type — which
        // javars has no pass for. They are told apart here by *arity* instead,
        // which is exact: a comparator takes two arguments and a key extractor
        // one, and `Comparator.isKeyExtractor` reads the count off the lambda.
        // The four `comparingXxx` statics differ only in the width they promise,
        // which javars does not track, so they share one body.
        "default Comparator reversed() { return (a, b) -> this.compare(b, a); } \
         default Comparator thenComparing(Object other) { Comparator c = Comparator.asComparator(other); return (a, b) -> { int r = this.compare(a, b); if (r != 0) { return r; } return c.compare(a, b); }; } \
         default Comparator thenComparing(Function key, Comparator keyCmp) { return this.thenComparing(Comparator.comparing(key, keyCmp)); } \
         default Comparator thenComparingInt(Function key) { return this.thenComparing(key); } \
         default Comparator thenComparingLong(Function key) { return this.thenComparing(key); } \
         default Comparator thenComparingDouble(Function key) { return this.thenComparing(key); } \
         static Comparator asComparator(Object x) { if (Comparator.isKeyExtractor(x)) { Function k = (Function) x; return (a, b) -> k.apply(a).compareTo(k.apply(b)); } return (Comparator) x; } \
         static Comparator naturalOrder() { return (a, b) -> a.compareTo(b); } \
         static Comparator reverseOrder() { return (a, b) -> b.compareTo(a); } \
         static Comparator comparing(Function key) { return (a, b) -> key.apply(a).compareTo(key.apply(b)); } \
         static Comparator comparing(Function key, Comparator keyCmp) { return (a, b) -> keyCmp.compare(key.apply(a), key.apply(b)); } \
         static Comparator nullsFirst(Comparator c) { return (a, b) -> { if (a == null) { return b == null ? 0 : -1; } if (b == null) { return 1; } return c == null ? 0 : c.compare(a, b); }; } \
         static Comparator nullsLast(Comparator c) { return (a, b) -> { if (a == null) { return b == null ? 0 : 1; } if (b == null) { return -1; } return c == null ? 0 : c.compare(a, b); }; } \
         static Comparator comparingInt(Function key) { return Comparator.comparing(key); } \
         static Comparator comparingLong(Function key) { return Comparator.comparing(key); } \
         static Comparator comparingDouble(Function key) { return Comparator.comparing(key); } \
         static Comparator comparingByKey() { return (a, b) -> a.getKey().compareTo(b.getKey()); } \
         static Comparator comparingByKey(Comparator c) { return (a, b) -> c.compare(a.getKey(), b.getKey()); } \
         static Comparator comparingByValue() { return (a, b) -> a.getValue().compareTo(b.getValue()); } \
         static Comparator comparingByValue(Comparator c) { return (a, b) -> c.compare(a.getValue(), b.getValue()); }",
    ),
    ("IntSupplier", "int getAsInt()", ""),
    (
        "IntPredicate",
        "boolean test(int value)",
        "default IntPredicate and(IntPredicate other) { return value -> this.test(value) && other.test(value); } \
         default IntPredicate negate() { return value -> !this.test(value); } \
         default IntPredicate or(IntPredicate other) { return value -> this.test(value) || other.test(value); }",
    ),
    (
        "IntConsumer",
        "void accept(int value)",
        "default IntConsumer andThen(IntConsumer after) { return value -> { this.accept(value); after.accept(value); }; }",
    ),
    (
        "IntUnaryOperator",
        "int applyAsInt(int operand)",
        "default IntUnaryOperator compose(IntUnaryOperator before) { return v -> this.applyAsInt(before.applyAsInt(v)); } \
         default IntUnaryOperator andThen(IntUnaryOperator after) { return v -> after.applyAsInt(this.applyAsInt(v)); } \
         static IntUnaryOperator identity() { return v -> v; }",
    ),
    ("IntBinaryOperator", "int applyAsInt(int left, int right)", ""),
    ("ToIntFunction", "int applyAsInt(Object value)", ""),
    ("ToDoubleFunction", "double applyAsDouble(Object value)", ""),
    ("ToLongFunction", "long applyAsLong(Object value)", ""),
    // The primitive-input, *reference*-output functions. Their declared return
    // type is what tells the compiler a `char`-typed lambda body crosses into a
    // reference position and has to box: without `IntFunction` declared,
    // `IntFunction<Character> f = c -> (char) c; f.apply(97)` answered 97
    // instead of `a`, because the lambda had no known return type to convert to.
    ("IntFunction", "Object apply(int value)", ""),
    ("LongFunction", "Object apply(long value)", ""),
    ("DoubleFunction", "Object apply(double value)", ""),
    ("IntToLongFunction", "long applyAsLong(int value)", ""),
    ("IntToDoubleFunction", "double applyAsDouble(int value)", ""),
    ("LongToIntFunction", "int applyAsInt(long value)", ""),
    ("DoubleToIntFunction", "int applyAsInt(double value)", ""),
    ("LongSupplier", "long getAsLong()", ""),
    ("DoubleSupplier", "double getAsDouble()", ""),
    (
        "LongUnaryOperator",
        "long applyAsLong(long operand)",
        "static LongUnaryOperator identity() { return v -> v; }",
    ),
    ("LongBinaryOperator", "long applyAsLong(long left, long right)", ""),
    (
        "DoubleUnaryOperator",
        "double applyAsDouble(double operand)",
        "static DoubleUnaryOperator identity() { return v -> v; }",
    ),
    (
        "DoubleBinaryOperator",
        "double applyAsDouble(double left, double right)",
        "",
    ),
    (
        "LongPredicate",
        "boolean test(long value)",
        "default LongPredicate negate() { return value -> !this.test(value); }",
    ),
    (
        "DoublePredicate",
        "boolean test(double value)",
        "default DoublePredicate negate() { return value -> !this.test(value); }",
    ),
    ("LongConsumer", "void accept(long value)", ""),
    ("DoubleConsumer", "void accept(double value)", ""),
];

/// True when `name` is one of the modeled functional interfaces.
pub fn is_functional(name: &str) -> bool {
    FUNCTIONAL.iter().any(|(n, _, _)| *n == name)
}

/// The Java source of the prelude classes the program does not already declare.
///
/// `Throwable` holds the message, the accessors, and the single `toString()` the
/// whole tree inherits; every subclass adds only its two constructors.
///
/// That one `toString()` asks `this.getClass().getName()` for the name, which is
/// what Java's own `Throwable.toString()` does. The earlier shape gave *each*
/// prelude class its own override with the qualified name written into the
/// string literal, so the name came from the class the compiler resolved the
/// override on rather than from the object. That is indistinguishable for a
/// prelude class thrown directly, and wrong for every user-defined one:
/// `class MyEx extends RuntimeException` inherited `RuntimeException`'s
/// override and rendered `java.lang.RuntimeException: b` where Java prints
/// `T$MyEx: b`. Subclassing an exception is the ordinary way to define one, so
/// that was the common case, not the corner.
fn prelude_source(declared: &[String]) -> String {
    let mut src =
        String::from("public class __JavaLang { public static void main(String[] a) { } }\n");
    for (name, sup) in THROWABLES {
        if declared.iter().any(|d| d == name) {
            continue;
        }
        let extends = if sup.is_empty() {
            String::new()
        } else {
            format!(" extends {sup}")
        };
        src.push_str(&format!("class {name}{extends} {{\n"));
        if sup.is_empty() {
            // The root carries the state and the accessors. An absent message is
            // the field's default (`null`), which is exactly what Java's
            // `getMessage()` returns for the no-arg constructor.
            src.push_str("  String detailMessage;\n");
            // Java marks a cause that was never set by pointing the field at
            // the throwable itself; `causeSet` is that sentinel, since a field
            // initializer cannot name `this` here. It is what lets `initCause`
            // succeed once on a `(String)` throwable and refuse on one
            // constructed with a cause.
            src.push_str("  Throwable cause;\n  boolean causeSet;\n");
            // The exceptions `addSuppressed` recorded, in order; `null` until
            // the first, as the JDK's list is the shared empty one until then.
            src.push_str("  ArrayList suppressed;\n");
            src.push_str(&format!("  {name}() {{ }}\n"));
            src.push_str(&format!("  {name}(String m) {{ detailMessage = m; }}\n"));
            src.push_str(&format!(
                "  {name}(String m, Throwable c) {{ detailMessage = m; cause = c; causeSet = true; }}\n"
            ));
            // `Throwable(Throwable)` takes the cause's `toString()` as its own
            // message, so `new RuntimeException(e)` prints
            // `java.lang.RuntimeException: java.lang.Exception: inner`.
            src.push_str(&format!(
                "  {name}(Throwable c) {{ detailMessage = (c == null ? null : c.toString()); \
                 cause = c; causeSet = true; }}\n"
            ));
            src.push_str("  Throwable getCause() { return cause; }\n");
            // `initCause`'s two refusals, with the JDK's messages. Both name
            // prelude throwables, so the method is left out when the program
            // declares its own class under either name.
            if !declared
                .iter()
                .any(|d| d == "IllegalStateException" || d == "IllegalArgumentException")
            {
                src.push_str(
                    "  Throwable initCause(Throwable c) { \
                     if (causeSet) { throw new IllegalStateException(\"Can't overwrite cause with \" \
                     + (c == null ? \"a null\" : c.toString()), this); } \
                     if (c == this) { throw new IllegalArgumentException(\"Self-causation not permitted\", this); } \
                     cause = c; causeSet = true; return this; }\n",
                );
            }
            // `addSuppressed` is always declared, because try-with-resources
            // lowers to a call of it. Its two refusals, with the JDK's
            // messages, name prelude throwables, so they are left out when the
            // program declares its own class under either name.
            let refusals = if declared
                .iter()
                .any(|d| d == "IllegalArgumentException" || d == "NullPointerException")
            {
                ""
            } else {
                "if (e == this) { throw new IllegalArgumentException(\"Self-suppression not permitted\", e); } \
                 if (e == null) { throw new NullPointerException(\"Cannot suppress a null exception.\"); } "
            };
            src.push_str(&format!(
                "  void addSuppressed(Throwable e) {{ {refusals}\
                 if (suppressed == null) {{ suppressed = new ArrayList<>(); }} \
                 suppressed.add(e); }}\n"
            ));
            src.push_str(
                "  Throwable[] getSuppressed() { int n = suppressed == null ? 0 : suppressed.size(); \
                 Throwable[] out = new Throwable[n]; \
                 for (int i = 0; i < n; i++) { out[i] = (Throwable) suppressed.get(i); } \
                 return out; }\n",
            );
            src.push_str("  String getMessage() { return detailMessage; }\n");
            // `getLocalizedMessage()` is `Throwable`'s own one-liner
            // (`return getMessage();`), and `toString()` below asks it — so a
            // subclass that overrides either one changes the rendered text.
            src.push_str("  String getLocalizedMessage() { return getMessage(); }\n");
            // `printStackTrace()` writes to standard error: the throwable's
            // `toString()`, then a `Caused by: ` line for each cause. javars
            // keeps no call-site table, so the `\tat …` frame lines between
            // them are absent; standard output is untouched either way.
            src.push_str(
                "  void printStackTrace() { System.err.println(this); \
                 Throwable[] s = getSuppressed(); \
                 for (int i = 0; i < s.length; i++) { System.err.println(\"\\tSuppressed: \" + s[i]); } \
                 Throwable c = getCause(); \
                 while (c != null && c != this) { System.err.println(\"Caused by: \" + c); \
                 c = c.getCause(); } }\n",
            );
            // The name comes from the *object*, not from the class this method
            // was resolved on — `getName()` already answers `java.lang.Foo` for
            // a modeled throwable (including the two that are not in
            // `java.lang`) and `T$MyEx` for a user-defined one.
            src.push_str(
                "  String toString() { String n = this.getClass().getName(); \
                 String m = getLocalizedMessage(); \
                 if (m == null) { return n; } return n + \": \" + m; }\n",
            );
        } else if *name == "ExceptionInInitializerError" {
            // The JDK's three constructors: `()` records a `null` cause,
            // `(Throwable)` the exception with no message of its own, and
            // `getException()` is the cause by another name.
            src.push_str(
                "  ExceptionInInitializerError() { cause = null; causeSet = true; }\n  \
                 ExceptionInInitializerError(String m) { detailMessage = m; cause = null; causeSet = true; }\n  \
                 ExceptionInInitializerError(Throwable thrown) { cause = thrown; causeSet = true; }\n  \
                 Throwable getException() { return getCause(); }\n",
            );
        } else if *name == "PatternSyntaxException" {
            // The JDK's class: one constructor, the three accessors, and a
            // `getMessage()` built from them — the description, ` near index
            // N`, the pattern on its own line, and a caret under the index. A
            // refusal javars raises itself (a construct it cannot run) is marked
            // `refused` and keeps the message it was raised with.
            src.push_str(
                "  String desc;\n  String pattern;\n  int index;\n  boolean refused;\n  \
                 PatternSyntaxException(String desc, String regex, int index) { \
                 super(desc); this.desc = desc; this.pattern = regex; this.index = index; }\n  \
                 String getDescription() { return desc; }\n  \
                 int getIndex() { return index; }\n  \
                 String getPattern() { return pattern; }\n  \
                 String getMessage() { if (refused) { return detailMessage; } \
                 StringBuilder sb = new StringBuilder(); sb.append(desc); \
                 if (index >= 0) { sb.append(\" near index \"); sb.append(index); } \
                 sb.append(\"\n\"); sb.append(pattern); \
                 if (index >= 0 && pattern != null && index < pattern.length()) { sb.append(\"\n\"); \
                 for (int i = 0; i < index; i++) { sb.append(pattern.charAt(i) == '\t' ? '\t' : ' '); } \
                 sb.append('^'); } return sb.toString(); }\n",
            );
        } else {
            src.push_str(&format!("  {name}() {{ }}\n"));
            src.push_str(&format!("  {name}(String m) {{ super(m); }}\n"));
            if CAUSE_CTORS.contains(name) {
                src.push_str(&format!(
                    "  {name}(String m, Throwable c) {{ super(m, c); }}\n  {name}(Throwable c) {{ super(c); }}\n"
                ));
            }
        }
        src.push_str("}\n");
    }
    src
}

/// Add the modeled `java.lang` throwables to `prog` when it uses exceptions.
///
/// A no-op for a program that never throws, catches, or constructs a throwable —
/// which keeps every existing program's AST, bytecode, and class table exactly
/// as they were. A class the user declares themselves (`class Exception { … }`)
/// wins: its name is skipped, so the user's definition is the only one.
pub fn inject(prog: &mut Program) -> Result<(), String> {
    if prog.uses_exceptions {
        let src = prelude_source(&declared_names(prog));
        merge(prog, &src)?;
    }
    if prog.uses_functional {
        let src = functional_source(&declared_names(prog));
        merge(prog, &src)?;
    }
    Ok(())
}

/// The names of every type the unit already declares (a user declaration always
/// wins over a prelude one of the same name).
fn declared_names(prog: &Program) -> Vec<String> {
    prog.classes.iter().map(|c| c.name.clone()).collect()
}

/// Parse a prelude compilation unit and fold its types into `prog`.
fn merge(prog: &mut Program, src: &str) -> Result<(), String> {
    let parsed = crate::parser::parse(src)?;
    // Everything except the synthetic entry class (which only exists because a
    // compilation unit must declare a `main`). `__` is not a name any Java
    // program uses for a type, and both prelude units spell theirs that way.
    prog.classes.extend(
        parsed
            .classes
            .into_iter()
            .filter(|c| !c.name.starts_with("__")),
    );
    // A prelude type's `static` members (`Function.identity`, `Predicate.not`,
    // `BinaryOperator.minBy`) live in the unit-wide pool a qualified `C.m(…)`
    // resolves against, not on the class node, so the pool has to be merged too.
    prog.methods.extend(
        parsed
            .methods
            .into_iter()
            .filter(|m| !m.owner.starts_with("__")),
    );
    Ok(())
}

/// The Java source of the functional interfaces the program does not already
/// declare. Each is a plain `interface` with one abstract method, so a lambda
/// assigned to it reaches the compiler's ordinary single-abstract-method lambda
/// target path, plus the `default`/`static` members the JDK declares alongside.
fn functional_source(declared: &[String]) -> String {
    let mut src = String::from(
        "public class __JavaUtilFunction { public static void main(String[] a) { } }\n",
    );
    for (name, sam, members) in FUNCTIONAL {
        if declared.iter().any(|d| d == name) {
            continue;
        }
        src.push_str(&format!("interface {name} {{ {sam}; {members} }}\n"));
    }
    src
}