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 @@ -9,6 +9,8 @@
import de.peeeq.wurstscript.ast.WPackage;
import de.peeeq.wurstscript.intermediatelang.*;
import de.peeeq.wurstscript.jassIm.*;
import de.peeeq.wurstscript.jassinterpreter.ExitwhenException;
import de.peeeq.wurstscript.jassinterpreter.ReturnException;
import de.peeeq.wurstscript.translation.imtranslation.CallType;
import de.peeeq.wurstscript.translation.imtranslation.ImPrinter;
import de.peeeq.wurstscript.types.TypesHelper;
Expand Down Expand Up @@ -131,14 +133,29 @@ public static ILconst eval(ImRealVal e, ProgramState globalState, LocalState loc

public static ILconst eval(ImStatementExpr e, ProgramState globalState, LocalState localState) {
e.getStatements().runStatements(globalState, localState);
leaveByException(localState);
return e.getExpr().evaluate(globalState, localState);
}

public static ILaddress evaluateLvalue(ImStatementExpr e, ProgramState globalState, LocalState localState) {
e.getStatements().runStatements(globalState, localState);
leaveByException(localState);
return ((ImLExpr) e.getExpr()).evaluateLvalue(globalState, localState);
}

/**
* A return or exitwhen inside a statement expression cannot stop the expression around it by a flag, so
* it leaves by the exception which the call and the loop still catch.
*/
private static void leaveByException(LocalState localState) {
if (localState.hasReturned()) {
throw new ReturnException(localState.takeReturn());
}
if (localState.consumeExit()) {
throw ExitwhenException.instance();
}
}

public static ILconst eval(ImStringVal e, ProgramState globalState, LocalState localState) {
return ILconstString.fromText(e.getValS());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import de.peeeq.wurstscript.gui.WurstGui;
import de.peeeq.wurstscript.intermediatelang.*;
import de.peeeq.wurstscript.jassIm.*;
import de.peeeq.wurstscript.jassinterpreter.ExitwhenException;
import de.peeeq.wurstscript.jassinterpreter.ReturnException;
import de.peeeq.wurstscript.jassinterpreter.TestFailException;
import de.peeeq.wurstscript.jassinterpreter.TestSuccessException;
Expand Down Expand Up @@ -393,6 +394,13 @@ public static LocalState runFunc(ProgramState globalState, ImFunction f, @Nullab

try {
f.getBody().runStatements(globalState, localState);
if (localState.hasReturned()) {
retVal = adjustTypeOfConstant(localState.takeReturn(), f.getReturnType());
didReturn = true;
} else if (localState.consumeExit()) {
// an exitwhen outside of any loop fails as it did when it was thrown
throw ExitwhenException.instance();
}
} catch (ReturnException e) {
retVal = adjustTypeOfConstant(e.getVal(), f.getReturnType());
didReturn = true;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import de.peeeq.wurstscript.intermediatelang.ILconst;
import de.peeeq.wurstscript.jassIm.ImTypeArgument;
import de.peeeq.wurstscript.jassIm.ImVar;
import de.peeeq.wurstscript.jassIm.ImTypeVar;
import org.eclipse.jdt.annotation.Nullable;

Expand All @@ -13,6 +14,74 @@
public class LocalState extends State {

private @Nullable ILconst returnVal;
/**
* Set by a return statement: the statements around it stop running and the call ends. A Java exception
* did this before, and unwinding one through the interpreter's frames on every return was a large part
* of the cost of a call.
*/
private boolean returned;
private @Nullable ILconst returnedValue;
/** Set by an exitwhen whose condition holds: the statements around it stop, and the loop ends. */
private boolean exiting;

/**
* The local variables and their values, side by side. A call has a few locals, and looking them up by
* identity in an array is cheaper than allocating and filling a hash map for every call. A function with
* many locals goes over to the map of {@link State}.
*/
private static final int MAX_ARRAY_LOCALS = 16;
private static final ImVar[] NO_VARS = new ImVar[0];
private static final ILconst[] NO_VALUES = new ILconst[0];
private ImVar[] localVars = NO_VARS;
private ILconst[] localValues = NO_VALUES;
private int localCount;
private boolean localsInMap;

@Override
public void setVal(ImVar v, ILconst val) {
if (localsInMap) {
super.setVal(v, val);
return;
}
ImVar[] vars = localVars;
for (int i = 0; i < localCount; i++) {
if (vars[i] == v) {
localValues[i] = val;
return;
}
}
if (localCount == vars.length) {
if (localCount == MAX_ARRAY_LOCALS) {
for (int i = 0; i < localCount; i++) {
super.setVal(vars[i], localValues[i]);
}
localsInMap = true;
localVars = NO_VARS;
localValues = NO_VALUES;
super.setVal(v, val);
return;
}
localVars = vars = java.util.Arrays.copyOf(vars, Math.max(4, vars.length * 2));
localValues = java.util.Arrays.copyOf(localValues, vars.length);
}
vars[localCount] = v;
localValues[localCount] = val;
localCount++;
}

@Override
public @Nullable ILconst getVal(ImVar v) {
if (localsInMap) {
return super.getVal(v);
}
ImVar[] vars = localVars;
for (int i = 0; i < localCount; i++) {
if (vars[i] == v) {
return localValues[i];
}
}
return null;
}
/**
* The type arguments this invocation was called with, kept only when the program still
* contains generics, i.e. when running before generic elimination. Type class dispatch reads
Expand Down Expand Up @@ -55,6 +124,39 @@ public LocalState() {
// no eager allocations
}

public void returnWith(@Nullable ILconst value) {
returned = true;
returnedValue = value;
}

public boolean hasReturned() {
return returned;
}

/** The value of the return, which is consumed. */
public @Nullable ILconst takeReturn() {
ILconst value = returnedValue;
returned = false;
returnedValue = null;
return value;
}

public void exitLoop() {
exiting = true;
}

/** Whether an exitwhen ended the loop, which is consumed. */
public boolean consumeExit() {
boolean result = exiting;
exiting = false;
return result;
}

/** Whether the statements being run have to stop: after a return, or an exitwhen. */
public boolean isLeaving() {
return returned || exiting;
}

public LocalState(ILconst returnVal) {
this.returnVal = returnVal;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
import de.peeeq.wurstscript.intermediatelang.ILconstBool;
import de.peeeq.wurstscript.jassIm.*;
import de.peeeq.wurstscript.jassinterpreter.ExitwhenException;
import de.peeeq.wurstscript.jassinterpreter.ReturnException;

public class RunStatement {

Expand All @@ -20,7 +19,7 @@ public static void run(ImExpr e, ProgramState globalState, LocalState localState
public static void run(ImExitwhen s, ProgramState globalState, LocalState localState) {
ILconstBool c = (ILconstBool) s.getCondition().evaluate(globalState, localState);
if (c.getVal()) {
throw ExitwhenException.instance();
localState.exitLoop();
}
}

Expand All @@ -42,9 +41,14 @@ public static void run(ImLoop s, ProgramState globalState, LocalState localState
throw new InterpreterException(globalState, "Execution interrupted");
}
s.getBody().runStatements(globalState, localState);
if (localState.isLeaving()) {
// an exitwhen ends this loop; a return stays set and ends the call
localState.consumeExit();
break;
}
}
} catch (ExitwhenException e) {
// end of loop
// end of loop: an exitwhen inside a statement expression, see EvaluateExpr.leaveByException
}

}
Expand All @@ -55,11 +59,18 @@ public static void run(ImReturn s, ProgramState globalState, LocalState localSta
ImExpr e = (ImExpr) s.getReturnValue();
r = e.evaluate(globalState, localState);
}
throw new ReturnException(r);
localState.returnWith(r);
}

public static void run(ImSet s, ProgramState globalState, LocalState localState) {
ImLExpr left = s.getLeft();
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);
(var.isGlobal() ? globalState : localState).setVal(var, right);
return;
}
ILaddress v = left.evaluateLvalue(globalState, localState);
ILconst right = s.getRight().evaluate(globalState, localState);
v.set(right);
Expand All @@ -71,6 +82,9 @@ public static void run(ImStmts stmts, ProgramState globalState, LocalState local
CompilationCancellation.check();
globalState.setLastStatement(s);
s.runStatement(globalState, localState);
if (localState.isLeaving()) {
return;
}
}
}

Expand All @@ -84,6 +98,10 @@ public static void run(ImVarargLoop loop, ProgramState globalState, LocalState l
for (int i = 0; i < val.size(); i++) {
localState.setVal(loop.getLoopVars().get(0).getVar(), val.get(i));
loop.getBody().runStatements(globalState, localState);
if (localState.isLeaving()) {
// an exitwhen ends the enclosing loop, as a return ends the call
break;
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import org.wurstscript.projectconfig.WurstProjectConfigData;
import de.peeeq.wurstio.languageserver.requests.MapRequest;
import de.peeeq.wurstio.languageserver.requests.UserRequest;
import de.peeeq.wurstscript.intermediatelang.interpreter.LocalState;
import de.peeeq.wurstscript.intermediatelang.interpreter.RunStatement;
import de.peeeq.wurstscript.jassIm.JassIm;
import de.peeeq.wurstscript.utils.CompilationCancellation;
Expand Down Expand Up @@ -151,7 +152,8 @@ public void emptyInterpreterLoopChecksCancellation() {
AtomicInteger checks = new AtomicInteger();
expectThrows(CancellationException.class, () -> CompilationCancellation.run(
() -> checks.incrementAndGet() == 3,
() -> RunStatement.run(JassIm.ImLoop(Ast.NoExpr(), JassIm.ImStmts()), null, null)));
// a loop runs in the local state of its call, which records an exitwhen or a return
() -> RunStatement.run(JassIm.ImLoop(Ast.NoExpr(), JassIm.ImStmts()), null, new LocalState())));
assertEquals(checks.get(), 3);
CompilationCancellation.check();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,61 @@ public void methodDispatchPerReceiverClassAtOneCallSite() {
);
}

/**
* A return leaves the loops and ifs around it and the call, an exitwhen only its own loop, also from inside
* a vararg loop. The interpreter stops the statements around them by a flag, not by unwinding an exception.
*/
@Test
public void returnAndExitwhenLeaveTheRightStatements() {
test().executeProg(true).testLua(false).lines(
"package Test",
"native testSuccess()",
"native testFail(string msg)",
"@extern native I2S(int i) returns string",
"int calls = 0",
"function findInNested(int target) returns int",
" for i = 0 to 9",
" for j = 0 to 9",
" if i * 10 + j == target",
" return i * 100 + j",
" return -1",
"function innerExit() returns int",
" var count = 0",
" for i = 0 to 4",
" var j = 0",
" while true",
" if j == i",
" break",
" j++",
" count++",
" return count",
"int limit = 0",
"function firstAbove(vararg int xs) returns int",
" for x in xs",
" if x > limit",
" return x",
" return -1",
"function firstAboveFive() returns int",
" limit = 5",
" return firstAbove(1, 7, 9)",
"function firstAboveTen() returns int",
" limit = 10",
" return firstAbove(1, 2)",
"function earlyOut(int x)",
" if x > 0",
" return",
" calls++",
"init",
" earlyOut(1)",
" earlyOut(0)",
" let r = findInNested(37) + innerExit() * 1000 + firstAboveFive() * 100000 + calls * 10000000",
" if r == 307 + 10000 + 700000 + 10000000 and firstAboveTen() == -1",
" testSuccess()",
" else",
" testFail(\"got \" + I2S(r))"
);
}

@Test(expectedExceptions = {InterpreterException.class})
public void r2swBeyondTheModelledRange() {
test().executeProg(true).testLua(false).lines(
Expand Down
Loading