46 Commits

Author SHA1 Message Date
Fabian Holzwarth
af15a1b90c Merge branch 'master' into feat/unify-server-mergeMaster 2025-07-24 14:41:05 +02:00
814f5dd5fa Add main method #372 2025-07-23 16:00:37 +02:00
24ca985ccc Fix #373 2025-07-23 14:41:57 +02:00
d6ed0689bc Fix test 2025-07-23 11:56:34 +02:00
d7676f36e3 Fix #371 2025-07-23 11:44:10 +02:00
Fabian Holzwarth
3d99f282f5 feat: cleanup code 2025-07-21 16:12:56 +02:00
Fabian Holzwarth
303c91dc87 chore: making classnames more expressive and cleanup some structures 2025-07-19 12:50:30 +02:00
julian
9e323759d6 sort resultsets before printing them to the console to enhance comparability between results 2025-07-16 11:17:53 +02:00
Fabian Holzwarth
603a8b176a feat: implement partically cancellable tasks 2025-07-16 11:16:30 +02:00
558083166d Fix subtyping of function types 2025-07-15 15:02:15 +02:00
julian
aec2f9a399 adjust FiniteClosure to only use imported types + some necessary ones 2025-07-15 14:06:51 +02:00
Fabian Holzwarth
f396189a4b feat: add timestamp to server output 2025-07-12 13:44:18 +02:00
Fabian Holzwarth
e7f4a94908 feat: fixed old condition on server timeout 2025-07-12 13:22:54 +02:00
Fabian Holzwarth
ce49a4b9a5 feat: reduce temporary objects and repeated loops 2025-07-12 13:14:55 +02:00
Fabian Holzwarth
03b3692724 feat: update indepenedentest 2025-07-11 12:50:27 +02:00
Fabian Holzwarth
f0022d2b6f feat: use presized hashMaps to reduce resizing 2025-07-11 11:22:06 +02:00
pl@gohorb.ba-horb.de
31df7a65f0 deleted: ../resources/bytecode/javFiles/Bug365a.jav
modified:   ../src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java
	modified:   ../src/test/java/TestComplete.java
