68 Commits

Author SHA1 Message Date
Fabian Holzwarth
133ca1fe41 feat: fix merge problems, update type inference to work with updated environment 2025-04-07 19:52:58 +02:00
Fabian Holzwarth
f9cf6fe722 Merge branch 'master' into feat/unification-webservice 2025-04-04 19:58:49 +02:00
Fabian Holzwarth
c0d8dc4692 chore: fix comment mistake and move tests to server-tests 2025-04-01 09:28:00 +02:00
Fabian Holzwarth
84f5f05672 feat: moved typeinference code from core to typeinference package
chore: optimize imports

feat: implement parameters for client-server separation

feat: add web sockets and packet communication

feat: add web sockets and packet communication

feat: Implement client to server data serialization

chore: adding comments, optimizing imports, formatting some code

feat: added some missing properties to packets

feat: make server configurable via arguments, cleanup some code
2025-04-01 09:14:53 +02:00
NoName11234
588036ea46 removed unused code 2024-03-15 15:49:15 +01:00
NoName11234
70b28bbfb0 removed debug variables 2024-03-15 14:54:14 +01:00
NoName11234
701962b0e7 code cleanup 2024-03-15 14:15:41 +01:00
NoName11234
e91a9370df removed threadcounter from TypeUnifyTask 2024-03-07 19:18:54 +01:00
NoName11234
d71e67cfdd Merge branch 'parallelUnifyResultModel' into unif23NoOptParallel_Lehmann 2024-02-21 18:10:03 +01:00
NoName11234
c2c2d6f445 implemented UnifyResultModelParallel in UnifyTest 2024-02-19 17:59:21 +01:00
NoName11234
7296e3de44 implemented UnifyResultModelParallel 2024-02-19 17:58:52 +01:00
NoName11234
c1aebaf1f5 implemented new class UnifyResultModelParallel 2024-02-19 17:27:16 +01:00
NoName11234
2871586c71 removed usesless variance in test 2024-02-06 18:39:44 +01:00
NoName11234
fa1f3a0507 removed unused statement 2024-02-05 19:39:36 +01:00
NoName11234
f66edd4c4b renamed helper methods 2024-02-05 19:27:06 +01:00
NoName11234
598fe8ebe9 renamed unify tests 2024-02-05 19:25:08 +01:00
NoName11234
41d97dfa80 Merge branch 'unif23NoOptParallel_Lehmann' of https://gitea.hb.dhbw-stuttgart.de/i21017/JavaCompilerCore into unif23NoOptParallel_Lehmann 2024-02-04 13:31:05 +01:00
NoName11234
0f18cedf90 implemented succesfully running test 2024-02-04 13:28:01 +01:00
f43d1f4f4f Merge pull request 'Update src/test/java/typeinference/UnifyTest.java' (#1) from stan-patch-Finite-Closure into unif23NoOptParallel_Lehmann
Reviewed-on: i21017/JavaCompilerCore#1
2024-02-04 12:03:32 +00:00
2a44773403 Update src/test/java/typeinference/UnifyTest.java
Die "Smaller" Relationen waren in falscher Richtung.
Außerdem müssen TypeParams bei List und AbstractList angefügt werden
2024-02-01 12:06:10 +00:00
NoName11234
a6ca31d509 changed UnifyTaskModel to UnifyTaskModelParallel 2024-01-30 19:37:47 +01:00
NoName11234
b13f2b357b removed old UnifyTaskModel from TypeUnify and TypeUnifyTask 2024-01-29 20:03:55 +01:00
NoName11234
45fa0ff0b9 added class for terminating calculations 2024-01-28 13:39:47 +01:00
NoName11234
c292ff2d9e added non-threaded close() method for logging 2024-01-25 20:08:32 +01:00
NoName11234
c14dd6e97c added support for non-threaded logging to WriterActiveObject 2024-01-25 19:55:56 +01:00
NoName11234
8f8ee9a385 fixed bug where constraints in test had undefinded placeholder 2024-01-24 22:20:13 +01:00
NoName11234
3863968a6e added smallest unify test possible 2024-01-23 18:59:39 +01:00
NoName11234
03c432455d fixed bug where statisticsFile was not initialized when using one of the constructors of TypeUnifyTask 2024-01-23 18:58:59 +01:00
NoName11234
441e50a70d removed useless synchronized-blocks and concenated multiple writes to logfile 2024-01-23 17:57:07 +01:00
NoName11234
0807885465 WriterActiveObject now uses same forkjointhreadpool as tasks 2024-01-21 22:16:35 +01:00
NoName11234
8abe7f6c28 updated classes to use WriterActiveObject for logging 2024-01-21 14:21:43 +01:00
NoName11234
2a92a0e48e added function for closing file to WriterActiveObject 2024-01-21 13:41:21 +01:00
NoName11234
b3639a3d08 removed synchronized(this) from TypeUnifyTask constructor 2024-01-20 23:23:08 +01:00
NoName11234
28969e7931 added class for thread safe writing in logfiles 2024-01-20 23:01:21 +01:00
NoName11234
b806fa88ff removed synchronized-block from writeLog() and writeStatistics() in TypeUnifyTask 2024-01-18 21:21:42 +01:00
NoName11234
301e9143ec changed output of unifyTest() 2024-01-18 21:20:48 +01:00
NoName11234
bb4eaaccc5 implemented unify test 2024-01-18 18:29:36 +01:00
NoName11234
4dbae46765 implemented list of UnifyPairs in test unifyTest() 2024-01-16 19:23:19 +01:00
NoName11234
c64071f235 Revert "added resources for tests"
This reverts commit 5aadb7545e.
2024-01-16 18:29:37 +01:00
NoName11234
94dbf1f7ad Revert "added resource files for testing"
This reverts commit 890f64c813.
2024-01-16 18:27:59 +01:00
NoName11234
890f64c813 added resource files for testing 2023-12-26 17:47:18 +01:00
NoName11234
5aadb7545e added resources for tests 2023-12-26 17:28:08 +01:00
NoName11234
0c0ac61a02 changed outputstream for debugging to NullOutputStream 2023-12-26 16:59:37 +01:00
NoName11234
46192e3fd3 changed java version from 19 to 21 2023-12-26 16:45:35 +01:00
pl@gohorb.ba-horb.de
61653c5d88 modified: src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java 2023-05-25 10:05:10 +02:00
pl@gohorb.ba-horb.de
3cd608a4ac modified: src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnify.java
modified:   src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java
2023-05-15 16:56:04 +02:00
pl@gohorb.ba-horb.de
deec0ae706 Start branch unif23NoOptParallel
modified:   Makefile
	modified:   src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java
	modified:   src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java
2023-04-24 17:18:45 +02:00
pl@gohorb.ba-horb.de
d6a79ea3a1 modified: src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java 2023-04-11 22:45:15 +02:00
pl@gohorb.ba-horb.de
1f909f13ee modified: src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java 2023-04-11 18:01:44 +02:00
pl@gohorb.ba-horb.de
be6f4bd578 Merge remote-tracking branch 'origin/targetBytecode' into unif23 2023-04-11 15:52:26 +02:00
pl@gohorb.ba-horb.de
478efd5649 Merge branch 'unif23' of ssh://gohorb.ba-horb.de/bahome/projekt/git/JavaCompilerCore into unif23 2023-04-11 15:40:27 +02:00
pl@gohorb.ba-horb.de
c73e57cf2b new file: resources/bytecode/javFiles/Scalar.jav 2023-04-11 15:35:15 +02:00
pl@gohorb.ba-horb.de
ce29f4bcf1 Merge branch 'unif23' of ssh://gohorb.ba-horb.de/bahome/projekt/git/JavaCompilerCore into Unif23
Conflicts:
	src/test/java/targetast/TestComplete.java
2023-04-10 22:14:46 +02:00
pl@gohorb.ba-horb.de
42821f3215 modified: src/main/java/de/dhbwstuttgart/typeinference/unify/RuleSet.java
modified:   src/test/java/targetast/TestComplete.java
2023-04-10 22:07:47 +02:00
pl@gohorb.ba-horb.de
f68afc88a6 modified: src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java 2023-04-06 17:58:32 +02:00
pl@gohorb.ba-horb.de
82061474b2 modified: resources/bytecode/javFiles/Scalar.jav
modified:   src/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java
2023-04-04 17:26:13 +02:00
pl@gohorb.ba-horb.de
d849bc127f Merge remote-tracking branch 'origin/targetBytecode' into unif23 2023-04-04 16:47:19 +02:00
pl@gohorb.ba-horb.de
6815d8fc0a modified: Makefile
modified:   src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java
2023-03-31 17:58:02 +02:00
pl@gohorb.ba-horb.de
317f8b1aad new file: Makefile
deleted:    Test.java
	modified:   src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java
2023-03-31 15:54:17 +02:00
pl@gohorb.ba-horb.de
79335449d0 modified: src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java
Statistics fertig (Version 1)
2023-03-23 12:00:04 +01:00
pl@gohorb.ba-horb.de
14606a846e modified: src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java
modified:   src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnify.java
	modified:   src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnify2Task.java
	modified:   src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java
2023-03-22 19:01:36 +01:00
2b67230a15 Consider public and standard constructors ones 2023-03-21 16:31:45 +01:00
pl@gohorb.ba-horb.de
29b05b56cc Merge branch 'targetBytecode' into unif23 2023-03-21 16:29:14 +01:00
pl@gohorb.ba-horb.de
08b9fc0ea3 modified: src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java
statistics eingefuegt
2023-03-21 16:23:18 +01:00
pl@gohorb.ba-horb.de
070dd16999 modified: src/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java 2023-03-21 10:30:13 +01:00
pl@gohorb.ba-horb.de
9d7e46925d modified: src/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java 2023-03-21 10:26:55 +01:00
pl@gohorb.ba-horb.de
d780d322f0 modified: src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java
modified:   src/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java
2023-03-20 18:33:58 +01:00
pl@gohorb.ba-horb.de
867f3d39e8 modified: src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java
modified:   src/test/java/targetast/TestComplete.java
2023-03-20 16:05:28 +01:00
215 changed files with 5326 additions and 7868 deletions

View File

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

3
Makefile Normal file
View File

@@ -0,0 +1,3 @@
NoOptParallel:
mvn -DskipTests package
cp target/JavaTXcompiler-0.1-jar-with-dependencies.jar target/JavaTXcompiler-0.1-jar-with-dependencies_NoOptParallel.jar

View File

@@ -1,40 +0,0 @@
#!/usr/bin/env bash
REPO="https://gitea.hb.dhbw-stuttgart.de/f.holzwarth/JavaCompilerCore.git"
TDIR="./testBuild"
rm -rf "$TDIR" 2>/dev/null
mkdir $TDIR
cd $TDIR
git clone $REPO .
git checkout feat/unify-server
# git checkout 93e1a8787cd94c73f4538f6a348f58613893a584
# git checkout dad468368b86bdd5a3d3b2754b17617cee0a9107 # 1:55
# git checkout a0c11b60e8c9d7addcbe0d3a09c9ce2924e9d5c0 # 2:25
# git checkout 4cddf73e6d6c9116d3e1705c4b27a8e7f18d80c3 # 2:27
# git checkout 6c2d97b7703d954e4a42eef3ec374bcf313af75c # 2:13
# git checkout f722a00fbb6e69423d48a890e4a6283471763e64 # 1:35
# git checkout f0a4a51ce65639ce9a9470ff0fdb538fdf9c02cc # 2:19
# git checkout 1391206dfe59263cdb22f93371cfd1dd5465d97f # 1:29
date "+%Y.%m.%d %H:%M:%S"
# sed -i -e 's/source>21/source>23/g' pom.xml
# sed -i -e 's/target>21/target>23/g' pom.xml
mvn clean compile -DskipTests package
time java -jar target/JavaTXcompiler-0.1-jar-with-dependencies.jar resources/bytecode/javFiles/Matrix.jav;
# mvn clean compile test
echo -e "\nCleanup... "
cd -
rm -rf "$TDIR" 2>/dev/null
echo -e "\nFinished "
date "+%Y.%m.%d %H:%M:%S"
echo -e "\n "

View File

@@ -44,6 +44,7 @@ http://maven.apache.org/maven-v4_0_0.xsd">
<artifactId>asm</artifactId>
<version>9.5</version>
</dependency>
<dependency>
<groupId>org.java-websocket</groupId>
<artifactId>Java-WebSocket</artifactId>
@@ -59,11 +60,7 @@ http://maven.apache.org/maven-v4_0_0.xsd">
<artifactId>jackson-databind</artifactId>
<version>2.17.2</version>
</dependency>
<dependency>
<groupId>com.diogonunes</groupId>
<artifactId>JColor</artifactId>
<version>5.5.1</version>
</dependency>
</dependencies>
<build>

View File

@@ -1,4 +1,4 @@
import java.util.Vector;
//import java.util.Vector;
import java.lang.Integer;
import java.lang.Float;
//import java.lang.Byte;
@@ -12,15 +12,14 @@ public class Scalar extends Vector<Integer> {
while(i < v.size()) {
this.add(v.elementAt(i));
i=i+1;
}
}
}
public mul(v) {
var ret = 0;
var i = 0;
while(i < size()) {
ret = ret + this.elementAt(i) * v.elementAt(i);
i = i+1;
}
return ret;
}

2
server-tests/.gitignore vendored Normal file
View File

@@ -0,0 +1,2 @@
out
outputs

13
server-tests/Lambda.jav Normal file
View File

@@ -0,0 +1,13 @@
class Apply { }
public class Lambda {
m () {
var lam1 = (x) -> {
return x;
};
return lam1.apply(new Apply());
}
}

28
server-tests/Matrix.jav Normal file
View File

@@ -0,0 +1,28 @@
import java.util.Vector;
import java.lang.Integer;
class Matrix extends Vector<Vector<Integer>> {
Integer mul1(Integer x, Integer y) { return x;}
Integer add1(Integer x, Integer y) { return x;}
mul(m) {
var ret = new Matrix();
var i = 0;
while(i < size()) {
var v1 = this.elementAt(i);
var v2 = new Vector<Integer>();
var j = 0;
while(j < v1.size()) {
var erg = 0;
var k = 0;
while(k < v1.size()) {
erg = erg + v1.elementAt(k) * m.elementAt(k).elementAt(j);
//erg = add1(erg, mul1(v1.elementAt(k),
// m.elementAt(k).elementAt(j)));
k++; }
v2.addElement(new Integer(erg));
j++; }
ret.addElement(v2);
i++; }
return ret;
}
}

25
server-tests/SomeList.jav Normal file
View File

@@ -0,0 +1,25 @@
import java.util.Vector;
import java.lang.Integer;
class SomeEvenMoreAbstractList<A, B> extends Vector<A> {
}
class SomeAbstractList<A, B> extends SomeEvenMoreAbstractList<A, B> {
}
class SomeList extends SomeAbstractList<Integer, Integer> {
mul(otherList) {
var result = new SomeList();
var i = 0;
while (i < 4) {
i++;
var a = this.elementAt(i);
var b = otherList.elementAt(i);
result.addElement(a * b);
}
return result;
}
}

21
server-tests/_runClient.sh Executable file
View File

@@ -0,0 +1,21 @@
#!/usr/bin/env bash
# build the compiler if -c is set
if [[ "${@,,}" == *"-c"* ]]; then
(cd .. && make || exit)
fi
# a very small and short running example
# JAV_FILE="Lambda.jav"
# a medium and average running example
JAV_FILE="SomeList.jav"
# a very large and long running example
# JAV_FILE="Matrix.jav"
# remove old generated files and run the compiler
rm -rf ./out/client
mkdir -p ./out/client \
&& java -jar ../target/JavaTXcompiler-0.1-jar-with-dependencies.jar -d ./out/client $JAV_FILE

12
server-tests/_runServer.sh Executable file
View File

@@ -0,0 +1,12 @@
#!/usr/bin/env bash
# build the compiler if -c is set
if [[ "${@,,}" == *"-c"* ]]; then
(cd .. && make || exit)
fi
# remove old generated files
rm -rf ./out/server
# run the server
mkdir -p ./out/server && java -jar ../target/JavaTXcompiler-0.1-jar-with-dependencies.jar -d ./out/server -server 5000

View File

