Before your leek can fight, the server first has to turn your AI into something the machine can run. This compilation happens every time an AI changes: you save a new version, and at the next fight, it gets recompiled. For a small AI, you never notice. For a big AI with several thousand lines and dozens of included files, it takes seconds.
Since November 29, this step is two to four times faster, depending on the AI. Nothing else changes: your AIs make exactly the same choices, use exactly the same operations and report their errors on the same lines. Here is the story of this project, which was really about learning to do without a middleman without anyone noticing.
LeekScript runs on the Java virtual machine (the JVM). Until now, the compiler translated your AI into Java text, a real source file like one a Java developer would write. Then it called javac, the official Java compiler, to turn that text into bytecode, the language the JVM runs.
It works very well, and it is even what made LeekScript fast for years. But it is a detour. The LeekScript compiler already knows everything about your AI: its variables, its types, its functions. It writes all of that out as text, and javac reads that text back, splits it up again, redoes the typing and rediscovers everything we already knew.
When I profiled compilation at the end of November, the verdict was clear: javac took about 80% of the time spent compiling an AI. Our own work (reading your code, analyzing it, writing the Java) was only the rest.
So the idea was simple to state: write the bytecode ourselves, straight from the AI's tree, without going through Java text or javac. Other JVM languages, like Kotlin or Groovy, do exactly that. And Java 25 now ships a standard API to build class files, the Class-File API, which even handles the tedious details for the programmer. No external library needed.
Let's take a small fighting AI: it takes the pistol, moves closer if the enemy is too far, and shoots twice.
setWeapon(WEAPON_PISTOL);
var enemy = getNearestEnemy();
integer distance = getCellDistance(getCell(), getCell(enemy));
if (distance > 7) {
moveToward(enemy);
}
for (integer i = 0; i < 2; i++) {
useWeapon(enemy);
}
Until now, the LeekScript compiler translated it into Java. Here is the heart of the generated text, as is:
public Object runIA(Session session) throws LeekRunException {
ops(EntityClass.setWeapon(AI_cmp.this, 37l), 15);
Object u_enemy = ops(FightClass.getNearestEnemy(AI_cmp.this), 26);
long u_distance = ops(Field_getCellDistance_ii(EntityClass.getCell(AI_cmp.this), Entity_getCell_x(u_enemy)), 26);
if (ops(u_distance > 7l, 2)) {
ops(Fight_moveToward_i(u_enemy), 500);
}
for (long u_i = ops(0l, 1);
ops(u_i < 2l, 1); ops(u_i++, 1)) {
ops(1);ops(Weapon_useWeapon_i(u_enemy), 3000);
}
return null;
}
You can recognize every line. WEAPON_PISTOL became its value, 37. Almost everything is wrapped in an ops(…) that adds its cost to your operation counter: 15 for setWeapon, 2 for the comparison, 1 for i++, 1 for each loop iteration... That is how the game knows when an AI goes over its limit. Your variables get a u_ prefix, and since distance and i are declared integer, they become real Java integers (long). Without that type, the Java would go through generic functions like more(…) or add(…), which handle any value but are slower. Finally, a few small helper methods (Fight_moveToward_i, Weapon_useWeapon_i...) are generated next to it to bridge to the fight engine.
javac then read this text back to produce bytecode. The JVM does not read Java: it reads a sequence of very simple instructions that work on a stack, a bit like a reverse Polish notation calculator. Here is the if once translated (the uppercase names are jump labels, added for readability):
aload_0 // the AI, for the upcoming call to ops
lload_3 // push distance onto the stack
ldc2_w 7 // push 7
lcmp // compare them: gives -1, 0 or 1
ifle FALSE // if distance <= 7, jump to FALSE
iconst_1 // otherwise, push "true"
goto NEXT
FALSE: iconst_0 // push "false"
NEXT: iconst_2 // the comparison costs 2 operations
invokevirtual ops // count them, and return the true / false
ifeq AFTER // if "false", skip the block
... // moveToward(enemy), as above
AFTER:
The for loop follows the same idea: a test at the top, the body, then i++ and a goto back to the test. The i++ alone takes a handful of instructions:
lload 5 // push i
dup2 // copy it (i++ returns the old value)
lconst_1 // push 1
ladd // compute i + 1
lstore 5 // store it into i
Each method becomes a list of these instructions, stored in a class file along with its constants and a few side tables (line numbers, for example, which are used to show an error at the right place in your code). The JVM loads this file, verifies it, interprets it, and compiles the parts that run a lot into machine code.
The new backend writes these instructions itself, straight from your AI, without going through Java text. And if we compare: for this AI, the runIA instructions written by the backend are exactly javac's, one by one, jumps included. The only differences in the file have no effect at runtime: the order of the methods, the internal numbering of constants, and the throws clauses, which the JVM ignores anyway. The file is even a bit lighter (2,322 bytes versus 2,683).
You may have noticed the little detour in the if: the comparison produces a "true" or "false", hands it to ops, then tests it again right away. javac does that because the Java wraps the condition in ops(…). We will come back to it at the end.
I could have written "bytecode that works". I chose to write the bytecode javac would have written, instruction by instruction, from the Java we used to give it. It is much more demanding, but it is what guarantees that nothing changes for you:
getUsedRAM() partly sees, stays close;And above all, it makes it possible to check the work by comparing both results. If the backend and javac must produce the same thing, the slightest difference is a bug, and we know exactly where to look.
The price is that you have to know javac by heart, quirks included. A few examples I had to reproduce:
switch on integers. javac picks between two instructions: an indexed table (fast, but large if the values are spread out) or a list of value / target pairs. It decides with a small space and time cost formula. I copied it as is.switch on strings. The JVM cannot switch on a string. javac turns it into two steps: a switch on the string's hashCode(), then an equals() to tell apart strings that share the same code, and finally a second switch on the position found. Fun detail: when several strings share the same hashCode, javac tests the last one first. Of course, we had to do the same.goto. At the end of a switch's last case, javac removes a jump that would just lead to the next instruction. One instruction less, to be imitated too.x << (2 + 3), javac computes 2 + 3 itself and writes 5 directly. My backend made the JVM do the addition. The result was the same, the bytecode was not.keys() returning an array, while the language's version returns any object), javac silently adds a small method linking the two. Without it, a call through the parent type would land on the wrong version.Replacing a compiler that has worked for years means touching every AI in the game at once. So before writing a single construct, I built the net.
The LeekScript test suite now has 22,923 tests. I added a differential mode to it: each program is compiled once by javac, once by the new backend, then both versions run with the same random seed. We compare the result, the number of operations, the RAM, the errors and the position of each error. The slightest difference fails the test.
The backend was built within that frame, construct by construct: expressions and calls first, then functions, classes and inheritance, anonymous functions and the variables they capture, the old LeekScript 1 syntax and its @ references, LeekScript 5 modules, editor tests, switch, ??=, big integers... As long as a construct was not covered, the program simply went through javac: so we could move forward in small steps, without ever breaking anything. In the end, the whole language is covered, and the whole suite passes in differential mode with 0 differences.
Tests are nice, but real AIs are more inventive. So I also compiled a local corpus of 1,071 AI files both ways, then the entry points of AIs from the top of the ranking, and finally replayed full fights with both compilers to compare how they played out:
These benches also caught things the tests did not see, like an error trace missing a line in one specific LeekScript 1 case. Fixed.
That left the real world: every AI of every player. For the first production run, on November 28, I chose caution. The worker (the program that runs the fights) compiled each AI twice: once with the new backend, once with javac. It then compared a fingerprint of each generated method. At the slightest difference, javac's version was used, and the difference was reported to me.
In other words, during this phase, no fight ever ran on doubtful bytecode: javac stayed in charge.
This mode did exactly what was expected of it. It reported a handful of differences on the first day, all fixed right away: the constant computation x << (2 + 3) mentioned above, a few cases of captured variables in LeekScript 1, and a for loop whose key was captured by a function, where the Java counted one more operation. Just one operation, but an operation all the same: that is exactly the kind of difference I wanted to see before it touched a fight. No difference since.
Meanwhile, coverage kept growing. Out of the 150 entry points of top-ranked AIs studied, 48 went fully through bytecode at the start, and 128 at the end. The other 22 do not compile at all, even with javac: the backend therefore covers every AI that compiles.
On November 29 around 1:50 pm (Paris time), the worker switched to bytecode-only mode: all AIs are now compiled without javac.
When you reproduce javac this closely, you end up reading the generated Java very carefully. And sometimes, you find a bug that has nothing to do with the new backend.
The functions intervalMin, intervalMax and their cousins come in two versions: one for integer intervals, one for real intervals. Used normally, all was fine. But used as a value (var f = intervalMin, then f([1.5..4.5])), both versions got the same internal name, and the last one declared won. Result: 0 instead of 1.5 on an interval with real bounds.
I stumbled on it while looking into why the backend choked on that case. It is fixed for everyone, whether the AI goes through javac or bytecode. If you used these functions as values on real intervals, they now return the right result.
| Measure | With javac | Direct bytecode | |---|---|---| | Local corpus, 618 AIs, warm JVM | 75 s | 18 s | | 128 top-ranked AIs | ~45 s | ~10 s | | Quantum, my AI | 2.9 s | 1.2 s |
The gain goes from ×2.4 for Quantum to ×4.5 for the top-ranked AIs. The remaining time is mostly our own analysis, plus writing the Java, which the compiler still does out of habit even though it is no longer used.
Code-wise, the backend is a bit more than 8,000 lines added to the public LeekScript repository, in the src/main/java/leekscript/compiler/bytecode/ folder and in a toBytecode method next to each construct of the language.
Not yet, and that is on purpose. Since the bytecode is the same as javac's, the JVM runs it the same way. On the first bench of 200 fights, execution went from 25.8 s to 25.7 s: measurement noise. The generated class files are a bit lighter (about 17% smaller on the local corpus), but the number of instructions barely moves (1%).
What changes for you is the time between saving an AI and the moment it is ready to fight. And for the server, that is computing time handed back to the fights themselves.
There is still a bit of cleanup:
if shown above is a small example: nothing forces us to produce a "true" only to test it again right away. A bigger one: the JVM refuses to compile into machine code a method of more than 8,000 bytes of bytecode, which then stays interpreted, much more slowly: that is the case for part of the big AIs that unroll their loops. Your operations will not move: they are counted by the LeekScript compiler, not by the JVM.This project changes nothing visible in your fights, and that was the whole point. If you notice anything odd when an AI compiles, a bug report on the forum is enough, I will take a close look.
Pilow
Impossible de charger les données du jeu.
Vérifiez votre connexion et réessayez.