2025-07-08 17:44:55 +02:00
pl@gohorb.ba-horb.de
185989ba62 --- a/src/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java
+++ b/src/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java
@@ -73,7 +73,7 @@ public class TYPEStmt implements StatementVisitor {

     @Override
     public void visit(LambdaExpression lambdaExpression) {
-        TypePlaceholder tphRetType = TypePlaceholder.fresh(new NullToken());
+        TypePlaceholder tphRetType = TypePlaceholder.fresh(new NullToken(), -1, false);
         List<RefTypeOrTPHOrWildcardOrGeneric> lambdaParams = lambdaExpression.params.getFormalparalist().stream().map((formalParameter -> formalParameter.getType())).collect(Collectors.toList());
         lambdaParams.add(tphRetType);
         // lambdaParams.add(0,tphRetType);
@@ -635,6 +635,7 @@ public class TYPEStmt implements StatementVisitor {
             params.add(resolver.resolve(new GenericRefType(gtv.getName(), new NullToken())));
         }
         RefTypeOrTPHOrWildcardOrGeneric receiverType;

	modified:   ../src/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java
2025-07-08 14:32:05 +02:00
Fabian Holzwarth
b1015cfa82 feat: update logging and add success-level 2025-07-07 16:19:04 +02:00
Fabian Holzwarth
b63a27a0a0 feat: improve server by assinging configured thread pools 2025-07-07 15:59:46 +02:00
Fabian Holzwarth
3b0a53d3c4 feat: add cross dependency, fix: socket closing and error messages 2025-07-07 15:19:56 +02:00
Fabian Holzwarth
50dbbf5f86 feat: implement generalized socket client, server logger and cleanup code 2025-07-07 14:01:27 +02:00
pl@gohorb.ba-horb.de
0eb48ba425 new file: resources/bytecode/javFiles/Bug365a.jav
modified:   src/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java
	modified:   src/test/java/TestComplete.java
2025-07-07 13:11:27 +02:00
Fabian Holzwarth
130c491ac0 feat: more Boxing replacements 2025-07-06 15:49:59 +02:00
Fabian Holzwarth
9f9b264ac4 feat: replace unnecessary boxing with primitives 2025-07-06 15:18:51 +02:00
Fabian Holzwarth
1393db05c2 feat: implement lazy evaluation for logger outputs 2025-07-06 13:37:47 +02:00
Fabian Holzwarth
93e1a8787c feat: do not create a new context, if nothing changes 2025-07-05 11:43:10 +02:00
Fabian Holzwarth
0129d7540f feat use perMessagDeflate compression in websocket and use logger for message outpute 2025-07-05 11:16:06 +02:00
Fabian Holzwarth
7ea8337aee feat: remove unused logging library 2025-07-05 11:15:33 +02:00
Fabian Holzwarth
28458d405f feat: ignore server test 2025-07-02 15:47:55 +02:00
ceee9a49c4 Merge branch 'issue363' of ssh://gitea.hb.dhbw-stuttgart.de:2222/JavaTX/JavaCompilerCore into issue363 2025-07-02 11:09:44 +02:00
ee64218a5f Fix class files not generating FunN types when using jar file 2025-07-02 11:09:38 +02:00
c50f14a4a3 .gitea/workflows/build_and_test.yml aktualisiert 2025-07-01 14:35:08 +00:00
1f4250ff84 Update project to java 24, update dependencies and change api to Junit 5 2025-07-01 15:55:58 +02:00
ae41c7f19d Fix #366 2025-07-01 15:54:08 +02:00
2416c80c20 Merge branch 'issue363' of ssh://gitea.hb.dhbw-stuttgart.de:2222/JavaTX/JavaCompilerCore into issue363 2025-07-01 13:46:19 +02:00
4cc55c0059 Add test for #366 2025-07-01 13:45:56 +02:00
9434facfa0 Purge generics from lambdas 2025-06-20 15:43:15 +02:00
09a6b9a788 Fix lambda expression captures 2025-06-18 18:31:22 +02:00
8b342c5604 the last commit message was a lie, nothing was fixed. The lambdas does not even respect the arguments it is given? 2025-06-18 16:46:27 +02:00
cdb93b5155 Remove ByteArrayClassLoader and fix #363 2025-06-18 15:26:14 +02:00
b07e848fa2 Remove print statement 2025-06-18 13:24:59 +02:00
313cd20f36 Fix #364 2025-06-18 13:24:06 +02:00
567fcc3b9a rename issues to bug 2025-06-18 12:59:00 +02:00
d9936e7197 add issue 364 2025-06-18 12:55:50 +02:00
8f194b3102 add issue 363 2025-06-18 12:48:55 +02:00
95 changed files with 2681 additions and 1876 deletions

View File

@@ -15,7 +15,7 @@ jobs:
uses: actions/setup-java@v4 uses: actions/setup-java@v4
with: with:
distribution: 'temurin' distribution: 'temurin'
java-version: '23' java-version: '24'
cache: 'maven' cache: 'maven'
- name: Compile project - name: Compile project
run: | run: |

View File

@@ -10,6 +10,7 @@ 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
@@ -19,15 +20,14 @@ 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
# mvn clean compile -DskipTests package # sed -i -e 's/target>21/target>23/g' pom.xml
## 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 test mvn clean compile -DskipTests package
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... "

28
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>junit</groupId> <groupId>org.junit.jupiter</groupId>
<artifactId>junit</artifactId> <artifactId>junit-jupiter-api</artifactId>
<version>4.13.2</version> <version>5.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.11.1</version> <version>4.13.2</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>commons-io</groupId> <groupId>commons-io</groupId>
<artifactId>commons-io</artifactId> <artifactId>commons-io</artifactId>
<version>2.16.1</version> <version>2.19.0</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>io.github.classgraph</groupId> <groupId>io.github.classgraph</groupId>
<artifactId>classgraph</artifactId> <artifactId>classgraph</artifactId>
<version>4.8.172</version> <version>4.8.180</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.google.guava</groupId> <groupId>com.google.guava</groupId>
<artifactId>guava</artifactId> <artifactId>guava</artifactId>
<version>33.2.0-jre</version> <version>33.4.8-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.5</version> <version>9.8</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.java-websocket</groupId> <groupId>org.java-websocket</groupId>
@@ -71,17 +71,17 @@ 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-compiler-plugin</artifactId> <artifactId>maven-compiler-plugin</artifactId>
<version>3.11.0</version> <version>3.14.0</version>
<configuration> <configuration>
<compilerArgs>--enable-preview</compilerArgs> <compilerArgs>--enable-preview</compilerArgs>
<source>23</source> <source>24</source>
<target>23</target> <target>24</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.1.0</version> <version>3.5.3</version>
<configuration> <configuration>
<redirectTestOutputToFile>true</redirectTestOutputToFile> <redirectTestOutputToFile>true</redirectTestOutputToFile>
<reportsDirectory>${project.build.directory}/test-reports</reportsDirectory> <reportsDirectory>${project.build.directory}/test-reports</reportsDirectory>
@@ -97,7 +97,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.11.1</version> <version>4.13.2</version>
<executions> <executions>
<execution> <execution>
<id>antlr</id> <id>antlr</id>
@@ -110,7 +110,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.3.0</version> <version>3.4.2</version>
<configuration> <configuration>
<archive> <archive>
<manifest> <manifest>

View File

@@ -6,7 +6,7 @@ import java.util.stream.Stream;
public class Bug325 { public class Bug325 {
public main() { public main() {
List<Integer> list = new ArrayList<>(List.of(1,2,3,4,5)); var 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

@@ -0,0 +1,22 @@
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

@@ -0,0 +1,8 @@
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

@@ -0,0 +1,21 @@
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

@@ -0,0 +1,12 @@
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

@@ -0,0 +1,10 @@
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

@@ -0,0 +1,17 @@
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,16 +0,0 @@
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

@@ -0,0 +1,14 @@
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

@@ -14,6 +14,7 @@ import org.objectweb.asm.*;
import java.lang.invoke.*; import java.lang.invoke.*;
import java.lang.reflect.Modifier; import java.lang.reflect.Modifier;
import java.util.*; import java.util.*;
import java.util.stream.Collectors;
import static org.objectweb.asm.Opcodes.*; import static org.objectweb.asm.Opcodes.*;
import static de.dhbwstuttgart.target.tree.expression.TargetBinaryOp.*; import static de.dhbwstuttgart.target.tree.expression.TargetBinaryOp.*;
@@ -87,14 +88,16 @@ public class Codegen {
int localCounter; int localCounter;
MethodVisitor mv; MethodVisitor mv;
TargetType returnType; TargetType returnType;
boolean isStatic = false;
Stack<BreakEnv> breakStack = new Stack<>(); Stack<BreakEnv> breakStack = new Stack<>();
Stack<Integer> switchResultValue = new Stack<>(); Stack<Integer> switchResultValue = new Stack<>();
State(TargetType returnType, MethodVisitor mv, int localCounter) { State(TargetType returnType, MethodVisitor mv, int localCounter, boolean isStatic) {
this.returnType = returnType; this.returnType = returnType;
this.mv = mv; this.mv = mv;
this.localCounter = localCounter; this.localCounter = localCounter;
this.isStatic = isStatic;
} }
void enterScope() { void enterScope() {
@@ -232,9 +235,9 @@ public class Codegen {
if (source.equals(dest)) if (source.equals(dest))
return; return;
if (source.equals(TargetType.Long)) { if (source.equals(TargetType.Long)) {
if (dest.equals(TargetType.Integer)) { if (dest.equals(TargetType.Integer))
mv.visitInsn(L2I); mv.visitInsn(L2I);
} else if (dest.equals(TargetType.Float)) else if (dest.equals(TargetType.Float))
mv.visitInsn(L2F); mv.visitInsn(L2F);
else if (dest.equals(TargetType.Double)) else if (dest.equals(TargetType.Double))
mv.visitInsn(L2D); mv.visitInsn(L2D);
@@ -277,6 +280,8 @@ public class Codegen {
mv.visitInsn(I2F); mv.visitInsn(I2F);
else if (dest.equals(TargetType.Double)) else if (dest.equals(TargetType.Double))
mv.visitInsn(I2D); mv.visitInsn(I2D);
} else if (source.equals(TargetType.Boolean)) {
unboxPrimitive(state, dest);
} else if (isFunctionalInterface(source) && isFunctionalInterface(dest) && } else if (isFunctionalInterface(source) && isFunctionalInterface(dest) &&
!(source instanceof TargetFunNType && dest instanceof TargetFunNType)) { !(source instanceof TargetFunNType && dest instanceof TargetFunNType)) {
boxFunctionalInterface(state, source, dest); boxFunctionalInterface(state, source, dest);
@@ -760,6 +765,16 @@ public class Codegen {
} }
} }
private static TargetType removeGenerics(TargetType param) {
return switch (param) {
case null -> null;
case TargetFunNType funNType -> new TargetFunNType(funNType.name(), funNType.funNParams(), List.of(), funNType.returnArguments());
case TargetRefType refType -> new TargetRefType(refType.name());
case TargetGenericType targetGenericType -> TargetType.Object;
default -> param;
};
}
private void generateLambdaExpression(State state, TargetLambdaExpression lambda) { private void generateLambdaExpression(State state, TargetLambdaExpression lambda) {
var mv = state.mv; var mv = state.mv;
@@ -771,7 +786,8 @@ public class Codegen {
var parameters = new ArrayList<>(lambda.captures()); var parameters = new ArrayList<>(lambda.captures());
parameters.addAll(signature.parameters()); parameters.addAll(signature.parameters());
var implSignature = new TargetMethod.Signature(Set.of(), parameters, lambda.signature().returnType()); parameters = parameters.stream().map(param -> param.withType(removeGenerics(param.pattern().type()))).collect(Collectors.toCollection(ArrayList::new));
var implSignature = new TargetMethod.Signature(Set.of(), parameters, removeGenerics(lambda.signature().returnType()));
TargetMethod impl; TargetMethod impl;
if (lambdas.containsKey(lambda)) { if (lambdas.containsKey(lambda)) {
@@ -779,20 +795,21 @@ public class Codegen {
} else { } else {
var name = "lambda$" + lambdaCounter++; var name = "lambda$" + lambdaCounter++;
impl = new TargetMethod(0, name, lambda.block(), implSignature, null); impl = new TargetMethod(state.isStatic ? ACC_STATIC : 0, name, lambda.block(), implSignature, null);
generateMethod(impl); generateMethod(impl, state);
lambdas.put(lambda, impl); lambdas.put(lambda, impl);
} }
var mt = MethodType.methodType(CallSite.class, MethodHandles.Lookup.class, String.class, MethodType.class, MethodType.class, MethodHandle.class, MethodType.class); var mt = MethodType.methodType(CallSite.class, MethodHandles.Lookup.class, String.class, MethodType.class, MethodType.class, MethodHandle.class, MethodType.class);
var bootstrap = new Handle(H_INVOKESTATIC, "java/lang/invoke/LambdaMetafactory", "metafactory", mt.toMethodDescriptorString(), false); var bootstrap = new Handle(H_INVOKESTATIC, "java/lang/invoke/LambdaMetafactory", "metafactory", mt.toMethodDescriptorString(), false);
var handle = new Handle(H_INVOKEVIRTUAL, clazz.getName(), impl.name(), implSignature.getDescriptor(), false); var handle = new Handle(state.isStatic ? H_INVOKESTATIC : H_INVOKEVIRTUAL, clazz.getName(), impl.name(), implSignature.getDescriptor(), false);
var params = new ArrayList<TargetType>(); var params = new ArrayList<TargetType>();
params.add(new TargetRefType(clazz.qualifiedName().getClassName())); if(!state.isStatic) params.add(new TargetRefType(clazz.qualifiedName().getClassName()));
params.addAll(lambda.captures().stream().map(mp -> mp.pattern().type()).toList()); params.addAll(lambda.captures().stream().map(mp -> mp.pattern().type()).toList());
if (!state.isStatic)
mv.visitVarInsn(ALOAD, 0); mv.visitVarInsn(ALOAD, 0);
for (var index = 0; index < lambda.captures().size(); index++) { for (var index = 0; index < lambda.captures().size(); index++) {
var capture = lambda.captures().get(index); var capture = lambda.captures().get(index);
@@ -1521,7 +1538,7 @@ public class Codegen {
MethodVisitor mv = cw.visitMethod(ACC_PUBLIC | ACC_STATIC, "<clinit>", "()V", null, null); MethodVisitor mv = cw.visitMethod(ACC_PUBLIC | ACC_STATIC, "<clinit>", "()V", null, null);
mv.visitCode(); mv.visitCode();
var state = new State(null, mv, 0); var state = new State(null, mv, 0, true);
generate(state, constructor.block()); generate(state, constructor.block());
mv.visitInsn(RETURN); mv.visitInsn(RETURN);
@@ -1535,7 +1552,7 @@ public class Codegen {
mv.visitAttribute(new JavaTXSignatureAttribute(constructor.getTXSignature())); mv.visitAttribute(new JavaTXSignatureAttribute(constructor.getTXSignature()));
mv.visitCode(); mv.visitCode();
var state = new State(null, mv, 1); var state = new State(null, mv, 1, false);
for (var param : constructor.parameters()) { for (var param : constructor.parameters()) {
var pattern = param.pattern(); var pattern = param.pattern();
if (pattern instanceof TargetTypePattern tp) if (pattern instanceof TargetTypePattern tp)
@@ -1581,9 +1598,31 @@ public class Codegen {
} }
} }
} }
private void generateMethod(TargetMethod method) { private void generateMethod(TargetMethod method) {
generateMethod(method, null);
}
private void generateMainMethod() {
var mv = cw.visitMethod(ACC_PUBLIC | ACC_STATIC, "main", "([Ljava/lang/String;)V", null, null);
mv.visitCode();
mv.visitVarInsn(ALOAD, 0);
mv.visitMethodInsn(INVOKESTATIC, "java/util/List", "of", "([Ljava/lang/Object;)Ljava/util/List;", true);
mv.visitMethodInsn(INVOKESTATIC, className, "main", "(Ljava/util/List;)V", false);
mv.visitInsn(RETURN);
mv.visitMaxs(0, 0);
mv.visitEnd();
}
private void generateMethod(TargetMethod method, State parent) {
var access = method.access(); var access = method.access();
var params = method.signature().parameters();
if (method.name().equals("main") && method.isStatic() && params.size() == 1 &&
params.getFirst().pattern().type().equals(new TargetRefType("java.util.List", List.of(new TargetRefType("java.lang.String"))))) {
generateMainMethod();
}
if (method.block() == null) if (method.block() == null)
access |= ACC_ABSTRACT; access |= ACC_ABSTRACT;
if (clazz instanceof TargetInterface) if (clazz instanceof TargetInterface)
@@ -1597,7 +1636,10 @@ public class Codegen {
if (method.block() != null) { if (method.block() != null) {
mv.visitCode(); mv.visitCode();
var state = new State(method.signature().returnType(), mv, method.isStatic() ? 0 : 1); var state = new State(method.signature().returnType(), mv, method.isStatic() ? 0 : 1, method.isStatic());
if (parent != null) {
state.scope.parent = parent.scope;
}
var offset = 1; var offset = 1;
for (var param : method.signature().parameters()) { for (var param : method.signature().parameters()) {
state.createVariable(param.pattern().name(), param.pattern().type()); state.createVariable(param.pattern().name(), param.pattern().type());
@@ -1607,6 +1649,8 @@ public class Codegen {
bindLocalVariables(state, cp, offset); bindLocalVariables(state, cp, offset);
offset++; offset++;
} }
//if (parent != null) System.out.println("parent: " + parent.scope.locals.keySet());
//System.out.println(state.scope.locals.keySet());
generate(state, method.block()); generate(state, method.block());
if (method.signature().returnType() == null) if (method.signature().returnType() == null)
mv.visitInsn(RETURN); mv.visitInsn(RETURN);
@@ -1713,7 +1757,7 @@ public class Codegen {
// Generate wrapper method // Generate wrapper method
var mv = cw2.visitMethod(ACC_PUBLIC, toMethod.name, toDescriptor, null, null); var mv = cw2.visitMethod(ACC_PUBLIC, toMethod.name, toDescriptor, null, null);
var state = new State(null, mv, 0); var state = new State(null, mv, 0, false);
mv.visitVarInsn(ALOAD, 0); mv.visitVarInsn(ALOAD, 0);
mv.visitFieldInsn(GETFIELD, className, "wrapped", pair.from.toDescriptor()); mv.visitFieldInsn(GETFIELD, className, "wrapped", pair.from.toDescriptor());
@@ -1745,7 +1789,7 @@ public class Codegen {
converter.classLoader.findClass(className); converter.classLoader.findClass(className);
} catch (ClassNotFoundException e) { } catch (ClassNotFoundException e) {
try { try {
converter.classLoader.loadClass(bytes); converter.classLoader.loadClass(className, bytes);
} catch (LinkageError ignored) {} } catch (LinkageError ignored) {}
} }
} }

View File

@@ -39,6 +39,10 @@ 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);

View File

@@ -1,5 +1,6 @@
package de.dhbwstuttgart.core; package de.dhbwstuttgart.core;
import de.dhbwstuttgart.server.SocketClient;
import de.dhbwstuttgart.util.Logger; import de.dhbwstuttgart.util.Logger;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
@@ -7,8 +8,12 @@ import java.util.*;
public class ConsoleInterface { public class ConsoleInterface {
/**
* Leave the argument configurations here for the rest of the code to read
*/
public static Logger.LogLevel logLevel = Logger.LogLevel.ERROR; public static Logger.LogLevel logLevel = Logger.LogLevel.ERROR;
public static boolean writeLogFiles = false; public static boolean writeLogFiles = false;
public static Optional<String> unifyServerUrl = Optional.empty();
public static void main(String[] args) throws IOException, ClassNotFoundException { public static void main(String[] args) throws IOException, ClassNotFoundException {
List<File> input = new ArrayList<>(); List<File> input = new ArrayList<>();
@@ -16,7 +21,6 @@ public class ConsoleInterface {
String outputPath = null; String outputPath = null;
Iterator<String> it = Arrays.asList(args).iterator(); Iterator<String> it = Arrays.asList(args).iterator();
Optional<Integer> serverPort = Optional.empty(); Optional<Integer> serverPort = Optional.empty();
Optional<String> unifyServer = Optional.empty();
if (args.length == 0) { if (args.length == 0) {
System.out.println("No input files given. Get help with --help"); System.out.println("No input files given. Get help with --help");
@@ -45,7 +49,7 @@ public class ConsoleInterface {
} else if (arg.equals("--server-mode")) { } else if (arg.equals("--server-mode")) {
serverPort = Optional.of(Integer.parseInt(it.next())); serverPort = Optional.of(Integer.parseInt(it.next()));
} else if (arg.equals("--unify-server")) { } else if (arg.equals("--unify-server")) {
unifyServer = Optional.of(it.next()); unifyServerUrl = Optional.of(it.next());
} else if (arg.equals("--write-logs")) { } else if (arg.equals("--write-logs")) {
ConsoleInterface.writeLogFiles = true; ConsoleInterface.writeLogFiles = true;
} else if (arg.startsWith("-v")) { } else if (arg.startsWith("-v")) {
@@ -61,15 +65,15 @@ public class ConsoleInterface {
} }
if (serverPort.isPresent()) { if (serverPort.isPresent()) {
if (unifyServer.isPresent()) throw new RuntimeException("Cannot use unifyServer when in server mode!"); if (unifyServerUrl.isPresent()) throw new RuntimeException("Cannot use unifyServer when in server mode!");
JavaTXServer server = new JavaTXServer(serverPort.get()); JavaTXServer server = new JavaTXServer(serverPort.get());
server.listen(); server.listen();
} }
else { else {
JavaTXCompiler compiler = new JavaTXCompiler(input, classpath, outputPath != null ? new File(outputPath) : null, unifyServer); JavaTXCompiler compiler = new JavaTXCompiler(input, classpath, outputPath != null ? new File(outputPath) : null);
//compiler.typeInference(); //compiler.typeInference();
compiler.generateBytecode(); compiler.generateBytecode();
SocketClient.closeIfOpen();
} }
} }

View File

@@ -13,6 +13,10 @@ 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;
@@ -81,29 +85,22 @@ public class JavaTXCompiler {
public final List<File> classPath; public final List<File> classPath;
private final File outputPath; private final File outputPath;
private final Optional<String> unifyServer;
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(Arrays.asList(sourceFile), List.of(), new File("."), Optional.empty()); this(Collections.singletonList(sourceFile), List.of(), new File("."));
} }
public JavaTXCompiler(List<File> sourceFiles) throws IOException, ClassNotFoundException { public JavaTXCompiler(List<File> sourceFiles) throws IOException, ClassNotFoundException {
this(sourceFiles, List.of(), new File("."), Optional.empty()); this(sourceFiles, List.of(), new File("."));
} }
public JavaTXCompiler(List<File> sources, List<File> contextPath, File outputPath) 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.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
@@ -404,10 +401,14 @@ public class JavaTXCompiler {
logger.debug("\nUnify_distributeInnerVars: " + unifyCons.toString()); logger.debug("\nUnify_distributeInnerVars: " + unifyCons.toString());
// Set<Set<UnifyPair>> results = new HashSet<>(); Nach vorne gezogen // Set<Set<UnifyPair>> results = new HashSet<>(); Nach vorne gezogen
logger.debug("FC:\\" + finiteClosure.toString() + "\n"); logger.debug("FC:\\" + finiteClosure.toString() + "\n");
logger.debug(ASTTypePrinter.print(sf));
logger.info(ASTTypePrinter.print(sf)); logger.info(ASTTypePrinter.print(sf));
// logFile.flush(); // logFile.flush();
logger.info("Unify nach Oder-Constraints-Anpassung:" + unifyCons.toString()); 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> varianceTPHold;
Set<PlaceholderType> varianceTPH = new HashSet<>(); Set<PlaceholderType> varianceTPH = new HashSet<>();
varianceTPH = varianceInheritanceConstraintSet(unifyCons); varianceTPH = varianceInheritanceConstraintSet(unifyCons);
@@ -424,12 +425,14 @@ public class JavaTXCompiler {
/* /*
* Set<Set<UnifyPair>> ret = new HashSet<>(); for (Constraint<UnifyPair> y : x) { ret.add(new HashSet<>(y)); } return ret; }).collect(Collectors.toCollection(ArrayList::new)) * 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()) {
if (unifyServer.isPresent()) {
UnifyResultModel urm = new UnifyResultModel(cons, finiteClosure); UnifyResultModel urm = new UnifyResultModel(cons, finiteClosure);
UnifyContext context = new UnifyContext(logger, true, urm, usedTasks, placeholderRegistry); UnifyContext context = new UnifyContext(logger, true, urm, usedTasks, placeholderRegistry);
SocketClient socketClient = new SocketClient(unifyServer.get()); SocketFuture<UnifyResultPacket> future = SocketClient.execute(
return socketClient.execute(finiteClosure, cons, unifyCons, context); UnifyRequestPacket.create(finiteClosure, cons, unifyCons, context.placeholderRegistry())
);
SocketClient.execute(SetAutoclosePacket.create());
return future.get().getResultSet(context);
} }
else if (resultmodel) { else if (resultmodel) {
/* UnifyResultModel Anfang */ /* UnifyResultModel Anfang */
@@ -438,10 +441,14 @@ public class JavaTXCompiler {
urm.addUnifyResultListener(li); urm.addUnifyResultListener(li);
UnifyContext context = new UnifyContext(logger, true, urm, usedTasks, placeholderRegistry); UnifyContext context = new UnifyContext(logger, true, urm, usedTasks, placeholderRegistry);
TypeUnify.unifyParallel(unifyCons.getUndConstraints(), oderConstraints, finiteClosure, context); TypeUnify.unifyParallel(unifyCons.getUndConstraints(), oderConstraints, finiteClosure, context);
logger.info("RESULT Final: " + li.getResults()); var finalResults = li.getResults().stream().sorted().toList();
logger.info("Constraints for Generated Generics: " + " ???"); int i = 0;
logFile.write("RES_FINAL: " + li.getResults().toString() + "\n"); logger.info("RESULT Final: ");
// logFile.flush(); for (var result : finalResults){
logger.info("Result: " + i++);
logger.info(result.getSortedResults());
}
logger.info("RES_FINAL: " + li.getResults().toString() + "\n");
return li.getResults(); return li.getResults();
} }
/* UnifyResultModel End */ /* UnifyResultModel End */
@@ -452,8 +459,6 @@ public class JavaTXCompiler {
UnifyContext context = new UnifyContext(logger, false, new UnifyResultModel(cons, finiteClosure), usedTasks, placeholderRegistry); UnifyContext context = new UnifyContext(logger, 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);
logger.info("RESULT: " + result); logger.info("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 -> {
@@ -648,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();
converter.auxiliaries.forEach((name, source) -> {
generatedClasses.put(new JavaClassName(name), source);
});
return generatedClasses; return generatedClasses;
} }
@@ -669,7 +674,7 @@ public class JavaTXCompiler {
output = new FileOutputStream(outputFile); output = new FileOutputStream(outputFile);
output.write(bytecode); output.write(bytecode);
output.close(); output.close();
defaultLogger.info(name + ".class file generated"); defaultLogger.success(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

@@ -1,13 +0,0 @@
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

@@ -6,18 +6,22 @@ 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._defineClass(null, code, 0, code.length); return this.loadClass(null, code);
} }
default Class loadClass(Path path) throws IOException { default Class<?> loadClass(String name, byte[] code) {
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

@@ -1100,9 +1100,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()));// ret-Type funNParams.add(TypePlaceholder.fresh(expression.getStart(), -1, false));// 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()))); funNParams.add(TypePlaceholder.fresh(expression.getStart(), 1, false)));
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

@@ -7,7 +7,7 @@ import java.util.*;
/** /**
* Speichert die Klassen f<>r einen bestimmten Projektscope * Speichert die Klassen f<>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,6 +22,10 @@ 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);
} }

View File

@@ -0,0 +1,41 @@
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,6 +1,8 @@
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;
@@ -17,6 +19,7 @@ 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;
@@ -32,39 +35,31 @@ public class SocketClient extends WebSocketClient {
public static Logger logger = new Logger("SocketClient"); 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); * The singleton object
// 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 static SocketClient socketClient = null;
private UnifyResultPacket unifyResultPacket;
public SocketClient(String url) { /**
super(URI.create(url), Map.of( * 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 "packetProtocolVersion", SocketServer.packetProtocolVersion
)); )
// make sure, the url is in a valid format );
// 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
@@ -73,62 +68,108 @@ 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);
} }
// send the unify task request
UnifyRequestPacket packet = new UnifyRequestPacket(finiteClosure, constraintSet, unifyConstraintSet, context.placeholderRegistry());
String json = PacketContainer.serialize(packet);
this.send(json);
// 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) { } catch (InterruptedException exception) {
System.err.println("Server connection interrupted: " + exception); throw new RuntimeException(exception);
this.notifyAll();
throw new RuntimeException("Aborted server connection", exception);
} }
catch (Exception exception) {
// add a shutdown hook to close the connection when the process ends or is stopped by a SIGINT signal
Runtime.getRuntime().addShutdownHook(new Thread(this::close));
}
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);
client.send(json);
} catch (Exception exception) {
logger.exception(exception);
throw new RuntimeException("Exception occurred in server connection: ", exception); throw new RuntimeException("Exception occurred in server connection: ", exception);
} }
// detect error cases, in which no error was thrown, but also no result was sent back from the server return future;
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
*
* @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 * 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());
try {
serverToClientPacket.onHandle(this.getConnection(), this);
}
catch (Exception exception) {
this.closeLatch.countDown();
this.close(); this.close();
throw exception;
}
return; return;
} }
System.err.println("Received package of invalid type + " + packet.getClass().getName()); serverToClientPacket.onHandle(this.getConnection(), this);
this.close();
} }
public void setUnifyResultSets(UnifyResultPacket unifyResultPacket) { /**
this.unifyResultPacket = unifyResultPacket; * Complete a registered future, so it can be handled by whoever executed the creator task
*
* @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.info("Connected to server with status " + handshakedata.getHttpStatus()); logger.success("Connected to server with status " + handshakedata.getHttpStatus());
} }
@Override @Override
@@ -146,16 +187,16 @@ public class SocketClient extends WebSocketClient {
(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.error("Error: " + e.getMessage()); logger.exception(e);
e.printStackTrace(); throw new RuntimeException(e);
} }
public void waitUntilClosed() throws InterruptedException {
closeLatch.await();
}
} }

View File

@@ -0,0 +1,48 @@
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

@@ -1,7 +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.JavaTXCompiler;
import de.dhbwstuttgart.server.packet.ErrorPacket; import de.dhbwstuttgart.server.packet.ErrorPacket;
import de.dhbwstuttgart.server.packet.IClientToServerPacket; import de.dhbwstuttgart.server.packet.IClientToServerPacket;
import de.dhbwstuttgart.server.packet.IPacket; import de.dhbwstuttgart.server.packet.IPacket;
@@ -9,69 +8,98 @@ import de.dhbwstuttgart.server.packet.MessagePacket;
import de.dhbwstuttgart.server.packet.PacketContainer; import de.dhbwstuttgart.server.packet.PacketContainer;
import de.dhbwstuttgart.util.Logger; import de.dhbwstuttgart.util.Logger;
import java.net.InetSocketAddress; import java.net.InetSocketAddress;
import java.util.Objects; import java.util.Collections;
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;
public class SocketServer extends WebSocketServer { public class SocketServer extends WebSocketServer {
public static Logger logger = new Logger("SocketServer"); 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 server version and client version do not match. * This will prevent errors when the 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
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)) {
try { this.sendError(webSocket,
ErrorPacket errorPacket = ErrorPacket.create( "Mismatch in packet protocol version! Client (you): \"" + ppv + "\" and Server (me): \"" + packetProtocolVersion + "\"",
"Mismatch in packet protocol version! Client (you): " + ppv + " and Server (me): " + packetProtocolVersion,
true 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);
SocketData socketData = new SocketData(UUID.randomUUID().toString());
webSocket.setAttachment(socketData);
logger.info("New connection: " + socketData.id + " (with ppv " + ppv + ")"); logger.info("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
try (ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor()) { final int secondsUntilTimeout = 10;
Runnable task = () -> { timeoutExecutor.schedule(() -> {
if (webSocket.<SocketData>getAttachment().unhandledTasks.get() == 0 || !webSocket.isOpen()) { if (webSocket.<SocketData>getAttachment().totalTasks.get() > 0 || !webSocket.isOpen()) {
return; return;
} }
sendMessage(webSocket, "No task received after 10 seconds. Closing connection..."); sendMessage(webSocket, "No task received after " + secondsUntilTimeout + " seconds. Closing connection...");
webSocket.close(); webSocket.close();
}; },
executor.schedule(task, 10, TimeUnit.SECONDS); secondsUntilTimeout,
executor.shutdown(); TimeUnit.SECONDS
} );
// and finally, when your program wants to exit // and finally, when your program wants to exit
} catch (Exception e) { } catch (Exception e) {
@@ -101,20 +129,22 @@ public class SocketServer extends WebSocketServer {
this.onPacketReceived(webSocket, reconstructedPacket); this.onPacketReceived(webSocket, reconstructedPacket);
} catch (JsonProcessingException e) { } catch (JsonProcessingException e) {
logger.exception(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) {
logger.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.info("Websocket server started on port " + this.getPort()); logger.success("Websocket server started on port " + this.getPort());
} }
/** /**
@@ -122,8 +152,7 @@ public class SocketServer extends WebSocketServer {
*/ */
public void sendMessage(WebSocket webSocket, String text) { public void sendMessage(WebSocket webSocket, String text) {
try { try {
MessagePacket message = new MessagePacket(); MessagePacket message = MessagePacket.create(text);
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);
@@ -134,14 +163,13 @@ public class SocketServer extends WebSocketServer {
/** /**
* 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) { public void sendError(WebSocket webSocket, String text, boolean isFatal) {
try { try {
ErrorPacket error = new ErrorPacket(); ErrorPacket error = ErrorPacket.create(text, isFatal);
error.error = text;
webSocket.send(PacketContainer.serialize(error)); webSocket.send(PacketContainer.serialize(error));
} catch (Exception e) { } catch (Exception e) {
logger.exception(e); logger.exception(e);
log("Failed to send error: " + text, webSocket); log(webSocket, "Failed to send error: " + text);
} }
} }
@@ -151,16 +179,15 @@ public class SocketServer extends WebSocketServer {
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 amount of tasks per connection // limit the number of tasks per connection
final int maxTasks = 100; if (socketData.totalTasks.get() >= maxTasksPerSession) {
if (socketData.totalTasks.get() >= maxTasks) { sendError(webSocket, "Exceeded the maximum amount of " + maxTasksPerSession + " tasks per session", true);
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;
} }
@@ -169,22 +196,24 @@ 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);
// if the websocket has 0 unhandled Tasks, close the connection
int remainingUnhandledTasks = socketData.unhandledTasks.decrementAndGet(); int remainingUnhandledTasks = socketData.unhandledTasks.decrementAndGet();
if (socketData.closeIfNoTasksLeft) {
// if the websocket has 0 unhandled Tasks, close the connection
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(String msg, WebSocket webSocket) { public void log(WebSocket webSocket, String msg) {
SocketData socketData = webSocket == null ? new SocketData("???") : webSocket.getAttachment(); String socketId = (webSocket == null) ? "???" : webSocket.<SocketData>getAttachment().id;
logger.info("["+socketData.id+"] " + msg); logger.info("[" + socketId + "] " + msg);
} }
/** /**
@@ -196,10 +225,11 @@ 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(String id) { public SocketData(WebSocket webSocket) {
this.id = id; this.id = UUID.randomUUID().toString();
webSocket.setAttachment(this);
} }
} }
} }

View File

@@ -2,6 +2,7 @@ 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;
@@ -10,7 +11,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, IServerToClientPacket { public class DebugPacket implements IClientToServerPacket.Void, IServerToClientPacket {
public SerialUUID a1; public SerialUUID a1;
public SerialUUID a2; public SerialUUID a2;
@@ -22,9 +23,13 @@ public class DebugPacket implements IClientToServerPacket, IServerToClientPacket
public SerialValue<?> d2; public SerialValue<?> d2;
@JsonIgnore @JsonIgnore
public void onHandle(WebSocket webSocket, SocketClient socketServer) {} public void onHandle(WebSocket webSocket, SocketClient socketClient) {}
@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,16 +2,17 @@ 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 IClientToServerPacket, IServerToClientPacket { public class ErrorPacket implements IServerToClientPacket {
/** /**
* The error endpoint for messages from the server, that should be logged out outputted * The error endpoint for messages from the server that should be logged out as errors and possibly abort the process
*/ */
public String error; public String error;
public boolean isFatal; public boolean isFatal;
@@ -27,15 +28,9 @@ public class ErrorPacket implements IClientToServerPacket, IServerToClientPacket
@JsonIgnore @JsonIgnore
public void onHandle(WebSocket webSocket, SocketClient socketClient) { public void onHandle(WebSocket webSocket, SocketClient socketClient) {
System.err.println("[socket] " + "ErrorPacket: " + this.error); SocketClient.logger.exception(new RuntimeException(this.error));
if (this.isFatal) { if (this.isFatal) {
throw new RuntimeException("Received fatal error from server: " + this.error); socketClient.close(1, "Received fatal error from server");
} }
} }
@JsonIgnore
public void onHandle(WebSocket webSocket, SocketServer socketServer) {
socketServer.log("ErrorPacket: " + this.error, webSocket);
}
} }

View File

@@ -1,12 +1,26 @@
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,13 +2,14 @@ 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, IServerToClientPacket { public class InvalidPacket implements IClientToServerPacket.Void, IServerToClientPacket {
/** /**
* If available, the error that caused this package to appear * If available, the error that caused this package to appear
@@ -18,12 +19,17 @@ public class InvalidPacket implements IClientToServerPacket, IServerToClientPack
@JsonIgnore @JsonIgnore
public void onHandle(WebSocket webSocket, SocketClient socketClient) { public void onHandle(WebSocket webSocket, SocketClient socketClient) {
System.err.println("[socket] " + "InvalidPacket: " + this.error); SocketClient.logger.error("InvalidPacket: " + this.error);
} }
@JsonIgnore @JsonIgnore
public void onHandle(WebSocket webSocket, SocketServer socketServer) { public void onHandle(WebSocket webSocket, SocketServer socketServer) {
socketServer.log("InvalidPacket: " + this.error, webSocket); socketServer.log(webSocket, "InvalidPacket: " + this.error);
}
@JsonIgnore
public SocketFuture<IServerToClientPacket> getFuture() {
return SocketFuture.completedFuture();
} }
} }

View File

@@ -2,16 +2,17 @@ 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, IServerToClientPacket { public class MessagePacket implements IClientToServerPacket.Void, 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;
@@ -24,13 +25,16 @@ public class MessagePacket implements IClientToServerPacket, IServerToClientPack
@JsonIgnore @JsonIgnore
public void onHandle(WebSocket webSocket, SocketClient socketClient) { public void onHandle(WebSocket webSocket, SocketClient socketClient) {
System.err.println("[socket] " + this.message); SocketClient.logger.info("SocketMessage: " + this.message);
} }
@JsonIgnore @JsonIgnore
public void onHandle(WebSocket webSocket, SocketServer socketServer) { public void onHandle(WebSocket webSocket, SocketServer socketServer) {
socketServer.log(this.message, webSocket); socketServer.log(webSocket, this.message);
} }
@JsonIgnore
public SocketFuture<IServerToClientPacket> getFuture() {
return SocketFuture.completedFuture();
}
} }

View File

@@ -25,13 +25,14 @@ 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);
@@ -47,7 +48,11 @@ 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);
} }
@@ -76,6 +81,8 @@ 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");

View File

@@ -0,0 +1,32 @@
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,6 +1,9 @@
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;
@@ -20,18 +23,16 @@ 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 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 { public class UnifyRequestPacket implements IClientToServerPacket<UnifyResultPacket> {
public SerialMap finiteClosure; public SerialMap finiteClosure;
public SerialMap constraintSet; public SerialMap constraintSet;
@@ -39,30 +40,33 @@ public class UnifyRequestPacket implements IClientToServerPacket {
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 UnifyRequestPacket() {} public static UnifyRequestPacket create(
public UnifyRequestPacket(
FiniteClosure finiteClosure, FiniteClosure finiteClosure,
ConstraintSet<Pair> constraintSet, ConstraintSet<Pair> constraintSet,
ConstraintSet<UnifyPair> unifyConstraintSet, ConstraintSet<UnifyPair> unifyConstraintSet,
PlaceholderRegistry placeholderRegistry PlaceholderRegistry placeholderRegistry
) { ) {
// store contraint and finite closure UnifyRequestPacket packet = new UnifyRequestPacket();
this.finiteClosure = finiteClosure.toSerial(keyStorage); // store constraint and finite closure
this.constraintSet = constraintSet.toSerial(keyStorage); packet.finiteClosure = finiteClosure.toSerial(packet.keyStorage);
this.unifyConstraintSet = unifyConstraintSet.toSerial(keyStorage); packet.constraintSet = constraintSet.toSerial(packet.keyStorage);
packet.unifyConstraintSet = unifyConstraintSet.toSerial(packet.keyStorage);
// store placeholder registry // store placeholder registry
var serialRegistry = placeholderRegistry.toSerial(keyStorage); var serialRegistry = placeholderRegistry.toSerial(packet.keyStorage);
this.placeholders = serialRegistry.getValue("ph"); packet.placeholders = serialRegistry.getValue("ph");
this.factoryplaceholders = serialRegistry.getList("factoryPh").assertListOfMaps(); packet.factoryplaceholders = serialRegistry.getList("factoryPh").assertListOfMaps();
// store referenced objects separately // store referenced objects separately
this.serialKeyStorage = keyStorage.toSerial(keyStorage); packet.serialKeyStorage = packet.keyStorage.toSerial(packet.keyStorage);
packet.logLevel = ConsoleInterface.logLevel.getValue();
return packet;
} }
@@ -95,15 +99,22 @@ public class UnifyRequestPacket implements IClientToServerPacket {
@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.logger.info("Client " + webSocket.<SocketServer.SocketData>getAttachment().id + " requested a unification. Starting now..."); socketServer.log(webSocket, "Client 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);
var unifyContext = new UnifyContext(Logger.NULL_LOGGER, true, Logger logger = new ServerTaskLogger(
new UnifyResultModel(new ConstraintSet<>(), new FiniteClosure(new HashSet<>(), Logger.NULL_LOGGER, placeholderRegistry)), webSocket,
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
); );
@@ -130,17 +141,24 @@ public class UnifyRequestPacket implements IClientToServerPacket {
var resultSets = resultListener.getResults(); var resultSets = resultListener.getResults();
SocketServer.logger.info("Finished unification for client " + webSocket.<SocketServer.SocketData>getAttachment().id); socketServer.log(webSocket, "Finished unification");
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); UnifyResultPacket resultPacket = UnifyResultPacket.create(resultSets, futureId);
webSocket.send(PacketContainer.serialize(resultPacket)); webSocket.send(PacketContainer.serialize(resultPacket));
} }
} catch (Exception e) { } catch (Exception e) {
SocketServer.logger.exception(e); SocketServer.logger.exception(e);
socketServer.log(e.getMessage(), webSocket); socketServer.log(webSocket, e.getMessage());
} }
} }
@JsonIgnore
public SocketFuture<UnifyResultPacket> getFuture() {
var future = new SocketFuture<>(List.of(UnifyResultPacket.class));
futureId = future.futureId;
return future;
}
} }

View File

@@ -18,12 +18,14 @@ 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) { public static UnifyResultPacket create(List<ResultSet> resultSets, String futureId) {
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;
} }
@@ -35,8 +37,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("[socket] Received unify result"); SocketClient.logger.info("Received unify result");
socketClient.setUnifyResultSets(this); socketClient.completeResponseFuture(futureId, 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 javax.annotation.Nullable; import org.jspecify.annotations.Nullable;
public class SerialMap extends HashMap<String, ISerialNode> implements ISerialNode { public class SerialMap extends HashMap<String, ISerialNode> implements ISerialNode {

View File

@@ -2,7 +2,6 @@ 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,6 +11,8 @@ 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.Target;
import de.dhbwstuttgart.target.tree.*; import de.dhbwstuttgart.target.tree.*;
import de.dhbwstuttgart.target.tree.expression.*; import de.dhbwstuttgart.target.tree.expression.*;
@@ -67,11 +68,11 @@ public class ASTToTargetAST {
public IByteArrayClassLoader classLoader; public IByteArrayClassLoader classLoader;
protected SourceFile sourceFile; protected SourceFile sourceFile;
public ASTToTargetAST(List<ResultSet> resultSets) { public ASTToTargetAST(List<ResultSet> resultSets, IByteArrayClassLoader classLoader) {
this(null, resultSets); this(null, resultSets, classLoader);
} }
public ASTToTargetAST(JavaTXCompiler compiler, List<ResultSet> resultSets) { public ASTToTargetAST(JavaTXCompiler compiler, List<ResultSet> resultSets, IByteArrayClassLoader classLoader) {
this(compiler, resultSets, null, new ByteArrayClassLoader()); this(compiler, resultSets, null, classLoader);
} }
public ASTToTargetAST(JavaTXCompiler compiler, List<ResultSet> resultSets, SourceFile sourceFile, IByteArrayClassLoader classLoader) { public ASTToTargetAST(JavaTXCompiler compiler, List<ResultSet> resultSets, SourceFile sourceFile, IByteArrayClassLoader classLoader) {
@@ -782,7 +783,15 @@ 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;
@@ -819,14 +828,6 @@ public class ASTToTargetAST {
.toList(); .toList();
var code = FunNGenerator.generateSpecializedBytecode(gep, superInterfaces); var code = FunNGenerator.generateSpecializedBytecode(gep, superInterfaces);
try {
classLoader.findClass(entry.getKey());
} catch (ClassNotFoundException e) {
try {
classLoader.loadClass(code);
} catch (LinkageError ignored) {}
}
auxiliaries.put(entry.getKey(), code); auxiliaries.put(entry.getKey(), code);
} }
} }
@@ -857,7 +858,7 @@ public class ASTToTargetAST {
classLoader.findClass(superClassName); classLoader.findClass(superClassName);
} catch (ClassNotFoundException e) { } catch (ClassNotFoundException e) {
try { try {
classLoader.loadClass(code); classLoader.loadClass(superClassName, code);
} catch (LinkageError ignored) {} } catch (LinkageError ignored) {}
} }
auxiliaries.put(superClassName, code); auxiliaries.put(superClassName, code);

View File

@@ -15,6 +15,7 @@ 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;
@@ -33,19 +34,17 @@ public class StatementToTargetExpression implements ASTVisitor {
throw new NotImplementedException(); throw new NotImplementedException();
} }
@Override private class LambdaCaptureFinder extends TracingStatementVisitor {
public void visit(LambdaExpression 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<>();
lambdaExpression.methodBody.accept(new TracingStatementVisitor() {
// TODO The same mechanism is implemented in Codegen, maybe use it from there? // TODO The same mechanism is implemented in Codegen, maybe use it from there?
final Stack<Set<String>> localVariables = new Stack<>(); 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<>()); localVariables.push(new HashSet<>());
this.parameters = parameters;
this.captures = captures;
} }
boolean hasLocalVar(String name) { boolean hasLocalVar(String name) {
@@ -79,8 +78,27 @@ public class StatementToTargetExpression implements ASTVisitor {
@Override @Override
public void visit(LambdaExpression lambda) { public void visit(LambdaExpression lambda) {
} // Don't look at lambda expressions 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
public void visit(LambdaExpression lambdaExpression) {
var parameters = createParameters(lambdaExpression);
List<MethodParameter> captures = new ArrayList<>();
var visitor = new LambdaCaptureFinder(parameters, captures);
lambdaExpression.methodBody.accept(visitor);
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());
@@ -121,7 +139,10 @@ public class StatementToTargetExpression implements ASTVisitor {
@Override @Override
public void visit(BoolExpression bool) { public void visit(BoolExpression bool) {
Target.logger.info("BoolExpression"); result = switch(bool.operation) {
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

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,21 +9,16 @@ 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 ISerializableData { public class Constraint<A extends IConstraintElement> extends HashSet<A> implements Comparable<Constraint<A>>, 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 * wird verwendet um bei der Codegenerierung die richtige Methoden - Signatur
@@ -37,27 +32,31 @@ public class Constraint<A extends IConstraintElement> extends HashSet<A> impleme
super(); super();
} }
public Constraint(Boolean isInherited, Boolean isImplemented) { public Constraint(int initialCapacity) {
super(initialCapacity);
}
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) { public Constraint(boolean isInherited, boolean isImplemented, Constraint<A> extendConstraint, Set<A> methodSignatureConstraint) {
this.isInherited = isInherited; this.isInherited = isInherited;
this.isImplemented = isImplemented; this.isImplemented = isImplemented;
this.extendConstraint = extendConstraint; this.extendConstraint = extendConstraint;
this.methodSignatureConstraint = methodSignatureConstraint; this.methodSignatureConstraint = methodSignatureConstraint;
} }
public void setIsInherited(Boolean isInherited) { public void setIsInherited(boolean isInherited) {
this.isInherited = isInherited; this.isInherited = isInherited;
} }
public Boolean isInherited() { public boolean isInherited() {
return isInherited; return isInherited;
} }
public Boolean isImplemented() { public boolean isImplemented() {
return isImplemented; return isImplemented;
} }
@@ -77,6 +76,14 @@ public class Constraint<A extends IConstraintElement> extends HashSet<A> impleme
methodSignatureConstraint = 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 String toString() {
return super.toString() + "\nisInherited = " + isInherited return super.toString() + "\nisInherited = " + isInherited
+ " isOveridden = " + isImplemented + " isOveridden = " + isImplemented
@@ -89,6 +96,12 @@ public class Constraint<A extends IConstraintElement> extends HashSet<A> impleme
return super.toString(); return super.toString();
} }
@Override
public int compareTo(Constraint<A> o) {
return this.toString().compareTo(o.toString());
}
private String serialUUID = null; private String serialUUID = null;
@Override @Override
@@ -155,5 +168,4 @@ 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 ISerializableData { implements Comparable<ResultPair<A,B>>, ISerializableData {
private final A left; private final A left;
private final B right; private final B right;
@@ -65,6 +65,16 @@ implements ISerializableData {
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,11 +5,13 @@ 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 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;
@@ -22,14 +24,14 @@ import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
public class ResultSet implements ISerializableData { public class ResultSet implements Comparable<ResultSet>, 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 = new HashSet<>(); this.genIns = TypeUnifyTaskHelper.getPresizedHashSet(results.size());
results.forEach(x -> { results.forEach(x -> {
if (x instanceof PairTPHsmallerTPH) { if (x instanceof PairTPHsmallerTPH) {
this.genIns.add(x); this.genIns.add(x);
@@ -37,6 +39,10 @@ public class ResultSet implements ISerializableData {
}); });
} }
public List<ResultPair> getSortedResults() {
return results.stream().sorted().toList();
}
public boolean contains(ResultPair toCheck) { public boolean contains(ResultPair toCheck) {
return this.results.contains(toCheck); return this.results.contains(toCheck);
} }
@@ -91,6 +97,21 @@ public class ResultSet implements ISerializableData {
return results.hashCode(); return results.hashCode();
} }
@Override
public int compareTo(ResultSet o) {
List<ResultPair> thisSorted = this.getSortedResults();
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
public SerialMap toSerial(KeyStorage keyStorage) { public SerialMap toSerial(KeyStorage keyStorage) {
SerialMap serialized = new SerialMap();; SerialMap serialized = new SerialMap();;

View File

@@ -1,6 +1,7 @@
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;
@@ -9,15 +10,19 @@ 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 {
@@ -33,7 +38,7 @@ public class TYPE {
public ConstraintSet getConstraints() { public ConstraintSet getConstraints() {
ConstraintSet ret = new ConstraintSet(); ConstraintSet ret = new ConstraintSet();
for (ClassOrInterface cl : sf.KlassenVektor) { for (ClassOrInterface cl : sf.KlassenVektor) {
var allClasses = new HashSet<ClassOrInterface>(); Set<ClassOrInterface> allClasses = TypeUnifyTaskHelper.getPresizedHashSet(allAvailableClasses.size() + sf.availableClasses.size());
allClasses.addAll(allAvailableClasses); allClasses.addAll(allAvailableClasses);
allClasses.addAll(sf.availableClasses); allClasses.addAll(sf.availableClasses);
ret.addAll(getConstraintsClass(cl, new TypeInferenceInformation(allClasses))); ret.addAll(getConstraintsClass(cl, new TypeInferenceInformation(allClasses)));
@@ -87,12 +92,25 @@ 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,6 +2,7 @@
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;
@@ -74,7 +75,7 @@ public class TYPEStmt implements StatementVisitor {
@Override @Override
public void visit(LambdaExpression lambdaExpression) { public void visit(LambdaExpression lambdaExpression) {
TypePlaceholder tphRetType = TypePlaceholder.fresh(new NullToken()); TypePlaceholder tphRetType = TypePlaceholder.fresh(new NullToken(), -1, false);
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);
@@ -117,17 +118,18 @@ 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);
Set<Constraint> oderConstraints = new HashSet<>(); List<FieldAssumption> fieldAssumptions = info.getFields(fieldVar.fieldVarName);
Set<Constraint> oderConstraints = TypeUnifyTaskHelper.getPresizedHashSet(fieldAssumptions.size());
for (FieldAssumption fieldAssumption : info.getFields(fieldVar.fieldVarName)) { for (FieldAssumption fieldAssumption : fieldAssumptions) {
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.size() == 0) if (oderConstraints.isEmpty())
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);
} }
@@ -142,7 +144,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(), Arrays.asList(new ExtendsWildcardType(forEachStmt.statement.getType(), new NullToken())), new NullToken()); var iterableType = new RefType(ASTFactory.createClass(java.lang.Iterable.class).getClassName(), List.of(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);
@@ -190,7 +192,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 : this.getMethods(methodCall.name, methodCall.arglist, info)) { for (MethodAssumption m : TYPEStmt.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);
@@ -200,7 +202,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.size() < 1) { if (methodConstraints.isEmpty()) {
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);
@@ -213,7 +215,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.size() < 1) { if (methodConstraints.isEmpty()) {
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);
@@ -283,8 +285,13 @@ 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 (info.getAvailableClasses().stream().map(x -> x.getClassName()).collect(Collectors.toCollection(HashSet::new)).contains(bytee.getName())) { if (classNames.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())));
@@ -292,7 +299,7 @@ public class TYPEStmt implements StatementVisitor {
numericAdditionOrStringConcatenation.add(numeric); numericAdditionOrStringConcatenation.add(numeric);
} }
// PL eingefuegt 2018-07-17 // PL eingefuegt 2018-07-17
if (info.getAvailableClasses().stream().map(x -> x.getClassName()).collect(Collectors.toCollection(HashSet::new)).contains(shortt.getName())) { if (classNames.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())));
@@ -300,7 +307,7 @@ public class TYPEStmt implements StatementVisitor {
numericAdditionOrStringConcatenation.add(numeric); numericAdditionOrStringConcatenation.add(numeric);
} }
// PL eingefuegt 2018-07-17 // PL eingefuegt 2018-07-17
if (info.getAvailableClasses().stream().map(x -> x.getClassName()).collect(Collectors.toCollection(HashSet::new)).contains(integer.getName())) { if (classNames.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())));
@@ -308,7 +315,7 @@ public class TYPEStmt implements StatementVisitor {
numericAdditionOrStringConcatenation.add(numeric); numericAdditionOrStringConcatenation.add(numeric);
} }
// PL eingefuegt 2018-07-17 // PL eingefuegt 2018-07-17
if (info.getAvailableClasses().stream().map(x -> x.getClassName()).collect(Collectors.toCollection(HashSet::new)).contains(longg.getName())) { if (classNames.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())));
@@ -316,7 +323,7 @@ public class TYPEStmt implements StatementVisitor {
numericAdditionOrStringConcatenation.add(numeric); numericAdditionOrStringConcatenation.add(numeric);
} }
// PL eingefuegt 2018-07-17 // PL eingefuegt 2018-07-17
if (info.getAvailableClasses().stream().map(x -> x.getClassName()).collect(Collectors.toCollection(HashSet::new)).contains(floatt.getName())) { if (classNames.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())));
@@ -324,7 +331,7 @@ public class TYPEStmt implements StatementVisitor {
numericAdditionOrStringConcatenation.add(numeric); numericAdditionOrStringConcatenation.add(numeric);
} }
// PL eingefuegt 2018-07-17 // PL eingefuegt 2018-07-17
if (info.getAvailableClasses().stream().map(x -> x.getClassName()).collect(Collectors.toCollection(HashSet::new)).contains(doublee.getName())) { if (classNames.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())));
@@ -339,7 +346,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 (info.getAvailableClasses().stream().map(x -> x.getClassName()).collect(Collectors.toCollection(HashSet::new)).contains(string.getName())) { if (classNames.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())));
@@ -347,7 +354,7 @@ public class TYPEStmt implements StatementVisitor {
numericAdditionOrStringConcatenation.add(stringConcat); numericAdditionOrStringConcatenation.add(stringConcat);
} }
} }
if (numericAdditionOrStringConcatenation.size() < 1) { if (numericAdditionOrStringConcatenation.isEmpty()) {
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);
@@ -636,6 +643,7 @@ 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 {
@@ -733,7 +741,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.get(foMethod.signature.size() - 1), assumption.getReturnType(), PairOperator.EQUALSDOT)); ret.add(new Pair(foMethod.signature.getLast(), assumption.getReturnType(), PairOperator.EQUALSDOT));
return ret; return ret;
} }
@@ -746,8 +754,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.get(funNParams.size() - 1); funNParams.getLast();
ret.add(new MethodAssumption(new FunNClass(funNParams), funNParams.get(funNParams.size() - 1), funNParams.subList(0, funNParams.size() - 1), new TypeScope() { ret.add(new MethodAssumption(new FunNClass(funNParams), funNParams.getLast(), 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();
@@ -883,13 +891,9 @@ public class TYPEStmt implements StatementVisitor {
child.getLabels().forEach(el -> { child.getLabels().forEach(el -> {
if (el.getType() instanceof RefType) { if (el.getType() instanceof RefType) {
var recType = el; if (el.getPattern() instanceof RecordPattern pattern) {
if (el.getPattern() instanceof RecordPattern) {
var pattern = (RecordPattern) recType.getPattern();
recursivelyAddRecordConstraints(pattern); recursivelyAddRecordConstraints(pattern);
} }
} }
}); });
@@ -905,7 +909,7 @@ 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.get(0).getConstructors(); var constructors = interestingClasses.getFirst().getConstructors();
int counter = 0; int counter = 0;

View File

@@ -0,0 +1,91 @@
package de.dhbwstuttgart.typeinference.unify;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.RecursiveTask;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* 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
* order for that to work, all cancellable child tasks must be added when they are created
*
* @param <T>
*/
public abstract class CancellableTask<T> extends RecursiveTask<T> {
private final AtomicBoolean executionCancelled = new AtomicBoolean(false);
private final List<CancellableTask<?>> childTasks = new LinkedList<>();
private CancellableTask<?> parentTask = null;
/**
* Set the execution for this task and all its (recursive) children to be canceled
*/
protected void cancelExecution() {
// is this branch already canceled? Then do nothing
if (this.executionCancelled.getAndSet(true)) return;
this.cancelChildExecution();
}
private 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) {
if (!reachedCheckpoint) {
reachedCheckpoint = childTask == checkpointTask;
}
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() {
if (this.parentTask != null) {
boolean thisWasCancelledBefore = this.executionCancelled.get();
this.parentTask.cancelChildExecution();
this.executionCancelled.set(thisWasCancelledBefore);
}
}
public void cancelYoungerSiblingTasks() {
if (this.parentTask != null) {
this.parentTask.cancelChildExecutionAfter(this);
}
}
public Boolean isExecutionCancelled() {
return executionCancelled.get();
}
public void addChildTask(CancellableTask<?> childTask) {
this.childTasks.add(childTask);
childTask.setParentTask(this);
if (this.executionCancelled.get()) {
childTask.executionCancelled.set(true);
}
}
private void setParentTask(CancellableTask<?> parentTask) {
this.parentTask = parentTask;
}
}

View File

@@ -95,7 +95,7 @@ public class MartelliMontanariUnify implements IUnify {
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 = termsList.stream().map(x -> mgu.apply(x)).collect(Collectors.toCollection(ArrayList::new)); termsList.replaceAll(mgu::apply);
idx = idx+1 == termsList.size() ? 0 : idx+1; idx = idx+1 == termsList.size() ? 0 : idx+1;
continue; continue;
} }

View File

@@ -6,6 +6,7 @@ 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;
@@ -648,9 +649,11 @@ 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) {
HashMap<UnifyType, Integer> typeMap = new HashMap<>(); // 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<>(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());
@@ -668,9 +671,9 @@ 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(x -> occuringTypes.push(x)); t1.getTypeParams().forEach(occuringTypes::push);
} }
Queue<UnifyPair> result1 = new LinkedList<UnifyPair>(pairs); LinkedList<UnifyPair> result1 = new LinkedList<UnifyPair>(pairs);
ArrayList<UnifyPair> result = new ArrayList<UnifyPair>(); ArrayList<UnifyPair> result = new ArrayList<UnifyPair>();
boolean applied = false; boolean applied = false;
@@ -691,19 +694,30 @@ 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);
result = result.stream().map(x -> uni.apply(pair,x)).collect(Collectors.toCollection(ArrayList::new)); // apply unifier to result and result1 in place
result1 = result1.stream().map(x -> uni.apply(pair,x)).collect(Collectors.toCollection(LinkedList::new)); result.replaceAll(p -> uni.apply(pair, p));
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().stream().map(x -> uni.apply(pair,x)).collect(Collectors.toCollection(Constraint::new)), b.getExtendConstraint().createdMapped(x -> uni.apply(pair,x)),
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 -> oc.stream().map(applyUni).collect(Collectors.toCollection(HashSet::new))); oderConstraints.replaceAll(oc -> {
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
@@ -858,8 +872,8 @@ public class RuleSet implements IRuleSet{
if (r instanceof PlaceholderType) { ((PlaceholderType)r).disableWildcardtable(); } if (r instanceof PlaceholderType) { ((PlaceholderType)r).disableWildcardtable(); }
} ); } );
logger.debug("FUNgreater: " + pair); logger.debug(() -> "FUNgreater: " + pair);
logger.debug("FUNred: " + result); logger.debug(() -> "FUNred: " + result);
return Optional.of(result); return Optional.of(result);
@@ -927,8 +941,8 @@ public class RuleSet implements IRuleSet{
Set<UnifyPair> result = new HashSet<UnifyPair>(); Set<UnifyPair> result = new HashSet<UnifyPair>();
Integer variance = ((PlaceholderType)rhsType).getVariance(); int variance = ((PlaceholderType)rhsType).getVariance();
Integer inversVariance = distributeVariance.inverseVariance(variance); int 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++) {
@@ -951,8 +965,8 @@ public class RuleSet implements IRuleSet{
if (r instanceof PlaceholderType) { ((PlaceholderType)r).disableWildcardtable(); } if (r instanceof PlaceholderType) { ((PlaceholderType)r).disableWildcardtable(); }
} ); } );
logger.debug("FUNgreater: " + pair); logger.debug(() -> "FUNgreater: " + pair);
logger.debug("FUNgreater: " + result); logger.debug(() -> "FUNgreater: " + result);
return Optional.of(result); return Optional.of(result);
} }
@@ -972,8 +986,8 @@ public class RuleSet implements IRuleSet{
Set<UnifyPair> result = new HashSet<UnifyPair>(); Set<UnifyPair> result = new HashSet<UnifyPair>();
Integer variance = ((PlaceholderType)lhsType).getVariance(); int variance = ((PlaceholderType)lhsType).getVariance();
Integer inversVariance = distributeVariance.inverseVariance(variance); int 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++) {
@@ -998,8 +1012,8 @@ public class RuleSet implements IRuleSet{
} ); } );
logger.debug("FUNgreater: " + pair); logger.debug(() -> "FUNgreater: " + pair);
logger.debug("FUNsmaller: " + result); logger.debug(() -> "FUNsmaller: " + result);
return Optional.of(result); return Optional.of(result);
} }

View File

@@ -45,7 +45,7 @@ public class TypeUnify2Task extends TypeUnifyTask {
*/ */
//writeLog("xxx"); //writeLog("xxx");
//noOfThread--; //noOfThread--;
if (this.myIsCancelled()) { if (this.isExecutionCancelled()) {
return CompletableFuture.completedFuture(new HashSet<>()); return CompletableFuture.completedFuture(new HashSet<>());
} else { } else {
return res; return res;

View File

@@ -3,6 +3,7 @@ package de.dhbwstuttgart.typeinference.unify;
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;
@@ -26,11 +27,7 @@ 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;
@@ -49,7 +46,6 @@ import java.util.concurrent.RecursiveTask;
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;
/** /**
@@ -57,7 +53,7 @@ import org.apache.commons.io.output.NullOutputStream;
* *
* @author Florian Steurer * @author Florian Steurer
*/ */
public class TypeUnifyTask extends RecursiveTask<CompletableFuture<Set<Set<UnifyPair>>>> { public class TypeUnifyTask extends CancellableTask<CompletableFuture<Set<Set<UnifyPair>>>> {
@Serial @Serial
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
@@ -106,19 +102,17 @@ public class TypeUnifyTask extends RecursiveTask<CompletableFuture<Set<Set<Unify
int rekTiefeField; int rekTiefeField;
Integer nOfUnify = 0; int nOfUnify = 0;
Integer noUndefPair = 0; int noUndefPair = 0;
Integer noAllErasedElements = 0; int 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.newWithLogger(Logger.NULL_LOGGER);
rules = new RuleSet(context.placeholderRegistry()); rules = new RuleSet(context.placeholderRegistry());
@@ -155,7 +149,7 @@ public class TypeUnifyTask extends RecursiveTask<CompletableFuture<Set<Set<Unify
this.fc = fc; this.fc = fc;
this.oup = new OrderingUnifyPair(fc, context); this.oup = new OrderingUnifyPair(fc, context);
this.context = context.newWithLogger( this.context = (context.logger() instanceof ServerTaskLogger) ? context : context.newWithLogger(
Logger.forFile( Logger.forFile(
System.getProperty("user.dir") + "/logFiles/" + "Thread", System.getProperty("user.dir") + "/logFiles/" + "Thread",
"Unify" "Unify"
@@ -213,13 +207,6 @@ public class TypeUnifyTask extends RecursiveTask<CompletableFuture<Set<Set<Unify
} }
} }
*/ */
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) {
@@ -249,7 +236,7 @@ public class TypeUnifyTask extends RecursiveTask<CompletableFuture<Set<Set<Unify
throw new TypeinferenceException("Unresolved constraints: " + res, new NullToken()); //return new HashSet<>(); throw new TypeinferenceException("Unresolved constraints: " + res, new NullToken()); //return new HashSet<>();
} }
if (this.myIsCancelled()) { if (this.isExecutionCancelled()) {
return new HashSet<>(); return new HashSet<>();
} }
@@ -286,14 +273,14 @@ public class TypeUnifyTask extends RecursiveTask<CompletableFuture<Set<Set<Unify
//.collect(Collectors.toCollection(HashSet::new))); //.collect(Collectors.toCollection(HashSet::new)));
if (this.myIsCancelled()) { if (this.isExecutionCancelled()) {
return CompletableFuture.completedFuture(new HashSet<>()); return CompletableFuture.completedFuture(new HashSet<>());
} }
rekTiefe++; rekTiefe++;
nOfUnify++; nOfUnify++;
context.logger().debug(nOfUnify.toString() + " Unifikation: " + eq.toString()); context.logger().debug(() -> nOfUnify + " Unifikation: " + eq.toString());
context.logger().debug(nOfUnify.toString() + " Oderconstraints: " + oderConstraints.toString()); context.logger().debug(() -> nOfUnify + " Oderconstraints: " + oderConstraints.toString());
/* /*
* Variancen auf alle Gleichungen vererben * Variancen auf alle Gleichungen vererben
@@ -315,15 +302,10 @@ public class TypeUnifyTask extends RecursiveTask<CompletableFuture<Set<Set<Unify
/* /*
* Occurs-Check durchfuehren * Occurs-Check durchfuehren
*/ */
Set<UnifyPair> ocurrPairs = eq.stream().filter(x -> { Set<UnifyPair> ocurrPairs = TypeUnifyTaskHelper.occursCheck(eq);
UnifyType lhs, rhs;
return (lhs = x.getLhsType()) instanceof PlaceholderType Set<UnifyPair> finalOcurrPairs = ocurrPairs;
&& !((rhs = x.getRhsType()) instanceof PlaceholderType) context.logger().debug(() -> "ocurrPairs: " + finalOcurrPairs);
&& rhs.getTypeParams().occurs((PlaceholderType) lhs);
})
.peek(UnifyPair::setUndefinedPair)
.collect(Collectors.toCollection(HashSet::new));
context.logger().debug("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);
@@ -344,15 +326,9 @@ public class TypeUnifyTask extends RecursiveTask<CompletableFuture<Set<Set<Unify
/* 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 = occurcheck.stream().filter(x -> { ocurrPairs = TypeUnifyTaskHelper.occursCheck(occurcheck);
UnifyType lhs, rhs; Set<UnifyPair> finalOcurrPairs1 = ocurrPairs;
return (lhs = x.getLhsType()) instanceof PlaceholderType context.logger().debug(() -> "ocurrPairs: " + finalOcurrPairs1);
&& !((rhs = x.getRhsType()) instanceof PlaceholderType)
&& rhs.getTypeParams().occurs((PlaceholderType) lhs);
})
.peek(UnifyPair::setUndefinedPair)
.collect(Collectors.toCollection(HashSet::new));
context.logger().debug("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);
@@ -364,8 +340,8 @@ public class TypeUnifyTask extends RecursiveTask<CompletableFuture<Set<Set<Unify
eq0.forEach(UnifyPair::disableCondWildcards); eq0.forEach(UnifyPair::disableCondWildcards);
context.logger().debug(nOfUnify.toString() + " Unifikation nach applyTypeUnificationRules: " + eq.toString()); context.logger().debug(() ->nOfUnify + " Unifikation nach applyTypeUnificationRules: " + eq.toString());
context.logger().debug(nOfUnify.toString() + " Oderconstraints nach applyTypeUnificationRules: " + oderConstraints.toString()); context.logger().debug(() -> nOfUnify + " 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
@@ -417,21 +393,21 @@ public class TypeUnifyTask extends RecursiveTask<CompletableFuture<Set<Set<Unify
//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.toString() + " Oderconstraints2: " + oderConstraintsOutput.toString()); context.logger().debug(() -> nOfUnify + " Oderconstraints2: " + oderConstraintsOutput.toString());
if (printtag) context.logger().info("secondLevelSets:" + secondLevelSets); if (printtag) context.logger().info("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.toString() + " UndefinedPairs; " + up); context.logger().debug(() -> noUndefPair + " UndefinedPairs; " + up);
context.logger().debug("BasePair; " + up.getBasePair()); context.logger().debug(() -> "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 -> context.logger().debug(() -> "AllSubst: " + x.getAllSubstitutions().toString()));
return CompletableFuture.completedFuture(error); return CompletableFuture.completedFuture(error);
} }
@@ -487,7 +463,7 @@ public class TypeUnifyTask extends RecursiveTask<CompletableFuture<Set<Set<Unify
// .collect(Collectors.toCollection(HashSet::new)); // .collect(Collectors.toCollection(HashSet::new));
//Muss auskommentiert werden, wenn computeCartesianRecursive ENDE //Muss auskommentiert werden, wenn computeCartesianRecursive ENDE
if (this.myIsCancelled()) { if (this.isExecutionCancelled()) {
return CompletableFuture.completedFuture(new HashSet<>()); return CompletableFuture.completedFuture(new HashSet<>());
} }
@@ -506,14 +482,14 @@ public class TypeUnifyTask extends RecursiveTask<CompletableFuture<Set<Set<Unify
* Step 5: Substitution * Step 5: Substitution
*/ */
//writeLog("vor Subst: " + eqPrime); //writeLog("vor Subst: " + eqPrime);
context.logger().debug("vor Subst: " + oderConstraints); context.logger().debug(() -> "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); context.logger().debug(() -> "nach Subst: " + newOderConstraints);
{// sequentiell (Step 6b is included) {// sequentiell (Step 6b is included)
@@ -536,7 +512,7 @@ public class TypeUnifyTask extends RecursiveTask<CompletableFuture<Set<Set<Unify
return eqPrimePrimeSet; return eqPrimePrimeSet;
}); });
if (finalresult && isSolvedForm(eqPrime)) { if (finalresult && isSolvedForm(eqPrime)) {
context.logger().debug("eqPrime:" + eqPrime.toString() + "\n"); context.logger().debug(() -> "eqPrime:" + eqPrime.toString() + "\n");
/* methodconstraintsets werden zum Ergebnis hinzugefuegt /* methodconstraintsets werden zum Ergebnis hinzugefuegt
* Anfang * Anfang
@@ -592,7 +568,8 @@ public class TypeUnifyTask extends RecursiveTask<CompletableFuture<Set<Set<Unify
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)) {
context.logger().debug("Result1 " + eqPrimePrimeSet); Set<Set<UnifyPair>> finalEqPrimePrimeSet = eqPrimePrimeSet;
context.logger().debug(() -> "Result1 " + finalEqPrimePrimeSet);
} }
return eqPrimePrimeSet; return eqPrimePrimeSet;
}); });
@@ -680,14 +657,16 @@ public class TypeUnifyTask extends RecursiveTask<CompletableFuture<Set<Set<Unify
*/ */
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.empty(); Optional<UnifyPair> optOrigPair;
if (!oderConstraint) { if (!oderConstraint) {
optOrigPair = TypeUnifyTaskHelper.findEqualityConstrainedUnifyPair(nextSetElement); optOrigPair = TypeUnifyTaskHelper.findEqualityConstrainedUnifyPair(nextSetElement);
context.logger().debug("optOrigPair: " + optOrigPair); context.logger().debug(() -> "optOrigPair: " + optOrigPair);
if (optOrigPair.isPresent()) { if (optOrigPair.isPresent()) {
sameEqSet = TypeUnifyTaskHelper.findConstraintsWithSameTVAssociation(optOrigPair.get(), singleElementSets); sameEqSet = TypeUnifyTaskHelper.findConstraintsWithSameTVAssociation(optOrigPair.get(), singleElementSets);
} }
} else {
optOrigPair = Optional.empty();
} }
@@ -697,7 +676,7 @@ public class TypeUnifyTask extends RecursiveTask<CompletableFuture<Set<Set<Unify
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()); context.logger().debug(() ->"Return computeCR: " + result.toString());
return result; return result;
}); });
} }
@@ -724,14 +703,14 @@ public class TypeUnifyTask extends RecursiveTask<CompletableFuture<Set<Set<Unify
VarianceCase varianceCase = VarianceCase.createFromVariance(variance, oderConstraint, this, context); VarianceCase varianceCase = VarianceCase.createFromVariance(variance, oderConstraint, this, context);
context.logger().debug("nextSet: " + nextSet.toString()); context.logger().debug(() -> "nextSet: " + nextSet.toString());
context.logger().debug("nextSetasList: " + prevNextSetAsList.toString()); context.logger().debug(() -> "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); context.logger().debug(() -> "ERSTELLUNG methodSignatureConstraint: " + methodSignatureConstraint);
//context.logger().info("ERSTELLUNG methodSignatureConstraint: " +noOfThread+" "+methodSignatureConstraint); //context.logger().info("ERSTELLUNG methodSignatureConstraint: " +noOfThread+" "+methodSignatureConstraint);
//context.logger().info("a: " +a); //context.logger().info("a: " +a);
//context.logger().info("eq: " +eq); //context.logger().info("eq: " +eq);
@@ -740,7 +719,7 @@ public class TypeUnifyTask extends RecursiveTask<CompletableFuture<Set<Set<Unify
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"); context.logger().debug(() -> "a1: " + rekTiefe + " " + "variance: " + variance + " " + varianceCase.a.toString() + "\n");
Set<Set<UnifyPair>> aParDef = new HashSet<>(); Set<Set<UnifyPair>> aParDef = new HashSet<>();
@@ -761,7 +740,8 @@ public class TypeUnifyTask extends RecursiveTask<CompletableFuture<Set<Set<Unify
// 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<Tuple<Set<Set<UnifyPair>>, Set<Set<Set<UnifyPair>>>>> parallelResultDataFuture; CompletableFuture<VarianceCase.ComputationResults> parallelResultDataFuture;
if (parallel) { if (parallel) {
parallelResultDataFuture = varianceCase.computeParallel( parallelResultDataFuture = varianceCase.computeParallel(
@@ -772,13 +752,16 @@ public class TypeUnifyTask extends RecursiveTask<CompletableFuture<Set<Set<Unify
// 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(currentThreadResult -> new Tuple<>(currentThreadResult, new HashSet<>())); .thenApply(VarianceCase.ComputationResults::new);
} }
if (this.isExecutionCancelled()) {
return CompletableFuture.completedFuture(new HashSet<>());
}
return parallelResultDataFuture.thenCompose(parallelResultData -> { return parallelResultDataFuture.thenCompose(parallelResultData -> {
Set<Set<UnifyPair>> currentThreadResult = parallelResultData.getFirst(); Set<Set<UnifyPair>> currentThreadResult = parallelResultData.mainResult;
Set<Set<Set<UnifyPair>>> forkResults = parallelResultData.getSecond(); Set<Set<Set<UnifyPair>>> forkResults = parallelResultData.forkResults;
Set<Set<UnifyPair>> result = prevResult; Set<Set<UnifyPair>> result = prevResult;
List<Set<UnifyPair>> nextSetAsList = prevNextSetAsList; List<Set<UnifyPair>> nextSetAsList = prevNextSetAsList;
@@ -814,7 +797,7 @@ public class TypeUnifyTask extends RecursiveTask<CompletableFuture<Set<Set<Unify
//context.logger().info(a_last); //context.logger().info(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 -> context.logger().debug(() -> "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
@@ -823,11 +806,12 @@ public class TypeUnifyTask extends RecursiveTask<CompletableFuture<Set<Set<Unify
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()); context.logger().debug(() -> "NullPointerException: " + a_last.toString());
} }
} else { } else {
//alle Fehlerfaelle und alle korrekten Ergebnis jeweils adden //alle Fehlerfaelle und alle korrekten Ergebnis jeweils adden
context.logger().debug("RES Fst: result: " + result.toString() + " currentThreadResult: " + currentThreadResult.toString()); Set<Set<UnifyPair>> finalResult = result;
context.logger().debug(() -> "RES Fst: result: " + finalResult.toString() + " currentThreadResult: " + currentThreadResult.toString());
result.addAll(currentThreadResult); result.addAll(currentThreadResult);
} }
} }
@@ -852,7 +836,8 @@ public class TypeUnifyTask extends RecursiveTask<CompletableFuture<Set<Set<Unify
|| (!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
context.logger().debug("RES var1 ADD:" + result.toString() + " " + par_res.toString()); Set<Set<UnifyPair>> finalResult1 = result;
context.logger().debug(() ->"RES var1 ADD:" + finalResult1.toString() + " " + par_res.toString());
result.addAll(par_res); result.addAll(par_res);
} }
} }
@@ -873,15 +858,15 @@ public class TypeUnifyTask extends RecursiveTask<CompletableFuture<Set<Set<Unify
// 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();
return CompletableFuture.completedFuture(result); return CompletableFuture.completedFuture(result);
} }
context.logger().debug("a: " + rekTiefe + " variance: " + variance + varianceCase.a.toString()); context.logger().debug(() -> "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)
@@ -913,7 +898,8 @@ public class TypeUnifyTask extends RecursiveTask<CompletableFuture<Set<Set<Unify
if (currentThreadResult.size() > 1) { if (currentThreadResult.size() > 1) {
// context.logger().info(); // context.logger().info();
} }
context.logger().debug("nextSetasList vor filter-Aufruf: " + nextSetAsList); List<Set<UnifyPair>> finalNextSetAsList = 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;
@@ -924,8 +910,11 @@ public class TypeUnifyTask extends RecursiveTask<CompletableFuture<Set<Set<Unify
})//.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));
} }
context.logger().debug("nextSetasList nach filter-Aufruf: " + nextSetAsList);
nofstred = nextSetAsList.size(); if (context.logger().isLogLevelActive(Logger.LogLevel.DEBUG)) {
List<Set<UnifyPair>> finalNextSetAsList1 = nextSetAsList;
context.logger().debug(() -> "nextSetasList nach filter-Aufruf: " + finalNextSetAsList1);
int nofstred = nextSetAsList.size();
//NOCH NICHT korrekt PL 2018-10-12 //NOCH NICHT korrekt PL 2018-10-12
//nextSetasList = nextSetasList.stream().filter(y -> couldBecorrect(reducedUndefResSubstGroundedBasePair, y)) //nextSetasList = nextSetasList.stream().filter(y -> couldBecorrect(reducedUndefResSubstGroundedBasePair, y))
// .collect(Collectors.toCollection(ArrayList::new)); // .collect(Collectors.toCollection(ArrayList::new));
@@ -939,8 +928,10 @@ public class TypeUnifyTask extends RecursiveTask<CompletableFuture<Set<Set<Unify
context.logger().debug("Number second erased Elements (undef): " + (nofstred - nextSetAsList.size())); context.logger().debug("Number second erased Elements (undef): " + (nofstred - nextSetAsList.size()));
context.logger().debug("Number erased Elements (undef): " + (len - nextSetAsList.size())); context.logger().debug("Number erased Elements (undef): " + (len - nextSetAsList.size()));
noAllErasedElements += (len - nextSetAsList.size()); noAllErasedElements += (len - nextSetAsList.size());
context.logger().debug("Number of all erased Elements (undef): " + noAllErasedElements.toString()); context.logger().debug("Number of all erased Elements (undef): " + noAllErasedElements);
context.logger().debug("Number of Backtracking: " + noBacktracking++); context.logger().debug("Number of Backtracking: " + noBacktracking++);
}
// context.logger().info(""); // context.logger().info("");
} }
//if (nextSetasList.size() == 0 && isUndefinedPairSetSet(result) && nextSet.size() > 1) { //if (nextSetasList.size() == 0 && isUndefinedPairSetSet(result) && nextSet.size() > 1) {
@@ -950,7 +941,7 @@ public class TypeUnifyTask extends RecursiveTask<CompletableFuture<Set<Set<Unify
// 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()); context.logger().debug(() -> "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);
@@ -967,7 +958,7 @@ public class TypeUnifyTask extends RecursiveTask<CompletableFuture<Set<Set<Unify
* 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
@@ -987,7 +978,7 @@ public class TypeUnifyTask extends RecursiveTask<CompletableFuture<Set<Set<Unify
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); context.logger().debug(() ->"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<>();
@@ -1008,7 +999,7 @@ public class TypeUnifyTask extends RecursiveTask<CompletableFuture<Set<Set<Unify
if (result.isEmpty() || isUndefinedPairSetSet(result)) { if (result.isEmpty() || isUndefinedPairSetSet(result)) {
result.addAll(localRes); result.addAll(localRes);
} }
context.logger().debug("FALSE: " + aPair + "sameEqSet: " + sameEqSet); context.logger().debug(() ->"FALSE: " + aPair + "sameEqSet: " + sameEqSet);
return false; return false;
} }
} else { } else {
@@ -1030,12 +1021,12 @@ public class TypeUnifyTask extends RecursiveTask<CompletableFuture<Set<Set<Unify
if (result.isEmpty() || isUndefinedPairSetSet(result)) { if (result.isEmpty() || isUndefinedPairSetSet(result)) {
result.addAll(localRes); result.addAll(localRes);
} }
context.logger().debug("FALSE: " + aPair + "sameEqSet: " + sameEqSet); context.logger().debug(() ->"FALSE: " + aPair + "sameEqSet: " + sameEqSet);
return false; return false;
} }
} }
} }
context.logger().debug("TRUE: " + aPair + "sameEqSet: " + sameEqSet); context.logger().debug(() ->"TRUE: " + aPair + "sameEqSet: " + sameEqSet);
return true; return true;
} }
return true; return true;
@@ -1121,7 +1112,7 @@ public class TypeUnifyTask extends RecursiveTask<CompletableFuture<Set<Set<Unify
// 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); context.logger().debug(() ->"Second erase:" + checkPair);
return false; return false;
} }
//*/ //*/
@@ -1320,7 +1311,7 @@ public class TypeUnifyTask extends RecursiveTask<CompletableFuture<Set<Set<Unify
* (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()); context.logger().debug(() ->"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);
@@ -1407,10 +1398,12 @@ public class TypeUnifyTask extends RecursiveTask<CompletableFuture<Set<Set<Unify
} }
} }
if (context.logger().isLogLevelActive(Logger.LogLevel.DEBUG)) {
context.logger().debug("eq2s: " + eq2s); context.logger().debug("eq2s: " + eq2s);
context.logger().debug("eq2sAsListFst: " + eq2sAsListFst); context.logger().debug("eq2sAsListFst: " + eq2sAsListFst);
context.logger().debug("eq2sAsListSnd: " + eq2sAsListSnd); context.logger().debug("eq2sAsListSnd: " + eq2sAsListSnd);
context.logger().debug("eq2sAsListBack: " + eq2sAsListBack); context.logger().debug("eq2sAsListBack: " + eq2sAsListBack);
}
eq2sAsList.addAll(eq2sAsListFst); eq2sAsList.addAll(eq2sAsListFst);
eq2sAsList.addAll(eq2sAsListSnd); eq2sAsList.addAll(eq2sAsListSnd);
@@ -1707,7 +1700,7 @@ public class TypeUnifyTask extends RecursiveTask<CompletableFuture<Set<Set<Unify
//} //}
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()); context.logger().debug(() ->"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
@@ -1718,8 +1711,9 @@ public class TypeUnifyTask extends RecursiveTask<CompletableFuture<Set<Set<Unify
aa.putAll(b); aa.putAll(b);
return aa; return aa;
}; };
HashMap<PlaceholderType, PlaceholderType> hm = x.getInvolvedPlaceholderTypes().stream() var involvedPlaceholderTypes = x.getInvolvedPlaceholderTypes();
.reduce(new HashMap<PlaceholderType, PlaceholderType>(), HashMap<PlaceholderType, PlaceholderType> hm = involvedPlaceholderTypes.stream()
.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;
@@ -1739,7 +1733,8 @@ public class TypeUnifyTask extends RecursiveTask<CompletableFuture<Set<Set<Unify
if ((match.match(ml)).isEmpty()) { if ((match.match(ml)).isEmpty()) {
thetaQs.remove(c); thetaQs.remove(c);
} }
context.logger().debug("thetaQs von " + c + ": " + thetaQs.toString()); Set<UnifyType> finalThetaQs = thetaQs;
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,
@@ -1763,7 +1758,7 @@ public class TypeUnifyTask extends RecursiveTask<CompletableFuture<Set<Set<Unify
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()); context.logger().debug(() ->"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);
@@ -1836,7 +1831,7 @@ public class TypeUnifyTask extends RecursiveTask<CompletableFuture<Set<Set<Unify
} }
} }
} }
context.logger().debug("result von " + pair + ": " + result); context.logger().debug(() ->"result von " + pair + ": " + result);
return result; return result;
} }

