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.types.WurstType;
import de.peeeq.wurstscript.types.WurstTypeUnknown;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

public class AttrForEachStatement {
Expand All @@ -20,13 +22,20 @@ public static Optional<FuncLink> calcIterator(StmtForIn forEach) {
ImmutableCollection<FuncLink> iterator = iterationTarget.lookupMemberFuncs(itrType, "iterator", false);
// find the 'iterator' function without parameters:
// must exist, because this is after type check
Optional<FuncLink> iteratorFunc = Optional.empty();
List<FuncLink> members = new ArrayList<>();
List<FuncLink> extensions = new ArrayList<>();
for (FuncLink nl : iterator) {
if (nl.getParameterTypes().isEmpty()) {
iteratorFunc = Optional.of(nl);
break;
(AttrPossibleFunctionSignatures.isExtension(nl) ? extensions : members).add(nl);
}
}
// Member methods take precedence over extension functions, so receivers are only compared
// within one of the two. A class and its subclass can each get an 'iterator' from a module
// they use: the one closest to the loop's target hides the other, the order of the lookup
// must not decide.
List<FuncLink> candidates = AttrPossibleFunctionSignatures.keepMostSpecificReceivers(
members.isEmpty() ? extensions : members, FuncLink::getReceiverType, iterationTarget);
Optional<FuncLink> iteratorFunc = candidates.isEmpty() ? Optional.empty() : Optional.of(candidates.get(0));
// find the 'hasNext' function without parameters
if (!iteratorFunc.isPresent()) {
forEach.getIn().addError("For loop target " + itrType + " doesn't provide a iterator() function");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,23 @@ public static boolean isVisible(de.peeeq.wurstscript.attributes.names.FuncLink f
return v != Visibility.PRIVATE_OTHER && v != Visibility.PROTECTED_OTHER;
}

/**
* Whether a function with receiver {@code more} hides one with receiver {@code than}
* when both fit a call equally well.
*
* <p>That is the case for a strict subtype. The receivers of functions injected by
* {@code use Module} are module instantiations, which are unrelated to each other even
* when one class extends the other, so for those the class owning the instantiation decides.
*/
private static boolean isMoreSpecificReceiver(WurstType more, WurstType than, Element site) {
boolean moreSubThan = more.isSubtypeOf(than, site);
boolean thanSubMore = than.isSubtypeOf(more, site);
if (moreSubThan || thanSubMore) {
return moreSubThan && !thanSubMore;
}
return NameResolution.isOwnedBySubclassOf(more, than);
}

public static <T> java.util.List<T> keepMostSpecificReceivers(
java.util.List<T> candidates,
java.util.function.Function<T, de.peeeq.wurstscript.types.WurstType> recvOf,
Expand All @@ -122,10 +139,8 @@ public static <T> java.util.List<T> keepMostSpecificReceivers(
if (i == j) continue;
var rj = recvOf.apply(candidates.get(j));
if (rj == null) continue;
// If rj is a strict subtype of ri, drop ri
boolean rj_le_ri = rj.isSubtypeOf(ri, site);
boolean ri_le_rj = ri.isSubtypeOf(rj, site);
if (rj_le_ri && !ri_le_rj) {
// If rj is more specific than ri, drop ri
if (isMoreSpecificReceiver(rj, ri, site)) {
continue outer;
}
}
Expand Down Expand Up @@ -297,11 +312,8 @@ public static ImmutableCollection<FunctionSignature> calculate(ExprMemberMethod
WurstType rj = best.get(j).getSig().getReceiverType();
if (rj == null) continue;

boolean jSubI = rj.isSubtypeOf(ri, mm);
boolean iSubJ = ri.isSubtypeOf(rj, mm);

// j strictly more specific than i → drop i
if (jSubI && !iSubJ) {
// j more specific than i → drop i
if (isMoreSpecificReceiver(rj, ri, mm)) {
drop[i] = true;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -429,6 +429,25 @@ private static int inheritanceDistance(ClassDef start, ClassDef target) {
return -1;
}

/**
* Whether {@code type} is the module instantiation of a class which strictly extends the class
* owning the module instantiation {@code other}.
*
* <p>A function a class gets through {@code use Module} has that class's module instantiation as
* its receiver, and the instantiations in a class and in its superclass are unrelated types.
* Subtyping alone therefore cannot say which of two equal static functions hides the other.
* Both receivers have to be module instantiations: that is the only pair subtyping leaves
* unordered, and it keeps this from ever ranking an extension function against a member.
*/
public static boolean isOwnedBySubclassOf(WurstType type, WurstType other) {
if (!(type instanceof WurstTypeModuleInstanciation) || !(other instanceof WurstTypeModuleInstanciation)) {
return false;
}
ClassDef sub = owningClass(type);
ClassDef sup = owningClass(other);
return sub != null && sup != null && sub != sup && inheritanceDistance(sub, sup) > 0;
}

private static @Nullable ClassDef owningClass(WurstType type) {
if (type instanceof WurstTypeClass) {
return ((WurstTypeClass) type).getClassDef();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,12 @@

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static de.peeeq.wurstscript.utils.Utils.string;

Expand Down Expand Up @@ -1941,7 +1947,7 @@ public void moduleInOtherPackage() {
}

@Test
public void linkedListModule_perClassStatics_andTyping_ok() {
public void linkedListModule_perClassStatics_andTyping_ok() throws IOException {
testAssertOkLinesWithStdLib(true,
"package Test",
"import LinkedListModule",
Expand Down Expand Up @@ -1981,6 +1987,166 @@ public void linkedListModule_perClassStatics_andTyping_ok() {
" doSmth()",
" testSuccess()"
);
// Compiling is not enough: the loop over B has to call B's iterator, not the one B inherits.
Assert.assertEquals(
iteratorCallsInDoSmth(readJass("linkedListModule_perClassStatics_andTyping_ok", "no_opts"), "LinkedListModule"),
List.of("A", "B"));
}

/**
* B extends A and both use the module, so looking up the module's static {@code iterator} on B
* finds B's own and the one B inherits from A. A loop over B or a call on B has to take B's. The
* lookup used to leave that to the order of a hash set, so it depended on the identity hash codes
* of the AST nodes, which differ with every compilation. One compilation therefore passes most of
* the time even with the defect; compile the same program many times and check every result.
*/
@Test
public void moduleStaticsOfSubclass_resolveToOwnClass_everyCompilation() throws IOException {
String[] variants = {"no_opts", "opt", "inl", "inlopt", "stacktraceinlopt"};
Map<String, String> first = new HashMap<>();
for (int run = 0; run < 40; run++) {
testAssertOkLines(true,
"package Test",
"native testSuccess()",
"",
"module Registry",
" static thistype first = null",
" thistype next = null",
"",
" construct()",
" next = first",
" first = this",
"",
" static function iterator() returns Iter",
" return new Iter(first)",
"",
" static class Iter",
" Registry.thistype current",
"",
" construct(Registry.thistype start)",
" current = start",
"",
" function hasNext() returns boolean",
" return current != null",
"",
" function next() returns Registry.thistype",
" let res = current",
" current = current.next",
" return res",
"",
" function close()",
" destroy this",
"",
"class A",
" use Registry",
"",
"class B extends A",
" use Registry",
"",
"class C extends A",
"",
"class D extends C",
" use Registry",
"",
"function doSmth()",
" for a in A",
" skip",
" for b in B",
" skip",
" let itrB = B.iterator()",
" itrB.close()",
" let itrD = D.iterator()",
" itrD.close()",
"",
"init",
" doSmth()",
" testSuccess()"
);

Map<String, String> jass = new HashMap<>();
for (String variant : variants) {
jass.put(variant, readJass("moduleStaticsOfSubclass_resolveToOwnClass_everyCompilation", variant));
}
// for A, for B, B.iterator(), D.iterator()
Assert.assertEquals(iteratorCallsInDoSmth(jass.get("no_opts"), "Registry"), List.of("A", "B", "B", "D"),
"compilation " + run + " resolved the module's iterator to the wrong class:\n" + jass.get("no_opts"));

if (run == 0) {
first.putAll(jass);
} else {
for (String variant : variants) {
Assert.assertEquals(jass.get(variant), first.get(variant),
"compilation " + run + " emitted other " + variant + " Jass than the first");
}
}
}
}

/**
* A loop takes the {@code iterator()} member a class inherits, not an extension function
* declared on the subclass: picking among the iterators by receiver must not cross from
* member methods to extensions.
*/
@Test
public void forInIterator_prefersInheritedMemberOverExtension() {
testAssertOkLines(true,
"package Test",
"native testSuccess()",
"int memberCalls = 0",
"",
"class MemberItr",
" function hasNext() returns boolean",
" memberCalls++",
" return false",
" function next() returns int",
" return 0",
" function close()",
" destroy this",
"",
"class ExtensionItr",
" function hasNext() returns boolean",
" return false",
" function next() returns int",
" return 0",
" function close()",
" destroy this",
"",
"class A",
" function iterator() returns MemberItr",
" return new MemberItr()",
"",
"class B extends A",
"",
"function B.iterator() returns ExtensionItr",
" return new ExtensionItr()",
"",
"init",
" B b = new B()",
" for x in b",
" skip",
" if memberCalls == 1",
" testSuccess()"
);
}

private String readJass(String testName, String variant) throws IOException {
return Files.toString(new File(TEST_OUTPUT_PATH + "BugTests_" + testName + "_" + variant + ".j"), Charsets.UTF_8);
}

/**
* The classes {@code doSmth} takes a per-class {@code iterator} of, in call order. Only the
* script emitted without optimisations still has these calls to read.
*/
private static List<String> iteratorCallsInDoSmth(String jass, String module) {
Matcher doSmth = Pattern.compile("function doSmth takes nothing returns nothing(.*?)endfunction",
Pattern.DOTALL).matcher(jass);
Assert.assertTrue(doSmth.find(), jass);
Matcher calls = Pattern.compile("\\b(\\w)_" + module + "_iterator\\w*\\(\\)").matcher(doSmth.group(1));
List<String> classes = new ArrayList<>();
while (calls.find()) {
classes.add(calls.group(1));
}
return classes;
}

@Test
Expand Down
Loading