Making Java's blocking sleep async is a fixpoint over the call graph
Misha's iterate mind writes code as well as running it, and on 1 November it brought back a set of games from the early 2000s.
Twenty-three Java games from the turn of the century, transpiled to TypeScript in 2019 and broken ever since, all because every one of them assumes it can stop the world for twenty milliseconds.
One of the apps the mind built on 1 November revives a set of old Java applet games in the browser. Between 2016 and 2019 the public repo mmkal/slimejs decompiled the applets, ran them through jsweet (a Java-to-TypeScript transpiler) and cleaned up the output with regexes. Its last build, in 2019, contained no games. A newer jsweet had changed the shape of its output, and the regexes no longer matched.
jsweet's online sandbox is gone, so the job couldn't be redone from the Java source. What remained was the TypeScript that the 2019 run had committed. The agent's task was to finish that output so it would run. Three things were wrong with it:
- Overloads came back with their Java signatures in their names:
Thread.sleep$long,fillPolygon$int_A$int_A$int. - The Java classes the games use (Applet, Graphics, Thread and others) came back as stub classes inside the game files, shadowing the real shims.
- Nothing was async. Each game loop paces itself with
Thread.sleep(20), which in Java blocks the thread. As synchronous JavaScript, the loop never yields to the browser.
Use regexes where the problem is textual
The first two problems really are textual. A renamed overload always looks the same, so a short list of patterns fixes it:
const RENAMES: [RegExp, string][] = [
[/\bThread\.sleep\$long(\$boolean)?\(/g, "Thread.sleep("],
[/\.println\$java_lang_Object\(/g, ".println("],
];
for (const [pattern, to] of RENAMES) text = text.replace(pattern, to);
Stub classes are found by parsing the file and removing any top-level class whose name is also imported from the shims. A regex could try this, but a parser gives the exact start and end of the class.
Use a parser where the problem is structural
Making the code async is not textual. Once sleep returns a promise, the method calling it has to be async and has to await it. Then every method that calls that method must become async and await it, and so on up the call graph. Miss one link and the caller runs ahead without waiting for the sleep, holding a promise it never awaited.
So postprocess.mjs uses TypeScript's own parser and computes the set of async methods as a fixpoint:
// seed: methods that sleep, plus the ones the shims always await
const asyncNames = new Set(ALWAYS_ASYNC);
for (const [name, decls] of methods)
if (decls.some((m) => callsIn(m).some(isSleep))) asyncNames.add(name);
// grow: a method that calls an async one is async, until nothing changes
for (let changed = true; changed; ) {
changed = false;
for (const [name, decls] of methods) {
if (asyncNames.has(name)) continue;
if (decls.some((m) => callsIn(m).some((c) => asyncNames.has(calledName(c))))) {
asyncNames.add(name);
changed = true;
}
}
}
A second pass over the syntax tree turns that set into edits. It inserts async before each method's name, changes a declared return type T to Promise<T>, and wraps each qualifying call as (await …). The edits are collected as offsets and applied from the end of the file backwards, so earlier edits don't move later positions.
The matching is by method name, not by resolved type. That is coarse but adequate. In decompiled applet code, a method name almost always refers to the same method, and marking one extra method async is harmless. Two cases are handled explicitly. Calls on the graphics object (fillRect, drawString and similar) belong to the shims and are never awaited, even when a game method has the same name. A call to an async method from somewhere that can't be made async, such as top-level code or a non-method function, isn't silently left alone. It becomes a build warning that names the call.
Stopping a game without stopping its loop
Once the loops yield, a second issue appears. The page has a game picker, and switching games has to stop the old one. Its loop is still a while (true) sitting in some await. The shims handle this with a generation counter:
let generation = 0; // bumped each time a game stops
Thread.sleep = (ms: number) => {
const mine = generation;
return new Promise<void>((resolve) =>
setTimeout(() => mine === generation && resolve(), ms));
};
A sleep that started under an older generation never resolves. The old loop just stays suspended in its await, and no game code needed a stop flag added. The same idea appears elsewhere for cancelling long-running async work: don't interrupt the worker, just stop answering its next request to wait.
What made it checkable
The build downloads the original repo at a pinned commit and runs the postprocessor over each game file. It writes each result under a // @ts-nocheck header marking it as finished transpiler output, then bundles the page with esbuild. All 23 games build, and the agent soak-tested each one in headless Chromium before publishing. The built files live in the mind's file store, and only their manifest is committed.
The general pattern: when cleaning up generated code, use regexes for the parts that are just text and a parser for the parts that are about structure. When a property spreads through calls, as async does, compute it as a fixpoint and don't try to guess it one file at a time. The old pipeline broke when the generator's output changed shape. The structural part now depends on the syntax tree, not on how the text happens to look.