View File

@@ -5,6 +5,7 @@ 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;
@@ -185,4 +186,36 @@ 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

@@ -9,7 +9,7 @@ public record UnifyContext(
// main logger of a unification // main logger of a unification
Logger logger, Logger logger,
// 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
@@ -22,7 +22,7 @@ public record UnifyContext(
public UnifyContext( public UnifyContext(
Logger logger, Logger logger,
Boolean parallel, boolean parallel,
UnifyResultModel resultModel, UnifyResultModel resultModel,
UnifyTaskModel usedTasks, UnifyTaskModel usedTasks,
ExecutorService executor, ExecutorService executor,
@@ -33,7 +33,7 @@ public record UnifyContext(
public UnifyContext( public UnifyContext(
Logger logger, Logger logger,
Boolean parallel, boolean parallel,
UnifyResultModel resultModel, UnifyResultModel resultModel,
UnifyTaskModel usedTasks, UnifyTaskModel usedTasks,
PlaceholderRegistry placeholderRegistry PlaceholderRegistry placeholderRegistry
@@ -52,6 +52,7 @@ public record UnifyContext(
} }
public UnifyContext newWithParallel(boolean parallel) { public UnifyContext newWithParallel(boolean parallel) {
if (this.parallel == parallel) return this;
return new UnifyContext(logger, parallel, resultModel, executor, placeholderRegistry, usedTasks); return new UnifyContext(logger, 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.myCancel(true); t.cancelExecution();
} }
} }
} }

View File

@@ -1,6 +1,5 @@
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;
@@ -17,11 +16,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 Variance1Case extends VarianceCase { public class ContravarianceCase extends VarianceCase {
protected final int variance = 1; protected final int variance = 1;
protected Variance1Case(boolean isOderConstraint, TypeUnifyTask typeUnifyTask, UnifyContext context) { protected ContravarianceCase(boolean isOderConstraint, TypeUnifyTask typeUnifyTask, UnifyContext context) {
super(isOderConstraint, typeUnifyTask, context); super(isOderConstraint, typeUnifyTask, context);
} }
@@ -37,7 +36,7 @@ public class Variance1Case extends VarianceCase {
if (this.isOderConstraint) { if (this.isOderConstraint) {
nextSetasListOderConstraints.add(((Constraint<UnifyPair>) a).getExtendConstraint()); nextSetasListOderConstraints.add(((Constraint<UnifyPair>) a).getExtendConstraint());
} }
context.logger().debug("nextSetasListOderConstraints 1: " + nextSetasListOderConstraints); context.logger().debug(() -> "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.
@@ -49,7 +48,7 @@ public class Variance1Case extends VarianceCase {
@Override @Override
public CompletableFuture<Tuple<Set<Set<UnifyPair>>, Set<Set<Set<UnifyPair>>>>> computeParallel( public CompletableFuture<ComputationResults> 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,
@@ -61,10 +60,6 @@ public class Variance1Case 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);
@@ -72,18 +67,19 @@ public class Variance1Case extends VarianceCase {
/* FORK ANFANG */ /* FORK ANFANG */
TypeUnify2Task forkOrig = new TypeUnify2Task(newElemsOrig, newEqOrig, newOderConstraintsOrig, a, fc, context, rekTiefe, methodSignatureConstraint); TypeUnify2Task forkOrig = new TypeUnify2Task(newElemsOrig, newEqOrig, newOderConstraintsOrig, a, fc, context, rekTiefe, methodSignatureConstraint);
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);
resultValues = resultValues.thenCombine(forkOrigFuture, CompletableFuture<ComputationResults> resultValues = forkOrigFuture.thenApply(
(prevResults, currentThreadResult) -> { (currentThreadResult) -> {
forkOrig.context.logger().debug("final Orig 1"); forkOrig.context.logger().debug("final Orig 1");
forkOrig.closeLogFile(); forkOrig.closeLogFile();
return new Tuple<>(currentThreadResult, prevResults.getSecond()); return new ComputationResults(currentThreadResult);
}); });
//forks.add(forkOrig); //forks.add(forkOrig);
if (typeUnifyTask.myIsCancelled()) { if (typeUnifyTask.isExecutionCancelled()) {
throw new UnifyCancelException(); return CompletableFuture.completedFuture(new ComputationResults());
} }
/* FORK ENDE */ /* FORK ENDE */
@@ -108,16 +104,17 @@ public class Variance1Case extends VarianceCase {
List<Set<Constraint<UnifyPair>>> newOderConstraints = new ArrayList<>(oderConstraints); List<Set<Constraint<UnifyPair>>> newOderConstraints = new ArrayList<>(oderConstraints);
newElems.add(nSaL); newElems.add(nSaL);
TypeUnify2Task fork = new TypeUnify2Task(newElems, newEq, newOderConstraints, nSaL, fc, context, rekTiefe, new HashSet<>(methodSignatureConstraint)); TypeUnify2Task fork = new TypeUnify2Task(newElems, newEq, newOderConstraints, nSaL, fc, context, rekTiefe, new HashSet<>(methodSignatureConstraint));
typeUnifyTask.addChildTask(fork);
// schedule compute() on another thread // schedule compute() on another thread
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.myIsCancelled()) { if (typeUnifyTask.isExecutionCancelled()) {
throw new UnifyCancelException(); return new ComputationResults();
} }
context.logger().debug("fork_res: " + fork_res.toString()); context.logger().debug("fork_res: " + fork_res.toString());
context.logger().debug(Boolean.valueOf((typeUnifyTask.isUndefinedPairSetSet(fork_res))).toString()); context.logger().debug(Boolean.valueOf((typeUnifyTask.isUndefinedPairSetSet(fork_res))).toString());
prevResults.getSecond().add(fork_res); prevResults.addForkResult(fork_res);
if (!typeUnifyTask.isUndefinedPairSetSet(fork_res)) { if (!typeUnifyTask.isUndefinedPairSetSet(fork_res)) {
aParDef.add(fork.getNextSetElement()); aParDef.add(fork.getNextSetElement());
} }
@@ -127,8 +124,8 @@ public class Variance1Case extends VarianceCase {
} }
); );
if (typeUnifyTask.myIsCancelled()) { if (typeUnifyTask.isExecutionCancelled()) {
throw new UnifyCancelException(); return CompletableFuture.completedFuture(new ComputationResults());
} }
} }

View File

@@ -1,6 +1,5 @@
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;
@@ -17,11 +16,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 VarianceM1Case extends VarianceCase { public class CovarianceCase extends VarianceCase {
protected final int variance = -1; protected final int variance = -1;
protected VarianceM1Case(boolean isOderConstraint, TypeUnifyTask typeUnifyTask, UnifyContext context) { protected CovarianceCase(boolean isOderConstraint, TypeUnifyTask typeUnifyTask, UnifyContext context) {
super(isOderConstraint, typeUnifyTask, context); super(isOderConstraint, typeUnifyTask, context);
} }
@@ -32,11 +31,11 @@ public class VarianceM1Case extends VarianceCase {
Optional<UnifyPair> optOrigPair Optional<UnifyPair> optOrigPair
) { ) {
a = typeUnifyTask.oup.min(nextSetAsList.iterator()); a = typeUnifyTask.oup.min(nextSetAsList.iterator());
context.logger().debug("Min: a in " + variance + " " + a); context.logger().debug(() -> "Min: a in " + variance + " " + 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); context.logger().debug(() -> "nextSetasListOderConstraints -1: " + nextSetasListOderConstraints);
nextSetAsList.remove(a); nextSetAsList.remove(a);
//Alle minimalen Elemente in nextSetasListRest bestimmen //Alle minimalen Elemente in nextSetasListRest bestimmen
@@ -49,7 +48,7 @@ public class VarianceM1Case extends VarianceCase {
@Override @Override
public CompletableFuture<Tuple<Set<Set<UnifyPair>>, Set<Set<Set<UnifyPair>>>>> computeParallel( public CompletableFuture<ComputationResults> 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,
@@ -61,10 +60,6 @@ public class VarianceM1Case 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);
@@ -72,28 +67,29 @@ public class VarianceM1Case extends VarianceCase {
/* FORK ANFANG */ /* FORK ANFANG */
TypeUnify2Task forkOrig = new TypeUnify2Task(newElemsOrig, newEqOrig, newOderConstraintsOrig, a, fc, context, rekTiefe, methodSignatureConstraint); TypeUnify2Task forkOrig = new TypeUnify2Task(newElemsOrig, newEqOrig, newOderConstraintsOrig, a, fc, context, rekTiefe, methodSignatureConstraint);
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);
resultValues = resultValues.thenCombine(forkOrigFuture, CompletableFuture<ComputationResults> resultValues = forkOrigFuture.thenApply(
(prevResults, currentThreadResult) -> { (currentThreadResult) -> {
forkOrig.context.logger().debug("final Orig -1"); forkOrig.context.logger().debug("final Orig -1");
forkOrig.closeLogFile(); forkOrig.closeLogFile();
return new Tuple<>(currentThreadResult, prevResults.getSecond()); return new ComputationResults(currentThreadResult);
}); });
//forks.add(forkOrig); //forks.add(forkOrig);
if (typeUnifyTask.myIsCancelled()) { if (typeUnifyTask.isExecutionCancelled()) {
throw new UnifyCancelException(); return resultValues;
} }
/* FORK ENDE */ /* FORK ENDE */
context.logger().debug("a in " + variance + " " + a); context.logger().debug(() -> "a in " + variance + " " + a);
context.logger().debug("nextSetasListRest: " + nextSetasListRest.toString()); context.logger().debug(() -> "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()); context.logger().debug(() -> "-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,16 +105,17 @@ public class VarianceM1Case extends VarianceCase {
List<Set<Constraint<UnifyPair>>> newOderConstraints = new ArrayList<>(oderConstraints); List<Set<Constraint<UnifyPair>>> newOderConstraints = new ArrayList<>(oderConstraints);
newElems.add(nSaL); newElems.add(nSaL);
TypeUnify2Task fork = new TypeUnify2Task(newElems, newEq, newOderConstraints, nSaL, fc, context, rekTiefe, new HashSet<>(methodSignatureConstraint)); TypeUnify2Task fork = new TypeUnify2Task(newElems, newEq, newOderConstraints, nSaL, fc, context, rekTiefe, new HashSet<>(methodSignatureConstraint));
typeUnifyTask.addChildTask(fork);
// schedule compute() on another thread // schedule compute() on another thread
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.myIsCancelled()) { if (typeUnifyTask.isExecutionCancelled()) {
throw new UnifyCancelException(); return prevResults;
} }
context.logger().debug("fork_res: " + fork_res.toString()); context.logger().debug(() -> "fork_res: " + fork_res.toString());
context.logger().debug(Boolean.valueOf((typeUnifyTask.isUndefinedPairSetSet(fork_res))).toString()); context.logger().debug(() -> Boolean.valueOf((typeUnifyTask.isUndefinedPairSetSet(fork_res))).toString());
prevResults.getSecond().add(fork_res); prevResults.addForkResult(fork_res);
if (!typeUnifyTask.isUndefinedPairSetSet(fork_res)) { if (!typeUnifyTask.isUndefinedPairSetSet(fork_res)) {
aParDef.add(fork.getNextSetElement()); aParDef.add(fork.getNextSetElement());
} }
@@ -128,8 +125,8 @@ public class VarianceM1Case extends VarianceCase {
} }
); );
if (typeUnifyTask.myIsCancelled()) { if (typeUnifyTask.isExecutionCancelled()) {
throw new UnifyCancelException(); return resultValues;
} }
} }
@@ -146,13 +143,13 @@ public class VarianceM1Case 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); context.logger().debug(() -> "Geloescht result: " + result);
result.clear(); result.clear();
result.addAll(currentThreadResult); result.addAll(currentThreadResult);
} else if (resOfCompare == 0) { } else if (resOfCompare == 0) {
result.addAll(currentThreadResult); result.addAll(currentThreadResult);
} else if (resOfCompare == -1) { } else if (resOfCompare == -1) {
context.logger().debug("Geloescht currentThreadResult: " + currentThreadResult); context.logger().debug(() -> "Geloescht currentThreadResult: " + currentThreadResult);
//result = result; //result = result;
} }
} }
@@ -165,13 +162,13 @@ public class VarianceM1Case extends VarianceCase {
) { ) {
// context.logger().info(""); // context.logger().info("");
context.logger().debug("a: " + rekTiefe + " variance: " + variance + a.toString()); context.logger().debug(() -> "a: " + rekTiefe + " variance: " + variance + a.toString());
context.logger().debug("aParDef: " + aParDef.toString()); context.logger().debug(() -> "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);
context.logger().debug("Removed: " + nextSetasListOderConstraints); context.logger().debug(() -> "Removed: " + nextSetasListOderConstraints);
nextSetasListOderConstraints = new ArrayList<>(); nextSetasListOderConstraints = new ArrayList<>();
while (aParDefIt.hasNext()) { while (aParDefIt.hasNext()) {
Set<UnifyPair> a_new = aParDefIt.next(); Set<UnifyPair> a_new = aParDefIt.next();
@@ -204,9 +201,9 @@ public class VarianceM1Case extends VarianceCase {
erased.removeAll(notErased); erased.removeAll(notErased);
nextSetAsList.removeAll(erased); nextSetAsList.removeAll(erased);
context.logger().debug("Removed: " + erased); context.logger().debug(() -> "Removed: " + erased);
context.logger().debug("Not Removed: " + nextSetAsList); context.logger().debug(() -> "Not Removed: " + nextSetAsList);
} }
} else { } else {
@@ -217,9 +214,9 @@ public class VarianceM1Case extends VarianceCase {
nextSetAsList.removeAll(erased); nextSetAsList.removeAll(erased);
context.logger().debug("Removed: " + erased); context.logger().debug(() -> "Removed: " + erased);
context.logger().debug("Not Removed: " + nextSetAsList); context.logger().debug(() -> "Not Removed: " + nextSetAsList);
} }
} }

