diff --git a/.gitignore b/.gitignore index a897efd8a..2d0d6112e 100644 --- a/.gitignore +++ b/.gitignore @@ -23,3 +23,9 @@ bin # manually/ + +logFiles/** +!logFiles/.gitkeep + +src/main/java/de/dhbwstuttgart/parser/antlr/ +src/main/java/de/dhbwstuttgart/sat/asp/parser/antlr/ diff --git a/PlugInBau.txt b/PlugInBau.txt deleted file mode 100644 index a76097ad7..000000000 --- a/PlugInBau.txt +++ /dev/null @@ -1,22 +0,0 @@ -Repositories: Branches: JavaCompilerCore: simplyRes - JavaCompilerPlugin: copy_libs -JavaCompilerCore > mvn install -Dskip.test=true - -[INFO] Installing /Users/pl/workspace_oxygen/JavaCompilerCore/target/JavaTXcompiler-0.2.jar to /Users/pl/.m2/repository/de/dhbwstuttgart/JavaTXcompiler/0.2/JavaTXcompiler-0.2.jar -[INFO] Installing /Users/pl/workspace_oxygen/JavaCompilerCore/pom.xml to /Users/pl/.m2/repository/de/dhbwstuttgart/JavaTXcompiler/0.2/JavaTXcompiler-0.2.pom -[INFO] Installing /Users/pl/workspace_oxygen/JavaCompilerCore/target/JavaTXcompiler-0.2-jar-with-dependencies.jar to /Users/pl/.m2/repository/de/dhbwstuttgart/JavaTXcompiler/0.2/JavaTXcompiler-0.2-jar-with-dependencies.jar -[INFO] ------------------------------------------------------------------------ -[INFO] BUILD SUCCESS -[INFO] ------------------------------------------------------------------------ -[INFO] Total time: 23.279 s -[INFO] Finished at: 2019-09-17T09:31:30+02:00 -[INFO] ------------------------------------- - -JavaCompilerCore > cd target - -JavaCompilerCore/target > cp JavaTXcompiler-0.2.jar ../../Plugin_JCC/JavaCompilerPlugin/bundles/JavaCompilerPlugin.Plugin/lib/JavaTXcompiler.jar - -Im Eclipse: Plugin_JCC/JavaCompilerPlugin> mvn install - -Plugin_JCC/JavaCompilerPlugin/releng/JavaCompilerPlugin.Update/target > cp JavaCompilerPlugin.Update-0.1.0-SNAPSHOT.zip ~/webdav/public_html/javatx/javatx_XXXXXX.zip - diff --git a/PluginBau.docx b/PluginBau.docx deleted file mode 100644 index 6b387c710..000000000 Binary files a/PluginBau.docx and /dev/null differ diff --git a/Website/JavaTXExamples.zip b/Website/JavaTXExamples.zip deleted file mode 100644 index db9eb324b..000000000 Binary files a/Website/JavaTXExamples.zip and /dev/null differ diff --git a/Website/index.html b/Website/index.html deleted file mode 100644 index 0253da16e..000000000 --- a/Website/index.html +++ /dev/null @@ -1,88 +0,0 @@ - - -Java-TX Plugin -
-

Java-TX Plugin

-
-

Content

- - -
-

Introduction

-Java-TX (Java Type eXtended) is an extension of Java in which a global type inference algorithm and real function types are added. Since the end of the nineties features from functional program- ming languages have been transferred to Java. Parametric polymorphism extended by wildcards, called generics, were transfered to Java 5.0. Higher-order functions and lambda expression were introduced in Java 8. Java 8 uses functional interfaces as target types of lambda expressions in contrast to real function types as in functional programming languages. -The powerful feature type inference from functional programming languages is incorporated into Java, as into other object-oriented -languages, i.e. only in a restricted way called local type inference. Local type inference allows certain type annotations to be omitted. For instance, it is often not necessary to specify the type of a variable. Type parameters of classes in the new-statement can be left out. Return types of methods can often also be omitted. Local type inference is at its most pronounced in Scala. In Java 10 an extention of local type inference is introduced, where types of local variables can be replaced by the keyword var and inferred automatically during the compilation. In contrast to global type inference, local type inference allows types of recursive methods and lambda expressions not to be omitted.
-The Java-TX project contributes to the design of object-oriented languages by developing global type inference algorithms for Java-like languages. - -

First Example

-The class Id has the method id. The type annotations are omitted. -
- -
 
-  class Id {
-      id(x) {
-          return x;
-      }
-  } 
- 
-The type inference algorithm inferrs the types, such that Id can be applied: -
-    new Id().id(1);
-
-    new Id().id("hallo");
-
- -

More complex example

-
-  import java.lang.Integer;
-  import java.lang.Double; 
-  import java.lang.String; 
-
-
-  class OL {
-     m(x) { return x + x; }
-	
-  }
-    
-         
-  class OLMain {
-     main(x) { 
-	var ol;
-	ol = new OL(); 
-	return ol.m(x); 
-     }  
-  }
-
-The type inference mechanism considers only imported types. Therefore Integer Double, and String are imported. -
-As the operator + is overloaded by all numeric types and String the methods m in the class OL and main in the class OLMain, respectively, gets all these types. The generated classfile demonstrates this: -
-> javap OL.class 
-Compiled from "OL.jav"
-class OL {
-  public OL();
-  public java.lang.Integer m(java.lang.Integer);
-  public java.lang.Double m(java.lang.Double);
-}
-
-> javap OLMain.class 
-Compiled from "OLMain.jav"
-class OLMain {
-  public OLMain();
-  public java.lang.Integer main(java.lang.Integer);
-  public java.lang.Double main(java.lang.Double);
-}
-
- - -
-
-Last modified: Fri Jun 1 16:43:55 CEST 2018 - diff --git a/Website/install/Restart.png b/Website/install/Restart.png deleted file mode 100644 index 5d3c3efc7..000000000 Binary files a/Website/install/Restart.png and /dev/null differ diff --git a/Website/install/availableSoftware1.png b/Website/install/availableSoftware1.png deleted file mode 100644 index 22097efef..000000000 Binary files a/Website/install/availableSoftware1.png and /dev/null differ diff --git a/Website/install/availableSoftware2.png b/Website/install/availableSoftware2.png deleted file mode 100644 index 7bdb93cc8..000000000 Binary files a/Website/install/availableSoftware2.png and /dev/null differ diff --git a/Website/install/instal.html b/Website/install/instal.html deleted file mode 100644 index 4b4e91c70..000000000 --- a/Website/install/instal.html +++ /dev/null @@ -1,40 +0,0 @@ - - -Install Java-TX Plugin - - - -

Install Java-TX Plugin

-
    -
  1. Select "Install New Software ..."
    - - -
  2. -
  3. Add ...
    - -
  4. -
  5. Insert address
    - -
  6. -
  7. Select installation
    - -
  8. -
  9. Installation details
    - -
  10. -
  11. Accept license agreement
    - -
  12. -
  13. Install anyway
    - -
  14. -
  15. Restart
    - -
  16. -
- - -
-
-Last modified: Fri Jun 1 11:57:15 CEST 2018 - diff --git a/Website/install/install.html b/Website/install/install.html deleted file mode 100644 index 11801117b..000000000 --- a/Website/install/install.html +++ /dev/null @@ -1,40 +0,0 @@ - - -Install Java-TX Plugin - - - -

Install Java-TX Plugin

-
    -
  1. Select "Install New Software ..."
    - - -
  2. -
  3. Add ...
    - -
  4. -
  5. Insert address
    - -
  6. -
  7. Select installation
    - -
  8. -
  9. Installation details
    - -
  10. -
  11. Accept license agreement
    - -
  12. -
  13. Install anyway
    - -
  14. -
  15. Restart
    - -
  16. -
