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 @@ -14,6 +14,7 @@
import de.peeeq.wurstscript.types.WurstTypeClass;
import de.peeeq.wurstscript.types.WurstTypeClassOrInterface;
import de.peeeq.wurstscript.types.WurstTypeInterface;
import de.peeeq.wurstscript.validation.WurstValidator;

import java.util.ArrayDeque;
import java.util.Collections;
Expand Down Expand Up @@ -105,15 +106,39 @@ private void translateInterfaceFuncDef(FuncDef f) {
ImMethod m = translator.getMethodFor(subM);

ImClass mClass = translator.getClassFor(subC);
if (f.attrHasEmptyBody() && !subClasses.contains(subM.attrNearestClassDef())) {
FuncDef interfaceDefault = defaultOf(subCT, f);
if (subM.attrNearestClassDef() == null) {
// the default of an interface extending this one, which the class takes for f
m = methodOfItsOwn(mClass, subCT, m, subM);
Comment thread
Frotty marked this conversation as resolved.
Resolved
} else if (f.attrHasEmptyBody() && !subClasses.contains(subM.attrNearestClassDef())) {
WurstTypeClass adopter = adopterOf(subCT, subM.attrNearestClassDef(), subClasses);
FuncDef interfaceDefault = WurstValidator.subInterfaceDefaultOf(adopter.getClassDef(), f);
if (interfaceDefault == null) {
interfaceDefault = defaultOf(adopter, f);
}
m = methodOfItsOwn(mClass, subCT, m, interfaceDefault == null ? subM : interfaceDefault);
}
OverrideUtils.addOverride(translator, f, mClass, m, subM, typeBinding);
}

}

/**
* The class which adopted the method {@code classType} inherits from {@code owner} as its implementation of this
* interface: the highest class from {@code classType} up to, not including, {@code owner} which implements the
* interface. Its interfaces decide whether a default beats the inherited method, and the classes below it inherit
* that choice, as the validator expects ({@code WurstValidator.findImplementationLink}). The default is that of a
* sub-interface, generic or not, else one of another interface ({@link #defaultOf}).
*/
private static WurstTypeClass adopterOf(WurstTypeClass classType, ClassDef owner, List<ClassDef> instances) {
WurstTypeClass adopter = classType;
for (WurstTypeClass t = classType.extendedClass(); t != null && t.getClassDef() != owner; t = t.extendedClass()) {
if (instances.contains(t.getClassDef())) {
adopter = t;
}
}
return adopter;
}

/**
* A method of {@code imClass} itself for the abstract method of this interface, which the class implements with a
* method it inherits from a class outside the interface ({@code C extends Base implements Omega}). The dispatch
Expand All @@ -122,7 +147,9 @@ private void translateInterfaceFuncDef(FuncDef f) {
* own with Base's implementation, which its subclasses inherit. The overrides below C are its sub-methods, as they
* are Base's ({@link ImTranslator#linkOverridesBelow}). Where another interface of C gives m a default, the
* default is the implementation: a default beats an inherited method (a call through that interface runs it on
* every backend), and Lua binds one implementation for C to both.
* every backend), and Lua binds one implementation for C to both. C also gets a method of its own where it takes m
* from the default of an interface extending this one, which belongs to that interface: that default is the
* implementation the validator chose ({@code WurstValidator.findImplementationLink}), not the first default found.
* <p>
* Where neither C nor the class of the implementation is generic, the method runs that implementation's function.
* Otherwise it gets a function of C which calls it ({@link #implementationOfItsOwn}).
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
import de.peeeq.wurstscript.attributes.names.DefLink;
import de.peeeq.wurstscript.attributes.names.FuncLink;
import de.peeeq.wurstscript.attributes.names.NameLink;
import de.peeeq.wurstscript.attributes.names.NameResolution;
import de.peeeq.wurstscript.attributes.names.OtherLink;
import de.peeeq.wurstscript.attributes.names.VarLink;
import de.peeeq.wurstscript.types.*;
Expand Down Expand Up @@ -394,6 +395,7 @@ private void check(Element e) {
checkName(astElementWithNameId);
if (e instanceof ClassDef classDef) {
checkAbstractMethods(classDef);
checkSubInterfaceDefaultConflicts(classDef);
visit(classDef);
}
if (e instanceof ClassOrModule classOrModule)
Expand Down Expand Up @@ -572,8 +574,33 @@ private boolean hasImplementationInHierarchy(ClassDef c, FuncLink abstractFunc)
return findImplementationLink(c, abstractFunc) != null;
}

/** The most specific non-abstract implementation of {@code abstractFunc} visible in {@code c}, if any. */
/**
* The non-abstract implementation of {@code abstractFunc} which {@code c} runs, if any. For a method of an interface
* which {@code c}'s superclass implements too, the superclass has settled it and {@code c} inherits that choice,
* unless {@code c} declares the method itself. Otherwise it is a method of {@code c} or of a superclass, else the
* default of a sub-interface ({@link #subInterfaceDefaults}). Where several sub-interface defaults compete, the
* validator reports it ({@link #checkSubInterfaceDefaultConflicts}) and this is the first of them.
*/
public static @Nullable FuncLink findImplementationLink(ClassDef c, FuncLink abstractFunc) {
FuncLink best = findClassImplementationLink(c, abstractFunc);
if (best != null && best.getDef().attrNearestClassDef() == c) {
return best;
}
FuncLink inherited = settledBySuperclass(c, abstractFunc);
if (inherited != null) {
return inherited;
}
if (best == null) {
List<FuncLink> defaults = subInterfaceDefaults(abstractFunc, interfaceMethods(c, abstractFunc.getName()));
if (!defaults.isEmpty()) {
best = defaults.get(0);
}
}
return best;
}