View File

@@ -1,6 +1,5 @@
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;
@@ -15,11 +14,12 @@ import java.util.Optional;
import java.util.Set; import java.util.Set;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
public class Variance2Case extends VarianceCase { public class InvarianceOrConstraintCase extends VarianceCase {
// either for invariance or for oderConstraints
protected final int variance = 2; protected final int variance = 2;
protected Variance2Case(boolean isOderConstraint, TypeUnifyTask typeUnifyTask, UnifyContext context) { protected InvarianceOrConstraintCase(boolean isOderConstraint, TypeUnifyTask typeUnifyTask, UnifyContext context) {
super(isOderConstraint, typeUnifyTask, context); super(isOderConstraint, typeUnifyTask, context);
} }
@@ -37,7 +37,7 @@ public class Variance2Case extends VarianceCase {
@Override @Override
public CompletableFuture<Tuple<Set<Set<UnifyPair>>, Set<Set<Set<UnifyPair>>>>> computeParallel( public CompletableFuture<ComputationResults> 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,8 +49,6 @@ public class Variance2Case 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>>>>> resultValuesFuture;
context.logger().debug("var2einstieg"); context.logger().debug("var2einstieg");
Set<TypeUnify2Task> forks = new HashSet<>(); Set<TypeUnify2Task> forks = new HashSet<>();
Set<UnifyPair> newEqOrig = new HashSet<>(eq); Set<UnifyPair> newEqOrig = new HashSet<>(eq);
@@ -60,19 +58,21 @@ public class Variance2Case extends VarianceCase {
/* FORK ANFANG */ /* FORK ANFANG */
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);
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);
resultValuesFuture = forkOrigFuture.thenApply((currentThreadResult) -> { CompletableFuture<ComputationResults> resultValues = forkOrigFuture.thenApply((currentThreadResult) -> {
forkOrig.context.logger().debug("final Orig 2"); forkOrig.context.logger().debug("final Orig 2");
forkOrig.closeLogFile(); forkOrig.closeLogFile();
return new Tuple<>(currentThreadResult, new HashSet<>()); return new ComputationResults(currentThreadResult);
}); });
if (typeUnifyTask.myIsCancelled()) {
throw new UnifyCancelException(); if (typeUnifyTask.isExecutionCancelled()) {
return resultValues;
} }
/* FORK ENDE */ /* FORK ENDE */
context.logger().debug("a in " + variance + " " + a); context.logger().debug(() -> "a in " + variance + " " + a);
context.logger().debug("nextSetasListRest: " + nextSetasListRest.toString()); context.logger().debug(() -> "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.
@@ -89,27 +89,24 @@ public class Variance2Case extends VarianceCase {
List<Set<Constraint<UnifyPair>>> newOderConstraints = new ArrayList<>(oderConstraints); List<Set<Constraint<UnifyPair>>> newOderConstraints = new ArrayList<>(oderConstraints);
newElems.add(nSaL); newElems.add(nSaL);
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);
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);
resultValuesFuture = resultValuesFuture.thenCombine(forkFuture, (resultValues, fork_res) -> { resultValues = resultValues.thenCombine(forkFuture, (prevResults, fork_res) -> {
if (typeUnifyTask.myIsCancelled()) { if (typeUnifyTask.isExecutionCancelled()) {
throw new UnifyCancelException(); return prevResults;
} }
resultValues.getSecond().add(fork_res); prevResults.addForkResult(fork_res);
fork.context.logger().debug("final 2"); fork.context.logger().debug("final 2");
fork.closeLogFile(); fork.closeLogFile();
return resultValues; return prevResults;
}); });
if (typeUnifyTask.myIsCancelled()) { if (typeUnifyTask.isExecutionCancelled()) {
throw new UnifyCancelException(); return resultValues;
} }
} }
if (typeUnifyTask.myIsCancelled()) { return resultValues;
throw new UnifyCancelException();
}
return resultValuesFuture;
} }
@Override @Override

View File

@@ -13,14 +13,13 @@ import java.util.List;
import java.util.Optional; 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.stream.Collectors; import java.util.stream.Collectors;
public class Variance0Case extends VarianceCase { public class UnknownVarianceCase extends VarianceCase {
protected final int variance = 0; protected final int variance = 0;
protected Variance0Case(boolean isOderConstraint, TypeUnifyTask typeUnifyTask, UnifyContext context) { protected UnknownVarianceCase(boolean isOderConstraint, TypeUnifyTask typeUnifyTask, UnifyContext context) {
super(isOderConstraint, typeUnifyTask, context); super(isOderConstraint, typeUnifyTask, context);
} }
@@ -50,7 +49,7 @@ public class Variance0Case extends VarianceCase {
} }
@Override @Override
public CompletableFuture<Tuple<Set<Set<UnifyPair>>, Set<Set<Set<UnifyPair>>>>> computeParallel( public CompletableFuture<ComputationResults> 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,
@@ -62,10 +61,9 @@ public class Variance0Case extends VarianceCase {
Set<Set<UnifyPair>> result, Set<Set<UnifyPair>> result,
Set<Set<UnifyPair>> aParDef Set<Set<UnifyPair>> aParDef
) { ) {
elems.add(a); //PL 2019-01-16 muss das wirklich hin steht schon in Zeile 859 ja braucht man siehe Zeile 859 elems.add(a);
return typeUnifyTask.unify2(elems, eq, oderConstraints, fc, context.parallel(), rekTiefe, new HashSet<>(methodSignatureConstraint)).thenApply( return typeUnifyTask.unify2(elems, eq, oderConstraints, fc, context.parallel(), rekTiefe, new HashSet<>(methodSignatureConstraint))
unify2Result -> new Tuple<>(unify2Result, new HashSet<>()) .thenApply(ComputationResults::new);
);
} }
@Override @Override
@@ -75,7 +73,7 @@ public class Variance0Case extends VarianceCase {
Set<UnifyPair> compResult, Set<UnifyPair> compResult,
Set<UnifyPair> compRes Set<UnifyPair> compRes
) { ) {
context.logger().debug("RES var=1 ADD:" + result.toString() + " " + currentThreadResult.toString()); context.logger().debug("RES var=0 ADD:" + result.toString() + " " + currentThreadResult.toString());
result.addAll(currentThreadResult); result.addAll(currentThreadResult);
} }

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,10 +17,10 @@ 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 Variance0Case(isOderConstraint, typeUnifyTask, context); case 0 -> new UnknownVarianceCase(isOderConstraint, typeUnifyTask, context);
case 1 -> new Variance1Case(isOderConstraint, typeUnifyTask, context); case 1 -> new ContravarianceCase(isOderConstraint, typeUnifyTask, context);
case -1 -> new VarianceM1Case(isOderConstraint, typeUnifyTask, context); case -1 -> new CovarianceCase(isOderConstraint, typeUnifyTask, context);
case 2 -> new Variance2Case(isOderConstraint, typeUnifyTask, context); case 2 -> new InvarianceOrConstraintCase(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<Tuple<Set<Set<UnifyPair>>, Set<Set<Set<UnifyPair>>>>> computeParallel( public abstract CompletableFuture<ComputationResults> 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,
@@ -104,4 +104,29 @@ public abstract class VarianceCase {
Set<Set<UnifyPair>> aParDef, Set<Set<UnifyPair>> aParDef,
List<Set<UnifyPair>> nextSetAsList List<Set<UnifyPair>> nextSetAsList
); );
/**
* Wrapper class for the parallel computation results
*/
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);
}
}
} }

View File

