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 @@ -13,11 +13,14 @@
import de.peeeq.wurstscript.parser.WPos;
import de.peeeq.wurstscript.utils.Utils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import static java.util.Collections.singletonList;

Expand All @@ -33,12 +36,20 @@ public class ClosureTranslator {
private ImFunction impl;
private ImClass c;
private ImVar capturedThisField;
// the outermost closure whose class is being created around this one, which captures the type variables
// of both, or null
private final ClosureTranslator outermost;
// the closures written inside this one, at any depth, in the order they were translated; only of an outermost one
private final List<ClosureTranslator> nested = new ArrayList<>();

public ClosureTranslator(ExprClosure e, ImTranslator tr, ImFunction f) {
super();
this.e = e;
this.tr = tr;
this.f = f;
ExprClosure enclosingClosure = e.getParent() == null ? null : e.getParent().attrNearestExprClosure();
ClosureTranslator enclosing = enclosingClosure == null ? null : tr.closuresInTranslation().get(enclosingClosure);
this.outermost = enclosing == null ? null : enclosing.outermost == null ? enclosing : enclosing.outermost;
}


Expand Down Expand Up @@ -189,6 +200,7 @@ private ImClass createClass() {
//JassIm.ImClass(e, "Closure", JassIm.ImTypeVars(), fields, methods, functions, superClasses);
tr.imProg().getClasses().add(c);

tr.closuresInTranslation().put(e, this);
impl = tr.getFuncFor(e);
impl.setName(makeFuncName(superMethod));
tr.getImProg().getFunctions().remove(impl);
Expand Down Expand Up @@ -227,8 +239,15 @@ private ImClass createClass() {
}
captureEnclosingThis();
transformTranslated(translated);
tr.closuresInTranslation().remove(e);

typeVars = rewriteTypeVars(c);
if (outermost != null) {
// Allocated in the enclosing closure without type arguments, which the outermost one gives it.
outermost.nested.add(this);
typeVars = Collections.emptyMap();
} else {
typeVars = rewriteTypeVars();
}
return c;
}

Expand Down Expand Up @@ -277,45 +296,73 @@ private String makeFuncName(FuncDef superClass) {
}

/**
* Replaces all captured type variables with new type variables.
* And adds these type variables to the closure-class c.
* Replaces all captured type variables with new type variables of the closure's class, for the closure and the
* closures written inside it, and returns the variables of the closure's own class.
* <p>
* A closure written in another one is created first, while the class of the enclosing closure has no type
* variables yet: the inner closure names that class without type arguments, as the type of the enclosing
* {@code this} it captures, and the enclosing closure allocates the inner one without them. So the closures
* written inside each other capture the same type variables, all those any of them uses, in the same order, and
* each class names another of them with its own variables.
*/
private Map<ImTypeVar, ImTypeVar> rewriteTypeVars(ImClass c) {
Map<ImTypeVar, ImTypeVar> result = new LinkedHashMap<>();
ImClassType thisType = JassIm.ImClassType(c, JassIm.ImTypeArguments());
TypeRewriter.rewriteTypes(c, t -> rewriteType(thisType, result, t));
return result;
private Map<ImTypeVar, ImTypeVar> rewriteTypeVars() {
List<ImClass> classes = new ArrayList<>();
classes.add(c);
for (ClosureTranslator n : nested) {
classes.add(n.c);
}
Set<ImTypeVar> captured = new LinkedHashSet<>();
for (ImClass k : classes) {
TypeRewriter.rewriteTypes(k, t -> {
collectTypeVars(t, captured);
return t;
});
}
List<Map<ImTypeVar, ImTypeVar>> newVarsByClass = new ArrayList<>();
for (ImClass k : classes) {
Map<ImTypeVar, ImTypeVar> newVars = new LinkedHashMap<>();
ImTypeArguments ownArguments = JassIm.ImTypeArguments();
for (ImTypeVar oldTypevar : captured) {
ImTypeVar newTypevar = JassIm.ImTypeVar(oldTypevar.getName() + "_captured");
// The same parameter as the one it captures: what the closure's body reads of the enclosing
// class, such as a static, belongs to the instantiation the closure was made for.
tr.recordSpecialisation(newTypevar, oldTypevar);
newVars.put(oldTypevar, newTypevar);
k.getTypeVariables().add(newTypevar);
ownArguments.add(JassIm.ImTypeArgument(JassIm.ImTypeVarRef(newTypevar), Collections.emptyMap()));
}
TypeRewriter.rewriteTypes(k, t -> rewriteType(classes, ownArguments, newVars, t));
newVarsByClass.add(newVars);
}
return newVarsByClass.get(0);
}

private ImType rewriteType(ImClassType thisType, Map<ImTypeVar, ImTypeVar> result, ImType type) {
private static void collectTypeVars(ImType type, Set<ImTypeVar> captured) {
type.match(new TypeRewriteMatcher() {
@Override
public ImType case_ImTypeVarRef(ImTypeVarRef t) {
captured.add(t.getTypeVariable());
return t;
}
});
}

private static ImType rewriteType(List<ImClass> classes, ImTypeArguments ownArguments,
Map<ImTypeVar, ImTypeVar> newVars, ImType type) {
return type.match(new TypeRewriteMatcher() {

@Override
public ImType case_ImClassType(ImClassType t) {
if (t.getClassDef() == c) {
return thisType;
if (classes.contains(t.getClassDef())) {
return JassIm.ImClassType(t.getClassDef(), ownArguments.copy());
}
return super.case_ImClassType(t);
}


@Override
public ImType case_ImTypeVarRef(ImTypeVarRef t) {
ImTypeVar oldTypevar = t.getTypeVariable();
ImTypeVar newTypevar = result.get(oldTypevar);
if (newTypevar == null) {
newTypevar = JassIm.ImTypeVar(oldTypevar.getName() + "_captured");
// The same parameter as the one it captures: what the closure's body reads of the enclosing
// class, such as a static, belongs to the instantiation the closure was made for.
tr.recordSpecialisation(newTypevar, oldTypevar);
result.put(oldTypevar, newTypevar);
c.getTypeVariables().add(newTypevar);
thisType.getTypeArguments().add(
JassIm.ImTypeArgument(
JassIm.ImTypeVarRef(newTypevar),
Collections.emptyMap()));
}
return JassIm.ImTypeVarRef(newTypevar);
return JassIm.ImTypeVarRef(newVars.get(t.getTypeVariable()));
}
});
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -859,16 +859,13 @@ private boolean inheritsFromSpecialisedClass(ImClass clazz, GenericTypes generic
* to the specialised class and the methods attached to it can never disagree. Answers only grow while the
* specialisation runs (a call is completed with type arguments, never stripped of the ones it depends on), so the
* first answer is the safe one.
* <p>
* A closure written inside another closure is left out ({@link #isInsideAnotherClosure}).
*/
private boolean classNeedsIdentity(ImClass clazz) {
Boolean known = classNeedsIdentityAnswers.get(clazz);
if (known != null) {
return known;
}
boolean answer = !clazz.getTypeVariables().isEmpty()
&& !(clazz.attrTrace() instanceof ExprClosure closure && isInsideAnotherClosure(closure))
&& classMembersNeedTypeArgument(clazz, Collections.newSetFromMap(new IdentityHashMap<>()),
Collections.newSetFromMap(new IdentityHashMap<>()));
classNeedsIdentityAnswers.put(clazz, answer);
Expand Down Expand Up @@ -910,20 +907,6 @@ private static boolean isClosureClass(ImClass classDef) {
return classDef.attrTrace() instanceof ExprClosure;
}

/**
* A closure written inside another one is left alone.
* <p>
* Its captured environment is reached through a receiver belonging to the enclosing closure,
* which by then has been specialised itself, and specialising the owner again with what is
* left over fails inside the rewrite. Supporting that is a further step; until it is taken,
* saying the bound could not be resolved - which is what happens without any of this - is
* better than an error about generics of the wrong size.
*/
private static boolean isInsideAnotherClosure(ExprClosure closure) {
de.peeeq.wurstscript.ast.Element parent = closure.getParent();
return parent != null && parent.attrNearestExprClosure() != null;
}

/**
* A field of a closure's class specialised from a construction has to be reached on the copy. The write that
* captures a closure's environment is the case that needs it: it names the field of the generic class, which
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3193,6 +3193,13 @@ public void visit(ImTypeVarRef ref) {

private final Map<ExprClosure, ImClass> classForClosure = Maps.newLinkedHashMap();

/** The closures whose class is being created, by expression: a closure written in one shares its type variables. */
private final Map<ExprClosure, ClosureTranslator> closuresInTranslation = new IdentityHashMap<>();

public Map<ExprClosure, ClosureTranslator> closuresInTranslation() {
return closuresInTranslation;
}

public ImClass getClassForClosure(ExprClosure s) {
Preconditions.checkNotNull(s);
return classForClosure.computeIfAbsent(s, s1 -> JassIm.ImClass(s1, "Closure", JassIm.ImTypeVars(), JassIm.ImVars(), JassIm.ImMethods(), JassIm.ImFunctions(), Lists.newArrayList()));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2651,6 +2651,164 @@ public void genericInstanceofOfAnObjectAnotherClosureConstructs() {
);
}

/**
* A closure written inside another closure checks against the instantiation of the class both are written in,
* which reaches the inner closure through the outer one's captured type parameter.
*/
@Test
public void genericInstanceofInAClosureInsideAnotherClosure() {
test().testLua(true).luaOnly(false).executeProg().lines(
"package Test",
"native testSuccess()",
"interface Marker",
"class Box<T:> implements Marker",
"interface Pred",
" function test(Marker m) returns bool",
"interface Mk",
" function mk() returns Pred",
"class G<T:>",
" function pred() returns Pred",
" Mk outer = () -> begin",
" Pred p = (Marker x) -> x instanceof Box<T>",
" return p",
" end",
" return outer.mk()",
"init",
" let pi = new G<int>().pred()",
" let ps = new G<string>().pred()",
" Marker bi = new Box<int>()",
" Marker bs = new Box<string>()",
" if pi.test(bi) and not pi.test(bs)",
" and ps.test(bs) and not ps.test(bi)",
" testSuccess()"
);
}

/** A closure inside another closure constructs with its owner's type parameter. */
@Test
public void genericConstructionInAClosureInsideAnotherClosure() {
test().testLua(true).luaOnly(false).executeProg().lines(
"package Test",
"native testSuccess()",
"class Box<T:>",
" T item",
"interface Make",
" function make(int i) returns int",
"interface Mk",
" function mk() returns Make",
"class G<T:>",
" function maker() returns Make",
" Mk outer = () -> begin",
" Make inner = (int i) -> begin",
" let b = new Box<T>()",
" destroy b",
" return i + 1",
" end",
" return inner",
" end",
" return outer.mk()",
"init",
" if new G<int>().maker().make(1) == 2",
" testSuccess()"
);
}

/** A closure inside another closure reads a field of type T of the object both captured. */
@Test
public void genericFieldReadInAClosureInsideAnotherClosure() {
test().testLua(true).luaOnly(false).executeProg().lines(
"package Test",
"native testSuccess()",
"interface Get<T:>",
" function get() returns T",
"interface MkGet<T:>",
" function mk() returns Get<T>",
"class G<T:>",
" T val",
" construct(T v)",
" val = v",
" function getter() returns Get<T>",
" MkGet<T> outer = () -> begin",
" Get<T> inner = () -> val",
" return inner",
" end",
" return outer.mk()",
"init",
" let gi = new G<int>(5)",
" let gs = new G<string>(\"a\")",
" if gi.getter().get() == 5 and gs.getter().get() == \"a\"",
" testSuccess()"
);
}

/** A closure inside another closure dispatches on its owner's type-class bound. */
@Test
public void boundDispatchInAClosureInsideAnotherClosure() {
test().testLua(true).luaOnly(false).executeProg().lines(
"package Test",
"native testSuccess()",
"interface Kc<T:>",
" function kmk(int n) returns T",
"implements Kc<int>",
" function kmk(int n) returns int",
" return n + 1",
"implements Kc<string>",
" function kmk(int n) returns string",
" return \"s\"",
"interface Get<T:>",
" function get() returns T",
"interface MkGet<T:>",
" function mk() returns Get<T>",
"class G<T: Kc>",
" function getter() returns Get<T>",
" MkGet<T> outer = () -> begin",
" Get<T> inner = () -> T.kmk(4)",
" return inner",
" end",
" return outer.mk()",
"init",
" if new G<int>().getter().get() == 5 and new G<string>().getter().get() == \"s\"",
" testSuccess()"
);
}

/** Three closures inside each other read the static of the instantiation of the class they are written in. */
@Test
public void genericStaticInAClosureTwoClosuresDeep() {
test().testLua(true).luaOnly(false).executeProg().lines(
"package Test",
"native testSuccess()",
"interface Fn",
" function get() returns int",
"interface MkFn",
" function mk() returns Fn",
"interface MkMkFn",
" function mk() returns MkFn",
"class G<T:>",
" static int cnt = 0",
" T val",
" function count() returns int",
" MkMkFn outer = () -> begin",
" MkFn middle = () -> begin",
" Fn inner = () -> begin",
" cnt += 1",
" return cnt",
" end",
" return inner",
" end",
" return middle",
" end",
" return outer.mk().mk().get()",
"init",
" let gi = new G<int>()",
" let gs = new G<string>()",
" gi.count()",
" gi.count()",
" if gs.count() == 1 and gi.count() == 3",
" testSuccess()"
);
}

/**
* An instantiation whose type argument has a type-class bound inside it is the same instantiation whether the
* check and the construction carry that binding or not: a binding is dispatch metadata, not part of the type.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -233,15 +233,13 @@ public void closureImplementingALuaKeywordName() {
}

/**
* A closure written inside another one is still rejected, and this pins that it is rejected in
* the same words as before rather than falling over inside the rewrite. The inner closure
* reaches its captured environment through a receiver belonging to the outer one, which has
* been specialised by then, so specialising the owner again with what is left over does not
* work. Should that be made to work, this test fails and becomes a success case.
* A closure written inside another one dispatches on the bound of the generic function both are written in:
* the closures share the type variables they capture, so the inner one reaches the outer one's captured
* environment with the instantiation the outer one was specialised for.
*/
@Test
public void nestedClosuresInsideBoundedGenericAreRejectedForLua() {
test().testLua(true).executeProg().expectError("could not be resolved for the Lua target").lines(
public void nestedClosuresInsideBoundedGenericDispatchOnTheBound() {
test().testLua(true).luaOnly(false).executeProg().lines(
"package test",
"native testSuccess()",
"interface ToIndex<T:>",
Expand Down
Loading