- - -
-
-Last modified: Fri Jun 1 12:05:43 CEST 2018 - diff --git a/Website/install/installAnyway.png b/Website/install/installAnyway.png deleted file mode 100644 index 1e8796556..000000000 Binary files a/Website/install/installAnyway.png and /dev/null differ diff --git a/Website/install/installationDetails.png b/Website/install/installationDetails.png deleted file mode 100644 index 3032caa3b..000000000 Binary files a/Website/install/installationDetails.png and /dev/null differ diff --git a/Website/install/licenseAgreement.png b/Website/install/licenseAgreement.png deleted file mode 100644 index 4c20ccbb3..000000000 Binary files a/Website/install/licenseAgreement.png and /dev/null differ diff --git a/Website/install/newsoftware.png b/Website/install/newsoftware.png deleted file mode 100644 index 65c7005fb..000000000 Binary files a/Website/install/newsoftware.png and /dev/null differ diff --git a/Website/install/selectInstallation.png b/Website/install/selectInstallation.png deleted file mode 100644 index eb9a3cdf3..000000000 Binary files a/Website/install/selectInstallation.png and /dev/null differ diff --git a/Website/newJavaTXProject/addLibrary2.png b/Website/newJavaTXProject/addLibrary2.png deleted file mode 100644 index e008eeab3..000000000 Binary files a/Website/newJavaTXProject/addLibrary2.png and /dev/null differ diff --git a/Website/newJavaTXProject/buildPath1.png b/Website/newJavaTXProject/buildPath1.png deleted file mode 100644 index e008eeab3..000000000 Binary files a/Website/newJavaTXProject/buildPath1.png and /dev/null differ diff --git a/Website/newJavaTXProject/buildPath2.png b/Website/newJavaTXProject/buildPath2.png deleted file mode 100644 index 920cc9685..000000000 Binary files a/Website/newJavaTXProject/buildPath2.png and /dev/null differ diff --git a/Website/newJavaTXProject/buildPath3.png b/Website/newJavaTXProject/buildPath3.png deleted file mode 100644 index 8a7877c63..000000000 Binary files a/Website/newJavaTXProject/buildPath3.png and /dev/null differ diff --git a/Website/newJavaTXProject/buildPath4.png b/Website/newJavaTXProject/buildPath4.png deleted file mode 100644 index 1c3dd3381..000000000 Binary files a/Website/newJavaTXProject/buildPath4.png and /dev/null differ diff --git a/Website/newJavaTXProject/newJavFile.png b/Website/newJavaTXProject/newJavFile.png deleted file mode 100644 index 850492679..000000000 Binary files a/Website/newJavaTXProject/newJavFile.png and /dev/null differ diff --git a/Website/newJavaTXProject/newJavFolder1.png b/Website/newJavaTXProject/newJavFolder1.png deleted file mode 100644 index 73e82fee1..000000000 Binary files a/Website/newJavaTXProject/newJavFolder1.png and /dev/null differ diff --git a/Website/newJavaTXProject/newJavFolder2.png b/Website/newJavaTXProject/newJavFolder2.png deleted file mode 100644 index 47e339516..000000000 Binary files a/Website/newJavaTXProject/newJavFolder2.png and /dev/null differ diff --git a/Website/newJavaTXProject/newJavaTXProject.html b/Website/newJavaTXProject/newJavaTXProject.html deleted file mode 100644 index 263e40445..000000000 --- a/Website/newJavaTXProject/newJavaTXProject.html +++ /dev/null @@ -1,34 +0,0 @@ - - - - -

New Java-TX project in eclipse

-
    -
  1. New -> Java Project
    - -
  2. -
    -
  3. Generate a jav-File folder
    -

    - -
  4. -
    -
  5. Add jav-File folder as library
    - At the moment no package system is implemented, Therefore the compiled class files are in the jav-File folder. This has to be added as library:
    -

    -

    -

    -
    - - -
  6. -
- -

- - - -
-
-Last modified: Fri Jun 1 16:50:02 CEST 2018 - diff --git a/Website/newJavaTXProject/newJavaTXProject.png b/Website/newJavaTXProject/newJavaTXProject.png deleted file mode 100644 index 57fc7727f..000000000 Binary files a/Website/newJavaTXProject/newJavaTXProject.png and /dev/null differ diff --git a/Website/usePlugin/usePlugin.html b/Website/usePlugin/usePlugin.html deleted file mode 100644 index 45e744cfb..000000000 --- a/Website/usePlugin/usePlugin.html +++ /dev/null @@ -1,24 +0,0 @@ - - -Using the plugin - -

Using the plugin

-
    -
  1. Overview
    - -
  2. -
    -
  3. Select types
    - If the method is overloaded the user can select types in the outline the right mouse button:

    -
    -
  4. -
- -