/** The nearest non-abstract implementation of {@code abstractFunc} in {@code c} or one of its superclasses. */
private static @Nullable FuncLink findClassImplementationLink(ClassDef c, FuncLink abstractFunc) {
FuncLink best = null;
int bestDistance = Integer.MAX_VALUE;
for (NameLink nameLink : c.attrNameLinks().get(abstractFunc.getName())) {
Expand Down Expand Up @@ -606,6 +633,171 @@ private boolean hasImplementationInHierarchy(ClassDef c, FuncLink abstractFunc)
return best;
}

/**
* The implementation {@code c}'s superclass runs for {@code abstractFunc}, a method of an interface which the
* superclass implements as well, or null when it does not implement the interface or has no implementation.
*/
private static @Nullable FuncLink settledBySuperclass(ClassDef c, FuncLink abstractFunc) {
WurstTypeClass superclass = c.attrTypC().extendedClass();
if (superclass == null
|| !(abstractFunc.getDef().attrNearestStructureDef() instanceof InterfaceDef declaring)
|| supertypeDistance(superclass, declaring) == Integer.MAX_VALUE) {
return null;
}
FunctionDefinition def = abstractFunc.getDef();
DefLink bound = NameResolution.matchDefLinkReceiver(
FuncLink.create(def, def.getParent().attrNearestScope()).withConfigDef(), superclass, def, false);
return bound instanceof FuncLink superLink ? findImplementationLink(superclass.getClassDef(), superLink) : null;
}

/**
* The default of a sub-interface which the class {@code c} takes for the interface method {@code f} in place of a
* method it inherits from a class outside the interface, or null; the first one where several compete, which the
* validator reports. Used by the translation ({@code InterfaceTranslator}), which lets such a default beat the
* inherited method.
*/
public static @Nullable FuncDef subInterfaceDefaultOf(ClassDef c, FuncDef f) {
DefLink bound = NameResolution.matchDefLinkReceiver(
FuncLink.create(f, f.getParent().attrNearestScope()).withConfigDef(), c.attrTypC(), f, false);
if (!(bound instanceof FuncLink abstractFunc)) {
return null;
}
List<FuncLink> defaults = subInterfaceDefaults(abstractFunc, interfaceMethods(c, f.getName()));
return defaults.isEmpty() ? null : (FuncDef) defaults.get(0).getDef();
}

/**
* The defaults which interfaces extending the interface of {@code abstractFunc} give it ({@code interface Shower
* extends Showable} with a body for Showable's {@code show}, which overrides Showable's default if it has one),
* among {@code links} and in their order. A default whose interface another candidate's interface extends is
* overridden by that one and left out. More than one left is a conflict the class must resolve by overriding the
* method, however far from the class each interface is. A default of an unrelated interface with the same
* signature is not one.
*/
private static List<FuncLink> subInterfaceDefaults(FuncLink abstractFunc, Iterable<? extends NameLink> links) {
if (!(abstractFunc.getDef().attrNearestStructureDef() instanceof InterfaceDef declaring)) {
return Collections.emptyList();
}
Map<InterfaceDef, FuncLink> candidates = new LinkedHashMap<>();
for (NameLink nameLink : links) {
if (!(nameLink instanceof FuncLink candidate)
|| !(candidate.getDef() instanceof FuncDef candidateDef)
|| candidateDef.attrIsAbstract()
|| !(candidateDef.attrNearestStructureDef() instanceof InterfaceDef owner)
|| owner == declaring
|| !WurstValidator.canOverride(candidate, abstractFunc, false)) {
continue;
}
if (supertypeDistance(owner.attrTypI(), declaring) != Integer.MAX_VALUE) {
candidates.putIfAbsent(owner, candidate);
}
}
List<FuncLink> mostSpecific = new ArrayList<>();
for (Map.Entry<InterfaceDef, FuncLink> candidate : candidates.entrySet()) {
boolean overridden = false;
for (InterfaceDef other : candidates.keySet()) {
if (other != candidate.getKey()
&& supertypeDistance(other.attrTypI(), candidate.getKey()) != Integer.MAX_VALUE) {
overridden = true;
break;
}
}
if (!overridden) {
mostSpecific.add(candidate.getValue());
}
}
return mostSpecific;
}

/**
* A class which takes a method of an interface from the defaults of several sub-interfaces, none of which extends
* another, has no single implementation of it and must override it. A method the class inherits from a superclass
* outside the interface does not settle it, because a default beats an inherited method
* ({@code InterfaceTranslator}); a superclass which implements the interface itself does, whatever it runs.
*/
private void checkSubInterfaceDefaultConflicts(ClassDef c) {
if (c.attrIsAbstract()) {
return;
}
WurstTypeClass classType = c.attrTypC();
Set<String> reported = new HashSet<>();
Set<InterfaceDef> visited = new HashSet<>();
for (WurstTypeInterface superInterface : classType.transitiveSuperInterfaces()) {
InterfaceDef interfaceDef = superInterface.getInterfaceDef();
if (!visited.add(interfaceDef)) {
continue;
}
for (FuncDef f : interfaceDef.getMethods()) {
if (f.attrIsStatic() || f.attrIsPrivate()) {
continue;
}
FuncLink declaration = FuncLink.create(f, f.getParent().attrNearestScope()).withConfigDef();
if (!(NameResolution.matchDefLinkReceiver(declaration, classType, f, false) instanceof FuncLink bound)) {
continue;
}
FuncLink implementation = findClassImplementationLink(c, bound);
if ((implementation != null && implementation.getDef().attrNearestClassDef() == c)
|| settledBySuperclass(c, bound) != null) {
continue;
}
// The interfaces' own methods, not the class's name links: an inherited class method hides the
// defaults there.
List<FuncLink> defaults = subInterfaceDefaults(bound, interfaceMethods(c, f.getName()));
if (defaults.size() < 2) {
continue;
}
List<String> interfaces = new ArrayList<>();
for (FuncLink d : defaults) {
interfaces.add(((InterfaceDef) d.getDef().attrNearestStructureDef()).getName());
}
if (reported.add(f.getName() + interfaces)) {
c.addError("Class " + c.getName() + " must override function " + f.getName()
+ ", because it inherits a default implementation of it from each of the interfaces "
+ String.join(", ", interfaces) + ".");
}
}
}
}

/** The methods named {@code name} of the interfaces of {@code c}, each bound to {@code c}. */
private static List<FuncLink> interfaceMethods(ClassDef c, String name) {
WurstTypeClass classType = c.attrTypC();
List<FuncLink> result = new ArrayList<>();
Set<InterfaceDef> visited = new HashSet<>();
for (WurstTypeInterface superInterface : classType.transitiveSuperInterfaces()) {
if (!visited.add(superInterface.getInterfaceDef())) {
continue;
}
for (FuncDef g : superInterface.getInterfaceDef().getMethods()) {
if (g.getName().equals(name) && !g.attrIsStatic() && !g.attrIsPrivate()
&& NameResolution.matchDefLinkReceiver(FuncLink.create(g, g.getParent().attrNearestScope())
.withConfigDef(), classType, g, false) instanceof FuncLink bound) {
result.add(bound);
}
}
}
return result;
}

/** The fewest supertype steps from {@code start} to {@code target}, or {@link Integer#MAX_VALUE}. */
private static int supertypeDistance(WurstTypeClassOrInterface start, ClassOrInterface target) {
Set<ClassOrInterface> visited = new HashSet<>();
List<WurstTypeClassOrInterface> level = List.of(start);
for (int distance = 0; !level.isEmpty(); distance++) {
List<WurstTypeClassOrInterface> next = new ArrayList<>();
for (WurstTypeClassOrInterface type : level) {
if (type.getDef() == target) {
return distance;
}
if (visited.add(type.getDef())) {
next.addAll(type.directSupertypes());
}
}
level = next;
}
return Integer.MAX_VALUE;
}

private static int distanceToOwner(ClassDef start, ClassDef owner) {
int distance = 0;
ClassDef current = start;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,68 @@ public void interfaceDefaultWithBoundIsIdenticalAcrossCompilations() throws IOEx
assertEquals(Files.toString(lua, Charsets.UTF_8), firstLua);
}

/**
* Sibling classes which take Showable's show from Shower's default, and one with a show of its own, emit the
* same Jass and Lua in two compilations, and their sub-methods of Showable's show come out alike whatever order
* the units are given in.
*/
@Test
public void subInterfaceDefaultDispatchIsIdenticalAcrossCompilations() throws IOException {
String name = "subInterfaceDefaultDispatch";
List<String> source = new ArrayList<>(List.of(
"package test",
"native testSuccess()",
"interface Showable",
" function show() returns int",
"interface Shower extends Showable",
" function show() returns int",
" return 7",
"class Own implements Shower",
" override function show() returns int",
" return 1",
"function viaShowable(Showable s) returns int",
" return s.show()"));
for (int i = 0; i < 5; i++) {
source.add("class C" + i + " implements Shower");
}
source.add("init");
source.add(" int sum = viaShowable(new Own())");
for (int i = 0; i < 5; i++) {
source.add(" sum += viaShowable(new C" + i + "())");
}
source.add(" if sum == 36");
source.add(" testSuccess()");
String[] lines = source.toArray(new String[0]);
testNamed(name).testLua(true).luaOnly(false).executeProg().lines(lines);
File jass = new File("test-output/DeterministicChecks_" + name + "_no_opts.j");
File lua = new File("test-output/lua/DeterministicChecks_" + name + ".lua");
String firstJass = Files.toString(jass, Charsets.UTF_8);
String firstLua = Files.toString(lua, Charsets.UTF_8);
testNamed(name).testLua(true).luaOnly(false).executeProg().lines(lines);
assertEquals(Files.toString(jass, Charsets.UTF_8), firstJass);
assertEquals(Files.toString(lua, Charsets.UTF_8), firstLua);

CU interfaces = compilationUnit("PkgShow.wurst",
"package PkgShow",
"public interface Showable",
" function show() returns int",
"public interface Shower extends Showable",
" function show() returns int",
" return 7");
List<CU> siblings = new ArrayList<>();
for (int i = 1; i <= 4; i++) {
siblings.add(compilationUnit("PkgC" + i + ".wurst",
"package PkgC" + i,
"import PkgShow",
"public class C" + i + " implements Shower"));
}
List<CU> forward = new ArrayList<>();
forward.add(interfaces);
forward.addAll(siblings);
List<CU> shuffled = List.of(siblings.get(2), siblings.get(0), interfaces, siblings.get(3), siblings.get(1));
assertSubMethodOrderIgnoresUnitOrder(forward, shuffled, 1);
}

@Test
public void simple() throws IOException {
ErrorHandler.outputTestSource = true;
Expand Down
Loading
Loading