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 @@ -160,7 +160,13 @@ private void loadFile(File file) throws Error {
}

public void loadWurstFilesInDir(File dir) {
for (File f : dir.listFiles()) {
File[] fileList = dir.listFiles();
if (fileList == null) {
WLogger.warning("Could not list directory " + dir);
return;
}
Arrays.sort(fileList, Comparator.comparing(File::getName));
for (File f : fileList) {
if (f.isDirectory()) {
loadWurstFilesInDir(f);
} else if (Utils.isWurstFile(f)) {
Expand Down Expand Up @@ -265,6 +271,7 @@ public static void addDependenciesFromFolder(File projectFolder, Collection<File
File dependencyFolder = new File(new File(projectFolder, "_build"), "dependencies");
File[] depProjects = dependencyFolder.listFiles();
if (depProjects == null) return;
Arrays.sort(depProjects, Comparator.comparing(File::getName));

// keep behavior (FileUtils.sameFile), but avoid O(n*m) scanning
List<File> existing = new ArrayList<>(dependencies);
Expand Down Expand Up @@ -377,7 +384,13 @@ private void addLibDir(File libDir) throws Error {
if (!libDir.exists() || !libDir.isDirectory()) {
throw new Error("Library folder " + libDir + " does not exist.");
}
for (File f : libDir.listFiles()) {
File[] fileList = libDir.listFiles();
if (fileList == null) {
WLogger.warning("Could not list library folder " + libDir);
return;
}
Arrays.sort(fileList, Comparator.comparing(File::getName));
for (File f : fileList) {
if (f.isDirectory()) {
// recursively scan directory
addLibDir(f);
Expand Down Expand Up @@ -697,6 +710,8 @@ private void printDebugImProg(String debugFile) {

private WurstModel mergeCompilationUnits(List<CompilationUnit> compilationUnits) {
gui.sendProgress("Merging Files");
// Compare with '/' separators so the order does not depend on the platform's path separator.
compilationUnits.sort(Comparator.comparing(cu -> Objects.toString(cu.getCuInfo().getFile(), "").replace('\\', '/')));
WurstModel result = Ast.WurstModel();
for (CompilationUnit compilationUnit : compilationUnits) {
// remove from old parent
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,14 +78,20 @@ private List<CompilationUnit> getJassdocCUs(Path jassdoc, WurstGui gui) {
ArrayList<CompilationUnit> units = new ArrayList<>();
WurstCompilerJassImpl comp = new WurstCompilerJassImpl(projectPath, gui, null, RunArgs.defaults());

for (File f : jassdoc.toFile().listFiles()) {
if (f.getName().endsWith(".j") && ! f.getName().startsWith("builtin-types")) {
try (InputStreamReader reader = new FileReader(f)) {
CompilationUnit cu = comp.parse(f.getAbsolutePath(), reader);
cu.getCuInfo().setFile(getCanonicalPath(f));
units.add(cu);
} catch (IOException e) {
e.printStackTrace();
File[] jassdocFiles = jassdoc.toFile().listFiles();
if (jassdocFiles == null) {
WLogger.warning("Could not list jassdoc folder " + jassdoc);
} else {
Arrays.sort(jassdocFiles, Comparator.comparing(File::getName));
for (File f : jassdocFiles) {
if (f.getName().endsWith(".j") && ! f.getName().startsWith("builtin-types")) {
try (InputStreamReader reader = new FileReader(f)) {
CompilationUnit cu = comp.parse(f.getAbsolutePath(), reader);
cu.getCuInfo().setFile(getCanonicalPath(f));
units.add(cu);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Expand Down Expand Up @@ -178,6 +184,7 @@ private File[] getFiles(File dir) {
if (res == null) {
return new File[0];
}
Arrays.sort(res, Comparator.comparing(File::getName));
return res;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -446,6 +446,7 @@ private static LinkedList<File> getFilesOfDirectory(File dir, LinkedList<File> a
if (listFiles == null) {
return addTo;
}
Arrays.sort(listFiles, Comparator.comparing(File::getName));
for (File f : listFiles) {
if (f.isDirectory()) {
getFilesOfDirectory(f, addTo);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@
import de.peeeq.wurstscript.utils.Utils;
import org.eclipse.jdt.annotation.Nullable;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

public class AttrImportedPackage {
Expand Down Expand Up @@ -37,14 +40,19 @@ public static WurstModel getModel(Element elem) {

public static ImmutableMap<String, WPackage> getPackages(WurstModel wurstModel) {
Map<String, WPackage> result = Maps.newLinkedHashMap();
List<WPackage> allPackages = new ArrayList<>();
for (CompilationUnit cu : wurstModel) {
for (WPackage p : cu.getPackages()) {
WPackage old = result.put(p.getName(), p);
if (old != null) {
if (!p.getName().equals("Wurst")) {
p.addError("Package '" + p.getName() + "' is defined multiple times. "
+ "This is currently not supported. First definition: " + Utils.printPos(old.getSource()));
}
allPackages.add(p);
}
}
allPackages.sort(Comparator.comparing(WPackage::getName));
for (WPackage p : allPackages) {
WPackage old = result.put(p.getName(), p);
if (old != null) {
if (!p.getName().equals("Wurst")) {
p.addError("Package '" + p.getName() + "' is defined multiple times. "
+ "This is currently not supported. First definition: " + Utils.printPos(old.getSource()));
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ public boolean removeGarbage() {
totalFunctionsRemoved += functionsRemoved;

// also consider class functions
Set<ImFunction> allFunctions = new HashSet<>(prog.getFunctions());
Set<ImFunction> allFunctions = new LinkedHashSet<>(prog.getFunctions());
for (ImClass c : prog.getClasses()) {
int classFunctionsBefore = c.getFunctions().size();
changes |= c.getFunctions().retainAll(usedFuncs);
Expand All @@ -166,7 +166,7 @@ public boolean removeGarbage() {
changes |= c.getFields().retainAll(c.getFields().stream()
.filter(field -> readVars.contains(field)
|| readVars.contains(trans.canonical(field)))
.collect(Collectors.toSet()));
.collect(Collectors.toCollection(LinkedHashSet::new)));
int classFieldsAfter = c.getFields().size();
totalGlobalsRemoved += classFieldsBefore - classFieldsAfter;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ public JassProg translate() {
private <T extends JassImElementWithName> void makeNamesUnique(List<T> list) {
List<T> sorted = new ArrayList<>(list);
sorted.sort(Comparator.comparing(JassImElementWithName::getName)
.thenComparing(v -> v.getTrace().attrSource().getFile())
.thenComparing(v -> new java.io.File(v.getTrace().attrSource().getFile()).getName())
.thenComparingInt(v -> v.getTrace().attrSource().getLine())
.thenComparingInt(v -> v.getTrace().attrSource().getStartColumn()));

Expand Down Expand Up @@ -111,8 +111,12 @@ private static de.peeeq.wurstscript.ast.Element getTrace(@Nullable Element elem)
}

private void collectGlobalVars() {
// An initializer can name a global later in this list (bj_DEGTORAD reads bj_PI).
// getJassVarFor emits a variable only once it is known to be global, and caches that
// result: translating the initializer first would cache bj_PI as a non-global and the
// later declaration would never be added.
globalImVars.addAll(imProg.getGlobals());
for (ImVar v : imProg.getGlobals()) {
globalImVars.add(v);
getJassVarFor(v);
}
}
Expand All @@ -132,8 +136,7 @@ private void translateFunctionTransitive(ImFunction imFunc) {
start = true;
}
if (start) {
msg.append("\n - ").append(Utils.printElement(getTrace(f))).append(" ( ").append(f.attrTrace().attrSource().getFile()).append(" line" +
" ").append(f.attrTrace().attrSource().getLine()).append(")");
msg.append("\n - ").append(Utils.printElement(getTrace(f))).append(" ( ").append(f.attrTrace().attrSource().printShort()).append(")");
}
}
WPos src = getTrace(imFunc).attrSource();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ public static Set<ImFunction> calculateFunctionsOfProg(ImProg prog) {
for (int i = 0; i < classes.size(); i++) {
functionCount += classes.get(i).getFunctions().size();
}
Set<ImFunction> allFunctions = HashSet.newHashSet(functionCount);
Set<ImFunction> allFunctions = new LinkedHashSet<>(functionCount);
for (int i = 0; i < functions.size(); i++) {
allFunctions.add(functions.get(i));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -609,41 +609,94 @@ private void sortEverything() {
}


private <T extends Element> void sortList(List<T> list) {
List<T> classes = removeAll(list);
Comparator<T> comparator = Comparator.comparing(this::getQualifiedClassName);
classes.sort(comparator);
list.addAll(classes);
}
private static class ElementWithKey<T> implements Comparable<ElementWithKey<T>> {
final T element;
final String key;

public <T> List<T> removeAll(List<T> list) {
List<T> result = new ArrayList<>();
while (!list.isEmpty()) {
result.add(0, list.remove(list.size() - 1));
ElementWithKey(T element, String key) {
this.element = element;
this.key = key;
}
return result;
}

private String getQualifiedClassName(Element c) {
return getQualifiedClassName(c.attrTrace());
@Override
public int compareTo(ElementWithKey<T> o) {
return this.key.compareTo(o.key);
}
}

private final Map<de.peeeq.wurstscript.ast.Element, String> scopePrefixCache = new IdentityHashMap<>();

private String getQualifiedClassName(de.peeeq.wurstscript.ast.Element e) {
String result = "";
if (e instanceof NamedScope) {
NamedScope ns = (NamedScope) e;
result = ns.getName();
private <T extends Element> void sortList(List<T> list) {
if (list.size() <= 1) {
return;
}
de.peeeq.wurstscript.ast.Element parent = e.getParent();
if (parent == null) {
return result;
@SuppressWarnings("unchecked")
ElementWithKey<T>[] elements = new ElementWithKey[list.size()];
for (int i = 0; i < list.size(); i++) {
T elem = list.get(i);
elements[i] = new ElementWithKey<>(elem, getSortKey(elem));
}
Arrays.sort(elements);
list.clear();
for (ElementWithKey<T> e : elements) {
list.add(e.element);
}
}

private String getSortKey(Element c) {
StringBuilder sb = new StringBuilder();
de.peeeq.wurstscript.ast.Element trace = c.attrTrace();
String scope = getScopePrefix(trace);
if (!scope.isEmpty()) {
sb.append(scope).append("_");
}
if (c instanceof ImFunction) {
ImFunction f = (ImFunction) c;
sb.append("fn::").append(f.getName()).append("(");
for (int i = 0; i < f.getParameters().size(); i++) {
if (i > 0) sb.append(",");
sb.append(f.getParameters().get(i).getType());
}
sb.append(")->").append(f.getReturnType());
} else if (c instanceof ImVar) {
ImVar v = (ImVar) c;
sb.append("var::").append(v.getName()).append(":").append(v.getType());
} else if (c instanceof ImClass) {
ImClass cls = (ImClass) c;
sb.append("class::").append(cls.getName());
} else if (c instanceof ImMethod) {
ImMethod m = (ImMethod) c;
sb.append("method::").append(m.getName());
} else {
sb.append(c.getClass().getSimpleName());
}
parent = parent.attrNearestNamedScope();
if (parent == null) {
return result;
if (trace != null) {
de.peeeq.wurstscript.parser.WPos pos = trace.attrSource();
if (pos != null) {
sb.append("@L").append(pos.getLine()).append("C").append(pos.getStartColumn());
}
}
return sb.toString();
}

private String getScopePrefix(de.peeeq.wurstscript.ast.Element e) {
if (e == null) {
return "";
}
String cached = scopePrefixCache.get(e);
if (cached != null) {
return cached;
}
return getQualifiedClassName(parent) + "_" + result;
NamedScope ns = e instanceof NamedScope ? (NamedScope) e : e.attrNearestNamedScope();
if (ns == null) {
scopePrefixCache.put(e, "");
return "";
}
de.peeeq.wurstscript.ast.Element parent = ns.getParent();
String parentScope = parent != null ? getScopePrefix(parent) : "";
String result = parentScope.isEmpty() ? ns.getName() : parentScope + "_" + ns.getName();
scopePrefixCache.put(e, result);
return result;
}


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,11 @@

public class TypeId {

// sort classes by name to get deterministic order
// sort classes by package, name, and source coordinate to get deterministic order
private static final Comparator<ImClass> class_comparator =
Comparator.comparing(ImClass::getName)
.thenComparing(TypeId::packageName);
Comparator.comparing(TypeId::packageName)
.thenComparing(ImClass::getName)
.thenComparing(TypeId::sourceKey);

// sort class types by name to get deterministic order
private static final Comparator<ImClassType> classtype_comparator =
Expand All @@ -43,13 +44,29 @@ public static Map<ImClass, Integer> calculate(ImProg prog) {

private static String packageName(ImClass ic) {
Element c = ic.attrTrace();
if (c == null) {
return "global";
}
@Nullable PackageOrGlobal nearestPackage = c.attrNearestPackage();
if (nearestPackage instanceof WPackage) {
return ((WPackage) nearestPackage).getName();
}
return "global";
}

private static String sourceKey(ImClass ic) {
Element c = ic.attrTrace();
if (c != null) {
de.peeeq.wurstscript.parser.WPos pos = c.attrSource();
if (pos != null) {
String file = pos.getFile();
String simpleFile = file != null ? new java.io.File(file).getName() : "";
return simpleFile + ":" + pos.getLine() + ":" + pos.getStartColumn();
}
}
return "";
}

private static void assignIds(AtomicInteger count, Map<ImClass, Integer> result,
List<ImClass> classes) {
Multimap<ImClass, ImClass> subClasses = calculateSubclasses(classes);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package de.peeeq.wurstscript.translation.lua.translation;

import com.google.common.collect.HashMultimap;
import com.google.common.collect.LinkedHashMultimap;
import com.google.common.collect.Multimap;
import de.peeeq.wurstscript.jassIm.*;
import de.peeeq.wurstscript.translation.imtranslation.ImTranslator;
Expand All @@ -25,16 +25,16 @@ public class RemoveGarbage {

private static class Used {
private final ImTranslator translator;
private final Set<ImFunction> functions = new HashSet<>();
private final Set<ImMethod> methods = new HashSet<>();
private final Set<ImFunction> functions = new LinkedHashSet<>();
private final Set<ImMethod> methods = new LinkedHashSet<>();
// methods that will be added once the class is used:
private final Multimap<ImClass, ImMethod> waitingMethods = HashMultimap.create();
private final Set<ImClass> classes = new HashSet<>();
private final Multimap<ImClass, ImMethod> waitingMethods = LinkedHashMultimap.create();
private final Set<ImClass> classes = new LinkedHashSet<>();
/** Classes whose reachable runtime objects may dispatch virtual methods. */
private final Set<ImClass> dispatchClasses = new HashSet<>();
private final Set<ImClass> dispatchClasses = new LinkedHashSet<>();
/** Classes which reachable code actually allocates, excluding nominal type-only references. */
private final Set<ImClass> instantiatedClasses = new HashSet<>();
private final Set<ImVar> vars = new HashSet<>();
private final Set<ImClass> instantiatedClasses = new LinkedHashSet<>();
private final Set<ImVar> vars = new LinkedHashSet<>();
private final Set<ImSet> ignoredInitializers;

private Used(ImTranslator translator, Set<ImSet> ignoredInitializers) {
Expand Down Expand Up @@ -97,7 +97,7 @@ public boolean addClass(ImClass c, boolean dispatchReachable) {
}
if (newDispatchClass) {
Collection<ImMethod> imMethods = waitingMethods.get(c);
// This is a HashMultimap set view, not an indexed list. Keep the one iterator:
// This is a multimap set view, not an indexed list. Keep the one iterator:
// taking an array snapshot here allocates one entry for every waiting method.
Iterator<ImMethod> iterator = imMethods.iterator();
while (iterator.hasNext()) {
Expand Down
Loading
Loading