Compare commits

..

16 Commits

Author SHA1 Message Date
Fabian Holzwarth
a0c11b60e8 Remove unnecessary parameter and fix some parallelization 2025-06-07 16:11:34 +02:00
Fabian Holzwarth
4cddf73e6d feat: small fixes for correct parameters 2025-06-07 14:38:18 +02:00
Fabian Holzwarth
5024a02447 feat: implement unify context and prepare variance code capsulation 2025-06-07 11:53:32 +02:00
Fabian Holzwarth
6c2d97b770 chore: code cleanup 2025-05-26 15:49:01 +02:00
Fabian Holzwarth
426c2916d3 feat: remove unnecessary synchronized blocks 2025-05-26 14:40:17 +02:00
Fabian Holzwarth
f722a00fbb feat: use the current thread for computation as well 2025-05-25 15:55:07 +02:00
Fabian Holzwarth
32797c9b9f feat: cleanup more cartesian product code 2025-05-24 12:43:42 +02:00
Fabian Holzwarth
87f655c85a feat: isolate constraint-filtering for one tv from computeCartesianRecursive 2025-05-23 16:10:37 +02:00
Fabian Holzwarth
613dceae1d feat: added Logger class, remove empty println start cleanup of computeCartesianRecursive 2025-05-23 14:12:25 +02:00
Fabian Holzwarth
81cac06e16 feat: add tool for merging many hash sets in parallel 2025-05-23 14:11:52 +02:00
Fabian Holzwarth
a47d5bc024 feat: slightly improved placeholder name generation 2025-05-23 14:04:48 +02:00
Fabian Holzwarth
e5916d455a feat: format and merge results in parallel 2025-05-19 17:05:18 +02:00
Fabian Holzwarth
ebb639e72e feat: remove log flushes 2025-05-18 16:29:19 +02:00
Fabian Holzwarth
f0a4a51ce6 feat: replace thread counter with thread pool 2025-05-18 15:40:31 +02:00
Fabian Holzwarth
7442880452 feat: limit placeholder generation to uppercase chars 2025-05-18 13:24:29 +02:00
Fabian Holzwarth
c4dc3b4245 feat: replace random based placeholder generation with deterministic approach 2025-05-18 12:41:56 +02:00
68 changed files with 4165 additions and 3862 deletions

View File

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

36
independentTest.sh Executable file
View File

@@ -0,0 +1,36 @@
#!/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/separate-variance
# 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"
# mvn clean compile -DskipTests package
## prefix each stderr line with " | "
# exec 2> >(trap "" INT TERM; sed 's/^/ | /' >&2)
# echo -e "\nMatrix test:\n |"
# time java -jar target/JavaTXcompiler-0.1-jar-with-dependencies.jar resources/bytecode/javFiles/Matrix.jav >/dev/null;
mvn clean compile -X && mvn test
echo -e "\Cleanup... "
rm -rf "$TDIR" 2>/dev/null
echo -e "\nFinished "
date "+%Y.%m.%d %H:%M:%S"
echo -e "\n "

28
pom.xml
View File