@@ -13,14 +13,11 @@ import de.dhbwstuttgart.typeinference.unify.model.UnifyType;
public class distributeVariance extends visitUnifyTypeVisitor<Integer> { public class distributeVariance extends visitUnifyTypeVisitor<Integer> {
public static int inverseVariance(int variance) { public static int inverseVariance(int variance) {
Integer ret = 0; return switch (variance) {
if (variance == 1) { case 1 -> -1;
ret = -1; case -1 -> 1;
} default -> 0;
if (variance == -1) { };
ret = 1;
}
return ret;
} }
@@ -42,7 +39,7 @@ public class distributeVariance extends visitUnifyTypeVisitor<Integer> {
List<UnifyType> param = new ArrayList<>(funnty.getTypeParams().get().length); List<UnifyType> param = new ArrayList<>(funnty.getTypeParams().get().length);
param.addAll(Arrays.asList(funnty.getTypeParams().get())); param.addAll(Arrays.asList(funnty.getTypeParams().get()));
UnifyType resultType = param.remove(param.size()-1); UnifyType resultType = param.remove(param.size()-1);
Integer htInverse = inverseVariance(ht); int htInverse = inverseVariance(ht);
param = param.stream() param = param.stream()
.map(x -> x.accept(this, htInverse)) .map(x -> x.accept(this, htInverse))
.collect(Collectors.toCollection(ArrayList::new)); .collect(Collectors.toCollection(ArrayList::new));

View File

@@ -1,14 +1,17 @@
package de.dhbwstuttgart.typeinference.unify.model; package de.dhbwstuttgart.typeinference.unify.model;
import de.dhbwstuttgart.parser.scope.JavaClassName;
import de.dhbwstuttgart.server.packet.dataContainers.ISerializableData; 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.PlaceholderRegistry; import de.dhbwstuttgart.typeinference.unify.PlaceholderRegistry;
import de.dhbwstuttgart.typeinference.unify.TypeUnifyTaskHelper;
import de.dhbwstuttgart.typeinference.unify.UnifyContext; import de.dhbwstuttgart.typeinference.unify.UnifyContext;
import de.dhbwstuttgart.util.Logger; import de.dhbwstuttgart.util.Logger;
import java.io.IOException; import java.io.IOException;
import java.io.Writer; import java.io.Writer;
import java.util.*;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
@@ -36,15 +39,16 @@ import org.antlr.v4.runtime.Token;
/** /**
* The finite closure for the type unification * The finite closure for the type unification
*
* @author Florian Steurer * @author Florian Steurer
*/ */
public class FiniteClosure implements IFiniteClosure, ISerializableData { public class FiniteClosure //extends Ordering<UnifyType> //entfernt PL 2018-12-11
implements IFiniteClosure, ISerializableData {
final JavaTXCompiler compiler; final JavaTXCompiler compiler;
final PlaceholderRegistry placeholderRegistry; final PlaceholderRegistry placeholderRegistry;
Logger logger; Logger logger;
/** /**
* A map that maps every type to the node in the inheritance graph that contains that type. * A map that maps every type to the node in the inheritance graph that contains that type.
*/ */
@@ -94,7 +98,7 @@ public class FiniteClosure implements IFiniteClosure, ISerializableData {
} }
*/ */
if(pair.getPairOp() != PairOperator.SMALLER) if (pair.getPairOp() != PairOperator.SMALLER)
continue; continue;
//VERSUCH PL 18-02-06 //VERSUCH PL 18-02-06
@@ -103,11 +107,11 @@ public class FiniteClosure implements IFiniteClosure, ISerializableData {
//if (!pair.getLhsType().getTypeParams().arePlaceholders() //if (!pair.getLhsType().getTypeParams().arePlaceholders()
// && !pair.getRhsType().getTypeParams().arePlaceholders()) // && !pair.getRhsType().getTypeParams().arePlaceholders())
// continue; // continue;
; ;
// Add nodes if not already in the graph // Add nodes if not already in the graph
if(!inheritanceGraph.containsKey(pair.getLhsType())) if (!inheritanceGraph.containsKey(pair.getLhsType()))
inheritanceGraph.put(pair.getLhsType(), new Node<UnifyType>(pair.getLhsType())); inheritanceGraph.put(pair.getLhsType(), new Node<UnifyType>(pair.getLhsType()));
if(!inheritanceGraph.containsKey(pair.getRhsType())) if (!inheritanceGraph.containsKey(pair.getRhsType()))
inheritanceGraph.put(pair.getRhsType(), new Node<UnifyType>(pair.getRhsType())); inheritanceGraph.put(pair.getRhsType(), new Node<UnifyType>(pair.getRhsType()));
Node<UnifyType> childNode = inheritanceGraph.get(pair.getLhsType()); Node<UnifyType> childNode = inheritanceGraph.get(pair.getLhsType());
@@ -121,12 +125,54 @@ public class FiniteClosure implements IFiniteClosure, ISerializableData {
childNode.getDescendants().stream().forEach(x -> x.addPredecessor(parentNode)); childNode.getDescendants().stream().forEach(x -> x.addPredecessor(parentNode));
//PL eingefuegt 2020-05-07 File UnitTest InheritTest.java //PL eingefuegt 2020-05-07 File UnitTest InheritTest.java
this.inheritanceGraph.forEach((x,y) -> { if (y.getDescendants().contains(parentNode)) { y.addDescendant(childNode); y.addAllDescendant(childNode.getDescendants());}; this.inheritanceGraph.forEach((x, y) -> {
if (y.getPredecessors().contains(childNode)) { y.addPredecessor(parentNode); y.addAllPredecessor(parentNode.getPredecessors());};} ); if (y.getDescendants().contains(parentNode)) {
y.addDescendant(childNode);
y.addAllDescendant(childNode.getDescendants());
}
;
if (y.getPredecessors().contains(childNode)) {
y.addPredecessor(parentNode);
y.addAllPredecessor(parentNode.getPredecessors());
}
;
});
}
List<String> classesToKeep = (compiler == null) ? new ArrayList<>() :
new ArrayList<>(compiler.classRegistry.getAllClassNames().stream().map(JavaClassName::toString).toList());
classesToKeep.add("java.lang.Object");
classesToKeep.add("java.lang.Number");
classesToKeep.add("java.util.Collection");
classesToKeep.add("java.lang.Iterable");
//filter out all types not imported
Iterator<Map.Entry<UnifyType, Node<UnifyType>>> iterator = inheritanceGraph.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<UnifyType, Node<UnifyType>> entry = iterator.next();
var name = entry.getKey().getName();
if (!classesToKeep.contains(name)) {
iterator.remove();
} else {
Node<UnifyType> node = entry.getValue();
// Remove unwanted predecessors
node.getPredecessors().removeIf(pred ->
!classesToKeep.contains(pred.getContent().getName())
);
// Remove unwanted descendants
node.getDescendants().removeIf(desc ->
!classesToKeep.contains(desc.getContent().getName())
);
}
} }
// Build the alternative representation with strings as keys // Build the alternative representation with strings as keys
strInheritanceGraph = new HashMap<>(); strInheritanceGraph = TypeUnifyTaskHelper.getPresizedHashMap(inheritanceGraph.size());
for(UnifyType key : inheritanceGraph.keySet()) { for(UnifyType key : inheritanceGraph.keySet()) {
if(!strInheritanceGraph.containsKey(key.getName())) if(!strInheritanceGraph.containsKey(key.getName()))
strInheritanceGraph.put(key.getName(), new HashSet<>()); strInheritanceGraph.put(key.getName(), new HashSet<>());
@@ -153,6 +199,7 @@ public class FiniteClosure implements IFiniteClosure, ISerializableData {
/** /**
* Returns all types of the finite closure that are subtypes of the argument. * Returns all types of the finite closure that are subtypes of the argument.
*
* @return The set of subtypes of the argument. * @return The set of subtypes of the argument.
*/ */
@Override @Override
@@ -164,10 +211,10 @@ public class FiniteClosure implements IFiniteClosure, ISerializableData {
return new HashSet<>(ret); return new HashSet<>(ret);
} }
if(type instanceof FunNType) if (type instanceof FunNType)
return computeSmallerFunN((FunNType) type, fBounded); return computeSmallerFunN((FunNType) type, fBounded);
Set<Pair<UnifyType,Set<UnifyType>>> ts = new HashSet<>(); Set<Pair<UnifyType, Set<UnifyType>>> ts = new HashSet<>();
ts.add(new Pair<>(type, fBounded)); ts.add(new Pair<>(type, fBounded));
Set<UnifyType> result = computeSmaller(ts); Set<UnifyType> result = computeSmaller(ts);
smallerHash.put(new hashKeyType(type), result); smallerHash.put(new hashKeyType(type), result);
@@ -199,34 +246,33 @@ public class FiniteClosure implements IFiniteClosure, ISerializableData {
// if T = T' then T <* T' // if T = T' then T <* T'
try { try {
result.add(new Pair<>(t, fBounded)); result.add(new Pair<>(t, fBounded));
} } catch (StackOverflowError e) {
catch (StackOverflowError e) { //System.out.println("");
// context.logger().info("");
} }
// if C<...> <* C<...> then ... (third case in definition of <*) // if C<...> <* C<...> then ... (third case in definition of <*)
if(t.getTypeParams().size() > 0) { if (t.getTypeParams().size() > 0) {
ArrayList<Set<UnifyType>> paramCandidates = new ArrayList<>(); ArrayList<Set<UnifyType>> paramCandidates = new ArrayList<>();
for (int i = 0; i < t.getTypeParams().size(); i++) for (int i = 0; i < t.getTypeParams().size(); i++)
paramCandidates.add(smArg(t.getTypeParams().get(i), fBounded)); paramCandidates.add(smArg(t.getTypeParams().get(i), fBounded));
permuteParams(paramCandidates).forEach(x -> result.add(new Pair<>(t.setTypeParams(x), fBounded))); permuteParams(paramCandidates).forEach(x -> result.add(new Pair<>(t.setTypeParams(x), fBounded)));
} }
if(!strInheritanceGraph.containsKey(t.getName())) if (!strInheritanceGraph.containsKey(t.getName()))
continue; continue;
// if T <* T' then sigma(T) <* sigma(T') // if T <* T' then sigma(T) <* sigma(T')
Set<Node<UnifyType>> candidates = strInheritanceGraph.get(t.getName()); //cadidates= [???Node(java.util.Vector<java.util.Vector<java.lang.Integer>>)??? Set<Node<UnifyType>> candidates = strInheritanceGraph.get(t.getName()); //cadidates= [???Node(java.util.Vector<java.util.Vector<java.lang.Integer>>)???
// , Node(java.util.Vector<gen_hv>) // , Node(java.util.Vector<gen_hv>)
//] //]
for(Node<UnifyType> candidate : candidates) { for (Node<UnifyType> candidate : candidates) {
UnifyType theta2 = candidate.getContent(); UnifyType theta2 = candidate.getContent();
//PL 18-02-05 Unifier durch Matcher ersetzt ANFANG //PL 18-02-05 Unifier durch Matcher ersetzt ANFANG
ArrayList<UnifyPair> termList= new ArrayList<UnifyPair>(); ArrayList<UnifyPair> termList = new ArrayList<UnifyPair>();
termList.add(new UnifyPair(theta2,t, PairOperator.EQUALSDOT)); termList.add(new UnifyPair(theta2, t, PairOperator.EQUALSDOT));
Optional<Unifier> optSigma = match.match(termList); Optional<Unifier> optSigma = match.match(termList);
//PL 18-02-05 Unifier durch Matcher ersetzt ENDE //PL 18-02-05 Unifier durch Matcher ersetzt ENDE
if(!optSigma.isPresent()) if (optSigma.isEmpty())
continue; continue;
Unifier sigma = optSigma.get(); Unifier sigma = optSigma.get();
@@ -234,13 +280,13 @@ public class FiniteClosure implements IFiniteClosure, ISerializableData {
Set<UnifyType> theta1Set = candidate.getContentOfDescendants(); Set<UnifyType> theta1Set = candidate.getContentOfDescendants();
for(UnifyType theta1 : theta1Set) for (UnifyType theta1 : theta1Set)
result.add(new Pair<>(theta1.apply(sigma), fBounded)); result.add(new Pair<>(theta1.apply(sigma), fBounded));
} }
} }
HashSet<UnifyType> resut = result.stream().map(x -> x.getKey()).collect(Collectors.toCollection(HashSet::new)); HashSet<UnifyType> resut = result.stream().map(x -> x.getKey()).collect(Collectors.toCollection(HashSet::new));
if(resut.equals(types.stream().map(x -> x.getKey()).collect(Collectors.toCollection(HashSet::new)))) if (resut.equals(types.stream().map(x -> x.getKey()).collect(Collectors.toCollection(HashSet::new))))
return resut; return resut;
return computeSmaller(result); return computeSmaller(result);
} }
@@ -272,26 +318,26 @@ public class FiniteClosure implements IFiniteClosure, ISerializableData {
@Override @Override
//Eingefuegt PL 2018-05-24 F-Bounded Problematik //Eingefuegt PL 2018-05-24 F-Bounded Problematik
public Set<UnifyType> greater(UnifyType type, Set<UnifyType> fBounded, SourceLoc location) { public Set<UnifyType> greater(UnifyType type, Set<UnifyType> fBounded, SourceLoc location) {
Set<UnifyType> ret; Set<UnifyType> ret = greaterHash.get(new hashKeyType(type));
if ((ret = greaterHash.get(new hashKeyType(type))) != null) { if (ret != null) {
//context.logger().info(greaterHash); //context.logger().info(greaterHash);
return new HashSet<>(ret); return new HashSet<>(ret);
} }
if(type instanceof FunNType) { if (type instanceof FunNType) {
return computeGreaterFunN((FunNType) type, fBounded); return computeGreaterFunN((FunNType) type, fBounded);
} }
Set<UnifyType> result = new HashSet<>(); Set<UnifyType> result = new HashSet<>();
Set<Pair<UnifyType,Set<UnifyType>>> PairResultFBounded = new HashSet<>(); Set<Pair<UnifyType, Set<UnifyType>>> PairResultFBounded = new HashSet<>();
Match match = new Match(); Match match = new Match();
// if T = T' then T <=* T' // if T = T' then T <=* T'
result.add(type); result.add(type);
if(!strInheritanceGraph.containsKey(type.getName())) if (!strInheritanceGraph.containsKey(type.getName()))
return result; return result;
// if T <* T' then sigma(T) <* sigma(T') // if T <* T' then sigma(T) <* sigma(T')
@@ -307,15 +353,15 @@ public class FiniteClosure implements IFiniteClosure, ISerializableData {
} }
*/ */
for(Node<UnifyType> candidate : candidates) { for (Node<UnifyType> candidate : candidates) {
UnifyType theta1 = candidate.getContent(); UnifyType theta1 = candidate.getContent();
//PL 18-04-05 Unifier durch Matcher ersetzt ANFANG //PL 18-04-05 Unifier durch Matcher ersetzt ANFANG
ArrayList<UnifyPair> termList= new ArrayList<UnifyPair>(); ArrayList<UnifyPair> termList = new ArrayList<UnifyPair>();
termList.add(new UnifyPair(theta1,type, PairOperator.EQUALSDOT, location)); termList.add(new UnifyPair(theta1, type, PairOperator.EQUALSDOT, location));
Optional<Unifier> optSigma = match.match(termList); Optional<Unifier> optSigma = match.match(termList);
//PL 18-04-05 Unifier durch Matcher ersetzt ENDE //PL 18-04-05 Unifier durch Matcher ersetzt ENDE
if(!optSigma.isPresent()) { if (optSigma.isEmpty()) {
continue; continue;
} }
Unifier sigma = optSigma.get(); Unifier sigma = optSigma.get();
@@ -325,7 +371,7 @@ public class FiniteClosure implements IFiniteClosure, ISerializableData {
fBoundedNew.add(theta1); fBoundedNew.add(theta1);
Set<UnifyType> theta2Set = candidate.getContentOfPredecessors(); Set<UnifyType> theta2Set = candidate.getContentOfPredecessors();
//context.logger().info(""); //context.logger().info("");
for(UnifyType theta2 : theta2Set) { for (UnifyType theta2 : theta2Set) {
result.add(theta2.apply(sigma)); result.add(theta2.apply(sigma));
PairResultFBounded.add(new Pair<>(theta2.apply(sigma), fBoundedNew)); PairResultFBounded.add(new Pair<>(theta2.apply(sigma), fBoundedNew));
} }
@@ -345,13 +391,13 @@ public class FiniteClosure implements IFiniteClosure, ISerializableData {
// if C<...> <* C<...> then ... (third case in definition of <*) // if C<...> <* C<...> then ... (third case in definition of <*)
//TypeParams typeparams = t.getTypeParams(); //TypeParams typeparams = t.getTypeParams();
if(t.getTypeParams().size() > 0) { if (t.getTypeParams().size() > 0) {
ArrayList<Set<UnifyType>> paramCandidates = new ArrayList<>(); ArrayList<Set<UnifyType>> paramCandidates = new ArrayList<>();
for (int i = 0; i < t.getTypeParams().size(); i++) { for (int i = 0; i < t.getTypeParams().size(); i++) {
//UnifyType parai = t.getTypeParams().get(i); //UnifyType parai = t.getTypeParams().get(i);
int i_ef = i; int i_ef = i;
BiFunction<Boolean,UnifyType,Boolean> f = (x,y) -> BiFunction<Boolean, UnifyType, Boolean> f = (x, y) ->
{ {
ArrayList<UnifyPair> termList = new ArrayList<UnifyPair>(); ArrayList<UnifyPair> termList = new ArrayList<UnifyPair>();
termList.add(new UnifyPair(y,t.getTypeParams().get(i_ef), PairOperator.EQUALSDOT, location)); termList.add(new UnifyPair(y,t.getTypeParams().get(i_ef), PairOperator.EQUALSDOT, location));
@@ -365,8 +411,7 @@ public class FiniteClosure implements IFiniteClosure, ISerializableData {
//F-Bounded Endlosrekursion //F-Bounded Endlosrekursion
HashSet<UnifyType> res = new HashSet<UnifyType>(); HashSet<UnifyType> res = new HashSet<UnifyType>();
paramCandidates.add(res); paramCandidates.add(res);
} } else {
else {
paramCandidates.add(grArg(t.getTypeParams().get(i), new HashSet<>(fBounded) )); paramCandidates.add(grArg(t.getTypeParams().get(i), new HashSet<>(fBounded) ));
} }
} }
@@ -507,34 +552,40 @@ public class FiniteClosure implements IFiniteClosure, ISerializableData {
Set<UnifyType> result = new HashSet<UnifyType>(); Set<UnifyType> result = new HashSet<UnifyType>();
result.add(type); result.add(type);
smaller(type, fBounded).forEach(x -> result.add(new SuperType(x))); smaller(type, fBounded).forEach(x -> result.add(new SuperType(x)));
greater(type,fBounded).forEach(x -> result.add(new ExtendsType(x)));
return result;
}
@Override
public Set<UnifyType> grArg(FunNType type, Set<UnifyType> fBounded) {
Set<UnifyType> result = new HashSet<UnifyType>();
result.add(type);
smaller(type, fBounded).forEach(x -> result.add(new SuperType(x)));
greater(type, fBounded).forEach(x -> result.add(new ExtendsType(x))); greater(type, fBounded).forEach(x -> result.add(new ExtendsType(x)));
return result; return result;
} }
@Override @Override
public Set<UnifyType> grArg(ExtendsType type, Set<UnifyType> fBounded) { public Set<UnifyType> grArg(FunNType type, Set<UnifyType> fBounded) {
Set<UnifyType> result = new HashSet<UnifyType>(); Set<UnifyType> smaller = smaller(type, fBounded);
Set<UnifyType> greater = greater(type, fBounded);
Set<UnifyType> result = TypeUnifyTaskHelper.getPresizedHashSet(1 + smaller.size() + greater.size());
result.add(type); result.add(type);
smaller.forEach(x -> result.add(new SuperType(x)));
greater.forEach(x -> result.add(new ExtendsType(x)));
return result;
}
@Override
public Set<UnifyType> grArg(ExtendsType type, Set<UnifyType> fBounded) {
UnifyType t = type.getExtendedType(); UnifyType t = type.getExtendedType();
greater(t, fBounded).forEach(x -> result.add(new ExtendsType(x))); Set<UnifyType> greater = greater(t, fBounded);
Set<UnifyType> result = TypeUnifyTaskHelper.getPresizedHashSet(1 + greater.size());
result.add(type);
greater.forEach(x -> result.add(new ExtendsType(x)));
return result; return result;
} }
@Override @Override
public Set<UnifyType> grArg(SuperType type, Set<UnifyType> fBounded) { public Set<UnifyType> grArg(SuperType type, Set<UnifyType> fBounded) {
Set<UnifyType> result = new HashSet<UnifyType>();
result.add(type);
UnifyType t = type.getSuperedType(); UnifyType t = type.getSuperedType();
smaller(t, fBounded).forEach(x -> result.add(new SuperType(x))); Set<UnifyType> smaller = smaller(t, fBounded);
Set<UnifyType> result = TypeUnifyTaskHelper.getPresizedHashSet(1 + smaller.size());
result.add(type);
smaller.forEach(x -> result.add(new SuperType(x)));
return result; return result;
} }
@@ -566,11 +617,13 @@ public class FiniteClosure implements IFiniteClosure, ISerializableData {
@Override @Override
public Set<UnifyType> smArg(ExtendsType type, Set<UnifyType> fBounded) { public Set<UnifyType> smArg(ExtendsType type, Set<UnifyType> fBounded) {
Set<UnifyType> result = new HashSet<UnifyType>();
result.add(type);
UnifyType t = type.getExtendedType(); UnifyType t = type.getExtendedType();
Set<UnifyType> smaller = smaller(t, fBounded);
Set<UnifyType> result = TypeUnifyTaskHelper.getPresizedHashSet(2 * (1 + smaller.size()));
result.add(type);
result.add(t); result.add(t);
smaller(t, fBounded).forEach(x -> { smaller.forEach(x -> {
result.add(new ExtendsType(x)); result.add(new ExtendsType(x));
result.add(x); result.add(x);
}); });
@@ -580,12 +633,14 @@ public class FiniteClosure implements IFiniteClosure, ISerializableData {
@Override @Override
public Set<UnifyType> smArg(SuperType type, Set<UnifyType> fBounded) { public Set<UnifyType> smArg(SuperType type, Set<UnifyType> fBounded) {
Set<UnifyType> result = new HashSet<UnifyType>();
result.add(type);
UnifyType t = type.getSuperedType(); UnifyType t = type.getSuperedType();
Set<UnifyType> greater = greater(t, fBounded);
Set<UnifyType> result = TypeUnifyTaskHelper.getPresizedHashSet(2 * (1 + greater.size()));
result.add(type);
result.add(t); result.add(t);
//*** ACHTUNG das koennte FALSCH sein PL 2018-05-23 evtl. HashSet durch smArg durchschleifen //*** ACHTUNG das koennte FALSCH sein PL 2018-05-23 evtl. HashSet durch smArg durchschleifen
greater(t, fBounded).forEach(x -> { greater.forEach(x -> {
result.add(new SuperType(x)); result.add(new SuperType(x));
result.add(x); result.add(x);
}); });
@@ -601,18 +656,18 @@ public class FiniteClosure implements IFiniteClosure, ISerializableData {
@Override @Override
public Set<UnifyType> getAllTypesByName(String typeName) { public Set<UnifyType> getAllTypesByName(String typeName) {
if(!strInheritanceGraph.containsKey(typeName)) if (!strInheritanceGraph.containsKey(typeName))
return new HashSet<>(); return new HashSet<>();
return strInheritanceGraph.get(typeName).stream().map(x -> x.getContent()).collect(Collectors.toCollection(HashSet::new)); return strInheritanceGraph.get(typeName).stream().map(x -> x.getContent()).collect(Collectors.toCollection(HashSet::new));
} }
@Override @Override
public Optional<UnifyType> getLeftHandedType(String typeName) { public Optional<UnifyType> getLeftHandedType(String typeName) {
if(!strInheritanceGraph.containsKey(typeName)) if (!strInheritanceGraph.containsKey(typeName))
return Optional.empty(); return Optional.empty();
for(UnifyPair pair : pairs) for (UnifyPair pair : pairs)
if(pair.getLhsType().getName().equals(typeName) && pair.getLhsType().typeParams.arePlaceholders()) if (pair.getLhsType().getName().equals(typeName) && pair.getLhsType().typeParams.arePlaceholders())
return Optional.of(pair.getLhsType()); return Optional.of(pair.getLhsType());
return Optional.empty(); return Optional.empty();
@@ -620,11 +675,11 @@ public class FiniteClosure implements IFiniteClosure, ISerializableData {
@Override @Override
public Optional<UnifyType> getRightHandedFunctionalInterfaceType(String typeName) { public Optional<UnifyType> getRightHandedFunctionalInterfaceType(String typeName) {
if(!strInheritanceGraph.containsKey(typeName)) if (!strInheritanceGraph.containsKey(typeName))
return Optional.empty(); return Optional.empty();
for(UnifyPair pair : pairs) for (UnifyPair pair : pairs)
if(pair.getRhsType().getName().equals(typeName)) if (pair.getRhsType().getName().equals(typeName))
return Optional.of(pair.getRhsType()); return Optional.of(pair.getRhsType());
return Optional.empty(); return Optional.empty();
@@ -632,7 +687,7 @@ public class FiniteClosure implements IFiniteClosure, ISerializableData {
@Override @Override
public Set<UnifyType> getAncestors(UnifyType t) { public Set<UnifyType> getAncestors(UnifyType t) {
if(!inheritanceGraph.containsKey(t)) if (!inheritanceGraph.containsKey(t))
return new HashSet<>(); return new HashSet<>();
Set<UnifyType> result = inheritanceGraph.get(t).getContentOfPredecessors(); Set<UnifyType> result = inheritanceGraph.get(t).getContentOfPredecessors();
result.add(t); result.add(t);
@@ -641,7 +696,7 @@ public class FiniteClosure implements IFiniteClosure, ISerializableData {
@Override @Override
public Set<UnifyType> getChildren(UnifyType t) { public Set<UnifyType> getChildren(UnifyType t) {
if(!inheritanceGraph.containsKey(t)) if (!inheritanceGraph.containsKey(t))
return new HashSet<>(); return new HashSet<>();
Set<UnifyType> result = inheritanceGraph.get(t).getContentOfDescendants(); Set<UnifyType> result = inheritanceGraph.get(t).getContentOfDescendants();
result.add(t); result.add(t);
@@ -650,6 +705,7 @@ public class FiniteClosure implements IFiniteClosure, ISerializableData {
/** /**
* Takes a set of candidates for each position and computes all possible permutations. * Takes a set of candidates for each position and computes all possible permutations.
*
* @param candidates The length of the list determines the number of type params. Each set * @param candidates The length of the list determines the number of type params. Each set
* contains the candidates for the corresponding position. * contains the candidates for the corresponding position.
*/ */
@@ -661,6 +717,7 @@ public class FiniteClosure implements IFiniteClosure, ISerializableData {
/** /**
* Takes a set of candidates for each position and computes all possible permutations. * Takes a set of candidates for each position and computes all possible permutations.
*
* @param candidates The length of the list determines the number of type params. Each set * @param candidates The length of the list determines the number of type params. Each set
* contains the candidates for the corresponding position. * contains the candidates for the corresponding position.
* @param idx Idx for the current permutatiton. * @param idx Idx for the current permutatiton.
@@ -668,21 +725,21 @@ public class FiniteClosure implements IFiniteClosure, ISerializableData {
* @param current The permutation of type params that is currently explored * @param current The permutation of type params that is currently explored
*/ */
protected void permuteParams(ArrayList<Set<UnifyType>> candidates, int idx, Set<TypeParams> result, UnifyType[] current) { protected void permuteParams(ArrayList<Set<UnifyType>> candidates, int idx, Set<TypeParams> result, UnifyType[] current) {
if(candidates.size() == idx) { if (candidates.size() == idx) {
result.add(new TypeParams(Arrays.copyOf(current, current.length))); result.add(new TypeParams(Arrays.copyOf(current, current.length)));
return; return;
} }
Set<UnifyType> localCandidates = candidates.get(idx); Set<UnifyType> localCandidates = candidates.get(idx);
for(UnifyType t : localCandidates) { for (UnifyType t : localCandidates) {
current[idx] = t; current[idx] = t;
permuteParams(candidates, idx+1, result, current); permuteParams(candidates, idx + 1, result, current);
} }
} }
@Override @Override
public String toString(){ public String toString() {
return this.inheritanceGraph.toString(); return this.inheritanceGraph.toString();
} }
@@ -693,9 +750,10 @@ public class FiniteClosure implements IFiniteClosure, ISerializableData {
*/ */
public int compare (UnifyType left, UnifyType right, PairOperator pairop, UnifyContext context) { public int compare (UnifyType left, UnifyType right, PairOperator pairop, UnifyContext context) {
logger.debug("left: "+ left + " right: " + right + " pairop: " + pairop +"\n"); logger.debug(() -> "left: " + left + " right: " + right + " pairop: " + pairop +"\n");
// if (left.getName().equals("Matrix") || right.getName().equals("Matrix")) //if (left.getName().equals("Matrix") || right.getName().equals("Matrix"))
// context.logger().info(""); // context.logger().info("");
/* /*
pairop = PairOperator.SMALLERDOTWC; pairop = PairOperator.SMALLERDOTWC;
List<UnifyType> al = new ArrayList<>(); List<UnifyType> al = new ArrayList<>();
@@ -727,21 +785,19 @@ public class FiniteClosure implements IFiniteClosure, ISerializableData {
UnifyType ex; UnifyType ex;
if (left instanceof PlaceholderType) { if (left instanceof PlaceholderType) {
if ((right instanceof WildcardType) if ((right instanceof WildcardType)
&& ((ex = ((WildcardType)right).wildcardedType) instanceof PlaceholderType) && ((ex = ((WildcardType) right).wildcardedType) instanceof PlaceholderType)
&& ((PlaceholderType)left).getName().equals(((PlaceholderType)ex).getName())) {// a <.? ? extends a oder a <.? ? super a && ((PlaceholderType) left).getName().equals(((PlaceholderType) ex).getName())) {// a <.? ? extends a oder a <.? ? super a
return -1; return -1;
} } else {
else {
return 0; return 0;
} }
} }
if (right instanceof PlaceholderType) {//&& (left instanceof WildcardType)) {PL geloescht 2019-01-15 analog zu oben if (right instanceof PlaceholderType) {//&& (left instanceof WildcardType)) {PL geloescht 2019-01-15 analog zu oben
if ((left instanceof WildcardType) //PL eingefuegt 2019-01-15 analog zu oben if ((left instanceof WildcardType) //PL eingefuegt 2019-01-15 analog zu oben
&& ((ex = ((WildcardType)left).wildcardedType) instanceof PlaceholderType) && ((ex = ((WildcardType)left).wildcardedType) instanceof PlaceholderType)
&& ((PlaceholderType)right).getName().equals(((PlaceholderType)ex).getName())) {// ? extends a <. a oder ? super a <. a && ((PlaceholderType)right).getName().equals(((PlaceholderType) ex).getName())) {// ? extends a <. a oder ? super a <. a
return 1; return 1;
} } else {
else {
return 0; return 0;
} }
} }
@@ -752,16 +808,17 @@ public class FiniteClosure implements IFiniteClosure, ISerializableData {
Set<UnifyPair> smallerRes = unifyTask.applyTypeUnificationRules(hs, this); Set<UnifyPair> smallerRes = unifyTask.applyTypeUnificationRules(hs, this);
//if (left.getName().equals("Vector") || right.getName().equals("AbstractList")) //if (left.getName().equals("Vector") || right.getName().equals("AbstractList"))
logger.debug("\nsmallerRes: " + smallerRes);//"smallerHash: " + greaterHash.toString()); logger.debug(() -> "\nsmallerRes: " + smallerRes); //"smallerHash: " + greaterHash.toString());
//Gleichungen der Form a <./=. Theta oder Theta <./=. a oder a <./=. b sind ok. //Gleichungen der Form a <./=. Theta oder Theta <./=. a oder a <./=. b sind ok.
Predicate<UnifyPair> delFun = x -> !((x.getLhsType() instanceof PlaceholderType || Predicate<UnifyPair> delFun = x -> !((x.getLhsType() instanceof PlaceholderType ||
x.getRhsType() instanceof PlaceholderType) x.getRhsType() instanceof PlaceholderType)
&& !((x.getLhsType() instanceof WildcardType) && //? extends/super a <.? a && !((x.getLhsType() instanceof WildcardType) && //? extends/super a <.? a
((WildcardType)x.getLhsType()).getWildcardedType().equals(x.getRhsType())) ((WildcardType) x.getLhsType()).getWildcardedType().equals(x.getRhsType()))
); );
long smallerLen = smallerRes.stream().filter(delFun).count(); long smallerLen = smallerRes.stream().filter(delFun).count();
logger.debug("\nsmallerLen: " + smallerLen +"\n"); logger.debug(() -> "\nsmallerLen: " + smallerLen + "\n");
if (smallerLen == 0) return -1; if (smallerLen == 0) return -1;
else { else {
up = new UnifyPair(right, left, pairop); up = new UnifyPair(right, left, pairop);
@@ -771,7 +828,7 @@ public class FiniteClosure implements IFiniteClosure, ISerializableData {
Set<UnifyPair> greaterRes = unifyTask.applyTypeUnificationRules(hs, this); Set<UnifyPair> greaterRes = unifyTask.applyTypeUnificationRules(hs, this);
//if (left.getName().equals("Vector") || right.getName().equals("AbstractList")) //if (left.getName().equals("Vector") || right.getName().equals("AbstractList"))
logger.debug("\ngreaterRes: " + greaterRes);//"smallerHash: " + greaterHash.toString()); logger.debug(() -> "\ngreaterRes: " + greaterRes);//"smallerHash: " + greaterHash.toString());
//Gleichungen der Form a <./=. Theta oder Theta <./=. a oder a <./=. b sind ok. //Gleichungen der Form a <./=. Theta oder Theta <./=. a oder a <./=. b sind ok.
long greaterLen = greaterRes.stream().filter(delFun).count(); long greaterLen = greaterRes.stream().filter(delFun).count();
@@ -795,5 +852,4 @@ public class FiniteClosure implements IFiniteClosure, ISerializableData {
.map(pairData -> UnifyPair.fromSerial(pairData, context, keyStorage)).collect(Collectors.toSet()); .map(pairData -> UnifyPair.fromSerial(pairData, context, keyStorage)).collect(Collectors.toSet());
return new FiniteClosure(pairs, context.logger(), context.placeholderRegistry()); return new FiniteClosure(pairs, context.logger(), context.placeholderRegistry());
} }
} }

View File

@@ -81,7 +81,7 @@ public class FunNType extends UnifyType implements ISerializableData {
} }
@Override @Override
public Boolean wrongWildcard() { public boolean wrongWildcard() {
return (new ArrayList<UnifyType>(Arrays.asList(getTypeParams() return (new ArrayList<UnifyType>(Arrays.asList(getTypeParams()
.get())).stream().filter(x -> (x instanceof WildcardType)).findFirst().isPresent()); .get())).stream().filter(x -> (x instanceof WildcardType)).findFirst().isPresent());
} }

View File

@@ -48,7 +48,7 @@ public class OrderingUnifyPair extends OrderingExtend<Set<UnifyPair>> {
return fc.compare(left.getRhsType(), right.getRhsType(), PairOperator.SMALLERDOT, context); return fc.compare(left.getRhsType(), right.getRhsType(), PairOperator.SMALLERDOT, context);
}} }}
catch (ClassCastException e) { catch (ClassCastException e) {
((FiniteClosure)fc).logger.debug("ClassCastException: " + left.toString() + " " + left.getGroundBasePair() + "\n\n"); ((FiniteClosure)fc).logger.debug(() -> "ClassCastException: " + left.toString() + " " + left.getGroundBasePair() + "\n\n");
return -99; return -99;
} }
} }
@@ -171,29 +171,65 @@ public class OrderingUnifyPair extends OrderingExtend<Set<UnifyPair>> {
left.add(p4); left.add(p4);
*/ */
Set<UnifyPair> lefteq = new HashSet<>();
Set<UnifyPair> leftle = new HashSet<>();
Set<UnifyPair> leftlewc = new HashSet<>();
Set<UnifyPair> lefteqOder = new HashSet<>();
Set<UnifyPair> lefteqRet = new HashSet<>();
Set<UnifyPair> leftleOder = new HashSet<>();
for (var x : left) {
boolean isLeftPlaceholder = x.getLhsType() instanceof PlaceholderType;
boolean isRightPlaceholder = x.getRhsType() instanceof PlaceholderType;
boolean hasPlaceholder = isLeftPlaceholder || isRightPlaceholder;
if (isLeftPlaceholder && x.getPairOp() == PairOperator.EQUALSDOT) lefteq.add(x);
if (hasPlaceholder && x.getPairOp() == PairOperator.SMALLERDOT) leftle.add(x);
if (hasPlaceholder && x.getPairOp() == PairOperator.SMALLERDOTWC) leftlewc.add(x);
UnifyPair y = x.getGroundBasePair();
boolean isBasePairLeftPlaceholder = y.getLhsType() instanceof PlaceholderType;
boolean isBasePairRightPlaceholder = y.getRhsType() instanceof PlaceholderType;
if (isBasePairLeftPlaceholder && !isBasePairRightPlaceholder && x.getPairOp() == PairOperator.EQUALSDOT) {
lefteqOder.add(x);
}
else if (isBasePairRightPlaceholder && ((PlaceholderType)y.getRhsType()).getOrCons() == (byte)-1) {
lefteqRet.add(x);
}
else if (x.getPairOp() == PairOperator.SMALLERDOT) {
leftleOder.add(x);
}
}
Set<UnifyPair> righteq = new HashSet<>();
Set<UnifyPair> rightle = new HashSet<>();
Set<UnifyPair> rightlewc = new HashSet<>();
Set<UnifyPair> righteqOder = new HashSet<>();
Set<UnifyPair> righteqRet = new HashSet<>();
Set<UnifyPair> rightleOder = new HashSet<>();
for (var x : right) {
boolean isLeftPlaceholder = x.getLhsType() instanceof PlaceholderType;
boolean isRightPlaceholder = x.getRhsType() instanceof PlaceholderType;
boolean hasPlaceholder = isLeftPlaceholder || isRightPlaceholder;
if (isLeftPlaceholder && x.getPairOp() == PairOperator.EQUALSDOT) righteq.add(x);
if (hasPlaceholder && x.getPairOp() == PairOperator.SMALLERDOT) rightle.add(x);
if (hasPlaceholder && x.getPairOp() == PairOperator.SMALLERDOTWC) rightlewc.add(x);
UnifyPair y = x.getGroundBasePair();
boolean isBasePairLeftPlaceholder = y.getLhsType() instanceof PlaceholderType;
boolean isBasePairRightPlaceholder = y.getRhsType() instanceof PlaceholderType;
if (isBasePairLeftPlaceholder && !isBasePairRightPlaceholder && x.getPairOp() == PairOperator.EQUALSDOT) {
righteqOder.add(x);
}
else if (isBasePairRightPlaceholder && ((PlaceholderType)y.getRhsType()).getOrCons() == (byte)-1) {
righteqRet.add(x);
}
else if (x.getPairOp() == PairOperator.SMALLERDOT) {
rightleOder.add(x);
}
}
Set<UnifyPair> lefteq = left.stream()
.filter(x -> (x.getLhsType() instanceof PlaceholderType && x.getPairOp() == PairOperator.EQUALSDOT))
.collect(Collectors.toCollection(HashSet::new));
Set<UnifyPair> righteq = right.stream()
.filter(x -> (x.getLhsType() instanceof PlaceholderType && x.getPairOp() == PairOperator.EQUALSDOT))
.collect(Collectors.toCollection(HashSet::new));
Set<UnifyPair> leftle = left.stream()
.filter(x -> ((x.getLhsType() instanceof PlaceholderType || x.getRhsType() instanceof PlaceholderType)
&& x.getPairOp() == PairOperator.SMALLERDOT))
.collect(Collectors.toCollection(HashSet::new));
Set<UnifyPair> rightle = right.stream()
.filter(x -> ((x.getLhsType() instanceof PlaceholderType || x.getRhsType() instanceof PlaceholderType)
&& x.getPairOp() == PairOperator.SMALLERDOT))
.collect(Collectors.toCollection(HashSet::new));
Set<UnifyPair> leftlewc = left.stream()
.filter(x -> ((x.getLhsType() instanceof PlaceholderType || x.getRhsType() instanceof PlaceholderType)
&& x.getPairOp() == PairOperator.SMALLERDOTWC))
.collect(Collectors.toCollection(HashSet::new));
Set<UnifyPair> rightlewc = right.stream()
.filter(x -> ((x.getLhsType() instanceof PlaceholderType || x.getRhsType() instanceof PlaceholderType)
&& x.getPairOp() == PairOperator.SMALLERDOTWC))
.collect(Collectors.toCollection(HashSet::new));
//context.logger().info(left.toString()); //context.logger().info(left.toString());
//Fall 2 //Fall 2
//if (lefteq.iterator().next().getLhsType().getName().equals("AJO")) { //if (lefteq.iterator().next().getLhsType().getName().equals("AJO")) {
@@ -201,53 +237,13 @@ public class OrderingUnifyPair extends OrderingExtend<Set<UnifyPair>> {
//} //}
//ODER-CONSTRAINT //ODER-CONSTRAINT
Set<UnifyPair> leftBase = left.stream().map(x -> x.getGroundBasePair()).collect(Collectors.toCollection(HashSet::new)); // Set<UnifyPair> leftBase = left.stream().map(x -> x.getGroundBasePair()).collect(Collectors.toCollection(HashSet::new));
Set<UnifyPair> rightBase = right.stream().map(x -> x.getGroundBasePair()).collect(Collectors.toCollection(HashSet::new)); // Set<UnifyPair> rightBase = right.stream().map(x -> x.getGroundBasePair()).collect(Collectors.toCollection(HashSet::new));
Set<UnifyPair> lefteqOder = left.stream()
.filter(x -> { UnifyPair y = x.getGroundBasePair();
/*try {
((FiniteClosure)fc).logFile.write("leftBase: " + leftBase.toString() +"\n");
((FiniteClosure)fc).logFile.write("rightBase: " + rightBase.toString() +"\n\n");
((FiniteClosure)fc).logFile.write("left: " + left.toString() +"\n");
((FiniteClosure)fc).logFile.write("right: " + right.toString() +"\n\n");
((FiniteClosure)fc).logFile.write("y: " + y.toString() +"\n");
((FiniteClosure)fc).logFile.write("y.getLhsType() : " + y.getLhsType() .toString() +"\n\n");
((FiniteClosure)fc).logFile.write("y.getRhsType(): " + y.getRhsType().toString() +"\n");
((FiniteClosure)fc).logFile.write("x.getPairOp(): " + x.getPairOp().toString() +"\n\n");
}
catch (IOException ie) {
} */
return (y.getLhsType() instanceof PlaceholderType &&
!(y.getRhsType() instanceof PlaceholderType) &&
x.getPairOp() == PairOperator.EQUALSDOT);})
.collect(Collectors.toCollection(HashSet::new));
left.removeAll(lefteqOder); left.removeAll(lefteqOder);
Set<UnifyPair> righteqOder = right.stream()
.filter(x -> { UnifyPair y = x.getGroundBasePair();
return (y.getLhsType() instanceof PlaceholderType &&
!(y.getRhsType() instanceof PlaceholderType) &&
x.getPairOp() == PairOperator.EQUALSDOT);})
.collect(Collectors.toCollection(HashSet::new));
right.removeAll(righteqOder);
Set<UnifyPair> lefteqRet = left.stream()
.filter(x -> { UnifyPair y = x.getGroundBasePair();
return (y.getRhsType() instanceof PlaceholderType &&
((PlaceholderType)y.getRhsType()).getOrCons() == (byte)-1);})
.collect(Collectors.toCollection(HashSet::new));
left.removeAll(lefteqRet); left.removeAll(lefteqRet);
Set<UnifyPair> righteqRet = right.stream() right.removeAll(righteqOder);
.filter(x -> { UnifyPair y = x.getGroundBasePair();
return (y.getRhsType() instanceof PlaceholderType &&
((PlaceholderType)y.getRhsType()).getOrCons() == (byte)-1);})
.collect(Collectors.toCollection(HashSet::new));
right.removeAll(righteqRet); right.removeAll(righteqRet);
Set<UnifyPair> leftleOder = left.stream()
.filter(x -> (x.getPairOp() == PairOperator.SMALLERDOT))
.collect(Collectors.toCollection(HashSet::new));
Set<UnifyPair> rightleOder = right.stream()
.filter(x -> (x.getPairOp() == PairOperator.SMALLERDOT))
.collect(Collectors.toCollection(HashSet::new));
/* /*
synchronized(this) { synchronized(this) {
@@ -270,46 +266,34 @@ public class OrderingUnifyPair extends OrderingExtend<Set<UnifyPair>> {
*/ */
Integer compareEq; int compareEq;
if (lefteqOder.size() == 1 && righteqOder.size() == 1 && lefteqRet.size() == 1 && righteqRet.size() == 1) { if (lefteqOder.size() == 1 && righteqOder.size() == 1 && lefteqRet.size() == 1 && righteqRet.size() == 1) {
Match m = new Match(); Match m = new Match();
if ((compareEq = compareEq(lefteqOder.iterator().next().getGroundBasePair(), righteqOder.iterator().next().getGroundBasePair())) == -1) { compareEq = compareEq(lefteqOder.iterator().next().getGroundBasePair(), righteqOder.iterator().next().getGroundBasePair());
if (compareEq == -1) {
ArrayList<UnifyPair> matchList = ArrayList<UnifyPair> matchList =
rightleOder.stream().map(x -> { rightleOder.stream().map(x -> {
UnifyPair leftElem = leftleOder.stream() UnifyPair leftElem = leftleOder.stream()
.filter(y -> y.getGroundBasePair().getLhsType().equals(x.getGroundBasePair().getLhsType())) .filter(y -> y.getGroundBasePair().getLhsType().equals(x.getGroundBasePair().getLhsType()))
.findAny().get(); .findAny().orElseThrow();
return new UnifyPair(x.getRhsType(), leftElem.getRhsType(), PairOperator.EQUALSDOT);}) return new UnifyPair(x.getRhsType(), leftElem.getRhsType(), PairOperator.EQUALSDOT);}
)
.collect(Collectors.toCollection(ArrayList::new)); .collect(Collectors.toCollection(ArrayList::new));
if (m.match(matchList).isPresent()) {
//try { ((FiniteClosure)fc).logFile.write("result1: -1 \n\n"); } catch (IOException ie) {} return (m.match(matchList).isPresent()) ? -1 : 0;
return -1;
}
else {
//try { ((FiniteClosure)fc).logFile.write("result1: 0 \n\n"); } catch (IOException ie) {}
return 0;
}
} else if (compareEq == 1) { } else if (compareEq == 1) {
ArrayList<UnifyPair> matchList = ArrayList<UnifyPair> matchList =
leftleOder.stream().map(x -> { leftleOder.stream().map(x -> {
UnifyPair rightElem = rightleOder.stream() UnifyPair rightElem = rightleOder.stream()
.filter(y -> .filter(y -> y.getGroundBasePair().getLhsType().equals(x.getGroundBasePair().getLhsType()))
y.getGroundBasePair().getLhsType().equals(x.getGroundBasePair().getLhsType())) .findAny().orElseThrow();
.findAny().get(); return new UnifyPair(x.getRhsType(), rightElem.getRhsType(), PairOperator.EQUALSDOT);}
return new UnifyPair(x.getRhsType(), rightElem.getRhsType(), PairOperator.EQUALSDOT);}) )
.collect(Collectors.toCollection(ArrayList::new)); .collect(Collectors.toCollection(ArrayList::new));
if (m.match(matchList).isPresent()) { return (m.match(matchList).isPresent()) ? 1 : 0;
//try { ((FiniteClosure)fc).logFile.write("result2: 1 \n\n"); } catch (IOException ie) {}
return 1;
}
else {
//try { ((FiniteClosure)fc).logFile.write("result2: 0 \n\n"); } catch (IOException ie) {}
return 0;
}
} else { } else {
/* /*
synchronized(this) {
try {
((FiniteClosure)fc).logFile.write("leftBase: " + leftBase.toString() +"\n"); ((FiniteClosure)fc).logFile.write("leftBase: " + leftBase.toString() +"\n");
((FiniteClosure)fc).logFile.write("rightBase: " + rightBase.toString() +"\n\n"); ((FiniteClosure)fc).logFile.write("rightBase: " + rightBase.toString() +"\n\n");
((FiniteClosure)fc).logFile.write("left: " + left.toString() +"\n"); ((FiniteClosure)fc).logFile.write("left: " + left.toString() +"\n");
@@ -322,37 +306,33 @@ public class OrderingUnifyPair extends OrderingExtend<Set<UnifyPair>> {
((FiniteClosure)fc).logFile.write("rightleOder: " + rightleOder.toString() +"\n\n"); ((FiniteClosure)fc).logFile.write("rightleOder: " + rightleOder.toString() +"\n\n");
((FiniteClosure)fc).logFile.write("result3: 0 \n\n"); ((FiniteClosure)fc).logFile.write("result3: 0 \n\n");
((FiniteClosure)fc).logFile.flush(); ((FiniteClosure)fc).logFile.flush();
}
catch (IOException ie) {
}
}
*/ */
return 0; return 0;
} }
} }
if (lefteq.size() == 1 && lefteq.iterator().next().getRhsType() instanceof ExtendsType && leftle.size() == 1 && righteq.size() == 0 && rightle.size() == 1) { if (lefteq.size() == 1 && lefteq.iterator().next().getRhsType() instanceof ExtendsType && leftle.size() == 1 && righteq.isEmpty() && rightle.size() == 1) {
return 1; return 1;
} }
//Fall 2 //Fall 2
if (lefteq.size() == 0 && leftle.size() == 1 && righteq.size() == 1 && righteq.iterator().next().getRhsType() instanceof ExtendsType && rightle.size() == 1) { if (lefteq.isEmpty() && leftle.size() == 1 && righteq.size() == 1 && righteq.iterator().next().getRhsType() instanceof ExtendsType && rightle.size() == 1) {
return -1; return -1;
} }
//Fall 3 //Fall 3
if (lefteq.size() == 1 && lefteq.iterator().next().getRhsType() instanceof SuperType && leftle.size() == 1 && righteq.size() == 0 && rightle.size() == 1) { if (lefteq.size() == 1 && lefteq.iterator().next().getRhsType() instanceof SuperType && leftle.size() == 1 && righteq.isEmpty() && rightle.size() == 1) {
return -1; return -1;
} }
//Fall 3 //Fall 3
if (lefteq.size() == 0 && leftle.size() == 1 && righteq.size() == 1 && righteq.iterator().next().getRhsType() instanceof SuperType && rightle.size() == 1) { if (lefteq.isEmpty() && leftle.size() == 1 && righteq.size() == 1 && righteq.iterator().next().getRhsType() instanceof SuperType && rightle.size() == 1) {
return 1; return 1;
} }
//Fall 5 //Fall 5
if (lefteq.size() == 1 && leftle.size() == 0 && righteq.size() == 1 && rightle.size() == 1) { if (lefteq.size() == 1 && leftle.isEmpty() && righteq.size() == 1 && rightle.size() == 1) {
return -1; return -1;
} }
//Fall 5 //Fall 5
if (lefteq.size() == 1 && leftle.size() == 1 && righteq.size() == 1 && rightle.size() == 0) { if (lefteq.size() == 1 && leftle.size() == 1 && righteq.size() == 1 && rightle.isEmpty()) {
return 1; return 1;
} }
//Fall 5 //Fall 5
@@ -360,7 +340,7 @@ public class OrderingUnifyPair extends OrderingExtend<Set<UnifyPair>> {
return 0; return 0;
} }
// Nur Paare a =. Theta // Nur Paare a =. Theta
if (leftle.size() == 0 && rightle.size() == 0 && leftlewc.size() == 0 && rightlewc.size() ==0) { if (leftle.isEmpty() && rightle.isEmpty() && leftlewc.isEmpty() && rightlewc.isEmpty()) {
Stream<UnifyPair> lseq = lefteq.stream(); //left.filter(x -> (x.getLhsType() instanceof PlaceholderType && x.getPairOp() == PairOperator.EQUALSDOT)); Stream<UnifyPair> lseq = lefteq.stream(); //left.filter(x -> (x.getLhsType() instanceof PlaceholderType && x.getPairOp() == PairOperator.EQUALSDOT));
Stream<UnifyPair> rseq = righteq.stream(); //right.filter(x -> (x.getLhsType() instanceof PlaceholderType && x.getPairOp() == PairOperator.EQUALSDOT)); Stream<UnifyPair> rseq = righteq.stream(); //right.filter(x -> (x.getLhsType() instanceof PlaceholderType && x.getPairOp() == PairOperator.EQUALSDOT));
BinaryOperator<HashMap<UnifyType,UnifyPair>> combiner = (x,y) -> { x.putAll(y); return x;}; BinaryOperator<HashMap<UnifyType,UnifyPair>> combiner = (x,y) -> { x.putAll(y); return x;};
@@ -368,11 +348,10 @@ public class OrderingUnifyPair extends OrderingExtend<Set<UnifyPair>> {
lseq = lseq.filter(x -> !(hm.get(x.getLhsType()) == null));//NOCHMALS UEBERPRUEFEN!!!! lseq = lseq.filter(x -> !(hm.get(x.getLhsType()) == null));//NOCHMALS UEBERPRUEFEN!!!!
lseq = lseq.filter(x -> !x.equals(hm.get(x.getLhsType()))); //Elemente die gleich sind muessen nicht verglichen werden lseq = lseq.filter(x -> !x.equals(hm.get(x.getLhsType()))); //Elemente die gleich sind muessen nicht verglichen werden
Optional<Integer> si = lseq.map(x -> compareEq(x, hm.get(x.getLhsType()))).reduce((x,y)-> { if (x == y) return x; else return 0; } ); Optional<Integer> si = lseq.map(x -> compareEq(x, hm.get(x.getLhsType()))).reduce((x,y)-> { if (x == y) return x; else return 0; } );
if (!si.isPresent()) return 0; return si.orElse(0);
else return si.get();
} }
//Fall 1 und 4 //Fall 1 und 4
if (lefteq.size() >= 1 && righteq.size() >= 1 && (leftlewc.size() > 0 || rightlewc.size() > 0)) { if (!lefteq.isEmpty() && !righteq.isEmpty() && (!leftlewc.isEmpty() || !rightlewc.isEmpty())) {
//Set<PlaceholderType> varsleft = lefteq.stream().map(x -> (PlaceholderType)x.getLhsType()).collect(Collectors.toCollection(HashSet::new)); //Set<PlaceholderType> varsleft = lefteq.stream().map(x -> (PlaceholderType)x.getLhsType()).collect(Collectors.toCollection(HashSet::new));
//Set<PlaceholderType> varsright = righteq.stream().map(x -> (PlaceholderType)x.getLhsType()).collect(Collectors.toCollection(HashSet::new)); //Set<PlaceholderType> varsright = righteq.stream().map(x -> (PlaceholderType)x.getLhsType()).collect(Collectors.toCollection(HashSet::new));
//filtern des Paares a = Theta, das durch a <. Thata' generiert wurde (nur im Fall 1 relevant) andere Substitutioen werden rausgefiltert //filtern des Paares a = Theta, das durch a <. Thata' generiert wurde (nur im Fall 1 relevant) andere Substitutioen werden rausgefiltert
@@ -393,12 +372,12 @@ public class OrderingUnifyPair extends OrderingExtend<Set<UnifyPair>> {
//TODO: Hier wird bei Wildcards nicht das richtige compare aufgerufen PL 18-04-20 //TODO: Hier wird bei Wildcards nicht das richtige compare aufgerufen PL 18-04-20
Pair<Integer, Set<UnifyPair>> int_Unifier = compare(lseq.getRhsType(), rseq.getRhsType()); Pair<Integer, Set<UnifyPair>> int_Unifier = compare(lseq.getRhsType(), rseq.getRhsType());
Unifier uni = new Unifier(); Unifier uni = new Unifier();
int_Unifier.getValue().get().forEach(x -> uni.add((PlaceholderType) x.getLhsType(), x.getRhsType())); int_Unifier.getValue().orElseThrow().forEach(x -> uni.add((PlaceholderType) x.getLhsType(), x.getRhsType()));
if (!lseq.getRhsType().getName().equals(rseq.getRhsType().getName()) if (!lseq.getRhsType().getName().equals(rseq.getRhsType().getName())
|| leftlewc.size() == 0 || rightlewc.size() == 0) return int_Unifier.getKey(); || leftlewc.isEmpty() || rightlewc.isEmpty()) return int_Unifier.getKey();
else { else {
Set <UnifyPair> lsleuni = leftlewc.stream().map(x -> uni.apply(x)).collect(Collectors.toCollection(HashSet::new)); Set <UnifyPair> lsleuni = leftlewc.stream().map(uni::apply).collect(Collectors.toCollection(HashSet::new));
Set <UnifyPair> rsleuni = rightlewc.stream().map(x -> uni.apply(x)).collect(Collectors.toCollection(HashSet::new)); Set <UnifyPair> rsleuni = rightlewc.stream().map(uni::apply).collect(Collectors.toCollection(HashSet::new));
BinaryOperator<HashMap<UnifyType,UnifyPair>> combiner = (x,y) -> { x.putAll(y); return x;}; BinaryOperator<HashMap<UnifyType,UnifyPair>> combiner = (x,y) -> { x.putAll(y); return x;};
HashMap<UnifyType,UnifyPair> hm; HashMap<UnifyType,UnifyPair> hm;
@@ -415,11 +394,11 @@ public class OrderingUnifyPair extends OrderingExtend<Set<UnifyPair>> {
Stream<UnifyPair> lslewcstr = lsleuni.stream().filter(x -> !(hm.get(x.getRhsType()) == null)); Stream<UnifyPair> lslewcstr = lsleuni.stream().filter(x -> !(hm.get(x.getRhsType()) == null));
si = lslewcstr.map(x -> fc.compare(x.getLhsType(), hm.get(x.getRhsType()).getLhsType(), PairOperator.SMALLERDOTWC, context)).reduce((x,y)-> { if (x == y) return x; else return 0; } ); si = lslewcstr.map(x -> fc.compare(x.getLhsType(), hm.get(x.getRhsType()).getLhsType(), PairOperator.SMALLERDOTWC, context)).reduce((x,y)-> { if (x == y) return x; else return 0; } );
} }
if (!si.isPresent()) return 0; return si.orElse(0);
else return si.get();
} }
} else { } else {
if (leftlewc.size() > 0) { if (!leftlewc.isEmpty()) {
/*
Set<UnifyPair> subst; Set<UnifyPair> subst;
subst = leftlewc.stream().map(x -> { subst = leftlewc.stream().map(x -> {
if (x.getLhsType() instanceof PlaceholderType) { if (x.getLhsType() instanceof PlaceholderType) {
@@ -428,6 +407,7 @@ public class OrderingUnifyPair extends OrderingExtend<Set<UnifyPair>> {
else { else {
return new UnifyPair(x.getRhsType(), x.getLhsType(), PairOperator.EQUALSDOT); return new UnifyPair(x.getRhsType(), x.getLhsType(), PairOperator.EQUALSDOT);
}}).collect(Collectors.toCollection(HashSet::new)); }}).collect(Collectors.toCollection(HashSet::new));
*/
Unifier uni = new Unifier(); Unifier uni = new Unifier();
lseq = uni.apply(lseq); lseq = uni.apply(lseq);
} }

View File

@@ -134,15 +134,15 @@ public final class PlaceholderType extends UnifyType{
wildcardable = true; wildcardable = true;
} }
public void setWildcardtable(Boolean wildcardable) { public void setWildcardtable(boolean wildcardable) {
this.wildcardable = wildcardable; this.wildcardable = wildcardable;
} }
public Boolean isInnerType() { public boolean isInnerType() {
return innerType; return innerType;
} }
public void setInnerType(Boolean innerType) { public void setInnerType(boolean innerType) {
this.innerType = innerType; this.innerType = innerType;
} }

View File

@@ -32,7 +32,7 @@ public class ReferenceType extends UnifyType implements ISerializableData {
return visitor.visit(this, ht); return visitor.visit(this, ht);
} }
public ReferenceType(String name, Boolean genericTypeVar) { public ReferenceType(String name, boolean genericTypeVar) {
super(name, new TypeParams()); super(name, new TypeParams());
hashCode = 31 + 17 * typeName.hashCode() + 17 * typeParams.hashCode(); hashCode = 31 + 17 * typeName.hashCode() + 17 * typeParams.hashCode();
this.genericTypeVar = genericTypeVar; this.genericTypeVar = genericTypeVar;

View File

@@ -201,7 +201,7 @@ public class UnifyPair implements IConstraintElement, ISerializableData {
} }
public Boolean wrongWildcard() { public boolean wrongWildcard() {
return lhs.wrongWildcard() || rhs.wrongWildcard(); return lhs.wrongWildcard() || rhs.wrongWildcard();
} }

View File

@@ -103,7 +103,7 @@ public abstract class UnifyType implements ISerializableData {
return new ArrayList<>(typeParams.getInvolvedPlaceholderTypes()); return new ArrayList<>(typeParams.getInvolvedPlaceholderTypes());
} }
public Boolean wrongWildcard() {//default public boolean wrongWildcard() {//default
return false; return false;
} }

View File

@@ -42,7 +42,7 @@ public abstract class WildcardType extends UnifyType implements ISerializableDat
} }
@Override @Override
public Boolean wrongWildcard () {//This is an error public boolean wrongWildcard () {//This is an error
return (wildcardedType instanceof WildcardType); return (wildcardedType instanceof WildcardType);
} }

View File

@@ -2,24 +2,29 @@ package de.dhbwstuttgart.util;
import com.diogonunes.jcolor.Attribute; import com.diogonunes.jcolor.Attribute;
import de.dhbwstuttgart.core.ConsoleInterface; import de.dhbwstuttgart.core.ConsoleInterface;
import de.dhbwstuttgart.server.SocketServer;
import java.io.File; import java.io.File;
import java.io.FileWriter; import java.io.FileWriter;
import java.io.IOException; import java.io.IOException;
import java.io.Writer; import java.io.Writer;
import java.nio.file.Path; import java.nio.file.Path;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays; import java.util.Arrays;
import java.util.Objects; import java.util.Objects;
import java.util.function.Supplier;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import static com.diogonunes.jcolor.Ansi.colorize; import static com.diogonunes.jcolor.Ansi.colorize;
public class Logger { public class Logger {
public static final Logger NULL_LOGGER = new NullLogger();
private static final DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
protected final Writer writer; protected final Writer writer;
protected final String prefix; protected final String prefix;
public static Logger NULL_LOGGER = new NullLogger();
public Logger() { public Logger() {
this(null, ""); this(null, "");
} }
@@ -53,7 +58,7 @@ public class Logger {
/** /**
* Create a new logger object that inherits the writer of the given logger object * Create a new logger object that inherits the writer of the given logger object
* *
* @param logger The old logger object, that will provide the writer * @param logger The old logger object that will provide the writer
* @return The new prefix for the new logger object * @return The new prefix for the new logger object
*/ */
public static Logger inherit(Logger logger, String newPrefix) { public static Logger inherit(Logger logger, String newPrefix) {
@@ -72,6 +77,7 @@ public class Logger {
case INFO -> colorize(fullPrefix, Attribute.BLUE_TEXT()); case INFO -> colorize(fullPrefix, Attribute.BLUE_TEXT());
case WARNING -> colorize(fullPrefix, Attribute.YELLOW_TEXT()); case WARNING -> colorize(fullPrefix, Attribute.YELLOW_TEXT());
case ERROR -> colorize(fullPrefix, Attribute.RED_TEXT()); case ERROR -> colorize(fullPrefix, Attribute.RED_TEXT());
case SUCCESS -> colorize(fullPrefix, Attribute.GREEN_TEXT());
}; };
} }
@@ -82,7 +88,15 @@ public class Logger {
*/ */
protected void print(String s, LogLevel logLevel) { protected void print(String s, LogLevel logLevel) {
String coloredPrefix = this.getPrefix(logLevel); String coloredPrefix = this.getPrefix(logLevel);
if (logLevel.value > LogLevel.WARNING.value) {
// if we are running the server, prepend the timestamp
if(SocketServer.isServerRunning()) {
String timestamp = LocalDateTime.now().format(timeFormatter);
coloredPrefix = "[" + timestamp + "] " + coloredPrefix;
}
// output to the correct output-stream
if (logLevel.getValue() == LogLevel.ERROR.getValue()) {
System.out.println(coloredPrefix + s); System.out.println(coloredPrefix + s);
} }
else { else {
@@ -90,8 +104,12 @@ public class Logger {
} }
} }
public boolean isLogLevelActive(LogLevel logLevel) {
return logLevel.isHigherOrEqualTo(ConsoleInterface.logLevel);
}
/** /**
* Write text to the attached writer, if there is any * Write text to the attached writer if there is any
* @param s The string to print * @param s The string to print
*/ */
protected void write(String s) { protected void write(String s) {
@@ -117,32 +135,49 @@ public class Logger {
* @param logLevel The logLevel on which the text should be logged * @param logLevel The logLevel on which the text should be logged
*/ */
public void log(String s, LogLevel logLevel) { public void log(String s, LogLevel logLevel) {
if (logLevel.value >= ConsoleInterface.logLevel.value) { if (isLogLevelActive(logLevel)) {
this.print(s, logLevel); this.print(s, logLevel);
this.write(s); this.write(s);
} }
} }
public void log(Supplier<String> supp, LogLevel logLevel) {
if (isLogLevelActive(logLevel)) {
this.log(supp.get(), logLevel);
}
}
public void log(Object obj, LogLevel logLevel) {
if (isLogLevelActive(logLevel)) {
this.log(obj.toString(), logLevel);
}
}
/** /**
* Replaces the old FileWriter.write() call * Output a debug message
* @param s The string to log * @param s The string to log
*/ */
public void debug(String s) { public void debug(String s) {
this.log(s, LogLevel.DEBUG); this.log(s, LogLevel.DEBUG);
} }
public void debug(Object o) { public void debug(Object o) {
this.debug(o.toString()); this.log(o, LogLevel.DEBUG);
}
public void debug(Supplier<String> supp) {
this.log(supp, LogLevel.DEBUG);
} }
/** /**
* Replaces the old System.out.println() call * Output an info message
* @param s The string to log * @param s The string to log
*/ */
public void info(String s) { public void info(String s) {
this.log(s, LogLevel.INFO); this.log(s, LogLevel.INFO);
} }
public void info(Object o) { public void info(Object o) {
this.info(o.toString()); this.log(o, LogLevel.INFO);
}
public void info(Supplier<String> supp) {
this.log(supp, LogLevel.INFO);
} }
/** /**
@@ -153,7 +188,10 @@ public class Logger {
this.log(s, LogLevel.WARNING); this.log(s, LogLevel.WARNING);
} }
public void warn(Object o) { public void warn(Object o) {
this.warn(o.toString()); this.log(o, LogLevel.WARNING);
}
public void warn(Supplier<String> supp) {
this.log(supp, LogLevel.WARNING);
} }
/** /**
@@ -164,7 +202,25 @@ public class Logger {
this.log(s, LogLevel.ERROR); this.log(s, LogLevel.ERROR);
} }
public void error(Object o) { public void error(Object o) {
this.error(o.toString()); this.log(o, LogLevel.ERROR);
}
public void error(Supplier<String> supp) {
this.log(supp, LogLevel.ERROR);
}
/**
* Output a success message
* @param s The string to log
*/
public void success(String s) {
this.log(s, LogLevel.SUCCESS);
}
public void success(Object o) {
this.log(o, LogLevel.SUCCESS);
}
public void success(Supplier<String> supp) {
this.log(supp, LogLevel.SUCCESS);
} }
/** /**
@@ -180,7 +236,7 @@ public class Logger {
" | " + stackTraceElement.toString() " | " + stackTraceElement.toString()
).collect(Collectors.joining("\n")); ).collect(Collectors.joining("\n"));
// if there will be a cause printed afterward, announce it with the print of the exception // if there is a cause printed afterward, announce it with the print of the exception
if (throwable.getCause() != null) { if (throwable.getCause() != null) {
s += "\n\nCaused by: "; s += "\n\nCaused by: ";
} }
@@ -207,22 +263,50 @@ public class Logger {
/** /**
* An enum representing the different log levels as integers * An enum representing the different log levels as integers:
* <ul>
* <li>DEBUG: highly specific output only for debugging</li>
* <li>INFO: informational output about the current state of the program</li>
* <li>WARNING: warnings about potential issues or an unexpected state</li>
* <li>ERROR: invalid states, errors and exceptions</li>
* <li>SUCCESS: successfully executed key steps of the program</li>
* </ul>
*/ */
public enum LogLevel { public enum LogLevel {
// all the output /** Highly specific output only for debugging */
DEBUG(0), DEBUG(0),
// a lot of info about the process /** Informational output about the current state of the program */
INFO(1), INFO(1),
// warnings and up /** Warnings about potential issues or an unexpected state **/
WARNING(2), WARNING(2),
// only errors and exceptions /** Invalid states, errors and exceptions */
ERROR(3); ERROR(3),
/** Successfully executed key steps of the program */
SUCCESS(4);
private final int value; private final int value;
LogLevel(final int newValue) { LogLevel(final int newValue) {
value = newValue; value = newValue;
} }
public boolean isHigherOrEqualTo(LogLevel other) {
return this.value >= other.value;
}
public int getValue() {
return value;
}
public static LogLevel fromValue(int value) {
return switch (value) {
case 0 -> LogLevel.DEBUG;
case 1 -> LogLevel.INFO;
case 2 -> LogLevel.WARNING;
case 3 -> LogLevel.ERROR;
case 4 -> LogLevel.SUCCESS;
default -> throw new RuntimeException("Invalid log level value: " + value);
};
}
} }
@@ -232,7 +316,7 @@ public class Logger {
private static class NullLogger extends Logger { private static class NullLogger extends Logger {
@Override @Override
public void log(String s, LogLevel logLevel) { public void log(String s, LogLevel logLevel) {
// do nothing. Yay // Do nothing. Yay
} }
} }
} }

View File

@@ -1,6 +1,6 @@
import static org.junit.Assert.*; import static org.junit.jupiter.api.Assertions.*;
import static targetast.TestCodegen.generateClassFiles; import static targetast.TestCodegen.generateClassFiles;
import java.io.File; import java.io.File;
@@ -9,13 +9,12 @@ import java.net.URL;
import java.net.URLClassLoader; import java.net.URLClassLoader;
import java.util.Arrays; import java.util.Arrays;
import org.junit.BeforeClass; import org.junit.jupiter.api.BeforeAll;
import org.junit.Test; import org.junit.jupiter.api.Test;
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.environment.ByteArrayClassLoader;
public class AllgemeinTest { public class AllgemeinTest {

View File

@@ -6,12 +6,12 @@ import de.dhbwstuttgart.syntaxtree.GenericTypeVar;
import de.dhbwstuttgart.syntaxtree.factory.ASTFactory; import de.dhbwstuttgart.syntaxtree.factory.ASTFactory;
import de.dhbwstuttgart.syntaxtree.type.*; import de.dhbwstuttgart.syntaxtree.type.*;
import de.dhbwstuttgart.target.generate.ASTToTargetAST; import de.dhbwstuttgart.target.generate.ASTToTargetAST;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import static org.junit.Assert.*; import static org.junit.jupiter.api.Assertions.*;
public class GenericsParserTest { public class GenericsParserTest {

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
import de.dhbwstuttgart.core.JavaTXCompiler; import de.dhbwstuttgart.core.JavaTXCompiler;
import org.junit.Ignore; import org.junit.jupiter.api.Disabled;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.io.File; import java.io.File;
import java.util.List; import java.util.List;
@@ -24,7 +24,7 @@ public class TestPackages {
} }
@Test @Test
@Ignore("This doesn't work") @Disabled("This doesn't work")
public void testPackagesCircular() throws Exception { public void testPackagesCircular() throws Exception {
var cmp = new JavaTXCompiler( var cmp = new JavaTXCompiler(
List.of( List.of(

View File

@@ -4,7 +4,7 @@ import de.dhbwstuttgart.syntaxtree.SourceFile;
import de.dhbwstuttgart.typedeployment.TypeInsert; import de.dhbwstuttgart.typedeployment.TypeInsert;
import de.dhbwstuttgart.typedeployment.TypeInsertFactory; import de.dhbwstuttgart.typedeployment.TypeInsertFactory;
import de.dhbwstuttgart.typeinference.result.ResultSet; import de.dhbwstuttgart.typeinference.result.ResultSet;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.io.File; import java.io.File;
import java.nio.file.Path; import java.nio.file.Path;

View File

@@ -4,7 +4,7 @@ package astfactory;
import de.dhbwstuttgart.syntaxtree.ClassOrInterface; import de.dhbwstuttgart.syntaxtree.ClassOrInterface;
import de.dhbwstuttgart.syntaxtree.factory.ASTFactory; import de.dhbwstuttgart.syntaxtree.factory.ASTFactory;
import de.dhbwstuttgart.syntaxtree.type.GenericRefType; import de.dhbwstuttgart.syntaxtree.type.GenericRefType;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.lang.reflect.ParameterizedType; import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type; import java.lang.reflect.Type;
@@ -12,7 +12,8 @@ import java.lang.reflect.TypeVariable;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
import static org.junit.Assert.*; import static org.junit.jupiter.api.Assertions.assertTrue;
public class ASTFactoryTest<A> extends HashMap<String, A>{ public class ASTFactoryTest<A> extends HashMap<String, A>{
@Test @Test

View File

@@ -4,12 +4,10 @@ import de.dhbwstuttgart.core.JavaTXCompiler;
import de.dhbwstuttgart.parser.SyntaxTreeGenerator.FCGenerator; import de.dhbwstuttgart.parser.SyntaxTreeGenerator.FCGenerator;
import de.dhbwstuttgart.syntaxtree.ClassOrInterface; import de.dhbwstuttgart.syntaxtree.ClassOrInterface;
import de.dhbwstuttgart.syntaxtree.factory.ASTFactory; import de.dhbwstuttgart.syntaxtree.factory.ASTFactory;
import de.dhbwstuttgart.typeinference.unify.PlaceholderRegistry; import org.junit.jupiter.api.Test;
import org.junit.Test;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.List;
public class SuperInterfacesTest { public class SuperInterfacesTest {
@Test @Test

View File

@@ -1,7 +1,7 @@
package server; package server;
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonProcessingException;
import de.dhbwstuttgart.environment.ByteArrayClassLoader; import de.dhbwstuttgart.core.JavaTXCompiler;
import de.dhbwstuttgart.parser.SourceLoc; import de.dhbwstuttgart.parser.SourceLoc;
import de.dhbwstuttgart.server.packet.DebugPacket; import de.dhbwstuttgart.server.packet.DebugPacket;
import de.dhbwstuttgart.server.packet.IPacket; import de.dhbwstuttgart.server.packet.IPacket;
@@ -16,18 +16,11 @@ 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 de.dhbwstuttgart.typeinference.constraints.Constraint; import de.dhbwstuttgart.typeinference.constraints.Constraint;
import de.dhbwstuttgart.typeinference.constraints.ConstraintSet; import de.dhbwstuttgart.typeinference.constraints.ConstraintSet;
import de.dhbwstuttgart.typeinference.unify.PlaceholderRegistry;
import de.dhbwstuttgart.typeinference.unify.UnifyContext; import de.dhbwstuttgart.typeinference.unify.UnifyContext;
import de.dhbwstuttgart.typeinference.unify.UnifyResultModel;
import de.dhbwstuttgart.typeinference.unify.UnifyTaskModel;
import de.dhbwstuttgart.typeinference.unify.model.FiniteClosure;
import de.dhbwstuttgart.typeinference.unify.model.UnifyPair; import de.dhbwstuttgart.typeinference.unify.model.UnifyPair;
import java.io.Writer;
import java.util.HashSet;
import java.util.concurrent.ForkJoinPool;
import java.util.function.BiFunction; import java.util.function.BiFunction;
import org.junit.Test; import org.junit.jupiter.api.Test;
import static org.junit.Assert.*; import static org.junit.jupiter.api.Assertions.*;
public class PacketTest { public class PacketTest {

View File

@@ -1,9 +1,12 @@
package server; package server;
import de.dhbwstuttgart.core.ConsoleInterface;
import de.dhbwstuttgart.core.JavaTXCompiler; import de.dhbwstuttgart.core.JavaTXCompiler;
import de.dhbwstuttgart.core.JavaTXServer; import de.dhbwstuttgart.core.JavaTXServer;
import de.dhbwstuttgart.environment.CompilationEnvironment; import de.dhbwstuttgart.environment.CompilationEnvironment;
import de.dhbwstuttgart.server.SocketClient; import de.dhbwstuttgart.server.SocketClient;
import de.dhbwstuttgart.server.packet.SetAutoclosePacket;
import de.dhbwstuttgart.server.packet.UnifyRequestPacket;
import de.dhbwstuttgart.syntaxtree.ClassOrInterface; import de.dhbwstuttgart.syntaxtree.ClassOrInterface;
import de.dhbwstuttgart.syntaxtree.factory.ASTFactory; import de.dhbwstuttgart.syntaxtree.factory.ASTFactory;
import de.dhbwstuttgart.syntaxtree.factory.UnifyTypeFactory; import de.dhbwstuttgart.syntaxtree.factory.UnifyTypeFactory;
@@ -27,22 +30,26 @@ import java.io.Writer;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.HashSet; import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Optional;
import java.util.Set; import java.util.Set;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import org.junit.Test;
import targetast.TestCodegen; import targetast.TestCodegen;
import static org.junit.Assert.*; import static org.junit.jupiter.api.Assertions.*;
public class ServerTest { public class ServerTest {
@Test public ServerTest() {
ConsoleInterface.unifyServerUrl = Optional.of("ws://localhost:5000");
}
//@Test
public void checkServer_Scalar() throws IOException, ClassNotFoundException { public void checkServer_Scalar() throws IOException, ClassNotFoundException {
compareLocalAndServerResult("Scalar.jav"); compareLocalAndServerResult("Scalar.jav");
} }
@Test //@Test
public void checkServer_Matrix() throws IOException, ClassNotFoundException { public void checkServer_Matrix() throws IOException, ClassNotFoundException {
compareLocalAndServerResult("Matrix.jav"); compareLocalAndServerResult("Matrix.jav");
} }
@@ -50,11 +57,11 @@ public class ServerTest {
protected void compareLocalAndServerResult(final String filename) throws IOException, ClassNotFoundException { protected void compareLocalAndServerResult(final String filename) throws IOException, ClassNotFoundException {
File file = Path.of(TestCodegen.path.toString(), filename).toFile(); File file = Path.of(TestCodegen.path.toString(), filename).toFile();
// get information from compiler // get information from the compiler
JavaTXCompiler compiler = new JavaTXCompiler(List.of(file)); JavaTXCompiler compiler = new JavaTXCompiler(List.of(file));
// NOW: simulate the call to method typeInference. Once via server and once locally // NOW: simulate the call to method typeInference. Once via server and once locally
// if everything works, they should neither interfere with each other, nor differ in their result // if everything works, they should neither interfere with each other nor differ in their result
// get the values from the compiler // get the values from the compiler
PlaceholderRegistry placeholderRegistry = JavaTXCompiler.defaultClientPlaceholderRegistry; //new PlaceholderRegistry(); PlaceholderRegistry placeholderRegistry = JavaTXCompiler.defaultClientPlaceholderRegistry; //new PlaceholderRegistry();
@@ -84,8 +91,10 @@ public class ServerTest {
PlaceholderRegistry prCopy = JavaTXCompiler.defaultClientPlaceholderRegistry.deepClone(); PlaceholderRegistry prCopy = JavaTXCompiler.defaultClientPlaceholderRegistry.deepClone();
UnifyResultModel urm = new UnifyResultModel(cons, finiteClosure); UnifyResultModel urm = new UnifyResultModel(cons, finiteClosure);
UnifyContext context = new UnifyContext(Logger.NULL_LOGGER, true, urm, usedTasks, prCopy); UnifyContext context = new UnifyContext(Logger.NULL_LOGGER, true, urm, usedTasks, prCopy);
SocketClient socketClient = new SocketClient("ws://localhost:5000"); SocketClient.execute(SetAutoclosePacket.create());
List<ResultSet> serverResult = socketClient.execute(finiteClosure, cons, unifyCons, context); List<ResultSet> serverResult = SocketClient.executeAndGet(
UnifyRequestPacket.create(finiteClosure, cons, unifyCons, context.placeholderRegistry())
).getResultSet(context);
// close the server // close the server
server.forceStop(); server.forceStop();

View File

@@ -1,9 +1,5 @@
package syntaxtreegenerator; package syntaxtreegenerator;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.File; import java.io.File;
import java.io.FileFilter; import java.io.FileFilter;
import java.io.FileInputStream; import java.io.FileInputStream;
@@ -12,21 +8,23 @@ import java.io.ObjectOutputStream;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import org.junit.BeforeClass; import org.junit.jupiter.api.BeforeAll;
import org.junit.Test; import org.junit.jupiter.api.Test;
import de.dhbwstuttgart.core.JavaTXCompiler; import de.dhbwstuttgart.core.JavaTXCompiler;
import de.dhbwstuttgart.exceptions.NotImplementedException; import de.dhbwstuttgart.exceptions.NotImplementedException;
import de.dhbwstuttgart.syntaxtree.SourceFile; import de.dhbwstuttgart.syntaxtree.SourceFile;
import de.dhbwstuttgart.syntaxtree.visual.ASTPrinter; import de.dhbwstuttgart.syntaxtree.visual.ASTPrinter;
import static org.junit.jupiter.api.Assertions.*;
/** /**
* Unit-Tests für den 'SyntaxTreeGenerator' aus dem Package 'parser' nach Vorbild der Klasse 'TestComplete' aus dem Test-Package 'targetast' * Unit-Tests für den 'SyntaxTreeGenerator' aus dem Package 'parser' nach Vorbild der Klasse 'TestComplete' aus dem Test-Package 'targetast'
*/ */
public class TestComplete { public class TestComplete {
private static HashMap<String, File[]> javFiles = new HashMap<>(); private static HashMap<String, File[]> javFiles = new HashMap<>();
@BeforeClass @BeforeAll
public static void setUp() { public static void setUp() {
final String testFileDirectory = "resources/bytecode/javFiles/"; final String testFileDirectory = "resources/bytecode/javFiles/";
final String expectedASTDirectory = "resources/syntaxtreegenerator/"; final String expectedASTDirectory = "resources/syntaxtreegenerator/";
@@ -353,7 +351,7 @@ public class TestComplete {
assertEquals("Comparing expected and resulting AST for mathStrucInteger.jav", expectedAST, resultingAST); assertEquals("Comparing expected and resulting AST for mathStrucInteger.jav", expectedAST, resultingAST);
} catch (Exception exc) { } catch (Exception exc) {
exc.printStackTrace(); exc.printStackTrace();
assertTrue("An error occured while generating the AST for mathStrucInteger.jav", exc instanceof NotImplementedException); assertInstanceOf(NotImplementedException.class, exc);
} }
} }

View File

@@ -1,15 +1,15 @@
package syntaxtreegenerator; package syntaxtreegenerator;
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.Assert.fail; import static org.junit.jupiter.api.Assertions.fail;
import java.io.File; import java.io.File;
import java.io.FileFilter; import java.io.FileFilter;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.util.HashMap; import java.util.HashMap;
import org.junit.BeforeClass; import org.junit.jupiter.api.BeforeAll;
import org.junit.Test; import org.junit.jupiter.api.Test;
import de.dhbwstuttgart.core.JavaTXCompiler; import de.dhbwstuttgart.core.JavaTXCompiler;
import de.dhbwstuttgart.syntaxtree.visual.ASTPrinter; import de.dhbwstuttgart.syntaxtree.visual.ASTPrinter;
@@ -17,7 +17,7 @@ import de.dhbwstuttgart.syntaxtree.visual.ASTPrinter;
public class TestNewFeatures { public class TestNewFeatures {
private static HashMap<String, File[]> javFiles = new HashMap<>(); private static HashMap<String, File[]> javFiles = new HashMap<>();
@BeforeClass @BeforeAll
public static void setUp() { public static void setUp() {
final String testFileDirectory = "resources/syntaxtreegenerator/javFiles/"; final String testFileDirectory = "resources/syntaxtreegenerator/javFiles/";
final String expectedASTDirectory = "resources/syntaxtreegenerator/"; final String expectedASTDirectory = "resources/syntaxtreegenerator/";

View File

@@ -2,7 +2,6 @@ package targetast;
import com.google.common.reflect.TypeToken; import com.google.common.reflect.TypeToken;
import de.dhbwstuttgart.core.JavaTXCompiler; import de.dhbwstuttgart.core.JavaTXCompiler;
import de.dhbwstuttgart.environment.ByteArrayClassLoader;
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.syntaxtree.*; import de.dhbwstuttgart.syntaxtree.*;
@@ -10,13 +9,13 @@ import de.dhbwstuttgart.syntaxtree.type.RefType;
import de.dhbwstuttgart.target.generate.ASTToTargetAST; import de.dhbwstuttgart.target.generate.ASTToTargetAST;
import de.dhbwstuttgart.target.tree.TargetStructure; import de.dhbwstuttgart.target.tree.TargetStructure;
import de.dhbwstuttgart.typeinference.result.ResultSet; import de.dhbwstuttgart.typeinference.result.ResultSet;
import org.junit.Ignore; import org.junit.jupiter.api.Disabled;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.*; import java.util.*;
import static org.junit.Assert.*; import static org.junit.jupiter.api.Assertions.*;
public class ASTToTypedTargetAST { public class ASTToTypedTargetAST {
@@ -24,7 +23,7 @@ public class ASTToTypedTargetAST {
public void emptyClass() { public void emptyClass() {
ClassOrInterface emptyClass = new ClassOrInterface(0, new JavaClassName("EmptyClass"), new ArrayList<>(), Optional.empty(), Optional.empty(), new ArrayList<>(), new ArrayList<>(), new GenericDeclarationList(new ArrayList<>(), new NullToken()), new RefType(new JavaClassName("Object"), new NullToken()), false, false, new ArrayList<>(), new ArrayList<>(), new NullToken(), null); ClassOrInterface emptyClass = new ClassOrInterface(0, new JavaClassName("EmptyClass"), new ArrayList<>(), Optional.empty(), Optional.empty(), new ArrayList<>(), new ArrayList<>(), new GenericDeclarationList(new ArrayList<>(), new NullToken()), new RefType(new JavaClassName("Object"), new NullToken()), false, false, new ArrayList<>(), new ArrayList<>(), new NullToken(), null);
ResultSet emptyResultSet = new ResultSet(new HashSet<>()); ResultSet emptyResultSet = new ResultSet(new HashSet<>());
TargetStructure emptyTargetClass = new ASTToTargetAST(List.of(emptyResultSet)).convert(emptyClass); TargetStructure emptyTargetClass = new ASTToTargetAST(List.of(emptyResultSet), TestCodegen.createClassLoader()).convert(emptyClass);
assert emptyTargetClass.getName().equals("EmptyClass"); assert emptyTargetClass.getName().equals("EmptyClass");
assert emptyTargetClass.methods().size() == 0; assert emptyTargetClass.methods().size() == 0;
assert emptyTargetClass.fields().size() == 0; assert emptyTargetClass.fields().size() == 0;
@@ -32,13 +31,14 @@ public class ASTToTypedTargetAST {
@Test @Test
public void overloading() throws Exception { public void overloading() throws Exception {
var classLoader = TestCodegen.createClassLoader();
var file = Path.of(System.getProperty("user.dir"), "/resources/bytecode/javFiles/Overloading.jav").toFile(); var file = Path.of(System.getProperty("user.dir"), "/resources/bytecode/javFiles/Overloading.jav").toFile();
var compiler = new JavaTXCompiler(file); var compiler = new JavaTXCompiler(file);
var resultSet = compiler.typeInference(file); var resultSet = compiler.typeInference(file);
var converter = new ASTToTargetAST(compiler, resultSet); var converter = new ASTToTargetAST(compiler, resultSet, classLoader);
var classes = compiler.sourceFiles.get(file).getClasses(); var classes = compiler.sourceFiles.get(file).getClasses();
var classLoader = new ByteArrayClassLoader();
var overloading = TestCodegen.generateClass(converter.convert(classes.get(0)), classLoader); var overloading = TestCodegen.generateClass(converter.convert(classes.get(0)), classLoader);
var overloading2 = TestCodegen.generateClass(converter.convert(classes.get(1)), classLoader); var overloading2 = TestCodegen.generateClass(converter.convert(classes.get(1)), classLoader);
@@ -54,46 +54,54 @@ public class ASTToTypedTargetAST {
@Test @Test
public void tphsAndGenerics() throws Exception { public void tphsAndGenerics() throws Exception {
var classLoader = TestCodegen.createClassLoader();
var file = Path.of(System.getProperty("user.dir"), "/resources/bytecode/javFiles/Tph2.jav").toFile(); var file = Path.of(System.getProperty("user.dir"), "/resources/bytecode/javFiles/Tph2.jav").toFile();
var compiler = new JavaTXCompiler(file); var compiler = new JavaTXCompiler(file);
var resultSet = compiler.typeInference(file); var resultSet = compiler.typeInference(file);
var converter = new ASTToTargetAST(compiler, resultSet); var converter = new ASTToTargetAST(compiler, resultSet, classLoader);
var classes = compiler.sourceFiles.get(file).getClasses(); var classes = compiler.sourceFiles.get(file).getClasses();
var tphAndGenerics = TestCodegen.generateClass(converter.convert(classes.get(0)), new ByteArrayClassLoader()); var tphAndGenerics = TestCodegen.generateClass(converter.convert(classes.get(0)), classLoader);
} }
@Test @Test
public void cycles() throws Exception { public void cycles() throws Exception {
var classLoader = TestCodegen.createClassLoader();
var file = Path.of(System.getProperty("user.dir"), "/resources/bytecode/javFiles/Cycle.jav").toFile(); var file = Path.of(System.getProperty("user.dir"), "/resources/bytecode/javFiles/Cycle.jav").toFile();
var compiler = new JavaTXCompiler(file); var compiler = new JavaTXCompiler(file);
var resultSet = compiler.typeInference(file); var resultSet = compiler.typeInference(file);
var converter = new ASTToTargetAST(compiler, resultSet); var converter = new ASTToTargetAST(compiler, resultSet, classLoader);
var classes = compiler.sourceFiles.get(file).getClasses(); var classes = compiler.sourceFiles.get(file).getClasses();
var cycle = TestCodegen.generateClass(converter.convert(classes.get(0)), new ByteArrayClassLoader()); var cycle = TestCodegen.generateClass(converter.convert(classes.get(0)), classLoader);
} }
@Test @Test
public void infimum() throws Exception { public void infimum() throws Exception {
var classLoader = TestCodegen.createClassLoader();
var file = Path.of(System.getProperty("user.dir"), "/resources/bytecode/javFiles/Infimum.jav").toFile(); var file = Path.of(System.getProperty("user.dir"), "/resources/bytecode/javFiles/Infimum.jav").toFile();
var compiler = new JavaTXCompiler(file); var compiler = new JavaTXCompiler(file);
var resultSet = compiler.typeInference(file); var resultSet = compiler.typeInference(file);
var converter = new ASTToTargetAST(compiler, resultSet); var converter = new ASTToTargetAST(compiler, resultSet, classLoader);
var classes = compiler.sourceFiles.get(file).getClasses(); var classes = compiler.sourceFiles.get(file).getClasses();
var infimum = TestCodegen.generateClass(converter.convert(classes.get(0)), new ByteArrayClassLoader()); var infimum = TestCodegen.generateClass(converter.convert(classes.get(0)), classLoader);
} }
@Test @Test
public void gen() throws Exception { public void gen() throws Exception {
var classLoader = TestCodegen.createClassLoader();
var file = Path.of(System.getProperty("user.dir"), "/resources/bytecode/javFiles/Gen.jav").toFile(); var file = Path.of(System.getProperty("user.dir"), "/resources/bytecode/javFiles/Gen.jav").toFile();
var compiler = new JavaTXCompiler(file); var compiler = new JavaTXCompiler(file);
var resultSet = compiler.typeInference(file); var resultSet = compiler.typeInference(file);
var converter = new ASTToTargetAST(compiler, resultSet); var converter = new ASTToTargetAST(compiler, resultSet, classLoader);
var classes = compiler.sourceFiles.get(file).getClasses(); var classes = compiler.sourceFiles.get(file).getClasses();
var generics = TestCodegen.generateClass(converter.convert(classes.get(0)), new ByteArrayClassLoader()); var generics = TestCodegen.generateClass(converter.convert(classes.get(0)), TestCodegen.createClassLoader());
var m = generics.getDeclaredMethod("m", Vector.class); var m = generics.getDeclaredMethod("m", Vector.class);
var mReturnType = m.getGenericReturnType(); var mReturnType = m.getGenericReturnType();
assertEquals(mReturnType, m.getParameters()[0].getParameterizedType()); assertEquals(mReturnType, m.getParameters()[0].getParameterizedType());
@@ -103,13 +111,15 @@ public class ASTToTypedTargetAST {
@Test @Test
public void definedGenerics() throws Exception { public void definedGenerics() throws Exception {
var classLoader = TestCodegen.createClassLoader();
var file = Path.of(System.getProperty("user.dir"), "/resources/bytecode/javFiles/Generics.jav").toFile(); var file = Path.of(System.getProperty("user.dir"), "/resources/bytecode/javFiles/Generics.jav").toFile();
var compiler = new JavaTXCompiler(file); var compiler = new JavaTXCompiler(file);
var resultSet = compiler.typeInference(file); var resultSet = compiler.typeInference(file);
var converter = new ASTToTargetAST(compiler, resultSet); var converter = new ASTToTargetAST(compiler, resultSet, classLoader);
var classes = compiler.sourceFiles.get(file).getClasses(); var classes = compiler.sourceFiles.get(file).getClasses();
var generics = TestCodegen.generateClass(converter.convert(classes.get(0)), new ByteArrayClassLoader()); var generics = TestCodegen.generateClass(converter.convert(classes.get(0)), classLoader);
var B = generics.getTypeParameters()[0]; var B = generics.getTypeParameters()[0];
var mt1 = generics.getDeclaredMethod("mt1", Object.class); var mt1 = generics.getDeclaredMethod("mt1", Object.class);
var constructor = generics.getDeclaredConstructor(Object.class); var constructor = generics.getDeclaredConstructor(Object.class);
@@ -121,13 +131,15 @@ public class ASTToTypedTargetAST {
@Test @Test
public void definedGenerics2() throws Exception { public void definedGenerics2() throws Exception {
var classLoader = TestCodegen.createClassLoader();
var file = Path.of(System.getProperty("user.dir"), "/resources/bytecode/javFiles/Generics2.jav").toFile(); var file = Path.of(System.getProperty("user.dir"), "/resources/bytecode/javFiles/Generics2.jav").toFile();
var compiler = new JavaTXCompiler(file); var compiler = new JavaTXCompiler(file);
var resultSet = compiler.typeInference(file); var resultSet = compiler.typeInference(file);
var converter = new ASTToTargetAST(compiler, resultSet); var converter = new ASTToTargetAST(compiler, resultSet, classLoader);
var classes = compiler.sourceFiles.get(file).getClasses(); var classes = compiler.sourceFiles.get(file).getClasses();
var generics2 = TestCodegen.generateClass(converter.convert(classes.get(0)), new ByteArrayClassLoader()); var generics2 = TestCodegen.generateClass(converter.convert(classes.get(0)), classLoader);
assertEquals(generics2.getTypeParameters()[0].getBounds()[0], String.class); assertEquals(generics2.getTypeParameters()[0].getBounds()[0], String.class);
var m = generics2.getDeclaredMethod("m1", Object.class); var m = generics2.getDeclaredMethod("m1", Object.class);
assertEquals(m.getTypeParameters()[0].getBounds()[0], Integer.class); assertEquals(m.getTypeParameters()[0].getBounds()[0], Integer.class);
@@ -135,26 +147,30 @@ public class ASTToTypedTargetAST {
} }
@Test @Test
@Ignore("Not implemented") @Disabled("Not implemented")
public void definedGenerics3() throws Exception { public void definedGenerics3() throws Exception {
var classLoader = TestCodegen.createClassLoader();
var file = Path.of(System.getProperty("user.dir"), "/resources/bytecode/javFiles/Generics3.jav").toFile(); var file = Path.of(System.getProperty("user.dir"), "/resources/bytecode/javFiles/Generics3.jav").toFile();
var compiler = new JavaTXCompiler(file); var compiler = new JavaTXCompiler(file);
var resultSet = compiler.typeInference(file); var resultSet = compiler.typeInference(file);
var converter = new ASTToTargetAST(compiler, resultSet); var converter = new ASTToTargetAST(compiler, resultSet, classLoader);
var classes = compiler.sourceFiles.get(file).getClasses(); var classes = compiler.sourceFiles.get(file).getClasses();
var generics3 = TestCodegen.generateClass(converter.convert(classes.get(0)), new ByteArrayClassLoader()); var generics3 = TestCodegen.generateClass(converter.convert(classes.get(0)), classLoader);
} }
@Test @Test
public void definedGenerics4() throws Exception { public void definedGenerics4() throws Exception {
var classLoader = TestCodegen.createClassLoader();
var file = Path.of(System.getProperty("user.dir"), "/resources/bytecode/javFiles/Generics4.jav").toFile(); var file = Path.of(System.getProperty("user.dir"), "/resources/bytecode/javFiles/Generics4.jav").toFile();
var compiler = new JavaTXCompiler(file); var compiler = new JavaTXCompiler(file);
var resultSet = compiler.typeInference(file); var resultSet = compiler.typeInference(file);
var converter = new ASTToTargetAST(compiler, resultSet); var converter = new ASTToTargetAST(compiler, resultSet, classLoader);
var classes = compiler.sourceFiles.get(file).getClasses(); var classes = compiler.sourceFiles.get(file).getClasses();
var generics4 = TestCodegen.generateClass(converter.convert(classes.get(0)), new ByteArrayClassLoader()); var generics4 = TestCodegen.generateClass(converter.convert(classes.get(0)), classLoader);
// var instance = generics4.getDeclaredConstructor().newInstance(); // var instance = generics4.getDeclaredConstructor().newInstance();
// var method = generics4.getDeclaredMethod("m2", Object.class); // var method = generics4.getDeclaredMethod("m2", Object.class);

View File

@@ -1,22 +1,21 @@
package targetast; package targetast;
import de.dhbwstuttgart.environment.ByteArrayClassLoader; import org.junit.jupiter.api.BeforeAll;
import org.junit.BeforeClass; import org.junit.jupiter.api.Test;
import org.junit.Test;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import static org.junit.Assert.assertFalse; import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.Assert.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
public class GreaterEqualTest { public class GreaterEqualTest {
static Class<?> classToTest; static Class<?> classToTest;
static Object instance; static Object instance;
@BeforeClass @BeforeAll
public static void beforeClass() throws Exception { public static void beforeClass() throws Exception {
var classFiles = TestCodegen.generateClassFiles(new ByteArrayClassLoader(), "GreaterEqual.jav"); var classFiles = TestCodegen.generateClassFiles(TestCodegen.createClassLoader(), "GreaterEqual.jav");
classToTest = classFiles.get("GreaterEqual"); classToTest = classFiles.get("GreaterEqual");
instance = classToTest.getDeclaredConstructor().newInstance(); instance = classToTest.getDeclaredConstructor().newInstance();
} }

View File

@@ -1,21 +1,20 @@
package targetast; package targetast;
import de.dhbwstuttgart.environment.ByteArrayClassLoader; import org.junit.jupiter.api.BeforeAll;
import org.junit.BeforeClass; import org.junit.jupiter.api.Test;
import org.junit.Test;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import static org.junit.Assert.assertFalse; import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.Assert.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
public class GreaterThanTest { public class GreaterThanTest {
static Class<?> classToTest; static Class<?> classToTest;
static Object instance; static Object instance;
@BeforeClass @BeforeAll
public static void beforeClass() throws Exception { public static void beforeClass() throws Exception {
var classFiles = TestCodegen.generateClassFiles(new ByteArrayClassLoader(), "GreaterThan.jav"); var classFiles = TestCodegen.generateClassFiles(TestCodegen.createClassLoader(), "GreaterThan.jav");
classToTest = classFiles.get("GreaterThan"); classToTest = classFiles.get("GreaterThan");
instance = classToTest.getDeclaredConstructor().newInstance(); instance = classToTest.getDeclaredConstructor().newInstance();
} }

View File

@@ -1,22 +1,20 @@
package targetast; package targetast;
import de.dhbwstuttgart.environment.ByteArrayClassLoader; import org.junit.jupiter.api.BeforeAll;
import org.junit.BeforeClass; import org.junit.jupiter.api.Test;
import org.junit.Test;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.nio.file.Path;
import java.util.Vector; import java.util.Vector;
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
public class InheritTest { public class InheritTest {
private static Class<?> classToTest, classToTestAA, classToTestBB, classToTestCC, classToTestDD; private static Class<?> classToTest, classToTestAA, classToTestBB, classToTestCC, classToTestDD;
private static Object instanceOfClass, instanceOfClassAA, instanceOfClassBB, instanceOfClassCC, instanceOfClassDD; private static Object instanceOfClass, instanceOfClassAA, instanceOfClassBB, instanceOfClassCC, instanceOfClassDD;
@BeforeClass @BeforeAll
public static void setUpBeforeClass() throws Exception { public static void setUpBeforeClass() throws Exception {
var classLoader = new ByteArrayClassLoader(); var classLoader = TestCodegen.createClassLoader();
var classes = TestCodegen.generateClassFiles(classLoader, "Inherit.jav"); var classes = TestCodegen.generateClassFiles(classLoader, "Inherit.jav");
classToTest = classes.get("Inherit"); classToTest = classes.get("Inherit");
@@ -35,72 +33,72 @@ public class InheritTest {
@Test @Test
public void testmainAA() throws Exception { public void testmainAA() throws Exception {
Method m = classToTestAA.getDeclaredMethod("m", Integer.class); Method m = classToTestAA.getDeclaredMethod("m", Integer.class);
assertEquals(m.invoke(instanceOfClassAA, 5), "AA"); assertEquals("AA", m.invoke(instanceOfClassAA, 5));
Method main = classToTest.getDeclaredMethod("main", classToTestAA, Integer.class); Method main = classToTest.getDeclaredMethod("main", classToTestAA, Integer.class);
assertEquals(main.invoke(instanceOfClass, instanceOfClassAA, 5), "AA"); assertEquals("AA", main.invoke(instanceOfClass, instanceOfClassAA, 5));
} }
@Test @Test
public void testmainBB() throws Exception { public void testmainBB() throws Exception {
Method m = classToTestAA.getDeclaredMethod("m", Integer.class); Method m = classToTestAA.getDeclaredMethod("m", Integer.class);
assertEquals(m.invoke(instanceOfClassBB, 5), "AA"); assertEquals("AA", m.invoke(instanceOfClassBB, 5));
Method main = classToTest.getDeclaredMethod("main", classToTestAA, Integer.class); Method main = classToTest.getDeclaredMethod("main", classToTestAA, Integer.class);
assertEquals(main.invoke(instanceOfClass, instanceOfClassBB, 5), "AA"); assertEquals("AA", main.invoke(instanceOfClass, instanceOfClassBB, 5));
} }
@Test @Test
public void testmainCC() throws Exception { public void testmainCC() throws Exception {
Method m = classToTestCC.getDeclaredMethod("m", Integer.class); Method m = classToTestCC.getDeclaredMethod("m", Integer.class);
assertEquals(m.invoke(instanceOfClassCC, 5), "CC"); assertEquals("CC", m.invoke(instanceOfClassCC, 5));
Method main = classToTest.getDeclaredMethod("main", classToTestCC, Integer.class); Method main = classToTest.getDeclaredMethod("main", classToTestCC, Integer.class);
assertEquals(main.invoke(instanceOfClass, instanceOfClassCC, 5), "CC"); assertEquals("CC", main.invoke(instanceOfClass, instanceOfClassCC, 5));
} }
@Test @Test
public void testmainDD() throws Exception { public void testmainDD() throws Exception {
Method m = classToTestCC.getDeclaredMethod("m", Integer.class); Method m = classToTestCC.getDeclaredMethod("m", Integer.class);
assertEquals(m.invoke(instanceOfClassDD, 5), "CC"); assertEquals("CC", m.invoke(instanceOfClassDD, 5));
Method main = classToTest.getDeclaredMethod("main", classToTestCC, Integer.class); Method main = classToTest.getDeclaredMethod("main", classToTestCC, Integer.class);
assertEquals(main.invoke(instanceOfClass, instanceOfClassDD, 5), "CC"); assertEquals("CC", main.invoke(instanceOfClass, instanceOfClassDD, 5));
} }
@Test @Test
public void testmainVectorAA() throws Exception { public void testmainVectorAA() throws Exception {
Method m = classToTestAA.getDeclaredMethod("m", Integer.class); Method m = classToTestAA.getDeclaredMethod("m", Integer.class);
assertEquals(m.invoke(instanceOfClassAA, 5), "AA"); assertEquals("AA", m.invoke(instanceOfClassAA, 5));
Vector v = new Vector<>(); Vector v = new Vector<>();
v.add(instanceOfClassAA); v.add(instanceOfClassAA);
Method main = classToTest.getDeclaredMethod("main", Vector.class, Integer.class); Method main = classToTest.getDeclaredMethod("main", Vector.class, Integer.class);
assertEquals(main.invoke(instanceOfClass, v, 5), "AA"); assertEquals("AA", main.invoke(instanceOfClass, v, 5));
} }
@Test @Test
public void testmainVectorBB() throws Exception { public void testmainVectorBB() throws Exception {
Method m = classToTestAA.getDeclaredMethod("m", Integer.class); Method m = classToTestAA.getDeclaredMethod("m", Integer.class);
assertEquals(m.invoke(instanceOfClassBB, 5), "AA"); assertEquals("AA", m.invoke(instanceOfClassBB, 5));
Vector v = new Vector<>(); Vector v = new Vector<>();
v.add(instanceOfClassBB); v.add(instanceOfClassBB);
Method main = classToTest.getDeclaredMethod("main", Vector.class, Integer.class); Method main = classToTest.getDeclaredMethod("main", Vector.class, Integer.class);
assertEquals(main.invoke(instanceOfClass, v, 5), "AA"); assertEquals("AA", main.invoke(instanceOfClass, v, 5));
} }
@Test @Test
public void testmainVectorCC() throws Exception { public void testmainVectorCC() throws Exception {
Method m = classToTestCC.getDeclaredMethod("m", Integer.class); Method m = classToTestCC.getDeclaredMethod("m", Integer.class);
assertEquals(m.invoke(instanceOfClassCC, 5), "CC"); assertEquals("CC", m.invoke(instanceOfClassCC, 5));
Vector v = new Vector<>(); Vector v = new Vector<>();
v.add(instanceOfClassCC); v.add(instanceOfClassCC);
Method main = classToTest.getDeclaredMethod("main", Vector.class, Integer.class); Method main = classToTest.getDeclaredMethod("main", Vector.class, Integer.class);
assertEquals(main.invoke(instanceOfClass, v, 5), "CC"); assertEquals("CC", main.invoke(instanceOfClass, v, 5));
} }
@Test @Test
public void testmainVectorDD() throws Exception { public void testmainVectorDD() throws Exception {
Method m = classToTestCC.getDeclaredMethod("m", Integer.class); Method m = classToTestCC.getDeclaredMethod("m", Integer.class);
assertEquals(m.invoke(instanceOfClassDD, 5), "CC"); assertEquals("CC", m.invoke(instanceOfClassDD, 5));
Vector v = new Vector<>(); Vector v = new Vector<>();
v.add(instanceOfClassDD); v.add(instanceOfClassDD);
Method main = classToTest.getDeclaredMethod("main", Vector.class, Integer.class); Method main = classToTest.getDeclaredMethod("main", Vector.class, Integer.class);
assertEquals(main.invoke(instanceOfClass, v, 5), "CC"); assertEquals("CC", main.invoke(instanceOfClass, v, 5));
} }
} }

View File

@@ -1,23 +1,22 @@
package targetast; package targetast;
import de.dhbwstuttgart.environment.ByteArrayClassLoader; import org.junit.jupiter.api.BeforeAll;
import org.junit.BeforeClass; import org.junit.jupiter.api.Disabled;
import org.junit.Ignore; import org.junit.jupiter.api.Test;
import org.junit.Test;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.util.Vector; import java.util.Vector;
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
@Ignore("FIXME") @Disabled("FIXME")
public class InheritTest2 { public class InheritTest2 {
private static Class<?> classToTest, classToTestAA, classToTestBB, classToTestCC, classToTestDD; private static Class<?> classToTest, classToTestAA, classToTestBB, classToTestCC, classToTestDD;
private static Object instanceOfClass, instanceOfClassAA, instanceOfClassBB, instanceOfClassCC, instanceOfClassDD; private static Object instanceOfClass, instanceOfClassAA, instanceOfClassBB, instanceOfClassCC, instanceOfClassDD;
@BeforeClass @BeforeAll
public static void setUpBeforeClass() throws Exception { public static void setUpBeforeClass() throws Exception {
var classLoader = new ByteArrayClassLoader(); var classLoader = TestCodegen.createClassLoader();
classToTest = TestCodegen.generateClassFiles(classLoader, "Inherit2.jav").get("Inherit2"); classToTest = TestCodegen.generateClassFiles(classLoader, "Inherit2.jav").get("Inherit2");
classToTestAA = TestCodegen.generateClassFiles(classLoader, "AA.jav").get("AA"); classToTestAA = TestCodegen.generateClassFiles(classLoader, "AA.jav").get("AA");
classToTestBB = TestCodegen.generateClassFiles(classLoader, "BB.jav").get("BB"); classToTestBB = TestCodegen.generateClassFiles(classLoader, "BB.jav").get("BB");

View File

@@ -1,21 +1,20 @@
package targetast; package targetast;
import de.dhbwstuttgart.environment.ByteArrayClassLoader; import org.junit.jupiter.api.BeforeAll;
import org.junit.BeforeClass; import org.junit.jupiter.api.Test;
import org.junit.Test;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import static org.junit.Assert.assertFalse; import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.Assert.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
public class LessEqualTest { public class LessEqualTest {
static Class<?> classToTest; static Class<?> classToTest;
static Object instance; static Object instance;
@BeforeClass @BeforeAll
public static void beforeClass() throws Exception { public static void beforeClass() throws Exception {
var classFiles = TestCodegen.generateClassFiles(new ByteArrayClassLoader(), "LessEqual.jav"); var classFiles = TestCodegen.generateClassFiles(TestCodegen.createClassLoader(), "LessEqual.jav");
classToTest = classFiles.get("LessEqual"); classToTest = classFiles.get("LessEqual");
instance = classToTest.getDeclaredConstructor().newInstance(); instance = classToTest.getDeclaredConstructor().newInstance();
} }

View File

@@ -1,21 +1,20 @@
package targetast; package targetast;
import de.dhbwstuttgart.environment.ByteArrayClassLoader; import org.junit.jupiter.api.BeforeAll;
import org.junit.BeforeClass; import org.junit.jupiter.api.Test;
import org.junit.Test;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import static org.junit.Assert.assertFalse; import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.Assert.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
public class LessThanTest { public class LessThanTest {
static Class<?> classToTest; static Class<?> classToTest;
static Object instance; static Object instance;
@BeforeClass @BeforeAll
public static void beforeClass() throws Exception { public static void beforeClass() throws Exception {
var classFiles = TestCodegen.generateClassFiles(new ByteArrayClassLoader(), "LessThan.jav"); var classFiles = TestCodegen.generateClassFiles(TestCodegen.createClassLoader(), "LessThan.jav");
classToTest = classFiles.get("LessThan"); classToTest = classFiles.get("LessThan");
instance = classToTest.getDeclaredConstructor().newInstance(); instance = classToTest.getDeclaredConstructor().newInstance();
} }

View File

@@ -1,12 +1,12 @@
package targetast; package targetast;
import de.dhbwstuttgart.environment.ByteArrayClassLoader; import org.junit.jupiter.api.BeforeAll;
import org.junit.BeforeClass; import org.junit.jupiter.api.Test;
import org.junit.Test;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
public class OLTest { public class OLTest {
private static Class<?> classToTest; private static Class<?> classToTest;
@@ -14,9 +14,9 @@ public class OLTest {
private static Object instanceOfClass; private static Object instanceOfClass;
private static Object instanceOfClass1; private static Object instanceOfClass1;
@BeforeClass @BeforeAll
public static void setUpBeforeClass() throws Exception { public static void setUpBeforeClass() throws Exception {
var classFiles = TestCodegen.generateClassFiles(new ByteArrayClassLoader(), "OL.jav"); var classFiles = TestCodegen.generateClassFiles(TestCodegen.createClassLoader(), "OL.jav");
classToTest = classFiles.get("OL"); classToTest = classFiles.get("OL");
instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); instanceOfClass = classToTest.getDeclaredConstructor().newInstance();
classToTest1 = classFiles.get("OLMain"); classToTest1 = classFiles.get("OLMain");

View File

@@ -1,20 +1,19 @@
package targetast; package targetast;
import de.dhbwstuttgart.environment.ByteArrayClassLoader; import org.junit.jupiter.api.BeforeAll;
import org.junit.BeforeClass; import org.junit.jupiter.api.Test;
import org.junit.Test;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
public class PostIncTest { public class PostIncTest {
private static Class<?> classToTest; private static Class<?> classToTest;
private static Object instanceOfClass; private static Object instanceOfClass;
@BeforeClass @BeforeAll
public static void setUpBeforeClass() throws Exception { public static void setUpBeforeClass() throws Exception {
var classFiles = TestCodegen.generateClassFiles(new ByteArrayClassLoader(), "PostIncDec.jav"); var classFiles = TestCodegen.generateClassFiles(TestCodegen.createClassLoader(), "PostIncDec.jav");
classToTest = classFiles.get("PostIncDec"); classToTest = classFiles.get("PostIncDec");
instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); instanceOfClass = classToTest.getDeclaredConstructor().newInstance();
} }

View File

@@ -1,20 +1,19 @@
package targetast; package targetast;
import de.dhbwstuttgart.environment.ByteArrayClassLoader; import org.junit.jupiter.api.BeforeAll;
import org.junit.BeforeClass; import org.junit.jupiter.api.Test;
import org.junit.Test;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
public class PreIncTest { public class PreIncTest {
private static Class<?> classToTest; private static Class<?> classToTest;
private static Object instanceOfClass; private static Object instanceOfClass;
@BeforeClass @BeforeAll
public static void setUpBeforeClass() throws Exception { public static void setUpBeforeClass() throws Exception {
var classFiles = TestCodegen.generateClassFiles(new ByteArrayClassLoader(), "PreInc.jav"); var classFiles = TestCodegen.generateClassFiles(TestCodegen.createClassLoader(), "PreInc.jav");
classToTest = classFiles.get("PreInc"); classToTest = classFiles.get("PreInc");
instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); instanceOfClass = classToTest.getDeclaredConstructor().newInstance();
} }

View File

@@ -1,22 +1,21 @@
package targetast; package targetast;
import de.dhbwstuttgart.environment.ByteArrayClassLoader; import org.junit.jupiter.api.BeforeAll;
import org.junit.BeforeClass; import org.junit.jupiter.api.Test;
import org.junit.Test;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.util.Stack; import java.util.Stack;
import java.util.Vector; import java.util.Vector;
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
public class PutTest { public class PutTest {
private static Class<?> classToTest; private static Class<?> classToTest;
private static Object instanceOfClass; private static Object instanceOfClass;
@BeforeClass @BeforeAll
public static void setUpBeforeClass() throws Exception { public static void setUpBeforeClass() throws Exception {
var classFiles = TestCodegen.generateClassFiles(new ByteArrayClassLoader(), "Put.jav"); var classFiles = TestCodegen.generateClassFiles(TestCodegen.createClassLoader(), "Put.jav");
classToTest = classFiles.get("Put"); classToTest = classFiles.get("Put");
instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); instanceOfClass = classToTest.getDeclaredConstructor().newInstance();
} }

View File

@@ -2,7 +2,7 @@ package targetast;
import de.dhbwstuttgart.core.JavaTXCompiler; import de.dhbwstuttgart.core.JavaTXCompiler;
import de.dhbwstuttgart.bytecode.Codegen; import de.dhbwstuttgart.bytecode.Codegen;
import de.dhbwstuttgart.environment.ByteArrayClassLoader; import de.dhbwstuttgart.environment.DirectoryClassLoader;
import de.dhbwstuttgart.environment.IByteArrayClassLoader; import de.dhbwstuttgart.environment.IByteArrayClassLoader;
import de.dhbwstuttgart.parser.scope.JavaClassName; import de.dhbwstuttgart.parser.scope.JavaClassName;
import de.dhbwstuttgart.target.generate.ASTToTargetAST; import de.dhbwstuttgart.target.generate.ASTToTargetAST;
@@ -14,10 +14,10 @@ import de.dhbwstuttgart.target.tree.expression.*;
import de.dhbwstuttgart.target.tree.type.TargetFunNType; import de.dhbwstuttgart.target.tree.type.TargetFunNType;
import de.dhbwstuttgart.target.tree.type.TargetRefType; import de.dhbwstuttgart.target.tree.type.TargetRefType;
import de.dhbwstuttgart.target.tree.type.TargetType; import de.dhbwstuttgart.target.tree.type.TargetType;
import org.junit.Ignore; import org.junit.jupiter.api.Disabled;
import org.junit.Test; import org.junit.jupiter.api.Test;
import static org.junit.Assert.*; import static org.junit.jupiter.api.Assertions.*;
import org.objectweb.asm.Opcodes; import org.objectweb.asm.Opcodes;
@@ -37,6 +37,10 @@ public class TestCodegen {
Files.write(outputPath.resolve(name + ".class"), code); Files.write(outputPath.resolve(name + ".class"), code);
} }
public static IByteArrayClassLoader createClassLoader() {
return new DirectoryClassLoader(List.of(outputPath.toFile()), ClassLoader.getSystemClassLoader());
}
public static Path path = Path.of(System.getProperty("user.dir"), "resources/bytecode/javFiles/"); public static Path path = Path.of(System.getProperty("user.dir"), "resources/bytecode/javFiles/");
public static Map<String, ? extends Class<?>> generateClassFiles(IByteArrayClassLoader classLoader, String... files) throws IOException, ClassNotFoundException { public static Map<String, ? extends Class<?>> generateClassFiles(IByteArrayClassLoader classLoader, String... files) throws IOException, ClassNotFoundException {
@@ -119,7 +123,7 @@ public class TestCodegen {
public void testEmptyClass() throws Exception { public void testEmptyClass() throws Exception {
var clazz = new TargetClass(Opcodes.ACC_PUBLIC, new JavaClassName("Empty")); var clazz = new TargetClass(Opcodes.ACC_PUBLIC, new JavaClassName("Empty"));
clazz.addMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "main", List.of(), null, new TargetBlock(List.of())); clazz.addMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "main", List.of(), null, new TargetBlock(List.of()));
generateClass(clazz, new ByteArrayClassLoader()).getDeclaredMethod("main").invoke(null); generateClass(clazz, createClassLoader()).getDeclaredMethod("main").invoke(null);
} }
@Test @Test
@@ -132,7 +136,7 @@ public class TestCodegen {
targetClass.addMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "mul", List.of(new MethodParameter(TargetType.Integer, "a"), new MethodParameter(TargetType.Integer, "b")), TargetType.Integer, new TargetBlock(List.of(new TargetReturn(new TargetBinaryOp.Mul(TargetType.Integer, new TargetLocalVar(TargetType.Integer, "a"), new TargetLocalVar(TargetType.Integer, "b")))))); targetClass.addMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "mul", List.of(new MethodParameter(TargetType.Integer, "a"), new MethodParameter(TargetType.Integer, "b")), TargetType.Integer, new TargetBlock(List.of(new TargetReturn(new TargetBinaryOp.Mul(TargetType.Integer, new TargetLocalVar(TargetType.Integer, "a"), new TargetLocalVar(TargetType.Integer, "b"))))));
targetClass.addMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "rem", List.of(new MethodParameter(TargetType.Integer, "a"), new MethodParameter(TargetType.Integer, "b")), TargetType.Integer, new TargetBlock(List.of(new TargetReturn(new TargetBinaryOp.Rem(TargetType.Integer, new TargetLocalVar(TargetType.Integer, "a"), new TargetLocalVar(TargetType.Integer, "b")))))); targetClass.addMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "rem", List.of(new MethodParameter(TargetType.Integer, "a"), new MethodParameter(TargetType.Integer, "b")), TargetType.Integer, new TargetBlock(List.of(new TargetReturn(new TargetBinaryOp.Rem(TargetType.Integer, new TargetLocalVar(TargetType.Integer, "a"), new TargetLocalVar(TargetType.Integer, "b"))))));
var clazz = generateClass(targetClass, new ByteArrayClassLoader()); var clazz = generateClass(targetClass, createClassLoader());
assertEquals(clazz.getDeclaredMethod("add", Integer.class, Integer.class).invoke(null, 10, 10), 20); assertEquals(clazz.getDeclaredMethod("add", Integer.class, Integer.class).invoke(null, 10, 10), 20);
assertEquals(clazz.getDeclaredMethod("sub", Integer.class, Integer.class).invoke(null, 20, 10), 10); assertEquals(clazz.getDeclaredMethod("sub", Integer.class, Integer.class).invoke(null, 20, 10), 10);
assertEquals(clazz.getDeclaredMethod("div", Integer.class, Integer.class).invoke(null, 20, 10), 2); assertEquals(clazz.getDeclaredMethod("div", Integer.class, Integer.class).invoke(null, 20, 10), 2);
@@ -148,7 +152,7 @@ public class TestCodegen {
targetClass.addMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "neg", List.of(new MethodParameter(TargetType.Integer, "a")), TargetType.Integer, new TargetBlock(List.of(new TargetReturn(new TargetUnaryOp.Negate(TargetType.Integer, new TargetLocalVar(TargetType.Integer, "a")))))); targetClass.addMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "neg", List.of(new MethodParameter(TargetType.Integer, "a")), TargetType.Integer, new TargetBlock(List.of(new TargetReturn(new TargetUnaryOp.Negate(TargetType.Integer, new TargetLocalVar(TargetType.Integer, "a"))))));
targetClass.addMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "add", List.of(new MethodParameter(TargetType.Integer, "a")), TargetType.Integer, new TargetBlock(List.of(new TargetReturn(new TargetUnaryOp.Add(TargetType.Integer, new TargetLocalVar(TargetType.Integer, "a")))))); targetClass.addMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "add", List.of(new MethodParameter(TargetType.Integer, "a")), TargetType.Integer, new TargetBlock(List.of(new TargetReturn(new TargetUnaryOp.Add(TargetType.Integer, new TargetLocalVar(TargetType.Integer, "a"))))));
var clazz = generateClass(targetClass, new ByteArrayClassLoader()); var clazz = generateClass(targetClass, createClassLoader());
assertEquals(clazz.getDeclaredMethod("not", Integer.class).invoke(null, 10), -11); assertEquals(clazz.getDeclaredMethod("not", Integer.class).invoke(null, 10), -11);
assertEquals(clazz.getDeclaredMethod("neg", Integer.class).invoke(null, 10), -10); assertEquals(clazz.getDeclaredMethod("neg", Integer.class).invoke(null, 10), -10);
assertEquals(clazz.getDeclaredMethod("add", Integer.class).invoke(null, 10), 10); assertEquals(clazz.getDeclaredMethod("add", Integer.class).invoke(null, 10), 10);
@@ -162,7 +166,7 @@ public class TestCodegen {
targetClass.addMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "and", List.of(new MethodParameter(TargetType.Boolean, "a"), new MethodParameter(TargetType.Boolean, "b")), TargetType.Boolean, new TargetBlock(List.of(new TargetReturn(new TargetBinaryOp.And(TargetType.Boolean, new TargetLocalVar(TargetType.Boolean, "a"), new TargetLocalVar(TargetType.Boolean, "b")))))); targetClass.addMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "and", List.of(new MethodParameter(TargetType.Boolean, "a"), new MethodParameter(TargetType.Boolean, "b")), TargetType.Boolean, new TargetBlock(List.of(new TargetReturn(new TargetBinaryOp.And(TargetType.Boolean, new TargetLocalVar(TargetType.Boolean, "a"), new TargetLocalVar(TargetType.Boolean, "b"))))));
targetClass.addMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "or", List.of(new MethodParameter(TargetType.Boolean, "a"), new MethodParameter(TargetType.Boolean, "b")), TargetType.Boolean, new TargetBlock(List.of(new TargetReturn(new TargetBinaryOp.Or(TargetType.Boolean, new TargetLocalVar(TargetType.Boolean, "a"), new TargetLocalVar(TargetType.Boolean, "b")))))); targetClass.addMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "or", List.of(new MethodParameter(TargetType.Boolean, "a"), new MethodParameter(TargetType.Boolean, "b")), TargetType.Boolean, new TargetBlock(List.of(new TargetReturn(new TargetBinaryOp.Or(TargetType.Boolean, new TargetLocalVar(TargetType.Boolean, "a"), new TargetLocalVar(TargetType.Boolean, "b"))))));
var clazz = generateClass(targetClass, new ByteArrayClassLoader()); var clazz = generateClass(targetClass, createClassLoader());
var and = clazz.getDeclaredMethod("and", Boolean.class, Boolean.class); var and = clazz.getDeclaredMethod("and", Boolean.class, Boolean.class);
var or = clazz.getDeclaredMethod("or", Boolean.class, Boolean.class); var or = clazz.getDeclaredMethod("or", Boolean.class, Boolean.class);
assertEquals(and.invoke(null, true, false), false); assertEquals(and.invoke(null, true, false), false);
@@ -176,7 +180,7 @@ public class TestCodegen {
public void testArithmeticConvert() throws Exception { public void testArithmeticConvert() throws Exception {
var targetClass = new TargetClass(Opcodes.ACC_PUBLIC, new JavaClassName("ArithmeticConvert")); var targetClass = new TargetClass(Opcodes.ACC_PUBLIC, new JavaClassName("ArithmeticConvert"));
targetClass.addMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "add", List.of(), TargetType.Long, new TargetBlock(List.of(new TargetReturn(new TargetBinaryOp.Add(TargetType.Long, new TargetLiteral.CharLiteral((char) 10), new TargetLiteral.LongLiteral((long) 20)))))); targetClass.addMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "add", List.of(), TargetType.Long, new TargetBlock(List.of(new TargetReturn(new TargetBinaryOp.Add(TargetType.Long, new TargetLiteral.CharLiteral((char) 10), new TargetLiteral.LongLiteral((long) 20))))));
var clazz = generateClass(targetClass, new ByteArrayClassLoader()); var clazz = generateClass(targetClass, createClassLoader());
assertEquals(clazz.getDeclaredMethod("add").invoke(null), (long) 30); assertEquals(clazz.getDeclaredMethod("add").invoke(null), (long) 30);
} }
@@ -185,7 +189,7 @@ public class TestCodegen {
var targetClass = new TargetClass(Opcodes.ACC_PUBLIC, new JavaClassName("HelloWorld")); var targetClass = new TargetClass(Opcodes.ACC_PUBLIC, new JavaClassName("HelloWorld"));
targetClass.addMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "helloWorld", List.of(), null, new TargetBlock(List.of(new TargetMethodCall(null, new TargetFieldVar(new TargetRefType("java.io.PrintStream"), new TargetRefType("java.lang.System"), true, new TargetClassName(new TargetRefType("java.lang.System")), "out"), List.of(new TargetLiteral.StringLiteral("Hello World!")), new TargetRefType("java.io.PrintStream"), "println", false, false, false)))); targetClass.addMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "helloWorld", List.of(), null, new TargetBlock(List.of(new TargetMethodCall(null, new TargetFieldVar(new TargetRefType("java.io.PrintStream"), new TargetRefType("java.lang.System"), true, new TargetClassName(new TargetRefType("java.lang.System")), "out"), List.of(new TargetLiteral.StringLiteral("Hello World!")), new TargetRefType("java.io.PrintStream"), "println", false, false, false))));
var clazz = generateClass(targetClass, new ByteArrayClassLoader()); var clazz = generateClass(targetClass, createClassLoader());
clazz.getDeclaredMethod("helloWorld").invoke(null); clazz.getDeclaredMethod("helloWorld").invoke(null);
} }
@@ -193,7 +197,7 @@ public class TestCodegen {
public void testIfStatement() throws Exception { public void testIfStatement() throws Exception {
var targetClass = new TargetClass(Opcodes.ACC_PUBLIC, new JavaClassName("IfStmt")); var targetClass = new TargetClass(Opcodes.ACC_PUBLIC, new JavaClassName("IfStmt"));
targetClass.addMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "ifStmt", List.of(new MethodParameter(TargetType.Integer, "val")), TargetType.Integer, new TargetBlock(List.of(new TargetIf(new TargetBinaryOp.Equal(TargetType.Integer, new TargetLocalVar(TargetType.Integer, "val"), new TargetLiteral.IntLiteral(10)), new TargetReturn(new TargetLiteral.IntLiteral(1)), new TargetIf(new TargetBinaryOp.Less(TargetType.Integer, new TargetLocalVar(TargetType.Integer, "val"), new TargetLiteral.IntLiteral(5)), new TargetReturn(new TargetLiteral.IntLiteral(2)), new TargetReturn(new TargetLiteral.IntLiteral(3))))))); targetClass.addMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "ifStmt", List.of(new MethodParameter(TargetType.Integer, "val")), TargetType.Integer, new TargetBlock(List.of(new TargetIf(new TargetBinaryOp.Equal(TargetType.Integer, new TargetLocalVar(TargetType.Integer, "val"), new TargetLiteral.IntLiteral(10)), new TargetReturn(new TargetLiteral.IntLiteral(1)), new TargetIf(new TargetBinaryOp.Less(TargetType.Integer, new TargetLocalVar(TargetType.Integer, "val"), new TargetLiteral.IntLiteral(5)), new TargetReturn(new TargetLiteral.IntLiteral(2)), new TargetReturn(new TargetLiteral.IntLiteral(3)))))));
var clazz = generateClass(targetClass, new ByteArrayClassLoader()); var clazz = generateClass(targetClass, createClassLoader());
var ifStmt = clazz.getDeclaredMethod("ifStmt", Integer.class); var ifStmt = clazz.getDeclaredMethod("ifStmt", Integer.class);
assertEquals(ifStmt.invoke(null, 10), 1); assertEquals(ifStmt.invoke(null, 10), 1);
assertEquals(ifStmt.invoke(null, 3), 2); assertEquals(ifStmt.invoke(null, 3), 2);
@@ -204,7 +208,7 @@ public class TestCodegen {
public void testFor() throws Exception { public void testFor() throws Exception {
var targetClass = new TargetClass(Opcodes.ACC_PUBLIC, new JavaClassName("For")); var targetClass = new TargetClass(Opcodes.ACC_PUBLIC, new JavaClassName("For"));
targetClass.addMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "forLoop", List.of(), TargetType.Integer, new TargetBlock(List.of(new TargetVarDecl(TargetType.Integer, "sum", new TargetLiteral.IntLiteral(0)), new TargetFor(List.of(new TargetVarDecl(TargetType.Integer, "i", new TargetLiteral.IntLiteral(0))), new TargetBinaryOp.Less(TargetType.Integer, new TargetLocalVar(TargetType.Integer, "i"), new TargetLiteral.IntLiteral(10)), List.of(new TargetAssign(TargetType.Integer, new TargetLocalVar(TargetType.Integer, "i"), new TargetBinaryOp.Add(TargetType.Integer, new TargetLocalVar(TargetType.Integer, "i"), new TargetLiteral.IntLiteral(1)))), new TargetBlock(List.of(new TargetAssign(TargetType.Integer, new TargetLocalVar(TargetType.Integer, "sum"), new TargetBinaryOp.Add(TargetType.Integer, new TargetLocalVar(TargetType.Integer, "sum"), new TargetLocalVar(TargetType.Integer, "i")))))), new TargetReturn(new TargetLocalVar(TargetType.Integer, "sum"))))); targetClass.addMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "forLoop", List.of(), TargetType.Integer, new TargetBlock(List.of(new TargetVarDecl(TargetType.Integer, "sum", new TargetLiteral.IntLiteral(0)), new TargetFor(List.of(new TargetVarDecl(TargetType.Integer, "i", new TargetLiteral.IntLiteral(0))), new TargetBinaryOp.Less(TargetType.Integer, new TargetLocalVar(TargetType.Integer, "i"), new TargetLiteral.IntLiteral(10)), List.of(new TargetAssign(TargetType.Integer, new TargetLocalVar(TargetType.Integer, "i"), new TargetBinaryOp.Add(TargetType.Integer, new TargetLocalVar(TargetType.Integer, "i"), new TargetLiteral.IntLiteral(1)))), new TargetBlock(List.of(new TargetAssign(TargetType.Integer, new TargetLocalVar(TargetType.Integer, "sum"), new TargetBinaryOp.Add(TargetType.Integer, new TargetLocalVar(TargetType.Integer, "sum"), new TargetLocalVar(TargetType.Integer, "i")))))), new TargetReturn(new TargetLocalVar(TargetType.Integer, "sum")))));
var clazz = generateClass(targetClass, new ByteArrayClassLoader()); var clazz = generateClass(targetClass, createClassLoader());
assertEquals(clazz.getDeclaredMethod("forLoop").invoke(null), 45); assertEquals(clazz.getDeclaredMethod("forLoop").invoke(null), 45);
} }
@@ -212,7 +216,7 @@ public class TestCodegen {
public void testWhile() throws Exception { public void testWhile() throws Exception {
var targetClass = new TargetClass(Opcodes.ACC_PUBLIC, new JavaClassName("While")); var targetClass = new TargetClass(Opcodes.ACC_PUBLIC, new JavaClassName("While"));
targetClass.addMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "whileLoop", List.of(), TargetType.Integer, new TargetBlock(List.of(new TargetVarDecl(TargetType.Integer, "i", new TargetLiteral.IntLiteral(0)), new TargetWhile(new TargetBinaryOp.Less(TargetType.Integer, new TargetLocalVar(TargetType.Integer, "i"), new TargetLiteral.IntLiteral(10)), new TargetBlock(List.of(new TargetAssign(TargetType.Integer, new TargetLocalVar(TargetType.Integer, "i"), new TargetBinaryOp.Add(TargetType.Integer, new TargetLocalVar(TargetType.Integer, "i"), new TargetLiteral.IntLiteral(1)))))), new TargetReturn(new TargetLocalVar(TargetType.Integer, "i"))))); targetClass.addMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "whileLoop", List.of(), TargetType.Integer, new TargetBlock(List.of(new TargetVarDecl(TargetType.Integer, "i", new TargetLiteral.IntLiteral(0)), new TargetWhile(new TargetBinaryOp.Less(TargetType.Integer, new TargetLocalVar(TargetType.Integer, "i"), new TargetLiteral.IntLiteral(10)), new TargetBlock(List.of(new TargetAssign(TargetType.Integer, new TargetLocalVar(TargetType.Integer, "i"), new TargetBinaryOp.Add(TargetType.Integer, new TargetLocalVar(TargetType.Integer, "i"), new TargetLiteral.IntLiteral(1)))))), new TargetReturn(new TargetLocalVar(TargetType.Integer, "i")))));
var clazz = generateClass(targetClass, new ByteArrayClassLoader()); var clazz = generateClass(targetClass, createClassLoader());
assertEquals(clazz.getDeclaredMethod("whileLoop").invoke(null), 10); assertEquals(clazz.getDeclaredMethod("whileLoop").invoke(null), 10);
} }
@@ -235,7 +239,7 @@ public class TestCodegen {
new TargetReturn(new TargetLocalVar(TargetType.Integer, "res")) new TargetReturn(new TargetLocalVar(TargetType.Integer, "res"))
))); )));
var clazz = generateClass(targetClass, new ByteArrayClassLoader()); var clazz = generateClass(targetClass, createClassLoader());
var m = clazz.getDeclaredMethod("switchClassic", Integer.class); var m = clazz.getDeclaredMethod("switchClassic", Integer.class);
assertEquals(m.invoke(null, 10), 0); assertEquals(m.invoke(null, 10), 0);
assertEquals(m.invoke(null, 15), 1); assertEquals(m.invoke(null, 15), 1);
@@ -264,7 +268,7 @@ public class TestCodegen {
List.of(new TargetLiteral.IntLiteral(2)) List.of(new TargetLiteral.IntLiteral(2))
), true), TargetType.Integer) ), true), TargetType.Integer)
)))); ))));
var clazz = generateClass(targetClass, new ByteArrayClassLoader()); var clazz = generateClass(targetClass, createClassLoader());
var m = clazz.getDeclaredMethod("switchType", Object.class); var m = clazz.getDeclaredMethod("switchType", Object.class);
assertEquals(m.invoke(null, "String"), 0); assertEquals(m.invoke(null, "String"), 0);
assertEquals(m.invoke(null, 10), 1); assertEquals(m.invoke(null, 10), 1);
@@ -273,9 +277,9 @@ public class TestCodegen {
} }
@Test @Test
@Ignore("The lambda class is not generated because we don't call ASTToTargetAST") @Disabled("The lambda class is not generated because we don't call ASTToTargetAST")
public void testLambda() throws Exception { public void testLambda() throws Exception {
var classLoader = new ByteArrayClassLoader(); var classLoader = createClassLoader();
// var fun = classLoader.loadClass(Path.of(System.getProperty("user.dir"), "src/test/java/targetast/Fun1$$.class")); // var fun = classLoader.loadClass(Path.of(System.getProperty("user.dir"), "src/test/java/targetast/Fun1$$.class"));
var interfaceType = TargetFunNType.fromParams(List.of(TargetType.Integer), 1); var interfaceType = TargetFunNType.fromParams(List.of(TargetType.Integer), 1);

View File

@@ -12,9 +12,9 @@ import de.dhbwstuttgart.target.generate.Bound;
import static de.dhbwstuttgart.target.generate.Bound.*; import static de.dhbwstuttgart.target.generate.Bound.*;
import de.dhbwstuttgart.target.generate.BoundsList; import de.dhbwstuttgart.target.generate.BoundsList;
import de.dhbwstuttgart.target.generate.GenericsResult; import de.dhbwstuttgart.target.generate.GenericsResult;
import org.junit.Ignore; import org.junit.jupiter.api.Disabled;
import org.junit.Test; import org.junit.jupiter.api.Test;
import static org.junit.Assert.*; import static org.junit.jupiter.api.Assertions.*;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
@@ -22,7 +22,7 @@ import java.nio.file.Path;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@Ignore("TODO: Rewrite with the new algorithm") @Disabled("TODO: Rewrite with the new algorithm")
public class TestGenerics { public class TestGenerics {
private static final String rootDirectory = System.getProperty("user.dir") + "/resources/insertGenerics/javFiles/"; private static final String rootDirectory = System.getProperty("user.dir") + "/resources/insertGenerics/javFiles/";
private static final String bytecodeDirectory = System.getProperty("user.dir") + "targetTest"; private static final String bytecodeDirectory = System.getProperty("user.dir") + "targetTest";

View File

@@ -1,21 +1,21 @@
package targetast; package targetast;
import de.dhbwstuttgart.environment.ByteArrayClassLoader; import org.junit.jupiter.api.BeforeAll;
import org.junit.BeforeClass; import org.junit.jupiter.api.Test;
import org.junit.Test;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
public class TphTest { public class TphTest {
private static Class<?> classToTest; private static Class<?> classToTest;
private static Object instanceOfClass; private static Object instanceOfClass;
@BeforeClass @BeforeAll
public static void setUpBeforeClass() throws Exception { public static void setUpBeforeClass() throws Exception {
var classFiles = TestCodegen.generateClassFiles(new ByteArrayClassLoader(), "Tph.jav"); var classFiles = TestCodegen.generateClassFiles(TestCodegen.createClassLoader(), "Tph.jav");
classToTest = classFiles.get("Tph"); classToTest = classFiles.get("Tph");
instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); instanceOfClass = classToTest.getDeclaredConstructor().newInstance();
} }

View File

@@ -1,20 +1,19 @@
package targetast; package targetast;
import de.dhbwstuttgart.environment.ByteArrayClassLoader; import org.junit.jupiter.api.BeforeAll;
import org.junit.BeforeClass; import org.junit.jupiter.api.Test;
import org.junit.Test;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
public class WhileTest { public class WhileTest {
private static Class<?> classToTest; private static Class<?> classToTest;
private static Object instanceOfClass; private static Object instanceOfClass;
@BeforeClass @BeforeAll
public static void setUpBeforeClass() throws Exception { public static void setUpBeforeClass() throws Exception {
var classFiles = TestCodegen.generateClassFiles(new ByteArrayClassLoader(), "While.jav"); var classFiles = TestCodegen.generateClassFiles(TestCodegen.createClassLoader(), "While.jav");
classToTest = classFiles.get("While"); classToTest = classFiles.get("While");
instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); instanceOfClass = classToTest.getDeclaredConstructor().newInstance();
} }

View File

@@ -8,8 +8,8 @@ import de.dhbwstuttgart.typedeployment.TypeInsert;
import de.dhbwstuttgart.typedeployment.TypeInsertFactory; import de.dhbwstuttgart.typedeployment.TypeInsertFactory;
import de.dhbwstuttgart.typeinference.result.ResultSet; import de.dhbwstuttgart.typeinference.result.ResultSet;
import org.junit.Ignore; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.Disabled;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
@@ -22,7 +22,7 @@ import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
@Ignore("To be renewed") @Disabled("To be renewed")
public class JavaTXCompilerTest { public class JavaTXCompilerTest {
public static final String rootDirectory = System.getProperty("user.dir") + "/src/test/resources/javFiles/"; public static final String rootDirectory = System.getProperty("user.dir") + "/src/test/resources/javFiles/";