Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
import com.google.common.collect.Maps;
import de.peeeq.wurstscript.intermediatelang.ILconst;
import de.peeeq.wurstscript.intermediatelang.ILconstAbstract;
import de.peeeq.wurstscript.intermediatelang.ILconstInt;
import de.peeeq.wurstscript.intermediatelang.ILconstReal;
import de.peeeq.wurstscript.types.WurstType;

import java.util.ArrayList;
Expand Down Expand Up @@ -59,6 +61,10 @@ public String print() {
}

public void set(int key, ILconst value) {
if (value instanceof ILconstInt i && type.equals("real")) {
// the engine converts an integer stored into a real array
value = new ILconstReal(i.getVal());
}
values.put(key, value);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,11 @@

import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class JassInterpreter implements AbstractInterpreter {

Expand All @@ -29,6 +32,10 @@ public class JassInterpreter implements AbstractInterpreter {
private boolean trace = false;
private final Map<String, ExecutableJassFunction> functionCache = new HashMap<>();
private final TimerMockHandler timerMockHandler = new TimerMockHandler();
/** Names of the real globals, which convert an integer stored into them. */
private final Set<String> realGlobals = new HashSet<>();
/** Names of the real locals and parameters of each function. */
private final Map<JassFunction, Set<String>> realLocals = new IdentityHashMap<>();

public void loadProgram(JassProg prog) {
this.prog = prog;
Expand All @@ -37,6 +44,9 @@ public void loadProgram(JassProg prog) {
List<JassVar> globals = prog.getGlobals();
// globals initialisieren
for (JassVar v : globals) {
if (!(v instanceof JassArrayVar) && v.getType().equals("real")) {
realGlobals.add(v.getName());
}
ILconst value = null;
if (v instanceof JassArrayVar) {
value = new JassArray(v.getType());
Expand Down Expand Up @@ -94,7 +104,7 @@ ILconst executeJassFunction(JassFunction func, ILconst... arguments) {
}
int i = 0;
for (JassSimpleVar v : func.getParams()) {
localVarMap.put(v.getName(), arguments[i]);
localVarMap.put(v.getName(), convertTo(v.getType(), arguments[i]));
i++;
}

Expand All @@ -104,7 +114,7 @@ ILconst executeJassFunction(JassFunction func, ILconst... arguments) {
if (trace) {
WLogger.trace(() -> "end function " + func.getName() + " returns " + e.getVal());
}
return e.getVal();
return convertTo(func.getReturnType(), e.getVal());
}

if (trace) {
Expand Down Expand Up @@ -134,6 +144,9 @@ public void case_JassStmtSetArray(JassStmtSetArray jassStmtSetArray) {
@Override
public void case_JassStmtSet(JassStmtSet jassStmtSet) {
ILconst right = executeExpr(localVarMap, jassStmtSet.getRight());
if (right instanceof ILconstInt && isRealVariable(localVarMap, jassStmtSet)) {
right = convertTo("real", right);
}
setVarValue(localVarMap, jassStmtSet.getLeft(), right);
}

Expand Down Expand Up @@ -387,6 +400,42 @@ public ILconst case_JassExprNull(JassExprNull e) {
}


/**
* The engine converts an integer to real where a real is declared: a variable it is stored into,
* a parameter it is passed to and a value a function returns.
*/
private static @Nullable ILconst convertTo(String type, @Nullable ILconst value) {
if (value instanceof ILconstInt i && type.equals("real")) {
return new ILconstReal(i.getVal());
}
return value;
}

private boolean isRealVariable(Map<String, ILconst> localVarMap, JassStmtSet set) {
String name = set.getLeft();
if (!isLocal(localVarMap, name)) {
return realGlobals.contains(name);
}
de.peeeq.wurstscript.jassAst.Element e = set.getParent();
while (!(e instanceof JassFunction)) {
e = e.getParent();
}
return realLocals.computeIfAbsent((JassFunction) e, f -> {
Set<String> names = new HashSet<>();
for (JassVar v : f.getLocals()) {
if (!(v instanceof JassArrayVar) && v.getType().equals("real")) {
names.add(v.getName());
}
}
for (JassSimpleVar v : f.getParams()) {
if (v.getType().equals("real")) {
names.add(v.getName());
}
}
return names;
}).contains(name);
}

private void setVarValue(Map<String, ILconst> localVarMap, String varName, ILconst s) {
if (isLocal(localVarMap, varName)) {
localVarMap.put(varName, s);
Expand Down Expand Up @@ -417,7 +466,7 @@ private ILconst getVarValue(Map<String, ILconst> localVarMap, String name) {
if (bjGlobal == null) {
throw new InterpreterException("Variable " + name + " not found.");
}
value = executeExpr(Collections.emptyMap(), bjGlobal.getVal());
value = convertTo(bjGlobal.getType(), executeExpr(Collections.emptyMap(), bjGlobal.getVal()));
globalVarMap.put(name, value);
}
}
Expand Down Expand Up @@ -480,7 +529,7 @@ public void runProgram() {
// a native mock only matters to a program that reads the global.
uninitializedBjGlobals.put(iVar.getName(), iVar);
} else {
globalVarMap.put(iVar.getName(), executeExpr(Collections.emptyMap(), iVar.getVal()));
globalVarMap.put(iVar.getName(), convertTo(iVar.getType(), executeExpr(Collections.emptyMap(), iVar.getVal())));
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -489,7 +489,7 @@ public static String buildStacktrace(ProgramState globalState, Throwable e) {


@SuppressWarnings("null")
private static ILconst adjustTypeOfConstant(@Nullable ILconst retVal, ImType expectedType) {
static ILconst adjustTypeOfConstant(@Nullable ILconst retVal, ImType expectedType) {
if (retVal instanceof ILconstInt && isTypeReal(expectedType)) {
ILconstInt retValI = (ILconstInt) retVal;
retVal = new ILconstReal(retValI.getVal());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import de.peeeq.wurstscript.intermediatelang.ILaddress;
import de.peeeq.wurstscript.intermediatelang.ILconst;
import de.peeeq.wurstscript.intermediatelang.ILconstBool;
import de.peeeq.wurstscript.intermediatelang.ILconstInt;
import de.peeeq.wurstscript.jassIm.*;
import de.peeeq.wurstscript.jassinterpreter.ExitwhenException;

Expand Down Expand Up @@ -67,12 +68,16 @@ public static void run(ImSet s, ProgramState globalState, LocalState localState)
if (left instanceof ImVarAccess va) {
// a variable needs no address: finding its state evaluates nothing
ImVar var = va.getVar();
ILconst right = s.getRight().evaluate(globalState, localState);
// Jass converts an integer stored into a real, as it does for a parameter or a return value
ILconst right = ILInterpreter.adjustTypeOfConstant(s.getRight().evaluate(globalState, localState), var.getType());
Comment on lines +71 to +72

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Coerce integer-to-real boundaries in emitted Lua

When targeting Lua, this conversion only runs in the IM interpreter; translation/lua/translation/StmtTranslation.java:237-238 still emits g = n unchanged for a real g. On the game's runtime, the added jassIntStoredIntoRealGlobalMultipliesAsReal case therefore leaves g as an integer and 65536 * 65536 wraps to 0 instead of producing the real value around 4.29e9; the stock-Lua test masks this because its numeric behavior differs from the game. Apply the coercion in Lua lowering at stores and the analogous real parameter/return boundaries.

AGENTS.md reference: AGENTS.md:L316-L322

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Real, and out of scope here: this PR covers the interpreters and the Jass optimiser rewrites. The Lua side is #1492, which makes the conversion explicit in the IM for Lua (stores, real parameters and returns); measured on the 3.0.0 client, the squared global goes from 0 to 65536 with it.

(var.isGlobal() ? globalState : localState).setVal(var, right);
return;
}
ILaddress v = left.evaluateLvalue(globalState, localState);
ILconst right = s.getRight().evaluate(globalState, localState);
if (right instanceof ILconstInt) {
right = ILInterpreter.adjustTypeOfConstant(right, left.attrTyp());
}
v.set(right);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -325,7 +325,14 @@ private void analyzeComponent(List<Node> scc, Map<Node, Knowledge> knowledge) {

// Constant folding is intentionally centralized in SimpleRewrites.
// This pass performs propagation only to keep fold semantics in one place.
if (right instanceof ImConst) {
if (TypesHelper.isRealType(var.getType()) && TypesHelper.isIntType(right.attrTyp())) {
// Jass converts an integer stored into a real, so the variable holds a real.
// Its integer source in place of a read would make `r / n` an integer division.
// A literal can be converted here; a copy of an integer variable cannot.
newValue = right instanceof ImIntVal intVal
? new Value(JassIm.ImRealVal(intVal.getValI() + "."))
: null;
} else if (right instanceof ImConst) {
newValue = Value.tryValue(right);
} else if (right instanceof ImVarAccess imVarAccess) {
ImVar varRight = imVarAccess.getVar();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -654,7 +654,10 @@ private void optimizeConsecutiveSet(ImSet imSet1, ImSet imSet2) {
if (rightOpCall2.getArguments().get(0) instanceof ImVarAccess) {
ImVarAccess imVarAccess2 = (ImVarAccess) rightOpCall2.getArguments().get(0);
if (imVarAccess2.getVar() == leftVar2 && !hasMergeLimitOfOperators(rightExpr1)) {
if (sideEffectAnalysis.cannotUseVar(rightOpCall2.getArguments().get(1), leftVar1)) {
// Jass converts an integer stored into a real: the integer in place of the
// variable would make `r / m` an integer division.
if (!(TypesHelper.isRealType(leftVar1.getType()) && TypesHelper.isIntType(rightExpr1.attrTyp()))
&& sideEffectAnalysis.cannotUseVar(rightOpCall2.getArguments().get(1), leftVar1)) {
rightExpr1.setParent(null);
imVarAccess2.replaceBy(rightExpr1);
imSet1.replaceBy(ImHelper.nullExpr());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import de.peeeq.wurstscript.jassIm.*;
import de.peeeq.wurstscript.translation.imtranslation.ImHelper;
import de.peeeq.wurstscript.translation.imtranslation.ImTranslator;
import de.peeeq.wurstscript.types.TypesHelper;
import de.peeeq.wurstscript.utils.Utils;
import de.peeeq.wurstscript.validation.NamePreservation;
import org.jetbrains.annotations.Nullable;
Expand Down Expand Up @@ -83,7 +84,7 @@ public int optimize(ImTranslator trans) {
continue;
}

ImExpr replacement = findReplacement(right, obs);
ImExpr replacement = findReplacement(right, obs, v.getType());
if (replacement != null) {
for (ImVarRead v3 : v.attrReads()) {
v3.replaceBy(replacement.copy());
Expand Down Expand Up @@ -137,10 +138,14 @@ public int optimize(ImTranslator trans) {
}

@Nullable
private ImExpr findReplacement(ImExpr right, ImVarWrite obs) {
private ImExpr findReplacement(ImExpr right, ImVarWrite obs, ImType varType) {
ImExpr replacement;
if (right instanceof ImIntVal val) {
replacement = (JassIm.ImIntVal(val.getValI()));
// Jass converts an integer stored into a real, so the global holds a real.
// The integer in place of a read would make `g / m` an integer division.
replacement = TypesHelper.isRealType(varType)
? JassIm.ImRealVal(val.getValI() + ".")
: JassIm.ImIntVal(val.getValI());
if (obs.getParent() != null)
obs.replaceBy(ImHelper.nullExpr());
} else if (right instanceof ImRealVal val) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,45 @@ public void jassModuloRejectsRealOperands() {
"endfunction"));
}

/** Jass converts an integer stored into a real variable, so the division that follows is real. */
@Test
public void jassIntStoredIntoRealLocalDividesAsReal() {
test().testLua(true).luaOnly(false).executeProg().compilationUnits(
compilationUnit("input.j",
"function jassDiv takes integer n, integer m returns real",
"\tlocal real r = n",
"\treturn r / m",
"endfunction"),
compilationUnit("test.wurst",
"package test",
"\tnative testSuccess()",
"\tinit",
"\t\tif jassDiv(7, 2) > 3.4",
"\t\t\ttestSuccess()",
"endpackage"));
}

/** The same conversion keeps a product of the stored value from wrapping at 32 bits. */
@Test
public void jassIntStoredIntoRealGlobalMultipliesAsReal() {
test().testLua(true).luaOnly(false).executeProg().compilationUnits(
compilationUnit("input.j",
"globals",
"\treal g",
"endglobals",
"function jassSquare takes integer n returns real",
"\tset g = n",
"\treturn g * g",
"endfunction"),
compilationUnit("test.wurst",
"package test",
"\tnative testSuccess()",
"\tinit",
"\t\tif jassSquare(65536) > 4000000000.",
"\t\t\ttestSuccess()",
"endpackage"));
}

@Test
public void test_init_order_jass_warning() {
testAssertErrorsLines(false, "Variable b may not have been initialized",
Expand Down
Loading
Loading