- - - -
-
-Last modified: Fri Jun 1 16:51:28 CEST 2018 - diff --git a/Website/usePlugin/usePlugin1.png b/Website/usePlugin/usePlugin1.png deleted file mode 100644 index c6f47149e..000000000 Binary files a/Website/usePlugin/usePlugin1.png and /dev/null differ diff --git a/Website/usePlugin/usePlugin2.png b/Website/usePlugin/usePlugin2.png deleted file mode 100644 index aefeb0bfc..000000000 Binary files a/Website/usePlugin/usePlugin2.png and /dev/null differ diff --git a/doc/Generics/generics.tex b/doc/Generics/generics.tex new file mode 100644 index 000000000..bacd9f928 --- /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/logFiles/.gitkeep b/logFiles/.gitkeep new file mode 100644 index 000000000..e69de29bb diff --git a/pom.xml b/pom.xml index 603338b94..95b20386f 100644 --- a/pom.xml +++ b/pom.xml @@ -79,7 +79,7 @@ http://maven.apache.org/maven-v4_0_0.xsd"> org.antlr antlr4-maven-plugin - 4.7 + 4.8-1 antlr @@ -88,28 +88,13 @@ 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 - - aspParser - - antlr4 - - - src/main/antlr4/sat - ${project.basedir}/target/generated-sources/antlr4/de/dhbwstuttgart/sat/asp/parser/antlr - - -package - de.dhbwstuttgart.sat.asp.parser.antlr - - - - @@ -123,50 +108,18 @@ http://maven.apache.org/maven-v4_0_0.xsd"> + + + de.dhbwstuttgart.core.ConsoleInterface + + jar-with-dependencies - - org.reficio - p2-maven-plugin - 1.1.2-SNAPSHOT - - - default-cli - - - - - - de.dhbwstuttgart:JavaTXcompiler:0.2 - - - org.reflections:reflections:0.9.11 - - - com.google.guava:guava:22.0 - - - javax.annotation:javax.annotation-api:1.3.1 - - - org.glassfish:javax.annotation:3.1.1 - - - - - - - - - reficio - http://repo.reficio.org/maven/ - - maven-repository @@ -179,6 +132,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/bytecode/BytecodeGen.java b/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGen.java index 508bd5207..04f408af9 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; @@ -7,6 +8,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,13 +83,13 @@ 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; private ResultSet resultSet; private SourceFile sf; - private String path; + private File path; private Optional fieldInitializations; @@ -107,7 +109,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<>(); @@ -118,24 +120,26 @@ 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) { + public BytecodeGen(HashMap classFiles, Collection listOfResultSets, List simplifyResultsForAllSourceFiles, SourceFile sf, + File 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().toString()); + classGen.writeClass(cl.getClassName()); } } @@ -145,22 +149,22 @@ 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); + cw.visitSource(className.getClassName() + ".jav", null); isInterface = (classOrInterface.getModifiers() & 512) == 512; @@ -172,7 +176,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()); @@ -199,7 +203,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; @@ -269,7 +273,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); if (!field.getParameterList().iterator().hasNext() && !(field.block.statements.get(field.block.statements.size() - 1) instanceof ReturnVoid)) { mv.visitInsn(Opcodes.RETURN); @@ -350,7 +354,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); 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 46caa52b8..0565d9335 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,7 +15,9 @@ 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.*; import de.dhbwstuttgart.syntaxtree.statement.BinaryExpr.Operator; import de.dhbwstuttgart.syntaxtree.statement.UnaryExpr.Operation; @@ -45,7 +48,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; @@ -54,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; @@ -71,16 +74,18 @@ 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<>();; + private final ClassLoader classLoader; + // 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, File path, Block block, int constructorPos, ClassLoader classLoader) { this.className = className; this.superClass = superClass; @@ -98,16 +103,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(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,File path, ClassLoader classLoader) { this.className = className; this.superClass = superClass; @@ -124,14 +128,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(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, - HashMap genericsAndBounds) { + public BytecodeGenMethod(JavaClassName className, ClassWriter cw, LambdaExpression lambdaExpression, ArrayList usedVars, ResultSet resultSet, MethodVisitor mv, + int indexOfFirstParamLam, boolean isInterface, HashMap classFiles, File path, int lamCounter, SourceFile sf,HashMap genericsAndBoundsMethod, + HashMap genericsAndBounds, ClassLoader classLoader) { this.className = className; this.cw = cw; this.resultSet = resultSet; @@ -144,6 +148,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; @@ -172,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) { @@ -180,6 +186,7 @@ public class BytecodeGenMethod implements StatementVisitor { mv.visitInsn(Opcodes.POP); } } + paramsAndLocals = paramsAndLocalsOld; } @Override @@ -217,7 +224,7 @@ public class BytecodeGenMethod implements StatementVisitor { // ?? @Override public void visit(LocalVarDecl localVarDecl) { - + paramsAndLocals.put(localVarDecl.getName(), paramsAndLocals.size()+1); } @Override @@ -622,7 +629,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.getClassName(), desugaredMethodName, newDesc, false); // Descriptor of functional interface methode SamMethod samMethod = new SamMethod(kindOfLambda.getArgumentList(), lambdaExpression.getType()); // Desc: (this/nothing)TargetType @@ -636,7 +643,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(); @@ -756,7 +763,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; @@ -767,13 +774,13 @@ 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 = ""; while(true) { try { - superClass = helper.getSuperClass(receiverName); + superClass = helper.getSuperClass(receiverName.replace("/", ".")); try { String superClazz = superClass.replace("/", "."); @@ -781,7 +788,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) { @@ -797,7 +804,7 @@ public class BytecodeGenMethod implements StatementVisitor { } if(methodRefl == null) { - boolean toCreate = !receiverName.equals(className) && helper.isInCurrPkg(clazz); + boolean toCreate = !receiverName.equals(className.getClassName()) && helper.isInCurrPkg(clazz); if(toCreate) { try { mDesc = helper.getDesc(clazz); @@ -811,7 +818,7 @@ public class BytecodeGenMethod implements StatementVisitor { // mDesc = helper.generateBCForFunN(methCallType,typesOfParams); }else { try { - cLoader2 = new URLClassLoader(new URL[] {new URL("file://"+path)}); + 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 argListMethCall = new LinkedList<>(); String receiverRefl=""; - if(methodRefl == null && receiverName.equals(className)) { + if(methodRefl == null && receiverName.equals(className.getClassName())) { MethodFromMethodCall method = new MethodFromMethodCall(methodCall.arglist, methodCall.getType(), receiverName, genericsAndBoundsMethod, genericsAndBounds); mDesc = method.accept(new DescriptorToString(resultSet)); @@ -910,7 +917,7 @@ public class BytecodeGenMethod implements StatementVisitor { } return clazz; } - + private String[] getTypes(List arguments) { String[] types = new String[arguments.size()]; for(int i = 0; i[] pTypes = m.getParameterTypes(); for(int j = 0; j{ @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/bytecode/genericsGenerator/GeneratedGenericsFinder.java b/src/main/java/de/dhbwstuttgart/bytecode/genericsGenerator/GeneratedGenericsFinder.java index 5e473ebec..ba55c4c7a 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 a541025c7..8e5bd4812 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 90eaffa9e..3bcf19396 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 75d1aaa7c..79eaabd03 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; import java.util.Optional; @@ -14,11 +16,11 @@ import com.google.common.collect.Lists; * */ 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()); } /** @@ -26,8 +28,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; @@ -36,7 +38,7 @@ public class GenericsGeneratorResultForClass { /** * @return the className */ - public String getClassName() { + public JavaClassName getClassName() { return className; } diff --git a/src/main/java/de/dhbwstuttgart/bytecode/utilities/ByteCodeForFunNGenerator.java b/src/main/java/de/dhbwstuttgart/bytecode/utilities/ByteCodeForFunNGenerator.java index 2de61726a..24b5f627f 100644 --- a/src/main/java/de/dhbwstuttgart/bytecode/utilities/ByteCodeForFunNGenerator.java +++ b/src/main/java/de/dhbwstuttgart/bytecode/utilities/ByteCodeForFunNGenerator.java @@ -20,7 +20,7 @@ import java.util.Iterator; public class ByteCodeForFunNGenerator { - public static void generateBCForFunN(LambdaExpression lambdaExpression, String methDesc, String path) { + public static void generateBCForFunN(LambdaExpression lambdaExpression, String methDesc, File path) { ClassWriter classWriter = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS); SignatureWriter methSig = new SignatureWriter(); @@ -46,7 +46,7 @@ public class ByteCodeForFunNGenerator { writeClassFile(classWriter.toByteArray(), name, path); } - public static void generateBCForFunN(ArgumentList argumentList, String methDesc, String path) { + public static void generateBCForFunN(ArgumentList argumentList, String methDesc, File path) { ClassWriter classWriter = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS); SignatureWriter methSig = new SignatureWriter(); @@ -75,12 +75,12 @@ public class ByteCodeForFunNGenerator { } - public static void writeClassFile(byte[] bytecode, String name, String path) { + public static void writeClassFile(byte[] bytecode, String name, File path) { FileOutputStream output; try { System.out.println("generating " + name + ".class file..."); output = new FileOutputStream( - new File(path + name + CONSTANTS.EXTENSIONCLASS)); + new File(path , name + CONSTANTS.EXTENSIONCLASS)); output.write(bytecode); output.close(); System.out.println(name + ".class file generated"); diff --git a/src/main/java/de/dhbwstuttgart/bytecode/utilities/MethodCallHelper.java b/src/main/java/de/dhbwstuttgart/bytecode/utilities/MethodCallHelper.java index 00d6e3080..ad3e28fa2 100644 --- a/src/main/java/de/dhbwstuttgart/bytecode/utilities/MethodCallHelper.java +++ b/src/main/java/de/dhbwstuttgart/bytecode/utilities/MethodCallHelper.java @@ -16,6 +16,7 @@ import javassist.NotFoundException; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; +import java.io.File; import java.util.*; /** @@ -26,7 +27,7 @@ public class MethodCallHelper { private MethodCall methCall; private SourceFile sourceFile; private ResultSet resultSet; - private String path; + private File path; /** * @param methCall @@ -34,7 +35,7 @@ public class MethodCallHelper { * @param resultSet * @param path TODO */ - public MethodCallHelper(MethodCall methCall, SourceFile sourceFile, ResultSet resultSet, String path) { + public MethodCallHelper(MethodCall methCall, SourceFile sourceFile, ResultSet resultSet, File path) { this.methCall = methCall; this.sourceFile = sourceFile; this.resultSet = resultSet; diff --git a/src/main/java/de/dhbwstuttgart/core/ConsoleInterface.java b/src/main/java/de/dhbwstuttgart/core/ConsoleInterface.java index 77a172bf6..14314d837 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") || arg.equals("-classpath")){ + String[] cps = it.next().split(":"); + for(String cp : cps){ + classpath.add(new File(cp)); + } + }else{ + input.add(new File(arg)); + } + } + JavaTXCompiler compiler = new JavaTXCompiler(input, classpath); compiler.typeInference(); + compiler.generateBytecode(outputPath); } + + } diff --git a/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java b/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java index 0f86d0447..8425d1806 100644 --- a/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java +++ b/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java @@ -1,21 +1,38 @@ //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; 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; @@ -41,57 +58,140 @@ 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.antlr.v4.runtime.Token; +import org.apache.commons.io.output.NullOutputStream; + 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); + } 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); + } + 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 File(System.getProperty("user.dir"))); + } + classLoader = new DirectoryClassLoader(contextPath, ClassLoader.getSystemClassLoader()); + environment = new CompilationEnvironment(sources); for (File s : sources) { sourceFiles.put(s, parse(s)); } //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<>(); + 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 (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.getSystemClassLoader().loadClass(name.toString())); + classLoader.loadClass(name.toString())); importedClasses.add(importedClass); } + for(Class c : CompilationEnvironment.loadDefaultPackageClasses(forSourceFile, classLoader)){ + ClassOrInterface importedClass = ASTFactory.createClass(c); + importedClasses.add(importedClass); + } + } + 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. + 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 { + //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(); + //TODO: PL 2020-05-06: Hier müssen ueberschriebene Methoden noch rausgefiltert werden + 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, + //new GenericDeclarationList(newGenericsList, ((GenericDeclarationList)m.getGenerics()).getOffset()), + (GenericDeclarationList)m.getGenerics(), + m.getOffset(), true)); + } + + } + cl.setMethodsAdded(); + } + + public List getAvailableClasses(SourceFile forSourceFile) throws ClassNotFoundException { //PL 2018-09-18: List durch Set ersetzt, damit die Klassen nur einmal hinzugefuegt werden @@ -122,7 +222,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); } @@ -275,12 +375,14 @@ 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()) { + 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(); @@ -291,7 +393,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); @@ -428,13 +530,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) { @@ -443,26 +545,28 @@ 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()) { + 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(); 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())); - IFiniteClosure finiteClosure = UnifyTypeFactory.generateFC(allClasses, logFile); + 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) @@ -474,7 +578,9 @@ public class JavaTXCompiler { return x; }; + 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(); @@ -482,6 +588,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(); @@ -570,6 +677,23 @@ 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); @@ -594,13 +718,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); @@ -708,12 +832,39 @@ 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; } + public void generateBytecodForFile(File path, HashMap classFiles, SourceFile sf, + List typeinferenceResult) throws IOException { + try { + List genericResults = getGeneratedGenericResultsForAllSourceFiles(typeinferenceResult); + BytecodeGen bytecodeGen = new BytecodeGen(classFiles,typeinferenceResult, genericResults, sf,path, classLoader); + bytecodeGen.visit(sf); + this.writeClassFile(bytecodeGen.getClassFiles(), path); + } catch (ClassNotFoundException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + + public List getGeneratedGenericResultsForAllSourceFiles() + throws ClassNotFoundException, IOException { + List result = new ArrayList<>(); + for (File f : sourceFiles.keySet()) { + SourceFile sf = sourceFiles.get(f); + List typeinferenceResult = this.typeInference(); + GeneratedGenericsFinder sResFinder = new GeneratedGenericsFinder(sf, typeinferenceResult); + GenericGenratorResultForSourceFile simplifyResOfSF = sResFinder.findGeneratedGenerics(); + result.add(simplifyResOfSF); + } + return result; + } + public List getGeneratedGenericResultsForAllSourceFiles( List typeinferenceResult) throws ClassNotFoundException { List result = new ArrayList<>(); @@ -726,8 +877,24 @@ public class JavaTXCompiler { return result; } - // um pfad erweitern + public void generateBytecode() throws ClassNotFoundException, IOException, BytecodeGeneratorError { + 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); @@ -735,35 +902,91 @@ public class JavaTXCompiler { } /** - * @param path + * @param outputPath - can be null, then class file output is in the same directory as the parsed source files * @param typeinferenceResult * @param simplifyResultsForAllSourceFiles * @throws IOException */ - public void generateBytecode(String path, List typeinferenceResult, + public void generateBytecode(File outputPath, List typeinferenceResult, List simplifyResultsForAllSourceFiles) throws IOException { for (File f : sourceFiles.keySet()) { - HashMap classFiles = new HashMap<>(); + HashMap classFiles = new HashMap<>(); SourceFile sf = sourceFiles.get(f); + File path; + if(outputPath == null){ + path = f.getParentFile(); //Set path to path of the parsed .jav file + }else{ + path = new File(outputPath ,sf.getPkgName().replace(".","/")); //add package path to root path + } BytecodeGen bytecodeGen = new BytecodeGen(classFiles, typeinferenceResult, simplifyResultsForAllSourceFiles, - sf, path); + sf, path, classLoader); bytecodeGen.visit(sf); writeClassFile(bytecodeGen.getClassFiles(), path); } } - private void writeClassFile(HashMap classFiles, String path) throws IOException { + private void writeClassFile(HashMap classFiles, File 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")); + File outputFile = new File(path, name.getClassName() + ".class"); + outputFile.getAbsoluteFile().getParentFile().mkdirs(); + output = new FileOutputStream(outputFile); output.write(bytecode); output.close(); 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) { + return typePlaceholder; //TypePlaceholder der vererbert wird kann bei der Vererbung nicht instanziert werden. + } + + @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()); + } + + } } diff --git a/src/main/java/de/dhbwstuttgart/environment/CompilationEnvironment.java b/src/main/java/de/dhbwstuttgart/environment/CompilationEnvironment.java index 3d450183c..746d1e850 100644 --- a/src/main/java/de/dhbwstuttgart/environment/CompilationEnvironment.java +++ b/src/main/java/de/dhbwstuttgart/environment/CompilationEnvironment.java @@ -4,18 +4,12 @@ import java.io.File; 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.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 org.antlr.v4.runtime.tree.TerminalNode; import de.dhbwstuttgart.exceptions.DebugException; import de.dhbwstuttgart.parser.JavaTXParser; @@ -49,8 +43,7 @@ public class CompilationEnvironment { * */ //String bootClassPath = System.getProperty("sun.boot.class.path"); - // ClassLoader cl = ClassLoader.getPlatformClassLoader(); - ClassLoader cl = ClassLoader.getSystemClassLoader(); + // DirectoryClassLoader cl = DirectoryClassLoader.getPlatformClassLoader(); String bootClassPath = System.getProperty("java.class.path"); librarys = new ArrayList<>(); for(String path : bootClassPath.split(File.pathSeparator)) { @@ -67,13 +60,44 @@ 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); + for(Class c : loadDefaultPackageClasses(forSourceFile, classLoader)){ + allNames.put(c.getName(), c.getTypeParameters().length); + } return new JavaClassRegistry(allNames); } + 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 + 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; + 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) { + 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 = ""; + if(forTree.packageDeclaration() != null && forTree.packageDeclaration().Identifier() != null) + 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/environment/DirectoryClassLoader.java b/src/main/java/de/dhbwstuttgart/environment/DirectoryClassLoader.java new file mode 100644 index 000000000..a74dbc490 --- /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 7c63a0b6d..646440b17 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/parser/SyntaxTreeGenerator/FCGenerator.java b/src/main/java/de/dhbwstuttgart/parser/SyntaxTreeGenerator/FCGenerator.java index 29c539817..71dcef529 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/parser/SyntaxTreeGenerator/StatementGenerator.java b/src/main/java/de/dhbwstuttgart/parser/SyntaxTreeGenerator/StatementGenerator.java index 067430e26..c4625a7a5 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; } @@ -279,9 +285,24 @@ 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()); + 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) { @@ -767,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(); } @@ -821,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) { @@ -879,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/parser/SyntaxTreeGenerator/SyntaxTreeGenerator.java b/src/main/java/de/dhbwstuttgart/parser/SyntaxTreeGenerator/SyntaxTreeGenerator.java index 6f1300dcc..33559a8e1 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 694815083..8e93355bc 100644 --- a/src/main/java/de/dhbwstuttgart/parser/scope/GatherNames.java +++ b/src/main/java/de/dhbwstuttgart/parser/scope/GatherNames.java @@ -1,13 +1,13 @@ 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; 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; @@ -15,7 +15,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 +64,12 @@ public class GatherNames { } } } - ret.putAll(getImports(ctx, packages)); - return ret; + 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/main/java/de/dhbwstuttgart/parser/scope/JavaClassName.java b/src/main/java/de/dhbwstuttgart/parser/scope/JavaClassName.java index b87ff719a..534d0916f 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/syntaxtree/ClassOrInterface.java b/src/main/java/de/dhbwstuttgart/syntaxtree/ClassOrInterface.java index bbd184f0d..c99caa53c 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<>(); @@ -34,6 +35,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 +52,33 @@ 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 if it is added + public Boolean areMethodsAdded() { + return methodAdded; + } + + //Sets that 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/syntaxtree/Constructor.java b/src/main/java/de/dhbwstuttgart/syntaxtree/Constructor.java index 8be687f8e..24b3bb81e 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/Method.java b/src/main/java/de/dhbwstuttgart/syntaxtree/Method.java index 33722c095..13e36b7b3 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/SourceFile.java b/src/main/java/de/dhbwstuttgart/syntaxtree/SourceFile.java index 945ee5d8c..4a22147be 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/syntaxtree/factory/ASTFactory.java b/src/main/java/de/dhbwstuttgart/syntaxtree/factory/ASTFactory.java index 2fb32dbee..fc704572f 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()){ @@ -70,7 +80,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) { @@ -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){ @@ -189,11 +199,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/main/java/de/dhbwstuttgart/syntaxtree/factory/UnifyTypeFactory.java b/src/main/java/de/dhbwstuttgart/syntaxtree/factory/UnifyTypeFactory.java index 1d7decee1..b60270b38 100644 --- a/src/main/java/de/dhbwstuttgart/syntaxtree/factory/UnifyTypeFactory.java +++ b/src/main/java/de/dhbwstuttgart/syntaxtree/factory/UnifyTypeFactory.java @@ -28,7 +28,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 @@ -39,7 +39,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){ @@ -119,6 +119,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); @@ -149,8 +150,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)); + Constraint unifyPairConstraint = constraint.stream() + .map(UnifyTypeFactory::convert) + .collect(Collectors.toCollection( () -> new Constraint (constraint.isInherited(), convert(constraint.getExtendConstraint())))); + return unifyPairConstraint; } public static UnifyPair convert(Pair p) { diff --git a/src/main/java/de/dhbwstuttgart/syntaxtree/statement/MethodCall.java b/src/main/java/de/dhbwstuttgart/syntaxtree/statement/MethodCall.java index f6307f1e2..752676197 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 d29f3d53b..f27bc3e8c 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 42cfb8ee0..3b7eebbff 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 e82405c0d..26579d2fb 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); } diff --git a/src/main/java/de/dhbwstuttgart/syntaxtree/type/TypePlaceholder.java b/src/main/java/de/dhbwstuttgart/syntaxtree/type/TypePlaceholder.java index 2edf6f22c..cdc204b0e 100644 --- a/src/main/java/de/dhbwstuttgart/syntaxtree/type/TypePlaceholder.java +++ b/src/main/java/de/dhbwstuttgart/syntaxtree/type/TypePlaceholder.java @@ -18,7 +18,12 @@ import org.antlr.v4.runtime.Token; public class TypePlaceholder extends RefTypeOrTPHOrWildcardOrGeneric { private final String name; - + + /** + * wird bisher nicht genutzt + * setVariance muss ggf. auskommentiert werden. + */ + int variance = 0; /** @@ -69,6 +74,16 @@ 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; + } + @Override public void accept(ASTVisitor visitor) { visitor.visit(this); diff --git a/src/main/java/de/dhbwstuttgart/syntaxtree/visual/OutputGenerator.java b/src/main/java/de/dhbwstuttgart/syntaxtree/visual/OutputGenerator.java index 3dfca38ae..078a74073 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/typedeployment/TypeInsertFactory.java b/src/main/java/de/dhbwstuttgart/typedeployment/TypeInsertFactory.java index 4959585f5..54a988c63 100644 --- a/src/main/java/de/dhbwstuttgart/typedeployment/TypeInsertFactory.java +++ b/src/main/java/de/dhbwstuttgart/typedeployment/TypeInsertFactory.java @@ -65,7 +65,7 @@ public class TypeInsertFactory { /* PL 2020-04-11 auskommentiert 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/main/java/de/dhbwstuttgart/typedeployment/TypeInsertPlacer.java b/src/main/java/de/dhbwstuttgart/typedeployment/TypeInsertPlacer.java index ef65a4458..042a76ebd 100644 --- a/src/main/java/de/dhbwstuttgart/typedeployment/TypeInsertPlacer.java +++ b/src/main/java/de/dhbwstuttgart/typedeployment/TypeInsertPlacer.java @@ -33,7 +33,7 @@ public class TypeInsertPlacer extends AbstractASTWalker{ public void visit(ClassOrInterface classOrInterface) { GenericsGeneratorResultForClass generatedGenerics = simplifyResultsForAllSourceFiles .stream() - .map(sr->sr.getSimplifyResultsByName(pkgName, classOrInterface.getClassName().toString())) + .map(sr->sr.getSimplifyResultsByName(classOrInterface.getClassName())) .findFirst() .get(); TypeInsertPlacerClass cl = new TypeInsertPlacerClass(classOrInterface, withResults, generatedGenerics); diff --git a/src/main/java/de/dhbwstuttgart/typeinference/assumptions/MethodAssumption.java b/src/main/java/de/dhbwstuttgart/typeinference/assumptions/MethodAssumption.java index c1a6d4498..6e6c5c5a9 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 476f18dda..8715fe552 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/constraints/Constraint.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/constraints/Constraint.java @@ -7,4 +7,47 @@ 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(); + } + + public Constraint(Boolean isInherited) { + this.isInherited = isInherited; + } + + public Constraint(Boolean isInherited, Constraint extendConstraint) { + this.isInherited = isInherited; + this.extendConstraint = extendConstraint; + } + + public void setIsInherited(Boolean isInherited) { + this.isInherited = isInherited; + } + + public Boolean isInherited() { + return isInherited; + } + + public Constraint getExtendConstraint() { + return extendConstraint; + } + + public void setExtendConstraint(Constraint c) { + extendConstraint = c; + } + + public String toString() { + return super.toString() + " isInherited = " + isInherited + //" + extendsContraint: " + (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 1dda8dc55..31a466dd1 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(){ @@ -41,16 +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) -> - as.stream().map(o).collect(Collectors.toCollection(Constraint::new))).collect(Collectors.toSet()) + oderConstraint.parallelStream().map((Constraint as) -> { + + 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/TYPE.java b/src/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPE.java index 246c36912..c84fa1435 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/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java b/src/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java index 30d76167e..ac643f381 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java @@ -16,7 +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; @@ -159,13 +162,27 @@ 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: - 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)); + Constraint oneMethodConstraint = generateConstraint(methodCall, m, info, resolver); + methodConstraints.add(oneMethodConstraint); + + 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(oneMethodConstraint.isInherited()))); + oneMethodConstraint.setExtendConstraint(extendsOneMethodConstraint); + extendsOneMethodConstraint.setExtendConstraint(oneMethodConstraint); + methodConstraints.add(extendsOneMethodConstraint); } if(methodConstraints.size()<1){ throw new TypeinferenceException("Methode "+methodCall.name+" ist nicht vorhanden!",methodCall.getOffset()); @@ -222,6 +239,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 +267,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 +275,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 +283,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 +291,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 +299,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 +307,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 +381,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 +393,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(); } @@ -555,7 +574,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<>(); @@ -569,7 +588,13 @@ 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 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)); methodConstraint.addAll(generateParameterConstraints(forMethod, assumption, info, resolver)); @@ -584,6 +609,10 @@ 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)); + + //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; } @@ -611,7 +640,7 @@ public class TYPEStmt implements StatementVisitor{ public RefTypeOrTPHOrWildcardOrGeneric getReturnType() { throw new NotImplementedException(); } - })); + }, false)); } for(ClassOrInterface cl : info.getAvailableClasses()){ for(Method m : cl.getMethods()){ @@ -620,7 +649,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)); } } } @@ -655,7 +684,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)); } } } @@ -666,8 +695,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/main/java/de/dhbwstuttgart/typeinference/unify/Match.java b/src/main/java/de/dhbwstuttgart/typeinference/unify/Match.java index 75469f642..914066121 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/RuleSet.java b/src/main/java/de/dhbwstuttgart/typeinference/unify/RuleSet.java index a392a2fa2..93f33d087 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/unify/RuleSet.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/unify/RuleSet.java @@ -26,11 +26,15 @@ 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; 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 +47,7 @@ public class RuleSet implements IRuleSet{ public RuleSet() { super(); + logFile = new OutputStreamWriter(new NullOutputStream()); } RuleSet(Writer logFile) { @@ -627,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<>(); @@ -674,16 +679,13 @@ 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)); - 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); - //} - } + Function,? extends Constraint> applyUni = b -> b.stream().map( + 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/TypeUnify.java b/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnify.java index 6b0455479..d78d8c8da 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 54c3fb998..798c6f05c 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 d3ebe2c65..6de6b9de7 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java @@ -28,11 +28,13 @@ 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; 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; @@ -100,11 +102,11 @@ public class TypeUnifyTask extends RecursiveTask>> { protected Set eq; //und-constraints - protected List>> oderConstraintsField; + protected List>> oderConstraintsField; protected IFiniteClosure fc; - protected Ordering> oup; + protected OrderingExtend> oup; protected boolean parallel; @@ -145,7 +147,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)); @@ -252,7 +254,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); @@ -297,7 +299,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()); @@ -319,8 +321,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 */ @@ -368,7 +369,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); @@ -396,8 +397,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 @@ -445,8 +446,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); } } @@ -461,7 +462,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 @@ -497,7 +498,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; @@ -587,23 +588,24 @@ 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); - writeLog("nextSet: " + nextSet.toString()); + Set> nextSet = remainingSets.remove(0); + //writeLog("nextSet: " + nextSet.toString()); List> nextSetasList =new ArrayList<>(nextSet); + /* try { //List> //nextSetasList = oup.sortedCopy(nextSet);//new ArrayList<>(nextSet); @@ -611,19 +613,21 @@ public class TypeUnifyTask extends RecursiveTask>> { catch (java.lang.IllegalArgumentException e) { System.out.print(""); } + */ Set> result = new HashSet<>(); int variance = 0; ArrayList zeroNextElem = new ArrayList<>(nextSetasList.get(0)); UnifyPair fstBasePair = zeroNextElem.remove(0).getBasePair(); + Boolean oderConstraint = false; if (fstBasePair != null) { Boolean sameBase = true; 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 @@ -635,50 +639,47 @@ public class TypeUnifyTask extends RecursiveTask>> { } } else { - variance = 2; + //variance = 2; + oderConstraint = true; } + } + else { + //variance = 2; + oderConstraint = true; + } + + if (oderConstraint) {//Varianz-Bestimmung Oder-Constraints + if (printtag) System.out.println("nextSetasList " + nextSetasList); + Optional optVariance = + nextSetasList.iterator() + .next() + .stream() + .filter(x -> x.getGroundBasePair().getLhsType() instanceof PlaceholderType && + ! (x.getRhsType() instanceof PlaceholderType) && + x.getPairOp() == PairOperator.EQUALSDOT) + .map(x -> + ((PlaceholderType)x.getGroundBasePair().getLhsType()).getVariance()) + .findAny(); + //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; + } - } - else { - variance = 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 (!nextSetasList.iterator().hasNext()) 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<>(); - if (variance != 2) { - Optional optOrigPair = nextSetElem.stream().filter(x -> ( + Optional optOrigPair = null; + //if (variance != 2) { + if (!oderConstraint) { + optOrigPair = nextSetElem.stream().filter(x -> ( //x.getBasePair() != null && ist gegeben wenn variance != 2 //x.getBasePair().getPairOp().equals(PairOperator.SMALLERDOT) && (x.getPairOp().equals(PairOperator.EQUALSDOT) @@ -711,12 +712,23 @@ public class TypeUnifyTask extends RecursiveTask>> { Set a = null; while (nextSetasList.size() > 0) { //(nextSetasList.size() != 0) { Set a_last = a; + + //Liste der Faelle für die parallele Verarbeitung List> nextSetasListRest = new ArrayList<>(); - //List> nextSetasListRestMin = new ArrayList<>(); - //List> nextSetasListRestOder = new ArrayList<>(); + + //Liste der Faelle, bei dem Receiver jeweils "? extends" enthaelt bzw. nicht enthaelt + //In der Regel ein Element + List> nextSetasListOderConstraints = new ArrayList<>(); + + writeLog("nextSet: " + nextSet.toString()); + writeLog("nextSetasList: " + nextSetasList.toString()); if (variance == 1) { a = oup.max(nextSetasList.iterator()); nextSetasList.remove(a); + if (oderConstraint) { + nextSetasListOderConstraints.add(((Constraint)a).getExtendConstraint()); + } + writeLog("nextSetasListOderConstraints 1: " + nextSetasListOderConstraints); nextSetasListRest = new ArrayList<>(nextSetasList); Iterator> nextSetasListItRest = new ArrayList>(nextSetasListRest).iterator(); while (nextSetasListItRest.hasNext()) { @@ -726,26 +738,17 @@ public class TypeUnifyTask extends RecursiveTask>> { nextSetasListRest.remove(a_next); } } - //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)); + //Alle maximale Elemente in nextSetasListRest bestimmen + nextSetasListRest = oup.maxElements(nextSetasListRest); } 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(); @@ -757,50 +760,38 @@ public class TypeUnifyTask extends RecursiveTask>> { } } //Alle minimalen Elemente in nextSetasListRest bestimmen - - 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)); + nextSetasListRest = oup.minElements(nextSetasListRest); } else if (variance == 2) { a = nextSetasList.remove(0); 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 { + 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"); //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 @@ -817,7 +808,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) && @@ -850,7 +841,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 */ @@ -875,10 +866,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())) @@ -890,21 +882,24 @@ 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 */ - + else { + nextSetasListOderConstraints.add(((Constraint)nSaL).getExtendConstraint()); + } 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); @@ -966,7 +961,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 */ @@ -990,8 +985,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) @@ -1006,21 +1002,24 @@ 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 */ - + else { + nextSetasListOderConstraints.add(((Constraint)nSaL).getExtendConstraint()); + } 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); @@ -1083,7 +1082,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 */ @@ -1103,10 +1102,10 @@ 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); + 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); @@ -1161,7 +1160,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; @@ -1292,129 +1291,132 @@ 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()); 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); - } - else { - writeLog("Not Removed: " + a_next.toString()); - System.out.println(""); + 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); + 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); + nextSetasList.removeAll(erased); + + writeLog("Removed: " + erased); + + writeLog("Not Removed: " + nextSetasList); + } + } } 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()); 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 + 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); + + //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<>(); + + //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 + 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); + nextSetasList.removeAll(erased); + + writeLog("Removed: " + erased); + + writeLog("Not Removed: " + nextSetasList); + } - else { - System.out.println(""); - writeLog("Not Removed: " + a_next.toString()); - } } - } + 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); + + nextSetasList.removeAll(erased); + + writeLog("Removed: " + erased); + + writeLog("Not Removed: " + nextSetasList); + } + } } else { if (variance == 0) { writeLog("a: " + rekTiefe + " variance: " + variance + a.toString()); - break; } - 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; + if (!oderConstraint) { + 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); + + } + + } + else { if (variance == 2) { }}} writeLog("a: " + rekTiefe + " variance: " + variance + a.toString()); } @@ -1433,7 +1435,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() ); @@ -1454,6 +1456,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) { @@ -1462,6 +1465,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)) @@ -1490,7 +1494,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; } @@ -1808,9 +1812,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++) @@ -1818,18 +1823,54 @@ public class TypeUnifyTask extends RecursiveTask>> { ArrayList eq2sprime = new ArrayList<>(eq2s); 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) - || (up.getRhsType() instanceof PlaceholderType && ((PlaceholderType)up.getRhsType()).getVariance() != 0)) { - eq2sAsList.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() == 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); eq2s.remove(up); } } - if (eq2sAsList.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) @@ -1839,26 +1880,62 @@ 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)); - ret.stream().forEach(x -> x.stream().forEach(y -> y.addSubstitutions(x))); + + //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() + && 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); + })); result.get(8).add(ret); first = false; } } + writeLog("eq2s: " + eq2s.toString()); + writeLog("eq2sAsListFst: " + eq2sAsListFst.toString()); + writeLog("eq2sAsListSnd: " + eq2sAsListSnd.toString()); + writeLog("eq2sAsListBack: " + eq2sAsListBack.toString()); + + eq2sAsList.addAll(eq2sAsListFst); + eq2sAsList.addAll(eq2sAsListSnd); + eq2sAsList.addAll(eq2sAsListThird); + eq2sAsList.addAll(eq2sAsListFourth); 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()) { - 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<>(); - //ret.stream().forEach(x -> retFlat.addAll(x)); - ret.stream().forEach(x -> x.stream().forEach(y -> y.addSubstitutions(x))); + //ret.stream().forEach(x -> retFlat.addAll(x)); + + //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() + && 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); + })); result.get(8).add(ret); first = false; } @@ -2078,8 +2155,15 @@ 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(); + 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; @@ -2097,7 +2181,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 @@ -2111,13 +2195,19 @@ 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); + } + 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, @@ -2125,7 +2215,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<>(); @@ -2141,8 +2231,8 @@ public class TypeUnifyTask extends RecursiveTask>> { for(TypeParams tp : permuteParams(candidateParams)) thetaQPrimes.add(c.setTypeParams(tp)); } - - for(UnifyType tqp : thetaQPrimes) { + 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); if (!opt.isPresent()) { @@ -2161,7 +2251,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)) @@ -2203,16 +2296,14 @@ 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()); } } - } } - + writeLog("result von " + pair + ": " + result.toString()); return result; } @@ -2222,7 +2313,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(); @@ -2237,7 +2327,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; @@ -2250,7 +2339,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(); @@ -2266,7 +2354,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()); @@ -2279,7 +2366,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; @@ -2343,7 +2429,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()); @@ -2358,8 +2443,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)); @@ -2379,7 +2463,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/interfaces/IRuleSet.java b/src/main/java/de/dhbwstuttgart/typeinference/unify/interfaces/IRuleSet.java index 752ff8b28..bac6bcb0e 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/main/java/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java b/src/main/java/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java index 95c903773..a48db2aa2 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,17 @@ 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 +104,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 @@ -655,6 +670,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(""); /* @@ -711,13 +727,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,17 +750,22 @@ 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; - 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/Node.java b/src/main/java/de/dhbwstuttgart/typeinference/unify/model/Node.java index d108e91bb..031130cff 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/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 000000000..8fa32343a --- /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; + } +} 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 736186d53..ce2fbd21b 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/unify/model/OrderingUnifyPair.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/unify/model/OrderingUnifyPair.java @@ -4,22 +4,25 @@ 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; import java.util.Set; import java.util.function.BinaryOperator; +import java.util.function.Function; import java.util.stream.Collectors; 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; -public class OrderingUnifyPair extends Ordering> { +public class OrderingUnifyPair extends OrderingExtend> { protected IFiniteClosure fc; @@ -42,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) { @@ -165,16 +168,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 +196,135 @@ public class OrderingUnifyPair extends Ordering> { //if (lefteq.iterator().next().getLhsType().getName().equals("AJO")) { // System.out.print(""); //} + + //ODER-CONSTRAINT + 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 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 PlaceholderType) && + x.getPairOp() == PairOperator.EQUALSDOT);}) + .collect(Collectors.toCollection(HashSet::new)); + Set lefteqRet = left.stream() + .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 -> { 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)) + .collect(Collectors.toCollection(HashSet::new)); + 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) { + } + } + */ + + + Integer compareEq; + if (lefteqOder.size() == 1 && righteqOder.size() == 1 && lefteqRet.size() == 1 && righteqRet.size() == 1) { + Match m = new Match(); + if ((compareEq = compareEq(lefteqOder.iterator().next().getGroundBasePair(), righteqOder.iterator().next().getGroundBasePair())) == -1) { + ArrayList matchList = + 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()) { + //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())) + .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; + } + } + + if (lefteq.size() == 1 && lefteq.iterator().next().getRhsType() instanceof ExtendsType && leftle.size() == 1 && righteq.size() == 0 && rightle.size() == 1) { return 1; } @@ -293,24 +416,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); 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 aafecf15a..497fd8110 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; } @@ -156,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) { @@ -213,11 +200,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) @@ -233,12 +222,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()+ "])"; } diff --git a/src/test/java/AllgemeinTest.java b/src/test/java/AllgemeinTest.java new file mode 100644 index 000000000..73f29ea98 --- /dev/null +++ b/src/test/java/AllgemeinTest.java @@ -0,0 +1,63 @@ + + +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"; + //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"; + //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/InheritTest.java b/src/test/java/bytecode/InheritTest.java new file mode 100644 index 000000000..19c16612b --- /dev/null +++ b/src/test/java/bytecode/InheritTest.java @@ -0,0 +1,193 @@ +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 InheritTest { + 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/Inherit.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("Inherit"); + instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); + } + + @Test + public void testInheritClassName() { + assertEquals("Inherit", 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 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"); + } + + @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 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 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 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/java/bytecode/InheritTest2.java b/src/test/java/bytecode/InheritTest2.java new file mode 100644 index 000000000..366027048 --- /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/java/bytecode/OLTest.java b/src/test/java/bytecode/OLTest.java index d9de9f256..5b98c7ff8 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/bytecode/PutTest.java b/src/test/java/bytecode/PutTest.java new file mode 100644 index 000000000..b5fd39d1a --- /dev/null +++ b/src/test/java/bytecode/PutTest.java @@ -0,0 +1,86 @@ +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(); + } + + @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()); + } +} diff --git a/src/test/java/bytecode/mathStrucMatrixOPTest.java.txt b/src/test/java/bytecode/mathStrucMatrixOPTest.java.txt new file mode 100644 index 000000000..30668595f --- /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 000000000..d26360dc9 --- /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/finiteClosure/SuperInterfacesTest.java b/src/test/java/finiteClosure/SuperInterfacesTest.java index 0e1368c3b..d74215b7b 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/src/test/java/packages/Bytecode.java b/src/test/java/packages/Bytecode.java new file mode 100644 index 000000000..7b5bb9588 --- /dev/null +++ b/src/test/java/packages/Bytecode.java @@ -0,0 +1,52 @@ +package packages; + +import de.dhbwstuttgart.core.JavaTXCompiler; +import junit.framework.TestCase; +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/"; + @Test + public void testSetPackageNameInBytecode() throws Exception { + JavaTXCompiler compiler = new JavaTXCompiler(new File(rootDirectory+"de/test/TestClass.jav")); + compiler.typeInference(); + File f = new File(rootDirectory + "de/test/TestClass.class"); + if(f.exists() && !f.isDirectory()) { + f.delete(); + } + compiler.generateBytecode(); + 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 Exception { + JavaTXCompiler compiler = new JavaTXCompiler(new File(rootDirectory+"de/test/TestClass.jav")); + compiler.typeInference(); + File f = new File(rootDirectory + "de/test/output/de/test/TestClass.class"); + if(f.exists() && !f.isDirectory()) { + f.delete(); + } + 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/CheckPackageFolder.java b/src/test/java/packages/CheckPackageFolder.java new file mode 100644 index 000000000..4f5454859 --- /dev/null +++ b/src/test/java/packages/CheckPackageFolder.java @@ -0,0 +1,80 @@ +package packages; + +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; +import java.util.Arrays; + +public class CheckPackageFolder extends TestCase { + + public static final String rootDirectory = System.getProperty("user.dir")+"/src/test/resources/javFiles/packageTest/de/test/"; + + @Test + public void testCorrectFolder1FileWithWrongPackageName() throws IOException, ClassNotFoundException { + JavaTXCompiler compiler = new JavaTXCompiler(new File(rootDirectory+"packageNameTestWrongPackage.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 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 + 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/java/packages/ConsoleInterfaceTest.java b/src/test/java/packages/ConsoleInterfaceTest.java new file mode 100644 index 000000000..c92bc8a95 --- /dev/null +++ b/src/test/java/packages/ConsoleInterfaceTest.java @@ -0,0 +1,133 @@ +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 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")); + 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()); + } + +} diff --git a/src/test/java/packages/ImportTest.java b/src/test/java/packages/ImportTest.java new file mode 100644 index 000000000..dc4596291 --- /dev/null +++ b/src/test/java/packages/ImportTest.java @@ -0,0 +1,108 @@ +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 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(); + f = new File(rootDirectory + "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 + public void testSetPackageNameInBytecodeAndOutputFolder() throws IOException, ClassNotFoundException { + JavaTXCompiler compiler = new JavaTXCompiler( + Lists.newArrayList(new File(rootDirectory+"ImportTest.jav")), + Lists.newArrayList(new File(rootDirectory+"output/"))); + 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()); + } + + @Test + public void testSetPackageNameInBytecodeAndStandardOutputFolder() throws IOException, ClassNotFoundException { + JavaTXCompiler compiler = new JavaTXCompiler( + Lists.newArrayList(new File(rootDirectory+"ImportTest.jav")), + Lists.newArrayList(new File(rootDirectory+"output/"))); + compiler.typeInference(); + File f = new File(rootDirectory + "ImportTest.class"); + if(f.exists() && !f.isDirectory()) { + f.delete(); + } + compiler.generateBytecode(); + 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 File(rootDirectory+"output/"))); + compiler.typeInference(); + File f = new File(rootDirectory + "ImportTest2.class"); + if(f.exists() && !f.isDirectory()) { + f.delete(); + } + compiler.generateBytecode(); + 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(); + f = new File(rootDirectory + "ImportTestDefault.class"); + assertTrue(f.exists()); + } + + +} diff --git a/src/test/java/packages/LoadDefaultPackageClassesTest.java b/src/test/java/packages/LoadDefaultPackageClassesTest.java new file mode 100644 index 000000000..8a3aa3c0d --- /dev/null +++ b/src/test/java/packages/LoadDefaultPackageClassesTest.java @@ -0,0 +1,55 @@ +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( + 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"); + 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"); + } +/* + 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()); + } + */ +} diff --git a/src/test/java/packages/OLOneFileTest.java b/src/test/java/packages/OLOneFileTest.java new file mode 100644 index 000000000..64b1a2b14 --- /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/java/packages/OLTest.java b/src/test/java/packages/OLTest.java new file mode 100644 index 000000000..c45b387db --- /dev/null +++ b/src/test/java/packages/OLTest.java @@ -0,0 +1,147 @@ +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 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 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 { + 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( + 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), 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( + 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), new URL("file://"+ rootDirectory + "/de/test/output/")}); + classToTest2 = loader.loadClass("OLMain"); + instanceOfClass2 = classToTest2.getDeclaredConstructor().newInstance(); + } + + @Test + public void testOLClassName() { + assertEquals("de.test.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 testOLextendsClassName() { + assertEquals("OLextends", classToTest1.getName()); + } + + @Test + 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 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 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/java/packages/ParsePackageName.java b/src/test/java/packages/ParsePackageName.java new file mode 100644 index 000000000..9dc0ea9ab --- /dev/null +++ b/src/test/java/packages/ParsePackageName.java @@ -0,0 +1,21 @@ +package packages; + +import de.dhbwstuttgart.core.JavaTXCompiler; +import de.dhbwstuttgart.syntaxtree.SourceFile; +import org.junit.Test; + +import java.io.File; +import java.io.IOException; + +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+"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/packages/mathStrucMatrixOPTest.java.txt b/src/test/java/packages/mathStrucMatrixOPTest.java.txt new file mode 100644 index 000000000..f383a2b84 --- /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/java/packages/mathStrucVectorTest.java b/src/test/java/packages/mathStrucVectorTest.java new file mode 100644 index 000000000..a9d076840 --- /dev/null +++ b/src/test/java/packages/mathStrucVectorTest.java @@ -0,0 +1,54 @@ +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 + */ + +/* 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+"vectorAdd.jav")); + compiler.typeInference(); + compiler.generateBytecode(rootDirectory + "output/"); + File 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 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/java/typeinference/JavaTXCompilerTest.java b/src/test/java/typeinference/JavaTXCompilerTest.java index 91446744a..3fa1562b9 100644 --- a/src/test/java/typeinference/JavaTXCompilerTest.java +++ b/src/test/java/typeinference/JavaTXCompilerTest.java @@ -29,6 +29,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/AllgemeinTest/FCTest1.jav b/src/test/resources/AllgemeinTest/FCTest1.jav new file mode 100644 index 000000000..98647278c --- /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 000000000..c3f892dd9 --- /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 000000000..e862c4b88 --- /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 000000000..409838aef --- /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 000000000..efed04f0b --- /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 000000000..960f01db1 --- /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 000000000..d56911526 --- /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 000000000..0ede39ae4 --- /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 000000000..44759c813 --- /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 000000000..b506efa98 --- /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; + } +} diff --git a/src/test/resources/bytecode/javFiles/AA.jav b/src/test/resources/bytecode/javFiles/AA.jav new file mode 100644 index 000000000..3f8f172d5 --- /dev/null +++ b/src/test/resources/bytecode/javFiles/AA.jav @@ -0,0 +1,8 @@ +import java.lang.Integer; +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/BB.jav b/src/test/resources/bytecode/javFiles/BB.jav new file mode 100644 index 000000000..27856c42b --- /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 000000000..d7d5c9673 --- /dev/null +++ b/src/test/resources/bytecode/javFiles/CC.jav @@ -0,0 +1,11 @@ +import java.lang.Integer; +import java.lang.String; + + +public class CC extends BB { + m(Integer i) { + return "CC"; + } + + m2(CC x) { return "CC"; } +} diff --git a/src/test/resources/bytecode/javFiles/DD.jav b/src/test/resources/bytecode/javFiles/DD.jav new file mode 100644 index 000000000..6d49f4c78 --- /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 new file mode 100644 index 000000000..7b5927d24 --- /dev/null +++ b/src/test/resources/bytecode/javFiles/Inherit.jav @@ -0,0 +1,18 @@ +import java.util.Vector; + +import java.lang.Integer; +import java.lang.String; + + +public class Inherit { + + main(d, i) { + return d.m(i); + } + + main(v, i) { + var aa = v.elementAt(0); + return aa.m(i); + } + +} \ No newline at end of file diff --git a/src/test/resources/bytecode/javFiles/Inherit2.jav b/src/test/resources/bytecode/javFiles/Inherit2.jav new file mode 100644 index 000000000..fe4c50628 --- /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 diff --git a/src/test/resources/bytecode/javFiles/OL.jav b/src/test/resources/bytecode/javFiles/OL.jav index 01a353fd1..4eab848fc 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 diff --git a/src/test/resources/bytecode/javFiles/Put.jav b/src/test/resources/bytecode/javFiles/Put.jav new file mode 100644 index 000000000..79a1cfa10 --- /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 diff --git a/src/test/resources/bytecode/javFiles/VectorAdd.jav b/src/test/resources/bytecode/javFiles/VectorAdd.jav index bb14aa211..252c322c3 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; -} +// } } diff --git a/src/test/resources/javFiles/Import.jav b/src/test/resources/javFiles/Import.jav index c48082baa..2fc3a8b31 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/Gen.jav b/src/test/resources/javFiles/packageTest/Gen.jav new file mode 100644 index 000000000..3b58b188d --- /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/OLMain.jav b/src/test/resources/javFiles/packageTest/OLMain.jav new file mode 100644 index 000000000..0cdb0b4f1 --- /dev/null +++ b/src/test/resources/javFiles/packageTest/OLMain.jav @@ -0,0 +1,12 @@ +import java.lang.String; +import java.lang.Integer; +import java.lang.Double; + +public class OLMain { + + main(x) { + var ol; + ol = new OLextends(); + return ol.m(x); + } +} diff --git a/src/test/resources/javFiles/packageTest/OLOneFile.jav b/src/test/resources/javFiles/packageTest/OLOneFile.jav new file mode 100644 index 000000000..eb865d612 --- /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); + } +} diff --git a/src/test/resources/javFiles/packageTest/OLTest.txt b/src/test/resources/javFiles/packageTest/OLTest.txt new file mode 100644 index 000000000..d91b58d75 --- /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/OLextends.jav b/src/test/resources/javFiles/packageTest/OLextends.jav new file mode 100644 index 000000000..b3c055dfc --- /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/Test.jav b/src/test/resources/javFiles/packageTest/Test.jav new file mode 100644 index 000000000..2f6429a1c --- /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/UseOLMain.java b/src/test/resources/javFiles/packageTest/UseOLMain.java new file mode 100644 index 000000000..2d7d6fd87 --- /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)); + } +} 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 000000000..58b6fc0b2 --- /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/ImportTest2.jav b/src/test/resources/javFiles/packageTest/de/test/ImportTest2.jav new file mode 100644 index 000000000..3526abc80 --- /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/ImportTestDefault.jav b/src/test/resources/javFiles/packageTest/de/test/ImportTestDefault.jav new file mode 100644 index 000000000..ecd8d7c59 --- /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 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 000000000..7f1ba512b --- /dev/null +++ b/src/test/resources/javFiles/packageTest/de/test/OL.jav @@ -0,0 +1,13 @@ +package de.test; +import java.lang.String; +import java.lang.Integer; +import java.lang.Double; +import java.lang.Boolean; +//import java.util.Vector; + + +public class OL { + + public m(x) { return x + x; } + +} 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 000000000..6681b36ad --- /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/ToImport.jav b/src/test/resources/javFiles/packageTest/de/test/ToImport.jav new file mode 100644 index 000000000..3afdba541 --- /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 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 000000000..28db5db85 --- /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 000000000..fe6d60557 --- /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; + + +public class mathStrucVector { + + public 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/output/de/test/mathStrucVectoruse.java b/src/test/resources/javFiles/packageTest/de/test/output/de/test/mathStrucVectoruse.java new file mode 100644 index 000000000..54b9e45b8 --- /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 000000000..9a9b2e753 --- /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/src/test/resources/javFiles/packageTest/de/test/packageNameTestWrongPackage.jav b/src/test/resources/javFiles/packageTest/de/test/packageNameTestWrongPackage.jav new file mode 100644 index 000000000..a86d22aa2 --- /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/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 000000000..a7011169d --- /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/subpackage1/ToImport2.jav b/src/test/resources/javFiles/packageTest/de/test/subpackage1/ToImport2.jav new file mode 100644 index 000000000..bcc67b95c --- /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/Test2.jav b/src/test/resources/javFiles/packageTest/de/test/subpackage2/Test2.jav new file mode 100644 index 000000000..750f7612d --- /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 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 000000000..3efd8ffff --- /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 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 000000000..727a83a93 --- /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; + + +public 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; + }; +}