From 766e71bb3a379fe3c490ce1a163c1e2b04d714ed Mon Sep 17 00:00:00 2001 From: JanUlrich Date: Tue, 19 Nov 2019 21:53:53 +0100 Subject: [PATCH 01/81] Beginn mit Werksvertrag: Package Support --- src/test/java/packages/ParsePackageName.java | 34 +++++++++++++++++++ .../resources/javFiles/packageNameTest.jav | 3 ++ vorgehen.md | 11 ++++++ 3 files changed, 48 insertions(+) create mode 100644 src/test/java/packages/ParsePackageName.java create mode 100644 src/test/resources/javFiles/packageNameTest.jav create mode 100644 vorgehen.md diff --git a/src/test/java/packages/ParsePackageName.java b/src/test/java/packages/ParsePackageName.java new file mode 100644 index 00000000..e2fe1682 --- /dev/null +++ b/src/test/java/packages/ParsePackageName.java @@ -0,0 +1,34 @@ +package packages; + +import de.dhbwstuttgart.core.JavaTXCompiler; +import de.dhbwstuttgart.syntaxtree.SourceFile; +import de.dhbwstuttgart.syntaxtree.visual.ASTPrinter; +import de.dhbwstuttgart.syntaxtree.visual.ASTTypePrinter; +import de.dhbwstuttgart.typedeployment.TypeInsert; +import de.dhbwstuttgart.typedeployment.TypeInsertFactory; +import de.dhbwstuttgart.typeinference.result.ResultSet; +import org.junit.Test; +import typeinference.JavaTXCompilerTest; + +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +public class ParsePackageName { + + public static final String rootDirectory = System.getProperty("user.dir")+"/src/test/resources/javFiles/"; + @Test + public void parsePackage() throws IOException, ClassNotFoundException { + JavaTXCompiler compiler = new JavaTXCompiler(new File(rootDirectory+"packageNameTest.jav")); + for(File f : compiler.sourceFiles.keySet()){ + SourceFile sf = compiler.sourceFiles.get(f); + System.out.println(ASTTypePrinter.print(sf)); + System.out.println(ASTPrinter.print(sf)); + } + List results = compiler.typeInference(); + + } +} diff --git a/src/test/resources/javFiles/packageNameTest.jav b/src/test/resources/javFiles/packageNameTest.jav new file mode 100644 index 00000000..b55d1071 --- /dev/null +++ b/src/test/resources/javFiles/packageNameTest.jav @@ -0,0 +1,3 @@ +package Test; + +class TestClass{} \ No newline at end of file diff --git a/vorgehen.md b/vorgehen.md new file mode 100644 index 00000000..d3d17653 --- /dev/null +++ b/vorgehen.md @@ -0,0 +1,11 @@ +* Parser um Packages erweitern + * Schätzung: 0 h + * Parser kann Java 8 und daher auch packages +* Convertierung zu AST + * AST kann schon Packages im Namen + * Es muss geprüft werden, ob geparste Datei im richtigen Ordner ist + * +* Constraints erstellen + * macht es hier einen Unterschied? + * es ändert sich nur der Namen der Typen + * das ist schon in JavaClassName enthalten From 09a6aec65d693084f07f49a133c6f0472199a63b Mon Sep 17 00:00:00 2001 From: JanUlrich Date: Sun, 24 Nov 2019 17:52:02 +0100 Subject: [PATCH 02/81] =?UTF-8?q?Erste=20Tests=20und=20die=20M=C3=B6glichk?= =?UTF-8?q?eit=20generateBytecode=20null=20als=20Pfad=20zu=20=C3=BCbergebe?= =?UTF-8?q?n?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- doc/Generics/generics.tex | 25 +++++++++++++++++++ .../de/dhbwstuttgart/core/JavaTXCompiler.java | 8 ++++-- src/test/java/packages/Bytecode.java | 25 +++++++++++++++++++ .../java/packages/CheckPackageFolder.java | 20 +++++++++++++++ src/test/java/packages/ParsePackageName.java | 17 ++----------- .../resources/javFiles/packageNameTest.jav | 3 --- .../packageTest/de/test/packageNameTest.jav | 3 +++ .../de/test/packageNameTestWrongPackage.jav | 3 +++ vorgehen.md | 19 ++++++++++++++ 9 files changed, 103 insertions(+), 20 deletions(-) create mode 100644 doc/Generics/generics.tex create mode 100644 src/test/java/packages/Bytecode.java create mode 100644 src/test/java/packages/CheckPackageFolder.java delete mode 100644 src/test/resources/javFiles/packageNameTest.jav create mode 100644 src/test/resources/javFiles/packageTest/de/test/packageNameTest.jav create mode 100644 src/test/resources/javFiles/packageTest/de/test/packageNameTestWrongPackage.jav diff --git a/doc/Generics/generics.tex b/doc/Generics/generics.tex new file mode 100644 index 00000000..bacd9f92 --- /dev/null +++ b/doc/Generics/generics.tex @@ -0,0 +1,25 @@ +\documentclass{article} + +\begin{document} + +\section{Generics sind notwendig} +Generics können nicht ignoriert werden. +Folgender Fall ist Typisierbar: + +\begin{program} + T m1(T x){ + return m2(x); +} + +m2(x){ + m1(1); + m2("Test"); + return m1(x); +} +\end{program} + +Beim weglassen des Generics T wäre es aber nicht mehr möglich. +Dann erhält jeder Constraint, welcher in Verbindung mit der Methode m1 steht +den selben TPH. + +\end{document} diff --git a/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java b/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java index d44ac77f..5f107ed0 100644 --- a/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java +++ b/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java @@ -762,7 +762,7 @@ public class JavaTXCompiler { } /** - * @param path + * @param path - can be null, then class file output is in the same directory as the parsed source files * @param typeinferenceResult * @param simplifyResultsForAllSourceFiles * @throws IOException @@ -775,7 +775,11 @@ public class JavaTXCompiler { BytecodeGen bytecodeGen = new BytecodeGen(classFiles, typeinferenceResult, simplifyResultsForAllSourceFiles, sf, path); bytecodeGen.visit(sf); - writeClassFile(bytecodeGen.getClassFiles(), path); + String packagePath = sf.getPkgName().replace(".","/"); + if(path == null){ + path = f.getPath(); + } + writeClassFile(bytecodeGen.getClassFiles(), path + packagePath); } } diff --git a/src/test/java/packages/Bytecode.java b/src/test/java/packages/Bytecode.java new file mode 100644 index 00000000..f02c83fa --- /dev/null +++ b/src/test/java/packages/Bytecode.java @@ -0,0 +1,25 @@ +package packages; + +import de.dhbwstuttgart.core.JavaTXCompiler; +import junit.framework.TestCase; +import org.junit.Test; + +import java.io.File; +import java.io.IOException; + +public class Bytecode extends TestCase { + + public static final String rootDirectory = System.getProperty("user.dir")+"/src/test/resources/javFiles/packageTest/de/test/"; + @Test + public void testSetPackageNameInBytecode() throws IOException, ClassNotFoundException { + JavaTXCompiler compiler = new JavaTXCompiler(new File(rootDirectory+"packageNameTest.jav")); + compiler.typeInference(); + File f = new File(rootDirectory + "Test.class"); + if(f.exists() && !f.isDirectory()) { + f.delete(); + } + compiler.generateBytecode(null); + f = new File(rootDirectory + "Test.class"); + assertTrue(f.exists()); + } +} diff --git a/src/test/java/packages/CheckPackageFolder.java b/src/test/java/packages/CheckPackageFolder.java new file mode 100644 index 00000000..9644d5da --- /dev/null +++ b/src/test/java/packages/CheckPackageFolder.java @@ -0,0 +1,20 @@ +package packages; + +import de.dhbwstuttgart.core.JavaTXCompiler; +import de.dhbwstuttgart.syntaxtree.SourceFile; +import junit.framework.TestCase; +import org.junit.Test; + +import java.io.File; +import java.io.IOException; + +public class CheckPackageFolder extends TestCase { + + public static final String rootDirectory = System.getProperty("user.dir")+"/src/test/resources/javFiles/packageTest/de/test/"; + + @Test + public void testCorrectFolder1File() throws IOException, ClassNotFoundException { + JavaTXCompiler compiler = new JavaTXCompiler(new File(rootDirectory+"packageNameTestWrongPackage.jav")); + assertTrue(true); //Es ist erlaubt falsche package Namen zu verwenden. Warnung wäre optional + } +} diff --git a/src/test/java/packages/ParsePackageName.java b/src/test/java/packages/ParsePackageName.java index e2fe1682..b54cf90e 100644 --- a/src/test/java/packages/ParsePackageName.java +++ b/src/test/java/packages/ParsePackageName.java @@ -2,33 +2,20 @@ package packages; import de.dhbwstuttgart.core.JavaTXCompiler; import de.dhbwstuttgart.syntaxtree.SourceFile; -import de.dhbwstuttgart.syntaxtree.visual.ASTPrinter; -import de.dhbwstuttgart.syntaxtree.visual.ASTTypePrinter; -import de.dhbwstuttgart.typedeployment.TypeInsert; -import de.dhbwstuttgart.typedeployment.TypeInsertFactory; -import de.dhbwstuttgart.typeinference.result.ResultSet; import org.junit.Test; -import typeinference.JavaTXCompilerTest; import java.io.File; import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.util.HashSet; -import java.util.List; -import java.util.Set; public class ParsePackageName { - 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/packageTest/de/test/"; @Test public void parsePackage() throws IOException, ClassNotFoundException { JavaTXCompiler compiler = new JavaTXCompiler(new File(rootDirectory+"packageNameTest.jav")); for(File f : compiler.sourceFiles.keySet()){ SourceFile sf = compiler.sourceFiles.get(f); - System.out.println(ASTTypePrinter.print(sf)); - System.out.println(ASTPrinter.print(sf)); + assert sf.getPkgName().equals("de.test"); } - List results = compiler.typeInference(); - } } diff --git a/src/test/resources/javFiles/packageNameTest.jav b/src/test/resources/javFiles/packageNameTest.jav deleted file mode 100644 index b55d1071..00000000 --- a/src/test/resources/javFiles/packageNameTest.jav +++ /dev/null @@ -1,3 +0,0 @@ -package Test; - -class TestClass{} \ No newline at end of file diff --git a/src/test/resources/javFiles/packageTest/de/test/packageNameTest.jav b/src/test/resources/javFiles/packageTest/de/test/packageNameTest.jav new file mode 100644 index 00000000..ad5b9f63 --- /dev/null +++ b/src/test/resources/javFiles/packageTest/de/test/packageNameTest.jav @@ -0,0 +1,3 @@ +package de.test; + +class TestClass{} \ No newline at end of file diff --git a/src/test/resources/javFiles/packageTest/de/test/packageNameTestWrongPackage.jav b/src/test/resources/javFiles/packageTest/de/test/packageNameTestWrongPackage.jav new file mode 100644 index 00000000..a86d22aa --- /dev/null +++ b/src/test/resources/javFiles/packageTest/de/test/packageNameTestWrongPackage.jav @@ -0,0 +1,3 @@ +package de.tesst; + +class TestClass{} \ No newline at end of file diff --git a/vorgehen.md b/vorgehen.md index d3d17653..61b62c4f 100644 --- a/vorgehen.md +++ b/vorgehen.md @@ -9,3 +9,22 @@ * macht es hier einen Unterschied? * es ändert sich nur der Namen der Typen * das ist schon in JavaClassName enthalten + +## Java verhalten +* das verhalten von Java soll kopiert werden +* Java kompiliert in den gleichen Ordner wie die source file +* Java erhält eine liste von Source Files, die es kompilieren soll +* anhand von deren Standort lassen sich relativ die Position von kompilierten Class-files bestimmen + +* -cp path or -classpath path + Specifies where to find user class files, and (optionally) annotation processors and source files. This class path overrides the user class path in the CLASSPATH environment variable. If neither CLASSPATH, -cp nor -classpath is specified, then the + user class path is the current directory. See Setting the Class Path. + +* Compiler kontrolliert nicht, ob package im korrekten Ordner ist + * auch keine Warnung + * unser kompiler könnte aber trotzdem zumindes eine Warnung ausgeben + +### -d Parameter +* Optional +* damit lässt sich ein andere ort zur Ausgabe der Class-files bestimmen + From af5b23e31aa731758eadd292f097bc2350474543 Mon Sep 17 00:00:00 2001 From: JanUlrich Date: Sat, 14 Dec 2019 15:35:52 +0100 Subject: [PATCH 03/81] Use JavaClassName instead of Strings --- .../dhbwstuttgart/bytecode/BytecodeGen.java | 17 ++++++------ .../bytecode/BytecodeGenMethod.java | 27 ++++++++++--------- .../GeneratedGenericsFinder.java | 5 ++-- .../genericsGenerator/GenericsGenerator.java | 3 ++- .../GenericGenratorResultForSourceFile.java | 6 +++-- .../GenericsGeneratorResultForClass.java | 12 +++++---- .../de/dhbwstuttgart/core/JavaTXCompiler.java | 21 ++++++++------- .../parser/scope/JavaClassName.java | 13 ++++++++- .../typedeployment/TypeInsertFactory.java | 2 +- src/test/java/packages/Bytecode.java | 4 +-- vorgehen.md | 16 +++++++++++ 11 files changed, 82 insertions(+), 44 deletions(-) diff --git a/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGen.java b/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGen.java index 508bd520..e0602731 100644 --- a/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGen.java +++ b/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGen.java @@ -7,6 +7,7 @@ import java.util.Iterator; import java.util.List; import java.util.Optional; +import de.dhbwstuttgart.parser.scope.JavaClassName; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.FieldVisitor; import org.objectweb.asm.MethodVisitor; @@ -81,7 +82,7 @@ public class BytecodeGen implements ASTVisitor { String type; public static RefTypeOrTPHOrWildcardOrGeneric THISTYPE = null; - private String className; + private JavaClassName className; private String pkgName; private boolean isInterface; private Collection listOfResultSets; @@ -107,7 +108,7 @@ public class BytecodeGen implements ASTVisitor { HashMap methodParamsAndTypes = new HashMap<>(); byte[] bytecode; - HashMap classFiles; + HashMap classFiles; private final ArrayList methodNameAndParamsT = new ArrayList<>(); private final ArrayList fieldNameAndParamsT = new ArrayList<>(); @@ -119,7 +120,7 @@ public class BytecodeGen implements ASTVisitor { private Resolver resolver; - public BytecodeGen(HashMap classFiles, Collection listOfResultSets, List simplifyResultsForAllSourceFiles, SourceFile sf, + public BytecodeGen(HashMap classFiles, Collection listOfResultSets, List simplifyResultsForAllSourceFiles, SourceFile sf, String path) { this.classFiles = classFiles; this.listOfResultSets = listOfResultSets; @@ -135,7 +136,7 @@ public class BytecodeGen implements ASTVisitor { System.out.println("in Class: " + cl.getClassName().toString()); BytecodeGen classGen = new BytecodeGen(classFiles, listOfResultSets, simplifyResultsForAllSourceFiles, sf, path); cl.accept(classGen); - classGen.writeClass(cl.getClassName().toString()); + classGen.writeClass(cl.getClassName()); } } @@ -145,20 +146,20 @@ public class BytecodeGen implements ASTVisitor { * * @param name name of the class with which the bytecode is to be associated */ - private void writeClass(String name) { + private void writeClass(JavaClassName name) { bytecode = cw.toByteArray(); classFiles.put(name, bytecode); } - public HashMap getClassFiles() { + public HashMap getClassFiles() { return classFiles; } @Override public void visit(ClassOrInterface classOrInterface) { - className = classOrInterface.getClassName().toString(); + className = classOrInterface.getClassName(); cw.visitSource(className + ".jav", null); @@ -172,7 +173,7 @@ public class BytecodeGen implements ASTVisitor { // resultSet = listOfResultSets.get(0); boolean isVisited = false; List listOfResultSetsList = new ArrayList<>(listOfResultSets); - generatedGenerics = simplifyResultsForAllSourceFiles.stream().map(sr->sr.getSimplifyResultsByName(pkgName, className)).findFirst().get(); + generatedGenerics = simplifyResultsForAllSourceFiles.stream().map(sr->sr.getSimplifyResultsByName(className)).findFirst().get(); for (int i = 0; i < listOfResultSetsList.size(); i++) { //for (ResultSet rs : listOfResultSets) { superClass = classOrInterface.getSuperClass().acceptTV(new TypeToDescriptor()); diff --git a/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java b/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java index 46caa52b..9a485561 100644 --- a/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java +++ b/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java @@ -15,6 +15,7 @@ import java.util.List; import de.dhbwstuttgart.bytecode.utilities.*; import de.dhbwstuttgart.exceptions.NotImplementedException; +import de.dhbwstuttgart.parser.scope.JavaClassName; import de.dhbwstuttgart.syntaxtree.statement.*; import de.dhbwstuttgart.syntaxtree.statement.BinaryExpr.Operator; import de.dhbwstuttgart.syntaxtree.statement.UnaryExpr.Operation; @@ -45,7 +46,7 @@ public class BytecodeGenMethod implements StatementVisitor { private Method m; private MethodVisitor mv; private HashMap paramsAndLocals = new HashMap<>(); - private String className; + private JavaClassName className; private int lamCounter; private ClassWriter cw; private ResultSet resultSet; @@ -71,16 +72,16 @@ public class BytecodeGenMethod implements StatementVisitor { private boolean isRightSideALambda = false; private KindOfLambda kindOfLambda; - private HashMap classFiles; + private HashMap classFiles; private int constructorPos = 0; private ArrayList varsFunInterface = new ArrayList<>();; // generate bytecode for constructor - public BytecodeGenMethod(String className, String superClass,ResultSet resultSet, Method m, MethodVisitor mv, - HashMap paramsAndLocals, ClassWriter cw, HashMap genericsAndBoundsMethod, - HashMap genericsAndBounds, boolean isInterface, HashMap classFiles, - SourceFile sf,String path, Block block, int constructorPos) { + public BytecodeGenMethod(JavaClassName className, String superClass, ResultSet resultSet, Method m, MethodVisitor mv, + HashMap paramsAndLocals, ClassWriter cw, HashMap genericsAndBoundsMethod, + HashMap genericsAndBounds, boolean isInterface, HashMap classFiles, + SourceFile sf, String path, Block block, int constructorPos) { this.className = className; this.superClass = superClass; @@ -105,9 +106,9 @@ public class BytecodeGenMethod implements StatementVisitor { } - public BytecodeGenMethod(String className, String superClass,ResultSet resultSet, Method m, MethodVisitor mv, + public BytecodeGenMethod(JavaClassName className, String superClass,ResultSet resultSet, Method m, MethodVisitor mv, HashMap paramsAndLocals, ClassWriter cw, HashMap genericsAndBoundsMethod, - HashMap genericsAndBounds, boolean isInterface, HashMap classFiles, SourceFile sf,String path) { + HashMap genericsAndBounds, boolean isInterface, HashMap classFiles, SourceFile sf,String path) { this.className = className; this.superClass = superClass; @@ -129,8 +130,8 @@ public class BytecodeGenMethod implements StatementVisitor { } - public BytecodeGenMethod(String className, ClassWriter cw, LambdaExpression lambdaExpression, ArrayList usedVars, ResultSet resultSet, MethodVisitor mv, - int indexOfFirstParamLam, boolean isInterface, HashMap classFiles, String path, int lamCounter, SourceFile sf,HashMap genericsAndBoundsMethod, + public BytecodeGenMethod(JavaClassName className, ClassWriter cw, LambdaExpression lambdaExpression, ArrayList usedVars, ResultSet resultSet, MethodVisitor mv, + int indexOfFirstParamLam, boolean isInterface, HashMap classFiles, String path, int lamCounter, SourceFile sf,HashMap genericsAndBoundsMethod, HashMap genericsAndBounds) { this.className = className; this.cw = cw; @@ -622,7 +623,7 @@ public class BytecodeGenMethod implements StatementVisitor { } String newDesc = addUsedVarsToDesugaredMethodDescriptor(lamDesc); // first check if capturing lambda then invokestatic or invokespecial - Handle arg2 = new Handle(staticOrSpecial, this.className, desugaredMethodName, newDesc, false); + Handle arg2 = new Handle(staticOrSpecial, this.className.toString(), desugaredMethodName, newDesc, false); // Descriptor of functional interface methode SamMethod samMethod = new SamMethod(kindOfLambda.getArgumentList(), lambdaExpression.getType()); // Desc: (this/nothing)TargetType @@ -797,7 +798,7 @@ public class BytecodeGenMethod implements StatementVisitor { } if(methodRefl == null) { - boolean toCreate = !receiverName.equals(className) && helper.isInCurrPkg(clazz); + boolean toCreate = !receiverName.equals(className.toString()) && helper.isInCurrPkg(clazz); if(toCreate) { try { mDesc = helper.getDesc(clazz); @@ -832,7 +833,7 @@ public class BytecodeGenMethod implements StatementVisitor { System.out.println("Methodcall type : " + resultSet.resolveType(methodCall.getType()).resolvedType.acceptTV(new TypeToDescriptor())); List argListMethCall = new LinkedList<>(); String receiverRefl=""; - if(methodRefl == null && receiverName.equals(className)) { + if(methodRefl == null && receiverName.equals(className.toString())) { MethodFromMethodCall method = new MethodFromMethodCall(methodCall.arglist, methodCall.getType(), receiverName, genericsAndBoundsMethod, genericsAndBounds); mDesc = method.accept(new DescriptorToString(resultSet)); diff --git a/src/main/java/de/dhbwstuttgart/bytecode/genericsGenerator/GeneratedGenericsFinder.java b/src/main/java/de/dhbwstuttgart/bytecode/genericsGenerator/GeneratedGenericsFinder.java index 5e473ebe..ba55c4c7 100644 --- a/src/main/java/de/dhbwstuttgart/bytecode/genericsGenerator/GeneratedGenericsFinder.java +++ b/src/main/java/de/dhbwstuttgart/bytecode/genericsGenerator/GeneratedGenericsFinder.java @@ -16,6 +16,7 @@ import de.dhbwstuttgart.bytecode.utilities.MethodAndTPH; import de.dhbwstuttgart.bytecode.utilities.MethodUtility; import de.dhbwstuttgart.bytecode.utilities.Resolver; import de.dhbwstuttgart.parser.SyntaxTreeGenerator.AssignToLocal; +import de.dhbwstuttgart.parser.scope.JavaClassName; import de.dhbwstuttgart.syntaxtree.ASTVisitor; import de.dhbwstuttgart.syntaxtree.ClassOrInterface; import de.dhbwstuttgart.syntaxtree.Constructor; @@ -75,7 +76,7 @@ public class GeneratedGenericsFinder implements ASTVisitor { private final List methodNameAndParamsT = new ArrayList<>(); private String pkgName; - private String className; + private JavaClassName className; private Resolver resolver; /** @@ -117,7 +118,7 @@ public class GeneratedGenericsFinder implements ASTVisitor { */ @Override public void visit(ClassOrInterface classOrInterface) { - className = classOrInterface.getClassName().toString(); + className = classOrInterface.getClassName(); List listOfResultSetsList = new ArrayList<>(listOfResultSets); boolean isVisited = false; diff --git a/src/main/java/de/dhbwstuttgart/bytecode/genericsGenerator/GenericsGenerator.java b/src/main/java/de/dhbwstuttgart/bytecode/genericsGenerator/GenericsGenerator.java index a541025c..8e5bd481 100644 --- a/src/main/java/de/dhbwstuttgart/bytecode/genericsGenerator/GenericsGenerator.java +++ b/src/main/java/de/dhbwstuttgart/bytecode/genericsGenerator/GenericsGenerator.java @@ -12,6 +12,7 @@ import java.util.Set; import java.util.stream.Collectors; import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.*; +import de.dhbwstuttgart.parser.scope.JavaClassName; import org.objectweb.asm.Type; import de.dhbwstuttgart.bytecode.TPHExtractor; @@ -30,7 +31,7 @@ public class GenericsGenerator { class constraints: tphClass < tphMeth1, tphMeth1 < tphMeth2, tphMeth2 < Object */ - public static GenericsGeneratorResultForClass generateConstraints(final String className, final TPHExtractor tphExtractor, + public static GenericsGeneratorResultForClass generateConstraints(final JavaClassName className, final TPHExtractor tphExtractor, final List tphsClass, final ConstraintsSimplierResult simplifiedConstraints) { List classConstraints = generateConstraintsForClass(tphExtractor, diff --git a/src/main/java/de/dhbwstuttgart/bytecode/genericsGeneratorTypes/GenericGenratorResultForSourceFile.java b/src/main/java/de/dhbwstuttgart/bytecode/genericsGeneratorTypes/GenericGenratorResultForSourceFile.java index 85d0bcbf..f0d11473 100644 --- a/src/main/java/de/dhbwstuttgart/bytecode/genericsGeneratorTypes/GenericGenratorResultForSourceFile.java +++ b/src/main/java/de/dhbwstuttgart/bytecode/genericsGeneratorTypes/GenericGenratorResultForSourceFile.java @@ -3,6 +3,8 @@ */ package de.dhbwstuttgart.bytecode.genericsGeneratorTypes; +import de.dhbwstuttgart.parser.scope.JavaClassName; + import java.util.ArrayList; import java.util.List; import java.util.NoSuchElementException; @@ -37,9 +39,9 @@ public class GenericGenratorResultForSourceFile { genericGeneratorResultForAllClasses.add(sResClass); } - public GenericsGeneratorResultForClass getSimplifyResultsByName(String pkgName, String name) { + public GenericsGeneratorResultForClass getSimplifyResultsByName(JavaClassName name) { - if (this.pkgName.equals(pkgName)) { + if (this.pkgName.equals(name.getPackageName())) { return genericGeneratorResultForAllClasses.stream() .filter(sr -> sr.getClassName().equals(name)) .findAny() diff --git a/src/main/java/de/dhbwstuttgart/bytecode/genericsGeneratorTypes/GenericsGeneratorResultForClass.java b/src/main/java/de/dhbwstuttgart/bytecode/genericsGeneratorTypes/GenericsGeneratorResultForClass.java index d6532ecb..eaeb1f3a 100644 --- a/src/main/java/de/dhbwstuttgart/bytecode/genericsGeneratorTypes/GenericsGeneratorResultForClass.java +++ b/src/main/java/de/dhbwstuttgart/bytecode/genericsGeneratorTypes/GenericsGeneratorResultForClass.java @@ -3,6 +3,8 @@ */ package de.dhbwstuttgart.bytecode.genericsGeneratorTypes; +import de.dhbwstuttgart.parser.scope.JavaClassName; + import java.util.Collections; import java.util.List; @@ -11,11 +13,11 @@ import java.util.List; * */ public class GenericsGeneratorResultForClass { - private final String className; + private final JavaClassName className; private final List classConstraints; private final GenericGeneratorResultsForAllMethods methodsAndTheirConstraints; - public GenericsGeneratorResultForClass(String className) { + public GenericsGeneratorResultForClass(JavaClassName className) { this(className, Collections.emptyList(), new GenericGeneratorResultsForAllMethods()); } /** @@ -23,8 +25,8 @@ public class GenericsGeneratorResultForClass { * @param classConstraints * @param methodsAndTheirConstraints */ - public GenericsGeneratorResultForClass(String className, List classConstraints, - GenericGeneratorResultsForAllMethods methodsAndTheirConstraints) { + public GenericsGeneratorResultForClass(JavaClassName className, List classConstraints, + GenericGeneratorResultsForAllMethods methodsAndTheirConstraints) { this.className = className; this.classConstraints = classConstraints; this.methodsAndTheirConstraints = methodsAndTheirConstraints; @@ -33,7 +35,7 @@ public class GenericsGeneratorResultForClass { /** * @return the className */ - public String getClassName() { + public JavaClassName getClassName() { return className; } diff --git a/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java b/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java index 5f107ed0..3c234175 100644 --- a/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java +++ b/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java @@ -714,7 +714,7 @@ public class JavaTXCompiler { return ret; } - public void generateBytecodForFile(String path, HashMap classFiles, SourceFile sf, + public void generateBytecodForFile(String path, HashMap classFiles, SourceFile sf, List typeinferenceResult) throws IOException { try { List genericResults = getGeneratedGenericResultsForAllSourceFiles(typeinferenceResult); @@ -753,7 +753,9 @@ public class JavaTXCompiler { return result; } - // um pfad erweitern + /** + * @param path - can be null, then class file output is in the same directory as the parsed source files + */ public void generateBytecode(String path) throws ClassNotFoundException, IOException, BytecodeGeneratorError { List typeinferenceResult = this.typeInference(); List simplifyResultsForAllSourceFiles = getGeneratedGenericResultsForAllSourceFiles( @@ -770,27 +772,28 @@ public class JavaTXCompiler { public void generateBytecode(String path, List typeinferenceResult, List simplifyResultsForAllSourceFiles) throws IOException { for (File f : sourceFiles.keySet()) { - HashMap classFiles = new HashMap<>(); + HashMap classFiles = new HashMap<>(); SourceFile sf = sourceFiles.get(f); BytecodeGen bytecodeGen = new BytecodeGen(classFiles, typeinferenceResult, simplifyResultsForAllSourceFiles, sf, path); bytecodeGen.visit(sf); - String packagePath = sf.getPkgName().replace(".","/"); if(path == null){ - path = f.getPath(); + path = f.getParent(); //Set path to path of the parsed .jav file + }else{ + path += sf.getPkgName().replace(".","/"); //add package path to root path } - writeClassFile(bytecodeGen.getClassFiles(), path + packagePath); + writeClassFile(bytecodeGen.getClassFiles(), path); } } - private void writeClassFile(HashMap classFiles, String path) throws IOException { + private void writeClassFile(HashMap classFiles, String path) throws IOException { FileOutputStream output; - for (String name : classFiles.keySet()) { + for (JavaClassName name : classFiles.keySet()) { byte[] bytecode = classFiles.get(name); System.out.println("generating " + name + ".class file ..."); // output = new FileOutputStream(new File(System.getProperty("user.dir") + // "/testBytecode/generatedBC/" +name+".class")); - output = new FileOutputStream(new File(path + name + ".class")); + output = new FileOutputStream(new File(path + File.separator + name.getClassName() + ".class")); output.write(bytecode); output.close(); System.out.println(name + ".class file generated"); diff --git a/src/main/java/de/dhbwstuttgart/parser/scope/JavaClassName.java b/src/main/java/de/dhbwstuttgart/parser/scope/JavaClassName.java index b87ff719..534d0916 100644 --- a/src/main/java/de/dhbwstuttgart/parser/scope/JavaClassName.java +++ b/src/main/java/de/dhbwstuttgart/parser/scope/JavaClassName.java @@ -84,7 +84,15 @@ public class JavaClassName { @Override public String toString() { - return (packageName!=null ? packageName.toString() : "") + name; + return (packageName!=null ? packageName.toString() + "." : "") + name; + } + + public String getPackageName() { + return (packageName!=null ? packageName.toString() : ""); + } + + public String getClassName(){ + return name; } } @@ -130,6 +138,9 @@ class PackageName{ String ret = ""; if(names == null)return ""; for(String n : names)ret+=n+"."; + if (ret != null && ret.length() > 0 && ret.charAt(ret.length() - 1) == '.') { + ret = ret.substring(0, ret.length() - 1); + } return ret; } } diff --git a/src/main/java/de/dhbwstuttgart/typedeployment/TypeInsertFactory.java b/src/main/java/de/dhbwstuttgart/typedeployment/TypeInsertFactory.java index 44bfd2ff..ebef5263 100644 --- a/src/main/java/de/dhbwstuttgart/typedeployment/TypeInsertFactory.java +++ b/src/main/java/de/dhbwstuttgart/typedeployment/TypeInsertFactory.java @@ -47,7 +47,7 @@ public class TypeInsertFactory { new TypeToInsertString(resolvedType.resolvedType).insert); List simplifyResults = JavaTXCompiler.INSTANCE.getGeneratedGenericResultsForAllSourceFiles(newResults); for (GenericGenratorResultForSourceFile simplifyResultsEntries : simplifyResults) { - GenericsGeneratorResultForClass genericResultsForClass = simplifyResultsEntries.getSimplifyResultsByName("", cl.getClassName().toString()); + GenericsGeneratorResultForClass genericResultsForClass = simplifyResultsEntries.getSimplifyResultsByName(cl.getClassName()); return new TypeInsert(insertPoint, createGenericInsert(genericResultsForClass, cl, m, resultSet, offset), resolvedType.getResultPair()); } diff --git a/src/test/java/packages/Bytecode.java b/src/test/java/packages/Bytecode.java index f02c83fa..1f7854c1 100644 --- a/src/test/java/packages/Bytecode.java +++ b/src/test/java/packages/Bytecode.java @@ -14,12 +14,12 @@ public class Bytecode extends TestCase { public void testSetPackageNameInBytecode() throws IOException, ClassNotFoundException { JavaTXCompiler compiler = new JavaTXCompiler(new File(rootDirectory+"packageNameTest.jav")); compiler.typeInference(); - File f = new File(rootDirectory + "Test.class"); + File f = new File(rootDirectory + "TestClass.class"); if(f.exists() && !f.isDirectory()) { f.delete(); } compiler.generateBytecode(null); - f = new File(rootDirectory + "Test.class"); + f = new File(rootDirectory + "TestClass.class"); assertTrue(f.exists()); } } diff --git a/vorgehen.md b/vorgehen.md index 61b62c4f..f6a3f169 100644 --- a/vorgehen.md +++ b/vorgehen.md @@ -28,3 +28,19 @@ * Optional * damit lässt sich ein andere ort zur Ausgabe der Class-files bestimmen +# Tasks +## Class files in richtigen Ordner legen ## +* Wenn Pfad übergeben, dann in Pfad + packageName +* Ohne Pfad, direkt neben die Source File legen +* wenn Source File nicht in richtigem Ordner -> Warnung ausgeben + +## Class files einlesen +* Wenn Classpath übergeben + * Suchen in Classpath + packageName +* Wenn nichts übergeben + * dann currentDirectory + packageName +* Für die Tests muss korrekter Classpath gesetzt werden + +## Class files mit packageNamen versehen +* In die Class file muss noch der korrekte name geschrieben werden + * kann möglicherweise ASM From a3b4ea9b1cc58805be862c379ccc67f426a8f402 Mon Sep 17 00:00:00 2001 From: JanUlrich Date: Sat, 14 Dec 2019 17:50:23 +0100 Subject: [PATCH 04/81] [Bytecde] Generate new directory if given output path doesnt exist yet --- .../java/de/dhbwstuttgart/core/JavaTXCompiler.java | 4 +++- src/test/java/packages/Bytecode.java | 13 +++++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java b/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java index 3c234175..b1bb04ca 100644 --- a/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java +++ b/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java @@ -793,7 +793,9 @@ public class JavaTXCompiler { System.out.println("generating " + name + ".class file ..."); // output = new FileOutputStream(new File(System.getProperty("user.dir") + // "/testBytecode/generatedBC/" +name+".class")); - output = new FileOutputStream(new File(path + File.separator + name.getClassName() + ".class")); + File outputFile = new File(path + File.separator + name.getClassName() + ".class"); + outputFile.getParentFile().mkdirs(); + output = new FileOutputStream(outputFile); output.write(bytecode); output.close(); System.out.println(name + ".class file generated"); diff --git a/src/test/java/packages/Bytecode.java b/src/test/java/packages/Bytecode.java index 1f7854c1..ece46ac8 100644 --- a/src/test/java/packages/Bytecode.java +++ b/src/test/java/packages/Bytecode.java @@ -22,4 +22,17 @@ public class Bytecode extends TestCase { f = new File(rootDirectory + "TestClass.class"); assertTrue(f.exists()); } + + @Test + public void testSetPackageNameInBytecodeAndOutputFolder() throws IOException, ClassNotFoundException { + JavaTXCompiler compiler = new JavaTXCompiler(new File(rootDirectory+"packageNameTest.jav")); + compiler.typeInference(); + File f = new File(rootDirectory + "output/de/test/TestClass.class"); + if(f.exists() && !f.isDirectory()) { + f.delete(); + } + compiler.generateBytecode(rootDirectory + "output/"); + f = new File(rootDirectory + "output/de/test/TestClass.class"); + assertTrue(f.exists()); + } } From c82abcaae5448b7d26d76afa32458cb3191c35e7 Mon Sep 17 00:00:00 2001 From: JanUlrich Date: Sun, 15 Dec 2019 14:49:19 +0100 Subject: [PATCH 05/81] Generate Package names in .class files --- .../dhbwstuttgart/bytecode/BytecodeGen.java | 4 +-- .../bytecode/BytecodeGenMethod.java | 6 ++-- src/test/java/packages/Bytecode.java | 32 +++++++++++++------ src/test/java/packages/ParsePackageName.java | 2 +- .../typeinference/JavaTXCompilerTest.java | 4 +++ src/test/resources/javFiles/Import.jav | 2 +- .../packageTest/de/test/TestClass.jav | 3 ++ .../packageTest/de/test/packageNameTest.jav | 3 -- vorgehen.md | 7 ++++ 9 files changed, 43 insertions(+), 20 deletions(-) create mode 100644 src/test/resources/javFiles/packageTest/de/test/TestClass.jav delete mode 100644 src/test/resources/javFiles/packageTest/de/test/packageNameTest.jav diff --git a/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGen.java b/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGen.java index e0602731..fff65180 100644 --- a/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGen.java +++ b/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGen.java @@ -161,7 +161,7 @@ public class BytecodeGen implements ASTVisitor { className = classOrInterface.getClassName(); - cw.visitSource(className + ".jav", null); + cw.visitSource(className.getClassName() + ".jav", null); isInterface = (classOrInterface.getModifiers() & 512) == 512; @@ -200,7 +200,7 @@ public class BytecodeGen implements ASTVisitor { System.out.println("Signature: => " + sig); } - cw.visit(Opcodes.V1_8, acc, classOrInterface.getClassName().toString(), sig, + cw.visit(Opcodes.V1_8, acc, classOrInterface.getClassName().toString().replace(".", "/"), sig, classOrInterface.getSuperClass().acceptTV(new TypeToDescriptor()), null); isVisited = true; diff --git a/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java b/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java index 9a485561..04f895fe 100644 --- a/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java +++ b/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java @@ -623,7 +623,7 @@ public class BytecodeGenMethod implements StatementVisitor { } String newDesc = addUsedVarsToDesugaredMethodDescriptor(lamDesc); // first check if capturing lambda then invokestatic or invokespecial - Handle arg2 = new Handle(staticOrSpecial, this.className.toString(), desugaredMethodName, newDesc, false); + Handle arg2 = new Handle(staticOrSpecial, this.className.getClassName(), desugaredMethodName, newDesc, false); // Descriptor of functional interface methode SamMethod samMethod = new SamMethod(kindOfLambda.getArgumentList(), lambdaExpression.getType()); // Desc: (this/nothing)TargetType @@ -798,7 +798,7 @@ public class BytecodeGenMethod implements StatementVisitor { } if(methodRefl == null) { - boolean toCreate = !receiverName.equals(className.toString()) && helper.isInCurrPkg(clazz); + boolean toCreate = !receiverName.equals(className.getClassName()) && helper.isInCurrPkg(clazz); if(toCreate) { try { mDesc = helper.getDesc(clazz); @@ -833,7 +833,7 @@ public class BytecodeGenMethod implements StatementVisitor { System.out.println("Methodcall type : " + resultSet.resolveType(methodCall.getType()).resolvedType.acceptTV(new TypeToDescriptor())); List argListMethCall = new LinkedList<>(); String receiverRefl=""; - if(methodRefl == null && receiverName.equals(className.toString())) { + if(methodRefl == null && receiverName.equals(className.getClassName())) { MethodFromMethodCall method = new MethodFromMethodCall(methodCall.arglist, methodCall.getType(), receiverName, genericsAndBoundsMethod, genericsAndBounds); mDesc = method.accept(new DescriptorToString(resultSet)); diff --git a/src/test/java/packages/Bytecode.java b/src/test/java/packages/Bytecode.java index ece46ac8..7a5c4c25 100644 --- a/src/test/java/packages/Bytecode.java +++ b/src/test/java/packages/Bytecode.java @@ -6,33 +6,45 @@ import org.junit.Test; import java.io.File; import java.io.IOException; +import java.lang.reflect.InvocationTargetException; +import java.net.URL; +import java.net.URLClassLoader; public class Bytecode extends TestCase { - public static final String rootDirectory = System.getProperty("user.dir")+"/src/test/resources/javFiles/packageTest/de/test/"; + public static final String rootDirectory = System.getProperty("user.dir")+"/src/test/resources/javFiles/packageTest/"; @Test - public void testSetPackageNameInBytecode() throws IOException, ClassNotFoundException { - JavaTXCompiler compiler = new JavaTXCompiler(new File(rootDirectory+"packageNameTest.jav")); + public void testSetPackageNameInBytecode() throws Exception { + JavaTXCompiler compiler = new JavaTXCompiler(new File(rootDirectory+"de/test/TestClass.jav")); compiler.typeInference(); - File f = new File(rootDirectory + "TestClass.class"); + File f = new File(rootDirectory + "de/test/TestClass.class"); if(f.exists() && !f.isDirectory()) { f.delete(); } compiler.generateBytecode(null); - f = new File(rootDirectory + "TestClass.class"); + f = new File(rootDirectory + "de/test/TestClass.class"); assertTrue(f.exists()); + + + URLClassLoader loader = new URLClassLoader(new URL[]{new URL("file://" + rootDirectory)}); + Class classToTest = loader.loadClass("de.test.TestClass"); + Object instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); } @Test - public void testSetPackageNameInBytecodeAndOutputFolder() throws IOException, ClassNotFoundException { - JavaTXCompiler compiler = new JavaTXCompiler(new File(rootDirectory+"packageNameTest.jav")); + public void testSetPackageNameInBytecodeAndOutputFolder() throws Exception { + JavaTXCompiler compiler = new JavaTXCompiler(new File(rootDirectory+"de/test/TestClass.jav")); compiler.typeInference(); - File f = new File(rootDirectory + "output/de/test/TestClass.class"); + File f = new File(rootDirectory + "de/test/output/de/test/TestClass.class"); if(f.exists() && !f.isDirectory()) { f.delete(); } - compiler.generateBytecode(rootDirectory + "output/"); - f = new File(rootDirectory + "output/de/test/TestClass.class"); + compiler.generateBytecode(rootDirectory + "de/test/output/"); + f = new File(rootDirectory + "de/test/output/de/test/TestClass.class"); assertTrue(f.exists()); + + URLClassLoader loader = new URLClassLoader(new URL[]{new URL("file://" + rootDirectory + "de/test/output/")}); + Class classToTest = loader.loadClass("de.test.TestClass"); + Object instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); } } diff --git a/src/test/java/packages/ParsePackageName.java b/src/test/java/packages/ParsePackageName.java index b54cf90e..9dc0ea9a 100644 --- a/src/test/java/packages/ParsePackageName.java +++ b/src/test/java/packages/ParsePackageName.java @@ -12,7 +12,7 @@ public class ParsePackageName { public static final String rootDirectory = System.getProperty("user.dir")+"/src/test/resources/javFiles/packageTest/de/test/"; @Test public void parsePackage() throws IOException, ClassNotFoundException { - JavaTXCompiler compiler = new JavaTXCompiler(new File(rootDirectory+"packageNameTest.jav")); + JavaTXCompiler compiler = new JavaTXCompiler(new File(rootDirectory+"TestClass.jav")); for(File f : compiler.sourceFiles.keySet()){ SourceFile sf = compiler.sourceFiles.get(f); assert sf.getPkgName().equals("de.test"); diff --git a/src/test/java/typeinference/JavaTXCompilerTest.java b/src/test/java/typeinference/JavaTXCompilerTest.java index 87ae477d..ac724771 100644 --- a/src/test/java/typeinference/JavaTXCompilerTest.java +++ b/src/test/java/typeinference/JavaTXCompilerTest.java @@ -28,6 +28,10 @@ public class JavaTXCompilerTest { execute(new File(rootDirectory+"fc.jav")); } @Test + public void importTest() throws IOException, ClassNotFoundException { + execute(new File(rootDirectory+"Import.jav")); + } + @Test public void lambda() throws IOException, ClassNotFoundException { execute(new File(rootDirectory+"Lambda.jav")); } diff --git a/src/test/resources/javFiles/Import.jav b/src/test/resources/javFiles/Import.jav index c48082ba..2fc3a8b3 100644 --- a/src/test/resources/javFiles/Import.jav +++ b/src/test/resources/javFiles/Import.jav @@ -2,7 +2,7 @@ import java.util.Vector; class Import { void methode(){ - Vector v; + var v; v.add(v); } } \ No newline at end of file diff --git a/src/test/resources/javFiles/packageTest/de/test/TestClass.jav b/src/test/resources/javFiles/packageTest/de/test/TestClass.jav new file mode 100644 index 00000000..6681b36a --- /dev/null +++ b/src/test/resources/javFiles/packageTest/de/test/TestClass.jav @@ -0,0 +1,3 @@ +package de.test; + +public class TestClass{} \ No newline at end of file diff --git a/src/test/resources/javFiles/packageTest/de/test/packageNameTest.jav b/src/test/resources/javFiles/packageTest/de/test/packageNameTest.jav deleted file mode 100644 index ad5b9f63..00000000 --- a/src/test/resources/javFiles/packageTest/de/test/packageNameTest.jav +++ /dev/null @@ -1,3 +0,0 @@ -package de.test; - -class TestClass{} \ No newline at end of file diff --git a/vorgehen.md b/vorgehen.md index f6a3f169..834c49e7 100644 --- a/vorgehen.md +++ b/vorgehen.md @@ -34,6 +34,10 @@ * Ohne Pfad, direkt neben die Source File legen * wenn Source File nicht in richtigem Ordner -> Warnung ausgeben +### Stand ### +* Beinahe abgeschlossen +* TODO: Tests schreiben + ## Class files einlesen * Wenn Classpath übergeben * Suchen in Classpath + packageName @@ -41,6 +45,9 @@ * dann currentDirectory + packageName * Für die Tests muss korrekter Classpath gesetzt werden +### Stand ### +TODO + ## Class files mit packageNamen versehen * In die Class file muss noch der korrekte name geschrieben werden * kann möglicherweise ASM From bb75fca0d71273df971910da362eff6807afdd39 Mon Sep 17 00:00:00 2001 From: JanUlrich Date: Sun, 15 Dec 2019 14:57:03 +0100 Subject: [PATCH 06/81] Add ImportTest --- src/test/java/packages/ImportTest.java | 44 +++++++++++++++++++ .../packageTest/de/test/ImportTest.jav | 9 ++++ .../javFiles/packageTest/de/test/ToImport.jav | 4 ++ 3 files changed, 57 insertions(+) create mode 100644 src/test/java/packages/ImportTest.java create mode 100644 src/test/resources/javFiles/packageTest/de/test/ImportTest.jav create mode 100644 src/test/resources/javFiles/packageTest/de/test/ToImport.jav diff --git a/src/test/java/packages/ImportTest.java b/src/test/java/packages/ImportTest.java new file mode 100644 index 00000000..a6fbc075 --- /dev/null +++ b/src/test/java/packages/ImportTest.java @@ -0,0 +1,44 @@ +package packages; + +import de.dhbwstuttgart.core.JavaTXCompiler; +import junit.framework.TestCase; +import org.junit.Before; +import org.junit.Test; + +import java.io.File; +import java.io.IOException; + +public class ImportTest extends TestCase { + + public static final String rootDirectory = System.getProperty("user.dir")+"/src/test/resources/javFiles/packageTest/de/test/"; + + + public ImportTest() throws ClassNotFoundException, IOException { + /* + Generate ToImport class in rootDirectory and in output-Directory + */ + JavaTXCompiler compiler = new JavaTXCompiler(new File(rootDirectory+"ToImport.jav")); + compiler.typeInference(); + compiler.generateBytecode(rootDirectory + "output/"); + File f = new File(rootDirectory + "output/de/test/ToImport.class"); + assertTrue(f.exists()); + compiler = new JavaTXCompiler(new File(rootDirectory+"ToImport.jav")); + compiler.typeInference(); + compiler.generateBytecode(null); + f = new File(rootDirectory + "output/de/test/ToImport.class"); + assertTrue(f.exists()); + } + + @Test + public void testSetPackageNameInBytecodeAndOutputFolder() throws IOException, ClassNotFoundException { + JavaTXCompiler compiler = new JavaTXCompiler(new File(rootDirectory+"ImportTest.jav")); + compiler.typeInference(); + File f = new File(rootDirectory + "output/de/test/ImportTest.class"); + if(f.exists() && !f.isDirectory()) { + f.delete(); + } + compiler.generateBytecode(rootDirectory + "output/"); + f = new File(rootDirectory + "output/de/test/ImportTest.class"); + assertTrue(f.exists()); + } +} diff --git a/src/test/resources/javFiles/packageTest/de/test/ImportTest.jav b/src/test/resources/javFiles/packageTest/de/test/ImportTest.jav new file mode 100644 index 00000000..58b6fc0b --- /dev/null +++ b/src/test/resources/javFiles/packageTest/de/test/ImportTest.jav @@ -0,0 +1,9 @@ +package de.test; + +import de.test.ToImport; + +class ImportTest{ + void methode(){ + new ToImport(); + } +} \ No newline at end of file diff --git a/src/test/resources/javFiles/packageTest/de/test/ToImport.jav b/src/test/resources/javFiles/packageTest/de/test/ToImport.jav new file mode 100644 index 00000000..3afdba54 --- /dev/null +++ b/src/test/resources/javFiles/packageTest/de/test/ToImport.jav @@ -0,0 +1,4 @@ +package de.test; + +class ToImport{ +} \ No newline at end of file From 74622550c26f33e3a2111ed4f381f38bdb9b02fd Mon Sep 17 00:00:00 2001 From: JanUlrich Date: Sun, 15 Dec 2019 21:58:29 +0100 Subject: [PATCH 07/81] Add Logfiles Directory, but ignore all files inside it --- .gitignore | 3 +++ logFiles/.gitkeep | 0 2 files changed, 3 insertions(+) create mode 100644 logFiles/.gitkeep diff --git a/.gitignore b/.gitignore index a897efd8..fe551a27 100644 --- a/.gitignore +++ b/.gitignore @@ -23,3 +23,6 @@ bin # manually/ + +logFiles/** +!logFiles/.gitkeep diff --git a/logFiles/.gitkeep b/logFiles/.gitkeep new file mode 100644 index 00000000..e69de29b From afd2c21ca8f9b7aaef31364cb12c82d9d0f58c9a Mon Sep 17 00:00:00 2001 From: JanUlrich Date: Mon, 16 Dec 2019 00:54:00 +0100 Subject: [PATCH 08/81] Add classPath option to JavaTXCompiler and parse with URLClassLoader --- .../de/dhbwstuttgart/core/JavaTXCompiler.java | 35 +++++++++++++------ .../environment/CompilationEnvironment.java | 4 +-- .../StatementGenerator.java | 18 ++++++++-- .../SyntaxTreeGenerator.java | 5 +-- .../parser/scope/GatherNames.java | 14 ++++---- src/test/java/packages/ImportTest.java | 6 +++- vorgehen.md | 10 ++++-- 7 files changed, 63 insertions(+), 29 deletions(-) diff --git a/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java b/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java index b1bb04ca..61f90e42 100644 --- a/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java +++ b/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java @@ -1,6 +1,7 @@ //PL 2018-12-19: typeInferenceOld nach typeInference uebertragen package de.dhbwstuttgart.core; +import com.google.common.collect.Lists; import de.dhbwstuttgart.bytecode.BytecodeGen; import de.dhbwstuttgart.bytecode.Exception.BytecodeGeneratorError; import de.dhbwstuttgart.bytecode.genericsGenerator.GeneratedGenericsFinder; @@ -41,6 +42,8 @@ import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; +import java.net.URL; +import java.net.URLClassLoader; import java.util.*; import java.util.function.Function; import java.util.stream.Collectors; @@ -50,24 +53,34 @@ public class JavaTXCompiler { public static JavaTXCompiler INSTANCE; final CompilationEnvironment environment; - Boolean resultmodel = true; + Boolean resultmodel = true; public final Map sourceFiles = new HashMap<>(); Boolean log = true; //gibt an ob ein Log-File nach System.getProperty("user.dir")+"src/test/java/logFiles" geschrieben werden soll? public volatile UnifyTaskModel usedTasks = new UnifyTaskModel(); - - public JavaTXCompiler(File sourceFile) throws IOException, ClassNotFoundException { - this(Arrays.asList(sourceFile)); - INSTANCE = this; - } + private final ClassLoader classLoader; + + public JavaTXCompiler(File sourceFile) throws IOException, ClassNotFoundException { + this(Arrays.asList(sourceFile), null); + INSTANCE = this; + } public JavaTXCompiler(File sourceFile, Boolean log) throws IOException, ClassNotFoundException { this(sourceFile); this.log = log; INSTANCE = this; } - - public JavaTXCompiler(List sources) throws IOException, ClassNotFoundException { - environment = new CompilationEnvironment(sources); + + public JavaTXCompiler(List sourceFiles) throws IOException, ClassNotFoundException { + this(sourceFiles, null); + INSTANCE = this; + } + public JavaTXCompiler(List sources, List contextPath) throws IOException, ClassNotFoundException { + if(contextPath == null || contextPath.isEmpty()){ + //When no contextPaths are given, the working directory is the sources root + contextPath = Lists.newArrayList(new URL("file://" + System.getProperty("user.dir"))); + } + classLoader = new URLClassLoader(contextPath.toArray(new URL[0]), ClassLoader.getSystemClassLoader()); + environment = new CompilationEnvironment(sources); for (File s : sources) { sourceFiles.put(s, parse(s)); } @@ -708,9 +721,9 @@ public class JavaTXCompiler { private SourceFile parse(File sourceFile) throws IOException, java.lang.ClassNotFoundException { CompilationUnitContext tree = JavaTXParser.parse(sourceFile); - SyntaxTreeGenerator generator = new SyntaxTreeGenerator(environment.getRegistry(sourceFile), + SyntaxTreeGenerator generator = new SyntaxTreeGenerator(environment.getRegistry(sourceFile, classLoader), new GenericsRegistry(null)); - SourceFile ret = generator.convert(tree, environment.packageCrawler); + SourceFile ret = generator.convert(tree, environment.packageCrawler, classLoader); return ret; } diff --git a/src/main/java/de/dhbwstuttgart/environment/CompilationEnvironment.java b/src/main/java/de/dhbwstuttgart/environment/CompilationEnvironment.java index 3d450183..7b759e27 100644 --- a/src/main/java/de/dhbwstuttgart/environment/CompilationEnvironment.java +++ b/src/main/java/de/dhbwstuttgart/environment/CompilationEnvironment.java @@ -67,10 +67,10 @@ public class CompilationEnvironment { this.packageCrawler = new PackageCrawler(librarys); } - public JavaClassRegistry getRegistry(File forSourceFile) throws ClassNotFoundException, IOException { + public JavaClassRegistry getRegistry(File forSourceFile, ClassLoader classLoader) throws ClassNotFoundException, IOException { Map allNames; CompilationUnitContext tree = JavaTXParser.parse(forSourceFile); - allNames = GatherNames.getNames(tree, packageCrawler); + allNames = GatherNames.getNames(tree, packageCrawler, classLoader); return new JavaClassRegistry(allNames); } diff --git a/src/main/java/de/dhbwstuttgart/parser/SyntaxTreeGenerator/StatementGenerator.java b/src/main/java/de/dhbwstuttgart/parser/SyntaxTreeGenerator/StatementGenerator.java index 067430e2..9305310d 100644 --- a/src/main/java/de/dhbwstuttgart/parser/SyntaxTreeGenerator/StatementGenerator.java +++ b/src/main/java/de/dhbwstuttgart/parser/SyntaxTreeGenerator/StatementGenerator.java @@ -279,9 +279,21 @@ public class StatementGenerator { } - private Statement convert(Java8Parser.ClassInstanceCreationExpressionContext stmt) { - //TODO - throw new NotImplementedException(); + private Statement convert(Java8Parser.ClassInstanceCreationExpressionContext newExpression) { + Java8Parser.TypeArgumentsContext genericArgs = null; + if(newExpression.expressionName()!= null)throw new NotImplementedException(); + if(newExpression.typeArgumentsOrDiamond()!= null){ + if(newExpression.typeArgumentsOrDiamond().typeArguments()!=null){ + genericArgs = newExpression.typeArgumentsOrDiamond().typeArguments(); + } + } + if(newExpression.typeArguments()!= null)throw new NotImplementedException(); + + TerminalNode identifier = newExpression.Identifier(0); + RefType newClass = (RefType) TypeGenerator.convertTypeName(identifier.getText(),genericArgs,identifier.getSymbol(),reg,generics); + + ArgumentList args = convert(newExpression.argumentList()); + return new NewClass(newClass, args, newExpression.getStart()); } private Statement convert(Java8Parser.PreIncrementExpressionContext stmt) { diff --git a/src/main/java/de/dhbwstuttgart/parser/SyntaxTreeGenerator/SyntaxTreeGenerator.java b/src/main/java/de/dhbwstuttgart/parser/SyntaxTreeGenerator/SyntaxTreeGenerator.java index 140b3432..c374dd06 100644 --- a/src/main/java/de/dhbwstuttgart/parser/SyntaxTreeGenerator/SyntaxTreeGenerator.java +++ b/src/main/java/de/dhbwstuttgart/parser/SyntaxTreeGenerator/SyntaxTreeGenerator.java @@ -19,6 +19,7 @@ import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric; import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder; import java.lang.reflect.Modifier; +import java.net.URL; import java.sql.Ref; import java.util.*; import java.util.stream.Collectors; @@ -74,10 +75,10 @@ public class SyntaxTreeGenerator{ return ret; } - public SourceFile convert(Java8Parser.CompilationUnitContext ctx, PackageCrawler packageCrawler) throws ClassNotFoundException{ + public SourceFile convert(Java8Parser.CompilationUnitContext ctx, PackageCrawler packageCrawler, ClassLoader classLoader) throws ClassNotFoundException{ if(ctx.packageDeclaration()!=null)this.pkgName = convert(ctx.packageDeclaration()); List classes = new ArrayList<>(); - Map imports = GatherNames.getImports(ctx, packageCrawler); + Map imports = GatherNames.getImports(ctx, packageCrawler, classLoader); this.imports = imports.keySet().stream().map(name -> reg.getName(name)).collect(Collectors.toSet()); for(Java8Parser.TypeDeclarationContext typeDecl : ctx.typeDeclaration()){ ClassOrInterface newClass; diff --git a/src/main/java/de/dhbwstuttgart/parser/scope/GatherNames.java b/src/main/java/de/dhbwstuttgart/parser/scope/GatherNames.java index 69481508..31c6d375 100644 --- a/src/main/java/de/dhbwstuttgart/parser/scope/GatherNames.java +++ b/src/main/java/de/dhbwstuttgart/parser/scope/GatherNames.java @@ -1,9 +1,8 @@ package de.dhbwstuttgart.parser.scope; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import java.net.URL; +import java.net.URLClassLoader; +import java.util.*; import de.dhbwstuttgart.parser.antlr.Java8BaseListener; import de.dhbwstuttgart.syntaxtree.AbstractASTWalker; @@ -15,7 +14,7 @@ import de.dhbwstuttgart.parser.antlr.Java8Parser; public class GatherNames { - public static Map getNames(Java8Parser.CompilationUnitContext ctx, PackageCrawler packages) throws ClassNotFoundException{ + public static Map getNames(Java8Parser.CompilationUnitContext ctx, PackageCrawler packages, ClassLoader classLoader) throws ClassNotFoundException{ Map ret = new HashMap<>(); String pkgName = getPackageName(ctx); String nameString = ""; @@ -64,14 +63,13 @@ public class GatherNames { } } } - ret.putAll(getImports(ctx, packages)); + ret.putAll(getImports(ctx, packages, classLoader)); return ret; } - public static Map getImports(Java8Parser.CompilationUnitContext ctx, PackageCrawler packages) throws ClassNotFoundException { + public static Map getImports(Java8Parser.CompilationUnitContext ctx, PackageCrawler packages, ClassLoader classLoader) throws ClassNotFoundException { Map ret = new HashMap<>(); - ClassLoader classLoader = ClassLoader.getSystemClassLoader(); //ret.putAll(packages.getClassNames("java.lang")); for(Java8Parser.ImportDeclarationContext importDeclCtx : ctx.importDeclaration()){ if(importDeclCtx.singleTypeImportDeclaration() != null){ diff --git a/src/test/java/packages/ImportTest.java b/src/test/java/packages/ImportTest.java index a6fbc075..6487c9ab 100644 --- a/src/test/java/packages/ImportTest.java +++ b/src/test/java/packages/ImportTest.java @@ -1,5 +1,6 @@ package packages; +import com.google.common.collect.Lists; import de.dhbwstuttgart.core.JavaTXCompiler; import junit.framework.TestCase; import org.junit.Before; @@ -7,6 +8,7 @@ import org.junit.Test; import java.io.File; import java.io.IOException; +import java.net.URL; public class ImportTest extends TestCase { @@ -31,7 +33,9 @@ public class ImportTest extends TestCase { @Test public void testSetPackageNameInBytecodeAndOutputFolder() throws IOException, ClassNotFoundException { - JavaTXCompiler compiler = new JavaTXCompiler(new File(rootDirectory+"ImportTest.jav")); + JavaTXCompiler compiler = new JavaTXCompiler( + Lists.newArrayList(new File(rootDirectory+"ImportTest.jav")), + Lists.newArrayList(new URL("file://"+rootDirectory+"output/"))); compiler.typeInference(); File f = new File(rootDirectory + "output/de/test/ImportTest.class"); if(f.exists() && !f.isDirectory()) { diff --git a/vorgehen.md b/vorgehen.md index 834c49e7..b9af4d76 100644 --- a/vorgehen.md +++ b/vorgehen.md @@ -15,10 +15,13 @@ * Java kompiliert in den gleichen Ordner wie die source file * Java erhält eine liste von Source Files, die es kompilieren soll * anhand von deren Standort lassen sich relativ die Position von kompilierten Class-files bestimmen + * macht der javac Compiler allerdings nicht + * er nimmt sein Running Directory als classPath standardmäßig, falls keiner angegeben + * javac geht davon aus, dass CP richtig gesetzt wird, oder javac im Source-Root ausgeführt wird * -cp path or -classpath path Specifies where to find user class files, and (optionally) annotation processors and source files. This class path overrides the user class path in the CLASSPATH environment variable. If neither CLASSPATH, -cp nor -classpath is specified, then the - user class path is the current directory. See Setting the Class Path. + user class path is the current directory. See Setting the Class Path. * Compiler kontrolliert nicht, ob package im korrekten Ordner ist * auch keine Warnung @@ -46,8 +49,11 @@ * Für die Tests muss korrekter Classpath gesetzt werden ### Stand ### -TODO +TODO: +* es muss überall wo im Quellcode ClassLoader.getSystemClassLoader() oder ein andere Classloader verwendet wird, + * dieser ausgetauscht werden mit dem classLaoder, welcher bei der Instanzierung von JavaTXCompiler erstellt wird ## Class files mit packageNamen versehen * In die Class file muss noch der korrekte name geschrieben werden * kann möglicherweise ASM + * wurde bereits erledigt -> TODO: Testen From 1d16b9f2b95a8fcb439e2eea9825f11a520d2998 Mon Sep 17 00:00:00 2001 From: JanUlrich Date: Mon, 16 Dec 2019 00:55:04 +0100 Subject: [PATCH 09/81] Documentation --- vorgehen.md | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/vorgehen.md b/vorgehen.md index 834c49e7..c85f2767 100644 --- a/vorgehen.md +++ b/vorgehen.md @@ -41,13 +41,21 @@ ## Class files einlesen * Wenn Classpath übergeben * Suchen in Classpath + packageName + * Müsste eigentlich UTLClassLoader automatisch machen (also packageNamen anfügen) * Wenn nichts übergeben * dann currentDirectory + packageName * Für die Tests muss korrekter Classpath gesetzt werden ### Stand ### -TODO +* In der GatherNames Klasse muss ein URLClassloader angefügt werden + * siehe ImportTest +* Es muss ein Classpath Parameter an den Compiler angefügt werden + * Wird dieser nicht gesetzt, so wird nur im Root-Verzeichnis nach Klassen gesucht + * root = Input Jav-Files - deren Package Namen ## Class files mit packageNamen versehen * In die Class file muss noch der korrekte name geschrieben werden - * kann möglicherweise ASM + * Kann ASM mittesl `cw.visit("name/mit/slashe/Getrennt"..` +## Stand ## +* bereits implementiert + * TODO TESTEN From 0378c17e7d61de3bf7c836e1aab823ff60038d58 Mon Sep 17 00:00:00 2001 From: JanUlrich Date: Sun, 22 Dec 2019 14:27:54 +0100 Subject: [PATCH 10/81] ClassLoader austauschen gegen den Classloader, welcher in JavaCompilerCore erstellt wird --- .../de/dhbwstuttgart/bytecode/BytecodeGen.java | 4 ++-- .../bytecode/BytecodeGenMethod.java | 18 ++++++++++-------- .../de/dhbwstuttgart/core/JavaTXCompiler.java | 8 ++++---- .../environment/CompilationEnvironment.java | 1 - .../SyntaxTreeGenerator/FCGenerator.java | 18 +++++++++--------- .../sat/asp/writer/ASPFactory.java | 8 ++++---- .../sat/asp/writer/ASPGencayFactory.java | 8 ++++---- .../syntaxtree/factory/UnifyTypeFactory.java | 4 ++-- src/test/java/asp/ClingoTest.java | 2 +- src/test/java/asp/UnifyWithoutWildcards.java | 2 +- src/test/java/asp/gencay/GeneratorTest.java | 4 ++-- src/test/java/asp/typeinference/ASPTest.java | 2 +- .../finiteClosure/SuperInterfacesTest.java | 4 ++-- vorgehen.md | 2 ++ 14 files changed, 44 insertions(+), 41 deletions(-) diff --git a/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGen.java b/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGen.java index fff65180..b5ac3e0b 100644 --- a/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGen.java +++ b/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGen.java @@ -270,7 +270,7 @@ public class BytecodeGen implements ASTVisitor { constructorPos += 1; BytecodeGenMethod gen = new BytecodeGenMethod(className, superClass, resultSet, field, mv, paramsAndLocals, cw, - genericsAndBoundsMethod, genericsAndBounds, isInterface, classFiles, sf, path, block, constructorPos); + genericsAndBoundsMethod, genericsAndBounds, isInterface, classFiles, sf, path, block, constructorPos, ClassLoader.getSystemClassLoader()); if (!field.getParameterList().iterator().hasNext() && !(field.block.statements.get(field.block.statements.size() - 1) instanceof ReturnVoid)) { mv.visitInsn(Opcodes.RETURN); @@ -351,7 +351,7 @@ public class BytecodeGen implements ASTVisitor { mv.visitCode(); BytecodeGenMethod gen = new BytecodeGenMethod(className, superClass, resultSet, method, mv, paramsAndLocals, cw, - genericsAndBoundsMethod, genericsAndBounds, isInterface, classFiles, sf, path); + genericsAndBoundsMethod, genericsAndBounds, isInterface, classFiles, sf, path, ClassLoader.getSystemClassLoader()); mv.visitMaxs(0, 0); mv.visitEnd(); diff --git a/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java b/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java index 04f895fe..b0ada708 100644 --- a/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java +++ b/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java @@ -77,11 +77,13 @@ public class BytecodeGenMethod implements StatementVisitor { private int constructorPos = 0; private ArrayList varsFunInterface = new ArrayList<>();; + private final ClassLoader classLoader; + // generate bytecode for constructor public BytecodeGenMethod(JavaClassName className, String superClass, ResultSet resultSet, Method m, MethodVisitor mv, HashMap paramsAndLocals, ClassWriter cw, HashMap genericsAndBoundsMethod, HashMap genericsAndBounds, boolean isInterface, HashMap classFiles, - SourceFile sf, String path, Block block, int constructorPos) { + SourceFile sf, String path, Block block, int constructorPos, ClassLoader classLoader) { this.className = className; this.superClass = superClass; @@ -99,16 +101,15 @@ public class BytecodeGenMethod implements StatementVisitor { this.path = path; this.lamCounter = -1; this.constructorPos = constructorPos; + this.classLoader = classLoader; if(block != null) this.blockFieldInit = block; this.m.block.accept(this); - - } public BytecodeGenMethod(JavaClassName className, String superClass,ResultSet resultSet, Method m, MethodVisitor mv, HashMap paramsAndLocals, ClassWriter cw, HashMap genericsAndBoundsMethod, - HashMap genericsAndBounds, boolean isInterface, HashMap classFiles, SourceFile sf,String path) { + HashMap genericsAndBounds, boolean isInterface, HashMap classFiles, SourceFile sf,String path, ClassLoader classLoader) { this.className = className; this.superClass = superClass; @@ -125,14 +126,14 @@ public class BytecodeGenMethod implements StatementVisitor { this.sf = sf; this.path = path; this.lamCounter = -1; + this.classLoader = classLoader; if (!isInterface) this.m.block.accept(this); - } public BytecodeGenMethod(JavaClassName className, ClassWriter cw, LambdaExpression lambdaExpression, ArrayList usedVars, ResultSet resultSet, MethodVisitor mv, int indexOfFirstParamLam, boolean isInterface, HashMap classFiles, String path, int lamCounter, SourceFile sf,HashMap genericsAndBoundsMethod, - HashMap genericsAndBounds) { + HashMap genericsAndBounds, ClassLoader classLoader) { this.className = className; this.cw = cw; this.resultSet = resultSet; @@ -145,6 +146,7 @@ public class BytecodeGenMethod implements StatementVisitor { this.sf = sf; this.genericsAndBoundsMethod = genericsAndBoundsMethod; this.genericsAndBounds = genericsAndBounds; + this.classLoader = classLoader; Iterator itr = lambdaExpression.params.iterator(); int i = indexOfFirstParamLam; @@ -637,7 +639,7 @@ public class BytecodeGenMethod implements StatementVisitor { new BytecodeGenMethod(className, cw,lambdaExpression, usedVars,this.resultSet, mvLambdaBody, indexOfFirstParamLam, isInterface, classFiles,this.path, lamCounter, sf, genericsAndBoundsMethod, - genericsAndBounds); + genericsAndBounds, classLoader); mvLambdaBody.visitMaxs(0, 0); mvLambdaBody.visitEnd(); @@ -757,7 +759,7 @@ public class BytecodeGenMethod implements StatementVisitor { MethodCallHelper helper = new MethodCallHelper(methodCall, sf, resultSet, path); - ClassLoader cLoader = ClassLoader.getSystemClassLoader(); + ClassLoader cLoader = this.classLoader; // This will be used if the class is not standard class (not in API) ClassLoader cLoader2; diff --git a/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java b/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java index 61f90e42..f79a3a35 100644 --- a/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java +++ b/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java @@ -98,7 +98,7 @@ public class JavaTXCompiler { for (JavaClassName name : sourceFiles.get(forSourceFile).getImports()) { //TODO: Hier werden imports von eigenen (.jav) Klassen nicht beachtet ClassOrInterface importedClass = ASTFactory.createClass( - ClassLoader.getSystemClassLoader().loadClass(name.toString())); + classLoader.loadClass(name.toString())); importedClasses.add(importedClass); } allClasses.addAll(importedClasses); @@ -135,7 +135,7 @@ public class JavaTXCompiler { for (JavaClassName name : forSourceFile.getImports()) { // TODO: Hier werden imports von eigenen (.jav) Klassen nicht beachtet ClassOrInterface importedClass = ASTFactory - .createClass(ClassLoader.getSystemClassLoader().loadClass(name.toString())); + .createClass(classLoader.loadClass(name.toString())); importedClasses.add(importedClass); allClasses.addAll(importedClasses); } @@ -304,7 +304,7 @@ public class JavaTXCompiler { logFile = logFile == null ? new FileWriter(new File("log_" + sourceFiles.keySet().iterator().next().getName())) : logFile; - IFiniteClosure finiteClosure = UnifyTypeFactory.generateFC(allClasses, logFile); + IFiniteClosure finiteClosure = UnifyTypeFactory.generateFC(allClasses, logFile, classLoader); System.out.println(finiteClosure); urm = new UnifyResultModel(cons, finiteClosure); urm.addUnifyResultListener(resultListener); @@ -472,7 +472,7 @@ public class JavaTXCompiler { // File(System.getProperty("user.dir")+"/src/test/resources/logFiles/"+"log_"+sourceFiles.keySet().iterator().next().getName())); new FileWriter(new File(System.getProperty("user.dir") + "/logFiles/" + "log_" + sourceFiles.keySet().iterator().next().getName())); - IFiniteClosure finiteClosure = UnifyTypeFactory.generateFC(allClasses, logFile); + IFiniteClosure finiteClosure = UnifyTypeFactory.generateFC(allClasses, logFile, classLoader); System.out.println(finiteClosure); ConstraintSet unifyCons = UnifyTypeFactory.convert(cons); diff --git a/src/main/java/de/dhbwstuttgart/environment/CompilationEnvironment.java b/src/main/java/de/dhbwstuttgart/environment/CompilationEnvironment.java index 7b759e27..43196b6f 100644 --- a/src/main/java/de/dhbwstuttgart/environment/CompilationEnvironment.java +++ b/src/main/java/de/dhbwstuttgart/environment/CompilationEnvironment.java @@ -50,7 +50,6 @@ public class CompilationEnvironment { */ //String bootClassPath = System.getProperty("sun.boot.class.path"); // ClassLoader cl = ClassLoader.getPlatformClassLoader(); - ClassLoader cl = ClassLoader.getSystemClassLoader(); String bootClassPath = System.getProperty("java.class.path"); librarys = new ArrayList<>(); for(String path : bootClassPath.split(File.pathSeparator)) { diff --git a/src/main/java/de/dhbwstuttgart/parser/SyntaxTreeGenerator/FCGenerator.java b/src/main/java/de/dhbwstuttgart/parser/SyntaxTreeGenerator/FCGenerator.java index 29c53981..71dcef52 100644 --- a/src/main/java/de/dhbwstuttgart/parser/SyntaxTreeGenerator/FCGenerator.java +++ b/src/main/java/de/dhbwstuttgart/parser/SyntaxTreeGenerator/FCGenerator.java @@ -22,16 +22,16 @@ public class FCGenerator { * * @param availableClasses - Alle geparsten Klassen */ - public static Set toUnifyFC(Collection availableClasses) throws ClassNotFoundException { - return toFC(availableClasses).stream().map(t -> UnifyTypeFactory.convert(t)).collect(Collectors.toSet()); + public static Set toUnifyFC(Collection availableClasses, ClassLoader classLoader) throws ClassNotFoundException { + return toFC(availableClasses, classLoader).stream().map(t -> UnifyTypeFactory.convert(t)).collect(Collectors.toSet()); } - public static Set toFC(Collection availableClasses) throws ClassNotFoundException { + public static Set toFC(Collection availableClasses, ClassLoader classLoader) throws ClassNotFoundException { HashSet pairs = new HashSet<>(); //PL 2018-09-18: gtvs vor die for-Schleife gezogen, damit immer die gleichen Typeplaceholder eingesetzt werden. HashMap gtvs = new HashMap<>(); for(ClassOrInterface cly : availableClasses){ - pairs.addAll(getSuperTypes(cly, availableClasses, gtvs)); + pairs.addAll(getSuperTypes(cly, availableClasses, gtvs, classLoader)); } return pairs; } @@ -48,8 +48,8 @@ public class FCGenerator { * @param forType * @return */ - private static List getSuperTypes(ClassOrInterface forType, Collection availableClasses) throws ClassNotFoundException { - return getSuperTypes(forType, availableClasses, new HashMap<>()); + private static List getSuperTypes(ClassOrInterface forType, Collection availableClasses, ClassLoader classLoader) throws ClassNotFoundException { + return getSuperTypes(forType, availableClasses, new HashMap<>(), classLoader); } /** @@ -61,7 +61,7 @@ public class FCGenerator { * @throws ClassNotFoundException */ private static List getSuperTypes(ClassOrInterface forType, Collection availableClasses, - HashMap gtvs) throws ClassNotFoundException { + HashMap gtvs, ClassLoader classLoader) throws ClassNotFoundException { List params = new ArrayList<>(); //Die GTVs, die in forType hinzukommen: HashMap newGTVs = new HashMap<>(); @@ -86,7 +86,7 @@ public class FCGenerator { ClassOrInterface superClass; if(!hasSuperclass.isPresent()) //Wenn es die Klasse in den available Klasses nicht gibt wird sie im Classpath gesucht. Ansonsten Exception { - superClass = ASTFactory.createClass(ClassLoader.getSystemClassLoader().loadClass(superType.getName().toString())); + superClass = ASTFactory.createClass(classLoader.loadClass(superType.getName().toString())); }else{ superClass = hasSuperclass.get(); } @@ -120,7 +120,7 @@ public class FCGenerator { if(superClass.getClassName().equals(ASTFactory.createObjectClass().getClassName())){ superTypes = Arrays.asList(new Pair(ASTFactory.createObjectType(), ASTFactory.createObjectType(), PairOperator.SMALLER)); }else{ - superTypes = getSuperTypes(superClass, availableClasses, newGTVs); + superTypes = getSuperTypes(superClass, availableClasses, newGTVs, classLoader); } retList.add(ret); diff --git a/src/main/java/de/dhbwstuttgart/sat/asp/writer/ASPFactory.java b/src/main/java/de/dhbwstuttgart/sat/asp/writer/ASPFactory.java index 1777eabd..8cb61fee 100644 --- a/src/main/java/de/dhbwstuttgart/sat/asp/writer/ASPFactory.java +++ b/src/main/java/de/dhbwstuttgart/sat/asp/writer/ASPFactory.java @@ -16,9 +16,9 @@ import java.util.*; public class ASPFactory implements TypeVisitor{ - public static String generateASP(ConstraintSet constraints, Collection fcClasses) throws ClassNotFoundException{ + public static String generateASP(ConstraintSet constraints, Collection fcClasses, ClassLoader classLoader) throws ClassNotFoundException{ ASPFactory factory = new ASPFactory(); - factory.convertFC(fcClasses); + factory.convertFC(fcClasses, classLoader); List> constraints1 = constraints.cartesianProduct().iterator().next(); for(Constraint constraint : constraints1){ for(Pair p : constraint){ @@ -32,8 +32,8 @@ public class ASPFactory implements TypeVisitor{ ASPWriter writer = new ASPWriter(); boolean isFCType = false; - private void convertFC(Collection classes) throws ClassNotFoundException { - Set fc = FCGenerator.toFC(classes); + private void convertFC(Collection classes, ClassLoader classLoader) throws ClassNotFoundException { + Set fc = FCGenerator.toFC(classes, classLoader); isFCType = true; for(Pair fcp : fc){ convertPair(fcp); diff --git a/src/main/java/de/dhbwstuttgart/sat/asp/writer/ASPGencayFactory.java b/src/main/java/de/dhbwstuttgart/sat/asp/writer/ASPGencayFactory.java index 11408c25..242c63e6 100644 --- a/src/main/java/de/dhbwstuttgart/sat/asp/writer/ASPGencayFactory.java +++ b/src/main/java/de/dhbwstuttgart/sat/asp/writer/ASPGencayFactory.java @@ -55,9 +55,9 @@ public class ASPGencayFactory implements TypeVisitor { return ret; } - public static String generateASP(ConstraintSet constraints, Collection fcClasses) throws ClassNotFoundException{ + public static String generateASP(ConstraintSet constraints, Collection fcClasses, ClassLoader classLoader) throws ClassNotFoundException{ ASPGencayFactory factory = new ASPGencayFactory(); - factory.convertFC(fcClasses); + factory.convertFC(fcClasses, classLoader); List> constraints1 = constraints.cartesianProduct().iterator().next(); for(Constraint constraint : constraints1){ for(Pair p : constraint){ @@ -69,8 +69,8 @@ public class ASPGencayFactory implements TypeVisitor { return factory.writer.getASPFile(); } - private void convertFC(Collection classes) throws ClassNotFoundException { - Set fc = FCGenerator.toFC(classes); + private void convertFC(Collection classes, ClassLoader classLoader) throws ClassNotFoundException { + Set fc = FCGenerator.toFC(classes, classLoader); isFCType = true; for(Pair fcp : fc){ generateTheta((RefType) fcp.TA1); diff --git a/src/main/java/de/dhbwstuttgart/syntaxtree/factory/UnifyTypeFactory.java b/src/main/java/de/dhbwstuttgart/syntaxtree/factory/UnifyTypeFactory.java index 4241af34..33d137eb 100644 --- a/src/main/java/de/dhbwstuttgart/syntaxtree/factory/UnifyTypeFactory.java +++ b/src/main/java/de/dhbwstuttgart/syntaxtree/factory/UnifyTypeFactory.java @@ -31,7 +31,7 @@ public class UnifyTypeFactory { private static ArrayList PLACEHOLDERS = new ArrayList<>(); - public static FiniteClosure generateFC(List fromClasses, Writer logFile) throws ClassNotFoundException { + public static FiniteClosure generateFC(List fromClasses, Writer logFile, ClassLoader classLoader) throws ClassNotFoundException { /* Die transitive Hülle muss funktionieren. Man darf schreiben List extends AL @@ -42,7 +42,7 @@ public class UnifyTypeFactory { Generell dürfen sie immer die gleichen Namen haben. TODO: die transitive Hülle bilden */ - return new FiniteClosure(FCGenerator.toUnifyFC(fromClasses), logFile); + return new FiniteClosure(FCGenerator.toUnifyFC(fromClasses, classLoader), logFile); } public static UnifyPair generateSmallerPair(UnifyType tl, UnifyType tr){ diff --git a/src/test/java/asp/ClingoTest.java b/src/test/java/asp/ClingoTest.java index 90635bde..ea09add3 100644 --- a/src/test/java/asp/ClingoTest.java +++ b/src/test/java/asp/ClingoTest.java @@ -25,7 +25,7 @@ public class ClingoTest { @Test public void test() throws IOException, InterruptedException, ClassNotFoundException { String content = ""; - content = ASPFactory.generateASP(this.getPairs(), this.getFC()); + content = ASPFactory.generateASP(this.getPairs(), this.getFC(), ClassLoader.getSystemClassLoader()); PrintWriter writer = new PrintWriter(tempDirectory + "test.lp", "UTF-8"); writer.println(content); diff --git a/src/test/java/asp/UnifyWithoutWildcards.java b/src/test/java/asp/UnifyWithoutWildcards.java index 6f69d639..c1a84702 100644 --- a/src/test/java/asp/UnifyWithoutWildcards.java +++ b/src/test/java/asp/UnifyWithoutWildcards.java @@ -40,7 +40,7 @@ public class UnifyWithoutWildcards { public ResultSet run(ConstraintSet toTest) throws IOException, InterruptedException, ClassNotFoundException { String content = ""; - content = ASPFactory.generateASP(toTest, this.getFC()); + content = ASPFactory.generateASP(toTest, this.getFC(), ClassLoader.getSystemClassLoader()); PrintWriter writer = new PrintWriter(tempDirectory + "test.lp", "UTF-8"); writer.println(content); diff --git a/src/test/java/asp/gencay/GeneratorTest.java b/src/test/java/asp/gencay/GeneratorTest.java index 2c9fc46f..36a74bde 100644 --- a/src/test/java/asp/gencay/GeneratorTest.java +++ b/src/test/java/asp/gencay/GeneratorTest.java @@ -35,7 +35,7 @@ public class GeneratorTest extends UnifyWithoutWildcards{ RefType t2 = new RefType(new JavaClassName("java.util.List"), list2, new NullToken()); testSet.addUndConstraint(new Pair(t1, t2, PairOperator.SMALLERDOT)); String resultSet = ASPGencayFactory.generateASP(testSet, - new HashSet<>(Arrays.asList(ASTFactory.createClass(List.class)))); + new HashSet<>(Arrays.asList(ASTFactory.createClass(List.class))), ClassLoader.getSystemClassLoader()); System.out.println(resultSet); } @@ -47,7 +47,7 @@ public class GeneratorTest extends UnifyWithoutWildcards{ RefType t1 = new RefType(new JavaClassName("asp.UnifyWithoutWildcards$Matrix"), list1, new NullToken()); RefType t2 = new RefType(new JavaClassName("java.util.HashMap"), list2, new NullToken()); testSet.addUndConstraint(new Pair(t1, t2, PairOperator.SMALLERDOT)); - String resultSet = ASPGencayFactory.generateASP(testSet, this.getFC()); + String resultSet = ASPGencayFactory.generateASP(testSet, this.getFC(), ClassLoader.getSystemClassLoader()); System.out.println(resultSet); } diff --git a/src/test/java/asp/typeinference/ASPTest.java b/src/test/java/asp/typeinference/ASPTest.java index 5a43b6a9..989e1233 100644 --- a/src/test/java/asp/typeinference/ASPTest.java +++ b/src/test/java/asp/typeinference/ASPTest.java @@ -55,7 +55,7 @@ public class ASPTest { } final ConstraintSet cons = compiler.getConstraints(); - String asp = ASPFactory.generateASP(cons, allClasses); + String asp = ASPFactory.generateASP(cons, allClasses, ClassLoader.getSystemClassLoader()); System.out.println(asp); } diff --git a/src/test/java/finiteClosure/SuperInterfacesTest.java b/src/test/java/finiteClosure/SuperInterfacesTest.java index 0e1368c3..d74215b7 100644 --- a/src/test/java/finiteClosure/SuperInterfacesTest.java +++ b/src/test/java/finiteClosure/SuperInterfacesTest.java @@ -14,14 +14,14 @@ public class SuperInterfacesTest { public void test() throws ClassNotFoundException { Collection classes = new ArrayList<>(); classes.add(ASTFactory.createClass(TestClass.class)); - System.out.println(FCGenerator.toFC(classes)); + System.out.println(FCGenerator.toFC(classes, ClassLoader.getSystemClassLoader())); } @Test public void testGeneric() throws ClassNotFoundException { Collection classes = new ArrayList<>(); classes.add(ASTFactory.createClass(TestClassGeneric.class)); - System.out.println(FCGenerator.toFC(classes)); + System.out.println(FCGenerator.toFC(classes, ClassLoader.getSystemClassLoader())); } } diff --git a/vorgehen.md b/vorgehen.md index 7ee69df2..0854c152 100644 --- a/vorgehen.md +++ b/vorgehen.md @@ -59,3 +59,5 @@ TODO: * kann möglicherweise ASM * Kann ASM mittesl `cw.visit("name/mit/slashe/Getrennt"..` * wurde bereits erledigt -> TODO: Testen + +## Console Interface um Parameter -classpath und -output directory erweitern From 75eaee6644f35ce7151a229ca3c3b897214713bb Mon Sep 17 00:00:00 2001 From: JanUlrich Date: Sun, 22 Dec 2019 17:59:40 +0100 Subject: [PATCH 11/81] Abgabeprotokoll --- abgabeprotokoll.md | 15 +++++++++++++++ src/test/java/packages/ImportTest.java | 20 +++++++++++++++----- 2 files changed, 30 insertions(+), 5 deletions(-) create mode 100644 abgabeprotokoll.md diff --git a/abgabeprotokoll.md b/abgabeprotokoll.md new file mode 100644 index 00000000..6ec54961 --- /dev/null +++ b/abgabeprotokoll.md @@ -0,0 +1,15 @@ +# JavaTXCompiler Klasse +* Konstruktor hat einen weiteren Parameter +* contextPath + * Arrays aus URLs (file-urls) +* Parameter ist Optional +* wird er gesetzt, so werden Classfiles aus den übergebenen Pfaden geladen + * die übergebenen Pfade müssen dabei die Source-Roots sein + * Beispiel: + `import de.test.Klasse;` + * `Klasse.class` liegt in `output/de/test/Klasse.class` + * dann muss contextpath auf `output` gesetzt werden +* wird der Parameter nicht übergeben, so wird der Sourceroot auf das Verzeichnis gesetzt, in dem der Compiler ausgeführt wird +* dies ist das Verhalten vom javac Compiler + + diff --git a/src/test/java/packages/ImportTest.java b/src/test/java/packages/ImportTest.java index 6487c9ab..575da032 100644 --- a/src/test/java/packages/ImportTest.java +++ b/src/test/java/packages/ImportTest.java @@ -24,11 +24,6 @@ public class ImportTest extends TestCase { compiler.generateBytecode(rootDirectory + "output/"); File f = new File(rootDirectory + "output/de/test/ToImport.class"); assertTrue(f.exists()); - compiler = new JavaTXCompiler(new File(rootDirectory+"ToImport.jav")); - compiler.typeInference(); - compiler.generateBytecode(null); - f = new File(rootDirectory + "output/de/test/ToImport.class"); - assertTrue(f.exists()); } @Test @@ -45,4 +40,19 @@ public class ImportTest extends TestCase { f = new File(rootDirectory + "output/de/test/ImportTest.class"); assertTrue(f.exists()); } + + @Test + public void testSetPackageNameInBytecodeAndStandardOutputFolder() throws IOException, ClassNotFoundException { + JavaTXCompiler compiler = new JavaTXCompiler( + Lists.newArrayList(new File(rootDirectory+"ImportTest.jav")), + Lists.newArrayList(new URL("file://"+rootDirectory+"output/"))); + compiler.typeInference(); + File f = new File(rootDirectory + "ImportTest.class"); + if(f.exists() && !f.isDirectory()) { + f.delete(); + } + compiler.generateBytecode(null); + f = new File(rootDirectory + "ImportTest.class"); + assertTrue(f.exists()); + } } From 306af907c552c0c51d3dde43133983a1419e77c4 Mon Sep 17 00:00:00 2001 From: JanUlrich Date: Sun, 22 Dec 2019 22:32:40 +0100 Subject: [PATCH 12/81] Nicht mit mehreren Eingabedateien testen --- abgabeprotokoll.md | 4 +++ .../de/dhbwstuttgart/core/JavaTXCompiler.java | 4 +++ .../java/packages/CheckPackageFolder.java | 35 ++++++++++++++++++- .../packageTest/de/test/subpackage1/Test1.jav | 4 +++ .../packageTest/de/test/subpackage2/Test2.jav | 4 +++ 5 files changed, 50 insertions(+), 1 deletion(-) create mode 100644 src/test/resources/javFiles/packageTest/de/test/subpackage1/Test1.jav create mode 100644 src/test/resources/javFiles/packageTest/de/test/subpackage2/Test2.jav diff --git a/abgabeprotokoll.md b/abgabeprotokoll.md index 6ec54961..db079dab 100644 --- a/abgabeprotokoll.md +++ b/abgabeprotokoll.md @@ -12,4 +12,8 @@ * wird der Parameter nicht übergeben, so wird der Sourceroot auf das Verzeichnis gesetzt, in dem der Compiler ausgeführt wird * dies ist das Verhalten vom javac Compiler +* generateBytecode - Methode hat neuen Parameter: path +* wird hier null übergeben, so wird die class-File in den gleichen Ordner wie die übergebene .jav File geschrieben +* wird hier ein Pfad übergeben, so gilt dieser als output root. + * Klassen werden in outputRoot/package/name/KlassenName.class geschrieben diff --git a/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java b/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java index f79a3a35..ee81d60d 100644 --- a/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java +++ b/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java @@ -766,6 +766,10 @@ public class JavaTXCompiler { return result; } + public void generateBytecode() throws ClassNotFoundException, IOException, BytecodeGeneratorError { + generateBytecode(null); + } + /** * @param path - can be null, then class file output is in the same directory as the parsed source files */ diff --git a/src/test/java/packages/CheckPackageFolder.java b/src/test/java/packages/CheckPackageFolder.java index 9644d5da..50b2773b 100644 --- a/src/test/java/packages/CheckPackageFolder.java +++ b/src/test/java/packages/CheckPackageFolder.java @@ -7,6 +7,7 @@ import org.junit.Test; import java.io.File; import java.io.IOException; +import java.util.Arrays; public class CheckPackageFolder extends TestCase { @@ -15,6 +16,38 @@ public class CheckPackageFolder extends TestCase { @Test public void testCorrectFolder1File() throws IOException, ClassNotFoundException { JavaTXCompiler compiler = new JavaTXCompiler(new File(rootDirectory+"packageNameTestWrongPackage.jav")); - assertTrue(true); //Es ist erlaubt falsche package Namen zu verwenden. Warnung wäre optional + compiler.typeInference(); + File f = new File(rootDirectory + "TestClass.class"); + if(f.exists() && !f.isDirectory()) { + f.delete(); + } + compiler.generateBytecode(); + f = new File(rootDirectory + "TestClass.class"); + assertTrue(f.exists()); //Es ist erlaubt falsche package Namen zu verwenden. Warnung wäre optional } + + /* + * Dieser Test wird übersprungen, da der Bytecode-Generator nicht mit zwei Eingabedateien gleichzeitig umgehen kann + @Test + public void testCorrectFolder2Files() throws IOException, ClassNotFoundException { + JavaTXCompiler compiler = new JavaTXCompiler(Arrays.asList( + new File(rootDirectory+"subpackage1/Test1.jav"), + new File(rootDirectory+"subpackage2/Test2.jav") + )); + compiler.typeInference(); + File f = new File(rootDirectory + "subpackage1/Test1.class"); + if(f.exists() && !f.isDirectory()) { + f.delete(); + } + File f2 = new File(rootDirectory + "subpackage2/Test2.class"); + if(f.exists() && !f.isDirectory()) { + f.delete(); + } + compiler.generateBytecode(); + f = new File(rootDirectory + "subpackage1/Test1.class"); + f2 = new File(rootDirectory + "subpackage2/Test2.class"); + assertTrue(f.exists()); + assertTrue(f2.exists()); + } + */ } diff --git a/src/test/resources/javFiles/packageTest/de/test/subpackage1/Test1.jav b/src/test/resources/javFiles/packageTest/de/test/subpackage1/Test1.jav new file mode 100644 index 00000000..a7011169 --- /dev/null +++ b/src/test/resources/javFiles/packageTest/de/test/subpackage1/Test1.jav @@ -0,0 +1,4 @@ +package de.test.subpackage1; + +class Test1{ +} \ No newline at end of file diff --git a/src/test/resources/javFiles/packageTest/de/test/subpackage2/Test2.jav b/src/test/resources/javFiles/packageTest/de/test/subpackage2/Test2.jav new file mode 100644 index 00000000..750f7612 --- /dev/null +++ b/src/test/resources/javFiles/packageTest/de/test/subpackage2/Test2.jav @@ -0,0 +1,4 @@ +package de.test.subpackage2; + +class Test2{ +} \ No newline at end of file From d0b6dbcd3082d5f582e9f58f939bb8f84934a74c Mon Sep 17 00:00:00 2001 From: JanUlrich Date: Sun, 22 Dec 2019 22:52:55 +0100 Subject: [PATCH 13/81] =?UTF-8?q?Tests=20anf=C3=BCgen=20und=20Bugs=20fixen?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dhbwstuttgart/bytecode/BytecodeGen.java | 10 ++++--- .../bytecode/BytecodeGenMethod.java | 2 +- .../de/dhbwstuttgart/core/JavaTXCompiler.java | 4 +-- src/test/java/packages/Bytecode.java | 2 ++ .../java/packages/CheckPackageFolder.java | 28 ++++++++++++++++++- src/test/java/packages/ImportTest.java | 28 +++++++++++++++++++ .../packageTest/de/test/ImportTest2.jav | 11 ++++++++ .../de/test/subpackage1/ToImport2.jav | 5 ++++ .../de/test/subpackage2/ToImport3.jav | 5 ++++ 9 files changed, 87 insertions(+), 8 deletions(-) create mode 100644 src/test/resources/javFiles/packageTest/de/test/ImportTest2.jav create mode 100644 src/test/resources/javFiles/packageTest/de/test/subpackage1/ToImport2.jav create mode 100644 src/test/resources/javFiles/packageTest/de/test/subpackage2/ToImport3.jav diff --git a/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGen.java b/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGen.java index b5ac3e0b..5091af5e 100644 --- a/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGen.java +++ b/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGen.java @@ -119,22 +119,24 @@ public class BytecodeGen implements ASTVisitor { private GenericsGeneratorResultForClass generatedGenerics; private Resolver resolver; + private final ClassLoader classLoader; public BytecodeGen(HashMap classFiles, Collection listOfResultSets, List simplifyResultsForAllSourceFiles, SourceFile sf, - String path) { + String path, ClassLoader classLoader) { this.classFiles = classFiles; this.listOfResultSets = listOfResultSets; this.simplifyResultsForAllSourceFiles = simplifyResultsForAllSourceFiles; this.sf = sf; this.path = path; this.pkgName = sf.getPkgName(); + this.classLoader = classLoader; } @Override public void visit(SourceFile sourceFile) { for (ClassOrInterface cl : sourceFile.getClasses()) { System.out.println("in Class: " + cl.getClassName().toString()); - BytecodeGen classGen = new BytecodeGen(classFiles, listOfResultSets, simplifyResultsForAllSourceFiles, sf, path); + BytecodeGen classGen = new BytecodeGen(classFiles, listOfResultSets, simplifyResultsForAllSourceFiles, sf, path, classLoader); cl.accept(classGen); classGen.writeClass(cl.getClassName()); } @@ -270,7 +272,7 @@ public class BytecodeGen implements ASTVisitor { constructorPos += 1; BytecodeGenMethod gen = new BytecodeGenMethod(className, superClass, resultSet, field, mv, paramsAndLocals, cw, - genericsAndBoundsMethod, genericsAndBounds, isInterface, classFiles, sf, path, block, constructorPos, ClassLoader.getSystemClassLoader()); + genericsAndBoundsMethod, genericsAndBounds, isInterface, classFiles, sf, path, block, constructorPos, classLoader); if (!field.getParameterList().iterator().hasNext() && !(field.block.statements.get(field.block.statements.size() - 1) instanceof ReturnVoid)) { mv.visitInsn(Opcodes.RETURN); @@ -351,7 +353,7 @@ public class BytecodeGen implements ASTVisitor { mv.visitCode(); BytecodeGenMethod gen = new BytecodeGenMethod(className, superClass, resultSet, method, mv, paramsAndLocals, cw, - genericsAndBoundsMethod, genericsAndBounds, isInterface, classFiles, sf, path, ClassLoader.getSystemClassLoader()); + genericsAndBoundsMethod, genericsAndBounds, isInterface, classFiles, sf, path, classLoader); mv.visitMaxs(0, 0); mv.visitEnd(); diff --git a/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java b/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java index b0ada708..136dec53 100644 --- a/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java +++ b/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java @@ -814,7 +814,7 @@ public class BytecodeGenMethod implements StatementVisitor { // mDesc = helper.generateBCForFunN(methCallType,typesOfParams); }else { try { - cLoader2 = new URLClassLoader(new URL[] {new URL("file://"+path)}); + cLoader2 = new URLClassLoader(new URL[] {new URL("file://"+path)}, classLoader); java.lang.reflect.Method[] methods = cLoader2.loadClass(clazz).getMethods(); System.out.println("Methods of " + receiverName + " "); for(int i = 0; i typeinferenceResult) throws IOException { try { List genericResults = getGeneratedGenericResultsForAllSourceFiles(typeinferenceResult); - BytecodeGen bytecodeGen = new BytecodeGen(classFiles,typeinferenceResult, genericResults, sf,path); + BytecodeGen bytecodeGen = new BytecodeGen(classFiles,typeinferenceResult, genericResults, sf,path, classLoader); bytecodeGen.visit(sf); this.writeClassFile(bytecodeGen.getClassFiles(), path); } catch (ClassNotFoundException e) { @@ -792,7 +792,7 @@ public class JavaTXCompiler { HashMap classFiles = new HashMap<>(); SourceFile sf = sourceFiles.get(f); BytecodeGen bytecodeGen = new BytecodeGen(classFiles, typeinferenceResult, simplifyResultsForAllSourceFiles, - sf, path); + sf, path, classLoader); bytecodeGen.visit(sf); if(path == null){ path = f.getParent(); //Set path to path of the parsed .jav file diff --git a/src/test/java/packages/Bytecode.java b/src/test/java/packages/Bytecode.java index 7a5c4c25..3fabed05 100644 --- a/src/test/java/packages/Bytecode.java +++ b/src/test/java/packages/Bytecode.java @@ -47,4 +47,6 @@ public class Bytecode extends TestCase { Class classToTest = loader.loadClass("de.test.TestClass"); Object instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); } + + } diff --git a/src/test/java/packages/CheckPackageFolder.java b/src/test/java/packages/CheckPackageFolder.java index 50b2773b..b0cfbb8e 100644 --- a/src/test/java/packages/CheckPackageFolder.java +++ b/src/test/java/packages/CheckPackageFolder.java @@ -14,7 +14,7 @@ public class CheckPackageFolder extends TestCase { public static final String rootDirectory = System.getProperty("user.dir")+"/src/test/resources/javFiles/packageTest/de/test/"; @Test - public void testCorrectFolder1File() throws IOException, ClassNotFoundException { + public void testCorrectFolder1FileWithWrongPackageName() throws IOException, ClassNotFoundException { JavaTXCompiler compiler = new JavaTXCompiler(new File(rootDirectory+"packageNameTestWrongPackage.jav")); compiler.typeInference(); File f = new File(rootDirectory + "TestClass.class"); @@ -26,6 +26,32 @@ public class CheckPackageFolder extends TestCase { assertTrue(f.exists()); //Es ist erlaubt falsche package Namen zu verwenden. Warnung wäre optional } + @Test + public void testCorrectFolder1File() throws IOException, ClassNotFoundException { + JavaTXCompiler compiler = new JavaTXCompiler(new File(rootDirectory+"TestClass.jav")); + compiler.typeInference(); + File f = new File(rootDirectory + "TestClass.class"); + if(f.exists() && !f.isDirectory()) { + f.delete(); + } + compiler.generateBytecode(); + f = new File(rootDirectory + "TestClass.class"); + assertTrue(f.exists()); //Es ist erlaubt falsche package Namen zu verwenden. Warnung wäre optional + } + + @Test + public void testCorrectFolder1FileAndOutputDirectory() throws IOException, ClassNotFoundException { + JavaTXCompiler compiler = new JavaTXCompiler(new File(rootDirectory+"TestClass.jav")); + compiler.typeInference(); + File f = new File(rootDirectory + "output/de/test/TestClass.class"); + if(f.exists() && !f.isDirectory()) { + f.delete(); + } + compiler.generateBytecode(rootDirectory+"output/"); + f = new File(rootDirectory + "output/de/test/TestClass.class"); + assertTrue(f.exists()); //Es ist erlaubt falsche package Namen zu verwenden. Warnung wäre optional + } + /* * Dieser Test wird übersprungen, da der Bytecode-Generator nicht mit zwei Eingabedateien gleichzeitig umgehen kann @Test diff --git a/src/test/java/packages/ImportTest.java b/src/test/java/packages/ImportTest.java index 575da032..b13918c6 100644 --- a/src/test/java/packages/ImportTest.java +++ b/src/test/java/packages/ImportTest.java @@ -24,6 +24,18 @@ public class ImportTest extends TestCase { compiler.generateBytecode(rootDirectory + "output/"); File f = new File(rootDirectory + "output/de/test/ToImport.class"); assertTrue(f.exists()); + + compiler = new JavaTXCompiler(new File(rootDirectory+"subpackage1/ToImport2.jav")); + compiler.typeInference(); + compiler.generateBytecode(rootDirectory + "output/"); + f = new File(rootDirectory + "output/de/test/subpackage1/ToImport2.class"); + assertTrue(f.exists()); + + compiler = new JavaTXCompiler(new File(rootDirectory+"subpackage2/ToImport3.jav")); + compiler.typeInference(); + compiler.generateBytecode(rootDirectory + "output/"); + f = new File(rootDirectory + "output/de/test/subpackage2/ToImport3.class"); + assertTrue(f.exists()); } @Test @@ -55,4 +67,20 @@ public class ImportTest extends TestCase { f = new File(rootDirectory + "ImportTest.class"); assertTrue(f.exists()); } + + + @Test + public void testImportTwoClasses() throws IOException, ClassNotFoundException { + JavaTXCompiler compiler = new JavaTXCompiler( + Lists.newArrayList(new File(rootDirectory+"ImportTest2.jav")), + Lists.newArrayList(new URL("file://"+rootDirectory+"output/"))); + compiler.typeInference(); + File f = new File(rootDirectory + "ImportTest2.class"); + if(f.exists() && !f.isDirectory()) { + f.delete(); + } + compiler.generateBytecode(null); + f = new File(rootDirectory + "ImportTest2.class"); + assertTrue(f.exists()); + } } diff --git a/src/test/resources/javFiles/packageTest/de/test/ImportTest2.jav b/src/test/resources/javFiles/packageTest/de/test/ImportTest2.jav new file mode 100644 index 00000000..3526abc8 --- /dev/null +++ b/src/test/resources/javFiles/packageTest/de/test/ImportTest2.jav @@ -0,0 +1,11 @@ +package de.test; + +import de.test.subpackage1.ToImport2; +import de.test.subpackage2.ToImport3; + +class ImportTest2{ + void methode(){ + new ToImport2().m1(); + new ToImport3().m2(); + } +} \ No newline at end of file diff --git a/src/test/resources/javFiles/packageTest/de/test/subpackage1/ToImport2.jav b/src/test/resources/javFiles/packageTest/de/test/subpackage1/ToImport2.jav new file mode 100644 index 00000000..bcc67b95 --- /dev/null +++ b/src/test/resources/javFiles/packageTest/de/test/subpackage1/ToImport2.jav @@ -0,0 +1,5 @@ +package de.test.subpackage1; + +class ToImport2{ +void m1(){} +} \ No newline at end of file diff --git a/src/test/resources/javFiles/packageTest/de/test/subpackage2/ToImport3.jav b/src/test/resources/javFiles/packageTest/de/test/subpackage2/ToImport3.jav new file mode 100644 index 00000000..3efd8fff --- /dev/null +++ b/src/test/resources/javFiles/packageTest/de/test/subpackage2/ToImport3.jav @@ -0,0 +1,5 @@ +package de.test.subpackage2; + +class ToImport3{ +void m2(){} +} \ No newline at end of file From 4391adfb0f4ccf5adda8a44b1e64098a711072b9 Mon Sep 17 00:00:00 2001 From: "pl@gohorb.ba-horb.de" Date: Mon, 23 Dec 2019 11:25:07 +0100 Subject: [PATCH 14/81] modified: src/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java modified: src/test/resources/bytecode/javFiles/OL.jav --- .../de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java | 3 +++ src/test/resources/bytecode/javFiles/OL.jav | 7 ++++--- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/src/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java b/src/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java index 30d76167..cbbd9227 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java @@ -666,8 +666,11 @@ public class TYPEStmt implements StatementVisitor{ protected Constraint generateConstructorConstraint(NewClass forConstructor, MethodAssumption assumption, TypeInferenceBlockInformation info, GenericsResolver resolver){ Constraint methodConstraint = new Constraint(); + //WELCHEN SINN MACHT DIESER CONSTRAINT??? + //Ist er nicht immer classname <. classname und damit redundant? methodConstraint.add(new Pair(assumption.getReturnType(resolver), forConstructor.getType(), PairOperator.SMALLERDOT)); + //WELCHEN SINN MACHT DIESER CONSTRAINT??? methodConstraint.addAll(generateParameterConstraints(forConstructor, assumption, info, resolver)); return methodConstraint; } diff --git a/src/test/resources/bytecode/javFiles/OL.jav b/src/test/resources/bytecode/javFiles/OL.jav index 01a353fd..4eab848f 100644 --- a/src/test/resources/bytecode/javFiles/OL.jav +++ b/src/test/resources/bytecode/javFiles/OL.jav @@ -7,9 +7,10 @@ import java.lang.Boolean; public class OL { - m(x) { return x + x; } - - m(Boolean x) { return x; } + java.lang.Double m(java.lang.Double x) { return x + x; } + java.lang.Integer m(java.lang.Integer x) { return x + x; } + java.lang.String m(java.lang.String x) { return x + x; } + java.lang.Boolean m(Boolean x) { return x; } // if the class contains just this method, then correct BC will be generated. // But if another methods are contained then the generated BC is not correct From c1c12fa33c63c96b798befcf25fd561897c2e359 Mon Sep 17 00:00:00 2001 From: "pl@gohorb.ba-horb.de" Date: Mon, 23 Dec 2019 16:34:07 +0100 Subject: [PATCH 15/81] new file: mathStrucVectorTest.java new file: ../../resources/javFiles/packageTest/de/test/mathStruc.jav new file: ../../resources/javFiles/packageTest/de/test/mathStrucVector.jav new file: ../../resources/javFiles/packageTest/de/test/vectorAdd.jav --- .../java/packages/mathStrucVectorTest.java | 53 +++++++++++++++++++ .../packageTest/de/test/mathStruc.jav | 18 +++++++ .../packageTest/de/test/mathStrucVector.jav | 33 ++++++++++++ .../packageTest/de/test/vectorAdd.jav | 20 +++++++ 4 files changed, 124 insertions(+) create mode 100644 src/test/java/packages/mathStrucVectorTest.java create mode 100644 src/test/resources/javFiles/packageTest/de/test/mathStruc.jav create mode 100644 src/test/resources/javFiles/packageTest/de/test/mathStrucVector.jav create mode 100644 src/test/resources/javFiles/packageTest/de/test/vectorAdd.jav diff --git a/src/test/java/packages/mathStrucVectorTest.java b/src/test/java/packages/mathStrucVectorTest.java new file mode 100644 index 00000000..d28f40ec --- /dev/null +++ b/src/test/java/packages/mathStrucVectorTest.java @@ -0,0 +1,53 @@ +package packages; + +import com.google.common.collect.Lists; +import de.dhbwstuttgart.core.JavaTXCompiler; +import junit.framework.TestCase; +import org.junit.Before; +import org.junit.Test; + +import java.io.File; +import java.io.IOException; +import java.net.URL; + +public class mathStrucVectorTest extends TestCase { + + public static final String rootDirectory = System.getProperty("user.dir")+"/src/test/resources/javFiles/packageTest/de/test/"; + + + public mathStrucVectorTest() throws ClassNotFoundException, IOException { + /* + Generate ToImport class in rootDirectory and in output-Directory + */ + + JavaTXCompiler compiler = new JavaTXCompiler(new File(rootDirectory+"mathStruc.jav")); + compiler.typeInference(); + compiler.generateBytecode(rootDirectory + "output/"); + File f = new File(rootDirectory + "output/de/test/mathStruc.class"); + assertTrue(f.exists()); + + compiler = new JavaTXCompiler(new File(rootDirectory+"vectorAdd.jav")); + compiler.typeInference(); + compiler.generateBytecode(rootDirectory + "output/"); + f = new File(rootDirectory + "output/de/test/vectorAdd.class"); + assertTrue(f.exists()); + + } + + @Test + public void testSetPackageNameInBytecodeAndOutputFolder() throws IOException, ClassNotFoundException { + JavaTXCompiler compiler = new JavaTXCompiler( + Lists.newArrayList(new File(rootDirectory+"mathStrucVector.jav")), + Lists.newArrayList(new URL("file://"+rootDirectory+"output/"))); + compiler.typeInference(); + File f = new File(rootDirectory + "output/de/test/mathStrucVector.class"); + if(f.exists() && !f.isDirectory()) { + f.delete(); + } + compiler.generateBytecode(rootDirectory + "output/"); + f = new File(rootDirectory + "output/de/test/mathStrucVector.class"); + assertTrue(f.exists()); + } + + +} diff --git a/src/test/resources/javFiles/packageTest/de/test/mathStruc.jav b/src/test/resources/javFiles/packageTest/de/test/mathStruc.jav new file mode 100644 index 00000000..28db5db8 --- /dev/null +++ b/src/test/resources/javFiles/packageTest/de/test/mathStruc.jav @@ -0,0 +1,18 @@ +package de.test; + + +import java.util.Vector; +import java.lang.Integer; + +public class mathStruc { + model; + + //Fun1*, Fun1*,MathStruc >> + innerOp = (o) -> (ms) -> new mathStruc<>(o.apply(model,ms.model)); + + public mathStruc(m) { + model =m; + //innerOp = (o) -> (ms) -> new mathStruc<>(o.apply(this.model,ms.model)); + } +} + diff --git a/src/test/resources/javFiles/packageTest/de/test/mathStrucVector.jav b/src/test/resources/javFiles/packageTest/de/test/mathStrucVector.jav new file mode 100644 index 00000000..b92b1b98 --- /dev/null +++ b/src/test/resources/javFiles/packageTest/de/test/mathStrucVector.jav @@ -0,0 +1,33 @@ +package de.test; + +import java.util.Vector; +import java.lang.Integer; +import java.lang.Boolean; + +import de.test.mathStruc; +import de.test.vectorAdd; + + +class mathStrucVector { + + main() { + Vector v1 = new Vector(); + v1.addElement(2); + v1.addElement(2); + Vector v2 = new Vector(); + v2.addElement(3); + v2.addElement(3); + + vectorAdd va = new vectorAdd(); + + var ms; + ms = new mathStruc<>(v1); + var ms2; + ms2 = new mathStruc<>(v2); + var ms3; + /* + ms3 = ms.innerOp.apply(va.add).apply(ms2); + return ms3; + */ + } +} diff --git a/src/test/resources/javFiles/packageTest/de/test/vectorAdd.jav b/src/test/resources/javFiles/packageTest/de/test/vectorAdd.jav new file mode 100644 index 00000000..d61ab841 --- /dev/null +++ b/src/test/resources/javFiles/packageTest/de/test/vectorAdd.jav @@ -0,0 +1,20 @@ +package de.test; + +import java.util.Vector; +import java.lang.Integer; +import java.lang.Boolean; + + +class vectorAdd { + + public add = (v1, v2) -> { + var ret = new Vector(); + var i = 0; + while(i < v1.size()) { + //if (i < v2.size()) { + ret.addElement(v1.elementAt(i) + v2.elementAt(i)); + //} + } + return ret; + }; +} From f59a7d221e550236b34393bff1390cd72149bf0c Mon Sep 17 00:00:00 2001 From: JanUlrich Date: Thu, 26 Dec 2019 15:22:40 +0100 Subject: [PATCH 16/81] Fix bug #181 --- .../java/de/dhbwstuttgart/syntaxtree/factory/ASTFactory.java | 4 ++-- src/test/java/packages/mathStrucVectorTest.java | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/de/dhbwstuttgart/syntaxtree/factory/ASTFactory.java b/src/main/java/de/dhbwstuttgart/syntaxtree/factory/ASTFactory.java index 2fb32dbe..826184a2 100644 --- a/src/main/java/de/dhbwstuttgart/syntaxtree/factory/ASTFactory.java +++ b/src/main/java/de/dhbwstuttgart/syntaxtree/factory/ASTFactory.java @@ -189,11 +189,11 @@ public class ASTFactory { public static de.dhbwstuttgart.syntaxtree.GenericTypeVar createGeneric(TypeVariable jreTypeVar, String jreTVName, Class context, String parentMethod){ JavaClassName parentClass = new JavaClassName(context.getName()); - List genericBounds = new ArrayList<>(); + List genericBounds = new ArrayList<>(); java.lang.reflect.Type[] bounds = jreTypeVar.getBounds(); if(bounds.length > 0){ for(java.lang.reflect.Type bound : bounds){ - genericBounds.add((RefType) createType(bound)); + genericBounds.add(createType(bound)); } } return new de.dhbwstuttgart.syntaxtree.GenericTypeVar(jreTVName, genericBounds, new NullToken(), new NullToken()); diff --git a/src/test/java/packages/mathStrucVectorTest.java b/src/test/java/packages/mathStrucVectorTest.java index d28f40ec..426fd15c 100644 --- a/src/test/java/packages/mathStrucVectorTest.java +++ b/src/test/java/packages/mathStrucVectorTest.java @@ -20,7 +20,7 @@ public class mathStrucVectorTest extends TestCase { Generate ToImport class in rootDirectory and in output-Directory */ - JavaTXCompiler compiler = new JavaTXCompiler(new File(rootDirectory+"mathStruc.jav")); + JavaTXCompiler compiler = new JavaTXCompiler(new File(rootDirectory+"mathStruc.jav")); compiler.typeInference(); compiler.generateBytecode(rootDirectory + "output/"); File f = new File(rootDirectory + "output/de/test/mathStruc.class"); From 19989bfe114a7d35a0d68e2a1a77c253344ee4d1 Mon Sep 17 00:00:00 2001 From: JanUlrich Date: Thu, 26 Dec 2019 19:43:00 +0100 Subject: [PATCH 17/81] Add Console Interface parameters, output directory and classpath --- pom.xml | 1 + .../dhbwstuttgart/core/ConsoleInterface.java | 26 ++++- .../java/packages/ConsoleInterfaceTest.java | 101 ++++++++++++++++++ 3 files changed, 126 insertions(+), 2 deletions(-) create mode 100644 src/test/java/packages/ConsoleInterfaceTest.java diff --git a/pom.xml b/pom.xml index 98ea3933..5b9b2e73 100644 --- a/pom.xml +++ b/pom.xml @@ -164,6 +164,7 @@ http://maven.apache.org/maven-v4_0_0.xsd"> 1.8 1.8 0.23.0 + de.dhbwstuttgart.core.ConsoleInterface diff --git a/src/main/java/de/dhbwstuttgart/core/ConsoleInterface.java b/src/main/java/de/dhbwstuttgart/core/ConsoleInterface.java index 77a172bf..2742bbbf 100644 --- a/src/main/java/de/dhbwstuttgart/core/ConsoleInterface.java +++ b/src/main/java/de/dhbwstuttgart/core/ConsoleInterface.java @@ -2,6 +2,7 @@ package de.dhbwstuttgart.core; import java.io.File; import java.io.IOException; +import java.net.URL; import java.util.*; import java.util.stream.Collectors; @@ -9,8 +10,29 @@ public class ConsoleInterface { private static final String directory = System.getProperty("user.dir"); public static void main(String[] args) throws IOException, ClassNotFoundException { - List input = Arrays.asList(args).stream().map((s -> new File(s))).collect(Collectors.toList()); - JavaTXCompiler compiler = new JavaTXCompiler(input); + List input = new ArrayList<>(); + List classpath = new ArrayList<>(); + String outputPath = null; + Iterator it = Arrays.asList(args).iterator(); + while(it.hasNext()){ + String arg = it.next(); + if(arg.equals("-d")){ + outputPath = it.next(); + }else if(arg.startsWith("-d")) { + outputPath = arg.substring(2); + }else if(arg.equals("-cp")){ + String[] cps = it.next().split(":"); + for(String cp : cps){ + classpath.add(new URL("file://"+cp)); + } + }else{ + input.add(new File(arg)); + } + } + JavaTXCompiler compiler = new JavaTXCompiler(input, classpath); compiler.typeInference(); + compiler.generateBytecode(outputPath); } + + } diff --git a/src/test/java/packages/ConsoleInterfaceTest.java b/src/test/java/packages/ConsoleInterfaceTest.java new file mode 100644 index 00000000..32fffe0d --- /dev/null +++ b/src/test/java/packages/ConsoleInterfaceTest.java @@ -0,0 +1,101 @@ +package packages; + +import de.dhbwstuttgart.core.ConsoleInterface; +import de.dhbwstuttgart.core.JavaTXCompiler; +import junit.framework.TestCase; +import org.junit.Test; + +import java.io.File; +import java.net.URL; +import java.net.URLClassLoader; + +public class ConsoleInterfaceTest extends TestCase { + + public static final String rootDirectory = System.getProperty("user.dir")+"/src/test/resources/javFiles/packageTest/"; + + @Test + public void testCompileSingleJavFile() throws Exception { + File f = new File(rootDirectory + "de/test/TestClass.class"); + if(f.exists() && !f.isDirectory()) { + f.delete(); + } + + ConsoleInterface.main(new String[]{rootDirectory + "de/test/TestClass.jav"}); + + f = new File(rootDirectory + "de/test/TestClass.class"); + assertTrue(f.exists()); + } + + @Test + public void testCompileSingleJavFileWithOutputDirectory() throws Exception { + File f = new File(rootDirectory + "de/test/output/de/test/TestClass.class"); + if(f.exists() && !f.isDirectory()) { + f.delete(); + } + + ConsoleInterface.main(new String[]{"-d", rootDirectory + "de/test/output/" ,rootDirectory + "de/test/TestClass.jav"}); + + f = new File(rootDirectory + "de/test/output/de/test/TestClass.class"); + assertTrue(f.exists()); + } + + @Test + public void testCompileSingleJavFileWithClassPath() throws Exception { + JavaTXCompiler compiler = new JavaTXCompiler(new File(rootDirectory+"/de/test/ToImport.jav")); + compiler.typeInference(); + compiler.generateBytecode(rootDirectory + "output/"); + File f = new File(rootDirectory + "output/de/test/ToImport.class"); + assertTrue(f.exists()); + + f = new File(rootDirectory + "de/test/ImportTest.class"); + if(f.exists() && !f.isDirectory()) { + f.delete(); + } + + ConsoleInterface.main(new String[]{"-cp", rootDirectory + "de/test/output/" ,rootDirectory + "de/test/ImportTest.jav"}); + + f = new File(rootDirectory + "de/test/ImportTest.class"); + assertTrue(f.exists()); + } + + @Test + public void testCompileSingleJavFileWithMultipleClassPath() throws Exception { + JavaTXCompiler compiler = new JavaTXCompiler(new File(rootDirectory+"/de/test/ToImport.jav")); + compiler.typeInference(); + compiler.generateBytecode(rootDirectory + "output/"); + File f = new File(rootDirectory + "output/de/test/ToImport.class"); + assertTrue(f.exists()); + + f = new File(rootDirectory + "de/test/ImportTest.class"); + if(f.exists() && !f.isDirectory()) { + f.delete(); + } + + ConsoleInterface.main(new String[]{"-cp", rootDirectory + "de/test/output/:"+rootDirectory+"de", + rootDirectory + "de/test/ImportTest.jav"}); + + f = new File(rootDirectory + "de/test/ImportTest.class"); + assertTrue(f.exists()); + } + + @Test + public void testCompileSingleJavFileWithClassPathAndOutputDir() throws Exception { + JavaTXCompiler compiler = new JavaTXCompiler(new File(rootDirectory+"/de/test/ToImport.jav")); + compiler.typeInference(); + compiler.generateBytecode(rootDirectory + "output/"); + File f = new File(rootDirectory + "output/de/test/ToImport.class"); + assertTrue(f.exists()); + + f = new File(rootDirectory + "de/test/output/de/test/ImportTest.class"); + if(f.exists() && !f.isDirectory()) { + f.delete(); + } + + ConsoleInterface.main(new String[]{"-cp", rootDirectory + "de/test/output/", + "-d"+rootDirectory + "de/test/output/" ,rootDirectory + "de/test/ImportTest.jav"}); + + f = new File(rootDirectory + "de/test/output/de/test/ImportTest.class"); + assertTrue(f.exists()); + } + +} From 4b4087ae24b688f2448c2007262ab271cc09fc22 Mon Sep 17 00:00:00 2001 From: JanUlrich Date: Fri, 27 Dec 2019 18:51:04 +0100 Subject: [PATCH 18/81] Trying to add Names that are not imported to availableClasses (unfinished) --- .../parser/scope/GatherNames.java | 53 +++++++++++++++++-- 1 file changed, 49 insertions(+), 4 deletions(-) diff --git a/src/main/java/de/dhbwstuttgart/parser/scope/GatherNames.java b/src/main/java/de/dhbwstuttgart/parser/scope/GatherNames.java index 31c6d375..757c323b 100644 --- a/src/main/java/de/dhbwstuttgart/parser/scope/GatherNames.java +++ b/src/main/java/de/dhbwstuttgart/parser/scope/GatherNames.java @@ -7,6 +7,7 @@ import java.util.*; import de.dhbwstuttgart.parser.antlr.Java8BaseListener; import de.dhbwstuttgart.syntaxtree.AbstractASTWalker; import org.antlr.v4.runtime.tree.AbstractParseTreeVisitor; +import org.antlr.v4.runtime.tree.ParseTreeWalker; import org.antlr.v4.runtime.tree.TerminalNode; import de.dhbwstuttgart.environment.PackageCrawler; @@ -63,12 +64,56 @@ public class GatherNames { } } } - ret.putAll(getImports(ctx, packages, classLoader)); - return ret; + ret.putAll(getImports(ctx, packages, classLoader)); + ret.putAll(getUsedTypes(ctx, classLoader, ret.keySet())); + return ret; } - - public static Map getImports(Java8Parser.CompilationUnitContext ctx, PackageCrawler packages, ClassLoader classLoader) throws ClassNotFoundException { + private static Map getUsedTypes(Java8Parser.CompilationUnitContext ctx, ClassLoader classLoader, Collection alreadyUsedNames) { + Map ret = new HashMap<>(); + new ParseTreeWalker().walk(new Java8BaseListener(){ + @Override + public void enterUnannClassType(Java8Parser.UnannClassTypeContext ctx) { + addClass(ctx.Identifier().getText()); + } + + @Override + public void enterUnannClassType_lf_unannClassOrInterfaceType(Java8Parser.UnannClassType_lf_unannClassOrInterfaceTypeContext ctx) { + addClass(ctx.Identifier().getText()); + } + + @Override + public void enterUnannClassType_lfno_unannClassOrInterfaceType(Java8Parser.UnannClassType_lfno_unannClassOrInterfaceTypeContext ctx) { + addClass(ctx.Identifier().getText()); + } + + @Override + public void enterClassInstanceCreationExpression(Java8Parser.ClassInstanceCreationExpressionContext ctx) { + addClass(ctx.Identifier(0).getText()); + } + + @Override + public void enterClassInstanceCreationExpression_lf_primary(Java8Parser.ClassInstanceCreationExpression_lf_primaryContext ctx) { + addClass(ctx.Identifier().getText()); + } + + @Override + public void enterClassInstanceCreationExpression_lfno_primary(Java8Parser.ClassInstanceCreationExpression_lfno_primaryContext ctx) { + addClass(ctx.Identifier(0).getText()); + } + + private void addClass(String name) { + try { + Class cl = classLoader.loadClass(name); + ret.put(cl.getName(), cl.getTypeParameters().length); + }catch (ClassNotFoundException e){ + } + } + }, ctx); + return ret; + } + + public static Map getImports(Java8Parser.CompilationUnitContext ctx, PackageCrawler packages, ClassLoader classLoader) throws ClassNotFoundException { Map ret = new HashMap<>(); //ret.putAll(packages.getClassNames("java.lang")); for(Java8Parser.ImportDeclarationContext importDeclCtx : ctx.importDeclaration()){ From 0c9c8ef321ae3b01f713a6514158c0ad80a4d767 Mon Sep 17 00:00:00 2001 From: "pl@gohorb.ba-horb.de" Date: Sun, 29 Dec 2019 19:42:40 +0100 Subject: [PATCH 19/81] modified: ../../../../../../../../../main/java/de/dhbwstuttgart/syntaxtree/factory/ASTFactory.java Bug 182 fixed modified: ../../../mathStrucVector.jav modified: ../../../vectorAdd.jav kleine Aenderungen --- .../de/dhbwstuttgart/syntaxtree/factory/ASTFactory.java | 2 +- .../javFiles/packageTest/de/test/mathStrucVector.jav | 8 ++++---- .../resources/javFiles/packageTest/de/test/vectorAdd.jav | 2 +- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/main/java/de/dhbwstuttgart/syntaxtree/factory/ASTFactory.java b/src/main/java/de/dhbwstuttgart/syntaxtree/factory/ASTFactory.java index 826184a2..a682717c 100644 --- a/src/main/java/de/dhbwstuttgart/syntaxtree/factory/ASTFactory.java +++ b/src/main/java/de/dhbwstuttgart/syntaxtree/factory/ASTFactory.java @@ -70,7 +70,7 @@ public class ASTFactory { } private static Field createField(java.lang.reflect.Field field, JavaClassName jreClass) { - return new Field(field.getName(), createType(field.getType()), field.getModifiers(), new NullToken()); + return new Field(field.getName(), createType(field.getGenericType()), field.getModifiers(), new NullToken()); } //private static RefType createType(Class classType) { diff --git a/src/test/resources/javFiles/packageTest/de/test/mathStrucVector.jav b/src/test/resources/javFiles/packageTest/de/test/mathStrucVector.jav index b92b1b98..fe6d6055 100644 --- a/src/test/resources/javFiles/packageTest/de/test/mathStrucVector.jav +++ b/src/test/resources/javFiles/packageTest/de/test/mathStrucVector.jav @@ -8,9 +8,9 @@ import de.test.mathStruc; import de.test.vectorAdd; -class mathStrucVector { +public class mathStrucVector { - main() { + public main() { Vector v1 = new Vector(); v1.addElement(2); v1.addElement(2); @@ -25,9 +25,9 @@ class mathStrucVector { var ms2; ms2 = new mathStruc<>(v2); var ms3; - /* + ms3 = ms.innerOp.apply(va.add).apply(ms2); return ms3; - */ + } } diff --git a/src/test/resources/javFiles/packageTest/de/test/vectorAdd.jav b/src/test/resources/javFiles/packageTest/de/test/vectorAdd.jav index d61ab841..727a83a9 100644 --- a/src/test/resources/javFiles/packageTest/de/test/vectorAdd.jav +++ b/src/test/resources/javFiles/packageTest/de/test/vectorAdd.jav @@ -5,7 +5,7 @@ import java.lang.Integer; import java.lang.Boolean; -class vectorAdd { +public class vectorAdd { public add = (v1, v2) -> { var ret = new Vector(); From bd0b2e605891d8fdbf3aa3651adb87036ba9a7ff Mon Sep 17 00:00:00 2001 From: "pl@gohorb.ba-horb.de" Date: Mon, 30 Dec 2019 10:45:32 +0100 Subject: [PATCH 20/81] new file: ../../../../../../../../java/packages/OLTest.java new file: ../../../OL.jav new file: ../../../OLMain.jav --- src/test/java/packages/OLTest.java | 102 ++++++++++++++++++ .../javFiles/packageTest/de/test/OL.jav | 12 +++ .../javFiles/packageTest/de/test/OLMain.jav | 10 ++ 3 files changed, 124 insertions(+) create mode 100644 src/test/java/packages/OLTest.java create mode 100644 src/test/resources/javFiles/packageTest/de/test/OL.jav create mode 100644 src/test/resources/javFiles/packageTest/de/test/OLMain.jav diff --git a/src/test/java/packages/OLTest.java b/src/test/java/packages/OLTest.java new file mode 100644 index 00000000..dc1646b7 --- /dev/null +++ b/src/test/java/packages/OLTest.java @@ -0,0 +1,102 @@ +package packages; + +import static org.junit.Assert.*; + +import java.io.File; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.net.URL; +import java.net.URLClassLoader; +import java.util.List; + +import org.junit.BeforeClass; +import org.junit.Test; + +import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.GenericGenratorResultForSourceFile; +import de.dhbwstuttgart.core.JavaTXCompiler; +import de.dhbwstuttgart.typeinference.result.ResultSet; + +public class OLTest { + private static String path; + private static File fileToTest; + private static JavaTXCompiler compiler; + private static ClassLoader loader; + private static Class classToTest; + private static Class classToTest1; + private static String pathToClassFile; + private static Object instanceOfClass; + private static Object instanceOfClass1; + + @BeforeClass + public static void setUpBeforeClass() throws Exception { + path = System.getProperty("user.dir")+"/src/test/resources/javFiles/packageTest/de/test/OL.jav"; + fileToTest = new File(path); + compiler = new JavaTXCompiler(fileToTest); + pathToClassFile = System.getProperty("user.dir")+"/src/test/resources/javFiles/packageTest/de/test/"; + compiler.generateBytecode(pathToClassFile); + loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); + classToTest = loader.loadClass("OL"); + instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); + + path = System.getProperty("user.dir")+"/src/test/resources/javFiles/packageTest/de/test/OLMain.jav"; + fileToTest = new File(path); + compiler = new JavaTXCompiler(fileToTest); + pathToClassFile = System.getProperty("user.dir")+"/src/test/resources/javFiles/packageTest/de/test/"; + compiler.generateBytecode(pathToClassFile); + loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); + classToTest1 = loader.loadClass("OLMain"); + instanceOfClass1 = classToTest1.getDeclaredConstructor().newInstance(); + } + + @Test + public void testOLClassName() { + assertEquals("OL", classToTest.getName()); + } + + @Test + public void testmInt() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + Method m = classToTest.getDeclaredMethod("m", Integer.class); + Integer result = (Integer) m.invoke(instanceOfClass, 5); + assertEquals(new Integer(10), result); + } + + @Test + public void testmDouble() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + Method m = classToTest.getDeclaredMethod("m", Double.class); + Double result = (Double) m.invoke(instanceOfClass, 5.0); + assertEquals(new Double(10.0), result); + } + + @Test + public void testmString() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + Method m = classToTest.getDeclaredMethod("m", String.class); + String result = (String) m.invoke(instanceOfClass, "xxx"); + assertEquals("xxxxxx", result); + } + + @Test + public void testOLMainClassName() { + assertEquals("OLMain", classToTest1.getName()); + } + + @Test + public void testmainInt() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + Method main = classToTest1.getDeclaredMethod("main", Integer.class); + Integer result = (Integer) main.invoke(instanceOfClass1, 5); + assertEquals(new Integer(10), result); + } + + @Test + public void testmainDouble() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + Method main = classToTest1.getDeclaredMethod("main", Double.class); + Double result = (Double) main.invoke(instanceOfClass1, 5.0); + assertEquals(new Double(10.0), result); + } + + @Test + public void testmainString() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + Method main = classToTest1.getDeclaredMethod("main", String.class); + String result = (String) main.invoke(instanceOfClass1, "xxx"); + assertEquals("xxxxxx", result); + } +} diff --git a/src/test/resources/javFiles/packageTest/de/test/OL.jav b/src/test/resources/javFiles/packageTest/de/test/OL.jav new file mode 100644 index 00000000..91d0f4ab --- /dev/null +++ b/src/test/resources/javFiles/packageTest/de/test/OL.jav @@ -0,0 +1,12 @@ +import java.lang.String; +import java.lang.Integer; +import java.lang.Double; +import java.lang.Boolean; +//import java.util.Vector; + + +public class OL { + + m(x) { return x + x; } + +} diff --git a/src/test/resources/javFiles/packageTest/de/test/OLMain.jav b/src/test/resources/javFiles/packageTest/de/test/OLMain.jav new file mode 100644 index 00000000..4f08635b --- /dev/null +++ b/src/test/resources/javFiles/packageTest/de/test/OLMain.jav @@ -0,0 +1,10 @@ +import OL; + +public class OLMain { + + main(x) { + var ol; + ol = new OL(); + return ol.m(x); + } +} From 691d31df5e9da3b1a4a2a784e6290e0d8caa5554 Mon Sep 17 00:00:00 2001 From: JanUlrich Date: Fri, 3 Jan 2020 00:18:09 +0100 Subject: [PATCH 21/81] Die getRegistry Methode der CompilationEnvironment Klasse beachtet jetzt auch alle .class Files, welche sich im gleichen Ordner befinden --- .../de/dhbwstuttgart/core/JavaTXCompiler.java | 1 + .../environment/CompilationEnvironment.java | 31 +++++++++++++ .../parser/scope/GatherNames.java | 45 ------------------- src/test/java/packages/ImportTest.java | 22 +++++++++ .../packageTest/de/test/ImportTestDefault.jav | 7 +++ 5 files changed, 61 insertions(+), 45 deletions(-) create mode 100644 src/test/resources/javFiles/packageTest/de/test/ImportTestDefault.jav diff --git a/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java b/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java index 98626fde..498ea41b 100644 --- a/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java +++ b/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java @@ -14,6 +14,7 @@ import de.dhbwstuttgart.parser.antlr.Java8Parser.CompilationUnitContext; import de.dhbwstuttgart.parser.scope.JavaClassName; import de.dhbwstuttgart.syntaxtree.ClassOrInterface; import de.dhbwstuttgart.syntaxtree.SourceFile; +import de.dhbwstuttgart.syntaxtree.TypeScope; import de.dhbwstuttgart.syntaxtree.factory.ASTFactory; import de.dhbwstuttgart.syntaxtree.factory.UnifyTypeFactory; import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder; diff --git a/src/main/java/de/dhbwstuttgart/environment/CompilationEnvironment.java b/src/main/java/de/dhbwstuttgart/environment/CompilationEnvironment.java index 43196b6f..05a8055c 100644 --- a/src/main/java/de/dhbwstuttgart/environment/CompilationEnvironment.java +++ b/src/main/java/de/dhbwstuttgart/environment/CompilationEnvironment.java @@ -1,15 +1,18 @@ package de.dhbwstuttgart.environment; import java.io.File; +import java.io.FilenameFilter; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.util.*; +import com.google.common.collect.Lists; import de.dhbwstuttgart.syntaxtree.ClassOrInterface; import de.dhbwstuttgart.syntaxtree.SourceFile; import de.dhbwstuttgart.syntaxtree.factory.ASTFactory; +import org.antlr.v4.runtime.tree.TerminalNode; import org.reflections.Reflections; import org.reflections.scanners.ResourcesScanner; import org.reflections.scanners.SubTypesScanner; @@ -70,9 +73,37 @@ public class CompilationEnvironment { Map allNames; CompilationUnitContext tree = JavaTXParser.parse(forSourceFile); allNames = GatherNames.getNames(tree, packageCrawler, classLoader); + for(Class c : loadDefaultPackageClasses(forSourceFile, classLoader)){ + allNames.put(c.getName(), c.getTypeParameters().length); + } return new JavaClassRegistry(allNames); } + public List loadDefaultPackageClasses(File forSourceFile, ClassLoader classLoader) throws IOException, ClassNotFoundException { + List ret = new ArrayList<>(); + String packageName = getPackageName(JavaTXParser.parse(forSourceFile)); + //Set classLoader to include default package for this specific source file + File dir = new File(forSourceFile.getParent()); + String path = "file://" + dir.toString().substring(0, dir.toString().length() - packageName.length() + 1); + ArrayList defaultPath = Lists.newArrayList(new URL(path)); + classLoader = new URLClassLoader(defaultPath.toArray(new URL[0]), classLoader); + //Gather all names in the default package for this source file (classes that are imported by default) + File [] files = dir.listFiles((dir1, name) -> name.endsWith(".class")); + if(files != null)for (File classFile : files) { + String className = classFile.getName().substring(0,classFile.getName().length()-6); + ret.add(classLoader.loadClass(packageName + className)); + } + return ret; + } + + private String getPackageName(CompilationUnitContext forTree){ + String packageName = ""; + for(TerminalNode subPackage : forTree.packageDeclaration().Identifier()){ + packageName += subPackage.toString() + "."; + } + return packageName; + } + public List getAllAvailableClasses() { List ret = new ArrayList<>(); for(Class c : new PackageCrawler(librarys).getAllAvailableClasses()){ diff --git a/src/main/java/de/dhbwstuttgart/parser/scope/GatherNames.java b/src/main/java/de/dhbwstuttgart/parser/scope/GatherNames.java index 757c323b..8e93355b 100644 --- a/src/main/java/de/dhbwstuttgart/parser/scope/GatherNames.java +++ b/src/main/java/de/dhbwstuttgart/parser/scope/GatherNames.java @@ -65,54 +65,9 @@ public class GatherNames { } } ret.putAll(getImports(ctx, packages, classLoader)); - ret.putAll(getUsedTypes(ctx, classLoader, ret.keySet())); return ret; } - private static Map getUsedTypes(Java8Parser.CompilationUnitContext ctx, ClassLoader classLoader, Collection alreadyUsedNames) { - Map ret = new HashMap<>(); - new ParseTreeWalker().walk(new Java8BaseListener(){ - @Override - public void enterUnannClassType(Java8Parser.UnannClassTypeContext ctx) { - addClass(ctx.Identifier().getText()); - } - - @Override - public void enterUnannClassType_lf_unannClassOrInterfaceType(Java8Parser.UnannClassType_lf_unannClassOrInterfaceTypeContext ctx) { - addClass(ctx.Identifier().getText()); - } - - @Override - public void enterUnannClassType_lfno_unannClassOrInterfaceType(Java8Parser.UnannClassType_lfno_unannClassOrInterfaceTypeContext ctx) { - addClass(ctx.Identifier().getText()); - } - - @Override - public void enterClassInstanceCreationExpression(Java8Parser.ClassInstanceCreationExpressionContext ctx) { - addClass(ctx.Identifier(0).getText()); - } - - @Override - public void enterClassInstanceCreationExpression_lf_primary(Java8Parser.ClassInstanceCreationExpression_lf_primaryContext ctx) { - addClass(ctx.Identifier().getText()); - } - - @Override - public void enterClassInstanceCreationExpression_lfno_primary(Java8Parser.ClassInstanceCreationExpression_lfno_primaryContext ctx) { - addClass(ctx.Identifier(0).getText()); - } - - private void addClass(String name) { - try { - Class cl = classLoader.loadClass(name); - ret.put(cl.getName(), cl.getTypeParameters().length); - }catch (ClassNotFoundException e){ - } - } - }, ctx); - return ret; - } - public static Map getImports(Java8Parser.CompilationUnitContext ctx, PackageCrawler packages, ClassLoader classLoader) throws ClassNotFoundException { Map ret = new HashMap<>(); //ret.putAll(packages.getClassNames("java.lang")); diff --git a/src/test/java/packages/ImportTest.java b/src/test/java/packages/ImportTest.java index b13918c6..4ae04779 100644 --- a/src/test/java/packages/ImportTest.java +++ b/src/test/java/packages/ImportTest.java @@ -25,6 +25,12 @@ public class ImportTest extends TestCase { File f = new File(rootDirectory + "output/de/test/ToImport.class"); assertTrue(f.exists()); + compiler = new JavaTXCompiler(new File(rootDirectory+"ToImport.jav")); + compiler.typeInference(); + compiler.generateBytecode(null); + f = new File(rootDirectory + "ToImport.class"); + assertTrue(f.exists()); + compiler = new JavaTXCompiler(new File(rootDirectory+"subpackage1/ToImport2.jav")); compiler.typeInference(); compiler.generateBytecode(rootDirectory + "output/"); @@ -83,4 +89,20 @@ public class ImportTest extends TestCase { f = new File(rootDirectory + "ImportTest2.class"); assertTrue(f.exists()); } + + @Test + public void testImportDefaultPackage() throws IOException, ClassNotFoundException { + JavaTXCompiler compiler = new JavaTXCompiler( + Lists.newArrayList(new File(rootDirectory+"ImportTestDefault.jav"))); + compiler.typeInference(); + File f = new File(rootDirectory + "ImportTestDefault.class"); + if(f.exists() && !f.isDirectory()) { + f.delete(); + } + compiler.generateBytecode(null); + f = new File(rootDirectory + "ImportTestDefault.class"); + assertTrue(f.exists()); + } + + } diff --git a/src/test/resources/javFiles/packageTest/de/test/ImportTestDefault.jav b/src/test/resources/javFiles/packageTest/de/test/ImportTestDefault.jav new file mode 100644 index 00000000..ecd8d7c5 --- /dev/null +++ b/src/test/resources/javFiles/packageTest/de/test/ImportTestDefault.jav @@ -0,0 +1,7 @@ +package de.test; + +class ImportTestDefault{ + void methode(){ + new ToImport(); + } +} \ No newline at end of file From abdff6c8d28da736bdecc6f1e1e835f2170754f5 Mon Sep 17 00:00:00 2001 From: JanUlrich Date: Fri, 3 Jan 2020 01:12:58 +0100 Subject: [PATCH 22/81] Fixed bug #184 --- .../de/dhbwstuttgart/core/JavaTXCompiler.java | 16 ++++++++++------ .../environment/CompilationEnvironment.java | 4 ++-- 2 files changed, 12 insertions(+), 8 deletions(-) diff --git a/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java b/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java index 498ea41b..13d752cb 100644 --- a/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java +++ b/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java @@ -88,22 +88,26 @@ public class JavaTXCompiler { INSTANCE = this; } - public ConstraintSet getConstraints() throws ClassNotFoundException { + public ConstraintSet getConstraints() throws ClassNotFoundException, IOException { List allClasses = new ArrayList<>();//environment.getAllAvailableClasses(); for (SourceFile sf : sourceFiles.values()) { allClasses.addAll(sf.getClasses()); } List importedClasses = new ArrayList<>(); //Alle Importierten Klassen in allen geparsten Sourcefiles kommen ins FC - for (File forSourceFile : sourceFiles.keySet()) + for (File forSourceFile : sourceFiles.keySet()){ for (JavaClassName name : sourceFiles.get(forSourceFile).getImports()) { //TODO: Hier werden imports von eigenen (.jav) Klassen nicht beachtet ClassOrInterface importedClass = ASTFactory.createClass( classLoader.loadClass(name.toString())); importedClasses.add(importedClass); } + for(Class c : CompilationEnvironment.loadDefaultPackageClasses(forSourceFile, classLoader)){ + ClassOrInterface importedClass = ASTFactory.createClass(c); + importedClasses.add(importedClass); + } + } allClasses.addAll(importedClasses); - return new TYPE(sourceFiles.values(), allClasses).getConstraints(); } @@ -289,7 +293,7 @@ public class JavaTXCompiler { */ public UnifyResultModel typeInferenceAsync(UnifyResultListener resultListener, Writer logFile) - throws ClassNotFoundException { + throws ClassNotFoundException, IOException { List allClasses = new ArrayList<>();// environment.getAllAvailableClasses(); // Alle Importierten Klassen in allen geparsten Sourcefiles kommen ins FC for (SourceFile sf : this.sourceFiles.values()) { @@ -457,7 +461,7 @@ public class JavaTXCompiler { return urm; } - public List typeInference() throws ClassNotFoundException { + public List typeInference() throws ClassNotFoundException, IOException { List allClasses = new ArrayList<>();// environment.getAllAvailableClasses(); // Alle Importierten Klassen in allen geparsten Sourcefiles kommen ins FC for (SourceFile sf : this.sourceFiles.values()) { @@ -743,7 +747,7 @@ public class JavaTXCompiler { public List getGeneratedGenericResultsForAllSourceFiles() - throws ClassNotFoundException { + throws ClassNotFoundException, IOException { List result = new ArrayList<>(); for (File f : sourceFiles.keySet()) { SourceFile sf = sourceFiles.get(f); diff --git a/src/main/java/de/dhbwstuttgart/environment/CompilationEnvironment.java b/src/main/java/de/dhbwstuttgart/environment/CompilationEnvironment.java index 05a8055c..7433d661 100644 --- a/src/main/java/de/dhbwstuttgart/environment/CompilationEnvironment.java +++ b/src/main/java/de/dhbwstuttgart/environment/CompilationEnvironment.java @@ -79,7 +79,7 @@ public class CompilationEnvironment { return new JavaClassRegistry(allNames); } - public List loadDefaultPackageClasses(File forSourceFile, ClassLoader classLoader) throws IOException, ClassNotFoundException { + public static List loadDefaultPackageClasses(File forSourceFile, ClassLoader classLoader) throws IOException, ClassNotFoundException { List ret = new ArrayList<>(); String packageName = getPackageName(JavaTXParser.parse(forSourceFile)); //Set classLoader to include default package for this specific source file @@ -96,7 +96,7 @@ public class CompilationEnvironment { return ret; } - private String getPackageName(CompilationUnitContext forTree){ + private static String getPackageName(CompilationUnitContext forTree){ String packageName = ""; for(TerminalNode subPackage : forTree.packageDeclaration().Identifier()){ packageName += subPackage.toString() + "."; From f63346649b3467514888254bd76c6e8ff2ca725e Mon Sep 17 00:00:00 2001 From: JanUlrich Date: Mon, 6 Jan 2020 22:04:29 +0100 Subject: [PATCH 23/81] Fix loading packages from same package --- .../de/dhbwstuttgart/core/JavaTXCompiler.java | 13 +++++-- .../environment/CompilationEnvironment.java | 11 ++++-- .../LoadDefaultPackageClassesTest.java | 39 +++++++++++++++++++ .../resources/javFiles/packageTest/Gen.jav | 8 ++++ .../resources/javFiles/packageTest/Test.jav | 3 ++ .../output/de/test/mathStrucVectoruse.java | 10 +++++ .../de/test/output/mathStrucVectoruse.java | 8 ++++ vorgehen.md | 11 ++++++ 8 files changed, 95 insertions(+), 8 deletions(-) create mode 100644 src/test/java/packages/LoadDefaultPackageClassesTest.java create mode 100644 src/test/resources/javFiles/packageTest/Gen.jav create mode 100644 src/test/resources/javFiles/packageTest/Test.jav create mode 100644 src/test/resources/javFiles/packageTest/de/test/output/de/test/mathStrucVectoruse.java create mode 100644 src/test/resources/javFiles/packageTest/de/test/output/mathStrucVectoruse.java diff --git a/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java b/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java index 13d752cb..658f0c65 100644 --- a/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java +++ b/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java @@ -90,9 +90,10 @@ public class JavaTXCompiler { public ConstraintSet getConstraints() throws ClassNotFoundException, IOException { List allClasses = new ArrayList<>();//environment.getAllAvailableClasses(); - for (SourceFile sf : sourceFiles.values()) { + for (File f : this.sourceFiles.keySet()) { + SourceFile sf = sourceFiles.get(f); allClasses.addAll(sf.getClasses()); - } + } List importedClasses = new ArrayList<>(); //Alle Importierten Klassen in allen geparsten Sourcefiles kommen ins FC for (File forSourceFile : sourceFiles.keySet()){ @@ -296,9 +297,11 @@ public class JavaTXCompiler { throws ClassNotFoundException, IOException { List allClasses = new ArrayList<>();// environment.getAllAvailableClasses(); // Alle Importierten Klassen in allen geparsten Sourcefiles kommen ins FC - for (SourceFile sf : this.sourceFiles.values()) { + for (File f : this.sourceFiles.keySet()) { + SourceFile sf = sourceFiles.get(f); allClasses.addAll(getAvailableClasses(sf)); allClasses.addAll(sf.getClasses()); + allClasses.addAll(CompilationEnvironment.loadDefaultPackageClasses(f,classLoader).stream().map(ASTFactory::createClass).collect(Collectors.toList())); } final ConstraintSet cons = getConstraints(); @@ -464,9 +467,11 @@ public class JavaTXCompiler { public List typeInference() throws ClassNotFoundException, IOException { List allClasses = new ArrayList<>();// environment.getAllAvailableClasses(); // Alle Importierten Klassen in allen geparsten Sourcefiles kommen ins FC - for (SourceFile sf : this.sourceFiles.values()) { + for (File f : this.sourceFiles.keySet()) { + SourceFile sf = sourceFiles.get(f); allClasses.addAll(getAvailableClasses(sf)); allClasses.addAll(sf.getClasses()); + allClasses.addAll(CompilationEnvironment.loadDefaultPackageClasses(f,classLoader).stream().map(ASTFactory::createClass).collect(Collectors.toList())); } final ConstraintSet cons = getConstraints(); diff --git a/src/main/java/de/dhbwstuttgart/environment/CompilationEnvironment.java b/src/main/java/de/dhbwstuttgart/environment/CompilationEnvironment.java index 7433d661..682e1eea 100644 --- a/src/main/java/de/dhbwstuttgart/environment/CompilationEnvironment.java +++ b/src/main/java/de/dhbwstuttgart/environment/CompilationEnvironment.java @@ -84,7 +84,9 @@ public class CompilationEnvironment { String packageName = getPackageName(JavaTXParser.parse(forSourceFile)); //Set classLoader to include default package for this specific source file File dir = new File(forSourceFile.getParent()); - String path = "file://" + dir.toString().substring(0, dir.toString().length() - packageName.length() + 1); + String dirPath = dir.toString() + "/"; + if(packageName.length()>0)dirPath = dirPath.substring(0,dirPath.length() - packageName.length()); + String path = "file://" + dirPath; ArrayList defaultPath = Lists.newArrayList(new URL(path)); classLoader = new URLClassLoader(defaultPath.toArray(new URL[0]), classLoader); //Gather all names in the default package for this source file (classes that are imported by default) @@ -92,14 +94,15 @@ public class CompilationEnvironment { if(files != null)for (File classFile : files) { String className = classFile.getName().substring(0,classFile.getName().length()-6); ret.add(classLoader.loadClass(packageName + className)); - } + } return ret; } private static String getPackageName(CompilationUnitContext forTree){ String packageName = ""; - for(TerminalNode subPackage : forTree.packageDeclaration().Identifier()){ - packageName += subPackage.toString() + "."; + if(forTree.packageDeclaration() != null && forTree.packageDeclaration().Identifier() != null) + for(TerminalNode subPackage : forTree.packageDeclaration().Identifier()){ + packageName += subPackage.toString() + "."; } return packageName; } diff --git a/src/test/java/packages/LoadDefaultPackageClassesTest.java b/src/test/java/packages/LoadDefaultPackageClassesTest.java new file mode 100644 index 00000000..25af87ef --- /dev/null +++ b/src/test/java/packages/LoadDefaultPackageClassesTest.java @@ -0,0 +1,39 @@ +package packages; + +import com.google.common.collect.Lists; +import de.dhbwstuttgart.core.JavaTXCompiler; +import de.dhbwstuttgart.environment.CompilationEnvironment; +import junit.framework.TestCase; +import org.junit.Test; + +import java.io.File; +import java.io.IOException; +import java.net.URL; +import java.net.URLClassLoader; + +public class LoadDefaultPackageClassesTest extends TestCase { + + public static final String rootDirectory = System.getProperty("user.dir")+"/src/test/resources/javFiles/packageTest/"; + + + public LoadDefaultPackageClassesTest() throws ClassNotFoundException, IOException { + /* + Generate ToImport class in rootDirectory and in output-Directory + */ + JavaTXCompiler compiler = new JavaTXCompiler(new File(rootDirectory+"Gen.jav")); + compiler.typeInference(); + compiler.generateBytecode(); + File f = new File(rootDirectory + "Gen.class"); + assertTrue(f.exists()); + } + + public void testLoadGenClass() throws IOException, ClassNotFoundException { + CompilationEnvironment.loadDefaultPackageClasses(new File( rootDirectory + "Test.jav"), ClassLoader.getSystemClassLoader()); + + } + public void testURLClassLoader() throws IOException, ClassNotFoundException { + URLClassLoader cl = new URLClassLoader(new URL[]{new URL("file://"+rootDirectory)}, ClassLoader.getSystemClassLoader()); + cl.loadClass("Gen"); + } + +} diff --git a/src/test/resources/javFiles/packageTest/Gen.jav b/src/test/resources/javFiles/packageTest/Gen.jav new file mode 100644 index 00000000..3b58b188 --- /dev/null +++ b/src/test/resources/javFiles/packageTest/Gen.jav @@ -0,0 +1,8 @@ +import java.lang.Integer; +import java.util.Vector; + +public class Gen{ + Vector m(Vector v){ + return v; + } +} diff --git a/src/test/resources/javFiles/packageTest/Test.jav b/src/test/resources/javFiles/packageTest/Test.jav new file mode 100644 index 00000000..2f6429a1 --- /dev/null +++ b/src/test/resources/javFiles/packageTest/Test.jav @@ -0,0 +1,3 @@ + +public class Test{ +} diff --git a/src/test/resources/javFiles/packageTest/de/test/output/de/test/mathStrucVectoruse.java b/src/test/resources/javFiles/packageTest/de/test/output/de/test/mathStrucVectoruse.java new file mode 100644 index 00000000..54b9e45b --- /dev/null +++ b/src/test/resources/javFiles/packageTest/de/test/output/de/test/mathStrucVectoruse.java @@ -0,0 +1,10 @@ +package de.test; +import de.test.mathStrucVector; + + +class mathStrucVectorUse { + + public static void main(String[] args) { + new mathStrucVector().main(); + } +} diff --git a/src/test/resources/javFiles/packageTest/de/test/output/mathStrucVectoruse.java b/src/test/resources/javFiles/packageTest/de/test/output/mathStrucVectoruse.java new file mode 100644 index 00000000..9a9b2e75 --- /dev/null +++ b/src/test/resources/javFiles/packageTest/de/test/output/mathStrucVectoruse.java @@ -0,0 +1,8 @@ + + +class mathStrucVectorUse { + + public static void main(String[] args) { + new mathStrucVector().main(); + } +} diff --git a/vorgehen.md b/vorgehen.md index 0854c152..a83ca18f 100644 --- a/vorgehen.md +++ b/vorgehen.md @@ -32,6 +32,17 @@ * damit lässt sich ein andere ort zur Ausgabe der Class-files bestimmen # Tasks +* Es steht nur noch ein Task aus: +## Klassen aus Default Package laden +* Das kann für jede SourceFile anders sein +* Momentan funktioniert der Compiler sowieso nur mit einer SourceFile! +* an allen Stellen, an denen die Imports der SourceFile beachtet werden, müssen jetzt auch alle Klassen aus dem gleichen Ordner beachtet werden + +### Stand +* CompilationEnvironment wurde erweitert und kann alle Klassen aus einem Ordner laden +* Allerdings funktionieren manche Tests noch nicht +* Die Bytecode-Tests funktionieren nicht, da sich kaputte Klassen im Bytecode-Jav-Ordner befinden + ## Class files in richtigen Ordner legen ## * Wenn Pfad übergeben, dann in Pfad + packageName * Ohne Pfad, direkt neben die Source File legen From 6779f10b0809b2a1d3ca53ff34902c143eb681e1 Mon Sep 17 00:00:00 2001 From: "pl@gohorb.ba-horb.de" Date: Tue, 7 Jan 2020 18:37:43 +0100 Subject: [PATCH 24/81] modified: ../../../../main/java/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java Bug "." wird in replaceAll nicht ersetzt, deshalb "/" durch "." und nicht "." durch "/" ersetzt. modified: ../../../java/packages/OLTest.java modified: ../../../java/packages/mathStrucVectorTest.java renamed: de/test/OL.jav -> OL.jav renamed: de/test/OLMain.jav -> OLMain.jav OL ins default-Package verschoben --- .../java/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java | 2 +- src/test/java/packages/OLTest.java | 8 ++++---- src/test/java/packages/mathStrucVectorTest.java | 7 ++++--- .../resources/javFiles/packageTest/{de/test => }/OL.jav | 0 .../javFiles/packageTest/{de/test => }/OLMain.jav | 4 +++- 5 files changed, 12 insertions(+), 9 deletions(-) rename src/test/resources/javFiles/packageTest/{de/test => }/OL.jav (100%) rename src/test/resources/javFiles/packageTest/{de/test => }/OLMain.jav (54%) diff --git a/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java b/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java index 136dec53..ac103378 100644 --- a/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java +++ b/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java @@ -960,7 +960,7 @@ public class BytecodeGenMethod implements StatementVisitor { boolean typesEqual = true; Class[] pTypes = m.getParameterTypes(); for(int j = 0; j Date: Wed, 8 Jan 2020 14:47:03 +0100 Subject: [PATCH 25/81] modified: ../../../main/java/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java .replace("/", ".")); anegfuegt, damit auch bei packages superklassen gefunden erden. --- src/main/java/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java b/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java index ac103378..5f1e6132 100644 --- a/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java +++ b/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java @@ -776,7 +776,7 @@ public class BytecodeGenMethod implements StatementVisitor { String superClass = ""; while(true) { try { - superClass = helper.getSuperClass(receiverName); + superClass = helper.getSuperClass(receiverName.replace("/", ".")); try { String superClazz = superClass.replace("/", "."); From d1138540deb24eaf100b8adb2ebeec3465aac073 Mon Sep 17 00:00:00 2001 From: JanUlrich Date: Fri, 10 Jan 2020 16:53:14 +0100 Subject: [PATCH 26/81] Make jar with dependencies executable --- pom.xml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/pom.xml b/pom.xml index 5b9b2e73..ef0f4502 100644 --- a/pom.xml +++ b/pom.xml @@ -110,6 +110,11 @@ http://maven.apache.org/maven-v4_0_0.xsd"> + + + de.dhbwstuttgart.core.ConsoleInterface + + jar-with-dependencies From f3d6fcb417aed7f55d045164cc0af6a5e49b3728 Mon Sep 17 00:00:00 2001 From: JanUlrich Date: Sat, 11 Jan 2020 20:19:23 +0100 Subject: [PATCH 27/81] add -classpath to ConsoleInterface. Fix bug --- .../dhbwstuttgart/bytecode/BytecodeGenMethod.java | 2 +- .../de/dhbwstuttgart/core/ConsoleInterface.java | 2 +- .../de/dhbwstuttgart/core/JavaTXCompiler.java | 15 ++++++++------- .../packages/LoadDefaultPackageClassesTest.java | 15 ++++++++++++++- 4 files changed, 24 insertions(+), 10 deletions(-) diff --git a/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java b/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java index 5f1e6132..a7664c6a 100644 --- a/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java +++ b/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java @@ -814,7 +814,7 @@ public class BytecodeGenMethod implements StatementVisitor { // mDesc = helper.generateBCForFunN(methCallType,typesOfParams); }else { try { - cLoader2 = new URLClassLoader(new URL[] {new URL("file://"+path)}, classLoader); + cLoader2 = new URLClassLoader(new URL[] {new URL("file://" + path + "/")}, classLoader); java.lang.reflect.Method[] methods = cLoader2.loadClass(clazz).getMethods(); System.out.println("Methods of " + receiverName + " "); for(int i = 0; i typeinferenceResult, + public void generateBytecode(String outputPath, List typeinferenceResult, List simplifyResultsForAllSourceFiles) throws IOException { for (File f : sourceFiles.keySet()) { HashMap classFiles = new HashMap<>(); SourceFile sf = sourceFiles.get(f); + String path; + if(outputPath == null){ + path = f.getParent(); //Set path to path of the parsed .jav file + }else{ + path = outputPath + sf.getPkgName().replace(".","/"); //add package path to root path + } BytecodeGen bytecodeGen = new BytecodeGen(classFiles, typeinferenceResult, simplifyResultsForAllSourceFiles, sf, path, classLoader); bytecodeGen.visit(sf); - if(path == null){ - path = f.getParent(); //Set path to path of the parsed .jav file - }else{ - path += sf.getPkgName().replace(".","/"); //add package path to root path - } writeClassFile(bytecodeGen.getClassFiles(), path); } } diff --git a/src/test/java/packages/LoadDefaultPackageClassesTest.java b/src/test/java/packages/LoadDefaultPackageClassesTest.java index 25af87ef..47fcc4d7 100644 --- a/src/test/java/packages/LoadDefaultPackageClassesTest.java +++ b/src/test/java/packages/LoadDefaultPackageClassesTest.java @@ -29,11 +29,24 @@ public class LoadDefaultPackageClassesTest extends TestCase { public void testLoadGenClass() throws IOException, ClassNotFoundException { CompilationEnvironment.loadDefaultPackageClasses(new File( rootDirectory + "Test.jav"), ClassLoader.getSystemClassLoader()); - } + public void testURLClassLoader() throws IOException, ClassNotFoundException { URLClassLoader cl = new URLClassLoader(new URL[]{new URL("file://"+rootDirectory)}, ClassLoader.getSystemClassLoader()); cl.loadClass("Gen"); } + public void testE2E() throws IOException, ClassNotFoundException { + JavaTXCompiler compiler = new JavaTXCompiler(new File(rootDirectory+"OL.jav")); + compiler.typeInference(); + compiler.generateBytecode(); + File f = new File(rootDirectory + "OL.class"); + assertTrue(f.exists()); + + compiler = new JavaTXCompiler(new File(rootDirectory+"OLMain.jav")); + compiler.typeInference(); + compiler.generateBytecode(); + f = new File(rootDirectory + "OLMain.class"); + assertTrue(f.exists()); + } } From 0c1ca3d20080bf5cce1a82ec63b5798eda0882d9 Mon Sep 17 00:00:00 2001 From: JanUlrich Date: Sun, 12 Jan 2020 22:49:51 +0100 Subject: [PATCH 28/81] =?UTF-8?q?Fehler=20beheben=20und=20DirecotryClassLo?= =?UTF-8?q?ader=20anf=C3=BCgen?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../bytecode/BytecodeGenMethod.java | 4 ++- .../dhbwstuttgart/core/ConsoleInterface.java | 4 +-- .../de/dhbwstuttgart/core/JavaTXCompiler.java | 7 +++-- .../environment/CompilationEnvironment.java | 17 +++------- .../environment/DirectoryClassLoader.java | 31 +++++++++++++++++++ .../environment/PackageCrawler.java | 6 ++-- .../typeinference/typeAlgo/TYPE.java | 2 +- .../java/packages/CheckPackageFolder.java | 1 + src/test/java/packages/ImportTest.java | 6 ++-- .../java/packages/mathStrucVectorTest.java | 2 +- vorgehen.md | 4 +++ 11 files changed, 57 insertions(+), 27 deletions(-) create mode 100644 src/main/java/de/dhbwstuttgart/environment/DirectoryClassLoader.java diff --git a/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java b/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java index a7664c6a..1c32748d 100644 --- a/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java +++ b/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java @@ -1,5 +1,6 @@ package de.dhbwstuttgart.bytecode; +import java.io.File; import java.lang.invoke.CallSite; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; @@ -14,6 +15,7 @@ import java.util.LinkedList; import java.util.List; import de.dhbwstuttgart.bytecode.utilities.*; +import de.dhbwstuttgart.environment.DirectoryClassLoader; import de.dhbwstuttgart.exceptions.NotImplementedException; import de.dhbwstuttgart.parser.scope.JavaClassName; import de.dhbwstuttgart.syntaxtree.statement.*; @@ -814,7 +816,7 @@ public class BytecodeGenMethod implements StatementVisitor { // mDesc = helper.generateBCForFunN(methCallType,typesOfParams); }else { try { - cLoader2 = new URLClassLoader(new URL[] {new URL("file://" + path + "/")}, classLoader); + cLoader2 = new DirectoryClassLoader(new File(path), classLoader); java.lang.reflect.Method[] methods = cLoader2.loadClass(clazz).getMethods(); System.out.println("Methods of " + receiverName + " "); for(int i = 0; i input = new ArrayList<>(); - List classpath = new ArrayList<>(); + List classpath = new ArrayList<>(); String outputPath = null; Iterator it = Arrays.asList(args).iterator(); while(it.hasNext()){ @@ -23,7 +23,7 @@ public class ConsoleInterface { }else if(arg.equals("-cp") || arg.equals("-classpath")){ String[] cps = it.next().split(":"); for(String cp : cps){ - classpath.add(new URL("file://"+cp)); + classpath.add(new File(cp)); } }else{ input.add(new File(arg)); diff --git a/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java b/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java index 04f7aa27..2ed5a67d 100644 --- a/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java +++ b/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java @@ -7,6 +7,7 @@ import de.dhbwstuttgart.bytecode.Exception.BytecodeGeneratorError; import de.dhbwstuttgart.bytecode.genericsGenerator.GeneratedGenericsFinder; import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.GenericGenratorResultForSourceFile; import de.dhbwstuttgart.environment.CompilationEnvironment; +import de.dhbwstuttgart.environment.DirectoryClassLoader; import de.dhbwstuttgart.parser.JavaTXParser; import de.dhbwstuttgart.parser.scope.GenericsRegistry; import de.dhbwstuttgart.parser.SyntaxTreeGenerator.SyntaxTreeGenerator; @@ -75,12 +76,12 @@ public class JavaTXCompiler { this(sourceFiles, null); INSTANCE = this; } - public JavaTXCompiler(List sources, List contextPath) throws IOException, ClassNotFoundException { + public JavaTXCompiler(List sources, List contextPath) throws IOException, ClassNotFoundException { if(contextPath == null || contextPath.isEmpty()){ //When no contextPaths are given, the working directory is the sources root - contextPath = Lists.newArrayList(new URL("file://" + System.getProperty("user.dir"))); + contextPath = Lists.newArrayList(new File(System.getProperty("user.dir"))); } - classLoader = new URLClassLoader(contextPath.toArray(new URL[0]), ClassLoader.getSystemClassLoader()); + classLoader = new DirectoryClassLoader(contextPath, ClassLoader.getSystemClassLoader()); environment = new CompilationEnvironment(sources); for (File s : sources) { sourceFiles.put(s, parse(s)); diff --git a/src/main/java/de/dhbwstuttgart/environment/CompilationEnvironment.java b/src/main/java/de/dhbwstuttgart/environment/CompilationEnvironment.java index 682e1eea..ca879cfd 100644 --- a/src/main/java/de/dhbwstuttgart/environment/CompilationEnvironment.java +++ b/src/main/java/de/dhbwstuttgart/environment/CompilationEnvironment.java @@ -1,24 +1,15 @@ package de.dhbwstuttgart.environment; import java.io.File; -import java.io.FilenameFilter; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; -import java.net.URLClassLoader; import java.util.*; import com.google.common.collect.Lists; import de.dhbwstuttgart.syntaxtree.ClassOrInterface; -import de.dhbwstuttgart.syntaxtree.SourceFile; import de.dhbwstuttgart.syntaxtree.factory.ASTFactory; import org.antlr.v4.runtime.tree.TerminalNode; -import org.reflections.Reflections; -import org.reflections.scanners.ResourcesScanner; -import org.reflections.scanners.SubTypesScanner; -import org.reflections.util.ClasspathHelper; -import org.reflections.util.ConfigurationBuilder; -import org.reflections.util.FilterBuilder; import de.dhbwstuttgart.exceptions.DebugException; import de.dhbwstuttgart.parser.JavaTXParser; @@ -52,7 +43,7 @@ public class CompilationEnvironment { * */ //String bootClassPath = System.getProperty("sun.boot.class.path"); - // ClassLoader cl = ClassLoader.getPlatformClassLoader(); + // DirectoryClassLoader cl = DirectoryClassLoader.getPlatformClassLoader(); String bootClassPath = System.getProperty("java.class.path"); librarys = new ArrayList<>(); for(String path : bootClassPath.split(File.pathSeparator)) { @@ -86,9 +77,9 @@ public class CompilationEnvironment { File dir = new File(forSourceFile.getParent()); String dirPath = dir.toString() + "/"; if(packageName.length()>0)dirPath = dirPath.substring(0,dirPath.length() - packageName.length()); - String path = "file://" + dirPath; - ArrayList defaultPath = Lists.newArrayList(new URL(path)); - classLoader = new URLClassLoader(defaultPath.toArray(new URL[0]), classLoader); + String path = dirPath; + ArrayList defaultPath = Lists.newArrayList(new File(path)); + classLoader = new DirectoryClassLoader(defaultPath, classLoader); //Gather all names in the default package for this source file (classes that are imported by default) File [] files = dir.listFiles((dir1, name) -> name.endsWith(".class")); if(files != null)for (File classFile : files) { diff --git a/src/main/java/de/dhbwstuttgart/environment/DirectoryClassLoader.java b/src/main/java/de/dhbwstuttgart/environment/DirectoryClassLoader.java new file mode 100644 index 00000000..a74dbc49 --- /dev/null +++ b/src/main/java/de/dhbwstuttgart/environment/DirectoryClassLoader.java @@ -0,0 +1,31 @@ +package de.dhbwstuttgart.environment; + +import java.io.File; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLClassLoader; +import java.util.List; +import java.util.stream.Collectors; + +public class DirectoryClassLoader extends URLClassLoader { + public DirectoryClassLoader(File directory, java.lang.ClassLoader parent) { + super(generateURLArray(dirToURL(directory)), parent); + } + + public DirectoryClassLoader(List directory, java.lang.ClassLoader parent) { + super(directory.stream().map(DirectoryClassLoader::dirToURL).collect(Collectors.toList()).toArray(new URL[0]), parent); + } + + private static URL[] generateURLArray(URL url) { + return new URL[]{url}; + } + + private static URL dirToURL(File url){ + if(!url.isDirectory())throw new RuntimeException(url.toString() + " is not a directory"); + try { + return url.toURI().toURL(); + } catch (MalformedURLException e) { + throw new RuntimeException(e); + } + } +} diff --git a/src/main/java/de/dhbwstuttgart/environment/PackageCrawler.java b/src/main/java/de/dhbwstuttgart/environment/PackageCrawler.java index 7c63a0b6..646440b1 100644 --- a/src/main/java/de/dhbwstuttgart/environment/PackageCrawler.java +++ b/src/main/java/de/dhbwstuttgart/environment/PackageCrawler.java @@ -26,11 +26,11 @@ public class PackageCrawler { public Set> getClassesInPackage(String packageName){ /* - List classLoadersList = new LinkedList(); + List classLoadersList = new LinkedList(); classLoadersList.add(Thread.currentThread().getContextClassLoader()); classLoadersList.add(ClasspathHelper.staticClassLoader()); classLoadersList.add(Thread.currentThread().getContextClassLoader().getParent()); - classLoadersList.add(ClassLoader.getSystemClassLoader()); + classLoadersList.add(DirectoryClassLoader.getSystemClassLoader()); String bootClassPath = System.getProperty("sun.boot.class.path"); ArrayList urlList = new ArrayList<>(); for(String path : bootClassPath.split(";")) { @@ -41,7 +41,7 @@ public class PackageCrawler { } } URL[] urls = urlList.toArray(new URL[0]); - classLoadersList.add(new URLClassLoader(urls, ClassLoader.getSystemClassLoader())); + classLoadersList.add(new URLClassLoader(urls, DirectoryClassLoader.getSystemClassLoader())); */ Reflections reflections = new Reflections(new ConfigurationBuilder() .setScanners(new SubTypesScanner(false /* don't exclude Object.class */), new ResourcesScanner()) diff --git a/src/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPE.java b/src/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPE.java index 246c3691..c84fa143 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPE.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPE.java @@ -46,7 +46,7 @@ public class TYPE { /* TODO: Hier eine Information erstellen nur mit den importierte Klassen einer einzigen SourceFile private TypeInferenceInformation getTypeInferenceInformation(sourceFile) { - ClassLoader classLoader = ClassLoader.getSystemClassLoader(); + DirectoryClassLoader classLoader = DirectoryClassLoader.getSystemClassLoader(); Set classes = new HashSet<>(); for(SourceFile sourceFile : sfs){ diff --git a/src/test/java/packages/CheckPackageFolder.java b/src/test/java/packages/CheckPackageFolder.java index b0cfbb8e..4f545485 100644 --- a/src/test/java/packages/CheckPackageFolder.java +++ b/src/test/java/packages/CheckPackageFolder.java @@ -4,6 +4,7 @@ import de.dhbwstuttgart.core.JavaTXCompiler; import de.dhbwstuttgart.syntaxtree.SourceFile; import junit.framework.TestCase; import org.junit.Test; +import org.junit.rules.ExpectedException; import java.io.File; import java.io.IOException; diff --git a/src/test/java/packages/ImportTest.java b/src/test/java/packages/ImportTest.java index 4ae04779..92d3f5bb 100644 --- a/src/test/java/packages/ImportTest.java +++ b/src/test/java/packages/ImportTest.java @@ -48,7 +48,7 @@ public class ImportTest extends TestCase { public void testSetPackageNameInBytecodeAndOutputFolder() throws IOException, ClassNotFoundException { JavaTXCompiler compiler = new JavaTXCompiler( Lists.newArrayList(new File(rootDirectory+"ImportTest.jav")), - Lists.newArrayList(new URL("file://"+rootDirectory+"output/"))); + Lists.newArrayList(new File(rootDirectory+"output/"))); compiler.typeInference(); File f = new File(rootDirectory + "output/de/test/ImportTest.class"); if(f.exists() && !f.isDirectory()) { @@ -63,7 +63,7 @@ public class ImportTest extends TestCase { public void testSetPackageNameInBytecodeAndStandardOutputFolder() throws IOException, ClassNotFoundException { JavaTXCompiler compiler = new JavaTXCompiler( Lists.newArrayList(new File(rootDirectory+"ImportTest.jav")), - Lists.newArrayList(new URL("file://"+rootDirectory+"output/"))); + Lists.newArrayList(new File(rootDirectory+"output/"))); compiler.typeInference(); File f = new File(rootDirectory + "ImportTest.class"); if(f.exists() && !f.isDirectory()) { @@ -79,7 +79,7 @@ public class ImportTest extends TestCase { public void testImportTwoClasses() throws IOException, ClassNotFoundException { JavaTXCompiler compiler = new JavaTXCompiler( Lists.newArrayList(new File(rootDirectory+"ImportTest2.jav")), - Lists.newArrayList(new URL("file://"+rootDirectory+"output/"))); + Lists.newArrayList(new File(rootDirectory+"output/"))); compiler.typeInference(); File f = new File(rootDirectory + "ImportTest2.class"); if(f.exists() && !f.isDirectory()) { diff --git a/src/test/java/packages/mathStrucVectorTest.java b/src/test/java/packages/mathStrucVectorTest.java index 8911ce9c..a9d07684 100644 --- a/src/test/java/packages/mathStrucVectorTest.java +++ b/src/test/java/packages/mathStrucVectorTest.java @@ -39,7 +39,7 @@ public class mathStrucVectorTest extends TestCase { public void testSetPackageNameInBytecodeAndOutputFolder() throws IOException, ClassNotFoundException { JavaTXCompiler compiler = new JavaTXCompiler( Lists.newArrayList(new File(rootDirectory+"mathStrucVector.jav")), - Lists.newArrayList(new URL("file://"+rootDirectory+"output/"))); + Lists.newArrayList(new File(rootDirectory+"output/"))); compiler.typeInference(); File f = new File(rootDirectory + "output/de/test/mathStrucVector.class"); if(f.exists() && !f.isDirectory()) { diff --git a/vorgehen.md b/vorgehen.md index a83ca18f..c779c036 100644 --- a/vorgehen.md +++ b/vorgehen.md @@ -72,3 +72,7 @@ TODO: * wurde bereits erledigt -> TODO: Testen ## Console Interface um Parameter -classpath und -output directory erweitern + +# TODO 11.1.20 : +* Es muss überall, wo der URLClassloader mit einem Pfad instantiert wird, gecheckt werden, ob der Pfad mit "/" aufhört. + * Am besten eine Hilfsmethode schreiben From 5500180c6bead60757a691c6be75060934510931 Mon Sep 17 00:00:00 2001 From: "pl@gohorb.ba-horb.de" Date: Wed, 15 Jan 2020 20:47:39 +0100 Subject: [PATCH 29/81] modified: ../../../../main/java/de/dhbwstuttgart/core/JavaTXCompiler.java modified: ../../../../main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java --- .../java/de/dhbwstuttgart/core/JavaTXCompiler.java | 10 ++++++---- .../typeinference/unify/TypeUnifyTask.java | 4 ++-- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java b/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java index 2ed5a67d..a24a94d5 100644 --- a/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java +++ b/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java @@ -44,12 +44,14 @@ import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; +import java.io.OutputStreamWriter; import java.net.URL; import java.net.URLClassLoader; import java.util.*; import java.util.function.Function; import java.util.stream.Collectors; -//import org.apache.commons.io.output.NullOutputStream; +import org.apache.commons.io.output.NullOutputStream; + public class JavaTXCompiler { @@ -478,11 +480,11 @@ public class JavaTXCompiler { final ConstraintSet cons = getConstraints(); Set> results = new HashSet<>(); try { - Writer logFile = // new OutputStreamWriter(new NullOutputStream()); + Writer logFile = new OutputStreamWriter(new NullOutputStream()); // new FileWriter(new // File(System.getProperty("user.dir")+"/src/test/resources/logFiles/"+"log_"+sourceFiles.keySet().iterator().next().getName())); - new FileWriter(new File(System.getProperty("user.dir") + "/logFiles/" + "log_" - + sourceFiles.keySet().iterator().next().getName())); + //new FileWriter(new File(System.getProperty("user.dir") + "/logFiles/" + "log_" + // + sourceFiles.keySet().iterator().next().getName())); IFiniteClosure finiteClosure = UnifyTypeFactory.generateFC(allClasses, logFile, classLoader); System.out.println(finiteClosure); ConstraintSet unifyCons = UnifyTypeFactory.convert(cons); diff --git a/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java b/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java index 8e940d70..b1cae201 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java @@ -172,9 +172,9 @@ public class TypeUnifyTask extends RecursiveTask>> { thNo = totalnoOfThread; writeLog("thNo2 " + thNo); try { - this.logFile = //new OutputStreamWriter(new NullOutputStream()); + this.logFile = new OutputStreamWriter(new NullOutputStream()); //new FileWriter(new File(System.getProperty("user.dir")+"/src/test/resources/logFiles/"+"Thread_"+thNo)); - new FileWriter(new File(System.getProperty("user.dir")+"/logFiles/"+"Thread_"+thNo)); + //new FileWriter(new File(System.getProperty("user.dir")+"/logFiles/"+"Thread_"+thNo)); logFile.write(""); } catch (IOException e) { From a6287b1551c08042b4c16ab08a84985acca3dff8 Mon Sep 17 00:00:00 2001 From: JanUlrich Date: Fri, 17 Jan 2020 16:06:51 +0100 Subject: [PATCH 30/81] Work with File instead of Strings when specifying output als classpath --- .../dhbwstuttgart/bytecode/BytecodeGen.java | 5 +-- .../bytecode/BytecodeGenMethod.java | 10 +++--- .../utilities/ByteCodeForFunNGenerator.java | 8 ++--- .../bytecode/utilities/MethodCallHelper.java | 5 +-- .../de/dhbwstuttgart/core/JavaTXCompiler.java | 28 ++++++++++------ .../environment/CompilationEnvironment.java | 2 +- src/test/java/bytecode/OLTest.java | 2 +- src/test/java/packages/Bytecode.java | 2 +- .../java/packages/ConsoleInterfaceTest.java | 32 +++++++++++++++++++ src/test/java/packages/ImportTest.java | 8 ++--- .../resources/bytecode/javFiles/VectorAdd.jav | 2 +- 11 files changed, 74 insertions(+), 30 deletions(-) diff --git a/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGen.java b/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGen.java index 5091af5e..04f408af 100644 --- a/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGen.java +++ b/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGen.java @@ -1,5 +1,6 @@ package de.dhbwstuttgart.bytecode; +import java.io.File; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; @@ -88,7 +89,7 @@ public class BytecodeGen implements ASTVisitor { private Collection listOfResultSets; private ResultSet resultSet; private SourceFile sf; - private String path; + private File path; private Optional fieldInitializations; @@ -122,7 +123,7 @@ public class BytecodeGen implements ASTVisitor { private final ClassLoader classLoader; public BytecodeGen(HashMap classFiles, Collection listOfResultSets, List simplifyResultsForAllSourceFiles, SourceFile sf, - String path, ClassLoader classLoader) { + File path, ClassLoader classLoader) { this.classFiles = classFiles; this.listOfResultSets = listOfResultSets; this.simplifyResultsForAllSourceFiles = simplifyResultsForAllSourceFiles; diff --git a/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java b/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java index 1c32748d..102438f8 100644 --- a/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java +++ b/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java @@ -57,7 +57,7 @@ public class BytecodeGenMethod implements StatementVisitor { private HashMap genericsAndBounds; public boolean isBinaryExp = false; private String superClass; - private String path; + private File path; private SourceFile sf; private IStatement statement = null; private boolean isReturnStmt = false; @@ -85,7 +85,7 @@ public class BytecodeGenMethod implements StatementVisitor { public BytecodeGenMethod(JavaClassName className, String superClass, ResultSet resultSet, Method m, MethodVisitor mv, HashMap paramsAndLocals, ClassWriter cw, HashMap genericsAndBoundsMethod, HashMap genericsAndBounds, boolean isInterface, HashMap classFiles, - SourceFile sf, String path, Block block, int constructorPos, ClassLoader classLoader) { + SourceFile sf, File path, Block block, int constructorPos, ClassLoader classLoader) { this.className = className; this.superClass = superClass; @@ -111,7 +111,7 @@ public class BytecodeGenMethod implements StatementVisitor { public BytecodeGenMethod(JavaClassName className, String superClass,ResultSet resultSet, Method m, MethodVisitor mv, HashMap paramsAndLocals, ClassWriter cw, HashMap genericsAndBoundsMethod, - HashMap genericsAndBounds, boolean isInterface, HashMap classFiles, SourceFile sf,String path, ClassLoader classLoader) { + HashMap genericsAndBounds, boolean isInterface, HashMap classFiles, SourceFile sf,File path, ClassLoader classLoader) { this.className = className; this.superClass = superClass; @@ -134,7 +134,7 @@ public class BytecodeGenMethod implements StatementVisitor { } public BytecodeGenMethod(JavaClassName className, ClassWriter cw, LambdaExpression lambdaExpression, ArrayList usedVars, ResultSet resultSet, MethodVisitor mv, - int indexOfFirstParamLam, boolean isInterface, HashMap classFiles, String path, int lamCounter, SourceFile sf,HashMap genericsAndBoundsMethod, + int indexOfFirstParamLam, boolean isInterface, HashMap classFiles, File path, int lamCounter, SourceFile sf,HashMap genericsAndBoundsMethod, HashMap genericsAndBounds, ClassLoader classLoader) { this.className = className; this.cw = cw; @@ -816,7 +816,7 @@ public class BytecodeGenMethod implements StatementVisitor { // mDesc = helper.generateBCForFunN(methCallType,typesOfParams); }else { try { - cLoader2 = new DirectoryClassLoader(new File(path), classLoader); + cLoader2 = new DirectoryClassLoader(path, classLoader); java.lang.reflect.Method[] methods = cLoader2.loadClass(clazz).getMethods(); System.out.println("Methods of " + receiverName + " "); for(int i = 0; i classFiles, SourceFile sf, + public void generateBytecodForFile(File path, HashMap classFiles, SourceFile sf, List typeinferenceResult) throws IOException { try { List genericResults = getGeneratedGenericResultsForAllSourceFiles(typeinferenceResult); @@ -780,13 +780,23 @@ public class JavaTXCompiler { } public void generateBytecode() throws ClassNotFoundException, IOException, BytecodeGeneratorError { - generateBytecode(null); + generateBytecode((File) null); } /** * @param path - can be null, then class file output is in the same directory as the parsed source files */ public void generateBytecode(String path) throws ClassNotFoundException, IOException, BytecodeGeneratorError { + if(path != null) + generateBytecode(new File(path)); + else + generateBytecode(); + } + + /** + * @param path - can be null, then class file output is in the same directory as the parsed source files + */ + public void generateBytecode(File path) throws ClassNotFoundException, IOException, BytecodeGeneratorError { List typeinferenceResult = this.typeInference(); List simplifyResultsForAllSourceFiles = getGeneratedGenericResultsForAllSourceFiles( typeinferenceResult); @@ -799,16 +809,16 @@ public class JavaTXCompiler { * @param simplifyResultsForAllSourceFiles * @throws IOException */ - public void generateBytecode(String outputPath, List typeinferenceResult, + public void generateBytecode(File outputPath, List typeinferenceResult, List simplifyResultsForAllSourceFiles) throws IOException { for (File f : sourceFiles.keySet()) { HashMap classFiles = new HashMap<>(); SourceFile sf = sourceFiles.get(f); - String path; + File path; if(outputPath == null){ - path = f.getParent(); //Set path to path of the parsed .jav file + path = f.getParentFile(); //Set path to path of the parsed .jav file }else{ - path = outputPath + sf.getPkgName().replace(".","/"); //add package path to root path + path = new File(outputPath ,sf.getPkgName().replace(".","/")); //add package path to root path } BytecodeGen bytecodeGen = new BytecodeGen(classFiles, typeinferenceResult, simplifyResultsForAllSourceFiles, sf, path, classLoader); @@ -817,15 +827,15 @@ public class JavaTXCompiler { } } - private void writeClassFile(HashMap classFiles, String path) throws IOException { + private void writeClassFile(HashMap classFiles, File path) throws IOException { FileOutputStream output; for (JavaClassName name : classFiles.keySet()) { byte[] bytecode = classFiles.get(name); System.out.println("generating " + name + ".class file ..."); // output = new FileOutputStream(new File(System.getProperty("user.dir") + // "/testBytecode/generatedBC/" +name+".class")); - File outputFile = new File(path + File.separator + name.getClassName() + ".class"); - outputFile.getParentFile().mkdirs(); + File outputFile = new File(path, name.getClassName() + ".class"); + outputFile.getAbsoluteFile().getParentFile().mkdirs(); output = new FileOutputStream(outputFile); output.write(bytecode); output.close(); diff --git a/src/main/java/de/dhbwstuttgart/environment/CompilationEnvironment.java b/src/main/java/de/dhbwstuttgart/environment/CompilationEnvironment.java index ca879cfd..746d1e85 100644 --- a/src/main/java/de/dhbwstuttgart/environment/CompilationEnvironment.java +++ b/src/main/java/de/dhbwstuttgart/environment/CompilationEnvironment.java @@ -74,7 +74,7 @@ public class CompilationEnvironment { List ret = new ArrayList<>(); String packageName = getPackageName(JavaTXParser.parse(forSourceFile)); //Set classLoader to include default package for this specific source file - File dir = new File(forSourceFile.getParent()); + File dir = new File(forSourceFile.getAbsoluteFile().getParent()); String dirPath = dir.toString() + "/"; if(packageName.length()>0)dirPath = dirPath.substring(0,dirPath.length() - packageName.length()); String path = dirPath; diff --git a/src/test/java/bytecode/OLTest.java b/src/test/java/bytecode/OLTest.java index d9de9f25..5b98c7ff 100644 --- a/src/test/java/bytecode/OLTest.java +++ b/src/test/java/bytecode/OLTest.java @@ -35,7 +35,7 @@ public class OLTest { pathToClassFile = System.getProperty("user.dir")+"/src/test/resources/testBytecode/generatedBC/"; List typeinferenceResult = compiler.typeInference(); List simplifyResultsForAllSourceFiles = compiler.getGeneratedGenericResultsForAllSourceFiles(typeinferenceResult); - compiler.generateBytecode(pathToClassFile,typeinferenceResult,simplifyResultsForAllSourceFiles); + compiler.generateBytecode(new File(pathToClassFile),typeinferenceResult,simplifyResultsForAllSourceFiles); loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); classToTest = loader.loadClass("OL"); instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); diff --git a/src/test/java/packages/Bytecode.java b/src/test/java/packages/Bytecode.java index 3fabed05..7b5bb958 100644 --- a/src/test/java/packages/Bytecode.java +++ b/src/test/java/packages/Bytecode.java @@ -21,7 +21,7 @@ public class Bytecode extends TestCase { if(f.exists() && !f.isDirectory()) { f.delete(); } - compiler.generateBytecode(null); + compiler.generateBytecode(); f = new File(rootDirectory + "de/test/TestClass.class"); assertTrue(f.exists()); diff --git a/src/test/java/packages/ConsoleInterfaceTest.java b/src/test/java/packages/ConsoleInterfaceTest.java index 32fffe0d..c92bc8a9 100644 --- a/src/test/java/packages/ConsoleInterfaceTest.java +++ b/src/test/java/packages/ConsoleInterfaceTest.java @@ -39,6 +39,38 @@ public class ConsoleInterfaceTest extends TestCase { assertTrue(f.exists()); } + @Test + public void testCpNotEndsWithSlash() throws Exception { + JavaTXCompiler compiler = new JavaTXCompiler(new File(rootDirectory+"/de/test/ToImport.jav")); + compiler.typeInference(); + compiler.generateBytecode(rootDirectory + "output/"); + File f = new File(rootDirectory + "output/de/test/ToImport.class"); + assertTrue(f.exists()); + + f = new File(rootDirectory + "de/test/ImportTest.class"); + if(f.exists() && !f.isDirectory()) { + f.delete(); + } + + ConsoleInterface.main(new String[]{"-cp", rootDirectory + "de/test/output" , rootDirectory + "de/test/ImportTest.jav"}); + + f = new File(rootDirectory + "de/test/ImportTest.class"); + assertTrue(f.exists()); + } + + @Test + public void testOutputDirNotEndsWithSlash() throws Exception { + File f = new File(rootDirectory + "de/test/output/de/test/TestClass.class"); + if(f.exists() && !f.isDirectory()) { + f.delete(); + } + + ConsoleInterface.main(new String[]{"-d", rootDirectory + "de/test/output" ,rootDirectory + "de/test/TestClass.jav"}); + + f = new File(rootDirectory + "de/test/output/de/test/TestClass.class"); + assertTrue(f.exists()); + } + @Test public void testCompileSingleJavFileWithClassPath() throws Exception { JavaTXCompiler compiler = new JavaTXCompiler(new File(rootDirectory+"/de/test/ToImport.jav")); diff --git a/src/test/java/packages/ImportTest.java b/src/test/java/packages/ImportTest.java index 92d3f5bb..dc459629 100644 --- a/src/test/java/packages/ImportTest.java +++ b/src/test/java/packages/ImportTest.java @@ -27,7 +27,7 @@ public class ImportTest extends TestCase { compiler = new JavaTXCompiler(new File(rootDirectory+"ToImport.jav")); compiler.typeInference(); - compiler.generateBytecode(null); + compiler.generateBytecode(); f = new File(rootDirectory + "ToImport.class"); assertTrue(f.exists()); @@ -69,7 +69,7 @@ public class ImportTest extends TestCase { if(f.exists() && !f.isDirectory()) { f.delete(); } - compiler.generateBytecode(null); + compiler.generateBytecode(); f = new File(rootDirectory + "ImportTest.class"); assertTrue(f.exists()); } @@ -85,7 +85,7 @@ public class ImportTest extends TestCase { if(f.exists() && !f.isDirectory()) { f.delete(); } - compiler.generateBytecode(null); + compiler.generateBytecode(); f = new File(rootDirectory + "ImportTest2.class"); assertTrue(f.exists()); } @@ -99,7 +99,7 @@ public class ImportTest extends TestCase { if(f.exists() && !f.isDirectory()) { f.delete(); } - compiler.generateBytecode(null); + compiler.generateBytecode(); f = new File(rootDirectory + "ImportTestDefault.class"); assertTrue(f.exists()); } diff --git a/src/test/resources/bytecode/javFiles/VectorAdd.jav b/src/test/resources/bytecode/javFiles/VectorAdd.jav index bb14aa21..252c322c 100644 --- a/src/test/resources/bytecode/javFiles/VectorAdd.jav +++ b/src/test/resources/bytecode/javFiles/VectorAdd.jav @@ -37,5 +37,5 @@ public class VectorAdd { // var y; // x.add(y); // z = x; -} +// } } From d55e6b3b7577c7cafc7475b8ce975d2039debc70 Mon Sep 17 00:00:00 2001 From: "pl@gohorb.ba-horb.de" Date: Tue, 21 Jan 2020 12:27:41 +0100 Subject: [PATCH 31/81] modified: ../../../../main/java/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java fehlerhafter Aufruf getMethod korrigiert. modified: ../../../java/packages/OLTest.java modified: OLMain.jav new file: OLextends.jav renamed: OL.jav -> de/test/OL.jav OL-Beispiel mit doppelter Vererbung eingefuegt. --- .../bytecode/BytecodeGenMethod.java | 3 +- src/test/java/packages/OLTest.java | 81 ++++++++++++++----- .../resources/javFiles/packageTest/OLMain.jav | 2 +- .../javFiles/packageTest/OLextends.jav | 7 ++ .../javFiles/packageTest/{ => de/test}/OL.jav | 3 +- 5 files changed, 75 insertions(+), 21 deletions(-) create mode 100644 src/test/resources/javFiles/packageTest/OLextends.jav rename src/test/resources/javFiles/packageTest/{ => de/test}/OL.jav (75%) diff --git a/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java b/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java index 102438f8..4bde13d8 100644 --- a/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java +++ b/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java @@ -772,7 +772,7 @@ public class BytecodeGenMethod implements StatementVisitor { java.lang.reflect.Method[] methods = cLoader.loadClass(clazz).getMethods(); System.out.println("Methods of " + receiverName + " "); - methodRefl = getMethod(methodCall.name, methodCall.arglist.getArguments().size(), methods); + methodRefl = getMethod(methodCall.name, methodCall.arglist.getArguments().size(),methCallType, typesOfParams, methods); } catch (Exception e) { String superClass = ""; @@ -934,6 +934,7 @@ public class BytecodeGenMethod implements StatementVisitor { */ private java.lang.reflect.Method getMethod(String name, int i, java.lang.reflect.Method[] methods) { for(java.lang.reflect.Method m : methods) { + //Fehler if(name.equals(m.getName()) && i == m.getParameterCount()) { return m; } diff --git a/src/test/java/packages/OLTest.java b/src/test/java/packages/OLTest.java index 39ca56be..c45b387d 100644 --- a/src/test/java/packages/OLTest.java +++ b/src/test/java/packages/OLTest.java @@ -12,6 +12,8 @@ import java.util.List; import org.junit.BeforeClass; import org.junit.Test; +import com.google.common.collect.Lists; + import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.GenericGenratorResultForSourceFile; import de.dhbwstuttgart.core.JavaTXCompiler; import de.dhbwstuttgart.typeinference.result.ResultSet; @@ -23,34 +25,51 @@ public class OLTest { private static ClassLoader loader; private static Class classToTest; private static Class classToTest1; + private static Class classToTest2; private static String pathToClassFile; private static Object instanceOfClass; private static Object instanceOfClass1; + private static Object instanceOfClass2; + + public static final String rootDirectory = System.getProperty("user.dir")+"/src/test/resources/javFiles/packageTest"; @BeforeClass public static void setUpBeforeClass() throws Exception { - path = System.getProperty("user.dir")+"/src/test/resources/javFiles/packageTest/OL.jav"; + JavaTXCompiler compiler = new JavaTXCompiler(new File(rootDirectory+"/de/test/OL.jav")); + compiler.typeInference(); + compiler.generateBytecode(rootDirectory + "/de/test/output/"); + loader = new URLClassLoader(new URL[] {new URL("file://"+ rootDirectory + "/de/test/output/")}); + classToTest = loader.loadClass("de.test.OL"); + instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); + + path = System.getProperty("user.dir")+"/src/test/resources/javFiles/packageTest/OLextends.jav"; fileToTest = new File(path); - compiler = new JavaTXCompiler(fileToTest); + compiler = new JavaTXCompiler( + Lists.newArrayList(new File(rootDirectory+"/OLextends.jav")), + Lists.newArrayList(new File(rootDirectory+"/de/test/output/"))); + //compiler = new JavaTXCompiler(fileToTest); pathToClassFile = System.getProperty("user.dir")+"/src/test/resources/javFiles/packageTest/"; compiler.generateBytecode(pathToClassFile); - loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); - classToTest = loader.loadClass("OL"); - instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); + loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile), new URL("file://"+ rootDirectory + "/de/test/output/")}); + classToTest1 = loader.loadClass("OLextends"); + instanceOfClass1 = classToTest1.getDeclaredConstructor().newInstance(); path = System.getProperty("user.dir")+"/src/test/resources/javFiles/packageTest/OLMain.jav"; fileToTest = new File(path); - compiler = new JavaTXCompiler(fileToTest); + compiler = new JavaTXCompiler( + Lists.newArrayList(new File(rootDirectory+"/OLMain.jav")), + Lists.newArrayList(new File(rootDirectory+"/de/test/output/"))); + //compiler = new JavaTXCompiler(fileToTest); pathToClassFile = System.getProperty("user.dir")+"/src/test/resources/javFiles/packageTest/"; compiler.generateBytecode(pathToClassFile); - loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); - classToTest1 = loader.loadClass("OLMain"); - instanceOfClass1 = classToTest1.getDeclaredConstructor().newInstance(); + loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile), new URL("file://"+ rootDirectory + "/de/test/output/")}); + classToTest2 = loader.loadClass("OLMain"); + instanceOfClass2 = classToTest2.getDeclaredConstructor().newInstance(); } @Test public void testOLClassName() { - assertEquals("OL", classToTest.getName()); + assertEquals("de.test.OL", classToTest.getName()); } @Test @@ -75,28 +94,54 @@ public class OLTest { } @Test - public void testOLMainClassName() { - assertEquals("OLMain", classToTest1.getName()); + public void testOLextendsClassName() { + assertEquals("OLextends", classToTest1.getName()); } @Test - public void testmainInt() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method main = classToTest1.getDeclaredMethod("main", Integer.class); + public void testextendsInt() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + Method main = classToTest1.getMethod("m", Integer.class); Integer result = (Integer) main.invoke(instanceOfClass1, 5); assertEquals(new Integer(10), result); } @Test - public void testmainDouble() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method main = classToTest1.getDeclaredMethod("main", Double.class); + public void testextendsDouble() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + Method main = classToTest1.getMethod("m", Double.class); Double result = (Double) main.invoke(instanceOfClass1, 5.0); assertEquals(new Double(10.0), result); } @Test - public void testmainString() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method main = classToTest1.getDeclaredMethod("main", String.class); + public void testextendsString() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + Method main = classToTest1.getMethod("m", String.class); String result = (String) main.invoke(instanceOfClass1, "xxx"); assertEquals("xxxxxx", result); } + + @Test + public void testOLMainClassName() { + assertEquals("OLMain", classToTest2.getName()); + } + + @Test + public void testmainInt() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + Method main = classToTest2.getDeclaredMethod("main", Integer.class); + Integer result = (Integer) main.invoke(instanceOfClass2, 5); + assertEquals(new Integer(10), result); + } + + @Test + public void testmainDouble() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + Method main = classToTest2.getDeclaredMethod("main", Double.class); + Double result = (Double) main.invoke(instanceOfClass2, 5.0); + assertEquals(new Double(10.0), result); + } + + @Test + public void testmainString() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + Method main = classToTest2.getDeclaredMethod("main", String.class); + String result = (String) main.invoke(instanceOfClass2, "xxx"); + assertEquals("xxxxxx", result); + } } diff --git a/src/test/resources/javFiles/packageTest/OLMain.jav b/src/test/resources/javFiles/packageTest/OLMain.jav index 89512771..0cdb0b4f 100644 --- a/src/test/resources/javFiles/packageTest/OLMain.jav +++ b/src/test/resources/javFiles/packageTest/OLMain.jav @@ -6,7 +6,7 @@ public class OLMain { main(x) { var ol; - ol = new OL(); + ol = new OLextends(); return ol.m(x); } } diff --git a/src/test/resources/javFiles/packageTest/OLextends.jav b/src/test/resources/javFiles/packageTest/OLextends.jav new file mode 100644 index 00000000..b3c055df --- /dev/null +++ b/src/test/resources/javFiles/packageTest/OLextends.jav @@ -0,0 +1,7 @@ +import de.test.OL; + + +public class OLextends extends OL { + + +} diff --git a/src/test/resources/javFiles/packageTest/OL.jav b/src/test/resources/javFiles/packageTest/de/test/OL.jav similarity index 75% rename from src/test/resources/javFiles/packageTest/OL.jav rename to src/test/resources/javFiles/packageTest/de/test/OL.jav index 91d0f4ab..7f1ba512 100644 --- a/src/test/resources/javFiles/packageTest/OL.jav +++ b/src/test/resources/javFiles/packageTest/de/test/OL.jav @@ -1,3 +1,4 @@ +package de.test; import java.lang.String; import java.lang.Integer; import java.lang.Double; @@ -7,6 +8,6 @@ import java.lang.Boolean; public class OL { - m(x) { return x + x; } + public m(x) { return x + x; } } From a9d6e08a20e8b1d878a155a7758fff4d5140437b Mon Sep 17 00:00:00 2001 From: "pl@gohorb.ba-horb.de" Date: Tue, 21 Jan 2020 14:10:38 +0100 Subject: [PATCH 32/81] modified: ../../../../main/java/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java --- src/main/java/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java b/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java index 4bde13d8..35ad67da 100644 --- a/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java +++ b/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java @@ -786,7 +786,7 @@ public class BytecodeGenMethod implements StatementVisitor { java.lang.reflect.Method[] methods = cLoader.loadClass(superClazz).getMethods(); System.out.println("Methods of " + superClass + " "); - methodRefl = getMethod(methodCall.name, methodCall.arglist.getArguments().size(), methods); + methodRefl = getMethod(methodCall.name, methodCall.arglist.getArguments().size(), methCallType, typesOfParams, methods); break; } catch (Exception e3) { @@ -934,7 +934,6 @@ public class BytecodeGenMethod implements StatementVisitor { */ private java.lang.reflect.Method getMethod(String name, int i, java.lang.reflect.Method[] methods) { for(java.lang.reflect.Method m : methods) { - //Fehler if(name.equals(m.getName()) && i == m.getParameterCount()) { return m; } From bf80361c1f1fe37ecbb284341e19ac3bfff1f00e Mon Sep 17 00:00:00 2001 From: "pl@gohorb.ba-horb.de" Date: Tue, 21 Jan 2020 14:12:48 +0100 Subject: [PATCH 33/81] new file: ../../../java/packages/OLOneFileTest.java new file: OLOneFile.jav --- src/test/java/packages/OLOneFileTest.java | 133 ++++++++++++++++++ .../javFiles/packageTest/OLOneFile.jav | 22 +++ 2 files changed, 155 insertions(+) create mode 100644 src/test/java/packages/OLOneFileTest.java create mode 100644 src/test/resources/javFiles/packageTest/OLOneFile.jav diff --git a/src/test/java/packages/OLOneFileTest.java b/src/test/java/packages/OLOneFileTest.java new file mode 100644 index 00000000..05ebbc5a --- /dev/null +++ b/src/test/java/packages/OLOneFileTest.java @@ -0,0 +1,133 @@ +package packages; + +import static org.junit.Assert.*; + +import java.io.File; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.net.URL; +import java.net.URLClassLoader; +import java.util.List; + +import org.junit.BeforeClass; +import org.junit.Test; + +import com.google.common.collect.Lists; + +import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.GenericGenratorResultForSourceFile; +import de.dhbwstuttgart.core.JavaTXCompiler; +import de.dhbwstuttgart.typeinference.result.ResultSet; + +public class OLOneFileTest { + private static String path; + private static File fileToTest; + private static JavaTXCompiler compiler; + private static ClassLoader loader; + private static Class classToTest; + private static Class classToTest1; + private static Class classToTest2; + private static String pathToClassFile; + private static Object instanceOfClass; + private static Object instanceOfClass1; + private static Object instanceOfClass2; + + public static final String rootDirectory = System.getProperty("user.dir")+"/src/test/resources/javFiles/packageTest"; + + @BeforeClass + public static void setUpBeforeClass() throws Exception { + path = rootDirectory +"/OLOneFile.jav"; + fileToTest = new File(path); + compiler = new JavaTXCompiler( + Lists.newArrayList(fileToTest), + Lists.newArrayList(new File(rootDirectory+"/de/test/output/"))); + pathToClassFile = System.getProperty("user.dir")+"/src/test/resources/javFiles/packageTest/"; + List typeinferenceResult = compiler.typeInference(); + List simplifyResultsForAllSourceFiles = compiler.getGeneratedGenericResultsForAllSourceFiles(typeinferenceResult); + compiler.generateBytecode(new File(pathToClassFile),typeinferenceResult,simplifyResultsForAllSourceFiles); + loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); + classToTest = loader.loadClass("OLOneFile"); + instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); + classToTest1 = loader.loadClass("OLextendsOneFile"); + instanceOfClass1 = classToTest1.getDeclaredConstructor().newInstance(); + classToTest2 = loader.loadClass("OLMainOneFile"); + instanceOfClass2 = classToTest2.getDeclaredConstructor().newInstance(); + } + + @Test + public void testOLClassName() { + assertEquals("OLOneFile", classToTest.getName()); + } + + @Test + public void testmInt() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + Method m = classToTest.getDeclaredMethod("m2", Integer.class); + Integer result = (Integer) m.invoke(instanceOfClass, 5); + assertEquals(new Integer(10), result); + } + + @Test + public void testmDouble() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + Method m = classToTest.getDeclaredMethod("m2", Double.class); + Double result = (Double) m.invoke(instanceOfClass, 5.0); + assertEquals(new Double(10.0), result); + } + + @Test + public void testmString() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + Method m = classToTest.getDeclaredMethod("m2", String.class); + String result = (String) m.invoke(instanceOfClass, "xxx"); + assertEquals("xxxxxx", result); + } + + @Test + public void testOLextendsClassName() { + assertEquals("OLextendsOneFile", classToTest1.getName()); + } + + @Test + public void testextendsInt() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + Method main = classToTest1.getMethod("m2", Integer.class); + Integer result = (Integer) main.invoke(instanceOfClass1, 5); + assertEquals(new Integer(10), result); + } + + @Test + public void testextendsDouble() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + Method main = classToTest1.getMethod("m2", Double.class); + Double result = (Double) main.invoke(instanceOfClass1, 5.0); + assertEquals(new Double(10.0), result); + } + + @Test + public void testextendsString() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + Method main = classToTest1.getMethod("m2", String.class); + String result = (String) main.invoke(instanceOfClass1, "xxx"); + assertEquals("xxxxxx", result); + } + + @Test + public void testOLMainClassName() { + assertEquals("OLMainOneFile", classToTest2.getName()); + } + + @Test + public void testmainInt() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + Method main = classToTest2.getDeclaredMethod("main", Integer.class); + Integer result = (Integer) main.invoke(instanceOfClass2, 5); + assertEquals(new Integer(10), result); + } + + @Test + public void testmainDouble() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + Method main = classToTest2.getDeclaredMethod("main", Double.class); + Double result = (Double) main.invoke(instanceOfClass2, 5.0); + assertEquals(new Double(10.0), result); + } + + @Test + public void testmainString() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + Method main = classToTest2.getDeclaredMethod("main", String.class); + String result = (String) main.invoke(instanceOfClass2, "xxx"); + assertEquals("xxxxxx", result); + } +} diff --git a/src/test/resources/javFiles/packageTest/OLOneFile.jav b/src/test/resources/javFiles/packageTest/OLOneFile.jav new file mode 100644 index 00000000..eb865d61 --- /dev/null +++ b/src/test/resources/javFiles/packageTest/OLOneFile.jav @@ -0,0 +1,22 @@ +import java.lang.String; +import java.lang.Integer; +import java.lang.Double; +import java.lang.Boolean; + + +public class OLOneFile { + + m2(x) { return x + x; } + +} + +public class OLextendsOneFile extends OLOneFile { } + +public class OLMainOneFile { + + main(x) { + var ol; + ol = new OLextendsOneFile(); + return ol.m2(x); + } +} From 8ec1c5148be5f52abed633804500cec12c34e40f Mon Sep 17 00:00:00 2001 From: "pl@gohorb.ba-horb.de" Date: Tue, 21 Jan 2020 14:34:09 +0100 Subject: [PATCH 34/81] =?UTF-8?q?=09new=20file:=20=20=20OLTest.txt=20=09ne?= =?UTF-8?q?w=20file:=20=20=20UseOLMain.java=20Test=20f=C3=BCr=20die=20Coma?= =?UTF-8?q?ndLine-Version?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/test/resources/javFiles/packageTest/OLTest.txt | 6 ++++++ src/test/resources/javFiles/packageTest/UseOLMain.java | 5 +++++ 2 files changed, 11 insertions(+) create mode 100644 src/test/resources/javFiles/packageTest/OLTest.txt create mode 100644 src/test/resources/javFiles/packageTest/UseOLMain.java diff --git a/src/test/resources/javFiles/packageTest/OLTest.txt b/src/test/resources/javFiles/packageTest/OLTest.txt new file mode 100644 index 00000000..d91b58d7 --- /dev/null +++ b/src/test/resources/javFiles/packageTest/OLTest.txt @@ -0,0 +1,6 @@ +java -jar ~/eclipse-workspace/JavaCompilerCore/target/JavaTXcompiler-0.2-jar-with-dependencies.jar de/test/OL.jav -d de/test/output +java -jar ~/eclipse-workspace/JavaCompilerCore/target/JavaTXcompiler-0.2-jar-with-dependencies.jar OLextends.jav -cp de/test/output +java -jar ~/eclipse-workspace/JavaCompilerCore/target/JavaTXcompiler-0.2-jar-with-dependencies.jar OLMain.jav -cp .:de/test/output +javac UseOLMain.java +java -cp .:de/test/output UseOLMain +rm -f UseOLMain.class diff --git a/src/test/resources/javFiles/packageTest/UseOLMain.java b/src/test/resources/javFiles/packageTest/UseOLMain.java new file mode 100644 index 00000000..2d7d6fd8 --- /dev/null +++ b/src/test/resources/javFiles/packageTest/UseOLMain.java @@ -0,0 +1,5 @@ +class UseOLMain { + public static void main(String[] arg) { + System.out.println(new OLMain().main(1+1)); + } +} From 1ec7a78b1475c68f68154f4c482087a8db65fdc6 Mon Sep 17 00:00:00 2001 From: "pl@gohorb.ba-horb.de" Date: Tue, 21 Jan 2020 18:04:56 +0100 Subject: [PATCH 35/81] modified: ../../../../main/java/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java basetype und RefType Fehler korrigiert Methode basetypeComp eingefuegt. --- .../bytecode/BytecodeGenMethod.java | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java b/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java index 35ad67da..60622f72 100644 --- a/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java +++ b/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java @@ -941,6 +941,17 @@ public class BytecodeGenMethod implements StatementVisitor { return null; } + + boolean basetypeComp(String demanded, String given) { + if (demanded.equals("java/lang/Boolean") && given.equals("boolean")) return true; + if (demanded.equals("java/lang/Integer") && given.equals("int")) return true; + if (demanded.equals("java/lang/Short") && given.equals("short")) return true; + if (demanded.equals("java/lang/Byte") && given.equals("byte")) return true; + if (demanded.equals("java/lang/Double") && given.equals("double")) return true; + if (demanded.equals("java/lang/Float") && given.equals("float")) return true; + return false; + } + /** * @param name name of a method * @param i number of parameters @@ -958,11 +969,15 @@ public class BytecodeGenMethod implements StatementVisitor { for(java.lang.reflect.Method m : methods) { if(name.equals(m.getName()) && i == m.getParameterCount() && (methCallType.equals(m.getReturnType().getName().replace(".", "/")) || - m.getReturnType().getName().replace(".", "/").equals(Type.getInternalName(Object.class)))) { + m.getReturnType().getName().replace(".", "/").equals(Type.getInternalName(Object.class)) || + basetypeComp(methCallType, m.getReturnType().getName().replace(".", "/")) + ) ) { boolean typesEqual = true; Class[] pTypes = m.getParameterTypes(); for(int j = 0; j Date: Tue, 21 Jan 2020 18:22:40 +0100 Subject: [PATCH 36/81] modified: ../../../java/packages/LoadDefaultPackageClassesTest.java modified: ../../../java/packages/OLOneFileTest.java --- src/test/java/packages/LoadDefaultPackageClassesTest.java | 7 +++++-- src/test/java/packages/OLOneFileTest.java | 6 +++--- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/src/test/java/packages/LoadDefaultPackageClassesTest.java b/src/test/java/packages/LoadDefaultPackageClassesTest.java index 47fcc4d7..8a3aa3c0 100644 --- a/src/test/java/packages/LoadDefaultPackageClassesTest.java +++ b/src/test/java/packages/LoadDefaultPackageClassesTest.java @@ -20,7 +20,9 @@ public class LoadDefaultPackageClassesTest extends TestCase { /* Generate ToImport class in rootDirectory and in output-Directory */ - JavaTXCompiler compiler = new JavaTXCompiler(new File(rootDirectory+"Gen.jav")); + JavaTXCompiler compiler = new JavaTXCompiler( + Lists.newArrayList(new File(rootDirectory+"Gen.jav")), + Lists.newArrayList(new File(rootDirectory+"/de/test/output/"))); compiler.typeInference(); compiler.generateBytecode(); File f = new File(rootDirectory + "Gen.class"); @@ -35,7 +37,7 @@ public class LoadDefaultPackageClassesTest extends TestCase { URLClassLoader cl = new URLClassLoader(new URL[]{new URL("file://"+rootDirectory)}, ClassLoader.getSystemClassLoader()); cl.loadClass("Gen"); } - +/* public void testE2E() throws IOException, ClassNotFoundException { JavaTXCompiler compiler = new JavaTXCompiler(new File(rootDirectory+"OL.jav")); compiler.typeInference(); @@ -49,4 +51,5 @@ public class LoadDefaultPackageClassesTest extends TestCase { f = new File(rootDirectory + "OLMain.class"); assertTrue(f.exists()); } + */ } diff --git a/src/test/java/packages/OLOneFileTest.java b/src/test/java/packages/OLOneFileTest.java index 05ebbc5a..64b1a2b1 100644 --- a/src/test/java/packages/OLOneFileTest.java +++ b/src/test/java/packages/OLOneFileTest.java @@ -31,15 +31,15 @@ public class OLOneFileTest { private static Object instanceOfClass1; private static Object instanceOfClass2; - public static final String rootDirectory = System.getProperty("user.dir")+"/src/test/resources/javFiles/packageTest"; + public static final String rootDirectory = System.getProperty("user.dir")+"/src/test/resources/javFiles/packageTest/"; @BeforeClass public static void setUpBeforeClass() throws Exception { - path = rootDirectory +"/OLOneFile.jav"; + path = rootDirectory +"OLOneFile.jav"; fileToTest = new File(path); compiler = new JavaTXCompiler( Lists.newArrayList(fileToTest), - Lists.newArrayList(new File(rootDirectory+"/de/test/output/"))); + Lists.newArrayList(new File(rootDirectory+"de/test/output/"))); pathToClassFile = System.getProperty("user.dir")+"/src/test/resources/javFiles/packageTest/"; List typeinferenceResult = compiler.typeInference(); List simplifyResultsForAllSourceFiles = compiler.getGeneratedGenericResultsForAllSourceFiles(typeinferenceResult); From 8d72b58fcc7482bdd51c358484c9cc25554cf51b Mon Sep 17 00:00:00 2001 From: "pl@gohorb.ba-horb.de" Date: Tue, 21 Jan 2020 19:48:31 +0100 Subject: [PATCH 37/81] modified: ../../../../main/java/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java Methode unbenannt in unbox --- .../java/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java b/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java index 60622f72..54f4ab1e 100644 --- a/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java +++ b/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java @@ -942,7 +942,7 @@ public class BytecodeGenMethod implements StatementVisitor { } - boolean basetypeComp(String demanded, String given) { + boolean unbox(String demanded, String given) { if (demanded.equals("java/lang/Boolean") && given.equals("boolean")) return true; if (demanded.equals("java/lang/Integer") && given.equals("int")) return true; if (demanded.equals("java/lang/Short") && given.equals("short")) return true; @@ -970,13 +970,13 @@ public class BytecodeGenMethod implements StatementVisitor { if(name.equals(m.getName()) && i == m.getParameterCount() && (methCallType.equals(m.getReturnType().getName().replace(".", "/")) || m.getReturnType().getName().replace(".", "/").equals(Type.getInternalName(Object.class)) || - basetypeComp(methCallType, m.getReturnType().getName().replace(".", "/")) + unbox(methCallType, m.getReturnType().getName().replace(".", "/")) ) ) { boolean typesEqual = true; Class[] pTypes = m.getParameterTypes(); for(int j = 0; j Date: Fri, 31 Jan 2020 10:03:33 +0100 Subject: [PATCH 38/81] modified: ../../../../main/java/de/dhbwstuttgart/core/JavaTXCompiler.java Weiter Ausgave der abstrakten Syntax auf die Console Fehler bei der Auswahl der Varianz behoben. --- src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java | 1 + .../de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java | 4 ++-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java b/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java index ffae2c9b..68e8befa 100644 --- a/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java +++ b/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java @@ -508,6 +508,7 @@ public class JavaTXCompiler { logFile.write("FC:\\" + finiteClosure.toString() + "\n"); for (SourceFile sf : this.sourceFiles.values()) { logFile.write(ASTTypePrinter.print(sf)); + System.out.println(ASTTypePrinter.print(sf)); } logFile.flush(); diff --git a/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java b/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java index b1cae201..6fc57a7f 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java @@ -607,8 +607,8 @@ public class TypeUnifyTask extends RecursiveTask>> { for (UnifyPair ele : nextSetasList.get(0)) {//check ob a <. ty base oder ob Ueberladung sameBase = sameBase && ele.getBasePair() != null && ele.getBasePair().equals(fstBasePair); } - if (sameBase) { - Optional xi = nextSetasList.stream().map(x -> x.stream().filter(y -> y.getLhsType() instanceof PlaceholderType) + if (sameBase) { //angefuegt PL 2020-02-30 + Optional 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 From 28400c8bde60afe7cdaf7e673627a91007335277 Mon Sep 17 00:00:00 2001 From: "pl@gohorb.ba-horb.de" Date: Thu, 6 Feb 2020 08:51:30 +0100 Subject: [PATCH 39/81] modified: ../../../../main/java/de/dhbwstuttgart/core/JavaTXCompiler.java Variance aller Argumente in Oderconstraints auf 1 gesetzt muss nochmals ueberarbeitet werden modified: ../../../../main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java Returntypen von Operatoren sind \doteq gestezt modified: ../../../../main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java Bei Variance = 2 parallel abgearbeitet geloescht, dass nicht nochmals bearbeitet werden. --- .../de/dhbwstuttgart/core/JavaTXCompiler.java | 22 ++++++++++++++++--- .../typeinference/typeAlgo/TYPEStmt.java | 20 ++++++++++------- .../typeinference/unify/TypeUnifyTask.java | 4 ++-- 3 files changed, 33 insertions(+), 13 deletions(-) diff --git a/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java b/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java index 68e8befa..aca8b17f 100644 --- a/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java +++ b/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java @@ -480,11 +480,11 @@ public class JavaTXCompiler { final ConstraintSet cons = getConstraints(); Set> results = new HashSet<>(); try { - Writer logFile = new OutputStreamWriter(new NullOutputStream()); + Writer logFile = //new OutputStreamWriter(new NullOutputStream()); // new FileWriter(new // File(System.getProperty("user.dir")+"/src/test/resources/logFiles/"+"log_"+sourceFiles.keySet().iterator().next().getName())); - //new FileWriter(new File(System.getProperty("user.dir") + "/logFiles/" + "log_" - // + sourceFiles.keySet().iterator().next().getName())); + new FileWriter(new File(System.getProperty("user.dir") + "/logFiles/" + "log_" + + sourceFiles.keySet().iterator().next().getName())); IFiniteClosure finiteClosure = UnifyTypeFactory.generateFC(allClasses, logFile, classLoader); System.out.println(finiteClosure); ConstraintSet unifyCons = UnifyTypeFactory.convert(cons); @@ -501,6 +501,7 @@ public class JavaTXCompiler { }; logFile.write("Unify:" + unifyCons.toString()); + System.out.println("Unify:" + unifyCons.toString()); unifyCons = unifyCons.map(distributeInnerVars); logFile.write("\nUnify_distributeInnerVars: " + unifyCons.toString()); TypeUnify unify = new TypeUnify(); @@ -597,6 +598,21 @@ public class JavaTXCompiler { return x;// HIER DIE JEWEILS RECHT BZW. LINKE SEITE AUF GLEICHE VARIANZ SETZEN WIE DIE // JEWEILS ANDERE SEITE }); + + //PL 2020-02-05 alle Oder-Constraints Receiver und Parameter werden auf variance 1 gesetzt + //Es wird davon ausgegangen, dass in OderConstraints in Bedingungen für Parameter die Typen der Argumente links stehen + //und die Typen der Rückgabewerte immer rechts stehen + + unifyCons.getOderConstraints().forEach(z -> z.forEach(y -> y.forEach(x -> { + if ((x.getLhsType() instanceof PlaceholderType) && x.getPairOp().compareTo(PairOperator.SMALLERDOT) == 0) { + ((PlaceholderType) x.getLhsType()).setVariance((byte)1); + } + else if ((x.getRhsType() instanceof PlaceholderType) && x.getPairOp().compareTo(PairOperator.EQUALSDOT) == 0) { + ((PlaceholderType) x.getRhsType()).setVariance((byte)-1); + } + }))); + + System.out.println("Unify nach Oder-Constraints-Anpassung:" + unifyCons.toString()); Set varianceTPHold; Set varianceTPH = new HashSet<>(); varianceTPH = varianceInheritanceConstraintSet(unifyCons); diff --git a/src/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java b/src/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java index cbbd9227..2639c6a4 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java @@ -159,6 +159,8 @@ public class TYPEStmt implements StatementVisitor{ } @Override + //Es wird in OderConstraints davon ausgegangen dass die Bedingungen für die Typen der Argumente links stehen + //und die Typen der Rückgabewerte immer rechts stehen (vgl. JavaTXCompiler) public void visit(MethodCall methodCall) { methodCall.receiver.accept(this); //Overloading: @@ -222,6 +224,8 @@ public class TYPEStmt implements StatementVisitor{ } @Override + //Es wird in OderConstraints davon ausgegangen dass die Bedingungen für die Typen der Argumente links stehen + //und die Typen der Rückgabewerte immer rechts stehen (vgl. JavaTXCompiler) public void visit(BinaryExpr binary) { binary.lexpr.accept(this); binary.rexpr.accept(this); @@ -248,7 +252,7 @@ public class TYPEStmt implements StatementVisitor{ numeric = new Constraint<>(); numeric.add(new Pair(binary.lexpr.getType(), bytee, PairOperator.SMALLERDOT)); numeric.add(new Pair(binary.rexpr.getType(), bytee, PairOperator.SMALLERDOT)); - numeric.add(new Pair(binary.getType(), integer, PairOperator.SMALLERDOT)); + numeric.add(new Pair(binary.getType(), integer, PairOperator.EQUALSDOT)); numericAdditionOrStringConcatenation.add(numeric); } //PL eingefuegt 2018-07-17 @@ -256,7 +260,7 @@ public class TYPEStmt implements StatementVisitor{ numeric = new Constraint<>(); numeric.add(new Pair(binary.lexpr.getType(), shortt, PairOperator.SMALLERDOT)); numeric.add(new Pair(binary.rexpr.getType(), shortt, PairOperator.SMALLERDOT)); - numeric.add(new Pair(binary.getType(), integer, PairOperator.SMALLERDOT)); + numeric.add(new Pair(binary.getType(), integer, PairOperator.EQUALSDOT)); numericAdditionOrStringConcatenation.add(numeric); } //PL eingefuegt 2018-07-17 @@ -264,7 +268,7 @@ public class TYPEStmt implements StatementVisitor{ numeric = new Constraint<>(); numeric.add(new Pair(binary.lexpr.getType(), integer, PairOperator.SMALLERDOT)); numeric.add(new Pair(binary.rexpr.getType(), integer, PairOperator.SMALLERDOT)); - numeric.add(new Pair(integer, binary.getType(), PairOperator.SMALLERDOT)); + numeric.add(new Pair(integer, binary.getType(), PairOperator.EQUALSDOT)); numericAdditionOrStringConcatenation.add(numeric); } //PL eingefuegt 2018-07-17 @@ -272,7 +276,7 @@ public class TYPEStmt implements StatementVisitor{ numeric = new Constraint<>(); numeric.add(new Pair(binary.lexpr.getType(), longg, PairOperator.SMALLERDOT)); numeric.add(new Pair(binary.rexpr.getType(), longg, PairOperator.SMALLERDOT)); - numeric.add(new Pair(longg, binary.getType(), PairOperator.SMALLERDOT)); + numeric.add(new Pair(longg, binary.getType(), PairOperator.EQUALSDOT)); numericAdditionOrStringConcatenation.add(numeric); } //PL eingefuegt 2018-07-17 @@ -280,7 +284,7 @@ public class TYPEStmt implements StatementVisitor{ numeric = new Constraint<>(); numeric.add(new Pair(binary.lexpr.getType(), floatt, PairOperator.SMALLERDOT)); numeric.add(new Pair(binary.rexpr.getType(), floatt, PairOperator.SMALLERDOT)); - numeric.add(new Pair(floatt, binary.getType(), PairOperator.SMALLERDOT)); + numeric.add(new Pair(floatt, binary.getType(), PairOperator.EQUALSDOT)); numericAdditionOrStringConcatenation.add(numeric); } //PL eingefuegt 2018-07-17 @@ -288,7 +292,7 @@ public class TYPEStmt implements StatementVisitor{ numeric = new Constraint<>(); numeric.add(new Pair(binary.lexpr.getType(), doublee, PairOperator.SMALLERDOT)); numeric.add(new Pair(binary.rexpr.getType(), doublee, PairOperator.SMALLERDOT)); - numeric.add(new Pair(doublee, binary.getType(), PairOperator.SMALLERDOT)); + numeric.add(new Pair(doublee, binary.getType(), PairOperator.EQUALSDOT)); numericAdditionOrStringConcatenation.add(numeric); } /* PL auskommentiert Anfang 2018-07-17 @@ -362,7 +366,7 @@ public class TYPEStmt implements StatementVisitor{ constraintsSet.addUndConstraint(new Pair(binary.lexpr.getType(), number, PairOperator.SMALLERNEQDOT)); constraintsSet.addUndConstraint(new Pair(binary.rexpr.getType(), number, PairOperator.SMALLERNEQDOT)); //Rückgabetyp ist Boolean - constraintsSet.addUndConstraint(new Pair(bool, binary.getType(), PairOperator.SMALLERDOT)); + constraintsSet.addUndConstraint(new Pair(bool, binary.getType(), PairOperator.EQUALSDOT)); //auskommentiert PL 2018-05-24 //constraintsSet.addUndConstraint(new Pair(binary.lexpr.getType(), number, PairOperator.SMALLERDOT)); @@ -374,7 +378,7 @@ public class TYPEStmt implements StatementVisitor{ The equality operators may be used to compare two operands that are convertible (§5.1.8) to numeric type, or two operands of type boolean or Boolean, or two operands that are each of either reference type or the null type. All other cases result in a compile-time error. */ //Der Equals Operator geht mit fast allen Typen, daher werden hier keine Constraints gesetzt - constraintsSet.addUndConstraint(new Pair(bool, binary.getType(), PairOperator.SMALLERDOT)); + constraintsSet.addUndConstraint(new Pair(bool, binary.getType(), PairOperator.EQUALSDOT)); }else{ throw new NotImplementedException(); } diff --git a/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java b/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java index 6fc57a7f..763faaf9 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java @@ -1068,7 +1068,7 @@ public class TypeUnifyTask extends RecursiveTask>> { } while (!nextSetasListRest.isEmpty()) { Set nSaL = nextSetasListRest.remove(0); - //nextSetasList.remove(nSaL); + nextSetasList.remove(nSaL); //PL einkommentiert 20-02-03 Set newEq = new HashSet<>(eq); Set> newElems = new HashSet<>(elems); List>> newOderConstraints = new ArrayList<>(oderConstraints); @@ -1445,7 +1445,7 @@ public class TypeUnifyTask extends RecursiveTask>> { //else result.stream().filter(y -> !isUndefinedPairSet(y)); writeLog("res: " + res.toString()); } - + //2020-02-02: if (variance ==2) Hier Aufruf von filterOverriding einfuegen writeLog("Return computeCR: " + result.toString()); return result; } From a5662cdd9a07fd022f64c0d74f3b09f5f40c1cb8 Mon Sep 17 00:00:00 2001 From: "pl@gohorb.ba-horb.de" Date: Thu, 6 Feb 2020 11:39:27 +0100 Subject: [PATCH 40/81] modified: src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java Nachtraegliches Einfuegen von Variance in OderConstraints auskommentiert. modified: src/main/java/de/dhbwstuttgart/syntaxtree/factory/UnifyTypeFactory.java Variance im konvertieren eingefuegt modified: src/main/java/de/dhbwstuttgart/syntaxtree/type/TypePlaceholder.java Variace eingefuegt modified: src/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java In OderConstraints Variance bei der Erstellung eingefuegt --- .../de/dhbwstuttgart/core/JavaTXCompiler.java | 2 ++ .../syntaxtree/factory/UnifyTypeFactory.java | 1 + .../syntaxtree/type/TypePlaceholder.java | 11 ++++++++++- .../typeinference/typeAlgo/TYPEStmt.java | 19 +++++++++++++++---- 4 files changed, 28 insertions(+), 5 deletions(-) diff --git a/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java b/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java index aca8b17f..989c100d 100644 --- a/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java +++ b/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java @@ -603,6 +603,7 @@ public class JavaTXCompiler { //Es wird davon ausgegangen, dass in OderConstraints in Bedingungen für Parameter die Typen der Argumente links stehen //und die Typen der Rückgabewerte immer rechts stehen + /* unifyCons.getOderConstraints().forEach(z -> z.forEach(y -> y.forEach(x -> { if ((x.getLhsType() instanceof PlaceholderType) && x.getPairOp().compareTo(PairOperator.SMALLERDOT) == 0) { ((PlaceholderType) x.getLhsType()).setVariance((byte)1); @@ -611,6 +612,7 @@ public class JavaTXCompiler { ((PlaceholderType) x.getRhsType()).setVariance((byte)-1); } }))); + */ System.out.println("Unify nach Oder-Constraints-Anpassung:" + unifyCons.toString()); Set varianceTPHold; diff --git a/src/main/java/de/dhbwstuttgart/syntaxtree/factory/UnifyTypeFactory.java b/src/main/java/de/dhbwstuttgart/syntaxtree/factory/UnifyTypeFactory.java index 33d137eb..84d0f1e5 100644 --- a/src/main/java/de/dhbwstuttgart/syntaxtree/factory/UnifyTypeFactory.java +++ b/src/main/java/de/dhbwstuttgart/syntaxtree/factory/UnifyTypeFactory.java @@ -122,6 +122,7 @@ public class UnifyTypeFactory { System.out.println("XXX"+innerType); } PlaceholderType ntph = new PlaceholderType(tph.getName()); + ntph.setVariance(tph.getVariance()); int in = PLACEHOLDERS.indexOf(ntph); if (in == -1) { PLACEHOLDERS.add(ntph); diff --git a/src/main/java/de/dhbwstuttgart/syntaxtree/type/TypePlaceholder.java b/src/main/java/de/dhbwstuttgart/syntaxtree/type/TypePlaceholder.java index 6f0fa3ff..533ea9a0 100644 --- a/src/main/java/de/dhbwstuttgart/syntaxtree/type/TypePlaceholder.java +++ b/src/main/java/de/dhbwstuttgart/syntaxtree/type/TypePlaceholder.java @@ -18,7 +18,8 @@ import org.antlr.v4.runtime.Token; public class TypePlaceholder extends RefTypeOrTPHOrWildcardOrGeneric { private final String name; - + + int variance = 0; /** @@ -69,6 +70,14 @@ public class TypePlaceholder extends RefTypeOrTPHOrWildcardOrGeneric return name; } + public void setVariance(int variance) { + this.variance= variance; + } + + public int getVariance() { + return this.variance; + } + @Override public void accept(ASTVisitor visitor) { visitor.visit(this); diff --git a/src/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java b/src/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java index 2639c6a4..aca5912e 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java @@ -17,6 +17,7 @@ import de.dhbwstuttgart.typeinference.assumptions.MethodAssumption; import de.dhbwstuttgart.typeinference.assumptions.TypeInferenceBlockInformation; import de.dhbwstuttgart.typeinference.constraints.*; import de.dhbwstuttgart.typeinference.unify.model.PairOperator; +import de.dhbwstuttgart.typeinference.unify.model.PlaceholderType; import java.util.*; import java.util.stream.Collectors; @@ -164,7 +165,7 @@ public class TYPEStmt implements StatementVisitor{ public void visit(MethodCall methodCall) { methodCall.receiver.accept(this); //Overloading: - Set methodConstraints = new HashSet<>(); + Set> methodConstraints = new HashSet<>(); for(MethodAssumption m : this.getMethods(methodCall.name, methodCall.arglist, info)){ GenericsResolver resolver = getResolverInstance(); methodConstraints.add(generateConstraint(methodCall, m, info, resolver)); @@ -559,7 +560,7 @@ public class TYPEStmt implements StatementVisitor{ protected Constraint generateConstraint(MethodCall forMethod, MethodAssumption assumption, TypeInferenceBlockInformation info, GenericsResolver resolver){ - Constraint methodConstraint = new Constraint(); + Constraint methodConstraint = new Constraint<>(); ClassOrInterface receiverCl = assumption.getReceiver(); /* List params = new ArrayList<>(); @@ -572,10 +573,17 @@ public class TYPEStmt implements StatementVisitor{ */ RefTypeOrTPHOrWildcardOrGeneric retType = assumption.getReceiverType(resolver); - methodConstraint.add(new Pair(forMethod.receiver.getType(), retType, + RefTypeOrTPHOrWildcardOrGeneric zwSp; + methodConstraint.add(new Pair(zwSp = forMethod.receiver.getType(), retType, PairOperator.SMALLERDOT)); - methodConstraint.add(new Pair(assumption.getReturnType(resolver), forMethod.getType(), + if (zwSp instanceof TypePlaceholder) { + ((TypePlaceholder) zwSp).setVariance(1); + } + methodConstraint.add(new Pair(assumption.getReturnType(resolver), zwSp = forMethod.getType(), PairOperator.EQUALSDOT)); + if (zwSp instanceof TypePlaceholder) { + ((TypePlaceholder) zwSp).setVariance(-1); + } methodConstraint.addAll(generateParameterConstraints(forMethod, assumption, info, resolver)); return methodConstraint; } @@ -588,6 +596,9 @@ public class TYPEStmt implements StatementVisitor{ RefTypeOrTPHOrWildcardOrGeneric argType = foMethod.arglist.getArguments().get(i).getType(); RefTypeOrTPHOrWildcardOrGeneric assType = assumption.getArgTypes(resolver).get(i); ret.add(new Pair(argType, assType, PairOperator.SMALLERDOT)); + if (argType instanceof TypePlaceholder) { + ((TypePlaceholder) argType).setVariance(1); + } } return ret; } From 23384f413dbea79b38cbe6fd9696b65bca218eee Mon Sep 17 00:00:00 2001 From: "pl@gohorb.ba-horb.de" Date: Thu, 6 Feb 2020 15:27:51 +0100 Subject: [PATCH 41/81] modified: src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java modified: src/main/java/de/dhbwstuttgart/typeinference/unify/model/UnifyPair.java variance von Pairs geloescht. --- .../typeinference/unify/TypeUnifyTask.java | 15 ++------------- .../typeinference/unify/model/UnifyPair.java | 18 ------------------ 2 files changed, 2 insertions(+), 31 deletions(-) diff --git a/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java b/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java index 763faaf9..74c71706 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java @@ -308,8 +308,7 @@ public class TypeUnifyTask extends RecursiveTask>> { nOfUnify++; writeLog(nOfUnify.toString() + " Unifikation: " + eq.toString()); writeLog(nOfUnify.toString() + " Oderconstraints: " + oderConstraints.toString()); - //eq = eq.stream().map(x -> {x.setVariance((byte)-1); return x;}).collect(Collectors.toCollection(HashSet::new)); - + /* * Variancen auf alle Gleichungen vererben */ @@ -2033,7 +2032,6 @@ public class TypeUnifyTask extends RecursiveTask>> { protected Set> unifyCase1(UnifyPair pair, IFiniteClosure fc) { PlaceholderType a = (PlaceholderType)pair.getLhsType(); UnifyType thetaPrime = pair.getRhsType(); - byte variance = pair.getVariance(); Set> result = new HashSet<>(); @@ -2158,7 +2156,6 @@ public class TypeUnifyTask extends RecursiveTask>> { } resultPrime.addAll(substitutionSet); //writeLog("Substitution: " + substitutionSet.toString()); - resultPrime = resultPrime.stream().map(x -> { x.setVariance(variance); return x;}).collect(Collectors.toCollection(HashSet::new)); result.add(resultPrime); //writeLog("Result: " + resultPrime.toString()); //writeLog("MAX: " + oup.max(resultPrime.iterator()).toString()); @@ -2177,7 +2174,6 @@ public class TypeUnifyTask extends RecursiveTask>> { private Set> unifyCase2(UnifyPair pair, IFiniteClosure fc) { PlaceholderType a = (PlaceholderType) pair.getLhsType(); ExtendsType extThetaPrime = (ExtendsType) pair.getRhsType(); - byte variance = pair.getVariance(); Set> result = new HashSet<>(); UnifyType aPrime = PlaceholderType.freshPlaceholder(); @@ -2192,7 +2188,6 @@ public class TypeUnifyTask extends RecursiveTask>> { resultPrime = new HashSet<>(); resultPrime.add(new UnifyPair(a, extAPrime, PairOperator.EQUALSDOT, pair.getSubstitution(), pair)); resultPrime.add(new UnifyPair(aPrime, thetaPrime, PairOperator.SMALLERDOT, pair.getSubstitution(), pair)); - resultPrime = resultPrime.stream().map(x -> { x.setVariance(variance); return x;}).collect(Collectors.toCollection(HashSet::new)); result.add(resultPrime); //writeLog("Result: " + resultPrime.toString()); return result; @@ -2205,7 +2200,6 @@ public class TypeUnifyTask extends RecursiveTask>> { PlaceholderType a = (PlaceholderType) pair.getLhsType(); a.reversVariance(); SuperType subThetaPrime = (SuperType) pair.getRhsType(); - byte variance = pair.getVariance(); Set> result = new HashSet<>(); UnifyType aPrime = PlaceholderType.freshPlaceholder(); @@ -2221,7 +2215,6 @@ public class TypeUnifyTask extends RecursiveTask>> { resultPrime = new HashSet<>(); resultPrime.add(new UnifyPair(a, supAPrime, PairOperator.EQUALSDOT, pair.getSubstitution(), pair)); resultPrime.add(new UnifyPair(thetaPrime, aPrime, PairOperator.SMALLERDOT, pair.getSubstitution(), pair)); - resultPrime = resultPrime.stream().map(x -> { x.setVariance(variance); return x;}).collect(Collectors.toCollection(HashSet::new)); result.add(resultPrime); //writeLog(resultPrime.toString()); @@ -2234,7 +2227,6 @@ public class TypeUnifyTask extends RecursiveTask>> { private Set> unifyCase5(UnifyPair pair, IFiniteClosure fc) { UnifyType theta = pair.getLhsType(); PlaceholderType a = (PlaceholderType) pair.getRhsType(); - byte variance = pair.getVariance(); Set> result = new HashSet<>(); boolean allGen = theta.getTypeParams().size() > 0; @@ -2298,7 +2290,6 @@ public class TypeUnifyTask extends RecursiveTask>> { resultPrime.add(new UnifyPair(a, thetaS, PairOperator.EQUALSDOT, pair.getSubstitution(), pair)); else resultPrime.add(new UnifyPair(a, thetaS.setTypeParams(new TypeParams(freshTphs)), PairOperator.EQUALSDOT, pair.getSubstitution(), pair)); - resultPrime = resultPrime.stream().map(x -> { x.setVariance(variance); return x;}).collect(Collectors.toCollection(HashSet::new)); result.add(resultPrime); //writeLog("FBOUNDED2: " + pair.getfBounded()); //writeLog("resultPrime Theta < a: " + greater + pair + "THETA: " + theta + "FBOUNDED: " + pair.getfBounded() + " " + resultPrime.toString()); @@ -2313,8 +2304,7 @@ public class TypeUnifyTask extends RecursiveTask>> { private Set> unifyCase8(UnifyPair pair, IFiniteClosure fc) { UnifyType theta = pair.getLhsType(); PlaceholderType a = (PlaceholderType) pair.getRhsType(); - byte variance = pair.getVariance(); - Set> result = new HashSet<>(); + Set> result = new HashSet<>(); //for(UnifyType thetaS : fc.grArg(theta)) { Set resultPrime = new HashSet<>(); resultPrime.add(new UnifyPair(a, theta, PairOperator.EQUALSDOT, pair.getSubstitution(), pair)); @@ -2334,7 +2324,6 @@ public class TypeUnifyTask extends RecursiveTask>> { resultPrime = new HashSet<>(); resultPrime.add(new UnifyPair(a, new SuperType(freshTph), PairOperator.EQUALSDOT, pair.getSubstitution(), pair)); resultPrime.add(new UnifyPair(freshTph, theta, PairOperator.SMALLERDOT, pair.getSubstitution(), pair)); - resultPrime = resultPrime.stream().map(x -> { x.setVariance(variance); return x;}).collect(Collectors.toCollection(HashSet::new)); result.add(resultPrime); //writeLog(resultPrime.toString()); //} diff --git a/src/main/java/de/dhbwstuttgart/typeinference/unify/model/UnifyPair.java b/src/main/java/de/dhbwstuttgart/typeinference/unify/model/UnifyPair.java index aafecf15..fbe3a099 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/unify/model/UnifyPair.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/unify/model/UnifyPair.java @@ -28,15 +28,6 @@ public class UnifyPair { * The operator that determines the relation between the left and right hand side type. */ private PairOperator pairOp; - - /** wieder loesecn wird nicht mehr benoetigt PL 2018-03-31 - * variance shows the variance of the pair - * -1: contravariant - * 1 covariant - * 0 invariant - * PL 2018-03-21 - */ - private byte variance = 0; private boolean undefinedPair = false; @@ -83,7 +74,6 @@ public class UnifyPair { pairOp = op; substitution = uni; basePair = base; - this.variance = variance; // Caching hashcode @@ -125,14 +115,6 @@ public class UnifyPair { substitution.addAll(sup); } - public byte getVariance() { - return variance; - } - - public void setVariance(byte v) { - variance = v; - } - public void setUndefinedPair() { undefinedPair = true; } From 5c97d80eb086e9e0471252990693a6a168d5b64a Mon Sep 17 00:00:00 2001 From: "pl@gohorb.ba-horb.de" Date: Thu, 6 Feb 2020 18:35:33 +0100 Subject: [PATCH 42/81] modified: src/main/java/de/dhbwstuttgart/syntaxtree/type/TypePlaceholder.java modified: src/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java --- .../syntaxtree/type/TypePlaceholder.java | 6 ++++++ .../typeinference/typeAlgo/TYPEStmt.java | 14 ++------------ 2 files changed, 8 insertions(+), 12 deletions(-) diff --git a/src/main/java/de/dhbwstuttgart/syntaxtree/type/TypePlaceholder.java b/src/main/java/de/dhbwstuttgart/syntaxtree/type/TypePlaceholder.java index 533ea9a0..73cd2df7 100644 --- a/src/main/java/de/dhbwstuttgart/syntaxtree/type/TypePlaceholder.java +++ b/src/main/java/de/dhbwstuttgart/syntaxtree/type/TypePlaceholder.java @@ -19,6 +19,10 @@ public class TypePlaceholder extends RefTypeOrTPHOrWildcardOrGeneric { private final String name; + /** + * wird bisher nicht genutzt + * setVariance muss ggf. auskommentiert werden. + */ int variance = 0; @@ -70,9 +74,11 @@ public class TypePlaceholder extends RefTypeOrTPHOrWildcardOrGeneric return name; } + /* wird bisher nicht genutzt public void setVariance(int variance) { this.variance= variance; } + */ public int getVariance() { return this.variance; diff --git a/src/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java b/src/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java index aca5912e..af1ba5ed 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java @@ -573,17 +573,10 @@ public class TYPEStmt implements StatementVisitor{ */ RefTypeOrTPHOrWildcardOrGeneric retType = assumption.getReceiverType(resolver); - RefTypeOrTPHOrWildcardOrGeneric zwSp; - methodConstraint.add(new Pair(zwSp = forMethod.receiver.getType(), retType, + methodConstraint.add(new Pair(forMethod.receiver.getType(), retType, PairOperator.SMALLERDOT)); - if (zwSp instanceof TypePlaceholder) { - ((TypePlaceholder) zwSp).setVariance(1); - } - methodConstraint.add(new Pair(assumption.getReturnType(resolver), zwSp = forMethod.getType(), + methodConstraint.add(new Pair(assumption.getReturnType(resolver), forMethod.getType(), PairOperator.EQUALSDOT)); - if (zwSp instanceof TypePlaceholder) { - ((TypePlaceholder) zwSp).setVariance(-1); - } methodConstraint.addAll(generateParameterConstraints(forMethod, assumption, info, resolver)); return methodConstraint; } @@ -596,9 +589,6 @@ public class TYPEStmt implements StatementVisitor{ RefTypeOrTPHOrWildcardOrGeneric argType = foMethod.arglist.getArguments().get(i).getType(); RefTypeOrTPHOrWildcardOrGeneric assType = assumption.getArgTypes(resolver).get(i); ret.add(new Pair(argType, assType, PairOperator.SMALLERDOT)); - if (argType instanceof TypePlaceholder) { - ((TypePlaceholder) argType).setVariance(1); - } } return ret; } From 98997d686ff2a0c5a7dfcbfac2f6160950fa2b7b Mon Sep 17 00:00:00 2001 From: "pl@gohorb.ba-horb.de" Date: Fri, 7 Feb 2020 17:46:11 +0100 Subject: [PATCH 43/81] modified: ../../../main/java/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java Lokale Variablen eingefuegt Wildcards korrigiert logFiule off modified: ../../../main/java/de/dhbwstuttgart/parser/SyntaxTreeGenerator/StatementGenerator.java modified: ../../../main/java/de/dhbwstuttgart/syntaxtree/Constructor.java modified: ../../../main/java/de/dhbwstuttgart/syntaxtree/statement/MethodCall.java modified: ../../../main/java/de/dhbwstuttgart/syntaxtree/statement/NewClass.java modified: ../../../main/java/de/dhbwstuttgart/syntaxtree/statement/SuperCall.java modified: ../../../main/java/de/dhbwstuttgart/syntaxtree/statement/ThisCall.java Typeargumente von Receiver und Argumenten in Methodcall eingefuegt. --- .../bytecode/BytecodeGenMethod.java | 4 ++- .../bytecode/descriptor/TypeToDescriptor.java | 6 ++-- .../de/dhbwstuttgart/core/JavaTXCompiler.java | 6 ++-- .../StatementGenerator.java | 33 +++++++++++++++---- .../dhbwstuttgart/syntaxtree/Constructor.java | 2 +- .../syntaxtree/statement/MethodCall.java | 13 +++++++- .../syntaxtree/statement/NewClass.java | 6 ++-- .../syntaxtree/statement/SuperCall.java | 11 ++++--- .../syntaxtree/statement/ThisCall.java | 2 +- 9 files changed, 62 insertions(+), 21 deletions(-) diff --git a/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java b/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java index 54f4ab1e..00b1fb6e 100644 --- a/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java +++ b/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java @@ -177,6 +177,7 @@ public class BytecodeGenMethod implements StatementVisitor { @Override public void visit(Block block) { + HashMap paramsAndLocalsOld = new HashMap<>(paramsAndLocals); for (Statement stmt : block.getStatements()) { stmt.accept(this); if(stmt instanceof MethodCall) { @@ -185,6 +186,7 @@ public class BytecodeGenMethod implements StatementVisitor { mv.visitInsn(Opcodes.POP); } } + paramsAndLocals = paramsAndLocalsOld; } @Override @@ -222,7 +224,7 @@ public class BytecodeGenMethod implements StatementVisitor { // ?? @Override public void visit(LocalVarDecl localVarDecl) { - + paramsAndLocals.put(localVarDecl.getName(), paramsAndLocals.size()+1); } @Override diff --git a/src/main/java/de/dhbwstuttgart/bytecode/descriptor/TypeToDescriptor.java b/src/main/java/de/dhbwstuttgart/bytecode/descriptor/TypeToDescriptor.java index 8ee84328..aa3db5b1 100644 --- a/src/main/java/de/dhbwstuttgart/bytecode/descriptor/TypeToDescriptor.java +++ b/src/main/java/de/dhbwstuttgart/bytecode/descriptor/TypeToDescriptor.java @@ -20,7 +20,8 @@ public class TypeToDescriptor implements TypeVisitor{ @Override public String visit(SuperWildcardType superWildcardType) { System.out.println("\nWILDCARD ="+superWildcardType.getInnerType().toString().replace(".", "/")); - return superWildcardType.getInnerType().toString().replace(".", "/"); + //return superWildcardType.getInnerType().toString().replace(".", "/"); + return superWildcardType.getInnerType().acceptTV(new TypeToDescriptor()); //throw new NotImplementedException(); } @@ -32,7 +33,8 @@ public class TypeToDescriptor implements TypeVisitor{ @Override public String visit(ExtendsWildcardType extendsWildcardType) { System.out.println("\nWILDCARD extends ="+extendsWildcardType.getInnerType().toString().replace(".", "/")); - return extendsWildcardType.getInnerType().toString().replace(".", "/"); + //return extendsWildcardType.getInnerType().toString().replace(".", "/"); + return extendsWildcardType.getInnerType().acceptTV(new TypeToDescriptor()); //throw new NotImplementedException(); } diff --git a/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java b/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java index 989c100d..5f510946 100644 --- a/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java +++ b/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java @@ -480,11 +480,11 @@ public class JavaTXCompiler { final ConstraintSet cons = getConstraints(); Set> results = new HashSet<>(); try { - Writer logFile = //new OutputStreamWriter(new NullOutputStream()); + Writer logFile = new OutputStreamWriter(new NullOutputStream()); // new FileWriter(new // File(System.getProperty("user.dir")+"/src/test/resources/logFiles/"+"log_"+sourceFiles.keySet().iterator().next().getName())); - new FileWriter(new File(System.getProperty("user.dir") + "/logFiles/" + "log_" - + sourceFiles.keySet().iterator().next().getName())); + //new FileWriter(new File(System.getProperty("user.dir") + "/logFiles/" + "log_" + // + sourceFiles.keySet().iterator().next().getName())); IFiniteClosure finiteClosure = UnifyTypeFactory.generateFC(allClasses, logFile, classLoader); System.out.println(finiteClosure); ConstraintSet unifyCons = UnifyTypeFactory.convert(cons); diff --git a/src/main/java/de/dhbwstuttgart/parser/SyntaxTreeGenerator/StatementGenerator.java b/src/main/java/de/dhbwstuttgart/parser/SyntaxTreeGenerator/StatementGenerator.java index 9305310d..c4625a7a 100644 --- a/src/main/java/de/dhbwstuttgart/parser/SyntaxTreeGenerator/StatementGenerator.java +++ b/src/main/java/de/dhbwstuttgart/parser/SyntaxTreeGenerator/StatementGenerator.java @@ -17,6 +17,7 @@ import org.antlr.v4.runtime.Token; import org.antlr.v4.runtime.tree.TerminalNode; import java.util.*; +import java.util.stream.Collectors; public class StatementGenerator { @@ -209,7 +210,12 @@ public class StatementGenerator { }else throw new NotImplementedException(); ArgumentList argumentList = convert(methodInvocationContext.argumentList()); - MethodCall ret = new MethodCall(TypePlaceholder.fresh(methodInvocationContext.getStart()), getReceiver(receiver), name, argumentList, methodInvocationContext.getStart()); + ArrayList argTypes = argumentList.getArguments().stream() + .map(x -> TypePlaceholder.fresh(methodInvocationContext.getStart())) + .collect(Collectors.toCollection(ArrayList::new)); + MethodCall ret = new MethodCall(TypePlaceholder.fresh(methodInvocationContext.getStart()), + getReceiver(receiver), name, argumentList, TypePlaceholder.fresh(methodInvocationContext.getStart()), + argTypes, methodInvocationContext.getStart()); return ret; } @@ -293,7 +299,10 @@ public class StatementGenerator { RefType newClass = (RefType) TypeGenerator.convertTypeName(identifier.getText(),genericArgs,identifier.getSymbol(),reg,generics); ArgumentList args = convert(newExpression.argumentList()); - return new NewClass(newClass, args, newExpression.getStart()); + ArrayList argTypes = args.getArguments().stream() + .map(x -> TypePlaceholder.fresh(newExpression.getStart())) + .collect(Collectors.toCollection(ArrayList::new)); + return new NewClass(newClass, args, null, argTypes, newExpression.getStart()); } private Statement convert(Java8Parser.PreIncrementExpressionContext stmt) { @@ -779,10 +788,14 @@ public class StatementGenerator { }else { Java8Parser.MethodInvocation_lf_primaryContext ctxt = e.methodInvocation_lf_primary(); String methodName = ctxt.Identifier().toString(); - return new MethodCall(TypePlaceholder.fresh(e.getStart()), getReceiver(expr), methodName, convert(ctxt.argumentList()), e.getStart()); + ArrayList argTypes = ctxt.argumentList().expression().stream() + .map(x -> TypePlaceholder.fresh(e.getStart())) + .collect(Collectors.toCollection(ArrayList::new)); + return new MethodCall(TypePlaceholder.fresh(e.getStart()), getReceiver(expr), methodName, + convert(ctxt.argumentList()), TypePlaceholder.fresh(e.getStart()), argTypes, e.getStart()); } } - + private Expression convert(Java8Parser.ArrayCreationExpressionContext expression) { throw new NotImplementedException(); } @@ -833,7 +846,10 @@ public class StatementGenerator { RefType newClass = (RefType) TypeGenerator.convertTypeName(identifier.getText(),genericArgs,identifier.getSymbol(),reg,generics); ArgumentList args = convert(newExpression.argumentList()); - return new NewClass(newClass, args, newExpression.getStart()); + ArrayList argTypes = args.getArguments().stream() + .map(x -> TypePlaceholder.fresh(newExpression.getStart())) + .collect(Collectors.toCollection(ArrayList::new)); + return new NewClass(newClass, args, null, argTypes, newExpression.getStart()); } private Expression convert(Java8Parser.LiteralContext literal) { @@ -891,7 +907,12 @@ public class StatementGenerator { } ArgumentList argumentList = convert(methodInvocationContext.argumentList()); - MethodCall ret = new MethodCall(TypePlaceholder.fresh(methodInvocationContext.getStart()), getReceiver(receiver), name, argumentList, methodInvocationContext.getStart()); + ArrayList argTypes = argumentList.getArguments().stream() + .map(x -> TypePlaceholder.fresh(methodInvocationContext.getStart())) + .collect(Collectors.toCollection(ArrayList::new)); + MethodCall ret = new MethodCall(TypePlaceholder.fresh(methodInvocationContext.getStart()), + getReceiver(receiver), name, argumentList, TypePlaceholder.fresh(methodInvocationContext.getStart()), + argTypes, methodInvocationContext.getStart()); return ret; } diff --git a/src/main/java/de/dhbwstuttgart/syntaxtree/Constructor.java b/src/main/java/de/dhbwstuttgart/syntaxtree/Constructor.java index 8be687f8..24b3bb81 100644 --- a/src/main/java/de/dhbwstuttgart/syntaxtree/Constructor.java +++ b/src/main/java/de/dhbwstuttgart/syntaxtree/Constructor.java @@ -27,7 +27,7 @@ public class Constructor extends Method { */ protected static Block prepareBlock(Block constructorBlock /*, List fieldInitializations new ArrayList<>() geloescht PL 2018-11-24 */){ List statements = constructorBlock.getStatements(); - statements.add(0, new SuperCall(constructorBlock.getOffset())); + statements.add(0, new SuperCall(null, null, constructorBlock.getOffset())); /* statements.addAll(fieldInitializations); geloescht PL 2018-11-24 */ return new Block(statements, constructorBlock.getOffset()); } diff --git a/src/main/java/de/dhbwstuttgart/syntaxtree/statement/MethodCall.java b/src/main/java/de/dhbwstuttgart/syntaxtree/statement/MethodCall.java index f6307f1e..75267619 100644 --- a/src/main/java/de/dhbwstuttgart/syntaxtree/statement/MethodCall.java +++ b/src/main/java/de/dhbwstuttgart/syntaxtree/statement/MethodCall.java @@ -21,13 +21,24 @@ public class MethodCall extends Statement { public final String name; public final Receiver receiver; + public final ArgumentList arglist; + + /* + * noetig fuer Bytecodegenerierung + */ + public RefTypeOrTPHOrWildcardOrGeneric receiverType; + public final ArrayList argTypes; + - public MethodCall(RefTypeOrTPHOrWildcardOrGeneric retType, Receiver receiver, String methodName, ArgumentList argumentList, Token offset){ + public MethodCall(RefTypeOrTPHOrWildcardOrGeneric retType, Receiver receiver, String methodName, ArgumentList argumentList, + RefTypeOrTPHOrWildcardOrGeneric receiverType, ArrayList argTypes, Token offset){ super(retType,offset); this.arglist = argumentList; this.name = methodName; this.receiver = receiver; + this.receiverType = receiverType; + this.argTypes = argTypes; } @Override diff --git a/src/main/java/de/dhbwstuttgart/syntaxtree/statement/NewClass.java b/src/main/java/de/dhbwstuttgart/syntaxtree/statement/NewClass.java index d29f3d53..f27bc3e8 100644 --- a/src/main/java/de/dhbwstuttgart/syntaxtree/statement/NewClass.java +++ b/src/main/java/de/dhbwstuttgart/syntaxtree/statement/NewClass.java @@ -29,8 +29,10 @@ public class NewClass extends MethodCall * @param args Argumente mit denen der New-Call aufgerufen wurde * @param start */ - public NewClass(RefType newClass, ArgumentList args, Token start) { - super(newClass, new ExpressionReceiver(new EmptyStmt(start)), newClass.getName().toString(), args, start); + public NewClass(RefType newClass, ArgumentList args, RefTypeOrTPHOrWildcardOrGeneric receiverType, + ArrayList argTypes, Token start) { + super(newClass, new ExpressionReceiver(new EmptyStmt(start)), newClass.getName().toString(), + args, receiverType, argTypes, start); } @Override diff --git a/src/main/java/de/dhbwstuttgart/syntaxtree/statement/SuperCall.java b/src/main/java/de/dhbwstuttgart/syntaxtree/statement/SuperCall.java index 42cfb8ee..3b7eebbf 100644 --- a/src/main/java/de/dhbwstuttgart/syntaxtree/statement/SuperCall.java +++ b/src/main/java/de/dhbwstuttgart/syntaxtree/statement/SuperCall.java @@ -2,6 +2,7 @@ package de.dhbwstuttgart.syntaxtree.statement; import de.dhbwstuttgart.syntaxtree.StatementVisitor; import de.dhbwstuttgart.syntaxtree.type.RefType; +import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric; import de.dhbwstuttgart.syntaxtree.type.Void; import org.antlr.v4.runtime.Token; @@ -12,12 +13,14 @@ import java.util.ArrayList; public class SuperCall extends MethodCall { - public SuperCall(Token offset){ - this(new ArgumentList(new ArrayList(), offset),offset); + public SuperCall(RefTypeOrTPHOrWildcardOrGeneric receiverType, + ArrayList argTypes, Token offset){ + this(new ArgumentList(new ArrayList(), offset), receiverType, argTypes, offset); } - public SuperCall(ArgumentList argumentList, Token offset){ - super(new Void(offset), new ExpressionReceiver(new This(offset)), "", argumentList, offset); + public SuperCall(ArgumentList argumentList, RefTypeOrTPHOrWildcardOrGeneric receiverType, + ArrayList argTypes, Token offset){ + super(new Void(offset), new ExpressionReceiver(new This(offset)), "", argumentList, receiverType, argTypes, offset); } diff --git a/src/main/java/de/dhbwstuttgart/syntaxtree/statement/ThisCall.java b/src/main/java/de/dhbwstuttgart/syntaxtree/statement/ThisCall.java index e82405c0..26579d2f 100644 --- a/src/main/java/de/dhbwstuttgart/syntaxtree/statement/ThisCall.java +++ b/src/main/java/de/dhbwstuttgart/syntaxtree/statement/ThisCall.java @@ -8,7 +8,7 @@ public class ThisCall extends MethodCall { public ThisCall(Receiver receiver, ArgumentList arglist, int offset) { - super(null, null, null, null, null); + super(null, null, null, null, null, null, null); } From e913bfa768e08e4edc2ddfc27542abe0abb97353 Mon Sep 17 00:00:00 2001 From: "pl@gohorb.ba-horb.de" Date: Fri, 7 Feb 2020 18:17:58 +0100 Subject: [PATCH 44/81] modified: ../../../main/java/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java modified: ../../../main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java Im Bytecode werden MethpdCaltypen bereits beim TYPEen angelegt. --- .../de/dhbwstuttgart/bytecode/BytecodeGenMethod.java | 10 ++++++---- .../dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java | 8 ++++++++ 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java b/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java index 00b1fb6e..3bdf21ea 100644 --- a/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java +++ b/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java @@ -754,7 +754,8 @@ public class BytecodeGenMethod implements StatementVisitor { public void visit(MethodCall methodCall) { boolean parentBinary = isParentBinary; System.out.println("In MethodCall = " + methodCall.name); - String receiverName = resolver.getResolvedType(methodCall.receiver.getType()); + //String receiverName = resolver.getResolvedType(methodCall.receiver.getType()); + String receiverName = resolver.getResolvedType(methodCall.receiverType); System.out.println("Methods of " + receiverName + " "); java.lang.reflect.Method methodRefl = null; String clazz = receiverName.replace("/", "."); @@ -768,7 +769,8 @@ public class BytecodeGenMethod implements StatementVisitor { ClassLoader cLoader2; String methCallType = resultSet.resolveType(methodCall.getType()).resolvedType.acceptTV(new TypeToDescriptor()); - String[] typesOfParams = getTypes(methodCall.arglist.getArguments()); + //String[] typesOfParams = getTypes(methodCall.arglist.getArguments()); + String[] typesOfParams = getTypes(methodCall.argTypes); try { clazz = getRawClassName(receiverName, clazz); @@ -918,10 +920,10 @@ public class BytecodeGenMethod implements StatementVisitor { return clazz; } - private String[] getTypes(List arguments) { + private String[] getTypes(List arguments) { String[] types = new String[arguments.size()]; for(int i = 0; i Date: Mon, 9 Mar 2020 14:06:41 +0100 Subject: [PATCH 45/81] modified: ../../../../main/java/de/dhbwstuttgart/core/JavaTXCompiler.java modified: ../../../../main/java/de/dhbwstuttgart/typeinference/constraints/ConstraintSet.java toString veraendert modified: ../../../../main/java/de/dhbwstuttgart/typeinference/unify/Match.java modified: ../../../../main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java Fall A <. theta' veraendert. modified: ../../bytecode/javFiles/MatrixOP.jav --- .../de/dhbwstuttgart/core/JavaTXCompiler.java | 9 +++--- .../constraints/ConstraintSet.java | 6 +++- .../typeinference/unify/Match.java | 1 + .../typeinference/unify/TypeUnifyTask.java | 30 +++++++++++++++---- .../resources/bytecode/javFiles/MatrixOP.jav | 2 +- 5 files changed, 36 insertions(+), 12 deletions(-) diff --git a/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java b/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java index 5f510946..4c065abb 100644 --- a/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java +++ b/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java @@ -480,15 +480,15 @@ public class JavaTXCompiler { final ConstraintSet cons = getConstraints(); Set> results = new HashSet<>(); try { - Writer logFile = new OutputStreamWriter(new NullOutputStream()); + Writer logFile = //new OutputStreamWriter(new NullOutputStream()); // new FileWriter(new // File(System.getProperty("user.dir")+"/src/test/resources/logFiles/"+"log_"+sourceFiles.keySet().iterator().next().getName())); - //new FileWriter(new File(System.getProperty("user.dir") + "/logFiles/" + "log_" - // + sourceFiles.keySet().iterator().next().getName())); + new FileWriter(new File(System.getProperty("user.dir") + "/logFiles/" + "log_" + + sourceFiles.keySet().iterator().next().getName())); IFiniteClosure finiteClosure = UnifyTypeFactory.generateFC(allClasses, logFile, classLoader); System.out.println(finiteClosure); ConstraintSet unifyCons = UnifyTypeFactory.convert(cons); - + System.out.println("xxx1"); Function distributeInnerVars = x -> { UnifyType lhs, rhs; if (((lhs = x.getLhsType()) instanceof PlaceholderType) @@ -500,6 +500,7 @@ public class JavaTXCompiler { return x; }; + logFile.write("Unify:" + unifyCons.toString()); System.out.println("Unify:" + unifyCons.toString()); unifyCons = unifyCons.map(distributeInnerVars); diff --git a/src/main/java/de/dhbwstuttgart/typeinference/constraints/ConstraintSet.java b/src/main/java/de/dhbwstuttgart/typeinference/constraints/ConstraintSet.java index 1dda8dc5..bc0ad928 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/constraints/ConstraintSet.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/constraints/ConstraintSet.java @@ -6,6 +6,7 @@ import de.dhbwstuttgart.typeinference.unify.GuavaSetOperations; import de.dhbwstuttgart.typeinference.unify.model.UnifyPair; import java.util.*; +import java.util.function.BinaryOperator; import java.util.function.Consumer; import java.util.function.Function; import java.util.stream.Collectors; @@ -29,7 +30,10 @@ public class ConstraintSet { @Override public String toString(){ - return cartesianProduct().toString(); + BinaryOperator b = (x,y) -> x+y; + return "\nUND:" + this.undConstraints.toString() + "\n" + + "ODER:" + this.oderConstraints.stream().reduce("", (x,y) -> x.toString()+ "\n" +y, b); + //cartesianProduct().toString(); } public Set>> cartesianProduct(){ diff --git a/src/main/java/de/dhbwstuttgart/typeinference/unify/Match.java b/src/main/java/de/dhbwstuttgart/typeinference/unify/Match.java index 75469f64..91406612 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/unify/Match.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/unify/Match.java @@ -22,6 +22,7 @@ import de.dhbwstuttgart.typeinference.unify.model.UnifyType; public class Match implements IMatch { @Override + //vorne muss das Pattern stehen //A =. A ==> True //A =. A ==> False public Optional match(ArrayList termsList) { diff --git a/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java b/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java index 74c71706..0362a5a0 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java @@ -28,6 +28,7 @@ import de.dhbwstuttgart.typeinference.constraints.Constraint; import de.dhbwstuttgart.typeinference.constraints.ConstraintSet; import de.dhbwstuttgart.typeinference.result.ResultSet; import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure; +import de.dhbwstuttgart.typeinference.unify.interfaces.IMatch; import de.dhbwstuttgart.typeinference.unify.interfaces.IRuleSet; import de.dhbwstuttgart.typeinference.unify.interfaces.ISetOperations; import de.dhbwstuttgart.typeinference.unify.interfaces.IUnify; @@ -172,9 +173,9 @@ public class TypeUnifyTask extends RecursiveTask>> { thNo = totalnoOfThread; writeLog("thNo2 " + thNo); try { - this.logFile = new OutputStreamWriter(new NullOutputStream()); + this.logFile = //new OutputStreamWriter(new NullOutputStream()); //new FileWriter(new File(System.getProperty("user.dir")+"/src/test/resources/logFiles/"+"Thread_"+thNo)); - //new FileWriter(new File(System.getProperty("user.dir")+"/logFiles/"+"Thread_"+thNo)); + new FileWriter(new File(System.getProperty("user.dir")+"/logFiles/"+"Thread_"+thNo)); logFile.write(""); } catch (IOException e) { @@ -2033,6 +2034,14 @@ public class TypeUnifyTask extends RecursiveTask>> { PlaceholderType a = (PlaceholderType)pair.getLhsType(); UnifyType thetaPrime = pair.getRhsType(); + if (thetaPrime instanceof ExtendsType) { + thetaPrime = ((ExtendsType)thetaPrime).getExtendedType(); + } + + if (thetaPrime instanceof SuperType) { + //HIER MUSS NOCH WAS UEBERLEGT WERDEN + } + Set> result = new HashSet<>(); boolean allGen = thetaPrime.getTypeParams().size() > 0; @@ -2064,13 +2073,18 @@ public class TypeUnifyTask extends RecursiveTask>> { return x.accept(new freshPlaceholder(), hm); }).collect(Collectors.toCollection(HashSet::new)); - + IMatch match = new Match(); for(UnifyType c : csPHRenamed) { //PL 18-02-05 getChildren durch smaller ersetzt in getChildren werden die Varianlen nicht ersetzt. Set thetaQs = new HashSet<>(); //TODO smaller wieder reinnehmen? //thetaQs.add(c);// thetaQs = fc.smaller(c, new HashSet<>()).stream().collect(Collectors.toCollection(HashSet::new)); + ArrayList ml = new ArrayList<>(); + ml.add(new UnifyPair(c, thetaPrime, PairOperator.EQUALSDOT)); + if (!(match.match(ml)).isPresent()) { + thetaQs.remove(c); + } //Set thetaQs = fc.getChildren(c).stream().collect(Collectors.toCollection(HashSet::new)); //thetaQs.add(thetaPrime); //PL 18-02-05 wieder geloescht //PL 2017-10-03: War auskommentiert habe ich wieder einkommentiert, @@ -2078,7 +2092,7 @@ public class TypeUnifyTask extends RecursiveTask>> { //PL 18-02-06: eingefuegt, thetaQs der Form V> <. V'> werden entfernt //TODO PL 19-01-14 wieder reinnehmen kurzfristig auskommentiert - thetaQs = thetaQs.stream().filter(ut -> ut.getTypeParams().arePlaceholders()).collect(Collectors.toCollection(HashSet::new)); + //thetaQs = thetaQs.stream().filter(ut -> ut.getTypeParams().arePlaceholders()).collect(Collectors.toCollection(HashSet::new)); //PL 18-02-06: eingefuegt Set thetaQPrimes = new HashSet<>(); @@ -2095,7 +2109,7 @@ public class TypeUnifyTask extends RecursiveTask>> { thetaQPrimes.add(c.setTypeParams(tp)); } - for(UnifyType tqp : thetaQPrimes) { + for(UnifyType tqp : thetaQPrimes) {//PL 2020-03-08 umbauen in der Schleife wird nur unifizierbarer Typ gesucht break am Ende Collection tphs = tqp.getInvolvedPlaceholderTypes(); Optional opt = stdUnify.unify(tqp, thetaPrime); if (!opt.isPresent()) { @@ -2114,7 +2128,10 @@ public class TypeUnifyTask extends RecursiveTask>> { } //List freshTphs = new ArrayList<>(); PL 18-02-06 in die For-Schleife verschoben for (UnifyType tq : thetaQs) { - Set smaller = fc.smaller(unifier.apply(tq), new HashSet<>()); + //geaendert PL 20-03-07 + Set smaller = new HashSet<>(); + smaller.add(unifier.apply(tq)); + //Set smaller = fc.smaller(unifier.apply(tq), new HashSet<>()); //eingefuegt PL 2018-03-29 Anfang ? ext. theta hinzufuegen if (a.isWildcardable()) { Set smaller_ext = smaller.stream().filter(x -> !(x instanceof ExtendsType) && !(x instanceof SuperType)) @@ -2161,6 +2178,7 @@ public class TypeUnifyTask extends RecursiveTask>> { //writeLog("MAX: " + oup.max(resultPrime.iterator()).toString()); } } + break;//Wenn ein unifier gefunden ist reicht es aus PL 2020-03-07 } } diff --git a/src/test/resources/bytecode/javFiles/MatrixOP.jav b/src/test/resources/bytecode/javFiles/MatrixOP.jav index 21d37347..52c3fe96 100644 --- a/src/test/resources/bytecode/javFiles/MatrixOP.jav +++ b/src/test/resources/bytecode/javFiles/MatrixOP.jav @@ -1,6 +1,6 @@ import java.util.Vector; import java.lang.Integer; -//import java.lang.Byte; +import java.lang.Byte; import java.lang.Boolean; public class MatrixOP extends Vector> { From d63c27579c75f3e37cd81289c42c68d39669cc46 Mon Sep 17 00:00:00 2001 From: "pl@gohorb.ba-horb.de" Date: Mon, 9 Mar 2020 18:30:36 +0100 Subject: [PATCH 46/81] modified: ../../../../main/java/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java Typen der Methoden der Oder-Constraiunts benutzen wieder rueckgaenig gemacht modified: ../../../../main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java wieder alle grArg im a <. theta' benutzen modified: ../../bytecode/javFiles/MatrixOP.jav --- .../de/dhbwstuttgart/bytecode/BytecodeGenMethod.java | 12 +++++------- .../typeinference/unify/TypeUnifyTask.java | 2 -- src/test/resources/bytecode/javFiles/MatrixOP.jav | 2 +- 3 files changed, 6 insertions(+), 10 deletions(-) diff --git a/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java b/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java index 3bdf21ea..0565d933 100644 --- a/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java +++ b/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java @@ -754,8 +754,7 @@ public class BytecodeGenMethod implements StatementVisitor { public void visit(MethodCall methodCall) { boolean parentBinary = isParentBinary; System.out.println("In MethodCall = " + methodCall.name); - //String receiverName = resolver.getResolvedType(methodCall.receiver.getType()); - String receiverName = resolver.getResolvedType(methodCall.receiverType); + String receiverName = resolver.getResolvedType(methodCall.receiver.getType()); System.out.println("Methods of " + receiverName + " "); java.lang.reflect.Method methodRefl = null; String clazz = receiverName.replace("/", "."); @@ -769,8 +768,7 @@ public class BytecodeGenMethod implements StatementVisitor { ClassLoader cLoader2; String methCallType = resultSet.resolveType(methodCall.getType()).resolvedType.acceptTV(new TypeToDescriptor()); - //String[] typesOfParams = getTypes(methodCall.arglist.getArguments()); - String[] typesOfParams = getTypes(methodCall.argTypes); + String[] typesOfParams = getTypes(methodCall.arglist.getArguments()); try { clazz = getRawClassName(receiverName, clazz); @@ -919,11 +917,11 @@ public class BytecodeGenMethod implements StatementVisitor { } return clazz; } - - private String[] getTypes(List arguments) { + + private String[] getTypes(List arguments) { String[] types = new String[arguments.size()]; for(int i = 0; i>> { //writeLog("MAX: " + oup.max(resultPrime.iterator()).toString()); } } - break;//Wenn ein unifier gefunden ist reicht es aus PL 2020-03-07 - } } diff --git a/src/test/resources/bytecode/javFiles/MatrixOP.jav b/src/test/resources/bytecode/javFiles/MatrixOP.jav index 52c3fe96..21d37347 100644 --- a/src/test/resources/bytecode/javFiles/MatrixOP.jav +++ b/src/test/resources/bytecode/javFiles/MatrixOP.jav @@ -1,6 +1,6 @@ import java.util.Vector; import java.lang.Integer; -import java.lang.Byte; +//import java.lang.Byte; import java.lang.Boolean; public class MatrixOP extends Vector> { From aa94ce8ad9256c37e87074f2ac4afef4d7ae20e4 Mon Sep 17 00:00:00 2001 From: "pl@gohorb.ba-horb.de" Date: Thu, 12 Mar 2020 10:18:48 +0100 Subject: [PATCH 47/81] modified: src/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java modified: src/main/java/de/dhbwstuttgart/typeinference/unify/model/OrderingUnifyPair.java Fehler korrigiert in compare --- .../typeinference/typeAlgo/TYPEStmt.java | 4 +-- .../unify/model/OrderingUnifyPair.java | 27 ++++++++++--------- 2 files changed, 16 insertions(+), 15 deletions(-) diff --git a/src/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java b/src/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java index c8437abd..bd054a7c 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java @@ -576,7 +576,7 @@ public class TYPEStmt implements StatementVisitor{ methodConstraint.add(new Pair(forMethod.receiver.getType(), retType, PairOperator.SMALLERDOT)); - //Fuer Bytecodegenerierung + //Fuer Bytecodegenerierung PL 2020-03-09 wird derzeit nicht benutzt methodConstraint.add(new Pair(forMethod.receiverType, retType, PairOperator.EQUALSDOT)); @@ -595,7 +595,7 @@ public class TYPEStmt implements StatementVisitor{ RefTypeOrTPHOrWildcardOrGeneric assType = assumption.getArgTypes(resolver).get(i); ret.add(new Pair(argType, assType, PairOperator.SMALLERDOT)); - //Fuer Bytecodegenerierung + //Fuer Bytecodegenerierung PL 2020-03-09 wird derzeit nicht benutzt ret.add(new Pair(foMethod.argTypes.get(i), assType, PairOperator.EQUALSDOT)); } return ret; diff --git a/src/main/java/de/dhbwstuttgart/typeinference/unify/model/OrderingUnifyPair.java b/src/main/java/de/dhbwstuttgart/typeinference/unify/model/OrderingUnifyPair.java index 736186d5..c342269b 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/unify/model/OrderingUnifyPair.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/unify/model/OrderingUnifyPair.java @@ -293,24 +293,25 @@ public class OrderingUnifyPair extends Ordering> { } else { if (leftlewc.size() > 0) { Set subst; - if (leftlewc.iterator().next().getLhsType() instanceof PlaceholderType) { - subst = leftlewc.stream().map(x -> new UnifyPair(x.getLhsType(), x.getRhsType(), PairOperator.EQUALSDOT)).collect(Collectors.toCollection(HashSet::new)); - } - else { - subst = leftlewc.stream().map(x -> new UnifyPair(x.getRhsType(), x.getLhsType(), PairOperator.EQUALSDOT)).collect(Collectors.toCollection(HashSet::new)); - } + subst = leftlewc.stream().map(x -> { + if (x.getLhsType() instanceof PlaceholderType) { + return new UnifyPair(x.getLhsType(), x.getRhsType(), PairOperator.EQUALSDOT); + } + else { + return new UnifyPair(x.getRhsType(), x.getLhsType(), PairOperator.EQUALSDOT); + }}).collect(Collectors.toCollection(HashSet::new)); Unifier uni = new Unifier(); - subst.stream().forEach(x -> uni.add((PlaceholderType) x.getLhsType(), x.getRhsType())); lseq = uni.apply(lseq); } else { Set subst; - if (rightlewc.iterator().next().getLhsType() instanceof PlaceholderType) { - subst = rightlewc.stream().map(x -> new UnifyPair(x.getLhsType(), x.getRhsType(), PairOperator.EQUALSDOT)).collect(Collectors.toCollection(HashSet::new)); - } - else { - subst = rightlewc.stream().map(x -> new UnifyPair(x.getRhsType(), x.getLhsType(), PairOperator.EQUALSDOT)).collect(Collectors.toCollection(HashSet::new)); - } + subst = rightlewc.stream().map(x -> { + if (x.getLhsType() instanceof PlaceholderType) { + return new UnifyPair(x.getLhsType(), x.getRhsType(), PairOperator.EQUALSDOT); + } + else { + return new UnifyPair(x.getRhsType(), x.getLhsType(), PairOperator.EQUALSDOT); + }}).collect(Collectors.toCollection(HashSet::new)); Unifier uni = new Unifier(); subst.stream().forEach(x -> uni.add((PlaceholderType) x.getLhsType(), x.getRhsType())); rseq = uni.apply(rseq); From 44368f2a2a347ed5f8963b8df32a036e94f798a8 Mon Sep 17 00:00:00 2001 From: "pl@gohorb.ba-horb.de" Date: Fri, 13 Mar 2020 14:04:57 +0100 Subject: [PATCH 48/81] modified: ../src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java modified: ../src/main/java/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java weitere Logausgaben bei a <. theta' --- .../dhbwstuttgart/typeinference/unify/TypeUnifyTask.java | 8 +++++--- .../typeinference/unify/model/FiniteClosure.java | 8 ++++++-- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java b/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java index 3c89ea38..79b73ba3 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java @@ -731,6 +731,7 @@ public class TypeUnifyTask extends RecursiveTask>> { } else if (variance == -1) { a = oup.min(nextSetasList.iterator()); + writeLog("Min: a in " + variance + " "+ a); nextSetasList.remove(a); nextSetasListRest = new ArrayList<>(nextSetasList); Iterator> nextSetasListItRest = new ArrayList>(nextSetasListRest).iterator(); @@ -2059,7 +2060,7 @@ public class TypeUnifyTask extends RecursiveTask>> { //} Set cs = fc.getAllTypesByName(thetaPrime.getName());//cs= [java.util.Vector, java.util.Vector>, ????java.util.Vector???] - + writeLog("cs: " + cs.toString()); //PL 18-02-06 entfernt, kommt durch unify wieder rein //cs.add(thetaPrime); //PL 18-02-06 entfernt @@ -2085,6 +2086,7 @@ public class TypeUnifyTask extends RecursiveTask>> { if (!(match.match(ml)).isPresent()) { thetaQs.remove(c); } + writeLog("thetaQs von " + c + ": " + thetaQs.toString()); //Set thetaQs = fc.getChildren(c).stream().collect(Collectors.toCollection(HashSet::new)); //thetaQs.add(thetaPrime); //PL 18-02-05 wieder geloescht //PL 2017-10-03: War auskommentiert habe ich wieder einkommentiert, @@ -2108,7 +2110,7 @@ public class TypeUnifyTask extends RecursiveTask>> { for(TypeParams tp : permuteParams(candidateParams)) thetaQPrimes.add(c.setTypeParams(tp)); } - + writeLog("thetaQPrimes von " + c + ": " + thetaQPrimes.toString()); for(UnifyType tqp : thetaQPrimes) {//PL 2020-03-08 umbauen in der Schleife wird nur unifizierbarer Typ gesucht break am Ende Collection tphs = tqp.getInvolvedPlaceholderTypes(); Optional opt = stdUnify.unify(tqp, thetaPrime); @@ -2180,7 +2182,7 @@ public class TypeUnifyTask extends RecursiveTask>> { } } } - + writeLog("result von " + pair + ": " + result.toString()); return result; } diff --git a/src/main/java/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java b/src/main/java/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java index 95c90377..8ee39d7f 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java @@ -711,13 +711,15 @@ implements IFiniteClosure { HashSet hs = new HashSet<>(); hs.add(up); Set smallerRes = unifyTask.applyTypeUnificationRules(hs, this); - if (left.getName().equals("Matrix") || right.getName().equals("Matrix")) + /* + //if (left.getName().equals("Matrix") || right.getName().equals("Matrix")) {try { logFile.write("\nsmallerRes: " + smallerRes);//"smallerHash: " + greaterHash.toString()); logFile.flush(); } catch (IOException e) { System.err.println("no LogFile");}} + */ //Gleichungen der Form a <./=. Theta oder Theta <./=. a oder a <./=. b sind ok. Predicate delFun = x -> !((x.getLhsType() instanceof PlaceholderType || x.getRhsType() instanceof PlaceholderType) @@ -732,13 +734,15 @@ implements IFiniteClosure { hs = new HashSet<>(); hs.add(up); Set greaterRes = unifyTask.applyTypeUnificationRules(hs, this); - if (left.getName().equals("Matrix") || right.getName().equals("Matrix")) + /* + //if (left.getName().equals("Matrix") || right.getName().equals("Matrix")) {try { logFile.write("\ngreaterRes: " + greaterRes);//"smallerHash: " + greaterHash.toString()); logFile.flush(); } catch (IOException e) { System.err.println("no LogFile");}} + */ //Gleichungen der Form a <./=. Theta oder Theta <./=. a oder a <./=. b sind ok. long greaterLen = greaterRes.stream().filter(delFun).count(); if (greaterLen == 0) return 1; From 21bc3e519399bfab26225d08fd542faadc5975b3 Mon Sep 17 00:00:00 2001 From: "pl@gohorb.ba-horb.de" Date: Fri, 13 Mar 2020 15:57:27 +0100 Subject: [PATCH 49/81] modified: ../../../../main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java Reigenfolge der der nextSets angepasst --- .../typeinference/unify/TypeUnifyTask.java | 30 ++++++++++++++++--- 1 file changed, 26 insertions(+), 4 deletions(-) diff --git a/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java b/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java index 79b73ba3..56e0eca2 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java @@ -1765,6 +1765,7 @@ public class TypeUnifyTask extends RecursiveTask>> { * (as in case 1 where sigma is added to the innermost set). */ protected Set>>> calculatePairSets(Set eq2s, List>> oderConstraintsInput, IFiniteClosure fc, Set undefined, List>> oderConstraintsOutput) { + writeLog("eq2s: " + eq2s.toString()); oderConstraintsOutput.addAll(oderConstraintsInput); List>>> result = new ArrayList<>(9); @@ -1774,17 +1775,30 @@ public class TypeUnifyTask extends RecursiveTask>> { ArrayList eq2sprime = new ArrayList<>(eq2s); Iterator eq2sprimeit = eq2sprime.iterator(); + ArrayList eq2sAsListFst = new ArrayList<>(); + ArrayList eq2sAsListSnd = new ArrayList<>(); + ArrayList eq2sAsListBack = new ArrayList<>(); ArrayList eq2sAsList = new ArrayList<>(); Boolean first = true; while(eq2sprimeit.hasNext()) {// alle mit Variance != 0 nach vorne schieben UnifyPair up = eq2sprimeit.next(); - if ((up.getLhsType() instanceof PlaceholderType && ((PlaceholderType)up.getLhsType()).getVariance() != 0) - || (up.getRhsType() instanceof PlaceholderType && ((PlaceholderType)up.getRhsType()).getVariance() != 0)) { - eq2sAsList.add(up); + if ((up.getLhsType() instanceof PlaceholderType && ((PlaceholderType)up.getLhsType()).getVariance() != 0 && !((PlaceholderType)up.getLhsType()).isInnerType()) + || (up.getRhsType() instanceof PlaceholderType && ((PlaceholderType)up.getRhsType()).getVariance() != 0) && !((PlaceholderType)up.getRhsType()).isInnerType()) { + eq2sAsListFst.add(up); + eq2s.remove(up); + } + else if ((up.getLhsType() instanceof PlaceholderType && ((PlaceholderType)up.getLhsType()).getVariance() != 0 && ((PlaceholderType)up.getLhsType()).isInnerType()) + || (up.getRhsType() instanceof PlaceholderType && ((PlaceholderType)up.getRhsType()).getVariance() != 0) && ((PlaceholderType)up.getRhsType()).isInnerType()) { + eq2sAsListSnd.add(up); + eq2s.remove(up); + } + else if ((up.getLhsType() instanceof PlaceholderType && ((PlaceholderType)up.getLhsType()).isInnerType()) + || (up.getRhsType() instanceof PlaceholderType && ((PlaceholderType)up.getRhsType()).isInnerType())) { + eq2sAsListBack.add(up); eq2s.remove(up); } } - if (eq2sAsList.isEmpty()) { + if (eq2sAsListFst.isEmpty()) { List>> oderConstraintsVariance = oderConstraintsOutput.stream() //Alle Elemente rauswerfen, die Variance 0 haben oder keine TPH in LHS oder RHS sind .filter(x -> x.stream() .filter(y -> @@ -1805,7 +1819,15 @@ public class TypeUnifyTask extends RecursiveTask>> { } } + writeLog("eq2s: " + eq2s.toString()); + writeLog("eq2sAsListFst: " + eq2sAsListFst.toString()); + writeLog("eq2sAsListSnd: " + eq2sAsListSnd.toString()); + writeLog("eq2sAsListBack: " + eq2sAsListBack.toString()); + + eq2sAsList.addAll(eq2sAsListFst); + eq2sAsList.addAll(eq2sAsListSnd); eq2sAsList.addAll(eq2s); + eq2sAsList.addAll(eq2sAsListBack); if (eq2sAsList.isEmpty() && first) {//Alle eq2s sind empty und alle oderConstraints mit Variance != 0 sind bearbeitet if (!oderConstraintsOutput.isEmpty()) { From e4e3704c7ba8f21b4865ad7cfe60b72bedd4d64d Mon Sep 17 00:00:00 2001 From: "pl@gohorb.ba-horb.de" Date: Tue, 17 Mar 2020 14:06:21 +0100 Subject: [PATCH 50/81] modified: src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java Umbau TYPEStmt Methods begonnen --- .../de/dhbwstuttgart/core/JavaTXCompiler.java | 116 +++++++++++++++++- 1 file changed, 112 insertions(+), 4 deletions(-) diff --git a/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java b/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java index 4c065abb..458585e1 100644 --- a/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java +++ b/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java @@ -8,17 +8,31 @@ import de.dhbwstuttgart.bytecode.genericsGenerator.GeneratedGenericsFinder; import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.GenericGenratorResultForSourceFile; import de.dhbwstuttgart.environment.CompilationEnvironment; import de.dhbwstuttgart.environment.DirectoryClassLoader; +import de.dhbwstuttgart.exceptions.DebugException; import de.dhbwstuttgart.parser.JavaTXParser; +import de.dhbwstuttgart.parser.NullToken; import de.dhbwstuttgart.parser.scope.GenericsRegistry; import de.dhbwstuttgart.parser.SyntaxTreeGenerator.SyntaxTreeGenerator; import de.dhbwstuttgart.parser.antlr.Java8Parser.CompilationUnitContext; import de.dhbwstuttgart.parser.scope.JavaClassName; import de.dhbwstuttgart.syntaxtree.ClassOrInterface; +import de.dhbwstuttgart.syntaxtree.GenericTypeVar; +import de.dhbwstuttgart.syntaxtree.Method; +import de.dhbwstuttgart.syntaxtree.ParameterList; import de.dhbwstuttgart.syntaxtree.SourceFile; import de.dhbwstuttgart.syntaxtree.TypeScope; +import de.dhbwstuttgart.syntaxtree.FormalParameter; +import de.dhbwstuttgart.syntaxtree.GenericDeclarationList; import de.dhbwstuttgart.syntaxtree.factory.ASTFactory; import de.dhbwstuttgart.syntaxtree.factory.UnifyTypeFactory; +import de.dhbwstuttgart.syntaxtree.statement.Block; +import de.dhbwstuttgart.syntaxtree.type.ExtendsWildcardType; +import de.dhbwstuttgart.syntaxtree.type.GenericRefType; +import de.dhbwstuttgart.syntaxtree.type.RefType; +import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric; +import de.dhbwstuttgart.syntaxtree.type.SuperWildcardType; import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder; +import de.dhbwstuttgart.syntaxtree.type.TypeVisitor; import de.dhbwstuttgart.syntaxtree.visual.ASTTypePrinter; import de.dhbwstuttgart.typeinference.constraints.Constraint; import de.dhbwstuttgart.typeinference.constraints.ConstraintSet; @@ -50,6 +64,8 @@ import java.net.URLClassLoader; import java.util.*; import java.util.function.Function; import java.util.stream.Collectors; + +import org.antlr.v4.runtime.Token; import org.apache.commons.io.output.NullOutputStream; @@ -93,10 +109,6 @@ public class JavaTXCompiler { public ConstraintSet getConstraints() throws ClassNotFoundException, IOException { List allClasses = new ArrayList<>();//environment.getAllAvailableClasses(); - for (File f : this.sourceFiles.keySet()) { - SourceFile sf = sourceFiles.get(f); - allClasses.addAll(sf.getClasses()); - } List importedClasses = new ArrayList<>(); //Alle Importierten Klassen in allen geparsten Sourcefiles kommen ins FC for (File forSourceFile : sourceFiles.keySet()){ @@ -111,6 +123,54 @@ public class JavaTXCompiler { importedClasses.add(importedClass); } } + for (File f : this.sourceFiles.keySet()) { + SourceFile sf = sourceFiles.get(f); + sf.KlassenVektor.forEach(cl -> { + ClassOrInterface superclass = null; + Optional optSuperclass = + importedClasses.stream().filter(x -> x.getClassName().equals( + cl.getSuperClass().getName())).findFirst(); + if (optSuperclass.isPresent()) { + superclass = optSuperclass.get(); + } + else { + //throw new ClassNotFoundException(""); + } + Iterator paraIt= cl.getSuperClass().getParaList().iterator(); + Iterator tvarVarIt = superclass.getGenerics().iterator(); + + HashMap gtvs = new HashMap<>(); + while (paraIt.hasNext()) { + gtvs.put(tvarVarIt.next().getName(), paraIt.next()); + } + Iterator methodIt = superclass.getMethods().iterator(); + while(methodIt.hasNext()) { + Method m = methodIt.next(); + ParameterList newParaList = new ParameterList( + m.getParameterList() + .getFormalparalist() + .stream() + .map(fp -> new FormalParameter(fp.getName(), fp.getType().acceptTV(new TypeExchanger(gtvs)), fp.getOffset())) + .collect(Collectors.toCollection(ArrayList::new)), m.getParameterList().getOffset()); + /* + Iterator genericsIt = m.getGenerics().iterator(); + List newGenericsList = new ArrayList<>(); + Set keys = gtvs.keySet(); + while (genericsIt.hasNext()) { + GenericTypeVar gtv = genericsIt.next(); + if (!keys.contains(gtv.getName())) { + newGenericsList.add(gtv); + } + } + */ + cl.getMethods().add(new Method(m.modifier, m.name, m.getReturnType().acceptTV(new TypeExchanger(gtvs)), newParaList, m.block, + //new GenericDeclarationList(newGenericsList, ((GenericDeclarationList)m.getGenerics()).getOffset()), + (GenericDeclarationList)m.getGenerics(), + m.getOffset())); + } + }); + allClasses.addAll(sf.getClasses()); + } allClasses.addAll(importedClasses); return new TYPE(sourceFiles.values(), allClasses).getConstraints(); } @@ -862,5 +922,53 @@ public class JavaTXCompiler { System.out.println(name + ".class file generated"); } } + + /* PL 2020-03-17 mit TypeExchanger in FCGenerator.java zusammenfuehren */ + /** + * Tauscht die GTVs in einem Typ gegen die entsprechenden Typen in der übergebenen Map aus. + */ + private static class TypeExchanger implements TypeVisitor{ + + private final HashMap gtvs; + + TypeExchanger(HashMap gtvs){ + this.gtvs = gtvs; + } + + @Override + public RefTypeOrTPHOrWildcardOrGeneric visit(RefType refType) { + List params = new ArrayList<>(); + for(RefTypeOrTPHOrWildcardOrGeneric param : refType.getParaList()){ + params.add(param.acceptTV(this)); + } + RefTypeOrTPHOrWildcardOrGeneric ret = new RefType(refType.getName(), params, new NullToken()); + return ret; + } + + @Override + public RefTypeOrTPHOrWildcardOrGeneric visit(SuperWildcardType superWildcardType) { + SuperWildcardType ret = new SuperWildcardType(superWildcardType.getInnerType().acceptTV(this), superWildcardType.getOffset()); + return ret; + } + + @Override + public RefTypeOrTPHOrWildcardOrGeneric visit(TypePlaceholder typePlaceholder) { + throw new DebugException("Dieser Fall darf nicht auftreten"); + } + + @Override + public RefTypeOrTPHOrWildcardOrGeneric visit(ExtendsWildcardType extendsWildcardType) { + ExtendsWildcardType ret = new ExtendsWildcardType(extendsWildcardType.getInnerType().acceptTV(this), extendsWildcardType.getOffset()); + return ret; + } + + @Override + public RefTypeOrTPHOrWildcardOrGeneric visit(GenericRefType genericRefType) { + if(! gtvs.containsKey(genericRefType.getParsedName())) + throw new DebugException("Dieser Fall darf nicht auftreten"); + return gtvs.get(genericRefType.getParsedName()); + } + + } } From 592de5310e631861e5195777b88417e0f6f69f79 Mon Sep 17 00:00:00 2001 From: "pl@gohorb.ba-horb.de" Date: Wed, 18 Mar 2020 17:36:10 +0100 Subject: [PATCH 51/81] modified: ../src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java modified: ../src/main/java/de/dhbwstuttgart/syntaxtree/ClassOrInterface.java modified: ../src/main/java/de/dhbwstuttgart/syntaxtree/SourceFile.java modified: ../src/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java modified: ../src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java modified: ../src/main/java/de/dhbwstuttgart/typeinference/unify/model/UnifyPair.java --- .../de/dhbwstuttgart/core/JavaTXCompiler.java | 41 +++++++++++-------- .../syntaxtree/ClassOrInterface.java | 18 ++++++++ .../dhbwstuttgart/syntaxtree/SourceFile.java | 7 ++++ .../typeinference/typeAlgo/TYPEStmt.java | 14 ++++--- .../typeinference/unify/TypeUnifyTask.java | 10 ++++- .../typeinference/unify/model/UnifyPair.java | 2 + 6 files changed, 66 insertions(+), 26 deletions(-) diff --git a/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java b/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java index 458585e1..157c6b82 100644 --- a/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java +++ b/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java @@ -110,6 +110,8 @@ public class JavaTXCompiler { public ConstraintSet getConstraints() throws ClassNotFoundException, IOException { List allClasses = new ArrayList<>();//environment.getAllAvailableClasses(); List importedClasses = new ArrayList<>(); + ClassOrInterface objectClass = ASTFactory.createClass( + classLoader.loadClass(new JavaClassName("java.lang.Object").toString())); //Alle Importierten Klassen in allen geparsten Sourcefiles kommen ins FC for (File forSourceFile : sourceFiles.keySet()){ for (JavaClassName name : sourceFiles.get(forSourceFile).getImports()) { @@ -125,16 +127,29 @@ public class JavaTXCompiler { } for (File f : this.sourceFiles.keySet()) { SourceFile sf = sourceFiles.get(f); + sf = new SourceFile(sf.getPkgName(), + sf.KlassenVektor.stream() + .map(cl -> new ClassOrInterface(cl)) + .collect(Collectors.toCollection(ArrayList::new)), + sf.imports); + //sf enthaelt neues Source-File, neue Klassen-Objekte und neue + //ArrayListen-Objekte fuer Fields, Construktoren und Methoden + //Alle anderen Objekte werden nur kopiert. sf.KlassenVektor.forEach(cl -> { ClassOrInterface superclass = null; - Optional optSuperclass = - importedClasses.stream().filter(x -> x.getClassName().equals( - cl.getSuperClass().getName())).findFirst(); - if (optSuperclass.isPresent()) { - superclass = optSuperclass.get(); - } + if (cl.getSuperClass().getName().equals(new JavaClassName("java.lang.Object"))) { + superclass = objectClass; + } else { - //throw new ClassNotFoundException(""); + Optional optSuperclass = + importedClasses.stream().filter(x -> x.getClassName().equals( + cl.getSuperClass().getName())).findFirst(); + if (optSuperclass.isPresent()) { + superclass = optSuperclass.get(); + } + else { + //throw new ClassNotFoundException(""); + } } Iterator paraIt= cl.getSuperClass().getParaList().iterator(); Iterator tvarVarIt = superclass.getGenerics().iterator(); @@ -152,22 +167,12 @@ public class JavaTXCompiler { .stream() .map(fp -> new FormalParameter(fp.getName(), fp.getType().acceptTV(new TypeExchanger(gtvs)), fp.getOffset())) .collect(Collectors.toCollection(ArrayList::new)), m.getParameterList().getOffset()); - /* - Iterator genericsIt = m.getGenerics().iterator(); - List newGenericsList = new ArrayList<>(); - Set keys = gtvs.keySet(); - while (genericsIt.hasNext()) { - GenericTypeVar gtv = genericsIt.next(); - if (!keys.contains(gtv.getName())) { - newGenericsList.add(gtv); - } - } - */ cl.getMethods().add(new Method(m.modifier, m.name, m.getReturnType().acceptTV(new TypeExchanger(gtvs)), newParaList, m.block, //new GenericDeclarationList(newGenericsList, ((GenericDeclarationList)m.getGenerics()).getOffset()), (GenericDeclarationList)m.getGenerics(), m.getOffset())); } + }); allClasses.addAll(sf.getClasses()); } diff --git a/src/main/java/de/dhbwstuttgart/syntaxtree/ClassOrInterface.java b/src/main/java/de/dhbwstuttgart/syntaxtree/ClassOrInterface.java index bbd184f0..87f11980 100644 --- a/src/main/java/de/dhbwstuttgart/syntaxtree/ClassOrInterface.java +++ b/src/main/java/de/dhbwstuttgart/syntaxtree/ClassOrInterface.java @@ -34,6 +34,7 @@ public class ClassOrInterface extends SyntaxTreeNode implements TypeScope{ private List implementedInterfaces; private List constructors; + public ClassOrInterface(int modifiers, JavaClassName name, List fielddecl, Optional fieldInitializations, List methods, List constructors, GenericDeclarationList genericClassParameters, RefType superClass, Boolean isInterface, List implementedInterfaces, Token offset){ super(offset); @@ -50,6 +51,23 @@ public class ClassOrInterface extends SyntaxTreeNode implements TypeScope{ this.constructors = constructors; } + /* erzeugt fuer Fields, Konstruktoren und Methoden neue ArrayList-Objekte + * alle anderen Datenobjekte werden nur kopiert. + */ + public ClassOrInterface(ClassOrInterface cl){ + super(cl.getOffset()); + this.modifiers = cl.modifiers; + this.name = cl.name; + this.fields = new ArrayList<>(cl.fields); + this.fieldInitializations= cl.fieldInitializations; + this.genericClassParameters = cl.genericClassParameters; + this.superClass = cl.superClass; + this.isInterface = cl.isInterface; + this.implementedInterfaces = cl.implementedInterfaces; + this.methods = new ArrayList<>(cl.methods); + this.constructors = new ArrayList<>(cl.constructors); + } + // Gets class name public JavaClassName getClassName(){ return this.name; diff --git a/src/main/java/de/dhbwstuttgart/syntaxtree/SourceFile.java b/src/main/java/de/dhbwstuttgart/syntaxtree/SourceFile.java index 945ee5d8..4a22147b 100644 --- a/src/main/java/de/dhbwstuttgart/syntaxtree/SourceFile.java +++ b/src/main/java/de/dhbwstuttgart/syntaxtree/SourceFile.java @@ -26,6 +26,13 @@ public class SourceFile extends SyntaxTreeNode{ this.imports = imports; } + public SourceFile(SourceFile sf) { + super(new NullToken()); + this.KlassenVektor = new ArrayList<>(sf.KlassenVektor); + this.imports = new HashSet<>(sf.imports); + } + + public String getPkgName(){ return this.pkgName; } diff --git a/src/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java b/src/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java index bd054a7c..684077e4 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java @@ -574,11 +574,12 @@ public class TYPEStmt implements StatementVisitor{ RefTypeOrTPHOrWildcardOrGeneric retType = assumption.getReceiverType(resolver); methodConstraint.add(new Pair(forMethod.receiver.getType(), retType, - PairOperator.SMALLERDOT)); + PairOperator.EQUALSDOT));//PL 2020-03-17 SMALLERDOT in EQUALSDOT umgewandelt, weil alle geerbten Methoden in den jeweilen Klassen enthalten sind. - //Fuer Bytecodegenerierung PL 2020-03-09 wird derzeit nicht benutzt - methodConstraint.add(new Pair(forMethod.receiverType, retType, - PairOperator.EQUALSDOT)); + //Fuer Bytecodegenerierung PL 2020-03-09 wird derzeit nicht benutzt ANFANG + //methodConstraint.add(new Pair(forMethod.receiverType, retType, + // PairOperator.EQUALSDOT)); + //Fuer Bytecodegenerierung PL 2020-03-09 wird derzeit nicht benutzt ENDE methodConstraint.add(new Pair(assumption.getReturnType(resolver), forMethod.getType(), PairOperator.EQUALSDOT)); @@ -595,8 +596,9 @@ public class TYPEStmt implements StatementVisitor{ RefTypeOrTPHOrWildcardOrGeneric assType = assumption.getArgTypes(resolver).get(i); ret.add(new Pair(argType, assType, PairOperator.SMALLERDOT)); - //Fuer Bytecodegenerierung PL 2020-03-09 wird derzeit nicht benutzt - ret.add(new Pair(foMethod.argTypes.get(i), assType, PairOperator.EQUALSDOT)); + //Fuer Bytecodegenerierung PL 2020-03-09 wird derzeit nicht benutzt ANFANG + // ret.add(new Pair(foMethod.argTypes.get(i), assType, PairOperator.EQUALSDOT)); + //Fuer Bytecodegenerierung PL 2020-03-09 wird derzeit nicht benutzt ENDE } return ret; } diff --git a/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java b/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java index 56e0eca2..76db7a2a 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java @@ -1813,7 +1813,10 @@ public class TypeUnifyTask extends RecursiveTask>> { oderConstraintsOutput.remove(ret); //Set retFlat = new HashSet<>(); //ret.stream().forEach(x -> retFlat.addAll(x)); - ret.stream().forEach(x -> x.stream().forEach(y -> y.addSubstitutions(x))); + ret.stream().forEach(x -> x.stream().forEach(y -> { Set x_new = new HashSet<>(x); //PL 2020-03-18: y selbst darf nicht in die Substitutionen + x_new.remove(y); + y.addSubstitutions(x_new); + })); result.get(8).add(ret); first = false; } @@ -1836,7 +1839,10 @@ public class TypeUnifyTask extends RecursiveTask>> { // System.out.println("M"); //Set retFlat = new HashSet<>(); //ret.stream().forEach(x -> retFlat.addAll(x)); - ret.stream().forEach(x -> x.stream().forEach(y -> y.addSubstitutions(x))); + ret.stream().forEach(x -> x.stream().forEach(y -> { Set x_new = new HashSet<>(x); //PL 2020-03-18: y selbst darf nicht in die Substitutionen + x_new.remove(y); + y.addSubstitutions(x_new); + })); result.get(8).add(ret); first = false; } diff --git a/src/main/java/de/dhbwstuttgart/typeinference/unify/model/UnifyPair.java b/src/main/java/de/dhbwstuttgart/typeinference/unify/model/UnifyPair.java index fbe3a099..06c464dc 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/unify/model/UnifyPair.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/unify/model/UnifyPair.java @@ -195,11 +195,13 @@ public class UnifyPair { if (other.getBasePair() != basePair || (other.getBasePair() == null && basePair == null)) { return false; } + if (!other.getBasePair().equals(basePair) || !other.getAllSubstitutions().equals(getAllSubstitutions())) { return false; } } + return other.getPairOp() == pairOp && other.getLhsType().equals(lhs) From ed1bb44089e50f288a132e787a9b35e6d2e8e95d Mon Sep 17 00:00:00 2001 From: "pl@gohorb.ba-horb.de" Date: Thu, 19 Mar 2020 17:03:54 +0100 Subject: [PATCH 52/81] modified: src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java modified: src/main/java/de/dhbwstuttgart/typeinference/unify/model/OrderingUnifyPair.java variance = 2 umgesetzt auf variance = 1, variance = -1, variance = 0 --- .../typeinference/unify/TypeUnifyTask.java | 120 ++++++++++++++---- .../unify/model/OrderingUnifyPair.java | 63 +++++++-- 2 files changed, 146 insertions(+), 37 deletions(-) diff --git a/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java b/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java index 76db7a2a..53390bbc 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java @@ -601,6 +601,7 @@ public class TypeUnifyTask extends RecursiveTask>> { ArrayList zeroNextElem = new ArrayList<>(nextSetasList.get(0)); UnifyPair fstBasePair = zeroNextElem.remove(0).getBasePair(); + Boolean oderConstraint = false; if (fstBasePair != null) { Boolean sameBase = true; @@ -620,13 +621,29 @@ public class TypeUnifyTask extends RecursiveTask>> { } } else { - variance = 2; + //variance = 2; + oderConstraint = true; } - } else { - variance = 2; + //variance = 2; + oderConstraint = true; } + + if (oderConstraint) { + if (printtag) System.out.println("nextSetasList " + nextSetasList); + Optional optVariance = + nextSetasList.iterator() + .next() + .stream() + .filter(x -> x.getGroundBasePair().getLhsType() instanceof PlaceholderType && + x.getRhsType() instanceof ReferenceType && + x.getPairOp() == PairOperator.EQUALSDOT) + .map(x -> ((PlaceholderType)x.getGroundBasePair().getLhsType()).getVariance()) + .findAny(); + variance = optVariance.isPresent() ? optVariance.get() : 2; + } + //if (variance == 1 && nextSetasList.size() > 1) { // List> al = new ArrayList<>(nextSetasList.size()); // for (int ii = 0; ii < nextSetasList.size();ii++) { @@ -662,7 +679,8 @@ public class TypeUnifyTask extends RecursiveTask>> { /* sameEqSet-Bestimmung: Wenn a = ty \in nextSet dann enthaelt sameEqSet alle Paare a < ty1 oder ty2 < a aus fstElems */ Set sameEqSet = new HashSet<>(); - if (variance != 2) { + //if (variance != 2) { + if (!oderConstraint) { Optional optOrigPair = nextSetElem.stream().filter(x -> ( //x.getBasePair() != null && ist gegeben wenn variance != 2 //x.getBasePair().getPairOp().equals(PairOperator.SMALLERDOT) && @@ -803,7 +821,7 @@ public class TypeUnifyTask extends RecursiveTask>> { Set> aParDef = new HashSet<>(); /* PL 2019-03-11 Anfang eingefuegt Vergleich mit anderen Paaren ggf. loeschen */ - if (variance != 2 && !sameEqSet.isEmpty()) { + if (!oderConstraint && !sameEqSet.isEmpty()) { Optional optAPair = a.stream().filter(x -> ( //x.getBasePair() != null && ist gegeben wenn variance != 2 //x.getBasePair().getPairOp().equals(PairOperator.SMALLERDOT) && @@ -861,10 +879,11 @@ public class TypeUnifyTask extends RecursiveTask>> { } /* PL 2019-03-13 Anfang eingefuegt Vergleich mit anderen Paaren ggf. loeschen */ - Optional optAPair = nSaL.stream().filter(x -> ( - //x.getBasePair() != null && ist gegeben wenn variance != 2 - //x.getBasePair().getPairOp().equals(PairOperator.SMALLERDOT) && - (x.getPairOp().equals(PairOperator.EQUALSDOT) + if (!oderConstraint) {//weiss nicht ob das wirklich stimmt + Optional optAPair = nSaL.stream().filter(x -> ( + //x.getBasePair() != null && ist gegeben wenn variance != 2 + //x.getBasePair().getPairOp().equals(PairOperator.SMALLERDOT) && + (x.getPairOp().equals(PairOperator.EQUALSDOT) /* (x.getBasePair().getLhsType() instanceof PlaceholderType && x.getLhsType().equals(x.getBasePair().getLhsType())) @@ -876,14 +895,15 @@ public class TypeUnifyTask extends RecursiveTask>> { x.getLhsType().equals(x.getBasePair().getRhsType()) ).findFirst(); - if (optAPair.isPresent()) {//basepair ist entweder a <. Ty oder ty <. a - UnifyPair aPair = optAPair.get(); - //writeLog("optOrigPair: " + optOrigPair + " " + "aPair: " + aPair+ " " + "aPair.basePair(): " + aPair.getBasePair()); - writeLog("variance: " + new Integer(variance).toString() + "sameEqSet:" + sameEqSet); - if (!sameEqSet.isEmpty() && !checkA(aPair, sameEqSet, elems, result)) { - nSaL = null; - noShortendElements++; - continue; + if (optAPair.isPresent()) {//basepair ist entweder a <. Ty oder ty <. a + UnifyPair aPair = optAPair.get(); + //writeLog("optOrigPair: " + optOrigPair + " " + "aPair: " + aPair+ " " + "aPair.basePair(): " + aPair.getBasePair()); + writeLog("variance: " + new Integer(variance).toString() + "sameEqSet:" + sameEqSet); + if (!sameEqSet.isEmpty() && !checkA(aPair, sameEqSet, elems, result)) { + nSaL = null; + noShortendElements++; + continue; + } } } /* PL 2019-03-13 Ende eingefuegt Vergleich mit anderen Paaren ggf. loeschen */ @@ -966,8 +986,9 @@ public class TypeUnifyTask extends RecursiveTask>> { writeLog("-1 RM" + nSaL.toString()); } + if (!oderConstraint) {//weiss nicht ob das wirklich stimmt /* PL 2019-03-13 Anfang eingefuegt Vergleich mit anderen Paaren ggf. loeschen */ - Optional optAPair = nSaL.stream().filter(x -> ( + Optional optAPair = nSaL.stream().filter(x -> ( //x.getBasePair() != null && ist gegeben wenn variance != 2 //x.getBasePair().getPairOp().equals(PairOperator.SMALLERDOT) && (x.getPairOp().equals(PairOperator.EQUALSDOT) @@ -982,14 +1003,15 @@ public class TypeUnifyTask extends RecursiveTask>> { x.getLhsType().equals(x.getBasePair().getRhsType()) ).findFirst(); - if (optAPair.isPresent()) {//basepair ist entweder a <. Ty oder ty <. a - UnifyPair aPair = optAPair.get(); - //writeLog("optOrigPair: " + optOrigPair + " " + "aPair: " + aPair+ " " + "aPair.basePair(): " + aPair.getBasePair()); - writeLog("variance: " + new Integer(variance).toString() + "sameEqSet:" + sameEqSet); - if (!sameEqSet.isEmpty() && !checkA(aPair, sameEqSet, elems, result)) { - nSaL = null; - noShortendElements++; - continue; + if (optAPair.isPresent()) {//basepair ist entweder a <. Ty oder ty <. a + UnifyPair aPair = optAPair.get(); + //writeLog("optOrigPair: " + optOrigPair + " " + "aPair: " + aPair+ " " + "aPair.basePair(): " + aPair.getBasePair()); + writeLog("variance: " + new Integer(variance).toString() + "sameEqSet:" + sameEqSet); + if (!sameEqSet.isEmpty() && !checkA(aPair, sameEqSet, elems, result)) { + nSaL = null; + noShortendElements++; + continue; + } } } /* PL 2019-03-13 Ende eingefuegt Vergleich mit anderen Paaren ggf. loeschen */ @@ -1346,7 +1368,51 @@ public class TypeUnifyTask extends RecursiveTask>> { } else { if (variance == 0) { writeLog("a: " + rekTiefe + " variance: " + variance + a.toString()); - break; } + if (!oderConstraint) { + break; + } + else {//TODO: Hier muessen alle kleineren und größeren Elemente von a geloescht werden + writeLog("a: " + rekTiefe + " variance: " + variance + a.toString()); + writeLog("aParDef: " + aParDef.toString()); + aParDef.add(a); + Iterator> aParDefIt = aParDef.iterator(); + while(aParDefIt.hasNext()) { + Set a_new = aParDefIt.next(); + while (nextSetasListIt.hasNext()) { + Set a_next = nextSetasListIt.next(); + if (a_new.equals(a_next) || + (oup.compare(a_new, a_next) == -1)) { + writeLog("Removed: " + a_next.toString()); + nextSetasList.remove(a_next); //PL geaendert 2019-01-09 + } + else { + System.out.println(""); + writeLog("Not Removed: " + a_next.toString()); + } + } + + } + writeLog("a: " + rekTiefe + " variance: " + variance + a.toString()); + writeLog("aParDef: " + aParDef.toString()); + aParDefIt = aParDef.iterator(); + while(aParDefIt.hasNext()) { + Set a_new = aParDefIt.next(); + while (nextSetasListIt.hasNext()) { + Set a_next = nextSetasListIt.next(); + if (a_new.equals(a_next) || + (oup.compare(a_new, a_next) == 1)) { + writeLog("Removed: " + a_next.toString()); + nextSetasList.remove(a_next); + } + else { + writeLog("Not Removed: " + a_next.toString()); + System.out.println(""); + } + } + } + } + + } else { if (variance == 2) { /* vorgezogen vor das if if (parallel) { diff --git a/src/main/java/de/dhbwstuttgart/typeinference/unify/model/OrderingUnifyPair.java b/src/main/java/de/dhbwstuttgart/typeinference/unify/model/OrderingUnifyPair.java index c342269b..8ce37eb6 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/unify/model/OrderingUnifyPair.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/unify/model/OrderingUnifyPair.java @@ -4,6 +4,7 @@ import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; +import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Optional; @@ -14,6 +15,7 @@ import java.util.stream.Stream; import com.google.common.collect.Ordering; +import de.dhbwstuttgart.typeinference.unify.Match; import de.dhbwstuttgart.typeinference.unify.TypeUnifyTask; import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure; @@ -165,16 +167,7 @@ public class OrderingUnifyPair extends Ordering> { left.add(p4); */ - if ((left.size() == 1) && right.size() == 1) { - if (left.iterator().next().getLhsType().getName().equals("AFS")) { - System.out.println(""); - } - if (((right.iterator().next().getRhsType() instanceof SuperType) && (((SuperType)right.iterator().next().getRhsType()).getSuperedType().getName().equals("java.lang.Object"))) - ||((left.iterator().next().getRhsType() instanceof SuperType) && (((SuperType)left.iterator().next().getRhsType()).getSuperedType().getName().equals("java.lang.Object")))) - { - System.out.println(""); - } - } + Set lefteq = left.stream() .filter(x -> (x.getLhsType() instanceof PlaceholderType && x.getPairOp() == PairOperator.EQUALSDOT)) .collect(Collectors.toCollection(HashSet::new)); @@ -202,6 +195,56 @@ public class OrderingUnifyPair extends Ordering> { //if (lefteq.iterator().next().getLhsType().getName().equals("AJO")) { // System.out.print(""); //} + + //ODER-CONSTRAINT + Set lefteqOder = lefteq.stream() + .filter(x -> (x.getLhsType() instanceof PlaceholderType && x.getRhsType() instanceof ReferenceType)) + .collect(Collectors.toCollection(HashSet::new)); + Set righteqOder = righteq.stream() + .filter(x -> (x.getLhsType() instanceof PlaceholderType && x.getRhsType() instanceof ReferenceType)) + .collect(Collectors.toCollection(HashSet::new)); + Set lefteqRet = left.stream() + .filter(x -> (x.getRhsType() instanceof PlaceholderType && x.getPairOp() == PairOperator.EQUALSDOT)) + .collect(Collectors.toCollection(HashSet::new)); + Set righteqRet = right.stream() + .filter(x -> (x.getRhsType() instanceof PlaceholderType && x.getPairOp() == PairOperator.EQUALSDOT)) + .collect(Collectors.toCollection(HashSet::new)); + Set leftleOder = left.stream() + .filter(x -> (x.getPairOp() == PairOperator.SMALLERDOT)) + .collect(Collectors.toCollection(HashSet::new)); + Set rightleOder = right.stream() + .filter(x -> (x.getPairOp() == PairOperator.SMALLERDOT)) + .collect(Collectors.toCollection(HashSet::new)); + if (lefteqOder.size() == 1 && righteqOder.size() == 1 && lefteqRet.size() == 1 && righteqRet.size() == 1) { + Match m = new Match(); + if (compareEq(lefteqOder.iterator().next(), righteqOder.iterator().next()) == -1) { + ArrayList matchList = + leftleOder.stream().map(x -> { Iterator rightleOderIt = rightleOder.iterator(); + return new UnifyPair(x.getRhsType(), rightleOderIt.next().getRhsType(), PairOperator.EQUALSDOT);}) + .collect(Collectors.toCollection(ArrayList::new)); + if (m.match(matchList).isPresent()) { + return -1; + } + else { + return 0; + } + } else if (compareEq(lefteqOder.iterator().next(), righteqOder.iterator().next()) == 1) { + ArrayList matchList = + rightleOder.stream().map(x -> { Iterator leftOderIt = leftleOder.iterator(); + return new UnifyPair(x.getRhsType(), leftOderIt.next().getRhsType(), PairOperator.EQUALSDOT);}) + .collect(Collectors.toCollection(ArrayList::new)); + if (m.match(matchList).isPresent()) { + return 1; + } + else { + return 0; + } + } else { + return 0; + } + } + + if (lefteq.size() == 1 && lefteq.iterator().next().getRhsType() instanceof ExtendsType && leftle.size() == 1 && righteq.size() == 0 && rightle.size() == 1) { return 1; } From 850af6a6ae8bd3604c412bfed814cdd7680387d3 Mon Sep 17 00:00:00 2001 From: "pl@gohorb.ba-horb.de" Date: Thu, 19 Mar 2020 18:36:20 +0100 Subject: [PATCH 53/81] modified: ../src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java modified: ../src/main/java/de/dhbwstuttgart/syntaxtree/ClassOrInterface.java modified: ../src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java Vererbung korrigiert --- .../de/dhbwstuttgart/core/JavaTXCompiler.java | 73 ++++++++++++------- .../syntaxtree/ClassOrInterface.java | 11 +++ .../typeinference/unify/TypeUnifyTask.java | 4 +- 3 files changed, 59 insertions(+), 29 deletions(-) diff --git a/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java b/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java index 157c6b82..8c2b6d41 100644 --- a/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java +++ b/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java @@ -135,50 +135,67 @@ public class JavaTXCompiler { //sf enthaelt neues Source-File, neue Klassen-Objekte und neue //ArrayListen-Objekte fuer Fields, Construktoren und Methoden //Alle anderen Objekte werden nur kopiert. - sf.KlassenVektor.forEach(cl -> { - ClassOrInterface superclass = null; - if (cl.getSuperClass().getName().equals(new JavaClassName("java.lang.Object"))) { - superclass = objectClass; - } - else { - Optional optSuperclass = - importedClasses.stream().filter(x -> x.getClassName().equals( + SourceFile sf_new = sf; + sf.KlassenVektor.forEach(cl -> addMethods(sf_new, cl, importedClasses, objectClass)); + allClasses.addAll(sf.getClasses()); + } + allClasses.addAll(importedClasses); + return new TYPE(sourceFiles.values(), allClasses).getConstraints(); + } + + void addMethods(SourceFile sf, ClassOrInterface cl, List importedClasses, ClassOrInterface objectClass) { + if (!cl.areMethodsAdded()) { + ClassOrInterface superclass = null; + if (cl.getSuperClass().getName().equals(new JavaClassName("java.lang.Object"))) { + superclass = objectClass; + } + else { + Optional optSuperclass = + importedClasses.stream().filter(x -> x.getClassName().equals( cl.getSuperClass().getName())).findFirst(); + if (optSuperclass.isPresent()) { + superclass = optSuperclass.get(); + } + else { + optSuperclass = + sf.KlassenVektor.stream().filter(x -> x.getClassName().equals( + cl.getSuperClass().getName())).findFirst(); if (optSuperclass.isPresent()) { superclass = optSuperclass.get(); + addMethods(sf, superclass, importedClasses, objectClass); } - else { + else { //throw new ClassNotFoundException(""); } } - Iterator paraIt= cl.getSuperClass().getParaList().iterator(); - Iterator tvarVarIt = superclass.getGenerics().iterator(); + } + Iterator paraIt= cl.getSuperClass().getParaList().iterator(); + Iterator tvarVarIt = superclass.getGenerics().iterator(); - HashMap gtvs = new HashMap<>(); - while (paraIt.hasNext()) { - gtvs.put(tvarVarIt.next().getName(), paraIt.next()); - } - Iterator methodIt = superclass.getMethods().iterator(); - while(methodIt.hasNext()) { - Method m = methodIt.next(); - ParameterList newParaList = new ParameterList( + HashMap gtvs = new HashMap<>(); + while (paraIt.hasNext()) { + gtvs.put(tvarVarIt.next().getName(), paraIt.next()); + } + Iterator methodIt = superclass.getMethods().iterator(); + while(methodIt.hasNext()) { + Method m = methodIt.next(); + ParameterList newParaList = new ParameterList( m.getParameterList() .getFormalparalist() .stream() .map(fp -> new FormalParameter(fp.getName(), fp.getType().acceptTV(new TypeExchanger(gtvs)), fp.getOffset())) .collect(Collectors.toCollection(ArrayList::new)), m.getParameterList().getOffset()); - cl.getMethods().add(new Method(m.modifier, m.name, m.getReturnType().acceptTV(new TypeExchanger(gtvs)), newParaList, m.block, + cl.getMethods().add(new Method(m.modifier, m.name, m.getReturnType().acceptTV(new TypeExchanger(gtvs)), newParaList, m.block, //new GenericDeclarationList(newGenericsList, ((GenericDeclarationList)m.getGenerics()).getOffset()), - (GenericDeclarationList)m.getGenerics(), - m.getOffset())); - } + (GenericDeclarationList)m.getGenerics(), + m.getOffset())); + } - }); - allClasses.addAll(sf.getClasses()); } - allClasses.addAll(importedClasses); - return new TYPE(sourceFiles.values(), allClasses).getConstraints(); - } + cl.setMethodsAdded(); + } + + public List getAvailableClasses(SourceFile forSourceFile) throws ClassNotFoundException { //PL 2018-09-18: List durch Set ersetzt, damit die Klassen nur einmal hinzugefuegt werden diff --git a/src/main/java/de/dhbwstuttgart/syntaxtree/ClassOrInterface.java b/src/main/java/de/dhbwstuttgart/syntaxtree/ClassOrInterface.java index 87f11980..d75602d6 100644 --- a/src/main/java/de/dhbwstuttgart/syntaxtree/ClassOrInterface.java +++ b/src/main/java/de/dhbwstuttgart/syntaxtree/ClassOrInterface.java @@ -23,6 +23,7 @@ import java.util.Optional; * Stellt jede Art von Klasse dar. Auch abstrakte Klassen und Interfaces */ public class ClassOrInterface extends SyntaxTreeNode implements TypeScope{ + private Boolean methodAdded = false; //wird benoetigt bei in JavaTXCompiler.getConstraints() protected int modifiers; protected JavaClassName name; private List fields = new ArrayList<>(); @@ -68,6 +69,16 @@ public class ClassOrInterface extends SyntaxTreeNode implements TypeScope{ this.constructors = new ArrayList<>(cl.constructors); } + //Gets if it is added + public Boolean areMethodsAdded() { + return methodAdded; + } + + //Sets taht it is added + public void setMethodsAdded() { + methodAdded = true; + } + // Gets class name public JavaClassName getClassName(){ return this.name; diff --git a/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java b/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java index 53390bbc..8f13f01f 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java @@ -641,7 +641,9 @@ public class TypeUnifyTask extends RecursiveTask>> { x.getPairOp() == PairOperator.EQUALSDOT) .map(x -> ((PlaceholderType)x.getGroundBasePair().getLhsType()).getVariance()) .findAny(); - variance = optVariance.isPresent() ? optVariance.get() : 2; + //Fuer Operatorenaufrufe wird variance auf 2 gesetzt + //Es werden alle Elemente des Kartesischen Produkts abgearbeitet + variance = optVariance.isPresent() ? optVariance.get() : 2; } //if (variance == 1 && nextSetasList.size() > 1) { From eca187da7995b7abe3867cc11e7fa345b307d890 Mon Sep 17 00:00:00 2001 From: "pl@gohorb.ba-horb.de" Date: Thu, 26 Mar 2020 12:44:56 +0100 Subject: [PATCH 54/81] modified: src/main/java/de/dhbwstuttgart/syntaxtree/visual/OutputGenerator.java modified: src/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java modified: src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java modified: src/main/java/de/dhbwstuttgart/typeinference/unify/model/OrderingUnifyPair.java modified: src/main/java/de/dhbwstuttgart/typeinference/unify/model/UnifyPair.java --- .../syntaxtree/visual/OutputGenerator.java | 6 ++ .../typeinference/typeAlgo/TYPEStmt.java | 7 ++ .../typeinference/unify/TypeUnifyTask.java | 24 +++++- .../unify/model/OrderingUnifyPair.java | 79 ++++++++++++++++--- .../typeinference/unify/model/UnifyPair.java | 10 ++- 5 files changed, 108 insertions(+), 18 deletions(-) diff --git a/src/main/java/de/dhbwstuttgart/syntaxtree/visual/OutputGenerator.java b/src/main/java/de/dhbwstuttgart/syntaxtree/visual/OutputGenerator.java index 3dfca38a..078a7407 100644 --- a/src/main/java/de/dhbwstuttgart/syntaxtree/visual/OutputGenerator.java +++ b/src/main/java/de/dhbwstuttgart/syntaxtree/visual/OutputGenerator.java @@ -7,6 +7,7 @@ import de.dhbwstuttgart.syntaxtree.type.*; import java.lang.reflect.Modifier; import java.util.Iterator; +import java.util.Optional; public class OutputGenerator implements ASTVisitor{ private static final String TAB = " "; @@ -123,6 +124,11 @@ public class OutputGenerator implements ASTVisitor{ f.accept(this); out.append("\n"); } + Optional fI; + if ((fI = classOrInterface.getfieldInitializations()).isPresent()) { + out.append("Initializations:"); + fI.get().accept(this); + } for(Method m : classOrInterface.getMethods()){ out.append(tabs); m.accept(this); diff --git a/src/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java b/src/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java index 684077e4..cf67b857 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java @@ -169,6 +169,13 @@ public class TYPEStmt implements StatementVisitor{ for(MethodAssumption m : this.getMethods(methodCall.name, methodCall.arglist, info)){ GenericsResolver resolver = getResolverInstance(); methodConstraints.add(generateConstraint(methodCall, m, info, resolver)); + resolver = getResolverInstance(); + Constraint oneMethodConstraint = generateConstraint(methodCall, m, info, resolver); + oneMethodConstraint = oneMethodConstraint.stream().map(x -> (x.TA1 instanceof TypePlaceholder && x.GetOperator() == PairOperator.EQUALSDOT && + !(x.TA2 instanceof TypePlaceholder)) ? + new Pair(x.TA1, new ExtendsWildcardType(x.TA2, x.TA2.getOffset()), PairOperator.EQUALSDOT) : + x).collect(Collectors.toCollection(Constraint::new)); + methodConstraints.add(oneMethodConstraint); } if(methodConstraints.size()<1){ throw new TypeinferenceException("Methode "+methodCall.name+" ist nicht vorhanden!",methodCall.getOffset()); diff --git a/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java b/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java index 8f13f01f..73fddb07 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java @@ -639,7 +639,8 @@ public class TypeUnifyTask extends RecursiveTask>> { .filter(x -> x.getGroundBasePair().getLhsType() instanceof PlaceholderType && x.getRhsType() instanceof ReferenceType && x.getPairOp() == PairOperator.EQUALSDOT) - .map(x -> ((PlaceholderType)x.getGroundBasePair().getLhsType()).getVariance()) + .map(x -> + ((PlaceholderType)x.getGroundBasePair().getLhsType()).getVariance()) .findAny(); //Fuer Operatorenaufrufe wird variance auf 2 gesetzt //Es werden alle Elemente des Kartesischen Produkts abgearbeitet @@ -671,6 +672,27 @@ public class TypeUnifyTask extends RecursiveTask>> { a_next = nextSetasList.iterator().next(); } */ + if (variance == 2) { + writeLog("VARIANCE2 " + nextSetasList.toString()); + Set XX = nextSetasList.iterator() + .next() + .stream() + .filter(x -> + x.getGroundBasePair().getLhsType() instanceof PlaceholderType && + ! (x.getRhsType() instanceof PlaceholderType) && + x.getPairOp() == PairOperator.EQUALSDOT) + .collect(Collectors.toCollection(HashSet::new)); + + Set sI = XX.stream() + .map(x -> + ((PlaceholderType)x.getGroundBasePair().getLhsType()).getVariance()) + .collect(Collectors.toCollection(HashSet::new));; + Optional oI = sI.stream() + .findAny(); + variance = oI.isPresent() ? oI.get() : 2; + System.out.println(""); + + } if (!nextSetasList.iterator().hasNext()) System.out.print(""); if (nextSetasList.iterator().next().stream().filter(x -> x.getLhsType().getName().equals("D")).findFirst().isPresent() && nextSetasList.size()>1) diff --git a/src/main/java/de/dhbwstuttgart/typeinference/unify/model/OrderingUnifyPair.java b/src/main/java/de/dhbwstuttgart/typeinference/unify/model/OrderingUnifyPair.java index 8ce37eb6..690e4c43 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/unify/model/OrderingUnifyPair.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/unify/model/OrderingUnifyPair.java @@ -10,6 +10,7 @@ import java.util.List; import java.util.Optional; import java.util.Set; import java.util.function.BinaryOperator; +import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -44,7 +45,7 @@ public class OrderingUnifyPair extends Ordering> { }} catch (ClassCastException e) { try { - ((FiniteClosure)fc).logFile.write("ClassCastException: " + left.toString() +"\n\n"); + ((FiniteClosure)fc).logFile.write("ClassCastException: " + left.toString() + " " + left.getGroundBasePair() + "\n\n"); ((FiniteClosure)fc).logFile.flush(); } catch (IOException ie) { @@ -197,17 +198,42 @@ public class OrderingUnifyPair extends Ordering> { //} //ODER-CONSTRAINT - Set lefteqOder = lefteq.stream() - .filter(x -> (x.getLhsType() instanceof PlaceholderType && x.getRhsType() instanceof ReferenceType)) + Set leftBase = left.stream().map(x -> x.getGroundBasePair()).collect(Collectors.toCollection(HashSet::new)); + Set rightBase = right.stream().map(x -> x.getGroundBasePair()).collect(Collectors.toCollection(HashSet::new)); + + Set lefteqOder = left.stream() + .filter(x -> { UnifyPair y = x.getGroundBasePair(); + try { + ((FiniteClosure)fc).logFile.write("leftBase: " + leftBase.toString() +"\n"); + ((FiniteClosure)fc).logFile.write("rightBase: " + rightBase.toString() +"\n\n"); + ((FiniteClosure)fc).logFile.write("left: " + left.toString() +"\n"); + ((FiniteClosure)fc).logFile.write("right: " + right.toString() +"\n\n"); + ((FiniteClosure)fc).logFile.write("y: " + y.toString() +"\n"); + ((FiniteClosure)fc).logFile.write("y.getLhsType() : " + y.getLhsType() .toString() +"\n\n"); + ((FiniteClosure)fc).logFile.write("y.getRhsType(): " + y.getRhsType().toString() +"\n"); + ((FiniteClosure)fc).logFile.write("x.getPairOp(): " + x.getPairOp().toString() +"\n\n"); + } + catch (IOException ie) { + } + return (y.getLhsType() instanceof PlaceholderType && + y.getRhsType() instanceof ReferenceType && + x.getPairOp() == PairOperator.EQUALSDOT);}) .collect(Collectors.toCollection(HashSet::new)); - Set righteqOder = righteq.stream() - .filter(x -> (x.getLhsType() instanceof PlaceholderType && x.getRhsType() instanceof ReferenceType)) + Set righteqOder = right.stream() + .filter(x -> { UnifyPair y = x.getGroundBasePair(); + return (y.getLhsType() instanceof PlaceholderType && + y.getRhsType() instanceof ReferenceType && + x.getPairOp() == PairOperator.EQUALSDOT);}) .collect(Collectors.toCollection(HashSet::new)); Set lefteqRet = left.stream() - .filter(x -> (x.getRhsType() instanceof PlaceholderType && x.getPairOp() == PairOperator.EQUALSDOT)) + .filter(x -> { UnifyPair y = x.getGroundBasePair(); + return (y.getRhsType() instanceof PlaceholderType && + x.getPairOp() == PairOperator.EQUALSDOT);}) .collect(Collectors.toCollection(HashSet::new)); Set righteqRet = right.stream() - .filter(x -> (x.getRhsType() instanceof PlaceholderType && x.getPairOp() == PairOperator.EQUALSDOT)) + .filter(x -> { UnifyPair y = x.getGroundBasePair(); + return (y.getRhsType() instanceof PlaceholderType && + x.getPairOp() == PairOperator.EQUALSDOT);}) .collect(Collectors.toCollection(HashSet::new)); Set leftleOder = left.stream() .filter(x -> (x.getPairOp() == PairOperator.SMALLERDOT)) @@ -215,12 +241,36 @@ public class OrderingUnifyPair extends Ordering> { Set rightleOder = right.stream() .filter(x -> (x.getPairOp() == PairOperator.SMALLERDOT)) .collect(Collectors.toCollection(HashSet::new)); + + + synchronized(this) { + try { + ((FiniteClosure)fc).logFile.write("leftBase: " + leftBase.toString() +"\n"); + ((FiniteClosure)fc).logFile.write("rightBase: " + rightBase.toString() +"\n\n"); + ((FiniteClosure)fc).logFile.write("left: " + left.toString() +"\n"); + ((FiniteClosure)fc).logFile.write("right: " + right.toString() +"\n\n"); + ((FiniteClosure)fc).logFile.write("lefteqOder: " + lefteqOder.toString() +"\n"); + ((FiniteClosure)fc).logFile.write("righteqOder: " + righteqOder.toString() +"\n\n"); + ((FiniteClosure)fc).logFile.write("lefteqRet: " + lefteqRet.toString() +"\n"); + ((FiniteClosure)fc).logFile.write("righteqRet: " + righteqRet.toString() +"\n\n"); + ((FiniteClosure)fc).logFile.write("leftleOder: " + leftleOder.toString() +"\n"); + ((FiniteClosure)fc).logFile.write("rightleOder: " + rightleOder.toString() +"\n\n"); + ((FiniteClosure)fc).logFile.flush(); + } + catch (IOException ie) { + } + } + + if (lefteqOder.size() == 1 && righteqOder.size() == 1 && lefteqRet.size() == 1 && righteqRet.size() == 1) { Match m = new Match(); - if (compareEq(lefteqOder.iterator().next(), righteqOder.iterator().next()) == -1) { + if (compareEq(lefteqOder.iterator().next().getGroundBasePair(), righteqOder.iterator().next().getGroundBasePair()) == -1) { ArrayList matchList = - leftleOder.stream().map(x -> { Iterator rightleOderIt = rightleOder.iterator(); - return new UnifyPair(x.getRhsType(), rightleOderIt.next().getRhsType(), PairOperator.EQUALSDOT);}) + leftleOder.stream().map(x -> { + UnifyPair rightElem = rightleOder.stream() + .filter(y -> y.getGroundBasePair().getLhsType().equals(x.getGroundBasePair().getLhsType())) + .findAny().get(); + return new UnifyPair(x.getRhsType(), rightElem.getRhsType(), PairOperator.EQUALSDOT);}) .collect(Collectors.toCollection(ArrayList::new)); if (m.match(matchList).isPresent()) { return -1; @@ -228,10 +278,13 @@ public class OrderingUnifyPair extends Ordering> { else { return 0; } - } else if (compareEq(lefteqOder.iterator().next(), righteqOder.iterator().next()) == 1) { + } else if (compareEq(lefteqOder.iterator().next().getGroundBasePair(), righteqOder.iterator().next().getGroundBasePair()) == 1) { ArrayList matchList = - rightleOder.stream().map(x -> { Iterator leftOderIt = leftleOder.iterator(); - return new UnifyPair(x.getRhsType(), leftOderIt.next().getRhsType(), PairOperator.EQUALSDOT);}) + rightleOder.stream().map(x -> { + UnifyPair leftElem = leftleOder.stream() + .filter(y -> y.getGroundBasePair().getLhsType().equals(x.getGroundBasePair().getLhsType())) + .findAny().get(); + return new UnifyPair(x.getRhsType(), leftElem.getRhsType(), PairOperator.EQUALSDOT);}) .collect(Collectors.toCollection(ArrayList::new)); if (m.match(matchList).isPresent()) { return 1; diff --git a/src/main/java/de/dhbwstuttgart/typeinference/unify/model/UnifyPair.java b/src/main/java/de/dhbwstuttgart/typeinference/unify/model/UnifyPair.java index 06c464dc..bc6e3013 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/unify/model/UnifyPair.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/unify/model/UnifyPair.java @@ -217,12 +217,14 @@ public class UnifyPair { public String toString() { String ret = ""; if (lhs instanceof PlaceholderType) { - ret = new Integer(((PlaceholderType)lhs).getVariance()).toString() + " " + ((PlaceholderType)lhs).isInnerType() - + " " + ((PlaceholderType)lhs).isWildcardable(); + ret = new Integer(((PlaceholderType)lhs).getVariance()).toString() + " " + + "WC: " + ((PlaceholderType)lhs).isWildcardable() + + ", IT: " + ((PlaceholderType)lhs).isInnerType(); } if (rhs instanceof PlaceholderType) { - ret = ret + ", " + new Integer(((PlaceholderType)rhs).getVariance()).toString() + " " + ((PlaceholderType)rhs).isInnerType() - + " " + ((PlaceholderType)rhs).isWildcardable(); + ret = ret + ", " + new Integer(((PlaceholderType)rhs).getVariance()).toString() + " " + + "WC: " + ((PlaceholderType)rhs).isWildcardable() + + ", IT: " + ((PlaceholderType)rhs).isInnerType(); } return "(" + lhs + " " + pairOp + " " + rhs + ", " + ret + ")"; //+ ", [" + getfBounded().toString()+ "])"; } From 8bdb7e7b13c756946b642c4dd857d70057170337 Mon Sep 17 00:00:00 2001 From: "pl@gohorb.ba-horb.de" Date: Thu, 26 Mar 2020 17:23:56 +0100 Subject: [PATCH 55/81] modified: ../src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java modified: ../src/main/java/de/dhbwstuttgart/typeinference/unify/RuleSet.java modified: ../src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java modified: ../src/main/java/de/dhbwstuttgart/typeinference/unify/model/OrderingUnifyPair.java noch Fehler bei mathStruc und Matrix laeuft sehr lange vll. terminiert es nicht. --- .../de/dhbwstuttgart/core/JavaTXCompiler.java | 2 +- .../typeinference/unify/RuleSet.java | 4 ++ .../typeinference/unify/TypeUnifyTask.java | 53 ++----------------- .../unify/model/OrderingUnifyPair.java | 11 ++-- 4 files changed, 16 insertions(+), 54 deletions(-) diff --git a/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java b/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java index 8c2b6d41..f03589ed 100644 --- a/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java +++ b/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java @@ -73,7 +73,7 @@ public class JavaTXCompiler { public static JavaTXCompiler INSTANCE; final CompilationEnvironment environment; - Boolean resultmodel = true; + Boolean resultmodel = false; public final Map sourceFiles = new HashMap<>(); Boolean log = true; //gibt an ob ein Log-File nach System.getProperty("user.dir")+"src/test/java/logFiles" geschrieben werden soll? public volatile UnifyTaskModel usedTasks = new UnifyTaskModel(); diff --git a/src/main/java/de/dhbwstuttgart/typeinference/unify/RuleSet.java b/src/main/java/de/dhbwstuttgart/typeinference/unify/RuleSet.java index a392a2fa..755cbf0a 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/unify/RuleSet.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/unify/RuleSet.java @@ -31,6 +31,9 @@ import de.dhbwstuttgart.typeinference.unify.distributeVariance; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; +import java.io.OutputStreamWriter; + +import org.apache.commons.io.output.NullOutputStream; /** * Implementation of the type inference rules. @@ -43,6 +46,7 @@ public class RuleSet implements IRuleSet{ public RuleSet() { super(); + logFile = new OutputStreamWriter(new NullOutputStream()); } RuleSet(Writer logFile) { diff --git a/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java b/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java index 73fddb07..04ffb57f 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java @@ -637,62 +637,17 @@ public class TypeUnifyTask extends RecursiveTask>> { .next() .stream() .filter(x -> x.getGroundBasePair().getLhsType() instanceof PlaceholderType && - x.getRhsType() instanceof ReferenceType && + ! (x.getRhsType() instanceof PlaceholderType) && x.getPairOp() == PairOperator.EQUALSDOT) .map(x -> ((PlaceholderType)x.getGroundBasePair().getLhsType()).getVariance()) .findAny(); - //Fuer Operatorenaufrufe wird variance auf 2 gesetzt + //Fuer Operatorenaufrufe wird variance auf 2 gesetzt. + //da kein Receiver existiert also keon x.getGroundBasePair().getLhsType() instanceof PlaceholderType //Es werden alle Elemente des Kartesischen Produkts abgearbeitet variance = optVariance.isPresent() ? optVariance.get() : 2; } - //if (variance == 1 && nextSetasList.size() > 1) { - // List> al = new ArrayList<>(nextSetasList.size()); - // for (int ii = 0; ii < nextSetasList.size();ii++) { - // al.add(0,nextSetasList.get(ii)); - // } - // nextSetasList = al; - //} - //Set a = nextSetasListIt.next(); - /*if (nextSetasList.size()>1) {zu loeschen - if (nextSetasList.iterator().next().iterator().next().getLhsType().getName().equals("D")) - System.out.print(""); - if (variance == 1) { - a_next = oup.max(nextSetasList.iterator()); - } - else if (variance == -1) { - a_next = oup.min(nextSetasList.iterator()); - } - else if (variance == 0) { - a_next = nextSetasList.iterator().next(); - } - } - else { - a_next = nextSetasList.iterator().next(); - } - */ - if (variance == 2) { - writeLog("VARIANCE2 " + nextSetasList.toString()); - Set XX = nextSetasList.iterator() - .next() - .stream() - .filter(x -> - x.getGroundBasePair().getLhsType() instanceof PlaceholderType && - ! (x.getRhsType() instanceof PlaceholderType) && - x.getPairOp() == PairOperator.EQUALSDOT) - .collect(Collectors.toCollection(HashSet::new)); - - Set sI = XX.stream() - .map(x -> - ((PlaceholderType)x.getGroundBasePair().getLhsType()).getVariance()) - .collect(Collectors.toCollection(HashSet::new));; - Optional oI = sI.stream() - .findAny(); - variance = oI.isPresent() ? oI.get() : 2; - System.out.println(""); - - } if (!nextSetasList.iterator().hasNext()) System.out.print(""); if (nextSetasList.iterator().next().stream().filter(x -> x.getLhsType().getName().equals("D")).findFirst().isPresent() && nextSetasList.size()>1) @@ -741,6 +696,8 @@ public class TypeUnifyTask extends RecursiveTask>> { List> nextSetasListRest = new ArrayList<>(); //List> nextSetasListRestMin = new ArrayList<>(); //List> nextSetasListRestOder = new ArrayList<>(); + writeLog("WhileAnfangNextSet: " + nextSet.toString()); + writeLog("WhileAnfangNextSetasList: " + nextSetasList.toString()); if (variance == 1) { a = oup.max(nextSetasList.iterator()); nextSetasList.remove(a); diff --git a/src/main/java/de/dhbwstuttgart/typeinference/unify/model/OrderingUnifyPair.java b/src/main/java/de/dhbwstuttgart/typeinference/unify/model/OrderingUnifyPair.java index 690e4c43..76383920 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/unify/model/OrderingUnifyPair.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/unify/model/OrderingUnifyPair.java @@ -203,7 +203,7 @@ public class OrderingUnifyPair extends Ordering> { Set lefteqOder = left.stream() .filter(x -> { UnifyPair y = x.getGroundBasePair(); - try { + /*try { ((FiniteClosure)fc).logFile.write("leftBase: " + leftBase.toString() +"\n"); ((FiniteClosure)fc).logFile.write("rightBase: " + rightBase.toString() +"\n\n"); ((FiniteClosure)fc).logFile.write("left: " + left.toString() +"\n"); @@ -214,15 +214,15 @@ public class OrderingUnifyPair extends Ordering> { ((FiniteClosure)fc).logFile.write("x.getPairOp(): " + x.getPairOp().toString() +"\n\n"); } catch (IOException ie) { - } + } */ return (y.getLhsType() instanceof PlaceholderType && - y.getRhsType() instanceof ReferenceType && + !(y.getRhsType() instanceof PlaceholderType) && x.getPairOp() == PairOperator.EQUALSDOT);}) .collect(Collectors.toCollection(HashSet::new)); Set righteqOder = right.stream() .filter(x -> { UnifyPair y = x.getGroundBasePair(); return (y.getLhsType() instanceof PlaceholderType && - y.getRhsType() instanceof ReferenceType && + !(y.getRhsType() instanceof PlaceholderType) && x.getPairOp() == PairOperator.EQUALSDOT);}) .collect(Collectors.toCollection(HashSet::new)); Set lefteqRet = left.stream() @@ -243,7 +243,7 @@ public class OrderingUnifyPair extends Ordering> { .collect(Collectors.toCollection(HashSet::new)); - synchronized(this) { + /* synchronized(this) { try { ((FiniteClosure)fc).logFile.write("leftBase: " + leftBase.toString() +"\n"); ((FiniteClosure)fc).logFile.write("rightBase: " + rightBase.toString() +"\n\n"); @@ -260,6 +260,7 @@ public class OrderingUnifyPair extends Ordering> { catch (IOException ie) { } } + */ if (lefteqOder.size() == 1 && righteqOder.size() == 1 && lefteqRet.size() == 1 && righteqRet.size() == 1) { From 577faa88af56378123c3f08e29147a282d072a3d Mon Sep 17 00:00:00 2001 From: "pl@gohorb.ba-horb.de" Date: Sat, 28 Mar 2020 00:16:43 +0100 Subject: [PATCH 56/81] modified: src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java modified: src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java Reihenfolge geaendert, so dass bei Variance 1 (x <. theta) vorne und bei Variance -1 (theta <. x) vorne --- .../de/dhbwstuttgart/core/JavaTXCompiler.java | 2 +- .../typeinference/unify/TypeUnifyTask.java | 38 +++++++++++++++---- 2 files changed, 32 insertions(+), 8 deletions(-) diff --git a/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java b/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java index f03589ed..8c2b6d41 100644 --- a/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java +++ b/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java @@ -73,7 +73,7 @@ public class JavaTXCompiler { public static JavaTXCompiler INSTANCE; final CompilationEnvironment environment; - Boolean resultmodel = false; + Boolean resultmodel = true; public final Map sourceFiles = new HashMap<>(); Boolean log = true; //gibt an ob ein Log-File nach System.getProperty("user.dir")+"src/test/java/logFiles" geschrieben werden soll? public volatile UnifyTaskModel usedTasks = new UnifyTaskModel(); diff --git a/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java b/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java index 04ffb57f..d35da74f 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java @@ -696,7 +696,7 @@ public class TypeUnifyTask extends RecursiveTask>> { List> nextSetasListRest = new ArrayList<>(); //List> nextSetasListRestMin = new ArrayList<>(); //List> nextSetasListRestOder = new ArrayList<>(); - writeLog("WhileAnfangNextSet: " + nextSet.toString()); + writeLog("qextSet: " + nextSet.toString()); writeLog("WhileAnfangNextSetasList: " + nextSetasList.toString()); if (variance == 1) { a = oup.max(nextSetasList.iterator()); @@ -1824,21 +1824,43 @@ public class TypeUnifyTask extends RecursiveTask>> { Iterator eq2sprimeit = eq2sprime.iterator(); ArrayList eq2sAsListFst = new ArrayList<>(); ArrayList eq2sAsListSnd = new ArrayList<>(); + ArrayList eq2sAsListThird = new ArrayList<>(); + ArrayList eq2sAsListFourth = new ArrayList<>(); ArrayList eq2sAsListBack = new ArrayList<>(); ArrayList eq2sAsList = new ArrayList<>(); Boolean first = true; while(eq2sprimeit.hasNext()) {// alle mit Variance != 0 nach vorne schieben UnifyPair up = eq2sprimeit.next(); - if ((up.getLhsType() instanceof PlaceholderType && ((PlaceholderType)up.getLhsType()).getVariance() != 0 && !((PlaceholderType)up.getLhsType()).isInnerType()) - || (up.getRhsType() instanceof PlaceholderType && ((PlaceholderType)up.getRhsType()).getVariance() != 0) && !((PlaceholderType)up.getRhsType()).isInnerType()) { - eq2sAsListFst.add(up); + if ((up.getLhsType() instanceof PlaceholderType && + ((PlaceholderType)up.getLhsType()).getVariance() == 1 && + !((PlaceholderType)up.getLhsType()).isInnerType()) || + (up.getRhsType() instanceof PlaceholderType && + ((PlaceholderType)up.getRhsType()).getVariance() == -1) && + !((PlaceholderType)up.getRhsType()).isInnerType()) + { + eq2sAsListFst.add(up); eq2s.remove(up); } - else if ((up.getLhsType() instanceof PlaceholderType && ((PlaceholderType)up.getLhsType()).getVariance() != 0 && ((PlaceholderType)up.getLhsType()).isInnerType()) - || (up.getRhsType() instanceof PlaceholderType && ((PlaceholderType)up.getRhsType()).getVariance() != 0) && ((PlaceholderType)up.getRhsType()).isInnerType()) { + else if ((up.getLhsType() instanceof PlaceholderType && ((PlaceholderType)up.getLhsType()).getVariance() == 1 && ((PlaceholderType)up.getLhsType()).isInnerType()) + || (up.getRhsType() instanceof PlaceholderType && ((PlaceholderType)up.getRhsType()).getVariance() == -1) && ((PlaceholderType)up.getRhsType()).isInnerType()) { eq2sAsListSnd.add(up); eq2s.remove(up); - } + } + else if ((up.getLhsType() instanceof PlaceholderType && + ((PlaceholderType)up.getLhsType()).getVariance() == -1 && + !((PlaceholderType)up.getLhsType()).isInnerType()) || + (up.getRhsType() instanceof PlaceholderType && + ((PlaceholderType)up.getRhsType()).getVariance() == -1) && + !((PlaceholderType)up.getRhsType()).isInnerType()) + { + eq2sAsListThird.add(up); + eq2s.remove(up); + } + else if ((up.getLhsType() instanceof PlaceholderType && ((PlaceholderType)up.getLhsType()).getVariance() == -1 && ((PlaceholderType)up.getLhsType()).isInnerType()) + || (up.getRhsType() instanceof PlaceholderType && ((PlaceholderType)up.getRhsType()).getVariance() == 1) && ((PlaceholderType)up.getRhsType()).isInnerType()) { + eq2sAsListFourth.add(up); + eq2s.remove(up); + } else if ((up.getLhsType() instanceof PlaceholderType && ((PlaceholderType)up.getLhsType()).isInnerType()) || (up.getRhsType() instanceof PlaceholderType && ((PlaceholderType)up.getRhsType()).isInnerType())) { eq2sAsListBack.add(up); @@ -1876,6 +1898,8 @@ public class TypeUnifyTask extends RecursiveTask>> { eq2sAsList.addAll(eq2sAsListFst); eq2sAsList.addAll(eq2sAsListSnd); + eq2sAsList.addAll(eq2sAsListThird); + eq2sAsList.addAll(eq2sAsListFourth); eq2sAsList.addAll(eq2s); eq2sAsList.addAll(eq2sAsListBack); From 7c7dbf3769b80f5e7dd699ad59bf3f845d192909 Mon Sep 17 00:00:00 2001 From: "pl@gohorb.ba-horb.de" Date: Sun, 29 Mar 2020 11:05:52 +0200 Subject: [PATCH 57/81] modified: ../../../../main/java/de/dhbwstuttgart/core/JavaTXCompiler.java modified: ../../../../main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java modified: ../../../../main/java/de/dhbwstuttgart/typeinference/unify/model/UnifyPair.java Das fehlerveruraschende Paar wird auch zu abhSubst hingefuegt. --- src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java | 2 +- .../de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java | 6 ++++-- .../dhbwstuttgart/typeinference/unify/model/UnifyPair.java | 5 +++++ 3 files changed, 10 insertions(+), 3 deletions(-) diff --git a/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java b/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java index 8c2b6d41..f03589ed 100644 --- a/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java +++ b/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java @@ -73,7 +73,7 @@ public class JavaTXCompiler { public static JavaTXCompiler INSTANCE; final CompilationEnvironment environment; - Boolean resultmodel = true; + Boolean resultmodel = false; public final Map sourceFiles = new HashMap<>(); Boolean log = true; //gibt an ob ein Log-File nach System.getProperty("user.dir")+"src/test/java/logFiles" geschrieben werden soll? public volatile UnifyTaskModel usedTasks = new UnifyTaskModel(); diff --git a/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java b/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java index d35da74f..98cad271 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java @@ -1120,7 +1120,7 @@ public class TypeUnifyTask extends RecursiveTask>> { //parallel = false; //Wenn MaxNoOfThreads erreicht ist, sequentiell weiterarbeiten elems.add(a); //PL 2019-01-16 muss das wirklich hin steht schon in Zeile 859 ja braucht man siehe Zeile 859 res = unify2(elems, eq, oderConstraints, fc, parallel, rekTiefe, finalresult); - }}} + }}} if (!isUndefinedPairSetSet(res) && isUndefinedPairSetSet(result)) { //wenn korrektes Ergebnis gefunden alle Fehlerfaelle loeschen result = res; @@ -1436,7 +1436,7 @@ public class TypeUnifyTask extends RecursiveTask>> { res.stream() .map(b -> b.stream() - .map(x -> x.getAllBases()) + .map(x -> x.getThisAndAllBases()) //getAllBases durch getThisAndAllBases ersetzt, weil auch im UnifyPair selbst schon ein Fehler liegen kann. .reduce((y,z) -> { y.addAll(z); return y;}).get()) .reduce((y,z) -> { y.addAll(z); return y;}).get() ); @@ -1457,6 +1457,7 @@ public class TypeUnifyTask extends RecursiveTask>> { if (res.size() > 1) { System.out.println(); } + writeLog("nextSetasList vor filter-Aufruf: " + nextSetasList); nextSetasList = nextSetasList.stream().filter(x -> { //Boolean ret = false; //for (PlaceholderType var : vars) { @@ -1465,6 +1466,7 @@ public class TypeUnifyTask extends RecursiveTask>> { return (!x.containsAll(durchschnitt)); })//.filter(y -> couldBecorrect(reducedUndefResSubstGroundedBasePair, y)) //fuer testzwecke auskommentiert um nofstred zu bestimmen PL 2018-10-10 .collect(Collectors.toCollection(ArrayList::new)); + writeLog("nextSetasList nach filter-Aufruf: " + nextSetasList); nofstred = nextSetasList.size(); //NOCH NICHT korrekt PL 2018-10-12 //nextSetasList = nextSetasList.stream().filter(y -> couldBecorrect(reducedUndefResSubstGroundedBasePair, y)) diff --git a/src/main/java/de/dhbwstuttgart/typeinference/unify/model/UnifyPair.java b/src/main/java/de/dhbwstuttgart/typeinference/unify/model/UnifyPair.java index bc6e3013..497fd811 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/unify/model/UnifyPair.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/unify/model/UnifyPair.java @@ -138,6 +138,11 @@ public class UnifyPair { return ret; } + public Set getThisAndAllBases () { + Set ret = getAllBases(); + ret.add(this); + return ret; + } public Set getAllBases () { Set ret = new HashSet<>(); if (basePair != null) { From 97bdfe1d3a810fc6fcdc79c44c62bca47fb83955 Mon Sep 17 00:00:00 2001 From: "pl@gohorb.ba-horb.de" Date: Mon, 30 Mar 2020 13:28:13 +0200 Subject: [PATCH 58/81] modified: src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java modified: src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java wenn nicht wildcardable dann receiver ? extends geloescht modified: src/main/java/de/dhbwstuttgart/typeinference/unify/model/OrderingUnifyPair.java kleiner Fehler in compare --- .../de/dhbwstuttgart/core/JavaTXCompiler.java | 2 +- .../typeinference/unify/TypeUnifyTask.java | 18 +++++++++++++++++- .../unify/model/OrderingUnifyPair.java | 18 +++++++++--------- 3 files changed, 27 insertions(+), 11 deletions(-) diff --git a/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java b/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java index f03589ed..8c2b6d41 100644 --- a/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java +++ b/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java @@ -73,7 +73,7 @@ public class JavaTXCompiler { public static JavaTXCompiler INSTANCE; final CompilationEnvironment environment; - Boolean resultmodel = false; + Boolean resultmodel = true; public final Map sourceFiles = new HashMap<>(); Boolean log = true; //gibt an ob ein Log-File nach System.getProperty("user.dir")+"src/test/java/logFiles" geschrieben werden soll? public volatile UnifyTaskModel usedTasks = new UnifyTaskModel(); diff --git a/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java b/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java index 98cad271..1352766b 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java @@ -1884,6 +1884,14 @@ public class TypeUnifyTask extends RecursiveTask>> { oderConstraintsOutput.remove(ret); //Set retFlat = new HashSet<>(); //ret.stream().forEach(x -> retFlat.addAll(x)); + ret = ret.stream().filter(x -> { Optional optElem; + return !((optElem=x.stream().filter(y -> (y.getLhsType()) instanceof PlaceholderType + && !((PlaceholderType)y.getLhsType()).isWildcardable() + && y.getPairOp() == PairOperator.EQUALSDOT + && !(y.getRhsType() instanceof PlaceholderType)) + .findAny()).isPresent() + && optElem.get().getRhsType() instanceof ExtendsType);}) + .collect(Collectors.toSet()); ret.stream().forEach(x -> x.stream().forEach(y -> { Set x_new = new HashSet<>(x); //PL 2020-03-18: y selbst darf nicht in die Substitutionen x_new.remove(y); y.addSubstitutions(x_new); @@ -1911,7 +1919,15 @@ public class TypeUnifyTask extends RecursiveTask>> { //if (ret.iterator().next().iterator().next().getLhsType().getName().equals("M")) // System.out.println("M"); //Set retFlat = new HashSet<>(); - //ret.stream().forEach(x -> retFlat.addAll(x)); + //ret.stream().forEach(x -> retFlat.addAll(x)); + ret = ret.stream().filter(x -> { Optional optElem; + return !((optElem=x.stream().filter(y -> (y.getLhsType()) instanceof PlaceholderType + && !((PlaceholderType)y.getLhsType()).isWildcardable() + && y.getPairOp() == PairOperator.EQUALSDOT + && !(y.getRhsType() instanceof PlaceholderType)) + .findAny()).isPresent() + && optElem.get().getRhsType() instanceof ExtendsType);}) + .collect(Collectors.toSet()); ret.stream().forEach(x -> x.stream().forEach(y -> { Set x_new = new HashSet<>(x); //PL 2020-03-18: y selbst darf nicht in die Substitutionen x_new.remove(y); y.addSubstitutions(x_new); diff --git a/src/main/java/de/dhbwstuttgart/typeinference/unify/model/OrderingUnifyPair.java b/src/main/java/de/dhbwstuttgart/typeinference/unify/model/OrderingUnifyPair.java index 76383920..9681f589 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/unify/model/OrderingUnifyPair.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/unify/model/OrderingUnifyPair.java @@ -262,16 +262,16 @@ public class OrderingUnifyPair extends Ordering> { } */ - + Integer compareEq; if (lefteqOder.size() == 1 && righteqOder.size() == 1 && lefteqRet.size() == 1 && righteqRet.size() == 1) { Match m = new Match(); - if (compareEq(lefteqOder.iterator().next().getGroundBasePair(), righteqOder.iterator().next().getGroundBasePair()) == -1) { + if ((compareEq = compareEq(lefteqOder.iterator().next().getGroundBasePair(), righteqOder.iterator().next().getGroundBasePair())) == -1) { ArrayList matchList = - leftleOder.stream().map(x -> { - UnifyPair rightElem = rightleOder.stream() + rightleOder.stream().map(x -> { + UnifyPair leftElem = leftleOder.stream() .filter(y -> y.getGroundBasePair().getLhsType().equals(x.getGroundBasePair().getLhsType())) .findAny().get(); - return new UnifyPair(x.getRhsType(), rightElem.getRhsType(), PairOperator.EQUALSDOT);}) + return new UnifyPair(x.getRhsType(), leftElem.getRhsType(), PairOperator.EQUALSDOT);}) .collect(Collectors.toCollection(ArrayList::new)); if (m.match(matchList).isPresent()) { return -1; @@ -279,13 +279,13 @@ public class OrderingUnifyPair extends Ordering> { else { return 0; } - } else if (compareEq(lefteqOder.iterator().next().getGroundBasePair(), righteqOder.iterator().next().getGroundBasePair()) == 1) { + } else if (compareEq == 1) { ArrayList matchList = - rightleOder.stream().map(x -> { - UnifyPair leftElem = leftleOder.stream() + leftleOder.stream().map(x -> { + UnifyPair rightElem = rightleOder.stream() .filter(y -> y.getGroundBasePair().getLhsType().equals(x.getGroundBasePair().getLhsType())) .findAny().get(); - return new UnifyPair(x.getRhsType(), leftElem.getRhsType(), PairOperator.EQUALSDOT);}) + return new UnifyPair(x.getRhsType(), rightElem.getRhsType(), PairOperator.EQUALSDOT);}) .collect(Collectors.toCollection(ArrayList::new)); if (m.match(matchList).isPresent()) { return 1; From 3f919be1bf6edbf7f2d01995c8ba727c575fbbe2 Mon Sep 17 00:00:00 2001 From: "pl@gohorb.ba-horb.de" Date: Mon, 30 Mar 2020 16:17:52 +0200 Subject: [PATCH 59/81] new file: ../../../java/AllgemeinTest.java new file: ../../../java/bytecode/mathStrucMatrixOPTest.java.txt new file: ../../../java/bytecode/mathStrucVectorAddTest.java.txt new file: ../../../java/packages/mathStrucMatrixOPTest.java.txt new file: ../../AllgemeinTest/FCTest1.jav new file: ../../AllgemeinTest/FCTest2.jav new file: ../../AllgemeinTest/FCTest3.jav new file: ../../AllgemeinTest/GenTest.jav new file: ../../AllgemeinTest/Generics.jav new file: ../../AllgemeinTest/OverloadingMain.jav new file: ../../AllgemeinTest/Overloading_Generics.jav new file: ../../AllgemeinTest/OverrideMain.jav new file: ../../AllgemeinTest/OverrideMainRet.jav new file: ../../AllgemeinTest/Pair.java --- src/test/java/AllgemeinTest.java | 61 +++++++++++++++++++ .../bytecode/mathStrucMatrixOPTest.java.txt | 40 ++++++++++++ .../bytecode/mathStrucVectorAddTest.java.txt | 38 ++++++++++++ .../packages/mathStrucMatrixOPTest.java.txt | 51 ++++++++++++++++ src/test/resources/AllgemeinTest/FCTest1.jav | 12 ++++ src/test/resources/AllgemeinTest/FCTest2.jav | 11 ++++ src/test/resources/AllgemeinTest/FCTest3.jav | 19 ++++++ src/test/resources/AllgemeinTest/GenTest.jav | 10 +++ src/test/resources/AllgemeinTest/Generics.jav | 9 +++ .../AllgemeinTest/OverloadingMain.jav | 9 +++ .../AllgemeinTest/Overloading_Generics.jav | 20 ++++++ .../resources/AllgemeinTest/OverrideMain.jav | 25 ++++++++ .../AllgemeinTest/OverrideMainRet.jav | 11 ++++ src/test/resources/AllgemeinTest/Pair.java | 12 ++++ 14 files changed, 328 insertions(+) create mode 100644 src/test/java/AllgemeinTest.java create mode 100644 src/test/java/bytecode/mathStrucMatrixOPTest.java.txt create mode 100644 src/test/java/bytecode/mathStrucVectorAddTest.java.txt create mode 100644 src/test/java/packages/mathStrucMatrixOPTest.java.txt create mode 100644 src/test/resources/AllgemeinTest/FCTest1.jav create mode 100644 src/test/resources/AllgemeinTest/FCTest2.jav create mode 100644 src/test/resources/AllgemeinTest/FCTest3.jav create mode 100644 src/test/resources/AllgemeinTest/GenTest.jav create mode 100644 src/test/resources/AllgemeinTest/Generics.jav create mode 100644 src/test/resources/AllgemeinTest/OverloadingMain.jav create mode 100644 src/test/resources/AllgemeinTest/Overloading_Generics.jav create mode 100644 src/test/resources/AllgemeinTest/OverrideMain.jav create mode 100644 src/test/resources/AllgemeinTest/OverrideMainRet.jav create mode 100644 src/test/resources/AllgemeinTest/Pair.java diff --git a/src/test/java/AllgemeinTest.java b/src/test/java/AllgemeinTest.java new file mode 100644 index 00000000..4c594edd --- /dev/null +++ b/src/test/java/AllgemeinTest.java @@ -0,0 +1,61 @@ + + +import static org.junit.Assert.*; + +import java.io.File; +import java.lang.reflect.Field; +import java.net.URL; +import java.net.URLClassLoader; +import java.util.Arrays; + +import org.junit.BeforeClass; +import org.junit.Test; + +import com.google.common.collect.Lists; + +import de.dhbwstuttgart.core.JavaTXCompiler; + +public class AllgemeinTest { + + private static String path; + private static File fileToTest; + private static JavaTXCompiler compiler; + private static ClassLoader loader; + private static Class classToTest; + private static String pathToClassFile; + private static Object instanceOfClass; + + + @Test + public void test() throws Exception { + //String className = "GenTest"; + //String className = "Overloading_Generics"; + //String className = "Generics"; + //String className = "OverloadingMain"; + //String className = "OverrideMain"; + //String className = "OverrideMainRet"; + //String className = "FCTest1"; + //String className = "FCTest2"; + //String className = "Pair"; + String className = "FCTest3"; + //PL 2019-10-24: genutzt fuer unterschiedliche Tests + path = System.getProperty("user.dir")+"/src/test/resources/AllgemeinTest/" + className + ".jav"; + //path = System.getProperty("user.dir")+"/src/test/resources/AllgemeinTest/Overloading_Generics.jav"; + //path = System.getProperty("user.dir")+"/src/test/resources/bytecode/javFiles/mathStrucInteger.jav"; + //compiler = new JavaTXCompiler(Lists.newArrayList(new File(System.getProperty("user.dir")+"/src/test/resources/AllgemeinTest/Overloading_Generics.jav"))); + ///* + compiler = new JavaTXCompiler( + Lists.newArrayList(new File(path)), + Lists.newArrayList(new File(System.getProperty("user.dir")+"/src/test/resources/testBytecode/generatedBC/"))); + //*/ + compiler.generateBytecode(System.getProperty("user.dir")+"/src/test/resources/testBytecode/generatedBC/"); + pathToClassFile = System.getProperty("user.dir")+"/src/test/resources/testBytecode/generatedBC/"; + loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); + classToTest = loader.loadClass(className); + //classToTest = loader.loadClass("Overloading_Generics"); + //instanceOfClass = classToTest.getDeclaredConstructor().newInstance("A"); + //classToTest = loader.loadClass("Overloading_Generics1"); + //instanceOfClass = classToTest.getDeclaredConstructor(Object.class).newInstance("B"); + } + +} diff --git a/src/test/java/bytecode/mathStrucMatrixOPTest.java.txt b/src/test/java/bytecode/mathStrucMatrixOPTest.java.txt new file mode 100644 index 00000000..30668595 --- /dev/null +++ b/src/test/java/bytecode/mathStrucMatrixOPTest.java.txt @@ -0,0 +1,40 @@ +package bytecode; + +import static org.junit.Assert.*; + +import java.io.File; +import java.lang.reflect.Field; +import java.net.URL; +import java.net.URLClassLoader; + +import org.junit.BeforeClass; +import org.junit.Test; + +import de.dhbwstuttgart.core.JavaTXCompiler; + +public class mathStrucMatrixOPTest { + + private static String path; + private static File fileToTest; + private static JavaTXCompiler compiler; + private static ClassLoader loader; + private static Class classToTest; + private static String pathToClassFile; + private static Object instanceOfClass; + + + @Test + public void test() throws Exception { + //PL 2019-10-24: laeuft nicht durch deshalb ersetzt + path = System.getProperty("user.dir")+"/src/test/resources/bytecode/javFiles/mathStrucMatrixOp.jav"; + //path = System.getProperty("user.dir")+"/src/test/resources/bytecode/javFiles/mathStrucInteger.jav"; + fileToTest = new File(path); + compiler = new JavaTXCompiler(fileToTest); + compiler.generateBytecode(System.getProperty("user.dir")+"/src/test/resources/testBytecode/generatedBC/"); + pathToClassFile = System.getProperty("user.dir")+"/src/test/resources/testBytecode/generatedBC/"; + loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); + classToTest = loader.loadClass("mathStrucMatrixOP"); + instanceOfClass = classToTest.getDeclaredConstructor(Object.class).newInstance("A"); + } + +} diff --git a/src/test/java/bytecode/mathStrucVectorAddTest.java.txt b/src/test/java/bytecode/mathStrucVectorAddTest.java.txt new file mode 100644 index 00000000..d26360dc --- /dev/null +++ b/src/test/java/bytecode/mathStrucVectorAddTest.java.txt @@ -0,0 +1,38 @@ +package bytecode; + +import static org.junit.Assert.*; + +import java.io.File; +import java.lang.reflect.Field; +import java.net.URL; +import java.net.URLClassLoader; + +import org.junit.BeforeClass; +import org.junit.Test; + +import de.dhbwstuttgart.core.JavaTXCompiler; + +public class mathStrucVectorAddTest { + + private static String path; + private static File fileToTest; + private static JavaTXCompiler compiler; + private static ClassLoader loader; + private static Class classToTest; + private static String pathToClassFile; + private static Object instanceOfClass; + + + @Test + public void test() throws Exception { + path = System.getProperty("user.dir")+"/src/test/resources/bytecode/javFiles/mathStrucVector.jav"; + fileToTest = new File(path); + compiler = new JavaTXCompiler(fileToTest); + compiler.generateBytecode(System.getProperty("user.dir")+"/src/test/resources/testBytecode/generatedBC/"); + pathToClassFile = System.getProperty("user.dir")+"/src/test/resources/testBytecode/generatedBC/"; + loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); + classToTest = loader.loadClass("mathStrucVector"); + //instanceOfClass = classToTest.getDeclaredConstructor(Integer.class).newInstance("A"); + } + +} diff --git a/src/test/java/packages/mathStrucMatrixOPTest.java.txt b/src/test/java/packages/mathStrucMatrixOPTest.java.txt new file mode 100644 index 00000000..f383a2b8 --- /dev/null +++ b/src/test/java/packages/mathStrucMatrixOPTest.java.txt @@ -0,0 +1,51 @@ +package packages; + +import com.google.common.collect.Lists; +import de.dhbwstuttgart.core.JavaTXCompiler; +import junit.framework.TestCase; +import org.junit.Before; +import org.junit.Test; + +import java.io.File; +import java.io.IOException; +import java.net.URL; + +public class mathStrucMatrixOPTest extends TestCase { + + public static final String rootDirectory = System.getProperty("user.dir")+"/src/test/resources/javFiles/packageTest/de/test/"; + + + public mathStrucMatrixOPTest() throws ClassNotFoundException, IOException { + /* + Generate ToImport class in rootDirectory and in output-Directory + */ + /* PL 2020-01-07 kann z.Zt. nicht erzeugt werden (siehe Bug 170, http://bugzilla.ba-horb.de/show_bug.cgi?id=170) + JavaTXCompiler compiler = new JavaTXCompiler(new File(rootDirectory+"mathStruc.jav")); + compiler.typeInference(); + compiler.generateBytecode(rootDirectory + "output/"); + File f = new File(rootDirectory + "output/de/test/mathStruc.class"); + assertTrue(f.exists()); +*/ + JavaTXCompiler compiler = new JavaTXCompiler(new File(rootDirectory+"MatrixOP.jav")); + compiler.typeInference(); + compiler.generateBytecode(rootDirectory + "output/"); + File f = new File(rootDirectory + "output/de/test/MatrixOP.class"); + assertTrue(f.exists()); + + } + + @Test + public void testSetPackageNameInBytecodeAndOutputFolder() throws IOException, ClassNotFoundException { + JavaTXCompiler compiler = new JavaTXCompiler( + Lists.newArrayList(new File(rootDirectory+"mathStrucMatrixOP.jav")), + Lists.newArrayList(new File(rootDirectory+"output/"))); + compiler.typeInference(); + File f = new File(rootDirectory + "output/de/test/mathStrucMatrixOP.class"); + if(f.exists() && !f.isDirectory()) { + f.delete(); + } + compiler.generateBytecode(rootDirectory + "output/"); + f = new File(rootDirectory + "output/de/test/mathStrucMatrixOP.class"); + assertTrue(f.exists()); + } +} diff --git a/src/test/resources/AllgemeinTest/FCTest1.jav b/src/test/resources/AllgemeinTest/FCTest1.jav new file mode 100644 index 00000000..98647278 --- /dev/null +++ b/src/test/resources/AllgemeinTest/FCTest1.jav @@ -0,0 +1,12 @@ +import java.util.Vector; +import java.util.List; +import java.lang.Integer; + +class FCTest1 extends Vector> { + fc1() { + var y; + var z; + y.add(z); + return y; + } +} \ No newline at end of file diff --git a/src/test/resources/AllgemeinTest/FCTest2.jav b/src/test/resources/AllgemeinTest/FCTest2.jav new file mode 100644 index 00000000..c3f892dd --- /dev/null +++ b/src/test/resources/AllgemeinTest/FCTest2.jav @@ -0,0 +1,11 @@ +import java.util.Vector; +import java.util.List; +import java.lang.Integer; + +class FCTest2 extends Vector> { + fc2(y) { + var z; + y.add(z); + return y; + } +} \ No newline at end of file diff --git a/src/test/resources/AllgemeinTest/FCTest3.jav b/src/test/resources/AllgemeinTest/FCTest3.jav new file mode 100644 index 00000000..e862c4b8 --- /dev/null +++ b/src/test/resources/AllgemeinTest/FCTest3.jav @@ -0,0 +1,19 @@ +import java.util.Vector; +import java.lang.Integer; + +class FCTest3 extends Pair, Vector> { + + + fc2(x) { + x.snd().addElement(2); + } + + + + fc2a() { + var y; + y.snd().addElement(2); + return y; + } + +} \ No newline at end of file diff --git a/src/test/resources/AllgemeinTest/GenTest.jav b/src/test/resources/AllgemeinTest/GenTest.jav new file mode 100644 index 00000000..409838ae --- /dev/null +++ b/src/test/resources/AllgemeinTest/GenTest.jav @@ -0,0 +1,10 @@ +import java.lang.Integer; +import java.util.Vector; + +public class GenTest { + + main(x) { + var v = new Vector(); + return 1 + v.elementAt(0); + } +} diff --git a/src/test/resources/AllgemeinTest/Generics.jav b/src/test/resources/AllgemeinTest/Generics.jav new file mode 100644 index 00000000..efed04f0 --- /dev/null +++ b/src/test/resources/AllgemeinTest/Generics.jav @@ -0,0 +1,9 @@ +class Generics { + a; + id(b) { return b; } + setA(x) { + a = x; + return a; + } + m(x,y) { x = id(y); } +} diff --git a/src/test/resources/AllgemeinTest/OverloadingMain.jav b/src/test/resources/AllgemeinTest/OverloadingMain.jav new file mode 100644 index 00000000..960f01db --- /dev/null +++ b/src/test/resources/AllgemeinTest/OverloadingMain.jav @@ -0,0 +1,9 @@ +import java.util.Stack; +import java.util.Vector; + +class OverloadingMain { + + mmMain(x) { var y; return new O1().mm(y); } + +} + diff --git a/src/test/resources/AllgemeinTest/Overloading_Generics.jav b/src/test/resources/AllgemeinTest/Overloading_Generics.jav new file mode 100644 index 00000000..d5691152 --- /dev/null +++ b/src/test/resources/AllgemeinTest/Overloading_Generics.jav @@ -0,0 +1,20 @@ +import java.lang.Integer; + + +public class Overloading_Generics { + + id1 (x) { return x; } + + //Integer id (Integer x) { return x; } +} + + +class Overloading_Generics1 { + main(x) { + var olg = new Overloading_Generics(); + return olg.id1(1); + } +} + + + diff --git a/src/test/resources/AllgemeinTest/OverrideMain.jav b/src/test/resources/AllgemeinTest/OverrideMain.jav new file mode 100644 index 00000000..0ede39ae --- /dev/null +++ b/src/test/resources/AllgemeinTest/OverrideMain.jav @@ -0,0 +1,25 @@ +import java.util.Vector; +import java.util.Stack; + +class OverrideMain { + ovrMain(x) { + var overide; + overide.ovr(x); + } +} + +/* + [ + [(TPH L = java.util.Stack), (TPH N = java.lang.String), (TPH M = ? extends Override2), (TPH FTN, TPH FTM), (TPH K = void)], +[(TPH FTO, TPH FTP), (TPH M = ? extends Override2), (TPH N = java.lang.String), (TPH L = java.util.Stack), (TPH K = void)], +[(TPH M = ? extends Override2), (TPH N = java.lang.String), (TPH K = void), (TPH FTR, TPH FTQ), (TPH L = java.util.Vector)], +[(TPH FTT, TPH FTS), (TPH M = ? extends Override2), (TPH L = java.util.Vector), (TPH K = void), (TPH N = java.lang.String)], +[(TPH L = java.util.Vector), (TPH M = ? extends Override2), (TPH N = java.lang.String), (TPH FTU, TPH FTV), (TPH K = void)], +[(TPH FTX, TPH FTW), (TPH M = ? extends Override2), (TPH L = java.util.Vector), (TPH K = void), (TPH N = java.lang.String)], +[(TPH M = ? extends Override2), (TPH L = java.util.Stack), (TPH K = void), (TPH FTY, TPH FTZ), (TPH N = java.lang.String)], +[(TPH FUB, TPH FUA), (TPH K = void), (TPH M = ? extends Override2), (TPH N = java.lang.String), (TPH L = java.util.Vector)], +[(TPH N = java.lang.String), (TPH L = java.util.Vector), (TPH FUD, TPH FUC), (TPH M = ? extends Override2), (TPH K = void)], +[(TPH N = java.lang.String), (TPH FUF, TPH FUE), (TPH M = ? extends Override2), (TPH K = void), (TPH L = java.util.Vector)]] + + [[(TPH M = ? extends Override2), (TPH MNX, TPH MNY), (TPH N = java.lang.String), (TPH K = void), (TPH L = java.util.Stack)], [(TPH L = java.util.Stack), (TPH N = java.lang.String), (TPH M = ? extends Override2), (TPH K = void), (TPH MOB, TPH MOC)], [(TPH M = ? extends Override2), (TPH N = java.lang.String), (TPH MNZ, TPH MOA), (TPH L = java.util.Vector), (TPH K = void)], [(TPH L = java.util.Vector), (TPH K = void), (TPH M = ? extends Override2), (TPH MOD, TPH MOE), (TPH N = java.lang.String)], [(TPH M = ? extends Override2), (TPH K = void), (TPH N = java.lang.String), (TPH MOF, TPH MOG), (TPH L = java.util.Stack)], [(TPH L = java.util.Vector), (TPH K = void), (TPH MOH, TPH MOI), (TPH M = ? extends Override2), (TPH N = java.lang.String)], [(TPH L = java.util.Vector), (TPH MOJ, TPH MOK), (TPH K = void), (TPH M = ? extends Override2), (TPH N = java.lang.String)], [(TPH MOL, TPH MOM), (TPH L = java.util.Stack), (TPH M = ? extends Override2), (TPH K = void), (TPH N = java.lang.String)], [(TPH L = java.util.Vector), (TPH MON, TPH MOO), (TPH N = java.lang.String), (TPH K = void), (TPH M = ? extends Override2)], [(TPH L = java.util.Stack), (TPH N = java.lang.String), (TPH M = ? extends Override2), (TPH MOQ, TPH MOP), (TPH K = void)]] +*/ diff --git a/src/test/resources/AllgemeinTest/OverrideMainRet.jav b/src/test/resources/AllgemeinTest/OverrideMainRet.jav new file mode 100644 index 00000000..44759c81 --- /dev/null +++ b/src/test/resources/AllgemeinTest/OverrideMainRet.jav @@ -0,0 +1,11 @@ +import java.util.Vector; +import java.util.Stack; + +class OverrideMainRet { + ovrMain() { + var overide; + var x; + overide.ovr(x); + return x; + } +} \ No newline at end of file diff --git a/src/test/resources/AllgemeinTest/Pair.java b/src/test/resources/AllgemeinTest/Pair.java new file mode 100644 index 00000000..b506efa9 --- /dev/null +++ b/src/test/resources/AllgemeinTest/Pair.java @@ -0,0 +1,12 @@ +class Pair { + T x; + U y; + + public T fst () { + return x; + } + + public U snd () { + return y; + } +} From 8b9f0d6376f5ddec5141be82dc760bd96c5d38eb Mon Sep 17 00:00:00 2001 From: "pl@gohorb.ba-horb.de" Date: Mon, 20 Apr 2020 14:29:15 +0200 Subject: [PATCH 60/81] modified: src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java modified: src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java log-Files abgeschaltet modified: src/test/java/AllgemeinTest.java File ergaenzt --- src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java | 6 +++--- .../de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java | 4 ++-- src/test/java/AllgemeinTest.java | 3 ++- 3 files changed, 7 insertions(+), 6 deletions(-) diff --git a/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java b/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java index 8c2b6d41..ab589e8d 100644 --- a/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java +++ b/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java @@ -562,11 +562,11 @@ public class JavaTXCompiler { final ConstraintSet cons = getConstraints(); Set> results = new HashSet<>(); try { - Writer logFile = //new OutputStreamWriter(new NullOutputStream()); + Writer logFile = new OutputStreamWriter(new NullOutputStream()); // new FileWriter(new // File(System.getProperty("user.dir")+"/src/test/resources/logFiles/"+"log_"+sourceFiles.keySet().iterator().next().getName())); - new FileWriter(new File(System.getProperty("user.dir") + "/logFiles/" + "log_" - + sourceFiles.keySet().iterator().next().getName())); + //new FileWriter(new File(System.getProperty("user.dir") + "/logFiles/" + "log_" + // + sourceFiles.keySet().iterator().next().getName())); IFiniteClosure finiteClosure = UnifyTypeFactory.generateFC(allClasses, logFile, classLoader); System.out.println(finiteClosure); ConstraintSet unifyCons = UnifyTypeFactory.convert(cons); diff --git a/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java b/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java index 1352766b..127b0fb4 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java @@ -173,9 +173,9 @@ public class TypeUnifyTask extends RecursiveTask>> { thNo = totalnoOfThread; writeLog("thNo2 " + thNo); try { - this.logFile = //new OutputStreamWriter(new NullOutputStream()); + this.logFile = new OutputStreamWriter(new NullOutputStream()); //new FileWriter(new File(System.getProperty("user.dir")+"/src/test/resources/logFiles/"+"Thread_"+thNo)); - new FileWriter(new File(System.getProperty("user.dir")+"/logFiles/"+"Thread_"+thNo)); + //new FileWriter(new File(System.getProperty("user.dir")+"/logFiles/"+"Thread_"+thNo)); logFile.write(""); } catch (IOException e) { diff --git a/src/test/java/AllgemeinTest.java b/src/test/java/AllgemeinTest.java index 4c594edd..9905f315 100644 --- a/src/test/java/AllgemeinTest.java +++ b/src/test/java/AllgemeinTest.java @@ -37,7 +37,8 @@ public class AllgemeinTest { //String className = "FCTest1"; //String className = "FCTest2"; //String className = "Pair"; - String className = "FCTest3"; + //String className = "FCTest3"; + String className = "Var"; //PL 2019-10-24: genutzt fuer unterschiedliche Tests path = System.getProperty("user.dir")+"/src/test/resources/AllgemeinTest/" + className + ".jav"; //path = System.getProperty("user.dir")+"/src/test/resources/AllgemeinTest/Overloading_Generics.jav"; From 4f10e789d4e18ac00f822ba3cad2325b0d8c7add Mon Sep 17 00:00:00 2001 From: "pl@gohorb.ba-horb.de" Date: Fri, 24 Apr 2020 23:05:42 +0200 Subject: [PATCH 61/81] modified: src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java modified: src/main/java/de/dhbwstuttgart/syntaxtree/ClassOrInterface.java modified: src/main/java/de/dhbwstuttgart/syntaxtree/Method.java modified: src/main/java/de/dhbwstuttgart/syntaxtree/factory/ASTFactory.java modified: src/main/java/de/dhbwstuttgart/syntaxtree/factory/UnifyTypeFactory.java modified: src/main/java/de/dhbwstuttgart/typeinference/assumptions/MethodAssumption.java modified: src/main/java/de/dhbwstuttgart/typeinference/constraints/Constraint.java modified: src/main/java/de/dhbwstuttgart/typeinference/constraints/ConstraintSet.java modified: src/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java modified: src/main/java/de/dhbwstuttgart/typeinference/unify/RuleSet.java modified: src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnify.java modified: src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnify2Task.java modified: src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java modified: src/main/java/de/dhbwstuttgart/typeinference/unify/interfaces/IRuleSet.java modified: src/test/java/AllgemeinTest.java Erster Ansatz Call-Graph zu beruecksichtigen --- .../de/dhbwstuttgart/core/JavaTXCompiler.java | 10 ++-- .../syntaxtree/ClassOrInterface.java | 2 +- .../de/dhbwstuttgart/syntaxtree/Method.java | 14 +++++ .../syntaxtree/factory/ASTFactory.java | 18 ++++-- .../syntaxtree/factory/UnifyTypeFactory.java | 6 +- .../assumptions/MethodAssumption.java | 8 ++- .../typeinference/constraints/Constraint.java | 21 +++++++ .../constraints/ConstraintSet.java | 8 ++- .../typeinference/typeAlgo/TYPEStmt.java | 9 +-- .../typeinference/unify/RuleSet.java | 11 ++-- .../typeinference/unify/TypeUnify.java | 8 +-- .../typeinference/unify/TypeUnify2Task.java | 2 +- .../typeinference/unify/TypeUnifyTask.java | 59 ++++++++++--------- .../unify/interfaces/IRuleSet.java | 3 +- src/test/java/AllgemeinTest.java | 3 +- 15 files changed, 124 insertions(+), 58 deletions(-) diff --git a/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java b/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java index ab589e8d..e264f0f4 100644 --- a/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java +++ b/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java @@ -534,13 +534,13 @@ public class JavaTXCompiler { // Set> result = unify.unifySequential(xConsSet, finiteClosure, // logFile, log); // Set> result = unify.unify(xConsSet, finiteClosure); - List>> oderConstraints = unifyCons.getOderConstraints().stream().map(x -> { + List>> oderConstraints = unifyCons.getOderConstraints()/*.stream().map(x -> { Set> ret = new HashSet<>(); for (Constraint y : x) { ret.add(new HashSet<>(y)); } return ret; - }).collect(Collectors.toCollection(ArrayList::new)); + }).collect(Collectors.toCollection(ArrayList::new))*/; unify.unifyAsync(unifyCons.getUndConstraints(), oderConstraints, finiteClosure, logFile, log, urm, usedTasks); } catch (IOException e) { @@ -722,13 +722,13 @@ public class JavaTXCompiler { // Set> result = unify.unifySequential(xConsSet, finiteClosure, // logFile, log); // Set> result = unify.unify(xConsSet, finiteClosure); - List>> oderConstraints = unifyCons.getOderConstraints().stream().map(x -> { - Set> ret = new HashSet<>(); + List>> oderConstraints = unifyCons.getOderConstraints()//.stream().map(x -> { + /*Set> ret = new HashSet<>(); for (Constraint y : x) { ret.add(new HashSet<>(y)); } return ret; - }).collect(Collectors.toCollection(ArrayList::new)); + }).collect(Collectors.toCollection(ArrayList::new))*/; if (resultmodel) { /* UnifyResultModel Anfang */ UnifyResultModel urm = new UnifyResultModel(cons, finiteClosure); diff --git a/src/main/java/de/dhbwstuttgart/syntaxtree/ClassOrInterface.java b/src/main/java/de/dhbwstuttgart/syntaxtree/ClassOrInterface.java index d75602d6..c99caa53 100644 --- a/src/main/java/de/dhbwstuttgart/syntaxtree/ClassOrInterface.java +++ b/src/main/java/de/dhbwstuttgart/syntaxtree/ClassOrInterface.java @@ -74,7 +74,7 @@ public class ClassOrInterface extends SyntaxTreeNode implements TypeScope{ return methodAdded; } - //Sets taht it is added + //Sets that it is added public void setMethodsAdded() { methodAdded = true; } diff --git a/src/main/java/de/dhbwstuttgart/syntaxtree/Method.java b/src/main/java/de/dhbwstuttgart/syntaxtree/Method.java index 99cd3f91..ec13878e 100644 --- a/src/main/java/de/dhbwstuttgart/syntaxtree/Method.java +++ b/src/main/java/de/dhbwstuttgart/syntaxtree/Method.java @@ -31,6 +31,7 @@ public class Method extends SyntaxTreeNode implements IItemWithOffset, TypeScope private ExceptionList exceptionlist; private GenericDeclarationList generics; private final RefTypeOrTPHOrWildcardOrGeneric returnType; + public final Boolean isInherited; public Method(int modifier, String name, RefTypeOrTPHOrWildcardOrGeneric returnType, ParameterList parameterList, Block block, GenericDeclarationList gtvDeclarations, Token offset) { @@ -41,6 +42,19 @@ public class Method extends SyntaxTreeNode implements IItemWithOffset, TypeScope this.parameterlist = parameterList; this.block = block; this.generics = gtvDeclarations; + this.isInherited = false; + } + + public Method(int modifier, String name, RefTypeOrTPHOrWildcardOrGeneric returnType, ParameterList parameterList, Block block, + GenericDeclarationList gtvDeclarations, Token offset, Boolean isInherited) { + super(offset); + this.name = name; + this.modifier = modifier; + this.returnType = returnType; + this.parameterlist = parameterList; + this.block = block; + this.generics = gtvDeclarations; + this.isInherited = isInherited; } public ParameterList getParameterList() { diff --git a/src/main/java/de/dhbwstuttgart/syntaxtree/factory/ASTFactory.java b/src/main/java/de/dhbwstuttgart/syntaxtree/factory/ASTFactory.java index a682717c..fc704572 100644 --- a/src/main/java/de/dhbwstuttgart/syntaxtree/factory/ASTFactory.java +++ b/src/main/java/de/dhbwstuttgart/syntaxtree/factory/ASTFactory.java @@ -3,8 +3,11 @@ package de.dhbwstuttgart.syntaxtree.factory; import java.lang.reflect.*; import java.lang.reflect.Constructor; import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; import java.util.List; import java.util.Optional; +import java.util.Set; import de.dhbwstuttgart.exceptions.NotImplementedException; import de.dhbwstuttgart.parser.NullToken; @@ -35,8 +38,15 @@ public class ASTFactory { for(java.lang.reflect.Constructor constructor : jreClass.getConstructors()){ konstruktoren.add(createConstructor(constructor, jreClass)); } - for(java.lang.reflect.Method method : jreClass.getMethods()){ - methoden.add(createMethod(method, jreClass)); + Set allMethods = new HashSet<>(Arrays.asList(jreClass.getMethods())); + Set allDeclaredMethods = new HashSet<>(Arrays.asList(jreClass.getDeclaredMethods())); + Set allInheritedMethods = new HashSet<>(allMethods); + allInheritedMethods.removeAll(allDeclaredMethods); + for(java.lang.reflect.Method method : allDeclaredMethods){ + methoden.add(createMethod(method, jreClass, false)); + } + for(java.lang.reflect.Method method : allInheritedMethods){ + methoden.add(createMethod(method, jreClass, true)); } List felder = new ArrayList<>(); for(java.lang.reflect.Field field : jreClass.getDeclaredFields()){ @@ -102,7 +112,7 @@ public class ASTFactory { return new de.dhbwstuttgart.syntaxtree.Constructor(modifier, name,returnType, parameterList, block, gtvDeclarations, offset /*, new ArrayList<>() geloescht PL 2018-11-24 */); } - public static Method createMethod(java.lang.reflect.Method jreMethod, java.lang.Class inClass){ + public static Method createMethod(java.lang.reflect.Method jreMethod, java.lang.Class inClass, Boolean isInherited){ String name = jreMethod.getName(); RefTypeOrTPHOrWildcardOrGeneric returnType; Type jreRetType; @@ -126,7 +136,7 @@ public class ASTFactory { GenericDeclarationList gtvDeclarations = createGenerics(jreMethod.getTypeParameters(), inClass, jreMethod.getName()); Token offset = new NullToken(); - return new Method(jreMethod.getModifiers(), name,returnType, parameterList, block, gtvDeclarations, offset); + return new Method(jreMethod.getModifiers(), name,returnType, parameterList, block, gtvDeclarations, offset, isInherited); } public static GenericDeclarationList createGenerics(TypeVariable[] typeParameters, Class context, String methodName){ diff --git a/src/main/java/de/dhbwstuttgart/syntaxtree/factory/UnifyTypeFactory.java b/src/main/java/de/dhbwstuttgart/syntaxtree/factory/UnifyTypeFactory.java index 84d0f1e5..addcc61e 100644 --- a/src/main/java/de/dhbwstuttgart/syntaxtree/factory/UnifyTypeFactory.java +++ b/src/main/java/de/dhbwstuttgart/syntaxtree/factory/UnifyTypeFactory.java @@ -153,8 +153,12 @@ public class UnifyTypeFactory { return constraints.map(UnifyTypeFactory::convert); } + //never used public static Constraint convert(Constraint constraint){ - return constraint.stream().map(UnifyTypeFactory::convert).collect(Collectors.toCollection(Constraint::new)); + Boolean isInherited = constraint.isInherited(); + Constraint unifyPairConstraint = constraint.stream().map(UnifyTypeFactory::convert).collect(Collectors.toCollection(Constraint::new)); + unifyPairConstraint.setIsInherited(isInherited); + return unifyPairConstraint; } public static UnifyPair convert(Pair p) { diff --git a/src/main/java/de/dhbwstuttgart/typeinference/assumptions/MethodAssumption.java b/src/main/java/de/dhbwstuttgart/typeinference/assumptions/MethodAssumption.java index c1a6d449..6e6c5c5a 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/assumptions/MethodAssumption.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/assumptions/MethodAssumption.java @@ -17,13 +17,15 @@ public class MethodAssumption extends Assumption{ private ClassOrInterface receiver; private RefTypeOrTPHOrWildcardOrGeneric retType; List params; + private final Boolean isInherited; public MethodAssumption(ClassOrInterface receiver, RefTypeOrTPHOrWildcardOrGeneric retType, - List params, TypeScope scope){ + List params, TypeScope scope, Boolean isInherited){ super(scope); this.receiver = receiver; this.retType = retType; this.params = params; + this.isInherited = isInherited; } /* @@ -70,4 +72,8 @@ public class MethodAssumption extends Assumption{ return receiverType; } + + public Boolean isInherited() { + return isInherited; + } } diff --git a/src/main/java/de/dhbwstuttgart/typeinference/constraints/Constraint.java b/src/main/java/de/dhbwstuttgart/typeinference/constraints/Constraint.java index 476f18dd..fbccd8b8 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/constraints/Constraint.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/constraints/Constraint.java @@ -7,4 +7,25 @@ import java.util.HashSet; import java.util.Set; public class Constraint extends HashSet { + private Boolean isInherited = false;//wird nur für die Method-Constraints benoetigt + + public Constraint() { + super(); + } + + public Constraint(Boolean isInherited) { + this.isInherited = isInherited; + } + + public void setIsInherited(Boolean isInherited) { + this.isInherited = isInherited; + } + + public Boolean isInherited() { + return isInherited; + } + + public String toString() { + return super.toString() + " isInherited = " + isInherited; + } } diff --git a/src/main/java/de/dhbwstuttgart/typeinference/constraints/ConstraintSet.java b/src/main/java/de/dhbwstuttgart/typeinference/constraints/ConstraintSet.java index bc0ad928..d8190e7d 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/constraints/ConstraintSet.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/constraints/ConstraintSet.java @@ -51,8 +51,12 @@ public class ConstraintSet { List>> newOder = new ArrayList<>(); for(Set> oderConstraint : oderConstraints){ newOder.add( - oderConstraint.parallelStream().map((Constraint as) -> - as.stream().map(o).collect(Collectors.toCollection(Constraint::new))).collect(Collectors.toSet()) + oderConstraint.parallelStream().map((Constraint as) -> { + Boolean isInherited = as.isInherited(); + Constraint newConst = as.stream().map(o).collect(Collectors.toCollection(Constraint::new)); + newConst.setIsInherited(isInherited); + return newConst; + }).collect(Collectors.toSet()) ); } ret.oderConstraints = newOder; diff --git a/src/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java b/src/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java index cf67b857..364077f2 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java @@ -175,6 +175,7 @@ public class TYPEStmt implements StatementVisitor{ !(x.TA2 instanceof TypePlaceholder)) ? new Pair(x.TA1, new ExtendsWildcardType(x.TA2, x.TA2.getOffset()), PairOperator.EQUALSDOT) : x).collect(Collectors.toCollection(Constraint::new)); + oneMethodConstraint.setIsInherited(m.isInherited()); methodConstraints.add(oneMethodConstraint); } if(methodConstraints.size()<1){ @@ -567,7 +568,7 @@ public class TYPEStmt implements StatementVisitor{ protected Constraint generateConstraint(MethodCall forMethod, MethodAssumption assumption, TypeInferenceBlockInformation info, GenericsResolver resolver){ - Constraint methodConstraint = new Constraint<>(); + Constraint methodConstraint = new Constraint<>(assumption.isInherited()); ClassOrInterface receiverCl = assumption.getReceiver(); /* List params = new ArrayList<>(); @@ -633,7 +634,7 @@ public class TYPEStmt implements StatementVisitor{ public RefTypeOrTPHOrWildcardOrGeneric getReturnType() { throw new NotImplementedException(); } - })); + }, false)); } for(ClassOrInterface cl : info.getAvailableClasses()){ for(Method m : cl.getMethods()){ @@ -642,7 +643,7 @@ public class TYPEStmt implements StatementVisitor{ RefTypeOrTPHOrWildcardOrGeneric retType = m.getReturnType();//info.checkGTV(m.getReturnType()); ret.add(new MethodAssumption(cl, retType, convertParams(m.getParameterList(),info), - createTypeScope(cl, m))); + createTypeScope(cl, m), m.isInherited)); } } } @@ -677,7 +678,7 @@ public class TYPEStmt implements StatementVisitor{ for(Method m : cl.getConstructors()){ if(m.getParameterList().getFormalparalist().size() == argList.getArguments().size()){ ret.add(new MethodAssumption(cl, ofType, convertParams(m.getParameterList(), - info), createTypeScope(cl, m))); + info), createTypeScope(cl, m), m.isInherited)); } } } diff --git a/src/main/java/de/dhbwstuttgart/typeinference/unify/RuleSet.java b/src/main/java/de/dhbwstuttgart/typeinference/unify/RuleSet.java index 755cbf0a..e52b3cd0 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/unify/RuleSet.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/unify/RuleSet.java @@ -26,6 +26,7 @@ import de.dhbwstuttgart.typeinference.unify.model.Unifier; import de.dhbwstuttgart.typeinference.unify.model.UnifyPair; import de.dhbwstuttgart.typeinference.unify.model.UnifyType; import de.dhbwstuttgart.typeinference.unify.model.WildcardType; +import de.dhbwstuttgart.typeinference.constraints.Constraint; import de.dhbwstuttgart.typeinference.unify.distributeVariance; import java.io.FileWriter; @@ -631,7 +632,7 @@ public class RuleSet implements IRuleSet{ } @Override - public Optional> subst(Set pairs, List>> oderConstraints) { + public Optional> subst(Set pairs, List>> oderConstraints) { HashMap typeMap = new HashMap<>(); Stack occuringTypes = new Stack<>(); @@ -678,17 +679,17 @@ public class RuleSet implements IRuleSet{ result = result.stream().map(x -> uni.apply(pair,x)).collect(Collectors.toCollection(ArrayList::new)); result1 = result1.stream().map(x -> uni.apply(pair,x)).collect(Collectors.toCollection(LinkedList::new)); - Function,? extends HashSet> applyUni = b -> b.stream().map( - x -> uni.apply(pair,x)).collect(Collectors.toCollection(HashSet::new)); + Function,? extends Constraint> applyUni = b -> b.stream().map( + x -> uni.apply(pair,x)).collect(Collectors.toCollection(Constraint::new)); List>> oderConstraintsRet = new ArrayList<>(); - for(Set> oc : oderConstraints) { + for(Set> oc : oderConstraints) { //Set> ocRet = new HashSet<>(); //for(Set cs : oc) { Set> csRet = oc.stream().map(applyUni).collect(Collectors.toCollection(HashSet::new)); oderConstraintsRet.add(csRet); //} } - oderConstraints.replaceAll(oc -> oc.stream().map(applyUni).collect(Collectors.toCollection(HashSet::new))); + oderConstraints.replaceAll(oc -> oc.stream().map(applyUni).collect(Collectors.toCollection(Constraint::new))); /* oderConstraints = oderConstraints.stream().map( a -> a.stream().map(applyUni diff --git a/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnify.java b/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnify.java index 6b045547..d78d8c8d 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnify.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnify.java @@ -28,7 +28,7 @@ public class TypeUnify { * @param cons * @return */ - public Set> unify(Set undConstrains, List>> oderConstraints, IFiniteClosure fc, Writer logFile, Boolean log, UnifyResultModel ret, UnifyTaskModel usedTasks) { + public Set> unify(Set undConstrains, List>> oderConstraints, IFiniteClosure fc, Writer logFile, Boolean log, UnifyResultModel ret, UnifyTaskModel usedTasks) { TypeUnifyTask unifyTask = new TypeUnifyTask(undConstrains, oderConstraints, fc, true, logFile, log, 0, ret, usedTasks); ForkJoinPool pool = new ForkJoinPool(); pool.invoke(unifyTask); @@ -54,7 +54,7 @@ public class TypeUnify { * @param ret * @return */ - public UnifyResultModel unifyAsync(Set undConstrains, List>> oderConstraints, IFiniteClosure fc, Writer logFile, Boolean log, UnifyResultModel ret, UnifyTaskModel usedTasks) { + public UnifyResultModel unifyAsync(Set undConstrains, List>> oderConstraints, IFiniteClosure fc, Writer logFile, Boolean log, UnifyResultModel ret, UnifyTaskModel usedTasks) { TypeUnifyTask unifyTask = new TypeUnifyTask(undConstrains, oderConstraints, fc, true, logFile, log, 0, ret, usedTasks); ForkJoinPool pool = new ForkJoinPool(); pool.invoke(unifyTask); @@ -72,7 +72,7 @@ public class TypeUnify { * @param ret * @return */ - public UnifyResultModel unifyParallel(Set undConstrains, List>> oderConstraints, IFiniteClosure fc, Writer logFile, Boolean log, UnifyResultModel ret, UnifyTaskModel usedTasks) { + public UnifyResultModel unifyParallel(Set undConstrains, List>> oderConstraints, IFiniteClosure fc, Writer logFile, Boolean log, UnifyResultModel ret, UnifyTaskModel usedTasks) { TypeUnifyTask unifyTask = new TypeUnifyTask(undConstrains, oderConstraints, fc, true, logFile, log, 0, ret, usedTasks); ForkJoinPool pool = new ForkJoinPool(); pool.invoke(unifyTask); @@ -105,7 +105,7 @@ public class TypeUnify { * @param cons * @return */ - public Set> unifyOderConstraints(Set undConstrains, List>> oderConstraints, IFiniteClosure fc, Writer logFile, Boolean log, UnifyResultModel ret, UnifyTaskModel usedTasks) { + public Set> unifyOderConstraints(Set undConstrains, List>> oderConstraints, IFiniteClosure fc, Writer logFile, Boolean log, UnifyResultModel ret, UnifyTaskModel usedTasks) { TypeUnifyTask unifyTask = new TypeUnifyTask(undConstrains, oderConstraints, fc, false, logFile, log, 0, ret, usedTasks); Set> res = unifyTask.compute(); try { diff --git a/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnify2Task.java b/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnify2Task.java index 54c3fb99..798c6f05 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnify2Task.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnify2Task.java @@ -18,7 +18,7 @@ public class TypeUnify2Task extends TypeUnifyTask { Set> setToFlatten; - public TypeUnify2Task(Set> setToFlatten, Set eq, List>> oderConstraints, Set nextSetElement, IFiniteClosure fc, boolean parallel, Writer logFile, Boolean log, int rekTiefe, UnifyResultModel urm, UnifyTaskModel usedTasks) { + public TypeUnify2Task(Set> setToFlatten, Set eq, List>> oderConstraints, Set nextSetElement, IFiniteClosure fc, boolean parallel, Writer logFile, Boolean log, int rekTiefe, UnifyResultModel urm, UnifyTaskModel usedTasks) { super(eq, oderConstraints, fc, parallel, logFile, log, rekTiefe, urm, usedTasks); this.setToFlatten = setToFlatten; this.nextSetElement = nextSetElement; diff --git a/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java b/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java index 127b0fb4..8ebce509 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java @@ -101,7 +101,7 @@ public class TypeUnifyTask extends RecursiveTask>> { protected Set eq; //und-constraints - protected List>> oderConstraintsField; + protected List>> oderConstraintsField; protected IFiniteClosure fc; @@ -146,7 +146,7 @@ public class TypeUnifyTask extends RecursiveTask>> { */ - public TypeUnifyTask(Set eq, List>> oderConstraints, IFiniteClosure fc, boolean parallel, Writer logFile, Boolean log, int rekTiefe, UnifyResultModel urm, UnifyTaskModel usedTasks) { + public TypeUnifyTask(Set eq, List>> oderConstraints, IFiniteClosure fc, boolean parallel, Writer logFile, Boolean log, int rekTiefe, UnifyResultModel urm, UnifyTaskModel usedTasks) { synchronized (this) { this.eq = eq; //this.oderConstraints = oderConstraints.stream().map(x -> x.stream().map(y -> new HashSet<>(y)).collect(Collectors.toSet(HashSet::new))).collect(Collectors.toList(ArrayList::new)); @@ -247,7 +247,7 @@ public class TypeUnifyTask extends RecursiveTask>> { oderConstraintsField.stream() .filter(x -> x.size()==1) .map(y -> y.stream().findFirst().get()).forEach(x -> neweq.addAll(x)); - ArrayList>> remainingOderconstraints = oderConstraintsField.stream() + ArrayList>> remainingOderconstraints = oderConstraintsField.stream() .filter(x -> x.size()>1) .collect(Collectors.toCollection(ArrayList::new)); Set> res = unify(neweq, remainingOderconstraints, fc, parallel, rekTiefeField, true); @@ -292,7 +292,7 @@ public class TypeUnifyTask extends RecursiveTask>> { * @param fc The finite closure * @return The set of all principal type unifiers */ - protected Set> unify(final Set eq, List>> oderConstraints, IFiniteClosure fc, boolean parallel, int rekTiefe, Boolean finalresult) { + protected Set> unify(final Set eq, List>> oderConstraints, IFiniteClosure fc, boolean parallel, int rekTiefe, Boolean finalresult) { //Set aas = eq.stream().filter(x -> x.getLhsType().getName().equals("AA") //&& x.getPairOp().equals(PairOperator.SMALLERDOT) // ).collect(Collectors.toCollection(HashSet::new)); //writeLog(nOfUnify.toString() + " AA: " + aas.toString()); @@ -357,7 +357,7 @@ public class TypeUnifyTask extends RecursiveTask>> { // There are up to 10 toplevel set. 8 of 10 are the result of the // cartesian product of the sets created by pattern matching. - List>> topLevelSets = new ArrayList<>(); + List>> topLevelSets = new ArrayList<>(); //System.out.println(eq2s); @@ -385,8 +385,8 @@ public class TypeUnifyTask extends RecursiveTask>> { Set undefinedPairs = new HashSet<>(); if (printtag) System.out.println("eq2s " + eq2s); //writeLog("BufferSet: " + bufferSet.toString()+"\n"); - List>> oderConstraintsOutput = new ArrayList<>();//new ArrayList<>(oderConstraints); - Set>>> secondLevelSets = calculatePairSets(eq2s, oderConstraints, fc, undefinedPairs, oderConstraintsOutput); + List>> oderConstraintsOutput = new ArrayList<>();//new ArrayList<>(oderConstraints); + Set>>> secondLevelSets = calculatePairSets(eq2s, oderConstraints, fc, undefinedPairs, oderConstraintsOutput); //PL 2017-09-20: Im calculatePairSets wird möglicherweise O .< java.lang.Integer //nicht ausgewertet Faculty Beispiel im 1. Schritt //PL 2017-10-03 geloest, muesste noch mit FCs mit kleineren @@ -434,8 +434,8 @@ public class TypeUnifyTask extends RecursiveTask>> { */ //Alternative KEIN KARTESISCHES PRODUKT der secondlevel Ebene bilden - for(Set>> secondLevelSet : secondLevelSets) { - for (Set> secondlevelelem : secondLevelSet) { + for(Set>> secondLevelSet : secondLevelSets) { + for (Set> secondlevelelem : secondLevelSet) { topLevelSets.add(secondlevelelem); } } @@ -450,7 +450,7 @@ public class TypeUnifyTask extends RecursiveTask>> { } - Set> unify2(Set> setToFlatten, Set eq, List>> oderConstraints, IFiniteClosure fc, boolean parallel, int rekTiefe, Boolean finalresult) { + Set> unify2(Set> setToFlatten, Set eq, List>> oderConstraints, IFiniteClosure fc, boolean parallel, int rekTiefe, Boolean finalresult) { //Aufruf von computeCartesianRecursive ENDE //keine Ahnung woher das kommt @@ -482,7 +482,7 @@ public class TypeUnifyTask extends RecursiveTask>> { //writeLog("vor Subst: " + eqPrime); writeLog("vor Subst: " + oderConstraints); String ocString = oderConstraints.toString(); - List>> newOderConstraints = new ArrayList<>(oderConstraints); + List>> newOderConstraints = new ArrayList<>(oderConstraints); Optional> eqPrimePrime = rules.subst(eqPrime, newOderConstraints); Set> unifyres1 = null; Set> unifyres2 = null; @@ -572,21 +572,21 @@ public class TypeUnifyTask extends RecursiveTask>> { - Set> computeCartesianRecursive(Set> fstElems, ArrayList>> topLevelSets, Set eq, List>> oderConstraints, IFiniteClosure fc, boolean parallel, int rekTiefe, Boolean finalresult) { + Set> computeCartesianRecursive(Set> fstElems, ArrayList>> topLevelSets, Set eq, List>> oderConstraints, IFiniteClosure fc, boolean parallel, int rekTiefe, Boolean finalresult) { //ArrayList>> remainingSets = new ArrayList<>(topLevelSets); fstElems.addAll(topLevelSets.stream() .filter(x -> x.size()==1) .map(y -> y.stream().findFirst().get()) .collect(Collectors.toCollection(HashSet::new))); - ArrayList>> remainingSets = topLevelSets.stream() + ArrayList>> remainingSets = topLevelSets.stream() .filter(x -> x.size()>1) .collect(Collectors.toCollection(ArrayList::new)); if (remainingSets.isEmpty()) {//Alle Elemente sind 1-elementig Set> result = unify2(fstElems, eq, oderConstraints, fc, parallel, rekTiefe, finalresult); return result; } - Set> nextSet = remainingSets.remove(0); + Set> nextSet = remainingSets.remove(0); writeLog("nextSet: " + nextSet.toString()); List> nextSetasList =new ArrayList<>(nextSet); try { @@ -835,7 +835,7 @@ public class TypeUnifyTask extends RecursiveTask>> { Set forks = new HashSet<>(); Set newEqOrig = new HashSet<>(eq); Set> newElemsOrig = new HashSet<>(elems); - List>> newOderConstraintsOrig = new ArrayList<>(oderConstraints); + List>> newOderConstraintsOrig = new ArrayList<>(oderConstraints); newElemsOrig.add(a); /* FORK ANFANG */ @@ -891,7 +891,7 @@ public class TypeUnifyTask extends RecursiveTask>> { Set newEq = new HashSet<>(eq); Set> newElems = new HashSet<>(elems); - List>> newOderConstraints = new ArrayList<>(oderConstraints); + List>> newOderConstraints = new ArrayList<>(oderConstraints); newElems.add(nSaL); TypeUnify2Task fork = new TypeUnify2Task(newElems, newEq, newOderConstraints, nSaL, fc, parallel, logFile, log, rekTiefe, urm, usedTasks); forks.add(fork); @@ -943,7 +943,7 @@ public class TypeUnifyTask extends RecursiveTask>> { Set forks = new HashSet<>(); Set newEqOrig = new HashSet<>(eq); Set> newElemsOrig = new HashSet<>(elems); - List>> newOderConstraintsOrig = new ArrayList<>(oderConstraints); + List>> newOderConstraintsOrig = new ArrayList<>(oderConstraints); newElemsOrig.add(a); /* FORK ANFANG */ @@ -999,7 +999,7 @@ public class TypeUnifyTask extends RecursiveTask>> { Set newEq = new HashSet<>(eq); Set> newElems = new HashSet<>(elems); - List>> newOderConstraints = new ArrayList<>(oderConstraints); + List>> newOderConstraints = new ArrayList<>(oderConstraints); newElems.add(nSaL); TypeUnify2Task fork = new TypeUnify2Task(newElems, newEq, newOderConstraints, nSaL, fc, parallel, logFile, log, rekTiefe, urm, usedTasks); forks.add(fork); @@ -1052,7 +1052,7 @@ public class TypeUnifyTask extends RecursiveTask>> { Set forks = new HashSet<>(); Set newEqOrig = new HashSet<>(eq); Set> newElemsOrig = new HashSet<>(elems); - List>> newOderConstraintsOrig = new ArrayList<>(oderConstraints); + List>> newOderConstraintsOrig = new ArrayList<>(oderConstraints); newElemsOrig.add(a); /* FORK ANFANG */ @@ -1075,7 +1075,7 @@ public class TypeUnifyTask extends RecursiveTask>> { nextSetasList.remove(nSaL); //PL einkommentiert 20-02-03 Set newEq = new HashSet<>(eq); Set> newElems = new HashSet<>(elems); - List>> newOderConstraints = new ArrayList<>(oderConstraints); + List>> newOderConstraints = new ArrayList<>(oderConstraints); newElems.add(nSaL); TypeUnify2Task fork = new TypeUnify2Task(newElems, newEq, newOderConstraints, nSaL, fc, parallel, logFile, log, rekTiefe, urm, usedTasks); forks.add(fork); @@ -1288,7 +1288,8 @@ public class TypeUnifyTask extends RecursiveTask>> { while (nextSetasListIt.hasNext()) { Set a_next = nextSetasListIt.next(); if (a_new.equals(a_next) || - (oup.compare(a_new, a_next) == 1)) { + ((oup.compare(a_new, a_next) == 1) && + (!oderConstraint || ((Constraint)a_next).isInherited()))) { writeLog("Removed: " + a_next.toString()); nextSetasList.remove(a_next); } @@ -1336,7 +1337,8 @@ public class TypeUnifyTask extends RecursiveTask>> { while (nextSetasListIt.hasNext()) { Set a_next = nextSetasListIt.next(); if (a_new.equals(a_next) || - (oup.compare(a_new, a_next) == -1)) { + ((oup.compare(a_new, a_next) == -1) && + (!oderConstraint || ((Constraint)a_new).isInherited()))) { writeLog("Removed: " + a_next.toString()); nextSetasList.remove(a_next); //PL geaendert 2019-01-09 } @@ -1813,10 +1815,10 @@ public class TypeUnifyTask extends RecursiveTask>> { * from the pairs that matched the case. Each generated set contains singleton sets or sets with few elements * (as in case 1 where sigma is added to the innermost set). */ - protected Set>>> calculatePairSets(Set eq2s, List>> oderConstraintsInput, IFiniteClosure fc, Set undefined, List>> oderConstraintsOutput) { + protected Set>>> calculatePairSets(Set eq2s, List>> oderConstraintsInput, IFiniteClosure fc, Set undefined, List>> oderConstraintsOutput) { writeLog("eq2s: " + eq2s.toString()); oderConstraintsOutput.addAll(oderConstraintsInput); - List>>> result = new ArrayList<>(9); + List>>> result = new ArrayList<>(9); // Init all 8 cases + 9. Case: oderConstraints for(int i = 0; i < 9; i++) @@ -1869,8 +1871,9 @@ public class TypeUnifyTask extends RecursiveTask>> { eq2s.remove(up); } } - if (eq2sAsListFst.isEmpty()) { - List>> oderConstraintsVariance = oderConstraintsOutput.stream() //Alle Elemente rauswerfen, die Variance 0 haben oder keine TPH in LHS oder RHS sind + //if (eq2sAsListFst.isEmpty()) + { + List>> oderConstraintsVariance = oderConstraintsOutput.stream() //Alle Elemente rauswerfen, die Variance 0 haben oder keine TPH in LHS oder RHS sind .filter(x -> x.stream() .filter(y -> y.stream().filter(z -> ((z.getLhsType() instanceof PlaceholderType) @@ -1880,7 +1883,7 @@ public class TypeUnifyTask extends RecursiveTask>> { ).findFirst().isPresent() ).findFirst().isPresent()).collect(Collectors.toList()); if (!oderConstraintsVariance.isEmpty()) { - Set> ret = oderConstraintsVariance.get(0); + Set> ret = oderConstraintsVariance.get(0); oderConstraintsOutput.remove(ret); //Set retFlat = new HashSet<>(); //ret.stream().forEach(x -> retFlat.addAll(x)); @@ -1915,7 +1918,7 @@ public class TypeUnifyTask extends RecursiveTask>> { if (eq2sAsList.isEmpty() && first) {//Alle eq2s sind empty und alle oderConstraints mit Variance != 0 sind bearbeitet if (!oderConstraintsOutput.isEmpty()) { - Set> ret = oderConstraintsOutput.remove(0); + Set> ret = oderConstraintsOutput.remove(0); //if (ret.iterator().next().iterator().next().getLhsType().getName().equals("M")) // System.out.println("M"); //Set retFlat = new HashSet<>(); diff --git a/src/main/java/de/dhbwstuttgart/typeinference/unify/interfaces/IRuleSet.java b/src/main/java/de/dhbwstuttgart/typeinference/unify/interfaces/IRuleSet.java index 752ff8b2..bac6bcb0 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/unify/interfaces/IRuleSet.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/unify/interfaces/IRuleSet.java @@ -4,6 +4,7 @@ import java.util.List; import java.util.Optional; import java.util.Set; +import de.dhbwstuttgart.typeinference.constraints.Constraint; import de.dhbwstuttgart.typeinference.unify.model.UnifyPair; /** @@ -91,7 +92,7 @@ public interface IRuleSet { * @param pairs The set of pairs where the subst rule should apply. * @return An optional of the modified set, if there were any substitutions. An empty optional if there were no substitutions. */ - public Optional> subst(Set pairs, List>> oderConstraints); + public Optional> subst(Set pairs, List>> oderConstraints); /** * Applies the subst-Rule to a set of pairs (usually Eq'). diff --git a/src/test/java/AllgemeinTest.java b/src/test/java/AllgemeinTest.java index 9905f315..73f29ea9 100644 --- a/src/test/java/AllgemeinTest.java +++ b/src/test/java/AllgemeinTest.java @@ -38,7 +38,8 @@ public class AllgemeinTest { //String className = "FCTest2"; //String className = "Pair"; //String className = "FCTest3"; - String className = "Var"; + //String className = "Var"; + String className = "Put"; //PL 2019-10-24: genutzt fuer unterschiedliche Tests path = System.getProperty("user.dir")+"/src/test/resources/AllgemeinTest/" + className + ".jav"; //path = System.getProperty("user.dir")+"/src/test/resources/AllgemeinTest/Overloading_Generics.jav"; From b83e2c10e3d5cc1f2d1de4edb9a6fb63da7910ef Mon Sep 17 00:00:00 2001 From: "pl@gohorb.ba-horb.de" Date: Mon, 27 Apr 2020 22:17:37 +0200 Subject: [PATCH 62/81] modified: ../../../../main/java/de/dhbwstuttgart/core/JavaTXCompiler.java modified: ../../../../main/java/de/dhbwstuttgart/typeinference/unify/RuleSet.java modified: ../../../../main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java Call-graph weiter umgesetzt, aber noch Fehler in MatrixOP --- src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java | 2 +- .../java/de/dhbwstuttgart/typeinference/unify/RuleSet.java | 6 +++--- .../de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java | 6 ++++-- 3 files changed, 8 insertions(+), 6 deletions(-) diff --git a/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java b/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java index e264f0f4..4710a02e 100644 --- a/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java +++ b/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java @@ -188,7 +188,7 @@ public class JavaTXCompiler { cl.getMethods().add(new Method(m.modifier, m.name, m.getReturnType().acceptTV(new TypeExchanger(gtvs)), newParaList, m.block, //new GenericDeclarationList(newGenericsList, ((GenericDeclarationList)m.getGenerics()).getOffset()), (GenericDeclarationList)m.getGenerics(), - m.getOffset())); + m.getOffset(), true)); } } diff --git a/src/main/java/de/dhbwstuttgart/typeinference/unify/RuleSet.java b/src/main/java/de/dhbwstuttgart/typeinference/unify/RuleSet.java index e52b3cd0..c7c6c6cc 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/unify/RuleSet.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/unify/RuleSet.java @@ -679,8 +679,8 @@ public class RuleSet implements IRuleSet{ result = result.stream().map(x -> uni.apply(pair,x)).collect(Collectors.toCollection(ArrayList::new)); result1 = result1.stream().map(x -> uni.apply(pair,x)).collect(Collectors.toCollection(LinkedList::new)); - Function,? extends Constraint> applyUni = b -> b.stream().map( - x -> uni.apply(pair,x)).collect(Collectors.toCollection(Constraint::new)); + Function,? extends Constraint> applyUni = b -> b.stream().map( + x -> uni.apply(pair,x)).collect(Collectors.toCollection(() -> new Constraint(b.isInherited()))); List>> oderConstraintsRet = new ArrayList<>(); for(Set> oc : oderConstraints) { //Set> ocRet = new HashSet<>(); @@ -689,7 +689,7 @@ public class RuleSet implements IRuleSet{ oderConstraintsRet.add(csRet); //} } - oderConstraints.replaceAll(oc -> oc.stream().map(applyUni).collect(Collectors.toCollection(Constraint::new))); + oderConstraints.replaceAll(oc -> oc.stream().map(applyUni).collect(Collectors.toCollection(HashSet::new))); /* oderConstraints = oderConstraints.stream().map( a -> a.stream().map(applyUni diff --git a/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java b/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java index 8ebce509..19a6c48b 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java @@ -1364,7 +1364,8 @@ public class TypeUnifyTask extends RecursiveTask>> { while (nextSetasListIt.hasNext()) { Set a_next = nextSetasListIt.next(); if (a_new.equals(a_next) || - (oup.compare(a_new, a_next) == -1)) { + ((oup.compare(a_new, a_next) == -1) && + (!oderConstraint || ((Constraint)a_new).isInherited()))){ writeLog("Removed: " + a_next.toString()); nextSetasList.remove(a_next); //PL geaendert 2019-01-09 } @@ -1383,7 +1384,8 @@ public class TypeUnifyTask extends RecursiveTask>> { while (nextSetasListIt.hasNext()) { Set a_next = nextSetasListIt.next(); if (a_new.equals(a_next) || - (oup.compare(a_new, a_next) == 1)) { + ((oup.compare(a_new, a_next) == 1) && + (!oderConstraint || ((Constraint)a_next).isInherited()))){ writeLog("Removed: " + a_next.toString()); nextSetasList.remove(a_next); } From 9d4980d9a109df8572e115d37f8ad81377ada370 Mon Sep 17 00:00:00 2001 From: "pl@gohorb.ba-horb.de" Date: Fri, 1 May 2020 22:55:25 +0200 Subject: [PATCH 63/81] modified: ../src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java modified: ../src/main/java/de/dhbwstuttgart/typeinference/constraints/Constraint.java modified: ../src/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java modified: ../src/main/java/de/dhbwstuttgart/typeinference/unify/RuleSet.java modified: ../src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java modified: ../src/main/java/de/dhbwstuttgart/typeinference/unify/model/OrderingUnifyPair.java --- .../de/dhbwstuttgart/core/JavaTXCompiler.java | 6 +- .../typeinference/constraints/Constraint.java | 2 +- .../typeinference/typeAlgo/TYPEStmt.java | 5 +- .../typeinference/unify/RuleSet.java | 8 - .../typeinference/unify/TypeUnifyTask.java | 159 +++++++++++++++--- .../unify/model/OrderingUnifyPair.java | 2 +- 6 files changed, 145 insertions(+), 37 deletions(-) diff --git a/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java b/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java index 4710a02e..4d4a2af2 100644 --- a/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java +++ b/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java @@ -562,11 +562,11 @@ public class JavaTXCompiler { final ConstraintSet cons = getConstraints(); Set> results = new HashSet<>(); try { - Writer logFile = new OutputStreamWriter(new NullOutputStream()); + Writer logFile = //new OutputStreamWriter(new NullOutputStream()); // new FileWriter(new // File(System.getProperty("user.dir")+"/src/test/resources/logFiles/"+"log_"+sourceFiles.keySet().iterator().next().getName())); - //new FileWriter(new File(System.getProperty("user.dir") + "/logFiles/" + "log_" - // + sourceFiles.keySet().iterator().next().getName())); + new FileWriter(new File(System.getProperty("user.dir") + "/logFiles/" + "log_" + + sourceFiles.keySet().iterator().next().getName())); IFiniteClosure finiteClosure = UnifyTypeFactory.generateFC(allClasses, logFile, classLoader); System.out.println(finiteClosure); ConstraintSet unifyCons = UnifyTypeFactory.convert(cons); diff --git a/src/main/java/de/dhbwstuttgart/typeinference/constraints/Constraint.java b/src/main/java/de/dhbwstuttgart/typeinference/constraints/Constraint.java index fbccd8b8..8159f181 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/constraints/Constraint.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/constraints/Constraint.java @@ -26,6 +26,6 @@ public class Constraint extends HashSet { } public String toString() { - return super.toString() + " isInherited = " + isInherited; + return super.toString() + " isInherited = " + isInherited + "\n"; } } diff --git a/src/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java b/src/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java index 364077f2..221d1016 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java @@ -169,14 +169,15 @@ public class TYPEStmt implements StatementVisitor{ for(MethodAssumption m : this.getMethods(methodCall.name, methodCall.arglist, info)){ GenericsResolver resolver = getResolverInstance(); methodConstraints.add(generateConstraint(methodCall, m, info, resolver)); + /* geloescht PL 2020-05-01 resolver = getResolverInstance(); Constraint oneMethodConstraint = generateConstraint(methodCall, m, info, resolver); oneMethodConstraint = oneMethodConstraint.stream().map(x -> (x.TA1 instanceof TypePlaceholder && x.GetOperator() == PairOperator.EQUALSDOT && !(x.TA2 instanceof TypePlaceholder)) ? new Pair(x.TA1, new ExtendsWildcardType(x.TA2, x.TA2.getOffset()), PairOperator.EQUALSDOT) : - x).collect(Collectors.toCollection(Constraint::new)); - oneMethodConstraint.setIsInherited(m.isInherited()); + x).collect(Collectors.toCollection(() -> new Constraint(true))); methodConstraints.add(oneMethodConstraint); + */ } if(methodConstraints.size()<1){ throw new TypeinferenceException("Methode "+methodCall.name+" ist nicht vorhanden!",methodCall.getOffset()); diff --git a/src/main/java/de/dhbwstuttgart/typeinference/unify/RuleSet.java b/src/main/java/de/dhbwstuttgart/typeinference/unify/RuleSet.java index c7c6c6cc..98d59b54 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/unify/RuleSet.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/unify/RuleSet.java @@ -681,14 +681,6 @@ public class RuleSet implements IRuleSet{ Function,? extends Constraint> applyUni = b -> b.stream().map( x -> uni.apply(pair,x)).collect(Collectors.toCollection(() -> new Constraint(b.isInherited()))); - List>> oderConstraintsRet = new ArrayList<>(); - for(Set> oc : oderConstraints) { - //Set> ocRet = new HashSet<>(); - //for(Set cs : oc) { - Set> csRet = oc.stream().map(applyUni).collect(Collectors.toCollection(HashSet::new)); - oderConstraintsRet.add(csRet); - //} - } oderConstraints.replaceAll(oc -> oc.stream().map(applyUni).collect(Collectors.toCollection(HashSet::new))); /* oderConstraints = oderConstraints.stream().map( diff --git a/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java b/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java index 19a6c48b..63a68773 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java @@ -34,6 +34,7 @@ import de.dhbwstuttgart.typeinference.unify.interfaces.ISetOperations; import de.dhbwstuttgart.typeinference.unify.interfaces.IUnify; import de.dhbwstuttgart.typeinference.unify.model.ExtendsType; import de.dhbwstuttgart.typeinference.unify.model.FunNType; +import de.dhbwstuttgart.typeinference.unify.model.OrderingExtend; import de.dhbwstuttgart.typeinference.unify.model.PairOperator; import de.dhbwstuttgart.typeinference.unify.model.PlaceholderType; import de.dhbwstuttgart.typeinference.unify.model.ReferenceType; @@ -105,7 +106,7 @@ public class TypeUnifyTask extends RecursiveTask>> { protected IFiniteClosure fc; - protected Ordering> oup; + protected OrderingExtend> oup; protected boolean parallel; @@ -173,9 +174,9 @@ public class TypeUnifyTask extends RecursiveTask>> { thNo = totalnoOfThread; writeLog("thNo2 " + thNo); try { - this.logFile = new OutputStreamWriter(new NullOutputStream()); + this.logFile = //new OutputStreamWriter(new NullOutputStream()); //new FileWriter(new File(System.getProperty("user.dir")+"/src/test/resources/logFiles/"+"Thread_"+thNo)); - //new FileWriter(new File(System.getProperty("user.dir")+"/logFiles/"+"Thread_"+thNo)); + new FileWriter(new File(System.getProperty("user.dir")+"/logFiles/"+"Thread_"+thNo)); logFile.write(""); } catch (IOException e) { @@ -630,6 +631,7 @@ public class TypeUnifyTask extends RecursiveTask>> { oderConstraint = true; } + UnifyPair oderRec = null; if (oderConstraint) { if (printtag) System.out.println("nextSetasList " + nextSetasList); Optional optVariance = @@ -691,9 +693,11 @@ public class TypeUnifyTask extends RecursiveTask>> { /* sameEqSet-Bestimmung Ende */ Set a = null; + UnifyPair a_rec = null; while (nextSetasList.size() > 0) { //(nextSetasList.size() != 0) { Set a_last = a; List> nextSetasListRest = new ArrayList<>(); + List> nextSetasListOderConstraints = new ArrayList<>(); //List> nextSetasListRestMin = new ArrayList<>(); //List> nextSetasListRestOder = new ArrayList<>(); writeLog("qextSet: " + nextSet.toString()); @@ -701,6 +705,47 @@ public class TypeUnifyTask extends RecursiveTask>> { if (variance == 1) { a = oup.max(nextSetasList.iterator()); nextSetasList.remove(a); + if (oderConstraint && nextSetasListOderConstraints.isEmpty()) { + Set a_final = a; + Optional opt_a_rec = a + .stream() + .filter(x -> x.getGroundBasePair().getLhsType() instanceof PlaceholderType && + ! (x.getRhsType() instanceof PlaceholderType) && + x.getPairOp() == PairOperator.EQUALSDOT).findAny(); + if (opt_a_rec.isPresent()) { + a_rec = opt_a_rec.get(); + PlaceholderType phd; + if ((phd = ((PlaceholderType)a_rec.getGroundBasePair().getLhsType())).isWildcardable()) { + Set a_super = a.stream() + .map(x -> new UnifyPair(x.getLhsType(), x.getRhsType(), x.getPairOp())) + .collect(Collectors.toCollection(() -> new Constraint<>(((Constraint)a_final).isInherited()))); + a_super.remove(a_rec); + a_super.add(new UnifyPair(a_rec.getLhsType(), new SuperType(a_rec.getRhsType()), a_rec.getPairOp())); + Set a_extends = a.stream() + .map(x -> new UnifyPair(x.getLhsType(), x.getRhsType(), x.getPairOp())) + .collect(Collectors.toCollection(() -> new Constraint<>(((Constraint)a_final).isInherited()))); + a_extends.remove(a_rec); + a_extends.add(new UnifyPair(a_rec.getLhsType(), new ExtendsType(a_rec.getRhsType()), a_rec.getPairOp())); + if (phd.isInnerType()) { + nextSetasList.add(a_super); + nextSetasListOderConstraints.add(a_super); + nextSetasList.add(a); + nextSetasListOderConstraints.add(a); + a = a_extends; + } + else { + nextSetasList.add(a_extends); + nextSetasListOderConstraints.add(a_extends); + nextSetasList.add(a); + nextSetasListOderConstraints.add(a); + a = a_super; + } + } + } + } + else { + nextSetasListOderConstraints.remove(a); + } nextSetasListRest = new ArrayList<>(nextSetasList); Iterator> nextSetasListItRest = new ArrayList>(nextSetasListRest).iterator(); while (nextSetasListItRest.hasNext()) { @@ -1283,22 +1328,55 @@ public class TypeUnifyTask extends RecursiveTask>> { writeLog("aParDef: " + aParDef.toString()); aParDef.add(a); Iterator> aParDefIt = aParDef.iterator(); - while(aParDefIt.hasNext()) { - Set a_new = aParDefIt.next(); - while (nextSetasListIt.hasNext()) { - Set a_next = nextSetasListIt.next(); - if (a_new.equals(a_next) || - ((oup.compare(a_new, a_next) == 1) && - (!oderConstraint || ((Constraint)a_next).isInherited()))) { - writeLog("Removed: " + a_next.toString()); - nextSetasList.remove(a_next); - } - else { - writeLog("Not Removed: " + a_next.toString()); - System.out.println(""); + if (oderConstraint) { + nextSetasList.removeAll(nextSetasListOderConstraints); + nextSetasListOderConstraints = new ArrayList<>(); + while(aParDefIt.hasNext()) { + Set a_new = aParDefIt.next(); + List> smallerSetasList = oup.smallerThan(a_new, nextSetasList); + List> notInherited = smallerSetasList.stream() + .filter(x -> !((Constraint)x).isInherited()) + .collect(Collectors.toCollection(ArrayList::new)); + List> notErased = new ArrayList<>(); + notInherited.stream().forEach(x -> { notErased.addAll(oup.smallerEqThan(x, smallerSetasList)); }); + List> erased = new ArrayList<>(smallerSetasList); + 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 a_new = aParDefIt.next(); + List> erased = oup.smallerEqThan(a_new, nextSetasList); + + /* loeschen + while (nextSetasListIt.hasNext()) { + Set a_next = nextSetasListIt.next(); + if (a_new.equals(a_next) || + ((oup.compare(a_new, a_next) == 1) && + (!oderConstraint || ((Constraint)a_next).isInherited()))) { + writeLog("Removed: " + a_next.toString()); + nextSetasList.remove(a_next); + } + else { + writeLog("Not Removed: " + a_next.toString()); + System.out.println(""); + } + } + Ende loeschen */ + nextSetasList.removeAll(erased); + + writeLog("Removed: " + erased); + + writeLog("Not Removed: " + nextSetasList); + } + } } else { if (variance == -1) { /* vorgezogen vor das if @@ -1332,8 +1410,32 @@ public class TypeUnifyTask extends RecursiveTask>> { writeLog("aParDef: " + aParDef.toString()); aParDef.add(a); Iterator> aParDefIt = aParDef.iterator(); - while(aParDefIt.hasNext()) { - Set a_new = aParDefIt.next(); + if (oderConstraint) { + while(aParDefIt.hasNext()) { + Set a_new = aParDefIt.next(); + List> greaterSetasList = oup.greaterThan(a_new, nextSetasList); + List> notInherited = greaterSetasList.stream() + .filter(x -> !((Constraint)x).isInherited()) + .collect(Collectors.toCollection(ArrayList::new)); + List> notErased = new ArrayList<>(); + notInherited.stream().forEach(x -> { notErased.addAll(oup.greaterThan(x, greaterSetasList)); }); + List> 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 a_new = aParDefIt.next(); + List> erased = oup.greaterEqThan(a_new, nextSetasList); + + /* zu loeschen while (nextSetasListIt.hasNext()) { Set a_next = nextSetasListIt.next(); if (a_new.equals(a_next) || @@ -1345,16 +1447,28 @@ public class TypeUnifyTask extends RecursiveTask>> { else { System.out.println(""); writeLog("Not Removed: " + a_next.toString()); + } } + Ende zu loeschen */ + nextSetasList.removeAll(erased); + + writeLog("Removed: " + erased); + + writeLog("Not Removed: " + nextSetasList); + } } } - } else { if (variance == 0) { writeLog("a: " + rekTiefe + " variance: " + variance + a.toString()); if (!oderConstraint) { break; } - else {//TODO: Hier muessen alle kleineren und größeren Elemente von a geloescht werden + else { + nextSetasList = nextSetasList.stream() + .filter(x -> !((Constraint)x).isInherited()) + .collect(Collectors.toCollection(ArrayList::new)); + /* + //TODO: Hier muessen alle kleineren und größeren Elemente von a geloescht werden writeLog("a: " + rekTiefe + " variance: " + variance + a.toString()); writeLog("aParDef: " + aParDef.toString()); aParDef.add(a); @@ -1395,8 +1509,9 @@ public class TypeUnifyTask extends RecursiveTask>> { } } } + */ } - + } else { if (variance == 2) { /* vorgezogen vor das if diff --git a/src/main/java/de/dhbwstuttgart/typeinference/unify/model/OrderingUnifyPair.java b/src/main/java/de/dhbwstuttgart/typeinference/unify/model/OrderingUnifyPair.java index 9681f589..d139cb88 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/unify/model/OrderingUnifyPair.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/unify/model/OrderingUnifyPair.java @@ -22,7 +22,7 @@ import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure; -public class OrderingUnifyPair extends Ordering> { +public class OrderingUnifyPair extends OrderingExtend> { protected IFiniteClosure fc; From 6deeb4105f8bc91ced56980c17b3dc7abd25ae93 Mon Sep 17 00:00:00 2001 From: "pl@gohorb.ba-horb.de" Date: Mon, 4 May 2020 17:02:15 +0200 Subject: [PATCH 64/81] modified: ../../../../main/java/de/dhbwstuttgart/syntaxtree/factory/UnifyTypeFactory.java modified: ../../../../main/java/de/dhbwstuttgart/typeinference/constraints/Constraint.java modified: ../../../../main/java/de/dhbwstuttgart/typeinference/constraints/ConstraintSet.java modified: ../../../../main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java modified: ../../../../main/java/de/dhbwstuttgart/typeinference/unify/RuleSet.java modified: ../../../../main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java modified: ../../../../main/java/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java modified: ../../../../main/java/de/dhbwstuttgart/typeinference/unify/model/OrderingUnifyPair.java Fuer Variance = 1 neue Version korrekt, konnte aber noch Fehler entbhalten --- .../syntaxtree/factory/UnifyTypeFactory.java | 8 +-- .../typeinference/constraints/Constraint.java | 25 +++++++- .../constraints/ConstraintSet.java | 37 ++++++++++-- .../typeinference/typeAlgo/TYPEStmt.java | 25 +++++--- .../typeinference/unify/RuleSet.java | 7 ++- .../typeinference/unify/TypeUnifyTask.java | 59 ++++--------------- .../unify/model/FiniteClosure.java | 6 +- .../unify/model/OrderingUnifyPair.java | 32 +++++++++- 8 files changed, 129 insertions(+), 70 deletions(-) diff --git a/src/main/java/de/dhbwstuttgart/syntaxtree/factory/UnifyTypeFactory.java b/src/main/java/de/dhbwstuttgart/syntaxtree/factory/UnifyTypeFactory.java index addcc61e..22c3b9d9 100644 --- a/src/main/java/de/dhbwstuttgart/syntaxtree/factory/UnifyTypeFactory.java +++ b/src/main/java/de/dhbwstuttgart/syntaxtree/factory/UnifyTypeFactory.java @@ -153,11 +153,11 @@ public class UnifyTypeFactory { return constraints.map(UnifyTypeFactory::convert); } - //never used + //NEVER USED public static Constraint convert(Constraint constraint){ - Boolean isInherited = constraint.isInherited(); - Constraint unifyPairConstraint = constraint.stream().map(UnifyTypeFactory::convert).collect(Collectors.toCollection(Constraint::new)); - unifyPairConstraint.setIsInherited(isInherited); + Constraint unifyPairConstraint = constraint.stream() + .map(UnifyTypeFactory::convert) + .collect(Collectors.toCollection( () -> new Constraint (constraint.isInherited(), convert(constraint.getExtendConstraint())))); return unifyPairConstraint; } diff --git a/src/main/java/de/dhbwstuttgart/typeinference/constraints/Constraint.java b/src/main/java/de/dhbwstuttgart/typeinference/constraints/Constraint.java index 8159f181..4b8de165 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/constraints/Constraint.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/constraints/Constraint.java @@ -7,7 +7,9 @@ import java.util.HashSet; import java.util.Set; public class Constraint extends HashSet { + private static final long serialVersionUID = 1L; private Boolean isInherited = false;//wird nur für die Method-Constraints benoetigt + private Constraint extendConstraint = null; public Constraint() { super(); @@ -17,6 +19,11 @@ public class Constraint extends HashSet { this.isInherited = isInherited; } + public Constraint(Boolean isInherited, Constraint extendConstraint) { + this.isInherited = isInherited; + this.extendConstraint = extendConstraint; + } + public void setIsInherited(Boolean isInherited) { this.isInherited = isInherited; } @@ -25,7 +32,21 @@ public class Constraint extends HashSet { return isInherited; } - public String toString() { - return super.toString() + " isInherited = " + isInherited + "\n"; + public Constraint getExtendConstraint() { + return extendConstraint; } + + public void setExtendConstraint(Constraint c) { + extendConstraint = c; + } + + public String toString() { + return super.toString() + " isInherited = " + isInherited + "\nextendsContraint: " + + (extendConstraint != null ? extendConstraint.toStringBase() : "null" ) + "\n" ; + } + + public String toStringBase() { + return super.toString(); + } + } diff --git a/src/main/java/de/dhbwstuttgart/typeinference/constraints/ConstraintSet.java b/src/main/java/de/dhbwstuttgart/typeinference/constraints/ConstraintSet.java index d8190e7d..31a466dd 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/constraints/ConstraintSet.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/constraints/ConstraintSet.java @@ -45,20 +45,49 @@ public class ConstraintSet { return new GuavaSetOperations().cartesianProduct(allConstraints); } - public ConstraintSet map(Function o) { + public ConstraintSet map(Function o) { + Hashtable,Constraint> CSA2CSB = new Hashtable<>(); ConstraintSet ret = new ConstraintSet<>(); ret.undConstraints = undConstraints.stream().map(o).collect(Collectors.toCollection(Constraint::new)); List>> newOder = new ArrayList<>(); + /* + for(Set> oderConstraint : oderConstraints){ + oderConstraint.forEach(as -> { + Constraint newConst = as.stream() + .map(o) + .collect(Collectors.toCollection( + () -> new Constraint (as.isInherited()))); + CSA2CSB.put(as, newConst);} ); + } + */ + for(Set> oderConstraint : oderConstraints){ newOder.add( oderConstraint.parallelStream().map((Constraint as) -> { - Boolean isInherited = as.isInherited(); - Constraint newConst = as.stream().map(o).collect(Collectors.toCollection(Constraint::new)); - newConst.setIsInherited(isInherited); + + Constraint newConst = as.stream() + .map(o) + .collect(Collectors.toCollection((as.getExtendConstraint() != null) + ? () -> new Constraint (as.isInherited(), + as.getExtendConstraint().stream().map(o).collect(Collectors.toCollection(Constraint::new))) + : () -> new Constraint (as.isInherited()) + )); + + //CSA2CSB.put(as, newConst); + return newConst; + + /* + Constraint bs = CSA2CSB.get(as); + if (as.getExtendConstraint() != null) { + bs.setExtendConstraint(CSA2CSB.get(as.getExtendConstraint())); + } + return bs; + */ }).collect(Collectors.toSet()) ); } + ret.oderConstraints = newOder; return ret; } diff --git a/src/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java b/src/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java index 221d1016..870a5d3b 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java @@ -16,8 +16,10 @@ import de.dhbwstuttgart.typeinference.assumptions.FunNClass; import de.dhbwstuttgart.typeinference.assumptions.MethodAssumption; import de.dhbwstuttgart.typeinference.assumptions.TypeInferenceBlockInformation; import de.dhbwstuttgart.typeinference.constraints.*; +import de.dhbwstuttgart.typeinference.unify.model.ExtendsType; import de.dhbwstuttgart.typeinference.unify.model.PairOperator; import de.dhbwstuttgart.typeinference.unify.model.PlaceholderType; +import de.dhbwstuttgart.typeinference.unify.model.UnifyPair; import java.util.*; import java.util.stream.Collectors; @@ -168,16 +170,23 @@ public class TYPEStmt implements StatementVisitor{ Set> methodConstraints = new HashSet<>(); for(MethodAssumption m : this.getMethods(methodCall.name, methodCall.arglist, info)){ GenericsResolver resolver = getResolverInstance(); - methodConstraints.add(generateConstraint(methodCall, m, info, resolver)); - /* geloescht PL 2020-05-01 - resolver = getResolverInstance(); Constraint oneMethodConstraint = generateConstraint(methodCall, m, info, resolver); - oneMethodConstraint = oneMethodConstraint.stream().map(x -> (x.TA1 instanceof TypePlaceholder && x.GetOperator() == PairOperator.EQUALSDOT && - !(x.TA2 instanceof TypePlaceholder)) ? - new Pair(x.TA1, new ExtendsWildcardType(x.TA2, x.TA2.getOffset()), PairOperator.EQUALSDOT) : - x).collect(Collectors.toCollection(() -> new Constraint(true))); methodConstraints.add(oneMethodConstraint); - */ + + // geloescht PL 2020-05-01 + //resolver = getResolverInstance(); + //oneMethodConstraint = generateConstraint(methodCall, m, info, resolver); + //Boolean oneMethodConstraint_isInherited = oneMethodConstraint.isInherited(); + Constraint extendsOneMethodConstraint = oneMethodConstraint.stream() + .map(x -> (x.TA1 instanceof TypePlaceholder && + x.GetOperator() == PairOperator.EQUALSDOT && + !(x.TA2 instanceof TypePlaceholder)) + ? new Pair(x.TA1, new ExtendsWildcardType(x.TA2, x.TA2.getOffset()), PairOperator.EQUALSDOT) + : x) + .collect(Collectors.toCollection(() -> new Constraint(true))); + oneMethodConstraint.setExtendConstraint(extendsOneMethodConstraint); + extendsOneMethodConstraint.setExtendConstraint(oneMethodConstraint); + methodConstraints.add(extendsOneMethodConstraint); } if(methodConstraints.size()<1){ throw new TypeinferenceException("Methode "+methodCall.name+" ist nicht vorhanden!",methodCall.getOffset()); diff --git a/src/main/java/de/dhbwstuttgart/typeinference/unify/RuleSet.java b/src/main/java/de/dhbwstuttgart/typeinference/unify/RuleSet.java index 98d59b54..93f33d08 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/unify/RuleSet.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/unify/RuleSet.java @@ -680,7 +680,12 @@ public class RuleSet implements IRuleSet{ result1 = result1.stream().map(x -> uni.apply(pair,x)).collect(Collectors.toCollection(LinkedList::new)); Function,? extends Constraint> applyUni = b -> b.stream().map( - x -> uni.apply(pair,x)).collect(Collectors.toCollection(() -> new Constraint(b.isInherited()))); + x -> uni.apply(pair,x)).collect(Collectors.toCollection((b.getExtendConstraint() != null) + ? () -> new Constraint( + b.isInherited(), + b.getExtendConstraint().stream().map(x -> uni.apply(pair,x)).collect(Collectors.toCollection(Constraint::new))) + : () -> new Constraint(b.isInherited()) + )); oderConstraints.replaceAll(oc -> oc.stream().map(applyUni).collect(Collectors.toCollection(HashSet::new))); /* oderConstraints = oderConstraints.stream().map( diff --git a/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java b/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java index 63a68773..02e2ed2a 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java @@ -588,8 +588,9 @@ public class TypeUnifyTask extends RecursiveTask>> { return result; } Set> nextSet = remainingSets.remove(0); - writeLog("nextSet: " + nextSet.toString()); + //writeLog("nextSet: " + nextSet.toString()); List> nextSetasList =new ArrayList<>(nextSet); + /* try { //List> //nextSetasList = oup.sortedCopy(nextSet);//new ArrayList<>(nextSet); @@ -597,6 +598,7 @@ public class TypeUnifyTask extends RecursiveTask>> { catch (java.lang.IllegalArgumentException e) { System.out.print(""); } + */ Set> result = new HashSet<>(); int variance = 0; @@ -654,9 +656,9 @@ public class TypeUnifyTask extends RecursiveTask>> { System.out.print(""); if (nextSetasList.iterator().next().stream().filter(x -> x.getLhsType().getName().equals("D")).findFirst().isPresent() && nextSetasList.size()>1) System.out.print(""); - writeLog("nextSetasList: " + nextSetasList.toString()); + //writeLog("nextSetasList: " + nextSetasList.toString()); Set nextSetElem = nextSetasList.get(0); - writeLog("BasePair1: " + nextSetElem + " " + nextSetElem.iterator().next().getBasePair()); + //writeLog("BasePair1: " + nextSetElem + " " + nextSetElem.iterator().next().getBasePair()); /* sameEqSet-Bestimmung: Wenn a = ty \in nextSet dann enthaelt sameEqSet alle Paare a < ty1 oder ty2 < a aus fstElems */ Set sameEqSet = new HashSet<>(); @@ -700,52 +702,15 @@ public class TypeUnifyTask extends RecursiveTask>> { List> nextSetasListOderConstraints = new ArrayList<>(); //List> nextSetasListRestMin = new ArrayList<>(); //List> nextSetasListRestOder = new ArrayList<>(); - writeLog("qextSet: " + nextSet.toString()); - writeLog("WhileAnfangNextSetasList: " + nextSetasList.toString()); + writeLog("nextSet: " + nextSet.toString()); + writeLog("nextSetasList: " + nextSetasList.toString()); if (variance == 1) { - a = oup.max(nextSetasList.iterator()); + Set a_final = a = oup.max(nextSetasList.iterator()); nextSetasList.remove(a); - if (oderConstraint && nextSetasListOderConstraints.isEmpty()) { - Set a_final = a; - Optional opt_a_rec = a - .stream() - .filter(x -> x.getGroundBasePair().getLhsType() instanceof PlaceholderType && - ! (x.getRhsType() instanceof PlaceholderType) && - x.getPairOp() == PairOperator.EQUALSDOT).findAny(); - if (opt_a_rec.isPresent()) { - a_rec = opt_a_rec.get(); - PlaceholderType phd; - if ((phd = ((PlaceholderType)a_rec.getGroundBasePair().getLhsType())).isWildcardable()) { - Set a_super = a.stream() - .map(x -> new UnifyPair(x.getLhsType(), x.getRhsType(), x.getPairOp())) - .collect(Collectors.toCollection(() -> new Constraint<>(((Constraint)a_final).isInherited()))); - a_super.remove(a_rec); - a_super.add(new UnifyPair(a_rec.getLhsType(), new SuperType(a_rec.getRhsType()), a_rec.getPairOp())); - Set a_extends = a.stream() - .map(x -> new UnifyPair(x.getLhsType(), x.getRhsType(), x.getPairOp())) - .collect(Collectors.toCollection(() -> new Constraint<>(((Constraint)a_final).isInherited()))); - a_extends.remove(a_rec); - a_extends.add(new UnifyPair(a_rec.getLhsType(), new ExtendsType(a_rec.getRhsType()), a_rec.getPairOp())); - if (phd.isInnerType()) { - nextSetasList.add(a_super); - nextSetasListOderConstraints.add(a_super); - nextSetasList.add(a); - nextSetasListOderConstraints.add(a); - a = a_extends; - } - else { - nextSetasList.add(a_extends); - nextSetasListOderConstraints.add(a_extends); - nextSetasList.add(a); - nextSetasListOderConstraints.add(a); - a = a_super; - } - } - } - } - else { - nextSetasListOderConstraints.remove(a); - } + if (oderConstraint) { + nextSetasListOderConstraints.add(((Constraint)a).getExtendConstraint()); + } + writeLog("nextSetasListOderConstraints: " + nextSetasListOderConstraints); nextSetasListRest = new ArrayList<>(nextSetasList); Iterator> nextSetasListItRest = new ArrayList>(nextSetasListRest).iterator(); while (nextSetasListItRest.hasNext()) { diff --git a/src/main/java/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java b/src/main/java/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java index 8ee39d7f..3a86af14 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java @@ -655,6 +655,7 @@ implements IFiniteClosure { */ public int compare (UnifyType left, UnifyType right, PairOperator pairop) { + //try {logFile.write("left: "+ left + " right: " + right + " pairop: " + pairop);} catch (IOException ie) {} if (left.getName().equals("Matrix") || right.getName().equals("Matrix")) System.out.println(""); /* @@ -746,7 +747,10 @@ implements IFiniteClosure { //Gleichungen der Form a <./=. Theta oder Theta <./=. a oder a <./=. b sind ok. long greaterLen = greaterRes.stream().filter(delFun).count(); if (greaterLen == 0) return 1; - else return 0; + else { + //try {logFile.write("0 left: "+ left + " right: " + right + " pairop: " + pairop);} catch (IOException ie) {} + return 0; + } } } } diff --git a/src/main/java/de/dhbwstuttgart/typeinference/unify/model/OrderingUnifyPair.java b/src/main/java/de/dhbwstuttgart/typeinference/unify/model/OrderingUnifyPair.java index d139cb88..ce2fbd21 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/unify/model/OrderingUnifyPair.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/unify/model/OrderingUnifyPair.java @@ -242,8 +242,8 @@ public class OrderingUnifyPair extends OrderingExtend> { .filter(x -> (x.getPairOp() == PairOperator.SMALLERDOT)) .collect(Collectors.toCollection(HashSet::new)); - - /* synchronized(this) { + /* + synchronized(this) { try { ((FiniteClosure)fc).logFile.write("leftBase: " + leftBase.toString() +"\n"); ((FiniteClosure)fc).logFile.write("rightBase: " + rightBase.toString() +"\n\n"); @@ -262,6 +262,7 @@ public class OrderingUnifyPair extends OrderingExtend> { } */ + Integer compareEq; if (lefteqOder.size() == 1 && righteqOder.size() == 1 && lefteqRet.size() == 1 && righteqRet.size() == 1) { Match m = new Match(); @@ -274,26 +275,51 @@ public class OrderingUnifyPair extends OrderingExtend> { return new UnifyPair(x.getRhsType(), leftElem.getRhsType(), PairOperator.EQUALSDOT);}) .collect(Collectors.toCollection(ArrayList::new)); if (m.match(matchList).isPresent()) { + //try { ((FiniteClosure)fc).logFile.write("result1: -1 \n\n"); } catch (IOException ie) {} return -1; } else { + //try { ((FiniteClosure)fc).logFile.write("result1: 0 \n\n"); } catch (IOException ie) {} return 0; } } else if (compareEq == 1) { ArrayList matchList = leftleOder.stream().map(x -> { UnifyPair rightElem = rightleOder.stream() - .filter(y -> y.getGroundBasePair().getLhsType().equals(x.getGroundBasePair().getLhsType())) + .filter(y -> + y.getGroundBasePair().getLhsType().equals(x.getGroundBasePair().getLhsType())) .findAny().get(); return new UnifyPair(x.getRhsType(), rightElem.getRhsType(), PairOperator.EQUALSDOT);}) .collect(Collectors.toCollection(ArrayList::new)); if (m.match(matchList).isPresent()) { + //try { ((FiniteClosure)fc).logFile.write("result2: 1 \n\n"); } catch (IOException ie) {} return 1; } else { + //try { ((FiniteClosure)fc).logFile.write("result2: 0 \n\n"); } catch (IOException ie) {} return 0; } } else { + /* + synchronized(this) { + try { + ((FiniteClosure)fc).logFile.write("leftBase: " + leftBase.toString() +"\n"); + ((FiniteClosure)fc).logFile.write("rightBase: " + rightBase.toString() +"\n\n"); + ((FiniteClosure)fc).logFile.write("left: " + left.toString() +"\n"); + ((FiniteClosure)fc).logFile.write("right: " + right.toString() +"\n\n"); + ((FiniteClosure)fc).logFile.write("lefteqOder: " + lefteqOder.toString() +"\n"); + ((FiniteClosure)fc).logFile.write("righteqOder: " + righteqOder.toString() +"\n\n"); + ((FiniteClosure)fc).logFile.write("lefteqRet: " + lefteqRet.toString() +"\n"); + ((FiniteClosure)fc).logFile.write("righteqRet: " + righteqRet.toString() +"\n\n"); + ((FiniteClosure)fc).logFile.write("leftleOder: " + leftleOder.toString() +"\n"); + ((FiniteClosure)fc).logFile.write("rightleOder: " + rightleOder.toString() +"\n\n"); + ((FiniteClosure)fc).logFile.write("result3: 0 \n\n"); + ((FiniteClosure)fc).logFile.flush(); + } + catch (IOException ie) { + } + } + */ return 0; } } From fd3d4e97a1f23bf95fcffcb346ab13b66be28109 Mon Sep 17 00:00:00 2001 From: "pl@gohorb.ba-horb.de" Date: Tue, 5 May 2020 17:14:52 +0200 Subject: [PATCH 65/81] =?UTF-8?q?=09modified:=20=20=20../../../../main/jav?= =?UTF-8?q?a/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java=20isInh?= =?UTF-8?q?erited=20f=C3=BCr=20=3F=20extends=20wieder=20mit=20gleich=20ges?= =?UTF-8?q?etzt?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit modified: ../../../../main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java Variance = -1 und Oderconstraints Vererbung eingebaut Variance = 0 min/max eingebaut --- .../typeinference/typeAlgo/TYPEStmt.java | 2 +- .../typeinference/unify/TypeUnifyTask.java | 68 +++++++++++++++---- 2 files changed, 56 insertions(+), 14 deletions(-) diff --git a/src/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java b/src/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java index 870a5d3b..613b1c26 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java @@ -183,7 +183,7 @@ public class TYPEStmt implements StatementVisitor{ !(x.TA2 instanceof TypePlaceholder)) ? new Pair(x.TA1, new ExtendsWildcardType(x.TA2, x.TA2.getOffset()), PairOperator.EQUALSDOT) : x) - .collect(Collectors.toCollection(() -> new Constraint(true))); + .collect(Collectors.toCollection(() -> new Constraint(oneMethodConstraint.isInherited()))); oneMethodConstraint.setExtendConstraint(extendsOneMethodConstraint); extendsOneMethodConstraint.setExtendConstraint(oneMethodConstraint); methodConstraints.add(extendsOneMethodConstraint); diff --git a/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java b/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java index 02e2ed2a..cc0fcbf1 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java @@ -633,8 +633,7 @@ public class TypeUnifyTask extends RecursiveTask>> { oderConstraint = true; } - UnifyPair oderRec = null; - if (oderConstraint) { + if (oderConstraint) {//Varianz-Bestimmung Oder-Constraints if (printtag) System.out.println("nextSetasList " + nextSetasList); Optional optVariance = nextSetasList.iterator() @@ -662,9 +661,10 @@ public class TypeUnifyTask extends RecursiveTask>> { /* sameEqSet-Bestimmung: Wenn a = ty \in nextSet dann enthaelt sameEqSet alle Paare a < ty1 oder ty2 < a aus fstElems */ Set sameEqSet = new HashSet<>(); + Optional optOrigPair = null; //if (variance != 2) { if (!oderConstraint) { - Optional optOrigPair = nextSetElem.stream().filter(x -> ( + optOrigPair = nextSetElem.stream().filter(x -> ( //x.getBasePair() != null && ist gegeben wenn variance != 2 //x.getBasePair().getPairOp().equals(PairOperator.SMALLERDOT) && (x.getPairOp().equals(PairOperator.EQUALSDOT) @@ -695,13 +695,16 @@ public class TypeUnifyTask extends RecursiveTask>> { /* sameEqSet-Bestimmung Ende */ Set a = null; - UnifyPair a_rec = null; while (nextSetasList.size() > 0) { //(nextSetasList.size() != 0) { Set a_last = a; + + //Liste der Faelle für die parallele Verarbeitung List> nextSetasListRest = new ArrayList<>(); + + //Liste der Faelle, bei dem Receiver jeweils "? extends" enthaelt bzw. nicht enthaelt + //In der Regel ein Element List> nextSetasListOderConstraints = new ArrayList<>(); - //List> nextSetasListRestMin = new ArrayList<>(); - //List> nextSetasListRestOder = new ArrayList<>(); + writeLog("nextSet: " + nextSet.toString()); writeLog("nextSetasList: " + nextSetasList.toString()); if (variance == 1) { @@ -710,7 +713,7 @@ public class TypeUnifyTask extends RecursiveTask>> { if (oderConstraint) { nextSetasListOderConstraints.add(((Constraint)a).getExtendConstraint()); } - writeLog("nextSetasListOderConstraints: " + nextSetasListOderConstraints); + writeLog("nextSetasListOderConstraints 1: " + nextSetasListOderConstraints); nextSetasListRest = new ArrayList<>(nextSetasList); Iterator> nextSetasListItRest = new ArrayList>(nextSetasListRest).iterator(); while (nextSetasListItRest.hasNext()) { @@ -741,6 +744,10 @@ public class TypeUnifyTask extends RecursiveTask>> { else if (variance == -1) { a = oup.min(nextSetasList.iterator()); writeLog("Min: a in " + variance + " "+ a); + if (oderConstraint) { + nextSetasListOderConstraints.add(((Constraint)a).getExtendConstraint()); + } + writeLog("nextSetasListOderConstraints -1: " + nextSetasListOderConstraints); nextSetasList.remove(a); nextSetasListRest = new ArrayList<>(nextSetasList); Iterator> nextSetasListItRest = new ArrayList>(nextSetasListRest).iterator(); @@ -774,7 +781,20 @@ public class TypeUnifyTask extends RecursiveTask>> { nextSetasListRest = new ArrayList<>(nextSetasList); } else if (variance == 0) { - a = nextSetasList.remove(0); + //wenn a <. theta dann ist ein maximales Element sehr wahrscheinlich + //wenn theta <. a dann ist ein minimales Element sehr wahrscheinlich + if (!oderConstraint && optOrigPair != null && optOrigPair.isPresent()) { + if (optOrigPair.get().getBasePair().getLhsType() instanceof PlaceholderType) { + a = oup.max(nextSetasList.iterator()); + } + else { + a = oup.min(nextSetasList.iterator()); + } + nextSetasList.remove(a); + } + else { + a = nextSetasList.remove(0); + } } //writeLog("nextSet: " + nextSetasList.toString()+ "\n"); //nextSetasList.remove(a); @@ -898,7 +918,9 @@ public class TypeUnifyTask extends RecursiveTask>> { } } /* PL 2019-03-13 Ende eingefuegt Vergleich mit anderen Paaren ggf. loeschen */ - + else { + nextSetasListOderConstraints.add(((Constraint)nSaL).getExtendConstraint()); + } Set newEq = new HashSet<>(eq); Set> newElems = new HashSet<>(elems); List>> newOderConstraints = new ArrayList<>(oderConstraints); @@ -1006,7 +1028,9 @@ public class TypeUnifyTask extends RecursiveTask>> { } } /* PL 2019-03-13 Ende eingefuegt Vergleich mit anderen Paaren ggf. loeschen */ - + else { + nextSetasListOderConstraints.add(((Constraint)nSaL).getExtendConstraint()); + } Set newEq = new HashSet<>(eq); Set> newElems = new HashSet<>(elems); List>> newOderConstraints = new ArrayList<>(oderConstraints); @@ -1296,6 +1320,7 @@ public class TypeUnifyTask extends RecursiveTask>> { if (oderConstraint) { nextSetasList.removeAll(nextSetasListOderConstraints); nextSetasListOderConstraints = new ArrayList<>(); + writeLog("Removed: " + nextSetasListOderConstraints); while(aParDefIt.hasNext()) { Set a_new = aParDefIt.next(); List> smallerSetasList = oup.smallerThan(a_new, nextSetasList); @@ -1376,14 +1401,31 @@ public class TypeUnifyTask extends RecursiveTask>> { aParDef.add(a); Iterator> aParDefIt = aParDef.iterator(); if (oderConstraint) { + nextSetasList.removeAll(nextSetasListOderConstraints); + writeLog("Removed: " + nextSetasListOderConstraints); + nextSetasListOderConstraints = new ArrayList<>(); while(aParDefIt.hasNext()) { Set a_new = aParDefIt.next(); - List> greaterSetasList = oup.greaterThan(a_new, nextSetasList); + List> greaterSetasList = oup.greaterThan(a_new, nextSetasList); + + //a_new muss hingefuegt werden, wenn es nicht vererbt ist, dann wird es spaeter wieder geloescht + if (!((Constraint)a_new).isInherited()) { + greaterSetasList.add(a_new); + } List> notInherited = greaterSetasList.stream() .filter(x -> !((Constraint)x).isInherited()) .collect(Collectors.toCollection(ArrayList::new)); List> notErased = new ArrayList<>(); - notInherited.stream().forEach(x -> { notErased.addAll(oup.greaterThan(x, greaterSetasList)); }); + + //Wenn x nicht vererbt ist, beginnt beim naechstgroesseren Element die naechste Ueberladung + notInherited.stream().forEach(x -> { notErased.addAll(oup.greaterEqThan(x, greaterSetasList)); }); + + //das kleineste Element ist das Element von dem a_new geerbt hat + //muss deshalb geloescht werden + Set min = oup.min(notErased.iterator()); + notErased.remove(min); + notErased.remove(((Constraint)min).getExtendConstraint()); + List> erased = new ArrayList<>(greaterSetasList); erased.removeAll(notErased); nextSetasList.removeAll(erased); @@ -1393,7 +1435,7 @@ public class TypeUnifyTask extends RecursiveTask>> { writeLog("Not Removed: " + nextSetasList); } - } + } else { while(aParDefIt.hasNext()) { //nextSetasListIt = nextSetasList.iterator(); Sollte eingefuegt werden PL 2020-04-28 From 3de735ebe349b6306f7fec2f57cb5c1d569b4f50 Mon Sep 17 00:00:00 2001 From: "pl@gohorb.ba-horb.de" Date: Tue, 5 May 2020 18:06:05 +0200 Subject: [PATCH 66/81] modified: ../../../../main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java new file: ../../../java/bytecode/PutTest.java new file: ../../bytecode/javFiles/Put.jav --- .../typeinference/unify/TypeUnifyTask.java | 33 ++++- src/test/java/bytecode/PutTest.java | 130 ++++++++++++++++++ src/test/resources/bytecode/javFiles/Put.jav | 19 +++ 3 files changed, 180 insertions(+), 2 deletions(-) create mode 100644 src/test/java/bytecode/PutTest.java create mode 100644 src/test/resources/bytecode/javFiles/Put.jav diff --git a/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java b/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java index cc0fcbf1..0c093c5b 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java @@ -708,7 +708,7 @@ public class TypeUnifyTask extends RecursiveTask>> { writeLog("nextSet: " + nextSet.toString()); writeLog("nextSetasList: " + nextSetasList.toString()); if (variance == 1) { - Set a_final = a = oup.max(nextSetasList.iterator()); + a = oup.max(nextSetasList.iterator()); nextSetasList.remove(a); if (oderConstraint) { nextSetasListOderConstraints.add(((Constraint)a).getExtendConstraint()); @@ -793,7 +793,14 @@ public class TypeUnifyTask extends RecursiveTask>> { nextSetasList.remove(a); } else { - a = nextSetasList.remove(0); + if (oderConstraint) { + a = oup.max(nextSetasList.iterator()); + nextSetasList.remove(a); + nextSetasListOderConstraints.add(((Constraint)a).getExtendConstraint()); + } + else { + a = nextSetasList.remove(0); + } } } //writeLog("nextSet: " + nextSetasList.toString()+ "\n"); @@ -1471,9 +1478,31 @@ public class TypeUnifyTask extends RecursiveTask>> { break; } else { + nextSetasList.removeAll(nextSetasListOderConstraints); + nextSetasListOderConstraints = new ArrayList<>(); + writeLog("Removed: " + nextSetasListOderConstraints); + List> smallerSetasList = oup.smallerThan(a, nextSetasList); + List> notInherited = smallerSetasList.stream() + .filter(x -> !((Constraint)x).isInherited()) + .collect(Collectors.toCollection(ArrayList::new)); + List> notErased = new ArrayList<>(); + notInherited.stream().forEach(x -> { notErased.addAll(oup.smallerEqThan(x, smallerSetasList)); }); + List> erased = new ArrayList<>(smallerSetasList); + erased.removeAll(notErased); + nextSetasList.removeAll(erased); + + writeLog("Removed: " + erased); + + writeLog("Not Removed: " + nextSetasList); + + + + /* zu loeschen PL 2020-05-05 nextSetasList = nextSetasList.stream() .filter(x -> !((Constraint)x).isInherited()) .collect(Collectors.toCollection(ArrayList::new)); + */ + /* //TODO: Hier muessen alle kleineren und größeren Elemente von a geloescht werden writeLog("a: " + rekTiefe + " variance: " + variance + a.toString()); diff --git a/src/test/java/bytecode/PutTest.java b/src/test/java/bytecode/PutTest.java new file mode 100644 index 00000000..91ff6f11 --- /dev/null +++ b/src/test/java/bytecode/PutTest.java @@ -0,0 +1,130 @@ +package bytecode; + +import static org.junit.Assert.*; + +import java.io.File; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.net.URL; +import java.net.URLClassLoader; +import java.util.List; +import java.util.Stack; +import java.util.Vector; + +import org.junit.BeforeClass; +import org.junit.Test; + +import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.GenericGenratorResultForSourceFile; +import de.dhbwstuttgart.core.JavaTXCompiler; +import de.dhbwstuttgart.typeinference.result.ResultSet; + +public class PutTest { + private static String path; + private static File fileToTest; + private static JavaTXCompiler compiler; + private static ClassLoader loader; + private static Class classToTest; + private static Class classToTest1; + private static String pathToClassFile; + private static Object instanceOfClass; + private static Object instanceOfClass1; + + @BeforeClass + public static void setUpBeforeClass() throws Exception { + path = System.getProperty("user.dir")+"/src/test/resources/bytecode/javFiles/Put.jav"; + fileToTest = new File(path); + compiler = new JavaTXCompiler(fileToTest); + pathToClassFile = System.getProperty("user.dir")+"/src/test/resources/testBytecode/generatedBC/"; + List typeinferenceResult = compiler.typeInference(); + List simplifyResultsForAllSourceFiles = compiler.getGeneratedGenericResultsForAllSourceFiles(typeinferenceResult); + compiler.generateBytecode(new File(pathToClassFile),typeinferenceResult,simplifyResultsForAllSourceFiles); + loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); + classToTest = loader.loadClass("Put"); + instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); + classToTest1 = loader.loadClass("OLMain"); + instanceOfClass1 = classToTest1.getDeclaredConstructor().newInstance(); + } + + @Test + public void testPutClassName() { + assertEquals("Put", classToTest.getName()); + } + + @Test + public void testPutElementVector() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + Method m = classToTest.getDeclaredMethod("putElement", Object.class, Vector.class); + Vector v_invoke = new Vector<>(); + m.invoke(instanceOfClass, 5, v_invoke); + Vector v = new Vector<>(); + v.add(5); + assertEquals(v, v_invoke); + } + + @Test + public void testPutElementStack() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + Method m = classToTest.getDeclaredMethod("putElement", Object.class, Stack.class); + Stack s_invoke = new Stack<>(); + m.invoke(instanceOfClass, 5, s_invoke); + assertEquals(new Integer(5), s_invoke.pop()); + } + + @Test + public void testMainVector() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + Method m = classToTest.getDeclaredMethod("main", Object.class, Vector.class); + Vector v_invoke = new Vector<>(); + m.invoke(instanceOfClass, 6, v_invoke); + Vector v = new Vector<>(); + v.add(6); + assertEquals(v, v_invoke); + } + + @Test + public void testMainStack() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + Method m = classToTest.getDeclaredMethod("main", Object.class, Stack.class); + Stack s_invoke = new Stack<>(); + m.invoke(instanceOfClass, 6, s_invoke); + assertEquals(new Integer(6), s_invoke.pop()); + } + + /* + @Test + public void testmDouble() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + Method m = classToTest.getDeclaredMethod("m", Double.class); + Double result = (Double) m.invoke(instanceOfClass, 5.0); + assertEquals(new Double(10.0), result); + } + + @Test + public void testmString() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + Method m = classToTest.getDeclaredMethod("m", String.class); + String result = (String) m.invoke(instanceOfClass, "xxx"); + assertEquals("xxxxxx", result); + } + + @Test + public void testOLMainClassName() { + assertEquals("OLMain", classToTest1.getName()); + } + + @Test + public void testmainInt() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + Method main = classToTest1.getDeclaredMethod("main", Integer.class); + Integer result = (Integer) main.invoke(instanceOfClass1, 5); + assertEquals(new Integer(10), result); + } + + @Test + public void testmainDouble() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + Method main = classToTest1.getDeclaredMethod("main", Double.class); + Double result = (Double) main.invoke(instanceOfClass1, 5.0); + assertEquals(new Double(10.0), result); + } + + @Test + public void testmainString() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + Method main = classToTest1.getDeclaredMethod("main", String.class); + String result = (String) main.invoke(instanceOfClass1, "xxx"); + assertEquals("xxxxxx", result); + } + */ +} diff --git a/src/test/resources/bytecode/javFiles/Put.jav b/src/test/resources/bytecode/javFiles/Put.jav new file mode 100644 index 00000000..79a1cfa1 --- /dev/null +++ b/src/test/resources/bytecode/javFiles/Put.jav @@ -0,0 +1,19 @@ +import java.util.Vector; +import java.util.Stack; + +public class Put { + + putElement(ele, v) { + v.addElement(ele); + } + + putElement(ele, s) { + s.push(ele); + } + + + main(ele, x) { + putElement(ele, x); + } + +} \ No newline at end of file From ccf5df1f1e1288b8cfdab568b5f553d2c741871e Mon Sep 17 00:00:00 2001 From: "pl@gohorb.ba-horb.de" Date: Tue, 5 May 2020 18:43:39 +0200 Subject: [PATCH 67/81] new file: ../../../java/bytecode/InheritTest.java modified: ../../../java/bytecode/PutTest.java new file: ../../bytecode/javFiles/Inherit.jav --- src/test/java/bytecode/InheritTest.java | 94 +++++++++++++++++++ src/test/java/bytecode/PutTest.java | 44 --------- .../resources/bytecode/javFiles/Inherit.jav | 29 ++++++ 3 files changed, 123 insertions(+), 44 deletions(-) create mode 100644 src/test/java/bytecode/InheritTest.java create mode 100644 src/test/resources/bytecode/javFiles/Inherit.jav diff --git a/src/test/java/bytecode/InheritTest.java b/src/test/java/bytecode/InheritTest.java new file mode 100644 index 00000000..713d82f4 --- /dev/null +++ b/src/test/java/bytecode/InheritTest.java @@ -0,0 +1,94 @@ +package bytecode; + +import static org.junit.Assert.*; + +import java.io.File; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.net.URL; +import java.net.URLClassLoader; +import java.util.List; +import java.util.Stack; +import java.util.Vector; + +import org.junit.BeforeClass; +import org.junit.Test; + +import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.GenericGenratorResultForSourceFile; +import de.dhbwstuttgart.core.JavaTXCompiler; +import de.dhbwstuttgart.typeinference.result.ResultSet; + +public class InheritTest { + private static String path; + private static File fileToTest; + private static JavaTXCompiler compiler; + private static ClassLoader loader; + private static Class classToTest; + private static Class classToTest1; + private static String pathToClassFile; + private static Object instanceOfClass; + private static Object instanceOfClass1; + + @BeforeClass + public static void setUpBeforeClass() throws Exception { + path = System.getProperty("user.dir")+"/src/test/resources/bytecode/javFiles/Inherit.jav"; + fileToTest = new File(path); + compiler = new JavaTXCompiler(fileToTest); + pathToClassFile = System.getProperty("user.dir")+"/src/test/resources/testBytecode/generatedBC/"; + List typeinferenceResult = compiler.typeInference(); + List simplifyResultsForAllSourceFiles = compiler.getGeneratedGenericResultsForAllSourceFiles(typeinferenceResult); + compiler.generateBytecode(new File(pathToClassFile),typeinferenceResult,simplifyResultsForAllSourceFiles); + loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); + classToTest = loader.loadClass("Inherit"); + instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); + classToTest1 = loader.loadClass("A"); + instanceOfClass1 = classToTest1.getDeclaredConstructor().newInstance(); + } + + @Test + public void testInheritClassName() { + assertEquals("Inherit", classToTest.getName()); + } + + @Test + public void testAName() { + assertEquals("A", classToTest1.getName()); + } + /* + @Test + public void testPutElementVector() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + Method m = classToTest.getDeclaredMethod("putElement", Object.class, Vector.class); + Vector v_invoke = new Vector<>(); + m.invoke(instanceOfClass, 5, v_invoke); + Vector v = new Vector<>(); + v.add(5); + assertEquals(v, v_invoke); + } + + @Test + public void testPutElementStack() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + Method m = classToTest.getDeclaredMethod("putElement", Object.class, Stack.class); + Stack s_invoke = new Stack<>(); + m.invoke(instanceOfClass, 5, s_invoke); + assertEquals(new Integer(5), s_invoke.pop()); + } + + @Test + public void testMainVector() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + Method m = classToTest.getDeclaredMethod("main", Object.class, Vector.class); + Vector v_invoke = new Vector<>(); + m.invoke(instanceOfClass, 6, v_invoke); + Vector v = new Vector<>(); + v.add(6); + assertEquals(v, v_invoke); + } + + @Test + public void testMainStack() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + Method m = classToTest.getDeclaredMethod("main", Object.class, Stack.class); + Stack s_invoke = new Stack<>(); + m.invoke(instanceOfClass, 6, s_invoke); + assertEquals(new Integer(6), s_invoke.pop()); + } + */ +} diff --git a/src/test/java/bytecode/PutTest.java b/src/test/java/bytecode/PutTest.java index 91ff6f11..b5fd39d1 100644 --- a/src/test/java/bytecode/PutTest.java +++ b/src/test/java/bytecode/PutTest.java @@ -41,8 +41,6 @@ public class PutTest { loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); classToTest = loader.loadClass("Put"); instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); - classToTest1 = loader.loadClass("OLMain"); - instanceOfClass1 = classToTest1.getDeclaredConstructor().newInstance(); } @Test @@ -85,46 +83,4 @@ public class PutTest { m.invoke(instanceOfClass, 6, s_invoke); assertEquals(new Integer(6), s_invoke.pop()); } - - /* - @Test - public void testmDouble() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method m = classToTest.getDeclaredMethod("m", Double.class); - Double result = (Double) m.invoke(instanceOfClass, 5.0); - assertEquals(new Double(10.0), result); - } - - @Test - public void testmString() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method m = classToTest.getDeclaredMethod("m", String.class); - String result = (String) m.invoke(instanceOfClass, "xxx"); - assertEquals("xxxxxx", result); - } - - @Test - public void testOLMainClassName() { - assertEquals("OLMain", classToTest1.getName()); - } - - @Test - public void testmainInt() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method main = classToTest1.getDeclaredMethod("main", Integer.class); - Integer result = (Integer) main.invoke(instanceOfClass1, 5); - assertEquals(new Integer(10), result); - } - - @Test - public void testmainDouble() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method main = classToTest1.getDeclaredMethod("main", Double.class); - Double result = (Double) main.invoke(instanceOfClass1, 5.0); - assertEquals(new Double(10.0), result); - } - - @Test - public void testmainString() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method main = classToTest1.getDeclaredMethod("main", String.class); - String result = (String) main.invoke(instanceOfClass1, "xxx"); - assertEquals("xxxxxx", result); - } - */ } diff --git a/src/test/resources/bytecode/javFiles/Inherit.jav b/src/test/resources/bytecode/javFiles/Inherit.jav new file mode 100644 index 00000000..271c4edd --- /dev/null +++ b/src/test/resources/bytecode/javFiles/Inherit.jav @@ -0,0 +1,29 @@ +import java.lang.Integer; +import java.util.Vector; + +public class A { + m(Integer i) { } +} + +public class B extends A { } + +public class C extends B { + m(Integer i) { } +} + +public class D extends C { } + + + +public class Inherit { +/* + main(d, i) { + d.m(1); + } +*/ + + main(v, i) { + var aa = v.elementAt(0); + aa.m(1); + } +} \ No newline at end of file From ba750187ba587a2ffe253d9aa01ec59181a896b1 Mon Sep 17 00:00:00 2001 From: "pl@gohorb.ba-horb.de" Date: Wed, 6 May 2020 19:22:08 +0200 Subject: [PATCH 68/81] modified: ../src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java modified: ../src/main/java/de/dhbwstuttgart/typeinference/constraints/Constraint.java modified: ../src/test/java/bytecode/InheritTest.java new file: ../src/test/resources/bytecode/javFiles/AA.jav new file: ../src/test/resources/bytecode/javFiles/BB.jav new file: ../src/test/resources/bytecode/javFiles/CC.jav new file: ../src/test/resources/bytecode/javFiles/DD.jav modified: ../src/test/resources/bytecode/javFiles/Inherit.jav Inherit funktioniert noch nicht ganz --- .../de/dhbwstuttgart/core/JavaTXCompiler.java | 3 +- .../typeinference/constraints/Constraint.java | 5 +- src/test/java/bytecode/InheritTest.java | 51 +++++++++++++++++-- src/test/resources/bytecode/javFiles/AA.jav | 5 ++ src/test/resources/bytecode/javFiles/BB.jav | 3 ++ src/test/resources/bytecode/javFiles/CC.jav | 7 +++ src/test/resources/bytecode/javFiles/DD.jav | 4 ++ .../resources/bytecode/javFiles/Inherit.jav | 24 +++------ 8 files changed, 76 insertions(+), 26 deletions(-) create mode 100644 src/test/resources/bytecode/javFiles/AA.jav create mode 100644 src/test/resources/bytecode/javFiles/BB.jav create mode 100644 src/test/resources/bytecode/javFiles/CC.jav create mode 100644 src/test/resources/bytecode/javFiles/DD.jav diff --git a/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java b/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java index 4d4a2af2..beab7c06 100644 --- a/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java +++ b/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java @@ -177,6 +177,7 @@ public class JavaTXCompiler { gtvs.put(tvarVarIt.next().getName(), paraIt.next()); } Iterator methodIt = superclass.getMethods().iterator(); + //TODO: PL 2020-05-06: Hier müssen ueberschriebene Methoden noch rausgefiltert werden while(methodIt.hasNext()) { Method m = methodIt.next(); ParameterList newParaList = new ParameterList( @@ -975,7 +976,7 @@ public class JavaTXCompiler { @Override public RefTypeOrTPHOrWildcardOrGeneric visit(TypePlaceholder typePlaceholder) { - throw new DebugException("Dieser Fall darf nicht auftreten"); + return typePlaceholder; //TypePlaceholder der vererbert wird kann bei der Vererbung nicht instanziert werden. } @Override diff --git a/src/main/java/de/dhbwstuttgart/typeinference/constraints/Constraint.java b/src/main/java/de/dhbwstuttgart/typeinference/constraints/Constraint.java index 4b8de165..8715fe55 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/constraints/Constraint.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/constraints/Constraint.java @@ -41,8 +41,9 @@ public class Constraint extends HashSet { } public String toString() { - return super.toString() + " isInherited = " + isInherited + "\nextendsContraint: " + - (extendConstraint != null ? extendConstraint.toStringBase() : "null" ) + "\n" ; + return super.toString() + " isInherited = " + isInherited + //" + extendsContraint: " + (extendConstraint != null ? extendConstraint.toStringBase() : "null" ) + + "\n" ; } public String toStringBase() { diff --git a/src/test/java/bytecode/InheritTest.java b/src/test/java/bytecode/InheritTest.java index 713d82f4..7166c54e 100644 --- a/src/test/java/bytecode/InheritTest.java +++ b/src/test/java/bytecode/InheritTest.java @@ -31,18 +31,59 @@ public class InheritTest { @BeforeClass public static void setUpBeforeClass() throws Exception { - path = System.getProperty("user.dir")+"/src/test/resources/bytecode/javFiles/Inherit.jav"; + path = System.getProperty("user.dir")+"/src/test/resources/bytecode/javFiles/AA.jav"; fileToTest = new File(path); compiler = new JavaTXCompiler(fileToTest); - pathToClassFile = System.getProperty("user.dir")+"/src/test/resources/testBytecode/generatedBC/"; + pathToClassFile = System.getProperty("user.dir")+"/src/test/resources/bytecode/javFiles/"; List typeinferenceResult = compiler.typeInference(); List simplifyResultsForAllSourceFiles = compiler.getGeneratedGenericResultsForAllSourceFiles(typeinferenceResult); compiler.generateBytecode(new File(pathToClassFile),typeinferenceResult,simplifyResultsForAllSourceFiles); loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); + classToTest1 = loader.loadClass("AA"); + instanceOfClass1 = classToTest1.getDeclaredConstructor().newInstance(); + + path = System.getProperty("user.dir")+"/src/test/resources/bytecode/javFiles/BB.jav"; + fileToTest = new File(path); + compiler = new JavaTXCompiler(fileToTest); + pathToClassFile = System.getProperty("user.dir")+"/src/test/resources/bytecode/javFiles/"; + typeinferenceResult = compiler.typeInference(); + simplifyResultsForAllSourceFiles = compiler.getGeneratedGenericResultsForAllSourceFiles(typeinferenceResult); + compiler.generateBytecode(new File(pathToClassFile),typeinferenceResult,simplifyResultsForAllSourceFiles); + loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); + classToTest1 = loader.loadClass("AA"); + instanceOfClass1 = classToTest1.getDeclaredConstructor().newInstance(); + + path = System.getProperty("user.dir")+"/src/test/resources/bytecode/javFiles/CC.jav"; + fileToTest = new File(path); + compiler = new JavaTXCompiler(fileToTest); + pathToClassFile = System.getProperty("user.dir")+"/src/test/resources/bytecode/javFiles/"; + typeinferenceResult = compiler.typeInference(); + simplifyResultsForAllSourceFiles = compiler.getGeneratedGenericResultsForAllSourceFiles(typeinferenceResult); + compiler.generateBytecode(new File(pathToClassFile),typeinferenceResult,simplifyResultsForAllSourceFiles); + loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); + classToTest1 = loader.loadClass("AA"); + instanceOfClass1 = classToTest1.getDeclaredConstructor().newInstance(); + + path = System.getProperty("user.dir")+"/src/test/resources/bytecode/javFiles/DD.jav"; + fileToTest = new File(path); + compiler = new JavaTXCompiler(fileToTest); + pathToClassFile = System.getProperty("user.dir")+"/src/test/resources/bytecode/javFiles/"; + typeinferenceResult = compiler.typeInference(); + simplifyResultsForAllSourceFiles = compiler.getGeneratedGenericResultsForAllSourceFiles(typeinferenceResult); + compiler.generateBytecode(new File(pathToClassFile),typeinferenceResult,simplifyResultsForAllSourceFiles); + loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); + classToTest1 = loader.loadClass("AA"); + instanceOfClass1 = classToTest1.getDeclaredConstructor().newInstance(); + path = System.getProperty("user.dir")+"/src/test/resources/bytecode/javFiles/Inherit.jav"; + fileToTest = new File(path); + compiler = new JavaTXCompiler(fileToTest); + pathToClassFile = System.getProperty("user.dir")+"/src/test/resources/testBytecode/generatedBC/"; + typeinferenceResult = compiler.typeInference(); + simplifyResultsForAllSourceFiles = compiler.getGeneratedGenericResultsForAllSourceFiles(typeinferenceResult); + compiler.generateBytecode(new File(pathToClassFile),typeinferenceResult,simplifyResultsForAllSourceFiles); + loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); classToTest = loader.loadClass("Inherit"); instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); - classToTest1 = loader.loadClass("A"); - instanceOfClass1 = classToTest1.getDeclaredConstructor().newInstance(); } @Test @@ -52,7 +93,7 @@ public class InheritTest { @Test public void testAName() { - assertEquals("A", classToTest1.getName()); + assertEquals("AA", classToTest1.getName()); } /* @Test diff --git a/src/test/resources/bytecode/javFiles/AA.jav b/src/test/resources/bytecode/javFiles/AA.jav new file mode 100644 index 00000000..aee2d5de --- /dev/null +++ b/src/test/resources/bytecode/javFiles/AA.jav @@ -0,0 +1,5 @@ +import java.lang.Integer; + +public class AA { + m(Integer i) { } +} \ No newline at end of file diff --git a/src/test/resources/bytecode/javFiles/BB.jav b/src/test/resources/bytecode/javFiles/BB.jav new file mode 100644 index 00000000..27856c42 --- /dev/null +++ b/src/test/resources/bytecode/javFiles/BB.jav @@ -0,0 +1,3 @@ +import java.lang.Integer; + +public class BB extends AA { } \ No newline at end of file diff --git a/src/test/resources/bytecode/javFiles/CC.jav b/src/test/resources/bytecode/javFiles/CC.jav new file mode 100644 index 00000000..af5a4000 --- /dev/null +++ b/src/test/resources/bytecode/javFiles/CC.jav @@ -0,0 +1,7 @@ +import java.lang.Integer; + + + +public class CC extends BB { + m(Integer i) { } +} diff --git a/src/test/resources/bytecode/javFiles/DD.jav b/src/test/resources/bytecode/javFiles/DD.jav new file mode 100644 index 00000000..6d49f4c7 --- /dev/null +++ b/src/test/resources/bytecode/javFiles/DD.jav @@ -0,0 +1,4 @@ +import java.lang.Integer; + +public class DD extends CC { } + diff --git a/src/test/resources/bytecode/javFiles/Inherit.jav b/src/test/resources/bytecode/javFiles/Inherit.jav index 271c4edd..4f13c94e 100644 --- a/src/test/resources/bytecode/javFiles/Inherit.jav +++ b/src/test/resources/bytecode/javFiles/Inherit.jav @@ -1,29 +1,17 @@ -import java.lang.Integer; import java.util.Vector; -public class A { - m(Integer i) { } -} - -public class B extends A { } - -public class C extends B { - m(Integer i) { } -} - -public class D extends C { } - +import java.lang.Integer; public class Inherit { -/* + main(d, i) { - d.m(1); + d.m(i); } -*/ - + main(v, i) { var aa = v.elementAt(0); - aa.m(1); + aa.m(i); } + } \ No newline at end of file From 71c801c19ce5f6126d9b6a13cedb9397078a16c2 Mon Sep 17 00:00:00 2001 From: "pl@gohorb.ba-horb.de" Date: Wed, 6 May 2020 19:25:19 +0200 Subject: [PATCH 69/81] modified: ../src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java --- .../de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java b/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java index 0c093c5b..3a8d5e3e 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java @@ -2040,6 +2040,8 @@ public class TypeUnifyTask extends RecursiveTask>> { oderConstraintsOutput.remove(ret); //Set retFlat = new HashSet<>(); //ret.stream().forEach(x -> retFlat.addAll(x)); + + //Alle wildcard Faelle rausfiltern bei not wildable ret = ret.stream().filter(x -> { Optional optElem; return !((optElem=x.stream().filter(y -> (y.getLhsType()) instanceof PlaceholderType && !((PlaceholderType)y.getLhsType()).isWildcardable() @@ -2076,6 +2078,8 @@ public class TypeUnifyTask extends RecursiveTask>> { // System.out.println("M"); //Set retFlat = new HashSet<>(); //ret.stream().forEach(x -> retFlat.addAll(x)); + + //Alle wildcard Faelle rausfiltern bei not wildable ret = ret.stream().filter(x -> { Optional optElem; return !((optElem=x.stream().filter(y -> (y.getLhsType()) instanceof PlaceholderType && !((PlaceholderType)y.getLhsType()).isWildcardable() From eb270035152a2162de76d9352c6ba333e4c92aaa Mon Sep 17 00:00:00 2001 From: "pl@gohorb.ba-horb.de" Date: Thu, 7 May 2020 16:29:00 +0200 Subject: [PATCH 70/81] modified: ../../../../main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java modified: ../../../../main/java/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java modified: ../../../../main/java/de/dhbwstuttgart/typeinference/unify/model/Node.java Fehler in der Transitivaet der Finit Closure gefixt modified: ../../../java/bytecode/InheritTest.java modified: ../../bytecode/javFiles/AA.jav modified: ../../bytecode/javFiles/CC.jav modified: ../../bytecode/javFiles/Inherit.jav Noch Probl;em in der Reflections --- .../typeinference/unify/TypeUnifyTask.java | 4 +- .../unify/model/FiniteClosure.java | 15 +++- .../typeinference/unify/model/Node.java | 18 +++++ src/test/java/bytecode/InheritTest.java | 76 ++++++++++++++----- src/test/resources/bytecode/javFiles/AA.jav | 3 +- src/test/resources/bytecode/javFiles/CC.jav | 4 +- .../resources/bytecode/javFiles/Inherit.jav | 5 +- 7 files changed, 96 insertions(+), 29 deletions(-) diff --git a/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java b/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java index 3a8d5e3e..9be3c74d 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java @@ -2041,7 +2041,7 @@ public class TypeUnifyTask extends RecursiveTask>> { //Set retFlat = new HashSet<>(); //ret.stream().forEach(x -> retFlat.addAll(x)); - //Alle wildcard Faelle rausfiltern bei not wildable + //Alle wildcard Faelle rausfiltern bei not wildcardable ret = ret.stream().filter(x -> { Optional optElem; return !((optElem=x.stream().filter(y -> (y.getLhsType()) instanceof PlaceholderType && !((PlaceholderType)y.getLhsType()).isWildcardable() @@ -2079,7 +2079,7 @@ public class TypeUnifyTask extends RecursiveTask>> { //Set retFlat = new HashSet<>(); //ret.stream().forEach(x -> retFlat.addAll(x)); - //Alle wildcard Faelle rausfiltern bei not wildable + //Alle wildcard Faelle rausfiltern bei not wildcardable ret = ret.stream().filter(x -> { Optional optElem; return !((optElem=x.stream().filter(y -> (y.getLhsType()) instanceof PlaceholderType && !((PlaceholderType)y.getLhsType()).isWildcardable() diff --git a/src/main/java/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java b/src/main/java/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java index 3a86af14..038f308e 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java @@ -75,6 +75,15 @@ implements IFiniteClosure { // Build the transitive closure of the inheritance tree for(UnifyPair pair : pairs) { + + try { + logFile.write("Pair: " + pair + "\n"); + logFile.flush(); + } + catch (IOException e) { + System.err.println("no LogFile"); + } + if(pair.getPairOp() != PairOperator.SMALLER) continue; @@ -93,13 +102,17 @@ implements IFiniteClosure { Node childNode = inheritanceGraph.get(pair.getLhsType()); Node parentNode = inheritanceGraph.get(pair.getRhsType()); - + // Add edge parentNode.addDescendant(childNode); // Add edges to build the transitive closure parentNode.getPredecessors().stream().forEach(x -> x.addDescendant(childNode)); childNode.getDescendants().stream().forEach(x -> x.addPredecessor(parentNode)); + + //PL eingefuegt 2020-05-07 File UnitTest InheritTest.java + this.inheritanceGraph.forEach((x,y) -> { if (y.getDescendants().contains(parentNode)) { y.addDescendant(childNode); y.addAllDescendant(childNode.getDescendants());}; + if (y.getPredecessors().contains(childNode)) { y.addPredecessor(parentNode); y.addAllPredecessor(parentNode.getPredecessors());};} ); } // Build the alternative representation with strings as keys diff --git a/src/main/java/de/dhbwstuttgart/typeinference/unify/model/Node.java b/src/main/java/de/dhbwstuttgart/typeinference/unify/model/Node.java index d108e91b..031130cf 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/unify/model/Node.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/unify/model/Node.java @@ -45,6 +45,15 @@ class Node { descendant.addPredecessor(this); } + /** + * Adds some directed edges from this node to the descendant (this -> descendant) + */ + public void addAllDescendant(Set> allDescendants) { + for(Node descendant: allDescendants) { + addDescendant(descendant); + } + } + /** * Adds a directed edge from the predecessor to this node (predecessor -> this) */ @@ -56,6 +65,15 @@ class Node { predecessor.addDescendant(this); } + /** + * Adds some directed edges from the predecessor to this node (predecessor -> this) + */ + public void addAllPredecessor(Set> allPredecessors) { + for(Node predecessor: allPredecessors) { + addPredecessor(predecessor); + } + } + /** * The content of this node. */ diff --git a/src/test/java/bytecode/InheritTest.java b/src/test/java/bytecode/InheritTest.java index 7166c54e..5d9bb231 100644 --- a/src/test/java/bytecode/InheritTest.java +++ b/src/test/java/bytecode/InheritTest.java @@ -7,13 +7,19 @@ import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.URL; import java.net.URLClassLoader; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; import java.util.List; import java.util.Stack; import java.util.Vector; +import java.util.stream.Collectors; import org.junit.BeforeClass; import org.junit.Test; +import com.google.common.collect.Lists; + import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.GenericGenratorResultForSourceFile; import de.dhbwstuttgart.core.JavaTXCompiler; import de.dhbwstuttgart.typeinference.result.ResultSet; @@ -24,17 +30,17 @@ public class InheritTest { private static JavaTXCompiler compiler; private static ClassLoader loader; private static Class classToTest; - private static Class classToTest1; - private static String pathToClassFile; + private static Class classToTest1, classToTest2, classToTest3, classToTest4; + private static String pathToClassFile = System.getProperty("user.dir")+"/src/test/resources/bytecode/javFiles/";; private static Object instanceOfClass; - private static Object instanceOfClass1; + private static Object instanceOfClass1, instanceOfClass2, instanceOfClass3, instanceOfClass4; + private static HashMap, Method> hm = new HashMap<>(); @BeforeClass public static void setUpBeforeClass() throws Exception { path = System.getProperty("user.dir")+"/src/test/resources/bytecode/javFiles/AA.jav"; fileToTest = new File(path); compiler = new JavaTXCompiler(fileToTest); - pathToClassFile = System.getProperty("user.dir")+"/src/test/resources/bytecode/javFiles/"; List typeinferenceResult = compiler.typeInference(); List simplifyResultsForAllSourceFiles = compiler.getGeneratedGenericResultsForAllSourceFiles(typeinferenceResult); compiler.generateBytecode(new File(pathToClassFile),typeinferenceResult,simplifyResultsForAllSourceFiles); @@ -45,45 +51,53 @@ public class InheritTest { path = System.getProperty("user.dir")+"/src/test/resources/bytecode/javFiles/BB.jav"; fileToTest = new File(path); compiler = new JavaTXCompiler(fileToTest); - pathToClassFile = System.getProperty("user.dir")+"/src/test/resources/bytecode/javFiles/"; typeinferenceResult = compiler.typeInference(); simplifyResultsForAllSourceFiles = compiler.getGeneratedGenericResultsForAllSourceFiles(typeinferenceResult); compiler.generateBytecode(new File(pathToClassFile),typeinferenceResult,simplifyResultsForAllSourceFiles); loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); - classToTest1 = loader.loadClass("AA"); - instanceOfClass1 = classToTest1.getDeclaredConstructor().newInstance(); + classToTest2 = loader.loadClass("BB"); + instanceOfClass2 = classToTest1.getDeclaredConstructor().newInstance(); path = System.getProperty("user.dir")+"/src/test/resources/bytecode/javFiles/CC.jav"; fileToTest = new File(path); compiler = new JavaTXCompiler(fileToTest); - pathToClassFile = System.getProperty("user.dir")+"/src/test/resources/bytecode/javFiles/"; typeinferenceResult = compiler.typeInference(); simplifyResultsForAllSourceFiles = compiler.getGeneratedGenericResultsForAllSourceFiles(typeinferenceResult); compiler.generateBytecode(new File(pathToClassFile),typeinferenceResult,simplifyResultsForAllSourceFiles); loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); - classToTest1 = loader.loadClass("AA"); - instanceOfClass1 = classToTest1.getDeclaredConstructor().newInstance(); + classToTest3 = loader.loadClass("CC"); + instanceOfClass3 = classToTest1.getDeclaredConstructor().newInstance(); path = System.getProperty("user.dir")+"/src/test/resources/bytecode/javFiles/DD.jav"; fileToTest = new File(path); compiler = new JavaTXCompiler(fileToTest); - pathToClassFile = System.getProperty("user.dir")+"/src/test/resources/bytecode/javFiles/"; typeinferenceResult = compiler.typeInference(); simplifyResultsForAllSourceFiles = compiler.getGeneratedGenericResultsForAllSourceFiles(typeinferenceResult); compiler.generateBytecode(new File(pathToClassFile),typeinferenceResult,simplifyResultsForAllSourceFiles); loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); - classToTest1 = loader.loadClass("AA"); - instanceOfClass1 = classToTest1.getDeclaredConstructor().newInstance(); + classToTest4 = loader.loadClass("DD"); + instanceOfClass4 = classToTest1.getDeclaredConstructor().newInstance(); + path = System.getProperty("user.dir")+"/src/test/resources/bytecode/javFiles/Inherit.jav"; fileToTest = new File(path); - compiler = new JavaTXCompiler(fileToTest); - pathToClassFile = System.getProperty("user.dir")+"/src/test/resources/testBytecode/generatedBC/"; + compiler = new JavaTXCompiler( + Lists.newArrayList(fileToTest), + Lists.newArrayList(new File(pathToClassFile))); + //compiler = new JavaTXCompiler(fileToTest); typeinferenceResult = compiler.typeInference(); simplifyResultsForAllSourceFiles = compiler.getGeneratedGenericResultsForAllSourceFiles(typeinferenceResult); compiler.generateBytecode(new File(pathToClassFile),typeinferenceResult,simplifyResultsForAllSourceFiles); loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); classToTest = loader.loadClass("Inherit"); instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); + + for (Method m: classToTest.getMethods()) { + ArrayList param = Arrays.stream(m.getParameterTypes()).map(x -> x.getName()).collect(Collectors.toCollection(ArrayList::new)); + ArrayList nameParam = new ArrayList<>(); + nameParam.add(m.getName()); + nameParam.addAll(param); + hm.put(nameParam, m); + } } @Test @@ -92,15 +106,35 @@ public class InheritTest { } @Test - public void testAName() { + public void testAAName() { assertEquals("AA", classToTest1.getName()); } - /* + @Test - public void testPutElementVector() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method m = classToTest.getDeclaredMethod("putElement", Object.class, Vector.class); - Vector v_invoke = new Vector<>(); - m.invoke(instanceOfClass, 5, v_invoke); + public void testBBName() { + assertEquals("BB", classToTest2.getName()); + } + + @Test + public void testCCName() { + assertEquals("CC", classToTest3.getName()); + } + + @Test + public void testDDName() { + assertEquals("DD", classToTest4.getName()); + } + + + @Test + public void testmainAA() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException { + String[] x = {"main", "AA", "java.lang.Integer"}; + ArrayList nameParam = new ArrayList<>(Arrays.asList(x)); + Method m = hm.get(nameParam); + assertEquals(m.invoke(classToTest1.getConstructor().newInstance(), 5), "AA"); + } + /* + Vector v_invoke = new Vector<>(); Vector v = new Vector<>(); v.add(5); assertEquals(v, v_invoke); diff --git a/src/test/resources/bytecode/javFiles/AA.jav b/src/test/resources/bytecode/javFiles/AA.jav index aee2d5de..4593fdfb 100644 --- a/src/test/resources/bytecode/javFiles/AA.jav +++ b/src/test/resources/bytecode/javFiles/AA.jav @@ -1,5 +1,6 @@ import java.lang.Integer; +import java.lang.String; public class AA { - m(Integer i) { } + m(Integer i) { return "AA"; } } \ No newline at end of file diff --git a/src/test/resources/bytecode/javFiles/CC.jav b/src/test/resources/bytecode/javFiles/CC.jav index af5a4000..4523dfda 100644 --- a/src/test/resources/bytecode/javFiles/CC.jav +++ b/src/test/resources/bytecode/javFiles/CC.jav @@ -1,7 +1,7 @@ import java.lang.Integer; - +import java.lang.String; public class CC extends BB { - m(Integer i) { } + m(Integer i) { return "CC"; } } diff --git a/src/test/resources/bytecode/javFiles/Inherit.jav b/src/test/resources/bytecode/javFiles/Inherit.jav index 4f13c94e..bf677af9 100644 --- a/src/test/resources/bytecode/javFiles/Inherit.jav +++ b/src/test/resources/bytecode/javFiles/Inherit.jav @@ -1,17 +1,18 @@ import java.util.Vector; import java.lang.Integer; +import java.lang.String; public class Inherit { main(d, i) { - d.m(i); + return d.m(i); } main(v, i) { var aa = v.elementAt(0); - aa.m(i); + return aa.m(i); } } \ No newline at end of file From 907ab2fcec6e92e970f5c2f865e67ef2ee19c969 Mon Sep 17 00:00:00 2001 From: "pl@gohorb.ba-horb.de" Date: Fri, 8 May 2020 10:19:00 +0200 Subject: [PATCH 71/81] modified: ../../../java/bytecode/InheritTest.java modified: ../../bytecode/javFiles/Inherit.jav --- src/test/java/bytecode/InheritTest.java | 63 +++++++++++-------- .../resources/bytecode/javFiles/Inherit.jav | 2 + 2 files changed, 40 insertions(+), 25 deletions(-) diff --git a/src/test/java/bytecode/InheritTest.java b/src/test/java/bytecode/InheritTest.java index 5d9bb231..86181bf6 100644 --- a/src/test/java/bytecode/InheritTest.java +++ b/src/test/java/bytecode/InheritTest.java @@ -5,6 +5,7 @@ import static org.junit.Assert.*; import java.io.File; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; +import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; @@ -30,14 +31,16 @@ public class InheritTest { private static JavaTXCompiler compiler; private static ClassLoader loader; private static Class classToTest; - private static Class classToTest1, classToTest2, classToTest3, classToTest4; + private static Class classToTestAA, classToTestBB, classToTestCC, classToTestDD; private static String pathToClassFile = System.getProperty("user.dir")+"/src/test/resources/bytecode/javFiles/";; + //private static String pathToClassFile1 = System.getProperty("user.dir") + "/src/test/resources/testBytecode/generatedBC/"; private static Object instanceOfClass; - private static Object instanceOfClass1, instanceOfClass2, instanceOfClass3, instanceOfClass4; + private static Object instanceOfClassAA, instanceOfClassBB, instanceOfClassCC, instanceOfClassDD; private static HashMap, Method> hm = new HashMap<>(); @BeforeClass public static void setUpBeforeClass() throws Exception { + path = System.getProperty("user.dir")+"/src/test/resources/bytecode/javFiles/AA.jav"; fileToTest = new File(path); compiler = new JavaTXCompiler(fileToTest); @@ -45,9 +48,10 @@ public class InheritTest { List simplifyResultsForAllSourceFiles = compiler.getGeneratedGenericResultsForAllSourceFiles(typeinferenceResult); compiler.generateBytecode(new File(pathToClassFile),typeinferenceResult,simplifyResultsForAllSourceFiles); loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); - classToTest1 = loader.loadClass("AA"); - instanceOfClass1 = classToTest1.getDeclaredConstructor().newInstance(); + classToTestAA = loader.loadClass("AA"); + instanceOfClassAA = classToTestAA.getDeclaredConstructor().newInstance(); + /* path = System.getProperty("user.dir")+"/src/test/resources/bytecode/javFiles/BB.jav"; fileToTest = new File(path); compiler = new JavaTXCompiler(fileToTest); @@ -55,8 +59,8 @@ public class InheritTest { simplifyResultsForAllSourceFiles = compiler.getGeneratedGenericResultsForAllSourceFiles(typeinferenceResult); compiler.generateBytecode(new File(pathToClassFile),typeinferenceResult,simplifyResultsForAllSourceFiles); loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); - classToTest2 = loader.loadClass("BB"); - instanceOfClass2 = classToTest1.getDeclaredConstructor().newInstance(); + classToTestBB = loader.loadClass("BB"); + instanceOfClassBB = classToTestBB.getDeclaredConstructor().newInstance(); path = System.getProperty("user.dir")+"/src/test/resources/bytecode/javFiles/CC.jav"; fileToTest = new File(path); @@ -65,8 +69,8 @@ public class InheritTest { simplifyResultsForAllSourceFiles = compiler.getGeneratedGenericResultsForAllSourceFiles(typeinferenceResult); compiler.generateBytecode(new File(pathToClassFile),typeinferenceResult,simplifyResultsForAllSourceFiles); loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); - classToTest3 = loader.loadClass("CC"); - instanceOfClass3 = classToTest1.getDeclaredConstructor().newInstance(); + classToTestCC = loader.loadClass("CC"); + instanceOfClassCC = classToTestCC.getDeclaredConstructor().newInstance(); path = System.getProperty("user.dir")+"/src/test/resources/bytecode/javFiles/DD.jav"; fileToTest = new File(path); @@ -75,15 +79,18 @@ public class InheritTest { simplifyResultsForAllSourceFiles = compiler.getGeneratedGenericResultsForAllSourceFiles(typeinferenceResult); compiler.generateBytecode(new File(pathToClassFile),typeinferenceResult,simplifyResultsForAllSourceFiles); loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); - classToTest4 = loader.loadClass("DD"); - instanceOfClass4 = classToTest1.getDeclaredConstructor().newInstance(); + classToTestDD = loader.loadClass("DD"); + instanceOfClassDD = classToTestDD.getDeclaredConstructor().newInstance(); + */ path = System.getProperty("user.dir")+"/src/test/resources/bytecode/javFiles/Inherit.jav"; fileToTest = new File(path); + compiler = new JavaTXCompiler(fileToTest); + /* compiler = new JavaTXCompiler( Lists.newArrayList(fileToTest), - Lists.newArrayList(new File(pathToClassFile))); - //compiler = new JavaTXCompiler(fileToTest); + Lists.newArrayList(new File(pathToClassFile1))); + */ typeinferenceResult = compiler.typeInference(); simplifyResultsForAllSourceFiles = compiler.getGeneratedGenericResultsForAllSourceFiles(typeinferenceResult); compiler.generateBytecode(new File(pathToClassFile),typeinferenceResult,simplifyResultsForAllSourceFiles); @@ -91,6 +98,7 @@ public class InheritTest { classToTest = loader.loadClass("Inherit"); instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); + /* for (Method m: classToTest.getMethods()) { ArrayList param = Arrays.stream(m.getParameterTypes()).map(x -> x.getName()).collect(Collectors.toCollection(ArrayList::new)); ArrayList nameParam = new ArrayList<>(); @@ -98,6 +106,7 @@ public class InheritTest { nameParam.addAll(param); hm.put(nameParam, m); } + */ } @Test @@ -105,33 +114,37 @@ public class InheritTest { assertEquals("Inherit", classToTest.getName()); } - @Test - public void testAAName() { - assertEquals("AA", classToTest1.getName()); - } + @Test + public void testAAName() { + assertEquals("AA", classToTestAA.getName()); + } + + /* @Test public void testBBName() { - assertEquals("BB", classToTest2.getName()); + assertEquals("BB", classToTestBB.getName()); } @Test public void testCCName() { - assertEquals("CC", classToTest3.getName()); + assertEquals("CC", classToTestCC.getName()); } @Test public void testDDName() { - assertEquals("DD", classToTest4.getName()); + assertEquals("DD", classToTestDD.getName()); } - + */ @Test - public void testmainAA() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException { - String[] x = {"main", "AA", "java.lang.Integer"}; - ArrayList nameParam = new ArrayList<>(Arrays.asList(x)); - Method m = hm.get(nameParam); - assertEquals(m.invoke(classToTest1.getConstructor().newInstance(), 5), "AA"); + public void testmainAA() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException, MalformedURLException, ClassNotFoundException { + loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); + classToTest = loader.loadClass("Inherit"); + Method m = classToTestAA.getDeclaredMethod("m", Integer.class); + assertEquals(m.invoke(instanceOfClassAA, 5), "AA"); + Method main = classToTest.getDeclaredMethod("main", classToTestAA, Integer.class); + assertEquals(main.invoke(instanceOfClass, instanceOfClassAA, 5), "AA"); } /* Vector v_invoke = new Vector<>(); diff --git a/src/test/resources/bytecode/javFiles/Inherit.jav b/src/test/resources/bytecode/javFiles/Inherit.jav index bf677af9..0ef9c020 100644 --- a/src/test/resources/bytecode/javFiles/Inherit.jav +++ b/src/test/resources/bytecode/javFiles/Inherit.jav @@ -6,6 +6,8 @@ import java.lang.String; public class Inherit { + //m(Integer i) { return "AA"; } + main(d, i) { return d.m(i); } From 8e2d4e1c7080496efd3aa5e0bb2b1d56581c87b3 Mon Sep 17 00:00:00 2001 From: "pl@gohorb.ba-horb.de" Date: Fri, 8 May 2020 11:04:05 +0200 Subject: [PATCH 72/81] modified: ../src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java new file: ../src/main/java/de/dhbwstuttgart/typeinference/unify/model/OrderingExtend.java --- .../typeinference/unify/TypeUnifyTask.java | 7 +- .../unify/model/OrderingExtend.java | 89 +++++++++++++++++++ 2 files changed, 94 insertions(+), 2 deletions(-) create mode 100644 src/main/java/de/dhbwstuttgart/typeinference/unify/model/OrderingExtend.java diff --git a/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java b/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java index 9be3c74d..2d63eafd 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java @@ -723,6 +723,8 @@ public class TypeUnifyTask extends RecursiveTask>> { nextSetasListRest.remove(a_next); } } + + List> maxElementsTest = oup.maxElements(nextSetasListRest); //Alle maximale Elemente in nextSetasListRest bestimmen List> nextSetasListRestTest; do { @@ -739,7 +741,7 @@ public class TypeUnifyTask extends RecursiveTask>> { }} } while(!nextSetasListRestTest.equals(nextSetasListRest)); - + writeLog("maxElementsTest: " + maxElementsTest.equals(nextSetasListRest)); } else if (variance == -1) { a = oup.min(nextSetasList.iterator()); @@ -759,7 +761,7 @@ public class TypeUnifyTask extends RecursiveTask>> { } } //Alle minimalen Elemente in nextSetasListRest bestimmen - + List> minElementsTest = oup.minElements(nextSetasListRest); List> nextSetasListRestTest; do { nextSetasListRestTest = new ArrayList>(nextSetasListRest); @@ -775,6 +777,7 @@ public class TypeUnifyTask extends RecursiveTask>> { }} } while(!nextSetasListRestTest.equals(nextSetasListRest)); + writeLog("minElementsTest: " + minElementsTest.equals(nextSetasListRest)); } else if (variance == 2) { a = nextSetasList.remove(0); diff --git a/src/main/java/de/dhbwstuttgart/typeinference/unify/model/OrderingExtend.java b/src/main/java/de/dhbwstuttgart/typeinference/unify/model/OrderingExtend.java new file mode 100644 index 00000000..8fa32343 --- /dev/null +++ b/src/main/java/de/dhbwstuttgart/typeinference/unify/model/OrderingExtend.java @@ -0,0 +1,89 @@ +package de.dhbwstuttgart.typeinference.unify.model; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Set; + +public abstract class OrderingExtend extends com.google.common.collect.Ordering { + + public List maxElements(Iterable iterable) { + ArrayList ret = new ArrayList<>(); + while (iterable.iterator().hasNext()) { + Set believe = new HashSet<>(); + + T max = max(iterable); + ret.add(max); + + Iterator it = iterable.iterator(); + while (it.hasNext()) { + T elem = it.next(); + if (!(compare(max, elem) == 1) && !max.equals(elem)) { + believe.add(elem); + } + } + iterable = believe; + } + return ret; + } + + public List minElements(Iterable iterable) { + ArrayList ret = new ArrayList<>(); + while (iterable.iterator().hasNext()) { + Set believe = new HashSet<>(); + + T min = min(iterable); + ret.add(min); + + Iterator it = iterable.iterator(); + while (it.hasNext()) { + T elem = it.next(); + if (!(compare(min, elem) == -1) && !min.equals(elem)) { + believe.add(elem); + } + } + iterable = believe; + } + return ret; + } + + + public List smallerEqThan(T elem, Iterable iterable) { + List ret = smallerThan(elem, iterable); + ret.add(elem); + return ret; + + } + + public List smallerThan(T elem, Iterable iterable) { + ArrayList ret = new ArrayList<>(); + Iterator it = iterable.iterator(); + while (it.hasNext()) { + T itElem = it.next(); + if (!itElem.equals(elem) && compare(elem, itElem) == 1) { + ret.add(itElem); + } + } + return ret; + } + + public List greaterEqThan(T elem, Iterable iterable) { + List ret = greaterThan(elem, iterable); + ret.add(elem); + return ret; + + } + + public List greaterThan(T elem, Iterable iterable) { + ArrayList ret = new ArrayList<>(); + Iterator it = iterable.iterator(); + while (it.hasNext()) { + T itElem = it.next(); + if (!itElem.equals(elem) && (compare(elem, itElem) == -1)) { + ret.add(itElem); + } + } + return ret; + } +} From 60b182b9b1578f5d0041831c4d48db7c3a6074c4 Mon Sep 17 00:00:00 2001 From: JanUlrich Date: Fri, 8 May 2020 11:26:07 +0200 Subject: [PATCH 73/81] =?UTF-8?q?Kleiner=20Hack=20f=C3=BCr=20Inherit=20tes?= =?UTF-8?q?t?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pom.xml | 4 ++-- src/test/java/bytecode/InheritTest.java | 3 ++- src/test/resources/bytecode/javFiles/Inherit.jav | 1 + 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/pom.xml b/pom.xml index ef0f4502..833b4270 100644 --- a/pom.xml +++ b/pom.xml @@ -75,7 +75,7 @@ http://maven.apache.org/maven-v4_0_0.xsd"> src/main/antlr4/java8 - ${project.basedir}/target/generated-sources/antlr4/de/dhbwstuttgart/parser/antlr + ${project.basedir}/src/main/java/de/dhbwstuttgart/parser/antlr -package de.dhbwstuttgart.parser.antlr @@ -89,7 +89,7 @@ http://maven.apache.org/maven-v4_0_0.xsd"> src/main/antlr4/sat - ${project.basedir}/target/generated-sources/antlr4/de/dhbwstuttgart/sat/asp/parser/antlr + ${project.basedir}/src/main/java/de/dhbwstuttgart/sat/asp/parser/antlr -package de.dhbwstuttgart.sat.asp.parser.antlr diff --git a/src/test/java/bytecode/InheritTest.java b/src/test/java/bytecode/InheritTest.java index 86181bf6..77fcb9a1 100644 --- a/src/test/java/bytecode/InheritTest.java +++ b/src/test/java/bytecode/InheritTest.java @@ -138,11 +138,12 @@ public class InheritTest { */ @Test - public void testmainAA() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException, MalformedURLException, ClassNotFoundException { + public void testmainAA() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException, MalformedURLException, ClassNotFoundException, NoSuchFieldException { loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); classToTest = loader.loadClass("Inherit"); Method m = classToTestAA.getDeclaredMethod("m", Integer.class); assertEquals(m.invoke(instanceOfClassAA, 5), "AA"); + classToTestAA = classToTest.getField("aafield").getType(); Method main = classToTest.getDeclaredMethod("main", classToTestAA, Integer.class); assertEquals(main.invoke(instanceOfClass, instanceOfClassAA, 5), "AA"); } diff --git a/src/test/resources/bytecode/javFiles/Inherit.jav b/src/test/resources/bytecode/javFiles/Inherit.jav index 0ef9c020..0dd5ddcc 100644 --- a/src/test/resources/bytecode/javFiles/Inherit.jav +++ b/src/test/resources/bytecode/javFiles/Inherit.jav @@ -6,6 +6,7 @@ import java.lang.String; public class Inherit { +AA aafield; //m(Integer i) { return "AA"; } main(d, i) { From a0a813f87c903b45e0c834d586d4e74a064c5643 Mon Sep 17 00:00:00 2001 From: JanUlrich Date: Fri, 8 May 2020 11:35:21 +0200 Subject: [PATCH 74/81] Inherit Test update --- src/test/java/bytecode/InheritTest.java | 2 +- src/test/resources/bytecode/javFiles/Inherit.jav | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/test/java/bytecode/InheritTest.java b/src/test/java/bytecode/InheritTest.java index 77fcb9a1..e5ecc6c9 100644 --- a/src/test/java/bytecode/InheritTest.java +++ b/src/test/java/bytecode/InheritTest.java @@ -143,7 +143,7 @@ public class InheritTest { classToTest = loader.loadClass("Inherit"); Method m = classToTestAA.getDeclaredMethod("m", Integer.class); assertEquals(m.invoke(instanceOfClassAA, 5), "AA"); - classToTestAA = classToTest.getField("aafield").getType(); + classToTestAA = classToTest.getDeclaredField("aafield").getType(); Method main = classToTest.getDeclaredMethod("main", classToTestAA, Integer.class); assertEquals(main.invoke(instanceOfClass, instanceOfClassAA, 5), "AA"); } diff --git a/src/test/resources/bytecode/javFiles/Inherit.jav b/src/test/resources/bytecode/javFiles/Inherit.jav index 0dd5ddcc..60f5f8ed 100644 --- a/src/test/resources/bytecode/javFiles/Inherit.jav +++ b/src/test/resources/bytecode/javFiles/Inherit.jav @@ -6,14 +6,14 @@ import java.lang.String; public class Inherit { -AA aafield; + AA aafield; //m(Integer i) { return "AA"; } - - main(d, i) { + + main2(d, i) { return d.m(i); } - main(v, i) { + main2(v, i) { var aa = v.elementAt(0); return aa.m(i); } From 9240b0d1630c8bdba495122a875fb113d93a0bd7 Mon Sep 17 00:00:00 2001 From: "pl@gohorb.ba-horb.de" Date: Mon, 11 May 2020 13:45:19 +0200 Subject: [PATCH 75/81] Changes to be committed: modified: src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java modified: src/test/java/bytecode/InheritTest.java modified: src/test/resources/bytecode/javFiles/Inherit.jav --- .../dhbwstuttgart/typeinference/unify/TypeUnifyTask.java | 5 ++++- src/test/java/bytecode/InheritTest.java | 8 ++++++-- src/test/resources/bytecode/javFiles/Inherit.jav | 2 +- 3 files changed, 11 insertions(+), 4 deletions(-) diff --git a/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java b/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java index 2d63eafd..d350077a 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java @@ -761,6 +761,7 @@ public class TypeUnifyTask extends RecursiveTask>> { } } //Alle minimalen Elemente in nextSetasListRest bestimmen + writeLog("nextSetasListRest davor: " + nextSetasListRest); List> minElementsTest = oup.minElements(nextSetasListRest); List> nextSetasListRestTest; do { @@ -777,7 +778,9 @@ public class TypeUnifyTask extends RecursiveTask>> { }} } while(!nextSetasListRestTest.equals(nextSetasListRest)); - writeLog("minElementsTest: " + minElementsTest.equals(nextSetasListRest)); + writeLog("minElementsTest Vergleich: " + minElementsTest.equals(nextSetasListRest)); + writeLog("minElementsTest danach: " + minElementsTest); + writeLog("nextSetasListRest danach: " + nextSetasListRest); } else if (variance == 2) { a = nextSetasList.remove(0); diff --git a/src/test/java/bytecode/InheritTest.java b/src/test/java/bytecode/InheritTest.java index 77fcb9a1..2373d40d 100644 --- a/src/test/java/bytecode/InheritTest.java +++ b/src/test/java/bytecode/InheritTest.java @@ -37,20 +37,24 @@ public class InheritTest { private static Object instanceOfClass; private static Object instanceOfClassAA, instanceOfClassBB, instanceOfClassCC, instanceOfClassDD; private static HashMap, Method> hm = new HashMap<>(); + private static List typeinferenceResult; + private static List simplifyResultsForAllSourceFiles; @BeforeClass public static void setUpBeforeClass() throws Exception { - + /* path = System.getProperty("user.dir")+"/src/test/resources/bytecode/javFiles/AA.jav"; fileToTest = new File(path); compiler = new JavaTXCompiler(fileToTest); List typeinferenceResult = compiler.typeInference(); List simplifyResultsForAllSourceFiles = compiler.getGeneratedGenericResultsForAllSourceFiles(typeinferenceResult); compiler.generateBytecode(new File(pathToClassFile),typeinferenceResult,simplifyResultsForAllSourceFiles); + */ loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); classToTestAA = loader.loadClass("AA"); instanceOfClassAA = classToTestAA.getDeclaredConstructor().newInstance(); + /* path = System.getProperty("user.dir")+"/src/test/resources/bytecode/javFiles/BB.jav"; fileToTest = new File(path); @@ -143,7 +147,7 @@ public class InheritTest { classToTest = loader.loadClass("Inherit"); Method m = classToTestAA.getDeclaredMethod("m", Integer.class); assertEquals(m.invoke(instanceOfClassAA, 5), "AA"); - classToTestAA = classToTest.getField("aafield").getType(); + classToTestAA = classToTestAA.getField("aafield").getType(); Method main = classToTest.getDeclaredMethod("main", classToTestAA, Integer.class); assertEquals(main.invoke(instanceOfClass, instanceOfClassAA, 5), "AA"); } diff --git a/src/test/resources/bytecode/javFiles/Inherit.jav b/src/test/resources/bytecode/javFiles/Inherit.jav index 0dd5ddcc..11ca65d3 100644 --- a/src/test/resources/bytecode/javFiles/Inherit.jav +++ b/src/test/resources/bytecode/javFiles/Inherit.jav @@ -6,7 +6,7 @@ import java.lang.String; public class Inherit { -AA aafield; +//AA aafield; //m(Integer i) { return "AA"; } main(d, i) { From c27e1fa4e1b9e7f7034ad067a87517175f2ffe7c Mon Sep 17 00:00:00 2001 From: "pl@gohorb.ba-horb.de" Date: Mon, 11 May 2020 17:54:37 +0200 Subject: [PATCH 76/81] modified: ../../../java/bytecode/InheritTest.java modified: Inherit.jav Funktioniert soweit --- src/test/java/bytecode/InheritTest.java | 108 +++++++++--------- .../resources/bytecode/javFiles/Inherit.jav | 10 +- 2 files changed, 60 insertions(+), 58 deletions(-) diff --git a/src/test/java/bytecode/InheritTest.java b/src/test/java/bytecode/InheritTest.java index 29ebe8a1..19c16612 100644 --- a/src/test/java/bytecode/InheritTest.java +++ b/src/test/java/bytecode/InheritTest.java @@ -5,6 +5,7 @@ import static org.junit.Assert.*; import java.io.File; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; +import java.lang.reflect.Field; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; @@ -42,27 +43,24 @@ public class InheritTest { @BeforeClass public static void setUpBeforeClass() throws Exception { - /* path = System.getProperty("user.dir")+"/src/test/resources/bytecode/javFiles/AA.jav"; fileToTest = new File(path); compiler = new JavaTXCompiler(fileToTest); List typeinferenceResult = compiler.typeInference(); List simplifyResultsForAllSourceFiles = compiler.getGeneratedGenericResultsForAllSourceFiles(typeinferenceResult); compiler.generateBytecode(new File(pathToClassFile),typeinferenceResult,simplifyResultsForAllSourceFiles); - */ loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); classToTestAA = loader.loadClass("AA"); instanceOfClassAA = classToTestAA.getDeclaredConstructor().newInstance(); - /* + path = System.getProperty("user.dir")+"/src/test/resources/bytecode/javFiles/BB.jav"; fileToTest = new File(path); compiler = new JavaTXCompiler(fileToTest); typeinferenceResult = compiler.typeInference(); simplifyResultsForAllSourceFiles = compiler.getGeneratedGenericResultsForAllSourceFiles(typeinferenceResult); compiler.generateBytecode(new File(pathToClassFile),typeinferenceResult,simplifyResultsForAllSourceFiles); - loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); classToTestBB = loader.loadClass("BB"); instanceOfClassBB = classToTestBB.getDeclaredConstructor().newInstance(); @@ -72,7 +70,6 @@ public class InheritTest { typeinferenceResult = compiler.typeInference(); simplifyResultsForAllSourceFiles = compiler.getGeneratedGenericResultsForAllSourceFiles(typeinferenceResult); compiler.generateBytecode(new File(pathToClassFile),typeinferenceResult,simplifyResultsForAllSourceFiles); - loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); classToTestCC = loader.loadClass("CC"); instanceOfClassCC = classToTestCC.getDeclaredConstructor().newInstance(); @@ -82,35 +79,18 @@ public class InheritTest { typeinferenceResult = compiler.typeInference(); simplifyResultsForAllSourceFiles = compiler.getGeneratedGenericResultsForAllSourceFiles(typeinferenceResult); compiler.generateBytecode(new File(pathToClassFile),typeinferenceResult,simplifyResultsForAllSourceFiles); - loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); classToTestDD = loader.loadClass("DD"); instanceOfClassDD = classToTestDD.getDeclaredConstructor().newInstance(); - */ + path = System.getProperty("user.dir")+"/src/test/resources/bytecode/javFiles/Inherit.jav"; fileToTest = new File(path); compiler = new JavaTXCompiler(fileToTest); - /* - compiler = new JavaTXCompiler( - Lists.newArrayList(fileToTest), - Lists.newArrayList(new File(pathToClassFile1))); - */ typeinferenceResult = compiler.typeInference(); simplifyResultsForAllSourceFiles = compiler.getGeneratedGenericResultsForAllSourceFiles(typeinferenceResult); compiler.generateBytecode(new File(pathToClassFile),typeinferenceResult,simplifyResultsForAllSourceFiles); - loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); classToTest = loader.loadClass("Inherit"); instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); - - /* - for (Method m: classToTest.getMethods()) { - ArrayList param = Arrays.stream(m.getParameterTypes()).map(x -> x.getName()).collect(Collectors.toCollection(ArrayList::new)); - ArrayList nameParam = new ArrayList<>(); - nameParam.add(m.getName()); - nameParam.addAll(param); - hm.put(nameParam, m); - } - */ } @Test @@ -124,7 +104,6 @@ public class InheritTest { assertEquals("AA", classToTestAA.getName()); } - /* @Test public void testBBName() { assertEquals("BB", classToTestBB.getName()); @@ -139,49 +118,76 @@ public class InheritTest { public void testDDName() { assertEquals("DD", classToTestDD.getName()); } - */ @Test public void testmainAA() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException, MalformedURLException, ClassNotFoundException, NoSuchFieldException { - loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); - classToTest = loader.loadClass("Inherit"); Method m = classToTestAA.getDeclaredMethod("m", Integer.class); assertEquals(m.invoke(instanceOfClassAA, 5), "AA"); - classToTestAA = classToTest.getDeclaredField("aafield").getType(); Method main = classToTest.getDeclaredMethod("main", classToTestAA, Integer.class); assertEquals(main.invoke(instanceOfClass, instanceOfClassAA, 5), "AA"); } - /* - Vector v_invoke = new Vector<>(); - Vector v = new Vector<>(); - v.add(5); - assertEquals(v, v_invoke); + + @Test + public void testmainBB() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException, MalformedURLException, ClassNotFoundException, NoSuchFieldException { + Method m = classToTestAA.getDeclaredMethod("m", Integer.class); + assertEquals(m.invoke(instanceOfClassBB, 5), "AA"); + Method main = classToTest.getDeclaredMethod("main", classToTestAA, Integer.class); + assertEquals(main.invoke(instanceOfClass, instanceOfClassBB, 5), "AA"); } @Test - public void testPutElementStack() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method m = classToTest.getDeclaredMethod("putElement", Object.class, Stack.class); - Stack s_invoke = new Stack<>(); - m.invoke(instanceOfClass, 5, s_invoke); - assertEquals(new Integer(5), s_invoke.pop()); + public void testmainCC() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException, MalformedURLException, ClassNotFoundException, NoSuchFieldException { + Method m = classToTestCC.getDeclaredMethod("m", Integer.class); + assertEquals(m.invoke(instanceOfClassCC, 5), "CC"); + Method main = classToTest.getDeclaredMethod("main", classToTestCC, Integer.class); + assertEquals(main.invoke(instanceOfClass, instanceOfClassCC, 5), "CC"); } @Test - public void testMainVector() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method m = classToTest.getDeclaredMethod("main", Object.class, Vector.class); - Vector v_invoke = new Vector<>(); - m.invoke(instanceOfClass, 6, v_invoke); - Vector v = new Vector<>(); - v.add(6); - assertEquals(v, v_invoke); + public void testmainDD() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException, MalformedURLException, ClassNotFoundException, NoSuchFieldException { + Method m = classToTestCC.getDeclaredMethod("m", Integer.class); + assertEquals(m.invoke(instanceOfClassDD, 5), "CC"); + Method main = classToTest.getDeclaredMethod("main", classToTestCC, Integer.class); + assertEquals(main.invoke(instanceOfClass, instanceOfClassDD, 5), "CC"); } @Test - public void testMainStack() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method m = classToTest.getDeclaredMethod("main", Object.class, Stack.class); - Stack s_invoke = new Stack<>(); - m.invoke(instanceOfClass, 6, s_invoke); - assertEquals(new Integer(6), s_invoke.pop()); + public void testmainVectorAA() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException, MalformedURLException, ClassNotFoundException, NoSuchFieldException { + Method m = classToTestAA.getDeclaredMethod("m", Integer.class); + assertEquals(m.invoke(instanceOfClassAA, 5), "AA"); + Vector v = new Vector<>(); + v.add(instanceOfClassAA); + Method main = classToTest.getDeclaredMethod("main", Vector.class, Integer.class); + assertEquals(main.invoke(instanceOfClass, v, 5), "AA"); + } + + @Test + public void testmainVectorBB() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException, MalformedURLException, ClassNotFoundException, NoSuchFieldException { + Method m = classToTestAA.getDeclaredMethod("m", Integer.class); + assertEquals(m.invoke(instanceOfClassBB, 5), "AA"); + Vector v = new Vector<>(); + v.add(instanceOfClassBB); + Method main = classToTest.getDeclaredMethod("main", Vector.class, Integer.class); + assertEquals(main.invoke(instanceOfClass, v, 5), "AA"); + } + + @Test + public void testmainVectorCC() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException, MalformedURLException, ClassNotFoundException, NoSuchFieldException { + Method m = classToTestCC.getDeclaredMethod("m", Integer.class); + assertEquals(m.invoke(instanceOfClassCC, 5), "CC"); + Vector v = new Vector<>(); + v.add(instanceOfClassCC); + Method main = classToTest.getDeclaredMethod("main", Vector.class, Integer.class); + assertEquals(main.invoke(instanceOfClass, v, 5), "CC"); + } + + @Test + public void testmainVectorDD() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException, MalformedURLException, ClassNotFoundException, NoSuchFieldException { + Method m = classToTestCC.getDeclaredMethod("m", Integer.class); + assertEquals(m.invoke(instanceOfClassDD, 5), "CC"); + Vector v = new Vector<>(); + v.add(instanceOfClassDD); + Method main = classToTest.getDeclaredMethod("main", Vector.class, Integer.class); + assertEquals(main.invoke(instanceOfClass, v, 5), "CC"); } - */ } diff --git a/src/test/resources/bytecode/javFiles/Inherit.jav b/src/test/resources/bytecode/javFiles/Inherit.jav index ba9f30bd..7b5927d2 100644 --- a/src/test/resources/bytecode/javFiles/Inherit.jav +++ b/src/test/resources/bytecode/javFiles/Inherit.jav @@ -5,16 +5,12 @@ import java.lang.String; public class Inherit { - - AA aafield; - - //m(Integer i) { return "AA"; } - - main2(d, i) { + + main(d, i) { return d.m(i); } - main2(v, i) { + main(v, i) { var aa = v.elementAt(0); return aa.m(i); } From c8ece0a0102ef53eb35d12a23879e1e39fb92f97 Mon Sep 17 00:00:00 2001 From: "pl@gohorb.ba-horb.de" Date: Tue, 12 May 2020 10:02:41 +0200 Subject: [PATCH 77/81] new file: ../../../java/bytecode/InheritTest2.java modified: AA.jav modified: CC.jav new file: Inherit2.jav --- src/test/java/bytecode/InheritTest2.java | 211 ++++++++++++++++++ src/test/resources/bytecode/javFiles/AA.jav | 2 + src/test/resources/bytecode/javFiles/CC.jav | 6 +- .../resources/bytecode/javFiles/Inherit2.jav | 17 ++ 4 files changed, 235 insertions(+), 1 deletion(-) create mode 100644 src/test/java/bytecode/InheritTest2.java create mode 100644 src/test/resources/bytecode/javFiles/Inherit2.jav diff --git a/src/test/java/bytecode/InheritTest2.java b/src/test/java/bytecode/InheritTest2.java new file mode 100644 index 00000000..36602704 --- /dev/null +++ b/src/test/java/bytecode/InheritTest2.java @@ -0,0 +1,211 @@ +package bytecode; + +import static org.junit.Assert.*; + +import java.io.File; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Field; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLClassLoader; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Stack; +import java.util.Vector; +import java.util.stream.Collectors; + +import org.junit.BeforeClass; +import org.junit.Test; + +import com.google.common.collect.Lists; + +import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.GenericGenratorResultForSourceFile; +import de.dhbwstuttgart.core.JavaTXCompiler; +import de.dhbwstuttgart.typeinference.result.ResultSet; + +public class InheritTest2 { + private static String path; + private static File fileToTest; + private static JavaTXCompiler compiler; + private static ClassLoader loader; + private static Class classToTest; + private static Class classToTestAA, classToTestBB, classToTestCC, classToTestDD; + private static String pathToClassFile = System.getProperty("user.dir")+"/src/test/resources/bytecode/javFiles/";; + //private static String pathToClassFile1 = System.getProperty("user.dir") + "/src/test/resources/testBytecode/generatedBC/"; + private static Object instanceOfClass; + private static Object instanceOfClassAA, instanceOfClassBB, instanceOfClassCC, instanceOfClassDD; + private static HashMap, Method> hm = new HashMap<>(); + private static List typeinferenceResult; + private static List simplifyResultsForAllSourceFiles; + + @BeforeClass + public static void setUpBeforeClass() throws Exception { + path = System.getProperty("user.dir")+"/src/test/resources/bytecode/javFiles/AA.jav"; + fileToTest = new File(path); + compiler = new JavaTXCompiler(fileToTest); + List typeinferenceResult = compiler.typeInference(); + List simplifyResultsForAllSourceFiles = compiler.getGeneratedGenericResultsForAllSourceFiles(typeinferenceResult); + compiler.generateBytecode(new File(pathToClassFile),typeinferenceResult,simplifyResultsForAllSourceFiles); + loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); + classToTestAA = loader.loadClass("AA"); + instanceOfClassAA = classToTestAA.getDeclaredConstructor().newInstance(); + + + + path = System.getProperty("user.dir")+"/src/test/resources/bytecode/javFiles/BB.jav"; + fileToTest = new File(path); + compiler = new JavaTXCompiler(fileToTest); + typeinferenceResult = compiler.typeInference(); + simplifyResultsForAllSourceFiles = compiler.getGeneratedGenericResultsForAllSourceFiles(typeinferenceResult); + compiler.generateBytecode(new File(pathToClassFile),typeinferenceResult,simplifyResultsForAllSourceFiles); + classToTestBB = loader.loadClass("BB"); + instanceOfClassBB = classToTestBB.getDeclaredConstructor().newInstance(); + + path = System.getProperty("user.dir")+"/src/test/resources/bytecode/javFiles/CC.jav"; + fileToTest = new File(path); + compiler = new JavaTXCompiler(fileToTest); + typeinferenceResult = compiler.typeInference(); + simplifyResultsForAllSourceFiles = compiler.getGeneratedGenericResultsForAllSourceFiles(typeinferenceResult); + compiler.generateBytecode(new File(pathToClassFile),typeinferenceResult,simplifyResultsForAllSourceFiles); + classToTestCC = loader.loadClass("CC"); + instanceOfClassCC = classToTestCC.getDeclaredConstructor().newInstance(); + + path = System.getProperty("user.dir")+"/src/test/resources/bytecode/javFiles/DD.jav"; + fileToTest = new File(path); + compiler = new JavaTXCompiler(fileToTest); + typeinferenceResult = compiler.typeInference(); + simplifyResultsForAllSourceFiles = compiler.getGeneratedGenericResultsForAllSourceFiles(typeinferenceResult); + compiler.generateBytecode(new File(pathToClassFile),typeinferenceResult,simplifyResultsForAllSourceFiles); + classToTestDD = loader.loadClass("DD"); + instanceOfClassDD = classToTestDD.getDeclaredConstructor().newInstance(); + + + path = System.getProperty("user.dir")+"/src/test/resources/bytecode/javFiles/Inherit2.jav"; + fileToTest = new File(path); + compiler = new JavaTXCompiler(fileToTest); + typeinferenceResult = compiler.typeInference(); + simplifyResultsForAllSourceFiles = compiler.getGeneratedGenericResultsForAllSourceFiles(typeinferenceResult); + compiler.generateBytecode(new File(pathToClassFile),typeinferenceResult,simplifyResultsForAllSourceFiles); + classToTest = loader.loadClass("Inherit2"); + instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); + } + + @Test + public void testInheritClassName() { + assertEquals("Inherit2", classToTest.getName()); + } + + + @Test + public void testAAName() { + assertEquals("AA", classToTestAA.getName()); + } + + @Test + public void testBBName() { + assertEquals("BB", classToTestBB.getName()); + } + + @Test + public void testCCName() { + assertEquals("CC", classToTestCC.getName()); + } + + @Test + public void testDDName() { + assertEquals("DD", classToTestDD.getName()); + } + + @Test + public void testmainAA() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException, MalformedURLException, ClassNotFoundException, NoSuchFieldException { + Method m2 = classToTestAA.getDeclaredMethod("m2", classToTestAA); + assertEquals(m2.invoke(instanceOfClassAA, instanceOfClassAA), "AA"); + Method main = classToTest.getDeclaredMethod("main", classToTestAA); + assertEquals(main.invoke(instanceOfClass, instanceOfClassAA), "AA"); + } + + @Test + public void testmainBB() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException, MalformedURLException, ClassNotFoundException, NoSuchFieldException { + Method m2 = classToTestAA.getDeclaredMethod("m2", classToTestAA); + assertEquals(m2.invoke(instanceOfClassAA, instanceOfClassAA), "AA"); + Method main = classToTest.getDeclaredMethod("main", classToTestAA); + assertEquals(main.invoke(instanceOfClass, instanceOfClassBB), "AA"); + } + + @Test + public void testmainCC() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException, MalformedURLException, ClassNotFoundException, NoSuchFieldException { + Method m2 = classToTestCC.getDeclaredMethod("m2", classToTestCC); + assertEquals(m2.invoke(instanceOfClassCC, instanceOfClassCC), "CC"); + Method main = classToTest.getDeclaredMethod("main", classToTestCC); + assertEquals(main.invoke(instanceOfClass, instanceOfClassCC), "CC"); + } + + @Test + public void testmainDD() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException, MalformedURLException, ClassNotFoundException, NoSuchFieldException { + Method m2 = classToTestCC.getDeclaredMethod("m2", classToTestCC); + assertEquals(m2.invoke(instanceOfClassCC, instanceOfClassCC), "CC"); + Method main = classToTest.getDeclaredMethod("main", classToTestCC); + assertEquals(main.invoke(instanceOfClass, instanceOfClassDD), "CC"); + } + + + //PL 2020-05-12: Die folgenden Test funktionieren erst, wenn Generics im Bytecode implementiert sind + @Test + public void testmainVectorAA() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException, MalformedURLException, ClassNotFoundException, NoSuchFieldException { + Method m2 = classToTestAA.getDeclaredMethod("m2", classToTestAA); + assertEquals(m2.invoke(instanceOfClassAA, instanceOfClassAA), "AA"); + Vector v = new Vector<>(); + v.add(instanceOfClassAA); + Method main = classToTest.getDeclaredMethod("main", Vector.class); + try { + assertEquals(main.invoke(instanceOfClass, v), "AA"); + } + catch (java.lang.reflect.InvocationTargetException e) { + testmainVectorCC(); + } + } + + @Test + public void testmainVectorBB() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException, MalformedURLException, ClassNotFoundException, NoSuchFieldException { + Method m2 = classToTestAA.getDeclaredMethod("m2", classToTestAA); + assertEquals(m2.invoke(instanceOfClassAA, instanceOfClassAA), "AA"); + Vector v = new Vector<>(); + v.add(instanceOfClassBB); + Method main = classToTest.getDeclaredMethod("main", Vector.class); + try { + assertEquals(main.invoke(instanceOfClass, v), "AA"); + } + catch (java.lang.reflect.InvocationTargetException e) { + testmainVectorCC(); + } + } + + @Test + public void testmainVectorCC() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException, MalformedURLException, ClassNotFoundException, NoSuchFieldException { + Method m2 = classToTestCC.getDeclaredMethod("m2", classToTestCC); + assertEquals(m2.invoke(instanceOfClassCC, instanceOfClassCC), "CC"); + Vector v = new Vector<>(); + v.add(instanceOfClassCC); + Method main = classToTest.getDeclaredMethod("main", Vector.class); + String erg; + assertEquals(erg= (String) main.invoke(instanceOfClass, v), + erg.equals("CC")? "CC": "AA"); + } + + @Test + public void testmainVectorDD() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException, MalformedURLException, ClassNotFoundException, NoSuchFieldException { + Method m2 = classToTestCC.getDeclaredMethod("m2", classToTestCC); + assertEquals(m2.invoke(instanceOfClassCC, instanceOfClassCC), "CC"); + Vector v = new Vector<>(); + v.add(instanceOfClassDD); + Method main = classToTest.getDeclaredMethod("main", Vector.class); + String erg; + assertEquals(erg= (String) main.invoke(instanceOfClass, v), + erg.equals("CC")? "CC": "AA"); + } + + +} diff --git a/src/test/resources/bytecode/javFiles/AA.jav b/src/test/resources/bytecode/javFiles/AA.jav index 4593fdfb..3f8f172d 100644 --- a/src/test/resources/bytecode/javFiles/AA.jav +++ b/src/test/resources/bytecode/javFiles/AA.jav @@ -3,4 +3,6 @@ import java.lang.String; public class AA { m(Integer i) { return "AA"; } + + m2(AA x) { return "AA"; } } \ No newline at end of file diff --git a/src/test/resources/bytecode/javFiles/CC.jav b/src/test/resources/bytecode/javFiles/CC.jav index 4523dfda..d7d5c967 100644 --- a/src/test/resources/bytecode/javFiles/CC.jav +++ b/src/test/resources/bytecode/javFiles/CC.jav @@ -3,5 +3,9 @@ import java.lang.String; public class CC extends BB { - m(Integer i) { return "CC"; } + m(Integer i) { + return "CC"; + } + + m2(CC x) { return "CC"; } } diff --git a/src/test/resources/bytecode/javFiles/Inherit2.jav b/src/test/resources/bytecode/javFiles/Inherit2.jav new file mode 100644 index 00000000..fe4c5062 --- /dev/null +++ b/src/test/resources/bytecode/javFiles/Inherit2.jav @@ -0,0 +1,17 @@ +import java.util.Vector; + +import java.lang.Integer; +import java.lang.String; + + +public class Inherit2 { + + main(d) { + return d.m2(d); + } + + main(v) { + var aa = v.elementAt(0); + return aa.m2(aa); + } +} \ No newline at end of file From 670e3ed99fe13f0909a0a2af9eb0690b03b40bea Mon Sep 17 00:00:00 2001 From: "pl@gohorb.ba-horb.de" Date: Tue, 12 May 2020 17:25:04 +0200 Subject: [PATCH 78/81] modified: ../../../../main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java nextSetasListRest = oup.minElements(nextSetasListRest); nextSetasListRest = oup.maxElements(nextSetasListRest); eingefuegt modified: ../../../../main/java/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java --- .../typeinference/unify/TypeUnifyTask.java | 49 ++++--------------- .../unify/model/FiniteClosure.java | 2 + 2 files changed, 11 insertions(+), 40 deletions(-) diff --git a/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java b/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java index d350077a..1acdeaa3 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java @@ -724,24 +724,8 @@ public class TypeUnifyTask extends RecursiveTask>> { } } - List> maxElementsTest = oup.maxElements(nextSetasListRest); //Alle maximale Elemente in nextSetasListRest bestimmen - List> nextSetasListRestTest; - do { - nextSetasListRestTest = new ArrayList>(nextSetasListRest); - if (!nextSetasListRest.isEmpty()) { - Set max = oup.max(nextSetasListRest.iterator()); - Iterator> nextSetasListItRest2 = new ArrayList>(nextSetasListRest).iterator(); - while (nextSetasListItRest2.hasNext()) { - Set a_nextRest = nextSetasListItRest2.next(); - if (//a.equals(a_next) || - (oup.compare(max, a_nextRest) == 1)) { - nextSetasListRest.remove(a_nextRest); - } - - }} - } while(!nextSetasListRestTest.equals(nextSetasListRest)); - writeLog("maxElementsTest: " + maxElementsTest.equals(nextSetasListRest)); + nextSetasListRest = oup.maxElements(nextSetasListRest); } else if (variance == -1) { a = oup.min(nextSetasList.iterator()); @@ -761,26 +745,8 @@ public class TypeUnifyTask extends RecursiveTask>> { } } //Alle minimalen Elemente in nextSetasListRest bestimmen - writeLog("nextSetasListRest davor: " + nextSetasListRest); - List> minElementsTest = oup.minElements(nextSetasListRest); - List> nextSetasListRestTest; - do { - nextSetasListRestTest = new ArrayList>(nextSetasListRest); - if (!nextSetasListRest.isEmpty()) { - Set min = oup.min(nextSetasListRest.iterator()); - Iterator> nextSetasListItRest2 = new ArrayList>(nextSetasListRest).iterator(); - while (nextSetasListItRest2.hasNext()) { - Set a_nextRest = nextSetasListItRest2.next(); - if (//a.equals(a_next) || - (oup.compare(min, a_nextRest) == -1)) { - nextSetasListRest.remove(a_nextRest); - } - - }} - } while(!nextSetasListRestTest.equals(nextSetasListRest)); - writeLog("minElementsTest Vergleich: " + minElementsTest.equals(nextSetasListRest)); - writeLog("minElementsTest danach: " + minElementsTest); - writeLog("nextSetasListRest danach: " + nextSetasListRest); + //writeLog("nextSetasListRest davor: " + nextSetasListRest); + nextSetasListRest = oup.minElements(nextSetasListRest); } else if (variance == 2) { a = nextSetasList.remove(0); @@ -1435,9 +1401,12 @@ public class TypeUnifyTask extends RecursiveTask>> { //das kleineste Element ist das Element von dem a_new geerbt hat //muss deshalb geloescht werden - Set min = oup.min(notErased.iterator()); - notErased.remove(min); - notErased.remove(((Constraint)min).getExtendConstraint()); + Iterator> notErasedIt = notErased.iterator(); + if (notErasedIt.hasNext()) { + Set min = oup.min(notErasedIt); + notErased.remove(min); + notErased.remove(((Constraint)min).getExtendConstraint()); + } List> erased = new ArrayList<>(greaterSetasList); erased.removeAll(notErased); diff --git a/src/main/java/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java b/src/main/java/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java index 038f308e..a48db2aa 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java @@ -76,6 +76,7 @@ implements IFiniteClosure { // Build the transitive closure of the inheritance tree for(UnifyPair pair : pairs) { + /* try { logFile.write("Pair: " + pair + "\n"); logFile.flush(); @@ -83,6 +84,7 @@ implements IFiniteClosure { catch (IOException e) { System.err.println("no LogFile"); } + */ if(pair.getPairOp() != PairOperator.SMALLER) continue; From 2e03b5b10c7fffa04fe1f0d4c22c8b8003bf2fd2 Mon Sep 17 00:00:00 2001 From: "pl@gohorb.ba-horb.de" Date: Tue, 12 May 2020 17:35:28 +0200 Subject: [PATCH 79/81] modified: ../../../../main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java auskommentierten Code geloescht --- .../typeinference/unify/TypeUnifyTask.java | 178 +----------------- 1 file changed, 1 insertion(+), 177 deletions(-) diff --git a/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java b/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java index 1acdeaa3..9e95521d 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java @@ -745,7 +745,6 @@ public class TypeUnifyTask extends RecursiveTask>> { } } //Alle minimalen Elemente in nextSetasListRest bestimmen - //writeLog("nextSetasListRest davor: " + nextSetasListRest); nextSetasListRest = oup.minElements(nextSetasListRest); } else if (variance == 2) { @@ -777,24 +776,7 @@ public class TypeUnifyTask extends RecursiveTask>> { } //writeLog("nextSet: " + nextSetasList.toString()+ "\n"); //nextSetasList.remove(a); - /* zu loeschen - if (nextSetasList.size() > 0) { - if (nextSetasList.size()>1) { - if (variance == 1) { - a_next = oup.max(nextSetasList.iterator()); - } - else if (variance == -1) { - a_next = oup.min(nextSetasList.iterator()); - } - else { - a_next = nextSetasList.iterator().next(); - } - } - else { - a_next = nextSetasList.iterator().next(); - } - } - */ + //PL 2018-03-01 //TODO: 1. Maximum und Minimum unterscheiden //TODO: 2. compare noch für alle Elmemente die nicht X =. ty sind erweitern @@ -1264,33 +1246,6 @@ public class TypeUnifyTask extends RecursiveTask>> { System.out.print(""); Iterator> nextSetasListIt = new ArrayList>(nextSetasList).iterator(); if (variance == 1) { - /* vorgezogen vor das if - if (parallel) { - for (Set> par_res : add_res) { - if (!isUndefinedPairSetSet(par_res) && isUndefinedPairSetSet(result)) { - //wenn korrektes Ergebnis gefunden alle Fehlerfaelle loeschen - result = par_res; - if (par_res.iterator().next() instanceof WildcardType) { - System.out.println(""); - } - } - else { - if ((isUndefinedPairSetSet(par_res) && isUndefinedPairSetSet(result)) - || (!isUndefinedPairSetSet(par_res) && !isUndefinedPairSetSet(result)) - || result.isEmpty()) { - //alle Fehlerfaelle und alle korrekten Ergebnis jeweils adden - writeLog("RES var1 ADD:" + result.toString() + " " + par_res.toString()); - result.addAll(par_res); - } - } - } - //break; - */ - - /* nextSetasList = nextSetasListRest; */ - /* wird bereits vor den unify2-Aufruf durchgefuehrt und nextSetasListRest zugeordnet - */ - System.out.println(""); writeLog("a: " + rekTiefe + " variance: " + variance + a.toString()); writeLog("aParDef: " + aParDef.toString()); @@ -1323,22 +1278,6 @@ public class TypeUnifyTask extends RecursiveTask>> { //nextSetasListIt = nextSetasList.iterator(); Sollte eingefuegt werden PL 2020-04-28 Set a_new = aParDefIt.next(); List> erased = oup.smallerEqThan(a_new, nextSetasList); - - /* loeschen - while (nextSetasListIt.hasNext()) { - Set a_next = nextSetasListIt.next(); - if (a_new.equals(a_next) || - ((oup.compare(a_new, a_next) == 1) && - (!oderConstraint || ((Constraint)a_next).isInherited()))) { - writeLog("Removed: " + a_next.toString()); - nextSetasList.remove(a_next); - } - else { - writeLog("Not Removed: " + a_next.toString()); - System.out.println(""); - } - } - Ende loeschen */ nextSetasList.removeAll(erased); writeLog("Removed: " + erased); @@ -1348,32 +1287,6 @@ public class TypeUnifyTask extends RecursiveTask>> { } } else { if (variance == -1) { - /* vorgezogen vor das if - if (parallel) { - for (Set> par_res : add_res) { - if (!isUndefinedPairSetSet(par_res) && isUndefinedPairSetSet(result)) { - //wenn korrektes Ergebnis gefunden alle Fehlerfaelle loeschen - result = par_res; - if (par_res.iterator().next() instanceof WildcardType) { - System.out.println(""); - } - } - else { - if ((isUndefinedPairSetSet(par_res) && isUndefinedPairSetSet(result)) - || (!isUndefinedPairSetSet(par_res) && !isUndefinedPairSetSet(result)) - || result.isEmpty()) { - //alle Fehlerfaelle und alle korrekten Ergebnis jeweils adden - writeLog("RES var-1 ADD:" + result.toString() + " " + par_res.toString()); - result.addAll(par_res); - } - } - } - //break; - } - - } - */ - System.out.println(""); writeLog("a: " + rekTiefe + " variance: " + variance + a.toString()); writeLog("aParDef: " + aParDef.toString()); @@ -1424,21 +1337,6 @@ public class TypeUnifyTask extends RecursiveTask>> { Set a_new = aParDefIt.next(); List> erased = oup.greaterEqThan(a_new, nextSetasList); - /* zu loeschen - while (nextSetasListIt.hasNext()) { - Set a_next = nextSetasListIt.next(); - if (a_new.equals(a_next) || - ((oup.compare(a_new, a_next) == -1) && - (!oderConstraint || ((Constraint)a_new).isInherited()))) { - writeLog("Removed: " + a_next.toString()); - nextSetasList.remove(a_next); //PL geaendert 2019-01-09 - } - else { - System.out.println(""); - writeLog("Not Removed: " + a_next.toString()); - } - } - Ende zu loeschen */ nextSetasList.removeAll(erased); writeLog("Removed: " + erased); @@ -1470,84 +1368,10 @@ public class TypeUnifyTask extends RecursiveTask>> { writeLog("Not Removed: " + nextSetasList); - - - /* zu loeschen PL 2020-05-05 - nextSetasList = nextSetasList.stream() - .filter(x -> !((Constraint)x).isInherited()) - .collect(Collectors.toCollection(ArrayList::new)); - */ - - /* - //TODO: Hier muessen alle kleineren und größeren Elemente von a geloescht werden - writeLog("a: " + rekTiefe + " variance: " + variance + a.toString()); - writeLog("aParDef: " + aParDef.toString()); - aParDef.add(a); - Iterator> aParDefIt = aParDef.iterator(); - while(aParDefIt.hasNext()) { - Set a_new = aParDefIt.next(); - while (nextSetasListIt.hasNext()) { - Set a_next = nextSetasListIt.next(); - if (a_new.equals(a_next) || - ((oup.compare(a_new, a_next) == -1) && - (!oderConstraint || ((Constraint)a_new).isInherited()))){ - writeLog("Removed: " + a_next.toString()); - nextSetasList.remove(a_next); //PL geaendert 2019-01-09 - } - else { - System.out.println(""); - writeLog("Not Removed: " + a_next.toString()); - } - } - - } - writeLog("a: " + rekTiefe + " variance: " + variance + a.toString()); - writeLog("aParDef: " + aParDef.toString()); - aParDefIt = aParDef.iterator(); - while(aParDefIt.hasNext()) { - Set a_new = aParDefIt.next(); - while (nextSetasListIt.hasNext()) { - Set a_next = nextSetasListIt.next(); - if (a_new.equals(a_next) || - ((oup.compare(a_new, a_next) == 1) && - (!oderConstraint || ((Constraint)a_next).isInherited()))){ - writeLog("Removed: " + a_next.toString()); - nextSetasList.remove(a_next); - } - else { - writeLog("Not Removed: " + a_next.toString()); - System.out.println(""); - } - } - } - */ } } else { if (variance == 2) { - /* vorgezogen vor das if - if (parallel) { - for (Set> par_res : add_res) { - if (!isUndefinedPairSetSet(par_res) && isUndefinedPairSetSet(result)) { - //wenn korrektes Ergebnis gefunden alle Fehlerfaelle loeschen - result = par_res; - if (par_res.iterator().next() instanceof WildcardType) { - System.out.println(""); - } - } - else { - if ((isUndefinedPairSetSet(par_res) && isUndefinedPairSetSet(result)) - || (!isUndefinedPairSetSet(par_res) && !isUndefinedPairSetSet(result)) - || result.isEmpty()) { - //alle Fehlerfaelle und alle korrekten Ergebnis jeweils adden - writeLog("RES var2 ADD:" + result.toString() + " " + par_res.toString()); - result.addAll(par_res); - } - } - } - //break; - } - */ }}} writeLog("a: " + rekTiefe + " variance: " + variance + a.toString()); } From 653901ef3248e8e51caa3a4e4df1e20ccc285dfe Mon Sep 17 00:00:00 2001 From: "pl@gohorb.ba-horb.de" Date: Wed, 13 May 2020 14:07:22 +0200 Subject: [PATCH 80/81] modified: ../../../../main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java alten Code geloescht --- .../de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java b/src/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java index 613b1c26..ac643f38 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java @@ -173,10 +173,6 @@ public class TYPEStmt implements StatementVisitor{ Constraint oneMethodConstraint = generateConstraint(methodCall, m, info, resolver); methodConstraints.add(oneMethodConstraint); - // geloescht PL 2020-05-01 - //resolver = getResolverInstance(); - //oneMethodConstraint = generateConstraint(methodCall, m, info, resolver); - //Boolean oneMethodConstraint_isInherited = oneMethodConstraint.isInherited(); Constraint extendsOneMethodConstraint = oneMethodConstraint.stream() .map(x -> (x.TA1 instanceof TypePlaceholder && x.GetOperator() == PairOperator.EQUALSDOT && From 941a3bed6680aba0f152dda40c7b331c399b594b Mon Sep 17 00:00:00 2001 From: JanUlrich Date: Thu, 17 Sep 2020 10:58:44 +0200 Subject: [PATCH 81/81] Add ANTLR parser generator output to gitignore --- .gitignore | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.gitignore b/.gitignore index fe551a27..2d0d6112 100644 --- a/.gitignore +++ b/.gitignore @@ -26,3 +26,6 @@ manually/ logFiles/** !logFiles/.gitkeep + +src/main/java/de/dhbwstuttgart/parser/antlr/ +src/main/java/de/dhbwstuttgart/sat/asp/parser/antlr/