Compare commits

..

2 Commits

Author SHA1 Message Date
Fabian Holzwarth
c54e012426 feat: introduce task cancelling 2025-06-30 22:20:52 +02:00
Fabian Holzwarth
52f6ebcf3c feat: select multiple elements for variance 0 2025-06-30 16:43:39 +02:00
142 changed files with 2881 additions and 4363 deletions

View File

@@ -1,8 +1,5 @@
name: Build and Test with Maven name: Build and Test with Maven
on: on: [push]
push:
branches-ignore:
- master
jobs: jobs:
Build-and-test-with-Maven: Build-and-test-with-Maven:
@@ -18,11 +15,11 @@ jobs:
uses: actions/setup-java@v4 uses: actions/setup-java@v4
with: with:
distribution: 'temurin' distribution: 'temurin'
java-version: '25' java-version: '23'
cache: 'maven' cache: 'maven'
- name: Compile project - name: Compile project
run: | run: |
mvn compile mvn compile
- name: Run tests - name: Run tests
run: | run: |
mvn test mvn test

View File

@@ -1,45 +0,0 @@
on:
push:
branches:
- master
pull_request:
types: [opened, synchronize, reopened]
name: SonarQube Scan
jobs:
sonarqube:
name: SonarQube Trigger
runs-on: ubuntu-latest
steps:
- name: Checking out
uses: actions/checkout@v4
with:
# Disabling shallow clone is recommended for improving relevancy of reporting
fetch-depth: 0
- name: Install maven
run: |
apt update
apt install -y maven
- name: Install java
uses: actions/setup-java@v4
with:
distribution: 'temurin'
java-version: '25'
cache: 'maven'
- name: Compile project
run: |
mvn clean dependency:copy-dependencies verify
- name: SonarQube Scan
uses: SonarSource/sonarqube-scan-action@v5.3.0
env:
SONAR_HOST_URL: ${{ secrets.SONARQUBE_HOST }}
SONAR_TOKEN: ${{ secrets.SONARQUBE_TOKEN }}
with:
args: >
-Dsonar.projectKey=Java-TX
-Dsonar.sources=src/main/java
-Dsonar.tests=src/test/java
-Dsonar.junit.reportPaths=target/test-reports
-Dsonar.java.binaries=target/classes
-Dsonar.java.libraries=target/dependency/*.jar
-Dsonar.coverage.jacoco.xmlReportPaths=target/site/jacoco/jacoco.xml

View File

@@ -1,7 +0,0 @@
## Java-TX Compiler
[![Lines of Code](https://gitea.hb.dhbw-stuttgart.de/sonarqube/api/project_badges/measure?project=Java-TX&metric=ncloc&token=sqb_d4a372fca7a6b86441243728a6ea5f88183db5eb)](https://gitea.hb.dhbw-stuttgart.de/sonarqube/dashboard?id=Java-TX)
[![Coverage](https://gitea.hb.dhbw-stuttgart.de/sonarqube/api/project_badges/measure?project=Java-TX&metric=coverage&token=sqb_d4a372fca7a6b86441243728a6ea5f88183db5eb)](https://gitea.hb.dhbw-stuttgart.de/sonarqube/dashboard?id=Java-TX)
[![Quality Gate Status](https://gitea.hb.dhbw-stuttgart.de/sonarqube/api/project_badges/measure?project=Java-TX&metric=alert_status&token=sqb_d4a372fca7a6b86441243728a6ea5f88183db5eb)](https://gitea.hb.dhbw-stuttgart.de/sonarqube/dashboard?id=Java-TX)
Work in Progress Java-TX Compiler repository!

View File

@@ -10,7 +10,6 @@ mkdir $TDIR
cd $TDIR cd $TDIR
git clone $REPO . git clone $REPO .
git checkout feat/unify-server git checkout feat/unify-server
# git checkout 93e1a8787cd94c73f4538f6a348f58613893a584
# git checkout dad468368b86bdd5a3d3b2754b17617cee0a9107 # 1:55 # git checkout dad468368b86bdd5a3d3b2754b17617cee0a9107 # 1:55
# git checkout a0c11b60e8c9d7addcbe0d3a09c9ce2924e9d5c0 # 2:25 # git checkout a0c11b60e8c9d7addcbe0d3a09c9ce2924e9d5c0 # 2:25
# git checkout 4cddf73e6d6c9116d3e1705c4b27a8e7f18d80c3 # 2:27 # git checkout 4cddf73e6d6c9116d3e1705c4b27a8e7f18d80c3 # 2:27
@@ -20,14 +19,15 @@ git checkout feat/unify-server
# git checkout 1391206dfe59263cdb22f93371cfd1dd5465d97f # 1:29 # git checkout 1391206dfe59263cdb22f93371cfd1dd5465d97f # 1:29
date "+%Y.%m.%d %H:%M:%S" date "+%Y.%m.%d %H:%M:%S"
# sed -i -e 's/source>21/source>23/g' pom.xml
# sed -i -e 's/target>21/target>23/g' pom.xml # mvn clean compile -DskipTests package
## prefix each stderr line with " | "
# exec 2> >(trap "" INT TERM; sed 's/^/ | /' >&2)
# echo -e "\nMatrix test:\n |"
# time java -jar target/JavaTXcompiler-0.1-jar-with-dependencies.jar resources/bytecode/javFiles/Matrix.jav >/dev/null;
mvn clean compile -DskipTests package mvn clean compile test
time java -jar target/JavaTXcompiler-0.1-jar-with-dependencies.jar resources/bytecode/javFiles/Matrix.jav;
# mvn clean compile test
echo -e "\nCleanup... " echo -e "\nCleanup... "

62
pom.xml
View File

@@ -12,37 +12,37 @@ http://maven.apache.org/maven-v4_0_0.xsd">
<url>http://maven.apache.org</url> <url>http://maven.apache.org</url>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>org.junit.jupiter</groupId> <groupId>junit</groupId>
<artifactId>junit-jupiter-api</artifactId> <artifactId>junit</artifactId>
<version>5.13.2</version> <version>4.13.2</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<!-- https://mvnrepository.com/artifact/org.antlr/antlr4 --> <!-- https://mvnrepository.com/artifact/org.antlr/antlr4 -->
<dependency> <dependency>
<groupId>org.antlr</groupId> <groupId>org.antlr</groupId>
<artifactId>antlr4</artifactId> <artifactId>antlr4</artifactId>
<version>4.13.2</version> <version>4.11.1</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>commons-io</groupId> <groupId>commons-io</groupId>
<artifactId>commons-io</artifactId> <artifactId>commons-io</artifactId>
<version>2.19.0</version> <version>2.16.1</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>io.github.classgraph</groupId> <groupId>io.github.classgraph</groupId>
<artifactId>classgraph</artifactId> <artifactId>classgraph</artifactId>
<version>4.8.180</version> <version>4.8.172</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.google.guava</groupId> <groupId>com.google.guava</groupId>
<artifactId>guava</artifactId> <artifactId>guava</artifactId>
<version>33.4.8-jre</version> <version>33.2.0-jre</version>
</dependency> </dependency>
<!-- https://mvnrepository.com/artifact/org.ow2.asm/asm --> <!-- https://mvnrepository.com/artifact/org.ow2.asm/asm -->
<dependency> <dependency>
<groupId>org.ow2.asm</groupId> <groupId>org.ow2.asm</groupId>
<artifactId>asm</artifactId> <artifactId>asm</artifactId>
<version>9.8</version> <version>9.5</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.java-websocket</groupId> <groupId>org.java-websocket</groupId>
@@ -59,56 +59,28 @@ http://maven.apache.org/maven-v4_0_0.xsd">
<artifactId>jackson-databind</artifactId> <artifactId>jackson-databind</artifactId>
<version>2.17.2</version> <version>2.17.2</version>
</dependency> </dependency>
<dependency>
<groupId>com.diogonunes</groupId>
<artifactId>JColor</artifactId>
<version>5.5.1</version>
</dependency>
<dependency>
<groupId>org.jcommander</groupId>
<artifactId>jcommander</artifactId>
<version>3.0</version>
</dependency>
</dependencies> </dependencies>
<build> <build>
<plugins> <plugins>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.13</version>
<executions>
<execution>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>report</id>
<phase>prepare-package</phase>
<goals>
<goal>report</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId> <artifactId>maven-compiler-plugin</artifactId>
<version>3.14.0</version> <version>3.11.0</version>
<configuration> <configuration>
<source>25</source> <compilerArgs>--enable-preview</compilerArgs>
<target>25</target> <source>23</source>
<target>23</target>
</configuration> </configuration>
</plugin> </plugin>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId> <artifactId>maven-surefire-plugin</artifactId>
<version>3.5.3</version> <version>3.1.0</version>
<configuration> <configuration>
<redirectTestOutputToFile>true</redirectTestOutputToFile> <redirectTestOutputToFile>true</redirectTestOutputToFile>
<reportsDirectory>${project.build.directory}/test-reports</reportsDirectory> <reportsDirectory>${project.build.directory}/test-reports</reportsDirectory>
<argLine>${argLine} --enable-preview</argLine> <argLine>--enable-preview</argLine>
<trimStackTrace>false</trimStackTrace> <trimStackTrace>false</trimStackTrace>
<excludes> <excludes>
<exclude>**/JavaTXCompilerTest.java</exclude> <exclude>**/JavaTXCompilerTest.java</exclude>
@@ -120,7 +92,7 @@ http://maven.apache.org/maven-v4_0_0.xsd">
<plugin> <plugin>
<groupId>org.antlr</groupId> <groupId>org.antlr</groupId>
<artifactId>antlr4-maven-plugin</artifactId> <artifactId>antlr4-maven-plugin</artifactId>
<version>4.13.2</version> <version>4.11.1</version>
<executions> <executions>
<execution> <execution>
<id>antlr</id> <id>antlr</id>
@@ -133,7 +105,7 @@ http://maven.apache.org/maven-v4_0_0.xsd">
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId> <artifactId>maven-jar-plugin</artifactId>
<version>3.4.2</version> <version>3.3.0</version>
<configuration> <configuration>
<archive> <archive>
<manifest> <manifest>
@@ -181,4 +153,4 @@ http://maven.apache.org/maven-v4_0_0.xsd">
<url>file:///${project.basedir}/maven-repository/</url> <url>file:///${project.basedir}/maven-repository/</url>
</repository> </repository>
</distributionManagement> </distributionManagement>
</project> </project>

View File

@@ -6,7 +6,7 @@ import java.util.stream.Stream;
public class Bug325 { public class Bug325 {
public main() { public main() {
var list = new ArrayList<>(List.of(1,2,3,4,5)); List<Integer> list = new ArrayList<>(List.of(1,2,3,4,5));
var func = x -> x*2; var func = x -> x*2;
return list.stream().map(func).toList(); return list.stream().map(func).toList();
} }

View File

@@ -1,22 +0,0 @@
import java.lang.String;
public class Bug363 {
uncurry (f){
return x -> f.apply(x);
}
uncurry (f){
return (x, y) -> f.apply(x).apply(y);
}
uncurry (f){
return (x, y, z) -> f.apply(x).apply(y).apply(z);
}
public test(){
var f = x -> y -> z -> x + y + z;
var g = uncurry(f);
return g.apply("A", "B", "C"); // Outputs: 6
}
}

View File

@@ -1,8 +0,0 @@
import java.lang.String;
public class Bug364{
public main(){
var f = x -> y -> z -> x + y + z;
return f.apply("A").apply("B").apply("C");
}
}

View File

@@ -1,21 +0,0 @@
import java.lang.String;
import java.lang.Object;
public class Bug365{
swap(f){
return x -> y -> f.apply(y).apply(x);
}
swap(Fun1$$<String, Fun1$$<String, Fun1$$<String, Object>>> f){
return x -> y -> z -> f.apply(z).apply(y).apply(x);
}
public ex1() {
var func = x -> y -> z -> x + y + z;
return func.apply("A").apply("B").apply("C");
}
public ex2() {
var func = x -> y -> z -> x + y + z;
return swap(func).apply("A").apply("B").apply("C");
}
}

View File

@@ -1,12 +0,0 @@
import java.lang.Integer;
public class Bug366 {
public static lambda() {
return (a, b) -> a + b;
}
public static test() {
var l = lambda();
return l.apply(10, 20);
}
}

View File

@@ -1,10 +0,0 @@
import java.lang.Boolean;
public class Bug371 {
static m1(x, y) { return x || y; }
static m2(x, y) { return x && y; }
public static test() {
return m2(m1(true, false), true);
}
}

View File

@@ -1,17 +0,0 @@
import java.lang.Boolean;
import java.lang.Integer;
import java.lang.System;
import java.io.PrintStream;
import java.lang.Character;
public class Bug373 {
public static main() {
System.out.println(true);
System.out.println(false);
System.out.println(1);
System.out.println(1l);
System.out.println(1.0);
System.out.println(1.0f);
System.out.println('a');
}
}

View File

@@ -1,3 +0,0 @@
class Bug378Id {
id2 = x -> x;
}

View File

@@ -1,8 +0,0 @@
import Bug378Id;
import java.lang.Integer;
public class Bug378Main {
public static main(args) {
var hallo = (new Bug378Id<Integer>().id2).apply(1);
}
}

View File

@@ -1,24 +0,0 @@
import java.lang.Integer;
import java.lang.Double;
import java.lang.System;
import java.io.PrintStream;
public class Bug379 {
public Fun1$$<Double, Double> fact = (x) -> {
if (x == 1) {
return 1;
} else {
return x * (fact.apply(x-1));
}
};
public getFact(x) {
return fact.apply(x);
}
public static void main(x) {
var f = new Bug379();
var intRes = f.getFact(3);
System.out.println(intRes);
}
}

View File

@@ -1,12 +0,0 @@
sealed interface List<T> permits Cons, Empty {}
record Cons<T>(T a , List<T> l ) implements List <T> {}
record Empty<T>() implements List <T> {}
public class Bug380 {
public <T> List<T> append(l1, List<T> l2) {
return switch ( l1 ) {
case Cons(e, rest) -> new Cons<>(e, append(rest, l2)); //::Typ TPH A
case Empty() -> l2;//::TPH B
};
}
}

View File

@@ -1,13 +0,0 @@
import java.lang.Runnable;
import java.lang.String;
import java.lang.System;
import java.io.PrintStream;
import java.lang.Thread;
public class Bug382 {
public static main(a) {
var f = () -> System.out.println("Hallo Welt!");
new Thread(f).run();
}
}

View File

@@ -1,10 +0,0 @@
import java.lang.String;
import java.lang.System;
import java.io.PrintStream;
public class Bug383 {
public static main(a) {
var f = () -> System.out.println("Hello from Thread!");
f.apply();
}
}

View File

@@ -0,0 +1,16 @@
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.lang.String;
import java.util.stream.Stream;
import java.util.function.Function;
import java.util.function.Predicate;
import java.lang.Integer;
class BugXXX {
public main() {
List<Integer> i = new ArrayList<>(List.of(1,2,3,4,5,6,7,8,9,10));
Optional<Integer> tmp = i.stream().filter(x -> x == 5).map(x -> x*2).findFirst();
return tmp;
}
}

View File

@@ -1,14 +0,0 @@
import java.lang.Object;
import java.lang.System;
import java.lang.Iterable;
import java.io.PrintStream;
import java.util.List;
import java.lang.String;
class Main {
static main(args) {
for (var arg : args) {
System.out.println(arg);
}
}
}

View File

@@ -4,7 +4,7 @@ import java.lang.Integer;
import java.lang.Boolean; import java.lang.Boolean;
public class MatrixOP extends Vector<Vector<Integer>> { public class MatrixOP extends Vector<Vector<Integer>> {
MatrixOP () { MatrixOP () {
} }
@@ -36,8 +36,8 @@ public class MatrixOP extends Vector<Vector<Integer>> {
v2.addElement(erg); v2.addElement(erg);
j++; } j++; }
ret.addElement(v2); ret.addElement(v2);
i++; i++;
} }
return ret; return ret;
}; };
} }

View File

@@ -1,18 +1,17 @@
import java.lang.Integer; import java.lang.Integer;
import java.lang.Double;
import java.lang.Number;
import java.lang.String; import java.lang.String;
public record R(String n) {} public record R(Number n) {}
public class SwitchOverload { public class SwitchOverload {
f() { return 10; } public f(){}
g() { return 20; }
public m(r) { public m(r) {
return switch(r) { return switch(r) {
case R("test") -> f(); case R("test") -> f();
case R("foo") -> g();
case R r -> 0;
}; };
} }
} }

File diff suppressed because it is too large Load Diff

View File

@@ -39,10 +39,6 @@ public class FunNGenerator {
public final List<TargetType> inParams; public final List<TargetType> inParams;
public final List<TargetType> realParams; public final List<TargetType> realParams;
public GenericParameters(TargetFunNType funNType) {
this(funNType.funNParams(), funNType.returnArguments());
}
public GenericParameters(List<TargetType> params, int numReturns) { public GenericParameters(List<TargetType> params, int numReturns) {
this.realParams = params; this.realParams = params;
this.inParams = flattenTypeParams(params); this.inParams = flattenTypeParams(params);
@@ -75,7 +71,7 @@ public class FunNGenerator {
if (type == null) return VOID; if (type == null) return VOID;
var res = "L" + type.getInternalName(); var res = "L" + type.getInternalName();
if (type instanceof TargetSpecializedType a) { if (type instanceof TargetSpecializedType a) {
if (!a.params().isEmpty() && !(a.params().size() == 1 && a.params().getFirst() == null)) { if (a.params().size() > 0) {
res += "<"; res += "<";
for (var param : a.params()) { for (var param : a.params()) {
if (param instanceof TargetGenericType gp) { if (param instanceof TargetGenericType gp) {
@@ -98,7 +94,7 @@ public class FunNGenerator {
} }
private static String applySignature(TargetType a) { return a.toSignature(); } private static String applySignature(TargetType a) { return a.toSignature(); }
private static String applyNameDescriptor(TargetType a){ return a instanceof TargetGenericType ? "LTPH;" : String.format("%s", a.toDescriptor()); } private static String applyNameDescriptor(TargetType a){ return a instanceof TargetGenericType ? "LTPH;" : String.format("%s", applySignature(a)); }
public static String encodeType(TargetType type) { public static String encodeType(TargetType type) {
if (type == null) return VOID; if (type == null) return VOID;
@@ -115,17 +111,16 @@ public class FunNGenerator {
superFunNMethodSignature.append(String.format("T%s;", argumentGenericBase + currentParameter)); superFunNMethodSignature.append(String.format("T%s;", argumentGenericBase + currentParameter));
superFunNMethodDescriptor.append(objectSignature); superFunNMethodDescriptor.append(objectSignature);
} }
superFunNClassSignature.append(String.format("%s:%s>%s", returnGeneric, objectSignature, objectSignature));
if (numReturnTypes > 0) { if (numReturnTypes > 0) {
superFunNClassSignature.append(String.format("%s:%s>%s", returnGeneric, objectSignature, objectSignature));
superFunNMethodSignature.append(String.format(")T%s;", returnGeneric)); superFunNMethodSignature.append(String.format(")T%s;", returnGeneric));
superFunNMethodDescriptor.append(String.format(")%s", objectSignature)); superFunNMethodDescriptor.append(String.format(")%s", objectSignature));
} else { } else {
superFunNClassSignature = new StringBuilder(objectSignature);
superFunNMethodSignature.append(")V"); superFunNMethodSignature.append(")V");
superFunNMethodDescriptor.append(")V"); superFunNMethodDescriptor.append(")V");
} }
Codegen.logger.info(superFunNMethodSignature); System.out.println(superFunNMethodSignature);
ClassWriter classWriter = new ClassWriter(0); ClassWriter classWriter = new ClassWriter(0);
MethodVisitor methodVisitor; MethodVisitor methodVisitor;

View File

@@ -1,83 +1,65 @@
package de.dhbwstuttgart.core; package de.dhbwstuttgart.core;
import com.beust.jcommander.JCommander;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.ParameterException;
import de.dhbwstuttgart.server.SocketClient;
import de.dhbwstuttgart.util.Logger;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.*; import java.util.*;
class Args {
@Parameter(description = "Set destination directory", names = "-d")
File outputPath;
@Parameter(description = "Set class path", names = {"-cp", "-classpath"})
String classpath;
@Parameter(description = "[FILE]...")
List<File> input;
@Parameter(description = "Server mode", names = "--server-port")
Integer serverPort;
@Parameter(description = "Unify server url", names = "--unify-server")
String serverUrl;
@Parameter(description = "Write logs", names = "--write-logs")
boolean writeLogs = false;
@Parameter(names = "-v", description = "Verbosity level")
int verbosity = 0;
@Parameter(names = "--infer-together", description = "Runs the type inference on all input files together instead of sequentially")
boolean inferTogether = false;
@Parameter(names = "--help", help = true)
boolean help;
}
public class ConsoleInterface { public class ConsoleInterface {
public static Logger.LogLevel logLevel = Logger.LogLevel.ERROR; private static final String directory = System.getProperty("user.dir");
public static boolean writeLogFiles = false;
public static boolean inferTogether = false;
public static Optional<String> unifyServerUrl = Optional.empty();
public static void main(String[] argv) throws IOException, ClassNotFoundException { public static void main(String[] args) throws IOException, ClassNotFoundException {
var args = new Args(); List<File> input = new ArrayList<>();
var builder = JCommander.newBuilder().addObject(args).build(); List<File> classpath = new ArrayList<>();
builder.setProgramName("javatx"); String outputPath = null;
try { Iterator<String> it = Arrays.asList(args).iterator();
builder.parse(argv); Optional<Integer> serverPort = Optional.empty();
if (args.help) { Optional<String> unifyServer = Optional.empty();
builder.usage();
return; if (args.length == 0) {
} System.out.println("No input files given. Get help with --help");
} catch (ParameterException e) { System.exit(1);
System.err.println(e.getMessage()); } else if (args.length == 1 && args[0].equals("--help")) {
System.err.println(); System.out.println("Usage: javatx [OPTION]... [FILE]...\n" +
builder.usage(); "\t-cp\tSet Classpath\n" +
System.exit(1); "\t-d\tSet destination directory\n" +
"\t[--server-mode <port>]\n" +
"\t[--unify-server <url>]\n");
System.exit(1);
}
while (it.hasNext()) {
String arg = it.next();
if (arg.equals("-d")) {
outputPath = it.next();
} else if (arg.startsWith("-d")) {
outputPath = arg.substring(2);
} else if (arg.equals("-cp") || arg.equals("-classpath")) {
String[] cps = it.next().split(":");
for (String cp : cps) {
classpath.add(new File(cp));
} }
} else if (arg.equals("--server-mode")) {
serverPort = Optional.of(Integer.parseInt(it.next()));
} else if (arg.equals("--unify-server")) {
unifyServer = Optional.of(it.next());
} else {
input.add(new File(arg));
}
}
inferTogether = args.inferTogether; if (serverPort.isPresent()) {
unifyServerUrl = Optional.ofNullable(args.serverUrl); if (unifyServer.isPresent()) throw new RuntimeException("Cannot use unifyServer when in server mode!");
writeLogFiles = args.writeLogs;
switch (args.verbosity) { JavaTXServer server = new JavaTXServer(serverPort.get());
case 1 -> logLevel = Logger.LogLevel.WARNING; server.listen();
case 2 -> logLevel = Logger.LogLevel.INFO; }
case 3 -> logLevel = Logger.LogLevel.DEBUG; else {
default -> logLevel = Logger.LogLevel.ERROR; JavaTXCompiler compiler = new JavaTXCompiler(input, classpath, outputPath != null ? new File(outputPath) : null, unifyServer);
} //compiler.typeInference();
compiler.generateBytecode();
}
}
if (args.serverPort != null) {
if (unifyServerUrl.isPresent()) throw new RuntimeException("Cannot use unifyServer when in server mode!");
JavaTXServer server = new JavaTXServer(args.serverPort);
server.listen();
} else {
if (args.input == null) {
System.err.println("No input files given. Get help with --help");
System.exit(1);
}
List<File> classpath = args.classpath == null ? List.of() : Arrays.stream(args.classpath.split(File.pathSeparator)).map(File::new).toList();
JavaTXCompiler compiler = new JavaTXCompiler(args.input, classpath, args.outputPath, inferTogether);
compiler.generateBytecode();
SocketClient.closeIfOpen();
}
}
} }

View File

@@ -2,24 +2,17 @@
package de.dhbwstuttgart.core; package de.dhbwstuttgart.core;
import de.dhbwstuttgart.bytecode.Codegen; import de.dhbwstuttgart.bytecode.Codegen;
import de.dhbwstuttgart.bytecode.FunNGenerator;
import de.dhbwstuttgart.environment.CompilationEnvironment; import de.dhbwstuttgart.environment.CompilationEnvironment;
import de.dhbwstuttgart.environment.DirectoryClassLoader; import de.dhbwstuttgart.environment.DirectoryClassLoader;
import de.dhbwstuttgart.exceptions.DebugException; import de.dhbwstuttgart.exceptions.DebugException;
import de.dhbwstuttgart.languageServerInterface.model.LanguageServerTransferObject;
import de.dhbwstuttgart.parser.JavaTXParser; import de.dhbwstuttgart.parser.JavaTXParser;
import de.dhbwstuttgart.parser.NullToken; import de.dhbwstuttgart.parser.NullToken;
import de.dhbwstuttgart.parser.antlr.Java17Parser;
import de.dhbwstuttgart.parser.scope.GenericsRegistry; import de.dhbwstuttgart.parser.scope.GenericsRegistry;
import de.dhbwstuttgart.parser.SyntaxTreeGenerator.SyntaxTreeGenerator; import de.dhbwstuttgart.parser.SyntaxTreeGenerator.SyntaxTreeGenerator;
import de.dhbwstuttgart.parser.antlr.Java17Parser.SourceFileContext; import de.dhbwstuttgart.parser.antlr.Java17Parser.SourceFileContext;
import de.dhbwstuttgart.parser.scope.JavaClassName; import de.dhbwstuttgart.parser.scope.JavaClassName;
import de.dhbwstuttgart.parser.scope.JavaClassRegistry; import de.dhbwstuttgart.parser.scope.JavaClassRegistry;
import de.dhbwstuttgart.server.SocketClient; import de.dhbwstuttgart.server.SocketClient;
import de.dhbwstuttgart.server.SocketFuture;
import de.dhbwstuttgart.server.packet.SetAutoclosePacket;
import de.dhbwstuttgart.server.packet.UnifyRequestPacket;
import de.dhbwstuttgart.server.packet.UnifyResultPacket;
import de.dhbwstuttgart.syntaxtree.ClassOrInterface; import de.dhbwstuttgart.syntaxtree.ClassOrInterface;
import de.dhbwstuttgart.syntaxtree.GenericTypeVar; import de.dhbwstuttgart.syntaxtree.GenericTypeVar;
import de.dhbwstuttgart.syntaxtree.Method; import de.dhbwstuttgart.syntaxtree.Method;
@@ -60,11 +53,9 @@ import de.dhbwstuttgart.typeinference.unify.UnifyResultListenerImpl;
import de.dhbwstuttgart.typeinference.unify.UnifyResultModel; import de.dhbwstuttgart.typeinference.unify.UnifyResultModel;
import de.dhbwstuttgart.typeinference.unify.UnifyTaskModel; import de.dhbwstuttgart.typeinference.unify.UnifyTaskModel;
import de.dhbwstuttgart.util.Logger;
import java.io.*; import java.io.*;
import java.lang.reflect.Modifier; import java.lang.reflect.Modifier;
import java.nio.file.Path; import java.nio.file.Path;
import java.sql.Array;
import java.util.*; import java.util.*;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.function.Function; import java.util.function.Function;
@@ -76,81 +67,60 @@ public class JavaTXCompiler {
// do not use this in any code, that can be executed serverside! // do not use this in any code, that can be executed serverside!
public static PlaceholderRegistry defaultClientPlaceholderRegistry = new PlaceholderRegistry(); public static PlaceholderRegistry defaultClientPlaceholderRegistry = new PlaceholderRegistry();
public static Logger defaultLogger = new Logger();
private final boolean inferTogether;
// public static JavaTXCompiler INSTANCE; // public static JavaTXCompiler INSTANCE;
final CompilationEnvironment environment; final CompilationEnvironment environment;
Boolean resultmodel = true; Boolean resultmodel = true;
public final Map<File, SourceFile> sourceFiles = new HashMap<>(); public final Map<File, SourceFile> sourceFiles = new HashMap<>();
public final Set<JavaClassName> input = new HashSet<>();
Boolean log = false; //gibt an ob ein Log-File nach System.getProperty("user.dir")+""/logFiles/"" geschrieben werden soll?
public volatile UnifyTaskModel usedTasks = new UnifyTaskModel(); public volatile UnifyTaskModel usedTasks = new UnifyTaskModel();
public final DirectoryClassLoader classLoader; public final DirectoryClassLoader classLoader;
public final List<File> classPath; public final List<File> classPath;
private final File outputPath; private final File outputPath;
public final Map<String, FunNGenerator.GenericParameters> usedFunN = new HashMap<>(); private final Optional<String> unifyServer;
public final Set<Integer> usedFunNSuperTypes = new HashSet<>();
private final Map<JavaClassName, ClassOrInterface> loadedClasses = new HashMap<>();
public Map<String, byte[]> auxiliaries = new HashMap<>();
public DirectoryClassLoader getClassLoader() { public DirectoryClassLoader getClassLoader() {
return classLoader; return classLoader;
} }
public JavaTXCompiler(File sourceFile) throws IOException, ClassNotFoundException { public JavaTXCompiler(File sourceFile) throws IOException, ClassNotFoundException {
this(Collections.singletonList(sourceFile), List.of(), new File("."), ConsoleInterface.inferTogether); this(Arrays.asList(sourceFile), List.of(), new File("."), Optional.empty());
}
public JavaTXCompiler(File sourceFile, Boolean log) throws IOException, ClassNotFoundException {
this(sourceFile);
this.log = log;
} }
public JavaTXCompiler(List<File> sourceFiles) throws IOException, ClassNotFoundException { public JavaTXCompiler(List<File> sourceFiles) throws IOException, ClassNotFoundException {
this(sourceFiles, List.of(), new File("."), ConsoleInterface.inferTogether); this(sourceFiles, List.of(), new File("."), Optional.empty());
} }
public JavaTXCompiler(List<File> sources, List<File> contextPath, File outputPath, boolean inferTogether) throws IOException, ClassNotFoundException { public JavaTXCompiler(List<File> sources, List<File> contextPath, File outputPath) throws IOException, ClassNotFoundException {
this(sources, contextPath, outputPath, Optional.empty());
}
public JavaTXCompiler(List<File> sources, List<File> contextPath, File outputPath, Optional<String> unifyServer) throws IOException, ClassNotFoundException {
// ensure new default placeholder registry for tests // ensure new default placeholder registry for tests
defaultClientPlaceholderRegistry = new PlaceholderRegistry(); defaultClientPlaceholderRegistry = new PlaceholderRegistry();
this.inferTogether = inferTogether;
this.unifyServer = unifyServer;
var path = new ArrayList<>(contextPath); var path = new ArrayList<>(contextPath);
if (contextPath.isEmpty()) { if (contextPath.isEmpty()) {
// When no contextPaths are given, the working directory is the sources root // When no contextPaths are given, the working directory is the sources root
path.add(new File(System.getProperty("user.dir"))); path.add(new File(System.getProperty("user.dir")));
} }
if (outputPath != null) path.add(outputPath); if (outputPath != null) path.add(outputPath);
classLoader = new DirectoryClassLoader(path, ClassLoader.getSystemClassLoader().getParent()); classLoader = new DirectoryClassLoader(path, ClassLoader.getSystemClassLoader());
environment = new CompilationEnvironment(sources, classLoader); environment = new CompilationEnvironment(sources, classLoader);
classPath = path; classPath = path;
this.outputPath = outputPath; this.outputPath = outputPath;
// TODO This should maybe be moved elsewhere for (File s : sources) {
var treeList = new ArrayList<SourceFileContext>(sources.size()); parse(s);
for (var s : sources) {
var tree = (Java17Parser.SrcfileContext) JavaTXParser.parse(s);
treeList.add(tree);
// Find defined classes
var pkgName = tree.packageDeclaration() != null ? tree.packageDeclaration().qualifiedName().getText(): "";
for (var ctx : tree.classOrInterface()) {
if (ctx instanceof Java17Parser.NoclassorinterfaceContext) continue;
var classContext = (Java17Parser.ClassorinterfacedeclContext) ctx;
String name = null;
if (classContext.classDeclaration() != null)
name = classContext.classDeclaration().identifier().getText();
else if (classContext.recordDeclaration() != null)
name = classContext.recordDeclaration().identifier().getText();
else if (classContext.interfaceDeclaration() != null)
name = classContext.interfaceDeclaration().identifier().getText();
var className = pkgName + (!pkgName.isEmpty() ? "." : "") + name;
classRegistry.addName(className, 0);
input.add(classRegistry.getName(className));
}
}
for (var i = 0; i < sources.size(); i++) {
parse(treeList.get(i), sources.get(i));
} }
// INSTANCE = this; // INSTANCE = this;
} }
@@ -160,26 +130,21 @@ public class JavaTXCompiler {
} }
public ClassOrInterface getClass(JavaClassName name) { public ClassOrInterface getClass(JavaClassName name) {
if (loadedClasses.containsKey(name)) return loadedClasses.get(name); if (loadedClasses.containsKey(name)) return loadedClasses.get(name).cif();
for (var sf : sourceFiles.values()) { for (var sf : sourceFiles.values()) {
for (var clazz : sf.KlassenVektor) { for (var clazz : sf.KlassenVektor) {
if (clazz.getClassName().equals(name)) return clazz; if (clazz.getClassName().equals(name)) return clazz;
} }
} }
if (input.contains(name)) return null;
try { try {
var clazz = classLoader.loadClass(name.toString()); var clazz = classLoader.loadClass(name.toString());
ClassOrInterface cif = null; if (clazz != null)
if (clazz != null) { return ASTFactory.createClass(clazz);
cif = ASTFactory.createClass(clazz);
loadedClasses.put(name, cif);
}
return cif;
} catch (ClassNotFoundException ignored) {} } catch (ClassNotFoundException ignored) {}
return null; return null;
} }
public Set<ClassOrInterface> getAvailableClasses(File sourceFile) throws ClassNotFoundException, IOException { public ConstraintSet<Pair> getConstraints(File sourceFile) throws ClassNotFoundException, IOException {
Set<ClassOrInterface> allClasses = new HashSet<>();// environment.getAllAvailableClasses(); Set<ClassOrInterface> allClasses = new HashSet<>();// environment.getAllAvailableClasses();
ClassOrInterface objectClass = ASTFactory.createClass(Object.class); ClassOrInterface objectClass = ASTFactory.createClass(Object.class);
var recordClass = ASTFactory.createClass(Record.class); var recordClass = ASTFactory.createClass(Record.class);
@@ -205,7 +170,7 @@ public class JavaTXCompiler {
for (var clazz : sf.availableClasses) { for (var clazz : sf.availableClasses) {
if (loadedClasses.containsKey(clazz.getClassName())) { if (loadedClasses.containsKey(clazz.getClassName())) {
allClasses.removeIf(cl -> cl.getClassName().equals(clazz.getClassName())); allClasses.removeIf(cl -> cl.getClassName().equals(clazz.getClassName()));
var cif = loadedClasses.get(clazz.getClassName()); var cif = loadedClasses.get(clazz.getClassName()).cif();
allClasses.add(cif); allClasses.add(cif);
isCached = true; isCached = true;
} }
@@ -218,13 +183,7 @@ public class JavaTXCompiler {
allClasses.addAll(sf.KlassenVektor); allClasses.addAll(sf.KlassenVektor);
return allClasses; TYPE ty = new TYPE(sf, allClasses);
}
public ConstraintSet<Pair> getConstraints(File sourceFile) throws ClassNotFoundException, IOException {
var sf = sourceFiles.get(sourceFile);
var allClasses = getAvailableClasses(sourceFile);
TYPE ty = new TYPE(new HashSet<>(sf.availableClasses), allClasses);
var constraints = ty.getConstraints(); var constraints = ty.getConstraints();
return constraints; return constraints;
} }
@@ -244,9 +203,8 @@ public class JavaTXCompiler {
try { try {
var className = cl.getSuperClass().getName().toString(); var className = cl.getSuperClass().getName().toString();
superclass = ASTFactory.createClass(classLoader.loadClass(className)); superclass = ASTFactory.createClass(classLoader.loadClass(className));
} catch (ClassNotFoundException e) { } catch (ClassNotFoundException ignored) {}
throw new RuntimeException(e); // throw new ClassNotFoundException("");
}
} }
} }
@@ -275,18 +233,13 @@ public class JavaTXCompiler {
private Set<ClassOrInterface> getAvailableClasses(JavaClassName name) throws ClassNotFoundException { private Set<ClassOrInterface> getAvailableClasses(JavaClassName name) throws ClassNotFoundException {
Set<ClassOrInterface> allClasses = new HashSet<>(); Set<ClassOrInterface> allClasses = new HashSet<>();
if (input.contains(name)) { var clazz = loadJavaTXClass(name);
for (var sf : sourceFiles.values()) { if (clazz == null) {
for (var cif : sf.KlassenVektor) { ClassOrInterface importedClass = ASTFactory.createClass(classLoader.loadClass(name.toString()));
if (cif.getClassName().equals(name)) { allClasses.add(importedClass);
allClasses.add(cif); } else {
return allClasses; allClasses.add(clazz);
}
}
}
} }
ClassOrInterface importedClass = ASTFactory.createClass(classLoader.loadClass(name.toString()));
allClasses.add(importedClass);
return allClasses; return allClasses;
} }
@@ -364,193 +317,58 @@ public class JavaTXCompiler {
Set<Set<UnifyPair>> results = new HashSet<>(); Set<Set<UnifyPair>> results = new HashSet<>();
UnifyResultModel urm = null; UnifyResultModel urm = null;
// urm.addUnifyResultListener(resultListener); // urm.addUnifyResultListener(resultListener);
logFile = logFile == null ? new FileWriter("log_" + sourceFiles.keySet().iterator().next().getName()) : logFile; UnifyContext context = new UnifyContext(logFile, log, true, urm, usedTasks, defaultClientPlaceholderRegistry);
Logger logger = new Logger(logFile, "TypeInferenceAsync"); try {
UnifyContext context = new UnifyContext(logger, true, urm, usedTasks, defaultClientPlaceholderRegistry); logFile = logFile == null ? new FileWriter(new File("log_" + sourceFiles.keySet().iterator().next().getName())) : logFile;
IFiniteClosure finiteClosure = UnifyTypeFactory.generateFC(allClasses, logFile, getClassLoader(), this, context.placeholderRegistry());
System.out.println(finiteClosure);
urm = new UnifyResultModel(cons, finiteClosure);
urm.addUnifyResultListener(resultListener);
ConstraintSet<UnifyPair> unifyCons = UnifyTypeFactory.convert(this, cons, context.placeholderRegistry());
IFiniteClosure finiteClosure = UnifyTypeFactory.generateFC(allClasses, logger, getClassLoader(), this, context.placeholderRegistry()); Function<UnifyPair, UnifyPair> distributeInnerVars = x -> {
logger.info(finiteClosure.toString()); UnifyType lhs, rhs;
urm = new UnifyResultModel(cons, finiteClosure); if (((lhs = x.getLhsType()) instanceof PlaceholderType) && ((rhs = x.getRhsType()) instanceof PlaceholderType) && (((PlaceholderType) lhs).isInnerType() || ((PlaceholderType) rhs).isInnerType())) {
urm.addUnifyResultListener(resultListener); ((PlaceholderType) lhs).setInnerType(true);
ConstraintSet<UnifyPair> unifyCons = UnifyTypeFactory.convert(this, cons, context.placeholderRegistry()); ((PlaceholderType) rhs).setInnerType(true);
}
return x;
Function<UnifyPair, UnifyPair> distributeInnerVars = x -> { };
UnifyType lhs, rhs; logFile.write(unifyCons.toString());
if (((lhs = x.getLhsType()) instanceof PlaceholderType) && ((rhs = x.getRhsType()) instanceof PlaceholderType) && (((PlaceholderType) lhs).isInnerType() || ((PlaceholderType) rhs).isInnerType())) { unifyCons = unifyCons.map(distributeInnerVars);
((PlaceholderType) lhs).setInnerType(true); logFile.write(unifyCons.toString());
((PlaceholderType) rhs).setInnerType(true); // Set<Set<UnifyPair>> results = new HashSet<>(); Nach vorne gezogen
logFile.write("FC:\\" + finiteClosure.toString() + "\n");
for (SourceFile f : this.sourceFiles.values()) {
logFile.write(ASTTypePrinter.print(f));
} }
return x; // logFile.flush();
Set<PlaceholderType> varianceTPHold;
Set<PlaceholderType> varianceTPH = new HashSet<>();
varianceTPH = varianceInheritanceConstraintSet(unifyCons);
}; /*
logger.debug(unifyCons.toString()); * PL 2018-11-07 wird in varianceInheritanceConstraintSet erledigt do { //PL 2018-11-05 Huellenbildung Variance auf alle TPHs der Terme auf der jeweiligen //anderen Seite übertragen varianceTPHold = new HashSet<>(varianceTPH); varianceTPH = varianceInheritanceConstraintSet(unifyCons); unifyCons.map( y -> { if ((y.getLhsType() instanceof PlaceholderType) && (y.getRhsType() instanceof PlaceholderType)) { if (((PlaceholderType)y.getLhsType()).getVariance() != 0 &&
unifyCons = unifyCons.map(distributeInnerVars); * ((PlaceholderType)y.getRhsType()).getVariance() == 0) { ((PlaceholderType)y.getRhsType()).setVariance(((PlaceholderType)y.getLhsType( )).getVariance()); } if (((PlaceholderType)y.getLhsType()).getVariance() == 0 && ((PlaceholderType)y.getRhsType()).getVariance() != 0) { ((PlaceholderType)y.getLhsType()).setVariance(((PlaceholderType)y.getRhsType( )).getVariance()); } } return y; } ); } while (!varianceTPHold.equals(varianceTPH));
logger.debug(unifyCons.toString()); */
// Set<Set<UnifyPair>> results = new HashSet<>(); Nach vorne gezogen
logger.debug("FC:\\" + finiteClosure.toString() + "\n"); // Set<Set<UnifyPair>> result = unify.unifySequential(xConsSet, finiteClosure,
for (SourceFile f : this.sourceFiles.values()) { // logFile, log);
logger.debug(ASTTypePrinter.print(f)); // Set<Set<UnifyPair>> result = unify.unify(xConsSet, finiteClosure);
List<Set<Constraint<UnifyPair>>> oderConstraints = unifyCons.getOderConstraints()/*
* .stream().map(x -> { Set<Set<UnifyPair>> ret = new HashSet<>(); for (Constraint<UnifyPair> y : x) { ret.add(new HashSet<>(y)); } return ret; }).collect(Collectors. toCollection(ArrayList::new))
*/;
TypeUnify.unifyAsync(unifyCons.getUndConstraints(), oderConstraints, finiteClosure, context);
} catch (IOException e) {
System.err.println("kein LogFile");
} }
// logFile.flush();
Set<PlaceholderType> varianceTPHold;
Set<PlaceholderType> varianceTPH = new HashSet<>();
varianceTPH = varianceInheritanceConstraintSet(unifyCons);
/*
* PL 2018-11-07 wird in varianceInheritanceConstraintSet erledigt do { //PL 2018-11-05 Huellenbildung Variance auf alle TPHs der Terme auf der jeweiligen //anderen Seite übertragen varianceTPHold = new HashSet<>(varianceTPH); varianceTPH = varianceInheritanceConstraintSet(unifyCons); unifyCons.map( y -> { if ((y.getLhsType() instanceof PlaceholderType) && (y.getRhsType() instanceof PlaceholderType)) { if (((PlaceholderType)y.getLhsType()).getVariance() != 0 &&
* ((PlaceholderType)y.getRhsType()).getVariance() == 0) { ((PlaceholderType)y.getRhsType()).setVariance(((PlaceholderType)y.getLhsType( )).getVariance()); } if (((PlaceholderType)y.getLhsType()).getVariance() == 0 && ((PlaceholderType)y.getRhsType()).getVariance() != 0) { ((PlaceholderType)y.getLhsType()).setVariance(((PlaceholderType)y.getRhsType( )).getVariance()); } } return y; } ); } while (!varianceTPHold.equals(varianceTPH));
*/
// Set<Set<UnifyPair>> result = unify.unifySequential(xConsSet, finiteClosure,
// logFile, log);
// Set<Set<UnifyPair>> result = unify.unify(xConsSet, finiteClosure);
List<Set<Constraint<UnifyPair>>> oderConstraints = unifyCons.getOderConstraints()/*
* .stream().map(x -> { Set<Set<UnifyPair>> ret = new HashSet<>(); for (Constraint<UnifyPair> y : x) { ret.add(new HashSet<>(y)); } return ret; }).collect(Collectors. toCollection(ArrayList::new))
*/;
TypeUnify.unifyAsync(unifyCons.getUndConstraints(), oderConstraints, finiteClosure, context);
return urm; return urm;
} }
public List<ResultSet> typeInference(File file) throws ClassNotFoundException, IOException { public List<ResultSet> typeInference(File file) throws ClassNotFoundException, IOException {
return typeInference(List.of(file));
}
public List<ResultSet> typeInference(List<File> files) throws ClassNotFoundException, IOException {
Set<ClassOrInterface> allClasses = new HashSet<>();
var ressf = new ArrayList<SourceFile>();
var definedClasses = new HashSet<ClassOrInterface>();
for (var file : files) {
var sf = sourceFiles.get(file);
definedClasses.addAll(sf.KlassenVektor);
ressf.add(sf);
allClasses.addAll(getAvailableClasses(file));
allClasses.addAll(sf.availableClasses);
}
TYPE ty = new TYPE(definedClasses, allClasses);
var cons = ty.getConstraints();
Set<Set<UnifyPair>> results = new HashSet<>();
PlaceholderRegistry placeholderRegistry = new PlaceholderRegistry();
var logFolder = new File(System.getProperty("user.dir") + "/logFiles/");
if (ConsoleInterface.writeLogFiles && !logFolder.mkdirs()) throw new RuntimeException("Could not create directory for log files: " + logFolder);
Writer logFile = ConsoleInterface.writeLogFiles ? new FileWriter(new File(logFolder, "log_" + sourceFiles.keySet().iterator().next().getName())) : new OutputStreamWriter(new NullOutputStream());
Logger logger = new Logger(logFile, "TypeInference");
FiniteClosure finiteClosure = UnifyTypeFactory.generateFC(allClasses.stream().toList(), logger, classLoader, this, placeholderRegistry);
logger.info(finiteClosure.toString());
ConstraintSet<UnifyPair> unifyCons = UnifyTypeFactory.convert(this, cons, placeholderRegistry);
logger.info("xxx1");
Function<UnifyPair, UnifyPair> distributeInnerVars = x -> {
UnifyType lhs, rhs;
if (((lhs = x.getLhsType()) instanceof PlaceholderType) && ((rhs = x.getRhsType()) instanceof PlaceholderType) && (((PlaceholderType) lhs).isInnerType() || ((PlaceholderType) rhs).isInnerType())) {
((PlaceholderType) lhs).setInnerType(true);
((PlaceholderType) rhs).setInnerType(true);
}
return x;
};
logger.debug("Unify:" + unifyCons.toString());
logger.info("Unify:" + unifyCons.toString());
unifyCons = unifyCons.map(distributeInnerVars);
logger.debug("\nUnify_distributeInnerVars: " + unifyCons.toString());
// Set<Set<UnifyPair>> results = new HashSet<>(); Nach vorne gezogen
logger.debug("FC:\\" + finiteClosure.toString() + "\n");
for (var sf : ressf) logger.info(ASTTypePrinter.print(sf));
// logFile.flush();
List<UnifyPair> andConstraintsSorted = unifyCons.getUndConstraints().stream()
.sorted(Comparator.comparing(UnifyPair::getPairOp).thenComparing(UnifyPair::getLhsType, Comparator.comparing(UnifyType::getName)))
.collect(Collectors.toList());
logger.info(andConstraintsSorted);
Set<PlaceholderType> varianceTPHold;
Set<PlaceholderType> varianceTPH = new HashSet<>();
varianceTPH = varianceInheritanceConstraintSet(unifyCons);
/*
* PL 2018-11-07 wird in varianceInheritanceConstraintSet erledigt do { //PL 2018-11-05 Huellenbildung Variance auf alle TPHs der Terme auf der jeweiligen //anderen Seite übertragen varianceTPHold = new HashSet<>(varianceTPH); varianceTPH = varianceInheritanceConstraintSet(unifyCons); unifyCons.map( y -> { if ((y.getLhsType() instanceof PlaceholderType) && (y.getRhsType() instanceof PlaceholderType)) { if (((PlaceholderType)y.getLhsType()).getVariance() != 0 &&
* ((PlaceholderType)y.getRhsType()).getVariance() == 0) { ((PlaceholderType)y.getRhsType()).setVariance(((PlaceholderType)y.getLhsType( )).getVariance()); } if (((PlaceholderType)y.getLhsType()).getVariance() == 0 && ((PlaceholderType)y.getRhsType()).getVariance() != 0) { ((PlaceholderType)y.getLhsType()).setVariance(((PlaceholderType)y.getRhsType( )).getVariance()); } } return y; } ); } while (!varianceTPHold.equals(varianceTPH));
*/
// Set<Set<UnifyPair>> result = unify.unifySequential(xConsSet, finiteClosure,
// logFile, log);
// Set<Set<UnifyPair>> result = unify.unify(xConsSet, finiteClosure);
List<Set<Constraint<UnifyPair>>> oderConstraints = unifyCons.getOderConstraints()// .stream().map(x -> {
/*
* Set<Set<UnifyPair>> ret = new HashSet<>(); for (Constraint<UnifyPair> y : x) { ret.add(new HashSet<>(y)); } return ret; }).collect(Collectors.toCollection(ArrayList::new))
*/;
if (ConsoleInterface.unifyServerUrl.isPresent()) {
UnifyResultModel urm = new UnifyResultModel(cons, finiteClosure);
UnifyContext context = new UnifyContext(logger, true, urm, usedTasks, placeholderRegistry);
SocketFuture<UnifyResultPacket> future = SocketClient.execute(
UnifyRequestPacket.create(finiteClosure, cons, unifyCons, context.placeholderRegistry())
);
SocketClient.execute(SetAutoclosePacket.create());
return future.get().getResultSet(context);
}
else if (resultmodel) {
/* UnifyResultModel Anfang */
UnifyResultModel urm = new UnifyResultModel(cons, finiteClosure);
UnifyResultListenerImpl li = new UnifyResultListenerImpl();
urm.addUnifyResultListener(li);
UnifyContext context = new UnifyContext(logger, true, urm, usedTasks, placeholderRegistry);
TypeUnify.unifyParallel(unifyCons.getUndConstraints(), oderConstraints, finiteClosure, context);
var finalResults = li.getResults().stream().sorted().toList();
int i = 0;
logger.info("RESULT Final: ");
for (var result : finalResults){
logger.info("Result: " + i++);
logger.info(result.getSortedResults());
}
logger.info("RES_FINAL: " + li.getResults().toString() + "\n");
return li.getResults();
}
/* UnifyResultModel End */
else {
// Set<Set<UnifyPair>> result = unify.unify(unifyCons.getUndConstraints(),
// oderConstraints, finiteClosure, logFile, log, new UnifyResultModel(cons,
// finiteClosure));
UnifyContext context = new UnifyContext(logger, false, new UnifyResultModel(cons, finiteClosure), usedTasks, placeholderRegistry);
Set<Set<UnifyPair>> result = TypeUnify.unifyOderConstraints(unifyCons.getUndConstraints(), oderConstraints, finiteClosure, context);
logger.info("RESULT: " + result);
results.addAll(result);
results = results.stream().map(x -> {
Optional<Set<UnifyPair>> res = new RuleSet(placeholderRegistry).subst(x.stream().map(y -> {
if (y.getPairOp() == PairOperator.SMALLERDOTWC)
y.setPairOp(PairOperator.EQUALSDOT);
return y; // alle Paare a <.? b erden durch a =. b ersetzt
}).collect(Collectors.toCollection(HashSet::new)));
if (res.isPresent()) {// wenn subst ein Erg liefert wurde was veraendert
return new TypeUnifyTask(context).applyTypeUnificationRules(res.get(), finiteClosure);
} else
return x; // wenn nichts veraendert wurde wird x zurueckgegeben
}).collect(Collectors.toCollection(HashSet::new));
logger.info("RESULT Final: " + results);
logger.info("Constraints for Generated Generics: " + " ???");
logger.debug("RES_FINAL: " + results.toString() + "\n");
// logFile.flush();
logger.debug("PLACEHOLDERS: " + placeholderRegistry);
// logFile.flush();
}
return results.stream().map((unifyPairs -> new ResultSet(UnifyTypeFactory.convert(unifyPairs, Pair.generateTPHMap(cons), placeholderRegistry)))).collect(Collectors.toList());
}
/**
* TEMPORARY - Only for Language Server Usage
*/
public LanguageServerTransferObject getResultSetAndAbstractSyntax(File file) throws IOException, ClassNotFoundException {
var sf = sourceFiles.get(file); var sf = sourceFiles.get(file);
if(sf == null){ Set<ClassOrInterface> allClasses = new HashSet<>();// environment.getAllAvailableClasses();
sf = sourceFiles.values().stream().findFirst().get();
}
Set<ClassOrInterface> allClasses = new HashSet<>();
allClasses.addAll(getAvailableClasses(sf)); allClasses.addAll(getAvailableClasses(sf));
allClasses.addAll(sf.getClasses()); allClasses.addAll(sf.getClasses());
var newClasses = CompilationEnvironment.loadDefaultPackageClasses(sf.getPkgName(), file, this).stream().map(ASTFactory::createClass).collect(Collectors.toSet()); var newClasses = CompilationEnvironment.loadDefaultPackageClasses(sf.getPkgName(), file, this).stream().map(ASTFactory::createClass).collect(Collectors.toSet());
@@ -564,13 +382,15 @@ public class JavaTXCompiler {
final ConstraintSet<Pair> cons = getConstraints(file); final ConstraintSet<Pair> cons = getConstraints(file);
Set<Set<UnifyPair>> results = new HashSet<>(); Set<Set<UnifyPair>> results = new HashSet<>();
PlaceholderRegistry placeholderRegistry = new PlaceholderRegistry();
Writer logFile = new OutputStreamWriter(new NullOutputStream());
Logger logger = new Logger(logFile, "TypeInferenceAsync");
UnifyContext context = new UnifyContext(logger, false, null, usedTasks, defaultClientPlaceholderRegistry);
try { try {
IFiniteClosure finiteClosure = UnifyTypeFactory.generateFC(allClasses.stream().toList(), logger, classLoader, this, context.placeholderRegistry()); var logFolder = new File(System.getProperty("user.dir") + "/logFiles/");
ConstraintSet<UnifyPair> unifyCons = UnifyTypeFactory.convert(this, cons, context.placeholderRegistry()); if (log) logFolder.mkdirs();
Writer logFile = log ? new FileWriter(new File(logFolder, "log_" + sourceFiles.keySet().iterator().next().getName())) : new OutputStreamWriter(new NullOutputStream());
FiniteClosure finiteClosure = UnifyTypeFactory.generateFC(allClasses.stream().toList(), logFile, classLoader, this, placeholderRegistry);
System.out.println(finiteClosure);
ConstraintSet<UnifyPair> unifyCons = UnifyTypeFactory.convert(this, cons, placeholderRegistry);
System.out.println("xxx1");
Function<UnifyPair, UnifyPair> distributeInnerVars = x -> { Function<UnifyPair, UnifyPair> distributeInnerVars = x -> {
UnifyType lhs, rhs; UnifyType lhs, rhs;
if (((lhs = x.getLhsType()) instanceof PlaceholderType) && ((rhs = x.getRhsType()) instanceof PlaceholderType) && (((PlaceholderType) lhs).isInnerType() || ((PlaceholderType) rhs).isInnerType())) { if (((lhs = x.getLhsType()) instanceof PlaceholderType) && ((rhs = x.getRhsType()) instanceof PlaceholderType) && (((PlaceholderType) lhs).isInnerType() || ((PlaceholderType) rhs).isInnerType())) {
@@ -581,30 +401,66 @@ public class JavaTXCompiler {
}; };
logFile.write("Unify:" + unifyCons.toString());
System.out.println("Unify:" + unifyCons.toString());
unifyCons = unifyCons.map(distributeInnerVars); unifyCons = unifyCons.map(distributeInnerVars);
logFile.write("\nUnify_distributeInnerVars: " + unifyCons.toString());
// Set<Set<UnifyPair>> results = new HashSet<>(); Nach vorne gezogen
logFile.write("FC:\\" + finiteClosure.toString() + "\n");
logFile.write(ASTTypePrinter.print(sf));
System.out.println(ASTTypePrinter.print(sf));
// logFile.flush();
System.out.println("Unify nach Oder-Constraints-Anpassung:" + unifyCons.toString());
Set<PlaceholderType> varianceTPHold; Set<PlaceholderType> varianceTPHold;
Set<PlaceholderType> varianceTPH = new HashSet<>(); Set<PlaceholderType> varianceTPH = new HashSet<>();
varianceTPH = varianceInheritanceConstraintSet(unifyCons); varianceTPH = varianceInheritanceConstraintSet(unifyCons);
List<Set<Constraint<UnifyPair>>> oderConstraints = unifyCons.getOderConstraints(); /*
* PL 2018-11-07 wird in varianceInheritanceConstraintSet erledigt do { //PL 2018-11-05 Huellenbildung Variance auf alle TPHs der Terme auf der jeweiligen //anderen Seite übertragen varianceTPHold = new HashSet<>(varianceTPH); varianceTPH = varianceInheritanceConstraintSet(unifyCons); unifyCons.map( y -> { if ((y.getLhsType() instanceof PlaceholderType) && (y.getRhsType() instanceof PlaceholderType)) { if (((PlaceholderType)y.getLhsType()).getVariance() != 0 &&
* ((PlaceholderType)y.getRhsType()).getVariance() == 0) { ((PlaceholderType)y.getRhsType()).setVariance(((PlaceholderType)y.getLhsType( )).getVariance()); } if (((PlaceholderType)y.getLhsType()).getVariance() == 0 && ((PlaceholderType)y.getRhsType()).getVariance() != 0) { ((PlaceholderType)y.getLhsType()).setVariance(((PlaceholderType)y.getRhsType( )).getVariance()); } } return y; } ); } while (!varianceTPHold.equals(varianceTPH));
*/
if (resultmodel) { // Set<Set<UnifyPair>> result = unify.unifySequential(xConsSet, finiteClosure,
// logFile, log);
// Set<Set<UnifyPair>> result = unify.unify(xConsSet, finiteClosure);
List<Set<Constraint<UnifyPair>>> oderConstraints = unifyCons.getOderConstraints()// .stream().map(x -> {
/*
* Set<Set<UnifyPair>> ret = new HashSet<>(); for (Constraint<UnifyPair> y : x) { ret.add(new HashSet<>(y)); } return ret; }).collect(Collectors.toCollection(ArrayList::new))
*/;
if (unifyServer.isPresent()) {
UnifyResultModel urm = new UnifyResultModel(cons, finiteClosure);
UnifyContext context = new UnifyContext(logFile, log, true, urm, usedTasks, placeholderRegistry);
SocketClient socketClient = new SocketClient(unifyServer.get());
return socketClient.execute(finiteClosure, cons, unifyCons, context);
}
else if (resultmodel) {
/* UnifyResultModel Anfang */ /* UnifyResultModel Anfang */
UnifyResultModel urm = new UnifyResultModel(cons, finiteClosure); UnifyResultModel urm = new UnifyResultModel(cons, finiteClosure);
UnifyResultListenerImpl li = new UnifyResultListenerImpl(); UnifyResultListenerImpl li = new UnifyResultListenerImpl();
urm.addUnifyResultListener(li); urm.addUnifyResultListener(li);
UnifyContext context = new UnifyContext(logFile, log, true, urm, usedTasks, placeholderRegistry);
TypeUnify.unifyParallel(unifyCons.getUndConstraints(), oderConstraints, finiteClosure, context); TypeUnify.unifyParallel(unifyCons.getUndConstraints(), oderConstraints, finiteClosure, context);
generateBytecode(sf, li.getResults()); System.out.println("RESULT Final: " + li.getResults());
return new LanguageServerTransferObject(li.getResults(), sf, ASTTypePrinter.print(sf), generatedGenerics); System.out.println("Constraints for Generated Generics: " + " ???");
logFile.write("RES_FINAL: " + li.getResults().toString() + "\n");
// logFile.flush();
return li.getResults();
} }
/* UnifyResultModel End */ /* UnifyResultModel End */
else { else {
// Set<Set<UnifyPair>> result = unify.unify(unifyCons.getUndConstraints(),
// oderConstraints, finiteClosure, logFile, log, new UnifyResultModel(cons,
// finiteClosure));
UnifyContext context = new UnifyContext(logFile, log, false, new UnifyResultModel(cons, finiteClosure), usedTasks, placeholderRegistry);
Set<Set<UnifyPair>> result = TypeUnify.unifyOderConstraints(unifyCons.getUndConstraints(), oderConstraints, finiteClosure, context); Set<Set<UnifyPair>> result = TypeUnify.unifyOderConstraints(unifyCons.getUndConstraints(), oderConstraints, finiteClosure, context);
System.out.println("RESULT: " + result);
logFile.write("RES: " + result.toString() + "\n");
// logFile.flush();
results.addAll(result); results.addAll(result);
results = results.stream().map(x -> { results = results.stream().map(x -> {
Optional<Set<UnifyPair>> res = new RuleSet(context.placeholderRegistry()).subst(x.stream().map(y -> { Optional<Set<UnifyPair>> res = new RuleSet(placeholderRegistry).subst(x.stream().map(y -> {
if (y.getPairOp() == PairOperator.SMALLERDOTWC) if (y.getPairOp() == PairOperator.SMALLERDOTWC)
y.setPairOp(PairOperator.EQUALSDOT); y.setPairOp(PairOperator.EQUALSDOT);
return y; // alle Paare a <.? b erden durch a =. b ersetzt return y; // alle Paare a <.? b erden durch a =. b ersetzt
@@ -614,15 +470,19 @@ public class JavaTXCompiler {
} else } else
return x; // wenn nichts veraendert wurde wird x zurueckgegeben return x; // wenn nichts veraendert wurde wird x zurueckgegeben
}).collect(Collectors.toCollection(HashSet::new)); }).collect(Collectors.toCollection(HashSet::new));
System.out.println("RESULT Final: " + results);
System.out.println("Constraints for Generated Generics: " + " ???");
logFile.write("RES_FINAL: " + results.toString() + "\n");
// logFile.flush();
logFile.write("PLACEHOLDERS: " + placeholderRegistry);
// logFile.flush();
} }
} catch (ClassNotFoundException e) { } catch (IOException e) {
System.err.println("kein LogFile");
} }
generateBytecode(sf, results.stream().map((unifyPairs -> new ResultSet(UnifyTypeFactory.convert(unifyPairs, Pair.generateTPHMap(cons), context.placeholderRegistry())))).collect(Collectors.toList())); return results.stream().map((unifyPairs -> new ResultSet(UnifyTypeFactory.convert(unifyPairs, Pair.generateTPHMap(cons), placeholderRegistry)))).collect(Collectors.toList());
return new LanguageServerTransferObject(results.stream().map((unifyPairs -> new ResultSet(UnifyTypeFactory.convert(unifyPairs, Pair.generateTPHMap(cons), context.placeholderRegistry())))).collect(Collectors.toList()), sf, ASTTypePrinter.print(sf), generatedGenerics);
} }
/** /**
* Vererbt alle Variancen bei Paaren (a <. theta) oder (Theta <. a) wenn a eine Variance !=0 hat auf alle Typvariablen in Theta. * Vererbt alle Variancen bei Paaren (a <. theta) oder (Theta <. a) wenn a eine Variance !=0 hat auf alle Typvariablen in Theta.
* *
@@ -680,36 +540,75 @@ public class JavaTXCompiler {
public final JavaClassRegistry classRegistry = new JavaClassRegistry(); public final JavaClassRegistry classRegistry = new JavaClassRegistry();
private void parse(SourceFileContext tree, File sourceFile) throws IOException, java.lang.ClassNotFoundException { public record ClassEntry(File classFile, ClassOrInterface cif) {}
SyntaxTreeGenerator generator = new SyntaxTreeGenerator(this, classRegistry, new GenericsRegistry(null), sourceFile.getName());
public final Map<JavaClassName, ClassEntry> loadedClasses = new HashMap<>();
private SourceFile parse(File sourceFile) throws IOException, java.lang.ClassNotFoundException {
if (sourceFiles.containsKey(sourceFile)) return sourceFiles.get(sourceFile);
SourceFileContext tree = JavaTXParser.parse(sourceFile);
environment.addClassesToRegistry(classRegistry, tree, sourceFile, this); environment.addClassesToRegistry(classRegistry, tree, sourceFile, this);
SyntaxTreeGenerator generator = new SyntaxTreeGenerator(this, classRegistry, new GenericsRegistry(null), sourceFile.getName());
var classes = new ArrayList<ClassOrInterface>(); var classes = new ArrayList<ClassOrInterface>();
var sf = new SourceFile("", classes, generator.imports); var sf = new SourceFile("", classes, generator.imports);
addSourceFile(sourceFile, sf); addSourceFile(sourceFile, sf);
generator.convert(classes, tree, environment.packageCrawler); generator.convert(classes, tree, environment.packageCrawler);
sf.setPackageName(generator.pkgName); sf.setPackageName(generator.pkgName);
sf.imports.addAll(generator.imports); sf.imports.addAll(generator.imports);
return sf;
}
/**
* When an import tries to import a JavaTX class it first looks it up in the cache and
* if it doesn't exist it's going to compile it and add it to the source files list
* @param name
*/
public ClassOrInterface loadJavaTXClass(JavaClassName name) {
var file = findFileForClass(name);
if (file != null) {
if (loadedClasses.containsKey(name)) return loadedClasses.get(name).cif();
try {
var tree = JavaTXParser.parse(file);
classRegistry.addName(name.toString(), 0); // TODO This gets overwritten later, is it bad if we don't know this right away?
environment.addClassesToRegistry(classRegistry, tree, file, this);
SyntaxTreeGenerator generator = new SyntaxTreeGenerator(this, classRegistry, new GenericsRegistry(null), file.getName());
var classes = new ArrayList<ClassOrInterface>();
var sf = new SourceFile("", classes, generator.imports);
addSourceFile(file, sf);
generator.convert(classes, tree, environment.packageCrawler);
sf.setPackageName(generator.pkgName);
var classFiles = generateBytecode(file);
sf.setGenerated();
writeClassFile(classFiles, outputPath != null ? outputPath : new File("."), false);
var clazz = classLoader.loadClass(name.toString());
var classOrInterface = ASTFactory.createClass(clazz);
loadedClasses.put(name, new ClassEntry(new File(outputPath, clazz.getName() + ".class"), classOrInterface));
return classOrInterface;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
return null;
}
public File findFileForClass(JavaClassName name) {
var packageName = name.getPackageName();
var className = name.getClassName().split("\\.")[0];
for (var cp : classPath) {
var file = new File(cp, packageName.replaceAll("\\.", "/") + "/" + className + ".jav");
if (file.exists()) return file;
}
return null;
} }
public void generateBytecode() throws ClassNotFoundException, IOException { public void generateBytecode() throws ClassNotFoundException, IOException {
if (inferTogether) { for (var file : sourceFiles.keySet()) {
var files = sourceFiles.keySet().stream().toList(); var sf = sourceFiles.get(file);
var typeinferenceResult = this.typeInference(files); if (sf.isGenerated()) continue;
for (var file : files) { var classes = generateBytecode(file);
var sf = sourceFiles.get(file); sf.setGenerated();
if (sf.isGenerated()) continue; writeClassFile(classes, outputPath == null ? file.getParentFile() : outputPath, outputPath == null);
var classes = generateBytecode(sf, typeinferenceResult);
sf.setGenerated();
writeClassFile(classes, outputPath == null ? file.getParentFile() : outputPath, outputPath == null);
}
} else {
for (var file : sourceFiles.keySet()) {
var sf = sourceFiles.get(file);
if (sf.isGenerated()) continue;
var classes = generateBytecode(file);
sf.setGenerated();
writeClassFile(classes, outputPath == null ? file.getParentFile() : outputPath, outputPath == null);
}
} }
} }
@@ -754,12 +653,12 @@ public class JavaTXCompiler {
var codegen = new Codegen(converter.convert(clazz), this, converter); var codegen = new Codegen(converter.convert(clazz), this, converter);
var code = codegen.generate(); var code = codegen.generate();
generatedClasses.put(clazz.getClassName(), code); generatedClasses.put(clazz.getClassName(), code);
converter.auxiliaries.forEach((name, source) -> {
generatedClasses.put(new JavaClassName(name), source);
});
} }
generatedGenerics.put(sf, converter.javaGenerics()); generatedGenerics.put(sf, converter.javaGenerics());
converter.generateFunNTypes(); converter.generateFunNTypes();
auxiliaries.forEach((name, source) -> {
generatedClasses.put(new JavaClassName(name), source);
});
return generatedClasses; return generatedClasses;
} }
@@ -767,15 +666,15 @@ public class JavaTXCompiler {
FileOutputStream output; FileOutputStream output;
for (JavaClassName name : classFiles.keySet()) { for (JavaClassName name : classFiles.keySet()) {
byte[] bytecode = classFiles.get(name); byte[] bytecode = classFiles.get(name);
defaultLogger.info("generating " + name + ".class file ..."); System.out.println("generating " + name + ".class file ...");
var subPath = preserveHierarchy ? path : Path.of(path.toString(), name.getPackageName().split("\\.")).toFile(); var subPath = preserveHierarchy ? path : Path.of(path.toString(), name.getPackageName().split("\\.")).toFile();
File outputFile = new File(subPath, name.getClassName() + ".class"); File outputFile = new File(subPath, name.getClassName() + ".class");
outputFile.getAbsoluteFile().getParentFile().mkdirs(); outputFile.getAbsoluteFile().getParentFile().mkdirs();
defaultLogger.info(outputFile.toString()); System.out.println(outputFile);
output = new FileOutputStream(outputFile); output = new FileOutputStream(outputFile);
output.write(bytecode); output.write(bytecode);
output.close(); output.close();
defaultLogger.success(name + ".class file generated"); System.out.println(name + ".class file generated");
} }
} }

View File

@@ -10,10 +10,10 @@ public class JavaTXServer {
public JavaTXServer(int port) { public JavaTXServer(int port) {
this.socketServer = new SocketServer(port); this.socketServer = new SocketServer(port);
isRunning = true;
} }
public void listen() { public void listen() {
isRunning = true;
socketServer.start(); socketServer.start();
} }

View File

@@ -0,0 +1,13 @@
package de.dhbwstuttgart.environment;
public class ByteArrayClassLoader extends ClassLoader implements IByteArrayClassLoader {
@Override
public Class _defineClass(String name, byte[] code, int i, int length) throws ClassFormatError {
return defineClass(name, code, i, length);
}
@Override
public Class<?> findClass(String name) throws ClassNotFoundException {
return super.findClass(name);
}
}

View File

@@ -8,7 +8,6 @@ import java.util.*;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import de.dhbwstuttgart.core.JavaTXCompiler; import de.dhbwstuttgart.core.JavaTXCompiler;
import de.dhbwstuttgart.parser.scope.JavaClassName;
import de.dhbwstuttgart.syntaxtree.ClassOrInterface; import de.dhbwstuttgart.syntaxtree.ClassOrInterface;
import de.dhbwstuttgart.syntaxtree.factory.ASTFactory; import de.dhbwstuttgart.syntaxtree.factory.ASTFactory;
@@ -31,7 +30,7 @@ public class CompilationEnvironment {
public final PackageCrawler packageCrawler; public final PackageCrawler packageCrawler;
/** /**
* Imitiert die Environment beim Aufruf des JavaCompilers auf einer Menge von java-Dateien Die Environment enthält automatisch die Java Standard Library * Imitiert die Environment beim Aufruf des JavaCompilers auf einer Menge von java-Dateien Die Environment enth<EFBFBD>lt automatisch die Java Standard Library
* *
* @param sourceFiles die zu kompilierenden Dateien * @param sourceFiles die zu kompilierenden Dateien
*/ */
@@ -88,8 +87,6 @@ public class CompilationEnvironment {
if (files != null) if (files != null)
for (File classFile : files) { for (File classFile : files) {
String className = classFile.getName().substring(0, classFile.getName().length() - 6); String className = classFile.getName().substring(0, classFile.getName().length() - 6);
// Don't load class if its defined in the input
if (compiler.input.contains(new JavaClassName(className))) continue;
if (className.matches("Fun\\d+\\$\\$.*")) if (className.matches("Fun\\d+\\$\\$.*"))
continue; continue;
var name = packageName; var name = packageName;

View File

@@ -16,7 +16,7 @@ public class DirectoryClassLoader extends URLClassLoader implements IByteArrayCl
// } // }
public DirectoryClassLoader(List<File> directory, java.lang.ClassLoader parent) { public DirectoryClassLoader(List<File> directory, java.lang.ClassLoader parent) {
super(directory.stream().map(DirectoryClassLoader::dirToURL).flatMap(List::stream).collect(Collectors.toList()).toArray(new URL[0]), parent); super(directory.stream().map(DirectoryClassLoader::dirToURL).flatMap(List::stream).collect(Collectors.toList()).toArray(new URL[0]), parent.getParent());
} }
private static URL[] generateURLArray(URL url) { private static URL[] generateURLArray(URL url) {

View File

@@ -6,22 +6,18 @@ import java.nio.file.Path;
public interface IByteArrayClassLoader { public interface IByteArrayClassLoader {
Class<?> loadClass(String path) throws ClassNotFoundException; Class loadClass(String path) throws ClassNotFoundException;
default Class<?> loadClass(byte[] code) { default Class loadClass(byte[] code) {
return this.loadClass(null, code); return this._defineClass(null, code, 0, code.length);
} }
default Class<?> loadClass(String name, byte[] code) { default Class loadClass(Path path) throws IOException {
return this._defineClass(name, code, 0, code.length);
}
default Class<?> loadClass(Path path) throws IOException {
var code = Files.readAllBytes(path); var code = Files.readAllBytes(path);
return this._defineClass(null, code, 0, code.length); return this._defineClass(null, code, 0, code.length);
} }
public Class<?> findClass(String name) throws ClassNotFoundException; public Class<?> findClass(String name) throws ClassNotFoundException;
Class<?> _defineClass(String name, byte[] code, int i, int length) throws ClassFormatError; Class _defineClass(String name, byte[] code, int i, int length) throws ClassFormatError;
} }

View File

@@ -1,120 +0,0 @@
package de.dhbwstuttgart.languageServerInterface;
import de.dhbwstuttgart.bytecode.Codegen;
import de.dhbwstuttgart.core.JavaTXCompiler;
import de.dhbwstuttgart.environment.IByteArrayClassLoader;
import de.dhbwstuttgart.languageServerInterface.model.LanguageServerTransferObject;
import de.dhbwstuttgart.parser.scope.JavaClassName;
import de.dhbwstuttgart.syntaxtree.SourceFile;
import de.dhbwstuttgart.syntaxtree.factory.NameGenerator;
import de.dhbwstuttgart.target.generate.ASTToTargetAST;
import de.dhbwstuttgart.target.generate.GenericsResult;
import de.dhbwstuttgart.target.tree.TargetStructure;
import org.apache.commons.io.FileUtils;
import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* Implementation of an Interface for the Language-Server to get the Resultset and abstract Syntax.
*/
public class LanguageServerInterface {
public LanguageServerTransferObject getResultSetAndAbastractSyntax(String path, String resetNamesTo) throws IOException, URISyntaxException, ClassNotFoundException {
NameGenerator.resetTo(resetNamesTo);
return getResultSetAndAbstractSyntax(path);
}
public SourceFile getAst(String path, String resetNamesTo) throws IOException, URISyntaxException, ClassNotFoundException {
NameGenerator.resetTo(resetNamesTo);
return getAST(path);
}
/**
* returns the ResultSets, GenericResultSet and the AST
* You have to give the input as well as the path because of potential locks when the File is currently opened in an IDE.
* Example: file:///c:/test/main.jav -> file:///c:/test/out/main.class
*
* @param pathAsString the URI of the File. See Example.
*/
public LanguageServerTransferObject getResultSetAndAbstractSyntax(String pathAsString){
System.setOut(new PrintStream(OutputStream.nullOutputStream()));
try {
var uri = new URI(pathAsString);
var path = Path.of(uri);
var file = path.toFile();
Files.createDirectories(path.getParent().resolve("out"));
var compiler = new JavaTXCompiler(List.of(file), List.of(path.getParent().toFile()), path.getParent().resolve("out").toFile(), false);
var parsedSource = compiler.sourceFiles.get(file);
var tiResults = compiler.typeInference(file);
Map<JavaClassName, byte[]> bytecode = compiler.generateBytecode(parsedSource, tiResults);
Files.createDirectories(path.getParent().resolve("out"));
compiler.writeClassFile(bytecode, path.getParent().resolve("out").toFile(), false);
return new LanguageServerTransferObject(tiResults, parsedSource, "", compiler.getGeneratedGenerics());
} catch (Exception e) {
throw new RuntimeException(e.getMessage(), e);
}
}
/**
* returns the AST without calculating the result
* You have to give the input as well as the path because of potential locks when the File is currently opened in an IDE.
* Example: file:///c:/test/main.jav -> file:///c:/test/out/main.class
*
* @param path the URI of the File. See Example.
* @throws IOException
* @throws ClassNotFoundException
* @throws URISyntaxException
*/
public SourceFile getAST(String path) throws IOException, ClassNotFoundException, URISyntaxException {
System.setOut(new PrintStream(OutputStream.nullOutputStream()));
URI uri = new URI(path);
ArrayList<String> pathWithoutName = new ArrayList<>(List.of(uri.getPath().split("/")));
pathWithoutName.remove(List.of(uri.getPath().split("/")).size() - 1);
String stringPathWithoutName = "";
for (String i : pathWithoutName) {
stringPathWithoutName += "/" + i;
}
try {
FileUtils.cleanDirectory(new File(stringPathWithoutName + "/out"));
} catch (Exception e) {
}
try {
(new File(stringPathWithoutName + "/out")).mkdirs();
} catch (Exception e) {
}
var test = getAST(uri.getPath().split("/")[uri.getPath().split("/").length - 1], new File(stringPathWithoutName).getPath());
System.setOut(System.out);
return test;
}
public static SourceFile getAST(String filename, String filePath) throws IOException, ClassNotFoundException {
var file = Path.of(filePath, filename).toFile();
var compiler = new JavaTXCompiler(List.of(file), List.of(file.getParentFile()), Path.of(filePath + "/out").toFile(), false);
return compiler.sourceFiles.get(file);
}
}

View File

@@ -1,40 +0,0 @@
package de.dhbwstuttgart.languageServerInterface;
import de.dhbwstuttgart.languageServerInterface.model.CustomParserErrorHandler;
import de.dhbwstuttgart.languageServerInterface.model.ParserError;
import de.dhbwstuttgart.parser.antlr.Java17Lexer;
import de.dhbwstuttgart.parser.antlr.Java17Parser;
import de.dhbwstuttgart.parser.antlr.Java17ParserBaseListener;
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.CharStreams;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.ParseTreeWalker;
import java.util.List;
public class ParserInterface {
public List<ParserError> getParseErrors(String input){
CustomParserErrorHandler errorListener = new CustomParserErrorHandler();
CharStream charStream = CharStreams.fromString(input);
Java17Lexer lexer = new Java17Lexer(charStream);
CommonTokenStream tokens = new CommonTokenStream(lexer);
Java17Parser parser = new Java17Parser(tokens);
parser.removeErrorListeners();
parser.addErrorListener(errorListener);
ParseTree tree = parser.sourceFile();
ParseTreeWalker walker = new ParseTreeWalker();
Java17ParserBaseListener listener = new Java17ParserBaseListener();
walker.walk(listener, tree);
return errorListener.getErrorMessages();
}
}

View File

@@ -1,47 +0,0 @@
package de.dhbwstuttgart.languageServerInterface.model;
import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.atn.ATNConfigSet;
import org.antlr.v4.runtime.dfa.DFA;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
public class CustomParserErrorHandler implements ANTLRErrorListener {
private final List<ParserError> errorMessages = new ArrayList<>();
@Override
public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) {
int endCharPosition = charPositionInLine;
if (offendingSymbol instanceof Token) {
Token offendingToken = (Token) offendingSymbol;
endCharPosition = charPositionInLine + offendingToken.getText().length();
}
ParserError parserError = new ParserError(line, charPositionInLine, endCharPosition, msg);
errorMessages.add(parserError);
}
@Override
public void reportAmbiguity(Parser parser, DFA dfa, int i, int i1, boolean b, BitSet bitSet, ATNConfigSet atnConfigSet) {
}
@Override
public void reportAttemptingFullContext(Parser parser, DFA dfa, int i, int i1, BitSet bitSet, ATNConfigSet atnConfigSet) {
}
@Override
public void reportContextSensitivity(Parser parser, DFA dfa, int i, int i1, int i2, ATNConfigSet atnConfigSet) {
}
public List<ParserError> getErrorMessages() {
return errorMessages;
}
}

View File

@@ -1,31 +0,0 @@
package de.dhbwstuttgart.languageServerInterface.model;
import de.dhbwstuttgart.syntaxtree.SourceFile;
import de.dhbwstuttgart.target.generate.GenericsResult;
import de.dhbwstuttgart.typeinference.result.ResultSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class LanguageServerTransferObject {
List<ResultSet> resultSets;
SourceFile Ast;
String printedAst;
Map<SourceFile, List<GenericsResult>> generatedGenerics = new HashMap<>();
public LanguageServerTransferObject(List<ResultSet> resultSets, SourceFile Ast, String printedAst, Map<SourceFile, List<GenericsResult>> generatedGenerics) {
this.resultSets = resultSets;
this.Ast = Ast;
this.printedAst = printedAst;
this.generatedGenerics = generatedGenerics;
}
public List<ResultSet> getResultSets() {return resultSets;}
public SourceFile getAst() {return Ast;}
public String getPrintedAst() {return printedAst;}
public Map<SourceFile, List<GenericsResult>> getGeneratedGenerics() {return generatedGenerics;}
}

View File

@@ -1,48 +0,0 @@
package de.dhbwstuttgart.languageServerInterface.model;
public class ParserError {
private int line;
private int charPositionInLine;
private int endCharPosition;
String msg;
public ParserError(int line, int charPositionInLine, int endCharPosition, String msg) {
this.line = line;
this.charPositionInLine = charPositionInLine;
this. endCharPosition = endCharPosition;
this.msg = msg;
}
public int getEndCharPosition() {
return endCharPosition;
}
public void setEndCharPosition(int endCharPosition) {
this.endCharPosition = endCharPosition;
}
public void setCharPositionInLine(int charPositionInLine) {
this.charPositionInLine = charPositionInLine;
}
public void setLine(int line) {
this.line = line;
}
public void setMsg(String msg) {
this.msg = msg;
}
public int getCharPositionInLine() {
return charPositionInLine;
}
public int getLine() {
return line;
}
public String getMsg() {
return msg;
}
}

View File

@@ -1,20 +0,0 @@
package de.dhbwstuttgart.languageServerInterface.model;
import com.google.common.reflect.TypeResolver;
import de.dhbwstuttgart.typeinference.unify.UnifyResultEvent;
import de.dhbwstuttgart.typeinference.unify.UnifyResultListener;
public class ResultSetListener implements UnifyResultListener {
TypeResolver typeResolver;
public ResultSetListener(TypeResolver typeResolver){
this.typeResolver = typeResolver;
}
@Override
public void onNewTypeResultFound(UnifyResultEvent evt) {
}
}

View File

@@ -7,7 +7,6 @@ import de.dhbwstuttgart.parser.antlr.Java17Parser;
import de.dhbwstuttgart.parser.scope.JavaClassRegistry; import de.dhbwstuttgart.parser.scope.JavaClassRegistry;
import de.dhbwstuttgart.syntaxtree.SourceFile; import de.dhbwstuttgart.syntaxtree.SourceFile;
import de.dhbwstuttgart.util.Logger;
import org.antlr.v4.runtime.CharStream; import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.CharStreams; import org.antlr.v4.runtime.CharStreams;
import org.antlr.v4.runtime.CommonTokenStream; import org.antlr.v4.runtime.CommonTokenStream;
@@ -18,9 +17,6 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
public class JavaTXParser { public class JavaTXParser {
public static Logger logger = new Logger("Parser");
public static Java17Parser.SourceFileContext parse(File source) throws IOException, java.lang.ClassNotFoundException { public static Java17Parser.SourceFileContext parse(File source) throws IOException, java.lang.ClassNotFoundException {
InputStream stream = new FileInputStream(source); InputStream stream = new FileInputStream(source);
// DEPRECATED: ANTLRInputStream input = new ANTLRInputStream(stream); // DEPRECATED: ANTLRInputStream input = new ANTLRInputStream(stream);

View File

@@ -1,6 +1,5 @@
package de.dhbwstuttgart.parser.SyntaxTreeGenerator; package de.dhbwstuttgart.parser.SyntaxTreeGenerator;
import de.dhbwstuttgart.parser.JavaTXParser;
import java.lang.reflect.Modifier; import java.lang.reflect.Modifier;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
@@ -151,7 +150,7 @@ public class StatementGenerator {
} else { } else {
type = methodparameters? type = methodparameters?
TypePlaceholder.fresh(fp.getStart(), 1, false) TypePlaceholder.fresh(fp.getStart(), 1, false)
: TypePlaceholder.fresh(fp.getStart(), 1, false); : TypePlaceholder.fresh(fp.getStart());
} }
ret.add(new FormalParameter(paramName, type, fp.getStart())); ret.add(new FormalParameter(paramName, type, fp.getStart()));
localVars.put(paramName, type); localVars.put(paramName, type);
@@ -260,7 +259,7 @@ public class StatementGenerator {
ret.setStatement(); ret.setStatement();
return ret; return ret;
default: default:
JavaTXParser.logger.info(stmt.getClass()); System.out.println(stmt.getClass());
throw new NotImplementedException(); throw new NotImplementedException();
} }
} }
@@ -1066,7 +1065,7 @@ public class StatementGenerator {
List<Pattern> parameterList = new ArrayList<>(); List<Pattern> parameterList = new ArrayList<>();
for (IdentifierContext identifier : lambdaParams.identifier()) { for (IdentifierContext identifier : lambdaParams.identifier()) {
Token offset = identifier.getStart(); Token offset = identifier.getStart();
parameterList.add(new FormalParameter(identifier.getText(), TypePlaceholder.fresh(offset, 1, false), offset)); parameterList.add(new FormalParameter(identifier.getText(), TypePlaceholder.fresh(offset), offset));
} }
params = new ParameterList(parameterList, lambdaParams.getStart()); params = new ParameterList(parameterList, lambdaParams.getStart());
} else if (lambdaParams.formalParameterList() != null) { } else if (lambdaParams.formalParameterList() != null) {
@@ -1076,7 +1075,7 @@ public class StatementGenerator {
List<Pattern> parameterList = new ArrayList<>(); List<Pattern> parameterList = new ArrayList<>();
for (LambdaLVTIParameterContext param : lambdaParams.lambdaLVTIList().lambdaLVTIParameter()) { for (LambdaLVTIParameterContext param : lambdaParams.lambdaLVTIList().lambdaLVTIParameter()) {
Token offset = param.getStart(); Token offset = param.getStart();
parameterList.add(new FormalParameter(param.identifier().getText(), TypePlaceholder.fresh(offset, 1, false), offset)); parameterList.add(new FormalParameter(param.identifier().getText(), TypePlaceholder.fresh(offset), offset));
} }
params = new ParameterList(parameterList, lambdaParams.getStart()); params = new ParameterList(parameterList, lambdaParams.getStart());
} else { } else {
@@ -1100,9 +1099,9 @@ public class StatementGenerator {
block = lambdaGenerator.convert(expression.lambdaBody().block(), true); block = lambdaGenerator.convert(expression.lambdaBody().block(), true);
} }
List<RefTypeOrTPHOrWildcardOrGeneric> funNParams = new ArrayList<>(); List<RefTypeOrTPHOrWildcardOrGeneric> funNParams = new ArrayList<>();
funNParams.add(TypePlaceholder.fresh(expression.getStart(), -1, false));// ret-Type funNParams.add(TypePlaceholder.fresh(expression.getStart()));// ret-Type
params.getFormalparalist().forEach(formalParameter -> // Für jeden Parameter einen TPH anfügen: params.getFormalparalist().forEach(formalParameter -> // Für jeden Parameter einen TPH anfügen:
funNParams.add(TypePlaceholder.fresh(expression.getStart(), 1, false))); funNParams.add(TypePlaceholder.fresh(expression.getStart())));
RefTypeOrTPHOrWildcardOrGeneric lambdaType = TypePlaceholder.fresh(expression.getStart()); RefTypeOrTPHOrWildcardOrGeneric lambdaType = TypePlaceholder.fresh(expression.getStart());
// RefType lambdaType = new // RefType lambdaType = new
// RefType(reg.getName("Fun"+params.getFormalparalist().size()), // RefType(reg.getName("Fun"+params.getFormalparalist().size()),

View File

@@ -111,7 +111,7 @@ public class SyntaxTreeGenerator {
this.allmodifiers.put(Modifier.toString(Modifier.INTERFACE), Modifier.INTERFACE); this.allmodifiers.put(Modifier.toString(Modifier.INTERFACE), Modifier.INTERFACE);
this.allmodifiers.put("sealed", 4096); this.allmodifiers.put("sealed", 4096);
this.allmodifiers.put("non-sealed", 8192); this.allmodifiers.put("non-sealed", 8192);
this.allmodifiers.put("default", 0); // Doesn't exist this.allmodifiers.put("default", 16384);
this.allmodifiers.put("strictfp", 32768); this.allmodifiers.put("strictfp", 32768);
this.compiler = compiler; this.compiler = compiler;

View File

@@ -74,7 +74,7 @@ public class TypeGenerator {
throw new NotImplementedException(); throw new NotImplementedException();
} }
} else if (!typeContext.LBRACK().isEmpty()) { // ArrayType über eckige Klammer prüfen } else if (!typeContext.LBRACK().isEmpty()) { // ArrayType über eckige Klammer prüfen
// JavaTXParser.logger.info(unannTypeContext.getText()); // System.out.println(unannTypeContext.getText());
throw new NotImplementedException(); throw new NotImplementedException();
} }
/* /*
@@ -168,7 +168,7 @@ public class TypeGenerator {
if (generics.contains(name)) { if (generics.contains(name)) {
return new GenericRefType(name, offset); return new GenericRefType(name, offset);
} else { } else {
Pattern p = Pattern.compile("Fun(Void|VoidImpl|Wrapper)?(\\d+)[$][$]"); // TODO Regex shenanigans Pattern p = Pattern.compile("Fun(\\d+)[$][$]");
Matcher m = p.matcher(name); Matcher m = p.matcher(name);
if (m.matches()) {// es ist FunN$$-Type if (m.matches()) {// es ist FunN$$-Type
return new RefType(new JavaClassName(name), convert(typeArguments, reg, generics), offset); return new RefType(new JavaClassName(name), convert(typeArguments, reg, generics), offset);

View File

@@ -140,7 +140,8 @@ public class GatherNames {
if (importDeclCtx.MUL() == null) { if (importDeclCtx.MUL() == null) {
var name = importDeclCtx.qualifiedName().getText(); var name = importDeclCtx.qualifiedName().getText();
var className = new JavaClassName(name); var className = new JavaClassName(name);
if (compiler.input.contains(className)) { var clazz = compiler.loadJavaTXClass(className);
if (clazz != null) {
ret.put(name, compiler.classRegistry.getNumberOfGenerics(name)); ret.put(name, compiler.classRegistry.getNumberOfGenerics(name));
} else { } else {
Class<?> cl = compiler.getClassLoader().loadClass(name); Class<?> cl = compiler.getClassLoader().loadClass(name);

View File

@@ -41,7 +41,7 @@ public class JavaClassName {
} }
/** /**
* Gibt von einem Klassennamen nur den Namen der Klasse zurück * Gibt von einem Klassennamen nur den Namen der Klasse zur<EFBFBD>ck
* Beispiel: * Beispiel:
* java.lang.Object wird zu: Object * java.lang.Object wird zu: Object
*/ */

View File

@@ -5,9 +5,9 @@ import de.dhbwstuttgart.exceptions.NotImplementedException;
import java.util.*; import java.util.*;
/** /**
* Speichert die Klassen für einen bestimmten Projektscope * Speichert die Klassen f<EFBFBD>r einen bestimmten Projektscope
*/ */
public class JavaClassRegistry{ public class JavaClassRegistry {
final Map<JavaClassName, Integer> existingClasses = new HashMap<>(); final Map<JavaClassName, Integer> existingClasses = new HashMap<>();
public JavaClassRegistry(Map<String, Integer> initialNames) { public JavaClassRegistry(Map<String, Integer> initialNames) {
@@ -22,10 +22,6 @@ public class JavaClassRegistry{
} }
} }
public Set<JavaClassName> getAllClassNames(){
return existingClasses.keySet();
}
public void addName(String className, int numberOfGenerics) { public void addName(String className, int numberOfGenerics) {
existingClasses.put(new JavaClassName(className), numberOfGenerics); existingClasses.put(new JavaClassName(className), numberOfGenerics);
} }
@@ -64,6 +60,6 @@ public class JavaClassRegistry{
} }
public int getNumberOfGenerics(String name) { public int getNumberOfGenerics(String name) {
return existingClasses.getOrDefault(new JavaClassName(name), 0); return existingClasses.get(new JavaClassName(name));
} }
} }

View File

@@ -1,41 +0,0 @@
package de.dhbwstuttgart.server;
import de.dhbwstuttgart.util.Logger;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import org.java_websocket.WebSocket;
public class ServerTaskLogger extends Logger {
private final WebSocket webSocket;
private final SocketServer socketServer;
private final LogLevel customLogLevel;
public ServerTaskLogger(WebSocket webSocket, SocketServer socketServer, LogLevel customLogLevel) {
this.webSocket = webSocket;
this.socketServer = socketServer;
this.customLogLevel = customLogLevel;
}
@Override
public boolean isLogLevelActive(LogLevel logLevel) {
return logLevel.isHigherOrEqualTo(customLogLevel);
}
@Override
protected void print(String s, LogLevel logLevel) {
String coloredPrefix = this.getPrefix(logLevel);
if (logLevel.isHigherOrEqualTo(LogLevel.ERROR)) {
socketServer.sendError(webSocket, coloredPrefix + s, false);
}
else {
socketServer.sendMessage(webSocket, coloredPrefix + s);
}
}
@Override
protected void write(String s) {
// under no circumstances write anything to a file
}
}

View File

@@ -1,8 +1,6 @@
package de.dhbwstuttgart.server; package de.dhbwstuttgart.server;
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonProcessingException;
import de.dhbwstuttgart.core.ConsoleInterface;
import de.dhbwstuttgart.server.packet.IClientToServerPacket;
import de.dhbwstuttgart.server.packet.IPacket; import de.dhbwstuttgart.server.packet.IPacket;
import de.dhbwstuttgart.server.packet.IServerToClientPacket; import de.dhbwstuttgart.server.packet.IServerToClientPacket;
import de.dhbwstuttgart.server.packet.PacketContainer; import de.dhbwstuttgart.server.packet.PacketContainer;
@@ -14,12 +12,10 @@ import de.dhbwstuttgart.typeinference.result.ResultSet;
import de.dhbwstuttgart.typeinference.unify.UnifyContext; import de.dhbwstuttgart.typeinference.unify.UnifyContext;
import de.dhbwstuttgart.typeinference.unify.model.FiniteClosure; import de.dhbwstuttgart.typeinference.unify.model.FiniteClosure;
import de.dhbwstuttgart.typeinference.unify.model.UnifyPair; import de.dhbwstuttgart.typeinference.unify.model.UnifyPair;
import de.dhbwstuttgart.util.Logger;
import java.net.URI; import java.net.URI;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch; import java.util.concurrent.CountDownLatch;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
@@ -33,33 +29,39 @@ import org.java_websocket.handshake.ServerHandshake;
*/ */
public class SocketClient extends WebSocketClient { public class SocketClient extends WebSocketClient {
public static Logger logger = new Logger("SocketClient"); // use a latch to wait until the connection is closed by the remote host
private final CountDownLatch closeLatch = new CountDownLatch(1);
// temporarily: The received unify result
// TODO: replace with uuid and future system, such that responses can be mapped by a uuid to fulfill a Future
private UnifyResultPacket unifyResultPacket;
/** public SocketClient(String url) {
* The singleton object super(URI.create(url), Map.of(
*/ "packetProtocolVersion", SocketServer.packetProtocolVersion
private static SocketClient socketClient = null; ));
// make sure, the url is in a valid format
/**
* List of futures that are still waiting to be fulfilled
*/
private final Map<String, SocketFuture<?>> responseFutures = new HashMap<>();
private SocketClient(String url) {
super(
URI.create(url), // target url
//SocketServer.perMessageDeflateDraft, // enable compression
Map.of( // headers
"packetProtocolVersion", SocketServer.packetProtocolVersion
)
);
// make sure the url is in a valid format
final String regex = "^wss?://(\\w+(\\.\\w+)?)*:(\\d+)$"; final String regex = "^wss?://(\\w+(\\.\\w+)?)*:(\\d+)$";
final Matcher matcher = Pattern.compile(regex).matcher(url); final Matcher matcher = Pattern.compile(regex).matcher(url);
if (!matcher.find()) { if (!matcher.find()) {
throw new RuntimeException("Provided string \"" + url + "\" is not a valid server URL! Use pattern ws(s?)://<host.name>:<port>"); throw new RuntimeException("Provided string \"" + url + "\" is not a valid server URL! Use pattern ws(s?)://<host.name>:<port>");
} }
}
public SocketClient(String host, int port, boolean secure) {
super(URI.create(String.format("%s://%s:%d/", secure ? "wss" : "ws", host, port)));
}
/**
* The main method for connecting, requesting and waiting for the server to unify.
* This is synchronized to prevent multiple webSockets connections at the moment, but it is not called from any
* thread except the main thread right now and is not necessary at all, probably. Maybe remove it later
*/
synchronized public List<ResultSet> execute(
FiniteClosure finiteClosure,
ConstraintSet<Pair> constraintSet,
ConstraintSet<UnifyPair> unifyConstraintSet,
UnifyContext context
) throws JsonProcessingException {
try { try {
// wait for the connection to be set up // wait for the connection to be set up
@@ -68,135 +70,89 @@ public class SocketClient extends WebSocketClient {
if (this.getReadyState() != ReadyState.OPEN) { if (this.getReadyState() != ReadyState.OPEN) {
throw new RuntimeException("WebSocket Client could not connect to remote host at " + this.uri); throw new RuntimeException("WebSocket Client could not connect to remote host at " + this.uri);
} }
} catch (InterruptedException exception) {
throw new RuntimeException(exception);
}
// add a shutdown hook to close the connection when the process ends or is stopped by a SIGINT signal // send the unify task request
Runtime.getRuntime().addShutdownHook(new Thread(this::close)); UnifyRequestPacket packet = new UnifyRequestPacket(finiteClosure, constraintSet, unifyConstraintSet, context.placeholderRegistry());
}
private SocketClient(String host, int port, boolean secure) throws InterruptedException {
this(String.format("%s://%s:%d/", secure ? "wss" : "ws", host, port));
}
/**
* Singleton access method, creates one if none is available
*
* @return The one and only socketClient
*/
private static SocketClient initializeClient() {
if (socketClient == null) {
socketClient = new SocketClient(ConsoleInterface.unifyServerUrl.get());
}
return socketClient;
}
/**
* Send a packet to the server (connection will be created, if none is found) and return a future
* for the response packet
*/
synchronized public static <T extends IServerToClientPacket> SocketFuture<T> execute(IClientToServerPacket<T> packet) {
SocketClient client = initializeClient();
/*
* Create a future that will be associated with the packet and eventually completed
*/
SocketFuture<T> future = packet.getFuture();
if (!future.isDone()) {
client.responseFutures.put(future.futureId, future);
}
/*
* Establish connection, if not already done.
* Serialize the packet and send it to the server.
* Return the future to be handled by the caller.
*/
try {
String json = PacketContainer.serialize(packet); String json = PacketContainer.serialize(packet);
client.send(json); this.send(json);
} catch (Exception exception) {
logger.exception(exception); // block the thread, until the connection is closed by the remote host (usually after sending the results)
this.waitUntilClosed();
// wait for the connection to fully close
this.closeBlocking();
} catch (InterruptedException exception) {
System.err.println("Server connection interrupted: " + exception);
this.notifyAll();
throw new RuntimeException("Aborted server connection", exception);
}
catch (Exception exception) {
throw new RuntimeException("Exception occurred in server connection: ", exception); throw new RuntimeException("Exception occurred in server connection: ", exception);
} }
return future; // detect error cases, in which no error was thrown, but also no result was sent back from the server
if (this.unifyResultPacket == null) {
throw new RuntimeException("Did not receive server response but closed connection already");
}
return unifyResultPacket.getResultSet(context);
} }
/** /**
* Shortcut for waiting and retrieving the response immediately * Specific client-side implementations to handle incoming packets
*
* @param packet The packet to send
* @param <T> The type of response packet to await
* @return The response packet, once it is received
*/
public static <T extends IServerToClientPacket> T executeAndGet(IClientToServerPacket<T> packet) {
return SocketClient.execute(packet).get();
}
/**
* Specific client-side implementations to handle incoming packets
*/ */
protected void handleReceivedPacket(IPacket packet) { protected void handleReceivedPacket(IPacket packet) {
if (!(packet instanceof IServerToClientPacket serverToClientPacket)) { if (packet instanceof IServerToClientPacket serverToClientPacket) {
System.err.println("Received package of invalid type + " + packet.getClass().getName());
this.close(); try {
serverToClientPacket.onHandle(this.getConnection(), this);
}
catch (Exception exception) {
this.closeLatch.countDown();
this.close();
throw exception;
}
return; return;
} }
serverToClientPacket.onHandle(this.getConnection(), this); System.err.println("Received package of invalid type + " + packet.getClass().getName());
this.close();
} }
/** public void setUnifyResultSets(UnifyResultPacket unifyResultPacket) {
* Complete a registered future, so it can be handled by whoever executed the creator task this.unifyResultPacket = unifyResultPacket;
*
* @param id The associated id for this future
* @param trigger The object triggering the completion
*/
public void completeResponseFuture(String id, IServerToClientPacket trigger) {
SocketFuture<?> future = this.responseFutures.remove(id);
if (future == null) return;
if (!future.accept(trigger)) {
throw new RuntimeException("Packet " + trigger.getClass().getName() + " tried to complete future, but was not allowed to");
}
}
public static void closeIfOpen() {
if (socketClient != null && socketClient.isOpen()) {
socketClient.close();
}
} }
@Override @Override
public void onOpen(ServerHandshake handshakedata) { public void onOpen(ServerHandshake handshakedata) {
logger.success("Connected to server with status " + handshakedata.getHttpStatus()); System.out.println("Connected to server with status " + handshakedata.getHttpStatus());
} }
@Override @Override
public void onMessage(String message) { public void onMessage(String message) {
// logger.info("received: " + message); // System.out.println("received: " + message);
IPacket packet = PacketContainer.deserialize(message); IPacket packet = PacketContainer.deserialize(message);
this.handleReceivedPacket(packet); this.handleReceivedPacket(packet);
} }
@Override @Override
public void onClose(int code, String reason, boolean remote) { public void onClose(int code, String reason, boolean remote) {
logger.info( System.out.println(
"Disconnected from server " + "Disconnected from server " +
"with code " + code + " " + "with code " + code + " " +
(reason.isEmpty() ? "" : "and reason " + reason + " ") + (reason.isEmpty() ? "" : "and reason " + reason + " ") +
"(closed by remote: " + remote + ")" "(closed by remote: " + remote + ")"
); );
this.closeLatch.countDown();
if (!this.responseFutures.isEmpty()) {
throw new RuntimeException("Server closed before all required tasks were answered");
}
} }
@Override @Override
public void onError(Exception e) { public void onError(Exception e) {
logger.exception(e); System.out.println("Error: " + e.getMessage());
throw new RuntimeException(e); e.printStackTrace();
} }
public void waitUntilClosed() throws InterruptedException {
closeLatch.await();
}
} }

View File

@@ -1,48 +0,0 @@
package de.dhbwstuttgart.server;
import de.dhbwstuttgart.server.packet.IServerToClientPacket;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
public class SocketFuture<T extends IServerToClientPacket> extends CompletableFuture<T> {
public final String futureId = UUID.randomUUID().toString();
public final List<Class<T>> allowedTriggers;
public SocketFuture(List<Class<T>> allowedTriggers) {
this.allowedTriggers = allowedTriggers;
}
public boolean accept(IServerToClientPacket trigger) {
if (this.allowedTriggers.contains(trigger.getClass())) {
this.complete((T)trigger);
return true;
}
return false;
}
@Override
public T get() {
try {
return super.get();
}
catch (InterruptedException | ExecutionException exception) {
throw new RuntimeException(exception);
}
}
/**
* Special case where the future is immediately fulfilled without a response package similar to
* <code>CompletableFuture.completedFuture()</code> but without a value
*/
public static <R extends IServerToClientPacket> SocketFuture<R> completedFuture() {
SocketFuture<R> dummyFuture = new SocketFuture<>(new ArrayList<>(0));
dummyFuture.complete(null);
return dummyFuture;
}
}

View File

@@ -6,104 +6,76 @@ import de.dhbwstuttgart.server.packet.IClientToServerPacket;
import de.dhbwstuttgart.server.packet.IPacket; import de.dhbwstuttgart.server.packet.IPacket;
import de.dhbwstuttgart.server.packet.MessagePacket; import de.dhbwstuttgart.server.packet.MessagePacket;
import de.dhbwstuttgart.server.packet.PacketContainer; import de.dhbwstuttgart.server.packet.PacketContainer;
import de.dhbwstuttgart.util.Logger;
import java.net.InetSocketAddress; import java.net.InetSocketAddress;
import java.util.Collections; import java.util.Objects;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
import org.java_websocket.WebSocket; import org.java_websocket.WebSocket;
import org.java_websocket.drafts.Draft;
import org.java_websocket.drafts.Draft_6455;
import org.java_websocket.extensions.permessage_deflate.PerMessageDeflateExtension;
import org.java_websocket.handshake.ClientHandshake; import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer; import org.java_websocket.server.WebSocketServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SocketServer extends WebSocketServer { public class SocketServer extends WebSocketServer {
public static Logger logger = new Logger("SocketServer");
public static final int maxTasksPerSession = 100;
private static boolean serverRunning = false;
/** /**
* Increase this every time a breaking change to the server communication is done. * Increase this every time a breaking change to the server communication is done.
* This will prevent errors when the server version and client version do not match. * This will prevent errors when server version and client version do not match.
*/ */
public static final String packetProtocolVersion = "1"; public static final String packetProtocolVersion = "1";
// create an executor for tasks that will always keep at least one task around public static final Logger log = LoggerFactory.getLogger(SocketServer.class);
private final ThreadPoolExecutor taskExecutor = new ThreadPoolExecutor(1, Integer.MAX_VALUE,60L, TimeUnit.SECONDS, new SynchronousQueue<>());
// create an executor for scheduling timeouts
private final ScheduledExecutorService timeoutExecutor = Executors.newSingleThreadScheduledExecutor();
public SocketServer(int port) { public SocketServer(int port) {
super(new InetSocketAddress(port)); super(new InetSocketAddress(port));
this.setConnectionLostTimeout(30);
serverRunning = true;
// add a shutdown hook to close all connections when the process ends or is stopped by a SIGINT signal
Runtime.getRuntime().addShutdownHook(new Thread(this::onShutdown));
}
public static boolean isServerRunning() {
return serverRunning;
}
private void onShutdown() {
serverRunning = false;
try {
for (var webSocket : this.getConnections()) {
this.sendError(webSocket, "Sorry, i am shutting down. You are now on your own, good Luck!", true);
webSocket.close();
}
this.stop();
taskExecutor.shutdown();
timeoutExecutor.shutdown();
} catch (InterruptedException exception) {
// we are shutting down anyway
}
} }
@Override @Override
public void onOpen(WebSocket webSocket, ClientHandshake clientHandshake) { public void onOpen(WebSocket webSocket, ClientHandshake clientHandshake) {
String ppv = clientHandshake.getFieldValue("packetProtocolVersion"); String ppv = clientHandshake.getFieldValue("packetProtocolVersion");
if (!ppv.equals(packetProtocolVersion)) { if (!ppv.equals(packetProtocolVersion)) {
this.sendError(webSocket, try {
"Mismatch in packet protocol version! Client (you): \"" + ppv + "\" and Server (me): \"" + packetProtocolVersion + "\"", ErrorPacket errorPacket = ErrorPacket.create(
true "Mismatch in packet protocol version! Client (you): " + ppv + " and Server (me): " + packetProtocolVersion,
); true
);
webSocket.send(PacketContainer.serialize(errorPacket));
}
catch (JsonProcessingException exception) {
System.err.println("Failed to serialize json: " + exception);
}
webSocket.close(1); webSocket.close(1);
return; return;
} }
SocketData socketData = new SocketData(webSocket);
logger.info("New connection: " + socketData.id + " (with ppv " + ppv + ")"); SocketData socketData = new SocketData(UUID.randomUUID().toString());
webSocket.setAttachment(socketData);
System.out.println("New connection: " + socketData.id + " (with ppv " + ppv + ")");
try { try {
sendMessage(webSocket, "Welcome to the server!"); sendMessage(webSocket, "Welcome to the server!");
// wait 10 seconds for the client to send a task and close the connection if nothing has been received until then // wait 10 seconds for the client to send a task and close the connection if nothing has been received until then
final int secondsUntilTimeout = 10; try (ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor()) {
timeoutExecutor.schedule(() -> { Runnable task = () -> {
if (webSocket.<SocketData>getAttachment().totalTasks.get() > 0 || !webSocket.isOpen()) { if (webSocket.<SocketData>getAttachment().unhandledTasks.get() == 0 || !webSocket.isOpen()) {
return; return;
} }
sendMessage(webSocket, "No task received after " + secondsUntilTimeout + " seconds. Closing connection..."); sendMessage(webSocket, "No task received after 10 seconds. Closing connection...");
webSocket.close(); webSocket.close();
}, };
secondsUntilTimeout, executor.schedule(task, 10, TimeUnit.SECONDS);
TimeUnit.SECONDS executor.shutdown();
); }
// and finally, when your program wants to exit // and finally, when your program wants to exit
} catch (Exception e) { } catch (Exception e) {
logger.exception(e); log.error("e: ", e);
webSocket.close(1, e.getMessage()); webSocket.close(1, e.getMessage());
} }
} }
@@ -111,8 +83,8 @@ public class SocketServer extends WebSocketServer {
@Override @Override
public void onClose(WebSocket webSocket, int code, String reason, boolean remote) { public void onClose(WebSocket webSocket, int code, String reason, boolean remote) {
SocketData socketData = webSocket.getAttachment(); SocketData socketData = webSocket.getAttachment();
logger.info("Connection closed: " + socketData.id); System.out.println("Connection closed: " + socketData.id);
logger.info( System.out.println(
"Disconnected client " + socketData.id + " " + "Disconnected client " + socketData.id + " " +
"with code " + code + " " + "with code " + code + " " +
(reason.isEmpty() ? "" : "and reason " + reason + " ") + (reason.isEmpty() ? "" : "and reason " + reason + " ") +
@@ -123,28 +95,24 @@ public class SocketServer extends WebSocketServer {
@Override @Override
public void onMessage(WebSocket webSocket, String s) { public void onMessage(WebSocket webSocket, String s) {
// logger.info("Received: " + s.substring(0, 50)); // System.out.println("Received: " + s.substring(0, 50));
IPacket reconstructedPacket = PacketContainer.deserialize(s); IPacket reconstructedPacket = PacketContainer.deserialize(s);
try { try {
this.onPacketReceived(webSocket, reconstructedPacket); this.onPacketReceived(webSocket, reconstructedPacket);
} catch (JsonProcessingException e) { } catch (JsonProcessingException e) {
logger.exception(e); this.log("Error on processing incoming package: " + e.getMessage(), webSocket);
this.log(webSocket, "Error on processing incoming package: " + e.getMessage());
} }
} }
@Override @Override
public void onError(WebSocket webSocket, Exception e) { public void onError(WebSocket webSocket, Exception e) {
if (webSocket != null) { log(e.getMessage(), webSocket);
log(webSocket, e.getMessage()); webSocket.close();
webSocket.close();
}
logger.exception(e);
} }
@Override @Override
public void onStart() { public void onStart() {
logger.success("Websocket server started on port " + this.getPort()); System.out.println("Websocket server started on port " + this.getPort());
} }
/** /**
@@ -152,42 +120,45 @@ public class SocketServer extends WebSocketServer {
*/ */
public void sendMessage(WebSocket webSocket, String text) { public void sendMessage(WebSocket webSocket, String text) {
try { try {
MessagePacket message = MessagePacket.create(text); MessagePacket message = new MessagePacket();
message.message = text;
webSocket.send(PacketContainer.serialize(message)); webSocket.send(PacketContainer.serialize(message));
} catch (Exception e) { } catch (Exception e) {
System.err.println("Failed to send message: " + text); System.err.println("Failed to send message: " + text);
logger.exception(e); log.error("e: ", e);
} }
} }
/** /**
* A shorthand method for sending error messages to the client * A shorthand method for sending error messages to the client
*/ */
public void sendError(WebSocket webSocket, String text, boolean isFatal) { public void sendError(WebSocket webSocket, String text) {
try { try {
ErrorPacket error = ErrorPacket.create(text, isFatal); ErrorPacket error = new ErrorPacket();
error.error = text;
webSocket.send(PacketContainer.serialize(error)); webSocket.send(PacketContainer.serialize(error));
} catch (Exception e) { } catch (Exception e) {
logger.exception(e); System.err.println("Failed to send error: " + text);
log(webSocket, "Failed to send error: " + text); log.error("e: ", e);
} }
} }
/** /**
* The server-side implementation on how to handle certain packets when received * The server-side implementation on how to handle certain packets when received
*/ */
private void onPacketReceived(WebSocket webSocket, IPacket packet) throws JsonProcessingException { private void onPacketReceived(WebSocket webSocket, IPacket packet) throws JsonProcessingException {
SocketData socketData = webSocket.getAttachment(); SocketData socketData = webSocket.getAttachment();
// limit the number of tasks per connection // limit the amount of tasks per connection
if (socketData.totalTasks.get() >= maxTasksPerSession) { final int maxTasks = 100;
sendError(webSocket, "Exceeded the maximum amount of " + maxTasksPerSession + " tasks per session", true); if (socketData.totalTasks.get() >= maxTasks) {
sendError(webSocket, "Exceeded the maximum amount of " + maxTasks + " tasks per session");
webSocket.close(); webSocket.close();
return; return;
} }
// only allow packets that are meant to be handled by the server // only allow packets, that are meant to be handled by the server
if (!(packet instanceof IClientToServerPacket<?> clientToServerPacket)) { if (!(packet instanceof IClientToServerPacket clientToServerPacket)) {
sendMessage(webSocket, "The package of type " + packet.getClass().getName() + " is not handled by the server!"); sendMessage(webSocket, "The package of type " + packet.getClass().getName() + " is not handled by the server!");
return; return;
} }
@@ -196,24 +167,22 @@ public class SocketServer extends WebSocketServer {
socketData.unhandledTasks.incrementAndGet(); socketData.unhandledTasks.incrementAndGet();
socketData.totalTasks.incrementAndGet(); socketData.totalTasks.incrementAndGet();
// add the packet to the queue so it can be started by the worker // add the packet to the queue, so it can be started by the worker
CompletableFuture.runAsync(() -> { CompletableFuture.runAsync(() -> {
clientToServerPacket.onHandle(webSocket, this); clientToServerPacket.onHandle(webSocket, this);
int remainingUnhandledTasks = socketData.unhandledTasks.decrementAndGet();
if (socketData.closeIfNoTasksLeft) { // if the websocket has 0 unhandled Tasks, close the connection
// if the websocket has 0 unhandled Tasks, close the connection int remainingUnhandledTasks = socketData.unhandledTasks.decrementAndGet();
if (remainingUnhandledTasks <= 0) { if (remainingUnhandledTasks <= 0) {
sendMessage(webSocket, "All requested tasks finished! Closing connection..."); sendMessage(webSocket, "All requested tasks finished! Closing connection...");
webSocket.close(); webSocket.close();
}
} }
}, taskExecutor); });
} }
public void log(WebSocket webSocket, String msg) { public void log(String msg, WebSocket webSocket) {
String socketId = (webSocket == null) ? "???" : webSocket.<SocketData>getAttachment().id; SocketData socketData = webSocket == null ? new SocketData("???") : webSocket.getAttachment();
logger.info("[" + socketId + "] " + msg); System.out.println("["+socketData.id+"] " + msg);
} }
/** /**
@@ -225,11 +194,10 @@ public class SocketServer extends WebSocketServer {
public final String id; public final String id;
public final AtomicInteger unhandledTasks = new AtomicInteger(0); public final AtomicInteger unhandledTasks = new AtomicInteger(0);
public final AtomicInteger totalTasks = new AtomicInteger(0); public final AtomicInteger totalTasks = new AtomicInteger(0);
public boolean closeIfNoTasksLeft = false;
public SocketData(WebSocket webSocket) { public SocketData(String id) {
this.id = UUID.randomUUID().toString(); this.id = id;
webSocket.setAttachment(this);
} }
} }
} }

View File

@@ -2,7 +2,6 @@ package de.dhbwstuttgart.server.packet;
import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnore;
import de.dhbwstuttgart.server.SocketClient; import de.dhbwstuttgart.server.SocketClient;
import de.dhbwstuttgart.server.SocketFuture;
import de.dhbwstuttgart.server.SocketServer; import de.dhbwstuttgart.server.SocketServer;
import de.dhbwstuttgart.server.packet.dataContainers.serialized.ISerialNode; import de.dhbwstuttgart.server.packet.dataContainers.serialized.ISerialNode;
import de.dhbwstuttgart.server.packet.dataContainers.serialized.SerialList; import de.dhbwstuttgart.server.packet.dataContainers.serialized.SerialList;
@@ -11,7 +10,7 @@ import de.dhbwstuttgart.server.packet.dataContainers.serialized.SerialUUID;
import de.dhbwstuttgart.server.packet.dataContainers.serialized.SerialValue; import de.dhbwstuttgart.server.packet.dataContainers.serialized.SerialValue;
import org.java_websocket.WebSocket; import org.java_websocket.WebSocket;
public class DebugPacket implements IClientToServerPacket.Void, IServerToClientPacket { public class DebugPacket implements IClientToServerPacket, IServerToClientPacket {
public SerialUUID a1; public SerialUUID a1;
public SerialUUID a2; public SerialUUID a2;
@@ -23,13 +22,9 @@ public class DebugPacket implements IClientToServerPacket.Void, IServerToClientP
public SerialValue<?> d2; public SerialValue<?> d2;
@JsonIgnore @JsonIgnore
public void onHandle(WebSocket webSocket, SocketClient socketClient) {} public void onHandle(WebSocket webSocket, SocketClient socketServer) {}
@JsonIgnore @JsonIgnore
public void onHandle(WebSocket webSocket, SocketServer socketServer) {} public void onHandle(WebSocket webSocket, SocketServer socketServer) {}
@JsonIgnore
public SocketFuture<IServerToClientPacket> getFuture() {
return SocketFuture.completedFuture();
}
} }

View File

@@ -2,17 +2,16 @@ package de.dhbwstuttgart.server.packet;
import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnore;
import de.dhbwstuttgart.server.SocketClient; import de.dhbwstuttgart.server.SocketClient;
import de.dhbwstuttgart.server.SocketFuture;
import de.dhbwstuttgart.server.SocketServer; import de.dhbwstuttgart.server.SocketServer;
import org.java_websocket.WebSocket; import org.java_websocket.WebSocket;
/** /**
* A packet to send simple error messages between the client and the server * A packet to send simple error messages between the client and the server
*/ */
public class ErrorPacket implements IServerToClientPacket { public class ErrorPacket implements IClientToServerPacket, IServerToClientPacket {
/** /**
* The error endpoint for messages from the server that should be logged out as errors and possibly abort the process * The error endpoint for messages from the server, that should be logged out outputted
*/ */
public String error; public String error;
public boolean isFatal; public boolean isFatal;
@@ -28,9 +27,15 @@ public class ErrorPacket implements IServerToClientPacket {
@JsonIgnore @JsonIgnore
public void onHandle(WebSocket webSocket, SocketClient socketClient) { public void onHandle(WebSocket webSocket, SocketClient socketClient) {
SocketClient.logger.exception(new RuntimeException(this.error)); System.err.println("[socket] " + "ErrorPacket: " + this.error);
if (this.isFatal) { if (this.isFatal) {
socketClient.close(1, "Received fatal error from server"); throw new RuntimeException("Received fatal error from server: " + this.error);
} }
} }
@JsonIgnore
public void onHandle(WebSocket webSocket, SocketServer socketServer) {
socketServer.log("ErrorPacket: " + this.error, webSocket);
}
} }

View File

@@ -1,26 +1,12 @@
package de.dhbwstuttgart.server.packet; package de.dhbwstuttgart.server.packet;
import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnore;
import de.dhbwstuttgart.server.SocketFuture;
import de.dhbwstuttgart.server.SocketServer; import de.dhbwstuttgart.server.SocketServer;
import org.java_websocket.WebSocket; import org.java_websocket.WebSocket;
/** public interface IClientToServerPacket extends IPacket {
* A packet that will be sent to the server. Use <code>Void</code> Sub-Interface for packets without response
*
* @param <T> The response packet that will fulfill the future.
*/
public interface IClientToServerPacket<T extends IServerToClientPacket> extends IPacket {
@JsonIgnore @JsonIgnore
void onHandle(WebSocket webSocket, SocketServer socketServer); void onHandle(WebSocket webSocket, SocketServer socketServer);
@JsonIgnore
SocketFuture<T> getFuture();
/**
* Special case, where the packet will remain unanswered by the server
*/
interface Void extends IClientToServerPacket<IServerToClientPacket> {}
} }

View File

@@ -2,14 +2,13 @@ package de.dhbwstuttgart.server.packet;
import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnore;
import de.dhbwstuttgart.server.SocketClient; import de.dhbwstuttgart.server.SocketClient;
import de.dhbwstuttgart.server.SocketFuture;
import de.dhbwstuttgart.server.SocketServer; import de.dhbwstuttgart.server.SocketServer;
import org.java_websocket.WebSocket; import org.java_websocket.WebSocket;
/** /**
* A fallback packet that is generated if the received JSON could not be mapped to an existing package * A fallback packet that is generated, if the received json could not be mapped to an existing package
*/ */
public class InvalidPacket implements IClientToServerPacket.Void, IServerToClientPacket { public class InvalidPacket implements IClientToServerPacket, IServerToClientPacket {
/** /**
* If available, the error that caused this package to appear * If available, the error that caused this package to appear
@@ -19,17 +18,12 @@ public class InvalidPacket implements IClientToServerPacket.Void, IServerToClien
@JsonIgnore @JsonIgnore
public void onHandle(WebSocket webSocket, SocketClient socketClient) { public void onHandle(WebSocket webSocket, SocketClient socketClient) {
SocketClient.logger.error("InvalidPacket: " + this.error); System.err.println("[socket] " + "InvalidPacket: " + this.error);
} }
@JsonIgnore @JsonIgnore
public void onHandle(WebSocket webSocket, SocketServer socketServer) { public void onHandle(WebSocket webSocket, SocketServer socketServer) {
socketServer.log(webSocket, "InvalidPacket: " + this.error); socketServer.log("InvalidPacket: " + this.error, webSocket);
}
@JsonIgnore
public SocketFuture<IServerToClientPacket> getFuture() {
return SocketFuture.completedFuture();
} }
} }

View File

@@ -2,17 +2,16 @@ package de.dhbwstuttgart.server.packet;
import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnore;
import de.dhbwstuttgart.server.SocketClient; import de.dhbwstuttgart.server.SocketClient;
import de.dhbwstuttgart.server.SocketFuture;
import de.dhbwstuttgart.server.SocketServer; import de.dhbwstuttgart.server.SocketServer;
import org.java_websocket.WebSocket; import org.java_websocket.WebSocket;
/** /**
* A packet to send simple informational messages between the client and the server * A packet to send simple informational messages between the client and the server
*/ */
public class MessagePacket implements IClientToServerPacket.Void, IServerToClientPacket { public class MessagePacket implements IClientToServerPacket, IServerToClientPacket {
/** /**
* The informational message from the server that should be logged out outputted * The informational message from the server, that should be logged out outputted
*/ */
public String message; public String message;
@@ -25,16 +24,13 @@ public class MessagePacket implements IClientToServerPacket.Void, IServerToClien
@JsonIgnore @JsonIgnore
public void onHandle(WebSocket webSocket, SocketClient socketClient) { public void onHandle(WebSocket webSocket, SocketClient socketClient) {
SocketClient.logger.info("SocketMessage: " + this.message); System.err.println("[socket] " + this.message);
} }
@JsonIgnore @JsonIgnore
public void onHandle(WebSocket webSocket, SocketServer socketServer) { public void onHandle(WebSocket webSocket, SocketServer socketServer) {
socketServer.log(webSocket, this.message); socketServer.log(this.message, webSocket);
} }
@JsonIgnore
public SocketFuture<IServerToClientPacket> getFuture() {
return SocketFuture.completedFuture();
}
} }

View File

@@ -3,7 +3,6 @@ package de.dhbwstuttgart.server.packet;
import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import de.dhbwstuttgart.util.Logger;
/** /**
* A wrapper for the packet to ensure correct serialization/deserialization and make it possible to detect the matching * A wrapper for the packet to ensure correct serialization/deserialization and make it possible to detect the matching
@@ -25,14 +24,13 @@ public class PacketContainer {
public UnifyRequestPacket unifyRequestPacket = null; public UnifyRequestPacket unifyRequestPacket = null;
public UnifyResultPacket unifyResultPacket = null; public UnifyResultPacket unifyResultPacket = null;
public DebugPacket debugPacket = null; public DebugPacket debugPacket = null;
public SetAutoclosePacket setAutoclosePacket = null;
/** /**
* Generate the JSON string for the given packet * Generate the JSON string for the given packet
* *
* @param packet The packet to serialize * @param packet The packet to serialize
* @return The JSON representation of the packet * @return The json representation of the packet
*/ */
public static String serialize(IPacket packet) throws JsonProcessingException { public static String serialize(IPacket packet) throws JsonProcessingException {
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
@@ -48,11 +46,7 @@ public class PacketContainer {
container.unifyResultPacket = (UnifyResultPacket) packet; container.unifyResultPacket = (UnifyResultPacket) packet;
else if (packet instanceof DebugPacket) else if (packet instanceof DebugPacket)
container.debugPacket = (DebugPacket) packet; container.debugPacket = (DebugPacket) packet;
else if (packet instanceof SetAutoclosePacket)
container.setAutoclosePacket = (SetAutoclosePacket) packet;
// Add new packets here and in the deserialize method // Add new packets here and in the deserialize method
else
throw new RuntimeException("Cannot map packet to any known packet class");
return objectMapper.writeValueAsString(container); return objectMapper.writeValueAsString(container);
} }
@@ -81,13 +75,11 @@ public class PacketContainer {
return container.unifyResultPacket; return container.unifyResultPacket;
if (container.debugPacket != null) if (container.debugPacket != null)
return container.debugPacket; return container.debugPacket;
if (container.setAutoclosePacket != null)
return container.setAutoclosePacket;
// Add new packets here and in the serialize method // Add new packets here and in the serialize method
throw new RuntimeException("Cannot map received json to any known packet class"); throw new RuntimeException("Cannot map received json to any known packet class");
} catch (Exception e) { } catch (Exception e) {
(new Logger()).exception(e); System.out.println(e);
InvalidPacket packet = new InvalidPacket(); InvalidPacket packet = new InvalidPacket();
packet.error = e.getMessage(); packet.error = e.getMessage();
return packet; return packet;

View File

@@ -1,32 +0,0 @@
package de.dhbwstuttgart.server.packet;
import com.fasterxml.jackson.annotation.JsonIgnore;
import de.dhbwstuttgart.server.SocketClient;
import de.dhbwstuttgart.server.SocketFuture;
import de.dhbwstuttgart.server.SocketServer;
import org.java_websocket.WebSocket;
/**
* Normally, a connection stays open until either the client or the server process ends.
* Send this packet to inform the server that the connection can be closed once all tasks are done
*/
public class SetAutoclosePacket implements IClientToServerPacket.Void {
public int dummyProperty = 1;
@JsonIgnore
public static SetAutoclosePacket create() {
return new SetAutoclosePacket();
}
@JsonIgnore
public void onHandle(WebSocket webSocket, SocketServer socketServer) {
webSocket.<SocketServer.SocketData>getAttachment().closeIfNoTasksLeft = true;
socketServer.log(webSocket, "Marked connection as autoclose");
}
@JsonIgnore
public SocketFuture<IServerToClientPacket> getFuture() {
return SocketFuture.completedFuture();
}
}

View File

@@ -1,9 +1,6 @@
package de.dhbwstuttgart.server.packet; package de.dhbwstuttgart.server.packet;
import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnore;
import de.dhbwstuttgart.core.ConsoleInterface;
import de.dhbwstuttgart.server.ServerTaskLogger;
import de.dhbwstuttgart.server.SocketFuture;
import de.dhbwstuttgart.server.SocketServer; import de.dhbwstuttgart.server.SocketServer;
import de.dhbwstuttgart.server.packet.dataContainers.KeyStorage; import de.dhbwstuttgart.server.packet.dataContainers.KeyStorage;
import de.dhbwstuttgart.server.packet.dataContainers.serialized.SerialList; import de.dhbwstuttgart.server.packet.dataContainers.serialized.SerialList;
@@ -22,17 +19,18 @@ import de.dhbwstuttgart.typeinference.unify.model.FiniteClosure;
import de.dhbwstuttgart.typeinference.unify.model.PlaceholderType; import de.dhbwstuttgart.typeinference.unify.model.PlaceholderType;
import de.dhbwstuttgart.typeinference.unify.model.UnifyPair; import de.dhbwstuttgart.typeinference.unify.model.UnifyPair;
import de.dhbwstuttgart.typeinference.unify.model.UnifyType; import de.dhbwstuttgart.typeinference.unify.model.UnifyType;
import de.dhbwstuttgart.util.Logger; import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashSet; import java.util.HashSet;
import java.util.List;
import java.util.concurrent.ForkJoinPool; import java.util.concurrent.ForkJoinPool;
import org.java_websocket.WebSocket; import org.java_websocket.WebSocket;
/** /**
* A packet to send all required data for the unification algorithm to the server and request the unification * A packet to send all required data for the unification algorithm to the server and request the unification
*/ */
public class UnifyRequestPacket implements IClientToServerPacket<UnifyResultPacket> { public class UnifyRequestPacket implements IClientToServerPacket {
public SerialMap finiteClosure; public SerialMap finiteClosure;
public SerialMap constraintSet; public SerialMap constraintSet;
@@ -40,33 +38,30 @@ public class UnifyRequestPacket implements IClientToServerPacket<UnifyResultPack
public SerialMap serialKeyStorage; public SerialMap serialKeyStorage;
public SerialValue<?> placeholders; public SerialValue<?> placeholders;
public SerialList<SerialMap> factoryplaceholders; public SerialList<SerialMap> factoryplaceholders;
public String futureId;
public int logLevel;
@JsonIgnore @JsonIgnore
private KeyStorage keyStorage = new KeyStorage(); private KeyStorage keyStorage = new KeyStorage();
@JsonIgnore @JsonIgnore
private boolean keyStorageLoaded = false; private boolean keyStorageLoaded = false;
public static UnifyRequestPacket create( public UnifyRequestPacket() {}
public UnifyRequestPacket(
FiniteClosure finiteClosure, FiniteClosure finiteClosure,
ConstraintSet<Pair> constraintSet, ConstraintSet<Pair> constraintSet,
ConstraintSet<UnifyPair> unifyConstraintSet, ConstraintSet<UnifyPair> unifyConstraintSet,
PlaceholderRegistry placeholderRegistry PlaceholderRegistry placeholderRegistry
) { ) {
UnifyRequestPacket packet = new UnifyRequestPacket(); // store contraint and finite closure
// store constraint and finite closure this.finiteClosure = finiteClosure.toSerial(keyStorage);
packet.finiteClosure = finiteClosure.toSerial(packet.keyStorage); this.constraintSet = constraintSet.toSerial(keyStorage);
packet.constraintSet = constraintSet.toSerial(packet.keyStorage); this.unifyConstraintSet = unifyConstraintSet.toSerial(keyStorage);
packet.unifyConstraintSet = unifyConstraintSet.toSerial(packet.keyStorage);
// store placeholder registry // store placeholder registry
var serialRegistry = placeholderRegistry.toSerial(packet.keyStorage); var serialRegistry = placeholderRegistry.toSerial(keyStorage);
packet.placeholders = serialRegistry.getValue("ph"); this.placeholders = serialRegistry.getValue("ph");
packet.factoryplaceholders = serialRegistry.getList("factoryPh").assertListOfMaps(); this.factoryplaceholders = serialRegistry.getList("factoryPh").assertListOfMaps();
// store referenced objects separately // store referenced objects separately
packet.serialKeyStorage = packet.keyStorage.toSerial(packet.keyStorage); this.serialKeyStorage = keyStorage.toSerial(keyStorage);
packet.logLevel = ConsoleInterface.logLevel.getValue();
return packet;
} }
@@ -99,22 +94,15 @@ public class UnifyRequestPacket implements IClientToServerPacket<UnifyResultPack
@JsonIgnore @JsonIgnore
public void onHandle(WebSocket webSocket, SocketServer socketServer) { public void onHandle(WebSocket webSocket, SocketServer socketServer) {
socketServer.sendMessage(webSocket, "You requested a unify! Please wait until I calculated everything..."); socketServer.sendMessage(webSocket, "You requested a unify! Please wait until I calculated everything...");
socketServer.log(webSocket, "Client requested a unification. Starting now..."); System.out.println("Client " + webSocket.<SocketServer.SocketData>getAttachment().id + " requested a unification. Starting now...");
try { try {
var placeholderRegistry = new PlaceholderRegistry(); var placeholderRegistry = new PlaceholderRegistry();
ArrayList<String> existingPlaceholders = (ArrayList) this.placeholders.getOf(ArrayList.class); ArrayList<String> existingPlaceholders = (ArrayList) this.placeholders.getOf(ArrayList.class);
existingPlaceholders.forEach(placeholderRegistry::addPlaceholder); existingPlaceholders.forEach(placeholderRegistry::addPlaceholder);
Logger logger = new ServerTaskLogger( var unifyContext = new UnifyContext(Writer.nullWriter(), false, true,
webSocket, new UnifyResultModel(new ConstraintSet<>(), new FiniteClosure(new HashSet<>(), null, placeholderRegistry)),
socketServer,
Logger.LogLevel.fromValue(
Math.max(this.logLevel, Logger.LogLevel.INFO.getValue())
)
);
var unifyContext = new UnifyContext(logger, true,
new UnifyResultModel(new ConstraintSet<>(), new FiniteClosure(new HashSet<>(), logger, placeholderRegistry)),
new UnifyTaskModel(), ForkJoinPool.commonPool(), placeholderRegistry new UnifyTaskModel(), ForkJoinPool.commonPool(), placeholderRegistry
); );
@@ -141,24 +129,17 @@ public class UnifyRequestPacket implements IClientToServerPacket<UnifyResultPack
var resultSets = resultListener.getResults(); var resultSets = resultListener.getResults();
socketServer.log(webSocket, "Finished unification"); System.out.println("Finished unification for client " + webSocket.<SocketServer.SocketData>getAttachment().id);
socketServer.sendMessage(webSocket, "Unification finished. Found " + resultSets.size() + " result sets"); socketServer.sendMessage(webSocket, "Unification finished. Found " + resultSets.size() + " result sets");
if (webSocket.isOpen()) { if (webSocket.isOpen()) {
UnifyResultPacket resultPacket = UnifyResultPacket.create(resultSets, futureId); UnifyResultPacket resultPacket = UnifyResultPacket.create(resultSets);
webSocket.send(PacketContainer.serialize(resultPacket)); webSocket.send(PacketContainer.serialize(resultPacket));
} }
} catch (Exception e) { } catch (Exception e) {
SocketServer.logger.exception(e); System.err.println(e);
socketServer.log(webSocket, e.getMessage()); SocketServer.log.error("e: ", e);
} }
} }
@JsonIgnore
public SocketFuture<UnifyResultPacket> getFuture() {
var future = new SocketFuture<>(List.of(UnifyResultPacket.class));
futureId = future.futureId;
return future;
}
} }

View File

@@ -18,14 +18,12 @@ public class UnifyResultPacket implements IServerToClientPacket {
public SerialList<ISerialNode> results; public SerialList<ISerialNode> results;
public SerialMap keyStorage; public SerialMap keyStorage;
public String futureId;
public static UnifyResultPacket create(List<ResultSet> resultSets, String futureId) { public static UnifyResultPacket create(List<ResultSet> resultSets) {
UnifyResultPacket serialized = new UnifyResultPacket(); UnifyResultPacket serialized = new UnifyResultPacket();
KeyStorage keyStorage = new KeyStorage(); KeyStorage keyStorage = new KeyStorage();
serialized.results = SerialList.fromMapped(resultSets, resultSet -> resultSet.toSerial(keyStorage)); serialized.results = SerialList.fromMapped(resultSets, resultSet -> resultSet.toSerial(keyStorage));
serialized.keyStorage = keyStorage.toSerial(keyStorage); serialized.keyStorage = keyStorage.toSerial(keyStorage);
serialized.futureId = futureId;
return serialized; return serialized;
} }
@@ -37,8 +35,8 @@ public class UnifyResultPacket implements IServerToClientPacket {
@JsonIgnore @JsonIgnore
public void onHandle(WebSocket webSocket, SocketClient socketClient) { public void onHandle(WebSocket webSocket, SocketClient socketClient) {
SocketClient.logger.info("Received unify result"); System.out.println("[socket] Received unify result");
socketClient.completeResponseFuture(futureId, this); socketClient.setUnifyResultSets(this);
} }

View File

@@ -3,7 +3,7 @@ package de.dhbwstuttgart.server.packet.dataContainers.serialized;
import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnore;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import org.jspecify.annotations.Nullable; import javax.annotation.Nullable;
public class SerialMap extends HashMap<String, ISerialNode> implements ISerialNode { public class SerialMap extends HashMap<String, ISerialNode> implements ISerialNode {

View File

@@ -6,12 +6,10 @@ import de.dhbwstuttgart.syntaxtree.type.GenericRefType;
import de.dhbwstuttgart.syntaxtree.type.RefType; import de.dhbwstuttgart.syntaxtree.type.RefType;
import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder; import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder;
import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric; import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric;
import de.dhbwstuttgart.target.tree.TargetGeneric;
import org.antlr.v4.runtime.Token; import org.antlr.v4.runtime.Token;
import java.lang.reflect.Modifier; import java.lang.reflect.Modifier;
import java.util.*; import java.util.*;
import java.util.stream.Collectors;
/** /**
* Stellt jede Art von Klasse dar. Auch abstrakte Klassen und Interfaces * Stellt jede Art von Klasse dar. Auch abstrakte Klassen und Interfaces
@@ -33,7 +31,6 @@ public class ClassOrInterface extends SyntaxTreeNode implements TypeScope {
private List<RefType> implementedInterfaces; private List<RefType> implementedInterfaces;
private List<RefType> permittedSubtypes; private List<RefType> permittedSubtypes;
private List<Constructor> constructors; private List<Constructor> constructors;
private Set<GenericTypeVar> userDefinedGenerics;
public ClassOrInterface(int modifiers, JavaClassName name, List<Field> fielddecl, Optional<Constructor> fieldInitializations, Optional<Method> staticInitializer, List<Method> methods, List<Constructor> constructors, GenericDeclarationList genericClassParameters, RefType superClass, Boolean isInterface, Boolean isFunctionalInterface, List<RefType> implementedInterfaces, List<RefType> permittedSubtypes, Token offset, String fileName) { public ClassOrInterface(int modifiers, JavaClassName name, List<Field> fielddecl, Optional<Constructor> fieldInitializations, Optional<Method> staticInitializer, List<Method> methods, List<Constructor> constructors, GenericDeclarationList genericClassParameters, RefType superClass, Boolean isInterface, Boolean isFunctionalInterface, List<RefType> implementedInterfaces, List<RefType> permittedSubtypes, Token offset, String fileName) {
super(offset); super(offset);
@@ -202,22 +199,4 @@ public class ClassOrInterface extends SyntaxTreeNode implements TypeScope {
public int hashCode() { public int hashCode() {
return Objects.hash(name); return Objects.hash(name);
} }
public Set<GenericTypeVar> getUserDefinedGenerics() {
if (this.userDefinedGenerics != null) return this.userDefinedGenerics;
var genericsIter = getGenerics().iterator();
if (genericsIter.hasNext()) {
// Add empty set of generics to cache so that it doesn't try to calculate it later
this.userDefinedGenerics = new HashSet<>();
while (genericsIter.hasNext()) {
var next = genericsIter.next();
userDefinedGenerics.add(next);
}
} else {
this.userDefinedGenerics = new HashSet<>();
}
return this.userDefinedGenerics;
}
} }

View File

@@ -5,10 +5,8 @@ import java.util.*;
import de.dhbwstuttgart.parser.NullToken; import de.dhbwstuttgart.parser.NullToken;
import de.dhbwstuttgart.parser.scope.JavaClassName; import de.dhbwstuttgart.parser.scope.JavaClassName;
import de.dhbwstuttgart.target.generate.ASTToTargetAST;
import de.dhbwstuttgart.typeinference.constraints.ConstraintSet; import de.dhbwstuttgart.typeinference.constraints.ConstraintSet;
import de.dhbwstuttgart.typeinference.assumptions.TypeInferenceInformation; import de.dhbwstuttgart.typeinference.assumptions.TypeInferenceInformation;
import de.dhbwstuttgart.typeinference.result.ResultSet;
//import sun.security.x509.X509CertInfo; //import sun.security.x509.X509CertInfo;
public class SourceFile extends SyntaxTreeNode { public class SourceFile extends SyntaxTreeNode {
@@ -20,7 +18,6 @@ public class SourceFile extends SyntaxTreeNode {
private boolean isGenerated; private boolean isGenerated;
public List<ClassOrInterface> availableClasses = new ArrayList<>(); public List<ClassOrInterface> availableClasses = new ArrayList<>();
public List<ASTToTargetAST.Generics> generics = new ArrayList<>();
/** /**
* Die SourceFile repräsntiert eine zu einem Syntaxbaum eingelesene Java-Datei. * Die SourceFile repräsntiert eine zu einem Syntaxbaum eingelesene Java-Datei.
@@ -43,10 +40,6 @@ public class SourceFile extends SyntaxTreeNode {
this.imports = new HashSet<>(sf.imports); this.imports = new HashSet<>(sf.imports);
} }
public void addResultSet(ResultSet rs) {
}
public void setPackageName(String packageName) { public void setPackageName(String packageName) {
this.pkgName = packageName; this.pkgName = packageName;
} }

View File

@@ -1,8 +0,0 @@
package de.dhbwstuttgart.syntaxtree;
import de.dhbwstuttgart.util.Logger;
public class SyntaxTree {
public static Logger logger = new Logger("SyntaxTree");
}

View File

@@ -16,10 +16,6 @@ public class NameGenerator {
public static void reset() { public static void reset() {
strNextName = "A"; strNextName = "A";
} }
public static void resetTo(String name) {
strNextName = name;
}
/** /**
* Berechnet einen neuen, eindeutigen Namen f�r eine neue * Berechnet einen neuen, eindeutigen Namen f�r eine neue

View File

@@ -1,8 +1,6 @@
package de.dhbwstuttgart.syntaxtree.factory; package de.dhbwstuttgart.syntaxtree.factory;
import de.dhbwstuttgart.syntaxtree.SyntaxTree;
import de.dhbwstuttgart.typeinference.unify.PlaceholderRegistry; import de.dhbwstuttgart.typeinference.unify.PlaceholderRegistry;
import de.dhbwstuttgart.util.Logger;
import java.io.Writer; import java.io.Writer;
import java.lang.reflect.Modifier; import java.lang.reflect.Modifier;
import java.util.*; import java.util.*;
@@ -36,7 +34,7 @@ public class UnifyTypeFactory {
public static FiniteClosure generateFC( public static FiniteClosure generateFC(
List<ClassOrInterface> fromClasses, List<ClassOrInterface> fromClasses,
Logger logger, Writer logFile,
ClassLoader classLoader, ClassLoader classLoader,
JavaTXCompiler compiler, JavaTXCompiler compiler,
PlaceholderRegistry placeholderRegistry PlaceholderRegistry placeholderRegistry
@@ -51,7 +49,7 @@ public class UnifyTypeFactory {
Generell dürfen sie immer die gleichen Namen haben. Generell dürfen sie immer die gleichen Namen haben.
TODO: die transitive Hülle bilden TODO: die transitive Hülle bilden
*/ */
return new FiniteClosure(FCGenerator.toUnifyFC(compiler, fromClasses, classLoader, placeholderRegistry), logger, compiler, placeholderRegistry); return new FiniteClosure(FCGenerator.toUnifyFC(compiler, fromClasses, classLoader, placeholderRegistry), logFile, compiler, placeholderRegistry);
} }
public static UnifyPair generateSmallerPair(UnifyType tl, UnifyType tr, SourceLoc location){ public static UnifyPair generateSmallerPair(UnifyType tl, UnifyType tr, SourceLoc location){
@@ -134,7 +132,7 @@ public class UnifyTypeFactory {
public static UnifyType convert(JavaTXCompiler compiler, TypePlaceholder tph, Boolean innerType, PlaceholderRegistry placeholderRegistry) { public static UnifyType convert(JavaTXCompiler compiler, TypePlaceholder tph, Boolean innerType, PlaceholderRegistry placeholderRegistry) {
if (tph.getName().equals("AFR")) { if (tph.getName().equals("AFR")) {
SyntaxTree.logger.info("XXX"+innerType); System.out.println("XXX"+innerType);
} }
PlaceholderType ntph = new PlaceholderType(tph.getName(), tph.getVariance(), placeholderRegistry); PlaceholderType ntph = new PlaceholderType(tph.getName(), tph.getVariance(), placeholderRegistry);
ntph.setVariance(tph.getVariance()); ntph.setVariance(tph.getVariance());
@@ -201,7 +199,7 @@ public class UnifyTypeFactory {
&& ((PlaceholderType)lhs).isWildcardable() && ((PlaceholderType)lhs).isWildcardable()
&& (rhs = ret.getLhsType()) instanceof PlaceholderType) { && (rhs = ret.getLhsType()) instanceof PlaceholderType) {
if (lhs.getName().equals("AQ")) { if (lhs.getName().equals("AQ")) {
// SyntaxTree.logger.info(""); // System.out.println("");
} }
((PlaceholderType)rhs).enableWildcardtable(); ((PlaceholderType)rhs).enableWildcardtable();
} }
@@ -210,7 +208,7 @@ public class UnifyTypeFactory {
&& ((PlaceholderType)rhs).isWildcardable() && ((PlaceholderType)rhs).isWildcardable()
&& (lhs = ret.getLhsType()) instanceof PlaceholderType) { && (lhs = ret.getLhsType()) instanceof PlaceholderType) {
if (rhs.getName().equals("AQ")) { if (rhs.getName().equals("AQ")) {
// SyntaxTree.logger.info(""); // System.out.println("");
} }
((PlaceholderType)lhs).enableWildcardtable(); ((PlaceholderType)lhs).enableWildcardtable();
} }

View File

@@ -1,8 +0,0 @@
package de.dhbwstuttgart.target;
import de.dhbwstuttgart.util.Logger;
public class Target {
public static Logger logger = new Logger("Target");
}

View File

@@ -1,8 +1,8 @@
package de.dhbwstuttgart.target.generate; package de.dhbwstuttgart.target.generate;
import de.dhbwstuttgart.bytecode.FunNGenerator; import de.dhbwstuttgart.bytecode.FunNGenerator;
import de.dhbwstuttgart.core.JavaTXCompiler; import de.dhbwstuttgart.core.JavaTXCompiler;
import de.dhbwstuttgart.environment.ByteArrayClassLoader;
import de.dhbwstuttgart.environment.IByteArrayClassLoader; import de.dhbwstuttgart.environment.IByteArrayClassLoader;
import de.dhbwstuttgart.exceptions.DebugException; import de.dhbwstuttgart.exceptions.DebugException;
import de.dhbwstuttgart.parser.NullToken; import de.dhbwstuttgart.parser.NullToken;
@@ -12,9 +12,6 @@ import de.dhbwstuttgart.syntaxtree.Record;
import de.dhbwstuttgart.syntaxtree.factory.ASTFactory; import de.dhbwstuttgart.syntaxtree.factory.ASTFactory;
import de.dhbwstuttgart.syntaxtree.statement.*; import de.dhbwstuttgart.syntaxtree.statement.*;
import de.dhbwstuttgart.syntaxtree.type.*; import de.dhbwstuttgart.syntaxtree.type.*;
import de.dhbwstuttgart.syntaxtree.visual.ASTPrinter;
import de.dhbwstuttgart.syntaxtree.visual.OutputGenerator;
import de.dhbwstuttgart.target.Target;
import de.dhbwstuttgart.target.tree.*; import de.dhbwstuttgart.target.tree.*;
import de.dhbwstuttgart.target.tree.expression.*; import de.dhbwstuttgart.target.tree.expression.*;
import de.dhbwstuttgart.target.tree.type.*; import de.dhbwstuttgart.target.tree.type.*;
@@ -38,6 +35,7 @@ public class ASTToTargetAST {
public Generics generics; public Generics generics;
public List<Generics> currentMethodOverloads; public List<Generics> currentMethodOverloads;
final Map<ClassOrInterface, Set<GenericTypeVar>> userDefinedGenerics = new HashMap<>();
final Map<Method, Set<SignaturePair>> tphsInMethods = new HashMap<>(); final Map<Method, Set<SignaturePair>> tphsInMethods = new HashMap<>();
private Method currentMethod; private Method currentMethod;
@@ -62,19 +60,17 @@ public class ASTToTargetAST {
} }
public record Generics(JavaGenerics javaGenerics, TxGenerics txGenerics) { public record Generics(JavaGenerics javaGenerics, TxGenerics txGenerics) {
public Generics(JavaTXCompiler compiler, ResultSet set) {
this(new JavaGenerics(compiler, set), new TxGenerics(compiler, set));
}
} }
public IByteArrayClassLoader classLoader; public IByteArrayClassLoader classLoader;
protected SourceFile sourceFile; protected SourceFile sourceFile;
public ASTToTargetAST(List<ResultSet> resultSets, IByteArrayClassLoader classLoader) { public ASTToTargetAST(List<ResultSet> resultSets) {
this(null, resultSets, classLoader); this(null, resultSets);
} }
public ASTToTargetAST(JavaTXCompiler compiler, List<ResultSet> resultSets, IByteArrayClassLoader classLoader) { public ASTToTargetAST(JavaTXCompiler compiler, List<ResultSet> resultSets) {
this(compiler, resultSets, null, classLoader); this(compiler, resultSets, null, new ByteArrayClassLoader());
} }
public ASTToTargetAST(JavaTXCompiler compiler, List<ResultSet> resultSets, SourceFile sourceFile, IByteArrayClassLoader classLoader) { public ASTToTargetAST(JavaTXCompiler compiler, List<ResultSet> resultSets, SourceFile sourceFile, IByteArrayClassLoader classLoader) {
@@ -84,9 +80,9 @@ public class ASTToTargetAST {
all = new ArrayList<>(); all = new ArrayList<>();
for (var set : resultSets) { for (var set : resultSets) {
all.add(new Generics(compiler, set)); all.add(new Generics(new JavaGenerics(this, set), new TxGenerics(this, set)));
} }
this.generics = all.getFirst(); this.generics = all.get(0);
} }
public void addSignaturePair(TypePlaceholder signature, RefTypeOrTPHOrWildcardOrGeneric parameter) { public void addSignaturePair(TypePlaceholder signature, RefTypeOrTPHOrWildcardOrGeneric parameter) {
@@ -96,13 +92,9 @@ public class ASTToTargetAST {
} }
Optional<Method> findMethod(ClassOrInterface owner, String name, List<TargetType> argumentList) { Optional<Method> findMethod(ClassOrInterface owner, String name, List<TargetType> argumentList) {
return findMethod(owner, name, argumentList, this.generics.javaGenerics, this.compiler);
}
public static Optional<Method> findMethod(ClassOrInterface owner, String name, List<TargetType> argumentList, GenerateGenerics generics, JavaTXCompiler compiler) {
Optional<Method> method = Optional.empty(); Optional<Method> method = Optional.empty();
while (method.isEmpty()) { while (method.isEmpty()) {
method = owner.getMethods().stream().filter(m -> m.name.equals(name) && parameterEquals(m.getParameterList(), argumentList, generics)).findFirst(); method = owner.getMethods().stream().filter(m -> m.name.equals(name) && parameterEquals(m.getParameterList(), argumentList)).findFirst();
if (owner.getClassName().toString().equals("java.lang.Object")) break; if (owner.getClassName().toString().equals("java.lang.Object")) break;
owner = compiler.getClass(owner.getSuperClass().getName()); owner = compiler.getClass(owner.getSuperClass().getName());
} }
@@ -110,16 +102,16 @@ public class ASTToTargetAST {
} }
Optional<Constructor> findConstructor(ClassOrInterface owner, List<TargetType> argumentList) { Optional<Constructor> findConstructor(ClassOrInterface owner, List<TargetType> argumentList) {
return owner.getConstructors().stream().filter(c -> parameterEquals(c.getParameterList(), argumentList, generics.javaGenerics)).findFirst(); return owner.getConstructors().stream().filter(c -> parameterEquals(c.getParameterList(), argumentList)).findFirst();
} }
static boolean parameterEquals(ParameterList parameterList, List<TargetType> arguments, GenerateGenerics generics) { boolean parameterEquals(ParameterList parameterList, List<TargetType> arguments) {
var pars = parameterList.getFormalparalist(); var pars = parameterList.getFormalparalist();
if (pars.size() != arguments.size()) if (pars.size() != arguments.size())
return false; return false;
for (var i = 0; i < pars.size(); i++) { for (var i = 0; i < pars.size(); i++) {
var type1 = generics.getTargetType(pars.get(i).getType()); var type1 = convert(pars.get(i).getType(), generics.javaGenerics);
var type2 = arguments.get(i); var type2 = arguments.get(i);
if (type1 instanceof TargetGenericType) if (type1 instanceof TargetGenericType)
return true; return true;
@@ -345,10 +337,10 @@ public class ASTToTargetAST {
var result = r0.stream().map(l -> l.stream().toList()).toList(); var result = r0.stream().map(l -> l.stream().toList()).toList();
Target.logger.info("============== OUTPUT =============="); System.out.println("============== OUTPUT ==============");
for (var l : result) { for (var l : result) {
for (var m : l) Target.logger.info(m.name() + " " + m.getSignature()); for (var m : l) System.out.println(m.name() + " " + m.getSignature());
Target.logger.info(""); System.out.println();
} }
return result; return result;
} }
@@ -357,14 +349,19 @@ public class ASTToTargetAST {
Set<TargetGeneric> javaGenerics = new HashSet<>(); Set<TargetGeneric> javaGenerics = new HashSet<>();
Set<TargetGeneric> txGenerics = new HashSet<>(); Set<TargetGeneric> txGenerics = new HashSet<>();
var userDefinedGenerics = input.getUserDefinedGenerics(); var genericsIter = input.getGenerics().iterator();
if (!userDefinedGenerics.isEmpty()) { if (genericsIter.hasNext()) {
// Add empty set of generics to cache so that it doesn't try to calculate it later // Add empty set of generics to cache so that it doesn't try to calculate it later
for (var generic : userDefinedGenerics) { var userDefinedGenerics = new HashSet<GenericTypeVar>();
// TODO Support multiple bouds this.userDefinedGenerics.put(input, userDefinedGenerics);
javaGenerics.add(new TargetGeneric(generic.getName(), convert(generic.getBounds().getFirst()))); while (genericsIter.hasNext()) {
var next = genericsIter.next();
userDefinedGenerics.add(next);
// TODO Support multiple bounds
javaGenerics.add(new TargetGeneric(next.getName(), convert(next.getBounds().get(0))));
} }
} else { } else {
this.userDefinedGenerics.put(input, new HashSet<>());
// Generate generics only if there are no user defined ones // Generate generics only if there are no user defined ones
javaGenerics = convert(generics.javaGenerics.generics(input), generics.javaGenerics); javaGenerics = convert(generics.javaGenerics.generics(input), generics.javaGenerics);
txGenerics = convert(generics.txGenerics.generics(input), generics.txGenerics); txGenerics = convert(generics.txGenerics.generics(input), generics.txGenerics);
@@ -426,7 +423,7 @@ public class ASTToTargetAST {
} }
private List<TargetConstructor> convert(ClassOrInterface currentClass, Constructor input, TargetBlock fieldInitializer) { private List<TargetConstructor> convert(ClassOrInterface currentClass, Constructor input, TargetBlock fieldInitializer) {
generics = all.getFirst(); generics = all.get(0);
List<TargetConstructor> result = new ArrayList<>(); List<TargetConstructor> result = new ArrayList<>();
Set<List<MethodParameter>> parameterSet = new HashSet<>(); Set<List<MethodParameter>> parameterSet = new HashSet<>();
this.currentMethod = input; this.currentMethod = input;
@@ -470,6 +467,13 @@ public class ASTToTargetAST {
} }
} }
private TargetType unwrap(TargetType type) {
if (type instanceof TargetRefType ref) {
if (!ref.params().isEmpty()) return new TargetRefType(ref.name());
}
return type;
}
private TargetExpression generatePatternOverloadsRec(int offset, TargetExpression switchExpr, List<TargetLocalVar> params, List<TargetPattern> patterns, List<TargetMethod> methods, TargetType classType) { private TargetExpression generatePatternOverloadsRec(int offset, TargetExpression switchExpr, List<TargetLocalVar> params, List<TargetPattern> patterns, List<TargetMethod> methods, TargetType classType) {
if (methods.isEmpty()) throw new DebugException("Couldn't find a candidate for switch overloading"); if (methods.isEmpty()) throw new DebugException("Couldn't find a candidate for switch overloading");
if (methods.size() == 1) { if (methods.size() == 1) {
@@ -740,6 +744,11 @@ public class ASTToTargetAST {
return new TargetField(input.modifier, convert(input.getType(), generics.javaGenerics), input.getName()); return new TargetField(input.modifier, convert(input.getType(), generics.javaGenerics), input.getName());
} }
private final Map<String, FunNGenerator.GenericParameters> usedFunN = new HashMap<>();
private final Set<Integer> usedFunNSuperTypes = new HashSet<>();
public Map<String, byte[]> auxiliaries = new HashMap<>();
public TargetType convert(RefTypeOrTPHOrWildcardOrGeneric input) { public TargetType convert(RefTypeOrTPHOrWildcardOrGeneric input) {
return convert(input, generics.javaGenerics); return convert(input, generics.javaGenerics);
} }
@@ -772,15 +781,7 @@ public class ASTToTargetAST {
return TargetFunNType.fromParams(params, filteredParams, gep.getReturnType() != null ? 1 : 0); return TargetFunNType.fromParams(params, filteredParams, gep.getReturnType() != null ? 1 : 0);
} }
private FunNGenerator.GenericParameters convertToParameters(TargetFunNType input) {
return null;
}
private boolean isSubtype(TargetType test, TargetType other) { private boolean isSubtype(TargetType test, TargetType other) {
if (other.equals(TargetType.Object)) return true;
if (test instanceof TargetFunNType tfun && other instanceof TargetFunNType ofun)
return isSubtype(new FunNGenerator.GenericParameters(tfun), new FunNGenerator.GenericParameters(ofun));
var testClass = compiler.getClass(new JavaClassName(test.name())); var testClass = compiler.getClass(new JavaClassName(test.name()));
var otherClass = compiler.getClass(new JavaClassName(other.name())); var otherClass = compiler.getClass(new JavaClassName(other.name()));
if (testClass == null) return false; if (testClass == null) return false;
@@ -808,24 +809,28 @@ public class ASTToTargetAST {
} }
public void generateFunNTypes() { public void generateFunNTypes() {
for (var entry : compiler.usedFunN.entrySet()) { for (var entry : usedFunN.entrySet()) {
var gep = entry.getValue(); var gep = entry.getValue();
var superInterfaces = compiler.usedFunN.values().stream() var superInterfaces = usedFunN.values().stream()
.filter(g -> !g.equals(gep)) .filter(g -> !g.equals(gep))
.filter(genericParameters -> isSubtype(gep, genericParameters)) .filter(genericParameters -> isSubtype(gep, genericParameters))
.map(FunNGenerator::getSpecializedClassName) .map(FunNGenerator::getSpecializedClassName)
.toList(); .toList();
var code = FunNGenerator.generateSpecializedBytecode(gep, superInterfaces); var code = FunNGenerator.generateSpecializedBytecode(gep, superInterfaces);
compiler.auxiliaries.put(entry.getKey(), code);
try {
classLoader.findClass(entry.getKey());
} catch (ClassNotFoundException e) {
try {
classLoader.loadClass(code);
} catch (LinkageError ignored) {}
}
auxiliaries.put(entry.getKey(), code);
} }
} }
public TargetType convert(RefTypeOrTPHOrWildcardOrGeneric input, GenerateGenerics generics) { protected TargetType convert(RefTypeOrTPHOrWildcardOrGeneric input, GenerateGenerics generics) {
return convert(input, generics, compiler);
}
public static TargetType convert(RefTypeOrTPHOrWildcardOrGeneric input, GenerateGenerics generics, JavaTXCompiler compiler) {
return input.acceptTV(new TypeVisitor<>() { return input.acceptTV(new TypeVisitor<>() {
@Override @Override
public TargetType visit(RefType refType) { public TargetType visit(RefType refType) {
@@ -837,24 +842,31 @@ public class ASTToTargetAST {
} }
var params = refType.getParaList().stream().map(type -> { var params = refType.getParaList().stream().map(type -> {
return convert(type, generics, compiler); return convert(type, generics);
}).toList(); }).toList();
if (name.matches("Fun\\d+\\$\\$")) { // TODO This seems like a bad idea if (name.matches("Fun\\d+\\$\\$")) { // TODO This seems like a bad idea
var returnType = FunNGenerator.getReturnType(params); var returnType = FunNGenerator.getReturnType(params);
var className = FunNGenerator.getSpecializedClassName(FunNGenerator.getArguments(params), returnType); var className = FunNGenerator.getSpecializedClassName(FunNGenerator.getArguments(params), returnType);
if (!compiler.usedFunNSuperTypes.contains(params.size())) { if (!usedFunNSuperTypes.contains(params.size())) {
compiler.usedFunNSuperTypes.add(params.size()); usedFunNSuperTypes.add(params.size());
var code = FunNGenerator.generateSuperBytecode(params.size() - 1, returnType != null ? 1 : 0); var code = FunNGenerator.generateSuperBytecode(params.size() - 1, returnType != null ? 1 : 0);
var superClassName = FunNGenerator.getSuperClassName(params.size() - 1, returnType != null ? 1 : 0); var superClassName = FunNGenerator.getSuperClassName(params.size() - 1, returnType != null ? 1 : 0);
compiler.auxiliaries.put(superClassName, code); try {
classLoader.findClass(superClassName);
} catch (ClassNotFoundException e) {
try {
classLoader.loadClass(code);
} catch (LinkageError ignored) {}
}
auxiliaries.put(superClassName, code);
} }
FunNGenerator.GenericParameters gep = null; FunNGenerator.GenericParameters gep = null;
if (!compiler.usedFunN.containsKey(className)) { if (!usedFunN.containsKey(className)) {
gep = new FunNGenerator.GenericParameters(params, returnType != null ? 1 : 0); gep = new FunNGenerator.GenericParameters(params, returnType != null ? 1 : 0);
compiler.usedFunN.put(className, gep); usedFunN.put(className, gep);
} else { } else {
gep = compiler.usedFunN.get(className); gep = usedFunN.get(className);
} }
return flattenFunNType(params, gep); return flattenFunNType(params, gep);
} }
@@ -863,7 +875,7 @@ public class ASTToTargetAST {
@Override @Override
public TargetType visit(SuperWildcardType superWildcardType) { public TargetType visit(SuperWildcardType superWildcardType) {
return new TargetSuperWildcard(convert(superWildcardType.getInnerType(), generics, compiler)); return new TargetSuperWildcard(convert(superWildcardType.getInnerType(), generics));
} }
@Override @Override
@@ -873,7 +885,7 @@ public class ASTToTargetAST {
@Override @Override
public TargetType visit(ExtendsWildcardType extendsWildcardType) { public TargetType visit(ExtendsWildcardType extendsWildcardType) {
return new TargetExtendsWildcard(convert(extendsWildcardType.getInnerType(), generics, compiler)); return new TargetExtendsWildcard(convert(extendsWildcardType.getInnerType(), generics));
} }
@Override @Override

View File

@@ -1,13 +1,10 @@
package de.dhbwstuttgart.target.generate; package de.dhbwstuttgart.target.generate;
import de.dhbwstuttgart.core.JavaTXCompiler;
import de.dhbwstuttgart.parser.JavaTXParser;
import de.dhbwstuttgart.parser.NullToken; import de.dhbwstuttgart.parser.NullToken;
import de.dhbwstuttgart.syntaxtree.*; import de.dhbwstuttgart.syntaxtree.*;
import de.dhbwstuttgart.syntaxtree.statement.*; import de.dhbwstuttgart.syntaxtree.statement.*;
import de.dhbwstuttgart.syntaxtree.type.*; import de.dhbwstuttgart.syntaxtree.type.*;
import de.dhbwstuttgart.syntaxtree.type.Void; import de.dhbwstuttgart.syntaxtree.type.Void;
import de.dhbwstuttgart.target.Target;
import de.dhbwstuttgart.target.tree.type.TargetGenericType; import de.dhbwstuttgart.target.tree.type.TargetGenericType;
import de.dhbwstuttgart.target.tree.type.TargetType; import de.dhbwstuttgart.target.tree.type.TargetType;
import de.dhbwstuttgart.typeinference.result.PairTPHEqualTPH; import de.dhbwstuttgart.typeinference.result.PairTPHEqualTPH;
@@ -21,7 +18,7 @@ import java.util.stream.Stream;
public abstract class GenerateGenerics { public abstract class GenerateGenerics {
private final JavaTXCompiler compiler; private final ASTToTargetAST astToTargetAST;
public class TPH { public class TPH {
private final TypePlaceholder wrap; private final TypePlaceholder wrap;
@@ -137,21 +134,21 @@ public abstract class GenerateGenerics {
Map<TPH, RefTypeOrTPHOrWildcardOrGeneric> concreteTypes = new HashMap<>(); Map<TPH, RefTypeOrTPHOrWildcardOrGeneric> concreteTypes = new HashMap<>();
Map<TypePlaceholder, TypePlaceholder> equality = new HashMap<>(); Map<TypePlaceholder, TypePlaceholder> equality = new HashMap<>();
GenerateGenerics(JavaTXCompiler compiler, ResultSet constraints) { GenerateGenerics(ASTToTargetAST astToTargetAST, ResultSet constraints) {
this.compiler = compiler; this.astToTargetAST = astToTargetAST;
for (var constraint : constraints.results) { for (var constraint : constraints.results) {
if (constraint instanceof PairTPHsmallerTPH p) { if (constraint instanceof PairTPHsmallerTPH p) {
Target.logger.info(p.left + " " + p.left.getVariance()); System.out.println(p.left + " " + p.left.getVariance());
simplifiedConstraints.add(new PairLT(new TPH(p.left), new TPH(p.right))); simplifiedConstraints.add(new PairLT(new TPH(p.left), new TPH(p.right)));
} else if (constraint instanceof PairTPHEqualTPH p) { } else if (constraint instanceof PairTPHEqualTPH p) {
equality.put(p.getLeft(), p.getRight()); equality.put(p.getLeft(), p.getRight());
} else if (constraint instanceof PairTPHequalRefTypeOrWildcardType p) { } else if (constraint instanceof PairTPHequalRefTypeOrWildcardType p) {
Target.logger.info(p.left + " = " + p.right); System.out.println(p.left + " = " + p.right);
concreteTypes.put(new TPH(p.left), p.right); concreteTypes.put(new TPH(p.left), p.right);
} }
} }
Target.logger.info("Simplified constraints: " + simplifiedConstraints); System.out.println("Simplified constraints: " + simplifiedConstraints);
} }
/*public record GenericsState(Map<TPH, RefTypeOrTPHOrWildcardOrGeneric> concreteTypes, Map<TypePlaceholder, TypePlaceholder> equality) {} /*public record GenericsState(Map<TPH, RefTypeOrTPHOrWildcardOrGeneric> concreteTypes, Map<TypePlaceholder, TypePlaceholder> equality) {}
@@ -251,7 +248,7 @@ public abstract class GenerateGenerics {
equality.put(entry.getKey(), to); equality.put(entry.getKey(), to);
} }
} }
Target.logger.info(from + " -> " + to + " " + from.getVariance()); System.out.println(from + " -> " + to + " " + from.getVariance());
//from.setVariance(to.getVariance()); //from.setVariance(to.getVariance());
equality.put(from, to); equality.put(from, to);
referenced.remove(new TPH(from)); referenced.remove(new TPH(from));
@@ -284,7 +281,7 @@ public abstract class GenerateGenerics {
Set<TPH> typeVariablesOfClass, Set<TPH> typeVariablesOfClass,
Set<Pair> result Set<Pair> result
) { ) {
var userDefinedGenericsOfClass = owner.getUserDefinedGenerics(); var userDefinedGenericsOfClass = astToTargetAST.userDefinedGenerics.get(owner);
// Type variables with bounds that are also type variables of the method // Type variables with bounds that are also type variables of the method
for (var typeVariable : new HashSet<>(typeVariables)) { for (var typeVariable : new HashSet<>(typeVariables)) {
@@ -320,7 +317,7 @@ public abstract class GenerateGenerics {
Set<TPH> T2s = new HashSet<>(); Set<TPH> T2s = new HashSet<>();
findTphs(superType, T2s); findTphs(superType, T2s);
Target.logger.info("T1s: " + T1s + " T2s: " + T2s); System.out.println("T1s: " + T1s + " T2s: " + T2s);
//Ende //Ende
superType = methodCall.receiverType; superType = methodCall.receiverType;
@@ -332,10 +329,10 @@ public abstract class GenerateGenerics {
if (methodCall.receiver instanceof ExpressionReceiver expressionReceiver) { if (methodCall.receiver instanceof ExpressionReceiver expressionReceiver) {
if (expressionReceiver.expr instanceof This) { if (expressionReceiver.expr instanceof This) {
var optMethod = ASTToTargetAST.findMethod(owner, methodCall.name, methodCall.signatureArguments().stream().map(x -> getTargetType(x)).toList(), GenerateGenerics.this, compiler); var optMethod = astToTargetAST.findMethod(owner, methodCall.name, methodCall.signatureArguments().stream().map(astToTargetAST::convert).toList());
if (optMethod.isEmpty()) return; if (optMethod.isEmpty()) return;
var method2 = optMethod.get(); var method2 = optMethod.get();
Target.logger.info("In: " + method.getName() + " Method: " + method2.getName()); System.out.println("In: " + method.getName() + " Method: " + method2.getName());
var generics = family(owner, method2); var generics = family(owner, method2);
// transitive and // transitive and
@@ -368,7 +365,7 @@ public abstract class GenerateGenerics {
if (!T1s.contains(R1) || !T2s.contains(R2)) continue; if (!T1s.contains(R1) || !T2s.contains(R2)) continue;
var newPair = new PairLT(R1, R2); var newPair = new PairLT(R1, R2);
Target.logger.info("New pair: " + newPair); System.out.println("New pair: " + newPair);
newPairs.add(newPair); newPairs.add(newPair);
if (!containsRelation(result, newPair)) if (!containsRelation(result, newPair))
@@ -570,7 +567,7 @@ public abstract class GenerateGenerics {
Set<Pair> generics(ClassOrInterface owner, Method method) { Set<Pair> generics(ClassOrInterface owner, Method method) {
if (computedGenericsOfMethods.containsKey(method)) { if (computedGenericsOfMethods.containsKey(method)) {
var cached = computedGenericsOfMethods.get(method); var cached = computedGenericsOfMethods.get(method);
Target.logger.info("Cached " + method.getName() + ": " + cached); System.out.println("Cached " + method.getName() + ": " + cached);
return cached; return cached;
} }
@@ -599,7 +596,7 @@ public abstract class GenerateGenerics {
normalize(result, classGenerics, usedTphs); normalize(result, classGenerics, usedTphs);
Target.logger.info(this.getClass().getSimpleName() + " " + method.name + ": " + result); System.out.println(this.getClass().getSimpleName() + " " + method.name + ": " + result);
return result; return result;
} }
@@ -678,7 +675,7 @@ public abstract class GenerateGenerics {
normalize(javaResult, null, referencedByClass); normalize(javaResult, null, referencedByClass);
Target.logger.info(this.getClass().getSimpleName() + " Class " + classOrInterface.getClassName().getClassName() + ": " + javaResult); System.out.println(this.getClass().getSimpleName() + " Class " + classOrInterface.getClassName().getClassName() + ": " + javaResult);
return javaResult; return javaResult;
} }
@@ -729,7 +726,7 @@ public abstract class GenerateGenerics {
if (!added) break; if (!added) break;
} }
Target.logger.info(chain + " " + chain.stream().map(e -> e.resolve().getVariance()).toList()); System.out.println(chain + " " + chain.stream().map(e -> e.resolve().getVariance()).toList());
var variance = chain.get(0).resolve().getVariance(); var variance = chain.get(0).resolve().getVariance();
if (variance != 1) continue; if (variance != 1) continue;
var index = 0; var index = 0;
@@ -924,7 +921,7 @@ public abstract class GenerateGenerics {
for (var pair : infima) { for (var pair : infima) {
var returnTypes = findTypeVariables(method.getReturnType()); var returnTypes = findTypeVariables(method.getReturnType());
var chain = findConnectionToReturnType(returnTypes, input, new HashSet<>(), pair.left); var chain = findConnectionToReturnType(returnTypes, input, new HashSet<>(), pair.left);
Target.logger.info("Find: " + pair.left + " " + chain); System.out.println("Find: " + pair.left + " " + chain);
chain.remove(pair.left); chain.remove(pair.left);
if (chain.size() > 0) { if (chain.size() > 0) {
for (var tph : chain) for (var tph : chain)
@@ -962,8 +959,8 @@ public abstract class GenerateGenerics {
} }
} }
newTph.setVariance(variance); newTph.setVariance(variance);
Target.logger.info(infima + " " + infima.stream().map(i -> i.right.resolve().getVariance()).toList()); System.out.println(infima + " " + infima.stream().map(i -> i.right.resolve().getVariance()).toList());
Target.logger.info("Infima new TPH " + newTph + " variance " + variance); System.out.println("Infima new TPH " + newTph + " variance " + variance);
//referenced.add(newTph); //referenced.add(newTph);
addToPairs(input, new PairLT(left, new TPH(newTph))); addToPairs(input, new PairLT(left, new TPH(newTph)));
@@ -1008,8 +1005,8 @@ public abstract class GenerateGenerics {
} }
var type = concreteTypes.get(new TPH(tph)); var type = concreteTypes.get(new TPH(tph));
if (type == null) return new TargetGenericType(tph.getName()); if (type == null) return new TargetGenericType(tph.getName());
return ASTToTargetAST.convert(type, this, compiler); return astToTargetAST.convert(type, this);
} }
return ASTToTargetAST.convert(in, this, compiler); return astToTargetAST.convert(in, this);
} }
} }

View File

@@ -69,4 +69,8 @@ public class GenericsResult {
return this.generics.getType(tph); return this.generics.getType(tph);
return type; return type;
} }
public TargetType resolveTarget(RefTypeOrTPHOrWildcardOrGeneric type) {
return this.generics.getTargetType(type);
}
} }

View File

@@ -1,6 +1,5 @@
package de.dhbwstuttgart.target.generate; package de.dhbwstuttgart.target.generate;
import de.dhbwstuttgart.core.JavaTXCompiler;
import de.dhbwstuttgart.syntaxtree.ClassOrInterface; import de.dhbwstuttgart.syntaxtree.ClassOrInterface;
import de.dhbwstuttgart.syntaxtree.Method; import de.dhbwstuttgart.syntaxtree.Method;
import de.dhbwstuttgart.typeinference.result.ResultSet; import de.dhbwstuttgart.typeinference.result.ResultSet;
@@ -8,8 +7,8 @@ import de.dhbwstuttgart.typeinference.result.ResultSet;
import java.util.Set; import java.util.Set;
final class JavaGenerics extends GenerateGenerics { final class JavaGenerics extends GenerateGenerics {
JavaGenerics(JavaTXCompiler compiler, ResultSet constraints) { JavaGenerics(ASTToTargetAST astToTargetAST, ResultSet constraints) {
super(compiler, constraints); super(astToTargetAST, constraints);
} }
@Override @Override

View File

@@ -8,14 +8,12 @@ import de.dhbwstuttgart.parser.scope.JavaClassName;
import de.dhbwstuttgart.syntaxtree.*; import de.dhbwstuttgart.syntaxtree.*;
import de.dhbwstuttgart.syntaxtree.statement.*; import de.dhbwstuttgart.syntaxtree.statement.*;
import de.dhbwstuttgart.syntaxtree.type.*; import de.dhbwstuttgart.syntaxtree.type.*;
import de.dhbwstuttgart.target.Target;
import de.dhbwstuttgart.target.tree.MethodParameter; import de.dhbwstuttgart.target.tree.MethodParameter;
import de.dhbwstuttgart.target.tree.TargetMethod; import de.dhbwstuttgart.target.tree.TargetMethod;
import de.dhbwstuttgart.target.tree.expression.*; import de.dhbwstuttgart.target.tree.expression.*;
import de.dhbwstuttgart.target.tree.type.*; import de.dhbwstuttgart.target.tree.type.*;
import java.lang.reflect.Modifier; import java.lang.reflect.Modifier;
import java.sql.Array;
import java.util.*; import java.util.*;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.stream.StreamSupport; import java.util.stream.StreamSupport;
@@ -34,71 +32,54 @@ public class StatementToTargetExpression implements ASTVisitor {
throw new NotImplementedException(); throw new NotImplementedException();
} }
private class LambdaCaptureFinder extends TracingStatementVisitor {
// TODO The same mechanism is implemented in Codegen, maybe use it from there?
final Stack<Set<String>> localVariables = new Stack<>();
private final List<MethodParameter> parameters;
private final List<MethodParameter> captures;
LambdaCaptureFinder(List<MethodParameter> parameters, List<MethodParameter> captures) {
localVariables.push(new HashSet<>());
this.parameters = parameters;
this.captures = captures;
}
boolean hasLocalVar(String name) {
for (var localVariables : this.localVariables) {
if (localVariables.contains(name))
return true;
}
return false;
}
@Override
public void visit(Block block) {
localVariables.push(new HashSet<>());
super.visit(block);
localVariables.pop();
}
@Override
public void visit(LocalVar localVar) {
super.visit(localVar);
var capture = new MethodParameter(new TargetTypePattern(converter.convert(localVar.getType()), localVar.name));
if (!hasLocalVar(localVar.name) && !parameters.contains(capture) && !captures.contains(capture))
captures.add(capture);
}
@Override
public void visit(LocalVarDecl varDecl) {
var localVariables = this.localVariables.peek();
localVariables.add(varDecl.getName());
}
@Override
public void visit(LambdaExpression lambda) {
var newCaptures = new ArrayList<MethodParameter>();
var captureFinder = new LambdaCaptureFinder(createParameters(lambda), newCaptures);
lambda.methodBody.accept(captureFinder);
newCaptures.removeAll(parameters);
captures.addAll(newCaptures);
}
}
private List<MethodParameter> createParameters(LambdaExpression lambda) {
return StreamSupport.stream(lambda.params.spliterator(), false)
.map(p -> (FormalParameter) p)
.map(p -> new MethodParameter(new TargetTypePattern(converter.convert(p.getType()), p.getName())))
.toList();
}
@Override @Override
public void visit(LambdaExpression lambdaExpression) { public void visit(LambdaExpression lambdaExpression) {
var parameters = createParameters(lambdaExpression); var parameters = StreamSupport.stream(lambdaExpression.params.spliterator(), false)
.map(p -> (FormalParameter) p)
.map(p -> new MethodParameter(new TargetTypePattern(converter.convert(p.getType()), p.getName())))
.toList();
List<MethodParameter> captures = new ArrayList<>(); List<MethodParameter> captures = new ArrayList<>();
var visitor = new LambdaCaptureFinder(parameters, captures); lambdaExpression.methodBody.accept(new TracingStatementVisitor() {
lambdaExpression.methodBody.accept(visitor); // TODO The same mechanism is implemented in Codegen, maybe use it from there?
final Stack<Set<String>> localVariables = new Stack<>();
{
localVariables.push(new HashSet<>());
}
boolean hasLocalVar(String name) {
for (var localVariables : this.localVariables) {
if (localVariables.contains(name))
return true;
}
return false;
}
@Override
public void visit(Block block) {
localVariables.push(new HashSet<>());
super.visit(block);
localVariables.pop();
}
@Override
public void visit(LocalVar localVar) {
super.visit(localVar);
var capture = new MethodParameter(new TargetTypePattern(converter.convert(localVar.getType()), localVar.name));
if (!hasLocalVar(localVar.name) && !parameters.contains(capture) && !captures.contains(capture))
captures.add(capture);
}
@Override
public void visit(LocalVarDecl varDecl) {
var localVariables = this.localVariables.peek();
localVariables.add(varDecl.getName());
}
@Override
public void visit(LambdaExpression lambda) {
} // Don't look at lambda expressions
});
TargetMethod.Signature signature = new TargetMethod.Signature(Set.of(), parameters, converter.convert(lambdaExpression.getReturnType()));; TargetMethod.Signature signature = new TargetMethod.Signature(Set.of(), parameters, converter.convert(lambdaExpression.getReturnType()));;
var tpe = converter.convert(lambdaExpression.getType()); var tpe = converter.convert(lambdaExpression.getType());
@@ -139,10 +120,7 @@ public class StatementToTargetExpression implements ASTVisitor {
@Override @Override
public void visit(BoolExpression bool) { public void visit(BoolExpression bool) {
result = switch(bool.operation) { System.out.println("BoolExpression");
case OR -> new TargetBinaryOp.Or(converter.convert(bool.getType()), converter.convert(bool.lexpr), converter.convert(bool.rexpr));
case AND -> new TargetBinaryOp.And(converter.convert(bool.getType()), converter.convert(bool.lexpr), converter.convert(bool.rexpr));
};
} }
@Override @Override
@@ -162,6 +140,7 @@ public class StatementToTargetExpression implements ASTVisitor {
@Override @Override
public void visit(FieldVar fieldVar) { public void visit(FieldVar fieldVar) {
var isStatic = false;
var type = converter.convert(fieldVar.receiver.getType()); var type = converter.convert(fieldVar.receiver.getType());
var clazz = converter.compiler.getClass(new JavaClassName(type.name())); var clazz = converter.compiler.getClass(new JavaClassName(type.name()));
var field = clazz.getField(fieldVar.fieldVarName).orElseThrow(); var field = clazz.getField(fieldVar.fieldVarName).orElseThrow();
@@ -255,7 +234,7 @@ public class StatementToTargetExpression implements ASTVisitor {
isInterface = receiverClass.isInterface(); isInterface = receiverClass.isInterface();
} }
Target.logger.info(argList); System.out.println(argList);
result = new TargetMethodCall(converter.convert(methodCall.getType()), returnType, argList, converter.convert(methodCall.receiver), methodCall.getArgumentList().getArguments().stream().map(converter::convert).toList(), receiverType, methodCall.name, isStatic, isInterface, isPrivate); result = new TargetMethodCall(converter.convert(methodCall.getType()), returnType, argList, converter.convert(methodCall.receiver), methodCall.getArgumentList().getArguments().stream().map(converter::convert).toList(), receiverType, methodCall.name, isStatic, isInterface, isPrivate);
} }

View File

@@ -1,6 +1,5 @@
package de.dhbwstuttgart.target.generate; package de.dhbwstuttgart.target.generate;
import de.dhbwstuttgart.core.JavaTXCompiler;
import de.dhbwstuttgart.syntaxtree.ClassOrInterface; import de.dhbwstuttgart.syntaxtree.ClassOrInterface;
import de.dhbwstuttgart.syntaxtree.Method; import de.dhbwstuttgart.syntaxtree.Method;
import de.dhbwstuttgart.typeinference.result.ResultSet; import de.dhbwstuttgart.typeinference.result.ResultSet;
@@ -8,8 +7,8 @@ import de.dhbwstuttgart.typeinference.result.ResultSet;
import java.util.Set; import java.util.Set;
final class TxGenerics extends GenerateGenerics { final class TxGenerics extends GenerateGenerics {
TxGenerics(JavaTXCompiler compiler, ResultSet constraints) { TxGenerics(ASTToTargetAST astToTargetAST, ResultSet constraints) {
super(compiler, constraints); super(astToTargetAST, constraints);
} }
@Override @Override

View File

@@ -36,30 +36,30 @@ public record TargetMethod(int access, String name, TargetBlock block, Signature
public static String getDescriptor(TargetType returnType, TargetType... parameters) { public static String getDescriptor(TargetType returnType, TargetType... parameters) {
String ret = "("; String ret = "(";
for (var parameterType : parameters) { for (var parameterType : parameters) {
ret += parameterType.toDescriptor(); ret += parameterType.toSignature();
} }
ret += ")"; ret += ")";
if (returnType == null) ret += "V"; if (returnType == null) ret += "V";
else ret += returnType.toDescriptor(); else ret += returnType.toSignature();
return ret; return ret;
} }
public static String getSignature(Set<TargetGeneric> generics, List<MethodParameter> parameters, TargetType returnType) { public static String getSignature(Set<TargetGeneric> generics, List<MethodParameter> parameters, TargetType returnType) {
String ret = ""; String ret = "";
if (!generics.isEmpty()) { if (generics.size() > 0) {
ret += "<"; ret += "<";
for (var generic : generics) { for (var generic : generics) {
ret += generic.name() + ":" + generic.bound().toSignature(); ret += generic.name() + ":" + generic.bound().toDescriptor();
} }
ret += ">"; ret += ">";
} }
ret += "("; ret += "(";
for (var param : parameters) { for (var param : parameters) {
ret += param.pattern().type().toSignature(); ret += param.pattern().type().toDescriptor();
} }
ret += ")"; ret += ")";
if (returnType == null) ret += "V"; if (returnType == null) ret += "V";
else ret += returnType.toSignature(); else ret += returnType.toDescriptor();
return ret; return ret;
} }

View File

@@ -8,42 +8,42 @@ public sealed interface TargetLiteral extends TargetExpression {
record BooleanLiteral(Boolean value) implements TargetLiteral { record BooleanLiteral(Boolean value) implements TargetLiteral {
@Override @Override
public TargetType type() { public TargetType type() {
return TargetType.boolean_; return TargetType.Boolean;
} }
} }
record CharLiteral(Character value) implements TargetLiteral { record CharLiteral(Character value) implements TargetLiteral {
@Override @Override
public TargetType type() { public TargetType type() {
return TargetType.char_; return TargetType.Char;
} }
} }
record IntLiteral(Integer value) implements TargetLiteral { record IntLiteral(Integer value) implements TargetLiteral {
@Override @Override
public TargetType type() { public TargetType type() {
return TargetType.int_; return TargetType.Integer;
} }
} }
record LongLiteral(Long value) implements TargetLiteral { record LongLiteral(Long value) implements TargetLiteral {
@Override @Override
public TargetType type() { public TargetType type() {
return TargetType.long_; return TargetType.Long;
} }
} }
record FloatLiteral(Float value) implements TargetLiteral { record FloatLiteral(Float value) implements TargetLiteral {
@Override @Override
public TargetType type() { public TargetType type() {
return TargetType.float_; return TargetType.Float;
} }
} }
record DoubleLiteral(Double value) implements TargetLiteral { record DoubleLiteral(Double value) implements TargetLiteral {
@Override @Override
public TargetType type() { public TargetType type() {
return TargetType.double_; return TargetType.Double;
} }
} }

View File

@@ -3,12 +3,12 @@ package de.dhbwstuttgart.target.tree.type;
public record TargetExtendsWildcard(TargetType innerType) implements TargetType { public record TargetExtendsWildcard(TargetType innerType) implements TargetType {
@Override @Override
public String toSignature() { public String toSignature() {
return "+" + innerType.toSignature(); return innerType.toSignature();
} }
@Override @Override
public String toDescriptor() { public String toDescriptor() {
return innerType.toDescriptor(); return "+" + innerType.toDescriptor();
} }
@Override @Override

View File

@@ -36,7 +36,6 @@ public record TargetFunNType(String name, List<TargetType> funNParams, List<Targ
@Override @Override
public String toSignature() { public String toSignature() {
var args = FunNGenerator.getArguments(funNParams); return "L" + getInternalName() + ";";
return "LFun" + args.size() + "$$" + TargetSpecializedType.signatureParameters(funNParams) + ";";
} }
} }

View File

@@ -2,12 +2,12 @@ package de.dhbwstuttgart.target.tree.type;
public record TargetGenericType(String name) implements TargetType { public record TargetGenericType(String name) implements TargetType {
@Override @Override
public String toDescriptor() { public String toSignature() {
return "Ljava/lang/Object;"; // TODO Use bounds for this? return "Ljava/lang/Object;"; // TODO Use bounds for this?
} }
@Override @Override
public String toSignature() { public String toDescriptor() {
return "T" + getInternalName() + ";"; return "T" + getInternalName() + ";";
} }

View File

@@ -12,6 +12,11 @@ public record TargetRefType(String name, List<TargetType> params) implements Tar
return this.name.replaceAll("\\.", "/"); return this.name.replaceAll("\\.", "/");
} }
@Override
public String toSignature() {
return "L" + getInternalName() + ";";
}
// Type erasure means we need to override hashCode and equals to only consider the name // Type erasure means we need to override hashCode and equals to only consider the name
@Override @Override
public int hashCode() { public int hashCode() {

View File

@@ -6,27 +6,16 @@ public sealed interface TargetSpecializedType extends TargetType permits TargetF
List<TargetType> params(); List<TargetType> params();
@Override @Override
default String toSignature() { default String toDescriptor() {
String ret = "L" + getInternalName(); String ret = "L" + getInternalName();
ret += signatureParameters(params()); if (params().size() > 0) {
ret += ";";
return ret;
}
static String signatureParameters(List<TargetType> params) {
var ret = "";
if (!params.isEmpty()) {
ret += "<"; ret += "<";
for (var param : params) { for (var param : params()) {
ret += param.toSignature(); ret += param.toDescriptor();
} }
ret += ">"; ret += ">";
} }
ret += ";";
return ret; return ret;
} }
@Override
default String toDescriptor() {
return "L" + getInternalName() + ";";
}
} }

View File

@@ -3,12 +3,12 @@ package de.dhbwstuttgart.target.tree.type;
public record TargetSuperWildcard(TargetType innerType) implements TargetType { public record TargetSuperWildcard(TargetType innerType) implements TargetType {
@Override @Override
public String toSignature() { public String toSignature() {
return "-" + innerType.toSignature(); return innerType.toSignature();
} }
@Override @Override
public String toDescriptor() { public String toDescriptor() {
return innerType.toDescriptor(); return "-" + innerType.toDescriptor();
} }
@Override @Override

View File

@@ -19,11 +19,11 @@ public class MethodAssumption extends Assumption{
private ClassOrInterface receiver; private ClassOrInterface receiver;
private RefTypeOrTPHOrWildcardOrGeneric retType; private RefTypeOrTPHOrWildcardOrGeneric retType;
List<? extends RefTypeOrTPHOrWildcardOrGeneric> params; List<? extends RefTypeOrTPHOrWildcardOrGeneric> params;
private final boolean isInherited; private final Boolean isInherited;
private final boolean isOverridden; private final Boolean isOverridden;
public MethodAssumption(ClassOrInterface receiver, RefTypeOrTPHOrWildcardOrGeneric retType, public MethodAssumption(ClassOrInterface receiver, RefTypeOrTPHOrWildcardOrGeneric retType,
List<? extends RefTypeOrTPHOrWildcardOrGeneric> params, TypeScope scope, boolean isInherited, boolean isOverridden){ List<? extends RefTypeOrTPHOrWildcardOrGeneric> params, TypeScope scope, Boolean isInherited, Boolean isOverridden){
super(scope); super(scope);
this.receiver = receiver; this.receiver = receiver;
this.retType = retType; this.retType = retType;
@@ -73,11 +73,11 @@ public class MethodAssumption extends Assumption{
return TYPEStmt.getReceiverType(receiver, resolver); return TYPEStmt.getReceiverType(receiver, resolver);
} }
public boolean isInherited() { public Boolean isInherited() {
return isInherited; return isInherited;
} }
public boolean isOverridden() { public Boolean isOverridden() {
return isOverridden; return isOverridden;
} }
} }

View File

@@ -9,97 +9,84 @@ import de.dhbwstuttgart.server.packet.dataContainers.serialized.SerialUUID;
import de.dhbwstuttgart.typeinference.unify.UnifyContext; import de.dhbwstuttgart.typeinference.unify.UnifyContext;
import de.dhbwstuttgart.typeinference.unify.model.UnifyPair; import de.dhbwstuttgart.typeinference.unify.model.UnifyPair;
import java.util.ArrayList;
import java.util.HashSet; import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional; import java.util.Optional;
import java.util.Set; import java.util.Set;
import java.util.function.Function; import java.util.function.Function;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import javax.annotation.Nullable;
public class Constraint<A extends IConstraintElement> extends HashSet<A> implements Comparable<Constraint<A>>, ISerializableData { public class Constraint<A extends IConstraintElement> extends HashSet<A> implements ISerializableData {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
private boolean isInherited = false;//wird beides nur für die Method-Constraints benoetigt private Boolean isInherited = false;//wird beides nur für die Method-Constraints benoetigt
private boolean isImplemented = false; private Boolean isImplemented = false;
/*
* wird verwendet um bei der Codegenerierung die richtige Methoden - Signatur
* auszuwaehlen
*/
/*private*/ Set<A> methodSignatureConstraint = new HashSet<>();
private Constraint<A> extendConstraint = null;
public Constraint() {
super();
}
public Constraint(int initialCapacity) { /*
super(initialCapacity); * wird verwendet um bei der Codegenerierung die richtige Methoden - Signatur
* auszuwaehlen
*/
/*private*/ Set<A> methodSignatureConstraint = new HashSet<>();
private Constraint<A> extendConstraint = null;
public Constraint() {
super();
} }
public Constraint(boolean isInherited, boolean isImplemented) { public Constraint(Boolean isInherited, Boolean isImplemented) {
this.isInherited = isInherited; this.isInherited = isInherited;
this.isImplemented = isImplemented; this.isImplemented = isImplemented;
}
public Constraint(boolean isInherited, boolean isImplemented, Constraint<A> extendConstraint, Set<A> methodSignatureConstraint) {
this.isInherited = isInherited;
this.isImplemented = isImplemented;
this.extendConstraint = extendConstraint;
this.methodSignatureConstraint = methodSignatureConstraint;
}
public void setIsInherited(boolean isInherited) {
this.isInherited = isInherited;
}
public boolean isInherited() {
return isInherited;
}
public boolean isImplemented() {
return isImplemented;
}
public Constraint<A> getExtendConstraint() {
return extendConstraint;
}
public void setExtendConstraint(Constraint<A> c) {
extendConstraint = c;
}
public Set<A> getmethodSignatureConstraint() {
return methodSignatureConstraint;
}
public void setmethodSignatureConstraint(Set<A> c) {
methodSignatureConstraint = c;
}
public <B extends IConstraintElement> Constraint<B> createdMapped(Function<A,B> mapper) {
Constraint<B> result = new Constraint<>(this.size());
for (A element : this) {
result.add(mapper.apply(element));
}
return result;
} }
public String toString() { public Constraint(Boolean isInherited, Boolean isImplemented, Constraint<A> extendConstraint, Set<A> methodSignatureConstraint) {
this.isInherited = isInherited;
this.isImplemented = isImplemented;
this.extendConstraint = extendConstraint;
this.methodSignatureConstraint = methodSignatureConstraint;
}
public void setIsInherited(Boolean isInherited) {
this.isInherited = isInherited;
}
public Boolean isInherited() {
return isInherited;
}
public Boolean isImplemented() {
return isImplemented;
}
public Constraint<A> getExtendConstraint() {
return extendConstraint;
}
public void setExtendConstraint(Constraint<A> c) {
extendConstraint = c;
}
public Set<A> getmethodSignatureConstraint() {
return methodSignatureConstraint;
}
public void setmethodSignatureConstraint(Set<A> c) {
methodSignatureConstraint = c;
}
public String toString() {
return super.toString() + "\nisInherited = " + isInherited return super.toString() + "\nisInherited = " + isInherited
+ " isOveridden = " + isImplemented + " isOveridden = " + isImplemented
+ " msc[" + methodSignatureConstraint.size() + "] = " + methodSignatureConstraint + " msc[" + methodSignatureConstraint.size() + "] = " + methodSignatureConstraint
//" + extendsContraint: " + (extendConstraint != null ? extendConstraint.toStringBase() : "null" ) //" + extendsContraint: " + (extendConstraint != null ? extendConstraint.toStringBase() : "null" )
+ "\n"; + "\n";
} }
public String toStringBase() {
return super.toString();
}
public String toStringBase() {
@Override return super.toString();
public int compareTo(Constraint<A> o) {
return this.toString().compareTo(o.toString());
} }
private String serialUUID = null; private String serialUUID = null;
@@ -168,4 +155,5 @@ public class Constraint<A extends IConstraintElement> extends HashSet<A> impleme
return keyStorage.getUnserialized(uuid, Constraint.class); return keyStorage.getUnserialized(uuid, Constraint.class);
} }
} }

View File

@@ -21,7 +21,7 @@ public class Pair implements Serializable, IConstraintElement, ISerializableData
private SourceLoc location; private SourceLoc location;
private PairOperator eOperator = PairOperator.SMALLER; private PairOperator eOperator = PairOperator.SMALLER;
private boolean noUnification = false; private Boolean noUnification = false;
private Pair(RefTypeOrTPHOrWildcardOrGeneric TA1, RefTypeOrTPHOrWildcardOrGeneric TA2) { private Pair(RefTypeOrTPHOrWildcardOrGeneric TA1, RefTypeOrTPHOrWildcardOrGeneric TA2) {
@@ -43,7 +43,7 @@ public class Pair implements Serializable, IConstraintElement, ISerializableData
this.location = location; this.location = location;
} }
public Pair(RefTypeOrTPHOrWildcardOrGeneric TA1, RefTypeOrTPHOrWildcardOrGeneric TA2, PairOperator eOp, boolean noUnification) { public Pair(RefTypeOrTPHOrWildcardOrGeneric TA1, RefTypeOrTPHOrWildcardOrGeneric TA2, PairOperator eOp, Boolean noUnification) {
// Konstruktor // Konstruktor
this(TA1, TA2); this(TA1, TA2);
this.eOperator = eOp; this.eOperator = eOp;
@@ -161,7 +161,7 @@ public class Pair implements Serializable, IConstraintElement, ISerializableData
String op = data.getValue("op").getOf(String.class); String op = data.getValue("op").getOf(String.class);
SerialMap ta1 = data.getMap("ta1"); SerialMap ta1 = data.getMap("ta1");
SerialMap ta2 = data.getMap("ta2"); SerialMap ta2 = data.getMap("ta2");
boolean noUnification = data.getValue("noUnification").getOf(Integer.class) == 1; Boolean noUnification = data.getValue("noUnification").getOf(Integer.class) == 1;
SerialMap location = data.getMapOrNull("location"); SerialMap location = data.getMapOrNull("location");
var pair = new Pair( var pair = new Pair(

View File

@@ -11,7 +11,7 @@ import de.dhbwstuttgart.typeinference.unify.UnifyContext;
* Paare, welche das Unifikationsergebnis darstellen * Paare, welche das Unifikationsergebnis darstellen
*/ */
public abstract class ResultPair<A extends RefTypeOrTPHOrWildcardOrGeneric,B extends RefTypeOrTPHOrWildcardOrGeneric> public abstract class ResultPair<A extends RefTypeOrTPHOrWildcardOrGeneric,B extends RefTypeOrTPHOrWildcardOrGeneric>
implements Comparable<ResultPair<A,B>>, ISerializableData { implements ISerializableData {
private final A left; private final A left;
private final B right; private final B right;
@@ -65,16 +65,6 @@ public abstract class ResultPair<A extends RefTypeOrTPHOrWildcardOrGeneric,B ext
return true; return true;
} }
@Override
public int compareTo(ResultPair<A, B> o) {
if (o == null) {
return 1; // this is greater than null
}
return o.left.toString().compareTo(this.left.toString());
}
@Override @Override
public SerialMap toSerial(KeyStorage keyStorage) { public SerialMap toSerial(KeyStorage keyStorage) {

View File

@@ -5,13 +5,10 @@ import de.dhbwstuttgart.server.packet.dataContainers.ISerializableData;
import de.dhbwstuttgart.server.packet.dataContainers.KeyStorage; import de.dhbwstuttgart.server.packet.dataContainers.KeyStorage;
import de.dhbwstuttgart.server.packet.dataContainers.serialized.SerialList; import de.dhbwstuttgart.server.packet.dataContainers.serialized.SerialList;
import de.dhbwstuttgart.server.packet.dataContainers.serialized.SerialMap; import de.dhbwstuttgart.server.packet.dataContainers.serialized.SerialMap;
import de.dhbwstuttgart.typeinference.unify.TypeUnifyTaskHelper;
import de.dhbwstuttgart.typeinference.unify.UnifyContext; import de.dhbwstuttgart.typeinference.unify.UnifyContext;
import de.dhbwstuttgart.util.Logger;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Comparator; import java.util.Comparator;
import java.util.HashSet; import java.util.HashSet;
import java.util.List;
import java.util.Set; import java.util.Set;
import de.dhbwstuttgart.exceptions.NotImplementedException; import de.dhbwstuttgart.exceptions.NotImplementedException;
@@ -24,32 +21,28 @@ import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
public class ResultSet implements Comparable<ResultSet>, ISerializableData { public class ResultSet implements ISerializableData {
public final Set<ResultPair> results; public final Set<ResultPair> results;
public Set<ResultPair<TypePlaceholder, TypePlaceholder>> genIns; public Set<ResultPair<TypePlaceholder, TypePlaceholder>> genIns;
public ResultSet(Set<ResultPair> set){ public ResultSet(Set<ResultPair> set) {
this.results = set; this.results = set;
this.genIns = TypeUnifyTaskHelper.getPresizedHashSet(results.size()); this.genIns = new HashSet<>();
results.forEach(x -> { results.forEach(x -> {
if (x instanceof PairTPHsmallerTPH) { if (x instanceof PairTPHsmallerTPH) {
this.genIns.add(x); this.genIns.add(x);
} }
}); });
} }
public List<ResultPair> getSortedResults() { public boolean contains(ResultPair toCheck) {
return results.stream().sorted().toList(); return this.results.contains(toCheck);
} }
public boolean contains(ResultPair toCheck) { public void remove(ResultPair toCheck) {
return this.results.contains(toCheck); results.remove(toCheck);
} }
public void remove(ResultPair toCheck) {
results.remove(toCheck);
}
public ResolvedType resolveType(RefTypeOrTPHOrWildcardOrGeneric type) { public ResolvedType resolveType(RefTypeOrTPHOrWildcardOrGeneric type) {
if (type instanceof TypePlaceholder) if (type instanceof TypePlaceholder)
@@ -92,24 +85,9 @@ public class ResultSet implements Comparable<ResultSet>, ISerializableData {
} }
} }
@Override
public int hashCode() {
return results.hashCode();
}
@Override @Override
public int compareTo(ResultSet o) { public int hashCode() {
List<ResultPair> thisSorted = this.getSortedResults(); return results.hashCode();
List<ResultPair> otherSorted = o.getSortedResults();
int sizeCompare = Integer.compare(thisSorted.size(), otherSorted.size());
if (sizeCompare != 0) return sizeCompare;
for (int i = 0; i < thisSorted.size(); i++) {
int cmp = thisSorted.get(i).compareTo(otherSorted.get(i));
if (cmp != 0) return cmp;
}
return 0;
} }
@Override @Override
@@ -132,8 +110,6 @@ class Resolver implements ResultSetVisitor {
private final Set<GenericInsertPair> additionalTPHs = new HashSet<>(); private final Set<GenericInsertPair> additionalTPHs = new HashSet<>();
private ResultPair<?, ?> currentPair; private ResultPair<?, ?> currentPair;
public static Logger logger = new Logger("Resolver");
public Resolver(ResultSet resultPairs) { public Resolver(ResultSet resultPairs) {
this.result = resultPairs; this.result = resultPairs;
} }
@@ -141,7 +117,7 @@ class Resolver implements ResultSetVisitor {
public ResolvedType resolve(TypePlaceholder tph) { public ResolvedType resolve(TypePlaceholder tph) {
toResolve = tph; toResolve = tph;
resolved = null; resolved = null;
logger.info(tph.toString()); System.out.println(tph.toString());
for (ResultPair<?, ?> resultPair : result.results) { for (ResultPair<?, ?> resultPair : result.results) {
if (resultPair instanceof PairTPHEqualTPH && ((PairTPHEqualTPH) resultPair).getLeft().equals(toResolve)) { if (resultPair instanceof PairTPHEqualTPH && ((PairTPHEqualTPH) resultPair).getLeft().equals(toResolve)) {
currentPair = resultPair; currentPair = resultPair;

View File

@@ -1,7 +1,6 @@
package de.dhbwstuttgart.typeinference.typeAlgo; package de.dhbwstuttgart.typeinference.typeAlgo;
import de.dhbwstuttgart.exceptions.DebugException; import de.dhbwstuttgart.exceptions.DebugException;
import de.dhbwstuttgart.parser.NullToken;
import de.dhbwstuttgart.parser.SourceLoc; import de.dhbwstuttgart.parser.SourceLoc;
import de.dhbwstuttgart.parser.antlr.Java17Parser; import de.dhbwstuttgart.parser.antlr.Java17Parser;
import de.dhbwstuttgart.parser.scope.JavaClassName; import de.dhbwstuttgart.parser.scope.JavaClassName;
@@ -10,36 +9,33 @@ import de.dhbwstuttgart.syntaxtree.factory.ASTFactory;
import de.dhbwstuttgart.syntaxtree.statement.Statement; import de.dhbwstuttgart.syntaxtree.statement.Statement;
import de.dhbwstuttgart.syntaxtree.type.RefType; import de.dhbwstuttgart.syntaxtree.type.RefType;
import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric; import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric;
import de.dhbwstuttgart.target.tree.type.TargetRefType;
import de.dhbwstuttgart.typeinference.assumptions.FieldAssumption; import de.dhbwstuttgart.typeinference.assumptions.FieldAssumption;
import de.dhbwstuttgart.typeinference.assumptions.TypeInferenceBlockInformation; import de.dhbwstuttgart.typeinference.assumptions.TypeInferenceBlockInformation;
import de.dhbwstuttgart.typeinference.assumptions.TypeInferenceInformation; import de.dhbwstuttgart.typeinference.assumptions.TypeInferenceInformation;
import de.dhbwstuttgart.typeinference.constraints.Constraint;
import de.dhbwstuttgart.typeinference.constraints.ConstraintSet; import de.dhbwstuttgart.typeinference.constraints.ConstraintSet;
import de.dhbwstuttgart.typeinference.constraints.Pair; import de.dhbwstuttgart.typeinference.constraints.Pair;
import de.dhbwstuttgart.typeinference.unify.TypeUnifyTaskHelper;
import de.dhbwstuttgart.typeinference.unify.model.PairOperator; import de.dhbwstuttgart.typeinference.unify.model.PairOperator;
import de.dhbwstuttgart.util.BiRelation; import de.dhbwstuttgart.util.BiRelation;
import org.antlr.v4.runtime.Token; import org.antlr.v4.runtime.Token;
import java.lang.reflect.Modifier;
import java.util.*; import java.util.*;
public class TYPE { public class TYPE {
private final SourceFile sf;
private final Set<ClassOrInterface> allAvailableClasses; private final Set<ClassOrInterface> allAvailableClasses;
private final Set<ClassOrInterface> definedClasses;
public TYPE(SourceFile sf, Set<ClassOrInterface> allAvailableClasses){
public TYPE(Set<ClassOrInterface> definedClasses, Set<ClassOrInterface> allAvailableClasses){ this.sf = sf;
this.allAvailableClasses = allAvailableClasses; this.allAvailableClasses = allAvailableClasses;
this.definedClasses = definedClasses;
} }
public ConstraintSet getConstraints() { public ConstraintSet getConstraints() {
ConstraintSet ret = new ConstraintSet(); ConstraintSet ret = new ConstraintSet();
for (ClassOrInterface cl : definedClasses) { for (ClassOrInterface cl : sf.KlassenVektor) {
Set<ClassOrInterface> allClasses = TypeUnifyTaskHelper.getPresizedHashSet(allAvailableClasses.size()); var allClasses = new HashSet<ClassOrInterface>();
allClasses.addAll(allAvailableClasses); allClasses.addAll(allAvailableClasses);
allClasses.addAll(sf.availableClasses);
ret.addAll(getConstraintsClass(cl, new TypeInferenceInformation(allClasses))); ret.addAll(getConstraintsClass(cl, new TypeInferenceInformation(allClasses)));
} }
return ret; return ret;
@@ -72,7 +68,7 @@ public class TYPE {
for(SourceFile sourceFile : sfs){ for(SourceFile sourceFile : sfs){
for(JavaClassName importName : sourceFile.imports){ for(JavaClassName importName : sourceFile.imports){
context.logger().info(importName); System.out.println(importName);
try { try {
classes.add(ASTFactory.createClass(classLoader.loadClass(importName.toString()))); classes.add(ASTFactory.createClass(classLoader.loadClass(importName.toString())));
} catch (ClassNotFoundException e) { } catch (ClassNotFoundException e) {
@@ -91,25 +87,12 @@ public class TYPE {
TypeInferenceBlockInformation blockInfo = new TypeInferenceBlockInformation(info.getAvailableClasses(), currentClass, m); TypeInferenceBlockInformation blockInfo = new TypeInferenceBlockInformation(info.getAvailableClasses(), currentClass, m);
TYPEStmt methodScope = new TYPEStmt(blockInfo); TYPEStmt methodScope = new TYPEStmt(blockInfo);
ConstraintSet constraintSet = new ConstraintSet(); ConstraintSet constraintSet = new ConstraintSet();
m.getParameterList().getFormalparalist().forEach(el -> {
if(el instanceof RecordPattern){
constraintSet.addAll(addRecursiveParameterConstraints((RecordPattern) el, blockInfo));
if (m.name.equals("main") && Modifier.isStatic(m.modifier) && m.getParameterList().getFormalparalist().size() == 1) { }
// Add constraint for main method });
var firstParam = m.getParameterList().getParameterAt(0);
constraintSet.addUndConstraint(new Pair(firstParam.getType(),
new RefType(new JavaClassName("java.util.List"),
List.of(new RefType(new JavaClassName("java.lang.String"), new NullToken())),
new NullToken()),
PairOperator.EQUALSDOT));
} else {
m.getParameterList().getFormalparalist().forEach(el -> {
if (el instanceof RecordPattern rp){
constraintSet.addAll(addRecursiveParameterConstraints(rp, blockInfo));
}
});
}
m.block.accept(methodScope); m.block.accept(methodScope);
constraintSet.addAll(methodScope.getConstraints()); constraintSet.addAll(methodScope.getConstraints());
return constraintSet; return constraintSet;

View File

@@ -2,7 +2,6 @@
package de.dhbwstuttgart.typeinference.typeAlgo; package de.dhbwstuttgart.typeinference.typeAlgo;
import de.dhbwstuttgart.typeinference.unify.PlaceholderRegistry; import de.dhbwstuttgart.typeinference.unify.PlaceholderRegistry;
import de.dhbwstuttgart.typeinference.unify.TypeUnifyTaskHelper;
import java.util.*; import java.util.*;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@@ -75,7 +74,7 @@ public class TYPEStmt implements StatementVisitor {
@Override @Override
public void visit(LambdaExpression lambdaExpression) { public void visit(LambdaExpression lambdaExpression) {
TypePlaceholder tphRetType = TypePlaceholder.fresh(new NullToken(), -1, false); TypePlaceholder tphRetType = TypePlaceholder.fresh(new NullToken());
List<RefTypeOrTPHOrWildcardOrGeneric> lambdaParams = lambdaExpression.params.getFormalparalist().stream().map((formalParameter -> formalParameter.getType())).collect(Collectors.toList()); List<RefTypeOrTPHOrWildcardOrGeneric> lambdaParams = lambdaExpression.params.getFormalparalist().stream().map((formalParameter -> formalParameter.getType())).collect(Collectors.toList());
lambdaParams.add(tphRetType); lambdaParams.add(tphRetType);
// lambdaParams.add(0,tphRetType); // lambdaParams.add(0,tphRetType);
@@ -118,18 +117,17 @@ public class TYPEStmt implements StatementVisitor {
@Override @Override
public void visit(FieldVar fieldVar) { public void visit(FieldVar fieldVar) {
fieldVar.receiver.accept(this); fieldVar.receiver.accept(this);
List<FieldAssumption> fieldAssumptions = info.getFields(fieldVar.fieldVarName); Set<Constraint> oderConstraints = new HashSet<>();
Set<Constraint> oderConstraints = TypeUnifyTaskHelper.getPresizedHashSet(fieldAssumptions.size());
for (FieldAssumption fieldAssumption : fieldAssumptions) { for (FieldAssumption fieldAssumption : info.getFields(fieldVar.fieldVarName)) {
Constraint constraint = new Constraint(); Constraint constraint = new Constraint();
GenericsResolver resolver = getResolverInstance(); GenericsResolver resolver = getResolverInstance();
constraint.add(new Pair(fieldVar.receiver.getType(), fieldAssumption.getReceiverType(resolver), PairOperator.SMALLERDOT, loc(fieldVar.getOffset()))); // PL 2019-12-09: SMALLERDOT eingefuegt, EQUALSDOT entfernt, wenn ds Field privat ist muesste es EQUALSDOT lauten constraint.add(new Pair(fieldVar.receiver.getType(), fieldAssumption.getReceiverType(resolver), PairOperator.SMALLERDOT, loc(fieldVar.getOffset()))); // PL 2019-12-09: SMALLERDOT eingefuegt, EQUALSDOT entfernt, wenn ds Field privat ist muesste es EQUALSDOT lauten
constraint.add(new Pair(fieldVar.getType(), fieldAssumption.getType(resolver), PairOperator.EQUALSDOT, loc(fieldVar.getOffset()))); constraint.add(new Pair(fieldVar.getType(), fieldAssumption.getType(resolver), PairOperator.EQUALSDOT, loc(fieldVar.getOffset())));
oderConstraints.add(constraint); oderConstraints.add(constraint);
} }
if (oderConstraints.isEmpty()) if (oderConstraints.size() == 0)
throw new TypeinferenceException("Kein Feld " + fieldVar.fieldVarName + " gefunden", fieldVar.getOffset()); throw new TypeinferenceException("Kein Feld " + fieldVar.fieldVarName + " gefunden", fieldVar.getOffset());
constraintsSet.addOderConstraint(oderConstraints); constraintsSet.addOderConstraint(oderConstraints);
} }
@@ -144,7 +142,7 @@ public class TYPEStmt implements StatementVisitor {
@Override @Override
public void visit(ForEachStmt forEachStmt) { public void visit(ForEachStmt forEachStmt) {
var iterableType = new RefType(ASTFactory.createClass(java.lang.Iterable.class).getClassName(), List.of(new ExtendsWildcardType(forEachStmt.statement.getType(), new NullToken())), new NullToken()); var iterableType = new RefType(ASTFactory.createClass(java.lang.Iterable.class).getClassName(), Arrays.asList(new ExtendsWildcardType(forEachStmt.statement.getType(), new NullToken())), new NullToken());
constraintsSet.addUndConstraint(new Pair(forEachStmt.expression.getType(), iterableType, PairOperator.SMALLERDOT, loc(forEachStmt.getOffset()))); constraintsSet.addUndConstraint(new Pair(forEachStmt.expression.getType(), iterableType, PairOperator.SMALLERDOT, loc(forEachStmt.getOffset())));
forEachStmt.statement.accept(this); forEachStmt.statement.accept(this);
forEachStmt.expression.accept(this); forEachStmt.expression.accept(this);
@@ -192,7 +190,7 @@ public class TYPEStmt implements StatementVisitor {
methodCall.receiver.accept(this); methodCall.receiver.accept(this);
// Overloading: // Overloading:
Set<Constraint<Pair>> methodConstraints = new HashSet<>(); Set<Constraint<Pair>> methodConstraints = new HashSet<>();
for (MethodAssumption m : TYPEStmt.getMethods(methodCall.name, methodCall.arglist, info)) { for (MethodAssumption m : this.getMethods(methodCall.name, methodCall.arglist, info)) {
GenericsResolver resolver = getResolverInstance(); GenericsResolver resolver = getResolverInstance();
Set<Constraint<Pair>> oneMethodConstraints = generateConstraint(methodCall, m, info, resolver); Set<Constraint<Pair>> oneMethodConstraints = generateConstraint(methodCall, m, info, resolver);
methodConstraints.addAll(oneMethodConstraints); methodConstraints.addAll(oneMethodConstraints);
@@ -202,7 +200,7 @@ public class TYPEStmt implements StatementVisitor {
* oneMethodConstraint.setExtendConstraint(extendsOneMethodConstraint); extendsOneMethodConstraint.setExtendConstraint(oneMethodConstraint); methodConstraints.add(extendsOneMethodConstraint); * oneMethodConstraint.setExtendConstraint(extendsOneMethodConstraint); extendsOneMethodConstraint.setExtendConstraint(oneMethodConstraint); methodConstraints.add(extendsOneMethodConstraint);
*/ */
} }
if (methodConstraints.isEmpty()) { if (methodConstraints.size() < 1) {
throw new TypeinferenceException("Methode " + methodCall.name + " ist nicht vorhanden!", methodCall.getOffset()); throw new TypeinferenceException("Methode " + methodCall.name + " ist nicht vorhanden!", methodCall.getOffset());
} }
constraintsSet.addOderConstraint(methodConstraints); constraintsSet.addOderConstraint(methodConstraints);
@@ -215,7 +213,7 @@ public class TYPEStmt implements StatementVisitor {
for (MethodAssumption m : this.getConstructors(info, (RefType) methodCall.getType(), methodCall.getArgumentList())) { for (MethodAssumption m : this.getConstructors(info, (RefType) methodCall.getType(), methodCall.getArgumentList())) {
methodConstraints.add(generateConstructorConstraint(methodCall, m, info, getResolverInstance())); methodConstraints.add(generateConstructorConstraint(methodCall, m, info, getResolverInstance()));
} }
if (methodConstraints.isEmpty()) { if (methodConstraints.size() < 1) {
throw new TypeinferenceException("Konstruktor in Klasse " + methodCall.getType().toString() + " ist nicht vorhanden!", methodCall.getOffset()); throw new TypeinferenceException("Konstruktor in Klasse " + methodCall.getType().toString() + " ist nicht vorhanden!", methodCall.getOffset());
} }
constraintsSet.addOderConstraint(methodConstraints); constraintsSet.addOderConstraint(methodConstraints);
@@ -285,13 +283,8 @@ public class TYPEStmt implements StatementVisitor {
// see: https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.17 // see: https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.17
// Expression muss zu Numeric Convertierbar sein. also von Numeric erben // Expression muss zu Numeric Convertierbar sein. also von Numeric erben
Constraint<Pair> numeric; Constraint<Pair> numeric;
HashSet<JavaClassName> classNames = TypeUnifyTaskHelper.getPresizedHashSet(info.getAvailableClasses().size());
for (var classEl : info.getAvailableClasses()) {
classNames.add(classEl.getClassName());
}
// PL eingefuegt 2018-07-17 // PL eingefuegt 2018-07-17
if (classNames.contains(bytee.getName())) { if (info.getAvailableClasses().stream().map(x -> x.getClassName()).collect(Collectors.toCollection(HashSet::new)).contains(bytee.getName())) {
numeric = new Constraint<>(); numeric = new Constraint<>();
numeric.add(new Pair(binary.lexpr.getType(), bytee, PairOperator.SMALLERDOT, loc(binary.getOffset()))); numeric.add(new Pair(binary.lexpr.getType(), bytee, PairOperator.SMALLERDOT, loc(binary.getOffset())));
numeric.add(new Pair(binary.rexpr.getType(), bytee, PairOperator.SMALLERDOT, loc(binary.getOffset()))); numeric.add(new Pair(binary.rexpr.getType(), bytee, PairOperator.SMALLERDOT, loc(binary.getOffset())));
@@ -299,7 +292,7 @@ public class TYPEStmt implements StatementVisitor {
numericAdditionOrStringConcatenation.add(numeric); numericAdditionOrStringConcatenation.add(numeric);
} }
// PL eingefuegt 2018-07-17 // PL eingefuegt 2018-07-17
if (classNames.contains(shortt.getName())) { if (info.getAvailableClasses().stream().map(x -> x.getClassName()).collect(Collectors.toCollection(HashSet::new)).contains(shortt.getName())) {
numeric = new Constraint<>(); numeric = new Constraint<>();
numeric.add(new Pair(binary.lexpr.getType(), shortt, PairOperator.SMALLERDOT, loc(binary.getOffset()))); numeric.add(new Pair(binary.lexpr.getType(), shortt, PairOperator.SMALLERDOT, loc(binary.getOffset())));
numeric.add(new Pair(binary.rexpr.getType(), shortt, PairOperator.SMALLERDOT, loc(binary.getOffset()))); numeric.add(new Pair(binary.rexpr.getType(), shortt, PairOperator.SMALLERDOT, loc(binary.getOffset())));
@@ -307,7 +300,7 @@ public class TYPEStmt implements StatementVisitor {
numericAdditionOrStringConcatenation.add(numeric); numericAdditionOrStringConcatenation.add(numeric);
} }
// PL eingefuegt 2018-07-17 // PL eingefuegt 2018-07-17
if (classNames.contains(integer.getName())) { if (info.getAvailableClasses().stream().map(x -> x.getClassName()).collect(Collectors.toCollection(HashSet::new)).contains(integer.getName())) {
numeric = new Constraint<>(); numeric = new Constraint<>();
numeric.add(new Pair(binary.lexpr.getType(), integer, PairOperator.SMALLERDOT, loc(binary.getOffset()))); numeric.add(new Pair(binary.lexpr.getType(), integer, PairOperator.SMALLERDOT, loc(binary.getOffset())));
numeric.add(new Pair(binary.rexpr.getType(), integer, PairOperator.SMALLERDOT, loc(binary.getOffset()))); numeric.add(new Pair(binary.rexpr.getType(), integer, PairOperator.SMALLERDOT, loc(binary.getOffset())));
@@ -315,7 +308,7 @@ public class TYPEStmt implements StatementVisitor {
numericAdditionOrStringConcatenation.add(numeric); numericAdditionOrStringConcatenation.add(numeric);
} }
// PL eingefuegt 2018-07-17 // PL eingefuegt 2018-07-17
if (classNames.contains(longg.getName())) { if (info.getAvailableClasses().stream().map(x -> x.getClassName()).collect(Collectors.toCollection(HashSet::new)).contains(longg.getName())) {
numeric = new Constraint<>(); numeric = new Constraint<>();
numeric.add(new Pair(binary.lexpr.getType(), longg, PairOperator.SMALLERDOT, loc(binary.getOffset()))); numeric.add(new Pair(binary.lexpr.getType(), longg, PairOperator.SMALLERDOT, loc(binary.getOffset())));
numeric.add(new Pair(binary.rexpr.getType(), longg, PairOperator.SMALLERDOT, loc(binary.getOffset()))); numeric.add(new Pair(binary.rexpr.getType(), longg, PairOperator.SMALLERDOT, loc(binary.getOffset())));
@@ -323,7 +316,7 @@ public class TYPEStmt implements StatementVisitor {
numericAdditionOrStringConcatenation.add(numeric); numericAdditionOrStringConcatenation.add(numeric);
} }
// PL eingefuegt 2018-07-17 // PL eingefuegt 2018-07-17
if (classNames.contains(floatt.getName())) { if (info.getAvailableClasses().stream().map(x -> x.getClassName()).collect(Collectors.toCollection(HashSet::new)).contains(floatt.getName())) {
numeric = new Constraint<>(); numeric = new Constraint<>();
numeric.add(new Pair(binary.lexpr.getType(), floatt, PairOperator.SMALLERDOT, loc(binary.getOffset()))); numeric.add(new Pair(binary.lexpr.getType(), floatt, PairOperator.SMALLERDOT, loc(binary.getOffset())));
numeric.add(new Pair(binary.rexpr.getType(), floatt, PairOperator.SMALLERDOT, loc(binary.getOffset()))); numeric.add(new Pair(binary.rexpr.getType(), floatt, PairOperator.SMALLERDOT, loc(binary.getOffset())));
@@ -331,7 +324,7 @@ public class TYPEStmt implements StatementVisitor {
numericAdditionOrStringConcatenation.add(numeric); numericAdditionOrStringConcatenation.add(numeric);
} }
// PL eingefuegt 2018-07-17 // PL eingefuegt 2018-07-17
if (classNames.contains(doublee.getName())) { if (info.getAvailableClasses().stream().map(x -> x.getClassName()).collect(Collectors.toCollection(HashSet::new)).contains(doublee.getName())) {
numeric = new Constraint<>(); numeric = new Constraint<>();
numeric.add(new Pair(binary.lexpr.getType(), doublee, PairOperator.SMALLERDOT, loc(binary.getOffset()))); numeric.add(new Pair(binary.lexpr.getType(), doublee, PairOperator.SMALLERDOT, loc(binary.getOffset())));
numeric.add(new Pair(binary.rexpr.getType(), doublee, PairOperator.SMALLERDOT, loc(binary.getOffset()))); numeric.add(new Pair(binary.rexpr.getType(), doublee, PairOperator.SMALLERDOT, loc(binary.getOffset())));
@@ -346,7 +339,7 @@ public class TYPEStmt implements StatementVisitor {
if (binary.operation.equals(BinaryExpr.Operator.ADD)) { if (binary.operation.equals(BinaryExpr.Operator.ADD)) {
// Dann kann der Ausdruck auch das aneinanderfügen zweier Strings sein: ("a" + "b") oder (1 + 2) // Dann kann der Ausdruck auch das aneinanderfügen zweier Strings sein: ("a" + "b") oder (1 + 2)
if (classNames.contains(string.getName())) { if (info.getAvailableClasses().stream().map(x -> x.getClassName()).collect(Collectors.toCollection(HashSet::new)).contains(string.getName())) {
Constraint<Pair> stringConcat = new Constraint<>(); Constraint<Pair> stringConcat = new Constraint<>();
stringConcat.add(new Pair(binary.lexpr.getType(), string, PairOperator.EQUALSDOT, loc(binary.getOffset()))); stringConcat.add(new Pair(binary.lexpr.getType(), string, PairOperator.EQUALSDOT, loc(binary.getOffset())));
stringConcat.add(new Pair(binary.rexpr.getType(), string, PairOperator.EQUALSDOT, loc(binary.getOffset()))); stringConcat.add(new Pair(binary.rexpr.getType(), string, PairOperator.EQUALSDOT, loc(binary.getOffset())));
@@ -354,7 +347,7 @@ public class TYPEStmt implements StatementVisitor {
numericAdditionOrStringConcatenation.add(stringConcat); numericAdditionOrStringConcatenation.add(stringConcat);
} }
} }
if (numericAdditionOrStringConcatenation.isEmpty()) { if (numericAdditionOrStringConcatenation.size() < 1) {
throw new TypeinferenceException("Kein Typ für " + binary.operation.toString() + " vorhanden", binary.getOffset()); throw new TypeinferenceException("Kein Typ für " + binary.operation.toString() + " vorhanden", binary.getOffset());
} }
constraintsSet.addOderConstraint(numericAdditionOrStringConcatenation); constraintsSet.addOderConstraint(numericAdditionOrStringConcatenation);
@@ -643,7 +636,6 @@ public class TYPEStmt implements StatementVisitor {
params.add(resolver.resolve(new GenericRefType(gtv.getName(), new NullToken()))); params.add(resolver.resolve(new GenericRefType(gtv.getName(), new NullToken())));
} }
RefTypeOrTPHOrWildcardOrGeneric receiverType; RefTypeOrTPHOrWildcardOrGeneric receiverType;
if (receiver instanceof FunNClass) { if (receiver instanceof FunNClass) {
receiverType = new RefType(new JavaClassName(receiver.getClassName().toString() + "$$"), params, new NullToken()); // new FunN(params); receiverType = new RefType(new JavaClassName(receiver.getClassName().toString() + "$$"), params, new NullToken()); // new FunN(params);
} else { } else {
@@ -702,8 +694,8 @@ public class TYPEStmt implements StatementVisitor {
Set<Pair> methodSignatureConstraint = generatemethodSignatureConstraint(forMethod, assumption, info, resolver); Set<Pair> methodSignatureConstraint = generatemethodSignatureConstraint(forMethod, assumption, info, resolver);
//context.logger().info("methodSignatureConstraint: " + methodSignatureConstraint); //System.out.println("methodSignatureConstraint: " + methodSignatureConstraint);
//context.logger().info("methodConstraint: " + methodConstraint); //System.out.println("methodConstraint: " + methodConstraint);
methodConstraint.setmethodSignatureConstraint(methodSignatureConstraint); methodConstraint.setmethodSignatureConstraint(methodSignatureConstraint);
extendsMethodConstraint.setmethodSignatureConstraint(methodSignatureConstraint); extendsMethodConstraint.setmethodSignatureConstraint(methodSignatureConstraint);
@@ -741,7 +733,7 @@ public class TYPEStmt implements StatementVisitor {
} }
// Zuordnung von MethodCall.signature(ReturnType) zu dem ReturnType der ausgewaehlten Methode (assumption.returnType) // Zuordnung von MethodCall.signature(ReturnType) zu dem ReturnType der ausgewaehlten Methode (assumption.returnType)
ret.add(new Pair(foMethod.signature.getLast(), assumption.getReturnType(), PairOperator.EQUALSDOT)); ret.add(new Pair(foMethod.signature.get(foMethod.signature.size() - 1), assumption.getReturnType(), PairOperator.EQUALSDOT));
return ret; return ret;
} }
@@ -754,8 +746,8 @@ public class TYPEStmt implements StatementVisitor {
// funNParams.add(TypePlaceholder.fresh(new NullToken())); // funNParams.add(TypePlaceholder.fresh(new NullToken()));
funNParams.add(new GenericRefType(NameGenerator.makeNewName(), new NullToken())); funNParams.add(new GenericRefType(NameGenerator.makeNewName(), new NullToken()));
} }
funNParams.getLast(); funNParams.get(funNParams.size() - 1);
ret.add(new MethodAssumption(new FunNClass(funNParams), funNParams.getLast(), funNParams.subList(0, funNParams.size() - 1), new TypeScope() { ret.add(new MethodAssumption(new FunNClass(funNParams), funNParams.get(funNParams.size() - 1), funNParams.subList(0, funNParams.size() - 1), new TypeScope() {
@Override @Override
public Iterable<? extends GenericTypeVar> getGenerics() { public Iterable<? extends GenericTypeVar> getGenerics() {
throw new NotImplementedException(); throw new NotImplementedException();
@@ -850,7 +842,7 @@ public class TYPEStmt implements StatementVisitor {
for (var child : switchStmt.getBlocks()) { for (var child : switchStmt.getBlocks()) {
for (var label : child.getLabels()) { for (var label : child.getLabels()) {
if (label.getPattern() == null) { if (label.getPattern() == null) {
//context.logger().info("DefaultCase"); //System.out.println("DefaultCase");
} else { } else {
constraintsSet.addUndConstraint( constraintsSet.addUndConstraint(
new Pair( new Pair(
@@ -891,9 +883,13 @@ public class TYPEStmt implements StatementVisitor {
child.getLabels().forEach(el -> { child.getLabels().forEach(el -> {
if (el.getType() instanceof RefType) { if (el.getType() instanceof RefType) {
if (el.getPattern() instanceof RecordPattern pattern) { var recType = el;
recursivelyAddRecordConstraints(pattern);
} if (el.getPattern() instanceof RecordPattern) {
var pattern = (RecordPattern) recType.getPattern();
recursivelyAddRecordConstraints(pattern);
}
} }
}); });
@@ -909,13 +905,13 @@ public class TYPEStmt implements StatementVisitor {
var allClasses = info.getAvailableClasses(); var allClasses = info.getAvailableClasses();
var interestingClasses = allClasses.stream().filter(as -> as.getClassName().equals(((RefType) pattern.getType()).getName())).toList(); var interestingClasses = allClasses.stream().filter(as -> as.getClassName().equals(((RefType) pattern.getType()).getName())).toList();
var constructors = interestingClasses.getFirst().getConstructors(); var constructors = interestingClasses.get(0).getConstructors();
int counter = 0; int counter = 0;
for (var subPattern : pattern.getSubPattern()) { for (var subPattern : pattern.getSubPattern()) {
for (Constructor con : constructors) { for (Constructor con : constructors) {
//context.logger().info("----------------------\n" + subPattern.getType() + " | " + con.getParameterList().getParameterAt(counter).getType() + "\n----------------------\n"); //System.out.println("----------------------\n" + subPattern.getType() + " | " + con.getParameterList().getParameterAt(counter).getType() + "\n----------------------\n");
constraintsSet.addUndConstraint(new Pair(subPattern.getType(), con.getParameterList().getParameterAt(counter).getType(), PairOperator.SMALLERDOT, loc(con.getParameterList().getParameterAt(counter).getOffset()))); constraintsSet.addUndConstraint(new Pair(subPattern.getType(), con.getParameterList().getParameterAt(counter).getType(), PairOperator.SMALLERDOT, loc(con.getParameterList().getParameterAt(counter).getOffset())));
} }
if (subPattern instanceof RecordPattern) recursivelyAddRecordConstraints((RecordPattern) subPattern); if (subPattern instanceof RecordPattern) recursivelyAddRecordConstraints((RecordPattern) subPattern);
@@ -939,7 +935,7 @@ public class TYPEStmt implements StatementVisitor {
@Override @Override
public void visit(Yield aYield) { public void visit(Yield aYield) {
aYield.retexpr.accept(this); aYield.retexpr.accept(this);
constraintsSet.addUndConstraint(new Pair(aYield.getType(), switchStack.peek().getType(), PairOperator.SMALLERDOT, loc(aYield.getOffset()))); constraintsSet.addUndConstraint(new Pair(aYield.getType(), switchStack.peek().getType(), PairOperator.EQUALSDOT, loc(aYield.getOffset())));
// TODO Auto-generated method stub // TODO Auto-generated method stub
} }
} }

View File

@@ -1,7 +1,6 @@
package de.dhbwstuttgart.typeinference.unify; package de.dhbwstuttgart.typeinference.unify;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.RecursiveTask; import java.util.concurrent.RecursiveTask;
@@ -9,7 +8,7 @@ import java.util.concurrent.atomic.AtomicBoolean;
/** /**
* An intermediate class for the recursive steps of the TypeUnifyTask: * An intermediate class for the recursive steps of the TypeUnifyTask:
* This allows canceling parts of the recursion tree, instead of only the whole execution as before. But in * This allows to cancel parts of the recursion tree, instead of only the whole execution as before. But in
* order for that to work, all cancellable child tasks must be added when they are created * order for that to work, all cancellable child tasks must be added when they are created
* *
* @param <T> * @param <T>
@@ -17,45 +16,26 @@ import java.util.concurrent.atomic.AtomicBoolean;
public abstract class CancellableTask<T> extends RecursiveTask<T> { public abstract class CancellableTask<T> extends RecursiveTask<T> {
private final AtomicBoolean executionCancelled = new AtomicBoolean(false); private final AtomicBoolean executionCancelled = new AtomicBoolean(false);
private final List<CancellableTask<?>> childTasks = new LinkedList<>(); private final List<CancellableTask<?>> childTasks = new ArrayList<>();
private CancellableTask<?> parentTask = null; private CancellableTask<?> parentTask = null;
/** /**
* Set the execution for this task and all its (recursive) children to be canceled * Set the execution for this task and all its (recursive) children to be cancelled
*/ */
protected void cancelExecution() { protected void cancelExecution() {
// is this branch already canceled? Then do nothing // is this branch already cancelled? Then do nothing
if (this.executionCancelled.getAndSet(true)) return; if (this.executionCancelled.get()) return;
executionCancelled.set(true);
this.cancelChildExecution(); this.cancelChildExecution();
} }
private void cancelChildExecution() { public void cancelChildExecution() {
synchronized (this.childTasks) {
for (var childTask : childTasks) {
// no need to cancel a branch that is already finished
if (!childTask.isDone()) {
childTask.cancelExecution();
}
}
}
}
private void cancelChildExecutionAfter(CancellableTask<?> checkpointTask) {
boolean reachedCheckpoint = false;
int i = 0;
for (var childTask : childTasks) { for (var childTask : childTasks) {
if (!reachedCheckpoint) { // no need to cancel a branch that is already finished
reachedCheckpoint = childTask == checkpointTask; if (!childTask.isDone()) {
} childTask.cancelExecution();
else {
// no need to cancel a branch that is already finished
if (!childTask.isDone()) {
childTask.cancelExecution();
}
i++;
} }
} }
System.out.println("Skipped " + i + " younger siblings");
} }
protected void cancelSiblingTasks() { protected void cancelSiblingTasks() {
@@ -66,12 +46,6 @@ public abstract class CancellableTask<T> extends RecursiveTask<T> {
} }
} }
public void cancelYoungerSiblingTasks() {
if (this.parentTask != null) {
this.parentTask.cancelChildExecutionAfter(this);
}
}
public Boolean isExecutionCancelled() { public Boolean isExecutionCancelled() {
return executionCancelled.get(); return executionCancelled.get();
} }
@@ -79,9 +53,6 @@ public abstract class CancellableTask<T> extends RecursiveTask<T> {
public void addChildTask(CancellableTask<?> childTask) { public void addChildTask(CancellableTask<?> childTask) {
this.childTasks.add(childTask); this.childTasks.add(childTask);
childTask.setParentTask(this); childTask.setParentTask(this);
if (this.executionCancelled.get()) {
childTask.executionCancelled.set(true);
}
} }
private void setParentTask(CancellableTask<?> parentTask) { private void setParentTask(CancellableTask<?> parentTask) {

View File

@@ -37,6 +37,9 @@ public class ConcurrentSetMergeTask<T> extends RecursiveTask<Set<T>> {
totalElements += list.get(i).size(); totalElements += list.get(i).size();
} }
System.out.println("ConcurrentSetMerge? -> " + (size <= LIST_THRESHOLD || totalElements < ELEMENT_THRESHOLD ? "true" : "false"));
// size will always be at least one // size will always be at least one
if (true || size <= LIST_THRESHOLD || totalElements < ELEMENT_THRESHOLD) { if (true || size <= LIST_THRESHOLD || totalElements < ELEMENT_THRESHOLD) {
Set<T> result = this.list.get(start); Set<T> result = this.list.get(start);

View File

@@ -94,8 +94,8 @@ public class MartelliMontanariUnify implements IUnify {
// SUBST - Rule // SUBST - Rule
if(lhsType instanceof PlaceholderType) { if(lhsType instanceof PlaceholderType) {
mgu.add((PlaceholderType) lhsType, rhsType); mgu.add((PlaceholderType) lhsType, rhsType);
//PL 2018-04-01 nach checken, ob es richtig ist, dass keine Substitutionen uebergeben werden muessen. //PL 2018-04-01 nach checken, ob es richtig ist, dass keine Substitutionen uebergeben werden muessen.
termsList.replaceAll(mgu::apply); termsList = termsList.stream().map(x -> mgu.apply(x)).collect(Collectors.toCollection(ArrayList::new));
idx = idx+1 == termsList.size() ? 0 : idx+1; idx = idx+1 == termsList.size() ? 0 : idx+1;
continue; continue;
} }

View File

@@ -1,12 +1,10 @@
package de.dhbwstuttgart.typeinference.unify; package de.dhbwstuttgart.typeinference.unify;
import de.dhbwstuttgart.util.Logger;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.ListIterator;
import java.util.Optional; import java.util.Optional;
import java.util.Queue; import java.util.Queue;
import java.util.Set; import java.util.Set;
@@ -14,16 +12,24 @@ import java.util.Stack;
import java.util.function.Function; import java.util.function.Function;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import de.dhbwstuttgart.core.JavaTXCompiler;
import de.dhbwstuttgart.exceptions.DebugException; import de.dhbwstuttgart.exceptions.DebugException;
import de.dhbwstuttgart.syntaxtree.factory.UnifyTypeFactory;
import de.dhbwstuttgart.syntaxtree.type.ExtendsWildcardType;
import de.dhbwstuttgart.syntaxtree.type.RefType;
import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure; import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure;
import de.dhbwstuttgart.typeinference.unify.interfaces.IRuleSet; import de.dhbwstuttgart.typeinference.unify.interfaces.IRuleSet;
import de.dhbwstuttgart.typeinference.unify.model.*; import de.dhbwstuttgart.typeinference.unify.model.*;
import de.dhbwstuttgart.typeinference.constraints.Constraint; import de.dhbwstuttgart.typeinference.constraints.Constraint;
import de.dhbwstuttgart.typeinference.unify.distributeVariance;
import java.io.FileWriter;
import java.io.IOException; import java.io.IOException;
import java.io.Writer; import java.io.Writer;
import java.io.OutputStreamWriter; import java.io.OutputStreamWriter;
import org.apache.commons.io.output.NullOutputStream;
/** /**
* Implementation of the type inference rules. * Implementation of the type inference rules.
* @author Florian Steurer * @author Florian Steurer
@@ -31,17 +37,17 @@ import java.io.OutputStreamWriter;
*/ */
public class RuleSet implements IRuleSet{ public class RuleSet implements IRuleSet{
Logger logger; Writer logFile;
final PlaceholderRegistry placeholderRegistry; final PlaceholderRegistry placeholderRegistry;
public RuleSet(PlaceholderRegistry placeholderRegistry) { public RuleSet(PlaceholderRegistry placeholderRegistry) {
super(); super();
logger = Logger.NULL_LOGGER; logFile = OutputStreamWriter.nullWriter();
this.placeholderRegistry = placeholderRegistry; this.placeholderRegistry = placeholderRegistry;
} }
RuleSet(Logger logger, PlaceholderRegistry placeholderRegistry) { RuleSet(Writer logFile, PlaceholderRegistry placeholderRegistry) {
this.logger = logger; this.logFile = logFile;
this.placeholderRegistry = placeholderRegistry; this.placeholderRegistry = placeholderRegistry;
} }
@@ -294,8 +300,8 @@ public class RuleSet implements IRuleSet{
if(dFromFc == null || !dFromFc.getTypeParams().arePlaceholders() || dFromFc.getTypeParams().size() != cFromFc.getTypeParams().size()) if(dFromFc == null || !dFromFc.getTypeParams().arePlaceholders() || dFromFc.getTypeParams().size() != cFromFc.getTypeParams().size())
return Optional.empty(); return Optional.empty();
//context.logger().info("cFromFc: " + cFromFc); //System.out.println("cFromFc: " + cFromFc);
//context.logger().info("dFromFc: " + dFromFc); //System.out.println("dFromFc: " + dFromFc);
int[] pi = pi(cFromFc.getTypeParams(), dFromFc.getTypeParams()); int[] pi = pi(cFromFc.getTypeParams(), dFromFc.getTypeParams());
if(pi.length == 0) if(pi.length == 0)
@@ -504,17 +510,17 @@ public class RuleSet implements IRuleSet{
TypeParams typeDParams = typeD.getTypeParams(); TypeParams typeDParams = typeD.getTypeParams();
TypeParams typeDgenParams = typeDgen.getTypeParams(); TypeParams typeDgenParams = typeDgen.getTypeParams();
//context.logger().info("Pair: " +pair); //System.out.println("Pair: " +pair);
//context.logger().info("typeD: " +typeD); //System.out.println("typeD: " +typeD);
//context.logger().info("typeDParams: " +typeDParams); //System.out.println("typeDParams: " +typeDParams);
//context.logger().info("typeDgen: " +typeD); //System.out.println("typeDgen: " +typeD);
//context.logger().info("typeDgenParams: " +typeDgenParams); //System.out.println("typeDgenParams: " +typeDgenParams);
Unifier unif = Unifier.identity(); Unifier unif = Unifier.identity();
for(int i = 0; i < typeDParams.size(); i++) { for(int i = 0; i < typeDParams.size(); i++) {
//context.logger().info("ADAPT" +typeDgenParams); //System.out.println("ADAPT" +typeDgenParams);
if (typeDgenParams.get(i) instanceof PlaceholderType) if (typeDgenParams.get(i) instanceof PlaceholderType)
unif.add((PlaceholderType) typeDgenParams.get(i), typeDParams.get(i)); unif.add((PlaceholderType) typeDgenParams.get(i), typeDParams.get(i));
else logger.exception(new Exception("ERROR in adapt rule: cannot add non placeholder type")); else System.out.println("ERROR");
} }
return Optional.of(new UnifyPair(unif.apply(newLhs), typeDs, PairOperator.SMALLERDOT, pair.getSubstitution(), pair.getBasePair())); return Optional.of(new UnifyPair(unif.apply(newLhs), typeDs, PairOperator.SMALLERDOT, pair.getSubstitution(), pair.getBasePair()));
} }
@@ -649,17 +655,15 @@ public class RuleSet implements IRuleSet{
@Override @Override
public Optional<Set<UnifyPair>> subst(Set<UnifyPair> pairs, List<Set<Constraint<UnifyPair>>> oderConstraints) { public Optional<Set<UnifyPair>> subst(Set<UnifyPair> pairs, List<Set<Constraint<UnifyPair>>> oderConstraints) {
// Statistically, typeMap will fill up quickly and resize multiple times. To reduce this, we start with a higher capacity HashMap<UnifyType, Integer> typeMap = new HashMap<>();
HashMap<UnifyType, Integer> typeMap = new HashMap<>(200);
Stack<UnifyType> occuringTypes = new Stack<>(); Stack<UnifyType> occuringTypes = new Stack<>();
occuringTypes.ensureCapacity(pairs.size() * 3);
for(UnifyPair pair : pairs) { for(UnifyPair pair : pairs) {
occuringTypes.push(pair.getLhsType()); occuringTypes.push(pair.getLhsType());
occuringTypes.push(pair.getRhsType()); occuringTypes.push(pair.getRhsType());
} }
while(!occuringTypes.isEmpty()) { while(!occuringTypes.isEmpty()) {
UnifyType t1 = occuringTypes.pop(); UnifyType t1 = occuringTypes.pop();
if(!typeMap.containsKey(t1)) if(!typeMap.containsKey(t1))
@@ -671,12 +675,12 @@ public class RuleSet implements IRuleSet{
if(t1 instanceof SuperType) if(t1 instanceof SuperType)
occuringTypes.push(((SuperType) t1).getSuperedType()); occuringTypes.push(((SuperType) t1).getSuperedType());
else else
t1.getTypeParams().forEach(occuringTypes::push); t1.getTypeParams().forEach(x -> occuringTypes.push(x));
} }
LinkedList<UnifyPair> result1 = new LinkedList<UnifyPair>(pairs); Queue<UnifyPair> result1 = new LinkedList<UnifyPair>(pairs);
ArrayList<UnifyPair> result = new ArrayList<UnifyPair>(); ArrayList<UnifyPair> result = new ArrayList<UnifyPair>();
boolean applied = false; boolean applied = false;
while(!result1.isEmpty()) { while(!result1.isEmpty()) {
UnifyPair pair = result1.poll(); UnifyPair pair = result1.poll();
PlaceholderType lhsType = null; PlaceholderType lhsType = null;
@@ -694,30 +698,19 @@ public class RuleSet implements IRuleSet{
&& !((rhsType instanceof WildcardType) && ((WildcardType)rhsType).getWildcardedType().equals(lhsType))) //PL eigefuegt 2018-02-18 && !((rhsType instanceof WildcardType) && ((WildcardType)rhsType).getWildcardedType().equals(lhsType))) //PL eigefuegt 2018-02-18
{ {
Unifier uni = new Unifier(lhsType, rhsType); Unifier uni = new Unifier(lhsType, rhsType);
// apply unifier to result and result1 in place result = result.stream().map(x -> uni.apply(pair,x)).collect(Collectors.toCollection(ArrayList::new));
result.replaceAll(p -> uni.apply(pair, p)); result1 = result1.stream().map(x -> uni.apply(pair,x)).collect(Collectors.toCollection(LinkedList::new));
ListIterator<UnifyPair> result1Iterator = result1.listIterator();
while (result1Iterator.hasNext()) {
UnifyPair x = result1Iterator.next();
result1Iterator.set(uni.apply(pair, x));
}
Function<? super Constraint<UnifyPair>,? extends Constraint<UnifyPair>> applyUni = b -> b.stream().map( Function<? super Constraint<UnifyPair>,? extends Constraint<UnifyPair>> applyUni = b -> b.stream().map(
x -> uni.apply(pair,x)).collect(Collectors.toCollection((b.getExtendConstraint() != null) x -> uni.apply(pair,x)).collect(Collectors.toCollection((b.getExtendConstraint() != null)
? () -> new Constraint<UnifyPair>( ? () -> new Constraint<UnifyPair>(
b.isInherited(), b.isInherited(),
b.isImplemented(), b.isImplemented(),
b.getExtendConstraint().createdMapped(x -> uni.apply(pair,x)), b.getExtendConstraint().stream().map(x -> uni.apply(pair,x)).collect(Collectors.toCollection(Constraint::new)),
b.getmethodSignatureConstraint().stream().map(x -> uni.apply(pair,x)).collect(Collectors.toCollection(HashSet::new))) b.getmethodSignatureConstraint().stream().map(x -> uni.apply(pair,x)).collect(Collectors.toCollection(HashSet::new)))
: () -> new Constraint<UnifyPair>(b.isInherited(), b.isImplemented()) : () -> new Constraint<UnifyPair>(b.isInherited(), b.isImplemented())
)); ));
oderConstraints.replaceAll(oc -> { oderConstraints.replaceAll(oc -> oc.stream().map(applyUni).collect(Collectors.toCollection(HashSet::new)));
HashSet<Constraint<UnifyPair>> mapped = new HashSet<>(oc.size());
for (var element : oc) {
mapped.add(applyUni.apply(element));
}
return mapped;
});
/* /*
oderConstraints = oderConstraints.stream().map( oderConstraints = oderConstraints.stream().map(
a -> a.stream().map(applyUni a -> a.stream().map(applyUni
@@ -871,11 +864,14 @@ public class RuleSet implements IRuleSet{
UnifyType r = x.getRhsType(); UnifyType r = x.getRhsType();
if (r instanceof PlaceholderType) { ((PlaceholderType)r).disableWildcardtable(); } if (r instanceof PlaceholderType) { ((PlaceholderType)r).disableWildcardtable(); }
} ); } );
try {
logger.debug(() -> "FUNgreater: " + pair); logFile.write("FUNgreater: " + pair + "\n");
logger.debug(() -> "FUNred: " + result); logFile.write("FUNred: " + result + "\n");
// logFile.flush();
}
catch (IOException e) {
System.out.println("logFile-Error");
}
return Optional.of(result); return Optional.of(result);
} }
@@ -941,8 +937,8 @@ public class RuleSet implements IRuleSet{
Set<UnifyPair> result = new HashSet<UnifyPair>(); Set<UnifyPair> result = new HashSet<UnifyPair>();
int variance = ((PlaceholderType)rhsType).getVariance(); Integer variance = ((PlaceholderType)rhsType).getVariance();
int inversVariance = distributeVariance.inverseVariance(variance); Integer inversVariance = distributeVariance.inverseVariance(variance);
UnifyType[] freshPlaceholders = new UnifyType[funNLhsType.getTypeParams().size()]; UnifyType[] freshPlaceholders = new UnifyType[funNLhsType.getTypeParams().size()];
for(int i = 0; i < freshPlaceholders.length-1; i++) { for(int i = 0; i < freshPlaceholders.length-1; i++) {
@@ -960,14 +956,18 @@ public class RuleSet implements IRuleSet{
result.add(new UnifyPair(rhsType, funNLhsType.setTypeParams(new TypeParams(freshPlaceholders)), PairOperator.EQUALSDOT, pair.getSubstitution(), pair.getBasePair())); result.add(new UnifyPair(rhsType, funNLhsType.setTypeParams(new TypeParams(freshPlaceholders)), PairOperator.EQUALSDOT, pair.getSubstitution(), pair.getBasePair()));
result.stream().forEach(x -> { UnifyType l = x.getLhsType(); result.stream().forEach(x -> { UnifyType l = x.getLhsType();
if (l instanceof PlaceholderType) { ((PlaceholderType)l).disableWildcardtable(); } if (l instanceof PlaceholderType) { ((PlaceholderType)l).disableWildcardtable(); }
UnifyType r = x.getRhsType(); UnifyType r = x.getRhsType();
if (r instanceof PlaceholderType) { ((PlaceholderType)r).disableWildcardtable(); } if (r instanceof PlaceholderType) { ((PlaceholderType)r).disableWildcardtable(); }
} ); } );
try {
logger.debug(() -> "FUNgreater: " + pair); logFile.write("FUNgreater: " + pair + "\n");
logger.debug(() -> "FUNgreater: " + result); logFile.write("FUNgreater: " + result + "\n");
// logFile.flush();
}
catch (IOException e) {
System.out.println("lofFile-Error");
}
return Optional.of(result); return Optional.of(result);
} }
@@ -986,8 +986,8 @@ public class RuleSet implements IRuleSet{
Set<UnifyPair> result = new HashSet<UnifyPair>(); Set<UnifyPair> result = new HashSet<UnifyPair>();
int variance = ((PlaceholderType)lhsType).getVariance(); Integer variance = ((PlaceholderType)lhsType).getVariance();
int inversVariance = distributeVariance.inverseVariance(variance); Integer inversVariance = distributeVariance.inverseVariance(variance);
UnifyType[] freshPlaceholders = new UnifyType[funNRhsType.getTypeParams().size()]; UnifyType[] freshPlaceholders = new UnifyType[funNRhsType.getTypeParams().size()];
for(int i = 0; i < freshPlaceholders.length-1; i++) { for(int i = 0; i < freshPlaceholders.length-1; i++) {
@@ -1006,15 +1006,18 @@ public class RuleSet implements IRuleSet{
result.add(new UnifyPair(lhsType, funNRhsType.setTypeParams(new TypeParams(freshPlaceholders)), PairOperator.EQUALSDOT, pair.getSubstitution(), pair.getBasePair())); result.add(new UnifyPair(lhsType, funNRhsType.setTypeParams(new TypeParams(freshPlaceholders)), PairOperator.EQUALSDOT, pair.getSubstitution(), pair.getBasePair()));
result.stream().forEach(x -> { UnifyType l = x.getLhsType(); result.stream().forEach(x -> { UnifyType l = x.getLhsType();
if (l instanceof PlaceholderType) { ((PlaceholderType)l).disableWildcardtable(); } if (l instanceof PlaceholderType) { ((PlaceholderType)l).disableWildcardtable(); }
UnifyType r = x.getRhsType(); UnifyType r = x.getRhsType();
if (r instanceof PlaceholderType) { ((PlaceholderType)r).disableWildcardtable(); } if (r instanceof PlaceholderType) { ((PlaceholderType)r).disableWildcardtable(); }
} ); } );
try {
logFile.write("FUNgreater: " + pair + "\n");
logger.debug(() -> "FUNgreater: " + pair); logFile.write("FUNsmaller: " + result + "\n");
logger.debug(() -> "FUNsmaller: " + result); // logFile.flush();
}
catch (IOException e) {
System.out.println("lofFile-Error");
}
return Optional.of(result); return Optional.of(result);
} }

View File

@@ -29,12 +29,17 @@ public class TypeUnify {
* unify parallel ohne result modell * unify parallel ohne result modell
*/ */
public static Set<Set<UnifyPair>> unify(Set<UnifyPair> undConstrains, List<Set<Constraint<UnifyPair>>> oderConstraints, IFiniteClosure fc, UnifyContext unifyContext) { public static Set<Set<UnifyPair>> unify(Set<UnifyPair> undConstrains, List<Set<Constraint<UnifyPair>>> oderConstraints, IFiniteClosure fc, UnifyContext unifyContext) {
ForkJoinPool pool = TypeUnify.createThreadPool(unifyContext.logger()); ForkJoinPool pool = TypeUnify.createThreadPool();
UnifyContext context = unifyContext.newWithParallel(true).newWithExecutor(pool); UnifyContext context = unifyContext.newWithParallel(true).newWithExecutor(pool);
TypeUnifyTask unifyTask = new TypeUnifyTask(undConstrains, oderConstraints, fc, context, 0); TypeUnifyTask unifyTask = new TypeUnifyTask(undConstrains, oderConstraints, fc, context, 0);
Set<Set<UnifyPair>> res = joinFuture(unifyTask.compute()); Set<Set<UnifyPair>> res = joinFuture(unifyTask.compute());
try {
unifyContext.logger().debug("\nnoShortendElements: " + TypeUnifyTask.noShortendElements + "\n"); unifyContext.logFile().write("\nnoShortendElements: " + TypeUnifyTask.noShortendElements + "\n");
// logFile.flush();
}
catch (IOException e) {
System.err.println("no log-File");
}
return res; return res;
} }
@@ -42,7 +47,7 @@ public class TypeUnify {
* unify asynchron mit Rückgabe UnifyResultModel ohne dass alle results gesammelt sind * unify asynchron mit Rückgabe UnifyResultModel ohne dass alle results gesammelt sind
*/ */
public static UnifyResultModel unifyAsync(Set<UnifyPair> undConstrains, List<Set<Constraint<UnifyPair>>> oderConstraints, IFiniteClosure fc, UnifyContext unifyContext) { public static UnifyResultModel unifyAsync(Set<UnifyPair> undConstrains, List<Set<Constraint<UnifyPair>>> oderConstraints, IFiniteClosure fc, UnifyContext unifyContext) {
ForkJoinPool pool = TypeUnify.createThreadPool(unifyContext.logger()); ForkJoinPool pool = TypeUnify.createThreadPool();
UnifyContext context = unifyContext.newWithExecutor(pool); UnifyContext context = unifyContext.newWithExecutor(pool);
TypeUnifyTask unifyTask = new TypeUnifyTask(undConstrains, oderConstraints, fc, context, 0); TypeUnifyTask unifyTask = new TypeUnifyTask(undConstrains, oderConstraints, fc, context, 0);
unifyTask.compute(); unifyTask.compute();
@@ -53,12 +58,18 @@ public class TypeUnify {
* unify parallel mit Rückgabe UnifyResultModel nachdem alle results gesammelt sind * unify parallel mit Rückgabe UnifyResultModel nachdem alle results gesammelt sind
*/ */
public static Set<Set<UnifyPair>> unifyParallel(Set<UnifyPair> undConstrains, List<Set<Constraint<UnifyPair>>> oderConstraints, IFiniteClosure fc, UnifyContext unifyContext) { public static Set<Set<UnifyPair>> unifyParallel(Set<UnifyPair> undConstrains, List<Set<Constraint<UnifyPair>>> oderConstraints, IFiniteClosure fc, UnifyContext unifyContext) {
ForkJoinPool pool = TypeUnify.createThreadPool(unifyContext.logger()); ForkJoinPool pool = TypeUnify.createThreadPool();
UnifyContext context = unifyContext.newWithParallel(true).newWithExecutor(pool); UnifyContext context = unifyContext.newWithParallel(true).newWithExecutor(pool);
TypeUnifyTask unifyTask = new TypeUnifyTask(undConstrains, oderConstraints, fc, context, 0); TypeUnifyTask unifyTask = new TypeUnifyTask(undConstrains, oderConstraints, fc, context, 0);
var result = joinFuture(unifyTask.compute()); var result = joinFuture(unifyTask.compute());
unifyContext.logger().debug("\nnoShortendElements: " + TypeUnifyTask.noShortendElements + "\n"); try {
unifyContext.logFile().write("\nnoShortendElements: " + TypeUnifyTask.noShortendElements +"\n");
// logFile.flush();
}
catch (IOException e) {
System.err.println("no log-File");
}
return result; return result;
} }
@@ -76,12 +87,18 @@ public class TypeUnify {
public static Set<Set<UnifyPair>> unifyOderConstraints(Set<UnifyPair> undConstrains, List<Set<Constraint<UnifyPair>>> oderConstraints, IFiniteClosure fc, UnifyContext unifyContext) { public static Set<Set<UnifyPair>> unifyOderConstraints(Set<UnifyPair> undConstrains, List<Set<Constraint<UnifyPair>>> oderConstraints, IFiniteClosure fc, UnifyContext unifyContext) {
TypeUnifyTask unifyTask = new TypeUnifyTask(undConstrains, oderConstraints, fc, unifyContext.newWithParallel(false), 0); TypeUnifyTask unifyTask = new TypeUnifyTask(undConstrains, oderConstraints, fc, unifyContext.newWithParallel(false), 0);
Set<Set<UnifyPair>> res = joinFuture(unifyTask.compute()); Set<Set<UnifyPair>> res = joinFuture(unifyTask.compute());
unifyContext.logger().debug("\nnoShortendElements: " + TypeUnifyTask.noShortendElements +"\n"); try {
unifyContext.logFile().write("\nnoShortendElements: " + TypeUnifyTask.noShortendElements +"\n");
// logFile.flush();
}
catch (IOException e) {
System.err.println("no log-File");
}
return res; return res;
} }
private static ForkJoinPool createThreadPool(Logger logger) { private static ForkJoinPool createThreadPool() {
logger.info("Available processors: " + Runtime.getRuntime().availableProcessors()); Logger.print("Available processors: " + Runtime.getRuntime().availableProcessors());
return new ForkJoinPool( return new ForkJoinPool(
Runtime.getRuntime().availableProcessors(), Runtime.getRuntime().availableProcessors(),
ForkJoinPool.defaultForkJoinWorkerThreadFactory, ForkJoinPool.defaultForkJoinWorkerThreadFactory,

View File

@@ -34,7 +34,7 @@ public class TypeUnify2Task extends TypeUnifyTask {
@Override @Override
public CompletableFuture<Set<Set<UnifyPair>>> compute() { public CompletableFuture<Set<Set<UnifyPair>>> compute() {
if (one) { if (one) {
context.logger().info("two"); System.out.println("two");
} }
one = true; one = true;
CompletableFuture<Set<Set<UnifyPair>>> res = CompletableFuture<Set<Set<UnifyPair>>> res =
@@ -45,7 +45,7 @@ public class TypeUnify2Task extends TypeUnifyTask {
*/ */
//writeLog("xxx"); //writeLog("xxx");
//noOfThread--; //noOfThread--;
if (this.isExecutionCancelled()) { if (this.myIsCancelled()) {
return CompletableFuture.completedFuture(new HashSet<>()); return CompletableFuture.completedFuture(new HashSet<>());
} else { } else {
return res; return res;
@@ -53,6 +53,12 @@ public class TypeUnify2Task extends TypeUnifyTask {
} }
public void closeLogFile() { public void closeLogFile() {
context.logger().close();
try {
context.logFile().close();
} catch (IOException ioE) {
System.err.println("no log-File");
}
} }
} }

View File

@@ -1,10 +1,8 @@
//PL 2018-12-19: Merge checken //PL 2018-12-19: Merge checken
package de.dhbwstuttgart.typeinference.unify; package de.dhbwstuttgart.typeinference.unify;
import de.dhbwstuttgart.core.ConsoleInterface;
import de.dhbwstuttgart.exceptions.TypeinferenceException; import de.dhbwstuttgart.exceptions.TypeinferenceException;
import de.dhbwstuttgart.parser.NullToken; import de.dhbwstuttgart.parser.NullToken;
import de.dhbwstuttgart.server.ServerTaskLogger;
import de.dhbwstuttgart.typeinference.constraints.Constraint; import de.dhbwstuttgart.typeinference.constraints.Constraint;
import de.dhbwstuttgart.typeinference.unify.cartesianproduct.VarianceCase; import de.dhbwstuttgart.typeinference.unify.cartesianproduct.VarianceCase;
import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure; import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure;
@@ -28,7 +26,11 @@ import de.dhbwstuttgart.typeinference.unify.model.WildcardType;
import de.dhbwstuttgart.util.Logger; import de.dhbwstuttgart.util.Logger;
import de.dhbwstuttgart.util.Pair; import de.dhbwstuttgart.util.Pair;
import de.dhbwstuttgart.util.Tuple; import de.dhbwstuttgart.util.Tuple;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Serial; import java.io.Serial;
import java.io.Writer;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collection; import java.util.Collection;
@@ -43,10 +45,13 @@ import java.util.Optional;
import java.util.Set; import java.util.Set;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.RecursiveTask; import java.util.concurrent.RecursiveTask;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiFunction; import java.util.function.BiFunction;
import java.util.function.BinaryOperator; import java.util.function.BinaryOperator;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import org.apache.commons.io.output.NullOutputStream;
/** /**
@@ -61,7 +66,7 @@ public class TypeUnifyTask extends CancellableTask<CompletableFuture<Set<Set<Uni
private static int i = 0; private static int i = 0;
private final boolean printtag = false; private final boolean printtag = false;
public final UnifyContext context; final UnifyContext context;
/** /**
* Element, das aus dem nextSet den Gleichunen dieses Threads hinzugefuegt wurde * Element, das aus dem nextSet den Gleichunen dieses Threads hinzugefuegt wurde
@@ -103,19 +108,21 @@ public class TypeUnifyTask extends CancellableTask<CompletableFuture<Set<Set<Uni
int rekTiefeField; int rekTiefeField;
int nOfUnify = 0; Integer nOfUnify = 0;
int noUndefPair = 0; Integer noUndefPair = 0;
int noAllErasedElements = 0; Integer noAllErasedElements = 0;
// some statistics for local output (they will not make sense when executed on the server) // some statistics for local output (they will not make sense when executed on the server)
public static int noBacktracking; public static int noBacktracking;
public static int noShortendElements; public static int noShortendElements;
public static int noou = 0; public static int noou = 0;
Boolean myIsCanceled = false;
public TypeUnifyTask(UnifyContext context) { public TypeUnifyTask(UnifyContext context) {
this.context = context.newWithLogger(Logger.NULL_LOGGER); this.context = context.newWithLogFile(new OutputStreamWriter(NullOutputStream.INSTANCE));
rules = new RuleSet(context.placeholderRegistry()); rules = new RuleSet(context.placeholderRegistry());
} }
@@ -150,19 +157,24 @@ public class TypeUnifyTask extends CancellableTask<CompletableFuture<Set<Set<Uni
this.fc = fc; this.fc = fc;
this.oup = new OrderingUnifyPair(fc, context); this.oup = new OrderingUnifyPair(fc, context);
this.context = (!ConsoleInterface.writeLogFiles || context.logger() instanceof ServerTaskLogger) ? context : context.newWithLogger( Writer logFileWriter = OutputStreamWriter.nullWriter();
Logger.forFile( if (context.log()) {
System.getProperty("user.dir") + "/logFiles/" + "Thread", try {
"Unify" logFileWriter = new FileWriter(System.getProperty("user.dir") + "/logFiles/" + "Thread");
) logFileWriter.write("");
); } catch (IOException e) {
System.err.println("log-File nicht vorhanden");
}
}
this.context = context.newWithLogFile(logFileWriter);
/*Abbruchtest /*Abbruchtest
if (thNo > 10) { if (thNo > 10) {
context.logger().info("cancel"); System.out.println("cancel");
usedTasks.cancel(); usedTasks.cancel();
writeLog(nOfUnify.toString() + "cancel"); writeLog(nOfUnify.toString() + "cancel");
context.logger().info("cancel"); System.out.println("cancel");
try { try {
logFile.write("Abbruch"); logFile.write("Abbruch");
} }
@@ -171,7 +183,7 @@ public class TypeUnifyTask extends CancellableTask<CompletableFuture<Set<Set<Uni
} }
} }
*/ */
rules = new RuleSet(context.logger(), context.placeholderRegistry()); rules = new RuleSet(context.logFile(), context.placeholderRegistry());
this.rekTiefeField = rekTiefe; this.rekTiefeField = rekTiefe;
context.usedTasks().add(this); context.usedTasks().add(this);
} }
@@ -208,10 +220,17 @@ public class TypeUnifyTask extends CancellableTask<CompletableFuture<Set<Set<Uni
} }
} }
*/ */
void myCancel(Boolean b) {
myIsCanceled = true;
}
public boolean myIsCancelled() {
return myIsCanceled;
}
public CompletableFuture<Set<Set<UnifyPair>>> compute() { public CompletableFuture<Set<Set<UnifyPair>>> compute() {
if (one) { if (one) {
context.logger().info("two"); System.out.println("two");
} }
one = true; one = true;
Set<UnifyPair> neweq = new HashSet<>(eq); Set<UnifyPair> neweq = new HashSet<>(eq);
@@ -228,7 +247,11 @@ public class TypeUnifyTask extends CancellableTask<CompletableFuture<Set<Set<Uni
.collect(Collectors.toCollection(ArrayList::new)); .collect(Collectors.toCollection(ArrayList::new));
var unifyFuture = unify(neweq, remainingOderconstraints, fc, context.parallel(), rekTiefeField, methodSignatureConstraint); var unifyFuture = unify(neweq, remainingOderconstraints, fc, context.parallel(), rekTiefeField, methodSignatureConstraint);
return unifyFuture.thenApply(res -> { return unifyFuture.thenApply(res -> {
context.logger().close(); try {
context.logFile().close();
} catch (IOException ioE) {
System.err.println("no log-File");
}
if (isUndefinedPairSetSet(res)) { if (isUndefinedPairSetSet(res)) {
//fuer debug-Zwecke //fuer debug-Zwecke
ArrayList<ArrayList<UnifyPair>> al = res.stream() ArrayList<ArrayList<UnifyPair>> al = res.stream()
@@ -237,7 +260,7 @@ public class TypeUnifyTask extends CancellableTask<CompletableFuture<Set<Set<Uni
throw new TypeinferenceException("Unresolved constraints: " + res, new NullToken()); //return new HashSet<>(); throw new TypeinferenceException("Unresolved constraints: " + res, new NullToken()); //return new HashSet<>();
} }
if (this.isExecutionCancelled()) { if (this.myIsCancelled()) {
return new HashSet<>(); return new HashSet<>();
} }
@@ -269,19 +292,19 @@ public class TypeUnifyTask extends CancellableTask<CompletableFuture<Set<Set<Uni
// ).collect(Collectors.toCollection(HashSet::new)); // ).collect(Collectors.toCollection(HashSet::new));
//writeLog(nOfUnify.toString() + " AA: " + aas.toString()); //writeLog(nOfUnify.toString() + " AA: " + aas.toString());
//if (aas.isEmpty()) { //if (aas.isEmpty()) {
// context.logger().info(""); // System.out.println("");
//} //}
//.collect(Collectors.toCollection(HashSet::new))); //.collect(Collectors.toCollection(HashSet::new)));
if (this.isExecutionCancelled()) { if (this.myIsCancelled()) {
return CompletableFuture.completedFuture(new HashSet<>()); return CompletableFuture.completedFuture(new HashSet<>());
} }
rekTiefe++; rekTiefe++;
nOfUnify++; nOfUnify++;
context.logger().debug(() -> nOfUnify + " Unifikation: " + eq.toString()); writeLog(nOfUnify.toString() + " Unifikation: " + eq.toString());
context.logger().debug(() -> nOfUnify + " Oderconstraints: " + oderConstraints.toString()); writeLog(nOfUnify.toString() + " Oderconstraints: " + oderConstraints.toString());
/* /*
* Variancen auf alle Gleichungen vererben * Variancen auf alle Gleichungen vererben
@@ -303,10 +326,15 @@ public class TypeUnifyTask extends CancellableTask<CompletableFuture<Set<Set<Uni
/* /*
* Occurs-Check durchfuehren * Occurs-Check durchfuehren
*/ */
Set<UnifyPair> ocurrPairs = TypeUnifyTaskHelper.occursCheck(eq); Set<UnifyPair> ocurrPairs = eq.stream().filter(x -> {
UnifyType lhs, rhs;
Set<UnifyPair> finalOcurrPairs = ocurrPairs; return (lhs = x.getLhsType()) instanceof PlaceholderType
context.logger().debug(() -> "ocurrPairs: " + finalOcurrPairs); && !((rhs = x.getRhsType()) instanceof PlaceholderType)
&& rhs.getTypeParams().occurs((PlaceholderType) lhs);
})
.peek(UnifyPair::setUndefinedPair)
.collect(Collectors.toCollection(HashSet::new));
writeLog("ocurrPairs: " + ocurrPairs);
if (!ocurrPairs.isEmpty()) { if (!ocurrPairs.isEmpty()) {
Set<Set<UnifyPair>> ret = new HashSet<>(); Set<Set<UnifyPair>> ret = new HashSet<>();
ret.add(ocurrPairs); ret.add(ocurrPairs);
@@ -327,9 +355,15 @@ public class TypeUnifyTask extends CancellableTask<CompletableFuture<Set<Set<Uni
/* In commit dfd91b5f8b7fca1cb5f302eec4b0ba3330271c9b eingefuegt ANFANG */ /* In commit dfd91b5f8b7fca1cb5f302eec4b0ba3330271c9b eingefuegt ANFANG */
Set<UnifyPair> occurcheck = new HashSet<>(eq0); Set<UnifyPair> occurcheck = new HashSet<>(eq0);
occurcheck.removeAll(eq0Prime); occurcheck.removeAll(eq0Prime);
ocurrPairs = TypeUnifyTaskHelper.occursCheck(occurcheck); ocurrPairs = occurcheck.stream().filter(x -> {
Set<UnifyPair> finalOcurrPairs1 = ocurrPairs; UnifyType lhs, rhs;
context.logger().debug(() -> "ocurrPairs: " + finalOcurrPairs1); return (lhs = x.getLhsType()) instanceof PlaceholderType
&& !((rhs = x.getRhsType()) instanceof PlaceholderType)
&& rhs.getTypeParams().occurs((PlaceholderType) lhs);
})
.peek(UnifyPair::setUndefinedPair)
.collect(Collectors.toCollection(HashSet::new));
writeLog("ocurrPairs: " + ocurrPairs);
if (!ocurrPairs.isEmpty()) { if (!ocurrPairs.isEmpty()) {
Set<Set<UnifyPair>> ret = new HashSet<>(); Set<Set<UnifyPair>> ret = new HashSet<>();
ret.add(ocurrPairs); ret.add(ocurrPairs);
@@ -341,8 +375,8 @@ public class TypeUnifyTask extends CancellableTask<CompletableFuture<Set<Set<Uni
eq0.forEach(UnifyPair::disableCondWildcards); eq0.forEach(UnifyPair::disableCondWildcards);
context.logger().debug(() ->nOfUnify + " Unifikation nach applyTypeUnificationRules: " + eq.toString()); writeLog(nOfUnify.toString() + " Unifikation nach applyTypeUnificationRules: " + eq.toString());
context.logger().debug(() -> nOfUnify + " Oderconstraints nach applyTypeUnificationRules: " + oderConstraints.toString()); writeLog(nOfUnify.toString() + " Oderconstraints nach applyTypeUnificationRules: " + oderConstraints.toString());
/* /*
* Step 2 and 3: Create a subset eq1s of pairs where both sides are TPH and eq2s of the other pairs * Step 2 and 3: Create a subset eq1s of pairs where both sides are TPH and eq2s of the other pairs
@@ -362,7 +396,7 @@ public class TypeUnifyTask extends CancellableTask<CompletableFuture<Set<Set<Uni
// cartesian product of the sets created by pattern matching. // cartesian product of the sets created by pattern matching.
List<Set<? extends Set<UnifyPair>>> topLevelSets = new ArrayList<>(); List<Set<? extends Set<UnifyPair>>> topLevelSets = new ArrayList<>();
//context.logger().info(eq2s); //System.out.println(eq2s);
if (!eq1s.isEmpty()) { // Do not add empty sets or the cartesian product will always be empty. if (!eq1s.isEmpty()) { // Do not add empty sets or the cartesian product will always be empty.
Set<Set<UnifyPair>> wrap = new HashSet<>(); Set<Set<UnifyPair>> wrap = new HashSet<>();
@@ -386,7 +420,7 @@ public class TypeUnifyTask extends CancellableTask<CompletableFuture<Set<Set<Uni
// Sets that originate from pair pattern matching // Sets that originate from pair pattern matching
// Sets of the "second level" // Sets of the "second level"
Set<UnifyPair> undefinedPairs = new HashSet<>(); Set<UnifyPair> undefinedPairs = new HashSet<>();
if (printtag) context.logger().info("eq2s " + eq2s); if (printtag) System.out.println("eq2s " + eq2s);
//writeLog("BufferSet: " + bufferSet.toString()+"\n"); //writeLog("BufferSet: " + bufferSet.toString()+"\n");
List<Set<Constraint<UnifyPair>>> oderConstraintsOutput = new ArrayList<>();//new ArrayList<>(oderConstraints); List<Set<Constraint<UnifyPair>>> oderConstraintsOutput = new ArrayList<>();//new ArrayList<>(oderConstraints);
Set<Set<Set<? extends Set<UnifyPair>>>> secondLevelSets = calculatePairSets(eq2s, oderConstraints, fc, undefinedPairs, oderConstraintsOutput); Set<Set<Set<? extends Set<UnifyPair>>>> secondLevelSets = calculatePairSets(eq2s, oderConstraints, fc, undefinedPairs, oderConstraintsOutput);
@@ -394,21 +428,21 @@ public class TypeUnifyTask extends CancellableTask<CompletableFuture<Set<Set<Uni
//nicht ausgewertet Faculty Beispiel im 1. Schritt //nicht ausgewertet Faculty Beispiel im 1. Schritt
//PL 2017-10-03 geloest, muesste noch mit FCs mit kleineren //PL 2017-10-03 geloest, muesste noch mit FCs mit kleineren
//Typen getestet werden. //Typen getestet werden.
context.logger().debug(() -> nOfUnify + " Oderconstraints2: " + oderConstraintsOutput.toString()); writeLog(nOfUnify.toString() + " Oderconstraints2: " + oderConstraintsOutput.toString());
if (printtag) context.logger().info("secondLevelSets:" + secondLevelSets); if (printtag) System.out.println("secondLevelSets:" + secondLevelSets);
// If pairs occured that did not match one of the cartesian product cases, // If pairs occured that did not match one of the cartesian product cases,
// those pairs are contradictory and the unification is impossible. // those pairs are contradictory and the unification is impossible.
if (!undefinedPairs.isEmpty()) { if (!undefinedPairs.isEmpty()) {
noUndefPair++; noUndefPair++;
for (UnifyPair up : undefinedPairs) { for (UnifyPair up : undefinedPairs) {
context.logger().debug(() -> noUndefPair + " UndefinedPairs; " + up); writeLog(noUndefPair.toString() + " UndefinedPairs; " + up);
context.logger().debug(() -> "BasePair; " + up.getBasePair()); writeLog("BasePair; " + up.getBasePair());
} }
Set<Set<UnifyPair>> error = new HashSet<>(); Set<Set<UnifyPair>> error = new HashSet<>();
undefinedPairs = undefinedPairs.stream().peek(UnifyPair::setUndefinedPair) undefinedPairs = undefinedPairs.stream().peek(UnifyPair::setUndefinedPair)
.collect(Collectors.toCollection(HashSet::new)); .collect(Collectors.toCollection(HashSet::new));
error.add(undefinedPairs); error.add(undefinedPairs);
undefinedPairs.forEach(x -> context.logger().debug(() -> "AllSubst: " + x.getAllSubstitutions().toString())); undefinedPairs.forEach(x -> writeLog("AllSubst: " + x.getAllSubstitutions().toString()));
return CompletableFuture.completedFuture(error); return CompletableFuture.completedFuture(error);
} }
@@ -418,16 +452,16 @@ public class TypeUnifyTask extends CancellableTask<CompletableFuture<Set<Set<Uni
// Alternative: Sub cartesian products of the second level (pattern matched) sets // Alternative: Sub cartesian products of the second level (pattern matched) sets
// "the big (x)" // "the big (x)"
/* for(Set<Set<Set<UnifyPair>>> secondLevelSet : secondLevelSets) { /* for(Set<Set<Set<UnifyPair>>> secondLevelSet : secondLevelSets) {
//context.logger().info("secondLevelSet "+secondLevelSet.size()); //System.out.println("secondLevelSet "+secondLevelSet.size());
List<Set<Set<UnifyPair>>> secondLevelSetList = new ArrayList<>(secondLevelSet); List<Set<Set<UnifyPair>>> secondLevelSetList = new ArrayList<>(secondLevelSet);
Set<List<Set<UnifyPair>>> cartResult = setOps.cartesianProduct(secondLevelSetList); Set<List<Set<UnifyPair>>> cartResult = setOps.cartesianProduct(secondLevelSetList);
//context.logger().info("CardResult: "+cartResult.size()); //System.out.println("CardResult: "+cartResult.size());
// Flatten and add to top level sets // Flatten and add to top level sets
Set<Set<UnifyPair>> flat = new HashSet<>(); Set<Set<UnifyPair>> flat = new HashSet<>();
int j = 0; int j = 0;
for(List<Set<UnifyPair>> s : cartResult) { for(List<Set<UnifyPair>> s : cartResult) {
j++; j++;
//context.logger().info("s from CardResult: "+cartResult.size() + " " + j); //System.out.println("s from CardResult: "+cartResult.size() + " " + j);
Set<UnifyPair> flat1 = new HashSet<>(); Set<UnifyPair> flat1 = new HashSet<>();
for(Set<UnifyPair> s1 : s) for(Set<UnifyPair> s1 : s)
flat1.addAll(s1); flat1.addAll(s1);
@@ -441,8 +475,8 @@ public class TypeUnifyTask extends CancellableTask<CompletableFuture<Set<Set<Uni
for (Set<Set<? extends Set<UnifyPair>>> secondLevelSet : secondLevelSets) { for (Set<Set<? extends Set<UnifyPair>>> secondLevelSet : secondLevelSets) {
topLevelSets.addAll(secondLevelSet); topLevelSets.addAll(secondLevelSet);
} }
//context.logger().info(topLevelSets); //System.out.println(topLevelSets);
//context.logger().info(); //System.out.println();
//Aufruf von computeCartesianRecursive ANFANG //Aufruf von computeCartesianRecursive ANFANG
@@ -464,7 +498,7 @@ public class TypeUnifyTask extends CancellableTask<CompletableFuture<Set<Set<Uni
// .collect(Collectors.toCollection(HashSet::new)); // .collect(Collectors.toCollection(HashSet::new));
//Muss auskommentiert werden, wenn computeCartesianRecursive ENDE //Muss auskommentiert werden, wenn computeCartesianRecursive ENDE
if (this.isExecutionCancelled()) { if (this.myIsCancelled()) {
return CompletableFuture.completedFuture(new HashSet<>()); return CompletableFuture.completedFuture(new HashSet<>());
} }
@@ -483,18 +517,18 @@ public class TypeUnifyTask extends CancellableTask<CompletableFuture<Set<Set<Uni
* Step 5: Substitution * Step 5: Substitution
*/ */
//writeLog("vor Subst: " + eqPrime); //writeLog("vor Subst: " + eqPrime);
context.logger().debug(() -> "vor Subst: " + oderConstraints); writeLog("vor Subst: " + oderConstraints);
String ocString = oderConstraints.toString(); String ocString = oderConstraints.toString();
List<Set<Constraint<UnifyPair>>> newOderConstraints = new ArrayList<>(oderConstraints); List<Set<Constraint<UnifyPair>>> newOderConstraints = new ArrayList<>(oderConstraints);
Optional<Set<UnifyPair>> eqPrimePrime = rules.subst(eqPrime, newOderConstraints); Optional<Set<UnifyPair>> eqPrimePrime = rules.subst(eqPrime, newOderConstraints);
Set<Set<UnifyPair>> unifyres1 = null; Set<Set<UnifyPair>> unifyres1 = null;
Set<Set<UnifyPair>> unifyres2 = null; Set<Set<UnifyPair>> unifyres2 = null;
if (!ocString.equals(newOderConstraints.toString())) if (!ocString.equals(newOderConstraints.toString()))
context.logger().debug(() -> "nach Subst: " + newOderConstraints); writeLog("nach Subst: " + newOderConstraints);
{// sequentiell (Step 6b is included) {// sequentiell (Step 6b is included)
if (printtag) context.logger().info("nextStep: " + eqPrimePrime); if (printtag) System.out.println("nextStep: " + eqPrimePrime);
if (eqPrime.equals(eq) && eqPrimePrime.isEmpty() if (eqPrime.equals(eq) && eqPrimePrime.isEmpty()
&& oderConstraints.isEmpty()) { //PL 2017-09-29 //(!eqPrimePrime.isPresent()) auskommentiert und durch && oderConstraints.isEmpty()) { //PL 2017-09-29 //(!eqPrimePrime.isPresent()) auskommentiert und durch
//PL 2017-09-29 dies ersetzt //(!eqPrimePrime.isPresent()) //PL 2017-09-29 dies ersetzt //(!eqPrimePrime.isPresent())
@@ -513,12 +547,12 @@ public class TypeUnifyTask extends CancellableTask<CompletableFuture<Set<Set<Uni
return eqPrimePrimeSet; return eqPrimePrimeSet;
}); });
if (finalresult && isSolvedForm(eqPrime)) { if (finalresult && isSolvedForm(eqPrime)) {
context.logger().debug(() -> "eqPrime:" + eqPrime.toString() + "\n"); writeLog("eqPrime:" + eqPrime.toString() + "\n");
/* methodconstraintsets werden zum Ergebnis hinzugefuegt /* methodconstraintsets werden zum Ergebnis hinzugefuegt
* Anfang * Anfang
*/ */
//context.logger().info("methodSignatureConstraint Return: " + methodSignatureConstraint + "\n"); //System.out.println("methodSignatureConstraint Return: " + methodSignatureConstraint + "\n");
eqPrimePrimeSetFuture = eqPrimePrimeSetFuture.thenApply(eqPrimePrimeSet -> { eqPrimePrimeSetFuture = eqPrimePrimeSetFuture.thenApply(eqPrimePrimeSet -> {
eqPrimePrimeSet.forEach(x -> x.addAll(methodSignatureConstraint)); eqPrimePrimeSet.forEach(x -> x.addAll(methodSignatureConstraint));
@@ -569,8 +603,7 @@ public class TypeUnifyTask extends CancellableTask<CompletableFuture<Set<Set<Uni
return eqPrimePrimeSetFuture.thenApply(eqPrimePrimeSet -> { return eqPrimePrimeSetFuture.thenApply(eqPrimePrimeSet -> {
eqPrimePrimeSet = eqPrimePrimeSet.stream().filter(x -> isSolvedForm(x) || this.isUndefinedPairSet(x)).collect(Collectors.toCollection(HashSet::new)); eqPrimePrimeSet = eqPrimePrimeSet.stream().filter(x -> isSolvedForm(x) || this.isUndefinedPairSet(x)).collect(Collectors.toCollection(HashSet::new));
if (!eqPrimePrimeSet.isEmpty() && !isUndefinedPairSetSet(eqPrimePrimeSet)) { if (!eqPrimePrimeSet.isEmpty() && !isUndefinedPairSetSet(eqPrimePrimeSet)) {
Set<Set<UnifyPair>> finalEqPrimePrimeSet = eqPrimePrimeSet; writeLog("Result1 " + eqPrimePrimeSet);
context.logger().debug(() -> "Result1 " + finalEqPrimePrimeSet);
} }
return eqPrimePrimeSet; return eqPrimePrimeSet;
}); });
@@ -642,7 +675,7 @@ public class TypeUnifyTask extends CancellableTask<CompletableFuture<Set<Set<Uni
} else { } else {
//Varianz-Bestimmung Oder-Constraints //Varianz-Bestimmung Oder-Constraints
if (printtag) { if (printtag) {
context.logger().info("nextSetasList " + nextSetAsList); System.out.println("nextSetasList " + nextSetAsList);
} }
variance = TypeUnifyTaskHelper.calculateOderConstraintVariance(nextSetAsList); variance = TypeUnifyTaskHelper.calculateOderConstraintVariance(nextSetAsList);
} }
@@ -658,16 +691,14 @@ public class TypeUnifyTask extends CancellableTask<CompletableFuture<Set<Set<Uni
*/ */
Set<UnifyPair> sameEqSet = new HashSet<>(); Set<UnifyPair> sameEqSet = new HashSet<>();
//optOrigPair enthaelt ggf. das Paar a = ty \in nextSet //optOrigPair enthaelt ggf. das Paar a = ty \in nextSet
Optional<UnifyPair> optOrigPair; Optional<UnifyPair> optOrigPair = Optional.empty();
if (!oderConstraint) { if (!oderConstraint) {
optOrigPair = TypeUnifyTaskHelper.findEqualityConstrainedUnifyPair(nextSetElement); optOrigPair = TypeUnifyTaskHelper.findEqualityConstrainedUnifyPair(nextSetElement);
context.logger().debug(() -> "optOrigPair: " + optOrigPair); writeLog("optOrigPair: " + optOrigPair);
if (optOrigPair.isPresent()) { if (optOrigPair.isPresent()) {
sameEqSet = TypeUnifyTaskHelper.findConstraintsWithSameTVAssociation(optOrigPair.get(), singleElementSets); sameEqSet = TypeUnifyTaskHelper.findConstraintsWithSameTVAssociation(optOrigPair.get(), singleElementSets);
} }
} else {
optOrigPair = Optional.empty();
} }
@@ -677,7 +708,7 @@ public class TypeUnifyTask extends CancellableTask<CompletableFuture<Set<Set<Uni
return resultFuture.thenApply(result -> { return resultFuture.thenApply(result -> {
//2020-02-02: if (variance ==2) Hier Aufruf von filterOverriding einfuegen //2020-02-02: if (variance ==2) Hier Aufruf von filterOverriding einfuegen
context.logger().debug(() ->"Return computeCR: " + result.toString()); writeLog("Return computeCR: " + result.toString());
return result; return result;
}); });
} }
@@ -704,23 +735,23 @@ public class TypeUnifyTask extends CancellableTask<CompletableFuture<Set<Set<Uni
VarianceCase varianceCase = VarianceCase.createFromVariance(variance, oderConstraint, this, context); VarianceCase varianceCase = VarianceCase.createFromVariance(variance, oderConstraint, this, context);
context.logger().debug(() -> "nextSet: " + nextSet.toString()); writeLog("nextSet: " + nextSet.toString());
context.logger().debug(() -> "nextSetasList: " + prevNextSetAsList.toString()); writeLog("nextSetasList: " + prevNextSetAsList.toString());
varianceCase.selectNextData(this, prevNextSetAsList, optOrigPair); varianceCase.selectNextData(this, prevNextSetAsList, optOrigPair);
if (oderConstraint) {//Methodconstraints werden abgespeichert für die Bytecodegenerierung von Methodenaufrufen if (oderConstraint) {//Methodconstraints werden abgespeichert für die Bytecodegenerierung von Methodenaufrufen
methodSignatureConstraint.addAll(((Constraint<UnifyPair>) varianceCase.a).getmethodSignatureConstraint()); methodSignatureConstraint.addAll(((Constraint<UnifyPair>) varianceCase.a).getmethodSignatureConstraint());
context.logger().debug(() -> "ERSTELLUNG methodSignatureConstraint: " + methodSignatureConstraint); writeLog("ERSTELLUNG methodSignatureConstraint: " + methodSignatureConstraint);
//context.logger().info("ERSTELLUNG methodSignatureConstraint: " +noOfThread+" "+methodSignatureConstraint); //System.out.println("ERSTELLUNG methodSignatureConstraint: " +noOfThread+" "+methodSignatureConstraint);
//context.logger().info("a: " +a); //System.out.println("a: " +a);
//context.logger().info("eq: " +eq); //System.out.println("eq: " +eq);
//context.logger().info(); //System.out.println();
} }
i++; i++;
Set<Set<UnifyPair>> elems = new HashSet<>(singleElementSets); Set<Set<UnifyPair>> elems = new HashSet<>(singleElementSets);
context.logger().debug(() -> "a1: " + rekTiefe + " " + "variance: " + variance + " " + varianceCase.a.toString() + "\n"); writeLog("a1: " + rekTiefe + " " + "variance: " + variance + " " + varianceCase.a.toString() + "\n");
Set<Set<UnifyPair>> aParDef = new HashSet<>(); Set<Set<UnifyPair>> aParDef = new HashSet<>();
@@ -741,8 +772,7 @@ public class TypeUnifyTask extends CancellableTask<CompletableFuture<Set<Set<Uni
// Ergebnisvariable für die parallele Verabeitung: Tupel aus // Ergebnisvariable für die parallele Verabeitung: Tupel aus
// - forkOrig result : currentThreadResult (frueher "res") // - forkOrig result : currentThreadResult (frueher "res")
// - fork results : forkResults (frueher "add_res") // - fork results : forkResults (frueher "add_res")
CompletableFuture<VarianceCase.ComputationResults> parallelResultDataFuture; CompletableFuture<Tuple<Set<Set<UnifyPair>>, Set<Set<Set<UnifyPair>>>>> parallelResultDataFuture;
if (parallel) { if (parallel) {
parallelResultDataFuture = varianceCase.computeParallel( parallelResultDataFuture = varianceCase.computeParallel(
@@ -753,16 +783,13 @@ public class TypeUnifyTask extends CancellableTask<CompletableFuture<Set<Set<Uni
// same as variance = 0 // same as variance = 0
elems.add(varianceCase.a); //PL 2019-01-16 muss das wirklich hin steht schon in Zeile 859 ja braucht man siehe Zeile 859 elems.add(varianceCase.a); //PL 2019-01-16 muss das wirklich hin steht schon in Zeile 859 ja braucht man siehe Zeile 859
parallelResultDataFuture = this.unify2(elems, eq, oderConstraints, fc, false, rekTiefe, new HashSet<>(methodSignatureConstraint)) parallelResultDataFuture = this.unify2(elems, eq, oderConstraints, fc, false, rekTiefe, new HashSet<>(methodSignatureConstraint))
.thenApply(VarianceCase.ComputationResults::new); .thenApply(currentThreadResult -> new Tuple<>(currentThreadResult, new HashSet<>()));
} }
if (this.isExecutionCancelled()) {
return CompletableFuture.completedFuture(new HashSet<>());
}
return parallelResultDataFuture.thenCompose(parallelResultData -> { return parallelResultDataFuture.thenCompose(parallelResultData -> {
Set<Set<UnifyPair>> currentThreadResult = parallelResultData.mainResult; Set<Set<UnifyPair>> currentThreadResult = parallelResultData.getFirst();
Set<Set<Set<UnifyPair>>> forkResults = parallelResultData.forkResults; Set<Set<Set<UnifyPair>>> forkResults = parallelResultData.getSecond();
Set<Set<UnifyPair>> result = prevResult; Set<Set<UnifyPair>> result = prevResult;
List<Set<UnifyPair>> nextSetAsList = prevNextSetAsList; List<Set<UnifyPair>> nextSetAsList = prevNextSetAsList;
@@ -771,7 +798,7 @@ public class TypeUnifyTask extends CancellableTask<CompletableFuture<Set<Set<Uni
//Ab hier alle parallele Berechnungen wieder zusammengeführt. //Ab hier alle parallele Berechnungen wieder zusammengeführt.
if (oderConstraint) {//Wenn weiteres Element nextSetasList genommen wird, muss die vorherige methodsignatur geloescht werden if (oderConstraint) {//Wenn weiteres Element nextSetasList genommen wird, muss die vorherige methodsignatur geloescht werden
methodSignatureConstraint.removeAll(((Constraint<UnifyPair>) varianceCase.a).getmethodSignatureConstraint()); methodSignatureConstraint.removeAll(((Constraint<UnifyPair>) varianceCase.a).getmethodSignatureConstraint());
//context.logger().info("REMOVE: " +methodSignatureConstraint); //System.out.println("REMOVE: " +methodSignatureConstraint);
} }
if (!isUndefinedPairSetSet(currentThreadResult) && isUndefinedPairSetSet(result)) { if (!isUndefinedPairSetSet(currentThreadResult) && isUndefinedPairSetSet(result)) {
//wenn korrektes Ergebnis gefunden alle Fehlerfaelle loeschen //wenn korrektes Ergebnis gefunden alle Fehlerfaelle loeschen
@@ -789,16 +816,16 @@ public class TypeUnifyTask extends CancellableTask<CompletableFuture<Set<Set<Uni
//Alle Variablen bestimmen die nicht hinzugefügt wurden in a //Alle Variablen bestimmen die nicht hinzugefügt wurden in a
//PL 2018-12-28: Hier gab es eine ClassCastException, war nicht reproduzierbar //PL 2018-12-28: Hier gab es eine ClassCastException, war nicht reproduzierbar
// context.logger().info(""); // System.out.println("");
List<PlaceholderType> vars_a = TypeUnifyTaskHelper.extractMatchingPlaceholderTypes(varianceCase.a); List<PlaceholderType> vars_a = TypeUnifyTaskHelper.extractMatchingPlaceholderTypes(varianceCase.a);
Set<UnifyPair> fstElemRes = currentThreadResult.iterator().next(); Set<UnifyPair> fstElemRes = currentThreadResult.iterator().next();
Set<UnifyPair> compRes = fstElemRes.stream().filter(x -> vars_a.contains(((PlaceholderType) x.getLhsType()))).collect(Collectors.toCollection(HashSet::new)); Set<UnifyPair> compRes = fstElemRes.stream().filter(x -> vars_a.contains(((PlaceholderType) x.getLhsType()))).collect(Collectors.toCollection(HashSet::new));
//Alle Variablen bestimmen die nicht hinzugefügt wurden in a_last //Alle Variablen bestimmen die nicht hinzugefügt wurden in a_last
//context.logger().info(a_last); //System.out.println(a_last);
try {//PL eingefuegt 2019-03-06 da bei map mmer wieder Nullpointer kamen try {//PL eingefuegt 2019-03-06 da bei map mmer wieder Nullpointer kamen
a_last.forEach(x -> context.logger().debug(() -> "a_last_elem:" + x + " basepair: " + x.getBasePair()));//PL 2019-05-13 ins try hinzugefuegt Nullpointer-Exception ist in der Zeile aufgetaucht. a_last.forEach(x -> writeLog("a_last_elem:" + x + " basepair: " + x.getBasePair()));//PL 2019-05-13 ins try hinzugefuegt Nullpointer-Exception ist in der Zeile aufgetaucht.
List<PlaceholderType> varsLast_a = TypeUnifyTaskHelper.extractMatchingPlaceholderTypes(a_last); List<PlaceholderType> varsLast_a = TypeUnifyTaskHelper.extractMatchingPlaceholderTypes(a_last);
//[(java.util.Vector<java.lang.Integer> <. gen_aq, , 1), (CEK =. ? extends gen_aq, 1)] KANN VORKOMMEN //[(java.util.Vector<java.lang.Integer> <. gen_aq, , 1), (CEK =. ? extends gen_aq, 1)] KANN VORKOMMEN
//erstes Element genügt, da vars immer auf die gleichen Elemente zugeordnet werden muessen //erstes Element genügt, da vars immer auf die gleichen Elemente zugeordnet werden muessen
@@ -807,12 +834,11 @@ public class TypeUnifyTask extends CancellableTask<CompletableFuture<Set<Set<Uni
varianceCase.applyComputedResults(result, currentThreadResult, compResult, compRes); varianceCase.applyComputedResults(result, currentThreadResult, compResult, compRes);
} catch (NullPointerException e) { } catch (NullPointerException e) {
context.logger().debug(() -> "NullPointerException: " + a_last.toString()); writeLog("NullPointerException: " + a_last.toString());
} }
} else { } else {
//alle Fehlerfaelle und alle korrekten Ergebnis jeweils adden //alle Fehlerfaelle und alle korrekten Ergebnis jeweils adden
Set<Set<UnifyPair>> finalResult = result; writeLog("RES Fst: result: " + result.toString() + " currentThreadResult: " + currentThreadResult.toString());
context.logger().debug(() -> "RES Fst: result: " + finalResult.toString() + " currentThreadResult: " + currentThreadResult.toString());
result.addAll(currentThreadResult); result.addAll(currentThreadResult);
} }
} }
@@ -826,19 +852,23 @@ public class TypeUnifyTask extends CancellableTask<CompletableFuture<Set<Set<Uni
if (parallel) { if (parallel) {
for (Set<Set<UnifyPair>> par_res : forkResults) { for (Set<Set<UnifyPair>> par_res : forkResults) {
if (variance == 0 && (!result.isEmpty() && (!isUndefinedPairSetSet(currentThreadResult)))) {
this.cancelChildExecution();
return CompletableFuture.completedFuture(result);
}
if (!isUndefinedPairSetSet(par_res) && isUndefinedPairSetSet(result)) { if (!isUndefinedPairSetSet(par_res) && isUndefinedPairSetSet(result)) {
//wenn korrektes Ergebnis gefunden alle Fehlerfaelle loeschen //wenn korrektes Ergebnis gefunden alle Fehlerfaelle loeschen
result = par_res; result = par_res;
if (!par_res.isEmpty() && par_res.iterator().next() instanceof WildcardType) { if (!par_res.isEmpty() && par_res.iterator().next() instanceof WildcardType) {
// context.logger().info(); // System.out.println();
} }
} else { } else {
if ((isUndefinedPairSetSet(par_res) && isUndefinedPairSetSet(result)) if ((isUndefinedPairSetSet(par_res) && isUndefinedPairSetSet(result))
|| (!isUndefinedPairSetSet(par_res) && !isUndefinedPairSetSet(result)) || (!isUndefinedPairSetSet(par_res) && !isUndefinedPairSetSet(result))
|| result.isEmpty()) { || result.isEmpty()) {
//alle Fehlerfaelle und alle korrekten Ergebnis jeweils adden //alle Fehlerfaelle und alle korrekten Ergebnis jeweils adden
Set<Set<UnifyPair>> finalResult1 = result; writeLog("RES var1 ADD:" + result.toString() + " " + par_res.toString());
context.logger().debug(() ->"RES var1 ADD:" + finalResult1.toString() + " " + par_res.toString());
result.addAll(par_res); result.addAll(par_res);
} }
} }
@@ -859,15 +889,16 @@ public class TypeUnifyTask extends CancellableTask<CompletableFuture<Set<Set<Uni
// Iterator<Set<UnifyPair>> nextSetasListIt = new ArrayList<>(nextSetAsList).iterator(); // Iterator<Set<UnifyPair>> nextSetasListIt = new ArrayList<>(nextSetAsList).iterator();
boolean shouldBreak = varianceCase.eraseInvalidSets(rekTiefe, aParDef, nextSetAsList); boolean shouldBreak = varianceCase.eraseInvalidSets(rekTiefe, aParDef, nextSetAsList);
if (shouldBreak) { if (shouldBreak) {
// this.cancelYoungerSiblingTasks(); this.cancelChildExecution();
return CompletableFuture.completedFuture(result); return CompletableFuture.completedFuture(result);
} }
context.logger().debug(() -> "a: " + rekTiefe + " variance: " + variance + varianceCase.a.toString()); writeLog("a: " + rekTiefe + " variance: " + variance + varianceCase.a.toString());
} }
/* auskommentiert um alle Max und min Betrachtung auszuschalten ENDE */ /* auskommentiert um alle Max und min Betrachtung auszuschalten ENDE */
if (isUndefinedPairSetSet(currentThreadResult) && aParDef.isEmpty()) { if (isUndefinedPairSetSet(currentThreadResult) && aParDef.isEmpty()) {
int nofstred = 0;
Set<UnifyPair> abhSubst = TypeUnifyTaskHelper.collectFromThreadResult(currentThreadResult, UnifyPair::getAllSubstitutions); Set<UnifyPair> abhSubst = TypeUnifyTaskHelper.collectFromThreadResult(currentThreadResult, UnifyPair::getAllSubstitutions);
abhSubst.addAll( abhSubst.addAll(
TypeUnifyTaskHelper.collectFromThreadResult(currentThreadResult, UnifyPair::getThisAndAllBases) TypeUnifyTaskHelper.collectFromThreadResult(currentThreadResult, UnifyPair::getThisAndAllBases)
@@ -897,10 +928,9 @@ public class TypeUnifyTask extends CancellableTask<CompletableFuture<Set<Set<Uni
*/ */
if (currentThreadResult.size() > 1) { if (currentThreadResult.size() > 1) {
// context.logger().info(); // System.out.println();
} }
List<Set<UnifyPair>> finalNextSetAsList = nextSetAsList; writeLog("nextSetasList vor filter-Aufruf: " + nextSetAsList);
context.logger().debug(() -> "nextSetasList vor filter-Aufruf: " + finalNextSetAsList);
if (!oderConstraint) {//PL 2023-02-08 eingefuegt: Bei oderconstraints sind Subststitutionen nicht als Substitutionen in idesem Sinne zu sehen if (!oderConstraint) {//PL 2023-02-08 eingefuegt: Bei oderconstraints sind Subststitutionen nicht als Substitutionen in idesem Sinne zu sehen
nextSetAsList = nextSetAsList.stream().filter(x -> { nextSetAsList = nextSetAsList.stream().filter(x -> {
//Boolean ret = false; //Boolean ret = false;
@@ -911,29 +941,24 @@ public class TypeUnifyTask extends CancellableTask<CompletableFuture<Set<Set<Uni
})//.filter(y -> couldBecorrect(reducedUndefResSubstGroundedBasePair, y)) //fuer testzwecke auskommentiert um nofstred zu bestimmen PL 2018-10-10 })//.filter(y -> couldBecorrect(reducedUndefResSubstGroundedBasePair, y)) //fuer testzwecke auskommentiert um nofstred zu bestimmen PL 2018-10-10
.collect(Collectors.toCollection(ArrayList::new)); .collect(Collectors.toCollection(ArrayList::new));
} }
writeLog("nextSetasList nach filter-Aufruf: " + nextSetAsList);
if (context.logger().isLogLevelActive(Logger.LogLevel.DEBUG)) { nofstred = nextSetAsList.size();
List<Set<UnifyPair>> finalNextSetAsList1 = nextSetAsList; //NOCH NICHT korrekt PL 2018-10-12
context.logger().debug(() -> "nextSetasList nach filter-Aufruf: " + finalNextSetAsList1); //nextSetasList = nextSetasList.stream().filter(y -> couldBecorrect(reducedUndefResSubstGroundedBasePair, y))
int nofstred = nextSetAsList.size(); // .collect(Collectors.toCollection(ArrayList::new));
//NOCH NICHT korrekt PL 2018-10-12 writeLog("currentThreadResult (undef): " + currentThreadResult.toString());
//nextSetasList = nextSetasList.stream().filter(y -> couldBecorrect(reducedUndefResSubstGroundedBasePair, y)) writeLog("abhSubst: " + abhSubst.toString());
// .collect(Collectors.toCollection(ArrayList::new)); writeLog("a2: " + rekTiefe + " " + varianceCase.a.toString());
context.logger().debug("currentThreadResult (undef): " + currentThreadResult.toString()); writeLog("Durchschnitt: " + durchschnitt.toString());
context.logger().debug("abhSubst: " + abhSubst.toString()); writeLog("nextSet: " + nextSet.toString());
context.logger().debug("a2: " + rekTiefe + " " + varianceCase.a.toString()); writeLog("nextSetasList: " + nextSetAsList.toString());
context.logger().debug("Durchschnitt: " + durchschnitt.toString()); writeLog("Number first erased Elements (undef): " + (len - nofstred));
context.logger().debug("nextSet: " + nextSet.toString()); writeLog("Number second erased Elements (undef): " + (nofstred - nextSetAsList.size()));
context.logger().debug("nextSetasList: " + nextSetAsList.toString()); writeLog("Number erased Elements (undef): " + (len - nextSetAsList.size()));
context.logger().debug("Number first erased Elements (undef): " + (len - nofstred)); noAllErasedElements += (len - nextSetAsList.size());
context.logger().debug("Number second erased Elements (undef): " + (nofstred - nextSetAsList.size())); writeLog("Number of all erased Elements (undef): " + noAllErasedElements.toString());
context.logger().debug("Number erased Elements (undef): " + (len - nextSetAsList.size())); writeLog("Number of Backtracking: " + noBacktracking++);
noAllErasedElements += (len - nextSetAsList.size()); // System.out.println("");
context.logger().debug("Number of all erased Elements (undef): " + noAllErasedElements);
context.logger().debug("Number of Backtracking: " + noBacktracking++);
}
// context.logger().info("");
} }
//if (nextSetasList.size() == 0 && isUndefinedPairSetSet(result) && nextSet.size() > 1) { //if (nextSetasList.size() == 0 && isUndefinedPairSetSet(result) && nextSet.size() > 1) {
// return result; // return result;
@@ -942,7 +967,7 @@ public class TypeUnifyTask extends CancellableTask<CompletableFuture<Set<Set<Uni
// result.removeIf(y -> isUndefinedPairSet(y)); // result.removeIf(y -> isUndefinedPairSet(y));
//} //}
//else result.stream().filter(y -> !isUndefinedPairSet(y)); //else result.stream().filter(y -> !isUndefinedPairSet(y));
context.logger().debug(() -> "currentThreadResult: " + currentThreadResult.toString()); writeLog("currentThreadResult: " + currentThreadResult.toString());
return this.innerCartesianLoop(variance, rekTiefe, oderConstraint, parallel, result, varianceCase.a, nextSet, return this.innerCartesianLoop(variance, rekTiefe, oderConstraint, parallel, result, varianceCase.a, nextSet,
nextSetAsList, optOrigPair, methodSignatureConstraint, singleElementSets, sameEqSet, oderConstraints); nextSetAsList, optOrigPair, methodSignatureConstraint, singleElementSets, sameEqSet, oderConstraints);
@@ -959,7 +984,7 @@ public class TypeUnifyTask extends CancellableTask<CompletableFuture<Set<Set<Uni
* the error constraints. Error constraints are added * the error constraints. Error constraints are added
* @result contradiction of (a = ty) in sameEqSet * @result contradiction of (a = ty) in sameEqSet
*/ */
public boolean checkNoContradiction(Set<UnifyPair> a, Set<UnifyPair> sameEqSet, Set<Set<UnifyPair>> result) { public Boolean checkNoContradiction(Set<UnifyPair> a, Set<UnifyPair> sameEqSet, Set<Set<UnifyPair>> result) {
//optAPair enthaelt ggf. das Paar a = ty' \in a //optAPair enthaelt ggf. das Paar a = ty' \in a
//unterscheidet sich von optOrigPair, da dort a = ty //unterscheidet sich von optOrigPair, da dort a = ty
@@ -979,7 +1004,7 @@ public class TypeUnifyTask extends CancellableTask<CompletableFuture<Set<Set<Uni
UnifyPair aPair = optAPair.get(); UnifyPair aPair = optAPair.get();
//writeLog("optOrigPair: " + optOrigPair + " " + "aPair: " + aPair+ " " + "aPair.basePair(): " + aPair.getBasePair()); //writeLog("optOrigPair: " + optOrigPair + " " + "aPair: " + aPair+ " " + "aPair.basePair(): " + aPair.getBasePair());
context.logger().debug(() ->"checkA: " + aPair + "sameEqSet: " + sameEqSet); writeLog("checkA: " + aPair + "sameEqSet: " + sameEqSet);
for (UnifyPair sameEq : sameEqSet) { for (UnifyPair sameEq : sameEqSet) {
if (sameEq.getLhsType() instanceof PlaceholderType) { if (sameEq.getLhsType() instanceof PlaceholderType) {
Set<UnifyPair> localEq = new HashSet<>(); Set<UnifyPair> localEq = new HashSet<>();
@@ -1000,7 +1025,7 @@ public class TypeUnifyTask extends CancellableTask<CompletableFuture<Set<Set<Uni
if (result.isEmpty() || isUndefinedPairSetSet(result)) { if (result.isEmpty() || isUndefinedPairSetSet(result)) {
result.addAll(localRes); result.addAll(localRes);
} }
context.logger().debug(() ->"FALSE: " + aPair + "sameEqSet: " + sameEqSet); writeLog("FALSE: " + aPair + "sameEqSet: " + sameEqSet);
return false; return false;
} }
} else { } else {
@@ -1022,12 +1047,12 @@ public class TypeUnifyTask extends CancellableTask<CompletableFuture<Set<Set<Uni
if (result.isEmpty() || isUndefinedPairSetSet(result)) { if (result.isEmpty() || isUndefinedPairSetSet(result)) {
result.addAll(localRes); result.addAll(localRes);
} }
context.logger().debug(() ->"FALSE: " + aPair + "sameEqSet: " + sameEqSet); writeLog("FALSE: " + aPair + "sameEqSet: " + sameEqSet);
return false; return false;
} }
} }
} }
context.logger().debug(() ->"TRUE: " + aPair + "sameEqSet: " + sameEqSet); writeLog("TRUE: " + aPair + "sameEqSet: " + sameEqSet);
return true; return true;
} }
return true; return true;
@@ -1113,7 +1138,7 @@ public class TypeUnifyTask extends CancellableTask<CompletableFuture<Set<Set<Uni
// Through application of the rules, every pair should have one of the above forms. // Through application of the rules, every pair should have one of the above forms.
// Pairs that do not have one of the aboves form are contradictory. // Pairs that do not have one of the aboves form are contradictory.
else { else {
context.logger().debug(() ->"Second erase:" + checkPair); writeLog("Second erase:" + checkPair);
return false; return false;
} }
//*/ //*/
@@ -1312,7 +1337,7 @@ public class TypeUnifyTask extends CancellableTask<CompletableFuture<Set<Set<Uni
* (as in case 1 where sigma is added to the innermost set). * (as in case 1 where sigma is added to the innermost set).
*/ */
protected Set<Set<Set<? extends Set<UnifyPair>>>> calculatePairSets(Set<UnifyPair> eq2s, List<Set<Constraint<UnifyPair>>> oderConstraintsInput, IFiniteClosure fc, Set<UnifyPair> undefined, List<Set<Constraint<UnifyPair>>> oderConstraintsOutput) { protected Set<Set<Set<? extends Set<UnifyPair>>>> calculatePairSets(Set<UnifyPair> eq2s, List<Set<Constraint<UnifyPair>>> oderConstraintsInput, IFiniteClosure fc, Set<UnifyPair> undefined, List<Set<Constraint<UnifyPair>>> oderConstraintsOutput) {
context.logger().debug(() ->"eq2s: " + eq2s.toString()); writeLog("eq2s: " + eq2s.toString());
oderConstraintsOutput.addAll(oderConstraintsInput); oderConstraintsOutput.addAll(oderConstraintsInput);
List<Set<Set<? extends Set<UnifyPair>>>> result = new ArrayList<>(9); List<Set<Set<? extends Set<UnifyPair>>>> result = new ArrayList<>(9);
@@ -1399,12 +1424,10 @@ public class TypeUnifyTask extends CancellableTask<CompletableFuture<Set<Set<Uni
} }
} }
if (context.logger().isLogLevelActive(Logger.LogLevel.DEBUG)) { writeLog("eq2s: " + eq2s);
context.logger().debug("eq2s: " + eq2s); writeLog("eq2sAsListFst: " + eq2sAsListFst);
context.logger().debug("eq2sAsListFst: " + eq2sAsListFst); writeLog("eq2sAsListSnd: " + eq2sAsListSnd);
context.logger().debug("eq2sAsListSnd: " + eq2sAsListSnd); writeLog("eq2sAsListBack: " + eq2sAsListBack);
context.logger().debug("eq2sAsListBack: " + eq2sAsListBack);
}
eq2sAsList.addAll(eq2sAsListFst); eq2sAsList.addAll(eq2sAsListFst);
eq2sAsList.addAll(eq2sAsListSnd); eq2sAsList.addAll(eq2sAsListSnd);
@@ -1417,7 +1440,7 @@ public class TypeUnifyTask extends CancellableTask<CompletableFuture<Set<Set<Uni
if (!oderConstraintsOutput.isEmpty()) { if (!oderConstraintsOutput.isEmpty()) {
Set<Constraint<UnifyPair>> ret = oderConstraintsOutput.removeFirst(); Set<Constraint<UnifyPair>> ret = oderConstraintsOutput.removeFirst();
//if (ret.iterator().next().iterator().next().getLhsType().getName().equals("M")) //if (ret.iterator().next().iterator().next().getLhsType().getName().equals("M"))
// context.logger().info("M"); // System.out.println("M");
//Set<UnifyPair> retFlat = new HashSet<>(); //Set<UnifyPair> retFlat = new HashSet<>();
//ret.stream().forEach(x -> retFlat.addAll(x)); //ret.stream().forEach(x -> retFlat.addAll(x));
@@ -1457,7 +1480,7 @@ public class TypeUnifyTask extends CancellableTask<CompletableFuture<Set<Set<Uni
// Case 1: (a <. Theta') // Case 1: (a <. Theta')
if (((pairOp == PairOperator.SMALLERDOT) || (pairOp == PairOperator.SMALLERNEQDOT)) && lhsType instanceof PlaceholderType) { if (((pairOp == PairOperator.SMALLERDOT) || (pairOp == PairOperator.SMALLERNEQDOT)) && lhsType instanceof PlaceholderType) {
//context.logger().info(pair); //System.out.println(pair);
if (first) { //writeLog(pair.toString()+"\n"); if (first) { //writeLog(pair.toString()+"\n");
Set<Set<UnifyPair>> x1 = new HashSet<>(); Set<Set<UnifyPair>> x1 = new HashSet<>();
if (pair.getRhsType().getName().equals("void")) { if (pair.getRhsType().getName().equals("void")) {
@@ -1479,7 +1502,7 @@ public class TypeUnifyTask extends CancellableTask<CompletableFuture<Set<Set<Uni
x1.remove(remElem); x1.remove(remElem);
} }
/* ZU LOESCHEN ANFANG /* ZU LOESCHEN ANFANG
//context.logger().info(x1); //System.out.println(x1);
Set<UnifyPair> sameEqSet = eq2sAsList.stream() Set<UnifyPair> sameEqSet = eq2sAsList.stream()
.filter(x -> ((x.getLhsType().equals(lhsType) || x.getRhsType().equals(lhsType)) && !x.equals(pair))) .filter(x -> ((x.getLhsType().equals(lhsType) || x.getRhsType().equals(lhsType)) && !x.equals(pair)))
.collect(Collectors.toCollection(HashSet::new)); .collect(Collectors.toCollection(HashSet::new));
@@ -1697,11 +1720,11 @@ public class TypeUnifyTask extends CancellableTask<CompletableFuture<Set<Set<Uni
// && ((ReferenceType)thetaPrime).getTypeParams().iterator().next() instanceof PlaceholderType) //.getName().equals("java.util.Vector")) // && ((ReferenceType)thetaPrime).getTypeParams().iterator().next() instanceof PlaceholderType) //.getName().equals("java.util.Vector"))
// && ((ReferenceType)((ReferenceType)thetaPrime).getTypeParams().iterator().next()).getTypeParams().iterator().next().getName().equals("java.lang.Integer")) { // && ((ReferenceType)((ReferenceType)thetaPrime).getTypeParams().iterator().next()).getTypeParams().iterator().next().getName().equals("java.lang.Integer")) {
// { // {
// context.logger().info(""); // System.out.println("");
//} //}
Set<UnifyType> cs = fc.getAllTypesByName(thetaPrime.getName());//cs= [java.util.Vector<NP>, java.util.Vector<java.util.Vector<java.lang.Integer>>, ????java.util.Vector<gen_hv>???] Set<UnifyType> cs = fc.getAllTypesByName(thetaPrime.getName());//cs= [java.util.Vector<NP>, java.util.Vector<java.util.Vector<java.lang.Integer>>, ????java.util.Vector<gen_hv>???]
context.logger().debug(() ->"cs: " + cs.toString()); writeLog("cs: " + cs.toString());
//PL 18-02-06 entfernt, kommt durch unify wieder rein //PL 18-02-06 entfernt, kommt durch unify wieder rein
//cs.add(thetaPrime); //cs.add(thetaPrime);
//PL 18-02-06 entfernt //PL 18-02-06 entfernt
@@ -1712,9 +1735,8 @@ public class TypeUnifyTask extends CancellableTask<CompletableFuture<Set<Set<Uni
aa.putAll(b); aa.putAll(b);
return aa; return aa;
}; };
var involvedPlaceholderTypes = x.getInvolvedPlaceholderTypes(); HashMap<PlaceholderType, PlaceholderType> hm = x.getInvolvedPlaceholderTypes().stream()
HashMap<PlaceholderType, PlaceholderType> hm = involvedPlaceholderTypes.stream() .reduce(new HashMap<PlaceholderType, PlaceholderType>(),
.reduce(TypeUnifyTaskHelper.getPresizedHashMap(involvedPlaceholderTypes.size()),
(aa, b) -> { (aa, b) -> {
aa.put(b, PlaceholderType.freshPlaceholder(context.placeholderRegistry())); aa.put(b, PlaceholderType.freshPlaceholder(context.placeholderRegistry()));
return aa; return aa;
@@ -1734,8 +1756,7 @@ public class TypeUnifyTask extends CancellableTask<CompletableFuture<Set<Set<Uni
if ((match.match(ml)).isEmpty()) { if ((match.match(ml)).isEmpty()) {
thetaQs.remove(c); thetaQs.remove(c);
} }
Set<UnifyType> finalThetaQs = thetaQs; writeLog("thetaQs von " + c + ": " + thetaQs.toString());
context.logger().debug(() ->"thetaQs von " + c + ": " + finalThetaQs.toString());
//Set<UnifyType> thetaQs = fc.getChildren(c).stream().collect(Collectors.toCollection(HashSet::new)); //Set<UnifyType> thetaQs = fc.getChildren(c).stream().collect(Collectors.toCollection(HashSet::new));
//thetaQs.add(thetaPrime); //PL 18-02-05 wieder geloescht //thetaQs.add(thetaPrime); //PL 18-02-05 wieder geloescht
//PL 2017-10-03: War auskommentiert habe ich wieder einkommentiert, //PL 2017-10-03: War auskommentiert habe ich wieder einkommentiert,
@@ -1759,7 +1780,7 @@ public class TypeUnifyTask extends CancellableTask<CompletableFuture<Set<Set<Uni
for (TypeParams tp : permuteParams(candidateParams)) for (TypeParams tp : permuteParams(candidateParams))
thetaQPrimes.add(c.setTypeParams(tp)); thetaQPrimes.add(c.setTypeParams(tp));
} }
context.logger().debug(() ->"thetaQPrimes von " + c + ": " + thetaQPrimes.toString()); writeLog("thetaQPrimes von " + c + ": " + thetaQPrimes.toString());
for (UnifyType tqp : thetaQPrimes) {//PL 2020-03-08 umbauen in der Schleife wird nur unifizierbarer Typ gesucht break am Ende for (UnifyType tqp : thetaQPrimes) {//PL 2020-03-08 umbauen in der Schleife wird nur unifizierbarer Typ gesucht break am Ende
Collection<PlaceholderType> tphs = tqp.getInvolvedPlaceholderTypes(); Collection<PlaceholderType> tphs = tqp.getInvolvedPlaceholderTypes();
Optional<Unifier> opt = stdUnify.unify(tqp, thetaPrime); Optional<Unifier> opt = stdUnify.unify(tqp, thetaPrime);
@@ -1832,7 +1853,7 @@ public class TypeUnifyTask extends CancellableTask<CompletableFuture<Set<Set<Uni
} }
} }
} }
context.logger().debug(() ->"result von " + pair + ": " + result); writeLog("result von " + pair + ": " + result);
return result; return result;
} }
@@ -1943,7 +1964,7 @@ public class TypeUnifyTask extends CancellableTask<CompletableFuture<Set<Set<Uni
return ((match.match(termList).isPresent()) || x); return ((match.match(termList).isPresent()) || x);
}; };
//if (parai.getName().equals("java.lang.Integer")) { //if (parai.getName().equals("java.lang.Integer")) {
// context.logger().info(""); // System.out.println("");
//} //}
BinaryOperator<Boolean> bo = (x, y) -> (x || y); BinaryOperator<Boolean> bo = (x, y) -> (x || y);
if (fBounded.stream().reduce(false, f, bo)) { if (fBounded.stream().reduce(false, f, bo)) {
@@ -2033,4 +2054,22 @@ public class TypeUnifyTask extends CancellableTask<CompletableFuture<Set<Set<Uni
permuteParams(candidates, idx + 1, result, current); permuteParams(candidates, idx + 1, result, current);
} }
} }
public void writeLog(String str) {
if (context.log() && finalresult) {
synchronized (context.logFile()) {
try {
/*
logFile.write("Thread no.:" + thNo + "\n");
logFile.write("noOfThread:" + noOfThread + "\n");
logFile.write("parallel:" + parallel + "\n");
*/
context.logFile().write(str + "\n\n");
// logFile.flush();
} catch (IOException e) {
System.err.println("kein LogFile");
}
}
}
}
} }

View File

@@ -5,7 +5,6 @@ import de.dhbwstuttgart.typeinference.unify.model.PlaceholderType;
import de.dhbwstuttgart.typeinference.unify.model.UnifyPair; import de.dhbwstuttgart.typeinference.unify.model.UnifyPair;
import de.dhbwstuttgart.typeinference.unify.model.UnifyType; import de.dhbwstuttgart.typeinference.unify.model.UnifyType;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
@@ -186,36 +185,4 @@ public class TypeUnifyTaskHelper {
.collect(Collectors.toCollection(ArrayList::new)); .collect(Collectors.toCollection(ArrayList::new));
} }
public static Set<UnifyPair> occursCheck(final Set<UnifyPair> eq) {
Set<UnifyPair> ocurrPairs = new HashSet<>(eq.size());
for (UnifyPair x : eq) {
UnifyType lhs = x.getLhsType();
UnifyType rhs = x.getRhsType();
if (lhs instanceof PlaceholderType lhsPlaceholder &&
!(rhs instanceof PlaceholderType) &&
rhs.getTypeParams().occurs(lhsPlaceholder))
{
x.setUndefinedPair();
ocurrPairs.add(x);
}
}
return ocurrPairs;
}
public static <T> HashSet<T> getPresizedHashSet(int minElements) {
if (minElements < 16) return new HashSet<>();
// HashSet and HashMap will resize at 75% load, so we account for that by multiplying with 1.5
int n = (int)(minElements * 1.5);
return new HashSet<>(n);
}
public static <S,T> HashMap<S,T> getPresizedHashMap(int minElements) {
if (minElements < 16) return new HashMap<>();
// HashSet and HashMap will resize at 75% load, so we account for that by multiplying with 1.5
int n = (int)(minElements * 1.5);
return new HashMap<>(n);
}
} }

View File

@@ -1,15 +1,17 @@
package de.dhbwstuttgart.typeinference.unify; package de.dhbwstuttgart.typeinference.unify;
import de.dhbwstuttgart.util.Logger;
import java.io.Writer; import java.io.Writer;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
import java.util.concurrent.ForkJoinPool; import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.atomic.AtomicInteger;
public record UnifyContext( public record UnifyContext(
// main logger of a unification // main log file of a unification
Logger logger, Writer logFile,
// if logs should be made
Boolean log,
// if the unify algorithm should run in parallel // if the unify algorithm should run in parallel
boolean parallel, Boolean parallel,
// the model for storing calculated results // the model for storing calculated results
UnifyResultModel resultModel, UnifyResultModel resultModel,
// the executor used for thread management in parallel execution // the executor used for thread management in parallel execution
@@ -21,24 +23,26 @@ public record UnifyContext(
) { ) {
public UnifyContext( public UnifyContext(
Logger logger, Writer logFile,
boolean parallel, Boolean log,
Boolean parallel,
UnifyResultModel resultModel, UnifyResultModel resultModel,
UnifyTaskModel usedTasks, UnifyTaskModel usedTasks,
ExecutorService executor, ExecutorService executor,
PlaceholderRegistry placeholderRegistry PlaceholderRegistry placeholderRegistry
) { ) {
this(logger, parallel, resultModel, executor, placeholderRegistry, usedTasks); this(logFile, log, parallel, resultModel, executor, placeholderRegistry, usedTasks);
} }
public UnifyContext( public UnifyContext(
Logger logger, Writer logFile,
boolean parallel, Boolean log,
Boolean parallel,
UnifyResultModel resultModel, UnifyResultModel resultModel,
UnifyTaskModel usedTasks, UnifyTaskModel usedTasks,
PlaceholderRegistry placeholderRegistry PlaceholderRegistry placeholderRegistry
) { ) {
this(logger, parallel, resultModel, usedTasks, ForkJoinPool.commonPool(), placeholderRegistry); this(logFile, log, parallel, resultModel, usedTasks, ForkJoinPool.commonPool(), placeholderRegistry);
} }
@@ -47,21 +51,20 @@ public record UnifyContext(
* causes the UnifyContext to be essentially handled as a * causes the UnifyContext to be essentially handled as a
*/ */
public UnifyContext newWithLogger(Logger logger) { public UnifyContext newWithLogFile(Writer logFile) {
return new UnifyContext(logger, parallel, resultModel, executor, placeholderRegistry, usedTasks); return new UnifyContext(logFile, log, parallel, resultModel, executor, placeholderRegistry, usedTasks);
} }
public UnifyContext newWithParallel(boolean parallel) { public UnifyContext newWithParallel(boolean parallel) {
if (this.parallel == parallel) return this; return new UnifyContext(logFile, log, parallel, resultModel, executor, placeholderRegistry, usedTasks);
return new UnifyContext(logger, parallel, resultModel, executor, placeholderRegistry, usedTasks);
} }
public UnifyContext newWithExecutor(ExecutorService executor) { public UnifyContext newWithExecutor(ExecutorService executor) {
return new UnifyContext(logger, parallel, resultModel, executor, placeholderRegistry, usedTasks); return new UnifyContext(logFile, log, parallel, resultModel, executor, placeholderRegistry, usedTasks);
} }
public UnifyContext newWithResultModel(UnifyResultModel resultModel) { public UnifyContext newWithResultModel(UnifyResultModel resultModel) {
return new UnifyContext(logger, parallel, resultModel, executor, placeholderRegistry, usedTasks); return new UnifyContext(logFile, log, parallel, resultModel, executor, placeholderRegistry, usedTasks);
} }
} }

View File

@@ -12,7 +12,7 @@ public class UnifyTaskModel {
public synchronized void cancel() { public synchronized void cancel() {
for(TypeUnifyTask t : usedTasks) { for(TypeUnifyTask t : usedTasks) {
t.cancelExecution(); t.myCancel(true);
} }
} }
} }

View File

@@ -1,110 +0,0 @@
package de.dhbwstuttgart.typeinference.unify.cartesianproduct;
import de.dhbwstuttgart.typeinference.constraints.Constraint;
import de.dhbwstuttgart.typeinference.unify.TypeUnifyTask;
import de.dhbwstuttgart.typeinference.unify.UnifyContext;
import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure;
import de.dhbwstuttgart.typeinference.unify.model.PlaceholderType;
import de.dhbwstuttgart.typeinference.unify.model.UnifyPair;
import de.dhbwstuttgart.util.Tuple;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
public class UnknownVarianceCase extends VarianceCase {
protected final int variance = 0;
protected UnknownVarianceCase(boolean isOderConstraint, TypeUnifyTask typeUnifyTask, UnifyContext context) {
super(isOderConstraint, typeUnifyTask, context);
}
@Override
public void selectNextData(
TypeUnifyTask typeUnifyTask,
List<Set<UnifyPair>> nextSetAsList,
Optional<UnifyPair> optOrigPair
) {
//wenn a <. theta dann ist ein maximales Element sehr wahrscheinlich
//wenn theta <. a dann ist ein minimales Element sehr wahrscheinlich
if (!this.isOderConstraint && optOrigPair != null && optOrigPair.isPresent()) {
if (optOrigPair.get().getBasePair().getLhsType() instanceof PlaceholderType) {
a = typeUnifyTask.oup.max(nextSetAsList.iterator());
} else {
a = typeUnifyTask.oup.min(nextSetAsList.iterator());
}
nextSetAsList.remove(a);
} else if (this.isOderConstraint) {
a = typeUnifyTask.oup.max(nextSetAsList.iterator());
nextSetAsList.remove(a);
nextSetasListOderConstraints.add(((Constraint<UnifyPair>) a).getExtendConstraint());
} else {
a = nextSetAsList.removeFirst();
}
}
@Override
public CompletableFuture<ComputationResults> computeParallel(
Set<Set<UnifyPair>> elems,
Set<UnifyPair> eq,
List<Set<Constraint<UnifyPair>>> oderConstraints,
IFiniteClosure fc,
int rekTiefe,
Set<UnifyPair> methodSignatureConstraint,
List<Set<UnifyPair>> nextSetAsList,
Set<UnifyPair> sameEqSet,
Set<Set<UnifyPair>> result,
Set<Set<UnifyPair>> aParDef
) {
elems.add(a);
return typeUnifyTask.unify2(elems, eq, oderConstraints, fc, context.parallel(), rekTiefe, new HashSet<>(methodSignatureConstraint))
.thenApply(ComputationResults::new);
}
@Override
public void applyComputedResults(
Set<Set<UnifyPair>> result,
Set<Set<UnifyPair>> currentThreadResult,
Set<UnifyPair> compResult,
Set<UnifyPair> compRes
) {
context.logger().debug("RES var=0 ADD:" + result.toString() + " " + currentThreadResult.toString());
result.addAll(currentThreadResult);
}
@Override
public boolean eraseInvalidSets(
int rekTiefe,
Set<Set<UnifyPair>> aParDef,
List<Set<UnifyPair>> nextSetAsList
) {
if (!this.isOderConstraint) {
return true;
} else {
nextSetAsList.removeAll(nextSetasListOderConstraints);
nextSetasListOderConstraints = new ArrayList<>();
context.logger().debug("Removed: " + nextSetasListOderConstraints);
List<Set<UnifyPair>> smallerSetasList = typeUnifyTask.oup.smallerThan(a, nextSetAsList);
List<Set<UnifyPair>> notInherited = smallerSetasList.stream()
.filter(x -> !((Constraint<UnifyPair>) x).isInherited())
.collect(Collectors.toCollection(ArrayList::new));
List<Set<UnifyPair>> notErased = new ArrayList<>();
notInherited.forEach(x -> notErased.addAll(typeUnifyTask.oup.smallerEqThan(x, smallerSetasList)));
List<Set<UnifyPair>> erased = new ArrayList<>(smallerSetasList);
erased.removeAll(notErased);
nextSetAsList.removeAll(erased);
context.logger().debug("Removed: " + erased);
context.logger().debug("Not Removed: " + nextSetAsList);
}
return false;
}
}

View File

@@ -0,0 +1,228 @@
package de.dhbwstuttgart.typeinference.unify.cartesianproduct;
import de.dhbwstuttgart.exceptions.UnifyCancelException;
import de.dhbwstuttgart.typeinference.constraints.Constraint;
import de.dhbwstuttgart.typeinference.unify.TypeUnify2Task;
import de.dhbwstuttgart.typeinference.unify.TypeUnifyTask;
import de.dhbwstuttgart.typeinference.unify.UnifyContext;
import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure;
import de.dhbwstuttgart.typeinference.unify.model.PlaceholderType;
import de.dhbwstuttgart.typeinference.unify.model.UnifyPair;
import de.dhbwstuttgart.util.Tuple;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;
public class Variance0Case extends VarianceCase {
protected final int variance = 0;
protected Variance0Case(boolean isOderConstraint, TypeUnifyTask typeUnifyTask, UnifyContext context) {
super(isOderConstraint, typeUnifyTask, context);
}
@Override
public void selectNextData(
TypeUnifyTask typeUnifyTask,
List<Set<UnifyPair>> nextSetAsList,
Optional<UnifyPair> optOrigPair
) {
//wenn a <. theta dann ist ein maximales Element sehr wahrscheinlich
//wenn theta <. a dann ist ein minimales Element sehr wahrscheinlich
if (!this.isOderConstraint && optOrigPair != null && optOrigPair.isPresent()) {
if (optOrigPair.get().getBasePair().getLhsType() instanceof PlaceholderType) {
a = typeUnifyTask.oup.max(nextSetAsList.iterator());
} else {
a = typeUnifyTask.oup.min(nextSetAsList.iterator());
}
nextSetAsList.remove(a);
} else if (this.isOderConstraint) {
a = typeUnifyTask.oup.max(nextSetAsList.iterator());
nextSetAsList.remove(a);
nextSetasListOderConstraints.add(((Constraint<UnifyPair>) a).getExtendConstraint());
} else {
a = nextSetAsList.removeFirst();
}
Set<UnifyPair> finalA = a;
if (!this.isOderConstraint && optOrigPair != null && optOrigPair.isPresent()) {
if (optOrigPair.get().getBasePair().getLhsType() instanceof PlaceholderType) {
nextSetasListRest = typeUnifyTask.oup.maxElements(
nextSetAsList.stream().filter(a_next -> typeUnifyTask.oup.compare(finalA, a_next) != 1).toList()
);
} else {
nextSetasListRest = typeUnifyTask.oup.minElements(
nextSetAsList.stream().filter(a_next -> typeUnifyTask.oup.compare(finalA, a_next) != -1).toList()
);
}
nextSetAsList.remove(a);
} else if (this.isOderConstraint) {
nextSetasListRest = typeUnifyTask.oup.maxElements(
nextSetAsList.stream().filter(a_next -> typeUnifyTask.oup.compare(finalA, a_next) != 1).toList()
);
} else {
for (int i = 0; i < Math.min(nextSetAsList.size(), 5); i++) {
nextSetasListRest.add(nextSetAsList.removeFirst());
}
}
}
@Override
public CompletableFuture<Tuple<Set<Set<UnifyPair>>, Set<Set<Set<UnifyPair>>>>> computeParallel(
Set<Set<UnifyPair>> elems,
Set<UnifyPair> eq,
List<Set<Constraint<UnifyPair>>> oderConstraints,
IFiniteClosure fc,
int rekTiefe,
Set<UnifyPair> methodSignatureConstraint,
List<Set<UnifyPair>> nextSetAsList,
Set<UnifyPair> sameEqSet,
Set<Set<UnifyPair>> result,
Set<Set<UnifyPair>> aParDef
) {
CompletableFuture<Tuple<Set<Set<UnifyPair>>, Set<Set<Set<UnifyPair>>>>> resultValues = CompletableFuture.completedFuture(new Tuple<>(
new HashSet<>(), new HashSet<>()
));
Set<UnifyPair> newEqOrig = new HashSet<>(eq);
Set<Set<UnifyPair>> newElemsOrig = new HashSet<>(elems);
List<Set<Constraint<UnifyPair>>> newOderConstraintsOrig = new ArrayList<>(oderConstraints);
newElemsOrig.add(a);
/* FORK ANFANG */
TypeUnify2Task forkOrig = new TypeUnify2Task(newElemsOrig, newEqOrig, newOderConstraintsOrig, a, fc, context, rekTiefe, new HashSet<>(methodSignatureConstraint));
typeUnifyTask.addChildTask(forkOrig);
// schedule compute() on another thread
CompletableFuture<Set<Set<UnifyPair>>> forkOrigFuture = CompletableFuture.supplyAsync(forkOrig::compute, context.executor()).thenCompose(f -> f);
resultValues = resultValues.thenCombine(forkOrigFuture,
(prevResults, currentThreadResult) -> {
forkOrig.writeLog("final Orig 0");
forkOrig.closeLogFile();
return new Tuple<>(currentThreadResult, prevResults.getSecond());
});
//forks.add(forkOrig);
if (typeUnifyTask.myIsCancelled()) {
throw new UnifyCancelException();
}
/* FORK ENDE */
writeLog("a in " + variance + " " + a);
writeLog("nextSetasListRest: " + nextSetasListRest.toString());
while (!nextSetasListRest.isEmpty()) {
Set<UnifyPair> nSaL = nextSetasListRest.removeFirst();
nextSetAsList.remove(nSaL);
writeLog("0 RM" + nSaL.toString());
if (!this.isOderConstraint) {
//ueberpruefung ob zu a =. ty \in nSaL in sameEqSet ein Widerspruch besteht
if (!sameEqSet.isEmpty() && !typeUnifyTask.checkNoContradiction(nSaL, sameEqSet, result)) {
TypeUnifyTask.noShortendElements++;
continue;
}
} else {
nextSetasListOderConstraints.add(((Constraint<UnifyPair>) nSaL).getExtendConstraint());
}
Set<UnifyPair> newEq = new HashSet<>(eq);
Set<Set<UnifyPair>> newElems = new HashSet<>(elems);
List<Set<Constraint<UnifyPair>>> newOderConstraints = new ArrayList<>(oderConstraints);
newElems.add(nSaL);
TypeUnify2Task fork = new TypeUnify2Task(newElems, newEq, newOderConstraints, nSaL, fc, context, rekTiefe, new HashSet<>(methodSignatureConstraint));
typeUnifyTask.addChildTask(fork);
// schedule compute() on another thread
CompletableFuture<Set<Set<UnifyPair>>> forkFuture = CompletableFuture.supplyAsync(fork::compute, context.executor()).thenCompose(f -> f);
resultValues = resultValues.thenCombine(forkFuture,
(prevResults, fork_res) -> {
if (typeUnifyTask.myIsCancelled()) {
throw new UnifyCancelException();
}
writeLog("fork_res: " + fork_res.toString());
writeLog(Boolean.valueOf((typeUnifyTask.isUndefinedPairSetSet(fork_res))).toString());
prevResults.getSecond().add(fork_res);
if (!typeUnifyTask.isUndefinedPairSetSet(fork_res)) {
aParDef.add(fork.getNextSetElement());
}
fork.writeLog("final 0");
fork.closeLogFile();
return prevResults;
}
);
if (typeUnifyTask.myIsCancelled()) {
throw new UnifyCancelException();
}
}
return resultValues;
}
@Override
public void applyComputedResults(
Set<Set<UnifyPair>> result,
Set<Set<UnifyPair>> currentThreadResult,
Set<UnifyPair> compResult,
Set<UnifyPair> compRes
) {
writeLog("RES var=0 ADD:" + result.toString() + " " + currentThreadResult.toString());
result.addAll(currentThreadResult);
}
@Override
public boolean eraseInvalidSets(
int rekTiefe,
Set<Set<UnifyPair>> aParDef,
List<Set<UnifyPair>> nextSetAsList
) {
if (!this.isOderConstraint) {
return true;
} else {
nextSetAsList.removeAll(nextSetasListOderConstraints);
nextSetasListOderConstraints = new ArrayList<>();
writeLog("Removed: " + nextSetasListOderConstraints);
final List<Set<UnifyPair>> smallerSetasList = typeUnifyTask.oup.smallerThan(a, nextSetAsList);
List<Set<UnifyPair>> notInherited = smallerSetasList.stream()
.filter(x -> !((Constraint<UnifyPair>) x).isInherited())
.collect(Collectors.toCollection(ArrayList::new));
final List<Set<UnifyPair>> notErased = new ArrayList<>();
notInherited.forEach(x -> notErased.addAll(typeUnifyTask.oup.smallerEqThan(x, smallerSetasList)));
List<Set<UnifyPair>> erased = new ArrayList<>(smallerSetasList);
erased.removeAll(notErased);
nextSetAsList.removeAll(erased);
writeLog("Removed: " + erased);
writeLog("Not Removed: " + nextSetAsList);
for (Set<UnifyPair> aPar : aParDef) {
nextSetAsList.removeAll(nextSetasListOderConstraints);
nextSetasListOderConstraints = new ArrayList<>();
writeLog("Removed: " + nextSetasListOderConstraints);
smallerSetasList.clear();
smallerSetasList.addAll(typeUnifyTask.oup.smallerThan(aPar, nextSetAsList));
notInherited = smallerSetasList.stream()
.filter(x -> !((Constraint<UnifyPair>) x).isInherited())
.collect(Collectors.toCollection(ArrayList::new));
notErased.clear();
notInherited.forEach(x -> notErased.addAll(typeUnifyTask.oup.smallerEqThan(x, smallerSetasList)));
erased = new ArrayList<>(smallerSetasList);
erased.removeAll(notErased);
nextSetAsList.removeAll(erased);
writeLog("Removed: " + erased);
writeLog("Not Removed: " + nextSetAsList);
}
}
return false;
}
}

View File

@@ -1,5 +1,6 @@
package de.dhbwstuttgart.typeinference.unify.cartesianproduct; package de.dhbwstuttgart.typeinference.unify.cartesianproduct;
import de.dhbwstuttgart.exceptions.UnifyCancelException;
import de.dhbwstuttgart.typeinference.constraints.Constraint; import de.dhbwstuttgart.typeinference.constraints.Constraint;
import de.dhbwstuttgart.typeinference.unify.TypeUnify2Task; import de.dhbwstuttgart.typeinference.unify.TypeUnify2Task;
import de.dhbwstuttgart.typeinference.unify.TypeUnifyTask; import de.dhbwstuttgart.typeinference.unify.TypeUnifyTask;
@@ -16,11 +17,11 @@ import java.util.Set;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors; import java.util.stream.Collectors;
public class ContravarianceCase extends VarianceCase { public class Variance1Case extends VarianceCase {
protected final int variance = 1; protected final int variance = 1;
protected ContravarianceCase(boolean isOderConstraint, TypeUnifyTask typeUnifyTask, UnifyContext context) { protected Variance1Case(boolean isOderConstraint, TypeUnifyTask typeUnifyTask, UnifyContext context) {
super(isOderConstraint, typeUnifyTask, context); super(isOderConstraint, typeUnifyTask, context);
} }
@@ -31,12 +32,12 @@ public class ContravarianceCase extends VarianceCase {
Optional<UnifyPair> optOrigPair Optional<UnifyPair> optOrigPair
) { ) {
a = typeUnifyTask.oup.max(nextSetAsList.iterator()); a = typeUnifyTask.oup.max(nextSetAsList.iterator());
context.logger().debug("Max: a in " + variance + " " + a); writeLog("Max: a in " + variance + " " + a);
nextSetAsList.remove(a); nextSetAsList.remove(a);
if (this.isOderConstraint) { if (this.isOderConstraint) {
nextSetasListOderConstraints.add(((Constraint<UnifyPair>) a).getExtendConstraint()); nextSetasListOderConstraints.add(((Constraint<UnifyPair>) a).getExtendConstraint());
} }
context.logger().debug(() -> "nextSetasListOderConstraints 1: " + nextSetasListOderConstraints); writeLog("nextSetasListOderConstraints 1: " + nextSetasListOderConstraints);
//Alle maximale Elemente in nextSetasListRest bestimmen //Alle maximale Elemente in nextSetasListRest bestimmen
//nur für diese wird parallele Berechnung angestossen. //nur für diese wird parallele Berechnung angestossen.
@@ -48,7 +49,7 @@ public class ContravarianceCase extends VarianceCase {
@Override @Override
public CompletableFuture<ComputationResults> computeParallel( public CompletableFuture<Tuple<Set<Set<UnifyPair>>, Set<Set<Set<UnifyPair>>>>> computeParallel(
Set<Set<UnifyPair>> elems, Set<Set<UnifyPair>> elems,
Set<UnifyPair> eq, Set<UnifyPair> eq,
List<Set<Constraint<UnifyPair>>> oderConstraints, List<Set<Constraint<UnifyPair>>> oderConstraints,
@@ -60,6 +61,10 @@ public class ContravarianceCase extends VarianceCase {
Set<Set<UnifyPair>> result, Set<Set<UnifyPair>> result,
Set<Set<UnifyPair>> aParDef Set<Set<UnifyPair>> aParDef
) { ) {
CompletableFuture<Tuple<Set<Set<UnifyPair>>, Set<Set<Set<UnifyPair>>>>> resultValues = CompletableFuture.completedFuture(new Tuple<>(
new HashSet<>(), new HashSet<>()
));
Set<UnifyPair> newEqOrig = new HashSet<>(eq); Set<UnifyPair> newEqOrig = new HashSet<>(eq);
Set<Set<UnifyPair>> newElemsOrig = new HashSet<>(elems); Set<Set<UnifyPair>> newElemsOrig = new HashSet<>(elems);
List<Set<Constraint<UnifyPair>>> newOderConstraintsOrig = new ArrayList<>(oderConstraints); List<Set<Constraint<UnifyPair>>> newOderConstraintsOrig = new ArrayList<>(oderConstraints);
@@ -70,25 +75,25 @@ public class ContravarianceCase extends VarianceCase {
typeUnifyTask.addChildTask(forkOrig); typeUnifyTask.addChildTask(forkOrig);
// schedule compute() on another thread // schedule compute() on another thread
CompletableFuture<Set<Set<UnifyPair>>> forkOrigFuture = CompletableFuture.supplyAsync(forkOrig::compute, context.executor()).thenCompose(f -> f); CompletableFuture<Set<Set<UnifyPair>>> forkOrigFuture = CompletableFuture.supplyAsync(forkOrig::compute, context.executor()).thenCompose(f -> f);
CompletableFuture<ComputationResults> resultValues = forkOrigFuture.thenApply( resultValues = resultValues.thenCombine(forkOrigFuture,
(currentThreadResult) -> { (prevResults, currentThreadResult) -> {
forkOrig.context.logger().debug("final Orig 1"); forkOrig.writeLog("final Orig 1");
forkOrig.closeLogFile(); forkOrig.closeLogFile();
return new ComputationResults(currentThreadResult); return new Tuple<>(currentThreadResult, prevResults.getSecond());
}); });
//forks.add(forkOrig); //forks.add(forkOrig);
if (typeUnifyTask.isExecutionCancelled()) { if (typeUnifyTask.myIsCancelled()) {
return CompletableFuture.completedFuture(new ComputationResults()); throw new UnifyCancelException();
} }
/* FORK ENDE */ /* FORK ENDE */
context.logger().debug("a in " + variance + " " + a); writeLog("a in " + variance + " " + a);
context.logger().debug("nextSetasListRest: " + nextSetasListRest.toString()); writeLog("nextSetasListRest: " + nextSetasListRest.toString());
while (!nextSetasListRest.isEmpty()) { while (!nextSetasListRest.isEmpty()) {
Set<UnifyPair> nSaL = nextSetasListRest.removeFirst(); Set<UnifyPair> nSaL = nextSetasListRest.removeFirst();
nextSetAsList.remove(nSaL); nextSetAsList.remove(nSaL);
context.logger().debug("1 RM" + nSaL.toString()); writeLog("1 RM" + nSaL.toString());
if (!this.isOderConstraint) { if (!this.isOderConstraint) {
//ueberpruefung ob zu a =. ty \in nSaL in sameEqSet ein Widerspruch besteht //ueberpruefung ob zu a =. ty \in nSaL in sameEqSet ein Widerspruch besteht
@@ -109,23 +114,23 @@ public class ContravarianceCase extends VarianceCase {
CompletableFuture<Set<Set<UnifyPair>>> forkFuture = CompletableFuture.supplyAsync(fork::compute, context.executor()).thenCompose(f -> f); CompletableFuture<Set<Set<UnifyPair>>> forkFuture = CompletableFuture.supplyAsync(fork::compute, context.executor()).thenCompose(f -> f);
resultValues = resultValues.thenCombine(forkFuture, resultValues = resultValues.thenCombine(forkFuture,
(prevResults, fork_res) -> { (prevResults, fork_res) -> {
if (typeUnifyTask.isExecutionCancelled()) { if (typeUnifyTask.myIsCancelled()) {
return new ComputationResults(); throw new UnifyCancelException();
} }
context.logger().debug("fork_res: " + fork_res.toString()); writeLog("fork_res: " + fork_res.toString());
context.logger().debug(Boolean.valueOf((typeUnifyTask.isUndefinedPairSetSet(fork_res))).toString()); writeLog(Boolean.valueOf((typeUnifyTask.isUndefinedPairSetSet(fork_res))).toString());
prevResults.addForkResult(fork_res); prevResults.getSecond().add(fork_res);
if (!typeUnifyTask.isUndefinedPairSetSet(fork_res)) { if (!typeUnifyTask.isUndefinedPairSetSet(fork_res)) {
aParDef.add(fork.getNextSetElement()); aParDef.add(fork.getNextSetElement());
} }
fork.context.logger().debug("final 1"); fork.writeLog("final 1");
fork.closeLogFile(); fork.closeLogFile();
return prevResults; return prevResults;
} }
); );
if (typeUnifyTask.isExecutionCancelled()) { if (typeUnifyTask.myIsCancelled()) {
return CompletableFuture.completedFuture(new ComputationResults()); throw new UnifyCancelException();
} }
} }
@@ -141,7 +146,7 @@ public class ContravarianceCase extends VarianceCase {
) { ) {
int resOfCompare = typeUnifyTask.oup.compare(compResult, compRes); int resOfCompare = typeUnifyTask.oup.compare(compResult, compRes);
if (resOfCompare == -1) { if (resOfCompare == -1) {
context.logger().debug("Geloescht result: " + result); writeLog("Geloescht result: " + result);
result.clear(); result.clear();
result.addAll(currentThreadResult); result.addAll(currentThreadResult);
} }
@@ -149,7 +154,7 @@ public class ContravarianceCase extends VarianceCase {
result.addAll(currentThreadResult); result.addAll(currentThreadResult);
} }
else if (resOfCompare == 1) { else if (resOfCompare == 1) {
context.logger().debug("Geloescht currentThreadResult: " + currentThreadResult); writeLog("Geloescht currentThreadResult: " + currentThreadResult);
//result = result; //result = result;
} }
} }
@@ -160,35 +165,35 @@ public class ContravarianceCase extends VarianceCase {
Set<Set<UnifyPair>> aParDef, Set<Set<UnifyPair>> aParDef,
List<Set<UnifyPair>> nextSetAsList List<Set<UnifyPair>> nextSetAsList
) { ) {
// context.logger().info(""); // System.out.println("");
context.logger().debug("a: " + rekTiefe + " variance: " + variance + a.toString()); writeLog("a: " + rekTiefe + " variance: " + variance + a.toString());
context.logger().debug("aParDef: " + aParDef.toString()); writeLog("aParDef: " + aParDef.toString());
aParDef.add(a); aParDef.add(a);
Iterator<Set<UnifyPair>> aParDefIt = aParDef.iterator(); Iterator<Set<UnifyPair>> aParDefIt = aParDef.iterator();
if (this.isOderConstraint) { if (this.isOderConstraint) {
nextSetAsList.removeAll(nextSetasListOderConstraints); nextSetAsList.removeAll(nextSetasListOderConstraints);
nextSetasListOderConstraints = new ArrayList<>(); nextSetasListOderConstraints = new ArrayList<>();
context.logger().debug("Removed: " + nextSetasListOderConstraints); writeLog("Removed: " + nextSetasListOderConstraints);
while (aParDefIt.hasNext()) { while (aParDefIt.hasNext()) {
Set<UnifyPair> a_new = aParDefIt.next(); Set<UnifyPair> a_new = aParDefIt.next();
List<Set<UnifyPair>> smallerSetasList = typeUnifyTask.oup.smallerThan(a_new, nextSetAsList); List<Set<UnifyPair>> smallerSetasList = typeUnifyTask.oup.smallerThan(a_new, nextSetAsList);
context.logger().debug("smallerSetasList: " + smallerSetasList); writeLog("smallerSetasList: " + smallerSetasList);
List<Set<UnifyPair>> notInherited = smallerSetasList.stream() List<Set<UnifyPair>> notInherited = smallerSetasList.stream()
.filter(x -> !((Constraint<UnifyPair>) x).isInherited() && !((Constraint<UnifyPair>) x).isImplemented()) .filter(x -> !((Constraint<UnifyPair>) x).isInherited() && !((Constraint<UnifyPair>) x).isImplemented())
.collect(Collectors.toCollection(ArrayList::new)); .collect(Collectors.toCollection(ArrayList::new));
context.logger().debug("notInherited: " + notInherited + "\n"); writeLog("notInherited: " + notInherited + "\n");
List<Set<UnifyPair>> notErased = new ArrayList<>(); List<Set<UnifyPair>> notErased = new ArrayList<>();
notInherited.forEach(x -> { notInherited.forEach(x -> {
notErased.addAll(typeUnifyTask.oup.smallerEqThan(x, smallerSetasList)); notErased.addAll(typeUnifyTask.oup.smallerEqThan(x, smallerSetasList));
}); });
List<Set<UnifyPair>> erased = new ArrayList<>(smallerSetasList); List<Set<UnifyPair>> erased = new ArrayList<>(smallerSetasList);
context.logger().debug("notErased: " + notErased + "\n"); writeLog("notErased: " + notErased + "\n");
erased.removeAll(notErased); erased.removeAll(notErased);
nextSetAsList.removeAll(erased); nextSetAsList.removeAll(erased);
context.logger().debug("Removed: " + erased); writeLog("Removed: " + erased);
context.logger().debug("Not Removed: " + nextSetAsList); writeLog("Not Removed: " + nextSetAsList);
} }
} else { } else {
@@ -198,9 +203,9 @@ public class ContravarianceCase extends VarianceCase {
List<Set<UnifyPair>> erased = typeUnifyTask.oup.smallerEqThan(a_new, nextSetAsList); List<Set<UnifyPair>> erased = typeUnifyTask.oup.smallerEqThan(a_new, nextSetAsList);
nextSetAsList.removeAll(erased); nextSetAsList.removeAll(erased);
context.logger().debug("Removed: " + erased); writeLog("Removed: " + erased);
context.logger().debug("Not Removed: " + nextSetAsList); writeLog("Not Removed: " + nextSetAsList);
} }
} }

View File

@@ -1,5 +1,6 @@
package de.dhbwstuttgart.typeinference.unify.cartesianproduct; package de.dhbwstuttgart.typeinference.unify.cartesianproduct;
import de.dhbwstuttgart.exceptions.UnifyCancelException;
import de.dhbwstuttgart.typeinference.constraints.Constraint; import de.dhbwstuttgart.typeinference.constraints.Constraint;
import de.dhbwstuttgart.typeinference.unify.TypeUnify2Task; import de.dhbwstuttgart.typeinference.unify.TypeUnify2Task;
import de.dhbwstuttgart.typeinference.unify.TypeUnifyTask; import de.dhbwstuttgart.typeinference.unify.TypeUnifyTask;
@@ -14,12 +15,11 @@ import java.util.Optional;
import java.util.Set; import java.util.Set;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
public class InvarianceOrConstraintCase extends VarianceCase { public class Variance2Case extends VarianceCase {
// either for invariance or for oderConstraints
protected final int variance = 2; protected final int variance = 2;
protected InvarianceOrConstraintCase(boolean isOderConstraint, TypeUnifyTask typeUnifyTask, UnifyContext context) { protected Variance2Case(boolean isOderConstraint, TypeUnifyTask typeUnifyTask, UnifyContext context) {
super(isOderConstraint, typeUnifyTask, context); super(isOderConstraint, typeUnifyTask, context);
} }
@@ -37,7 +37,7 @@ public class InvarianceOrConstraintCase extends VarianceCase {
@Override @Override
public CompletableFuture<ComputationResults> computeParallel( public CompletableFuture<Tuple<Set<Set<UnifyPair>>, Set<Set<Set<UnifyPair>>>>> computeParallel(
Set<Set<UnifyPair>> elems, Set<Set<UnifyPair>> elems,
Set<UnifyPair> eq, Set<UnifyPair> eq,
List<Set<Constraint<UnifyPair>>> oderConstraints, List<Set<Constraint<UnifyPair>>> oderConstraints,
@@ -49,7 +49,9 @@ public class InvarianceOrConstraintCase extends VarianceCase {
Set<Set<UnifyPair>> result, Set<Set<UnifyPair>> result,
Set<Set<UnifyPair>> aParDef Set<Set<UnifyPair>> aParDef
) { ) {
context.logger().debug("var2einstieg"); CompletableFuture<Tuple<Set<Set<UnifyPair>>, Set<Set<Set<UnifyPair>>>>> resultValuesFuture;
writeLog("var2einstieg");
Set<TypeUnify2Task> forks = new HashSet<>(); Set<TypeUnify2Task> forks = new HashSet<>();
Set<UnifyPair> newEqOrig = new HashSet<>(eq); Set<UnifyPair> newEqOrig = new HashSet<>(eq);
Set<Set<UnifyPair>> newElemsOrig = new HashSet<>(elems); Set<Set<UnifyPair>> newElemsOrig = new HashSet<>(elems);
@@ -60,19 +62,18 @@ public class InvarianceOrConstraintCase extends VarianceCase {
TypeUnify2Task forkOrig = new TypeUnify2Task(newElemsOrig, newEqOrig, newOderConstraintsOrig, a, fc, context, rekTiefe, new HashSet<>(methodSignatureConstraint)); TypeUnify2Task forkOrig = new TypeUnify2Task(newElemsOrig, newEqOrig, newOderConstraintsOrig, a, fc, context, rekTiefe, new HashSet<>(methodSignatureConstraint));
typeUnifyTask.addChildTask(forkOrig); typeUnifyTask.addChildTask(forkOrig);
CompletableFuture<Set<Set<UnifyPair>>> forkOrigFuture = CompletableFuture.supplyAsync(forkOrig::compute, context.executor()).thenCompose(f -> f); CompletableFuture<Set<Set<UnifyPair>>> forkOrigFuture = CompletableFuture.supplyAsync(forkOrig::compute, context.executor()).thenCompose(f -> f);
CompletableFuture<ComputationResults> resultValues = forkOrigFuture.thenApply((currentThreadResult) -> { resultValuesFuture = forkOrigFuture.thenApply((currentThreadResult) -> {
forkOrig.context.logger().debug("final Orig 2"); forkOrig.writeLog("final Orig 2");
forkOrig.closeLogFile(); forkOrig.closeLogFile();
return new ComputationResults(currentThreadResult); return new Tuple<>(currentThreadResult, new HashSet<>());
}); });
if (typeUnifyTask.myIsCancelled()) {
if (typeUnifyTask.isExecutionCancelled()) { throw new UnifyCancelException();
return resultValues;
} }
/* FORK ENDE */ /* FORK ENDE */
context.logger().debug(() -> "a in " + variance + " " + a); writeLog("a in " + variance + " " + a);
context.logger().debug(() -> "nextSetasListRest: " + nextSetasListRest.toString()); writeLog("nextSetasListRest: " + nextSetasListRest.toString());
//Fuer parallele Berechnung der Oder-Contraints wird methodSignature kopiert //Fuer parallele Berechnung der Oder-Contraints wird methodSignature kopiert
//und jeweils die methodSignature von a bzw. nSaL wieder gelöscht, wenn es keine Lösung ist. //und jeweils die methodSignature von a bzw. nSaL wieder gelöscht, wenn es keine Lösung ist.
@@ -91,22 +92,26 @@ public class InvarianceOrConstraintCase extends VarianceCase {
TypeUnify2Task fork = new TypeUnify2Task(newElems, newEq, newOderConstraints, nSaL, fc, context, rekTiefe, new HashSet<>(methodSignatureConstraintForParallel)); TypeUnify2Task fork = new TypeUnify2Task(newElems, newEq, newOderConstraints, nSaL, fc, context, rekTiefe, new HashSet<>(methodSignatureConstraintForParallel));
typeUnifyTask.addChildTask(fork); typeUnifyTask.addChildTask(fork);
CompletableFuture<Set<Set<UnifyPair>>> forkFuture = CompletableFuture.supplyAsync(fork::compute, context.executor()).thenCompose(f -> f); CompletableFuture<Set<Set<UnifyPair>>> forkFuture = CompletableFuture.supplyAsync(fork::compute, context.executor()).thenCompose(f -> f);
resultValues = resultValues.thenCombine(forkFuture, (prevResults, fork_res) -> { resultValuesFuture = resultValuesFuture.thenCombine(forkFuture, (resultValues, fork_res) -> {
if (typeUnifyTask.isExecutionCancelled()) { if (typeUnifyTask.myIsCancelled()) {
return prevResults; throw new UnifyCancelException();
} }
prevResults.addForkResult(fork_res); resultValues.getSecond().add(fork_res);
fork.context.logger().debug("final 2"); fork.writeLog("final 2");
fork.closeLogFile(); fork.closeLogFile();
return prevResults; return resultValues;
}); });
if (typeUnifyTask.isExecutionCancelled()) { if (typeUnifyTask.myIsCancelled()) {
return resultValues; throw new UnifyCancelException();
} }
} }
return resultValues; if (typeUnifyTask.myIsCancelled()) {
throw new UnifyCancelException();
}
return resultValuesFuture;
} }
@Override @Override

View File

@@ -5,9 +5,9 @@ import de.dhbwstuttgart.typeinference.unify.TypeUnifyTask;
import de.dhbwstuttgart.typeinference.unify.UnifyContext; import de.dhbwstuttgart.typeinference.unify.UnifyContext;
import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure; import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure;
import de.dhbwstuttgart.typeinference.unify.model.UnifyPair; import de.dhbwstuttgart.typeinference.unify.model.UnifyPair;
import de.dhbwstuttgart.util.Logger;
import de.dhbwstuttgart.util.Tuple; import de.dhbwstuttgart.util.Tuple;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
import java.util.Set; import java.util.Set;
@@ -17,11 +17,11 @@ public abstract class VarianceCase {
public static VarianceCase createFromVariance(int variance, boolean isOderConstraint, TypeUnifyTask typeUnifyTask, UnifyContext context) { public static VarianceCase createFromVariance(int variance, boolean isOderConstraint, TypeUnifyTask typeUnifyTask, UnifyContext context) {
return switch (variance) { return switch (variance) {
case 0 -> new UnknownVarianceCase(isOderConstraint, typeUnifyTask, context); case 0 -> new Variance0Case(isOderConstraint, typeUnifyTask, context);
case 1 -> new ContravarianceCase(isOderConstraint, typeUnifyTask, context); case 1 -> new Variance1Case(isOderConstraint, typeUnifyTask, context);
case -1 -> new CovarianceCase(isOderConstraint, typeUnifyTask, context); case -1 -> new VarianceM1Case(isOderConstraint, typeUnifyTask, context);
case 2 -> new InvarianceOrConstraintCase(isOderConstraint, typeUnifyTask, context); case 2 -> new Variance2Case(isOderConstraint, typeUnifyTask, context);
default -> throw new RuntimeException("Invalid variance: " + variance); default -> throw new RuntimeException("Invalid variance: " + variance);
}; };
} }
@@ -72,7 +72,7 @@ public abstract class VarianceCase {
/** /**
* *
*/ */
public abstract CompletableFuture<ComputationResults> computeParallel( public abstract CompletableFuture<Tuple<Set<Set<UnifyPair>>, Set<Set<Set<UnifyPair>>>>> computeParallel(
Set<Set<UnifyPair>> elems, Set<Set<UnifyPair>> elems,
Set<UnifyPair> eq, Set<UnifyPair> eq,
List<Set<Constraint<UnifyPair>>> oderConstraints, List<Set<Constraint<UnifyPair>>> oderConstraints,
@@ -105,28 +105,8 @@ public abstract class VarianceCase {
List<Set<UnifyPair>> nextSetAsList List<Set<UnifyPair>> nextSetAsList
); );
/** protected void writeLog(String s) {
* Wrapper class for the parallel computation results typeUnifyTask.writeLog(s);
*/
public static class ComputationResults {
public Set<Set<UnifyPair>> mainResult;
public Set<Set<Set<UnifyPair>>> forkResults;
public ComputationResults() {
this(new HashSet<>(), new HashSet<>());
}
public ComputationResults(Set<Set<UnifyPair>> mainResult) {
this(mainResult, new HashSet<>());
}
public ComputationResults(Set<Set<UnifyPair>> mainResult, Set<Set<Set<UnifyPair>>> forkResults) {
this.mainResult = mainResult;
this.forkResults = forkResults;
}
void addForkResult(Set<Set<UnifyPair>> forkResult) {
forkResults.add(forkResult);
}
} }
} }

Some files were not shown because too many files have changed in this diff Show More