@@ -12,37 +12,37 @@ http://maven.apache.org/maven-v4_0_0.xsd">
<url>http://maven.apache.org</url> <url>http://maven.apache.org</url>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>org.junit.jupiter</groupId> <groupId>junit</groupId>
<artifactId>junit-jupiter-api</artifactId> <artifactId>junit</artifactId>
<version>5.13.2</version> <version>4.13.2</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<!-- https://mvnrepository.com/artifact/org.antlr/antlr4 --> <!-- https://mvnrepository.com/artifact/org.antlr/antlr4 -->
<dependency> <dependency>
<groupId>org.antlr</groupId> <groupId>org.antlr</groupId>
<artifactId>antlr4</artifactId> <artifactId>antlr4</artifactId>
<version>4.13.2</version> <version>4.11.1</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>commons-io</groupId> <groupId>commons-io</groupId>
<artifactId>commons-io</artifactId> <artifactId>commons-io</artifactId>
<version>2.19.0</version> <version>2.16.1</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>io.github.classgraph</groupId> <groupId>io.github.classgraph</groupId>
<artifactId>classgraph</artifactId> <artifactId>classgraph</artifactId>
<version>4.8.180</version> <version>4.8.172</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.google.guava</groupId> <groupId>com.google.guava</groupId>
<artifactId>guava</artifactId> <artifactId>guava</artifactId>
<version>33.4.8-jre</version> <version>33.2.0-jre</version>
</dependency> </dependency>
<!-- https://mvnrepository.com/artifact/org.ow2.asm/asm --> <!-- https://mvnrepository.com/artifact/org.ow2.asm/asm -->
<dependency> <dependency>
<groupId>org.ow2.asm</groupId> <groupId>org.ow2.asm</groupId>
<artifactId>asm</artifactId> <artifactId>asm</artifactId>
<version>9.8</version> <version>9.5</version>
</dependency> </dependency>
</dependencies> </dependencies>
@@ -51,17 +51,17 @@ http://maven.apache.org/maven-v4_0_0.xsd">
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId> <artifactId>maven-compiler-plugin</artifactId>
<version>3.14.0</version> <version>3.11.0</version>
<configuration> <configuration>
<compilerArgs>--enable-preview</compilerArgs> <compilerArgs>--enable-preview</compilerArgs>
<source>24</source> <source>23</source>
<target>24</target> <target>23</target>
</configuration> </configuration>
</plugin> </plugin>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId> <artifactId>maven-surefire-plugin</artifactId>
<version>3.5.3</version> <version>3.1.0</version>
<configuration> <configuration>
<redirectTestOutputToFile>true</redirectTestOutputToFile> <redirectTestOutputToFile>true</redirectTestOutputToFile>
<reportsDirectory>${project.build.directory}/test-reports</reportsDirectory> <reportsDirectory>${project.build.directory}/test-reports</reportsDirectory>
@@ -77,7 +77,7 @@ http://maven.apache.org/maven-v4_0_0.xsd">
<plugin> <plugin>
<groupId>org.antlr</groupId> <groupId>org.antlr</groupId>
<artifactId>antlr4-maven-plugin</artifactId> <artifactId>antlr4-maven-plugin</artifactId>
<version>4.13.2</version> <version>4.11.1</version>
<executions> <executions>
<execution> <execution>
<id>antlr</id> <id>antlr</id>
@@ -90,7 +90,7 @@ http://maven.apache.org/maven-v4_0_0.xsd">
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId> <artifactId>maven-jar-plugin</artifactId>
<version>3.4.2</version> <version>3.3.0</version>
<configuration> <configuration>
<archive> <archive>
<manifest> <manifest>

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -13,7 +13,6 @@ import org.objectweb.asm.*;
import java.lang.invoke.*; import java.lang.invoke.*;
import java.lang.reflect.Modifier; import java.lang.reflect.Modifier;
import java.util.*; import java.util.*;
import java.util.stream.Collectors;
import static org.objectweb.asm.Opcodes.*; import static org.objectweb.asm.Opcodes.*;
import static de.dhbwstuttgart.target.tree.expression.TargetBinaryOp.*; import static de.dhbwstuttgart.target.tree.expression.TargetBinaryOp.*;
@@ -85,16 +84,14 @@ public class Codegen {
int localCounter; int localCounter;
MethodVisitor mv; MethodVisitor mv;
TargetType returnType; TargetType returnType;
boolean isStatic = false;
Stack<BreakEnv> breakStack = new Stack<>(); Stack<BreakEnv> breakStack = new Stack<>();
Stack<Integer> switchResultValue = new Stack<>(); Stack<Integer> switchResultValue = new Stack<>();
State(TargetType returnType, MethodVisitor mv, int localCounter, boolean isStatic) { State(TargetType returnType, MethodVisitor mv, int localCounter) {
this.returnType = returnType; this.returnType = returnType;
this.mv = mv; this.mv = mv;
this.localCounter = localCounter; this.localCounter = localCounter;
this.isStatic = isStatic;
} }
void enterScope() { void enterScope() {
@@ -760,16 +757,6 @@ public class Codegen {
} }
} }
private static TargetType removeGenerics(TargetType param) {
return switch (param) {
case null -> null;
case TargetFunNType funNType -> new TargetFunNType(funNType.name(), funNType.funNParams(), List.of(), funNType.returnArguments());
case TargetRefType refType -> new TargetRefType(refType.name());
case TargetGenericType targetGenericType -> TargetType.Object;
default -> param;
};
}
private void generateLambdaExpression(State state, TargetLambdaExpression lambda) { private void generateLambdaExpression(State state, TargetLambdaExpression lambda) {
var mv = state.mv; var mv = state.mv;
@@ -781,8 +768,7 @@ public class Codegen {
var parameters = new ArrayList<>(lambda.captures()); var parameters = new ArrayList<>(lambda.captures());
parameters.addAll(signature.parameters()); parameters.addAll(signature.parameters());
parameters = parameters.stream().map(param -> param.withType(removeGenerics(param.pattern().type()))).collect(Collectors.toCollection(ArrayList::new)); var implSignature = new TargetMethod.Signature(Set.of(), parameters, lambda.signature().returnType());
var implSignature = new TargetMethod.Signature(Set.of(), parameters, removeGenerics(lambda.signature().returnType()));
TargetMethod impl; TargetMethod impl;
if (lambdas.containsKey(lambda)) { if (lambdas.containsKey(lambda)) {
@@ -790,21 +776,20 @@ public class Codegen {
} else { } else {
var name = "lambda$" + lambdaCounter++; var name = "lambda$" + lambdaCounter++;
impl = new TargetMethod(state.isStatic ? ACC_STATIC : 0, name, lambda.block(), implSignature, null); impl = new TargetMethod(0, name, lambda.block(), implSignature, null);
generateMethod(impl, state); generateMethod(impl);
lambdas.put(lambda, impl); lambdas.put(lambda, impl);
} }
var mt = MethodType.methodType(CallSite.class, MethodHandles.Lookup.class, String.class, MethodType.class, MethodType.class, MethodHandle.class, MethodType.class); var mt = MethodType.methodType(CallSite.class, MethodHandles.Lookup.class, String.class, MethodType.class, MethodType.class, MethodHandle.class, MethodType.class);
var bootstrap = new Handle(H_INVOKESTATIC, "java/lang/invoke/LambdaMetafactory", "metafactory", mt.toMethodDescriptorString(), false); var bootstrap = new Handle(H_INVOKESTATIC, "java/lang/invoke/LambdaMetafactory", "metafactory", mt.toMethodDescriptorString(), false);
var handle = new Handle(state.isStatic ? H_INVOKESTATIC : H_INVOKEVIRTUAL, clazz.getName(), impl.name(), implSignature.getDescriptor(), false); var handle = new Handle(H_INVOKEVIRTUAL, clazz.getName(), impl.name(), implSignature.getDescriptor(), false);
var params = new ArrayList<TargetType>(); var params = new ArrayList<TargetType>();
if(!state.isStatic) params.add(new TargetRefType(clazz.qualifiedName().getClassName())); params.add(new TargetRefType(clazz.qualifiedName().getClassName()));
params.addAll(lambda.captures().stream().map(mp -> mp.pattern().type()).toList()); params.addAll(lambda.captures().stream().map(mp -> mp.pattern().type()).toList());
if (!state.isStatic)
mv.visitVarInsn(ALOAD, 0); mv.visitVarInsn(ALOAD, 0);
for (var index = 0; index < lambda.captures().size(); index++) { for (var index = 0; index < lambda.captures().size(); index++) {
var capture = lambda.captures().get(index); var capture = lambda.captures().get(index);
@@ -1533,7 +1518,7 @@ public class Codegen {
MethodVisitor mv = cw.visitMethod(ACC_PUBLIC | ACC_STATIC, "<clinit>", "()V", null, null); MethodVisitor mv = cw.visitMethod(ACC_PUBLIC | ACC_STATIC, "<clinit>", "()V", null, null);
mv.visitCode(); mv.visitCode();
var state = new State(null, mv, 0, true); var state = new State(null, mv, 0);
generate(state, constructor.block()); generate(state, constructor.block());
mv.visitInsn(RETURN); mv.visitInsn(RETURN);
@@ -1547,7 +1532,7 @@ public class Codegen {
mv.visitAttribute(new JavaTXSignatureAttribute(constructor.getTXSignature())); mv.visitAttribute(new JavaTXSignatureAttribute(constructor.getTXSignature()));
mv.visitCode(); mv.visitCode();
var state = new State(null, mv, 1, false); var state = new State(null, mv, 1);
for (var param : constructor.parameters()) { for (var param : constructor.parameters()) {
var pattern = param.pattern(); var pattern = param.pattern();
if (pattern instanceof TargetTypePattern tp) if (pattern instanceof TargetTypePattern tp)
@@ -1593,11 +1578,8 @@ public class Codegen {
} }
} }
} }
private void generateMethod(TargetMethod method) {
generateMethod(method, null);
}
private void generateMethod(TargetMethod method, State parent) { private void generateMethod(TargetMethod method) {
var access = method.access(); var access = method.access();
if (method.block() == null) if (method.block() == null)
access |= ACC_ABSTRACT; access |= ACC_ABSTRACT;
@@ -1612,10 +1594,7 @@ public class Codegen {
if (method.block() != null) { if (method.block() != null) {
mv.visitCode(); mv.visitCode();
var state = new State(method.signature().returnType(), mv, method.isStatic() ? 0 : 1, method.isStatic()); var state = new State(method.signature().returnType(), mv, method.isStatic() ? 0 : 1);
if (parent != null) {
state.scope.parent = parent.scope;
}
var offset = 1; var offset = 1;
for (var param : method.signature().parameters()) { for (var param : method.signature().parameters()) {
state.createVariable(param.pattern().name(), param.pattern().type()); state.createVariable(param.pattern().name(), param.pattern().type());
@@ -1625,8 +1604,6 @@ public class Codegen {
bindLocalVariables(state, cp, offset); bindLocalVariables(state, cp, offset);
offset++; offset++;
} }
//if (parent != null) System.out.println("parent: " + parent.scope.locals.keySet());
//System.out.println(state.scope.locals.keySet());
generate(state, method.block()); generate(state, method.block());
if (method.signature().returnType() == null) if (method.signature().returnType() == null)
mv.visitInsn(RETURN); mv.visitInsn(RETURN);
@@ -1733,7 +1710,7 @@ public class Codegen {
// Generate wrapper method // Generate wrapper method
var mv = cw2.visitMethod(ACC_PUBLIC, toMethod.name, toDescriptor, null, null); var mv = cw2.visitMethod(ACC_PUBLIC, toMethod.name, toDescriptor, null, null);
var state = new State(null, mv, 0, false); var state = new State(null, mv, 0);
mv.visitVarInsn(ALOAD, 0); mv.visitVarInsn(ALOAD, 0);
mv.visitFieldInsn(GETFIELD, className, "wrapped", pair.from.toDescriptor()); mv.visitFieldInsn(GETFIELD, className, "wrapped", pair.from.toDescriptor());
@@ -1765,7 +1742,7 @@ public class Codegen {
converter.classLoader.findClass(className); converter.classLoader.findClass(className);
} catch (ClassNotFoundException e) { } catch (ClassNotFoundException e) {
try { try {
converter.classLoader.loadClass(className, bytes); converter.classLoader.loadClass(bytes);
} catch (LinkageError ignored) {} } catch (LinkageError ignored) {}
} }
} }

View File

@@ -39,10 +39,6 @@ public class FunNGenerator {
public final List<TargetType> inParams; public final List<TargetType> inParams;
public final List<TargetType> realParams; public final List<TargetType> realParams;
public GenericParameters(TargetFunNType funNType) {
this(funNType.funNParams(), funNType.returnArguments());
}
public GenericParameters(List<TargetType> params, int numReturns) { public GenericParameters(List<TargetType> params, int numReturns) {
this.realParams = params; this.realParams = params;
this.inParams = flattenTypeParams(params); this.inParams = flattenTypeParams(params);

View File

@@ -37,6 +37,7 @@ import de.dhbwstuttgart.typeinference.result.ResultSet;
import de.dhbwstuttgart.typeinference.typeAlgo.TYPE; import de.dhbwstuttgart.typeinference.typeAlgo.TYPE;
import de.dhbwstuttgart.typeinference.unify.RuleSet; import de.dhbwstuttgart.typeinference.unify.RuleSet;
import de.dhbwstuttgart.typeinference.unify.TypeUnify; import de.dhbwstuttgart.typeinference.unify.TypeUnify;
import de.dhbwstuttgart.typeinference.unify.UnifyContext;
import de.dhbwstuttgart.typeinference.unify.distributeVariance; import de.dhbwstuttgart.typeinference.unify.distributeVariance;
import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure; import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure;
import de.dhbwstuttgart.typeinference.unify.model.PairOperator; import de.dhbwstuttgart.typeinference.unify.model.PairOperator;
@@ -300,6 +301,7 @@ public class JavaTXCompiler {
Set<Set<UnifyPair>> results = new HashSet<>(); Set<Set<UnifyPair>> results = new HashSet<>();
UnifyResultModel urm = null; UnifyResultModel urm = null;
// urm.addUnifyResultListener(resultListener); // urm.addUnifyResultListener(resultListener);
UnifyContext context = new UnifyContext(logFile, log, true, urm, usedTasks);
try { try {
logFile = logFile == null ? new FileWriter(new File("log_" + sourceFiles.keySet().iterator().next().getName())) : logFile; logFile = logFile == null ? new FileWriter(new File("log_" + sourceFiles.keySet().iterator().next().getName())) : logFile;
IFiniteClosure finiteClosure = UnifyTypeFactory.generateFC(allClasses, logFile, getClassLoader(), this); IFiniteClosure finiteClosure = UnifyTypeFactory.generateFC(allClasses, logFile, getClassLoader(), this);
@@ -326,7 +328,7 @@ public class JavaTXCompiler {
for (SourceFile f : this.sourceFiles.values()) { for (SourceFile f : this.sourceFiles.values()) {
logFile.write(ASTTypePrinter.print(f)); logFile.write(ASTTypePrinter.print(f));
} }
logFile.flush(); // logFile.flush();
Set<PlaceholderType> varianceTPHold; Set<PlaceholderType> varianceTPHold;
Set<PlaceholderType> varianceTPH = new HashSet<>(); Set<PlaceholderType> varianceTPH = new HashSet<>();
varianceTPH = varianceInheritanceConstraintSet(unifyCons); varianceTPH = varianceInheritanceConstraintSet(unifyCons);
@@ -342,7 +344,7 @@ public class JavaTXCompiler {
List<Set<Constraint<UnifyPair>>> oderConstraints = unifyCons.getOderConstraints()/* 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)) * .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); unify.unifyAsync(unifyCons.getUndConstraints(), oderConstraints, finiteClosure, context);
} catch (IOException e) { } catch (IOException e) {
System.err.println("kein LogFile"); System.err.println("kein LogFile");
} }
@@ -392,13 +394,8 @@ public class JavaTXCompiler {
logFile.write("FC:\\" + finiteClosure.toString() + "\n"); logFile.write("FC:\\" + finiteClosure.toString() + "\n");
logFile.write(ASTTypePrinter.print(sf)); logFile.write(ASTTypePrinter.print(sf));
System.out.println(ASTTypePrinter.print(sf)); System.out.println(ASTTypePrinter.print(sf));
logFile.flush(); // logFile.flush();
List<UnifyPair> andConstraintsSorted = unifyCons.getUndConstraints().stream() System.out.println("Unify nach Oder-Constraints-Anpassung:" + unifyCons.toString());
.sorted(Comparator.comparing(UnifyPair::getPairOp).thenComparing(UnifyPair::getLhsType, Comparator.comparing(UnifyType::getName)))
.collect(Collectors.toList());
System.out.println(andConstraintsSorted);
Set<PlaceholderType> varianceTPHold; Set<PlaceholderType> varianceTPHold;
Set<PlaceholderType> varianceTPH = new HashSet<>(); Set<PlaceholderType> varianceTPH = new HashSet<>();
varianceTPH = varianceInheritanceConstraintSet(unifyCons); varianceTPH = varianceInheritanceConstraintSet(unifyCons);
@@ -420,18 +417,12 @@ public class JavaTXCompiler {
UnifyResultModel urm = new UnifyResultModel(cons, finiteClosure); UnifyResultModel urm = new UnifyResultModel(cons, finiteClosure);
UnifyResultListenerImpl li = new UnifyResultListenerImpl(); UnifyResultListenerImpl li = new UnifyResultListenerImpl();
urm.addUnifyResultListener(li); urm.addUnifyResultListener(li);
unify.unifyParallel(unifyCons.getUndConstraints(), oderConstraints, finiteClosure, logFile, log, urm, usedTasks); UnifyContext context = new UnifyContext(logFile, log, true, urm, usedTasks);
//System.out.println("RESULT Final: " + li.getResults()); unify.unifyParallel(unifyCons.getUndConstraints(), oderConstraints, finiteClosure, context);
var finalResults = li.getResults().stream().sorted().toList(); System.out.println("RESULT Final: " + li.getResults());
int i = 0;
System.out.println("RESULT Final: ");
for (var result : finalResults){
System.out.println("Result: " + i++);
System.out.println(result.getSortedResults());
}
System.out.println("Constraints for Generated Generics: " + " ???"); System.out.println("Constraints for Generated Generics: " + " ???");
logFile.write("RES_FINAL: " + li.getResults().toString() + "\n"); logFile.write("RES_FINAL: " + li.getResults().toString() + "\n");
logFile.flush(); // logFile.flush();
return li.getResults(); return li.getResults();
} }
/* UnifyResultModel End */ /* UnifyResultModel End */
@@ -439,10 +430,11 @@ public class JavaTXCompiler {
// Set<Set<UnifyPair>> result = unify.unify(unifyCons.getUndConstraints(), // Set<Set<UnifyPair>> result = unify.unify(unifyCons.getUndConstraints(),
// oderConstraints, finiteClosure, logFile, log, new UnifyResultModel(cons, // oderConstraints, finiteClosure, logFile, log, new UnifyResultModel(cons,
// finiteClosure)); // finiteClosure));
Set<Set<UnifyPair>> result = unify.unifyOderConstraints(unifyCons.getUndConstraints(), oderConstraints, finiteClosure, logFile, log, new UnifyResultModel(cons, finiteClosure), usedTasks); UnifyContext context = new UnifyContext(logFile, log, false, new UnifyResultModel(cons, finiteClosure), usedTasks);
Set<Set<UnifyPair>> result = unify.unifyOderConstraints(unifyCons.getUndConstraints(), oderConstraints, finiteClosure, context);
System.out.println("RESULT: " + result); System.out.println("RESULT: " + result);
logFile.write("RES: " + result.toString() + "\n"); logFile.write("RES: " + result.toString() + "\n");
logFile.flush(); // logFile.flush();
results.addAll(result); results.addAll(result);
results = results.stream().map(x -> { results = results.stream().map(x -> {
@@ -452,16 +444,16 @@ public class JavaTXCompiler {
return y; // alle Paare a <.? b erden durch a =. b ersetzt return y; // alle Paare a <.? b erden durch a =. b ersetzt
}).collect(Collectors.toCollection(HashSet::new))); }).collect(Collectors.toCollection(HashSet::new)));
if (res.isPresent()) {// wenn subst ein Erg liefert wurde was veraendert if (res.isPresent()) {// wenn subst ein Erg liefert wurde was veraendert
return new TypeUnifyTask().applyTypeUnificationRules(res.get(), finiteClosure); return new TypeUnifyTask(context).applyTypeUnificationRules(res.get(), finiteClosure);
} else } else
return x; // wenn nichts veraendert wurde wird x zurueckgegeben return x; // wenn nichts veraendert wurde wird x zurueckgegeben
}).collect(Collectors.toCollection(HashSet::new)); }).collect(Collectors.toCollection(HashSet::new));
System.out.println("RESULT Final: " + results); System.out.println("RESULT Final: " + results);
System.out.println("Constraints for Generated Generics: " + " ???"); System.out.println("Constraints for Generated Generics: " + " ???");
logFile.write("RES_FINAL: " + results.toString() + "\n"); logFile.write("RES_FINAL: " + results.toString() + "\n");
logFile.flush(); // logFile.flush();
logFile.write("PLACEHOLDERS: " + PlaceholderType.EXISTING_PLACEHOLDERS); logFile.write("PLACEHOLDERS: " + PlaceholderType.EXISTING_PLACEHOLDERS);
logFile.flush(); // logFile.flush();
} }
} catch (IOException e) { } catch (IOException e) {
System.err.println("kein LogFile"); System.err.println("kein LogFile");
@@ -643,12 +635,12 @@ public class JavaTXCompiler {
var codegen = new Codegen(converter.convert(clazz), this, converter); var codegen = new Codegen(converter.convert(clazz), this, converter);
var code = codegen.generate(); var code = codegen.generate();
generatedClasses.put(clazz.getClassName(), code); generatedClasses.put(clazz.getClassName(), code);
}
generatedGenerics.put(sf, converter.javaGenerics());
converter.generateFunNTypes();
converter.auxiliaries.forEach((name, source) -> { converter.auxiliaries.forEach((name, source) -> {
generatedClasses.put(new JavaClassName(name), source); generatedClasses.put(new JavaClassName(name), source);
}); });
}
generatedGenerics.put(sf, converter.javaGenerics());
converter.generateFunNTypes();
return generatedClasses; return generatedClasses;
} }

View File

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

View File

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

View File

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

@@ -1099,9 +1099,9 @@ public class StatementGenerator {
block = lambdaGenerator.convert(expression.lambdaBody().block(), true); block = lambdaGenerator.convert(expression.lambdaBody().block(), true);
} }
List<RefTypeOrTPHOrWildcardOrGeneric> funNParams = new ArrayList<>(); List<RefTypeOrTPHOrWildcardOrGeneric> funNParams = new ArrayList<>();
funNParams.add(TypePlaceholder.fresh(expression.getStart(), -1, false));// ret-Type funNParams.add(TypePlaceholder.fresh(expression.getStart()));// ret-Type
params.getFormalparalist().forEach(formalParameter -> // Für jeden Parameter einen TPH anfügen: params.getFormalparalist().forEach(formalParameter -> // Für jeden Parameter einen TPH anfügen:
funNParams.add(TypePlaceholder.fresh(expression.getStart(), 1, false))); funNParams.add(TypePlaceholder.fresh(expression.getStart())));
RefTypeOrTPHOrWildcardOrGeneric lambdaType = TypePlaceholder.fresh(expression.getStart()); RefTypeOrTPHOrWildcardOrGeneric lambdaType = TypePlaceholder.fresh(expression.getStart());
// RefType lambdaType = new // RefType lambdaType = new
// RefType(reg.getName("Fun"+params.getFormalparalist().size()), // RefType(reg.getName("Fun"+params.getFormalparalist().size()),

View File

@@ -7,7 +7,7 @@ import java.util.*;
/** /**
* Speichert die Klassen f<>r einen bestimmten Projektscope * Speichert die Klassen f<>r einen bestimmten Projektscope
*/ */
public class JavaClassRegistry{ public class JavaClassRegistry {
final Map<JavaClassName, Integer> existingClasses = new HashMap<>(); final Map<JavaClassName, Integer> existingClasses = new HashMap<>();
public JavaClassRegistry(Map<String, Integer> initialNames) { public JavaClassRegistry(Map<String, Integer> initialNames) {
@@ -22,10 +22,6 @@ public class JavaClassRegistry{
} }
} }
public Set<JavaClassName> getAllClassNames(){
return existingClasses.keySet();
}
public void addName(String className, int numberOfGenerics) { public void addName(String className, int numberOfGenerics) {
existingClasses.put(new JavaClassName(className), numberOfGenerics); existingClasses.put(new JavaClassName(className), numberOfGenerics);
} }

View File

@@ -194,7 +194,7 @@ public class UnifyTypeFactory {
&& ((PlaceholderType)lhs).isWildcardable() && ((PlaceholderType)lhs).isWildcardable()
&& (rhs = ret.getLhsType()) instanceof PlaceholderType) { && (rhs = ret.getLhsType()) instanceof PlaceholderType) {
if (lhs.getName().equals("AQ")) { if (lhs.getName().equals("AQ")) {
System.out.println(""); // System.out.println("");
} }
((PlaceholderType)rhs).enableWildcardtable(); ((PlaceholderType)rhs).enableWildcardtable();
} }
@@ -203,7 +203,7 @@ public class UnifyTypeFactory {
&& ((PlaceholderType)rhs).isWildcardable() && ((PlaceholderType)rhs).isWildcardable()
&& (lhs = ret.getLhsType()) instanceof PlaceholderType) { && (lhs = ret.getLhsType()) instanceof PlaceholderType) {
if (rhs.getName().equals("AQ")) { if (rhs.getName().equals("AQ")) {
System.out.println(""); // System.out.println("");
} }
((PlaceholderType)lhs).enableWildcardtable(); ((PlaceholderType)lhs).enableWildcardtable();
} }

View File

@@ -2,6 +2,7 @@ package de.dhbwstuttgart.target.generate;
import de.dhbwstuttgart.bytecode.FunNGenerator; import de.dhbwstuttgart.bytecode.FunNGenerator;
import de.dhbwstuttgart.core.JavaTXCompiler; import de.dhbwstuttgart.core.JavaTXCompiler;
import de.dhbwstuttgart.environment.ByteArrayClassLoader;
import de.dhbwstuttgart.environment.IByteArrayClassLoader; import de.dhbwstuttgart.environment.IByteArrayClassLoader;
import de.dhbwstuttgart.exceptions.DebugException; import de.dhbwstuttgart.exceptions.DebugException;
import de.dhbwstuttgart.parser.NullToken; import de.dhbwstuttgart.parser.NullToken;
@@ -11,8 +12,6 @@ import de.dhbwstuttgart.syntaxtree.Record;
import de.dhbwstuttgart.syntaxtree.factory.ASTFactory; import de.dhbwstuttgart.syntaxtree.factory.ASTFactory;
import de.dhbwstuttgart.syntaxtree.statement.*; import de.dhbwstuttgart.syntaxtree.statement.*;
import de.dhbwstuttgart.syntaxtree.type.*; import de.dhbwstuttgart.syntaxtree.type.*;
import de.dhbwstuttgart.syntaxtree.visual.ASTPrinter;
import de.dhbwstuttgart.syntaxtree.visual.OutputGenerator;
import de.dhbwstuttgart.target.tree.*; import de.dhbwstuttgart.target.tree.*;
import de.dhbwstuttgart.target.tree.expression.*; import de.dhbwstuttgart.target.tree.expression.*;
import de.dhbwstuttgart.target.tree.type.*; import de.dhbwstuttgart.target.tree.type.*;
@@ -67,11 +66,11 @@ public class ASTToTargetAST {
public IByteArrayClassLoader classLoader; public IByteArrayClassLoader classLoader;
protected SourceFile sourceFile; protected SourceFile sourceFile;
public ASTToTargetAST(List<ResultSet> resultSets, IByteArrayClassLoader classLoader) { public ASTToTargetAST(List<ResultSet> resultSets) {
this(null, resultSets, classLoader); this(null, resultSets);
} }
public ASTToTargetAST(JavaTXCompiler compiler, List<ResultSet> resultSets, IByteArrayClassLoader classLoader) { public ASTToTargetAST(JavaTXCompiler compiler, List<ResultSet> resultSets) {
this(compiler, resultSets, null, classLoader); this(compiler, resultSets, null, new ByteArrayClassLoader());
} }
public ASTToTargetAST(JavaTXCompiler compiler, List<ResultSet> resultSets, SourceFile sourceFile, IByteArrayClassLoader classLoader) { public ASTToTargetAST(JavaTXCompiler compiler, List<ResultSet> resultSets, SourceFile sourceFile, IByteArrayClassLoader classLoader) {
@@ -782,15 +781,7 @@ public class ASTToTargetAST {
return TargetFunNType.fromParams(params, filteredParams, gep.getReturnType() != null ? 1 : 0); return TargetFunNType.fromParams(params, filteredParams, gep.getReturnType() != null ? 1 : 0);
} }
private FunNGenerator.GenericParameters convertToParameters(TargetFunNType input) {
return null;
}
private boolean isSubtype(TargetType test, TargetType other) { private boolean isSubtype(TargetType test, TargetType other) {
if (other.equals(TargetType.Object)) return true;
if (test instanceof TargetFunNType tfun && other instanceof TargetFunNType ofun)
return isSubtype(new FunNGenerator.GenericParameters(tfun), new FunNGenerator.GenericParameters(ofun));
var testClass = compiler.getClass(new JavaClassName(test.name())); var testClass = compiler.getClass(new JavaClassName(test.name()));
var otherClass = compiler.getClass(new JavaClassName(other.name())); var otherClass = compiler.getClass(new JavaClassName(other.name()));
if (testClass == null) return false; if (testClass == null) return false;
@@ -827,6 +818,14 @@ public class ASTToTargetAST {
.toList(); .toList();
var code = FunNGenerator.generateSpecializedBytecode(gep, superInterfaces); var code = FunNGenerator.generateSpecializedBytecode(gep, superInterfaces);
try {
classLoader.findClass(entry.getKey());
} catch (ClassNotFoundException e) {
try {
classLoader.loadClass(code);
} catch (LinkageError ignored) {}
}
auxiliaries.put(entry.getKey(), code); auxiliaries.put(entry.getKey(), code);
} }
} }
@@ -857,7 +856,7 @@ public class ASTToTargetAST {
classLoader.findClass(superClassName); classLoader.findClass(superClassName);
} catch (ClassNotFoundException e) { } catch (ClassNotFoundException e) {
try { try {
classLoader.loadClass(superClassName, code); classLoader.loadClass(code);
} catch (LinkageError ignored) {} } catch (LinkageError ignored) {}
} }
auxiliaries.put(superClassName, code); auxiliaries.put(superClassName, code);

View File

@@ -14,7 +14,6 @@ import de.dhbwstuttgart.target.tree.expression.*;
import de.dhbwstuttgart.target.tree.type.*; import de.dhbwstuttgart.target.tree.type.*;
import java.lang.reflect.Modifier; import java.lang.reflect.Modifier;
import java.sql.Array;
import java.util.*; import java.util.*;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.stream.StreamSupport; import java.util.stream.StreamSupport;
@@ -33,17 +32,19 @@ public class StatementToTargetExpression implements ASTVisitor {
throw new NotImplementedException(); throw new NotImplementedException();
} }
private class LambdaCaptureFinder extends TracingStatementVisitor { @Override
public void visit(LambdaExpression lambdaExpression) {
var parameters = StreamSupport.stream(lambdaExpression.params.spliterator(), false)
.map(p -> (FormalParameter) p)
.map(p -> new MethodParameter(new TargetTypePattern(converter.convert(p.getType()), p.getName())))
.toList();
List<MethodParameter> captures = new ArrayList<>();
lambdaExpression.methodBody.accept(new TracingStatementVisitor() {
// TODO The same mechanism is implemented in Codegen, maybe use it from there? // TODO The same mechanism is implemented in Codegen, maybe use it from there?
final Stack<Set<String>> localVariables = new Stack<>(); final Stack<Set<String>> localVariables = new Stack<>();
private final List<MethodParameter> parameters; {
private final List<MethodParameter> captures;
LambdaCaptureFinder(List<MethodParameter> parameters, List<MethodParameter> captures) {
localVariables.push(new HashSet<>()); localVariables.push(new HashSet<>());
this.parameters = parameters;
this.captures = captures;
} }
boolean hasLocalVar(String name) { boolean hasLocalVar(String name) {
@@ -77,27 +78,8 @@ public class StatementToTargetExpression implements ASTVisitor {
@Override @Override
public void visit(LambdaExpression lambda) { public void visit(LambdaExpression lambda) {
var newCaptures = new ArrayList<MethodParameter>(); } // Don't look at lambda expressions
var captureFinder = new LambdaCaptureFinder(createParameters(lambda), newCaptures); });
lambda.methodBody.accept(captureFinder);
newCaptures.removeAll(parameters);
captures.addAll(newCaptures);
}
}
private List<MethodParameter> createParameters(LambdaExpression lambda) {
return StreamSupport.stream(lambda.params.spliterator(), false)
.map(p -> (FormalParameter) p)
.map(p -> new MethodParameter(new TargetTypePattern(converter.convert(p.getType()), p.getName())))
.toList();
}
@Override
public void visit(LambdaExpression lambdaExpression) {
var parameters = createParameters(lambdaExpression);
List<MethodParameter> captures = new ArrayList<>();
var visitor = new LambdaCaptureFinder(parameters, captures);
lambdaExpression.methodBody.accept(visitor);
TargetMethod.Signature signature = new TargetMethod.Signature(Set.of(), parameters, converter.convert(lambdaExpression.getReturnType()));; TargetMethod.Signature signature = new TargetMethod.Signature(Set.of(), parameters, converter.convert(lambdaExpression.getReturnType()));;
var tpe = converter.convert(lambdaExpression.getType()); var tpe = converter.convert(lambdaExpression.getType());
@@ -138,10 +120,7 @@ public class StatementToTargetExpression implements ASTVisitor {
@Override @Override
public void visit(BoolExpression bool) { public void visit(BoolExpression bool) {
result = switch(bool.operation) { System.out.println("BoolExpression");
case OR -> new TargetBinaryOp.Or(converter.convert(bool.getType()), converter.convert(bool.lexpr), converter.convert(bool.rexpr));
case AND -> new TargetBinaryOp.And(converter.convert(bool.getType()), converter.convert(bool.lexpr), converter.convert(bool.rexpr));
};
} }
@Override @Override

View File

@@ -6,7 +6,7 @@ import java.util.Collection;
import java.util.HashSet; import java.util.HashSet;
import java.util.Set; import java.util.Set;
public class Constraint<A> extends HashSet<A> implements Comparable<Constraint<A>> { public class Constraint<A> extends HashSet<A> {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
private Boolean isInherited = false;//wird beides nur für die Method-Constraints benoetigt private Boolean isInherited = false;//wird beides nur für die Method-Constraints benoetigt
private Boolean isImplemented = false; private Boolean isImplemented = false;
@@ -74,8 +74,4 @@ public class Constraint<A> extends HashSet<A> implements Comparable<Constraint<A
return super.toString(); return super.toString();
} }
@Override
public int compareTo(Constraint<A> o) {
return this.toString().compareTo(o.toString());
}
} }

View File

@@ -5,7 +5,7 @@ import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric;
/** /**
* Paare, welche das Unifikationsergebnis darstellen * Paare, welche das Unifikationsergebnis darstellen
*/ */
public abstract class ResultPair<A extends RefTypeOrTPHOrWildcardOrGeneric, B extends RefTypeOrTPHOrWildcardOrGeneric> implements Comparable<ResultPair<A,B>> { public abstract class ResultPair<A extends RefTypeOrTPHOrWildcardOrGeneric,B extends RefTypeOrTPHOrWildcardOrGeneric> {
private final A left; private final A left;
private final B right; private final B right;
@@ -59,13 +59,4 @@ public abstract class ResultPair<A extends RefTypeOrTPHOrWildcardOrGeneric, B ex
return true; return true;
} }
@Override
public int compareTo(ResultPair<A, B> o) {
if (o == null) {
return 1; // this is greater than null
}
return o.left.toString().compareTo(this.left.toString());
}
} }

View File

@@ -1,8 +1,6 @@
package de.dhbwstuttgart.typeinference.result; package de.dhbwstuttgart.typeinference.result;
import java.util.Collections;
import java.util.HashSet; import java.util.HashSet;
import java.util.List;
import java.util.Set; import java.util.Set;
import de.dhbwstuttgart.exceptions.NotImplementedException; import de.dhbwstuttgart.exceptions.NotImplementedException;
@@ -14,7 +12,7 @@ import de.dhbwstuttgart.syntaxtree.type.SuperWildcardType;
import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder; import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder;
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
public class ResultSet implements Comparable<ResultSet>{ public class ResultSet {
public final Set<ResultPair> results; public final Set<ResultPair> results;
public Set<ResultPair<TypePlaceholder, TypePlaceholder>> genIns; public Set<ResultPair<TypePlaceholder, TypePlaceholder>> genIns;
@@ -25,10 +23,6 @@ public class ResultSet implements Comparable<ResultSet>{
results.forEach(x -> { if (x instanceof PairTPHsmallerTPH) { this.genIns.add(x);}} ); results.forEach(x -> { if (x instanceof PairTPHsmallerTPH) { this.genIns.add(x);}} );
} }
public List<ResultPair> getSortedResults() {
return results.stream().sorted().toList();
}
public boolean contains(ResultPair toCheck) { public boolean contains(ResultPair toCheck) {
return this.results.contains(toCheck); return this.results.contains(toCheck);
} }
@@ -69,21 +63,6 @@ public class ResultSet implements Comparable<ResultSet>{
public int hashCode() { public int hashCode() {
return results.hashCode(); return results.hashCode();
} }
@Override
public int compareTo(ResultSet o) {
List<ResultPair> thisSorted = this.getSortedResults();
List<ResultPair> otherSorted = o.getSortedResults();
int sizeCompare = Integer.compare(thisSorted.size(), otherSorted.size());
if (sizeCompare != 0) return sizeCompare;
for (int i = 0; i < thisSorted.size(); i++) {
int cmp = thisSorted.get(i).compareTo(otherSorted.get(i));
if (cmp != 0) return cmp;
}
return 0;
}
} }
class Resolver implements ResultSetVisitor { class Resolver implements ResultSetVisitor {

View File

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

View File

@@ -0,0 +1,64 @@
package de.dhbwstuttgart.typeinference.unify;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.RecursiveTask;
public class ConcurrentSetMergeTask<T> extends RecursiveTask<Set<T>> {
public static <E> Set<E> merge(List<Set<E>> list) {
if (list.isEmpty()) {
return new HashSet<>();
}
var task = new ConcurrentSetMergeTask<>(list, 0, list.size());
return task.compute();
}
private static final int LIST_THRESHOLD = 3;
private static final int ELEMENT_THRESHOLD = 1000;
private final List<Set<T>> list;
private final int start;
private final int end;
private ConcurrentSetMergeTask(List<Set<T>> list, int start, int end) {
this.list = list;
this.start = start;
this.end = end;
}
@Override
protected Set<T> compute() {
int size = end - start;
int totalElements = 0;
for (int i = start+1; i < end; i++) {
totalElements += list.get(i).size();
}
System.out.println("ConcurrentSetMerge? -> " + (size <= LIST_THRESHOLD || totalElements < ELEMENT_THRESHOLD ? "true" : "false"));
// size will always be at least one
if (true || size <= LIST_THRESHOLD || totalElements < ELEMENT_THRESHOLD) {
Set<T> result = this.list.get(start);
for (int i = start+1; i < end; i++) {
result.addAll(list.get(i));
}
return result;
} else {
int mid = start + (size / 2);
ConcurrentSetMergeTask<T> leftTask = new ConcurrentSetMergeTask<>(list, start, mid);
ConcurrentSetMergeTask<T> rightTask = new ConcurrentSetMergeTask<>(list, mid, end);
leftTask.fork();
Set<T> rightResult = rightTask.compute();
Set<T> leftResult = leftTask.join();
// Merge results
leftResult.addAll(rightResult);
return leftResult;
}
}
}

View File

@@ -864,7 +864,7 @@ public class RuleSet implements IRuleSet{
try { try {
logFile.write("FUNgreater: " + pair + "\n"); logFile.write("FUNgreater: " + pair + "\n");
logFile.write("FUNred: " + result + "\n"); logFile.write("FUNred: " + result + "\n");
logFile.flush(); // logFile.flush();
} }
catch (IOException e) { catch (IOException e) {
System.out.println("logFile-Error"); System.out.println("logFile-Error");
@@ -960,7 +960,7 @@ public class RuleSet implements IRuleSet{
try { try {
logFile.write("FUNgreater: " + pair + "\n"); logFile.write("FUNgreater: " + pair + "\n");
logFile.write("FUNgreater: " + result + "\n"); logFile.write("FUNgreater: " + result + "\n");
logFile.flush(); // logFile.flush();
} }
catch (IOException e) { catch (IOException e) {
System.out.println("lofFile-Error"); System.out.println("lofFile-Error");
@@ -1010,7 +1010,7 @@ public class RuleSet implements IRuleSet{
try { try {
logFile.write("FUNgreater: " + pair + "\n"); logFile.write("FUNgreater: " + pair + "\n");
logFile.write("FUNsmaller: " + result + "\n"); logFile.write("FUNsmaller: " + result + "\n");
logFile.flush(); // logFile.flush();
} }
catch (IOException e) { catch (IOException e) {
System.out.println("lofFile-Error"); System.out.println("lofFile-Error");

View File

@@ -1,41 +1,28 @@
package de.dhbwstuttgart.typeinference.unify; package de.dhbwstuttgart.typeinference.unify;
import java.io.FileWriter;
import java.io.IOException; import java.io.IOException;
import java.io.Writer; import java.io.Writer;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import java.util.concurrent.ForkJoinPool; import java.util.concurrent.ForkJoinPool;
import de.dhbwstuttgart.core.JavaTXCompiler;
import de.dhbwstuttgart.typeinference.constraints.Constraint; import de.dhbwstuttgart.typeinference.constraints.Constraint;
import de.dhbwstuttgart.typeinference.constraints.ConstraintSet;
import de.dhbwstuttgart.typeinference.constraints.Pair;
import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure; import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure;
import de.dhbwstuttgart.typeinference.unify.model.FiniteClosure;
import de.dhbwstuttgart.typeinference.unify.model.UnifyPair; import de.dhbwstuttgart.typeinference.unify.model.UnifyPair;
public class TypeUnify { public class TypeUnify {
/** /**
* unify parallel ohne result modell * unify parallel ohne result modell
* @param undConstrains
* @param oderConstraints
* @param fc
* @param logFile
* @param log
* @param cons
* @return
*/ */
public Set<Set<UnifyPair>> unify(Set<UnifyPair> undConstrains, List<Set<Constraint<UnifyPair>>> oderConstraints, IFiniteClosure fc, Writer logFile, Boolean log, UnifyResultModel ret, UnifyTaskModel usedTasks) { public Set<Set<UnifyPair>> unify(Set<UnifyPair> undConstrains, List<Set<Constraint<UnifyPair>>> oderConstraints, IFiniteClosure fc, UnifyContext unifyContext) {
TypeUnifyTask unifyTask = new TypeUnifyTask(undConstrains, oderConstraints, fc, true, logFile, log, 0, ret, usedTasks); TypeUnifyTask unifyTask = new TypeUnifyTask(undConstrains, oderConstraints, fc, unifyContext.newWithParallel(true), 0);
ForkJoinPool pool = new ForkJoinPool(); ForkJoinPool pool = this.createThreadPool();
pool.invoke(unifyTask); pool.invoke(unifyTask);
Set<Set<UnifyPair>> res = unifyTask.join(); Set<Set<UnifyPair>> res = unifyTask.join();
try { try {
logFile.write("\nnoShortendElements: " + unifyTask.noShortendElements + "\n"); unifyContext.logFile.write("\nnoShortendElements: " + unifyTask.noShortendElements + "\n");
logFile.flush(); // logFile.flush();
} }
catch (IOException e) { catch (IOException e) {
System.err.println("no log-File"); System.err.println("no log-File");
@@ -45,46 +32,30 @@ public class TypeUnify {
/** /**
* unify asynchron mit Rückgabe UnifyResultModel ohne dass alle results gesammelt sind * unify asynchron mit Rückgabe UnifyResultModel ohne dass alle results gesammelt sind
* @param undConstrains
* @param oderConstraints
* @param fc
* @param logFile
* @param log
* @param cons
* @param ret
* @return
*/ */
public UnifyResultModel unifyAsync(Set<UnifyPair> undConstrains, List<Set<Constraint<UnifyPair>>> oderConstraints, IFiniteClosure fc, Writer logFile, Boolean log, UnifyResultModel ret, UnifyTaskModel usedTasks) { public UnifyResultModel unifyAsync(Set<UnifyPair> undConstrains, List<Set<Constraint<UnifyPair>>> oderConstraints, IFiniteClosure fc, UnifyContext unifyContext) {
TypeUnifyTask unifyTask = new TypeUnifyTask(undConstrains, oderConstraints, fc, true, logFile, log, 0, ret, usedTasks); TypeUnifyTask unifyTask = new TypeUnifyTask(undConstrains, oderConstraints, fc, unifyContext, 0);
ForkJoinPool pool = new ForkJoinPool(); ForkJoinPool pool = this.createThreadPool();
pool.invoke(unifyTask); pool.invoke(unifyTask);
return ret; return unifyContext.resultModel;
} }
/** /**
* unify parallel mit Rückgabe UnifyResultModel nachdem alle results gesammelt sind * unify parallel mit Rückgabe UnifyResultModel nachdem alle results gesammelt sind
* @param undConstrains
* @param oderConstraints
* @param fc
* @param logFile
* @param log
* @param cons
* @param ret
* @return
*/ */
public UnifyResultModel unifyParallel(Set<UnifyPair> undConstrains, List<Set<Constraint<UnifyPair>>> oderConstraints, IFiniteClosure fc, Writer logFile, Boolean log, UnifyResultModel ret, UnifyTaskModel usedTasks) { public UnifyResultModel unifyParallel(Set<UnifyPair> undConstrains, List<Set<Constraint<UnifyPair>>> oderConstraints, IFiniteClosure fc, UnifyContext unifyContext) {
TypeUnifyTask unifyTask = new TypeUnifyTask(undConstrains, oderConstraints, fc, true, logFile, log, 0, ret, usedTasks); TypeUnifyTask unifyTask = new TypeUnifyTask(undConstrains, oderConstraints, fc, unifyContext.newWithParallel(true), 0);
ForkJoinPool pool = new ForkJoinPool(); ForkJoinPool pool = this.createThreadPool();
pool.invoke(unifyTask); pool.invoke(unifyTask);
Set<Set<UnifyPair>> res = unifyTask.join(); Set<Set<UnifyPair>> res = unifyTask.join();
try { try {
logFile.write("\nnoShortendElements: " + unifyTask.noShortendElements +"\n"); unifyContext.logFile.write("\nnoShortendElements: " + unifyTask.noShortendElements +"\n");
logFile.flush(); // logFile.flush();
} }
catch (IOException e) { catch (IOException e) {
System.err.println("no log-File"); System.err.println("no log-File");
} }
return ret; return unifyContext.resultModel;
} }
/* /*
@@ -97,20 +68,13 @@ public class TypeUnify {
/** /**
* unify sequentiell mit oderconstraints * unify sequentiell mit oderconstraints
* @param undConstrains
* @param oderConstraints
* @param fc
* @param logFile
* @param log
* @param cons
* @return
*/ */
public Set<Set<UnifyPair>> unifyOderConstraints(Set<UnifyPair> undConstrains, List<Set<Constraint<UnifyPair>>> oderConstraints, IFiniteClosure fc, Writer logFile, Boolean log, UnifyResultModel ret, UnifyTaskModel usedTasks) { public Set<Set<UnifyPair>> unifyOderConstraints(Set<UnifyPair> undConstrains, List<Set<Constraint<UnifyPair>>> oderConstraints, IFiniteClosure fc, UnifyContext unifyContext) {
TypeUnifyTask unifyTask = new TypeUnifyTask(undConstrains, oderConstraints, fc, false, logFile, log, 0, ret, usedTasks); TypeUnifyTask unifyTask = new TypeUnifyTask(undConstrains, oderConstraints, fc, unifyContext.newWithParallel(false), 0);
Set<Set<UnifyPair>> res = unifyTask.compute(); Set<Set<UnifyPair>> res = unifyTask.compute();
try { try {
logFile.write("\nnoShortendElements: " + unifyTask.noShortendElements +"\n"); unifyContext.logFile.write("\nnoShortendElements: " + unifyTask.noShortendElements +"\n");
logFile.flush(); // logFile.flush();
} }
catch (IOException e) { catch (IOException e) {
System.err.println("no log-File"); System.err.println("no log-File");
@@ -118,4 +82,13 @@ public class TypeUnify {
return res; return res;
} }
private ForkJoinPool createThreadPool() {
return new ForkJoinPool(
Runtime.getRuntime().availableProcessors(),
ForkJoinPool.defaultForkJoinWorkerThreadFactory,
null,
false // do not use asyncMode (FIFO), as we want smaller tasks to complete first -> Improves locality and cuts small branches first
);
}
} }

View File

@@ -19,47 +19,43 @@ public class TypeUnify2Task extends TypeUnifyTask {
Set<Set<UnifyPair>> setToFlatten; Set<Set<UnifyPair>> setToFlatten;
Set<UnifyPair> methodSignatureConstraintUebergabe; Set<UnifyPair> methodSignatureConstraintUebergabe;
public TypeUnify2Task(Set<Set<UnifyPair>> setToFlatten, Set<UnifyPair> eq, List<Set<Constraint<UnifyPair>>> oderConstraints, Set<UnifyPair> nextSetElement, IFiniteClosure fc, boolean parallel, Writer logFile, Boolean log, int rekTiefe, UnifyResultModel urm, UnifyTaskModel usedTasks, Set<UnifyPair> methodSignatureConstraintUebergabe) { public TypeUnify2Task(Set<Set<UnifyPair>> setToFlatten, Set<UnifyPair> eq, List<Set<Constraint<UnifyPair>>> oderConstraints, Set<UnifyPair> nextSetElement, IFiniteClosure fc, UnifyContext context, int rekTiefe, Set<UnifyPair> methodSignatureConstraintUebergabe) {
super(eq, oderConstraints, fc, parallel, logFile, log, rekTiefe, urm, usedTasks); super(eq, oderConstraints, fc, context, rekTiefe);
this.setToFlatten = setToFlatten; this.setToFlatten = setToFlatten;
this.nextSetElement = nextSetElement; this.nextSetElement = nextSetElement;
this.methodSignatureConstraintUebergabe = methodSignatureConstraintUebergabe; this.methodSignatureConstraintUebergabe = methodSignatureConstraintUebergabe;
} }
Set<UnifyPair> getNextSetElement() { public Set<UnifyPair> getNextSetElement() {
return nextSetElement; return nextSetElement;
} }
@Override @Override
protected Set<Set<UnifyPair>> compute() { public Set<Set<UnifyPair>> compute() {
if (one) { if (one) {
System.out.println("two"); System.out.println("two");
} }
one = true; one = true;
Set<Set<UnifyPair>> res = unify2(setToFlatten, eq, oderConstraintsField, fc, parallel, rekTiefeField, methodSignatureConstraintUebergabe); Set<Set<UnifyPair>> res = unify2(setToFlatten, eq, oderConstraintsField, fc, context.isParallel(), rekTiefeField, methodSignatureConstraintUebergabe);
/*if (isUndefinedPairSetSet(res)) { /*if (isUndefinedPairSetSet(res)) {
return new HashSet<>(); } return new HashSet<>(); }
else else
*/ */
//writeLog("xxx"); //writeLog("xxx");
//noOfThread--; //noOfThread--;
synchronized (usedTasks) {
if (this.myIsCancelled()) { if (this.myIsCancelled()) {
return new HashSet<>(); return new HashSet<>();
} } else {
else {
return res; return res;
} }
} }
}
public void closeLogFile() { public void closeLogFile() {
try { try {
logFile.close(); context.logFile.close();
} } catch (IOException ioE) {
catch (IOException ioE) { System.err.println("no log-File");
System.err.println("no log-File" + thNo);
} }
} }

View File

@@ -0,0 +1,188 @@
package de.dhbwstuttgart.typeinference.unify;
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 java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* A collection of capsuled (and thus static) functions to split up large algorithms in TypeUnifyTask
*/
public class TypeUnifyTaskHelper {
/**
* Filter all topLevelSets for those with a single element that contain only one pair:
* a <. theta,
* theta <. a or
* a =. theta
*/
public static Set<Set<UnifyPair>> getSingleElementSets(ArrayList<Set<? extends Set<UnifyPair>>> topLevelSets) {
return topLevelSets.stream()
.filter(x -> x.size() == 1)
.map(y -> y.stream().findFirst().get()).collect(Collectors.toSet());
}
/**
* Varianzbestimmung Anfang
* Oderconstraint, wenn entweder kein Basepair oder unterschiedliche Basepairs => oderConstraint = true;
* Varianz = 1 => Argumentvariable
* Varianz = -1 => Rückgabevariable
* Varianz = 0 => unklar
* Varianz = 2 => Operatoren oderConstraints
*/
public static int calculateVariance(List<Set<UnifyPair>> nextSetasList) {
Optional<Integer> xi = nextSetasList.stream().map(x -> x.stream().filter(y -> (y.getLhsType() instanceof PlaceholderType && !(y.getRhsType() instanceof PlaceholderType)))
.filter(z -> ((PlaceholderType) z.getLhsType()).getVariance() != 0)
.map(c -> ((PlaceholderType) c.getLhsType()).getVariance())
.reduce((a, b) -> {
if (a == b) return a;
else return 0;
})) //2 kommt insbesondere bei Oder-Constraints vor
.filter(d -> d.isPresent())
.map(e -> e.get())
.findAny();
return xi.orElse(0);
}
/**
*
*/
public static int calculateOderConstraintVariance(List<Set<UnifyPair>> nextSetAsList) {
Optional<Integer> optVariance =
nextSetAsList
.getFirst()
.stream()
.filter(x -> x.getGroundBasePair().getLhsType() instanceof PlaceholderType &&
!(x.getRhsType() instanceof PlaceholderType) &&
x.getPairOp() == PairOperator.EQUALSDOT)
.map(x ->
((PlaceholderType) x.getGroundBasePair().getLhsType()).getVariance())
.reduce((n, m) -> (n != 0) ? n : m);
//Fuer Operatorenaufrufe wird variance auf 2 gesetzt.
//da kein Receiver existiert also kein x.getGroundBasePair().getLhsType() instanceof PlaceholderType
//Bei Varianz = 2 werden alle Elemente des Kartesischen Produkts abgearbeitet
return optVariance.orElse(2);
}
/**
* Find the first occurrence (if any) of a UnifyPair with operator EQUALSDOT while having
* one side equal to its base pair counterpart
*/
public static Optional<UnifyPair> findEqualityConstrainedUnifyPair(Set<UnifyPair> nextSetElement) {
return nextSetElement.stream().filter(x ->
x.getPairOp()
.equals(PairOperator.EQUALSDOT))
.filter(x -> //Sicherstellen, dass bei a = ty a auch wirklich die gesuchte Typvariable ist
x.getLhsType()
.equals(x.getBasePair().getLhsType()) ||
x.getLhsType()
.equals(x.getBasePair().getRhsType())
).findFirst();
}
/**
* Find all unifyPairs, that associate the identified type variable of origPair with any concrete type. That means:
* If "a = type" is in origPair, then we get all UnifyPairs that contain either "a < typeA" or "typeB < a"
*/
public static Set<UnifyPair> findConstraintsWithSameTVAssociation(UnifyPair origPair, Set<Set<UnifyPair>> singleElementSets) {
UnifyType tyVar = origPair.getLhsType();
if (!(tyVar instanceof PlaceholderType)) {
tyVar = origPair.getRhsType();
}
UnifyType tyVarEF = tyVar;
return singleElementSets.stream()
.map(xx ->
xx.iterator().next())
.filter(x ->
(x.getLhsType().equals(tyVarEF) && !(x.getRhsType() instanceof PlaceholderType))
||
(x.getRhsType().equals(tyVarEF) && !(x.getLhsType() instanceof PlaceholderType))
)
.collect(Collectors.toCollection(HashSet::new));
}
/**
*
*/
public static boolean doesFirstNextSetHasSameBase(List<Set<UnifyPair>> nextSetAsList) {
if (nextSetAsList.isEmpty()) {
return false;
}
UnifyPair firstBasePair = null;
for (var unifyPair : nextSetAsList.getFirst().stream().toList()) {
var basePair = unifyPair.getBasePair();
// if any base pair is null, there is NOT always the same base!
if (basePair == null) {
return false;
}
if (firstBasePair == null) {
firstBasePair = basePair;
}
else if (!basePair.equals(firstBasePair)) {
return false;
}
}
return true;
}
/**
* Extracts data from every element in the nested lists of results. What data depends on the given
* extractor function
*/
public static Set<UnifyPair> collectFromThreadResult (
Set<Set<UnifyPair>> currentThreadResult,
Function<UnifyPair, Set<UnifyPair>> extractor
) {
return currentThreadResult.stream()
.map(b ->
b.stream()
.map(extractor)
.reduce((y, z) -> {
y.addAll(z);
return y;
})
.orElse(new HashSet<>()))
.reduce((y, z) -> {
y.addAll(z);
return y;
})
.orElse(new HashSet<>());
}
/**
* Extract a list of PlaceholderTypes from a set of pairs, such that each resulting element:
* - Is the LHS of a pair
* - Is a PlaceholderType
* - has a basePair Side that is a PlaceholderType with the same name
*/
public static List<PlaceholderType> extractMatchingPlaceholderTypes(Set<UnifyPair> pairs) {
return pairs.stream()
.filter(x -> {
UnifyType lhs = x.getLhsType();
UnifyType baseLhs = x.getBasePair().getLhsType();
UnifyType baseRhs = x.getBasePair().getRhsType();
return (lhs instanceof PlaceholderType) &&
((baseLhs instanceof PlaceholderType && lhs.getName().equals(baseLhs.getName())) ||
(baseRhs instanceof PlaceholderType && lhs.getName().equals(baseRhs.getName())));
})
.map(x -> (PlaceholderType) x.getLhsType())
.collect(Collectors.toCollection(ArrayList::new));
}
}

View File

@@ -0,0 +1,39 @@
package de.dhbwstuttgart.typeinference.unify;
import java.io.Writer;
public class UnifyContext {
final Writer logFile;
final Boolean log;
final Boolean parallel;
final UnifyResultModel resultModel;
volatile UnifyTaskModel usedTasks;
public UnifyContext(
Writer logFile,
Boolean log,
Boolean parallel,
UnifyResultModel resultModel,
UnifyTaskModel usedTasks
) {
this.logFile = logFile;
this.log = log;
this.parallel = parallel;
this.resultModel = resultModel;
this.usedTasks = usedTasks;
}
public UnifyContext newWithLogFile(Writer logFile) {
return new UnifyContext(logFile, log, parallel, resultModel, usedTasks);
}
public UnifyContext newWithParallel(boolean parallel) {
return new UnifyContext(logFile, log, parallel, resultModel, usedTasks);
}
public Boolean isParallel() {
return parallel;
}
}

View File

@@ -36,14 +36,14 @@ public class UnifyResultModel {
listeners.remove(listenerToRemove); listeners.remove(listenerToRemove);
} }
public void notify(Set<Set<UnifyPair>> eqPrimePrimeSet) { public void notify(Set<Set<UnifyPair>> eqPrimePrimeSet, UnifyContext context) {
Set<Set<UnifyPair>> eqPrimePrimeSetRet = eqPrimePrimeSet.stream().map(x -> { Set<Set<UnifyPair>> eqPrimePrimeSetRet = eqPrimePrimeSet.stream().map(x -> {
Optional<Set<UnifyPair>> res = new RuleSet().subst(x.stream().map(y -> { Optional<Set<UnifyPair>> res = new RuleSet().subst(x.stream().map(y -> {
if (y.getPairOp() == PairOperator.SMALLERDOTWC) y.setPairOp(PairOperator.EQUALSDOT); if (y.getPairOp() == PairOperator.SMALLERDOTWC) y.setPairOp(PairOperator.EQUALSDOT);
return y; //alle Paare a <.? b erden durch a =. b ersetzt return y; //alle Paare a <.? b erden durch a =. b ersetzt
}).collect(Collectors.toCollection(HashSet::new))); }).collect(Collectors.toCollection(HashSet::new)));
if (res.isPresent()) {//wenn subst ein Erg liefert wurde was veraendert if (res.isPresent()) {//wenn subst ein Erg liefert wurde was veraendert
return new TypeUnifyTask().applyTypeUnificationRules(res.get(), fc); return new TypeUnifyTask(context).applyTypeUnificationRules(res.get(), fc);
} }
else return x; //wenn nichts veraendert wurde wird x zurueckgegeben else return x; //wenn nichts veraendert wurde wird x zurueckgegeben
}).collect(Collectors.toCollection(HashSet::new)); }).collect(Collectors.toCollection(HashSet::new));

View File

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

View File

@@ -0,0 +1,211 @@
package de.dhbwstuttgart.typeinference.unify.cartesianproduct;
import de.dhbwstuttgart.exceptions.UnifyCancelException;
import de.dhbwstuttgart.typeinference.constraints.Constraint;
import de.dhbwstuttgart.typeinference.unify.TypeUnify2Task;
import de.dhbwstuttgart.typeinference.unify.TypeUnifyTask;
import de.dhbwstuttgart.typeinference.unify.UnifyContext;
import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure;
import de.dhbwstuttgart.typeinference.unify.model.UnifyPair;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
public class Variance1Case extends VarianceCase {
protected final int variance = 1;
protected Variance1Case(boolean isOderConstraint, TypeUnifyTask typeUnifyTask, UnifyContext context) {
super(isOderConstraint, typeUnifyTask, context);
}
@Override
public void selectNextData(
TypeUnifyTask typeUnifyTask,
List<Set<UnifyPair>> nextSetAsList,
Optional<UnifyPair> optOrigPair
) {
a = typeUnifyTask.oup.max(nextSetAsList.iterator());
writeLog("Max: a in " + variance + " " + a);
nextSetAsList.remove(a);
if (this.isOderConstraint) {
nextSetasListOderConstraints.add(((Constraint<UnifyPair>) a).getExtendConstraint());
}
writeLog("nextSetasListOderConstraints 1: " + nextSetasListOderConstraints);
//Alle maximale Elemente in nextSetasListRest bestimmen
//nur für diese wird parallele Berechnung angestossen.
Set<UnifyPair> finalA = a;
nextSetasListRest = typeUnifyTask.oup.maxElements(
nextSetAsList.stream().filter(a_next -> typeUnifyTask.oup.compare(finalA, a_next) != 1).toList()
);
}
@Override
public Set<Set<UnifyPair>> computeParallel(
Set<Set<Set<UnifyPair>>> forkResults,
Set<Set<UnifyPair>> elems,
Set<UnifyPair> eq,
List<Set<Constraint<UnifyPair>>> oderConstraints,
IFiniteClosure fc,
int rekTiefe,
Set<UnifyPair> methodSignatureConstraint,
List<Set<UnifyPair>> nextSetAsList,
Set<UnifyPair> sameEqSet,
Set<Set<UnifyPair>> result,
Set<Set<UnifyPair>> aParDef
) {
Set<TypeUnify2Task> forks = new HashSet<>();
Set<UnifyPair> newEqOrig = new HashSet<>(eq);
Set<Set<UnifyPair>> newElemsOrig = new HashSet<>(elems);
List<Set<Constraint<UnifyPair>>> newOderConstraintsOrig = new ArrayList<>(oderConstraints);
newElemsOrig.add(a);
/* FORK ANFANG */
TypeUnify2Task forkOrig = new TypeUnify2Task(newElemsOrig, newEqOrig, newOderConstraintsOrig, a, fc, context, rekTiefe, methodSignatureConstraint);
//forks.add(forkOrig);
if (typeUnifyTask.myIsCancelled()) {
throw new UnifyCancelException();
}
/* FORK ENDE */
writeLog("a in " + variance + " " + a);
writeLog("nextSetasListRest: " + nextSetasListRest.toString());
while (!nextSetasListRest.isEmpty()) {
Set<UnifyPair> nSaL = nextSetasListRest.removeFirst();
nextSetAsList.remove(nSaL);
writeLog("1 RM" + nSaL.toString());
if (!this.isOderConstraint) {
//ueberpruefung ob zu a =. ty \in nSaL in sameEqSet ein Widerspruch besteht
if (!sameEqSet.isEmpty() && !typeUnifyTask.checkNoContradiction(nSaL, sameEqSet, result)) {
TypeUnifyTask.noShortendElements++;
continue;
}
} else {
nextSetasListOderConstraints.add(((Constraint<UnifyPair>) nSaL).getExtendConstraint());
}
Set<UnifyPair> newEq = new HashSet<>(eq);
Set<Set<UnifyPair>> newElems = new HashSet<>(elems);
List<Set<Constraint<UnifyPair>>> newOderConstraints = new ArrayList<>(oderConstraints);
newElems.add(nSaL);
TypeUnify2Task fork = new TypeUnify2Task(newElems, newEq, newOderConstraints, nSaL, fc, context, rekTiefe, new HashSet<>(methodSignatureConstraint));
forks.add(fork);
if (typeUnifyTask.myIsCancelled()) {
throw new UnifyCancelException();
}
fork.fork();
}
//currentThreadResult = unify2(newElemsOrig, newEqOrig, newOderConstraintsOrig, fc, parallel, rekTiefe);
/* FORK ANFANG */
Set<Set<UnifyPair>> currentThreadResult = forkOrig.compute();
if (typeUnifyTask.myIsCancelled()) {
throw new UnifyCancelException();
}
//noOfThread++;
forkOrig.writeLog("final Orig 1");
forkOrig.closeLogFile();
//Set<Set<UnifyPair>> fork_res = forkOrig.join();
//forkResults.add(fork_res);;
/* FORK ENDE */
for (TypeUnify2Task fork : forks) {
Set<Set<UnifyPair>> fork_res = fork.join();
if (typeUnifyTask.myIsCancelled()) {
throw new UnifyCancelException();
}
writeLog("fork_res: " + fork_res.toString());
writeLog(Boolean.valueOf((typeUnifyTask.isUndefinedPairSetSet(fork_res))).toString());
forkResults.add(fork_res);
if (!typeUnifyTask.isUndefinedPairSetSet(fork_res)) {
aParDef.add(fork.getNextSetElement());
}
fork.writeLog("final 1");
fork.closeLogFile();
}
//noOfThread++;
return currentThreadResult;
}
@Override
public void applyComputedResults(
Set<Set<UnifyPair>> result,
Set<Set<UnifyPair>> currentThreadResult,
Set<UnifyPair> compResult,
Set<UnifyPair> compRes
) {
int resOfCompare = typeUnifyTask.oup.compare(compResult, compRes);
if (resOfCompare == -1) {
writeLog("Geloescht result: " + result);
result.clear();
result.addAll(currentThreadResult);
}
else if (resOfCompare == 0) {
result.addAll(currentThreadResult);
}
else if (resOfCompare == 1) {
writeLog("Geloescht currentThreadResult: " + currentThreadResult);
//result = result;
}
}
@Override
public boolean eraseInvalidSets(
int rekTiefe,
Set<Set<UnifyPair>> aParDef,
List<Set<UnifyPair>> nextSetAsList
) {
// System.out.println("");
writeLog("a: " + rekTiefe + " variance: " + variance + a.toString());
writeLog("aParDef: " + aParDef.toString());
aParDef.add(a);
Iterator<Set<UnifyPair>> aParDefIt = aParDef.iterator();
if (this.isOderConstraint) {
nextSetAsList.removeAll(nextSetasListOderConstraints);
nextSetasListOderConstraints = new ArrayList<>();
writeLog("Removed: " + nextSetasListOderConstraints);
while (aParDefIt.hasNext()) {
Set<UnifyPair> a_new = aParDefIt.next();
List<Set<UnifyPair>> smallerSetasList = typeUnifyTask.oup.smallerThan(a_new, nextSetAsList);
writeLog("smallerSetasList: " + smallerSetasList);
List<Set<UnifyPair>> notInherited = smallerSetasList.stream()
.filter(x -> !((Constraint<UnifyPair>) x).isInherited() && !((Constraint<UnifyPair>) x).isImplemented())
.collect(Collectors.toCollection(ArrayList::new));
writeLog("notInherited: " + notInherited + "\n");
List<Set<UnifyPair>> notErased = new ArrayList<>();
notInherited.forEach(x -> {
notErased.addAll(typeUnifyTask.oup.smallerEqThan(x, smallerSetasList));
});
List<Set<UnifyPair>> erased = new ArrayList<>(smallerSetasList);
writeLog("notErased: " + notErased + "\n");
erased.removeAll(notErased);
nextSetAsList.removeAll(erased);
writeLog("Removed: " + erased);
writeLog("Not Removed: " + nextSetAsList);
}
} else {
while (aParDefIt.hasNext()) {
//nextSetasListIt = nextSetasList.iterator(); Sollte eingefuegt werden PL 2020-04-28
Set<UnifyPair> a_new = aParDefIt.next();
List<Set<UnifyPair>> erased = typeUnifyTask.oup.smallerEqThan(a_new, nextSetAsList);
nextSetAsList.removeAll(erased);
writeLog("Removed: " + erased);
writeLog("Not Removed: " + nextSetAsList);
}
}
return false;
}
}

View File

@@ -0,0 +1,137 @@
package de.dhbwstuttgart.typeinference.unify.cartesianproduct;
import de.dhbwstuttgart.exceptions.UnifyCancelException;
import de.dhbwstuttgart.typeinference.constraints.Constraint;
import de.dhbwstuttgart.typeinference.unify.TypeUnify2Task;
import de.dhbwstuttgart.typeinference.unify.TypeUnifyTask;
import de.dhbwstuttgart.typeinference.unify.UnifyContext;
import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure;
import de.dhbwstuttgart.typeinference.unify.model.UnifyPair;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
public class Variance2Case extends VarianceCase {
protected final int variance = 2;
protected Variance2Case(boolean isOderConstraint, TypeUnifyTask typeUnifyTask, UnifyContext context) {
super(isOderConstraint, typeUnifyTask, context);
}
@Override
public void selectNextData(
TypeUnifyTask typeUnifyTask,
List<Set<UnifyPair>> nextSetAsList,
Optional<UnifyPair> optOrigPair
) {
a = nextSetAsList.removeFirst();
//Fuer alle Elemente wird parallele Berechnung angestossen.
nextSetasListRest = new ArrayList<>(nextSetAsList);
}
@Override
public Set<Set<UnifyPair>> computeParallel(
Set<Set<Set<UnifyPair>>> forkResults,
Set<Set<UnifyPair>> elems,
Set<UnifyPair> eq,
List<Set<Constraint<UnifyPair>>> oderConstraints,
IFiniteClosure fc,
int rekTiefe,
Set<UnifyPair> methodSignatureConstraint,
List<Set<UnifyPair>> nextSetAsList,
Set<UnifyPair> sameEqSet,
Set<Set<UnifyPair>> result,
Set<Set<UnifyPair>> aParDef
) {
writeLog("var2einstieg");
Set<TypeUnify2Task> forks = new HashSet<>();
Set<UnifyPair> newEqOrig = new HashSet<>(eq);
Set<Set<UnifyPair>> newElemsOrig = new HashSet<>(elems);
List<Set<Constraint<UnifyPair>>> newOderConstraintsOrig = new ArrayList<>(oderConstraints);
newElemsOrig.add(a);
/* FORK ANFANG */
TypeUnify2Task forkOrig = new TypeUnify2Task(newElemsOrig, newEqOrig, newOderConstraintsOrig, a, fc, context, rekTiefe, new HashSet<>(methodSignatureConstraint));
//forks.add(forkOrig);
if (typeUnifyTask.myIsCancelled()) {
throw new UnifyCancelException();
}
/* FORK ENDE */
writeLog("a in " + variance + " " + a);
writeLog("nextSetasListRest: " + nextSetasListRest.toString());
//Fuer parallele Berechnung der Oder-Contraints wird methodSignature kopiert
//und jeweils die methodSignature von a bzw. nSaL wieder gelöscht, wenn es keine Lösung ist.
Set<UnifyPair> methodSignatureConstraintForParallel = new HashSet<>(methodSignatureConstraint);
Set<UnifyPair> nSaL = a;
while (!nextSetasListRest.isEmpty()) {
methodSignatureConstraintForParallel.removeAll(((Constraint<UnifyPair>) nSaL).getmethodSignatureConstraint());
nSaL = nextSetasListRest.removeFirst();
nextSetAsList.remove(nSaL); //PL einkommentiert 20-02-03
methodSignatureConstraintForParallel.addAll(((Constraint<UnifyPair>) nSaL).getmethodSignatureConstraint());
Set<UnifyPair> newEq = new HashSet<>(eq);
Set<Set<UnifyPair>> newElems = new HashSet<>(elems);
List<Set<Constraint<UnifyPair>>> newOderConstraints = new ArrayList<>(oderConstraints);
newElems.add(nSaL);
TypeUnify2Task fork = new TypeUnify2Task(newElems, newEq, newOderConstraints, nSaL, fc, context, rekTiefe, new HashSet<>(methodSignatureConstraintForParallel));
forks.add(fork);
if (typeUnifyTask.myIsCancelled()) {
throw new UnifyCancelException();
}
fork.fork();
}
//currentThreadResult = unify2(newElemsOrig, newEqOrig, newOderConstraintsOrig, fc, parallel, rekTiefe);
/* FORK ANFANG */
Set<Set<UnifyPair>> currentThreadResult = forkOrig.compute();
if (typeUnifyTask.myIsCancelled()) {
throw new UnifyCancelException();
}
//noOfThread++;
forkOrig.writeLog("final Orig 2");
forkOrig.closeLogFile();
//Set<Set<UnifyPair>> fork_res = forkOrig.join();
//forkResults.add(fork_res); //vermutlich falsch
/* FORK ENDE */
for (TypeUnify2Task fork : forks) {
Set<Set<UnifyPair>> fork_res = fork.join();
if (typeUnifyTask.myIsCancelled()) {
throw new UnifyCancelException();
}
forkResults.add(fork_res);
fork.writeLog("final 2");
fork.closeLogFile();
}
//noOfThread++;
return currentThreadResult;
}
@Override
public void applyComputedResults(
Set<Set<UnifyPair>> result,
Set<Set<UnifyPair>> currentThreadResult,
Set<UnifyPair> compResult,
Set<UnifyPair> compRes
) {
// Nothing
}
@Override
public boolean eraseInvalidSets(
int rekTiefe,
Set<Set<UnifyPair>> aParDef,
List<Set<UnifyPair>> nextSetAsList
) {
// Nothing
return false;
}
}

View File

@@ -0,0 +1,110 @@
package de.dhbwstuttgart.typeinference.unify.cartesianproduct;
import de.dhbwstuttgart.typeinference.constraints.Constraint;
import de.dhbwstuttgart.typeinference.unify.TypeUnifyTask;
import de.dhbwstuttgart.typeinference.unify.UnifyContext;
import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure;
import de.dhbwstuttgart.typeinference.unify.model.UnifyPair;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Set;
public abstract class VarianceCase {
public static VarianceCase createFromVariance(int variance, boolean isOderConstraint, TypeUnifyTask typeUnifyTask, UnifyContext context) {
return switch (variance) {
case 0 -> new Variance0Case(isOderConstraint, typeUnifyTask, context);
case 1 -> new Variance1Case(isOderConstraint, typeUnifyTask, context);
case -1 -> new VarianceM1Case(isOderConstraint, typeUnifyTask, context);
case 2 -> new Variance2Case(isOderConstraint, typeUnifyTask, context);
default -> throw new RuntimeException("Invalid variance: " + variance);
};
}
protected final boolean isOderConstraint;
protected final TypeUnifyTask typeUnifyTask;
protected final UnifyContext context;
/**
* Aktueller Fall
*/
public Set<UnifyPair> a;
/**
* Liste der Faelle für die parallele Verarbeitung
* Enthaelt Elemente, die nicht in Relation zu aktuellem Fall in der
* Variablen a stehen. Diese muesse auf alle Faelle bearbeitet werden,
* Deshalb wird ihre Berechnung parallel angestossen.
*/
public List<Set<UnifyPair>> nextSetasListRest = new ArrayList<>();
/**
* Liste der Faelle, bei dem Receiver jeweils "? extends" enthaelt bzw. nicht enthaelt
* In der Regel ist dies genau ein Element
* Dieses Element wird später aus nextSetasList geloescht, wenn das jeweils andere Element zum Erfolg
* gefuehrt hat.
*/
public List<Set<UnifyPair>> nextSetasListOderConstraints = new ArrayList<>();
protected VarianceCase(boolean isOderConstraint, TypeUnifyTask typeUnifyTask, UnifyContext context) {
this.isOderConstraint = isOderConstraint;
this.typeUnifyTask = typeUnifyTask;
this.context = context;
}
/**
* Selects values for the next iteration in the run method:
* - a : The element to ???
* - nextSetAsList: The list of cases that have no relation to the selected a and will have to be worked on
* - nextSetasListOderConstraints: The list of cases of which the receiver contains "? extends", typically one element
*/
public abstract void selectNextData(
TypeUnifyTask typeUnifyTask,
List<Set<UnifyPair>> nextSetAsList,
Optional<UnifyPair> optOrigPair
);
/**
*
*/
public abstract Set<Set<UnifyPair>> computeParallel(
Set<Set<Set<UnifyPair>>> forkResults,
Set<Set<UnifyPair>> elems,
Set<UnifyPair> eq,
List<Set<Constraint<UnifyPair>>> oderConstraints,
IFiniteClosure fc,
int rekTiefe,
Set<UnifyPair> methodSignatureConstraint,
List<Set<UnifyPair>> nextSetAsList,
Set<UnifyPair> sameEqSet,
Set<Set<UnifyPair>> result,
Set<Set<UnifyPair>> aParDef
);
/**
*
*/
public abstract void applyComputedResults(
Set<Set<UnifyPair>> result,
Set<Set<UnifyPair>> currentThreadResult,
Set<UnifyPair> compResult,
Set<UnifyPair> compRes
);
/**
*
* @return If the current iteration should be broken out of
*/
public abstract boolean eraseInvalidSets(
int rekTiefe,
Set<Set<UnifyPair>> aParDef,
List<Set<UnifyPair>> nextSetAsList
);
protected void writeLog(String s) {
// TODO
}
}

View File

@@ -0,0 +1,231 @@
package de.dhbwstuttgart.typeinference.unify.cartesianproduct;
import de.dhbwstuttgart.exceptions.UnifyCancelException;
import de.dhbwstuttgart.typeinference.constraints.Constraint;
import de.dhbwstuttgart.typeinference.unify.TypeUnify2Task;
import de.dhbwstuttgart.typeinference.unify.TypeUnifyTask;
import de.dhbwstuttgart.typeinference.unify.UnifyContext;
import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure;
import de.dhbwstuttgart.typeinference.unify.model.UnifyPair;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
public class VarianceM1Case extends VarianceCase {
protected final int variance = -1;
protected VarianceM1Case(boolean isOderConstraint, TypeUnifyTask typeUnifyTask, UnifyContext context) {
super(isOderConstraint, typeUnifyTask, context);
}
@Override
public void selectNextData(
TypeUnifyTask typeUnifyTask,
List<Set<UnifyPair>> nextSetAsList,
Optional<UnifyPair> optOrigPair
) {
a = typeUnifyTask.oup.min(nextSetAsList.iterator());
writeLog("Min: a in " + variance + " " + a);
if (this.isOderConstraint) {
nextSetasListOderConstraints.add(((Constraint<UnifyPair>) a).getExtendConstraint());
}
writeLog("nextSetasListOderConstraints -1: " + nextSetasListOderConstraints);
nextSetAsList.remove(a);
//Alle minimalen Elemente in nextSetasListRest bestimmen
//nur für diese wird parallele Berechnung angestossen.
Set<UnifyPair> finalA = a;
nextSetasListRest = typeUnifyTask.oup.minElements(
nextSetAsList.stream().filter(a_next -> typeUnifyTask.oup.compare(finalA, a_next) != -1).toList()
);
}
@Override
public Set<Set<UnifyPair>> computeParallel(
Set<Set<Set<UnifyPair>>> forkResults,
Set<Set<UnifyPair>> elems,
Set<UnifyPair> eq,
List<Set<Constraint<UnifyPair>>> oderConstraints,
IFiniteClosure fc,
int rekTiefe,
Set<UnifyPair> methodSignatureConstraint,
List<Set<UnifyPair>> nextSetAsList,
Set<UnifyPair> sameEqSet,
Set<Set<UnifyPair>> result,
Set<Set<UnifyPair>> aParDef
) {
Set<TypeUnify2Task> forks = new HashSet<>();
Set<UnifyPair> newEqOrig = new HashSet<>(eq);
Set<Set<UnifyPair>> newElemsOrig = new HashSet<>(elems);
List<Set<Constraint<UnifyPair>>> newOderConstraintsOrig = new ArrayList<>(oderConstraints);
newElemsOrig.add(a);
/* FORK ANFANG */
TypeUnify2Task forkOrig = new TypeUnify2Task(newElemsOrig, newEqOrig, newOderConstraintsOrig, a, fc, context, rekTiefe, new HashSet<>(methodSignatureConstraint));
//forks.add(forkOrig);
if (typeUnifyTask.myIsCancelled()) {
throw new UnifyCancelException();
}
/* FORK ENDE */
writeLog("a in " + variance + " " + a);
writeLog("nextSetasListRest: " + nextSetasListRest.toString());
while (!nextSetasListRest.isEmpty()) {
Set<UnifyPair> nSaL = nextSetasListRest.removeFirst();
nextSetAsList.remove(nSaL);
writeLog("-1 RM" + nSaL.toString());
if (!this.isOderConstraint) {
//ueberpruefung ob zu a =. ty \in nSaL in sameEqSet ein Widerspruch besteht
if (!sameEqSet.isEmpty() && !typeUnifyTask.checkNoContradiction(nSaL, sameEqSet, result)) {
TypeUnifyTask.noShortendElements++;
continue;
}
} else {
nextSetasListOderConstraints.add(((Constraint<UnifyPair>) nSaL).getExtendConstraint());
}
Set<UnifyPair> newEq = new HashSet<>(eq);
Set<Set<UnifyPair>> newElems = new HashSet<>(elems);
List<Set<Constraint<UnifyPair>>> newOderConstraints = new ArrayList<>(oderConstraints);
newElems.add(nSaL);
TypeUnify2Task fork = new TypeUnify2Task(newElems, newEq, newOderConstraints, nSaL, fc, context, rekTiefe, new HashSet<>(methodSignatureConstraint));
forks.add(fork);
if (typeUnifyTask.myIsCancelled()) {
throw new UnifyCancelException();
}
fork.fork();
}
//currentThreadResult = unify2(newElemsOrig, newEqOrig, newOderConstraintsOrig, fc, parallel, rekTiefe);
/* FORK ANFANG */
Set<Set<UnifyPair>> currentThreadResult = forkOrig.compute();
if (typeUnifyTask.myIsCancelled()) {
throw new UnifyCancelException();
}
//noOfThread++;
forkOrig.writeLog("final Orig -1");
forkOrig.closeLogFile();
//Set<Set<UnifyPair>> fork_res = forkOrig.join();
//forkResults.add(fork_res);
/* FORK ENDE */
for (TypeUnify2Task fork : forks) {
Set<Set<UnifyPair>> fork_res = fork.join();
if (typeUnifyTask.myIsCancelled()) {
throw new UnifyCancelException();
}
//noOfThread++;
//noOfThread--; an das Ende von compute verschoben
writeLog("fork_res: " + fork_res.toString());
writeLog(Boolean.valueOf((typeUnifyTask.isUndefinedPairSetSet(fork_res))).toString());
forkResults.add(fork_res);
if (!typeUnifyTask.isUndefinedPairSetSet(fork_res)) {
aParDef.add(fork.getNextSetElement());
}
fork.writeLog("final -1");
fork.closeLogFile();
}
//noOfThread++;
return currentThreadResult;
}
@Override
public void applyComputedResults(
Set<Set<UnifyPair>> result,
Set<Set<UnifyPair>> currentThreadResult,
Set<UnifyPair> compResult,
Set<UnifyPair> compRes
) {
int resOfCompare = typeUnifyTask.oup.compare(compResult, compRes);
if (resOfCompare == 1) {
writeLog("Geloescht result: " + result);
result.clear();
result.addAll(currentThreadResult);
} else if (resOfCompare == 0) {
result.addAll(currentThreadResult);
} else if (resOfCompare == -1) {
writeLog("Geloescht currentThreadResult: " + currentThreadResult);
//result = result;
}
}
@Override
public boolean eraseInvalidSets(
int rekTiefe,
Set<Set<UnifyPair>> aParDef,
List<Set<UnifyPair>> nextSetAsList
) {
// System.out.println("");
writeLog("a: " + rekTiefe + " variance: " + variance + a.toString());
writeLog("aParDef: " + aParDef.toString());
aParDef.add(a);
Iterator<Set<UnifyPair>> aParDefIt = aParDef.iterator();
if (this.isOderConstraint) {
nextSetAsList.removeAll(nextSetasListOderConstraints);
writeLog("Removed: " + nextSetasListOderConstraints);
nextSetasListOderConstraints = new ArrayList<>();
while (aParDefIt.hasNext()) {
Set<UnifyPair> a_new = aParDefIt.next();
List<Set<UnifyPair>> greaterSetasList = typeUnifyTask.oup.greaterThan(a_new, nextSetAsList);
//a_new muss hingefuegt werden, wenn es nicht vererbt ist, dann wird es spaeter wieder geloescht
if (!((Constraint<UnifyPair>) a_new).isInherited()) {
greaterSetasList.add(a_new);
}
List<Set<UnifyPair>> notInherited = greaterSetasList.stream()
.filter(x -> !((Constraint<UnifyPair>) x).isInherited())
.collect(Collectors.toCollection(ArrayList::new));
List<Set<UnifyPair>> notErased = new ArrayList<>();
//Wenn x nicht vererbt ist, beginnt beim naechstgroesseren Element die naechste Ueberladung
notInherited.forEach(x -> {
notErased.addAll(typeUnifyTask.oup.greaterEqThan(x, greaterSetasList));
});
//das kleineste Element ist das Element von dem a_new geerbt hat
//muss deshalb geloescht werden
Iterator<Set<UnifyPair>> notErasedIt = notErased.iterator();
if (notErasedIt.hasNext()) {
Set<UnifyPair> min = typeUnifyTask.oup.min(notErasedIt);
notErased.remove(min);
notErased.remove(((Constraint<UnifyPair>) min).getExtendConstraint());
}
List<Set<UnifyPair>> erased = new ArrayList<>(greaterSetasList);
erased.removeAll(notErased);
nextSetAsList.removeAll(erased);
writeLog("Removed: " + erased);
writeLog("Not Removed: " + nextSetAsList);
}
} else {
while (aParDefIt.hasNext()) {
//nextSetasListIt = nextSetasList.iterator(); Sollte eingefuegt werden PL 2020-04-28
Set<UnifyPair> a_new = aParDefIt.next();
List<Set<UnifyPair>> erased = typeUnifyTask.oup.greaterEqThan(a_new, nextSetAsList);
nextSetAsList.removeAll(erased);
writeLog("Removed: " + erased);
writeLog("Not Removed: " + nextSetAsList);
}
}
return false;
}
}

View File

@@ -1,5 +1,6 @@
package de.dhbwstuttgart.typeinference.unify.interfaces; package de.dhbwstuttgart.typeinference.unify.interfaces;
import de.dhbwstuttgart.typeinference.unify.UnifyContext;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
import java.util.Set; import java.util.Set;
@@ -74,5 +75,5 @@ public interface IFiniteClosure {
public Set<UnifyType> getChildren(UnifyType t); public Set<UnifyType> getChildren(UnifyType t);
public Set<UnifyType> getAllTypesByName(String typeName); public Set<UnifyType> getAllTypesByName(String typeName);
public int compare(UnifyType rhsType, UnifyType rhsType2, PairOperator pairop); public int compare(UnifyType rhsType, UnifyType rhsType2, PairOperator pairop, UnifyContext context);
} }

View File

@@ -1,11 +1,19 @@
package de.dhbwstuttgart.typeinference.unify.model; package de.dhbwstuttgart.typeinference.unify.model;
import de.dhbwstuttgart.typeinference.unify.UnifyContext;
import java.io.FileWriter; import java.io.FileWriter;
import java.io.IOException; import java.io.IOException;
import java.io.Writer; import java.io.Writer;
import java.lang.reflect.Modifier; import java.lang.reflect.Modifier;
import java.sql.Array; import java.sql.Array;
import java.util.*; import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.function.BiFunction; import java.util.function.BiFunction;
import java.util.function.BinaryOperator; import java.util.function.BinaryOperator;
import java.util.function.Predicate; import java.util.function.Predicate;
@@ -33,21 +41,17 @@ import org.apache.commons.io.output.NullWriter;
/** /**
* The finite closure for the type unification * The finite closure for the type unification
*
* @author Florian Steurer * @author Florian Steurer
*/ */
public class FiniteClosure //extends Ordering<UnifyType> //entfernt PL 2018-12-11 public class FiniteClosure implements IFiniteClosure {
implements IFiniteClosure {
final JavaTXCompiler compiler; final JavaTXCompiler compiler;
Writer logFile; Writer logFile;
static Boolean log = false; static Boolean log = false;
public void setLogTrue() { public void setLogTrue() {
log = true; log = true;
} }
/** /**
* A map that maps every type to the node in the inheritance graph that contains that type. * A map that maps every type to the node in the inheritance graph that contains that type.
*/ */
@@ -84,7 +88,7 @@ public class FiniteClosure //extends Ordering<UnifyType> //entfernt PL 2018-12-1
inheritanceGraph = new HashMap<UnifyType, Node<UnifyType>>(); inheritanceGraph = new HashMap<UnifyType, Node<UnifyType>>();
// Build the transitive closure of the inheritance tree // Build the transitive closure of the inheritance tree
for (UnifyPair pair : pairs) { for(UnifyPair pair : pairs) {
/* /*
try { try {
@@ -96,7 +100,7 @@ public class FiniteClosure //extends Ordering<UnifyType> //entfernt PL 2018-12-1
} }
*/ */
if (pair.getPairOp() != PairOperator.SMALLER) if(pair.getPairOp() != PairOperator.SMALLER)
continue; continue;
//VERSUCH PL 18-02-06 //VERSUCH PL 18-02-06
@@ -105,11 +109,11 @@ public class FiniteClosure //extends Ordering<UnifyType> //entfernt PL 2018-12-1
//if (!pair.getLhsType().getTypeParams().arePlaceholders() //if (!pair.getLhsType().getTypeParams().arePlaceholders()
// && !pair.getRhsType().getTypeParams().arePlaceholders()) // && !pair.getRhsType().getTypeParams().arePlaceholders())
// continue; // continue;
; ;
// Add nodes if not already in the graph // Add nodes if not already in the graph
if (!inheritanceGraph.containsKey(pair.getLhsType())) if(!inheritanceGraph.containsKey(pair.getLhsType()))
inheritanceGraph.put(pair.getLhsType(), new Node<UnifyType>(pair.getLhsType())); inheritanceGraph.put(pair.getLhsType(), new Node<UnifyType>(pair.getLhsType()));
if (!inheritanceGraph.containsKey(pair.getRhsType())) if(!inheritanceGraph.containsKey(pair.getRhsType()))
inheritanceGraph.put(pair.getRhsType(), new Node<UnifyType>(pair.getRhsType())); inheritanceGraph.put(pair.getRhsType(), new Node<UnifyType>(pair.getRhsType()));
Node<UnifyType> childNode = inheritanceGraph.get(pair.getLhsType()); Node<UnifyType> childNode = inheritanceGraph.get(pair.getLhsType());
@@ -123,55 +127,14 @@ public class FiniteClosure //extends Ordering<UnifyType> //entfernt PL 2018-12-1
childNode.getDescendants().stream().forEach(x -> x.addPredecessor(parentNode)); childNode.getDescendants().stream().forEach(x -> x.addPredecessor(parentNode));
//PL eingefuegt 2020-05-07 File UnitTest InheritTest.java //PL eingefuegt 2020-05-07 File UnitTest InheritTest.java
this.inheritanceGraph.forEach((x, y) -> { this.inheritanceGraph.forEach((x,y) -> { if (y.getDescendants().contains(parentNode)) { y.addDescendant(childNode); y.addAllDescendant(childNode.getDescendants());};
if (y.getDescendants().contains(parentNode)) { if (y.getPredecessors().contains(childNode)) { y.addPredecessor(parentNode); y.addAllPredecessor(parentNode.getPredecessors());};} );
y.addDescendant(childNode);
y.addAllDescendant(childNode.getDescendants());
}
;
if (y.getPredecessors().contains(childNode)) {
y.addPredecessor(parentNode);
y.addAllPredecessor(parentNode.getPredecessors());
}
;
});
}
List<String> classesToKeep = new ArrayList<>(compiler.classRegistry.getAllClassNames().stream().map(JavaClassName::toString).toList());
classesToKeep.add("java.lang.Object");
classesToKeep.add("java.lang.Number");
classesToKeep.add("java.util.Collection");
classesToKeep.add("java.lang.Iterable");
//filter out all types not imported
Iterator<Map.Entry<UnifyType, Node<UnifyType>>> iterator = inheritanceGraph.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<UnifyType, Node<UnifyType>> entry = iterator.next();
var name = entry.getKey().getName();
if (!classesToKeep.contains(name)) {
iterator.remove();
} else {
Node<UnifyType> node = entry.getValue();
// Remove unwanted predecessors
node.getPredecessors().removeIf(pred ->
!classesToKeep.contains(pred.getContent().getName())
);
// Remove unwanted descendants
node.getDescendants().removeIf(desc ->
!classesToKeep.contains(desc.getContent().getName())
);
}
} }
// Build the alternative representation with strings as keys // Build the alternative representation with strings as keys
strInheritanceGraph = new HashMap<>(); strInheritanceGraph = new HashMap<>();
for (UnifyType key : inheritanceGraph.keySet()) { for(UnifyType key : inheritanceGraph.keySet()) {
if (!strInheritanceGraph.containsKey(key.getName())) if(!strInheritanceGraph.containsKey(key.getName()))
strInheritanceGraph.put(key.getName(), new HashSet<>()); strInheritanceGraph.put(key.getName(), new HashSet<>());
strInheritanceGraph.get(key.getName()).add(inheritanceGraph.get(key)); strInheritanceGraph.get(key.getName()).add(inheritanceGraph.get(key));
@@ -196,7 +159,6 @@ public class FiniteClosure //extends Ordering<UnifyType> //entfernt PL 2018-12-1
/** /**
* Returns all types of the finite closure that are subtypes of the argument. * Returns all types of the finite closure that are subtypes of the argument.
*
* @return The set of subtypes of the argument. * @return The set of subtypes of the argument.
*/ */
@Override @Override
@@ -208,10 +170,10 @@ public class FiniteClosure //extends Ordering<UnifyType> //entfernt PL 2018-12-1
return new HashSet<>(ret); return new HashSet<>(ret);
} }
if (type instanceof FunNType) if(type instanceof FunNType)
return computeSmallerFunN((FunNType) type, fBounded); return computeSmallerFunN((FunNType) type, fBounded);
Set<Pair<UnifyType, Set<UnifyType>>> ts = new HashSet<>(); Set<Pair<UnifyType,Set<UnifyType>>> ts = new HashSet<>();
ts.add(new Pair<>(type, fBounded)); ts.add(new Pair<>(type, fBounded));
Set<UnifyType> result = computeSmaller(ts); Set<UnifyType> result = computeSmaller(ts);
smallerHash.put(new hashKeyType(type), result); smallerHash.put(new hashKeyType(type), result);
@@ -229,47 +191,48 @@ public class FiniteClosure //extends Ordering<UnifyType> //entfernt PL 2018-12-1
/** /**
* Computes the smaller functions for every type except FunNTypes. * Computes the smaller functions for every type except FunNTypes.
*/ */
private Set<UnifyType> computeSmaller(Set<Pair<UnifyType, Set<UnifyType>>> types) { private Set<UnifyType> computeSmaller(Set<Pair<UnifyType,Set<UnifyType>>> types) {
Set<Pair<UnifyType, Set<UnifyType>>> result = new HashSet<>(); Set<Pair<UnifyType,Set<UnifyType>>> result = new HashSet<>();
//PL 18-02-05 Unifier durch Matcher ersetzt //PL 18-02-05 Unifier durch Matcher ersetzt
//IUnify unify = new MartelliMontanariUnify(); //IUnify unify = new MartelliMontanariUnify();
Match match = new Match(); Match match = new Match();
for (Pair<UnifyType, Set<UnifyType>> pt : types) { for(Pair<UnifyType,Set<UnifyType>> pt : types) {
UnifyType t = pt.getKey(); UnifyType t = pt.getKey();
Set<UnifyType> fBounded = pt.getValue().get(); Set<UnifyType> fBounded = pt.getValue().get();
// if T = T' then T <* T' // if T = T' then T <* T'
try { try {
result.add(new Pair<>(t, fBounded)); result.add(new Pair<>(t, fBounded));
} catch (StackOverflowError e) { }
System.out.println(""); catch (StackOverflowError e) {
// System.out.println("");
} }
// if C<...> <* C<...> then ... (third case in definition of <*) // if C<...> <* C<...> then ... (third case in definition of <*)
if (t.getTypeParams().size() > 0) { if(t.getTypeParams().size() > 0) {
ArrayList<Set<UnifyType>> paramCandidates = new ArrayList<>(); ArrayList<Set<UnifyType>> paramCandidates = new ArrayList<>();
for (int i = 0; i < t.getTypeParams().size(); i++) for (int i = 0; i < t.getTypeParams().size(); i++)
paramCandidates.add(smArg(t.getTypeParams().get(i), fBounded)); paramCandidates.add(smArg(t.getTypeParams().get(i), fBounded));
permuteParams(paramCandidates).forEach(x -> result.add(new Pair<>(t.setTypeParams(x), fBounded))); permuteParams(paramCandidates).forEach(x -> result.add(new Pair<>(t.setTypeParams(x), fBounded)));
} }
if (!strInheritanceGraph.containsKey(t.getName())) if(!strInheritanceGraph.containsKey(t.getName()))
continue; continue;
// if T <* T' then sigma(T) <* sigma(T') // if T <* T' then sigma(T) <* sigma(T')
Set<Node<UnifyType>> candidates = strInheritanceGraph.get(t.getName()); //cadidates= [???Node(java.util.Vector<java.util.Vector<java.lang.Integer>>)??? Set<Node<UnifyType>> candidates = strInheritanceGraph.get(t.getName()); //cadidates= [???Node(java.util.Vector<java.util.Vector<java.lang.Integer>>)???
// , Node(java.util.Vector<gen_hv>) // , Node(java.util.Vector<gen_hv>)
//] //]
for (Node<UnifyType> candidate : candidates) { for(Node<UnifyType> candidate : candidates) {
UnifyType theta2 = candidate.getContent(); UnifyType theta2 = candidate.getContent();
//PL 18-02-05 Unifier durch Matcher ersetzt ANFANG //PL 18-02-05 Unifier durch Matcher ersetzt ANFANG
ArrayList<UnifyPair> termList = new ArrayList<UnifyPair>(); ArrayList<UnifyPair> termList= new ArrayList<UnifyPair>();
termList.add(new UnifyPair(theta2, t, PairOperator.EQUALSDOT)); termList.add(new UnifyPair(theta2,t, PairOperator.EQUALSDOT));
Optional<Unifier> optSigma = match.match(termList); Optional<Unifier> optSigma = match.match(termList);
//PL 18-02-05 Unifier durch Matcher ersetzt ENDE //PL 18-02-05 Unifier durch Matcher ersetzt ENDE
if (!optSigma.isPresent()) if(!optSigma.isPresent())
continue; continue;
Unifier sigma = optSigma.get(); Unifier sigma = optSigma.get();
@@ -277,13 +240,13 @@ public class FiniteClosure //extends Ordering<UnifyType> //entfernt PL 2018-12-1
Set<UnifyType> theta1Set = candidate.getContentOfDescendants(); Set<UnifyType> theta1Set = candidate.getContentOfDescendants();
for (UnifyType theta1 : theta1Set) for(UnifyType theta1 : theta1Set)
result.add(new Pair<>(theta1.apply(sigma), fBounded)); result.add(new Pair<>(theta1.apply(sigma), fBounded));
} }
} }
HashSet<UnifyType> resut = result.stream().map(x -> x.getKey()).collect(Collectors.toCollection(HashSet::new)); HashSet<UnifyType> resut = result.stream().map(x -> x.getKey()).collect(Collectors.toCollection(HashSet::new));
if (resut.equals(types.stream().map(x -> x.getKey()).collect(Collectors.toCollection(HashSet::new)))) if(resut.equals(types.stream().map(x -> x.getKey()).collect(Collectors.toCollection(HashSet::new))))
return resut; return resut;
return computeSmaller(result); return computeSmaller(result);
} }
@@ -310,7 +273,6 @@ public class FiniteClosure //extends Ordering<UnifyType> //entfernt PL 2018-12-1
/** /**
* Returns all types of the finite closure that are supertypes of the argument. * Returns all types of the finite closure that are supertypes of the argument.
*
* @return The set of supertypes of the argument. * @return The set of supertypes of the argument.
*/ */
@Override @Override
@@ -323,19 +285,19 @@ public class FiniteClosure //extends Ordering<UnifyType> //entfernt PL 2018-12-1
} }
if (type instanceof FunNType) { if(type instanceof FunNType) {
return computeGreaterFunN((FunNType) type, fBounded); return computeGreaterFunN((FunNType) type, fBounded);
} }
Set<UnifyType> result = new HashSet<>(); Set<UnifyType> result = new HashSet<>();
Set<Pair<UnifyType, Set<UnifyType>>> PairResultFBounded = new HashSet<>(); Set<Pair<UnifyType,Set<UnifyType>>> PairResultFBounded = new HashSet<>();
Match match = new Match(); Match match = new Match();
// if T = T' then T <=* T' // if T = T' then T <=* T'
result.add(type); result.add(type);
if (!strInheritanceGraph.containsKey(type.getName())) if(!strInheritanceGraph.containsKey(type.getName()))
return result; return result;
// if T <* T' then sigma(T) <* sigma(T') // if T <* T' then sigma(T) <* sigma(T')
@@ -351,15 +313,15 @@ public class FiniteClosure //extends Ordering<UnifyType> //entfernt PL 2018-12-1
} }
*/ */
for (Node<UnifyType> candidate : candidates) { for(Node<UnifyType> candidate : candidates) {
UnifyType theta1 = candidate.getContent(); UnifyType theta1 = candidate.getContent();
//PL 18-04-05 Unifier durch Matcher ersetzt ANFANG //PL 18-04-05 Unifier durch Matcher ersetzt ANFANG
ArrayList<UnifyPair> termList = new ArrayList<UnifyPair>(); ArrayList<UnifyPair> termList= new ArrayList<UnifyPair>();
termList.add(new UnifyPair(theta1, type, PairOperator.EQUALSDOT, location)); termList.add(new UnifyPair(theta1,type, PairOperator.EQUALSDOT, location));
Optional<Unifier> optSigma = match.match(termList); Optional<Unifier> optSigma = match.match(termList);
//PL 18-04-05 Unifier durch Matcher ersetzt ENDE //PL 18-04-05 Unifier durch Matcher ersetzt ENDE
if (!optSigma.isPresent()) { if(!optSigma.isPresent()) {
continue; continue;
} }
Unifier sigma = optSigma.get(); Unifier sigma = optSigma.get();
@@ -369,7 +331,7 @@ public class FiniteClosure //extends Ordering<UnifyType> //entfernt PL 2018-12-1
fBoundedNew.add(theta1); fBoundedNew.add(theta1);
Set<UnifyType> theta2Set = candidate.getContentOfPredecessors(); Set<UnifyType> theta2Set = candidate.getContentOfPredecessors();
//System.out.println(""); //System.out.println("");
for (UnifyType theta2 : theta2Set) { for(UnifyType theta2 : theta2Set) {
result.add(theta2.apply(sigma)); result.add(theta2.apply(sigma));
PairResultFBounded.add(new Pair<>(theta2.apply(sigma), fBoundedNew)); PairResultFBounded.add(new Pair<>(theta2.apply(sigma), fBoundedNew));
} }
@@ -383,34 +345,35 @@ public class FiniteClosure //extends Ordering<UnifyType> //entfernt PL 2018-12-1
System.err.println("no LogFile"); System.err.println("no LogFile");
} }
*/ */
for (Pair<UnifyType, Set<UnifyType>> pt : PairResultFBounded) { for(Pair<UnifyType,Set<UnifyType>> pt : PairResultFBounded) {
UnifyType t = pt.getKey(); UnifyType t = pt.getKey();
Set<UnifyType> lfBounded = pt.getValue().get(); Set<UnifyType> lfBounded = pt.getValue().get();
// if C<...> <* C<...> then ... (third case in definition of <*) // if C<...> <* C<...> then ... (third case in definition of <*)
//TypeParams typeparams = t.getTypeParams(); //TypeParams typeparams = t.getTypeParams();
if (t.getTypeParams().size() > 0) { if(t.getTypeParams().size() > 0) {
ArrayList<Set<UnifyType>> paramCandidates = new ArrayList<>(); ArrayList<Set<UnifyType>> paramCandidates = new ArrayList<>();
for (int i = 0; i < t.getTypeParams().size(); i++) { for (int i = 0; i < t.getTypeParams().size(); i++) {
//UnifyType parai = t.getTypeParams().get(i); //UnifyType parai = t.getTypeParams().get(i);
int i_ef = i; int i_ef = i;
BiFunction<Boolean, UnifyType, Boolean> f = (x, y) -> BiFunction<Boolean,UnifyType,Boolean> f = (x,y) ->
{ {
ArrayList<UnifyPair> termList = new ArrayList<UnifyPair>(); ArrayList<UnifyPair> termList = new ArrayList<UnifyPair>();
termList.add(new UnifyPair(y, t.getTypeParams().get(i_ef), PairOperator.EQUALSDOT, location)); termList.add(new UnifyPair(y,t.getTypeParams().get(i_ef), PairOperator.EQUALSDOT, location));
return ((match.match(termList).isPresent()) || x); return ((match.match(termList).isPresent()) || x);
}; };
//if (parai.getName().equals("java.lang.Integer")) { //if (parai.getName().equals("java.lang.Integer")) {
// System.out.println(""); // System.out.println("");
//} //}
BinaryOperator<Boolean> bo = (a, b) -> (a || b); BinaryOperator<Boolean> bo = (a,b) -> (a || b);
if (lfBounded.stream().reduce(false, f, bo)) { if (lfBounded.stream().reduce(false,f,bo)) {
//F-Bounded Endlosrekursion //F-Bounded Endlosrekursion
HashSet<UnifyType> res = new HashSet<UnifyType>(); HashSet<UnifyType> res = new HashSet<UnifyType>();
paramCandidates.add(res); paramCandidates.add(res);
} else { }
paramCandidates.add(grArg(t.getTypeParams().get(i), new HashSet<>(fBounded))); else {
paramCandidates.add(grArg(t.getTypeParams().get(i), new HashSet<>(fBounded) ));
} }
} }
permuteParams(paramCandidates).forEach(x -> result.add(t.setTypeParams(x))); permuteParams(paramCandidates).forEach(x -> result.add(t.setTypeParams(x)));
@@ -550,7 +513,7 @@ public class FiniteClosure //extends Ordering<UnifyType> //entfernt PL 2018-12-1
Set<UnifyType> result = new HashSet<UnifyType>(); Set<UnifyType> result = new HashSet<UnifyType>();
result.add(type); result.add(type);
smaller(type, fBounded).forEach(x -> result.add(new SuperType(x))); smaller(type, fBounded).forEach(x -> result.add(new SuperType(x)));
greater(type, fBounded).forEach(x -> result.add(new ExtendsType(x))); greater(type,fBounded).forEach(x -> result.add(new ExtendsType(x)));
return result; return result;
} }
@@ -644,18 +607,18 @@ public class FiniteClosure //extends Ordering<UnifyType> //entfernt PL 2018-12-1
@Override @Override
public Set<UnifyType> getAllTypesByName(String typeName) { public Set<UnifyType> getAllTypesByName(String typeName) {
if (!strInheritanceGraph.containsKey(typeName)) if(!strInheritanceGraph.containsKey(typeName))
return new HashSet<>(); return new HashSet<>();
return strInheritanceGraph.get(typeName).stream().map(x -> x.getContent()).collect(Collectors.toCollection(HashSet::new)); return strInheritanceGraph.get(typeName).stream().map(x -> x.getContent()).collect(Collectors.toCollection(HashSet::new));
} }
@Override @Override
public Optional<UnifyType> getLeftHandedType(String typeName) { public Optional<UnifyType> getLeftHandedType(String typeName) {
if (!strInheritanceGraph.containsKey(typeName)) if(!strInheritanceGraph.containsKey(typeName))
return Optional.empty(); return Optional.empty();
for (UnifyPair pair : pairs) for(UnifyPair pair : pairs)
if (pair.getLhsType().getName().equals(typeName) && pair.getLhsType().typeParams.arePlaceholders()) if(pair.getLhsType().getName().equals(typeName) && pair.getLhsType().typeParams.arePlaceholders())
return Optional.of(pair.getLhsType()); return Optional.of(pair.getLhsType());
return Optional.empty(); return Optional.empty();
@@ -663,11 +626,11 @@ public class FiniteClosure //extends Ordering<UnifyType> //entfernt PL 2018-12-1
@Override @Override
public Optional<UnifyType> getRightHandedFunctionalInterfaceType(String typeName) { public Optional<UnifyType> getRightHandedFunctionalInterfaceType(String typeName) {
if (!strInheritanceGraph.containsKey(typeName)) if(!strInheritanceGraph.containsKey(typeName))
return Optional.empty(); return Optional.empty();
for (UnifyPair pair : pairs) for(UnifyPair pair : pairs)
if (pair.getRhsType().getName().equals(typeName)) if(pair.getRhsType().getName().equals(typeName))
return Optional.of(pair.getRhsType()); return Optional.of(pair.getRhsType());
return Optional.empty(); return Optional.empty();
@@ -675,7 +638,7 @@ public class FiniteClosure //extends Ordering<UnifyType> //entfernt PL 2018-12-1
@Override @Override
public Set<UnifyType> getAncestors(UnifyType t) { public Set<UnifyType> getAncestors(UnifyType t) {
if (!inheritanceGraph.containsKey(t)) if(!inheritanceGraph.containsKey(t))
return new HashSet<>(); return new HashSet<>();
Set<UnifyType> result = inheritanceGraph.get(t).getContentOfPredecessors(); Set<UnifyType> result = inheritanceGraph.get(t).getContentOfPredecessors();
result.add(t); result.add(t);
@@ -684,7 +647,7 @@ public class FiniteClosure //extends Ordering<UnifyType> //entfernt PL 2018-12-1
@Override @Override
public Set<UnifyType> getChildren(UnifyType t) { public Set<UnifyType> getChildren(UnifyType t) {
if (!inheritanceGraph.containsKey(t)) if(!inheritanceGraph.containsKey(t))
return new HashSet<>(); return new HashSet<>();
Set<UnifyType> result = inheritanceGraph.get(t).getContentOfDescendants(); Set<UnifyType> result = inheritanceGraph.get(t).getContentOfDescendants();
result.add(t); result.add(t);
@@ -693,7 +656,6 @@ public class FiniteClosure //extends Ordering<UnifyType> //entfernt PL 2018-12-1
/** /**
* Takes a set of candidates for each position and computes all possible permutations. * Takes a set of candidates for each position and computes all possible permutations.
*
* @param candidates The length of the list determines the number of type params. Each set * @param candidates The length of the list determines the number of type params. Each set
* contains the candidates for the corresponding position. * contains the candidates for the corresponding position.
*/ */
@@ -705,7 +667,6 @@ public class FiniteClosure //extends Ordering<UnifyType> //entfernt PL 2018-12-1
/** /**
* Takes a set of candidates for each position and computes all possible permutations. * Takes a set of candidates for each position and computes all possible permutations.
*
* @param candidates The length of the list determines the number of type params. Each set * @param candidates The length of the list determines the number of type params. Each set
* contains the candidates for the corresponding position. * contains the candidates for the corresponding position.
* @param idx Idx for the current permutatiton. * @param idx Idx for the current permutatiton.
@@ -713,21 +674,21 @@ public class FiniteClosure //extends Ordering<UnifyType> //entfernt PL 2018-12-1
* @param current The permutation of type params that is currently explored * @param current The permutation of type params that is currently explored
*/ */
protected void permuteParams(ArrayList<Set<UnifyType>> candidates, int idx, Set<TypeParams> result, UnifyType[] current) { protected void permuteParams(ArrayList<Set<UnifyType>> candidates, int idx, Set<TypeParams> result, UnifyType[] current) {
if (candidates.size() == idx) { if(candidates.size() == idx) {
result.add(new TypeParams(Arrays.copyOf(current, current.length))); result.add(new TypeParams(Arrays.copyOf(current, current.length)));
return; return;
} }
Set<UnifyType> localCandidates = candidates.get(idx); Set<UnifyType> localCandidates = candidates.get(idx);
for (UnifyType t : localCandidates) { for(UnifyType t : localCandidates) {
current[idx] = t; current[idx] = t;
permuteParams(candidates, idx + 1, result, current); permuteParams(candidates, idx+1, result, current);
} }
} }
@Override @Override
public String toString() { public String toString(){
return this.inheritanceGraph.toString(); return this.inheritanceGraph.toString();
} }
@@ -737,13 +698,10 @@ public class FiniteClosure //extends Ordering<UnifyType> //entfernt PL 2018-12-1
} }
*/ */
public int compare(UnifyType left, UnifyType right, PairOperator pairop) { public int compare (UnifyType left, UnifyType right, PairOperator pairop, UnifyContext context) {
try { try {logFile.write("left: "+ left + " right: " + right + " pairop: " + pairop +"\n");} catch (IOException ie) {}
logFile.write("left: " + left + " right: " + right + " pairop: " + pairop + "\n"); // if (left.getName().equals("Matrix") || right.getName().equals("Matrix"))
} catch (IOException ie) { // System.out.println("");
}
if (left.getName().equals("Matrix") || right.getName().equals("Matrix"))
System.out.println("");
/* /*
pairop = PairOperator.SMALLERDOTWC; pairop = PairOperator.SMALLERDOTWC;
List<UnifyType> al = new ArrayList<>(); List<UnifyType> al = new ArrayList<>();
@@ -775,51 +733,51 @@ public class FiniteClosure //extends Ordering<UnifyType> //entfernt PL 2018-12-1
UnifyType ex; UnifyType ex;
if (left instanceof PlaceholderType) { if (left instanceof PlaceholderType) {
if ((right instanceof WildcardType) if ((right instanceof WildcardType)
&& ((ex = ((WildcardType) right).wildcardedType) instanceof PlaceholderType) && ((ex = ((WildcardType)right).wildcardedType) instanceof PlaceholderType)
&& ((PlaceholderType) left).getName().equals(((PlaceholderType) ex).getName())) {// a <.? ? extends a oder a <.? ? super a && ((PlaceholderType)left).getName().equals(((PlaceholderType)ex).getName())) {// a <.? ? extends a oder a <.? ? super a
return -1; return -1;
} else { }
else {
return 0; return 0;
} }
} }
if (right instanceof PlaceholderType) {//&& (left instanceof WildcardType)) {PL geloescht 2019-01-15 analog zu oben if (right instanceof PlaceholderType) {//&& (left instanceof WildcardType)) {PL geloescht 2019-01-15 analog zu oben
if ((left instanceof WildcardType) //PL eingefuegt 2019-01-15 analog zu oben if ((left instanceof WildcardType) //PL eingefuegt 2019-01-15 analog zu oben
&& ((ex = ((WildcardType) left).wildcardedType) instanceof PlaceholderType) && ((ex = ((WildcardType)left).wildcardedType) instanceof PlaceholderType)
&& ((PlaceholderType) right).getName().equals(((PlaceholderType) ex).getName())) {// ? extends a <. a oder ? super a <. a && ((PlaceholderType)right).getName().equals(((PlaceholderType)ex).getName())) {// ? extends a <. a oder ? super a <. a
return 1; return 1;
} else { }
else {
return 0; return 0;
} }
} }
UnifyPair up = new UnifyPair(left, right, pairop); UnifyPair up = new UnifyPair(left, right, pairop);
TypeUnifyTask unifyTask = new TypeUnifyTask(); TypeUnifyTask unifyTask = new TypeUnifyTask(context);
HashSet<UnifyPair> hs = new HashSet<>(); HashSet<UnifyPair> hs = new HashSet<>();
hs.add(up); hs.add(up);
Set<UnifyPair> smallerRes = unifyTask.applyTypeUnificationRules(hs, this); Set<UnifyPair> smallerRes = unifyTask.applyTypeUnificationRules(hs, this);
//if (left.getName().equals("Vector") || right.getName().equals("AbstractList")) //if (left.getName().equals("Vector") || right.getName().equals("AbstractList"))
{ {try {
try {
logFile.write("\nsmallerRes: " + smallerRes);//"smallerHash: " + greaterHash.toString()); logFile.write("\nsmallerRes: " + smallerRes);//"smallerHash: " + greaterHash.toString());
logFile.flush(); // logFile.flush();
} catch (IOException e) {
System.err.println("no LogFile");
}
} }
catch (IOException e) {
System.err.println("no LogFile");}}
//Gleichungen der Form a <./=. Theta oder Theta <./=. a oder a <./=. b sind ok. //Gleichungen der Form a <./=. Theta oder Theta <./=. a oder a <./=. b sind ok.
Predicate<UnifyPair> delFun = x -> !((x.getLhsType() instanceof PlaceholderType || Predicate<UnifyPair> delFun = x -> !((x.getLhsType() instanceof PlaceholderType ||
x.getRhsType() instanceof PlaceholderType) x.getRhsType() instanceof PlaceholderType)
&& !((x.getLhsType() instanceof WildcardType) && //? extends/super a <.? a && !((x.getLhsType() instanceof WildcardType) && //? extends/super a <.? a
((WildcardType) x.getLhsType()).getWildcardedType().equals(x.getRhsType())) ((WildcardType)x.getLhsType()).getWildcardedType().equals(x.getRhsType()))
); );
long smallerLen = smallerRes.stream().filter(delFun).count(); long smallerLen = smallerRes.stream().filter(delFun).count();
try { try {
logFile.write("\nsmallerLen: " + smallerLen + "\n"); logFile.write("\nsmallerLen: " + smallerLen +"\n");
logFile.flush(); // logFile.flush();
} catch (IOException e) {
System.err.println("no LogFile");
} }
catch (IOException e) {
System.err.println("no LogFile");}
if (smallerLen == 0) return -1; if (smallerLen == 0) return -1;
else { else {
up = new UnifyPair(right, left, pairop); up = new UnifyPair(right, left, pairop);
@@ -829,14 +787,12 @@ public class FiniteClosure //extends Ordering<UnifyType> //entfernt PL 2018-12-1
Set<UnifyPair> greaterRes = unifyTask.applyTypeUnificationRules(hs, this); Set<UnifyPair> greaterRes = unifyTask.applyTypeUnificationRules(hs, this);
//if (left.getName().equals("Vector") || right.getName().equals("AbstractList")) //if (left.getName().equals("Vector") || right.getName().equals("AbstractList"))
{ {try {
try {
logFile.write("\ngreaterRes: " + greaterRes);//"smallerHash: " + greaterHash.toString()); logFile.write("\ngreaterRes: " + greaterRes);//"smallerHash: " + greaterHash.toString());
logFile.flush(); // logFile.flush();
} catch (IOException e) {
System.err.println("no LogFile");
}
} }
catch (IOException e) {
System.err.println("no LogFile");}}
//Gleichungen der Form a <./=. Theta oder Theta <./=. a oder a <./=. b sind ok. //Gleichungen der Form a <./=. Theta oder Theta <./=. a oder a <./=. b sind ok.
long greaterLen = greaterRes.stream().filter(delFun).count(); long greaterLen = greaterRes.stream().filter(delFun).count();

View File

@@ -1,5 +1,6 @@
package de.dhbwstuttgart.typeinference.unify.model; package de.dhbwstuttgart.typeinference.unify.model;
import de.dhbwstuttgart.typeinference.unify.UnifyContext;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
@@ -26,9 +27,11 @@ import de.dhbwstuttgart.util.Pair;
public class OrderingUnifyPair extends OrderingExtend<Set<UnifyPair>> { public class OrderingUnifyPair extends OrderingExtend<Set<UnifyPair>> {
protected IFiniteClosure fc; protected IFiniteClosure fc;
protected UnifyContext context;
public OrderingUnifyPair(IFiniteClosure fc) { public OrderingUnifyPair(IFiniteClosure fc, UnifyContext context) {
this.fc = fc; this.fc = fc;
this.context = context;
} }
/* /*
@@ -39,15 +42,15 @@ public class OrderingUnifyPair extends OrderingExtend<Set<UnifyPair>> {
try { try {
//if (left.getRhsType() instanceof WildcardType || right.getRhsType() instanceof WildcardType) {//PL 2019-01-12 ausgetauscht //if (left.getRhsType() instanceof WildcardType || right.getRhsType() instanceof WildcardType) {//PL 2019-01-12 ausgetauscht
if (((PlaceholderType)left.getLhsType()).isInnerType() && ((PlaceholderType)right.getLhsType()).isInnerType()) { if (((PlaceholderType)left.getLhsType()).isInnerType() && ((PlaceholderType)right.getLhsType()).isInnerType()) {
return fc.compare(left.getRhsType(), right.getRhsType(), PairOperator.SMALLERDOTWC); return fc.compare(left.getRhsType(), right.getRhsType(), PairOperator.SMALLERDOTWC, context);
} }
else { else {
return fc.compare(left.getRhsType(), right.getRhsType(), PairOperator.SMALLERDOT); return fc.compare(left.getRhsType(), right.getRhsType(), PairOperator.SMALLERDOT, context);
}} }}
catch (ClassCastException e) { catch (ClassCastException e) {
try { try {
((FiniteClosure)fc).logFile.write("ClassCastException: " + left.toString() + " " + left.getGroundBasePair() + "\n\n"); ((FiniteClosure)fc).logFile.write("ClassCastException: " + left.toString() + " " + left.getGroundBasePair() + "\n\n");
((FiniteClosure)fc).logFile.flush(); // ((FiniteClosure)fc).logFile.flush();
} }
catch (IOException ie) { catch (IOException ie) {
} }
@@ -79,18 +82,18 @@ public class OrderingUnifyPair extends OrderingExtend<Set<UnifyPair>> {
&& (((ExtendsType)right).getExtendedType().getName().equals("java.util.Vector")) && (((ExtendsType)right).getExtendedType().getName().equals("java.util.Vector"))
&& (((ReferenceType)((ExtendsType)right).getExtendedType()).getTypeParams().iterator().next() instanceof ExtendsType))) && (((ReferenceType)((ExtendsType)right).getExtendedType()).getTypeParams().iterator().next() instanceof ExtendsType)))
{ {
System.out.println(""); // System.out.println("");
} }
if (((right instanceof SuperType) && (((SuperType)right).getSuperedType().getName().equals("java.lang.Object"))) if (((right instanceof SuperType) && (((SuperType)right).getSuperedType().getName().equals("java.lang.Object")))
||((left instanceof SuperType) && (((SuperType)left).getSuperedType().getName().equals("java.lang.Object")))) ||((left instanceof SuperType) && (((SuperType)left).getSuperedType().getName().equals("java.lang.Object"))))
{ {
System.out.println(""); // System.out.println("");
} }
} }
else { else {
up = new UnifyPair(left, right, PairOperator.SMALLERDOT); up = new UnifyPair(left, right, PairOperator.SMALLERDOT);
} }
TypeUnifyTask unifyTask = new TypeUnifyTask(); TypeUnifyTask unifyTask = new TypeUnifyTask(context);
HashSet<UnifyPair> hs = new HashSet<>(); HashSet<UnifyPair> hs = new HashSet<>();
hs.add(up); hs.add(up);
Set<UnifyPair> smallerRes = unifyTask.applyTypeUnificationRules(hs, fc); Set<UnifyPair> smallerRes = unifyTask.applyTypeUnificationRules(hs, fc);
@@ -106,11 +109,11 @@ public class OrderingUnifyPair extends OrderingExtend<Set<UnifyPair>> {
&& (((ExtendsType)right).getExtendedType().getName().equals("java.util.Vector")) && (((ExtendsType)right).getExtendedType().getName().equals("java.util.Vector"))
&& (((ReferenceType)((ExtendsType)right).getExtendedType()).getTypeParams().iterator().next() instanceof ExtendsType))) && (((ReferenceType)((ExtendsType)right).getExtendedType()).getTypeParams().iterator().next() instanceof ExtendsType)))
{ {
System.out.println(""); // System.out.println("");
} }
if (right instanceof SuperType) if (right instanceof SuperType)
{ {
System.out.println(""); // System.out.println("");
} }
} }
else { else {
@@ -411,13 +414,13 @@ public class OrderingUnifyPair extends OrderingExtend<Set<UnifyPair>> {
if (leftlewc.iterator().next().getLhsType() instanceof PlaceholderType) { if (leftlewc.iterator().next().getLhsType() instanceof PlaceholderType) {
hm = rsleuni.stream().reduce(new HashMap<UnifyType,UnifyPair>(), (x, y)-> { x.put(y.getLhsType(),y); return x; }, combiner); hm = rsleuni.stream().reduce(new HashMap<UnifyType,UnifyPair>(), (x, y)-> { x.put(y.getLhsType(),y); return x; }, combiner);
Stream<UnifyPair> lslewcstr = lsleuni.stream().filter(x -> !(hm.get(x.getLhsType()) == null)); Stream<UnifyPair> lslewcstr = lsleuni.stream().filter(x -> !(hm.get(x.getLhsType()) == null));
si = lslewcstr.map(x -> fc.compare(x.getRhsType(), hm.get(x.getLhsType()).getRhsType(), PairOperator.SMALLERDOTWC)).reduce((x,y)-> { if (x == y) return x; else return 0; } ); si = lslewcstr.map(x -> fc.compare(x.getRhsType(), hm.get(x.getLhsType()).getRhsType(), PairOperator.SMALLERDOTWC, context)).reduce((x,y)-> { if (x == y) return x; else return 0; } );
} }
//4. Fall //4. Fall
else { else {
hm = rsleuni.stream().reduce(new HashMap<UnifyType,UnifyPair>(), (x, y)-> { x.put(y.getRhsType(),y); return x; }, combiner); hm = rsleuni.stream().reduce(new HashMap<UnifyType,UnifyPair>(), (x, y)-> { x.put(y.getRhsType(),y); return x; }, combiner);
Stream<UnifyPair> lslewcstr = lsleuni.stream().filter(x -> !(hm.get(x.getRhsType()) == null)); Stream<UnifyPair> lslewcstr = lsleuni.stream().filter(x -> !(hm.get(x.getRhsType()) == null));
si = lslewcstr.map(x -> fc.compare(x.getLhsType(), hm.get(x.getRhsType()).getLhsType(), PairOperator.SMALLERDOTWC)).reduce((x,y)-> { if (x == y) return x; else return 0; } ); si = lslewcstr.map(x -> fc.compare(x.getLhsType(), hm.get(x.getRhsType()).getLhsType(), PairOperator.SMALLERDOTWC, context)).reduce((x,y)-> { if (x == y) return x; else return 0; } );
} }
if (!si.isPresent()) return 0; if (!si.isPresent()) return 0;
else return si.get(); else return si.get();

View File

@@ -1,17 +1,11 @@
package de.dhbwstuttgart.typeinference.unify.model; package de.dhbwstuttgart.typeinference.unify.model;
import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
import de.dhbwstuttgart.typeinference.unify.distributeVariance;
import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure; import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure;
import de.dhbwstuttgart.typeinference.unify.interfaces.UnifyTypeVisitor; import de.dhbwstuttgart.typeinference.unify.interfaces.UnifyTypeVisitor;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
/** /**
* An unbounded placeholder type. * An unbounded placeholder type.
@@ -25,15 +19,8 @@ public final class PlaceholderType extends UnifyType{
*/ */
public static final ArrayList<String> EXISTING_PLACEHOLDERS = new ArrayList<String>(); public static final ArrayList<String> EXISTING_PLACEHOLDERS = new ArrayList<String>();
/**
* Prefix of auto-generated placeholder names.
*/
protected static String nextName = "gen_";
/** private static final AtomicInteger placeholderCount = new AtomicInteger(0);
* Random number generator used to generate fresh placeholder name.
*/
protected static Random rnd = new Random(43558747548978L);
/** /**
* True if this object was auto-generated, false if this object was user-generated. * True if this object was auto-generated, false if this object was user-generated.
@@ -100,18 +87,34 @@ public final class PlaceholderType extends UnifyType{
} }
/** /**
* Creates a fresh placeholder type with a name that does so far not exist. * Creates a fresh placeholder type with a name that does so far not exist from the chars A-Z.
* A user could later instantiate a type using the same name that is equivalent to this type. * A user could later instantiate a type using the same name that is equivalent to this type.
* @return A fresh placeholder type. * @return A fresh placeholder type.
*/ */
public synchronized static PlaceholderType freshPlaceholder() { public static PlaceholderType freshPlaceholder() {
String name = nextName + (char) (rnd.nextInt(22) + 97); // Returns random char between 'a' and 'z' String name;
// Add random chars while the name is in use.
while(EXISTING_PLACEHOLDERS.contains(name)) { int attempts = 1000;
name += (char) (rnd.nextInt(22) + 97); // Returns random char between 'a' and 'z' while (attempts-- > 0) {
int pc = PlaceholderType.placeholderCount.incrementAndGet();
StringBuilder sb = new StringBuilder();
while (pc >= 0) {
sb.append((char)(pc % 26 + 97));
pc = pc / 26 - 1;
} }
name = sb.toString();
synchronized (EXISTING_PLACEHOLDERS) {
if (!EXISTING_PLACEHOLDERS.contains(name)) {
return new PlaceholderType(name, true); return new PlaceholderType(name, true);
} }
}
}
throw new RuntimeException("Failed to generate placeholder name in the allowed number of attempts");
}
/** /**

View File

@@ -0,0 +1,9 @@
package de.dhbwstuttgart.util;
public class Logger {
public static void print(String s) {
System.out.println(s);
}
}

View File

@@ -1,6 +1,6 @@
import static org.junit.jupiter.api.Assertions.*; import static org.junit.Assert.*;
import static targetast.TestCodegen.generateClassFiles; import static targetast.TestCodegen.generateClassFiles;
import java.io.File; import java.io.File;
@@ -9,12 +9,13 @@ import java.net.URL;
import java.net.URLClassLoader; import java.net.URLClassLoader;
import java.util.Arrays; import java.util.Arrays;
import org.junit.jupiter.api.BeforeAll; import org.junit.BeforeClass;
import org.junit.jupiter.api.Test; import org.junit.Test;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import de.dhbwstuttgart.core.JavaTXCompiler; import de.dhbwstuttgart.core.JavaTXCompiler;
import de.dhbwstuttgart.environment.ByteArrayClassLoader;
public class AllgemeinTest { public class AllgemeinTest {

View File

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

File diff suppressed because it is too large Load Diff

View File

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

View File

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

View File

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

View File

@@ -3,7 +3,7 @@ package finiteClosure;
import de.dhbwstuttgart.parser.SyntaxTreeGenerator.FCGenerator; import de.dhbwstuttgart.parser.SyntaxTreeGenerator.FCGenerator;
import de.dhbwstuttgart.syntaxtree.ClassOrInterface; import de.dhbwstuttgart.syntaxtree.ClassOrInterface;
import de.dhbwstuttgart.syntaxtree.factory.ASTFactory; import de.dhbwstuttgart.syntaxtree.factory.ASTFactory;
import org.junit.jupiter.api.Test; import org.junit.Test;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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