@@ -8,20 +8,17 @@ import de.dhbwstuttgart.target.generate.ASTToTargetAST;
import de.dhbwstuttgart.target.tree.*;
import de.dhbwstuttgart.target.tree.expression.*;
import de.dhbwstuttgart.target.tree.type.*;
import de.dhbwstuttgart.util.Logger;
import org.objectweb.asm.*;
import java.lang.invoke.*;
import java.lang.reflect.Modifier;
import java.util.*;
import static org.objectweb.asm.Opcodes.*;
import static de.dhbwstuttgart.target.tree.expression.TargetBinaryOp.*;
import static de.dhbwstuttgart.target.tree.expression.TargetLiteral.*;
import static org.objectweb.asm.Opcodes.*;
public class Codegen {
public static Logger logger = new Logger("codegen");
private final TargetStructure clazz;
private final ClassWriter cw;
public final String className;
@@ -1320,7 +1317,7 @@ public class Codegen {
types.add(Type.getObjectType(guard.inner().type().getInternalName()));
// TODO Same here we need to evaluate constant;
} else {
logger.info(label);
System.out.println(label);
throw new NotImplementedException();
}
}
@@ -1533,7 +1530,7 @@ public class Codegen {
MethodVisitor mv = cw.visitMethod(constructor.access(), "<init>", constructor.getDescriptor(), constructor.getSignature(), null);
if (constructor.txGenerics() != null)
mv.visitAttribute(new JavaTXSignatureAttribute(constructor.getTXSignature()));
mv.visitCode();
var state = new State(null, mv, 1);
for (var param : constructor.parameters()) {

View File

@@ -120,7 +120,7 @@ public class FunNGenerator {
superFunNMethodDescriptor.append(")V");
}
Codegen.logger.info(superFunNMethodSignature);
System.out.println(superFunNMethodSignature);
ClassWriter classWriter = new ClassWriter(0);
MethodVisitor methodVisitor;

View File

@@ -1,81 +1,77 @@
package de.dhbwstuttgart.core;
import de.dhbwstuttgart.server.SocketClient;
import de.dhbwstuttgart.util.Logger;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
public class ConsoleInterface {
private static final String directory = System.getProperty("user.dir");
/**
* Leave the argument configurations here for the rest of the code to read
*/
public static Logger.LogLevel logLevel = Logger.LogLevel.ERROR;
public static boolean writeLogFiles = false;
public static Optional<String> unifyServerUrl = Optional.empty();
public static void main(String[] args) throws IOException, ClassNotFoundException {
List<File> input = new ArrayList<>();
List<File> classpath = new ArrayList<>();
String outputPath = null;
int runAsServerWithPort = -1;
String unificationServer = null;
public static void main(String[] args) throws IOException, ClassNotFoundException {
List<File> input = new ArrayList<>();
List<File> classpath = new ArrayList<>();
String outputPath = null;
Iterator<String> it = Arrays.asList(args).iterator();
Optional<Integer> serverPort = Optional.empty();
if (args.length == 0) {
System.out.println("No input files given. Get help with --help");
System.exit(1);
} else if (args.length == 1 && args[0].equals("--help")) {
System.out.println("Usage: javatx [OPTION]... [FILE]...\n" +
"\t-cp\tSet Classpath\n" +
"\t-d\tSet destination directory\n" +
"\t[--server-mode <port>]\n" +
"\t[--unify-server <url>]\n" +
"\t[--write-logs]\n" +
"\t[-v|-vv-|-vvv]");
System.exit(1);
}
while (it.hasNext()) {
String arg = it.next();
if (arg.equals("-d")) {
outputPath = it.next();
} else if (arg.startsWith("-d")) {
outputPath = arg.substring(2);
} else if (arg.equals("-cp") || arg.equals("-classpath")) {
String[] cps = it.next().split(":");
for (String cp : cps) {
classpath.add(new File(cp));
Iterator<String> it = Arrays.asList(args).iterator();
if (args.length == 0) {
System.out.println("No input files given. Get help with --help");
System.exit(1);
} else if (args.length == 1 && args[0].equals("--help")) {
System.out.println("Usage: javatx [OPTION]... [FILE]...\n" +
"\t-cp\tSet Classpath\n" +
"\t-d\tSet destination directory\n" +
"\t-s\tRun the compiler in server mode and listen for incoming requests on the given port\n" +
"\t-us\tSet the address of a remote server for the unification process"
);
System.exit(1);
}
while (it.hasNext()) {
String arg = it.next();
if (arg.equals("-d")) {
outputPath = it.next();
}
else if (arg.startsWith("-d")) {
outputPath = arg.substring(2);
}
else if (arg.equals("-cp") || arg.equals("-classpath")) {
String[] cps = it.next().split(":");
for (String cp : cps) {
classpath.add(new File(cp));
}
}
else if (arg.equals("-s") || arg.equals("-server")) {
if (unificationServer != null) {
throw new IllegalArgumentException("Cannot run in server-Mode and use unification server at the same time");
}
runAsServerWithPort = Integer.parseInt(it.next());
}
else if (arg.equals("-us") || arg.equals("-unification-server")) {
if (runAsServerWithPort != -1) {
throw new IllegalArgumentException("Cannot run in server-Mode and use unification server at the same time");
}
unificationServer = it.next();
} else {
input.add(new File(arg));
}
}
} else if (arg.equals("--server-mode")) {
serverPort = Optional.of(Integer.parseInt(it.next()));
} else if (arg.equals("--unify-server")) {
unifyServerUrl = Optional.of(it.next());
} else if (arg.equals("--write-logs")) {
ConsoleInterface.writeLogFiles = true;
} else if (arg.startsWith("-v")) {
logLevel = switch (arg) {
case "-v" -> Logger.LogLevel.WARNING;
case "-vv" -> Logger.LogLevel.INFO;
case "-vvv" -> Logger.LogLevel.DEBUG;
default -> throw new IllegalArgumentException("Argument " + arg + " is not a valid verbosity level");
};
} else {
input.add(new File(arg));
}
}
if (serverPort.isPresent()) {
if (unifyServerUrl.isPresent()) throw new RuntimeException("Cannot use unifyServer when in server mode!");
JavaTXServer server = new JavaTXServer(serverPort.get());
server.listen();
}
else {
JavaTXCompiler compiler = new JavaTXCompiler(input, classpath, outputPath != null ? new File(outputPath) : null);
//compiler.typeInference();
compiler.generateBytecode();
SocketClient.closeIfOpen();
}
}
if (runAsServerWithPort != -1) {
JavaTXServer server = new JavaTXServer(runAsServerWithPort);
}
else {
JavaTXCompiler compiler = new JavaTXCompiler(input, classpath, outputPath != null ? new File(outputPath) : null);
//compiler.typeInference();
compiler.generateBytecode();
}
}
}

View File

@@ -13,10 +13,6 @@ import de.dhbwstuttgart.parser.antlr.Java17Parser.SourceFileContext;
import de.dhbwstuttgart.parser.scope.JavaClassName;
import de.dhbwstuttgart.parser.scope.JavaClassRegistry;
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.GenericTypeVar;
import de.dhbwstuttgart.syntaxtree.Method;
@@ -35,29 +31,20 @@ import de.dhbwstuttgart.syntaxtree.type.TypeVisitor;
import de.dhbwstuttgart.syntaxtree.visual.ASTTypePrinter;
import de.dhbwstuttgart.target.generate.ASTToTargetAST;
import de.dhbwstuttgart.target.generate.GenericsResult;
import de.dhbwstuttgart.typeinference.TypeInference;
import de.dhbwstuttgart.typeinference.TypeInferenceHelper;
import de.dhbwstuttgart.typeinference.constraints.Constraint;
import de.dhbwstuttgart.typeinference.constraints.ConstraintSet;
import de.dhbwstuttgart.typeinference.constraints.Pair;
import de.dhbwstuttgart.typeinference.result.ResultSet;
import de.dhbwstuttgart.typeinference.typeAlgo.TYPE;
import de.dhbwstuttgart.typeinference.unify.PlaceholderRegistry;
import de.dhbwstuttgart.typeinference.unify.RuleSet;
import de.dhbwstuttgart.typeinference.unify.TypeUnify;
import de.dhbwstuttgart.typeinference.unify.UnifyContext;
import de.dhbwstuttgart.typeinference.unify.distributeVariance;
import de.dhbwstuttgart.typeinference.unify.*;
import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure;
import de.dhbwstuttgart.typeinference.unify.model.FiniteClosure;
import de.dhbwstuttgart.typeinference.unify.model.PairOperator;
import de.dhbwstuttgart.typeinference.unify.model.PlaceholderType;
import de.dhbwstuttgart.typeinference.unify.model.UnifyPair;
import de.dhbwstuttgart.typeinference.unify.model.UnifyType;
import de.dhbwstuttgart.typeinference.unify.TypeUnifyTask;
import de.dhbwstuttgart.typeinference.unify.UnifyResultListener;
import de.dhbwstuttgart.typeinference.unify.UnifyResultListenerImpl;
import de.dhbwstuttgart.typeinference.unify.UnifyResultModel;
import de.dhbwstuttgart.typeinference.unify.UnifyTaskModel;
import de.dhbwstuttgart.util.Logger;
import java.io.*;
import java.lang.reflect.Modifier;
import java.nio.file.Path;
@@ -66,20 +53,19 @@ import java.util.Map.Entry;
import java.util.function.Function;
import java.util.stream.Collectors;
import de.dhbwstuttgart.util.Logger;
import org.apache.commons.io.output.NullOutputStream;
public class JavaTXCompiler {
// do not use this in any code, that can be executed serverside!
public static PlaceholderRegistry defaultClientPlaceholderRegistry = new PlaceholderRegistry();
public static Logger defaultLogger = new Logger();
// public static JavaTXCompiler INSTANCE;
final CompilationEnvironment environment;
Boolean resultmodel = true;
public final Map<File, SourceFile> sourceFiles = new HashMap<>();
Optional<String> unificationServer = Optional.empty();
public final Map<File, SourceFile> sourceFiles = new HashMap<>();
public volatile UnifyTaskModel usedTasks = new UnifyTaskModel();
Boolean log = false; //gibt an ob ein Log-File nach System.getProperty("user.dir")+""/logFiles/"" geschrieben werden soll?
public UnifyTaskModelParallel usedTasks = new UnifyTaskModelParallel();
public final DirectoryClassLoader classLoader;
public final List<File> classPath;
@@ -88,9 +74,14 @@ public class JavaTXCompiler {
public DirectoryClassLoader getClassLoader() {
return classLoader;
}
public JavaTXCompiler(File sourceFile) throws IOException, ClassNotFoundException {
this(Collections.singletonList(sourceFile), List.of(), new File("."));
this(Arrays.asList(sourceFile), List.of(), new File("."));
}
public JavaTXCompiler(File sourceFile, Boolean log) throws IOException, ClassNotFoundException {
this(sourceFile);
this.log = log;
}
public JavaTXCompiler(List<File> sourceFiles) throws IOException, ClassNotFoundException {
@@ -98,9 +89,6 @@ public class JavaTXCompiler {
}
public JavaTXCompiler(List<File> sources, List<File> contextPath, File outputPath) throws IOException, ClassNotFoundException {
// ensure new default placeholder registry for tests
defaultClientPlaceholderRegistry = new PlaceholderRegistry();
var path = new ArrayList<>(contextPath);
if (contextPath.isEmpty()) {
// When no contextPaths are given, the working directory is the sources root
@@ -292,7 +280,7 @@ public class JavaTXCompiler {
* x.getRhsType().accept(new distributeVariance(), a.getVariance());}); eq1 = new HashSet<>(eq); eq1.removeIf(x -> !(x.getRhsType() instanceof PlaceholderType && ((PlaceholderType)x.getRhsType()).equals(a))); eq1.stream().forEach(x -> { x.getLhsType().accept(new distributeVariance(), a.getVariance());}); phSetVariance = new ArrayList<>(phSet); phSetVariance.removeIf(x -> (x.getVariance() == 0 || usedTPH.contains(x))); } }
*/
public UnifyResultModel typeInferenceAsync(UnifyResultListener resultListener, Writer logFile) throws ClassNotFoundException, IOException {
public UnifyResultModelParallel typeInferenceAsync(UnifyResultListener resultListener, Writer logFile) throws ClassNotFoundException, IOException {
List<ClassOrInterface> allClasses = new ArrayList<>();// environment.getAllAvailableClasses();
// Alle Importierten Klassen in allen geparsten Sourcefiles kommen ins FC
for (Entry<File, SourceFile> source : this.sourceFiles.entrySet()) {
@@ -308,57 +296,68 @@ public class JavaTXCompiler {
}
Set<Set<UnifyPair>> results = new HashSet<>();
UnifyResultModel urm = null;
UnifyResultModelParallel urm = null;
// urm.addUnifyResultListener(resultListener);
logFile = logFile == null ? new FileWriter("log_" + sourceFiles.keySet().iterator().next().getName()) : logFile;
Logger logger = new Logger(logFile, "TypeInferenceAsync");
UnifyContext context = new UnifyContext(logger, true, urm, usedTasks, defaultClientPlaceholderRegistry);
IFiniteClosure finiteClosure = UnifyTypeFactory.generateFC(allClasses, logger, getClassLoader(), this, context.placeholderRegistry());
logger.info(finiteClosure.toString());
urm = new UnifyResultModel(cons, finiteClosure);
urm.addUnifyResultListener(resultListener);
ConstraintSet<UnifyPair> unifyCons = UnifyTypeFactory.convert(this, cons, context.placeholderRegistry());
Function<UnifyPair, UnifyPair> distributeInnerVars = x -> {
UnifyType lhs, rhs;
if (((lhs = x.getLhsType()) instanceof PlaceholderType) && ((rhs = x.getRhsType()) instanceof PlaceholderType) && (((PlaceholderType) lhs).isInnerType() || ((PlaceholderType) rhs).isInnerType())) {
((PlaceholderType) lhs).setInnerType(true);
((PlaceholderType) rhs).setInnerType(true);
try {
Logger logger = new Logger(true, "log_" + sourceFiles.keySet().iterator().next().getName());
if (logFile == null) {
logFile = logger.getLogFileWriter();
}
return x;
};
logger.debug(unifyCons.toString());
unifyCons = unifyCons.map(distributeInnerVars);
logger.debug(unifyCons.toString());
// Set<Set<UnifyPair>> results = new HashSet<>(); Nach vorne gezogen
logger.debug("FC:\\" + finiteClosure.toString() + "\n");
for (SourceFile f : this.sourceFiles.values()) {
logger.debug(ASTTypePrinter.print(f));
IFiniteClosure finiteClosure = UnifyTypeFactory.generateFC(allClasses, logger, getClassLoader(), this);
System.out.println(finiteClosure);
urm = new UnifyResultModelParallel(cons, finiteClosure);
urm.addUnifyResultListener(resultListener);
ConstraintSet<UnifyPair> unifyCons = UnifyTypeFactory.convert(this, cons);
Function<UnifyPair, UnifyPair> distributeInnerVars = x -> {
UnifyType lhs, rhs;
if (((lhs = x.getLhsType()) instanceof PlaceholderType) && ((rhs = x.getRhsType()) instanceof PlaceholderType) && (((PlaceholderType) lhs).isInnerType() || ((PlaceholderType) rhs).isInnerType())) {
((PlaceholderType) lhs).setInnerType(true);
((PlaceholderType) rhs).setInnerType(true);
}
return x;
};
logFile.write(unifyCons.toString());
unifyCons = unifyCons.map(distributeInnerVars);
logFile.write(unifyCons.toString());
TypeUnify unify = new TypeUnify();
// Set<Set<UnifyPair>> results = new HashSet<>(); Nach vorne gezogen
logFile.write("FC:\\" + finiteClosure.toString() + "\n");
for (SourceFile f : this.sourceFiles.values()) {
logFile.write(ASTTypePrinter.print(f));
}
logFile.flush();
Set<PlaceholderType> varianceTPHold;
Set<PlaceholderType> varianceTPH = new HashSet<>();
varianceTPH = varianceInheritanceConstraintSet(unifyCons);
/*
* PL 2018-11-07 wird in varianceInheritanceConstraintSet erledigt do { //PL 2018-11-05 Huellenbildung Variance auf alle TPHs der Terme auf der jeweiligen //anderen Seite übertragen varianceTPHold = new HashSet<>(varianceTPH); varianceTPH = varianceInheritanceConstraintSet(unifyCons); unifyCons.map( y -> { if ((y.getLhsType() instanceof PlaceholderType) && (y.getRhsType() instanceof PlaceholderType)) { if (((PlaceholderType)y.getLhsType()).getVariance() != 0 &&
* ((PlaceholderType)y.getRhsType()).getVariance() == 0) { ((PlaceholderType)y.getRhsType()).setVariance(((PlaceholderType)y.getLhsType( )).getVariance()); } if (((PlaceholderType)y.getLhsType()).getVariance() == 0 && ((PlaceholderType)y.getRhsType()).getVariance() != 0) { ((PlaceholderType)y.getLhsType()).setVariance(((PlaceholderType)y.getRhsType( )).getVariance()); } } return y; } ); } while (!varianceTPHold.equals(varianceTPH));
*/
// Set<Set<UnifyPair>> result = unify.unifySequential(xConsSet, finiteClosure,
// logFile, log);
// Set<Set<UnifyPair>> result = unify.unify(xConsSet, finiteClosure);
List<Set<Constraint<UnifyPair>>> oderConstraints = unifyCons.getOderConstraints()/*
* .stream().map(x -> { Set<Set<UnifyPair>> ret = new HashSet<>(); for (Constraint<UnifyPair> y : x) { ret.add(new HashSet<>(y)); } return ret; }).collect(Collectors. toCollection(ArrayList::new))
*/;
unify.unifyAsync(unifyCons.getUndConstraints(), oderConstraints, finiteClosure, logFile, log, urm, usedTasks);
} catch (IOException e) {
System.err.println("kein LogFile");
}
// logFile.flush();
Set<PlaceholderType> varianceTPHold;
Set<PlaceholderType> varianceTPH = new HashSet<>();
varianceTPH = varianceInheritanceConstraintSet(unifyCons);
/*
* PL 2018-11-07 wird in varianceInheritanceConstraintSet erledigt do { //PL 2018-11-05 Huellenbildung Variance auf alle TPHs der Terme auf der jeweiligen //anderen Seite übertragen varianceTPHold = new HashSet<>(varianceTPH); varianceTPH = varianceInheritanceConstraintSet(unifyCons); unifyCons.map( y -> { if ((y.getLhsType() instanceof PlaceholderType) && (y.getRhsType() instanceof PlaceholderType)) { if (((PlaceholderType)y.getLhsType()).getVariance() != 0 &&
* ((PlaceholderType)y.getRhsType()).getVariance() == 0) { ((PlaceholderType)y.getRhsType()).setVariance(((PlaceholderType)y.getLhsType( )).getVariance()); } if (((PlaceholderType)y.getLhsType()).getVariance() == 0 && ((PlaceholderType)y.getRhsType()).getVariance() != 0) { ((PlaceholderType)y.getLhsType()).setVariance(((PlaceholderType)y.getRhsType( )).getVariance()); } } return y; } ); } while (!varianceTPHold.equals(varianceTPH));
*/
// Set<Set<UnifyPair>> result = unify.unifySequential(xConsSet, finiteClosure,
// logFile, log);
// Set<Set<UnifyPair>> result = unify.unify(xConsSet, finiteClosure);
List<Set<Constraint<UnifyPair>>> oderConstraints = unifyCons.getOderConstraints()/*
* .stream().map(x -> { Set<Set<UnifyPair>> ret = new HashSet<>(); for (Constraint<UnifyPair> y : x) { ret.add(new HashSet<>(y)); } return ret; }).collect(Collectors. toCollection(ArrayList::new))
*/;
TypeUnify.unifyAsync(unifyCons.getUndConstraints(), oderConstraints, finiteClosure, context);
return urm;
}
public List<ResultSet> typeInference(File file) throws ClassNotFoundException, IOException {
// START create logger
Logger logger = new Logger(log, "log_" + sourceFiles.keySet().iterator().next().getName());
// END create logger
// START gather classes and interfaces
var sf = sourceFiles.get(file);
Set<ClassOrInterface> allClasses = new HashSet<>();// environment.getAllAvailableClasses();
allClasses.addAll(getAvailableClasses(sf));
@@ -371,116 +370,56 @@ public class JavaTXCompiler {
if (allClasses.stream().noneMatch(old -> old.getClassName().equals(clazz.getClassName())))
allClasses.add(clazz);
}
logger.write(ASTTypePrinter.print(sf));
// END gather classes and interfaces
final ConstraintSet<Pair> cons = getConstraints(file);
Set<Set<UnifyPair>> results = new HashSet<>();
PlaceholderRegistry placeholderRegistry = new PlaceholderRegistry();
// START create finite closure
IFiniteClosure finiteClosure = UnifyTypeFactory.generateFC(allClasses.stream().toList(), logger, classLoader, this);
logger.write("FC:\\" + finiteClosure.toString() + "\n");
// END create finite closure
var logFolder = new File(System.getProperty("user.dir") + "/logFiles/");
if (ConsoleInterface.writeLogFiles && !logFolder.mkdirs()) throw new RuntimeException("Could not creat directoy for log files: " + logFolder);
Writer logFile = ConsoleInterface.writeLogFiles ? new FileWriter(new File(logFolder, "log_" + sourceFiles.keySet().iterator().next().getName())) : new OutputStreamWriter(new NullOutputStream());
Logger logger = new Logger(logFile, "TypeInference");
// START create unify constraints
ConstraintSet<Pair> cons = getConstraints(file);
ConstraintSet<UnifyPair> unifyCons = UnifyTypeFactory.convert(this, cons);
logger.write("Unify:" + unifyCons.toString());
unifyCons = unifyCons.map(TypeInferenceHelper::distributeInnerVars);
logger.write("\nUnify_distributeInnerVars: " + unifyCons.toString());
System.out.println("xxx1");
// END create unify constraints
FiniteClosure finiteClosure = UnifyTypeFactory.generateFC(allClasses.stream().toList(), logger, classLoader, this, placeholderRegistry);
logger.info(finiteClosure.toString());
ConstraintSet<UnifyPair> unifyCons = UnifyTypeFactory.convert(this, cons, placeholderRegistry);
logger.info("xxx1");
Function<UnifyPair, UnifyPair> distributeInnerVars = x -> {
UnifyType lhs, rhs;
if (((lhs = x.getLhsType()) instanceof PlaceholderType) && ((rhs = x.getRhsType()) instanceof PlaceholderType) && (((PlaceholderType) lhs).isInnerType() || ((PlaceholderType) rhs).isInnerType())) {
((PlaceholderType) lhs).setInnerType(true);
((PlaceholderType) rhs).setInnerType(true);
}
return x;
};
logger.debug("Unify:" + unifyCons.toString());
logger.info("Unify:" + unifyCons.toString());
unifyCons = unifyCons.map(distributeInnerVars);
logger.debug("\nUnify_distributeInnerVars: " + unifyCons.toString());
// Set<Set<UnifyPair>> results = new HashSet<>(); Nach vorne gezogen
logger.debug("FC:\\" + finiteClosure.toString() + "\n");
logger.debug(ASTTypePrinter.print(sf));
logger.info(ASTTypePrinter.print(sf));
// logFile.flush();
logger.info("Unify nach Oder-Constraints-Anpassung:" + unifyCons.toString());
// START unused variance calculation
Set<PlaceholderType> varianceTPHold;
Set<PlaceholderType> varianceTPH = new HashSet<>();
varianceTPH = varianceInheritanceConstraintSet(unifyCons);
Set<PlaceholderType> varianceTPH = varianceInheritanceConstraintSet(unifyCons);
/*
* PL 2018-11-07 wird in varianceInheritanceConstraintSet erledigt do { //PL 2018-11-05 Huellenbildung Variance auf alle TPHs der Terme auf der jeweiligen //anderen Seite übertragen varianceTPHold = new HashSet<>(varianceTPH); varianceTPH = varianceInheritanceConstraintSet(unifyCons); unifyCons.map( y -> { if ((y.getLhsType() instanceof PlaceholderType) && (y.getRhsType() instanceof PlaceholderType)) { if (((PlaceholderType)y.getLhsType()).getVariance() != 0 &&
* ((PlaceholderType)y.getRhsType()).getVariance() == 0) { ((PlaceholderType)y.getRhsType()).setVariance(((PlaceholderType)y.getLhsType( )).getVariance()); } if (((PlaceholderType)y.getLhsType()).getVariance() == 0 && ((PlaceholderType)y.getRhsType()).getVariance() != 0) { ((PlaceholderType)y.getLhsType()).setVariance(((PlaceholderType)y.getRhsType( )).getVariance()); } } return y; } ); } while (!varianceTPHold.equals(varianceTPH));
*/
// END unused variance calculation
// Set<Set<UnifyPair>> result = unify.unifySequential(xConsSet, finiteClosure,
// logFile, log);
// Set<Set<UnifyPair>> result = unify.unify(xConsSet, finiteClosure);
List<Set<Constraint<UnifyPair>>> oderConstraints = unifyCons.getOderConstraints()// .stream().map(x -> {
/*
* Set<Set<UnifyPair>> ret = new HashSet<>(); for (Constraint<UnifyPair> y : x) { ret.add(new HashSet<>(y)); } return ret; }).collect(Collectors.toCollection(ArrayList::new))
*/;
if (ConsoleInterface.unifyServerUrl.isPresent()) {
UnifyResultModel urm = new UnifyResultModel(cons, finiteClosure);
UnifyContext context = new UnifyContext(logger, true, urm, usedTasks, placeholderRegistry);
SocketFuture<UnifyResultPacket> future = SocketClient.execute(
UnifyRequestPacket.create(finiteClosure, cons, unifyCons, context.placeholderRegistry())
);
SocketClient.execute(SetAutoclosePacket.create());
return future.get().getResultSet(context);
TypeInference typeInference = new TypeInference(
logger,
classLoader,
usedTasks,
file,
cons,
allClasses,
finiteClosure,
unifyCons
);
if (unificationServer.isPresent()) {
return typeInference.executeOnRemoteServer(unificationServer.get());
}
else if (resultmodel) {
/* UnifyResultModel Anfang */
UnifyResultModel urm = new UnifyResultModel(cons, finiteClosure);
UnifyResultListenerImpl li = new UnifyResultListenerImpl();
urm.addUnifyResultListener(li);
UnifyContext context = new UnifyContext(logger, true, urm, usedTasks, placeholderRegistry);
TypeUnify.unifyParallel(unifyCons.getUndConstraints(), oderConstraints, finiteClosure, context);
logger.info("RESULT Final: " + li.getResults());
logger.info("Constraints for Generated Generics: " + " ???");
logFile.write("RES_FINAL: " + li.getResults().toString() + "\n");
// logFile.flush();
return li.getResults();
return typeInference.executeResultModel();
}
/* UnifyResultModel End */
else {
// Set<Set<UnifyPair>> result = unify.unify(unifyCons.getUndConstraints(),
// oderConstraints, finiteClosure, logFile, log, new UnifyResultModel(cons,
// finiteClosure));
UnifyContext context = new UnifyContext(logger, false, new UnifyResultModel(cons, finiteClosure), usedTasks, placeholderRegistry);
Set<Set<UnifyPair>> result = TypeUnify.unifyOderConstraints(unifyCons.getUndConstraints(), oderConstraints, finiteClosure, context);
logger.info("RESULT: " + result);
logFile.write("RES: " + result.toString() + "\n");
// logFile.flush();
results.addAll(result);
results = results.stream().map(x -> {
Optional<Set<UnifyPair>> res = new RuleSet(placeholderRegistry).subst(x.stream().map(y -> {
if (y.getPairOp() == PairOperator.SMALLERDOTWC)
y.setPairOp(PairOperator.EQUALSDOT);
return y; // alle Paare a <.? b erden durch a =. b ersetzt
}).collect(Collectors.toCollection(HashSet::new)));
if (res.isPresent()) {// wenn subst ein Erg liefert wurde was veraendert
return new TypeUnifyTask(context).applyTypeUnificationRules(res.get(), finiteClosure);
} else
return x; // wenn nichts veraendert wurde wird x zurueckgegeben
}).collect(Collectors.toCollection(HashSet::new));
logger.info("RESULT Final: " + results);
logger.info("Constraints for Generated Generics: " + " ???");
logger.debug("RES_FINAL: " + results.toString() + "\n");
// logFile.flush();
logger.debug("PLACEHOLDERS: " + placeholderRegistry);
// logFile.flush();
return typeInference.executeNoResultModel();
}
return results.stream().map((unifyPairs -> new ResultSet(UnifyTypeFactory.convert(unifyPairs, Pair.generateTPHMap(cons), placeholderRegistry)))).collect(Collectors.toList());
}
/**
* Vererbt alle Variancen bei Paaren (a <. theta) oder (Theta <. a) wenn a eine Variance !=0 hat auf alle Typvariablen in Theta.
*
*
*
*/
private Set<PlaceholderType> varianceInheritanceConstraintSet(ConstraintSet<UnifyPair> cons) {
@@ -607,6 +546,10 @@ public class JavaTXCompiler {
}
}
/**
* @param path - output-Directory can be null, then class file output is in the same directory as the parsed source files
* @return
*/
public Map<JavaClassName, byte[]> generateBytecode(File sourceFile) throws ClassNotFoundException, IOException {
var sf = sourceFiles.get(sourceFile);
if (sf.isGenerated()) return null;
@@ -661,15 +604,15 @@ public class JavaTXCompiler {
FileOutputStream output;
for (JavaClassName name : classFiles.keySet()) {
byte[] bytecode = classFiles.get(name);
defaultLogger.info("generating " + name + ".class file ...");
System.out.println("generating " + name + ".class file ...");
var subPath = preserveHierarchy ? path : Path.of(path.toString(), name.getPackageName().split("\\.")).toFile();
File outputFile = new File(subPath, name.getClassName() + ".class");
outputFile.getAbsoluteFile().getParentFile().mkdirs();
defaultLogger.info(outputFile.toString());
System.out.println(outputFile);
output = new FileOutputStream(outputFile);
output.write(bytecode);
output.close();
defaultLogger.success(name + ".class file generated");
System.out.println(name + ".class file generated");
}
}

View File

@@ -4,28 +4,12 @@ import de.dhbwstuttgart.server.SocketServer;
public class JavaTXServer {
public static boolean isRunning = false;
final SocketServer socketServer;
public JavaTXServer(int port) {
this.socketServer = new SocketServer(port);
}
public void listen() {
isRunning = true;
socketServer.start();
}
public void forceStop() {
JavaTXServer(int port) {
try {
socketServer.stop();
SocketServer socketServer = new SocketServer(port);
socketServer.start();
} catch (Exception e) {
e.printStackTrace();
}
catch (InterruptedException exception) {
System.err.println("Interrupted socketServer: " + exception);
}
isRunning = false;
}
}

View File

@@ -1,11 +1,5 @@
package de.dhbwstuttgart.environment;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;
import com.google.common.collect.Lists;
import de.dhbwstuttgart.core.JavaTXCompiler;
import de.dhbwstuttgart.syntaxtree.ClassOrInterface;
@@ -18,6 +12,17 @@ import de.dhbwstuttgart.parser.antlr.Java17Parser.SourceFileContext;
import de.dhbwstuttgart.parser.antlr.Java17Parser.SrcfileContext;
import de.dhbwstuttgart.parser.scope.GatherNames;
import de.dhbwstuttgart.parser.scope.JavaClassRegistry;
import de.dhbwstuttgart.syntaxtree.ClassOrInterface;
import de.dhbwstuttgart.syntaxtree.factory.ASTFactory;
import org.antlr.v4.runtime.tree.TerminalNode;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* Stellt die Java-Environment dar und speichert alle Binarys, Librarys und Sourcefiles im zu kompilierenden Projekt Sie erstellt anhand dieser Informationen die JavaClassNameRegistry
@@ -31,7 +36,7 @@ public class CompilationEnvironment {
/**
* Imitiert die Environment beim Aufruf des JavaCompilers auf einer Menge von java-Dateien Die Environment enth<74>lt automatisch die Java Standard Library
*
*
* @param sourceFiles die zu kompilierenden Dateien
*/
public CompilationEnvironment(List<File> sourceFiles, DirectoryClassLoader classLoader) {

View File

@@ -1,11 +0,0 @@
package de.dhbwstuttgart.exceptions;
/**
* Eine Runtime Exception, die für den Fall genutzt wird, dass eine Unifikation abgebrochen wird.
* Durch das Werfen einer Exception können Abbrüche auch aus Methodenaufrufen heraus
* geprüft werden, da zuvor nur ein return X; stattfinden würde.
*/
public class UnifyCancelException extends RuntimeException {
}

View File

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

View File

@@ -1,25 +1,4 @@
package de.dhbwstuttgart.parser;
import de.dhbwstuttgart.server.packet.dataContainers.ISerializableData;
import de.dhbwstuttgart.server.packet.dataContainers.KeyStorage;
import de.dhbwstuttgart.server.packet.dataContainers.serialized.SerialMap;
public record SourceLoc(String file, int line) implements ISerializableData {
@Override
public SerialMap toSerial(KeyStorage keyStorage) {
var serialized = new SerialMap();
serialized.put("file", file);
serialized.put("line", line);
return serialized;
}
public static SourceLoc fromSerial(SerialMap data) {
return new SourceLoc(
data.getValue("file").getOf(String.class),
data.getValue("line").getOf(Integer.class)
);
}
public record SourceLoc(String file, int line) {
}

View File

@@ -2,7 +2,6 @@ package de.dhbwstuttgart.parser.SyntaxTreeGenerator;
import de.dhbwstuttgart.syntaxtree.StatementVisitor;
import de.dhbwstuttgart.syntaxtree.statement.AssignLeftSide;
import de.dhbwstuttgart.syntaxtree.statement.Expression;
import de.dhbwstuttgart.syntaxtree.statement.LocalVar;
public class AssignToLocal extends AssignLeftSide {
@@ -17,4 +16,4 @@ public class AssignToLocal extends AssignLeftSide {
public void accept(StatementVisitor visitor) {
visitor.visit(this);
}
}
}

View File

@@ -12,14 +12,12 @@ import de.dhbwstuttgart.syntaxtree.factory.ASTFactory;
import de.dhbwstuttgart.syntaxtree.factory.UnifyTypeFactory;
import de.dhbwstuttgart.syntaxtree.type.*;
import de.dhbwstuttgart.typeinference.constraints.Pair;
import de.dhbwstuttgart.typeinference.unify.PlaceholderRegistry;
import de.dhbwstuttgart.typeinference.unify.model.*;
import de.dhbwstuttgart.typeinference.unify.model.PairOperator;
import de.dhbwstuttgart.typeinference.unify.model.UnifyPair;
import java.util.*;
import java.util.stream.Collectors;
import org.antlr.v4.runtime.Token;
public class FCGenerator {
/**
* Baut die FiniteClosure aus availableClasses.
@@ -27,24 +25,19 @@ public class FCGenerator {
*
* @param availableClasses - Alle geparsten Klassen
*/
public static Set<UnifyPair> toUnifyFC(JavaTXCompiler compiler, Collection<ClassOrInterface> availableClasses, ClassLoader classLoader, PlaceholderRegistry placeholderRegistry) throws ClassNotFoundException {
return toFC(
availableClasses,
classLoader,
placeholderRegistry
).stream().map(t -> UnifyTypeFactory.convert(compiler, t, placeholderRegistry))
.collect(Collectors.toSet());
public static Set<UnifyPair> toUnifyFC(JavaTXCompiler compiler, Collection<ClassOrInterface> availableClasses, ClassLoader classLoader) throws ClassNotFoundException {
return toFC(availableClasses, classLoader).stream().map(t -> UnifyTypeFactory.convert(compiler, t)).collect(Collectors.toSet());
}
public static Set<Pair> toFC(Collection<ClassOrInterface> availableClasses, ClassLoader classLoader, PlaceholderRegistry placeholderRegistry) throws ClassNotFoundException {
public static Set<Pair> toFC(Collection<ClassOrInterface> availableClasses, ClassLoader classLoader) throws ClassNotFoundException {
HashSet<Pair> pairs = new HashSet<>();
//PL 2018-09-18: gtvs vor die for-Schleife gezogen, damit immer die gleichen Typeplaceholder eingesetzt werden.
HashMap<String, RefTypeOrTPHOrWildcardOrGeneric> gtvs = new HashMap<>();
for(ClassOrInterface cly : availableClasses){
List<Pair> newPairs = getSuperTypes(cly, availableClasses, gtvs, classLoader, placeholderRegistry);
List<Pair> newPairs = getSuperTypes(cly, availableClasses, gtvs, classLoader);
pairs.addAll(newPairs);
//For all Functional Interfaces FI: FunN$$<... args auf dem Functional Interface ...> <. FI is added to FC
//For all Functional Interfaces FI: FunN$$<... args auf dem Functional Interface ...> <. FI is added to FC
if (isFunctionalInterface(cly)) {
pairs.add(genImplFunType(cly, newPairs.get(0).TA1, gtvs));
}
@@ -54,19 +47,19 @@ public class FCGenerator {
private static Boolean isFunctionalInterface(ClassOrInterface cly) {
return (cly.isInterface() && (cly.isFunctionalInterface() || cly.getMethods().size() == 1));
return (cly.isInterface() && (cly.isFunctionalInterface() || cly.getMethods().size() == 1));
}
private static Pair genImplFunType(ClassOrInterface cly, RefTypeOrTPHOrWildcardOrGeneric fIType, HashMap<String, RefTypeOrTPHOrWildcardOrGeneric> gtvs) {
for(Method m : cly.getMethods()) {
if (!java.lang.reflect.Modifier.isAbstract(m.modifier))
continue;
List<RefTypeOrTPHOrWildcardOrGeneric> tl =
List<RefTypeOrTPHOrWildcardOrGeneric> tl =
(m.getParameterList().getFormalparalist()
.stream().map(p -> p.getType().acceptTV(new TypeExchanger(gtvs)))
.collect(Collectors.toList()));
tl.add(m.getReturnType().acceptTV(new TypeExchanger(gtvs)));
return new Pair(new RefType(new JavaClassName("Fun" + (tl.size()-1) + "$$"), tl, new NullToken()),
return new Pair(new RefType(new JavaClassName("Fun" + (tl.size()-1) + "$$"), tl, new NullToken()),
fIType, PairOperator.SMALLER);
}
return null; //kann nicht passieren, da die Methode nur aufgerufen wird wenn cl Functional Interface ist
@@ -81,13 +74,8 @@ public class FCGenerator {
* @param forType
* @return
*/
private static List<Pair> getSuperTypes(
ClassOrInterface forType,
Collection<ClassOrInterface> availableClasses,
ClassLoader classLoader,
PlaceholderRegistry placeholderRegistry
) throws ClassNotFoundException {
return getSuperTypes(forType, availableClasses, new HashMap<>(), classLoader, placeholderRegistry);
private static List<Pair> getSuperTypes(ClassOrInterface forType, Collection<ClassOrInterface> availableClasses, ClassLoader classLoader) throws ClassNotFoundException {
return getSuperTypes(forType, availableClasses, new HashMap<>(), classLoader);
}
/**
@@ -98,13 +86,8 @@ public class FCGenerator {
* @return
* @throws ClassNotFoundException
*/
private static List<Pair> getSuperTypes(
ClassOrInterface forType,
Collection<ClassOrInterface> availableClasses,
HashMap<String, RefTypeOrTPHOrWildcardOrGeneric> gtvs,
ClassLoader classLoader,
PlaceholderRegistry placeholderRegistry
) throws ClassNotFoundException {
private static List<Pair> getSuperTypes(ClassOrInterface forType, Collection<ClassOrInterface> availableClasses,
HashMap<String, RefTypeOrTPHOrWildcardOrGeneric> gtvs, ClassLoader classLoader) throws ClassNotFoundException {
List<RefTypeOrTPHOrWildcardOrGeneric> params = new ArrayList<>();
//Die GTVs, die in forType hinzukommen:
HashMap<String, RefTypeOrTPHOrWildcardOrGeneric> newGTVs = new HashMap<>();
@@ -163,7 +146,7 @@ public class FCGenerator {
if(superClass.getClassName().equals(ASTFactory.createObjectClass().getClassName())){
superTypes = Arrays.asList(new Pair(ASTFactory.createObjectType(), ASTFactory.createObjectType(), PairOperator.SMALLER));
}else{
superTypes = getSuperTypes(superClass, availableClasses, newGTVs, classLoader, placeholderRegistry);
superTypes = getSuperTypes(superClass, availableClasses, newGTVs, classLoader);
}
retList.add(ret);
@@ -218,7 +201,7 @@ public class FCGenerator {
}
}
/**
* Tauscht die GTVs in einem Typ gegen die entsprechenden Typen in der übergebenen Map aus auf den Argumenten der Argumente.
* Hier sind Wildcards zulässig
@@ -264,5 +247,5 @@ public class FCGenerator {
}
}
}

View File

@@ -1,6 +1,5 @@
package de.dhbwstuttgart.parser.SyntaxTreeGenerator;
import de.dhbwstuttgart.parser.JavaTXParser;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
@@ -150,11 +149,11 @@ public class StatementGenerator {
type = TypeGenerator.convert(fp.typeType(), reg, generics);
} else {
type = methodparameters?
TypePlaceholder.fresh(fp.getStart(), 1, false)
TypePlaceholder.fresh(fp.getStart(), 1, false)
: TypePlaceholder.fresh(fp.getStart());
}
ret.add(new FormalParameter(paramName, type, fp.getStart()));
localVars.put(paramName, type);
localVars.put(paramName, type);
}
}
return new ParameterList(ret, ret.get(0).getOffset());
@@ -260,7 +259,7 @@ public class StatementGenerator {
ret.setStatement();
return ret;
default:
JavaTXParser.logger.info(stmt.getClass());
System.out.println(stmt.getClass());
throw new NotImplementedException();
}
}

View File

@@ -1,9 +1,7 @@
package de.dhbwstuttgart.parser.SyntaxTreeGenerator;
import de.dhbwstuttgart.exceptions.NotImplementedException;
import de.dhbwstuttgart.parser.NullToken;
import de.dhbwstuttgart.syntaxtree.AbstractASTWalker;
import de.dhbwstuttgart.syntaxtree.Constructor;
import de.dhbwstuttgart.syntaxtree.statement.*;
import java.util.List;

View File

@@ -14,12 +14,7 @@ import de.dhbwstuttgart.parser.scope.JavaClassRegistry;
import de.dhbwstuttgart.syntaxtree.GenericDeclarationList;
import de.dhbwstuttgart.syntaxtree.GenericTypeVar;
import de.dhbwstuttgart.syntaxtree.factory.ASTFactory;
import de.dhbwstuttgart.syntaxtree.type.ExtendsWildcardType;
import de.dhbwstuttgart.syntaxtree.type.GenericRefType;
import de.dhbwstuttgart.syntaxtree.type.RefType;
import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric;
import de.dhbwstuttgart.syntaxtree.type.SuperWildcardType;
import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder;
import de.dhbwstuttgart.syntaxtree.type.*;
import org.antlr.v4.runtime.Token;
import java.util.ArrayList;
@@ -74,7 +69,7 @@ public class TypeGenerator {
throw new NotImplementedException();
}
} else if (!typeContext.LBRACK().isEmpty()) { // ArrayType über eckige Klammer prüfen
// JavaTXParser.logger.info(unannTypeContext.getText());
// System.out.println(unannTypeContext.getText());
throw new NotImplementedException();
}
/*

View File

@@ -164,4 +164,4 @@ public class GatherNames {
}
return pkgName;
}
}
}

View File

@@ -2,7 +2,10 @@ package de.dhbwstuttgart.parser.scope;
import de.dhbwstuttgart.exceptions.NotImplementedException;
import java.util.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Speichert die Klassen f<>r einen bestimmten Projektscope
@@ -62,4 +65,4 @@ public class JavaClassRegistry {
public int getNumberOfGenerics(String name) {
return existingClasses.get(new JavaClassName(name));
}
}
}

View File

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

View File

@@ -1,25 +1,20 @@
package de.dhbwstuttgart.server;
import com.fasterxml.jackson.core.JsonProcessingException;
import de.dhbwstuttgart.core.ConsoleInterface;
import de.dhbwstuttgart.server.packet.IClientToServerPacket;
import de.dhbwstuttgart.server.packet.ErrorPacket;
import de.dhbwstuttgart.server.packet.IPacket;
import de.dhbwstuttgart.server.packet.IServerToClientPacket;
import de.dhbwstuttgart.server.packet.InvalidPacket;
import de.dhbwstuttgart.server.packet.MessagePacket;
import de.dhbwstuttgart.server.packet.PacketContainer;
import de.dhbwstuttgart.server.packet.UnifyRequestPacket;
import de.dhbwstuttgart.server.packet.UnifyResultPacket;
import de.dhbwstuttgart.typeinference.constraints.ConstraintSet;
import de.dhbwstuttgart.typeinference.constraints.Pair;
import de.dhbwstuttgart.typeinference.result.ResultSet;
import de.dhbwstuttgart.typeinference.unify.UnifyContext;
import de.dhbwstuttgart.typeinference.unify.model.FiniteClosure;
import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure;
import de.dhbwstuttgart.typeinference.unify.model.UnifyPair;
import de.dhbwstuttgart.util.Logger;
import java.net.URI;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -33,34 +28,35 @@ import org.java_websocket.handshake.ServerHandshake;
*/
public class SocketClient extends WebSocketClient {
public static Logger logger = new Logger("SocketClient");
// use a latch to wait until the connection is closed by the remote host
private final CountDownLatch closeLatch = new CountDownLatch(1);
// temporarily: The received unify result packet
private UnifyResultPacket unifyResultPacket = null;
/**
* The singleton object
*/
private static SocketClient socketClient = null;
/**
* List of futures that are still waiting to be fulfilled
*/
private final Map<String, SocketFuture<?>> responseFutures = new HashMap<>();
private SocketClient(String url) {
super(
URI.create(url), // target url
//SocketServer.perMessageDeflateDraft, // enable compression
Map.of( // headers
"packetProtocolVersion", SocketServer.packetProtocolVersion
)
);
// make sure the url is in a valid format
public SocketClient(String url) {
super(URI.create(url));
// make sure, the url is in a valid format
final String regex = "^wss?://(\\w+(\\.\\w+)?)*:(\\d+)$";
final Matcher matcher = Pattern.compile(regex).matcher(url);
if (!matcher.find()) {
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(
IFiniteClosure finiteClosure,
ConstraintSet<Pair> constraints,
ConstraintSet<UnifyPair> unifyConstraints
) {
try {
// wait for the connection to be set up
this.connectBlocking();
@@ -68,135 +64,80 @@ public class SocketClient extends WebSocketClient {
if (this.getReadyState() != ReadyState.OPEN) {
throw new RuntimeException("WebSocket Client could not connect to remote host at " + this.uri);
}
} catch (InterruptedException exception) {
throw new RuntimeException(exception);
}
// add a shutdown hook to close the connection when the process ends or is stopped by a SIGINT signal
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 {
// send the unify task request
UnifyRequestPacket packet = UnifyRequestPacket.create(finiteClosure, constraints, unifyConstraints);
String json = PacketContainer.serialize(packet);
client.send(json);
} catch (Exception exception) {
logger.exception(exception);
throw new RuntimeException("Exception occurred in server connection: ", exception);
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) {
System.err.println("Interrupted: " + exception);
this.notifyAll();
throw new RuntimeException("Remote unification failed: " + exception);
} catch (JsonProcessingException exception) {
System.err.println("JSON processing exception: " + exception);
this.notifyAll();
throw new RuntimeException("Remote unification failed: " + exception);
}
return future;
// detect error cases, in which no error was thrown, but also no result was sent back from the server
if (this.unifyResultPacket == null) {
throw new RuntimeException("Did not receive server response but closed connection already");
}
return unifyResultPacket.getResultSet();
}
/**
* 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 incomming packets
*/
protected void handleReceivedPacket(IPacket packet) {
if (!(packet instanceof IServerToClientPacket serverToClientPacket)) {
System.err.println("Received package of invalid type + " + packet.getClass().getName());
this.close();
return;
}
serverToClientPacket.onHandle(this.getConnection(), this);
}
/**
* 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();
if (packet instanceof InvalidPacket) {
System.err.println("[socket] " + ((InvalidPacket) packet).error);
} else if (packet instanceof MessagePacket) {
System.out.println("[socket] " + ((MessagePacket) packet).message);
} else if (packet instanceof ErrorPacket) {
System.err.println("[socket] " + ((ErrorPacket) packet).error);
} else if (packet instanceof UnifyResultPacket) {
System.out.println("[socket] Received unify result");
unifyResultPacket = (UnifyResultPacket) packet;
}
}
@Override
public void onOpen(ServerHandshake handshakedata) {
logger.success("Connected to server with status " + handshakedata.getHttpStatus());
System.out.println("Connected to server with status " + handshakedata.getHttpStatus());
}
@Override
public void onMessage(String message) {
// logger.info("received: " + message);
// System.out.println("received: " + message);
IPacket packet = PacketContainer.deserialize(message);
this.handleReceivedPacket(packet);
}
@Override
public void onClose(int code, String reason, boolean remote) {
logger.info(
System.out.println(
"Disconnected from server " +
"with code " + code + " " +
(reason.isEmpty() ? "" : "and reason " + reason + " ") +
"(closed by remote: " + remote + ")"
);
if (!this.responseFutures.isEmpty()) {
throw new RuntimeException("Server closed before all required tasks were answered");
}
this.closeLatch.countDown();
}
@Override
public void onError(Exception e) {
logger.exception(e);
throw new RuntimeException(e);
System.out.println("Error: " + e.getMessage());
e.printStackTrace();
}
public void waitUntilClosed() throws InterruptedException {
closeLatch.await();
}
}

View File

@@ -0,0 +1,17 @@
package de.dhbwstuttgart.server;
/**
* The data that is associated server-side with any connected client.
* This makes it possible to store information that can be mapped to any existing connection.
*/
public class SocketData {
public final String id;
// used for the timeout of 10 seconds, until an unused open connection is automatically closed
public boolean hasSentTask = false;
public SocketData(String id) {
this.id = id;
}
}

View File

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

View File

@@ -1,119 +1,65 @@
package de.dhbwstuttgart.server;
import com.fasterxml.jackson.core.JsonProcessingException;
import de.dhbwstuttgart.server.packet.ErrorPacket;
import de.dhbwstuttgart.server.packet.IClientToServerPacket;
import de.dhbwstuttgart.server.packet.IPacket;
import de.dhbwstuttgart.server.packet.MessagePacket;
import de.dhbwstuttgart.server.packet.PacketContainer;
import de.dhbwstuttgart.util.Logger;
import de.dhbwstuttgart.server.packet.UnifyRequestPacket;
import de.dhbwstuttgart.server.packet.UnifyResultPacket;
import de.dhbwstuttgart.typeinference.TypeInference;
import de.dhbwstuttgart.typeinference.result.ResultSet;
import de.dhbwstuttgart.typeinference.unify.model.PlaceholderType;
import java.net.InetSocketAddress;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
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.server.WebSocketServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SocketServer extends WebSocketServer {
public static Logger logger = new Logger("SocketServer");
public static final int maxTasksPerSession = 100;
private static boolean serverRunning = false;
/**
* Increase this every time a breaking change to the server communication is done.
* This will prevent errors when the server version and client version do not match.
*/
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();
private static final Logger log = LoggerFactory.getLogger(SocketServer.class);
public SocketServer(int 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
public void onOpen(WebSocket webSocket, ClientHandshake clientHandshake) {
String ppv = clientHandshake.getFieldValue("packetProtocolVersion");
if (!ppv.equals(packetProtocolVersion)) {
this.sendError(webSocket,
"Mismatch in packet protocol version! Client (you): \"" + ppv + "\" and Server (me): \"" + packetProtocolVersion + "\"",
true
);
webSocket.close(1);
return;
}
SocketData socketData = new SocketData(webSocket);
logger.info("New connection: " + socketData.id + " (with ppv " + ppv + ")");
System.out.println("New connection: " + webSocket.getResourceDescriptor());
webSocket.setAttachment(new SocketData(UUID.randomUUID().toString()));
try {
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
final int secondsUntilTimeout = 10;
timeoutExecutor.schedule(() -> {
if (webSocket.<SocketData>getAttachment().totalTasks.get() > 0 || !webSocket.isOpen()) {
return;
}
sendMessage(webSocket, "No task received after " + secondsUntilTimeout + " seconds. Closing connection...");
webSocket.close();
},
secondsUntilTimeout,
TimeUnit.SECONDS
);
// wait 10 seconds for the client to send a task and close the connection, if nothing has been received until then
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
Runnable task = () -> {
if (webSocket.<SocketData>getAttachment().hasSentTask || !webSocket.isOpen()) {
return;
}
sendMessage(webSocket, "No task received after 10 seconds. Closing connection...");
webSocket.close();
};
executor.schedule(task, 10, TimeUnit.SECONDS);
executor.shutdown();
// and finally, when your program wants to exit
} catch (Exception e) {
logger.exception(e);
log.error("e: ", e);
webSocket.close(1, e.getMessage());
}
}
@Override
public void onClose(WebSocket webSocket, int code, String reason, boolean remote) {
SocketData socketData = webSocket.getAttachment();
logger.info("Connection closed: " + socketData.id);
logger.info(
"Disconnected client " + socketData.id + " " +
System.out.println("Connection closed: " + webSocket.getResourceDescriptor());
System.out.println(
"Disconnected client " + webSocket.getResourceDescriptor() + " " +
"with code " + code + " " +
(reason.isEmpty() ? "" : "and reason " + reason + " ") +
"(closed by client: " + remote + ")"
@@ -123,28 +69,19 @@ public class SocketServer extends WebSocketServer {
@Override
public void onMessage(WebSocket webSocket, String s) {
// logger.info("Received: " + s.substring(0, 50));
// System.out.println("Received: " + s.substring(0, 50));
IPacket reconstructedPacket = PacketContainer.deserialize(s);
try {
this.onPacketReceived(webSocket, reconstructedPacket);
} catch (JsonProcessingException e) {
logger.exception(e);
this.log(webSocket, "Error on processing incoming package: " + e.getMessage());
}
this.onPacketReceived(webSocket, reconstructedPacket);
}
@Override
public void onError(WebSocket webSocket, Exception e) {
if (webSocket != null) {
log(webSocket, e.getMessage());
webSocket.close();
}
logger.exception(e);
webSocket.close();
}
@Override
public void onStart() {
logger.success("Websocket server started on port " + this.getPort());
System.out.println("Websocket server started");
}
/**
@@ -152,84 +89,50 @@ public class SocketServer extends WebSocketServer {
*/
public void sendMessage(WebSocket webSocket, String text) {
try {
MessagePacket message = MessagePacket.create(text);
MessagePacket message = new MessagePacket();
message.message = text;
webSocket.send(PacketContainer.serialize(message));
} catch (Exception e) {
System.err.println("Failed to send message: " + text);
logger.exception(e);
System.err.println(e);
}
}
/**
* A shorthand method for sending error messages to the client
* The server-side implementation on how to handle certain packets when received
*/
public void sendError(WebSocket webSocket, String text, boolean isFatal) {
try {
ErrorPacket error = ErrorPacket.create(text, isFatal);
webSocket.send(PacketContainer.serialize(error));
} catch (Exception e) {
logger.exception(e);
log(webSocket, "Failed to send error: " + text);
}
}
private void onPacketReceived(WebSocket webSocket, IPacket packet) {
if (packet instanceof UnifyRequestPacket unifyRequestPacket) {
/**
* The server-side implementation on how to handle certain packets when received
*/
private void onPacketReceived(WebSocket webSocket, IPacket packet) throws JsonProcessingException {
SocketData socketData = webSocket.getAttachment();
// TODO: this static property will be a problem once we send more than one request per server and
// should be replaced by a dynamic object property
PlaceholderType.EXISTING_PLACEHOLDERS.clear();
sendMessage(webSocket, "You requested a unify! Please wait until I calculated everything...");
System.out.println("Client " + webSocket.<SocketData>getAttachment().id + " requested a unification. Starting now...");
webSocket.<SocketData>getAttachment().hasSentTask = true;
// limit the number of tasks per connection
if (socketData.totalTasks.get() >= maxTasksPerSession) {
sendError(webSocket, "Exceeded the maximum amount of " + maxTasksPerSession + " tasks per session", true);
webSocket.close();
return;
}
try {
// start the unification algorithm from the received data
List<ResultSet> result = TypeInference.executeWithoutContext(
unifyRequestPacket.retrieveFiniteClosure(),
unifyRequestPacket.retrieveConstraints(),
unifyRequestPacket.retrieveUnifyConstraints()
);
System.out.println("Finished unification for client " + webSocket.<SocketData>getAttachment().id);
sendMessage(webSocket, "Unification finished. Found " + result.size() + " result sets");
// only allow packets that are meant to be handled by the server
if (!(packet instanceof IClientToServerPacket<?> clientToServerPacket)) {
sendMessage(webSocket, "The package of type " + packet.getClass().getName() + " is not handled by the server!");
return;
}
// update the socket data
socketData.unhandledTasks.incrementAndGet();
socketData.totalTasks.incrementAndGet();
// add the packet to the queue so it can be started by the worker
CompletableFuture.runAsync(() -> {
clientToServerPacket.onHandle(webSocket, this);
int remainingUnhandledTasks = socketData.unhandledTasks.decrementAndGet();
if (socketData.closeIfNoTasksLeft) {
// if the websocket has 0 unhandled Tasks, close the connection
if (remainingUnhandledTasks <= 0) {
sendMessage(webSocket, "All requested tasks finished! Closing connection...");
webSocket.close();
if (webSocket.isOpen()) {
UnifyResultPacket resultPacket = UnifyResultPacket.create(result);
webSocket.send(PacketContainer.serialize(resultPacket));
}
} catch (Exception e) {
System.err.println(e);
log.error("e: ", e);
}
}, taskExecutor);
}
public void log(WebSocket webSocket, String msg) {
String socketId = (webSocket == null) ? "???" : webSocket.<SocketData>getAttachment().id;
logger.info("[" + socketId + "] " + msg);
}
/**
* The data that is associated server-side with any connected client.
* This makes it possible to store information that can be mapped to any existing connection.
*/
public static class SocketData {
public final String id;
public final AtomicInteger unhandledTasks = new AtomicInteger(0);
public final AtomicInteger totalTasks = new AtomicInteger(0);
public boolean closeIfNoTasksLeft = false;
public SocketData(WebSocket webSocket) {
this.id = UUID.randomUUID().toString();
webSocket.setAttachment(this);
webSocket.close();
} else {
sendMessage(webSocket, "The package of type " + packet.getClass().getName() + " is not handled by the server!");
}
}
}

View File

@@ -1,35 +0,0 @@
package de.dhbwstuttgart.server.packet;
import com.fasterxml.jackson.annotation.JsonIgnore;
import de.dhbwstuttgart.server.SocketClient;
import de.dhbwstuttgart.server.SocketFuture;
import de.dhbwstuttgart.server.SocketServer;
import de.dhbwstuttgart.server.packet.dataContainers.serialized.ISerialNode;
import de.dhbwstuttgart.server.packet.dataContainers.serialized.SerialList;
import de.dhbwstuttgart.server.packet.dataContainers.serialized.SerialMap;
import de.dhbwstuttgart.server.packet.dataContainers.serialized.SerialUUID;
import de.dhbwstuttgart.server.packet.dataContainers.serialized.SerialValue;
import org.java_websocket.WebSocket;
public class DebugPacket implements IClientToServerPacket.Void, IServerToClientPacket {
public SerialUUID a1;
public SerialUUID a2;
public SerialMap b1;
public SerialMap b2;
public SerialList<? extends ISerialNode> c1;
public SerialList<? extends ISerialNode> c2;
public SerialValue<?> d1;
public SerialValue<?> d2;
@JsonIgnore
public void onHandle(WebSocket webSocket, SocketClient socketClient) {}
@JsonIgnore
public void onHandle(WebSocket webSocket, SocketServer socketServer) {}
@JsonIgnore
public SocketFuture<IServerToClientPacket> getFuture() {
return SocketFuture.completedFuture();
}
}

View File

@@ -1,36 +1,14 @@
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;
/**
* A packet to send simple error messages between the client and the server
*/
public class ErrorPacket implements IServerToClientPacket {
public class ErrorPacket implements IPacket {
/**
* The error endpoint for messages from the server that should be logged out as errors and possibly abort the process
* The error endpoint for messages from the server, that should be logged out outputted
*/
public String error;
public boolean isFatal;
@JsonIgnore
public static ErrorPacket create(String error, boolean isFatal) {
ErrorPacket packet = new ErrorPacket();
packet.error = error;
packet.isFatal = isFatal;
return packet;
}
@JsonIgnore
public void onHandle(WebSocket webSocket, SocketClient socketClient) {
SocketClient.logger.exception(new RuntimeException(this.error));
if (this.isFatal) {
socketClient.close(1, "Received fatal error from server");
}
}
}

View File

@@ -1,26 +0,0 @@
package de.dhbwstuttgart.server.packet;
import com.fasterxml.jackson.annotation.JsonIgnore;
import de.dhbwstuttgart.server.SocketFuture;
import de.dhbwstuttgart.server.SocketServer;
import org.java_websocket.WebSocket;
/**
* 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
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

@@ -1,12 +1,18 @@
package de.dhbwstuttgart.server.packet;
/**
* The shared interface for all packet of the client-server connection.
* The shared interface for all packet of the server connection.
* A packet must always:
* - Have a default / no-parameter constructor
* - Have only serializable public properties (or disable them via jackson annotations)
* A packet should have, for easy usage and consisteny:
* - a static create() method
*
*/
public interface IPacket {
interface IDataContainer<T> {
T toObject();
}
}

View File

@@ -1,12 +0,0 @@
package de.dhbwstuttgart.server.packet;
import com.fasterxml.jackson.annotation.JsonIgnore;
import de.dhbwstuttgart.server.SocketClient;
import org.java_websocket.WebSocket;
public interface IServerToClientPacket extends IPacket {
@JsonIgnore
void onHandle(WebSocket webSocket, SocketClient socketClient);
}

View File

@@ -1,35 +1,13 @@
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;
/**
* A fallback packet that is generated if the received JSON could not be mapped to an existing package
* A fallback packet that is generated, if the received json could not be mapped to an existing package
*/
public class InvalidPacket implements IClientToServerPacket.Void, IServerToClientPacket {
public class InvalidPacket implements IPacket {
/**
* If available, the error that caused this package to appear
*/
public String error = "<unknown error>";
@JsonIgnore
public void onHandle(WebSocket webSocket, SocketClient socketClient) {
SocketClient.logger.error("InvalidPacket: " + this.error);
}
@JsonIgnore
public void onHandle(WebSocket webSocket, SocketServer socketServer) {
socketServer.log(webSocket, "InvalidPacket: " + this.error);
}
@JsonIgnore
public SocketFuture<IServerToClientPacket> getFuture() {
return SocketFuture.completedFuture();
}
}

View File

@@ -1,40 +1,13 @@
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;
/**
* A packet to send simple informational messages between the client and the server
*/
public class MessagePacket implements IClientToServerPacket.Void, IServerToClientPacket {
public class MessagePacket implements IPacket {
/**
* 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;
@JsonIgnore
public static MessagePacket create(String message) {
MessagePacket packet = new MessagePacket();
packet.message = message;
return packet;
}
@JsonIgnore
public void onHandle(WebSocket webSocket, SocketClient socketClient) {
SocketClient.logger.info("SocketMessage: " + this.message);
}
@JsonIgnore
public void onHandle(WebSocket webSocket, SocketServer socketServer) {
socketServer.log(webSocket, this.message);
}
@JsonIgnore
public SocketFuture<IServerToClientPacket> getFuture() {
return SocketFuture.completedFuture();
}
}

View File

@@ -3,7 +3,6 @@ package de.dhbwstuttgart.server.packet;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import de.dhbwstuttgart.util.Logger;
/**
* A wrapper for the packet to ensure correct serialization/deserialization and make it possible to detect the matching
@@ -17,22 +16,20 @@ public class PacketContainer {
/*
* The available packet types. The one type that is represented in the JSON should always be the ONLY non-null value.
* They have to be public (for the moment) to let jackson fill them in while deserializing
* They have to be private (for the moment) to let jackson fill them in while deserializing
*/
public ErrorPacket errorPacket = null;
public MessagePacket messagePacket = null;
public InvalidPacket invalidPacket = null;
public UnifyRequestPacket unifyRequestPacket = null;
public UnifyResultPacket unifyResultPacket = null;
public DebugPacket debugPacket = null;
public SetAutoclosePacket setAutoclosePacket = null;
/**
* Generate the JSON string for the given packet
*
* @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 {
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
@@ -46,13 +43,7 @@ public class PacketContainer {
container.unifyRequestPacket = (UnifyRequestPacket) packet;
else if (packet instanceof UnifyResultPacket)
container.unifyResultPacket = (UnifyResultPacket) packet;
else if (packet instanceof DebugPacket)
container.debugPacket = (DebugPacket) packet;
else if (packet instanceof SetAutoclosePacket)
container.setAutoclosePacket = (SetAutoclosePacket) packet;
// 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);
}
@@ -79,15 +70,10 @@ public class PacketContainer {
return container.unifyRequestPacket;
if (container.unifyResultPacket != null)
return container.unifyResultPacket;
if (container.debugPacket != null)
return container.debugPacket;
if (container.setAutoclosePacket != null)
return container.setAutoclosePacket;
// Add new packets here and in the serialize method
throw new RuntimeException("Cannot map received json to any known packet class");
} catch (Exception e) {
(new Logger()).exception(e);
InvalidPacket packet = new InvalidPacket();
packet.error = e.getMessage();
return packet;

View File

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

View File

@@ -1,164 +1,48 @@
package de.dhbwstuttgart.server.packet;
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.packet.dataContainers.KeyStorage;
import de.dhbwstuttgart.server.packet.dataContainers.serialized.SerialList;
import de.dhbwstuttgart.server.packet.dataContainers.serialized.SerialMap;
import de.dhbwstuttgart.server.packet.dataContainers.serialized.SerialValue;
import de.dhbwstuttgart.server.packet.dataContainers.SerializedFiniteClosure;
import de.dhbwstuttgart.server.packet.dataContainers.SerializedPairConstraintSet;
import de.dhbwstuttgart.server.packet.dataContainers.SerializedUnifyConstraintSet;
import de.dhbwstuttgart.typeinference.constraints.ConstraintSet;
import de.dhbwstuttgart.typeinference.constraints.Pair;
import de.dhbwstuttgart.typeinference.unify.PlaceholderRegistry;
import de.dhbwstuttgart.typeinference.unify.TypeUnify;
import de.dhbwstuttgart.typeinference.unify.UnifyContext;
import de.dhbwstuttgart.typeinference.unify.UnifyResultListenerImpl;
import de.dhbwstuttgart.typeinference.unify.UnifyResultModel;
import de.dhbwstuttgart.typeinference.unify.UnifyTaskModel;
import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure;
import de.dhbwstuttgart.typeinference.unify.model.FiniteClosure;
import de.dhbwstuttgart.typeinference.unify.model.PlaceholderType;
import de.dhbwstuttgart.typeinference.unify.model.UnifyPair;
import de.dhbwstuttgart.typeinference.unify.model.UnifyType;
import de.dhbwstuttgart.util.Logger;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.concurrent.ForkJoinPool;
import org.java_websocket.WebSocket;
/**
* A packet to send all required data for the unification algorithm to the server and request the unification
*/
public class UnifyRequestPacket implements IClientToServerPacket<UnifyResultPacket> {
public class UnifyRequestPacket implements IPacket {
public SerialMap finiteClosure;
public SerialMap constraintSet;
public SerialMap unifyConstraintSet;
public SerialMap serialKeyStorage;
public SerialValue<?> placeholders;
public SerialList<SerialMap> factoryplaceholders;
public String futureId;
public int logLevel;
@JsonIgnore
private KeyStorage keyStorage = new KeyStorage();
@JsonIgnore
private boolean keyStorageLoaded = false;
public SerializedFiniteClosure finiteClosure;
public SerializedPairConstraintSet constraints;
public SerializedUnifyConstraintSet unifyConstraints;
public static UnifyRequestPacket create(
FiniteClosure finiteClosure,
ConstraintSet<Pair> constraintSet,
ConstraintSet<UnifyPair> unifyConstraintSet,
PlaceholderRegistry placeholderRegistry
IFiniteClosure finiteClosure,
ConstraintSet<Pair> constraints,
ConstraintSet<UnifyPair> unifyConstraints
) {
UnifyRequestPacket packet = new UnifyRequestPacket();
// store constraint and finite closure
packet.finiteClosure = finiteClosure.toSerial(packet.keyStorage);
packet.constraintSet = constraintSet.toSerial(packet.keyStorage);
packet.unifyConstraintSet = unifyConstraintSet.toSerial(packet.keyStorage);
// store placeholder registry
var serialRegistry = placeholderRegistry.toSerial(packet.keyStorage);
packet.placeholders = serialRegistry.getValue("ph");
packet.factoryplaceholders = serialRegistry.getList("factoryPh").assertListOfMaps();
// store referenced objects separately
packet.serialKeyStorage = packet.keyStorage.toSerial(packet.keyStorage);
packet.logLevel = ConsoleInterface.logLevel.getValue();
packet.finiteClosure = SerializedFiniteClosure.create(finiteClosure);
packet.constraints = SerializedPairConstraintSet.create(constraints);
packet.unifyConstraints = SerializedUnifyConstraintSet.create(unifyConstraints);
return packet;
}
@JsonIgnore
public void loadKeyStorage(UnifyContext context) {
if (!keyStorageLoaded) {
keyStorageLoaded = true;
keyStorage = KeyStorage.fromSerial(this.serialKeyStorage, context);
}
public IFiniteClosure retrieveFiniteClosure() {
return this.finiteClosure.toObject();
}
@JsonIgnore
private FiniteClosure retrieveFiniteClosure(UnifyContext context) {
this.loadKeyStorage(context);
return FiniteClosure.fromSerial(this.finiteClosure, context, keyStorage);
public ConstraintSet<Pair> retrieveConstraints() {
return this.constraints.toObject();
}
@JsonIgnore
private ConstraintSet<Pair> retrieveConstraintSet(UnifyContext context) {
this.loadKeyStorage(context);
return ConstraintSet.fromSerial(this.constraintSet, context, Pair.class, keyStorage);
}
@JsonIgnore
private ConstraintSet<UnifyPair> retrieveUnifyConstraintSet(UnifyContext context) {
this.loadKeyStorage(context);
return ConstraintSet.fromSerial(this.unifyConstraintSet, context, UnifyPair.class, keyStorage);
}
@JsonIgnore
public void onHandle(WebSocket webSocket, SocketServer socketServer) {
socketServer.sendMessage(webSocket, "You requested a unify! Please wait until I calculated everything...");
socketServer.log(webSocket, "Client requested a unification. Starting now...");
try {
var placeholderRegistry = new PlaceholderRegistry();
ArrayList<String> existingPlaceholders = (ArrayList) this.placeholders.getOf(ArrayList.class);
existingPlaceholders.forEach(placeholderRegistry::addPlaceholder);
Logger logger = new ServerTaskLogger(
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
);
this.factoryplaceholders.stream()
.map(p -> (PlaceholderType)UnifyType.fromSerial(p, unifyContext))
.forEach(placeholderRegistry.UnifyTypeFactory_PLACEHOLDERS::add);
// start the unification algorithm from the received data
IFiniteClosure finiteClosure = this.retrieveFiniteClosure(unifyContext);
ConstraintSet<Pair> constraintSet = this.retrieveConstraintSet(unifyContext);
ConstraintSet<UnifyPair> unifyConstraintSet = this.retrieveUnifyConstraintSet(unifyContext);
var resultModel = new UnifyResultModel(constraintSet, finiteClosure);
UnifyResultListenerImpl resultListener = new UnifyResultListenerImpl();
resultModel.addUnifyResultListener(resultListener);
TypeUnify.unifyParallel(
unifyConstraintSet.getUndConstraints(),
unifyConstraintSet.getOderConstraints(),
finiteClosure,
unifyContext.newWithResultModel(resultModel)
);
var resultSets = resultListener.getResults();
socketServer.log(webSocket, "Finished unification");
socketServer.sendMessage(webSocket, "Unification finished. Found " + resultSets.size() + " result sets");
if (webSocket.isOpen()) {
UnifyResultPacket resultPacket = UnifyResultPacket.create(resultSets, futureId);
webSocket.send(PacketContainer.serialize(resultPacket));
}
} catch (Exception e) {
SocketServer.logger.exception(e);
socketServer.log(webSocket, e.getMessage());
}
}
@JsonIgnore
public SocketFuture<UnifyResultPacket> getFuture() {
var future = new SocketFuture<>(List.of(UnifyResultPacket.class));
futureId = future.futureId;
return future;
public ConstraintSet<UnifyPair> retrieveUnifyConstraints() {
return this.unifyConstraints.toObject();
}
}

View File

@@ -1,45 +1,27 @@
package de.dhbwstuttgart.server.packet;
import com.fasterxml.jackson.annotation.JsonIgnore;
import de.dhbwstuttgart.server.SocketClient;
import de.dhbwstuttgart.server.packet.dataContainers.KeyStorage;
import de.dhbwstuttgart.server.packet.dataContainers.serialized.ISerialNode;
import de.dhbwstuttgart.server.packet.dataContainers.serialized.SerialList;
import de.dhbwstuttgart.server.packet.dataContainers.serialized.SerialMap;
import de.dhbwstuttgart.server.packet.dataContainers.SerializedResultSet;
import de.dhbwstuttgart.typeinference.result.ResultSet;
import de.dhbwstuttgart.typeinference.unify.UnifyContext;
import java.util.Arrays;
import java.util.List;
import org.java_websocket.WebSocket;
/**
* A packet to send all calculated data from the unification algorithm back to the client
*/
public class UnifyResultPacket implements IServerToClientPacket {
public class UnifyResultPacket implements IPacket {
public SerialList<ISerialNode> results;
public SerialMap keyStorage;
public String futureId;
public SerializedResultSet[] results;
public static UnifyResultPacket create(List<ResultSet> resultSets, String futureId) {
public static UnifyResultPacket create(List<ResultSet> resultSets) {
UnifyResultPacket serialized = new UnifyResultPacket();
KeyStorage keyStorage = new KeyStorage();
serialized.results = SerialList.fromMapped(resultSets, resultSet -> resultSet.toSerial(keyStorage));
serialized.keyStorage = keyStorage.toSerial(keyStorage);
serialized.futureId = futureId;
serialized.results = resultSets.stream().map(SerializedResultSet::create).toArray(SerializedResultSet[]::new);
return serialized;
}
@JsonIgnore
public List<ResultSet> getResultSet(UnifyContext context) {
return this.results.assertListOfMaps().stream()
.map(resultData -> ResultSet.fromSerial(resultData, context)).toList();
public List<ResultSet> getResultSet() {
return Arrays.stream(this.results).map(SerializedResultSet::toObject).toList();
}
@JsonIgnore
public void onHandle(WebSocket webSocket, SocketClient socketClient) {
SocketClient.logger.info("Received unify result");
socketClient.completeResponseFuture(futureId, this);
}
}

View File

@@ -1,16 +0,0 @@
package de.dhbwstuttgart.server.packet.dataContainers;
import de.dhbwstuttgart.exceptions.NotImplementedException;
import de.dhbwstuttgart.server.packet.dataContainers.serialized.ISerialNode;
import de.dhbwstuttgart.server.packet.dataContainers.serialized.SerialMap;
import de.dhbwstuttgart.typeinference.unify.UnifyContext;
public interface ISerializableData {
public abstract ISerialNode toSerial(KeyStorage keyStorage);
public static Object fromSerial(SerialMap data, UnifyContext context) {
throw new NotImplementedException("Missing implementation of \"fromSerial\" for a serializable element");
}
}

View File

@@ -1,103 +0,0 @@
package de.dhbwstuttgart.server.packet.dataContainers;
import de.dhbwstuttgart.server.packet.dataContainers.serialized.SerialMap;
import de.dhbwstuttgart.typeinference.unify.UnifyContext;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
public class KeyStorage implements ISerializableData {
/**
* Store a unique identifier for every element, so it can be referenced in the json
*/
protected AtomicInteger identifierCount = new AtomicInteger();
/**
* Store the serialized element per identifier when serializing
*/
protected SerialMap serializedElements = new SerialMap();
/**
* Store the unserialized element per identifier when unserializing
*/
protected Map<String, ISerializableData> unserializedElements = new HashMap<>();
/**
* Retrieve or generate a new identifier for a constraint
*/
public String getIdentifier() {
return this.identifierCount.incrementAndGet() + "_";
}
/**
* Checks if the given element identifier belongs to an element that was already serialized
*/
public boolean isAlreadySerialized(String identifier) {
return this.serializedElements.containsKey(identifier);
}
/**
* Checks if the given element identifier belongs to a element that was already unserialized
*/
public boolean isAlreadyUnserialized(String identifier) {
return this.unserializedElements.containsKey(identifier);
}
/**
* Register a serialized element to prevent it from being serialized again
*/
public void putSerialized(String identifier, SerialMap serializedElement) {
this.serializedElements.put(identifier, serializedElement);
}
/**
* Retrieve a serialized element
*/
public SerialMap getSerialized(String identifier) {
if (!this.serializedElements.containsKey(identifier)) {
throw new RuntimeException("No serialized element of identifier " + identifier + " available to get");
}
return this.serializedElements.getMap(identifier);
}
/**
* Register an unserialized element to prevent it from being unserialized again
*/
public void putUnserialized(String identifier, ISerializableData element) {
this.unserializedElements.put(identifier, element);
}
/**
* Retrieve an unserialized element
*/
public <T extends ISerializableData> T getUnserialized(String identifier, Class<T> target) {
if (!this.unserializedElements.containsKey(identifier)) {
throw new RuntimeException("No unserialized element of identifier " + identifier + " available to get");
}
var element = this.unserializedElements.get(identifier);
if (target.isInstance(element)) {
return (T) element;
}
throw new RuntimeException("Failed to get unserialized element from KeyStorage. Expected instance of " +
target.getName() + " but found " + element.getClass().getName());
}
@Override
public SerialMap toSerial(KeyStorage keyStorage) {
SerialMap serialized = new SerialMap();
serialized.put("serializedElements", this.serializedElements);
return serialized;
}
public static KeyStorage fromSerial(SerialMap data, UnifyContext context) {
var serializedConstraintsData = data.getMap("serializedElements");
var constraintContext = new KeyStorage();
for (var entry : serializedConstraintsData.entrySet()) {
if (entry.getValue() instanceof SerialMap valueMap) {
constraintContext.putSerialized(entry.getKey(), valueMap);
}
}
return constraintContext;
}
}

View File

@@ -0,0 +1,30 @@
package de.dhbwstuttgart.server.packet.dataContainers;
import de.dhbwstuttgart.server.packet.IPacket;
import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure;
import de.dhbwstuttgart.typeinference.unify.model.FiniteClosure;
import java.util.Arrays;
import java.util.HashSet;
/**
* Serializable container of
*
* @see IFiniteClosure
*/
public class SerializedFiniteClosure implements IPacket.IDataContainer<IFiniteClosure> {
public SerializedUnifyPair[] pairs;
public static SerializedFiniteClosure create(IFiniteClosure finiteClosure) {
SerializedFiniteClosure fc = new SerializedFiniteClosure();
fc.pairs = finiteClosure.getPairs().stream().map(SerializedUnifyPair::create).toArray(SerializedUnifyPair[]::new);
return fc;
}
@Override
public IFiniteClosure toObject() {
return new FiniteClosure(
new HashSet<>(Arrays.stream(pairs).map(SerializedUnifyPair::toObject).toList()),
null
);
}
}

View File

@@ -0,0 +1,37 @@
package de.dhbwstuttgart.server.packet.dataContainers;
import com.fasterxml.jackson.annotation.JsonProperty;
import de.dhbwstuttgart.server.packet.IPacket;
import de.dhbwstuttgart.typeinference.constraints.Pair;
import de.dhbwstuttgart.typeinference.unify.model.PairOperator;
/**
* Serializable container of
*
* @see Pair
*/
public class SerializedPair implements IPacket.IDataContainer<Pair> {
@JsonProperty("o")
public PairOperator operator;
public SerializedTokenWrapper ta1;
public SerializedTokenWrapper ta2;
public static SerializedPair create(Pair pair) {
SerializedPair sPair = new SerializedPair();
sPair.operator = pair.GetOperator();
sPair.ta1 = SerializedTokenWrapper.create(pair.TA1);
sPair.ta2 = SerializedTokenWrapper.create(pair.TA2);
return sPair;
}
@Override
public Pair toObject() {
return new Pair(
ta1.toObject(),
ta2.toObject(),
operator
);
}
}

View File

@@ -0,0 +1,82 @@
package de.dhbwstuttgart.server.packet.dataContainers;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import de.dhbwstuttgart.server.packet.IPacket;
import de.dhbwstuttgart.typeinference.constraints.Constraint;
import de.dhbwstuttgart.typeinference.constraints.Pair;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
/**
* Serializable container of
*
* @see Constraint<Pair>
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
public class SerializedPairConstraint implements IPacket.IDataContainer<Constraint<Pair>> {
// serialize recursive structure
public static final HashMap<Constraint<Pair>, String> UNIQUE_CONSTRAINT_KEY_MAP = new HashMap<>();
public static final HashMap<String, SerializedPairConstraint> UNIQUE_CONSTRAINT_MAP = new HashMap<>();
// deserialize recursive structure
private static final HashMap<String, Constraint<Pair>> UNIQUE_OBJECT_MAP = new HashMap<>();
@JsonProperty("i")
public boolean isInherited;
@JsonProperty("u")
public String uniqueKey;
@JsonProperty("e")
public String extendedConstraint = null;
@JsonProperty("m")
public SerializedPair[] methodSignatureConstraint;
@JsonProperty("c")
public SerializedPair[] constraintElements;
public static SerializedPairConstraint create(Constraint<Pair> constraint) {
final String uniqueKey = UNIQUE_CONSTRAINT_KEY_MAP.getOrDefault(constraint, "_" + UNIQUE_CONSTRAINT_MAP.size());
if (UNIQUE_CONSTRAINT_MAP.containsKey(uniqueKey)) {
return UNIQUE_CONSTRAINT_MAP.get(uniqueKey);
}
SerializedPairConstraint pairConstraint = new SerializedPairConstraint();
pairConstraint.uniqueKey = uniqueKey;
UNIQUE_CONSTRAINT_KEY_MAP.put(constraint, uniqueKey);
UNIQUE_CONSTRAINT_MAP.put(uniqueKey, pairConstraint);
pairConstraint.constraintElements = constraint.stream().map(SerializedPair::create).toArray(SerializedPair[]::new);
pairConstraint.isInherited = constraint.isInherited();
pairConstraint.methodSignatureConstraint = constraint.getmethodSignatureConstraint().stream().map(SerializedPair::create).toArray(SerializedPair[]::new);
if (constraint.getExtendConstraint() != null) {
pairConstraint.extendedConstraint = SerializedPairConstraint.create(constraint.getExtendConstraint()).uniqueKey;
}
return pairConstraint;
}
@Override
public Constraint<Pair> toObject() {
if (UNIQUE_OBJECT_MAP.containsKey(uniqueKey)) {
return UNIQUE_OBJECT_MAP.get(uniqueKey);
}
Constraint<Pair> constraint = new Constraint<>();
UNIQUE_OBJECT_MAP.put(uniqueKey, constraint);
constraint.addAll(Arrays.stream(constraintElements).map(SerializedPair::toObject).toList());
constraint.setIsInherited(isInherited);
constraint.setmethodSignatureConstraint(new HashSet<>(
Arrays.stream(methodSignatureConstraint).map(SerializedPair::toObject).toList()
));
SerializedPairConstraint extendedConstraint = this.extendedConstraint == null ? null :
SerializedPairConstraint.UNIQUE_CONSTRAINT_MAP.get(this.extendedConstraint);
if (extendedConstraint != null) {
constraint.setExtendConstraint(extendedConstraint.toObject());
}
return constraint;
}
}

View File

@@ -0,0 +1,60 @@
package de.dhbwstuttgart.server.packet.dataContainers;
import de.dhbwstuttgart.server.packet.IPacket;
import de.dhbwstuttgart.typeinference.constraints.Constraint;
import de.dhbwstuttgart.typeinference.constraints.ConstraintSet;
import de.dhbwstuttgart.typeinference.constraints.Pair;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Serializable container of
*
* @see ConstraintSet<Pair>
*/
public class SerializedPairConstraintSet implements IPacket.IDataContainer<ConstraintSet<Pair>> {
public SerializedPair[] undConstraints;
public SerializedPairConstraint[][] oderConstraints;
public Map<String, SerializedPairConstraint> uniqueConstraintMap = new HashMap<>();
public static SerializedPairConstraintSet create(ConstraintSet<Pair> constraints) {
SerializedPairConstraintSet constraintSet = new SerializedPairConstraintSet();
constraintSet.undConstraints = constraints.getUndConstraints().stream().map(SerializedPair::create).toArray(SerializedPair[]::new);
constraintSet.oderConstraints = constraints.getOderConstraints().stream().map(consSet ->
consSet.stream().map(SerializedPairConstraint::create).toArray(SerializedPairConstraint[]::new)
).toArray(SerializedPairConstraint[][]::new);
// add all the gathered constraints to a serializable property
constraintSet.uniqueConstraintMap.putAll(SerializedPairConstraint.UNIQUE_CONSTRAINT_MAP);
return constraintSet;
}
@Override
public ConstraintSet<Pair> toObject() {
ConstraintSet<Pair> consSet = new ConstraintSet<>();
// read all the constraints from the serializable property
SerializedPairConstraint.UNIQUE_CONSTRAINT_MAP.putAll(this.uniqueConstraintMap);
Constraint<Pair> undCons = new Constraint<>();
undCons.addAll(Arrays.stream(undConstraints).map(SerializedPair::toObject).toList());
consSet.addAllUndConstraint(undCons);
List<Set<Constraint<Pair>>> oderCons = new ArrayList<>(Arrays.stream(oderConstraints).map(cons ->
new HashSet<>(
Arrays.stream(cons).map(SerializedPairConstraint::toObject).toList()
)
).toList());
consSet.addAllOderConstraint(oderCons);
return consSet;
}
}

View File

@@ -0,0 +1,63 @@
package de.dhbwstuttgart.server.packet.dataContainers;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import de.dhbwstuttgart.server.packet.IPacket;
import de.dhbwstuttgart.server.packet.dataContainers.resultPairs.SerializedPairNoResult;
import de.dhbwstuttgart.server.packet.dataContainers.resultPairs.SerializedPairTPHEqualTPH;
import de.dhbwstuttgart.server.packet.dataContainers.resultPairs.SerializedPairTPHequalRefTypeOrWildcardType;
import de.dhbwstuttgart.server.packet.dataContainers.resultPairs.SerializedPairTPHsmallerTPH;
import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric;
import de.dhbwstuttgart.typeinference.result.PairNoResult;
import de.dhbwstuttgart.typeinference.result.PairTPHEqualTPH;
import de.dhbwstuttgart.typeinference.result.PairTPHequalRefTypeOrWildcardType;
import de.dhbwstuttgart.typeinference.result.PairTPHsmallerTPH;
import de.dhbwstuttgart.typeinference.result.ResultPair;
/**
* Serializable container of
*
* @see ResultPair
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
public class SerializedResultPairWrapper implements IPacket.IDataContainer<ResultPair<RefTypeOrTPHOrWildcardOrGeneric, RefTypeOrTPHOrWildcardOrGeneric>> {
@JsonProperty("nr")
public SerializedPairNoResult noResult = null;
@JsonProperty("teo")
public SerializedPairTPHequalRefTypeOrWildcardType tphEqualOther = null;
@JsonProperty("tet")
public SerializedPairTPHEqualTPH tphEqualTph = null;
@JsonProperty("tst")
public SerializedPairTPHsmallerTPH tphSmallerTPH = null;
public static <A extends RefTypeOrTPHOrWildcardOrGeneric, B extends RefTypeOrTPHOrWildcardOrGeneric> SerializedResultPairWrapper create(ResultPair<A, B> pair) {
SerializedResultPairWrapper serialized = new SerializedResultPairWrapper();
if (pair instanceof PairNoResult noResult)
serialized.noResult = SerializedPairNoResult.create(noResult);
else if (pair instanceof PairTPHequalRefTypeOrWildcardType tphEqualOther)
serialized.tphEqualOther = SerializedPairTPHequalRefTypeOrWildcardType.create(tphEqualOther);
else if (pair instanceof PairTPHEqualTPH tphEqualTph)
serialized.tphEqualTph = SerializedPairTPHEqualTPH.create(tphEqualTph);
else if (pair instanceof PairTPHsmallerTPH tphSmallerTPH)
serialized.tphSmallerTPH = SerializedPairTPHsmallerTPH.create(tphSmallerTPH);
return serialized;
}
@Override
@SuppressWarnings("rawtypes") // this is not optimal, but we have to conform to interface specifications
public ResultPair toObject() {
if (noResult != null)
return noResult.toObject();
else if (tphEqualOther != null)
return tphEqualOther.toObject();
else if (tphEqualTph != null)
return tphEqualTph.toObject();
else if (tphSmallerTPH != null)
return tphSmallerTPH.toObject();
return null;
}
}

View File

@@ -0,0 +1,31 @@
package de.dhbwstuttgart.server.packet.dataContainers;
import de.dhbwstuttgart.server.packet.IPacket;
import de.dhbwstuttgart.typeinference.result.ResultSet;
import java.util.Arrays;
import java.util.HashSet;
/**
* Serializable container of
*
* @see ResultSet
*/
public class SerializedResultSet implements IPacket.IDataContainer<ResultSet> {
public SerializedResultPairWrapper[] results;
public static SerializedResultSet create(ResultSet resultSet) {
SerializedResultSet serialized = new SerializedResultSet();
serialized.results = resultSet.results.stream().map(SerializedResultPairWrapper::create).toArray(SerializedResultPairWrapper[]::new);
return serialized;
}
public ResultSet toObject() {
return new ResultSet(
new HashSet<>(
Arrays.stream(this.results).map(SerializedResultPairWrapper::toObject).toList()
)
);
}
}

View File

@@ -0,0 +1,72 @@
package de.dhbwstuttgart.server.packet.dataContainers;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import de.dhbwstuttgart.server.packet.IPacket;
import de.dhbwstuttgart.server.packet.dataContainers.token.SerializedExtendsWildcardType;
import de.dhbwstuttgart.server.packet.dataContainers.token.SerializedGenericRefType;
import de.dhbwstuttgart.server.packet.dataContainers.token.SerializedPlaceholderType;
import de.dhbwstuttgart.server.packet.dataContainers.token.SerializedRefType;
import de.dhbwstuttgart.server.packet.dataContainers.token.SerializedSuperWildcardType;
import de.dhbwstuttgart.server.packet.dataContainers.token.SerializedVoidType;
import de.dhbwstuttgart.syntaxtree.type.ExtendsWildcardType;
import de.dhbwstuttgart.syntaxtree.type.GenericRefType;
import de.dhbwstuttgart.syntaxtree.type.RefType;
import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric;
import de.dhbwstuttgart.syntaxtree.type.SuperWildcardType;
import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder;
import de.dhbwstuttgart.syntaxtree.type.Void;
/**
* Serializable container of
*
* @see RefTypeOrTPHOrWildcardOrGeneric
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
public class SerializedTokenWrapper implements IPacket.IDataContainer<RefTypeOrTPHOrWildcardOrGeneric> {
@JsonProperty("ew")
public SerializedExtendsWildcardType extendsWildcardType = null;
@JsonProperty("gr")
public SerializedGenericRefType genericRefType = null;
@JsonProperty("p")
public SerializedPlaceholderType placeholderType = null;
@JsonProperty("r")
public SerializedRefType refType = null;
@JsonProperty("sw")
public SerializedSuperWildcardType superWildcardType = null;
@JsonProperty("v")
public SerializedVoidType voidType = null;
public static SerializedTokenWrapper create(RefTypeOrTPHOrWildcardOrGeneric type) {
SerializedTokenWrapper wrapper = new SerializedTokenWrapper();
if (type instanceof ExtendsWildcardType)
wrapper.extendsWildcardType = SerializedExtendsWildcardType.create((ExtendsWildcardType) type);
else if (type instanceof GenericRefType)
wrapper.genericRefType = SerializedGenericRefType.create((GenericRefType) type);
else if (type instanceof TypePlaceholder)
wrapper.placeholderType = SerializedPlaceholderType.create((TypePlaceholder) type);
else if (type instanceof Void)
wrapper.voidType = SerializedVoidType.create((Void) type);
else if (type instanceof RefType)
wrapper.refType = SerializedRefType.create((RefType) type);
else if (type instanceof SuperWildcardType)
wrapper.superWildcardType = SerializedSuperWildcardType.create((SuperWildcardType) type);
return wrapper;
}
@Override
public RefTypeOrTPHOrWildcardOrGeneric toObject() {
if (extendsWildcardType != null) return extendsWildcardType.toObject();
if (genericRefType != null) return genericRefType.toObject();
if (placeholderType != null) return placeholderType.toObject();
if (refType != null) return refType.toObject();
if (superWildcardType != null) return superWildcardType.toObject();
if (voidType != null) return voidType.toObject();
return null;
}
}

View File

@@ -0,0 +1,49 @@
package de.dhbwstuttgart.server.packet.dataContainers;
import de.dhbwstuttgart.server.packet.IPacket;
import de.dhbwstuttgart.typeinference.constraints.Constraint;
import de.dhbwstuttgart.typeinference.constraints.ConstraintSet;
import de.dhbwstuttgart.typeinference.unify.model.UnifyPair;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Serializable container of
*
* @see ConstraintSet<UnifyPair>
*/
public class SerializedUnifyConstraintSet implements IPacket.IDataContainer<ConstraintSet<UnifyPair>> {
public SerializedUnifyPair[] undConstraints;
public SerializedUnifyPairConstraint[][] oderConstraints;
public static SerializedUnifyConstraintSet create(ConstraintSet<UnifyPair> unifyCons) {
SerializedUnifyConstraintSet constraintSet = new SerializedUnifyConstraintSet();
constraintSet.undConstraints = unifyCons.getUndConstraints().stream().map(SerializedUnifyPair::create).toArray(SerializedUnifyPair[]::new);
constraintSet.oderConstraints = unifyCons.getOderConstraints().stream().map(constraints ->
constraints.stream().map(SerializedUnifyPairConstraint::create).toArray(SerializedUnifyPairConstraint[]::new)
).toArray(SerializedUnifyPairConstraint[][]::new);
return constraintSet;
}
@Override
public ConstraintSet<UnifyPair> toObject() {
ConstraintSet<UnifyPair> consSet = new ConstraintSet<>();
Constraint<UnifyPair> undCons = new Constraint<>();
undCons.addAll(Arrays.stream(undConstraints).map(SerializedUnifyPair::toObject).toList());
consSet.addAllUndConstraint(undCons);
List<Set<Constraint<UnifyPair>>> oderCons = new ArrayList<>(Arrays.stream(oderConstraints).map(oderConsSet ->
new HashSet<>(
Arrays.stream(oderConsSet).map(SerializedUnifyPairConstraint::toObject).toList()
)
).toList());
consSet.addAllOderConstraint(oderCons);
return consSet;
}
}

View File

@@ -0,0 +1,32 @@
package de.dhbwstuttgart.server.packet.dataContainers;
import com.fasterxml.jackson.annotation.JsonProperty;
import de.dhbwstuttgart.server.packet.IPacket;
import de.dhbwstuttgart.typeinference.unify.model.PairOperator;
import de.dhbwstuttgart.typeinference.unify.model.UnifyPair;
/**
* Serializable container of
*
* @see UnifyPair
*/
public class SerializedUnifyPair implements IPacket.IDataContainer<UnifyPair> {
public SerializedUnifyTypeWrapper lhs;
public SerializedUnifyTypeWrapper rhs;
@JsonProperty("o")
public PairOperator operator;
public static SerializedUnifyPair create(UnifyPair unifyPair) {
SerializedUnifyPair pair = new SerializedUnifyPair();
pair.lhs = SerializedUnifyTypeWrapper.create(unifyPair.getLhsType());
pair.rhs = SerializedUnifyTypeWrapper.create(unifyPair.getRhsType());
pair.operator = unifyPair.getPairOp();
return pair;
}
@Override
public UnifyPair toObject() {
return new UnifyPair(lhs.toObject(), rhs.toObject(), operator);
}
}

View File

@@ -0,0 +1,52 @@
package de.dhbwstuttgart.server.packet.dataContainers;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import de.dhbwstuttgart.server.packet.IPacket;
import de.dhbwstuttgart.typeinference.constraints.Constraint;
import de.dhbwstuttgart.typeinference.unify.model.UnifyPair;
import java.util.Arrays;
import java.util.HashSet;
/**
* Serializable container of
*
* @see Constraint<UnifyPair>
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
public class SerializedUnifyPairConstraint implements IPacket.IDataContainer<Constraint<UnifyPair>> {
@JsonProperty("i")
public boolean isInherited;
@JsonProperty("ec")
public SerializedUnifyPairConstraint extendedConstraint = null;
@JsonProperty("p")
public SerializedUnifyPair[] methodSignatureConstraints;
@JsonProperty("c")
public SerializedUnifyPair[] constraintElements;
public static SerializedUnifyPairConstraint create(Constraint<UnifyPair> constraint) {
SerializedUnifyPairConstraint cons = new SerializedUnifyPairConstraint();
cons.constraintElements = constraint.stream().map(SerializedUnifyPair::create).toArray(SerializedUnifyPair[]::new);
cons.isInherited = constraint.isInherited();
if (constraint.getExtendConstraint() != null) {
cons.extendedConstraint = SerializedUnifyPairConstraint.create(constraint.getExtendConstraint());
}
cons.methodSignatureConstraints = constraint.getmethodSignatureConstraint().stream().map(SerializedUnifyPair::create).toArray(SerializedUnifyPair[]::new);
return cons;
}
@Override
public Constraint<UnifyPair> toObject() {
Constraint<UnifyPair> cons = new Constraint<>();
cons.addAll(Arrays.stream(constraintElements).map(SerializedUnifyPair::toObject).toList());
cons.setIsInherited(isInherited);
if (extendedConstraint != null) {
cons.setExtendConstraint(extendedConstraint.toObject());
}
cons.setmethodSignatureConstraint(new HashSet<>(Arrays.stream(methodSignatureConstraints).map(SerializedUnifyPair::toObject).toList()));
return cons;
}
}

View File

@@ -0,0 +1,65 @@
package de.dhbwstuttgart.server.packet.dataContainers;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import de.dhbwstuttgart.server.packet.IPacket;
import de.dhbwstuttgart.server.packet.dataContainers.unifyType.SerializedExtendsType;
import de.dhbwstuttgart.server.packet.dataContainers.unifyType.SerializedFunNType;
import de.dhbwstuttgart.server.packet.dataContainers.unifyType.SerializedPlaceholderType;
import de.dhbwstuttgart.server.packet.dataContainers.unifyType.SerializedReferenceType;
import de.dhbwstuttgart.server.packet.dataContainers.unifyType.SerializedSuperType;
import de.dhbwstuttgart.typeinference.unify.model.ExtendsType;
import de.dhbwstuttgart.typeinference.unify.model.FunNType;
import de.dhbwstuttgart.typeinference.unify.model.PlaceholderType;
import de.dhbwstuttgart.typeinference.unify.model.ReferenceType;
import de.dhbwstuttgart.typeinference.unify.model.SuperType;
import de.dhbwstuttgart.typeinference.unify.model.UnifyType;
/**
* Serializable container of
*
* @see UnifyType
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
public class SerializedUnifyTypeWrapper implements IPacket.IDataContainer<UnifyType> {
@JsonProperty("e")
public SerializedExtendsType extendsType = null;
@JsonProperty("s")
public SerializedSuperType superType = null;
@JsonProperty("r")
public SerializedReferenceType referenceType = null;
@JsonProperty("f")
public SerializedFunNType funNType = null;
@JsonProperty("p")
public SerializedPlaceholderType placeholderType = null;
public static SerializedUnifyTypeWrapper create(UnifyType unifyType) {
SerializedUnifyTypeWrapper wrapper = new SerializedUnifyTypeWrapper();
if (unifyType instanceof ExtendsType)
wrapper.extendsType = SerializedExtendsType.create((ExtendsType) unifyType);
else if (unifyType instanceof SuperType)
wrapper.superType = SerializedSuperType.create((SuperType) unifyType);
else if (unifyType instanceof ReferenceType)
wrapper.referenceType = SerializedReferenceType.create((ReferenceType) unifyType);
else if (unifyType instanceof FunNType)
wrapper.funNType = SerializedFunNType.create((FunNType) unifyType);
else if (unifyType instanceof PlaceholderType)
wrapper.placeholderType = SerializedPlaceholderType.create((PlaceholderType) unifyType);
return wrapper;
}
@Override
public UnifyType toObject() {
if (extendsType != null) return extendsType.toObject();
if (superType != null) return superType.toObject();
if (referenceType != null) return referenceType.toObject();
if (funNType != null) return funNType.toObject();
if (placeholderType != null) return placeholderType.toObject();
return null;
}
}

View File

@@ -0,0 +1,38 @@
package de.dhbwstuttgart.server.packet.dataContainers.resultPairs;
import com.fasterxml.jackson.annotation.JsonProperty;
import de.dhbwstuttgart.server.packet.IPacket;
import de.dhbwstuttgart.server.packet.dataContainers.SerializedTokenWrapper;
import de.dhbwstuttgart.typeinference.result.PairNoResult;
/**
* Serializable container of
*
* @see PairNoResult
*/
public class SerializedPairNoResult implements IPacket.IDataContainer<PairNoResult> {
@JsonProperty("l")
public SerializedTokenWrapper left;
@JsonProperty("r")
public SerializedTokenWrapper right;
/**
* Use a static create method to leave the default constructor and simplify list conversions
*/
public static SerializedPairNoResult create(PairNoResult pair) {
SerializedPairNoResult serialized = new SerializedPairNoResult();
serialized.left = SerializedTokenWrapper.create(pair.getLeft());
serialized.right = SerializedTokenWrapper.create(pair.getRight());
return serialized;
}
@Override
public PairNoResult toObject() {
return new PairNoResult(
left.toObject(),
right.toObject()
);
}
}

View File

@@ -0,0 +1,34 @@
package de.dhbwstuttgart.server.packet.dataContainers.resultPairs;
import com.fasterxml.jackson.annotation.JsonProperty;
import de.dhbwstuttgart.server.packet.IPacket;
import de.dhbwstuttgart.server.packet.dataContainers.token.SerializedPlaceholderType;
import de.dhbwstuttgart.typeinference.result.PairTPHEqualTPH;
/**
* Serializable container of
*
* @see PairTPHEqualTPH
*/
public class SerializedPairTPHEqualTPH implements IPacket.IDataContainer<PairTPHEqualTPH> {
@JsonProperty("l")
public SerializedPlaceholderType left;
@JsonProperty("r")
public SerializedPlaceholderType right;
public static SerializedPairTPHEqualTPH create(PairTPHEqualTPH pair) {
SerializedPairTPHEqualTPH serialized = new SerializedPairTPHEqualTPH();
serialized.left = SerializedPlaceholderType.create(pair.getLeft());
serialized.right = SerializedPlaceholderType.create(pair.getRight());
return serialized;
}
@Override
public PairTPHEqualTPH toObject() {
return new PairTPHEqualTPH(
left.toObject(),
right.toObject()
);
}
}

View File

@@ -0,0 +1,36 @@
package de.dhbwstuttgart.server.packet.dataContainers.resultPairs;
import com.fasterxml.jackson.annotation.JsonProperty;
import de.dhbwstuttgart.server.packet.IPacket;
import de.dhbwstuttgart.server.packet.dataContainers.SerializedTokenWrapper;
import de.dhbwstuttgart.server.packet.dataContainers.token.SerializedPlaceholderType;
import de.dhbwstuttgart.typeinference.result.PairTPHequalRefTypeOrWildcardType;
/**
* Serializable container of
*
* @see PairTPHequalRefTypeOrWildcardType
*/
public class SerializedPairTPHequalRefTypeOrWildcardType implements IPacket.IDataContainer<PairTPHequalRefTypeOrWildcardType> {
@JsonProperty("l")
public SerializedPlaceholderType left;
@JsonProperty("r")
public SerializedTokenWrapper right;
public static SerializedPairTPHequalRefTypeOrWildcardType create(PairTPHequalRefTypeOrWildcardType pair) {
SerializedPairTPHequalRefTypeOrWildcardType serialized = new SerializedPairTPHequalRefTypeOrWildcardType();
serialized.left = SerializedPlaceholderType.create(pair.left);
serialized.right = SerializedTokenWrapper.create(pair.right);
return serialized;
}
@Override
public PairTPHequalRefTypeOrWildcardType toObject() {
return new PairTPHequalRefTypeOrWildcardType(
left.toObject(),
right.toObject()
);
}
}

View File

@@ -0,0 +1,34 @@
package de.dhbwstuttgart.server.packet.dataContainers.resultPairs;
import com.fasterxml.jackson.annotation.JsonProperty;
import de.dhbwstuttgart.server.packet.IPacket;
import de.dhbwstuttgart.server.packet.dataContainers.token.SerializedPlaceholderType;
import de.dhbwstuttgart.typeinference.result.PairTPHsmallerTPH;
/**
* Serializable container of
*
* @see PairTPHsmallerTPH
*/
public class SerializedPairTPHsmallerTPH implements IPacket.IDataContainer<PairTPHsmallerTPH> {
@JsonProperty("l")
public SerializedPlaceholderType left;
@JsonProperty("r")
public SerializedPlaceholderType right;
public static SerializedPairTPHsmallerTPH create(PairTPHsmallerTPH pair) {
SerializedPairTPHsmallerTPH serialized = new SerializedPairTPHsmallerTPH();
serialized.left = SerializedPlaceholderType.create(pair.left);
serialized.right = SerializedPlaceholderType.create(pair.right);
return serialized;
}
@Override
public PairTPHsmallerTPH toObject() {
return new PairTPHsmallerTPH(
left.toObject(),
right.toObject()
);
}
}

View File

@@ -1,31 +0,0 @@
package de.dhbwstuttgart.server.packet.dataContainers.serialized;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
/**
* Use the following classes for an intermediate serialized tree structure
*/
@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.PROPERTY,
property = "_t"
)
@JsonSubTypes({
@JsonSubTypes.Type(value = SerialMap.class, name = "m"),
@JsonSubTypes.Type(value = SerialList.class, name = "l"),
@JsonSubTypes.Type(value = SerialValue.class, name = "v"),
@JsonSubTypes.Type(value = SerialUUID.class, name = "u")
})
public interface ISerialNode {
default <T extends ISerialNode> T assertType(Class<T> type) {
if (type.isInstance(this)) {
return (T) this;
}
throw new RuntimeException("Expected ISerialNode to be of type " + type.getName()
+ " but found " + this.getClass().getName() + " instead");
}
}

View File

@@ -1,74 +0,0 @@
package de.dhbwstuttgart.server.packet.dataContainers.serialized;
import com.fasterxml.jackson.annotation.JsonIgnore;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.function.Function;
import java.util.stream.Stream;
public class SerialList<I extends ISerialNode> extends ArrayList<I> implements ISerialNode {
public SerialList() {}
public SerialList(Collection<I> data) {
this.addAll(data);
}
public SerialList(Stream<I> data) {
this(data.toList());
}
public SerialList(I[] data) {
this(Arrays.stream(data).toList());
}
@SafeVarargs
@JsonIgnore
public static <A extends ISerialNode> ArrayList<A> from(A ...values) {
ArrayList<A> list = new SerialList<>();
Collections.addAll(list, values);
return list;
}
@JsonIgnore
public static <A,B extends ISerialNode> SerialList<B> fromMapped(Stream<A> data, Function<A,B> mapper) {
return new SerialList<>(data.map(mapper).toList());
}
@JsonIgnore
public static <A,B extends ISerialNode> SerialList<B> fromMapped(Collection<A> data, Function<A,B> mapper) {
return SerialList.fromMapped(data.stream(), mapper);
}
@JsonIgnore
public static <A,B extends ISerialNode> SerialList<B> fromMapped(A[] data, Function<A,B> mapper) {
return SerialList.fromMapped(Arrays.stream(data), mapper);
}
@JsonIgnore
public SerialList<SerialMap> assertListOfMaps() {
if (this.isEmpty() || this.get(0) instanceof SerialMap) {
return (SerialList<SerialMap>) this;
}
throw new RuntimeException("Required List to contain SerialMap elements but condition failed");
}
@JsonIgnore
public SerialList<SerialList<?>> assertListOfLists() {
if (this.isEmpty() || this.get(0) instanceof SerialList) {
return (SerialList<SerialList<?>>) this;
}
throw new RuntimeException("Required List to contain SerialList elements but condition failed");
}
@JsonIgnore
public SerialList<SerialValue<?>> assertListOfValues() {
if (this.isEmpty() || this.get(0) instanceof SerialValue) {
return (SerialList<SerialValue<?>>) this;
}
throw new RuntimeException("Required List to contain SerialValue elements but condition failed");
}
@JsonIgnore
public SerialList<SerialUUID> assertListOfUUIDs() {
if (this.isEmpty() || this.get(0) instanceof SerialUUID) {
return (SerialList<SerialUUID>) this;
}
throw new RuntimeException("Required List to contain SerialUUID elements but condition failed");
}
}

View File

@@ -1,84 +0,0 @@
package de.dhbwstuttgart.server.packet.dataContainers.serialized;
import com.fasterxml.jackson.annotation.JsonIgnore;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Nullable;
public class SerialMap extends HashMap<String, ISerialNode> implements ISerialNode {
public SerialMap() {
super();
}
public SerialMap(Map<String, ISerialNode> data) {
super(data);
}
@JsonIgnore
public void put(String key, Boolean value) {
this.put(key, new SerialValue<>(value));
}
@JsonIgnore
public void put(String key, String value) {
this.put(key, new SerialValue<>(value));
}
@JsonIgnore
public void put(String key, Number value) {
this.put(key, new SerialValue<>(value));
}
@JsonIgnore
private <T> T get(String key, Class<T> expectedType) {
if (!this.containsKey(key)) {
throw new RuntimeException("Missing required value " + key + " in ObjectMap");
}
var element = this.get(key);
if (element != null && element.getClass() != expectedType) {
throw new RuntimeException(
"Required value " + key + " to be of type " + expectedType.getName() + " but found " + element.getClass().getName()
);
}
return (T)element;
}
@JsonIgnore
public SerialList<?> getList(String key) {
return this.get(key, SerialList.class);
}
@Nullable
@JsonIgnore
public SerialList<?> getListOrNull(String key) {
return this.containsKey(key) ? this.getList(key) : null;
}
@JsonIgnore
public SerialMap getMap(String key) {
return this.get(key, SerialMap.class);
}
@Nullable
@JsonIgnore
public SerialMap getMapOrNull(String key) {
return this.containsKey(key) ? this.getMap(key) : null;
}
@JsonIgnore
public SerialValue<?> getValue(String key) {
return this.get(key, SerialValue.class);
}
@JsonIgnore
public SerialUUID getUUID(String key) {
return this.get(key, SerialUUID.class);
}
@Nullable
@JsonIgnore
public SerialUUID getUUIDOrNull(String key) {
return this.containsKey(key) ? this.getUUID(key) : null;
}
}

View File

@@ -1,13 +0,0 @@
package de.dhbwstuttgart.server.packet.dataContainers.serialized;
public class SerialUUID implements ISerialNode {
public String uuid;
public SerialUUID() {}
public SerialUUID(String uuid) {
this.uuid = uuid;
}
}

View File

@@ -1,28 +0,0 @@
package de.dhbwstuttgart.server.packet.dataContainers.serialized;
import com.fasterxml.jackson.annotation.JsonIgnore;
public class SerialValue<T> implements ISerialNode {
public T value;
public static final SerialValue<Object> NULL = new SerialValue<>(null);
public SerialValue() {}
public SerialValue(T value) {
this.value = value;
}
@JsonIgnore
public <A> SerialValue<A> assertValueOf(Class<A> targetClass) {
if (this.value == null || targetClass.isInstance(this.value)) {
return (SerialValue<A>) this;
}
throw new RuntimeException("Required Value to contain " + targetClass.getName() + " value but condition failed on" +
" type " + this.value.getClass().getName());
}
@JsonIgnore
public <A> A getOf(Class<A> targetClass) {
return this.assertValueOf(targetClass).value;
}
}

View File

@@ -0,0 +1,29 @@
package de.dhbwstuttgart.server.packet.dataContainers.token;
import com.fasterxml.jackson.annotation.JsonProperty;
import de.dhbwstuttgart.parser.NullToken;
import de.dhbwstuttgart.server.packet.IPacket;
import de.dhbwstuttgart.server.packet.dataContainers.SerializedTokenWrapper;
import de.dhbwstuttgart.syntaxtree.type.ExtendsWildcardType;
/**
* Serializable container of
*
* @see ExtendsWildcardType
*/
public class SerializedExtendsWildcardType implements IPacket.IDataContainer<ExtendsWildcardType> {
@JsonProperty("e")
public SerializedTokenWrapper extendsType;
public static SerializedExtendsWildcardType create(ExtendsWildcardType extendsWildcardType) {
SerializedExtendsWildcardType type = new SerializedExtendsWildcardType();
type.extendsType = SerializedTokenWrapper.create(extendsWildcardType.getInnerType());
return type;
}
@Override
public ExtendsWildcardType toObject() {
return new ExtendsWildcardType(extendsType.toObject(), new NullToken());
}
}

View File

@@ -0,0 +1,28 @@
package de.dhbwstuttgart.server.packet.dataContainers.token;
import com.fasterxml.jackson.annotation.JsonProperty;
import de.dhbwstuttgart.parser.NullToken;
import de.dhbwstuttgart.server.packet.IPacket;
import de.dhbwstuttgart.syntaxtree.type.GenericRefType;
/**
* Serializable container of
*
* @see GenericRefType
*/
public class SerializedGenericRefType implements IPacket.IDataContainer<GenericRefType> {
@JsonProperty("n")
public String name;
public static SerializedGenericRefType create(GenericRefType genericRefType) {
SerializedGenericRefType serialized = new SerializedGenericRefType();
serialized.name = genericRefType.getParsedName();
return serialized;
}
@Override
public GenericRefType toObject() {
return new GenericRefType(name, new NullToken());
}
}

View File

@@ -0,0 +1,27 @@
package de.dhbwstuttgart.server.packet.dataContainers.token;
import com.fasterxml.jackson.annotation.JsonProperty;
import de.dhbwstuttgart.server.packet.IPacket;
import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder;
/**
* Serializable container of
*
* @see TypePlaceholder
*/
public class SerializedPlaceholderType implements IPacket.IDataContainer<TypePlaceholder> {
@JsonProperty("n")
public String name;
public static SerializedPlaceholderType create(TypePlaceholder typePlaceholder) {
SerializedPlaceholderType serialized = new SerializedPlaceholderType();
serialized.name = typePlaceholder.getName();
return serialized;
}
@Override
public TypePlaceholder toObject() {
return (TypePlaceholder) TypePlaceholder.of(name);
}
}

View File

@@ -0,0 +1,40 @@
package de.dhbwstuttgart.server.packet.dataContainers.token;
import com.fasterxml.jackson.annotation.JsonProperty;
import de.dhbwstuttgart.parser.NullToken;
import de.dhbwstuttgart.parser.scope.JavaClassName;
import de.dhbwstuttgart.server.packet.IPacket;
import de.dhbwstuttgart.server.packet.dataContainers.SerializedTokenWrapper;
import de.dhbwstuttgart.syntaxtree.type.RefType;
import java.util.Arrays;
/**
* Serializable container of
*
* @see RefType
*/
public class SerializedRefType implements IPacket.IDataContainer<RefType> {
@JsonProperty("n")
public String name;
@JsonProperty("p")
public SerializedTokenWrapper[] parameters;
public static SerializedRefType create(RefType refType) {
SerializedRefType serialized = new SerializedRefType();
serialized.name = refType.getName().toString();
serialized.parameters = refType.getParaList().stream().map(SerializedTokenWrapper::create).toArray(SerializedTokenWrapper[]::new);
return serialized;
}
@Override
public RefType toObject() {
return new RefType(
new JavaClassName(name),
Arrays.stream(parameters).map(SerializedTokenWrapper::toObject).toList(),
new NullToken()
);
}
}

View File

@@ -0,0 +1,30 @@
package de.dhbwstuttgart.server.packet.dataContainers.token;
import com.fasterxml.jackson.annotation.JsonProperty;
import de.dhbwstuttgart.parser.NullToken;
import de.dhbwstuttgart.server.packet.IPacket;
import de.dhbwstuttgart.server.packet.dataContainers.SerializedTokenWrapper;
import de.dhbwstuttgart.syntaxtree.type.SuperWildcardType;
/**
* Serializable container of
*
* @see SuperWildcardType
*/
public class SerializedSuperWildcardType implements IPacket.IDataContainer<SuperWildcardType> {
@JsonProperty("s")
public SerializedTokenWrapper superType;
public static SerializedSuperWildcardType create(SuperWildcardType superWildcardType) {
SerializedSuperWildcardType type = new SerializedSuperWildcardType();
type.superType = SerializedTokenWrapper.create(superWildcardType.getInnerType());
type.superType = SerializedTokenWrapper.create(superWildcardType.getInnerType());
return type;
}
@Override
public SuperWildcardType toObject() {
return new SuperWildcardType(superType.toObject(), new NullToken());
}
}

View File

@@ -0,0 +1,24 @@
package de.dhbwstuttgart.server.packet.dataContainers.token;
import de.dhbwstuttgart.parser.NullToken;
import de.dhbwstuttgart.server.packet.IPacket;
import de.dhbwstuttgart.syntaxtree.type.Void;
/**
* Serializable container of
*
* @see Void
*/
public class SerializedVoidType implements IPacket.IDataContainer<Void> {
public int i = 0;
public static SerializedVoidType create(Void voidType) {
return new SerializedVoidType();
}
@Override
public Void toObject() {
return new Void(new NullToken());
}
}

View File

@@ -0,0 +1,26 @@
package de.dhbwstuttgart.server.packet.dataContainers.unifyType;
import de.dhbwstuttgart.server.packet.IPacket;
import de.dhbwstuttgart.typeinference.unify.model.ExtendsType;
/**
* Serializable container of
*
* @see ExtendsType
*/
public class SerializedExtendsType extends SerializedWildcardType implements IPacket.IDataContainer<ExtendsType> {
public static SerializedExtendsType create(ExtendsType extendsType) {
SerializedExtendsType type = new SerializedExtendsType();
type.readWildcardTypeValues(extendsType);
return type;
}
@Override
public ExtendsType toObject() {
return new ExtendsType(
this.wildcardedType.toObject()
);
}
}

View File

@@ -0,0 +1,32 @@
package de.dhbwstuttgart.server.packet.dataContainers.unifyType;
import de.dhbwstuttgart.server.packet.IPacket;
import de.dhbwstuttgart.server.packet.dataContainers.SerializedUnifyTypeWrapper;
import de.dhbwstuttgart.typeinference.unify.model.FunNType;
import de.dhbwstuttgart.typeinference.unify.model.TypeParams;
import java.util.Arrays;
/**
* Serializable container of
*
* @see FunNType
*/
public class SerializedFunNType extends SerializedUnifyType implements IPacket.IDataContainer<FunNType> {
public static SerializedFunNType create(FunNType funN) {
SerializedFunNType type = new SerializedFunNType();
type.readUnifyTypeValues(funN);
return type;
}
@Override
public FunNType toObject() {
return FunNType.getFunNType(
new TypeParams(
Arrays.stream(this.params).map(SerializedUnifyTypeWrapper::toObject).toList()
)
);
}
}

View File

@@ -0,0 +1,38 @@
package de.dhbwstuttgart.server.packet.dataContainers.unifyType;
import de.dhbwstuttgart.server.packet.IPacket;
import de.dhbwstuttgart.typeinference.unify.model.PlaceholderType;
/**
* Serializable container of
*
* @see PlaceholderType
*/
public class SerializedPlaceholderType extends SerializedUnifyType implements IPacket.IDataContainer<PlaceholderType> {
public boolean isGenerated;
public boolean isInnerType;
public int variance;
public byte orCons;
public static SerializedPlaceholderType create(PlaceholderType placeholder) {
SerializedPlaceholderType type = new SerializedPlaceholderType();
type.readUnifyTypeValues(placeholder);
type.isGenerated = placeholder.isGenerated();
type.isInnerType = placeholder.isInnerType();
type.variance = placeholder.getVariance();
type.orCons = placeholder.getOrCons();
return type;
}
@Override
public PlaceholderType toObject() {
PlaceholderType placeholderType = new PlaceholderType(this.name, this.isGenerated);
placeholderType.setInnerType(this.isInnerType);
placeholderType.setVariance(this.variance);
placeholderType.setOrCons(this.orCons);
return placeholderType;
}
}

View File

@@ -0,0 +1,37 @@
package de.dhbwstuttgart.server.packet.dataContainers.unifyType;
import com.fasterxml.jackson.annotation.JsonProperty;
import de.dhbwstuttgart.server.packet.IPacket;
import de.dhbwstuttgart.server.packet.dataContainers.SerializedUnifyTypeWrapper;
import de.dhbwstuttgart.typeinference.unify.model.ReferenceType;
import de.dhbwstuttgart.typeinference.unify.model.TypeParams;
import java.util.Arrays;
/**
* Serializable container of
*
* @see ReferenceType
*/
public class SerializedReferenceType extends SerializedUnifyType implements IPacket.IDataContainer<ReferenceType> {
@JsonProperty("gt")
public boolean genericTypeVar;
public static SerializedReferenceType create(ReferenceType referenceType) {
SerializedReferenceType type = new SerializedReferenceType();
type.readUnifyTypeValues(referenceType);
type.genericTypeVar = referenceType.isGenTypeVar();
return type;
}
@Override
public ReferenceType toObject() {
ReferenceType referenceType = new ReferenceType(this.name, this.genericTypeVar);
return (ReferenceType) referenceType.setTypeParams(
new TypeParams(
Arrays.stream(this.params).map(SerializedUnifyTypeWrapper::toObject).toList()
)
);
}
}

View File

@@ -0,0 +1,26 @@
package de.dhbwstuttgart.server.packet.dataContainers.unifyType;
import de.dhbwstuttgart.server.packet.IPacket;
import de.dhbwstuttgart.typeinference.unify.model.SuperType;
/**
* Serializable container of
*
* @see SuperType
*/
public class SerializedSuperType extends SerializedWildcardType implements IPacket.IDataContainer<SuperType> {
public static SerializedSuperType create(SuperType superType) {
SerializedSuperType type = new SerializedSuperType();
type.readWildcardTypeValues(superType);
return type;
}
@Override
public SuperType toObject() {
return new SuperType(
this.wildcardedType.toObject()
);
}
}

View File

@@ -0,0 +1,24 @@
package de.dhbwstuttgart.server.packet.dataContainers.unifyType;
import com.fasterxml.jackson.annotation.JsonProperty;
import de.dhbwstuttgart.server.packet.dataContainers.SerializedUnifyTypeWrapper;
import de.dhbwstuttgart.typeinference.unify.model.UnifyType;
import java.util.Arrays;
/**
* Serializable abstract container of
*
* @see UnifyType
*/
abstract class SerializedUnifyType {
@JsonProperty("n")
public String name;
@JsonProperty("p")
public SerializedUnifyTypeWrapper[] params = new SerializedUnifyTypeWrapper[]{};
public void readUnifyTypeValues(UnifyType unifyType) {
name = unifyType.getName();
params = Arrays.stream(unifyType.getTypeParams().get()).map(SerializedUnifyTypeWrapper::create).toArray(SerializedUnifyTypeWrapper[]::new);
}
}

View File

@@ -0,0 +1,20 @@
package de.dhbwstuttgart.server.packet.dataContainers.unifyType;
import de.dhbwstuttgart.server.packet.dataContainers.SerializedUnifyTypeWrapper;
import de.dhbwstuttgart.typeinference.unify.model.WildcardType;
/**
* Serializable abstract container of
*
* @see WildcardType
*/
abstract class SerializedWildcardType extends SerializedUnifyType {
public SerializedUnifyTypeWrapper wildcardedType;
public void readWildcardTypeValues(WildcardType wildcardType) {
this.readUnifyTypeValues(wildcardType);
wildcardedType = SerializedUnifyTypeWrapper.create(wildcardType.getWildcardedType());
}
}

View File

@@ -349,4 +349,4 @@ public abstract class AbstractASTWalker implements ASTVisitor {
ternary.iftrue.accept(this);
ternary.iffalse.accept(this);
}
}
}

View File

@@ -4,7 +4,6 @@ import de.dhbwstuttgart.parser.NullToken;
import de.dhbwstuttgart.syntaxtree.statement.Statement;
import de.dhbwstuttgart.syntaxtree.statement.Super;
import de.dhbwstuttgart.syntaxtree.statement.SuperCall;
import de.dhbwstuttgart.syntaxtree.type.RefType;
import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric;
import de.dhbwstuttgart.syntaxtree.type.Void;
import org.antlr.v4.runtime.Token;

View File

@@ -1,9 +1,8 @@
package de.dhbwstuttgart.syntaxtree;
import de.dhbwstuttgart.syntaxtree.statement.Expression;
import org.antlr.v4.runtime.Token;
import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric;
import org.antlr.v4.runtime.Token;
/**
* Eine Feldinitialisation steht für eine Felddeklaration mit gleichzeitiger Wertzuweisung
@@ -25,4 +24,4 @@ public class FieldDeclaration extends Field{
}
}
}

View File

@@ -1,12 +1,12 @@
package de.dhbwstuttgart.syntaxtree;
import com.google.common.collect.Lists;
import org.antlr.v4.runtime.Token;
import com.google.common.collect.Lists;
import de.dhbwstuttgart.parser.NullToken;
import java.util.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
/**

View File

@@ -1,7 +1,6 @@
package de.dhbwstuttgart.syntaxtree;
import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric;
import org.antlr.v4.runtime.Token;
import java.util.ArrayList;

View File

@@ -3,17 +3,14 @@ package de.dhbwstuttgart.syntaxtree;
import java.util.ArrayList;
import java.util.Objects;
import de.dhbwstuttgart.core.IItemWithOffset;
import de.dhbwstuttgart.parser.NullToken;
import de.dhbwstuttgart.syntaxtree.statement.Block;
import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric;
import de.dhbwstuttgart.typeinference.assumptions.TypeInferenceBlockInformation;
import de.dhbwstuttgart.typeinference.constraints.ConstraintSet;
import de.dhbwstuttgart.typeinference.assumptions.TypeInferenceInformation;
import de.dhbwstuttgart.typeinference.typeAlgo.TYPE;
import de.dhbwstuttgart.typeinference.typeAlgo.TYPEStmt;
import org.antlr.v4.runtime.Token;
import de.dhbwstuttgart.core.IItemWithOffset;
import de.dhbwstuttgart.syntaxtree.statement.Block;
import java.util.ArrayList;
/**
* Stellt eine Methode dar. Problem: Parser kann nicht zwischen Methode und
@@ -34,7 +31,7 @@ public class Method extends SyntaxTreeNode implements IItemWithOffset, TypeScope
private final RefTypeOrTPHOrWildcardOrGeneric returnType;
public final Boolean isInherited;
public final Boolean isImplemented;
/*
* its Constraints
* eingefuegt PL 2021-02-15
@@ -110,10 +107,10 @@ public class Method extends SyntaxTreeNode implements IItemWithOffset, TypeScope
public int hashCode() {
return Objects.hash(name, parameterlist, returnType);
}
@Override
public String toString() {
return name;
}
}

View File

@@ -5,8 +5,11 @@ import java.util.*;
import de.dhbwstuttgart.parser.NullToken;
import de.dhbwstuttgart.parser.scope.JavaClassName;
import de.dhbwstuttgart.typeinference.constraints.ConstraintSet;
import de.dhbwstuttgart.typeinference.assumptions.TypeInferenceInformation;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
//import sun.security.x509.X509CertInfo;
public class SourceFile extends SyntaxTreeNode {

View File

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

View File

@@ -1,10 +1,6 @@
package de.dhbwstuttgart.syntaxtree;
import java.util.ArrayList;
import java.util.List;
import de.dhbwstuttgart.core.IItemWithOffset;
import de.dhbwstuttgart.typeinference.assumptions.TypeInferenceInformation;
import org.antlr.v4.runtime.Token;
//import org.antlr.v4.runtime.misc.Pair;
@@ -20,4 +16,4 @@ public abstract class SyntaxTreeNode implements IItemWithOffset{
}
public abstract void accept(ASTVisitor visitor);
}
}

View File

@@ -2,11 +2,9 @@ package de.dhbwstuttgart.syntaxtree;
import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric;
import java.util.Collection;
public interface TypeScope {
Iterable<? extends GenericTypeVar> getGenerics();
RefTypeOrTPHOrWildcardOrGeneric getReturnType();
}
}

View File

@@ -26,6 +26,10 @@ import org.objectweb.asm.*;
import org.objectweb.asm.signature.SignatureReader;
import org.objectweb.asm.signature.SignatureVisitor;
import java.lang.reflect.Constructor;
import java.lang.reflect.*;
import java.util.*;
/**
* Anmerkung: Die ASTFactory Methoden, welche ASTBäume aus java.lang.Class Objekten generieren, können davon ausgehen, dass alle Imports und Typnamen korrekt sind und müssen diese nicht überprüfen.
*/
@@ -111,9 +115,9 @@ public class ASTFactory {
else {
Boolean isImplemented = false;
isImplemented = Arrays.stream(jreClass.getInterfaces()).
reduce(false,
reduce(false,
(x,y) -> {
try {
try {
y.getDeclaredMethod(method.getName(), method.getParameterTypes());
return true;
}
@@ -122,24 +126,24 @@ public class ASTFactory {
}},
(x,y) -> (x || y)
);
if (isImplemented) {
methoden.add(createMethod(method, signature, jreClass, false, true));
}
else {
if (Modifier.isAbstract(jreClass.getSuperclass().getModifiers())) {
if (Modifier.isAbstract(jreClass.getSuperclass().getModifiers())) {
try {
jreClass.getSuperclass().getDeclaredMethod(method.getName(), method.getParameterTypes());
methoden.add(createMethod(method, signature, jreClass, false, true));
}
catch (java.lang.NoSuchMethodException e) {
methoden.add(createMethod(method, signature, jreClass, false, false));
catch (java.lang.NoSuchMethodException e) {
methoden.add(createMethod(method, signature, jreClass, false, false));
}
}
else {
methoden.add(createMethod(method, signature, jreClass, false, false));
}
}
}}
for (java.lang.reflect.Method method : allInheritedMethods) {
@@ -153,11 +157,11 @@ public class ASTFactory {
int modifier = jreClass.getModifiers();
boolean isInterface = jreClass.isInterface();
List<Annotation> aLA;
boolean isFunctionalInterface =
(aLA = Arrays.asList(jreClass.getAnnotations())).size() > 0 &&
aLA.get(0) instanceof FunctionalInterface ?
true :
false;
boolean isFunctionalInterface =
(aLA = Arrays.asList(jreClass.getAnnotations())).size() > 0 &&
aLA.get(0) instanceof FunctionalInterface ?
true :
false;
// see: https://stackoverflow.com/questions/9934774/getting-generic-parameter-from-supertype-class
ParameterizedType parameterSuperClass = null;
Type tempSuperClass = jreClass.getGenericSuperclass();
@@ -464,25 +468,25 @@ public class ASTFactory {
/*
* public Constructor createEmptyConstructor(Class parent){ Block block = new Block(); block.setType(new de.dhbwstuttgart.syntaxtree.type.Void(block, 0)); block.statements.add(new SuperCall(block));
*
*
* return ASTFactory.createConstructor(parent, new ParameterList(), block); }
*
*
* public static Constructor createConstructor(Class superClass, ParameterList paralist, Block block){ block.parserPostProcessing(superClass);
*
*
* Method method = ASTFactory.createMethod("<init>", paralist, block, superClass); method.setType(new de.dhbwstuttgart.syntaxtree.type.Void(block, 0));
*
*
* return new Constructor(method, superClass); }
*
*
* public static Class createClass(String className, RefType type, Modifiers modifiers, Menge supertypeGenPara, SourceFile parent) { // TODO bytecode createClass //String name, RefType superClass, Modifiers modifiers, Menge<String> supertypeGenPara Class generatedClass = new Class(className, type, modifiers, supertypeGenPara); generatedClass.addField(ASTFactory.createEmptyConstructor(generatedClass));
*
*
* generatedClass.parserPostProcessing(parent);
*
*
* return generatedClass; }
*
*
* public static Class createObject(){ return createClass(java.lang.Object.class); }
*
*
* public static Class createInterface(String className, RefType superClass, Modifiers modifiers, Menge supertypeGenPara, SourceFile parent){ Class generatedClass = new Class(new JavaClassName(className), new ArrayList<Method>(), new ArrayList<Field>(), modifiers, true, superClass, new ArrayList<RefType>(), new GenericDeclarationList(), -1); generatedClass.parserPostProcessing(parent); return generatedClass; }
*
*
* public static RefType createObjectType(){ return createObjectClass().getType(); }
*/
}
}

View File

@@ -1,8 +1,5 @@
package de.dhbwstuttgart.syntaxtree.factory;
import de.dhbwstuttgart.core.JavaTXCompiler;
import de.dhbwstuttgart.core.JavaTXServer;
public class NameGenerator {
private static String strNextName = "A";
@@ -29,11 +26,7 @@ public class NameGenerator {
// n�chster Name berechnen und in strNextName speichern
inc( strNextName.length() - 1 );
if (JavaTXServer.isRunning) {
throw new RuntimeException("Using the NameGenerator on a server is not allowed");
}
JavaTXCompiler.defaultClientPlaceholderRegistry.addPlaceholder(strReturn);
return strReturn;
}

View File

@@ -1,8 +1,5 @@
package de.dhbwstuttgart.syntaxtree.factory;
import de.dhbwstuttgart.syntaxtree.SyntaxTree;
import de.dhbwstuttgart.typeinference.unify.PlaceholderRegistry;
import de.dhbwstuttgart.util.Logger;
import java.io.Writer;
import java.lang.reflect.Modifier;
import java.util.*;
@@ -24,23 +21,25 @@ import de.dhbwstuttgart.syntaxtree.type.Void;
import de.dhbwstuttgart.syntaxtree.type.WildcardType;
import de.dhbwstuttgart.typeinference.constraints.ConstraintSet;
import de.dhbwstuttgart.typeinference.constraints.Pair;
import de.dhbwstuttgart.typeinference.result.PairNoResult;
import de.dhbwstuttgart.typeinference.result.PairTPHEqualTPH;
import de.dhbwstuttgart.typeinference.result.PairTPHequalRefTypeOrWildcardType;
import de.dhbwstuttgart.typeinference.result.PairTPHsmallerTPH;
import de.dhbwstuttgart.typeinference.result.ResultPair;
import de.dhbwstuttgart.typeinference.result.*;
import de.dhbwstuttgart.typeinference.unify.model.*;
import de.dhbwstuttgart.util.Logger;
import org.antlr.v4.runtime.Token;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
public class UnifyTypeFactory {
public static FiniteClosure generateFC(
List<ClassOrInterface> fromClasses,
Logger logger,
ClassLoader classLoader,
JavaTXCompiler compiler,
PlaceholderRegistry placeholderRegistry
) throws ClassNotFoundException {
private static ArrayList<PlaceholderType> PLACEHOLDERS = new ArrayList<>();
public static FiniteClosure generateFC(List<ClassOrInterface> fromClasses, Logger logger, ClassLoader classLoader, JavaTXCompiler compiler) throws ClassNotFoundException {
/*
Die transitive Hülle muss funktionieren.
Man darf schreiben List<A> extends AL<A>
@@ -51,7 +50,7 @@ public class UnifyTypeFactory {
Generell dürfen sie immer die gleichen Namen haben.
TODO: die transitive Hülle bilden
*/
return new FiniteClosure(FCGenerator.toUnifyFC(compiler, fromClasses, classLoader, placeholderRegistry), logger, compiler, placeholderRegistry);
return new FiniteClosure(FCGenerator.toUnifyFC(compiler, fromClasses, classLoader), logger, compiler);
}
public static UnifyPair generateSmallerPair(UnifyType tl, UnifyType tr, SourceLoc location){
@@ -74,23 +73,23 @@ public class UnifyTypeFactory {
* Convert from
* ASTType -> UnifyType
*/
public static UnifyType convert(JavaTXCompiler compiler, RefTypeOrTPHOrWildcardOrGeneric t, Boolean innerType, PlaceholderRegistry placeholderRegistry){
public static UnifyType convert(JavaTXCompiler compiler, RefTypeOrTPHOrWildcardOrGeneric t, Boolean innerType){
if (t instanceof GenericRefType){
return UnifyTypeFactory.convert(compiler, (GenericRefType)t, innerType, placeholderRegistry);
return UnifyTypeFactory.convert(compiler, (GenericRefType)t, innerType);
} else if (t instanceof TypePlaceholder){
return UnifyTypeFactory.convert(compiler, (TypePlaceholder)t, innerType, placeholderRegistry);
return UnifyTypeFactory.convert(compiler, (TypePlaceholder)t, innerType);
} else if (t instanceof ExtendsWildcardType){
return UnifyTypeFactory.convert(compiler, (ExtendsWildcardType)t, innerType, placeholderRegistry);
return UnifyTypeFactory.convert(compiler, (ExtendsWildcardType)t, innerType);
} else if (t instanceof SuperWildcardType) {
return UnifyTypeFactory.convert(compiler, (SuperWildcardType) t, innerType, placeholderRegistry);
return UnifyTypeFactory.convert(compiler, (SuperWildcardType) t, innerType);
} else if (t instanceof RefType){
return UnifyTypeFactory.convert(compiler, (RefType)t, innerType, placeholderRegistry);
return UnifyTypeFactory.convert(compiler, (RefType)t, innerType);
}
//Es wurde versucht ein Typ umzuwandeln, welcher noch nicht von der Factory abgedeckt ist
throw new NotImplementedException("Der Typ "+t+" kann nicht umgewandelt werden");
}
public static UnifyType convert(JavaTXCompiler compiler, RefType t, Boolean innerType, PlaceholderRegistry placeholderRegistry){
public static UnifyType convert(JavaTXCompiler compiler, RefType t, Boolean innerType){
//Check if it is a FunN Type:
Pattern p = Pattern.compile("Fun(\\d+)[$][$]");
Matcher m = p.matcher(t.getName().toString());
@@ -98,76 +97,76 @@ public class UnifyTypeFactory {
if(b){
Integer N = Integer.valueOf(m.group(1));
if((N + 1) == t.getParaList().size()){
return convertFunN(compiler, t.getParaList(), false, placeholderRegistry);
return convertFunN(compiler, t.getParaList(), false);
}
}
UnifyType ret;
List<UnifyType> params = new ArrayList<>();
if (t.getParaList() != null) {
for (RefTypeOrTPHOrWildcardOrGeneric pT : t.getParaList()) {
params.add(UnifyTypeFactory.convert(compiler, pT, true, placeholderRegistry));
params.add(UnifyTypeFactory.convert(compiler, pT, true));
}
}
var clazz = compiler.getClass(t.getName());
if (clazz != null && clazz.isInterface() && clazz.isFunctionalInterface()) {
var method = clazz.getMethods().stream().filter(x -> Modifier.isAbstract(x.modifier)).findFirst().orElseThrow();
var methodParams = method.getParameterList().getFormalparalist().stream().map(x -> convert(compiler, x.getType(), true, placeholderRegistry)).toList();
var methodParams = method.getParameterList().getFormalparalist().stream().map(x -> convert(compiler, x.getType(), true)).toList();
var generics = StreamSupport.stream(clazz.getGenerics().spliterator(), false).map(GenericTypeVar::getName).toList();
return new FunInterfaceType(t.getName().toString(), new TypeParams(params), methodParams, convert(compiler, method.getReturnType(), true, placeholderRegistry), generics);
return new FunInterfaceType(t.getName().toString(), new TypeParams(params), methodParams, convert(compiler, method.getReturnType(), true), generics);
}
return new ReferenceType(t.getName().toString(),new TypeParams(params));
}
public static UnifyType convertFunN(JavaTXCompiler compiler, List<RefTypeOrTPHOrWildcardOrGeneric> paraList, Boolean innerType, PlaceholderRegistry placeholderRegistry){
public static UnifyType convertFunN(JavaTXCompiler compiler, List<RefTypeOrTPHOrWildcardOrGeneric> paraList, Boolean innerType){
UnifyType ret;
List<UnifyType> params = new ArrayList<>();
if(paraList != null && paraList.size() > 0){
for(RefTypeOrTPHOrWildcardOrGeneric pT : paraList){
params.add(UnifyTypeFactory.convert(compiler, pT, false, placeholderRegistry));
params.add(UnifyTypeFactory.convert(compiler, pT, false));
}
}
ret = FunNType.getFunNType(new TypeParams(params));
return ret;
}
public static UnifyType convert(JavaTXCompiler compiler, TypePlaceholder tph, Boolean innerType, PlaceholderRegistry placeholderRegistry) {
public static UnifyType convert(JavaTXCompiler compiler, TypePlaceholder tph, Boolean innerType){
if (tph.getName().equals("AFR")) {
SyntaxTree.logger.info("XXX"+innerType);
System.out.println("XXX"+innerType);
}
PlaceholderType ntph = new PlaceholderType(tph.getName(), tph.getVariance(), placeholderRegistry);
PlaceholderType ntph = new PlaceholderType(tph.getName(), tph.getVariance());
ntph.setVariance(tph.getVariance());
ntph.setOrCons(tph.getOrCons());
ntph.setWildcardtable(tph.getWildcardtable());
int in = placeholderRegistry.UnifyTypeFactory_PLACEHOLDERS.indexOf(ntph);
int in = PLACEHOLDERS.indexOf(ntph);
if (in == -1) {
placeholderRegistry.UnifyTypeFactory_PLACEHOLDERS.add(ntph);
PLACEHOLDERS.add(ntph);
ntph.setInnerType(innerType);
return ntph;
}
else {
PlaceholderType oldpht = placeholderRegistry.UnifyTypeFactory_PLACEHOLDERS.get(in);
PlaceholderType oldpht = PLACEHOLDERS.get(in);
oldpht.setInnerType(oldpht.isInnerType() || innerType);
return oldpht;
}
}
public static UnifyType convert(JavaTXCompiler compiler, GenericRefType t, Boolean innerType, PlaceholderRegistry placeholderRegistry){
public static UnifyType convert(JavaTXCompiler compiler, GenericRefType t, Boolean innerType){
return new ReferenceType(t.getParsedName(), true);
}
public static UnifyType convert(JavaTXCompiler compiler, WildcardType t, Boolean innerType, PlaceholderRegistry placeholderRegistry){
public static UnifyType convert(JavaTXCompiler compiler, WildcardType t, Boolean innerType){
if(t.isExtends())
return new ExtendsType(UnifyTypeFactory.convert(compiler, t.getInnerType(), false, placeholderRegistry));
return new ExtendsType(UnifyTypeFactory.convert(compiler, t.getInnerType(), false));
else if(t.isSuper())
return new SuperType(UnifyTypeFactory.convert(compiler, t.getInnerType(), false, placeholderRegistry));
return new SuperType(UnifyTypeFactory.convert(compiler, t.getInnerType(), false));
else throw new NotImplementedException();
}
public static ConstraintSet<UnifyPair> convert(JavaTXCompiler compiler, ConstraintSet<Pair> constraints, PlaceholderRegistry placeholderRegistry) {
return constraints.map(c -> UnifyTypeFactory.convert(compiler, c, placeholderRegistry));
public static ConstraintSet<UnifyPair> convert(JavaTXCompiler compiler, ConstraintSet<Pair> constraints) {
return constraints.map(c -> UnifyTypeFactory.convert(compiler, c));
}
//NEVER USED
@@ -178,30 +177,30 @@ public class UnifyTypeFactory {
// return unifyPairConstraint;
//}
public static UnifyPair convert(JavaTXCompiler compiler, Pair p, PlaceholderRegistry placeholderRegistry) {
public static UnifyPair convert(JavaTXCompiler compiler, Pair p) {
UnifyPair ret = null;
if(p.GetOperator().equals(PairOperator.SMALLERDOT)) {
ret = generateSmallerDotPair(UnifyTypeFactory.convert(compiler, p.TA1, false, placeholderRegistry)
, UnifyTypeFactory.convert(compiler, p.TA2, false, placeholderRegistry), p.getLocation());
ret = generateSmallerDotPair(UnifyTypeFactory.convert(compiler, p.TA1, false)
, UnifyTypeFactory.convert(compiler, p.TA2, false), p.getLocation());
//return ret;
}else if(p.GetOperator().equals(PairOperator.SMALLERNEQDOT)) {
ret = generateSmallNotEqualDotPair(UnifyTypeFactory.convert(compiler, p.TA1, false, placeholderRegistry)
, UnifyTypeFactory.convert(compiler, p.TA2, false, placeholderRegistry), p.getLocation());
ret = generateSmallNotEqualDotPair(UnifyTypeFactory.convert(compiler, p.TA1, false)
, UnifyTypeFactory.convert(compiler, p.TA2, false), p.getLocation());
//return ret;
}else if(p.GetOperator().equals(PairOperator.EQUALSDOT)) {
ret = generateEqualDotPair(UnifyTypeFactory.convert(compiler, p.TA1, false, placeholderRegistry)
, UnifyTypeFactory.convert(compiler, p.TA2, false, placeholderRegistry), p.getLocation());
ret = generateEqualDotPair(UnifyTypeFactory.convert(compiler, p.TA1, false)
, UnifyTypeFactory.convert(compiler, p.TA2, false), p.getLocation());
//return ret;
}else if(p.GetOperator().equals(PairOperator.SMALLER)){
ret = generateSmallerPair(UnifyTypeFactory.convert(compiler, p.TA1, false, placeholderRegistry),
UnifyTypeFactory.convert(compiler, p.TA2, false, placeholderRegistry), p.getLocation());
ret = generateSmallerPair(UnifyTypeFactory.convert(compiler, p.TA1, false),
UnifyTypeFactory.convert(compiler, p.TA2, false), p.getLocation());
}else throw new NotImplementedException();
UnifyType lhs, rhs;
if (((lhs = ret.getLhsType()) instanceof PlaceholderType)
&& ((PlaceholderType)lhs).isWildcardable()
&& (rhs = ret.getLhsType()) instanceof PlaceholderType) {
if (lhs.getName().equals("AQ")) {
// SyntaxTree.logger.info("");
System.out.println("");
}
((PlaceholderType)rhs).enableWildcardtable();
}
@@ -210,7 +209,7 @@ public class UnifyTypeFactory {
&& ((PlaceholderType)rhs).isWildcardable()
&& (lhs = ret.getLhsType()) instanceof PlaceholderType) {
if (rhs.getName().equals("AQ")) {
// SyntaxTree.logger.info("");
System.out.println("");
}
((PlaceholderType)lhs).enableWildcardtable();
}
@@ -221,16 +220,16 @@ public class UnifyTypeFactory {
* Convert from
* UnifyType -> ASTType
*/
public static Set<ResultPair> convert(Set<UnifyPair> unifyPairSet, Map<String,TypePlaceholder> tphs, PlaceholderRegistry placeholderRegistry) {
public static Set<ResultPair> convert(Set<UnifyPair> unifyPairSet, Map<String,TypePlaceholder> tphs) {
return unifyPairSet.stream().map(
unifyPair -> convert(unifyPair, tphs, placeholderRegistry))
unifyPair -> convert(unifyPair, tphs))
.collect(Collectors.toSet());
}
public static ResultPair convert(UnifyPair mp, Map<String,TypePlaceholder> tphs, PlaceholderRegistry placeholderRegistry) {
public static ResultPair convert(UnifyPair mp, Map<String,TypePlaceholder> tphs) {
if (mp == null) { return null;} //kann bei basePairs passieren
RefTypeOrTPHOrWildcardOrGeneric tl = UnifyTypeFactory.convert(mp.getLhsType(), tphs, placeholderRegistry);
RefTypeOrTPHOrWildcardOrGeneric tr = UnifyTypeFactory.convert(mp.getRhsType(), tphs, placeholderRegistry);
RefTypeOrTPHOrWildcardOrGeneric tl = UnifyTypeFactory.convert(mp.getLhsType(), tphs);
RefTypeOrTPHOrWildcardOrGeneric tr = UnifyTypeFactory.convert(mp.getRhsType(), tphs);
if(tl instanceof TypePlaceholder){
if(tr instanceof TypePlaceholder) {
@@ -239,7 +238,7 @@ public class UnifyTypeFactory {
//Einfach ignorieren TODO: Das hier muss ausgebessert werden:
//return new PairTPHequalRefTypeOrWildcardType((TypePlaceholder)tl, ASTFactory.createObjectType());
}else{
return new PairTPHsmallerTPH((TypePlaceholder)tl, (TypePlaceholder)tr, convert(mp.getBasePair(), tphs, placeholderRegistry));
return new PairTPHsmallerTPH((TypePlaceholder)tl, (TypePlaceholder)tr, convert(mp.getBasePair(), tphs));
}
}else if(tr instanceof RefType){
return new PairTPHequalRefTypeOrWildcardType((TypePlaceholder)tl, (RefType) tr);
@@ -251,51 +250,51 @@ public class UnifyTypeFactory {
}else return new PairNoResult(tl, tr);//throw new NotImplementedException();
}
public static RefTypeOrTPHOrWildcardOrGeneric convert(ReferenceType t, Map<String,TypePlaceholder> tphs, PlaceholderRegistry placeholderRegistry) {
public static RefTypeOrTPHOrWildcardOrGeneric convert(ReferenceType t, Map<String,TypePlaceholder> tphs) {
if(JavaClassName.Void.equals(t.getName()))return new Void(new NullToken());
if (t.isGenTypeVar()) return new GenericRefType(t.getName(),new NullToken());
RefType ret = new RefType(new JavaClassName(t.getName()),convert(t.getTypeParams(), tphs, placeholderRegistry),new NullToken());
RefType ret = new RefType(new JavaClassName(t.getName()),convert(t.getTypeParams(), tphs),new NullToken());
return ret;
}
public static RefTypeOrTPHOrWildcardOrGeneric convert(FunNType t, Map<String,TypePlaceholder> tphs, PlaceholderRegistry placeholderRegistry) {
RefType ret = new RefType(new JavaClassName(t.getName()), convert(t.getTypeParams(), tphs, placeholderRegistry), new NullToken());
public static RefTypeOrTPHOrWildcardOrGeneric convert(FunNType t, Map<String,TypePlaceholder> tphs) {
RefType ret = new RefType(new JavaClassName(t.getName()), convert(t.getTypeParams(), tphs), new NullToken());
return ret;
}
public static RefTypeOrTPHOrWildcardOrGeneric convert(SuperType t, Map<String,TypePlaceholder> tphs, PlaceholderRegistry placeholderRegistry) {
RefTypeOrTPHOrWildcardOrGeneric innerType = convert(t.getSuperedType(), tphs, placeholderRegistry);
public static RefTypeOrTPHOrWildcardOrGeneric convert(SuperType t, Map<String,TypePlaceholder> tphs) {
RefTypeOrTPHOrWildcardOrGeneric innerType = convert(t.getSuperedType(), tphs);
return new SuperWildcardType(innerType, new NullToken());
}
public static RefTypeOrTPHOrWildcardOrGeneric convert(ExtendsType t, Map<String,TypePlaceholder> tphs, PlaceholderRegistry placeholderRegistry) {
RefTypeOrTPHOrWildcardOrGeneric innerType = convert(t.getExtendedType(), tphs, placeholderRegistry);
public static RefTypeOrTPHOrWildcardOrGeneric convert(ExtendsType t, Map<String,TypePlaceholder> tphs) {
RefTypeOrTPHOrWildcardOrGeneric innerType = convert(t.getExtendedType(), tphs);
return new ExtendsWildcardType(innerType, new NullToken());
}
public static RefTypeOrTPHOrWildcardOrGeneric convert(PlaceholderType t, Map<String,TypePlaceholder> tphs, PlaceholderRegistry placeholderRegistry) {
public static RefTypeOrTPHOrWildcardOrGeneric convert(PlaceholderType t, Map<String,TypePlaceholder> tphs) {
TypePlaceholder ret = tphs.get(t.getName());
if(ret == null){ //Dieser TPH wurde vom Unifikationsalgorithmus erstellt
ret = TypePlaceholder.fresh(new NullToken(), placeholderRegistry);
ret = TypePlaceholder.fresh(new NullToken());
tphs.put(t.getName(), ret);
}
ret.setVariance(t.getVariance());
return ret;
}
public static RefTypeOrTPHOrWildcardOrGeneric convert(UnifyType t, Map<String,TypePlaceholder> tphs, PlaceholderRegistry placeholderRegistry) {
if(t instanceof FunNType)return convert((FunNType) t, tphs, placeholderRegistry);
if(t instanceof ReferenceType)return convert((ReferenceType) t, tphs, placeholderRegistry);
if(t instanceof SuperType)return convert((SuperType) t, tphs, placeholderRegistry);
if(t instanceof ExtendsType)return convert((ExtendsType) t, tphs, placeholderRegistry);
if(t instanceof PlaceholderType)return convert((PlaceholderType) t, tphs, placeholderRegistry);
public static RefTypeOrTPHOrWildcardOrGeneric convert(UnifyType t, Map<String,TypePlaceholder> tphs) {
if(t instanceof FunNType)return convert((FunNType) t, tphs);
if(t instanceof ReferenceType)return convert((ReferenceType) t, tphs);
if(t instanceof SuperType)return convert((SuperType) t, tphs);
if(t instanceof ExtendsType)return convert((ExtendsType) t, tphs);
if(t instanceof PlaceholderType)return convert((PlaceholderType) t, tphs);
throw new NotImplementedException("Der Typ "+t+" kann nicht umgewandelt werden");
}
private static List<RefTypeOrTPHOrWildcardOrGeneric> convert(TypeParams typeParams, Map<String,TypePlaceholder> tphs, PlaceholderRegistry placeholderRegistry) {
private static List<RefTypeOrTPHOrWildcardOrGeneric> convert(TypeParams typeParams, Map<String,TypePlaceholder> tphs) {
List<RefTypeOrTPHOrWildcardOrGeneric> ret = new ArrayList<>();
for(UnifyType uT : typeParams){
RefTypeOrTPHOrWildcardOrGeneric toAdd = convert(uT, tphs, placeholderRegistry);
RefTypeOrTPHOrWildcardOrGeneric toAdd = convert(uT, tphs);
ret.add(toAdd);
}
return ret;

View File

@@ -2,9 +2,6 @@
package de.dhbwstuttgart.syntaxtree.statement;
import de.dhbwstuttgart.syntaxtree.StatementVisitor;
import de.dhbwstuttgart.typeinference.assumptions.TypeInferenceBlockInformation;
import de.dhbwstuttgart.typeinference.constraints.ConstraintSet;
import de.dhbwstuttgart.typeinference.unify.model.PairOperator;
import org.antlr.v4.runtime.Token;
/*
@@ -25,4 +22,4 @@ public class Assign extends Statement {
public void accept(StatementVisitor visitor) {
visitor.visit(this);
}
}
}

View File

@@ -1,6 +1,5 @@
package de.dhbwstuttgart.syntaxtree.statement;
import de.dhbwstuttgart.syntaxtree.StatementVisitor;
import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric;
import org.antlr.v4.runtime.Token;
@@ -9,4 +8,4 @@ public abstract class AssignLeftSide extends TypableStatement{
public AssignLeftSide(RefTypeOrTPHOrWildcardOrGeneric type, Token offset) {
super(type, offset);
}
}
}

View File

@@ -1,10 +1,7 @@
package de.dhbwstuttgart.syntaxtree.statement;
import de.dhbwstuttgart.exceptions.NotImplementedException;
import de.dhbwstuttgart.syntaxtree.StatementVisitor;
import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric;
import de.dhbwstuttgart.typeinference.assumptions.TypeInferenceBlockInformation;
import de.dhbwstuttgart.typeinference.constraints.ConstraintSet;
import org.antlr.v4.runtime.Token;
@@ -22,4 +19,4 @@ public class CastExpr extends Expression
public void accept(StatementVisitor visitor) {
visitor.visit(this);
}
}
}

View File

@@ -1,7 +1,6 @@
package de.dhbwstuttgart.syntaxtree.statement;
import de.dhbwstuttgart.syntaxtree.StatementVisitor;
import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder;
import org.antlr.v4.runtime.Token;
public class DoStmt extends WhileStmt
@@ -15,4 +14,4 @@ public class DoStmt extends WhileStmt
public void accept(StatementVisitor visitor) {
visitor.visit(this);
}
}
}

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