Compare commits

..

5 Commits

Author SHA1 Message Date
Martin Plümicke
d33335a6d9 modified: ../../../main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java
Bildung von newOderConstraints wieder rueckgaengig gemacht

	modified:   ../../resources/bytecode/javFiles/MatrixOP.jav
2019-02-14 09:38:26 +01:00
Martin Plümicke
25b1d3e62d modified: ../../../main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java
ArrayList durch LinkedList ersetzt
computeCartesianRecursiveOderConstraints auskommentiert
2019-02-14 08:53:32 +01:00
Martin Plümicke
85a15cb256 modified: ../../../../main/java/de/dhbwstuttgart/typeinference/unify/PartialOrderSet.java
modified:   ../../../../main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java
PartialOrderSet als LinkedList realisiert

	modified:   ../../bytecode/javFiles/Matrix.jav
2019-02-13 18:34:12 +01:00
Martin Plümicke
0c03c2fbc8 Merge branch 'unify-test' of ssh://gohorb.ba-horb.de/bahome/projekt/git/JavaCompilerCore into unify-PartialOrderSet
Conflicts:
	src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnify2Task.java

	modified:   ../../../main/java/de/dhbwstuttgart/typeinference/unify/TypeUnify2Task.java
	modified:   ../../../main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java
	modified:   ../../resources/bytecode/javFiles/Matrix.jav
	modified:   ../../resources/bytecode/javFiles/MatrixOP.jav
2019-02-11 14:41:28 +01:00
Martin Plümicke
c8daa665f6 new file: src/main/java/de/dhbwstuttgart/typeinference/unify/PartialOrderSet.java
modified:   src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnify.java
	modified:   src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnify2Task.java
	modified:   src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java
PartialOrderSet implemetiert und in TypeUnify, TypeUnify2Task, TypeUnifyTask eingepasst
2019-02-02 20:26:26 +01:00
173 changed files with 23685 additions and 27404 deletions

View File

@@ -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

Binary file not shown.

35
pom.xml
View File

@@ -14,13 +14,13 @@ http://maven.apache.org/maven-v4_0_0.xsd">
<dependency> <dependency>
<groupId>junit</groupId> <groupId>junit</groupId>
<artifactId>junit</artifactId> <artifactId>junit</artifactId>
<version>4.11</version> <version>4.0</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.antlr</groupId> <groupId>org.antlr</groupId>
<artifactId>antlr4</artifactId> <artifactId>antlr4</artifactId>
<version>4.8-1</version> <version>4.7</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>commons-io</groupId> <groupId>commons-io</groupId>
@@ -55,27 +55,6 @@ http://maven.apache.org/maven-v4_0_0.xsd">
<finalName>${project.artifactId}-${project.version}</finalName> <finalName>${project.artifactId}-${project.version}</finalName>
<testOutputDirectory>target/test-classes</testOutputDirectory> <testOutputDirectory>target/test-classes</testOutputDirectory>
<plugins> <plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M3</version>
<configuration>
<skipTests>true</skipTests>
</configuration>
</plugin>
<!-- plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<verbose>true</verbose>
<fork>true</fork>
<executable>/home/michael/programs/jdk/jdk8u232-b09/bin/javac</executable>
<compilerVersion>1.8</compilerVersion>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin -->
<plugin> <plugin>
<groupId>org.antlr</groupId> <groupId>org.antlr</groupId>
<artifactId>antlr4-maven-plugin</artifactId> <artifactId>antlr4-maven-plugin</artifactId>
@@ -140,7 +119,7 @@ http://maven.apache.org/maven-v4_0_0.xsd">
<!-- specify your depencies here --> <!-- specify your depencies here -->
<!-- groupId:artifactId:version --> <!-- groupId:artifactId:version -->
<artifact> <artifact>
<id>de.dhbwstuttgart:JavaTXcompiler:0.2</id> <id>de.dhbwstuttgart:JavaTXcompiler:0.1</id>
</artifact> </artifact>
<artifact> <artifact>
<id>org.reflections:reflections:0.9.11</id> <id>org.reflections:reflections:0.9.11</id>
@@ -159,6 +138,10 @@ http://maven.apache.org/maven-v4_0_0.xsd">
</execution> </execution>
</executions> </executions>
</plugin> </plugin>
<!-- plugin> <groupId>org.eclipse.tycho</groupId> <artifactId>tycho-p2-repository-plugin</artifactId>
<version>${tycho.version}</version> <executions> <execution> <phase>package</phase>
<goals> <goal>archive-repository</goal> </goals> </execution> </executions>
</plugin -->
</plugins> </plugins>
</build> </build>
<pluginRepositories> <pluginRepositories>
@@ -174,8 +157,6 @@ http://maven.apache.org/maven-v4_0_0.xsd">
</repository> </repository>
</repositories> </repositories>
<properties> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target> <maven.compiler.target>1.8</maven.compiler.target>
<tycho.version>0.23.0</tycho.version> <tycho.version>0.23.0</tycho.version>
@@ -188,3 +169,5 @@ http://maven.apache.org/maven-v4_0_0.xsd">
</repository> </repository>
</distributionManagement> </distributionManagement>
</project> </project>

View File

@@ -61,7 +61,7 @@ public class ArgumentVisitor implements StatementVisitor {
assign.accept(bytecodeGenMethod); assign.accept(bytecodeGenMethod);
if(argListMethCall.get(0)) if(argListMethCall.get(0))
bytecodeGenMethod.doUnboxing(bytecodeGenMethod.getResolver().getResolvedType(assign.getType())); bytecodeGenMethod.doUnboxing(bytecodeGenMethod.getResolvedType(assign.getType()));
argListMethCall.remove(0); argListMethCall.remove(0);
} }
@@ -70,9 +70,9 @@ public class ArgumentVisitor implements StatementVisitor {
binary.accept(bytecodeGenMethod); binary.accept(bytecodeGenMethod);
if(argListMethCall.get(0)) { if(argListMethCall.get(0)) {
bytecodeGenMethod.doUnboxing(bytecodeGenMethod.getResolver().getResolvedType(binary.getType())); bytecodeGenMethod.doUnboxing(bytecodeGenMethod.getResolvedType(binary.getType()));
} else { } else {
bytecodeGenMethod.doBoxing(bytecodeGenMethod.getResolver().getResolvedType(binary.getType())); bytecodeGenMethod.doBoxing(bytecodeGenMethod.getResolvedType(binary.getType()));
} }
argListMethCall.remove(0); argListMethCall.remove(0);
} }
@@ -88,7 +88,7 @@ public class ArgumentVisitor implements StatementVisitor {
castExpr.accept(bytecodeGenMethod); castExpr.accept(bytecodeGenMethod);
if(argListMethCall.get(0)) if(argListMethCall.get(0))
bytecodeGenMethod.doUnboxing(bytecodeGenMethod.getResolver().getResolvedType(castExpr.getType())); bytecodeGenMethod.doUnboxing(bytecodeGenMethod.getResolvedType(castExpr.getType()));
argListMethCall.remove(0); argListMethCall.remove(0);
} }
@@ -103,7 +103,7 @@ public class ArgumentVisitor implements StatementVisitor {
fieldVar.accept(bytecodeGenMethod); fieldVar.accept(bytecodeGenMethod);
if(argListMethCall.get(0)) if(argListMethCall.get(0))
bytecodeGenMethod.doUnboxing(bytecodeGenMethod.getResolver().getResolvedType(fieldVar.getType())); bytecodeGenMethod.doUnboxing(bytecodeGenMethod.getResolvedType(fieldVar.getType()));
argListMethCall.remove(0); argListMethCall.remove(0);
} }
@@ -124,7 +124,7 @@ public class ArgumentVisitor implements StatementVisitor {
instanceOf.accept(bytecodeGenMethod); instanceOf.accept(bytecodeGenMethod);
if(argListMethCall.get(0)) if(argListMethCall.get(0))
bytecodeGenMethod.doUnboxing(bytecodeGenMethod.getResolver().getResolvedType(instanceOf.getType())); bytecodeGenMethod.doUnboxing(bytecodeGenMethod.getResolvedType(instanceOf.getType()));
argListMethCall.remove(0); argListMethCall.remove(0);
} }
@@ -133,7 +133,7 @@ public class ArgumentVisitor implements StatementVisitor {
localVar.accept(bytecodeGenMethod); localVar.accept(bytecodeGenMethod);
if(!bytecodeGenMethod.isBinaryExp) { if(!bytecodeGenMethod.isBinaryExp) {
if(argListMethCall.get(0)) if(argListMethCall.get(0))
bytecodeGenMethod.doUnboxing(bytecodeGenMethod.getResolver().getResolvedType(localVar.getType())); bytecodeGenMethod.doUnboxing(bytecodeGenMethod.getResolvedType(localVar.getType()));
} }
argListMethCall.remove(0); argListMethCall.remove(0);
} }
@@ -149,7 +149,7 @@ public class ArgumentVisitor implements StatementVisitor {
methodCall.accept(bytecodeGenMethod); methodCall.accept(bytecodeGenMethod);
if(argListMethCall.get(0)) if(argListMethCall.get(0))
bytecodeGenMethod.doUnboxing(bytecodeGenMethod.getResolver().getResolvedType(methodCall.getType())); bytecodeGenMethod.doUnboxing(bytecodeGenMethod.getResolvedType(methodCall.getType()));
argListMethCall.remove(0); argListMethCall.remove(0);
} }
@@ -158,7 +158,7 @@ public class ArgumentVisitor implements StatementVisitor {
methodCall.accept(bytecodeGenMethod); methodCall.accept(bytecodeGenMethod);
if(argListMethCall.get(0)) if(argListMethCall.get(0))
bytecodeGenMethod.doUnboxing(bytecodeGenMethod.getResolver().getResolvedType(methodCall.getType())); bytecodeGenMethod.doUnboxing(bytecodeGenMethod.getResolvedType(methodCall.getType()));
argListMethCall.remove(0); argListMethCall.remove(0);
} }
@@ -197,7 +197,7 @@ public class ArgumentVisitor implements StatementVisitor {
aThis.accept(bytecodeGenMethod); aThis.accept(bytecodeGenMethod);
if(argListMethCall.get(0)) if(argListMethCall.get(0))
bytecodeGenMethod.doUnboxing(bytecodeGenMethod.getResolver().getResolvedType(aThis.getType())); bytecodeGenMethod.doUnboxing(bytecodeGenMethod.getResolvedType(aThis.getType()));
argListMethCall.remove(0); argListMethCall.remove(0);
} }
@@ -242,7 +242,7 @@ public class ArgumentVisitor implements StatementVisitor {
unaryExpr.accept(bytecodeGenMethod); unaryExpr.accept(bytecodeGenMethod);
if(argListMethCall.get(0)) if(argListMethCall.get(0))
bytecodeGenMethod.doUnboxing(bytecodeGenMethod.getResolver().getResolvedType(unaryExpr.getType())); bytecodeGenMethod.doUnboxing(bytecodeGenMethod.getResolvedType(unaryExpr.getType()));
argListMethCall.remove(0); argListMethCall.remove(0);
} }
@@ -251,7 +251,7 @@ public class ArgumentVisitor implements StatementVisitor {
literal.accept(bytecodeGenMethod); literal.accept(bytecodeGenMethod);
if(argListMethCall.get(0)) if(argListMethCall.get(0))
bytecodeGenMethod.doUnboxing(bytecodeGenMethod.getResolver().getResolvedType(literal.getType())); bytecodeGenMethod.doUnboxing(bytecodeGenMethod.getResolvedType(literal.getType()));
argListMethCall.remove(0); argListMethCall.remove(0);
} }

View File

@@ -1,77 +1,46 @@
package de.dhbwstuttgart.bytecode; package de.dhbwstuttgart.bytecode;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator; import java.util.Iterator;
import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.NoSuchElementException;
import java.util.Optional; import java.util.Optional;
import de.dhbwstuttgart.exceptions.NotImplementedException;
import de.dhbwstuttgart.syntaxtree.statement.*;
import org.objectweb.asm.ClassWriter; import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.FieldVisitor; import org.objectweb.asm.FieldVisitor;
import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes; import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type; import org.objectweb.asm.Type;
import de.dhbwstuttgart.bytecode.Exception.BytecodeGeneratorError; import de.dhbwstuttgart.bytecode.constraint.ExtendsConstraint;
import de.dhbwstuttgart.bytecode.constraint.TPHConstraint;
import de.dhbwstuttgart.bytecode.constraint.TPHConstraint.Relation;
import de.dhbwstuttgart.bytecode.descriptor.DescriptorToString; import de.dhbwstuttgart.bytecode.descriptor.DescriptorToString;
import de.dhbwstuttgart.bytecode.descriptor.TypeToDescriptor; import de.dhbwstuttgart.bytecode.descriptor.TypeToDescriptor;
import de.dhbwstuttgart.bytecode.signature.Signature; import de.dhbwstuttgart.bytecode.signature.Signature;
import de.dhbwstuttgart.bytecode.signature.TypeToSignature; import de.dhbwstuttgart.bytecode.signature.TypeToSignature;
import de.dhbwstuttgart.bytecode.signature.TypeToString; import de.dhbwstuttgart.bytecode.signature.TypeToString;
import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.GenericGenratorResultForSourceFile; import de.dhbwstuttgart.bytecode.utilities.MethodAndTPH;
import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.GenericsGeneratorResult;
import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.GenericsGeneratorResultForClass;
import de.dhbwstuttgart.bytecode.utilities.MethodUtility;
import de.dhbwstuttgart.bytecode.utilities.NormalConstructor; import de.dhbwstuttgart.bytecode.utilities.NormalConstructor;
import de.dhbwstuttgart.bytecode.utilities.NormalMethod; import de.dhbwstuttgart.bytecode.utilities.NormalMethod;
import de.dhbwstuttgart.bytecode.utilities.Resolver; import de.dhbwstuttgart.bytecode.utilities.Simplify;
import de.dhbwstuttgart.exceptions.NotImplementedException;
import de.dhbwstuttgart.parser.SyntaxTreeGenerator.AssignToLocal; import de.dhbwstuttgart.parser.SyntaxTreeGenerator.AssignToLocal;
import de.dhbwstuttgart.syntaxtree.ASTVisitor; import de.dhbwstuttgart.syntaxtree.*;
import de.dhbwstuttgart.syntaxtree.ClassOrInterface;
import de.dhbwstuttgart.syntaxtree.Constructor;
import de.dhbwstuttgart.syntaxtree.Field;
import de.dhbwstuttgart.syntaxtree.FormalParameter;
import de.dhbwstuttgart.syntaxtree.GenericDeclarationList;
import de.dhbwstuttgart.syntaxtree.GenericTypeVar;
import de.dhbwstuttgart.syntaxtree.Method;
import de.dhbwstuttgart.syntaxtree.ParameterList;
import de.dhbwstuttgart.syntaxtree.SourceFile;
import de.dhbwstuttgart.syntaxtree.statement.ArgumentList;
import de.dhbwstuttgart.syntaxtree.statement.Assign;
import de.dhbwstuttgart.syntaxtree.statement.AssignToField;
import de.dhbwstuttgart.syntaxtree.statement.BinaryExpr;
import de.dhbwstuttgart.syntaxtree.statement.Block;
import de.dhbwstuttgart.syntaxtree.statement.CastExpr;
import de.dhbwstuttgart.syntaxtree.statement.DoStmt;
import de.dhbwstuttgart.syntaxtree.statement.EmptyStmt;
import de.dhbwstuttgart.syntaxtree.statement.ExpressionReceiver;
import de.dhbwstuttgart.syntaxtree.statement.FieldVar;
import de.dhbwstuttgart.syntaxtree.statement.ForStmt;
import de.dhbwstuttgart.syntaxtree.statement.IfStmt;
import de.dhbwstuttgart.syntaxtree.statement.InstanceOf;
import de.dhbwstuttgart.syntaxtree.statement.LambdaExpression;
import de.dhbwstuttgart.syntaxtree.statement.Literal; import de.dhbwstuttgart.syntaxtree.statement.Literal;
import de.dhbwstuttgart.syntaxtree.statement.LocalVar;
import de.dhbwstuttgart.syntaxtree.statement.LocalVarDecl;
import de.dhbwstuttgart.syntaxtree.statement.MethodCall;
import de.dhbwstuttgart.syntaxtree.statement.NewArray;
import de.dhbwstuttgart.syntaxtree.statement.NewClass;
import de.dhbwstuttgart.syntaxtree.statement.Return;
import de.dhbwstuttgart.syntaxtree.statement.ReturnVoid;
import de.dhbwstuttgart.syntaxtree.statement.StaticClassName;
import de.dhbwstuttgart.syntaxtree.statement.Super;
import de.dhbwstuttgart.syntaxtree.statement.SuperCall;
import de.dhbwstuttgart.syntaxtree.statement.This;
import de.dhbwstuttgart.syntaxtree.statement.UnaryExpr;
import de.dhbwstuttgart.syntaxtree.statement.WhileStmt;
import de.dhbwstuttgart.syntaxtree.type.ExtendsWildcardType; import de.dhbwstuttgart.syntaxtree.type.ExtendsWildcardType;
import de.dhbwstuttgart.syntaxtree.type.GenericRefType; import de.dhbwstuttgart.syntaxtree.type.GenericRefType;
import de.dhbwstuttgart.syntaxtree.type.RefType; import de.dhbwstuttgart.syntaxtree.type.RefType;
import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric; import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric;
import de.dhbwstuttgart.syntaxtree.type.SuperWildcardType; import de.dhbwstuttgart.syntaxtree.type.SuperWildcardType;
import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder; import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder;
import de.dhbwstuttgart.typeinference.result.GenericInsertPair;
import de.dhbwstuttgart.typeinference.result.ResolvedType;
import de.dhbwstuttgart.typeinference.result.ResultPair;
import de.dhbwstuttgart.typeinference.result.ResultSet; import de.dhbwstuttgart.typeinference.result.ResultSet;
public class BytecodeGen implements ASTVisitor { public class BytecodeGen implements ASTVisitor {
@@ -81,10 +50,9 @@ public class BytecodeGen implements ASTVisitor {
String type; String type;
public static RefTypeOrTPHOrWildcardOrGeneric THISTYPE = null; public static RefTypeOrTPHOrWildcardOrGeneric THISTYPE = null;
private String className; String className;
private String pkgName;
private boolean isInterface; private boolean isInterface;
private Collection<ResultSet> listOfResultSets; private List<ResultSet> listOfResultSets;
private ResultSet resultSet; private ResultSet resultSet;
private SourceFile sf; private SourceFile sf;
private String path; private String path;
@@ -95,55 +63,46 @@ public class BytecodeGen implements ASTVisitor {
private String superClass; private String superClass;
private List<String> tphsClass; private ArrayList<TypePlaceholder> tphsClass;
// stores parameter, local vars and the next index on the local variable table, // stores parameter, local vars and the next index on the local variable table, which use for aload_i, astore_i,...
// which use for aload_i, astore_i,...
HashMap<String, Integer> paramsAndLocals = new HashMap<>(); HashMap<String, Integer> paramsAndLocals = new HashMap<>();
// stores generics and their bounds of class // stores generics and their bounds of class
HashMap<String, String> genericsAndBounds = new HashMap<>(); HashMap<String, String> genericsAndBounds = new HashMap<>();
private int constructorPos = 0; private int constructorPos = 0;
private final TPHExtractor tphExtractor = new TPHExtractor();
private final ArrayList<GenericInsertPair> commonPairs = new ArrayList<>();
HashMap<String,RefTypeOrTPHOrWildcardOrGeneric> methodParamsAndTypes = new HashMap<>(); HashMap<String,RefTypeOrTPHOrWildcardOrGeneric> methodParamsAndTypes = new HashMap<>();
byte[] bytecode; byte[] bytecode;
HashMap<String,byte[]> classFiles; HashMap<String,byte[]> classFiles;
private final ArrayList<String> methodNameAndParamsT = new ArrayList<>(); ArrayList<String> methodNameAndParamsT = new ArrayList<>();
private final ArrayList<String> fieldNameAndParamsT = new ArrayList<>();
private final ArrayList<String> fieldNameSignature = new ArrayList<>(); public BytecodeGen(HashMap<String,byte[]> classFiles, List<ResultSet> listOfResultSets,SourceFile sf ,String path) {
private List<GenericGenratorResultForSourceFile> simplifyResultsForAllSourceFiles;
private GenericsGeneratorResultForClass generatedGenerics;
private Resolver resolver;
public BytecodeGen(HashMap<String, byte[]> classFiles, Collection<ResultSet> listOfResultSets, List<GenericGenratorResultForSourceFile> simplifyResultsForAllSourceFiles, SourceFile sf,
String path) {
this.classFiles = classFiles; this.classFiles = classFiles;
this.listOfResultSets = listOfResultSets; this.listOfResultSets = listOfResultSets;
this.simplifyResultsForAllSourceFiles = simplifyResultsForAllSourceFiles;
this.sf = sf; this.sf = sf;
this.path = path; this.path = path;
this.pkgName = sf.getPkgName();
} }
@Override @Override
public void visit(SourceFile sourceFile) { public void visit(SourceFile sourceFile) {
for(ClassOrInterface cl : sourceFile.getClasses()) { for(ClassOrInterface cl : sourceFile.getClasses()) {
System.out.println("in Class: " + cl.getClassName().toString()); System.out.println("in Class: " + cl.getClassName().toString());
BytecodeGen classGen = new BytecodeGen(classFiles, listOfResultSets, simplifyResultsForAllSourceFiles, sf, path); BytecodeGen classGen = new BytecodeGen(classFiles, listOfResultSets, sf, path);
cl.accept(classGen); cl.accept(classGen);
classGen.writeClass(cl.getClassName().toString()); classGen.writeClass(cl.getClassName().toString());
} }
} }
/** /**
* Associates the bytecode of the class that was build with the classWriter * Associates the bytecode of the class that was build with the classWriter {@link #cw}
* {@link #cw} with the class name in the map {@link #classFiles} * with the class name in the map {@link #classFiles}
* *
* @param name name of the class with which the bytecode is to be associated * @param name name of the class with which the the bytecode is to be associated
*/ */
private void writeClass(String name) { private void writeClass(String name) {
bytecode = cw.toByteArray(); bytecode = cw.toByteArray();
@@ -155,6 +114,7 @@ public class BytecodeGen implements ASTVisitor {
return classFiles; return classFiles;
} }
@Override @Override
public void visit(ClassOrInterface classOrInterface) { public void visit(ClassOrInterface classOrInterface) {
@@ -164,43 +124,61 @@ public class BytecodeGen implements ASTVisitor {
isInterface = (classOrInterface.getModifiers()&512)==512; isInterface = (classOrInterface.getModifiers()&512)==512;
int acc = isInterface ? classOrInterface.getModifiers() + Opcodes.ACC_ABSTRACT int acc = isInterface?classOrInterface.getModifiers()+Opcodes.ACC_ABSTRACT:classOrInterface.getModifiers()+Opcodes.ACC_SUPER;
: classOrInterface.getModifiers() + Opcodes.ACC_SUPER;
fieldInitializations = classOrInterface.getfieldInitializations(); fieldInitializations = classOrInterface.getfieldInitializations();
// resultSet = listOfResultSets.get(0); // resultSet = listOfResultSets.get(0);
boolean isConsWithNoParamsVisited = false;
boolean isVisited = false; boolean isVisited = false;
List<ResultSet> listOfResultSetsList = new ArrayList<>(listOfResultSets); for(ResultSet rs : listOfResultSets) {
generatedGenerics = simplifyResultsForAllSourceFiles.stream().map(sr->sr.getSimplifyResultsByName(pkgName, className)).findFirst().get();
for (int i = 0; i < listOfResultSetsList.size(); i++) {
//for (ResultSet rs : listOfResultSets) {
superClass = classOrInterface.getSuperClass().acceptTV(new TypeToDescriptor()); superClass = classOrInterface.getSuperClass().acceptTV(new TypeToDescriptor());
resultSet = listOfResultSetsList.get(i); resultSet = rs;
resolver = new Resolver(resultSet); tphExtractor.setResultSet(resultSet);
// tphExtractor.setResultSet(resultSet);
// Nur einmal ausführen!! // Nur einmal ausführen!!
if(!isVisited) { if(!isVisited) {
classOrInterface.accept(tphExtractor);
getCommonTPHS(tphExtractor);
tphsClass = new ArrayList<>();
for(TypePlaceholder t : tphExtractor.allTPHS.keySet()) {
if(!tphExtractor.allTPHS.get(t))
tphsClass.add(t);
}
ArrayList<TPHConstraint> consClass = new ArrayList<>();
for(TPHConstraint cons : tphExtractor.allCons) {
TypePlaceholder right = null;
for(TypePlaceholder tph : tphsClass) {
if(cons.getLeft().equals(tph.getName())) {
consClass.add(cons);
right = getTPH(cons.getRight());
}
}
if(right != null) {
tphsClass.add(right);
removeFromMethod(right.getName());
right = null;
}
}
String sig = null; String sig = null;
/* /* if class has generics then creates signature
* if class has generics then creates signature Signature looks like: * Signature looks like:
* <E:Ljava/...>Superclass * <E:Ljava/...>Superclass
*/ */
if (classOrInterface.getGenerics().iterator().hasNext() || classOrInterface.getSuperClass().acceptTV(new TypeToSignature()).contains("<") if(classOrInterface.getGenerics().iterator().hasNext() || !commonPairs.isEmpty() ||
|| !generatedGenerics.getClassConstraints().isEmpty()) { classOrInterface.getSuperClass().acceptTV(new TypeToSignature()).contains("<")
|| !tphsClass.isEmpty()) {
List<GenericsGeneratorResult> consClass = generatedGenerics.getClassConstraints(); Signature signature = new Signature(classOrInterface, genericsAndBounds,commonPairs,tphsClass, consClass);
// sig = signature.toString();
Signature signature = new Signature(classOrInterface, genericsAndBounds, consClass);
sig = signature.createSignatureForClassOrInterface();
System.out.println("Signature: => " + sig); System.out.println("Signature: => " + sig);
} }
cw.visit(Opcodes.V1_8, acc, classOrInterface.getClassName().toString(), sig, cw.visit(Opcodes.V1_8, acc, classOrInterface.getClassName().toString()
classOrInterface.getSuperClass().acceptTV(new TypeToDescriptor()), null); , sig, classOrInterface.getSuperClass().acceptTV(new TypeToDescriptor()), null);
isVisited = true; isVisited = true;
} }
@@ -210,7 +188,12 @@ public class BytecodeGen implements ASTVisitor {
} }
for(Constructor c : classOrInterface.getConstructors()) { for(Constructor c : classOrInterface.getConstructors()) {
// if(!isConsWithNoParamsVisited) {
c.accept(this); c.accept(this);
// }
// if(!c.getParameterList().iterator().hasNext())
// isConsWithNoParamsVisited = true;
} }
for(Method m : classOrInterface.getMethods()) { for(Method m : classOrInterface.getMethods()) {
@@ -221,20 +204,69 @@ public class BytecodeGen implements ASTVisitor {
} }
private void removeFromMethod(String name) {
for(MethodAndTPH m : tphExtractor.ListOfMethodsAndTph) {
ArrayList<String> toRemove = new ArrayList<>();
for(String tph : m.getTphs()) {
if(tph.equals(name)) {
toRemove.add(tph);
}
}
if(!toRemove.isEmpty()) {
m.getTphs().removeAll(toRemove);
return;
}
}
}
private TypePlaceholder getTPH(String name) {
for(TypePlaceholder tph: tphExtractor.allTPHS.keySet()) {
if(tph.getName().equals(name))
return tph;
}
throw new NoSuchElementException("TPH "+name +" does not exist");
}
private void getCommonTPHS(TPHExtractor tphExtractor) {
// Gemeinsame TPHs
ArrayList<TypePlaceholder> cTPHs = new ArrayList<>();
// Alle TPHs der Felder speichern
for(TypePlaceholder tph : tphExtractor.allTPHS.keySet()) {
if(!tphExtractor.allTPHS.get(tph))
cTPHs.add(tph);
}
}
@Override @Override
public void visit(Constructor field) { public void visit(Constructor field) {
System.out.println("ResultSet: ");
resultSet.results.forEach(a->{
System.out.println(a.getLeft().toString() + " = " + a.getRight().toString());
});
System.out.println("---------------");
// stores generics and their bounds of method // stores generics and their bounds of method
HashMap<String, String> genericsAndBoundsMethod = new HashMap<>(); HashMap<String, String> genericsAndBoundsMethod = new HashMap<>();
field.getParameterList().accept(this); field.getParameterList().accept(this);
String id = MethodUtility.createID(resolver, field); String methParamTypes = field.name+"%%";
if (methodNameAndParamsT.contains(id)) { Iterator<FormalParameter> itr = field.getParameterList().iterator();
while(itr.hasNext()) {
FormalParameter fp = itr.next();
methParamTypes += resultSet.resolveType(fp.getType()).resolvedType.acceptTV(new TypeToDescriptor())+";";
// methParamTypes += resultSet.resolveType(fp.getType()).resolvedType.acceptTV(new TypeToSignature())+";";
}
if(methodNameAndParamsT.contains(methParamTypes)) {
System.out.println("ignore - Method: "+field.name +" , paramsType: "+methParamTypes);
return; return;
} }
methodNameAndParamsT.add(id); methodNameAndParamsT.add(methParamTypes);
System.out.println("Constructor: " + field.name + " , paramsType: " + id); System.out.println("Method: "+field.name +" , paramsType: "+methParamTypes);
String desc = null; String desc = null;
boolean hasGen = false; boolean hasGen = false;
@@ -242,18 +274,17 @@ public class BytecodeGen implements ASTVisitor {
for(String paramName : methodParamsAndTypes.keySet()) { for(String paramName : methodParamsAndTypes.keySet()) {
String typeOfParam = methodParamsAndTypes.get(paramName).acceptTV(new TypeToSignature()); String typeOfParam = methodParamsAndTypes.get(paramName).acceptTV(new TypeToSignature());
System.out.println(typeOfParam); System.out.println(typeOfParam);
if (genericsAndBounds.containsKey(typeOfParam) || typeOfParam.contains("$") || typeOfParam.contains("<")) { if(genericsAndBounds.containsKey(typeOfParam) ||typeOfParam.contains("$")
|| typeOfParam.contains("<")) {
hasGen = true; hasGen = true;
break; break;
} }
} }
String sig = null; String sig = null;
if(hasGen) { if(hasGen) {
List<GenericsGeneratorResult> constraints = generatedGenerics.getClassConstraints(); HashMap<TPHConstraint, HashSet<String>> constraints = Simplify.simplifyConstraints(field.name, tphExtractor,tphsClass);
Signature signature = new Signature(genericsAndBounds, Signature signature = new Signature(field, genericsAndBounds,methodParamsAndTypes,resultSet,constraints);
methodParamsAndTypes, resultSet, constraints); sig = signature.toString();
sig = signature.createSignatureForConstructor(field);
} }
if(field.getParameterList().iterator().hasNext()) if(field.getParameterList().iterator().hasNext())
System.out.println(field.getParameterList().iterator().next().getType().acceptTV(new TypeToDescriptor())); System.out.println(field.getParameterList().iterator().next().getType().acceptTV(new TypeToDescriptor()));
@@ -270,8 +301,7 @@ public class BytecodeGen implements ASTVisitor {
BytecodeGenMethod gen = new BytecodeGenMethod(className,superClass,resultSet,field, mv,paramsAndLocals,cw, 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);
if (!field.getParameterList().iterator().hasNext() if(!field.getParameterList().iterator().hasNext() && !(field.block.statements.get(field.block.statements.size()-1) instanceof ReturnVoid)) {
&& !(field.block.statements.get(field.block.statements.size() - 1) instanceof ReturnVoid)) {
mv.visitInsn(Opcodes.RETURN); mv.visitInsn(Opcodes.RETURN);
} }
mv.visitMaxs(0, 0); mv.visitMaxs(0, 0);
@@ -280,23 +310,27 @@ public class BytecodeGen implements ASTVisitor {
@Override @Override
public void visit(Method method) { public void visit(Method method) {
// TODO: check if the method is static => if static then the first param will be // TODO: check if the method is static => if static then the first param will be stored in pos 0
// stored in pos 0
// else it will be stored in pos 1 and this will be stored in pos 0 // else it will be stored in pos 1 and this will be stored in pos 0
String retType = resultSet.resolveType(method.getReturnType()).resolvedType.acceptTV(new TypeToDescriptor()); String retType = resultSet.resolveType(method.getReturnType()).resolvedType.acceptTV(new TypeToDescriptor());
// String retType = resultSet.resolveType(method.getReturnType()).resolvedType.acceptTV(new TypeToSignature());
String id = MethodUtility.createID(resolver, method); String methParamTypes = retType+method.name+"%%";
if (methodNameAndParamsT.contains(id)) {
return;
}
methodNameAndParamsT.add(id);
System.out.println("Method: " + method.name + " , paramsType: " + id);
// stores generics and their bounds of method
HashMap<String, String> genericsAndBoundsMethod = new HashMap<>();
method.getParameterList().accept(this); method.getParameterList().accept(this);
Iterator<FormalParameter> itr = method.getParameterList().iterator();
while(itr.hasNext()) {
FormalParameter fp = itr.next();
methParamTypes += resultSet.resolveType(fp.getType()).resolvedType.acceptTV(new TypeToDescriptor())+";";
// methParamTypes += resultSet.resolveType(fp.getType()).resolvedType.acceptTV(new TypeToSignature())+";";
}
if(methodNameAndParamsT.contains(methParamTypes)) {
return;
}
methodNameAndParamsT.add(methParamTypes);
System.out.println("Method: "+method.name +" , paramsType: "+methParamTypes);
// stores generics and their bounds of method
HashMap<String, String> genericsAndBoundsMethod = new HashMap<>();
String methDesc = null; String methDesc = null;
// Method getModifiers() ? // Method getModifiers() ?
@@ -304,48 +338,43 @@ public class BytecodeGen implements ASTVisitor {
System.out.println(acc); System.out.println(acc);
/*Prüfe, ob die Rückgabe-Type der Methode eine Type-Variable ist*/ /*Prüfe, ob die Rückgabe-Type der Methode eine Type-Variable ist*/
boolean hasGenInParameterList = genericsAndBounds.containsKey(retType) || retType.contains("TPH ") boolean hasGenInParameterList = genericsAndBounds.containsKey(retType) || retType.subSequence(0, 4).equals("TPH ") ||
|| resultSet.resolveType(method.getReturnType()).resolvedType.acceptTV(new TypeToSignature()) resultSet.resolveType(method.getReturnType()).resolvedType.acceptTV(new TypeToSignature()).contains("<");
.contains("<"); /*Wenn die Rückgabe-Type eine Typ-variable ist, erzeuge direkt die Signature, wenn nicht,
/* * prüfe, ob einer der Parameter Typ-Variable als Typ hat*/
* Wenn die Rückgabe-Type eine Typ-variable ist, erzeuge direkt die Signature,
* wenn nicht, prüfe, ob einer der Parameter Typ-Variable als Typ hat
*/
if(!hasGenInParameterList) { if(!hasGenInParameterList) {
for(String paramName : methodParamsAndTypes.keySet()) { for(String paramName : methodParamsAndTypes.keySet()) {
String typeOfParam = methodParamsAndTypes.get(paramName).acceptTV(new TypeToDescriptor()); String typeOfParam = methodParamsAndTypes.get(paramName).acceptTV(new TypeToDescriptor());
String sigOfParam = methodParamsAndTypes.get(paramName).acceptTV(new TypeToSignature()); String sigOfParam = methodParamsAndTypes.get(paramName).acceptTV(new TypeToSignature());
if (genericsAndBounds.containsKey(typeOfParam) || typeOfParam.contains("TPH ") if(genericsAndBounds.containsKey(typeOfParam)||typeOfParam.substring(0, 4).equals("TPH ")||sigOfParam.contains("<")) {
|| sigOfParam.contains("<")) {
hasGenInParameterList = true; hasGenInParameterList = true;
break; break;
} }
} }
} }
// TODO: Test if the return-type or any of the parameter is a parameterized //TODO: Test if the return-type or any of the parameter is a parameterized type. (VP)
// type. (VP)
//then create the descriptor with the new syntax. //then create the descriptor with the new syntax.
String sig = null; String sig = null;
/* /* method.getGenerics: <....> RT method(..)
* method.getGenerics: <....> RT method(..) * */
*/
boolean hasGen = method.getGenerics().iterator().hasNext() || hasGenInParameterList; boolean hasGen = method.getGenerics().iterator().hasNext() || hasGenInParameterList;
/* if method has generics or return type is TPH, create signature */ /* if method has generics or return type is TPH, create signature */
// zwite operand muss weggelassen werden // zwite operand muss weggelassen werden
if (hasGen || resultSet.resolveType(method.getReturnType()).resolvedType.acceptTV(new TypeToString()) if(hasGen||resultSet.resolveType(method.getReturnType()).resolvedType.acceptTV(new TypeToString()).equals("TPH")) {
.equals("TPH")) { System.out.println("ALL CONST: " + tphExtractor.allCons.size());
tphExtractor.allCons.forEach(c->System.out.println(c.toString()));
List<GenericsGeneratorResult> constraints = generatedGenerics.getMethodConstraintsByID(id); System.out.println("----------------");
List<GenericsGeneratorResult> classConstraints = generatedGenerics.getClassConstraints(); HashMap<TPHConstraint, HashSet<String>> constraints = Simplify.simplifyConstraints(method.name, tphExtractor, tphsClass);
Signature signature = new Signature(genericsAndBoundsMethod, genericsAndBounds, // ArrayList<GenericInsertPair> pairs = simplifyPairs(method.name,tphExtractor.allPairs,tphExtractor.allCons);
methodParamsAndTypes, resultSet, constraints,classConstraints); Signature signature = new Signature(method, genericsAndBoundsMethod, genericsAndBounds,methodParamsAndTypes,resultSet,constraints);
sig = signature.createSignatureForMethod(method); sig = signature.toString();
} }
System.out.println(method.getName()+" ==> "+sig); System.out.println(method.getName()+" ==> "+sig);
NormalMethod meth = new NormalMethod(method,genericsAndBounds,genericsAndBoundsMethod,hasGen); NormalMethod meth = new NormalMethod(method,genericsAndBounds,genericsAndBoundsMethod,hasGen);
methDesc = meth.accept(new DescriptorToString(resultSet)); methDesc = meth.accept(new DescriptorToString(resultSet));
// System.out.println(methDesc);
MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC+acc, method.getName(), methDesc, sig, null); MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC+acc, method.getName(), methDesc, sig, null);
mv.visitCode(); mv.visitCode();
@@ -410,8 +439,7 @@ public class BytecodeGen implements ASTVisitor {
public void visit(FieldVar fieldVar) { public void visit(FieldVar fieldVar) {
System.out.println("In FieldVar ---"); System.out.println("In FieldVar ---");
// cw.newField(fieldVar.receiver.toString(), fieldVar.fieldVarName.toString(), fieldVar.getType().toString()); // cw.newField(fieldVar.receiver.toString(), fieldVar.fieldVarName.toString(), fieldVar.getType().toString());
FieldVisitor fv = cw.visitField(Opcodes.ACC_PRIVATE, fieldVar.fieldVarName, "L" + fieldVar.getType() + ";", FieldVisitor fv = cw.visitField(Opcodes.ACC_PRIVATE, fieldVar.fieldVarName, "L"+fieldVar.getType()+";", null, null);
null, null);
fv.visitEnd(); fv.visitEnd();
} }
@@ -426,23 +454,14 @@ public class BytecodeGen implements ASTVisitor {
} }
des +=";"; des +=";";
System.out.println(des); System.out.println(des);
String sig = resultSet.resolveType(field.getType()).resolvedType.acceptTV(new TypeToSignature(generatedGenerics.getClassConstraints())); String sig = resultSet.resolveType(field.getType()).resolvedType.acceptTV(new TypeToSignature());
System.out.println(sig); System.out.println(sig);
if(sig.charAt(sig.length()-1) != (";").charAt(0)) { if(sig.charAt(sig.length()-1) != (";").charAt(0)) {
sig +=";"; sig +=";";
} }
String nameAndDesc = field.getName() + "%%" + des; cw.visitField(field.modifier, field.getName(),
String nameAndSig = field.getName() + "%%" + sig; des, sig,
if (fieldNameAndParamsT.contains(nameAndDesc)) { null);
if (fieldNameSignature.contains(nameAndSig)) {
return;
}
throw new BytecodeGeneratorError("Bytecode generation aborted due to duplicate field name&signature");
}
fieldNameAndParamsT.add(nameAndDesc);
fieldNameSignature.add(nameAndSig);
cw.visitField(field.modifier, field.getName(), des, sig, null);
} }
@Override @Override
@@ -623,4 +642,5 @@ public class BytecodeGen implements ASTVisitor {
throw new NotImplementedException(); throw new NotImplementedException();
} }
} }

View File

@@ -1,19 +0,0 @@
/**
*
*/
package de.dhbwstuttgart.bytecode.Exception;
/**
* @author fayez
*
*/
public class BytecodeGeneratorError extends RuntimeException {
/**
* @param message
*/
public BytecodeGeneratorError(String message) {
super(message);
}
}

View File

@@ -1,25 +0,0 @@
/**
*
*/
package de.dhbwstuttgart.bytecode.Exception;
/**
* @author fayez
*
*/
public class NotFoundException extends Exception {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* @param message
*/
public NotFoundException(String message) {
super(message);
}
}

View File

@@ -1,26 +0,0 @@
/**
*
*/
package de.dhbwstuttgart.bytecode.Exception;
/**
* @author fayez
*
*/
public class NotInCurrentPackageException extends Exception {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* @param message
*/
public NotInCurrentPackageException(String message) {
super(message);
}
}

View File

@@ -5,33 +5,15 @@ package de.dhbwstuttgart.bytecode;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import de.dhbwstuttgart.bytecode.constraint.ExtendsConstraint; import de.dhbwstuttgart.bytecode.constraint.ExtendsConstraint;
import de.dhbwstuttgart.bytecode.constraint.TPHConstraint; import de.dhbwstuttgart.bytecode.constraint.TPHConstraint;
import de.dhbwstuttgart.bytecode.constraint.TPHConstraint.Relation; import de.dhbwstuttgart.bytecode.constraint.TPHConstraint.Relation;
import de.dhbwstuttgart.bytecode.utilities.MethodAndTPH; import de.dhbwstuttgart.bytecode.utilities.MethodAndTPH;
import de.dhbwstuttgart.bytecode.utilities.MethodUtility;
import de.dhbwstuttgart.bytecode.utilities.Resolver;
import de.dhbwstuttgart.syntaxtree.AbstractASTWalker; import de.dhbwstuttgart.syntaxtree.AbstractASTWalker;
import de.dhbwstuttgart.syntaxtree.ClassOrInterface;
import de.dhbwstuttgart.syntaxtree.Constructor;
import de.dhbwstuttgart.syntaxtree.Field;
import de.dhbwstuttgart.syntaxtree.FormalParameter;
import de.dhbwstuttgart.syntaxtree.Method; import de.dhbwstuttgart.syntaxtree.Method;
import de.dhbwstuttgart.syntaxtree.ParameterList;
import de.dhbwstuttgart.syntaxtree.statement.LocalVar;
import de.dhbwstuttgart.syntaxtree.statement.LocalVarDecl;
import de.dhbwstuttgart.syntaxtree.type.GenericRefType;
import de.dhbwstuttgart.syntaxtree.type.RefType;
import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric;
import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder; import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder;
import de.dhbwstuttgart.typeinference.result.GenericInsertPair; import de.dhbwstuttgart.typeinference.result.GenericInsertPair;
import de.dhbwstuttgart.typeinference.result.ResultPair;
import de.dhbwstuttgart.typeinference.result.ResultSet; import de.dhbwstuttgart.typeinference.result.ResultSet;
/** /**
@@ -41,18 +23,13 @@ import de.dhbwstuttgart.typeinference.result.ResultSet;
public class TPHExtractor extends AbstractASTWalker{ public class TPHExtractor extends AbstractASTWalker{
// Alle TPHs der Felder werden iKopf der Klasse definiert // Alle TPHs der Felder werden iKopf der Klasse definiert
// alle TPHs der Klasse: (TPH, is in Method?) // alle TPHs der Klasse: (TPH, is in Method?)
public final HashMap<String, Boolean> allTPHS = new HashMap<>(); final HashMap<TypePlaceholder,Boolean> allTPHS = new HashMap<>();
public final List<String> tphsClass = new ArrayList<>();
MethodAndTPH methodAndTph; MethodAndTPH methodAndTph;
Boolean inMethod = false; Boolean inMethod = false;
boolean inLocalOrParamOrReturn = false;
public final ArrayList<MethodAndTPH> ListOfMethodsAndTph = new ArrayList<>(); public final ArrayList<MethodAndTPH> ListOfMethodsAndTph = new ArrayList<>();
final ArrayList<ResultPair<TypePlaceholder, TypePlaceholder>> allPairs = new ArrayList<>(); final ArrayList<GenericInsertPair> allPairs = new ArrayList<>();
public final ArrayList<TPHConstraint> allCons = new ArrayList<>(); public final ArrayList<TPHConstraint> allCons = new ArrayList<>();
private ResultSet resultSet; private ResultSet resultSet;
private Resolver resolver;
public TPHExtractor() { public TPHExtractor() {
@@ -60,108 +37,27 @@ public class TPHExtractor extends AbstractASTWalker {
public void setResultSet(ResultSet resultSet) { public void setResultSet(ResultSet resultSet) {
this.resultSet = resultSet; this.resultSet = resultSet;
this.resolver = new Resolver(resultSet);
} }
public Resolver getResolver() {
return resolver;
}
// @Override
// public void visit(ClassOrInterface classOrInterface) {
// inMethod = false;
// classOrInterface.getfieldInitializations().ifPresent(c->c.block.accept(this));
// super.visit(classOrInterface);
// inMethod = true;
// }
@Override @Override
public void visit(TypePlaceholder tph) { public void visit(TypePlaceholder tph) {
if(resultSet.resolveType(tph).resolvedType instanceof TypePlaceholder) { if(resultSet.resolveType(tph).resolvedType instanceof TypePlaceholder) {
TypePlaceholder resolvedTPH = (TypePlaceholder) resultSet.resolveType(tph).resolvedType; TypePlaceholder resolvedTPH = (TypePlaceholder) resultSet.resolveType(tph).resolvedType;
if (inMethod) { if(inMethod)
methodAndTph.getTphs().add(resolvedTPH.getName()); methodAndTph.getTphs().add(resolvedTPH.getName());
if (inLocalOrParamOrReturn)
methodAndTph.getLocalTphs().add(resolvedTPH.getName());
}else {
tphsClass.add(resolvedTPH.getName());
}
allTPHS.put(resolvedTPH.getName(), inMethod); allTPHS.put(resolvedTPH,inMethod);
// final List<TPHConstraint> cons = new ArrayList<>(); resultSet.resolveType(tph).additionalGenerics.forEach(ag ->{
// resultSet.resolveType(tph).additionalGenerics.forEach(ag -> { if(ag.contains(resolvedTPH)&&ag.TA1.equals(resolvedTPH)&&!contains(allPairs,ag)) {
// TPHConstraint con = new ExtendsConstraint(ag.TA1.getName(), ag.TA2.getName(), Relation.EXTENDS);
// cons.add(con);
// });
//
// Map<TPHConstraint, Boolean> visitMap = new HashMap<>();
// for(TPHConstraint cc : cons) {
// visitMap.put(cc, false);
// }
//
// String left = resolvedTPH.getName();
// for (TPHConstraint cc : visitMap.keySet()) {
//
// if(visitMap.get(cc))
// continue;
//
// if (cc.getLeft().equals(left)) {
// allCons.add(cc);
// List<TPHConstraint> toVisit = getToVisitCons(cons,cc.getRight(), visitMap);
// }
// }
//resultSet.resolveType(tph).getAdditionalGenerics().forEach(ag -> {
resultSet.genIns.forEach(ag -> {
// if (ag.contains(resolvedTPH) /* && ag.TA1.equals(resolvedTPH) */ && !contains(allPairs, ag)) {
if(inMethod) if(inMethod)
methodAndTph.getPairs().add(ag); methodAndTph.getPairs().add(ag);
allPairs.add(ag); allPairs.add(ag);
TPHConstraint con = new ExtendsConstraint(ag.getLeft().getName(), ag.getRight().getName()); TPHConstraint con = new ExtendsConstraint(ag.TA1.getName(), ag.TA2.getName(), Relation.EXTENDS);
if(!containsConstraint(allCons,con))
allCons.add(con); allCons.add(con);
// } }
}); });
} else if (resultSet.resolveType(tph).resolvedType instanceof RefType) {
RefType rt = (RefType) resultSet.resolveType(tph).resolvedType;
rt.accept(this);
} }
} }
private static boolean containsConstraint(ArrayList<TPHConstraint> allCons, TPHConstraint c) {
for(TPHConstraint con:allCons) {
if(c.getLeft().equals(con.getLeft()) && c.getRight().equals(con.getRight())) {
return true;
}
}
return false;
}
private List<TPHConstraint> getToVisitCons(List<TPHConstraint> cons, String right, Map<TPHConstraint, Boolean> visitMap) {
List<TPHConstraint> res = new ArrayList<>();
for(TPHConstraint cc : cons) {
if(cc.getLeft().equals(right)) {
res.add(cc);
if(visitMap.get(cc))
visitMap.replace(cc, false);
}
}
return res;
}
@Override
public void visit(GenericRefType genericRefType) {
String name = genericRefType.getParsedName();
if (inMethod) {
methodAndTph.getTphs().add(name);
if (inLocalOrParamOrReturn)
methodAndTph.getLocalTphs().add(name);
}else {
tphsClass.add(name);
}
allTPHS.put(name, inMethod);
}
private boolean contains(ArrayList<GenericInsertPair> pairs, GenericInsertPair genPair) { private boolean contains(ArrayList<GenericInsertPair> pairs, GenericInsertPair genPair) {
for(int i=0; i<pairs.size();++i) { for(int i=0; i<pairs.size();++i) {
GenericInsertPair p = pairs.get(i); GenericInsertPair p = pairs.get(i);
@@ -170,54 +66,13 @@ public class TPHExtractor extends AbstractASTWalker {
} }
return false; return false;
} }
@Override @Override
public void visit(Method method) { public void visit(Method method) {
inMethod = true; inMethod = true;
String id = MethodUtility.createID(resolver,method); methodAndTph = new MethodAndTPH(method.name);
methodAndTph = new MethodAndTPH(id); super.visit(method);
inLocalOrParamOrReturn = true;
method.getReturnType().accept(this);
method.getParameterList().accept(this);
inLocalOrParamOrReturn = false;
if(method.block != null)
method.block.accept(this);
inMethod = false; inMethod = false;
ListOfMethodsAndTph.add(methodAndTph); ListOfMethodsAndTph.add(methodAndTph);
} }
@Override
public void visit(Constructor cons) {
inMethod = false;
//super.visit(cons);
cons.getParameterList().accept(this);
if(cons.block != null)
cons.block.accept(this);
inMethod = true;
}
@Override
public void visit(LocalVarDecl localVarDecl) {
// inLocalOrParamOrReturn = inMethod;
super.visit(localVarDecl);
// inLocalOrParamOrReturn = false;
}
@Override
public void visit(LocalVar localVar) {
// inLocalOrParamOrReturn = inMethod;
super.visit(localVar);
// inLocalOrParamOrReturn = false;
}
@Override
public void visit(ParameterList formalParameters) {
inLocalOrParamOrReturn = inMethod;
super.visit(formalParameters);
inLocalOrParamOrReturn = false;
}
} }

View File

@@ -2,8 +2,8 @@ package de.dhbwstuttgart.bytecode.constraint;
public class EqualConstraint extends TPHConstraint { public class EqualConstraint extends TPHConstraint {
public EqualConstraint(String left, String right) { public EqualConstraint(String left, String right, Relation rel) {
super(left, right, Relation.EQUAL); super(left, right, rel);
} }
} }

View File

@@ -2,8 +2,8 @@ package de.dhbwstuttgart.bytecode.constraint;
public class ExtendsConstraint extends TPHConstraint { public class ExtendsConstraint extends TPHConstraint {
public ExtendsConstraint(String left, String right) { public ExtendsConstraint(String left, String right, Relation rel) {
super(left, right, Relation.EXTENDS); super(left, right, rel);
} }
} }

View File

@@ -44,10 +44,6 @@ public class TPHConstraint {
return left.equals(tph)||right.equals(tph); return left.equals(tph)||right.equals(tph);
} }
public boolean equalConstraint(TPHConstraint constraint) {
return rel == constraint.getRel() && left.equals(constraint.getLeft()) && right.equals(constraint.getRight());
}
@Override @Override
public String toString() { public String toString() {
if(rel == Relation.EXTENDS) { if(rel == Relation.EXTENDS) {

View File

@@ -1,29 +1,30 @@
package de.dhbwstuttgart.bytecode.descriptor; package de.dhbwstuttgart.bytecode.descriptor;
import java.util.HashMap;
import java.util.Iterator; import java.util.Iterator;
import de.dhbwstuttgart.bytecode.utilities.*;
import de.dhbwstuttgart.syntaxtree.statement.ArgumentList;
import org.objectweb.asm.Type; import org.objectweb.asm.Type;
import de.dhbwstuttgart.bytecode.signature.TypeToSignature;
import de.dhbwstuttgart.bytecode.utilities.Lambda;
import de.dhbwstuttgart.bytecode.utilities.MethodFromMethodCall;
import de.dhbwstuttgart.bytecode.utilities.NormalConstructor;
import de.dhbwstuttgart.bytecode.utilities.NormalMethod;
import de.dhbwstuttgart.bytecode.utilities.SamMethod;
import de.dhbwstuttgart.syntaxtree.FormalParameter; import de.dhbwstuttgart.syntaxtree.FormalParameter;
import de.dhbwstuttgart.syntaxtree.statement.Expression; import de.dhbwstuttgart.syntaxtree.statement.Expression;
import de.dhbwstuttgart.syntaxtree.type.RefType;
import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric; import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric;
import de.dhbwstuttgart.typeinference.result.ResultSet; import de.dhbwstuttgart.typeinference.result.ResultSet;
public class DescriptorToString implements DescriptorVisitor, CONSTANTS { public class DescriptorToString implements DescriptorVisitor{
ResultSet resultSet; ResultSet resultSet;
public DescriptorToString() {
}
public DescriptorToString(ResultSet resultSet) { public DescriptorToString(ResultSet resultSet) {
this.resultSet = resultSet; this.resultSet = resultSet;
} }
private String addReturnType(String desc, RefTypeOrTPHOrWildcardOrGeneric returnType, ResultSet resultSet) { private String addReturnType(String desc, RefTypeOrTPHOrWildcardOrGeneric returnType, ResultSet resultSet) {
if(resultSet.resolveType(returnType).resolvedType.toString().equals(CONSTANTS.VOID)){ if(resultSet.resolveType(returnType).resolvedType.toString().equals("void")){
desc = desc + ")V"; desc = desc + ")V";
}else { }else {
desc = desc + ")" + "L"+resultSet.resolveType(returnType).resolvedType.acceptTV(new TypeToDescriptor())+ ";"; desc = desc + ")" + "L"+resultSet.resolveType(returnType).resolvedType.acceptTV(new TypeToDescriptor())+ ";";
@@ -43,41 +44,30 @@ public class DescriptorToString implements DescriptorVisitor, CONSTANTS {
if(method.hasGen()) { if(method.hasGen()) {
String fpDesc = fp.getType().acceptTV(new TypeToDescriptor()); String fpDesc = fp.getType().acceptTV(new TypeToDescriptor());
if(method.getGenericsAndBoundsMethod().containsKey(fpDesc)) { if(method.getGenericsAndBoundsMethod().containsKey(fpDesc)) {
String bound = getBound(fpDesc, method.getGenericsAndBoundsMethod()); desc += "L"+method.getGenericsAndBoundsMethod().get(fpDesc)+ ";";
desc += "L"+bound+ ";";
}else if(method.getGenericsAndBounds().containsKey(fpDesc)){ }else if(method.getGenericsAndBounds().containsKey(fpDesc)){
String bound = getBound(fpDesc, method.getGenericsAndBounds()); desc += "L"+method.getGenericsAndBounds().get(fpDesc)+ ";";
desc += "L"+bound+ ";";
}else { }else {
// desc += "L"+resultSet.resolveType(fp.getType()).resolvedType.acceptTV(new TypeToDescriptor())+ ";"; // desc += "L"+resultSet.resolveType(fp.getType()).resolvedType.acceptTV(new TypeToDescriptor())+ ";";
String resType = resultSet.resolveType(fp.getType()).resolvedType.acceptTV(new TypeToDescriptor()); String resType = resultSet.resolveType(fp.getType()).resolvedType.acceptTV(new TypeToDescriptor());
if(resType.contains(CONSTANTS.TPH)/*resType.subSequence(0, 4).equals("TPH ")*/) { if(resType.subSequence(0, 4).equals("TPH ")) {
// Bound ist immer Object // Bound ist immer Object
desc += "L"+Type.getInternalName(Object.class)+ ";"; desc += "L"+Type.getInternalName(Object.class)+ ";";
} else {
// TODO::
if(method.getGenericsAndBounds().containsKey(resType)) {
String bound = getBound(resType, method.getGenericsAndBounds());
desc += "L"+bound+ ";";
}else if(method.getGenericsAndBoundsMethod().containsKey(resType)) {
String bound = getBound(resType, method.getGenericsAndBoundsMethod());
desc += "L"+bound+ ";";
} else { } else {
desc += "L"+resType+ ";"; desc += "L"+resType+ ";";
} }
} }
} }
}
//TODO: generate a class java%% ... %% //TODO: generate a class java%% ... %%
else if(resultSet.resolveType(fp.getType()).resolvedType.acceptTV(new TypeToDescriptor()).contains(CONSTANTS.ANGLEBRACKET)){ else if(resultSet.resolveType(fp.getType()).resolvedType.acceptTV(new TypeToDescriptor()).contains("<")){
desc += "L"+resultSet.resolveType(fp.getType()).resolvedType.toString().replace(".", "$$").replace(CONSTANTS.ANGLEBRACKET, "$$$").replace(">", "$$$")+ ";"; desc += "L"+resultSet.resolveType(fp.getType()).resolvedType.toString().replace(".", "$$").replace("<", "$$$").replace(">", "$$$")+ ";";
} }
else { else {
desc += "L"+resultSet.resolveType(fp.getType()).resolvedType.acceptTV(new TypeToDescriptor())+ ";"; desc += "L"+resultSet.resolveType(fp.getType()).resolvedType.acceptTV(new TypeToDescriptor())+ ";";
} }
} }
if(resultSet.resolveType(method.getReturnType()).resolvedType.toString().equals(CONSTANTS.VOID)) { if(resultSet.resolveType(method.getReturnType()).resolvedType.toString().equals("void")) {
desc += ")V"; desc += ")V";
}else { }else {
if(method.hasGen()) { if(method.hasGen()) {
@@ -88,21 +78,11 @@ public class DescriptorToString implements DescriptorVisitor, CONSTANTS {
desc += ")L"+method.getGenericsAndBounds().get(ret)+ ";"; desc += ")L"+method.getGenericsAndBounds().get(ret)+ ";";
}else { }else {
String resType = resultSet.resolveType(method.getReturnType()).resolvedType.acceptTV(new TypeToDescriptor()); String resType = resultSet.resolveType(method.getReturnType()).resolvedType.acceptTV(new TypeToDescriptor());
if(resType.contains(CONSTANTS.TPH)/*resType.subSequence(0, 4).equals("TPH ")*/) { if(resType.subSequence(0, 4).equals("TPH ")) {
// desc += ")" + "L"+method.getGenericsAndBoundsMethod().get(resType.substring(4)+"$")+ ";"; // desc += ")" + "L"+method.getGenericsAndBoundsMethod().get(resType.substring(4)+"$")+ ";";
desc += ")" + "L"+Type.getInternalName(Object.class)+ ";"; desc += ")" + "L"+Type.getInternalName(Object.class)+ ";";
} else { } else {
// TODO:: desc += ")" + "L"+resType+ ";";
if(method.getGenericsAndBounds().containsKey(resType)) {
String bound = getBound(resType, method.getGenericsAndBounds());
desc += ")L"+bound+ ";";
}else if(method.getGenericsAndBoundsMethod().containsKey(resType)) {
String bound = getBound(resType, method.getGenericsAndBoundsMethod());
desc += ")L"+bound+ ";";
} else {
desc += ")L"+resType+ ";";
}
// desc += ")" + "L"+resType+ ";";
} }
} }
}else { }else {
@@ -113,15 +93,6 @@ public class DescriptorToString implements DescriptorVisitor, CONSTANTS {
return desc; return desc;
} }
private String getBound(String fpDesc, HashMap<String, String> genericsAndBounds) {
String start = genericsAndBounds.get(fpDesc);
while(genericsAndBounds.containsKey(start)) {
start = genericsAndBounds.get(start);
}
return start;
}
@Override @Override
public String visit(NormalConstructor constructor) { public String visit(NormalConstructor constructor) {
String desc = "("; String desc = "(";
@@ -137,7 +108,7 @@ public class DescriptorToString implements DescriptorVisitor, CONSTANTS {
}else { }else {
// desc += "L"+resultSet.resolveType(fp.getType()).resolvedType.acceptTV(new TypeToDescriptor())+ ";"; // desc += "L"+resultSet.resolveType(fp.getType()).resolvedType.acceptTV(new TypeToDescriptor())+ ";";
String resType = resultSet.resolveType(fp.getType()).resolvedType.acceptTV(new TypeToDescriptor()); String resType = resultSet.resolveType(fp.getType()).resolvedType.acceptTV(new TypeToDescriptor());
if(resType.subSequence(0, 4).equals(CONSTANTS.TPH)) { if(resType.subSequence(0, 4).equals("TPH ")) {
// Bound ist immer Object // Bound ist immer Object
desc += "L"+Type.getInternalName(Object.class)+ ";"; desc += "L"+Type.getInternalName(Object.class)+ ";";
} else { } else {
@@ -160,7 +131,7 @@ public class DescriptorToString implements DescriptorVisitor, CONSTANTS {
while(itr.hasNext()) { while(itr.hasNext()) {
FormalParameter fp = itr.next(); FormalParameter fp = itr.next();
String d = resultSet.resolveType(fp.getType()).resolvedType.acceptTV(new TypeToDescriptor()); String d = resultSet.resolveType(fp.getType()).resolvedType.acceptTV(new TypeToDescriptor());
if(d.contains(CONSTANTS.TPH) ||d.contains(CONSTANTS.ANGLEBRACKET)) { if(d.substring(0, 4).equals("TPH ") ||d.contains("<")) {
desc += "L"+Type.getInternalName(Object.class)+ ";"; desc += "L"+Type.getInternalName(Object.class)+ ";";
}else { }else {
desc = desc + "L"+ d + ";"; desc = desc + "L"+ d + ";";
@@ -169,7 +140,7 @@ public class DescriptorToString implements DescriptorVisitor, CONSTANTS {
String retType = resultSet.resolveType(lambdaExpression.getReturnType()).resolvedType.acceptTV(new TypeToDescriptor()); String retType = resultSet.resolveType(lambdaExpression.getReturnType()).resolvedType.acceptTV(new TypeToDescriptor());
if(retType.contains(CONSTANTS.TPH)|| retType.contains(CONSTANTS.ANGLEBRACKET)){ if(retType.substring(0, 4).equals("TPH ")|| retType.contains("<")){
desc += ")L"+Type.getInternalName(Object.class)+ ";"; desc += ")L"+Type.getInternalName(Object.class)+ ";";
}else { }else {
desc = desc + ")"+"L"+retType+";"; desc = desc + ")"+"L"+retType+";";
@@ -185,7 +156,7 @@ public class DescriptorToString implements DescriptorVisitor, CONSTANTS {
RefTypeOrTPHOrWildcardOrGeneric rt = itr.next(); RefTypeOrTPHOrWildcardOrGeneric rt = itr.next();
String d = resultSet.resolveType(rt).resolvedType.acceptTV(new TypeToDescriptor()); String d = resultSet.resolveType(rt).resolvedType.acceptTV(new TypeToDescriptor());
if(d.contains(CONSTANTS.TPH) ||d.contains(CONSTANTS.ANGLEBRACKET)) { if(d.substring(0, 4).equals("TPH ") ||d.contains("<")) {
desc += "L"+Type.getInternalName(Object.class)+ ";"; desc += "L"+Type.getInternalName(Object.class)+ ";";
}else { }else {
desc += "L"+ d + ";"; desc += "L"+ d + ";";
@@ -194,7 +165,7 @@ public class DescriptorToString implements DescriptorVisitor, CONSTANTS {
} }
String retType = resultSet.resolveType(samMethod.getReturnType()).resolvedType.acceptTV(new TypeToDescriptor()); String retType = resultSet.resolveType(samMethod.getReturnType()).resolvedType.acceptTV(new TypeToDescriptor());
if(retType.contains(CONSTANTS.TPH)|| retType.contains(CONSTANTS.ANGLEBRACKET)){ if(retType.substring(0, 4).equals("TPH ")|| retType.contains("<")){
desc += ")L"+Type.getInternalName(Object.class)+ ";"; desc += ")L"+Type.getInternalName(Object.class)+ ";";
}else { }else {
desc = desc + ")"+"L"+retType+";"; desc = desc + ")"+"L"+retType+";";
@@ -208,7 +179,7 @@ public class DescriptorToString implements DescriptorVisitor, CONSTANTS {
for(Expression e : methodFromMethodCall.getArgList().getArguments()) { for(Expression e : methodFromMethodCall.getArgList().getArguments()) {
String d = resultSet.resolveType(e.getType()).resolvedType.acceptTV(new TypeToDescriptor()); String d = resultSet.resolveType(e.getType()).resolvedType.acceptTV(new TypeToDescriptor());
if(d.contains(CONSTANTS.TPH) ||d.contains(CONSTANTS.ANGLEBRACKET) || methodFromMethodCall.getReceiverName().contains("$$")) { if(d.substring(0, 4).equals("TPH ") ||d.contains("<") || methodFromMethodCall.getReceiverName().contains("$$")) {
desc += "L"+Type.getInternalName(Object.class)+ ";"; desc += "L"+Type.getInternalName(Object.class)+ ";";
}else { }else {
if(methodFromMethodCall.getGenericsAndBoundsMethod().containsKey(d)) { if(methodFromMethodCall.getGenericsAndBoundsMethod().containsKey(d)) {
@@ -223,9 +194,9 @@ public class DescriptorToString implements DescriptorVisitor, CONSTANTS {
} }
String retType = resultSet.resolveType(methodFromMethodCall.getReturnType()).resolvedType.acceptTV(new TypeToDescriptor()); String retType = resultSet.resolveType(methodFromMethodCall.getReturnType()).resolvedType.acceptTV(new TypeToDescriptor());
System.out.println("DescriptorToString retType = " + retType); System.out.println("DescriptorToString retType = " + retType);
if(retType.equals(CONSTANTS.VOID)) { if(retType.equals("void")) {
desc += ")V"; desc += ")V";
}else if(retType.contains(CONSTANTS.TPH)|| retType.contains(CONSTANTS.ANGLEBRACKET) || methodFromMethodCall.getReceiverName().contains("$$")){ }else if(retType.substring(0, 4).equals("TPH ")|| retType.contains("<") || methodFromMethodCall.getReceiverName().contains("$$")){
desc += ")L"+Type.getInternalName(Object.class)+ ";"; desc += ")L"+Type.getInternalName(Object.class)+ ";";
}else { }else {
if(methodFromMethodCall.getGenericsAndBoundsMethod().containsKey(retType)) { if(methodFromMethodCall.getGenericsAndBoundsMethod().containsKey(retType)) {
@@ -240,20 +211,4 @@ public class DescriptorToString implements DescriptorVisitor, CONSTANTS {
return desc; return desc;
} }
@Override
public String createDescForFunN(ArgumentList argumentList, String returnType) {
Iterator<Expression> itr1 = argumentList.getArguments().iterator();
String methDesc = "(";
while(itr1.hasNext()) {
methDesc += "L" + Type.getInternalName(Object.class) + ";";
itr1.next();
}
if (returnType.equals(CONSTANTS.VOID)){
methDesc += ")V";
} else {
methDesc += ")L" + Type.getInternalName(Object.class) + ";";
}
return methDesc;
}
} }

View File

@@ -5,13 +5,11 @@ import de.dhbwstuttgart.bytecode.utilities.MethodFromMethodCall;
import de.dhbwstuttgart.bytecode.utilities.NormalConstructor; import de.dhbwstuttgart.bytecode.utilities.NormalConstructor;
import de.dhbwstuttgart.bytecode.utilities.NormalMethod; import de.dhbwstuttgart.bytecode.utilities.NormalMethod;
import de.dhbwstuttgart.bytecode.utilities.SamMethod; import de.dhbwstuttgart.bytecode.utilities.SamMethod;
import de.dhbwstuttgart.syntaxtree.statement.ArgumentList;
public interface DescriptorVisitor { public interface DescriptorVisitor {
String visit(NormalMethod method); public String visit(NormalMethod method);
String visit(NormalConstructor constructor); public String visit(NormalConstructor constructor);
String visit(Lambda lambdaExpression); public String visit(Lambda lambdaExpression);
String visit(SamMethod samMethod); public String visit(SamMethod samMethod);
String visit(MethodFromMethodCall methodFromMethodCall); public String visit(MethodFromMethodCall methodFromMethodCall);
String createDescForFunN(ArgumentList argumentList, String returnType);
} }

View File

@@ -1,53 +0,0 @@
/**
*
*/
package de.dhbwstuttgart.bytecode.genericsGenerator;
import java.util.List;
import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.NameReplacementResult;
import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.GenericsGeneratorResult;
/**
* This class represents the result of the constraints simplifier.
*
* @author fayez
*
*/
public class ConstraintsSimplierResult {
private List<GenericsGeneratorResult> genericsGenResults;
private List<NameReplacementResult> nameReplacementResults;
/**
* @param genericsGenResults
*/
public ConstraintsSimplierResult(List<GenericsGeneratorResult> genericsGenResults,
List<NameReplacementResult> nameReplacementResults) {
this.genericsGenResults = genericsGenResults;
this.setNameReplacementResults(nameReplacementResults);
}
/**
* @return the genericsGenResults
*/
public List<GenericsGeneratorResult> getGenericsGenResults() {
return genericsGenResults;
}
/**
* @param genericsGenResults the genericsGenResults to set
*/
public void setGenericsGenResults(List<GenericsGeneratorResult> genericsGenResults) {
this.genericsGenResults = genericsGenResults;
}
/**
* @return the nameReplacementResults
*/
public List<NameReplacementResult> getNameReplacementResults() {
return nameReplacementResults;
}
/**
* @param nameReplacementResults the nameReplacementResults to set
*/
public void setNameReplacementResults(List<NameReplacementResult> nameReplacementResults) {
this.nameReplacementResults = nameReplacementResults;
}
}

View File

@@ -1,137 +0,0 @@
/**
*
*/
package de.dhbwstuttgart.bytecode.genericsGenerator;
import java.util.*;
import de.dhbwstuttgart.bytecode.TPHExtractor;
import de.dhbwstuttgart.bytecode.constraint.TPHConstraint;
import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.*;
/**
* @author fayez
*
*/
public class ConstraintsSimplifier {
public static ConstraintsSimplierResult simplifyConstraints(final TPHExtractor tphExtractor, final List<GenericsGeneratorResult> genericsGeneratorResults, final List<String> tphsClass) {
List<TPHConstraint> allCons = tphExtractor.allCons;
List<TPHConstraint> equalCons = new ArrayList<>();
/* Step 1 */
List<ConstraintsWithSameLeftSide> foundCons = GenericsGeneratorUtility.findConstraintsWithLeftSameLeftSide(allCons);
if(!foundCons.isEmpty()) {
List<TPHConstraint> equalCons2 = new ArrayList<>();
GenericsGeneratorUtility.simplifyConstraintsWithSameLeftSide(foundCons,tphExtractor,tphsClass,equalCons2);
equalCons.addAll(equalCons2);
}
// if(!simpleCycles.isEmpty()) {
// handleSimpleCycles(allCons, simpleCycles,tphExtractor);
// equalCons.addAll(GenericsGeneratorUtility.getEqualConstraints(allCons));
// }
//
List<Cycle> cycles = findCycles(allCons);
if(!cycles.isEmpty()) {
handleCycle(genericsGeneratorResults, allCons, cycles,tphExtractor);
}
/* The right hand side of equal constraint is the new name in name replacement result */
List<NameReplacementResult> nameReplacementResults = GenericsGeneratorUtility.createNameReplacementResultsFromEqualConstraints(equalCons);
getEqualsFromNameReplacementResults(genericsGeneratorResults,nameReplacementResults);
ConstraintsSimplierResult result = new ConstraintsSimplierResult(genericsGeneratorResults, nameReplacementResults);
return result;
}
private static void getEqualsFromNameReplacementResults(List<GenericsGeneratorResult> genericsGeneratorResults,
List<NameReplacementResult> nameReplacementResults) {
genericsGeneratorResults.forEach(g->{
String tph = g.getConstraint().getLeft();
if (!nameReplacementResults.isEmpty()) {
collectAllEquals(nameReplacementResults, g, tph);
}
if (!nameReplacementResults.isEmpty()) {
collectAllEquals(nameReplacementResults, g);
}
});
}
private static void collectAllEquals(List<NameReplacementResult> nameReplacementResults, GenericsGeneratorResult g) {
Set<String> equalsTPHs = g.getEqualsTPHs();
Set<String> tphsToAdd = getAllEqualTphs(equalsTPHs, nameReplacementResults);
while (!tphsToAdd.isEmpty()){
equalsTPHs.addAll(tphsToAdd);
tphsToAdd = getAllEqualTphs(equalsTPHs, nameReplacementResults);
}
}
private static Set<String> getAllEqualTphs(Set<String> equalsTPHs, List<NameReplacementResult> nameReplacementResults) {
Set<String> tphsToAdd = new HashSet<>();
equalsTPHs.forEach(e->{
collectAllEquals(nameReplacementResults, tphsToAdd,e);
});
return tphsToAdd;
}
public static void collectAllEquals(List<NameReplacementResult> nameReplacementResults, Set<String> tphsToAdd,
String tph) {
List<NameReplacementResult> toRemoveList = new ArrayList<>();
Optional<NameReplacementResult> nameReplacementResult = nameReplacementResults.stream().filter(n->n.getName().equals(tph)).findFirst();
nameReplacementResult.ifPresent(toRemove->{
tphsToAdd.addAll(toRemove.getOldNames());
toRemoveList.add(toRemove);
});
if(!toRemoveList.isEmpty()){
nameReplacementResults.remove(toRemoveList.get(0));
toRemoveList.clear();
}
}
/**
* @param nameReplacementResults
* @param g
* @param tph
*/
public static void collectAllEquals(List<NameReplacementResult> nameReplacementResults, GenericsGeneratorResult g,
String tph) {
List<NameReplacementResult> toRemoveList = new ArrayList<>();
Optional<NameReplacementResult> nameReplacementResult = nameReplacementResults.stream().filter(n->n.getName().equals(tph)).findFirst();
nameReplacementResult.ifPresent(toRemove->{
g.getEqualsTPHs().addAll(toRemove.getOldNames());
toRemoveList.add(toRemove);
});
if(!toRemoveList.isEmpty()){
nameReplacementResults.remove(toRemoveList.get(0));
toRemoveList.clear();
}
}
/**
* @param genericsGeneratorResults
* @param allCons
* @param cycles
* @param tphExtractor
*/
public static void handleCycle(List<GenericsGeneratorResult> genericsGeneratorResults,
List<TPHConstraint> allCons, List<Cycle> cycles, TPHExtractor tphExtractor) {
GenericsGeneratorUtility.modifyRelationForConstraintsInCycle(cycles);
List<NameReplacementResult> nameReplacementResults = GenericsGeneratorUtility.substituteTPHSFormCycle(allCons, cycles,tphExtractor);
GenericsGeneratorUtility.createResults(genericsGeneratorResults,nameReplacementResults);
GenericsGeneratorUtility.removeEqualConstraints(allCons);
}
/**
* @param allCons
* @return
*/
public static List<Cycle> findCycles(List<TPHConstraint> allCons) {
/* find all cycles */
CyclesFinder cyclesFinder = new CyclesFinder(allCons);
List<Cycle> cycles = cyclesFinder.findCycles();
return cycles;
}
}

View File

@@ -1,106 +0,0 @@
/**
*
*/
package de.dhbwstuttgart.bytecode.genericsGenerator;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import de.dhbwstuttgart.bytecode.constraint.TPHConstraint;
import de.dhbwstuttgart.bytecode.constraint.TPHConstraint.Relation;
import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.Cycle;
/**
* @author fayez
*
*/
public class CyclesFinder {
private final List<TPHConstraint> allCons;
public CyclesFinder(List<TPHConstraint> allCons) {
this.allCons = allCons;
}
public List<Cycle> findCycles() {
List<TPHConstraint> vistedConstraints = new ArrayList<>(allCons.size());
List<Cycle> cycles = new ArrayList<>();
for (TPHConstraint constraint : allCons) {
if(constraint.getRel()==Relation.EQUAL)
continue;
if (!vistedConstraints.contains(constraint)) {
vistedConstraints.add(constraint);
checkConstraint(constraint, vistedConstraints, cycles);
}
}
return cycles;
}
private void checkConstraint(TPHConstraint constraint, List<TPHConstraint> vistedConstraints,
List<Cycle> cycles) {
List<String> tphsInRelation = new LinkedList<>();
List<TPHConstraint> maybeCycle = new ArrayList<>();
maybeCycle.add(constraint);
tphsInRelation.add(constraint.getLeft());
tphsInRelation.add(constraint.getRight());
Optional<TPHConstraint> nextConstraint = getConstraintInRelation(tphsInRelation, maybeCycle);
while (nextConstraint.isPresent()) {
if(containsInLongCycle(nextConstraint.get(), cycles)) {
break;
}
if (isCycle(tphsInRelation)) {
addAllToVisitedConstraints(vistedConstraints, maybeCycle);
Cycle cycle = new Cycle(maybeCycle);
cycles.add(cycle);
return;
}
nextConstraint = getConstraintInRelation(tphsInRelation, maybeCycle);
}
// addAllToVisitedConstraints(vistedConstraints, maybeCycle);
}
private boolean containsInLongCycle(TPHConstraint c, List<Cycle> cycles) {
for(Cycle cycle : cycles) {
if(cycle.containConstraint(c))
return true;
}
return false;
}
private void addAllToVisitedConstraints(List<TPHConstraint> vistedConstraints, List<TPHConstraint> maybeCycle) {
for (TPHConstraint con : maybeCycle) {
if (!vistedConstraints.contains(con))
vistedConstraints.add(con);
}
}
private Optional<TPHConstraint> getConstraintInRelation(List<String> tphsInRelation,
List<TPHConstraint> maybeCycle) {
TPHConstraint constraint = getConstraintByLeftSide(tphsInRelation.get(tphsInRelation.size()-1),maybeCycle);
Optional<TPHConstraint> nextConstraint = Optional.ofNullable(constraint);
if(nextConstraint.isPresent()) {
maybeCycle.add(constraint);
tphsInRelation.add(constraint.getRight());
}
return nextConstraint;
}
private TPHConstraint getConstraintByLeftSide(String left, List<TPHConstraint> maybeCycle) {
for(TPHConstraint constraint : allCons) {
if(constraint.getRel()==Relation.EQUAL)
continue;
if(maybeCycle.contains(constraint))
continue;
if(constraint.getLeft().equals(left))
return constraint;
}
return null;
}
private boolean isCycle(List<String> tphsInRelation) {
return tphsInRelation.get(0).equals(tphsInRelation.get(tphsInRelation.size() - 1));
}
}

View File

@@ -1,674 +0,0 @@
/**
*
*/
package de.dhbwstuttgart.bytecode.genericsGenerator;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import de.dhbwstuttgart.bytecode.TPHExtractor;
import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.GenericGenratorResultForSourceFile;
import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.GenericsGeneratorResultForClass;
import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.MethodAndConstraints;
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.syntaxtree.ASTVisitor;
import de.dhbwstuttgart.syntaxtree.ClassOrInterface;
import de.dhbwstuttgart.syntaxtree.Constructor;
import de.dhbwstuttgart.syntaxtree.Field;
import de.dhbwstuttgart.syntaxtree.FormalParameter;
import de.dhbwstuttgart.syntaxtree.GenericDeclarationList;
import de.dhbwstuttgart.syntaxtree.GenericTypeVar;
import de.dhbwstuttgart.syntaxtree.Method;
import de.dhbwstuttgart.syntaxtree.ParameterList;
import de.dhbwstuttgart.syntaxtree.SourceFile;
import de.dhbwstuttgart.syntaxtree.statement.ArgumentList;
import de.dhbwstuttgart.syntaxtree.statement.Assign;
import de.dhbwstuttgart.syntaxtree.statement.AssignToField;
import de.dhbwstuttgart.syntaxtree.statement.BinaryExpr;
import de.dhbwstuttgart.syntaxtree.statement.Block;
import de.dhbwstuttgart.syntaxtree.statement.CastExpr;
import de.dhbwstuttgart.syntaxtree.statement.DoStmt;
import de.dhbwstuttgart.syntaxtree.statement.EmptyStmt;
import de.dhbwstuttgart.syntaxtree.statement.ExpressionReceiver;
import de.dhbwstuttgart.syntaxtree.statement.FieldVar;
import de.dhbwstuttgart.syntaxtree.statement.ForStmt;
import de.dhbwstuttgart.syntaxtree.statement.IfStmt;
import de.dhbwstuttgart.syntaxtree.statement.InstanceOf;
import de.dhbwstuttgart.syntaxtree.statement.LambdaExpression;
import de.dhbwstuttgart.syntaxtree.statement.Literal;
import de.dhbwstuttgart.syntaxtree.statement.LocalVar;
import de.dhbwstuttgart.syntaxtree.statement.LocalVarDecl;
import de.dhbwstuttgart.syntaxtree.statement.MethodCall;
import de.dhbwstuttgart.syntaxtree.statement.NewArray;
import de.dhbwstuttgart.syntaxtree.statement.NewClass;
import de.dhbwstuttgart.syntaxtree.statement.Return;
import de.dhbwstuttgart.syntaxtree.statement.ReturnVoid;
import de.dhbwstuttgart.syntaxtree.statement.StaticClassName;
import de.dhbwstuttgart.syntaxtree.statement.Super;
import de.dhbwstuttgart.syntaxtree.statement.SuperCall;
import de.dhbwstuttgart.syntaxtree.statement.This;
import de.dhbwstuttgart.syntaxtree.statement.UnaryExpr;
import de.dhbwstuttgart.syntaxtree.statement.WhileStmt;
import de.dhbwstuttgart.syntaxtree.type.ExtendsWildcardType;
import de.dhbwstuttgart.syntaxtree.type.GenericRefType;
import de.dhbwstuttgart.syntaxtree.type.RefType;
import de.dhbwstuttgart.syntaxtree.type.SuperWildcardType;
import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder;
import de.dhbwstuttgart.typeinference.result.ResultSet;
/**
* @author fayez
*
*/
public class GeneratedGenericsFinder implements ASTVisitor {
private final TPHExtractor tphExtractor = new TPHExtractor();
private Collection<ResultSet> listOfResultSets;
private SourceFile sf;
private List<String> tphsClass;
private GenericGenratorResultForSourceFile generatedGenericsForSF;
private ResultSet resultSet;
private final List<String> methodNameAndParamsT = new ArrayList<>();
private String pkgName;
private String className;
private Resolver resolver;
/**
* @param sf
* @param listOfResultSets
*/
public GeneratedGenericsFinder(SourceFile sf, Collection<ResultSet> listOfResultSets) {
this.sf = sf;
this.listOfResultSets = listOfResultSets;
}
public GenericGenratorResultForSourceFile findGeneratedGenerics() {
sf.accept(this);
return generatedGenericsForSF;
}
/*
* (non-Javadoc)
*
* @see
* de.dhbwstuttgart.syntaxtree.ASTVisitor#visit(de.dhbwstuttgart.syntaxtree.
* SourceFile)
*/
@Override
public void visit(SourceFile sourceFile) {
pkgName = sf.getPkgName();
generatedGenericsForSF = new GenericGenratorResultForSourceFile(pkgName);
for (ClassOrInterface cl : sourceFile.getClasses()) {
cl.accept(this);
}
}
/*
* (non-Javadoc)
*
* @see
* de.dhbwstuttgart.syntaxtree.ASTVisitor#visit(de.dhbwstuttgart.syntaxtree.
* ClassOrInterface)
*/
@Override
public void visit(ClassOrInterface classOrInterface) {
className = classOrInterface.getClassName().toString();
List<ResultSet> listOfResultSetsList = new ArrayList<>(listOfResultSets);
boolean isVisited = false;
ConstraintsSimplierResult simplifiedConstraints = null;
GenericsGeneratorResultForClass ggResult = null;
for (int i = 0; i < listOfResultSetsList.size(); i++) {
resultSet = listOfResultSetsList.get(i);
tphExtractor.setResultSet(resultSet);
resolver = new Resolver(resultSet);
classOrInterface.accept(tphExtractor);
tphsClass = tphExtractor.tphsClass;
simplifiedConstraints = GenericsGenerator.simplifyConstraints(tphExtractor, tphsClass);
if(!isVisited) {
ggResult = GenericsGenerator.generateConstraints(className, tphExtractor, tphsClass,simplifiedConstraints);
isVisited = true;
}
for(Method m : classOrInterface.getMethods()) {
addMethodConstraints(simplifiedConstraints, ggResult, m);
}
if(ggResult != null)
generatedGenericsForSF.addGenericGeneratorResultClass(ggResult);
}
}
/**
* @param simplifiedConstraints
* @param ggResult
* @param m
*/
public void addMethodConstraints(ConstraintsSimplierResult simplifiedConstraints,
GenericsGeneratorResultForClass ggResult, Method m) {
String id = MethodUtility.createID(resolver, m);
boolean isInGGResult = (ggResult != null) && ggResult.contains(id);
if(methodNameAndParamsT.contains(id) || isInGGResult)
return;
methodNameAndParamsT.add(id);
Optional<MethodAndTPH> methodAndTPH = GenericsGeneratorUtility.getMethodAndTphs(tphExtractor.ListOfMethodsAndTph,id);
methodAndTPH.ifPresent(mt->{
MethodAndConstraints methodConstraints = GenericsGenerator.generateConstraintsForMethod(tphExtractor.allCons, mt , simplifiedConstraints, tphsClass);
ggResult.getMethodsAndTheirConstraints().getMethodsAndConstraints().add(methodConstraints);
});
}
/*
* (non-Javadoc)
*
* @see
* de.dhbwstuttgart.syntaxtree.ASTVisitor#visit(de.dhbwstuttgart.syntaxtree.
* Method)
*/
@Override
public void visit(Method method) {
}
/*
* (non-Javadoc)
*
* @see
* de.dhbwstuttgart.syntaxtree.ASTVisitor#visit(de.dhbwstuttgart.syntaxtree.
* ParameterList)
*/
@Override
public void visit(ParameterList formalParameters) {
}
/*
* (non-Javadoc)
*
* @see
* de.dhbwstuttgart.syntaxtree.ASTVisitor#visit(de.dhbwstuttgart.syntaxtree.
* Constructor)
*/
@Override
public void visit(Constructor field) {
}
/*
* (non-Javadoc)
*
* @see de.dhbwstuttgart.syntaxtree.StatementVisitor#visit(de.dhbwstuttgart.
* syntaxtree.statement.ArgumentList)
*/
@Override
public void visit(ArgumentList argumentList) {
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
*
* @see de.dhbwstuttgart.syntaxtree.StatementVisitor#visit(de.dhbwstuttgart.
* syntaxtree.statement.LambdaExpression)
*/
@Override
public void visit(LambdaExpression lambdaExpression) {
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
*
* @see de.dhbwstuttgart.syntaxtree.StatementVisitor#visit(de.dhbwstuttgart.
* syntaxtree.statement.Assign)
*/
@Override
public void visit(Assign assign) {
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
*
* @see de.dhbwstuttgart.syntaxtree.StatementVisitor#visit(de.dhbwstuttgart.
* syntaxtree.statement.BinaryExpr)
*/
@Override
public void visit(BinaryExpr binary) {
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
*
* @see de.dhbwstuttgart.syntaxtree.StatementVisitor#visit(de.dhbwstuttgart.
* syntaxtree.statement.Block)
*/
@Override
public void visit(Block block) {
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
*
* @see de.dhbwstuttgart.syntaxtree.StatementVisitor#visit(de.dhbwstuttgart.
* syntaxtree.statement.CastExpr)
*/
@Override
public void visit(CastExpr castExpr) {
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
*
* @see de.dhbwstuttgart.syntaxtree.StatementVisitor#visit(de.dhbwstuttgart.
* syntaxtree.statement.EmptyStmt)
*/
@Override
public void visit(EmptyStmt emptyStmt) {
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
*
* @see de.dhbwstuttgart.syntaxtree.StatementVisitor#visit(de.dhbwstuttgart.
* syntaxtree.statement.FieldVar)
*/
@Override
public void visit(FieldVar fieldVar) {
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
*
* @see de.dhbwstuttgart.syntaxtree.StatementVisitor#visit(de.dhbwstuttgart.
* syntaxtree.statement.ForStmt)
*/
@Override
public void visit(ForStmt forStmt) {
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
*
* @see de.dhbwstuttgart.syntaxtree.StatementVisitor#visit(de.dhbwstuttgart.
* syntaxtree.statement.IfStmt)
*/
@Override
public void visit(IfStmt ifStmt) {
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
*
* @see de.dhbwstuttgart.syntaxtree.StatementVisitor#visit(de.dhbwstuttgart.
* syntaxtree.statement.InstanceOf)
*/
@Override
public void visit(InstanceOf instanceOf) {
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
*
* @see de.dhbwstuttgart.syntaxtree.StatementVisitor#visit(de.dhbwstuttgart.
* syntaxtree.statement.LocalVar)
*/
@Override
public void visit(LocalVar localVar) {
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
*
* @see de.dhbwstuttgart.syntaxtree.StatementVisitor#visit(de.dhbwstuttgart.
* syntaxtree.statement.LocalVarDecl)
*/
@Override
public void visit(LocalVarDecl localVarDecl) {
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
*
* @see de.dhbwstuttgart.syntaxtree.StatementVisitor#visit(de.dhbwstuttgart.
* syntaxtree.statement.MethodCall)
*/
@Override
public void visit(MethodCall methodCall) {
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
*
* @see de.dhbwstuttgart.syntaxtree.StatementVisitor#visit(de.dhbwstuttgart.
* syntaxtree.statement.NewClass)
*/
@Override
public void visit(NewClass methodCall) {
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
*
* @see de.dhbwstuttgart.syntaxtree.StatementVisitor#visit(de.dhbwstuttgart.
* syntaxtree.statement.NewArray)
*/
@Override
public void visit(NewArray newArray) {
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
*
* @see de.dhbwstuttgart.syntaxtree.StatementVisitor#visit(de.dhbwstuttgart.
* syntaxtree.statement.Return)
*/
@Override
public void visit(Return aReturn) {
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
*
* @see de.dhbwstuttgart.syntaxtree.StatementVisitor#visit(de.dhbwstuttgart.
* syntaxtree.statement.ReturnVoid)
*/
@Override
public void visit(ReturnVoid aReturn) {
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
*
* @see de.dhbwstuttgart.syntaxtree.StatementVisitor#visit(de.dhbwstuttgart.
* syntaxtree.statement.StaticClassName)
*/
@Override
public void visit(StaticClassName staticClassName) {
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
*
* @see de.dhbwstuttgart.syntaxtree.StatementVisitor#visit(de.dhbwstuttgart.
* syntaxtree.statement.Super)
*/
@Override
public void visit(Super aSuper) {
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
*
* @see de.dhbwstuttgart.syntaxtree.StatementVisitor#visit(de.dhbwstuttgart.
* syntaxtree.statement.This)
*/
@Override
public void visit(This aThis) {
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
*
* @see de.dhbwstuttgart.syntaxtree.StatementVisitor#visit(de.dhbwstuttgart.
* syntaxtree.statement.WhileStmt)
*/
@Override
public void visit(WhileStmt whileStmt) {
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
*
* @see de.dhbwstuttgart.syntaxtree.StatementVisitor#visit(de.dhbwstuttgart.
* syntaxtree.statement.DoStmt)
*/
@Override
public void visit(DoStmt whileStmt) {
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
*
* @see de.dhbwstuttgart.syntaxtree.StatementVisitor#visit(de.dhbwstuttgart.
* syntaxtree.statement.AssignToField)
*/
@Override
public void visit(AssignToField assignLeftSide) {
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
*
* @see
* de.dhbwstuttgart.syntaxtree.StatementVisitor#visit(de.dhbwstuttgart.parser.
* SyntaxTreeGenerator.AssignToLocal)
*/
@Override
public void visit(AssignToLocal assignLeftSide) {
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
*
* @see de.dhbwstuttgart.syntaxtree.StatementVisitor#visit(de.dhbwstuttgart.
* syntaxtree.statement.SuperCall)
*/
@Override
public void visit(SuperCall superCall) {
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
*
* @see de.dhbwstuttgart.syntaxtree.StatementVisitor#visit(de.dhbwstuttgart.
* syntaxtree.statement.ExpressionReceiver)
*/
@Override
public void visit(ExpressionReceiver expressionReceiver) {
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
*
* @see de.dhbwstuttgart.syntaxtree.StatementVisitor#visit(de.dhbwstuttgart.
* syntaxtree.statement.UnaryExpr)
*/
@Override
public void visit(UnaryExpr unaryExpr) {
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
*
* @see de.dhbwstuttgart.syntaxtree.StatementVisitor#visit(de.dhbwstuttgart.
* syntaxtree.statement.Literal)
*/
@Override
public void visit(Literal literal) {
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
*
* @see
* de.dhbwstuttgart.syntaxtree.ASTVisitor#visit(de.dhbwstuttgart.syntaxtree.
* GenericTypeVar)
*/
@Override
public void visit(GenericTypeVar genericTypeVar) {
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
*
* @see
* de.dhbwstuttgart.syntaxtree.ASTVisitor#visit(de.dhbwstuttgart.syntaxtree.
* FormalParameter)
*/
@Override
public void visit(FormalParameter formalParameter) {
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
*
* @see
* de.dhbwstuttgart.syntaxtree.ASTVisitor#visit(de.dhbwstuttgart.syntaxtree.
* GenericDeclarationList)
*/
@Override
public void visit(GenericDeclarationList genericTypeVars) {
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
*
* @see
* de.dhbwstuttgart.syntaxtree.ASTVisitor#visit(de.dhbwstuttgart.syntaxtree.
* Field)
*/
@Override
public void visit(Field field) {
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
*
* @see
* de.dhbwstuttgart.syntaxtree.ASTVisitor#visit(de.dhbwstuttgart.syntaxtree.type
* .RefType)
*/
@Override
public void visit(RefType refType) {
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
*
* @see
* de.dhbwstuttgart.syntaxtree.ASTVisitor#visit(de.dhbwstuttgart.syntaxtree.type
* .SuperWildcardType)
*/
@Override
public void visit(SuperWildcardType superWildcardType) {
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
*
* @see
* de.dhbwstuttgart.syntaxtree.ASTVisitor#visit(de.dhbwstuttgart.syntaxtree.type
* .TypePlaceholder)
*/
@Override
public void visit(TypePlaceholder typePlaceholder) {
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
*
* @see
* de.dhbwstuttgart.syntaxtree.ASTVisitor#visit(de.dhbwstuttgart.syntaxtree.type
* .ExtendsWildcardType)
*/
@Override
public void visit(ExtendsWildcardType extendsWildcardType) {
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
*
* @see
* de.dhbwstuttgart.syntaxtree.ASTVisitor#visit(de.dhbwstuttgart.syntaxtree.type
* .GenericRefType)
*/
@Override
public void visit(GenericRefType genericRefType) {
// TODO Auto-generated method stub
}
}

View File

@@ -1,255 +0,0 @@
/**
*
*/
package de.dhbwstuttgart.bytecode.genericsGenerator;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.*;
import org.objectweb.asm.Type;
import de.dhbwstuttgart.bytecode.TPHExtractor;
import de.dhbwstuttgart.bytecode.constraint.ExtendsConstraint;
import de.dhbwstuttgart.bytecode.constraint.TPHConstraint;
import de.dhbwstuttgart.bytecode.utilities.MethodAndTPH;
/**
* @author fayez
*
*/
public class GenericsGenerator {
/*TODO: When generating generics for a class if we have the following:
tphClass < tphMeth1 < tphMeth2
then we have to convert tphMeth1, tphMeth2 to tph class and generate the following
class constraints: tphClass < tphMeth1, tphMeth1 < tphMeth2, tphMeth2 < Object
*/
public static GenericsGeneratorResultForClass generateConstraints(final String className, final TPHExtractor tphExtractor,
final List<String> tphsClass, final ConstraintsSimplierResult simplifiedConstraints) {
List<GenericsGeneratorResult> classConstraints = generateConstraintsForClass(tphExtractor,
simplifiedConstraints, tphsClass);
// GenericGeneratorResultsForAllMethods methodsAndConstraints = generateConstraintsForAllMethods(tphExtractor,
// simplifiedConstraints, tphsClass);
GenericGeneratorResultsForAllMethods methodsAndConstraints = new GenericGeneratorResultsForAllMethods(new ArrayList<>());
return new GenericsGeneratorResultForClass(className, classConstraints, methodsAndConstraints);
}
/**
* @param tphExtractor
* @param tphsClass
* @return
*/
public static ConstraintsSimplierResult simplifyConstraints(final TPHExtractor tphExtractor,
final List<String> tphsClass) {
final List<GenericsGeneratorResult> genericsGeneratorResults = new ArrayList<>();
ConstraintsSimplierResult simplifiedConstraints = ConstraintsSimplifier.simplifyConstraints(tphExtractor,
genericsGeneratorResults, tphsClass);
return simplifiedConstraints;
}
private static List<GenericsGeneratorResult> generateConstraintsForClass(final TPHExtractor tphExtractor,
final ConstraintsSimplierResult simplifiedConstraints, final List<String> tphsClass) {
final List<GenericsGeneratorResult> constraints = new ArrayList<>();
if (tphsClass.isEmpty())
return constraints;
final List<TPHConstraint> allCons = tphExtractor.allCons;
final Set<String> visitedTPHs = new HashSet<>();
final List<String> methodTPHs = tphExtractor.ListOfMethodsAndTph.stream().map(m -> m.getLocalTphs())
.flatMap(l -> l.stream()).collect(Collectors.toList());
createConstraintsForClassTphs(simplifiedConstraints, tphsClass, constraints, allCons, visitedTPHs, methodTPHs);
GenericsGeneratorUtility.addTPHsToClassTPHs(constraints, tphsClass);
GenericsGeneratorUtility.removeClassTPHsFromMethodTPHs(tphsClass, tphExtractor);
generateGGConstraintsForTPH(tphsClass, constraints, simplifiedConstraints);
return constraints;
}
private static void createConstraintsForClassTphs(ConstraintsSimplierResult simplifiedConstraints, List<String> tphsClass, List<GenericsGeneratorResult> constraints, List<TPHConstraint> allCons, Set<String> visitedTPHs, List<String> methodTPHs) {
List<String> classAndMethodTphs = new ArrayList<>(tphsClass);
classAndMethodTphs.addAll(methodTPHs);
for (String tph : tphsClass) {
if (visitedTPHs.contains(tph))
continue;
final LinkedList<String> tphsInRel = GenericsGeneratorUtility
.createLinkedListForTPHsInRelationClass(allCons, tphsClass, methodTPHs, visitedTPHs, tph);
generateConstraintsForClassFromList(tphsInRel,simplifiedConstraints,classAndMethodTphs,constraints);
}
}
private static void generateConstraintsForClassFromList(LinkedList<String> tphsInRel, ConstraintsSimplierResult simplifiedConstraints, List<String> classAndMethodTphs, List<GenericsGeneratorResult> constraints) {
if(tphsInRel.isEmpty())
return;
List<GenericsGeneratorResult> resultConstraints = new ArrayList<>();
String subType = tphsInRel.getFirst();
String superType = GenericsGeneratorUtility.getNextClassTph(classAndMethodTphs, tphsInRel);
int idxOfSuper = tphsInRel.indexOf(superType);
int size = tphsInRel.size();
while (size > 2 && idxOfSuper < size-1){
GenericsGeneratorResult genericsGeneratorResult = getGenericsGeneratorResultForClass(simplifiedConstraints, subType, superType);
constraints.add(genericsGeneratorResult);
tphsInRel = new LinkedList<>(tphsInRel.subList(idxOfSuper, size));
subType = tphsInRel.getFirst();
superType = GenericsGeneratorUtility.getNextClassTph(classAndMethodTphs, tphsInRel);
idxOfSuper = tphsInRel.indexOf(superType);
size = tphsInRel.size();
}
GenericsGeneratorResult genericsGeneratorResult = getGenericsGeneratorResultForClass(simplifiedConstraints, subType, superType);
constraints.add(genericsGeneratorResult);
}
private static GenericsGeneratorResult getGenericsGeneratorResultForClass(ConstraintsSimplierResult simplifiedConstraints, String subType, String superType) {
TPHConstraint constraint = new ExtendsConstraint(subType, superType);
Set<String> equalSet = GenericsGeneratorUtility
.createEqualSet(simplifiedConstraints.getNameReplacementResults(), subType);
return new GenericsGeneratorResult(constraint, equalSet);
}
/* TODO Remove this methoda*/
private static GenericsGeneratorResult generateGGResultForClass(LinkedList<String> tphsInRel,
ConstraintsSimplierResult simplifiedConstraints, List<String> tphsClass) {
String subType = tphsInRel.getFirst();
String superType = GenericsGeneratorUtility.getNextClassTph(tphsClass, tphsInRel);
TPHConstraint constraint = new ExtendsConstraint(subType, superType);
Set<String> equalSet = GenericsGeneratorUtility
.createEqualSet(simplifiedConstraints.getNameReplacementResults(), subType);
return new GenericsGeneratorResult(constraint, equalSet);
}
private static GenericGeneratorResultsForAllMethods generateConstraintsForAllMethods(
final TPHExtractor tphExtractor, ConstraintsSimplierResult simplifiedConstraints, List<String> tphsClass) {
final List<MethodAndConstraints> methodsAndConstraints = new ArrayList<>();
final GenericGeneratorResultsForAllMethods results = new GenericGeneratorResultsForAllMethods(
methodsAndConstraints);
tphExtractor.ListOfMethodsAndTph.forEach(m -> {
MethodAndConstraints methAndCons = generateConstraintsForMethod(tphExtractor.allCons, m,
simplifiedConstraints, tphsClass);
methodsAndConstraints.add(methAndCons);
});
return results;
}
public static MethodAndConstraints generateConstraintsForMethod(final List<TPHConstraint> allCons,
final MethodAndTPH m, final ConstraintsSimplierResult simplifiedConstraints, List<String> tphsClass) {
final List<String> localTphs = m.getLocalTphs();
List<GenericsGeneratorResult> constraints = new ArrayList<>();
MethodAndConstraints result = new MethodAndConstraints(m.getId(), constraints);
if (localTphs.isEmpty())
return result;
if (localTphs.size() == 1 && tphsClass.isEmpty()) {
generateGGConstraintsForTPH(localTphs, constraints, simplifiedConstraints);
return result;
}
final Set<String> visitedTPHs = new HashSet<>();
for (String tph : localTphs) {
if (visitedTPHs.contains(tph))
continue;
final LinkedList<String> tphsInRel = GenericsGeneratorUtility.createLinkedListForTPHsInRelation(allCons,
localTphs, tphsClass, visitedTPHs, tph);
if (!tphsInRel.isEmpty()) {
GenericsGeneratorUtility.removeNotLocalTphs(tphsInRel, localTphs, tphsClass);
if (!GenericsGeneratorUtility.isInResult(tphsInRel.getFirst(), constraints)) {
GenericsGeneratorResult constraint = generateGGResult(tphsInRel, simplifiedConstraints);
constraints.add(constraint);
}
}
}
generateGGConstraintsForTPH(localTphs, constraints, simplifiedConstraints);
return result;
}
private static void generateGGConstraintsForTPH(List<String> localTphs,
final List<GenericsGeneratorResult> constraints, final ConstraintsSimplierResult simplifiedConstraints) {
localTphs.forEach(tph -> {
boolean isInSimplifiedConstraints = GenericsGeneratorUtility.isTPHInGenericGeneratorResult(simplifiedConstraints.getGenericsGenResults(), tph);
if (isInSimplifiedConstraints) {
GenericsGeneratorResult ggResult = GenericsGeneratorUtility.getGenericGeneratorResult(simplifiedConstraints.getGenericsGenResults(), tph).get();
// GenericsGeneratorUtility.removeGenericGeneratorResult(simplifiedConstraints.getGenericsGenResults(),ggResult);
constraints.add(ggResult);
} else {
boolean isInConstraints = GenericsGeneratorUtility.isTPHInGenericGeneratorResult(constraints, tph);
if (!isInConstraints) {
GenericsGeneratorResult ggResult = generateGGResult(tph, simplifiedConstraints.getNameReplacementResults());
constraints.add(ggResult);
}
}
});
}
private static GenericsGeneratorResult generateGGResult(String tph,
List<NameReplacementResult> nameReplacementResults) {
String superType = Type.getInternalName(Object.class);
TPHConstraint constraint = new ExtendsConstraint(tph, superType);
Set<String> equalSet = GenericsGeneratorUtility.createEqualSet(nameReplacementResults, tph);
return new GenericsGeneratorResult(constraint, equalSet);
}
private static GenericsGeneratorResult generateGGResult(final LinkedList<String> tphsInRel,
final ConstraintsSimplierResult simplifiedConstraints) {
String subType = tphsInRel.getFirst();
if (tphsInRel.size() == 1) {
Optional<GenericsGeneratorResult> constraintFromSimplifiedCon = simplifiedConstraints
.getGenericsGenResults().stream().filter(g -> g.getConstraint().getLeft().equals(subType))
.findFirst();
if (constraintFromSimplifiedCon.isPresent())
return constraintFromSimplifiedCon.get();
}
String superType = tphsInRel.size() > 1 ? tphsInRel.getLast() : Type.getInternalName(Object.class);
TPHConstraint constraint = new ExtendsConstraint(subType, superType);
Set<String> equalSet = GenericsGeneratorUtility
.createEqualSet(simplifiedConstraints.getNameReplacementResults(), subType);
return new GenericsGeneratorResult(constraint, equalSet);
}
}

View File

@@ -1,571 +0,0 @@
/**
*
*/
package de.dhbwstuttgart.bytecode.genericsGenerator;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.*;
import org.objectweb.asm.Type;
import de.dhbwstuttgart.bytecode.TPHExtractor;
import de.dhbwstuttgart.bytecode.constraint.EqualConstraint;
import de.dhbwstuttgart.bytecode.constraint.ExtendsConstraint;
import de.dhbwstuttgart.bytecode.constraint.TPHConstraint;
import de.dhbwstuttgart.bytecode.constraint.TPHConstraint.Relation;
import de.dhbwstuttgart.bytecode.utilities.ConstraintsFinder;
import de.dhbwstuttgart.bytecode.utilities.MethodAndTPH;
import de.dhbwstuttgart.bytecode.utilities.NameReplacer;
/**
* @author fayez
*
*/
public class GenericsGeneratorUtility {
/**
* Returns a list of type placeholders names of a specified method
*
* @param methodID The id of the method ReturnTypeMethodName(ParameterTypes)
* @param listOfMethodsAndTph List of all methods
* @return a list of type placehoders names
*/
public static List<String> getMethodTPHS(String methodID, ArrayList<MethodAndTPH> listOfMethodsAndTph) {
return listOfMethodsAndTph.stream().filter(mt->mt.getId().equals(methodID)).findAny().get().getTphs();
}
/**
* Returns a reverse constraint of a specified constraint which is given by its left and right
* side
*
* @param allCons List of all constraints
* @param left The left side of the given constraint
* @param right The right side of the given constraint
* @return An Optional object which contains the reverse constraint if it is exist
*/
public static Optional<TPHConstraint> getReverseConstraint(List<TPHConstraint> allCons, String left, String right) {
return allCons.stream().filter(c->{
return c.getRight().equals(left) && c.getLeft().equals(right);
}).findAny();
}
/**
* Substitutes the old name by the new name in all constraints
*
* @param allCons List of all constraints
* @param oldName The name to be replaced
* @param newName The new name
*/
public static void substituteTPH(List<TPHConstraint> allCons, String oldName, String newName) {
allCons.stream()
.filter(c->c.getRel()==Relation.EXTENDS)
.forEach(c->{
if(c.getLeft().equals(oldName))
c.setLeft(newName);
if(c.getRight().equals(oldName))
c.setRight(newName);
});
}
public static List<ConstraintsWithSameLeftSide> findConstraintsWithLeftSameLeftSide(List<TPHConstraint> allCons) {
// finder looks for constraints that have the same left hand side
// and put them in a list
ConstraintsFinder finder = new ConstraintsFinder(allCons);
List<ConstraintsWithSameLeftSide> foundCons = finder.findConstraints();
return foundCons;
}
public static void simplifyConstraintsWithSameLeftSide(List<ConstraintsWithSameLeftSide> consWithSameLeftSide,
List<TPHConstraint> allCons, List<String> methodTPHS) {
List<TPHConstraint> eqCons = new ArrayList<>();
for (ConstraintsWithSameLeftSide list : consWithSameLeftSide) {
NameReplacementResult replRes = modifyNames(allCons, methodTPHS, list);
createEqualConstraintsForNames(replRes.getName(), replRes.getOldNames(),eqCons);
for (TPHConstraint c : allCons) {
if (c.getRel() == Relation.EQUAL && replRes.getName().equals(c.getRight())) {
eqCons.add(c);
}
}
updateEqualCons(replRes, eqCons);
TPHConstraint c = list.getConstraints().get(0);
allCons.removeAll(list.getConstraints());
allCons.add(c);
}
}
public static void simplifyConstraintsWithSameLeftSide(List<ConstraintsWithSameLeftSide> consWithSameLeftSide,
TPHExtractor tphExtractor, List<String> tphsClass, List<TPHConstraint> equalCons) {
List<TPHConstraint> allCons = tphExtractor.allCons;
for (ConstraintsWithSameLeftSide list : consWithSameLeftSide) {
if(!stillWithSameLeftSide(list))
continue;
NameReplacementResult replRes = modifyNames(allCons, list, tphExtractor.ListOfMethodsAndTph,tphsClass);
createEqualConstraintsForNames(replRes.getName(), replRes.getOldNames(),equalCons);
for (TPHConstraint c : allCons) {
if (c.getRel() == Relation.EQUAL && replRes.getName().equals(c.getRight())) {
equalCons.add(c);
}
}
updateEqualCons(replRes, equalCons);
TPHConstraint c = list.getConstraints().get(0);
allCons.removeAll(list.getConstraints());
removeConstraintsWithSameLeftAndRightSide(allCons);
allCons.add(c);
removeDuplicate(allCons);
}
consWithSameLeftSide.clear();
consWithSameLeftSide = findConstraintsWithLeftSameLeftSide(allCons);
if(!consWithSameLeftSide.isEmpty())
simplifyConstraintsWithSameLeftSide(consWithSameLeftSide,tphExtractor,tphsClass,equalCons);
}
private static void removeDuplicate(List<TPHConstraint> allCons) {
List<TPHConstraint> visited = new ArrayList<>();
List<Integer> toRemove = new ArrayList<>();
checkForDuplicate(allCons, visited, toRemove);
removeConstraintsByIndex(allCons, toRemove);
}
private static void removeConstraintsByIndex(List<TPHConstraint> allCons, List<Integer> toRemove) {
for(int index : toRemove)
allCons.remove(index);
}
private static void checkForDuplicate(List<TPHConstraint> allCons, List<TPHConstraint> visited, List<Integer> toRemove) {
for(int i = 0;i<allCons.size();++i){
markConstraintIfDuplicate(allCons, visited, toRemove, i);
}
}
private static void markConstraintIfDuplicate(List<TPHConstraint> allCons, List<TPHConstraint> visited, List<Integer> toRemove, int i) {
TPHConstraint constraint = allCons.get(i);
if(containsInList(visited,constraint.getLeft(),constraint.getRight())){
toRemove.add(i);
} else {
visited.add(constraint);
}
}
private static boolean containsInList(List<TPHConstraint> allConstraints, String left, String right) {
for(TPHConstraint constraint : allConstraints)
if(constraint.getLeft().equals(left) && constraint.getRight().equals(right))
return true;
return false;
}
private static void addNewConstraintsWithSameLeftSide(ConstraintsWithSameLeftSide constraintsWithSameLeftSide, List<TPHConstraint> allCons) {
allCons.forEach(c->{
if (constraintsWithSameLeftSide.getConstraints().get(0).getLeft().equals(c.getLeft())){
if(!constraintsWithSameLeftSide.getConstraints().contains(c))
constraintsWithSameLeftSide.getConstraints().add(c);
}
});
}
private static void checkForNewConstraintsWithSameLeftSide(List<ConstraintsWithSameLeftSide> consWithSameLeftSide, List<TPHConstraint> allCons) {
allCons.forEach(c->{
Optional<ConstraintsWithSameLeftSide> constraintsWithSameLeftSide = getConstraintsWithSameLeftSide(consWithSameLeftSide, c.getLeft());
constraintsWithSameLeftSide.ifPresent(cls->{
if(!cls.getConstraints().contains(c))
cls.getConstraints().add(c);
});
});
}
private static Optional<ConstraintsWithSameLeftSide> getConstraintsWithSameLeftSide(List<ConstraintsWithSameLeftSide> consWithSameLeftSide, String left) {
return consWithSameLeftSide.stream().filter(csl->isContainedInConsWithLeftSide(csl,left)).findAny();
}
private static boolean isContainedInConsWithLeftSide(ConstraintsWithSameLeftSide csl, String left) {
return csl.getConstraints().get(0).getLeft().equals(left);
}
private static boolean stillWithSameLeftSide(ConstraintsWithSameLeftSide constraints) {
removeUnvalidConstraints(constraints);
return constraints.getConstraints().size()>1;
}
private static void removeUnvalidConstraints(ConstraintsWithSameLeftSide constraints) {
List<TPHConstraint> toRemove = new ArrayList<>();
constraints.getConstraints().forEach(c->{
if(c.getLeft().equals(c.getRight()))
toRemove.add(c);
});
if(!toRemove.isEmpty())
constraints.getConstraints().removeAll(toRemove);
}
private static void removeConstraintsWithSameLeftAndRightSide(List<TPHConstraint> allCons) {
List<TPHConstraint> toRemove = new ArrayList<>();
allCons.forEach(c->{
if(c.getLeft().equals(c.getRight()))
toRemove.add(c);
});
allCons.removeAll(toRemove);
}
private static void createEqualConstraintsForNames(String name, List<String> equalNames, List<TPHConstraint> eqCons) {
// create an equal constraint for each value in repres
for (String eName : equalNames) {
EqualConstraint ec = new EqualConstraint(eName, name);
eqCons.add(ec);
}
}
/**
* @param allCons
* @param methodTPHS
* @param list
* @return
*/
public static NameReplacementResult modifyNames(List<TPHConstraint> allCons, List<String> methodTPHS,
ConstraintsWithSameLeftSide list) {
// generate a new name and replace the right hand side for each constraint
// in list with the new name
NameReplacer replacer = new NameReplacer(list.getConstraints(), allCons, methodTPHS);
// new name -> [all old names]
NameReplacementResult replRes = replacer.replaceNames();
return replRes;
}
public static NameReplacementResult modifyNames(List<TPHConstraint> allCons, ConstraintsWithSameLeftSide list, List<MethodAndTPH> methodAndTPHs, List<String> tphsClass) {
// generate a new name and replace the right hand side for each constraint
// in list with the new name
NameReplacer replacer = new NameReplacer(list.getConstraints(), allCons, methodAndTPHs, tphsClass);
// new name -> [all old names]
NameReplacementResult replRes = replacer.replaceNames();
return replRes;
}
public static void updateEqualCons(NameReplacementResult nameReplacementResult, List<TPHConstraint> eqCons) {
List<String> oldNames = nameReplacementResult.getOldNames();
String newName = nameReplacementResult.getName();
for (TPHConstraint c : eqCons) {
// if(oldNames.contains(c.getLeft()))
// c.setLeft(newName);
if (oldNames.contains(c.getRight()))
c.setRight(newName);
}
}
public static void modifyRelationForConstraintsInCycle(List<Cycle> cycles) {
cycles.stream().map(lc->lc.getConstraints()).flatMap(e->e.stream()).forEach(c->c.setRel(Relation.EQUAL));
}
public static List<NameReplacementResult> substituteTPHSFormCycle(List<TPHConstraint> allCons, List<Cycle> cycles, TPHExtractor tphExtractor) {
List<NameReplacementResult> results = new ArrayList<>();
cycles.forEach(lc->{
Set<String> names = getNamesFromCycle(lc);
String newName = names.stream().findFirst().get();
List<String> equalNames = new ArrayList<>(names);
Stream<ArrayList<String>> tphsOfMethods = tphExtractor.ListOfMethodsAndTph.stream().map(m->m.getTphs());
Stream<ArrayList<String>> localTphsOfMethods = tphExtractor.ListOfMethodsAndTph.stream().map(m->m.getLocalTphs());
replaceOldNames(newName, equalNames, tphsOfMethods);
replaceOldNames(newName, equalNames, localTphsOfMethods);
NameReplacementResult res = new NameReplacementResult(newName, equalNames);
results.add(res);
substituteAll(allCons,names,newName);
});
return results;
}
/**
* @param newName
* @param names
* @param tphsOfMethods
*/
public static void replaceOldNames(final String newName, final List<String> names, Stream<ArrayList<String>> tphsOfMethods) {
tphsOfMethods.forEach(tphsMethod->{
if(tphsMethod.removeAll(names))
tphsMethod.add(newName);
});
}
public static void substituteAll(List<TPHConstraint> allCons, Set<String> names, String newName) {
allCons.stream()
.filter(c-> c.getRel()==Relation.EXTENDS)
.forEach(c->{
if(names.contains(c.getLeft())) {
c.setLeft(newName);
} else if(names.contains(c.getRight())) {
c.setRight(newName);
}
});
}
public static Set<String> getNamesFromCycle(Cycle lc) {
Set<String> names = new HashSet<>();
lc.getConstraints().forEach(c->names.add(c.getLeft()));
return names;
}
public static void createResults(List<GenericsGeneratorResult> genericsGeneratorResults,
List<NameReplacementResult> nameReplacementResults) {
nameReplacementResults.forEach(n->{
Set<String> equals = new HashSet<>(n.getOldNames());
TPHConstraint cons = new ExtendsConstraint(n.getName(), Type.getInternalName(Object.class));
GenericsGeneratorResult ggRes = new GenericsGeneratorResult(cons, equals);
genericsGeneratorResults.add(ggRes);
});
}
public static void removeEqualConstraints(List<TPHConstraint> allCons) {
List<TPHConstraint> equalConstraints = getEqualConstraints(allCons);
allCons.removeAll(equalConstraints);
}
public static List<TPHConstraint> getEqualConstraints(List<TPHConstraint> allCons) {
return allCons.stream().filter(c->c.getRel()==Relation.EQUAL).collect(Collectors.toList());
}
public static List<NameReplacementResult> createNameReplacementResultsFromEqualConstraints(
List<TPHConstraint> equalCons) {
List<NameReplacementResult> nameReplacementResults = new ArrayList<>();
equalCons.forEach(c->{
if(isInNameReplacementResults(nameReplacementResults,c.getRight())) {
getNameReplacementByName(nameReplacementResults,c.getRight()).getOldNames().add(c.getLeft());
} else {
List<String> oldNames = new ArrayList<>();
oldNames.add(c.getLeft());
NameReplacementResult nrRes = new NameReplacementResult(c.getRight(), oldNames);
nameReplacementResults.add(nrRes);
}
});
return nameReplacementResults;
}
private static NameReplacementResult getNameReplacementByName(List<NameReplacementResult> nameReplacementResults,
String name) {
return nameReplacementResults.stream().filter(n->n.getName().equals(name)).findFirst().get();
}
public static boolean isInNameReplacementResults(List<NameReplacementResult> nameReplacementResults,String name){
if(nameReplacementResults.isEmpty())
return false;
return nameReplacementResults.stream().map(r->r.getName()).filter(n->name.equals(n)).findFirst().isPresent();
}
public static Optional<TPHConstraint> getConstraintByLeftSide(List<TPHConstraint> allCons, String tph) {
return allCons.stream().filter(c->c.getLeft().equals(tph)).findFirst();
}
public static Optional<TPHConstraint> getConstraintByRightSide(List<TPHConstraint> allCons, String tph) {
return allCons.stream().filter(c->c.getRight().equals(tph)).findFirst();
}
public static boolean isTPHInGenericGeneratorResult(final List<GenericsGeneratorResult> constraints, final String tph) {
return constraints.stream().filter(g->g.getConstraint().getLeft().equals(tph)).findFirst().isPresent();
}
/**
* @param allCons
* @param tphsMethod
* @param tphsClass
* @param visitedTPHs
* @param tph
* @return
*/
public static LinkedList<String> createLinkedListForTPHsInRelation(final List<TPHConstraint> allCons,
List<String> tphsMethod, List<String> tphsClass, final Set<String> visitedTPHs, String tph) {
final LinkedList<String> tphsInRel = new LinkedList<>();
List<String> tphsList = new ArrayList<>(tphsMethod);
tphsList.addAll(tphsClass);
boolean isNextSuperTypeFound = findNextSuperTyp(allCons,tphsList ,visitedTPHs, tph, tphsInRel);
if(!isNextSuperTypeFound)
findNextSubType(allCons, tphsList,visitedTPHs, tph, tphsInRel);
return tphsInRel;
}
public static boolean findNextSubType(List<TPHConstraint> allCons, List<String> tphsList, Set<String> visitedTPHs, String tph,
LinkedList<String> tphsInRel) {
Optional<TPHConstraint> con = getConstraintByRightSide(allCons, tph);
while (con.isPresent()) {
String left = con.get().getLeft();
String right = con.get().getRight();
addTPHsToListFromLeft(tphsInRel, left, right);
markAsVisited(visitedTPHs, left);
if(tphsList.contains(left))
return true;
con = getConstraintByRightSide(allCons, left);
}
return false;
}
public static void addTPHsToListFromLeft(LinkedList<String> tphsInRel, String left, String right) {
if (tphsInRel.isEmpty())
tphsInRel.add(right);
tphsInRel.addFirst(left);
}
/**
* @param allCons
* @param tphsList
* @param visitedTPHs
* @param tph
* @param tphsInRel
* @return
*/
public static boolean findNextSuperTyp(final List<TPHConstraint> allCons, List<String> tphsList, final Set<String> visitedTPHs, String tph,
final LinkedList<String> tphsInRel) {
Optional<TPHConstraint> con = getConstraintByLeftSide(allCons, tph);
markAsVisited(visitedTPHs, tph);
while (con.isPresent()) {
String left = con.get().getLeft();
String right = con.get().getRight();
addTPHsToList(tphsInRel, left, right);
if(tphsList.contains(right))
return true;
markAsVisited(visitedTPHs, right);
con = getConstraintByLeftSide(allCons, right);
}
return false;
}
public static void markAsVisited(Set<String> visitedTPHs, String left) {
visitedTPHs.add(left);
}
/**
* @param visitedTPHs
* @param right
* @param left
*/
public static void markAsVisited(final Set<String> visitedTPHs, String left, String right) {
visitedTPHs.add(left);
visitedTPHs.add(right);
}
/**
* @param tphsInRel
* @param right
* @param left
*/
public static void addTPHsToList(final LinkedList<String> tphsInRel, String left, String right) {
if (tphsInRel.isEmpty())
tphsInRel.add(left);
tphsInRel.add(right);
}
public static void removeNotLocalTphs(final LinkedList<String> tphsInRel, final List<String> localTphs,
List<String> tphsClass) {
while (!localTphs.contains(tphsInRel.peek())) {
tphsInRel.removeFirst();
}
String last = tphsInRel.peekLast();
while (!localTphs.contains(last) && !tphsClass.contains(last)) {
tphsInRel.removeLast();
last = tphsInRel.peekLast();
}
}
/**
* @param nameReplacementResults
* @param subType
* @return
*/
public static Set<String> createEqualSet(final List<NameReplacementResult> nameReplacementResults, String subType) {
Optional<NameReplacementResult> equals = nameReplacementResults.stream()
.filter(n -> n.getName().equals(subType)).findFirst();
Set<String> equalSet = equals.isPresent() ? new HashSet<>(equals.get().getOldNames()) : new HashSet<>();
return equalSet;
}
public static String getNextClassTph(List<String> tphsClass, LinkedList<String> tphsInRel) {
for(int i = 1;i<tphsInRel.size();++i) {
String next = tphsInRel.get(i);
if(tphsClass.contains(next))
return next;
}
return tphsInRel.getLast();
}
public static void addTPHsToClassTPHs(final List<GenericsGeneratorResult> constraints, final List<String> tphsClass) {
List<String> lefts = constraints.stream().map(r->r.getConstraint()).map(c->c.getLeft()).collect(Collectors.toList());
List<String> rights = constraints.stream().map(r->r.getConstraint()).map(c->c.getRight()).collect(Collectors.toList());
List<String> leftsAndRights = new ArrayList<>(lefts);
leftsAndRights.addAll(rights);
List<String> shouldBeClassTphs = leftsAndRights.stream().distinct().collect(Collectors.toList());
for(String tph : shouldBeClassTphs) {
if(!tphsClass.contains(tph))
tphsClass.add(tph);
}
}
public static void removeClassTPHsFromMethodTPHs(List<String> tphsClass, TPHExtractor tphExtractor) {
tphExtractor.ListOfMethodsAndTph.stream().map(m->m.getTphs()).forEach(tphs->{
tphs.removeAll(tphsClass);
});
tphExtractor.ListOfMethodsAndTph.stream().map(m->m.getLocalTphs()).forEach(tphs->{
tphs.removeAll(tphsClass);
});
}
public static LinkedList<String> createLinkedListForTPHsInRelationClass(List<TPHConstraint> allCons,
List<String> tphsClass, List<String> methodTPHs, Set<String> visitedTPHs, String tph) {
final LinkedList<String> tphsInRel = new LinkedList<>();
boolean isNextSuperTypeFound = findNextSuperTyp(allCons,tphsClass ,visitedTPHs, tph, tphsInRel);
if(!tphsInRel.isEmpty() && !isNextSuperTypeFound && !methodTPHs.contains(tphsInRel.getLast()))
findNextSubType(allCons, tphsClass,visitedTPHs, tph, tphsInRel);
return tphsInRel;
}
public static boolean isInResult(String first, List<GenericsGeneratorResult> constraints) {
return constraints.stream().map(r->r.getConstraint()).filter(c->c.getLeft().equals(first)).findFirst().isPresent();
}
public static Optional<GenericsGeneratorResult> getGenericGeneratorResult(List<GenericsGeneratorResult> list,
String tph) {
return list.stream().filter(g->g.getConstraint().getLeft().equals(tph)).findFirst();
}
public static void removeGenericGeneratorResult(List<GenericsGeneratorResult> genericsGenResults,
GenericsGeneratorResult ggResult) {
genericsGenResults.remove(ggResult);
}
public static Optional<MethodAndTPH> getMethodAndTphs(ArrayList<MethodAndTPH> listOfMethodsAndTph, String id) {
return listOfMethodsAndTph.stream().filter(m->m.getId().equals(id)).findFirst();
}
}

View File

@@ -1,35 +0,0 @@
package de.dhbwstuttgart.bytecode.genericsGeneratorTypes;
import java.util.List;
import de.dhbwstuttgart.bytecode.constraint.TPHConstraint;
public class ConstraintsWithSameLeftSide {
private List<TPHConstraint> constraints;
/**
* @param constraints
*/
public ConstraintsWithSameLeftSide(List<TPHConstraint> constraints) {
this.constraints = constraints;
}
/**
* @return the constraints
*/
public List<TPHConstraint> getConstraints() {
return constraints;
}
/**
* @param constraints the constraints to set
*/
public void setConstraints(List<TPHConstraint> constraints) {
this.constraints = constraints;
}
@Override
public String toString() {
return "[" + constraints.toString() + "]";
}
}

View File

@@ -1,46 +0,0 @@
/**
*
*/
package de.dhbwstuttgart.bytecode.genericsGeneratorTypes;
import java.util.List;
import de.dhbwstuttgart.bytecode.constraint.TPHConstraint;
/**
* @author fayez
*
*/
public class Cycle {
private final List<TPHConstraint> constraints;
/**
* @param constraints
*/
public Cycle(List<TPHConstraint> constraints) {
this.constraints = constraints;
}
/**
* @return the constraints
*/
public List<TPHConstraint> getConstraints() {
return constraints;
}
public boolean containConstraint(TPHConstraint constraint) {
for(TPHConstraint c : constraints) {
if(c.equalConstraint(constraint))
return true;
}
return false;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
constraints.forEach(c->sb.append(c.getLeft()+" -> "));
sb.append(constraints.get(constraints.size()-1).getRight());
return sb.toString();
}
}

View File

@@ -1,33 +0,0 @@
/**
*
*/
package de.dhbwstuttgart.bytecode.genericsGeneratorTypes;
import java.util.Collections;
import java.util.List;
/**
* @author fayez
*
*/
public class GenericGeneratorResultsForAllMethods {
private final List<MethodAndConstraints> methodsAndConstraints;
public GenericGeneratorResultsForAllMethods() {
this(Collections.emptyList());
}
/**
* @param methodsAndConstraints
*/
public GenericGeneratorResultsForAllMethods(List<MethodAndConstraints> methodsAndConstraints) {
this.methodsAndConstraints = methodsAndConstraints;
}
/**
* @return the methodsAndConstraints
*/
public List<MethodAndConstraints> getMethodsAndConstraints() {
return methodsAndConstraints;
}
}

View File

@@ -1,50 +0,0 @@
/**
*
*/
package de.dhbwstuttgart.bytecode.genericsGeneratorTypes;
import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;
/**
* The simplify results of a source file (package)
*
* @author fayez
*
*/
public class GenericGenratorResultForSourceFile {
private String pkgName;
private final List<GenericsGeneratorResultForClass> genericGeneratorResultForAllClasses = new ArrayList<>();
/**
* @param pkgName
*/
public GenericGenratorResultForSourceFile(String pkgName) {
this.pkgName = pkgName;
}
public List<GenericsGeneratorResultForClass> getGenericGeneratorResultForAllClasses() {
return genericGeneratorResultForAllClasses;
}
/**
* Appends the simplify results of a class to simplifyResForSF
*
* @param sResClass simplify results of a class to added
*/
public void addGenericGeneratorResultClass(GenericsGeneratorResultForClass sResClass) {
genericGeneratorResultForAllClasses.add(sResClass);
}
public GenericsGeneratorResultForClass getSimplifyResultsByName(String pkgName, String name) {
if (this.pkgName.equals(pkgName)) {
return genericGeneratorResultForAllClasses.stream()
.filter(sr -> sr.getClassName().equals(name))
.findAny()
.orElse(new GenericsGeneratorResultForClass(name));
}
return new GenericsGeneratorResultForClass(name);
}
}

View File

@@ -1,55 +0,0 @@
/**
*
*/
package de.dhbwstuttgart.bytecode.genericsGeneratorTypes;
import java.util.Set;
import de.dhbwstuttgart.bytecode.constraint.TPHConstraint;
/**
* @author fayez
*
*/
public class GenericsGeneratorResult {
private TPHConstraint constraint;
/**
* contains the names of all type placeholders which are equals to the left side of
* the constraint {@link #constraint}.
*/
private Set<String> equalsTPHs;
/**
* @param constraint
* @param equalsTPHs
*/
public GenericsGeneratorResult(TPHConstraint constraint, Set<String> equalsTPHs) {
this.constraint = constraint;
this.equalsTPHs = equalsTPHs;
}
/**
* @return the constraint
*/
public TPHConstraint getConstraint() {
return constraint;
}
/**
* @param constraint the constraint to set
*/
public void setConstraint(TPHConstraint constraint) {
this.constraint = constraint;
}
/**
* @return the equalsTPHs
*/
public Set<String> getEqualsTPHs() {
return equalsTPHs;
}
/**
* @param equalsTPHs the equalsTPHs to set
*/
public void setEqualsTPHs(Set<String> equalsTPHs) {
this.equalsTPHs = equalsTPHs;
}
}

View File

@@ -1,74 +0,0 @@
/**
*
*/
package de.dhbwstuttgart.bytecode.genericsGeneratorTypes;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import com.google.common.collect.Lists;
/**
* @author fayez
*
*/
public class GenericsGeneratorResultForClass {
private final String className;
private final List<GenericsGeneratorResult> classConstraints;
private final GenericGeneratorResultsForAllMethods methodsAndTheirConstraints;
public GenericsGeneratorResultForClass(String className) {
this(className, Collections.emptyList(), new GenericGeneratorResultsForAllMethods());
}
/**
* @param className
* @param classConstraints
* @param methodsAndTheirConstraints
*/
public GenericsGeneratorResultForClass(String className, List<GenericsGeneratorResult> classConstraints,
GenericGeneratorResultsForAllMethods methodsAndTheirConstraints) {
this.className = className;
this.classConstraints = classConstraints;
this.methodsAndTheirConstraints = methodsAndTheirConstraints;
}
/**
* @return the className
*/
public String getClassName() {
return className;
}
/**
* @return the classConstraints
*/
public List<GenericsGeneratorResult> getClassConstraints() {
return classConstraints;
}
/**
* @return the methodsAndTheirConstraints
*/
public GenericGeneratorResultsForAllMethods getMethodsAndTheirConstraints() {
return methodsAndTheirConstraints;
}
public boolean contains(String id) {
return methodsAndTheirConstraints.getMethodsAndConstraints().stream().map(mc -> mc.getMethodID())
.anyMatch(i -> i.equals(id));
}
public List<GenericsGeneratorResult> getMethodConstraintsByID(String id) {
Optional<MethodAndConstraints> methodConstraints = methodsAndTheirConstraints.getMethodsAndConstraints()
.stream()
.filter(mc -> mc.getMethodID().equals(id))
.findFirst();
if (methodConstraints.isPresent()) {
return methodConstraints.get().getConstraints();
} else {
return Collections.emptyList();
}
}
}

View File

@@ -1,36 +0,0 @@
/**
*
*/
package de.dhbwstuttgart.bytecode.genericsGeneratorTypes;
import java.util.List;
/**
* @author fayez
*
*/
public class MethodAndConstraints {
private final String methodID;
private final List<GenericsGeneratorResult> constraints;
/**
* @param methodID
* @param constraints
*/
public MethodAndConstraints(String methodID, List<GenericsGeneratorResult> constraints) {
this.methodID = methodID;
this.constraints = constraints;
}
/**
* @return the methodID
*/
public String getMethodID() {
return methodID;
}
/**
* @return the constraints
*/
public List<GenericsGeneratorResult> getConstraints() {
return constraints;
}
}

View File

@@ -1,49 +0,0 @@
/**
*
*/
package de.dhbwstuttgart.bytecode.genericsGeneratorTypes;
import java.util.List;
/**
* @author fayez
*
*/
public class NameReplacementResult {
private String name;
private List<String> oldNames;
/**
* @param name
* @param oldNames
*/
public NameReplacementResult(String name, List<String> oldNames) {
this.name = name;
this.oldNames = oldNames;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the oldNames
*/
public List<String> getOldNames() {
return oldNames;
}
/**
* @param oldNames the oldNames to set
*/
public void setOldNames(List<String> oldNames) {
this.oldNames = oldNames;
};
}

View File

@@ -1,166 +1,93 @@
package de.dhbwstuttgart.bytecode.signature; package de.dhbwstuttgart.bytecode.signature;
import java.util.*; import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import org.objectweb.asm.Type; import org.objectweb.asm.Type;
import org.objectweb.asm.signature.SignatureVisitor; import org.objectweb.asm.signature.SignatureVisitor;
import org.objectweb.asm.signature.SignatureWriter; import org.objectweb.asm.signature.SignatureWriter;
import de.dhbwstuttgart.bytecode.constraint.ExtendsConstraint;
import de.dhbwstuttgart.bytecode.constraint.TPHConstraint; import de.dhbwstuttgart.bytecode.constraint.TPHConstraint;
import de.dhbwstuttgart.bytecode.constraint.TPHConstraint.Relation;
import de.dhbwstuttgart.bytecode.descriptor.TypeToDescriptor; import de.dhbwstuttgart.bytecode.descriptor.TypeToDescriptor;
import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.GenericsGeneratorResult; import de.dhbwstuttgart.bytecode.utilities.Simplify;
import de.dhbwstuttgart.syntaxtree.ClassOrInterface; import de.dhbwstuttgart.syntaxtree.ClassOrInterface;
import de.dhbwstuttgart.syntaxtree.Constructor; import de.dhbwstuttgart.syntaxtree.Constructor;
import de.dhbwstuttgart.syntaxtree.GenericTypeVar; import de.dhbwstuttgart.syntaxtree.GenericTypeVar;
import de.dhbwstuttgart.syntaxtree.Method; import de.dhbwstuttgart.syntaxtree.Method;
import de.dhbwstuttgart.syntaxtree.statement.LambdaExpression;
import de.dhbwstuttgart.syntaxtree.type.ExtendsWildcardType; import de.dhbwstuttgart.syntaxtree.type.ExtendsWildcardType;
import de.dhbwstuttgart.syntaxtree.type.GenericRefType; import de.dhbwstuttgart.syntaxtree.type.GenericRefType;
import de.dhbwstuttgart.syntaxtree.type.RefType; import de.dhbwstuttgart.syntaxtree.type.RefType;
import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric; import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric;
import de.dhbwstuttgart.syntaxtree.type.SuperWildcardType; import de.dhbwstuttgart.syntaxtree.type.SuperWildcardType;
import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder; import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder;
import de.dhbwstuttgart.syntaxtree.type.WildcardType;
import de.dhbwstuttgart.typeinference.result.GenericInsertPair;
import de.dhbwstuttgart.typeinference.result.ResolvedType;
import de.dhbwstuttgart.typeinference.result.ResultSet; import de.dhbwstuttgart.typeinference.result.ResultSet;
public class Signature { public class Signature {
private static final char SUPER_CHAR = '-';
private static final char EXTENDS_CHAR = '+';
private static final String SPECIAL_CHAR_FOR_FUN = "$$";
private static final String SPECIAL_CHAR = "$";
private ClassOrInterface classOrInterface; private ClassOrInterface classOrInterface;
private HashMap<String, String> genericsAndBounds; private HashMap<String, String> genericsAndBounds;
private HashMap<String, String> genericsAndBoundsMethod; private HashMap<String, String> genericsAndBoundsMethod;
private final SignatureWriter sw = new SignatureWriter();; private SignatureWriter sw;
private Constructor constructor; private Constructor constructor;
private Method method; private Method method;
private HashMap<String,RefTypeOrTPHOrWildcardOrGeneric> methodParamsAndTypes; private HashMap<String,RefTypeOrTPHOrWildcardOrGeneric> methodParamsAndTypes;
private ResultSet resultSet; private ResultSet resultSet;
private Map<TPHConstraint, Set<String>> methodConstraints; private ArrayList<GenericInsertPair> commonPairs;
private List<GenericsGeneratorResult> consClass; private HashMap<TPHConstraint,HashSet<String>> methodConstraints;
private List<GenericsGeneratorResult> constraints; private ArrayList<TypePlaceholder> tphsClass;
private ArrayList<TPHConstraint> consClass;
// public Signature(ClassOrInterface classOrInterface, HashMap<String, String> genericsAndBounds, public Signature(ClassOrInterface classOrInterface, HashMap<String, String> genericsAndBounds,
// List<TPHConstraint> consClass) { ArrayList<GenericInsertPair> commonPairs, ArrayList<TypePlaceholder> tphsClass, ArrayList<TPHConstraint> consClass) {
// this.classOrInterface = classOrInterface; this.classOrInterface = classOrInterface;
// this.genericsAndBounds = genericsAndBounds; this.genericsAndBounds = genericsAndBounds;
// this.consClass = consClass; this.commonPairs = commonPairs;
// sw = new SignatureWriter(); this.tphsClass = tphsClass;
// createSignatureForClassOrInterface(); this.consClass = consClass;
// } sw = new SignatureWriter();
createSignatureForClassOrInterface();
}
public Signature(HashMap<String, String> genericsAndBounds, public Signature(Constructor constructor, HashMap<String, String> genericsAndBounds,
HashMap<String,RefTypeOrTPHOrWildcardOrGeneric> methodParamsAndTypes,ResultSet resultSet, HashMap<String,RefTypeOrTPHOrWildcardOrGeneric> methodParamsAndTypes,ResultSet resultSet,
List<GenericsGeneratorResult> constraints) { HashMap<TPHConstraint,HashSet<String>> methodConstraints) {
//this.constructor = constructor; this.constructor = constructor;
this.genericsAndBounds = genericsAndBounds; this.genericsAndBounds = genericsAndBounds;
this.methodParamsAndTypes = methodParamsAndTypes; this.methodParamsAndTypes = methodParamsAndTypes;
this.resultSet = resultSet; this.resultSet = resultSet;
this.constraints = constraints; this.methodConstraints = methodConstraints;
sw = new SignatureWriter();
createSignatureForConsOrMethod(this.constructor,true);
} }
public Signature(int numberOfParams) { public Signature(Method method, HashMap<String, String> genericsAndBoundsMethod,HashMap<String, String> genericsAndBounds,
createSignatureForFunN(numberOfParams);
}
public Signature(int numberOfParams, String to, String[] paramTypes) {
createSignatureForFunN(numberOfParams, to, paramTypes);
}
public Signature(ClassOrInterface classOrInterface, HashMap<String, String> genericsAndBounds,
List<GenericsGeneratorResult> consClass) {
this.classOrInterface = classOrInterface;
this.genericsAndBounds = genericsAndBounds;
this.consClass = consClass;
}
public Signature(HashMap<String, String> genericsAndBoundsMethod,
HashMap<String, String> genericsAndBounds,
HashMap<String, RefTypeOrTPHOrWildcardOrGeneric> methodParamsAndTypes, ResultSet resultSet, HashMap<String, RefTypeOrTPHOrWildcardOrGeneric> methodParamsAndTypes, ResultSet resultSet,
List<GenericsGeneratorResult> constraints,List<GenericsGeneratorResult> consClass) { HashMap<TPHConstraint,HashSet<String>> methodConstraints) {
this.method = method;
this.genericsAndBoundsMethod = genericsAndBoundsMethod; this.genericsAndBoundsMethod = genericsAndBoundsMethod;
this.genericsAndBounds = genericsAndBounds; this.genericsAndBounds = genericsAndBounds;
this.methodParamsAndTypes = methodParamsAndTypes; this.methodParamsAndTypes = methodParamsAndTypes;
this.resultSet = resultSet; this.resultSet = resultSet;
this.constraints = constraints; this.methodConstraints = methodConstraints;
this.consClass = consClass; sw = new SignatureWriter();
createSignatureForConsOrMethod(this.method,false);
} }
public String createSignatureForConstructor(Constructor constructor) { public Signature(LambdaExpression lambdaExpression,int numberOfParams) {
visitParams(); sw = new SignatureWriter();
sw.visitReturnType().visitBaseType('V'); createSignatureForFunN(lambdaExpression, numberOfParams);
return sw.toString();
} }
public String createSignatureForMethod(Method method) { private void createSignatureForFunN(LambdaExpression lambdaExpression, int numberOfParams) {
defineGenerics(method);
String ret = resultSet.resolveType(method.getReturnType()).resolvedType.acceptTV(new TypeToSignature()); // sw.visitClassBound().visitEnd();
visitParams();
visitReturnType(method, ret);
return sw.toString();
}
/**
* @param method
* @param ret
*/
private void visitReturnType(Method method, String ret) {
if (ret.equals("V")) {
sw.visitReturnType().visitBaseType('V');
} else {
RefTypeOrTPHOrWildcardOrGeneric returnType = method.getReturnType();
SignatureVisitor sv = sw.visitReturnType();
doVisitParamsOrReturn(returnType, sv);
}
}
/**
*
*/
private void visitParams() {
for (String paramName : methodParamsAndTypes.keySet()) {
RefTypeOrTPHOrWildcardOrGeneric t = methodParamsAndTypes.get(paramName);
SignatureVisitor sv = sw.visitParameterType();
doVisitParamsOrReturn(t, sv);
}
}
/**
*
* @param method
*/
private void defineGenerics(Method method) {
method.getGenerics().forEach(g -> {
visitTypeVarsAndTheirBounds(g, genericsAndBoundsMethod);
});
defineGenericsFromConstraints(constraints,genericsAndBoundsMethod);
}
private void createSignatureForFunN(int numberOfParams, String to, String[] paramTypes) {
defineTypeVariablesForParametersOfFunN(numberOfParams);
sw.visitFormalTypeParameter("R");
visitClassBound(to);
// TODO: prüfe ob Return-Type = void,
sw.visitSuperclass().visitClassType(Type.getInternalName(Object.class));
sw.visitEnd();
}
private void createSignatureForFunN(int numberOfParams) {
defineTypeVariablesForParametersOfFunN(numberOfParams);
sw.visitFormalTypeParameter("R");
// getBounds vom Return-Type
sw.visitClassBound().visitClassType(Type.getInternalName(Object.class));
sw.visitClassBound().visitEnd();
// TODO: prüfe ob Return-Type = void,
sw.visitSuperclass().visitClassType(Type.getInternalName(Object.class));
sw.visitEnd();
}
private void defineTypeVariablesForParametersOfFunN(int numberOfParams) {
for(int i = 0;i<numberOfParams;i++) { for(int i = 0;i<numberOfParams;i++) {
int j = i+1; int j = i+1;
sw.visitFormalTypeParameter("T"+ j); sw.visitFormalTypeParameter("T"+ j);
@@ -168,212 +95,375 @@ public class Signature {
sw.visitClassBound().visitClassType(Type.getInternalName(Object.class)); sw.visitClassBound().visitClassType(Type.getInternalName(Object.class));
sw.visitClassBound().visitEnd(); sw.visitClassBound().visitEnd();
} }
sw.visitFormalTypeParameter("R");
// getBounds vom Return-Type
sw.visitClassBound().visitClassType(Type.getInternalName(Object.class));
sw.visitClassBound().visitEnd();
// TODO: prüfe ob Return-Type = void,
sw.visitSuperclass().visitClassType(Type.getInternalName(Object.class));;
sw.visitEnd();
}
/**
* Creates signature for a method or constructor with @see {@link SignatureWriter}
* Signature looks like:
* <typevaliables (K:Ljava/lang/Object "Bounds")>(params L.. OR T.. Or basistape)ReturnType
*
* @param method method or constructor
* @param isConstructor true if constructor
*/
private void createSignatureForConsOrMethod(Method method, boolean isConstructor) {
Iterator<? extends GenericTypeVar> itr = method.getGenerics().iterator();
// visits all formal type parameter and visits their bounds <T:...;B:...;...>
while(itr.hasNext()) {
System.out.println("HAS GENERICS!!");
GenericTypeVar g = itr.next();
getBoundsOfTypeVar(g,genericsAndBoundsMethod);
}
// Wenn die RückgabeType eine TPH ist, wird als generic behandelt
// z.B: Type = TPH K => wird eine Formal Type Parameter K$ erzeugt und Bound = Object
if(!isConstructor) {
String ret = resultSet.resolveType(method.getReturnType()).resolvedType.acceptTV(new TypeToSignature());
ArrayList<TPHConstraint> allConsBeforeSimplify = new ArrayList<>();
HashMap<TPHConstraint,HashSet<String>> allConstraints = new HashMap<>();
if(ret.contains("<")) {
allConsBeforeSimplify = getAllConstraints((RefType) resultSet.resolveType(method.getReturnType()).resolvedType);
}
for(String paramName : methodParamsAndTypes.keySet()) {
RefTypeOrTPHOrWildcardOrGeneric t = methodParamsAndTypes.get(paramName);
String pT = t.acceptTV(new TypeToSignature());
if(pT.contains("<"))
allConsBeforeSimplify = getAllConstraints((RefType) t);
}
boolean doSimplify = false;
if(!allConsBeforeSimplify.isEmpty()) {
addConstraintsToMap(allConstraints,allConsBeforeSimplify);
doSimplify = true;
}
createTypeVars(allConstraints, doSimplify);
if(!ret.equals("V")) {
if(ret.contains("$") && !ret.contains("$$") && !ret.contains("<")) {
if(genericsAndBounds.containsKey(ret)) {
genericsAndBoundsMethod.put(ret.substring(1), genericsAndBounds.get(ret.substring(1)));
}
}
}
}
// visit each method-parameter to create the signature
for(String paramName : methodParamsAndTypes.keySet()) {
RefTypeOrTPHOrWildcardOrGeneric t = methodParamsAndTypes.get(paramName);
// parameter type deswegen ist true
doVisitParamsOrReturn(t,true);
}
if(isConstructor ||
resultSet.resolveType(method.getReturnType()).resolvedType.acceptTV(new TypeToSignature()).equals("V")) {
sw.visitReturnType().visitBaseType('V');
}else {
RefTypeOrTPHOrWildcardOrGeneric returnType = method.getReturnType();
// return type deswegen ist false
doVisitParamsOrReturn(returnType, false);
}
// sw.visitEnd();
}
private void addConstraintsToMap(HashMap<TPHConstraint, HashSet<String>> allConstraints,
ArrayList<TPHConstraint> allConsBeforeSimplify) {
for(TPHConstraint tphCons : allConsBeforeSimplify) {
allConstraints.put(tphCons, null);
}
}
private String getEqualTPH(HashMap<TPHConstraint, HashSet<String>> methodConstraints, String tph) {
for(TPHConstraint cons : methodConstraints.keySet()) {
if(methodConstraints.get(cons) != null) {
if(methodConstraints.get(cons).contains(tph)) {
return cons.getLeft();
}
}
}
return tph;
}
private void createTypeVars(HashMap<TPHConstraint, HashSet<String>> allConstraints, boolean doSimplify) {
allConstraints.putAll(methodConstraints);
HashMap<TPHConstraint, HashSet<String>> simplifiedConstraints;
if(doSimplify) {
simplifiedConstraints = Simplify.simplifyContraints(allConstraints);
}else {
simplifiedConstraints = allConstraints;
}
for(TPHConstraint cons : simplifiedConstraints.keySet()) {
// need subst.
String sub = cons.getLeft()+"$";
if(!genericsAndBoundsMethod.containsKey(sub) && !genericsAndBounds.containsKey(sub)) {
sw.visitFormalTypeParameter(sub);
String bound = cons.getRight();
if(bound.equals(Type.getInternalName(Object.class))) {
sw.visitClassBound().visitClassType(Type.getInternalName(Object.class));
sw.visitClassBound().visitEnd();
genericsAndBoundsMethod.put(sub, bound);
} else {
String boundName = bound+"$";
sw.visitClassBound().visitTypeVariable(boundName);
genericsAndBoundsMethod.put(sub, boundName);
}
}
}
}
private ArrayList<TPHConstraint> getAllConstraints(RefType ref) {
final ArrayList<TPHConstraint> res = new ArrayList<>();
for(RefTypeOrTPHOrWildcardOrGeneric p : ref.getParaList()) {
ResolvedType resType;
if(p instanceof WildcardType) {
resType = resultSet.resolveType(((WildcardType) p).getInnerType());
}else {
resType = resultSet.resolveType(p);
}
RefTypeOrTPHOrWildcardOrGeneric resolved = resType.resolvedType;
if(resolved instanceof TypePlaceholder) {
resType.additionalGenerics.forEach(ag ->{
TPHConstraint constr = new ExtendsConstraint(ag.TA1.getName(), ag.TA2.getName(), Relation.EXTENDS);
if(!contains(res,constr)) {
res.add(constr);
}
});
}
if(resolved instanceof WildcardType) {
WildcardType resWC = (WildcardType) resolved;
ResolvedType resType2 = resultSet.resolveType(resWC.getInnerType());
if(resType2.resolvedType instanceof TypePlaceholder) {
resType2.additionalGenerics.forEach(ag ->{
TPHConstraint constr = new ExtendsConstraint(ag.TA1.getName(), ag.TA2.getName(), Relation.EXTENDS);
if(!contains(res,constr)) {
res.add(constr);
}
});
}
}
}
System.out.println("RES GIP === " + res.size());
return res;
}
private boolean contains(ArrayList<TPHConstraint> constraints, TPHConstraint constr) {
for(int i=0; i<constraints.size();++i) {
TPHConstraint p = constraints.get(i);
if(constr.getLeft().equals(p.getLeft()) && constr.getRight().equals(p.getRight()))
return true;
}
return false;
} }
/** /**
* Visits parameter type or return type with {@link SignatureVisitor} to create * Visits parameter type or return type with {@link SignatureVisitor} to create
* the method signature * the method signature
*
* @param t type of parameter or return type * @param t type of parameter or return type
* @param sv true if t is type of parameter * @param isParameterType true if t is type of parameter
*/ */
private void doVisitParamsOrReturn(RefTypeOrTPHOrWildcardOrGeneric t, SignatureVisitor sv) { private void doVisitParamsOrReturn(RefTypeOrTPHOrWildcardOrGeneric t, boolean isParameterType) {
String type = t.acceptTV(new TypeToString()); String type = t.acceptTV(new TypeToString());
SignatureVisitor sv;
if(isParameterType) {
sv = sw.visitParameterType();
}
else {
sv = sw.visitReturnType();
}
switch (type) { switch (type) {
case "RT": case "RT":
String sig = t.acceptTV(new TypeToSignature(constraints)); String sig = t.acceptTV(new TypeToSignature());
sv.visitClassType(sig.substring(1, sig.length())); sv.visitClassType(sig.substring(1, sig.length()));
break; break;
case "GRT": case "GRT":
GenericRefType g = (GenericRefType) t; GenericRefType g = (GenericRefType) t;
sv.visitTypeVariable(g.acceptTV(new TypeToSignature(constraints))); sv.visitTypeVariable(g.acceptTV(new TypeToSignature()).substring(1));
break; break;
case "TPH": case "TPH":
RefTypeOrTPHOrWildcardOrGeneric r = resultSet.resolveType(t).resolvedType; RefTypeOrTPHOrWildcardOrGeneric r = resultSet.resolveType(t).resolvedType;
// der Fall wenn der Typ eine Interface ist, muss betrachtet werden // der Fall wenn die Type eine Interface ist, muss betrachtet werden
// Deswegen muss in ResutSet noch enthalten werden, ob die Type eine // Deswegen muss in ResutSet noch enthalten werden, ob die Type eine
// Interface oder eine Klasse ist. // Interface oder eine Klasse ist.
// das braucht man nicht es reicht: sv.visitTypeVariable(r.acceptTV(new // das braucht man nicht es reicht: sv.visitTypeVariable(r.acceptTV(new TypeToSignature())
// TypeToSignature())
// //
String sig2 = r.acceptTV(new TypeToSignature(constraints)); String sig2 = r.acceptTV(new TypeToSignature());
if (r instanceof GenericRefType) { String eqTPH = getEqualTPH(methodConstraints, sig2.substring(1, sig2.length()-1))+"$";
sv.visitTypeVariable(sig2); if(!(r instanceof TypePlaceholder)) {
} else if (!(r instanceof TypePlaceholder)) { if(sig2.contains("$$")) {
if (sig2.contains(SPECIAL_CHAR_FOR_FUN)) { System.out.println(" Signature FUN$$: "+r);
sv.visitInterface().visitClassType(sig2.substring(1)); sv.visitInterface().visitClassType(sig2.substring(1, sig2.length()));
} else { } else {
// Kann zwischen GenericRefType und RefType nicht unterscheiden sv.visitClassType(sig2.substring(1, sig2.length()));
// Deswegen wird immer geprüft, ob der Name in Generic Maps liegt
String n = sig2.substring(1, sig2.length() - 1);
// if(genericsAndBoundsMethod.containsKey(n) || genericsAndBounds.containsKey(n)) {
// sv.visitTypeVariable(n);
// } else {
sv.visitClassType(n);
sv.visitEnd();
// }
// sv.visitClassType(n);
} }
} else { } else {
String realName = sig2.substring(1, sig2.length() - 1); System.out.println(r.getClass()+" Signature TPH: "+r.acceptTV(new TypeToSignature()));
String toVisit = realName+SPECIAL_CHAR; sv.visitTypeVariable(eqTPH);
if(!genericsAndBounds.containsKey(toVisit)) {
Optional<GenericsGeneratorResult> equalTPH = getEqualTPHFromClassConstraints(consClass, realName);
if(equalTPH.isPresent()){
toVisit = equalTPH.get().getConstraint().getLeft() + SPECIAL_CHAR;
} else {
toVisit = getEqualTPH(constraints, realName) + SPECIAL_CHAR;
}
}
sv.visitTypeVariable(toVisit);
} }
break; break;
case "SWC": case "SWC":
System.out.println("SWC---Signature");
SuperWildcardType swc = (SuperWildcardType) t; SuperWildcardType swc = (SuperWildcardType) t;
String sigInner = swc.getInnerType().acceptTV(new TypeToSignature(constraints)); String sigInner = swc.getInnerType().acceptTV(new TypeToSignature());
int length = sigInner.length(); if(swc.getInnerType() instanceof TypePlaceholder) {
visitWildCard(sv, sigInner, length, swc.getInnerType(), SUPER_CHAR); sv.visitTypeArgument('-').visitTypeVariable(sigInner.substring(1, sigInner.length()));
} else if(swc.getInnerType() instanceof RefType) {
if(sigInner.contains("$$")) {
sv.visitTypeArgument('-').visitInterface().visitClassType(sigInner.substring(1,sigInner.length()));
}else {
sv.visitTypeArgument('-').visitClassType(sigInner.substring(1,sigInner.length()));
}
}else {
sv.visitTypeArgument('-').visitTypeVariable(sigInner.substring(1));
}
break; break;
case "EWC": case "EWC":
System.out.println("EWC---Signature");
ExtendsWildcardType ewc = (ExtendsWildcardType) t; ExtendsWildcardType ewc = (ExtendsWildcardType) t;
String esigInner = ewc.getInnerType().acceptTV(new TypeToSignature(constraints)); String esigInner = ewc.getInnerType().acceptTV(new TypeToSignature());
int lengthEWCSig = esigInner.length(); System.out.println(esigInner);
visitWildCard(sv, esigInner, lengthEWCSig, ewc.getInnerType(), EXTENDS_CHAR); if(ewc.getInnerType() instanceof TypePlaceholder) {
sv.visitTypeArgument('+').visitTypeVariable(esigInner.substring(1, esigInner.length()));
} else if(ewc.getInnerType() instanceof RefType) {
if(esigInner.contains("$$")) {
sv.visitTypeArgument('+').visitInterface().visitClassType(esigInner.substring(1,esigInner.length()));
}else {
// sv.visitClassType(esigInner.substring(1,esigInner.length()));
sv.visitTypeArgument('+').visitClassType(esigInner.substring(1,esigInner.length()));
}
}else {
sv.visitTypeArgument('+').visitTypeVariable(esigInner.substring(1));
}
break; break;
default: default:
// if (!sv) if(!isParameterType)
// sv.visitBaseType('V'); sv.visitBaseType('V');
break; break;
} }
} }
private void visitWildCard(SignatureVisitor sv, String sigInner, int length, RefTypeOrTPHOrWildcardOrGeneric innerType, char superOrExtendsChar) {
if (innerType instanceof TypePlaceholder) {
sv.visitTypeArgument(superOrExtendsChar).visitTypeVariable(sigInner.substring(1, length));
} else if (innerType instanceof RefType) {
checkInnerSignatureOfWildCard(sv, sigInner, length, superOrExtendsChar);
} else {
sv.visitTypeArgument(superOrExtendsChar).visitTypeVariable(sigInner.substring(1));
}
}
private void checkInnerSignatureOfWildCard(SignatureVisitor sv, String sigInner, int length, char superOrExtendsChar) {
if (sigInner.contains(SPECIAL_CHAR_FOR_FUN)) {
sv.visitTypeArgument(superOrExtendsChar).visitInterface().visitClassType(sigInner.substring(1, length));
} else {
sv.visitTypeArgument(superOrExtendsChar).visitClassType(sigInner.substring(1, length));
}
}
private Optional<GenericsGeneratorResult> getEqualTPHFromClassConstraints(List<GenericsGeneratorResult> consClass, String tph) {
return consClass.stream()
.filter(c -> c.getConstraint().getLeft().equals(tph) || c.getEqualsTPHs().contains(tph))
.findFirst();
}
private String getEqualTPH(List<GenericsGeneratorResult> constraints2, String tph) {
return constraints2.stream()
.filter(c -> c.getConstraint().getLeft().equals(tph) || c.getEqualsTPHs().contains(tph))
.findFirst().get().getConstraint().getLeft();
}
/** /**
* Creates signature for class or interface with {@link SignatureWriter} * Creates signature for class or interface with {@link SignatureWriter}
* Signature looks like: <typevaliables (K:Ljava/lang/Object * Signature looks like:
* "Bounds")>superclass * <typevaliables (K:Ljava/lang/Object "Bounds")>superclass
*/ */
public String createSignatureForClassOrInterface() { private void createSignatureForClassOrInterface() {
defineTypeVariablesForClassOrInterface();
defineGenericsFromConstraints(consClass,genericsAndBounds);
String sClass = classOrInterface.getSuperClass().acceptTV(new TypeToSignature());
sw.visitSuperclass().visitClassType(sClass.substring(1, sClass.length() - 1));
sw.visitEnd();
return sw.toString();
}
private void defineTypeVariablesForClassOrInterface() {
Iterator<GenericTypeVar> itr = classOrInterface.getGenerics().iterator(); Iterator<GenericTypeVar> itr = classOrInterface.getGenerics().iterator();
while(itr.hasNext()) { while(itr.hasNext()) {
GenericTypeVar g = itr.next(); GenericTypeVar g = itr.next();
visitTypeVarsAndTheirBounds(g, genericsAndBounds); getBoundsOfTypeVar(g,genericsAndBounds);
}
} }
/** if(!consClass.isEmpty()) {
* @param genericsAndBounds2 ArrayList<String> types = new ArrayList<>();
* ArrayList<String> superTypes = new ArrayList<>();
*/
private void defineGenericsFromConstraints(List<GenericsGeneratorResult> constraints, HashMap<String,String> genericsAndBounds2) {
constraints.forEach(c -> {
String typeVariable = c.getConstraint().getLeft() + SPECIAL_CHAR;
sw.visitFormalTypeParameter(typeVariable);
String bound = c.getConstraint().getRight(); for(TPHConstraint cons : consClass) {
bound = checkBound(bound); types.add(cons.getLeft());
genericsAndBounds2.put(typeVariable, bound); superTypes.add(cons.getRight());
});
} }
/** for(TPHConstraint cons : consClass) {
* @param bound String t = cons.getLeft()+"$";
* @return String bound = cons.getRight()+"$";
*/ sw.visitFormalTypeParameter(t);
private String checkBound(String bound) {
if (bound.equals(Type.getInternalName(Object.class))) {
visitClassBound(bound);
} else {
bound += SPECIAL_CHAR;
sw.visitClassBound().visitTypeVariable(bound); sw.visitClassBound().visitTypeVariable(bound);
} genericsAndBounds.put(t, bound);
return bound;
} }
/** for(TPHConstraint cons : consClass) {
* @param bound if(!types.contains(cons.getRight())) {
*/ String t = cons.getRight()+"$";
private void visitClassBound(String bound) { String bound = Type.getInternalName(Object.class);
sw.visitFormalTypeParameter(t);
sw.visitClassBound().visitClassType(bound); sw.visitClassBound().visitClassType(bound);
genericsAndBounds.put(t, bound);
sw.visitClassBound().visitEnd(); sw.visitClassBound().visitEnd();
} }
}
}
/*if(!commonPairs.isEmpty()) {
ArrayList<TypePlaceholder> types = new ArrayList<>();
ArrayList<TypePlaceholder> superTypes = new ArrayList<>();
for(GenericInsertPair p : commonPairs) {
types.add(p.TA1);
superTypes.add(p.TA2);
}
for(GenericInsertPair p : commonPairs) {
String t = p.TA1.getName()+"$";
String bound = p.TA2.getName()+"$";
sw.visitFormalTypeParameter(t);
sw.visitClassBound().visitTypeVariable(bound);
genericsAndBounds.put(t, bound);
}
for(GenericInsertPair p : commonPairs) {
if(!types.contains(p.TA2)) {
String t = p.TA2.getName()+"$";
String bound = Type.getInternalName(Object.class);
sw.visitFormalTypeParameter(t);
sw.visitClassBound().visitClassType(bound);
genericsAndBounds.put(t, bound);
sw.visitClassBound().visitEnd();
}
}
}
for(TypePlaceholder t : tphsClass) {
String n = t.getName()+"$";
String bound = Type.getInternalName(Object.class);
sw.visitFormalTypeParameter(n);
sw.visitClassBound().visitClassType(bound);
genericsAndBounds.put(n, bound);
sw.visitClassBound().visitEnd();
}*/
String sClass = classOrInterface.getSuperClass().acceptTV(new TypeToSignature());
sw.visitSuperclass().visitClassType(sClass.substring(1, sClass.length()-1));
sw.visitEnd();
}
/** /**
* Get bounds of type variable * Get bounds of type variable
*
* @param g type variable * @param g type variable
* @param genAndBounds * @param genAndBounds
*/ */
private void visitTypeVarsAndTheirBounds(GenericTypeVar g, HashMap<String, String> genAndBounds) { private void getBoundsOfTypeVar(GenericTypeVar g, HashMap<String, String> genAndBounds) {
sw.visitFormalTypeParameter(g.getName()); sw.visitFormalTypeParameter(g.getName());
Iterator<? extends RefTypeOrTPHOrWildcardOrGeneric> bItr = g.getBounds().iterator(); Iterator<? extends RefTypeOrTPHOrWildcardOrGeneric> bItr = g.getBounds().iterator();
while(bItr.hasNext()) { while(bItr.hasNext()) {
RefTypeOrTPHOrWildcardOrGeneric b =bItr.next(); RefTypeOrTPHOrWildcardOrGeneric b =bItr.next();
String boundDesc = b.acceptTV(new TypeToDescriptor()); String boundDesc = b.acceptTV(new TypeToDescriptor());
// System.out.println("GetBounds: " + boundDesc);
// Ensure that <...> extends java.lang.Object OR ... // Ensure that <...> extends java.lang.Object OR ...
if (b instanceof GenericRefType) { sw.visitClassBound().visitClassType(boundDesc);
sw.visitClassBound().visitTypeVariable(boundDesc);
} else {
visitClassBound(boundDesc);
}
genAndBounds.put(g.getName(), boundDesc); genAndBounds.put(g.getName(), boundDesc);
} }
sw.visitClassBound().visitEnd();
} }
@Override
public String toString() { public String toString() {
if(sw == null)
return super.toString();
return sw.toString(); return sw.toString();
} }
} }

View File

@@ -1,11 +1,8 @@
package de.dhbwstuttgart.bytecode.signature; package de.dhbwstuttgart.bytecode.signature;
import java.util.ArrayList;
import java.util.Iterator; import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.GenericsGeneratorResult; import de.dhbwstuttgart.exceptions.NotImplementedException;
import de.dhbwstuttgart.syntaxtree.type.ExtendsWildcardType; import de.dhbwstuttgart.syntaxtree.type.ExtendsWildcardType;
import de.dhbwstuttgart.syntaxtree.type.GenericRefType; import de.dhbwstuttgart.syntaxtree.type.GenericRefType;
import de.dhbwstuttgart.syntaxtree.type.RefType; import de.dhbwstuttgart.syntaxtree.type.RefType;
@@ -15,15 +12,6 @@ import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder;
import de.dhbwstuttgart.syntaxtree.type.TypeVisitor; import de.dhbwstuttgart.syntaxtree.type.TypeVisitor;
public class TypeToSignature implements TypeVisitor<String> { public class TypeToSignature implements TypeVisitor<String> {
private List<GenericsGeneratorResult> constraints;
public TypeToSignature() {
this.constraints = new ArrayList<>();
}
public TypeToSignature(List<GenericsGeneratorResult> constraints) {
this.constraints = constraints;
}
@Override @Override
public String visit(RefType refType) { public String visit(RefType refType) {
@@ -45,7 +33,7 @@ public class TypeToSignature implements TypeVisitor<String> {
// } else { // } else {
// params += "L"+param.toString().replace(".", "/"); // params += "L"+param.toString().replace(".", "/");
// } // }
params += param.acceptTV(new TypeToSignature(constraints)); params += param.acceptTV(new TypeToSignature());
if(param instanceof TypePlaceholder) if(param instanceof TypePlaceholder)
params += ";"; params += ";";
@@ -60,7 +48,7 @@ public class TypeToSignature implements TypeVisitor<String> {
@Override @Override
public String visit(SuperWildcardType superWildcardType) { public String visit(SuperWildcardType superWildcardType) {
// throw new NotImplementedException(); // throw new NotImplementedException();
String sig = "-" + superWildcardType.getInnerType().acceptTV(new TypeToSignature(constraints)); String sig = "-" + superWildcardType.getInnerType().acceptTV(new TypeToSignature());
if(superWildcardType.getInnerType() instanceof TypePlaceholder) if(superWildcardType.getInnerType() instanceof TypePlaceholder)
sig += ";"; sig += ";";
return sig; return sig;
@@ -69,21 +57,13 @@ public class TypeToSignature implements TypeVisitor<String> {
@Override @Override
public String visit(TypePlaceholder typePlaceholder) { public String visit(TypePlaceholder typePlaceholder) {
// return typePlaceholder.toString().replace(".", "/"); // return typePlaceholder.toString().replace(".", "/");
String name = typePlaceholder.getName(); return "T" + typePlaceholder.getName() + "$";
if(!constraints.isEmpty()){
Optional<GenericsGeneratorResult> equalName = getEqualTPHFromClassConstraints(constraints, name);
if(equalName.isPresent())
name = equalName.get().getConstraint().getLeft();
}
return "T" + name + "$";
} }
@Override @Override
public String visit(ExtendsWildcardType extendsWildcardType) { public String visit(ExtendsWildcardType extendsWildcardType) {
// throw new NotImplementedException(); // throw new NotImplementedException();
String sig = "+" + extendsWildcardType.getInnerType().acceptTV(new TypeToSignature(constraints)); String sig = "+" + extendsWildcardType.getInnerType().acceptTV(new TypeToSignature());
if(extendsWildcardType.getInnerType() instanceof TypePlaceholder) if(extendsWildcardType.getInnerType() instanceof TypePlaceholder)
sig += ";"; sig += ";";
return sig; return sig;
@@ -94,9 +74,4 @@ public class TypeToSignature implements TypeVisitor<String> {
return genericRefType.getParsedName().replace(".", "/"); return genericRefType.getParsedName().replace(".", "/");
} }
private Optional<GenericsGeneratorResult> getEqualTPHFromClassConstraints(List<GenericsGeneratorResult> listOfConstraints, String tph) {
return listOfConstraints.stream()
.filter(c -> c.getConstraint().getLeft().equals(tph) || c.getEqualsTPHs().contains(tph))
.findFirst();
}
} }

View File

@@ -1,50 +0,0 @@
/**
*
*/
package de.dhbwstuttgart.bytecode.simplifyRes;
import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;
/**
* The simplify results of a source file (package)
*
* @author fayez
*
*/
public class GenericGenratorResultForSourceFile {
private String pkgName;
private final List<GenericsGeneratorResultForClass> genericGeneratorResultForAllClasses = new ArrayList<>();
/**
* @param pkgName
*/
public GenericGenratorResultForSourceFile(String pkgName) {
this.pkgName = pkgName;
}
public List<GenericsGeneratorResultForClass> getGenericGeneratorResultForAllClasses() {
return genericGeneratorResultForAllClasses;
}
/**
* Appends the simplify results of a class to simplifyResForSF
*
* @param sResClass simplify results of a class to added
*/
public void addGenericGeneratorResultClass(GenericsGeneratorResultForClass sResClass) {
genericGeneratorResultForAllClasses.add(sResClass);
}
public GenericsGeneratorResultForClass getSimplifyResultsByName(String pkgName, String name) {
for (int i = 0; i < genericGeneratorResultForAllClasses.size(); i++) {
GenericsGeneratorResultForClass genericsGeneratorResult = genericGeneratorResultForAllClasses.get(i);
if (genericsGeneratorResult.getClassName().equals(name)) {
return genericsGeneratorResult;
}
}
return new GenericsGeneratorResultForClass(name);
}
}

View File

@@ -1,75 +0,0 @@
/**
*
*/
package de.dhbwstuttgart.bytecode.simplifyRes;
import java.util.Collections;
import java.util.List;
import com.google.common.base.Optional;
import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.GenericGeneratorResultsForAllMethods;
import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.GenericsGeneratorResult;
import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.MethodAndConstraints;
/**
* @author fayez
*
*/
public class GenericsGeneratorResultForClass {
private final String className;
private final List<GenericsGeneratorResult> classConstraints;
private final GenericGeneratorResultsForAllMethods methodsAndTheirConstraints;
public GenericsGeneratorResultForClass(String className) {
this(className, Collections.emptyList(), new GenericGeneratorResultsForAllMethods());
}
/**
* @param className
* @param classConstraints
* @param methodsAndTheirConstraints
*/
public GenericsGeneratorResultForClass(String className, List<GenericsGeneratorResult> classConstraints,
GenericGeneratorResultsForAllMethods methodsAndTheirConstraints) {
this.className = className;
this.classConstraints = classConstraints;
this.methodsAndTheirConstraints = methodsAndTheirConstraints;
}
/**
* @return the className
*/
public String getClassName() {
return className;
}
/**
* @return the classConstraints
*/
public List<GenericsGeneratorResult> getClassConstraints() {
return classConstraints;
}
/**
* @return the methodsAndTheirConstraints
*/
public GenericGeneratorResultsForAllMethods getMethodsAndTheirConstraints() {
return methodsAndTheirConstraints;
}
public boolean contains(String id) {
return methodsAndTheirConstraints.getMethodsAndConstraints().stream().map(mc -> mc.getMethodID())
.anyMatch(i -> i.equals(id));
}
public List<GenericsGeneratorResult> getMethodConstraintsByID(String id) {
java.util.Optional<MethodAndConstraints> methodAndConstraints = methodsAndTheirConstraints.getMethodsAndConstraints().stream().filter(mc -> mc.getMethodID().equals(id))
.findFirst();
return methodAndConstraints.isPresent() ? methodAndConstraints.get().getConstraints() : Collections.emptyList();
}
}

View File

@@ -1,94 +0,0 @@
package de.dhbwstuttgart.bytecode.utilities;
import de.dhbwstuttgart.bytecode.signature.Signature;
import de.dhbwstuttgart.syntaxtree.FormalParameter;
import de.dhbwstuttgart.syntaxtree.statement.ArgumentList;
import de.dhbwstuttgart.syntaxtree.statement.Expression;
import de.dhbwstuttgart.syntaxtree.statement.LambdaExpression;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.signature.SignatureVisitor;
import org.objectweb.asm.signature.SignatureWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
public class ByteCodeForFunNGenerator {
public static void generateBCForFunN(LambdaExpression lambdaExpression, String methDesc, String path) {
ClassWriter classWriter = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS);
SignatureWriter methSig = new SignatureWriter();
int numberOfParams = 0;
SignatureVisitor paramVisitor = methSig.visitParameterType();
Iterator<FormalParameter> itr = lambdaExpression.params.iterator();
while (itr.hasNext()) {
numberOfParams++;
// getBounds
paramVisitor.visitTypeVariable(CONSTANTS.T + numberOfParams);
itr.next();
}
methSig.visitReturnType().visitTypeVariable(CONSTANTS.R);
// ")"+lam.getReturn.getBounds
Signature sig = new Signature(numberOfParams);
String name = CONSTANTS.FUN + numberOfParams + CONSTANTS.$$;
classWriter.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC+Opcodes.ACC_INTERFACE + Opcodes.ACC_ABSTRACT, name, sig.toString(),
Type.getInternalName(Object.class), null);
MethodVisitor mvApply = classWriter.visitMethod(Opcodes.ACC_PUBLIC + Opcodes.ACC_ABSTRACT, "apply", methDesc,
methSig.toString(), null);
mvApply.visitEnd();
writeClassFile(classWriter.toByteArray(), name, path);
}
public static void generateBCForFunN(ArgumentList argumentList, String methDesc, String path) {
ClassWriter classWriter = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS);
SignatureWriter methSig = new SignatureWriter();
int numberOfParams = 0;
SignatureVisitor paramVisitor = methSig.visitParameterType();
Iterator<Expression> itr1 = argumentList.getArguments().iterator();
while(itr1.hasNext()) {
numberOfParams++;
// getBounds
paramVisitor.visitTypeVariable(CONSTANTS.T + numberOfParams);
itr1.next();
}
methSig.visitReturnType().visitTypeVariable(CONSTANTS.R);
// ")"+lam.getReturn.getBounds
Signature sig = new Signature(numberOfParams);
String name = CONSTANTS.FUN + numberOfParams + CONSTANTS.$$;
classWriter.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC+Opcodes.ACC_INTERFACE + Opcodes.ACC_ABSTRACT, name, sig.toString(),
Type.getInternalName(Object.class), null);
MethodVisitor mvApply = classWriter.visitMethod(Opcodes.ACC_PUBLIC + Opcodes.ACC_ABSTRACT, "apply", methDesc,
methSig.toString(), null);
mvApply.visitEnd();
writeClassFile(classWriter.toByteArray(), name, path);
}
public static void writeClassFile(byte[] bytecode, String name, String path) {
FileOutputStream output;
try {
System.out.println("generating " + name + ".class file...");
output = new FileOutputStream(
new File(path + name + CONSTANTS.EXTENSIONCLASS));
output.write(bytecode);
output.close();
System.out.println(name + ".class file generated");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

View File

@@ -1,22 +0,0 @@
package de.dhbwstuttgart.bytecode.utilities;
public interface CONSTANTS {
String VOID = "void";
String TPH = "TPH ";
String ANGLEBRACKET = "<";
String FUN = "Fun";
String EXTENSIONCLASS = ".class";
String $$ = "$$";
String T = "T";
String R = "R";
String DESUGAREDMETHODNAME = "lambda$new$";
String REFTYPE_BYTE = "java/lang/Byte";
String REFTYPE_SHORT = "java/lang/Short";
String REFTYPE_INTEGER = "java/lang/Integer";
String REFTYPE_LONG = "java/lang/Long";
String REFTYPE_DOUBLE = "java/lang/Double";
String REFTYPE_FLOAT = "java/lang/Float";
String REFTYPE_STRING = "java/lang/String";
String TO_STRING = "toString";
}

View File

@@ -1,53 +0,0 @@
package de.dhbwstuttgart.bytecode.utilities;
import java.util.ArrayList;
import java.util.List;
import de.dhbwstuttgart.bytecode.constraint.TPHConstraint;
import de.dhbwstuttgart.bytecode.constraint.TPHConstraint.Relation;
import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.ConstraintsWithSameLeftSide;
public class ConstraintsFinder {
private List<TPHConstraint> allConstaints;
public ConstraintsFinder(List<TPHConstraint> allConstaints) {
this.allConstaints = allConstaints;
}
public List<ConstraintsWithSameLeftSide> findConstraints() {
List<ConstraintsWithSameLeftSide> result = new ArrayList<>();
List<TPHConstraint> visitedCons = new ArrayList<>();
for(TPHConstraint c : allConstaints) {
if(c.getRel() == Relation.EXTENDS) {
// get constraints with the same left side
List<TPHConstraint> cons = getConstraints(c,visitedCons);
if(cons.size()>1) {
ConstraintsWithSameLeftSide consWithSameLeftSide = new ConstraintsWithSameLeftSide(cons);
result.add(consWithSameLeftSide);
}
}
}
return result;
}
private List<TPHConstraint> getConstraints(TPHConstraint c, List<TPHConstraint> visitedCons) {
List<TPHConstraint> res = new ArrayList<>();
for(TPHConstraint cons : allConstaints) {
if(!isVisited(cons,visitedCons) && cons.getLeft().equals(c.getLeft())) {
res.add(cons);
visitedCons.add(cons);
}
}
return res;
}
private boolean isVisited(TPHConstraint cons, List<TPHConstraint> visitedCons) {
for(TPHConstraint c : visitedCons) {
if(c.getLeft().equals(cons.getLeft()) && c.getRight().equals(cons.getRight()))
return true;
}
return false;
}
}

View File

@@ -1,5 +1,6 @@
package de.dhbwstuttgart.bytecode.utilities; package de.dhbwstuttgart.bytecode.utilities;
import de.dhbwstuttgart.exceptions.NotImplementedException;
import de.dhbwstuttgart.syntaxtree.statement.*; import de.dhbwstuttgart.syntaxtree.statement.*;
import java.util.ArrayList; import java.util.ArrayList;
@@ -18,8 +19,7 @@ public class KindOfLambda implements StatementVisitor{
private boolean isInstanceCapturingLambda = false; private boolean isInstanceCapturingLambda = false;
private List<RefTypeOrTPHOrWildcardOrGeneric> argumentList = new ArrayList<>(); private List<RefTypeOrTPHOrWildcardOrGeneric> argumentList = new ArrayList<>();
private ArrayList<String> usedVars = new ArrayList<>(); private ArrayList<String> usedVars = new ArrayList<>();
private ArrayList<String> varsFromInnerLambdas = new ArrayList<>(); private boolean hasThis = false;
private boolean thisUsed = false;
private ArrayList<String> definedLocals = new ArrayList<>(); private ArrayList<String> definedLocals = new ArrayList<>();
public KindOfLambda(LambdaExpression lambdaExpression) { public KindOfLambda(LambdaExpression lambdaExpression) {
@@ -40,20 +40,19 @@ public class KindOfLambda implements StatementVisitor{
return argumentList; return argumentList;
} }
public boolean isThisUsed() { public boolean isHasThis() {
return thisUsed; return hasThis;
} }
@Override @Override
public void visit(ArgumentList argumentList) { public void visit(ArgumentList argumentList) {
argumentList.getArguments().forEach(a->a.accept(this)); // TODO Auto-generated method stub
} }
@Override @Override
public void visit(LambdaExpression lambdaExpression) { public void visit(LambdaExpression lambdaExpression) {
lambdaExpression.params.getFormalparalist().forEach(p->varsFromInnerLambdas.add(p.getName()));
lambdaExpression.methodBody.accept(this);
} }
@Override @Override
@@ -112,11 +111,9 @@ public class KindOfLambda implements StatementVisitor{
@Override @Override
public void visit(LocalVar localVar) { public void visit(LocalVar localVar) {
boolean addVar = !contain(params, localVar.name) && !definedLocals.contains(localVar.name) && if(!contain(params, localVar.name) && !definedLocals.contains(localVar.name)) {
!varsFromInnerLambdas.contains(localVar.name) && !usedVars.contains(localVar.name);
if(addVar) {
argumentList.add(localVar.getType()); argumentList.add(localVar.getType());
if(thisUsed) { if(hasThis) {
usedVars.add(1, localVar.name); usedVars.add(1, localVar.name);
} else { } else {
usedVars.add(0, localVar.name); usedVars.add(0, localVar.name);
@@ -144,13 +141,12 @@ public class KindOfLambda implements StatementVisitor{
@Override @Override
public void visit(MethodCall methodCall) { public void visit(MethodCall methodCall) {
methodCall.receiver.accept(this); methodCall.receiver.accept(this);
methodCall.arglist.accept(this);
} }
@Override @Override
public void visit(NewClass methodCall) { public void visit(NewClass methodCall) {
methodCall.receiver.accept(this); // TODO Auto-generated method stub
methodCall.arglist.accept(this);
} }
@Override @Override
@@ -194,8 +190,8 @@ public class KindOfLambda implements StatementVisitor{
@Override @Override
public void visit(This aThis) { public void visit(This aThis) {
if(!thisUsed) { if(!hasThis) {
thisUsed = true; hasThis = true;
this.argumentList.add(0,aThis.getType()); this.argumentList.add(0,aThis.getType());
} }
if(!isInstanceCapturingLambda) { if(!isInstanceCapturingLambda) {

View File

@@ -2,41 +2,28 @@ package de.dhbwstuttgart.bytecode.utilities;
import java.util.ArrayList; import java.util.ArrayList;
import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric;
import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder; import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder;
import de.dhbwstuttgart.typeinference.result.GenericInsertPair; import de.dhbwstuttgart.typeinference.result.GenericInsertPair;
import de.dhbwstuttgart.typeinference.result.ResultPair;
public class MethodAndTPH { public class MethodAndTPH {
private String id; private String name;
private final ArrayList<String> tphs = new ArrayList<>(); private final ArrayList<String> tphs = new ArrayList<>();
//private final ArrayList<GenericInsertPair> pairs = new ArrayList<>(); private final ArrayList<GenericInsertPair> pairs = new ArrayList<>();
private final ArrayList<ResultPair<TypePlaceholder, TypePlaceholder>> pairs = new ArrayList<>();
// tphs of local variables and parameters
private final ArrayList<String> localTphs = new ArrayList<>();
public MethodAndTPH(String name) { public MethodAndTPH(String name) {
this.id = name; this.name = name;
} }
public ArrayList<String> getTphs() { public ArrayList<String> getTphs() {
return tphs; return tphs;
} }
// public ArrayList<GenericInsertPair> getPairs(){ public ArrayList<GenericInsertPair> getPairs(){
// return pairs;
// }
public ArrayList<ResultPair<TypePlaceholder, TypePlaceholder>> getPairs(){
return pairs; return pairs;
} }
public String getId() { public String getName() {
return id; return name;
} }
public ArrayList<String> getLocalTphs() {
return localTphs;
}
} }

View File

@@ -1,243 +0,0 @@
/**
*
*/
package de.dhbwstuttgart.bytecode.utilities;
import de.dhbwstuttgart.bytecode.Exception.NotInCurrentPackageException;
import de.dhbwstuttgart.bytecode.descriptor.DescriptorToString;
import de.dhbwstuttgart.bytecode.descriptor.TypeToDescriptor;
import de.dhbwstuttgart.bytecode.signature.TypeToSignature;
import de.dhbwstuttgart.syntaxtree.*;
import de.dhbwstuttgart.syntaxtree.statement.Expression;
import de.dhbwstuttgart.syntaxtree.statement.MethodCall;
import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric;
import de.dhbwstuttgart.typeinference.result.ResultSet;
import javassist.NotFoundException;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import java.util.*;
/**
* @author fayez
*
*/
public class MethodCallHelper {
private MethodCall methCall;
private SourceFile sourceFile;
private ResultSet resultSet;
private String path;
/**
* @param methCall
* @param sourceFile
* @param resultSet
* @param path TODO
*/
public MethodCallHelper(MethodCall methCall, SourceFile sourceFile, ResultSet resultSet, String path) {
this.methCall = methCall;
this.sourceFile = sourceFile;
this.resultSet = resultSet;
this.path = path;
}
public String getResolvedType(RefTypeOrTPHOrWildcardOrGeneric type) {
return resultSet.resolveType(type).resolvedType.acceptTV(new TypeToDescriptor());
}
public boolean isInCurrPkg(String className) {
for (ClassOrInterface cl : sourceFile.KlassenVektor) {
if (className.equals(cl.getClassName().toString()))
return true;
}
return false;
}
public String getSuperClass(String className) throws NotInCurrentPackageException {
for (ClassOrInterface cl : sourceFile.getClasses()) {
if (className.equals(cl.getClassName().toString())) {
return cl.getSuperClass().getName().toString();
}
}
throw new NotInCurrentPackageException("Class " + className + " is not in the current package.");
}
public ClassOrInterface getClassFromCurrPkg(String className) throws NotInCurrentPackageException {
for (ClassOrInterface cl : sourceFile.KlassenVektor) {
if (className.equals(cl.getClassName().toString()))
return cl;
}
throw new NotInCurrentPackageException("Class of " + className + " is not in the current package.");
}
public String getDesc(String className) throws NotInCurrentPackageException, NotFoundException {
String name = methCall.name;
ClassOrInterface clazz = getClassFromCurrPkg(className);
String retType = getResolvedType(methCall.getType());
ArrayList<String> params = getTypes(methCall.arglist.getArguments());
Map<String, String> genAndBoundsClass = getGenericsAndBounds(clazz.getGenerics());
modifyGenAndBounds(genAndBoundsClass);
for (Method m : clazz.getMethods()) {
if (name.equals(m.getName()) && retType.equals(getResolvedType(m.getReturnType()))) {
ArrayList<String> paramsOfM = getTypes(m.getParameterList());
if(areEquals(params,paramsOfM)) {
Map<String, String> genAndBoundsMethod = getGenericsAndBoundsMethod(m.getGenerics());
modifyGenAndBounds(genAndBoundsMethod);
boolean hasGen = hasGen(m, genAndBoundsClass);
NormalMethod nm = new NormalMethod(m, (HashMap<String, String>) genAndBoundsClass,
(HashMap<String, String>) genAndBoundsMethod, hasGen);
return nm.accept(new DescriptorToString(resultSet));
}
}
}
throw new NotFoundException("Method " + name + " is not found");
}
private boolean areEquals(ArrayList<String> params, ArrayList<String> paramsOfM) {
if(params.size() != paramsOfM.size())
return false;
for(String t : params) {
for(String t2 : paramsOfM) {
if(!t.equals(t2))
return false;
}
}
return true;
}
private ArrayList<String> getTypes(ParameterList parameterList) {
Iterator<FormalParameter> itr = parameterList.iterator();
ArrayList<String> typeList = new ArrayList<>();
while (itr.hasNext()) {
FormalParameter fp = itr.next();
String t = getResolvedType(fp.getType());
typeList.add(t);
}
return typeList;
}
private ArrayList<String> getTypes(List<Expression> arguments) {
ArrayList<String> types = new ArrayList<>();
for(int i = 0; i<arguments.size(); ++i) {
String t = getResolvedType(arguments.get(i).getType());
types.add(t);
}
return types;
}
private boolean hasGen(Method m, Map<String, String> genericsAndBounds) {
String retType = resultSet.resolveType(m.getReturnType()).resolvedType.acceptTV(new TypeToSignature());
/*Prüfe, ob die Rückgabe-Type der Methode eine Type-Variable ist*/
boolean hasGenInParameterList = genericsAndBounds.containsKey(retType) || retType.contains("TPH ") || retType.contains("<");
Map<String,RefTypeOrTPHOrWildcardOrGeneric> methodParamsAndTypes = new HashMap<>();
Iterator<FormalParameter> itr = m.getParameterList().iterator();
while(itr.hasNext()) {
FormalParameter fp = itr.next();
methodParamsAndTypes.put(fp.getName(), resultSet.resolveType(fp.getType()).resolvedType);
}
/*Wenn die Rückgabe-Type eine Typ-variable ist, erzeuge direkt die Signature, wenn nicht,
* prüfe, ob einer der Parameter Typ-Variable als Typ hat*/
if(!hasGenInParameterList) {
for(String paramName : methodParamsAndTypes.keySet()) {
String typeOfParam = methodParamsAndTypes.get(paramName).acceptTV(new TypeToDescriptor());
String sigOfParam = methodParamsAndTypes.get(paramName).acceptTV(new TypeToSignature());
if(genericsAndBounds.containsKey(typeOfParam)||typeOfParam.contains("TPH ")||sigOfParam.contains("<")) {
hasGenInParameterList = true;
break;
}
}
}
return m.getGenerics().iterator().hasNext() || hasGenInParameterList;
}
private Map<String, String> getGenericsAndBoundsMethod(Iterable<? extends GenericTypeVar> generics) {
Map<String, String> genAndBounds = new HashMap<>();
Iterator<? extends GenericTypeVar> itr = generics.iterator();
while (itr.hasNext()) {
GenericTypeVar gtv = itr.next();
getBoundsOfTypeVar(gtv, genAndBounds);
}
return genAndBounds;
}
private void modifyGenAndBounds(Map<String, String> genAndBoundsClass) {
List<String> visited = new ArrayList<>(genAndBoundsClass.size());
Map<String, String> toReplace = new HashMap<>();
for (String tv : genAndBoundsClass.keySet()) {
if (visited.contains(tv))
continue;
List<String> types = new LinkedList<>();
String bound = genAndBoundsClass.get(tv);
types.add(tv);
visited.add(tv);
boolean doReplace = false;
while (genAndBoundsClass.keySet().contains(bound)) {
doReplace = true;
types.add(bound);
visited.add(bound);
bound = genAndBoundsClass.get(bound);
}
if (doReplace) {
for (String tt : types) {
toReplace.put(tt, bound);
}
}
}
for (String key : toReplace.keySet()) {
genAndBoundsClass.replace(key, toReplace.get(key));
}
}
private Map<String, String> getGenericsAndBounds(GenericDeclarationList generics) {
Map<String, String> genAndBounds = new HashMap<>();
Iterator<GenericTypeVar> itr = generics.iterator();
while (itr.hasNext()) {
GenericTypeVar gtv = itr.next();
getBoundsOfTypeVar(gtv, genAndBounds);
}
return genAndBounds;
}
private void getBoundsOfTypeVar(GenericTypeVar g, Map<String, String> genAndBounds) {
Iterator<? extends RefTypeOrTPHOrWildcardOrGeneric> bItr = g.getBounds().iterator();
while (bItr.hasNext()) {
RefTypeOrTPHOrWildcardOrGeneric b = bItr.next();
String boundDesc = b.acceptTV(new TypeToDescriptor());
genAndBounds.put(g.getName(), boundDesc);
}
}
public void generateBCForFunN(String methodDescriptor) {
ByteCodeForFunNGenerator.generateBCForFunN(methCall.arglist,methodDescriptor,path);
}
public String getDescriptorOfApplyMethod(String methodCallType) {
return new DescriptorToString().createDescForFunN(methCall.arglist, methodCallType);
}
/**
* @param methodCall
*/
public void createCheckCast(MethodCall methodCall, MethodVisitor mv) {
String checkCast = getResolvedType(methodCall.getType());
if(!checkCast.contains("TPH ")) {
int pos = checkCast.length();
if(checkCast.contains("<"))
pos = checkCast.indexOf("<");
mv.visitTypeInsn(Opcodes.CHECKCAST,checkCast.substring(0,pos));
}
}
}

View File

@@ -23,7 +23,6 @@ public class MethodFromMethodCall {
this.genericsAndBounds = genericsAndBounds; this.genericsAndBounds = genericsAndBounds;
} }
public ArgumentList getArgList() { public ArgumentList getArgList() {
return argList; return argList;
} }

View File

@@ -1,34 +0,0 @@
/**
*
*/
package de.dhbwstuttgart.bytecode.utilities;
import java.util.Iterator;
import de.dhbwstuttgart.syntaxtree.FormalParameter;
import de.dhbwstuttgart.syntaxtree.Method;
/**
* @author fayez
*
*/
public class MethodUtility {
/**
* Creates an ID for a method
*
* @param resolver type Resolver
* @param method for which the ID will be generated
* @return ID for the given method.
* ID = ReturntypeMethodname(Parametertypes)
*/
public static String createID(Resolver resolver, Method method) {
String id = resolver.getResolvedType(method.getReturnType()) + method.name + "(";
Iterator<FormalParameter> itr = method.getParameterList().iterator();
while (itr.hasNext()) {
FormalParameter fp = itr.next();
id += resolver.getResolvedType(fp.getType());
}
id += ")";
return id;
}
}

View File

@@ -1,145 +0,0 @@
package de.dhbwstuttgart.bytecode.utilities;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
import de.dhbwstuttgart.bytecode.constraint.TPHConstraint;
import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.NameReplacementResult;
import de.dhbwstuttgart.syntaxtree.factory.NameGenerator;
public class NameReplacer {
//TODO rename
private List<TPHConstraint> constraints;
private List<TPHConstraint> allConstraints;
private List<MethodAndTPH> methodAndTPHs;
// TODO rename into tphClass
private List<String> tphs;
private List<String> localTphs;
public NameReplacer(List<TPHConstraint> constraints, List<TPHConstraint> allConstraints,List<String> tphs, ArrayList<String> localTphs) {
super();
this.constraints = constraints;
this.allConstraints = allConstraints;
this.tphs = tphs;
this.localTphs = localTphs;
}
public NameReplacer(List<TPHConstraint> constraints, List<TPHConstraint> allConstraints,List<String> tphs) {
super();
this.constraints = constraints;
this.allConstraints = allConstraints;
this.tphs = tphs;
}
public NameReplacer(List<TPHConstraint> constraints, List<TPHConstraint> allConstraints) {
this.constraints = constraints;
this.allConstraints = allConstraints;
}
public NameReplacer(List<TPHConstraint> constraints, List<TPHConstraint> allConstraints, List<MethodAndTPH> methodAndTPHs,
List<String> tphsClass) {
this.constraints = constraints;
this.allConstraints = allConstraints;
this.methodAndTPHs = methodAndTPHs;
this.tphs = tphsClass;
}
public NameReplacementResult replaceNames() {
String newName = NameGenerator.makeNewName();
List<String> names = new ArrayList<>();
substituteRightSidesWithNewName(newName, names);
substituteNamesInAllConstraints(newName, names);
Stream<ArrayList<String>> tphsOfMethods = methodAndTPHs.stream().map(m->m.getTphs());
Stream<ArrayList<String>> localTphsOfMethods = methodAndTPHs.stream().map(m->m.getLocalTphs());
replaceOldNames(newName, names, tphsOfMethods);
replaceOldNames(newName, names, localTphsOfMethods);
if(tphs.removeAll(names))
tphs.add(newName);
NameReplacementResult res = new NameReplacementResult(newName, names);
return res;
}
/**
* @param newName
* @param names
* @param tphsOfMethods
*/
public void replaceOldNames(final String newName, final List<String> names, Stream<ArrayList<String>> tphsOfMethods) {
tphsOfMethods.forEach(tphsMethod->{
if(tphsMethod.removeAll(names))
tphsMethod.add(newName);
});
}
public NameReplacementResult replaceNamesLocal() {
String newName = NameGenerator.makeNewName();
List<String> names = new ArrayList<>();
substituteRightSidesWithNewName(newName, names);
substituteNamesInAllConstraints(newName, names);
tphs.removeAll(names);
tphs.add(newName);
NameReplacementResult res = new NameReplacementResult(newName, names);
return res;
}
/**
* @param newName
* @param names
*/
public void substituteNamesInAllConstraints(String newName, List<String> names) {
for(TPHConstraint cons : allConstraints) {
if(names.contains(cons.getLeft()))
cons.setLeft(newName);
if(names.contains(cons.getRight()))
cons.setRight(newName);
}
}
/**
* @param newName
* @param names
*/
public void substituteRightSidesWithNewName(String newName, List<String> names) {
for(TPHConstraint cons : constraints) {
names.add(cons.getRight());
cons.setRight(newName);
}
}
public Map<String, List<String>> replaceNamesWithLocals() {
String newName = NameGenerator.makeNewName();
ArrayList<String> names = new ArrayList<>();
for(TPHConstraint cons : constraints) {
names.add(cons.getRight());
cons.setRight(newName);
}
for(TPHConstraint cons : allConstraints) {
if(names.contains(cons.getLeft()))
cons.setLeft(newName);
if(names.contains(cons.getRight()))
cons.setRight(newName);
}
tphs.removeAll(names);
tphs.add(newName);
localTphs.removeAll(names);
localTphs.add(newName);
HashMap<String, List<String>> res = new HashMap<>();
res.put(newName, names);
return res;
}
}

View File

@@ -1,28 +0,0 @@
/**
*
*/
package de.dhbwstuttgart.bytecode.utilities;
import de.dhbwstuttgart.bytecode.descriptor.TypeToDescriptor;
import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric;
import de.dhbwstuttgart.typeinference.result.ResultSet;
/**
* @author fayez
*
*/
public class Resolver {
private ResultSet resultSet;
/**
* @param resultSet
*/
public Resolver(ResultSet resultSet) {
this.resultSet = resultSet;
}
public String getResolvedType(RefTypeOrTPHOrWildcardOrGeneric type) {
return resultSet.resolveType(type).resolvedType.acceptTV(new TypeToDescriptor());
}
}

View File

@@ -0,0 +1,651 @@
package de.dhbwstuttgart.bytecode.utilities;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import org.objectweb.asm.Type;
import de.dhbwstuttgart.bytecode.TPHExtractor;
import de.dhbwstuttgart.bytecode.constraint.EqualConstraint;
import de.dhbwstuttgart.bytecode.constraint.ExtendsConstraint;
import de.dhbwstuttgart.bytecode.constraint.TPHConstraint;
import de.dhbwstuttgart.bytecode.constraint.TPHConstraint.Relation;
import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder;
public class Simplify {
public static HashMap<TPHConstraint, HashSet<String>> simplifyConstraints(String name, TPHExtractor tphExtractor, ArrayList<TypePlaceholder> tphsClass) {
// 1. check if there are any simple cycles like L<R and R<L:
// a) yes => set L=R and:
// * remove both constraints
// * substitute L with R in all constraint
// b)no => go to next step
// 2. check the result of step 1 if there are any equal-constraints like L=R, M=R ..
// a) yes => put all such TPhs in a map and define "key-Cons"
// -- key-Cons = TPH < Object --
// put this Constraint and the
// b) no
// 3. is
// all constraints that will be simplified
ArrayList<TPHConstraint> allCons = tphExtractor.allCons;
ArrayList<TPHConstraint> consToRemove = new ArrayList<>();
// step 1:
for(TPHConstraint c : allCons) {
String left = c.getLeft();
String right = c.getRight();
if(c.getRel() == Relation.EXTENDS) {
TPHConstraint revCon = getReverseConstraint(allCons,left,right);
if(revCon != null) {
revCon.setRel(Relation.EQUAL);
// the reverse constraint is removed because
// otherwise there is the same constraint twice
// (e.g. A<B and B<A => A=B and B=A)
consToRemove.add(revCon);
c.setRel(Relation.EQUAL);
substituteTPH(allCons,left, right);
}
}
}
System.out.println();
System.out.println("NEW ALL CONST: " + allCons.size());
allCons.forEach(c->System.out.println(c.toString()));
System.out.println("----------------");
allCons.removeAll(consToRemove);
consToRemove = new ArrayList<>();
int size = allCons.size();
System.out.println("AFTER DELETE ALL CONST: " + allCons.size());
allCons.forEach(c->System.out.println(c.toString()));
System.out.println("----------------");
HashMap<TPHConstraint, HashSet<String>> result = new HashMap<>();
// check if there is any long cycle (e.g. A<B<C<A)
// to save all types that are in relation
LinkedList<String> allTypes = new LinkedList<>();
// we will put all constraints which are in the cycle, in this ArrayList.
// Later these contraints will be converted to equal-constraints
ArrayList<TPHConstraint> constraints = new ArrayList<>(size);
int visited = 0;
// contains all constraints
HashMap<String,String> ss1 = new HashMap<>();
for(TPHConstraint constr : allCons) {
ss1.put(constr.getLeft(), constr.getRight());
}
for(TPHConstraint c : allCons) {
if(visited >= size)
break;
// Only extends-constraints will be checked
if(c.getRel() == Relation.EXTENDS) {
++visited;
String left = c.getLeft();
String right = c.getRight();
// put the types in linked list
allTypes.add(left);
allTypes.add(right);
constraints.add(c);
boolean isCycle = false;
// iterate through the map to check if there is a cycle
while(ss1.containsKey(right)) {
++visited;
String oldRight = right;
right = ss1.get(right);
TPHConstraint toAdd = getConstraint(oldRight, right, allCons);
if(toAdd != null)
constraints.add(toAdd);
if(left.equals(right)) {
isCycle = true;
break;
}
allTypes.add(right);
}
if(isCycle) {
// convert all constraints to equal constraints
setAllEqual(constraints);
// these constraints will be removed from allCons
consToRemove.addAll(constraints);
// all equal types will be substitute with one type
substituteAllTPH(allCons,constraints,left);
HashSet<String> eq = new HashSet<>();
// put all equal types in a set
for(String t:allTypes) {
eq.add(t);
}
// generate a new constraint (left < Object)
TPHConstraint constraint = new ExtendsConstraint(left, Type.getInternalName(Object.class), Relation.EXTENDS);
// put the generated constraint and its equal set into result set
result.put(constraint, eq);
constraints.clear();
}
allTypes.clear();
}
}
// build an equal set that contains all types
// which are equal and for each equal constraint put left side and right side
// in this set Then generate a constraint type < Object and put it
// with the equal set into the result.
for(TPHConstraint c : allCons) {
if(c.getRel()==Relation.EQUAL) {
if(!isTPHInResEqual(result, c.getLeft())) {
HashSet<String> equalTPHs = getEqualsTPHs(result, c);
TPHConstraint constraint = getKeyConstraint(result,c);
equalTPHs.add(c.getLeft());
equalTPHs.add(c.getRight());
result.put(constraint, equalTPHs);
}
consToRemove.add(c);
size--;
}
}
System.out.println("Step 2 Result: ");
result.forEach((c,hs)->{
System.out.print(c.toString() + " -> ");
hs.forEach(s->{
System.out.print(s + ", ");
});
System.out.println();
});
System.out.println("----------------");
// remove all equal-constraints
allCons.removeAll(consToRemove);
// add all generated constraints to allCons
allCons.addAll(result.keySet());
if(!allCons.isEmpty() && allCons.size()<2) {
TPHConstraint cons = allCons.get(0);
if(!result.containsKey(cons)) {
result.put(cons, null);
result.put(new ExtendsConstraint(cons.getRight(), Type.getInternalName(Object.class), Relation.EXTENDS), null);
}
return result;
}
size += result.keySet().size();
// all constraints which have Object on the right side will
// be ignored, because they are simplified and can not be changed.
for(TPHConstraint c : allCons) {
if(c.getRight().equals(Type.getInternalName(Object.class)))
size--;
}
// get all tph of the method
ArrayList<String> methodTphs = new ArrayList<>();
for(MethodAndTPH m : tphExtractor.ListOfMethodsAndTph) {
if(m.getName().equals(name)) {
methodTphs = m.getTphs();
break;
}
}
// check if there are multiple constraint with the same left side.
// if yes => check if the super type in the method, if not
// then ignore it.
HashMap<String, String> subAndSuper = new HashMap<>();
ArrayList<TPHConstraint> eqCons = new ArrayList<>();
for(TPHConstraint c : allCons) {
if(subAndSuper.containsKey(c.getLeft())) {
LinkedList<String> all = new LinkedList<>();
all.add(c.getLeft());
String sup =c.getRight();
all.add(sup);
HashMap<String, String> ss = new HashMap<>();
for(TPHConstraint constr : allCons) {
ss.put(constr.getLeft(), constr.getRight());
}
while(ss.containsKey(sup)) {
sup = ss.get(sup);
all.add(sup);
}
if(!containTPH(methodTphs, all.getLast()))
continue;
}
if(subAndSuper.containsKey(c.getLeft())) {
System.out.println(c.getLeft());
String r = c.getRight();
String r2 = subAndSuper.get(c.getLeft());
EqualConstraint eq = new EqualConstraint(r2, r, Relation.EQUAL);
eqCons.add(eq);
substituteInMap(subAndSuper,eqCons,allCons,r,r2);
}
subAndSuper.put(c.getLeft(), c.getRight());
}
System.out.println("SAME LEFT SIDE: ");
subAndSuper.forEach((c,hs)->{
if(c!=null) {
System.out.print(c+ " -> " + hs);
}
System.out.println();
});
System.out.println("----------------");
int numOfVisitedPairs = 0;
for(String sub : subAndSuper.keySet()) {
if(isTPHInConstraint(result,sub))
continue;
if(!containTPH(methodTphs,sub))
continue;
if(numOfVisitedPairs>=size)
break;
LinkedList<String> tphInRel = new LinkedList<>();
tphInRel.add(sub);
String superT = subAndSuper.get(sub);
tphInRel.add(superT);
numOfVisitedPairs++;
while(subAndSuper.containsKey(superT)) {
superT = subAndSuper.get(superT);
if(tphInRel.contains(superT)) {
break;
}
tphInRel.add(superT);
numOfVisitedPairs++;
}
// Subtype
String subTphRes = tphInRel.getFirst();
// Die größte Supertype
String superTphRes = tphInRel.getLast();
// if there is any constraint X < subTph, then
// add X at the beginning of the list.
while(subAndSuper.containsValue(subTphRes)) {
for(String tph : subAndSuper.keySet()) {
if(containTPH(methodTphs,tph) && subAndSuper.get(tph).equals(subTphRes)) {
subTphRes = tph;
break;
}
}
if(subTphRes.equals(tphInRel.getFirst())) {
break;
}
if(isTPHInConstraint(result, subTphRes))
break;
tphInRel.addFirst(subTphRes);
numOfVisitedPairs++;
}
subTphRes = tphInRel.getFirst();
// if the last type in the list not a type in method-types
// then find the last type in front of this type, which is
// a type in method-types
int i = 2;
while(!containTPH(methodTphs,superTphRes) && (tphInRel.size()-i) >0) {
superTphRes = tphInRel.get(tphInRel.size()-i);
i++;
}
if(!containTPH(methodTphs, superTphRes)) {
HashSet<String> equals = getEqualsTphsFromEqualCons(eqCons,superTphRes);
if(classTPHSContainsTPH(tphsClass,superTphRes)) {
result.put(new ExtendsConstraint(subTphRes, superTphRes, Relation.EXTENDS), equals);
} else {
result.put(new ExtendsConstraint(subTphRes, Type.getInternalName(Object.class), Relation.EXTENDS), equals);
}
} else {
HashSet<String> equals = getEqualsTphsFromEqualCons(eqCons,subTphRes);
result.put(new ExtendsConstraint(subTphRes, superTphRes, Relation.EXTENDS), equals);
if(!isTPHInConstraint(result, superTphRes) && !isTphInEqualSet(result,superTphRes)) {
HashSet<String> equals2 = getEqualsTphsFromEqualCons(eqCons,superTphRes);
result.put(new ExtendsConstraint(superTphRes, Type.getInternalName(Object.class), Relation.EXTENDS), equals2);
}
}
}
for(String tph : methodTphs) {
if(!isTPHInConstraint(result, tph) && !isTphInEqualSet(result,tph)) {
HashSet<String> equals = getEqualsTphsFromEqualCons(eqCons,tph);
result.put(new ExtendsConstraint(tph, Type.getInternalName(Object.class), Relation.EXTENDS), equals);
}
}
System.out.println("EndResult: ");
result.forEach((c,hs)->{
if(c!=null) {
System.out.print(c.toString() + " -> ");
if(hs == null) {
System.out.print(" [] ");
}else {
hs.forEach(s->{
System.out.print(s + ", ");
});
}
}
System.out.println();
});
System.out.println("----------------");
return result;
}
private static boolean classTPHSContainsTPH(ArrayList<TypePlaceholder> tphsClass, String superTphRes) {
for(TypePlaceholder tph : tphsClass) {
if(tph.getName().equals(superTphRes))
return true;
}
return false;
}
private static boolean isTphInEqualSet(HashMap<TPHConstraint, HashSet<String>> result, String tph) {
for(HashSet<String> hs: result.values()) {
if(hs.contains(tph))
return true;
}
return false;
}
private static HashSet<String> getEqualsTphsFromEqualCons(ArrayList<TPHConstraint> eqCons, String tph) {
HashSet<String> ee = new HashSet<>();
for(TPHConstraint c : eqCons) {
if(c.getLeft().equals(tph))
ee.add(c.getRight());
if(c.getRight().equals(tph))
ee.add(c.getLeft());
}
return ee;
}
private static void substituteInMap(HashMap<String, String> subAndSuper, ArrayList<TPHConstraint> allCons,ArrayList<TPHConstraint> eqCons, String toSubs,
String tph) {
substituteTPH(allCons, toSubs, tph);
if(subAndSuper.containsKey(toSubs) && subAndSuper.containsKey(tph)) {
toSubs = subAndSuper.remove(toSubs);
EqualConstraint eq = new EqualConstraint(subAndSuper.get(tph), toSubs, Relation.EQUAL);
eqCons.add(eq);
substituteInMap(subAndSuper, allCons,eqCons,toSubs, subAndSuper.get(tph));
} else if(subAndSuper.containsKey(toSubs) && !subAndSuper.containsKey(tph)) {
String val = subAndSuper.remove(toSubs);
subAndSuper.put(tph, val);
} else {
for(String k : subAndSuper.keySet()) {
subAndSuper.replace(k, toSubs, tph);
}
}
}
private static TPHConstraint getConstraint(String oldRight, String right, ArrayList<TPHConstraint> allCons) {
for(TPHConstraint c : allCons) {
if(c.getLeft().equals(oldRight) && c.getRight().equals(right))
return c;
}
return null;
}
private static boolean isTPHInResEqual(HashMap<TPHConstraint, HashSet<String>> result, String left) {
for(HashSet<String> eq : result.values()) {
if(eq.contains(left)) {
return true;
}
}
return false;
}
private static void substituteAllTPH(ArrayList<TPHConstraint> allCons, ArrayList<TPHConstraint> constraints,
String first) {
for(TPHConstraint c : allCons) {
for(TPHConstraint c2 : constraints) {
if(c.getRel() == Relation.EXTENDS) {
if(c2.getLeft().equals(c.getLeft()) || c2.getRight().equals(c.getLeft()))
c.setLeft(first);
if(c2.getLeft().equals(c.getRight()) || c2.getRight().equals(c.getRight()))
c.setRight(first);
}
}
}
}
private static void setAllEqual(ArrayList<TPHConstraint> constraints) {
for(TPHConstraint c:constraints) {
c.setRel(Relation.EQUAL);
}
}
public static HashMap<TPHConstraint, HashSet<String>> simplifyContraints(HashMap<TPHConstraint, HashSet<String>> allConstraints) {
// 1. check if there are any cycles like L<R and R<L:
// a) yes => set L=R and:
// * remove both constraints
// * substitute L with R in all constraint
// b)no => go to next step
// 2. check the result of step 1 if there are any equal-constraints like L=R, M=R ..
// a) yes => put all such TPhs in a map and define "key-Cons"
// -- key-Cons = TPH < Object --
// put this Constraint and the
// b) no
// 3. is
ArrayList<TPHConstraint> allCons = new ArrayList<>();
for(TPHConstraint tphCons : allConstraints.keySet()) {
allCons.add(tphCons);
}
ArrayList<TPHConstraint> consToRemove = new ArrayList<>();
// step 1:
for(TPHConstraint c : allCons) {
String left = c.getLeft();
String right = c.getRight();
if(c.getRel() == Relation.EXTENDS) {
TPHConstraint revCon = getReverseConstraint(allCons,left,right);
if(revCon != null) {
revCon.setRel(Relation.EQUAL);
consToRemove.add(revCon);
c.setRel(Relation.EQUAL);
substituteTPH(allCons,left, right);
}
}
}
System.out.println();
System.out.println("NEW ALL CONST: " + allCons.size());
allCons.forEach(c->System.out.println(c.toString()));
System.out.println("----------------");
allCons.removeAll(consToRemove);
consToRemove = new ArrayList<>();
// int size = allCons.size();
System.out.println("AFTER DELETE ALL CONST: " + allCons.size());
allCons.forEach(c->System.out.println(c.toString()));
System.out.println("----------------");
HashMap<TPHConstraint, HashSet<String>> result = new HashMap<>();
for(TPHConstraint c : allCons) {
if(c.getRel()==Relation.EQUAL) {
HashSet<String> equalTPHs = getEqualsTPHs(result, c);
TPHConstraint constraint = getKeyConstraint(result,c);
equalTPHs.add(c.getLeft());
equalTPHs.add(c.getRight());
result.put(constraint, equalTPHs);
consToRemove.add(c);
// size--;
}
}
System.out.println("Step 2 Result: ");
result.forEach((c,hs)->{
System.out.print(c.toString() + " -> ");
hs.forEach(s->{
System.out.print(s + ", ");
});
System.out.println();
});
System.out.println("----------------");
allCons.removeAll(consToRemove);
allCons.addAll(result.keySet());
if(!allCons.isEmpty() && allCons.size()<2) {
if(!result.containsKey(allCons.get(0)))
result.put(allCons.get(0), null);
return result;
}
// size += result.keySet().size();
// for(TPHConstraint c : allCons) {
// if(c.getRight().equals(Type.getInternalName(Object.class)))
// size--;
// }
HashMap<String, String> subAndSuper = new HashMap<>();
for(TPHConstraint c : allCons) {
subAndSuper.put(c.getLeft(), c.getRight());
}
// int numOfVisitedPairs = 0;
for(String sub : subAndSuper.keySet()) {
if(isTPHInConstraint(result,sub))
continue;
// if(numOfVisitedPairs>=size)
// break;
LinkedList<String> tphInRel = new LinkedList<>();
tphInRel.add(sub);
String superT = subAndSuper.get(sub);
tphInRel.add(superT);
// numOfVisitedPairs++;
while(subAndSuper.containsKey(superT)) {
superT = subAndSuper.get(superT);
if(tphInRel.contains(superT)) {
break;
}
tphInRel.add(superT);
// numOfVisitedPairs++;
}
// Subtype
String subTphRes = tphInRel.getFirst();
// Die größte Supertype
String superTphRes = tphInRel.getLast();
while(subAndSuper.containsValue(subTphRes)) {
for(String tph : subAndSuper.keySet()) {
if(subAndSuper.get(tph).equals(subTphRes)) {
subTphRes = tph;
break;
}
}
if(subTphRes.equals(tphInRel.getFirst())) {
break;
}
tphInRel.addFirst(subTphRes);
// numOfVisitedPairs++;
}
subTphRes = tphInRel.getFirst();
int i = 2;
while(superTphRes.equals(Type.getInternalName(Object.class)) && (tphInRel.size()-i) >0) {
superTphRes = tphInRel.get(tphInRel.size()-i);
i++;
}
if(superTphRes.equals(Type.getInternalName(Object.class))) {
result.put(new ExtendsConstraint(subTphRes, Type.getInternalName(Object.class), Relation.EXTENDS), null);
} else {
result.put(new ExtendsConstraint(subTphRes, superTphRes, Relation.EXTENDS), null);
result.put(new ExtendsConstraint(superTphRes, Type.getInternalName(Object.class), Relation.EXTENDS), null);
}
}
System.out.println("EndResult: ");
result.forEach((c,hs)->{
if(c!=null) {
System.out.print(c.toString() + " -> ");
if(hs == null) {
System.out.print(" [] ");
}else {
hs.forEach(s->{
System.out.print(s + ", ");
});
}
}
System.out.println();
});
System.out.println("----------------");
return result;
}
private static void substituteTPH(ArrayList<TPHConstraint> allCons,String left ,String right) {
allCons.forEach(c->{
if(c.getRel() == Relation.EXTENDS) {
if(c.getLeft().equals(left))
c.setLeft(right);
if(c.getRight().equals(left))
c.setRight(right);
}
});
}
private static TPHConstraint getReverseConstraint(ArrayList<TPHConstraint> allCons, String left, String right) {
for(TPHConstraint c : allCons) {
if(c.getLeft().equals(right) && c.getRight().equals(left)){
return c;
}
}
return null;
}
private static boolean isTPHInConstraint(HashMap<TPHConstraint, HashSet<String>> result, String sub) {
for(TPHConstraint c : result.keySet()) {
if(c.getLeft().equals(sub))
return true;
}
return false;
}
private static boolean containTPH(ArrayList<String> methodTphs, String sub) {
for(String tph : methodTphs) {
if(tph.equals(sub))
return true;
}
return false;
}
private static TPHConstraint getKeyConstraint(HashMap<TPHConstraint, HashSet<String>> result, TPHConstraint toFind) {
for(TPHConstraint c : result.keySet()) {
if(c.containTPH(toFind.getLeft()) || c.containTPH(toFind.getRight()))
return c;
}
return new ExtendsConstraint(toFind.getRight(), Type.getInternalName(Object.class), Relation.EXTENDS);
}
private static HashSet<String> getEqualsTPHs(HashMap<TPHConstraint,HashSet<String>> result, TPHConstraint toFind) {
for(TPHConstraint c : result.keySet()) {
if(c.containTPH(toFind.getLeft()) || c.containTPH(toFind.getRight()))
return result.get(c);
}
return new HashSet<>();
}
}

View File

@@ -1,20 +1,22 @@
//PL 2018-12-19: typeInferenceOld nach typeInference uebertragen //PL 2018-12-19: typeInferenceOld nach typeInference uebertragen
package de.dhbwstuttgart.core; package de.dhbwstuttgart.core;
import de.dhbwstuttgart.bytecode.BytecodeGen; 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.CompilationEnvironment;
import de.dhbwstuttgart.parser.JavaTXParser; import de.dhbwstuttgart.parser.JavaTXParser;
import de.dhbwstuttgart.parser.NullToken;
import de.dhbwstuttgart.parser.scope.GenericsRegistry; import de.dhbwstuttgart.parser.scope.GenericsRegistry;
import de.dhbwstuttgart.parser.SyntaxTreeGenerator.SyntaxTreeGenerator; import de.dhbwstuttgart.parser.SyntaxTreeGenerator.SyntaxTreeGenerator;
import de.dhbwstuttgart.parser.antlr.Java8Parser.CompilationUnitContext; import de.dhbwstuttgart.parser.antlr.Java8Parser.CompilationUnitContext;
import de.dhbwstuttgart.parser.scope.JavaClassName; import de.dhbwstuttgart.parser.scope.JavaClassName;
import de.dhbwstuttgart.parser.scope.JavaClassRegistry;
import de.dhbwstuttgart.syntaxtree.ClassOrInterface; import de.dhbwstuttgart.syntaxtree.ClassOrInterface;
import de.dhbwstuttgart.syntaxtree.ParameterList;
import de.dhbwstuttgart.syntaxtree.SourceFile; import de.dhbwstuttgart.syntaxtree.SourceFile;
import de.dhbwstuttgart.syntaxtree.factory.ASTFactory; import de.dhbwstuttgart.syntaxtree.factory.ASTFactory;
import de.dhbwstuttgart.syntaxtree.factory.UnifyTypeFactory; import de.dhbwstuttgart.syntaxtree.factory.UnifyTypeFactory;
import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric;
import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder; import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder;
import de.dhbwstuttgart.syntaxtree.visual.ASTTypePrinter; import de.dhbwstuttgart.syntaxtree.visual.ASTTypePrinter;
import de.dhbwstuttgart.typeinference.constraints.Constraint; import de.dhbwstuttgart.typeinference.constraints.Constraint;
@@ -26,44 +28,40 @@ import de.dhbwstuttgart.typeinference.unify.RuleSet;
import de.dhbwstuttgart.typeinference.unify.TypeUnify; import de.dhbwstuttgart.typeinference.unify.TypeUnify;
import de.dhbwstuttgart.typeinference.unify.distributeVariance; import de.dhbwstuttgart.typeinference.unify.distributeVariance;
import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure; import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure;
import de.dhbwstuttgart.typeinference.unify.model.FiniteClosure;
import de.dhbwstuttgart.typeinference.unify.model.PairOperator; import de.dhbwstuttgart.typeinference.unify.model.PairOperator;
import de.dhbwstuttgart.typeinference.unify.model.PlaceholderType; import de.dhbwstuttgart.typeinference.unify.model.PlaceholderType;
import de.dhbwstuttgart.typeinference.unify.model.UnifyPair; import de.dhbwstuttgart.typeinference.unify.model.UnifyPair;
import de.dhbwstuttgart.typeinference.unify.model.UnifyType; import de.dhbwstuttgart.typeinference.unify.model.UnifyType;
import de.dhbwstuttgart.typeinference.unify.TypeUnifyTask; import de.dhbwstuttgart.typeinference.unify.TypeUnifyTask;
import de.dhbwstuttgart.typeinference.unify.UnifyResultListener;
import de.dhbwstuttgart.typeinference.unify.UnifyResultListenerImpl; import de.dhbwstuttgart.typeinference.unify.UnifyResultListenerImpl;
import de.dhbwstuttgart.typeinference.unify.UnifyResultModel; import de.dhbwstuttgart.typeinference.unify.UnifyResultModel;
import de.dhbwstuttgart.typeinference.unify.UnifyTaskModel;
import java.io.File; import java.io.File;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.FileWriter; import java.io.FileWriter;
import java.io.IOException; import java.io.IOException;
import java.io.Writer;
import java.util.*; import java.util.*;
import java.util.function.Function; import java.util.function.Function;
import java.util.stream.Collectors; import java.util.stream.Collectors;
//import org.apache.commons.io.output.NullOutputStream; import java.util.stream.Stream;
import org.antlr.v4.parse.ANTLRParser.throwsSpec_return;
public class JavaTXCompiler { public class JavaTXCompiler {
//public static JavaTXCompiler INSTANCE;
final CompilationEnvironment environment; final CompilationEnvironment environment;
Boolean resultmodel = true; Boolean resultmodel = true;
public final Map<File, SourceFile> sourceFiles = new HashMap<>(); public final Map<File, SourceFile> sourceFiles = new HashMap<>();
Boolean log = true; //gibt an ob ein Log-File nach System.getProperty("user.dir")+"src/test/java/logFiles" geschrieben werden soll? 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 { public JavaTXCompiler(File sourceFile) throws IOException, ClassNotFoundException {
this(Arrays.asList(sourceFile)); this(Arrays.asList(sourceFile));
//INSTANCE = this;
} }
public JavaTXCompiler(File sourceFile, Boolean log) throws IOException, ClassNotFoundException { public JavaTXCompiler(File sourceFile, Boolean log) throws IOException, ClassNotFoundException {
this(sourceFile); this(sourceFile);
this.log = log; this.log = log;
//INSTANCE = this;
} }
public JavaTXCompiler(List<File> sources) throws IOException, ClassNotFoundException { public JavaTXCompiler(List<File> sources) throws IOException, ClassNotFoundException {
@@ -71,7 +69,6 @@ public class JavaTXCompiler {
for (File s : sources) { for (File s : sources) {
sourceFiles.put(s, parse(s)); sourceFiles.put(s, parse(s));
} }
//INSTANCE = this;
} }
public ConstraintSet<Pair> getConstraints() throws ClassNotFoundException { public ConstraintSet<Pair> getConstraints() throws ClassNotFoundException {
@@ -99,30 +96,16 @@ public class JavaTXCompiler {
Set<ClassOrInterface> allClasses = new HashSet<>(); Set<ClassOrInterface> allClasses = new HashSet<>();
/* PL 2018-09-19 geloescht werden bereits in typeInference hinzugefuegt /* PL 2018-09-19 geloescht werden bereits in typeInference hinzugefuegt
for (SourceFile sf : sourceFiles.values()) {
allClasses.addAll(sf.getClasses());
} }
allClasses.addAll(importedClasses);
return new TYPE(sourceFiles.values(), allClasses).getConstraints();
}
public List<ClassOrInterface> getAvailableClasses(SourceFile forSourceFile) throws ClassNotFoundException {
// PL 2018-09-18: List durch Set ersetzt, damit die Klassen nur einmal
// hinzugefuegt werden
// List<ClassOrInterface> allClasses = new
// ArrayList<>();//environment.getAllAvailableClasses();
Set<ClassOrInterface> allClasses = new HashSet<>();
/*
* PL 2018-09-19 geloescht werden bereits in typeInference hinzugefuegt for
* (SourceFile sf : sourceFiles.values()) { allClasses.addAll(sf.getClasses());
* }
*/ */
List<ClassOrInterface> importedClasses = new ArrayList<>(); List<ClassOrInterface> importedClasses = new ArrayList<>();
for (JavaClassName name : forSourceFile.getImports()) { for (JavaClassName name : forSourceFile.getImports()) {
//TODO: Hier werden imports von eigenen (.jav) Klassen nicht beachtet //TODO: Hier werden imports von eigenen (.jav) Klassen nicht beachtet
ClassOrInterface importedClass = ASTFactory ClassOrInterface importedClass = ASTFactory.createClass(
.createClass(ClassLoader.getSystemClassLoader().loadClass(name.toString())); ClassLoader.getSystemClassLoader().loadClass(name.toString()));
importedClasses.add(importedClass); importedClasses.add(importedClass);
allClasses.addAll(importedClasses); allClasses.addAll(importedClasses);
} }
@@ -130,152 +113,168 @@ public class JavaTXCompiler {
} }
/* /*
* public List<ResultSet> typeInferenceOld() throws ClassNotFoundException { public List<ResultSet> typeInferenceOld() throws ClassNotFoundException {
* List<ClassOrInterface> allClasses = new List<ClassOrInterface> allClasses = new ArrayList<>();//environment.getAllAvailableClasses();
* ArrayList<>();//environment.getAllAvailableClasses(); //Alle Importierten //Alle Importierten Klassen in allen geparsten Sourcefiles kommen ins FC
* Klassen in allen geparsten Sourcefiles kommen ins FC for(SourceFile sf : for(SourceFile sf : this.sourceFiles.values()) {
* this.sourceFiles.values()) { allClasses.addAll(getAvailableClasses(sf)); allClasses.addAll(getAvailableClasses(sf));
* allClasses.addAll(sf.getClasses()); } allClasses.addAll(sf.getClasses());
* }
* final ConstraintSet<Pair> cons = getConstraints();
* final ConstraintSet<Pair> cons = getConstraints();
* FiniteClosure finiteClosure = UnifyTypeFactory.generateFC(allClasses);
* System.out.println(finiteClosure); ConstraintSet<UnifyPair> unifyCons = FiniteClosure finiteClosure = UnifyTypeFactory.generateFC(allClasses);
* UnifyTypeFactory.convert(cons); System.out.println(finiteClosure);
* ConstraintSet<UnifyPair> unifyCons = UnifyTypeFactory.convert(cons);
* TypeUnify unify = new TypeUnify(); Set<Set<UnifyPair>> results = new
* HashSet<>(); try { File logPath = new TypeUnify unify = new TypeUnify();
* File(System.getProperty("user.dir")+"/target/logFiles/"); logPath.mkdirs(); Set<Set<UnifyPair>> results = new HashSet<>();
* FileWriter logFile = new FileWriter(new File(logPath, "log")); try {
* logFile.write("FC:\\" + finiteClosure.toString()+"\n"); for(SourceFile sf : File logPath = new File(System.getProperty("user.dir")+"/target/logFiles/");
* this.sourceFiles.values()) { logFile.write(ASTTypePrinter.print(sf)); } logPath.mkdirs();
* logFile.flush(); Set<List<Constraint<UnifyPair>>> cardProd = FileWriter logFile = new FileWriter(new File(logPath, "log"));
* unifyCons.cartesianProduct(); for (List<Constraint<UnifyPair>> xCons : logFile.write("FC:\\" + finiteClosure.toString()+"\n");
* cardProd ){ Set<UnifyPair> xConsSet = new HashSet<>(); for for(SourceFile sf : this.sourceFiles.values()) {
* (Constraint<UnifyPair> constraint : xCons) { xConsSet.addAll(constraint); } logFile.write(ASTTypePrinter.print(sf));
* //.collect(Collectors.toCollection(ArrayList::new)))) }
* System.out.println(xConsSet); Set<String> methodParaTypeVarNames = logFile.flush();
* allClasses.stream().map(x -> x.getMethods().stream().map(y -> Set<List<Constraint<UnifyPair>>> cardProd = unifyCons.cartesianProduct();
* y.getParameterList().getFormalparalist() .stream().filter(z -> z.getType() for (List<Constraint<UnifyPair>> xCons : cardProd ){
* instanceof TypePlaceholder) .map(z -> Set<UnifyPair> xConsSet = new HashSet<>();
* ((TypePlaceholder)z.getType()).getName()).collect(Collectors.toCollection( for (Constraint<UnifyPair> constraint : xCons) {
* HashSet::new))) .reduce(new HashSet<String>(), (a,b) -> { a.addAll(b); return xConsSet.addAll(constraint);
* a;}, (a,b) -> { a.addAll(b); return a;} ) ) .reduce(new HashSet<String>(), }
* (a,b) -> { a.addAll(b); return a;} ); //.collect(Collectors.toCollection(ArrayList::new))))
* System.out.println(xConsSet);
* Set<String> constructorParaTypeVarNames = allClasses.stream().map(x -> Set<String> methodParaTypeVarNames = allClasses.stream().map(x -> x.getMethods().stream().map(y -> y.getParameterList().getFormalparalist()
* x.getConstructors().stream().map(y -> .stream().filter(z -> z.getType() instanceof TypePlaceholder)
* y.getParameterList().getFormalparalist() .stream().filter(z -> z.getType() .map(z -> ((TypePlaceholder)z.getType()).getName()).collect(Collectors.toCollection(HashSet::new)))
* instanceof TypePlaceholder) .map(z -> .reduce(new HashSet<String>(), (a,b) -> { a.addAll(b); return a;}, (a,b) -> { a.addAll(b); return a;} ) )
* ((TypePlaceholder)z.getType()).getName()).collect(Collectors.toCollection( .reduce(new HashSet<String>(), (a,b) -> { a.addAll(b); return a;} );
* HashSet::new))) .reduce(new HashSet<String>(), (a,b) -> { a.addAll(b); return
* a;}, (a,b) -> { a.addAll(b); return a;} ) ) .reduce(new HashSet<String>(), Set<String> constructorParaTypeVarNames = allClasses.stream().map(x -> x.getConstructors().stream().map(y -> y.getParameterList().getFormalparalist()
* (a,b) -> { a.addAll(b); return a;} ); .stream().filter(z -> z.getType() instanceof TypePlaceholder)
* .map(z -> ((TypePlaceholder)z.getType()).getName()).collect(Collectors.toCollection(HashSet::new)))
* Set<String> paraTypeVarNames = methodParaTypeVarNames; .reduce(new HashSet<String>(), (a,b) -> { a.addAll(b); return a;}, (a,b) -> { a.addAll(b); return a;} ) )
* paraTypeVarNames.addAll(constructorParaTypeVarNames); .reduce(new HashSet<String>(), (a,b) -> { a.addAll(b); return a;} );
*
* Set<String> returnTypeVarNames = allClasses.stream().map(x -> Set<String> paraTypeVarNames = methodParaTypeVarNames;
* x.getMethods().stream().filter(y -> y.getReturnType() instanceof paraTypeVarNames.addAll(constructorParaTypeVarNames);
* TypePlaceholder) .map(z ->
* ((TypePlaceholder)z.getReturnType()).getName()).collect(Collectors. Set<String> returnTypeVarNames = allClasses.stream().map(x -> x.getMethods().stream().filter(y -> y.getReturnType() instanceof TypePlaceholder)
* toCollection(HashSet::new))).reduce((a,b) -> { a.addAll(b); return a;} .map(z -> ((TypePlaceholder)z.getReturnType()).getName()).collect(Collectors.toCollection(HashSet::new))).reduce((a,b) -> { a.addAll(b); return a;} ).get();
* ).get();
* Set<String> fieldTypeVarNames = allClasses.stream().map(x -> x.getFieldDecl().stream().filter(y -> y.getReturnType() instanceof TypePlaceholder)
* Set<String> fieldTypeVarNames = allClasses.stream().map(x -> .map(z -> ((TypePlaceholder)z.getReturnType()).getName()).collect(Collectors.toCollection(HashSet::new))).reduce((a,b) -> { a.addAll(b); return a;} ).get();
* x.getFieldDecl().stream().filter(y -> y.getReturnType() instanceof
* TypePlaceholder) .map(z -> returnTypeVarNames.addAll(fieldTypeVarNames);
* ((TypePlaceholder)z.getReturnType()).getName()).collect(Collectors.
* toCollection(HashSet::new))).reduce((a,b) -> { a.addAll(b); return a;} xConsSet = xConsSet.stream().map(x -> {
* ).get(); //Hier muss ueberlegt werden, ob
* //1. alle Argument- und Retuntyp-Variablen in allen UnifyPairs
* returnTypeVarNames.addAll(fieldTypeVarNames); // mit disableWildcardtable() werden.
* //2. alle Typvariablen mit Argument- oder Retuntyp-Variablen
* xConsSet = xConsSet.stream().map(x -> { //Hier muss ueberlegt werden, ob //1. //in Beziehung auch auf disableWildcardtable() gesetzt werden muessen
* alle Argument- und Retuntyp-Variablen in allen UnifyPairs // mit //PL 2018-04-23
* disableWildcardtable() werden. //2. alle Typvariablen mit Argument- oder if ((x.getLhsType() instanceof PlaceholderType)) {
* Retuntyp-Variablen //in Beziehung auch auf disableWildcardtable() gesetzt if (paraTypeVarNames.contains(x.getLhsType().getName())) {
* werden muessen //PL 2018-04-23 if ((x.getLhsType() instanceof ((PlaceholderType)x.getLhsType()).setVariance((byte)1);
* PlaceholderType)) { if (paraTypeVarNames.contains(x.getLhsType().getName())) ((PlaceholderType)x.getLhsType()).disableWildcardtable();
* { ((PlaceholderType)x.getLhsType()).setVariance((byte)1); }
* ((PlaceholderType)x.getLhsType()).disableWildcardtable(); } if if (returnTypeVarNames.contains(x.getLhsType().getName())) {
* (returnTypeVarNames.contains(x.getLhsType().getName())) { ((PlaceholderType)x.getLhsType()).setVariance((byte)-1);
* ((PlaceholderType)x.getLhsType()).setVariance((byte)-1); ((PlaceholderType)x.getLhsType()).disableWildcardtable();
* ((PlaceholderType)x.getLhsType()).disableWildcardtable(); } } if }
* ((x.getRhsType() instanceof PlaceholderType)) { if }
* (paraTypeVarNames.contains(x.getRhsType().getName())) { if ((x.getRhsType() instanceof PlaceholderType)) {
* ((PlaceholderType)x.getRhsType()).setVariance((byte)1); if (paraTypeVarNames.contains(x.getRhsType().getName())) {
* ((PlaceholderType)x.getRhsType()).disableWildcardtable(); } if ((PlaceholderType)x.getRhsType()).setVariance((byte)1);
* (returnTypeVarNames.contains(x.getRhsType().getName())) { ((PlaceholderType)x.getRhsType()).disableWildcardtable();
* ((PlaceholderType)x.getRhsType()).setVariance((byte)-1); }
* ((PlaceholderType)x.getRhsType()).disableWildcardtable(); } } return x;//HIER if (returnTypeVarNames.contains(x.getRhsType().getName())) {
* DIE JEWEILS RECHT BZW. LINKE SEITE AUF GLEICHE VARIANZ SETZEN WIE DIE JEWEILS ((PlaceholderType)x.getRhsType()).setVariance((byte)-1);
* ANDERE SEITE }).map( y -> { if ((y.getLhsType() instanceof PlaceholderType) ((PlaceholderType)x.getRhsType()).disableWildcardtable();
* && (y.getRhsType() instanceof PlaceholderType)) { if }
* (((PlaceholderType)y.getLhsType()).getVariance() != 0 && }
* ((PlaceholderType)y.getRhsType()).getVariance() == 0) { return x;//HIER DIE JEWEILS RECHT BZW. LINKE SEITE AUF GLEICHE VARIANZ SETZEN WIE DIE JEWEILS ANDERE SEITE
* ((PlaceholderType)y.getRhsType()).setVariance(((PlaceholderType)y.getLhsType( }).map( y -> {
* )).getVariance()); } if (((PlaceholderType)y.getLhsType()).getVariance() == 0 if ((y.getLhsType() instanceof PlaceholderType) && (y.getRhsType() instanceof PlaceholderType)) {
* && ((PlaceholderType)y.getRhsType()).getVariance() != 0) { if (((PlaceholderType)y.getLhsType()).getVariance() != 0 && ((PlaceholderType)y.getRhsType()).getVariance() == 0) {
* ((PlaceholderType)y.getLhsType()).setVariance(((PlaceholderType)y.getRhsType( ((PlaceholderType)y.getRhsType()).setVariance(((PlaceholderType)y.getLhsType()).getVariance());
* )).getVariance()); } } return y; } ) }
* .collect(Collectors.toCollection(HashSet::new)); if (((PlaceholderType)y.getLhsType()).getVariance() == 0 && ((PlaceholderType)y.getRhsType()).getVariance() != 0) {
* varianceInheritance(xConsSet); Set<Set<UnifyPair>> result = ((PlaceholderType)y.getLhsType()).setVariance(((PlaceholderType)y.getRhsType()).getVariance());
* unify.unifySequential(xConsSet, finiteClosure, logFile, log); }
* //Set<Set<UnifyPair>> result = unify.unify(xConsSet, finiteClosure); }
* System.out.println("RESULT: " + result); logFile.write("RES: " + return y; } )
* result.toString()+"\n"); logFile.flush(); results.addAll(result); } .collect(Collectors.toCollection(HashSet::new));
* varianceInheritance(xConsSet);
* results = results.stream().map(x -> { Optional<Set<UnifyPair>> res = new Set<Set<UnifyPair>> result = unify.unifySequential(xConsSet, finiteClosure, logFile, log);
* RuleSet().subst(x.stream().map(y -> { if (y.getPairOp() == //Set<Set<UnifyPair>> result = unify.unify(xConsSet, finiteClosure);
* PairOperator.SMALLERDOTWC) y.setPairOp(PairOperator.EQUALSDOT); return y; System.out.println("RESULT: " + result);
* //alle Paare a <.? b erden durch a =. b ersetzt logFile.write("RES: " + result.toString()+"\n");
* }).collect(Collectors.toCollection(HashSet::new))); if (res.isPresent()) logFile.flush();
* {//wenn subst ein Erg liefert wurde was veraendert return new results.addAll(result);
* TypeUnifyTask().applyTypeUnificationRules(res.get(), finiteClosure); } else }
* return x; //wenn nichts veraendert wurde wird x zurueckgegeben
* }).collect(Collectors.toCollection(HashSet::new)); results = results.stream().map(x -> {
* System.out.println("RESULT Final: " + results); logFile.write("RES_FINAL: " + Optional<Set<UnifyPair>> res = new RuleSet().subst(x.stream().map(y -> {
* results.toString()+"\n"); logFile.flush(); logFile.write("PLACEHOLDERS: " + if (y.getPairOp() == PairOperator.SMALLERDOTWC) y.setPairOp(PairOperator.EQUALSDOT);
* PlaceholderType.EXISTING_PLACEHOLDERS); logFile.flush(); } catch (IOException return y; //alle Paare a <.? b erden durch a =. b ersetzt
* e) { e.printStackTrace(); } return results.stream().map((unifyPairs -> new }).collect(Collectors.toCollection(HashSet::new)));
* ResultSet(UnifyTypeFactory.convert(unifyPairs, if (res.isPresent()) {//wenn subst ein Erg liefert wurde was veraendert
* generateTPHMap(cons))))).collect(Collectors.toList()); } return new TypeUnifyTask().applyTypeUnificationRules(res.get(), finiteClosure);
}
else return x; //wenn nichts veraendert wurde wird x zurueckgegeben
}).collect(Collectors.toCollection(HashSet::new));
System.out.println("RESULT Final: " + results);
logFile.write("RES_FINAL: " + results.toString()+"\n");
logFile.flush();
logFile.write("PLACEHOLDERS: " + PlaceholderType.EXISTING_PLACEHOLDERS);
logFile.flush();
}
catch (IOException e) {
e.printStackTrace();
}
return results.stream().map((unifyPairs ->
new ResultSet(UnifyTypeFactory.convert(unifyPairs, generateTPHMap(cons))))).collect(Collectors.toList());
}
*/ */
/** /**
* Vererbt alle Variancen bei Paaren (a <. theta) oder (Theta <. a) wenn a eine * Vererbt alle Variancen bei Paaren (a <. theta) oder (Theta <. a)
* Variance !=0 hat auf alle Typvariablen in Theta. * wenn a eine Variance !=0 hat auf alle Typvariablen in Theta.
* * @param eq The set of constraints
*
*/ */
/* /*
* private void varianceInheritance(Set<UnifyPair> eq) { Set<PlaceholderType> private void varianceInheritance(Set<UnifyPair> eq) {
* usedTPH = new HashSet<>(); Set<PlaceholderType> phSet = eq.stream().map(x -> Set<PlaceholderType> usedTPH = new HashSet<>();
* { Set<PlaceholderType> pair = new HashSet<>(); if (x.getLhsType() instanceof Set<PlaceholderType> phSet = eq.stream().map(x -> {
* PlaceholderType) pair.add((PlaceholderType)x.getLhsType()); if Set<PlaceholderType> pair = new HashSet<>();
* (x.getRhsType() instanceof PlaceholderType) if (x.getLhsType() instanceof PlaceholderType) pair.add((PlaceholderType)x.getLhsType());
* pair.add((PlaceholderType)x.getRhsType()); return pair; }).reduce(new if (x.getRhsType() instanceof PlaceholderType) pair.add((PlaceholderType)x.getRhsType());
* HashSet<>(), (a,b) -> { a.addAll(b); return a;} , (c,d) -> { c.addAll(d); return pair;
* return c;}); }).reduce(new HashSet<>(), (a,b) -> { a.addAll(b); return a;} , (c,d) -> { c.addAll(d); return c;});
*
* ArrayList<PlaceholderType> phSetVariance = new ArrayList<>(phSet); ArrayList<PlaceholderType> phSetVariance = new ArrayList<>(phSet);
* phSetVariance.removeIf(x -> (x.getVariance() == 0)); phSetVariance.removeIf(x -> (x.getVariance() == 0));
* while(!phSetVariance.isEmpty()) { PlaceholderType a = while(!phSetVariance.isEmpty()) {
* phSetVariance.remove(0); usedTPH.add(a); //HashMap<PlaceholderType,Integer> PlaceholderType a = phSetVariance.remove(0);
* ht = new HashMap<>(); //ht.put(a, a.getVariance()); Set<UnifyPair> eq1 = new usedTPH.add(a);
* HashSet<>(eq); eq1.removeIf(x -> !(x.getLhsType() instanceof PlaceholderType //HashMap<PlaceholderType,Integer> ht = new HashMap<>();
* && ((PlaceholderType)x.getLhsType()).equals(a))); eq1.stream().forEach(x -> { //ht.put(a, a.getVariance());
* x.getRhsType().accept(new distributeVariance(), a.getVariance());}); eq1 = Set<UnifyPair> eq1 = new HashSet<>(eq);
* new HashSet<>(eq); eq1.removeIf(x -> !(x.getRhsType() instanceof eq1.removeIf(x -> !(x.getLhsType() instanceof PlaceholderType && ((PlaceholderType)x.getLhsType()).equals(a)));
* PlaceholderType && ((PlaceholderType)x.getRhsType()).equals(a))); eq1.stream().forEach(x -> { x.getRhsType().accept(new distributeVariance(), a.getVariance());});
* eq1.stream().forEach(x -> { x.getLhsType().accept(new distributeVariance(), eq1 = new HashSet<>(eq);
* a.getVariance());}); phSetVariance = new ArrayList<>(phSet); eq1.removeIf(x -> !(x.getRhsType() instanceof PlaceholderType && ((PlaceholderType)x.getRhsType()).equals(a)));
* phSetVariance.removeIf(x -> (x.getVariance() == 0 || usedTPH.contains(x))); } eq1.stream().forEach(x -> { x.getLhsType().accept(new distributeVariance(), a.getVariance());});
* } phSetVariance = new ArrayList<>(phSet);
phSetVariance.removeIf(x -> (x.getVariance() == 0 || usedTPH.contains(x)));
}
}
*/ */
public UnifyResultModel typeInferenceAsync(UnifyResultListener resultListener, Writer logFile) public UnifyResultModel typeInferenceAsync() throws ClassNotFoundException {
throws ClassNotFoundException {
List<ClassOrInterface> allClasses = new ArrayList<>();//environment.getAllAvailableClasses(); List<ClassOrInterface> allClasses = new ArrayList<>();//environment.getAllAvailableClasses();
//Alle Importierten Klassen in allen geparsten Sourcefiles kommen ins FC //Alle Importierten Klassen in allen geparsten Sourcefiles kommen ins FC
for(SourceFile sf : this.sourceFiles.values()) { for(SourceFile sf : this.sourceFiles.values()) {
@@ -285,23 +284,22 @@ public class JavaTXCompiler {
final ConstraintSet<Pair> cons = getConstraints(); final ConstraintSet<Pair> cons = getConstraints();
Set<Set<UnifyPair>> results = new HashSet<>(); Set<Set<UnifyPair>> results = new HashSet<>();
UnifyResultModel urm = null; UnifyResultModel urm = new UnifyResultModel();
// urm.addUnifyResultListener(resultListener);
try { try {
logFile = logFile == null FileWriter logFile = new FileWriter(new File(System.getProperty("user.dir")+"/src/test/java/logFiles/"+"log_"+sourceFiles.keySet().iterator().next().getName()));
? new FileWriter(new File("log_" + sourceFiles.keySet().iterator().next().getName()))
: logFile;
IFiniteClosure finiteClosure = UnifyTypeFactory.generateFC(allClasses,logFile); IFiniteClosure finiteClosure = UnifyTypeFactory.generateFC(allClasses,logFile);
System.out.println(finiteClosure); System.out.println(finiteClosure);
urm = new UnifyResultModel(cons, finiteClosure);
urm.addUnifyResultListener(resultListener);
ConstraintSet<UnifyPair> unifyCons = UnifyTypeFactory.convert(cons); ConstraintSet<UnifyPair> unifyCons = UnifyTypeFactory.convert(cons);
Function<UnifyPair, UnifyPair> distributeInnerVars = x -> { Function<UnifyPair, UnifyPair> distributeInnerVars =
x -> {
UnifyType lhs, rhs; UnifyType lhs, rhs;
if (((lhs = x.getLhsType()) instanceof PlaceholderType) if (((lhs = x.getLhsType()) instanceof PlaceholderType)
&& ((rhs = x.getRhsType()) instanceof PlaceholderType) && ((rhs = x.getRhsType()) instanceof PlaceholderType)
&& (((PlaceholderType) lhs).isInnerType() || ((PlaceholderType) rhs).isInnerType())) { && (((PlaceholderType)lhs).isInnerType()
|| ((PlaceholderType)rhs).isInnerType()))
{
((PlaceholderType)lhs).setInnerType(true); ((PlaceholderType)lhs).setInnerType(true);
((PlaceholderType)rhs).setInnerType(true); ((PlaceholderType)rhs).setInnerType(true);
} }
@@ -319,58 +317,27 @@ public class JavaTXCompiler {
} }
logFile.flush(); logFile.flush();
Set<String> methodParaTypeVarNames = allClasses.stream().map(x -> x.getMethods().stream() Set<String> methodParaTypeVarNames = allClasses.stream().map(x -> x.getMethods().stream().map(y -> y.getParameterList().getFormalparalist()
.map(y -> y.getParameterList().getFormalparalist().stream() .stream().filter(z -> z.getType() instanceof TypePlaceholder)
.filter(z -> z.getType() instanceof TypePlaceholder) .map(z -> ((TypePlaceholder)z.getType()).getName()).collect(Collectors.toCollection(HashSet::new)))
.map(z -> ((TypePlaceholder) z.getType()).getName()) .reduce(new HashSet<String>(), (a,b) -> { a.addAll(b); return a;}, (a,b) -> { a.addAll(b); return a;} ) )
.collect(Collectors.toCollection(HashSet::new))) .reduce(new HashSet<String>(), (a,b) -> { a.addAll(b); return a;} );
.reduce(new HashSet<String>(), (a, b) -> {
a.addAll(b);
return a;
}, (a, b) -> {
a.addAll(b);
return a;
})).reduce(new HashSet<String>(), (a, b) -> {
a.addAll(b);
return a;
});
Set<String> constructorParaTypeVarNames = allClasses.stream().map(x -> x.getConstructors().stream() Set<String> constructorParaTypeVarNames = allClasses.stream().map(x -> x.getConstructors().stream().map(y -> y.getParameterList().getFormalparalist()
.map(y -> y.getParameterList().getFormalparalist().stream() .stream().filter(z -> z.getType() instanceof TypePlaceholder)
.filter(z -> z.getType() instanceof TypePlaceholder) .map(z -> ((TypePlaceholder)z.getType()).getName()).collect(Collectors.toCollection(HashSet::new)))
.map(z -> ((TypePlaceholder) z.getType()).getName()) .reduce(new HashSet<String>(), (a,b) -> { a.addAll(b); return a;}, (a,b) -> { a.addAll(b); return a;} ) )
.collect(Collectors.toCollection(HashSet::new))) .reduce(new HashSet<String>(), (a,b) -> { a.addAll(b); return a;} );
.reduce(new HashSet<String>(), (a, b) -> {
a.addAll(b);
return a;
}, (a, b) -> {
a.addAll(b);
return a;
})).reduce(new HashSet<String>(), (a, b) -> {
a.addAll(b);
return a;
});
Set<String> paraTypeVarNames = methodParaTypeVarNames; Set<String> paraTypeVarNames = methodParaTypeVarNames;
paraTypeVarNames.addAll(constructorParaTypeVarNames); paraTypeVarNames.addAll(constructorParaTypeVarNames);
Set<String> returnTypeVarNames = allClasses.stream()
.map(x -> x.getMethods().stream().filter(y -> y.getReturnType() instanceof TypePlaceholder)
.map(z -> ((TypePlaceholder) z.getReturnType()).getName())
.collect(Collectors.toCollection(HashSet::new)))
.reduce((a, b) -> {
a.addAll(b);
return a;
}).get();
Set<String> fieldTypeVarNames = allClasses.stream() Set<String> returnTypeVarNames = allClasses.stream().map(x -> x.getMethods().stream().filter(y -> y.getReturnType() instanceof TypePlaceholder)
.map(x -> x.getFieldDecl().stream().filter(y -> y.getReturnType() instanceof TypePlaceholder) .map(z -> ((TypePlaceholder)z.getReturnType()).getName()).collect(Collectors.toCollection(HashSet::new))).reduce((a,b) -> { a.addAll(b); return a;} ).get();
.map(z -> ((TypePlaceholder) z.getReturnType()).getName())
.collect(Collectors.toCollection(HashSet::new))) Set<String> fieldTypeVarNames = allClasses.stream().map(x -> x.getFieldDecl().stream().filter(y -> y.getReturnType() instanceof TypePlaceholder)
.reduce((a, b) -> { .map(z -> ((TypePlaceholder)z.getReturnType()).getName()).collect(Collectors.toCollection(HashSet::new))).reduce((a,b) -> { a.addAll(b); return a;} ).get();
a.addAll(b);
return a;
}).get();
returnTypeVarNames.addAll(fieldTypeVarNames); returnTypeVarNames.addAll(fieldTypeVarNames);
@@ -401,32 +368,31 @@ public class JavaTXCompiler {
((PlaceholderType)x.getRhsType()).disableWildcardtable(); ((PlaceholderType)x.getRhsType()).disableWildcardtable();
} }
} }
return x;// HIER DIE JEWEILS RECHT BZW. LINKE SEITE AUF GLEICHE VARIANZ SETZEN WIE DIE return x;//HIER DIE JEWEILS RECHT BZW. LINKE SEITE AUF GLEICHE VARIANZ SETZEN WIE DIE JEWEILS ANDERE SEITE
// JEWEILS ANDERE SEITE
}); });
Set<PlaceholderType> varianceTPHold; Set<PlaceholderType> varianceTPHold;
Set<PlaceholderType> varianceTPH = new HashSet<>(); Set<PlaceholderType> varianceTPH = new HashSet<>();
varianceTPH = varianceInheritanceConstraintSet(unifyCons); varianceTPH = varianceInheritanceConstraintSet(unifyCons);
/* /* PL 2018-11-07 wird in varianceInheritanceConstraintSet erledigt
* PL 2018-11-07 wird in varianceInheritanceConstraintSet erledigt do { //PL do { //PL 2018-11-05 Huellenbildung Variance auf alle TPHs der Terme auf der jeweiligen
* 2018-11-05 Huellenbildung Variance auf alle TPHs der Terme auf der jeweiligen //anderen Seite übertragen
* //anderen Seite übertragen varianceTPHold = new HashSet<>(varianceTPH); varianceTPHold = new HashSet<>(varianceTPH);
* varianceTPH = varianceInheritanceConstraintSet(unifyCons); unifyCons.map( y varianceTPH = varianceInheritanceConstraintSet(unifyCons);
* -> { if ((y.getLhsType() instanceof PlaceholderType) && (y.getRhsType() unifyCons.map( y -> {
* instanceof PlaceholderType)) { if if ((y.getLhsType() instanceof PlaceholderType) && (y.getRhsType() instanceof PlaceholderType)) {
* (((PlaceholderType)y.getLhsType()).getVariance() != 0 && if (((PlaceholderType)y.getLhsType()).getVariance() != 0 && ((PlaceholderType)y.getRhsType()).getVariance() == 0) {
* ((PlaceholderType)y.getRhsType()).getVariance() == 0) { ((PlaceholderType)y.getRhsType()).setVariance(((PlaceholderType)y.getLhsType()).getVariance());
* ((PlaceholderType)y.getRhsType()).setVariance(((PlaceholderType)y.getLhsType( }
* )).getVariance()); } if (((PlaceholderType)y.getLhsType()).getVariance() == 0 if (((PlaceholderType)y.getLhsType()).getVariance() == 0 && ((PlaceholderType)y.getRhsType()).getVariance() != 0) {
* && ((PlaceholderType)y.getRhsType()).getVariance() != 0) { ((PlaceholderType)y.getLhsType()).setVariance(((PlaceholderType)y.getRhsType()).getVariance());
* ((PlaceholderType)y.getLhsType()).setVariance(((PlaceholderType)y.getRhsType( }
* )).getVariance()); } } return y; } ); } while }
* (!varianceTPHold.equals(varianceTPH)); return y; } ); }
while (!varianceTPHold.equals(varianceTPH));
*/ */
// Set<Set<UnifyPair>> result = unify.unifySequential(xConsSet, finiteClosure, //Set<Set<UnifyPair>> result = unify.unifySequential(xConsSet, finiteClosure, logFile, log);
// logFile, log);
//Set<Set<UnifyPair>> result = unify.unify(xConsSet, finiteClosure); //Set<Set<UnifyPair>> result = unify.unify(xConsSet, finiteClosure);
List<Set<Set<UnifyPair>>> oderConstraints = unifyCons.getOderConstraints().stream().map(x -> { List<Set<Set<UnifyPair>>> oderConstraints = unifyCons.getOderConstraints().stream().map(x -> {
Set<Set<UnifyPair>> ret = new HashSet<>(); Set<Set<UnifyPair>> ret = new HashSet<>();
@@ -435,14 +401,15 @@ public class JavaTXCompiler {
} }
return ret; return ret;
}).collect(Collectors.toCollection(ArrayList::new)); }).collect(Collectors.toCollection(ArrayList::new));
unify.unifyAsync(unifyCons.getUndConstraints(), oderConstraints, finiteClosure, logFile, log, urm, unify.unifyAsync(unifyCons.getUndConstraints(), oderConstraints, finiteClosure, logFile, log, cons, urm);
usedTasks); }
} catch (IOException e) { catch (IOException e) {
System.err.println("kein LogFile"); System.err.println("kein LogFile");
} }
return urm; return urm;
} }
public List<ResultSet> typeInference() throws ClassNotFoundException { public List<ResultSet> typeInference() throws ClassNotFoundException {
List<ClassOrInterface> allClasses = new ArrayList<>();//environment.getAllAvailableClasses(); List<ClassOrInterface> allClasses = new ArrayList<>();//environment.getAllAvailableClasses();
//Alle Importierten Klassen in allen geparsten Sourcefiles kommen ins FC //Alle Importierten Klassen in allen geparsten Sourcefiles kommen ins FC
@@ -454,29 +421,29 @@ public class JavaTXCompiler {
final ConstraintSet<Pair> cons = getConstraints(); final ConstraintSet<Pair> cons = getConstraints();
Set<Set<UnifyPair>> results = new HashSet<>(); Set<Set<UnifyPair>> results = new HashSet<>();
try { try {
Writer logFile = // new OutputStreamWriter(new NullOutputStream()); FileWriter logFile = new FileWriter(new File(System.getProperty("user.dir")+"/src/test/java/logFiles/"+"log_"+sourceFiles.keySet().iterator().next().getName()));
// 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);
System.out.println(finiteClosure); System.out.println(finiteClosure);
ConstraintSet<UnifyPair> unifyCons = UnifyTypeFactory.convert(cons); ConstraintSet<UnifyPair> unifyCons = UnifyTypeFactory.convert(cons);
Function<UnifyPair, UnifyPair> distributeInnerVars = x -> { Function<UnifyPair, UnifyPair> distributeInnerVars =
x -> {
UnifyType lhs, rhs; UnifyType lhs, rhs;
if (((lhs = x.getLhsType()) instanceof PlaceholderType) if (((lhs = x.getLhsType()) instanceof PlaceholderType)
&& ((rhs = x.getRhsType()) instanceof PlaceholderType) && ((rhs = x.getRhsType()) instanceof PlaceholderType)
&& (((PlaceholderType) lhs).isInnerType() || ((PlaceholderType) rhs).isInnerType())) { && (((PlaceholderType)lhs).isInnerType()
|| ((PlaceholderType)rhs).isInnerType()))
{
((PlaceholderType)lhs).setInnerType(true); ((PlaceholderType)lhs).setInnerType(true);
((PlaceholderType)rhs).setInnerType(true); ((PlaceholderType)rhs).setInnerType(true);
} }
return x; return x;
}; };
logFile.write("Unify:" + unifyCons.toString()); logFile.write(unifyCons.toString());
unifyCons = unifyCons.map(distributeInnerVars); unifyCons = unifyCons.map(distributeInnerVars);
logFile.write("\nUnify_distributeInnerVars: " + unifyCons.toString()); logFile.write(unifyCons.toString());
TypeUnify unify = new TypeUnify(); TypeUnify unify = new TypeUnify();
//Set<Set<UnifyPair>> results = new HashSet<>(); Nach vorne gezogen //Set<Set<UnifyPair>> results = new HashSet<>(); Nach vorne gezogen
logFile.write("FC:\\" + finiteClosure.toString()+"\n"); logFile.write("FC:\\" + finiteClosure.toString()+"\n");
@@ -485,58 +452,27 @@ public class JavaTXCompiler {
} }
logFile.flush(); logFile.flush();
Set<String> methodParaTypeVarNames = allClasses.stream().map(x -> x.getMethods().stream() Set<String> methodParaTypeVarNames = allClasses.stream().map(x -> x.getMethods().stream().map(y -> y.getParameterList().getFormalparalist()
.map(y -> y.getParameterList().getFormalparalist().stream() .stream().filter(z -> z.getType() instanceof TypePlaceholder)
.filter(z -> z.getType() instanceof TypePlaceholder) .map(z -> ((TypePlaceholder)z.getType()).getName()).collect(Collectors.toCollection(HashSet::new)))
.map(z -> ((TypePlaceholder) z.getType()).getName()) .reduce(new HashSet<String>(), (a,b) -> { a.addAll(b); return a;}, (a,b) -> { a.addAll(b); return a;} ) )
.collect(Collectors.toCollection(HashSet::new))) .reduce(new HashSet<String>(), (a,b) -> { a.addAll(b); return a;} );
.reduce(new HashSet<String>(), (a, b) -> {
a.addAll(b);
return a;
}, (a, b) -> {
a.addAll(b);
return a;
})).reduce(new HashSet<String>(), (a, b) -> {
a.addAll(b);
return a;
});
Set<String> constructorParaTypeVarNames = allClasses.stream().map(x -> x.getConstructors().stream() Set<String> constructorParaTypeVarNames = allClasses.stream().map(x -> x.getConstructors().stream().map(y -> y.getParameterList().getFormalparalist()
.map(y -> y.getParameterList().getFormalparalist().stream() .stream().filter(z -> z.getType() instanceof TypePlaceholder)
.filter(z -> z.getType() instanceof TypePlaceholder) .map(z -> ((TypePlaceholder)z.getType()).getName()).collect(Collectors.toCollection(HashSet::new)))
.map(z -> ((TypePlaceholder) z.getType()).getName()) .reduce(new HashSet<String>(), (a,b) -> { a.addAll(b); return a;}, (a,b) -> { a.addAll(b); return a;} ) )
.collect(Collectors.toCollection(HashSet::new))) .reduce(new HashSet<String>(), (a,b) -> { a.addAll(b); return a;} );
.reduce(new HashSet<String>(), (a, b) -> {
a.addAll(b);
return a;
}, (a, b) -> {
a.addAll(b);
return a;
})).reduce(new HashSet<String>(), (a, b) -> {
a.addAll(b);
return a;
});
Set<String> paraTypeVarNames = methodParaTypeVarNames; Set<String> paraTypeVarNames = methodParaTypeVarNames;
paraTypeVarNames.addAll(constructorParaTypeVarNames); paraTypeVarNames.addAll(constructorParaTypeVarNames);
Set<String> returnTypeVarNames = allClasses.stream()
.map(x -> x.getMethods().stream().filter(y -> y.getReturnType() instanceof TypePlaceholder)
.map(z -> ((TypePlaceholder) z.getReturnType()).getName())
.collect(Collectors.toCollection(HashSet::new)))
.reduce((a, b) -> {
a.addAll(b);
return a;
}).get();
Set<String> fieldTypeVarNames = allClasses.stream() Set<String> returnTypeVarNames = allClasses.stream().map(x -> x.getMethods().stream().filter(y -> y.getReturnType() instanceof TypePlaceholder)
.map(x -> x.getFieldDecl().stream().filter(y -> y.getReturnType() instanceof TypePlaceholder) .map(z -> ((TypePlaceholder)z.getReturnType()).getName()).collect(Collectors.toCollection(HashSet::new))).reduce((a,b) -> { a.addAll(b); return a;} ).get();
.map(z -> ((TypePlaceholder) z.getReturnType()).getName())
.collect(Collectors.toCollection(HashSet::new))) Set<String> fieldTypeVarNames = allClasses.stream().map(x -> x.getFieldDecl().stream().filter(y -> y.getReturnType() instanceof TypePlaceholder)
.reduce((a, b) -> { .map(z -> ((TypePlaceholder)z.getReturnType()).getName()).collect(Collectors.toCollection(HashSet::new))).reduce((a,b) -> { a.addAll(b); return a;} ).get();
a.addAll(b);
return a;
}).get();
returnTypeVarNames.addAll(fieldTypeVarNames); returnTypeVarNames.addAll(fieldTypeVarNames);
@@ -567,32 +503,31 @@ public class JavaTXCompiler {
((PlaceholderType)x.getRhsType()).disableWildcardtable(); ((PlaceholderType)x.getRhsType()).disableWildcardtable();
} }
} }
return x;// HIER DIE JEWEILS RECHT BZW. LINKE SEITE AUF GLEICHE VARIANZ SETZEN WIE DIE return x;//HIER DIE JEWEILS RECHT BZW. LINKE SEITE AUF GLEICHE VARIANZ SETZEN WIE DIE JEWEILS ANDERE SEITE
// JEWEILS ANDERE SEITE
}); });
Set<PlaceholderType> varianceTPHold; Set<PlaceholderType> varianceTPHold;
Set<PlaceholderType> varianceTPH = new HashSet<>(); Set<PlaceholderType> varianceTPH = new HashSet<>();
varianceTPH = varianceInheritanceConstraintSet(unifyCons); varianceTPH = varianceInheritanceConstraintSet(unifyCons);
/* /* PL 2018-11-07 wird in varianceInheritanceConstraintSet erledigt
* PL 2018-11-07 wird in varianceInheritanceConstraintSet erledigt do { //PL do { //PL 2018-11-05 Huellenbildung Variance auf alle TPHs der Terme auf der jeweiligen
* 2018-11-05 Huellenbildung Variance auf alle TPHs der Terme auf der jeweiligen //anderen Seite übertragen
* //anderen Seite übertragen varianceTPHold = new HashSet<>(varianceTPH); varianceTPHold = new HashSet<>(varianceTPH);
* varianceTPH = varianceInheritanceConstraintSet(unifyCons); unifyCons.map( y varianceTPH = varianceInheritanceConstraintSet(unifyCons);
* -> { if ((y.getLhsType() instanceof PlaceholderType) && (y.getRhsType() unifyCons.map( y -> {
* instanceof PlaceholderType)) { if if ((y.getLhsType() instanceof PlaceholderType) && (y.getRhsType() instanceof PlaceholderType)) {
* (((PlaceholderType)y.getLhsType()).getVariance() != 0 && if (((PlaceholderType)y.getLhsType()).getVariance() != 0 && ((PlaceholderType)y.getRhsType()).getVariance() == 0) {
* ((PlaceholderType)y.getRhsType()).getVariance() == 0) { ((PlaceholderType)y.getRhsType()).setVariance(((PlaceholderType)y.getLhsType()).getVariance());
* ((PlaceholderType)y.getRhsType()).setVariance(((PlaceholderType)y.getLhsType( }
* )).getVariance()); } if (((PlaceholderType)y.getLhsType()).getVariance() == 0 if (((PlaceholderType)y.getLhsType()).getVariance() == 0 && ((PlaceholderType)y.getRhsType()).getVariance() != 0) {
* && ((PlaceholderType)y.getRhsType()).getVariance() != 0) { ((PlaceholderType)y.getLhsType()).setVariance(((PlaceholderType)y.getRhsType()).getVariance());
* ((PlaceholderType)y.getLhsType()).setVariance(((PlaceholderType)y.getRhsType( }
* )).getVariance()); } } return y; } ); } while }
* (!varianceTPHold.equals(varianceTPH)); return y; } ); }
while (!varianceTPHold.equals(varianceTPH));
*/ */
// Set<Set<UnifyPair>> result = unify.unifySequential(xConsSet, finiteClosure, //Set<Set<UnifyPair>> result = unify.unifySequential(xConsSet, finiteClosure, logFile, log);
// logFile, log);
//Set<Set<UnifyPair>> result = unify.unify(xConsSet, finiteClosure); //Set<Set<UnifyPair>> result = unify.unify(xConsSet, finiteClosure);
List<Set<Set<UnifyPair>>> oderConstraints = unifyCons.getOderConstraints().stream().map(x -> { List<Set<Set<UnifyPair>>> oderConstraints = unifyCons.getOderConstraints().stream().map(x -> {
Set<Set<UnifyPair>> ret = new HashSet<>(); Set<Set<UnifyPair>> ret = new HashSet<>();
@@ -603,11 +538,10 @@ public class JavaTXCompiler {
}).collect(Collectors.toCollection(ArrayList::new)); }).collect(Collectors.toCollection(ArrayList::new));
if (resultmodel) { if (resultmodel) {
/* UnifyResultModel Anfang */ /* UnifyResultModel Anfang */
UnifyResultModel urm = new UnifyResultModel(cons, finiteClosure); UnifyResultModel urm = new UnifyResultModel();
UnifyResultListenerImpl li = new UnifyResultListenerImpl(); UnifyResultListenerImpl li = new UnifyResultListenerImpl();
urm.addUnifyResultListener(li); urm.addUnifyResultListener(li);
unify.unifyParallel(unifyCons.getUndConstraints(), oderConstraints, finiteClosure, logFile, log, urm, unify.unifyParallel(unifyCons.getUndConstraints(), oderConstraints, finiteClosure, logFile, log, cons, urm);
usedTasks);
System.out.println("RESULT Final: " + li.getResults()); System.out.println("RESULT Final: " + li.getResults());
logFile.write("RES_FINAL: " + li.getResults().toString()+"\n"); logFile.write("RES_FINAL: " + li.getResults().toString()+"\n");
logFile.flush(); logFile.flush();
@@ -615,64 +549,53 @@ public class JavaTXCompiler {
} }
/* UnifyResultModel End */ /* UnifyResultModel End */
else { else {
// Set<Set<UnifyPair>> result = unify.unify(unifyCons.getUndConstraints(), Set<Set<UnifyPair>> result = unify.unify(unifyCons.getUndConstraints(), oderConstraints, finiteClosure, logFile, log, cons);
// oderConstraints, finiteClosure, logFile, log, new UnifyResultModel(cons, //Set<Set<UnifyPair>> result = unify.unifyOderConstraints(unifyCons.getUndConstraints(), oderConstraints, finiteClosure, logFile, log, cons);
// finiteClosure));
Set<Set<UnifyPair>> result = unify.unifyOderConstraints(unifyCons.getUndConstraints(), oderConstraints,
finiteClosure, logFile, log, new UnifyResultModel(cons, finiteClosure), usedTasks);
System.out.println("RESULT: " + result); System.out.println("RESULT: " + result);
logFile.write("RES: " + result.toString()+"\n"); logFile.write("RES: " + result.toString()+"\n");
logFile.flush(); logFile.flush();
results.addAll(result); results.addAll(result);
results = results.stream().map(x -> { results = results.stream().map(x -> {
Optional<Set<UnifyPair>> res = new RuleSet().subst(x.stream().map(y -> { Optional<Set<UnifyPair>> res = new RuleSet().subst(x.stream().map(y -> {
if (y.getPairOp() == PairOperator.SMALLERDOTWC) if (y.getPairOp() == PairOperator.SMALLERDOTWC) y.setPairOp(PairOperator.EQUALSDOT);
y.setPairOp(PairOperator.EQUALSDOT);
return y; //alle Paare a <.? b erden durch a =. b ersetzt return y; //alle Paare a <.? b erden durch a =. b ersetzt
}).collect(Collectors.toCollection(HashSet::new))); }).collect(Collectors.toCollection(HashSet::new)));
if (res.isPresent()) {//wenn subst ein Erg liefert wurde was veraendert if (res.isPresent()) {//wenn subst ein Erg liefert wurde was veraendert
return new TypeUnifyTask().applyTypeUnificationRules(res.get(), finiteClosure); return new TypeUnifyTask().applyTypeUnificationRules(res.get(), finiteClosure);
} else }
return x; // wenn nichts veraendert wurde wird x zurueckgegeben else return x; //wenn nichts veraendert wurde wird x zurueckgegeben
}).collect(Collectors.toCollection(HashSet::new)); }).collect(Collectors.toCollection(HashSet::new));
System.out.println("RESULT Final: " + results); System.out.println("RESULT Final: " + results);
logFile.write("RES_FINAL: " + results.toString()+"\n"); logFile.write("RES_FINAL: " + results.toString()+"\n");
logFile.flush(); logFile.flush();
logFile.write("PLACEHOLDERS: " + PlaceholderType.EXISTING_PLACEHOLDERS); logFile.write("PLACEHOLDERS: " + PlaceholderType.EXISTING_PLACEHOLDERS);
logFile.flush(); logFile.flush();
} }}
} catch (IOException e) { catch (IOException e) {
System.err.println("kein LogFile"); System.err.println("kein LogFile");
} }
return results.stream() return results.stream().map((unifyPairs ->
.map((unifyPairs -> new ResultSet(UnifyTypeFactory.convert(unifyPairs, Pair.generateTPHMap(cons))))) new ResultSet(UnifyTypeFactory.convert(unifyPairs, Pair.generateTPHMap(cons))))).collect(Collectors.toList());
.collect(Collectors.toList());
} }
/** /**
* Vererbt alle Variancen bei Paaren (a <. theta) oder (Theta <. a) wenn a eine * Vererbt alle Variancen bei Paaren (a <. theta) oder (Theta <. a)
* Variance !=0 hat auf alle Typvariablen in Theta. * wenn a eine Variance !=0 hat auf alle Typvariablen in Theta.
* * @param eq The set of constraints
*
*/ */
private Set<PlaceholderType> varianceInheritanceConstraintSet(ConstraintSet<UnifyPair> cons) { private Set<PlaceholderType> varianceInheritanceConstraintSet(ConstraintSet<UnifyPair> cons) {
Set<UnifyPair> eq = cons.getAll(); Set<UnifyPair> eq = cons.getAll();
Set<PlaceholderType> usedTPH = new HashSet<>(); Set<PlaceholderType> usedTPH = new HashSet<>();
Set<PlaceholderType> phSet = eq.stream().map(x -> { Set<PlaceholderType> phSet = eq.stream().map(x -> {
Set<PlaceholderType> pair = new HashSet<>(); Set<PlaceholderType> pair = new HashSet<>();
if (x.getLhsType() instanceof PlaceholderType) if (x.getLhsType() instanceof PlaceholderType) pair.add((PlaceholderType)x.getLhsType());
pair.add((PlaceholderType) x.getLhsType()); if (x.getRhsType() instanceof PlaceholderType) pair.add((PlaceholderType)x.getRhsType());
if (x.getRhsType() instanceof PlaceholderType)
pair.add((PlaceholderType) x.getRhsType());
return pair; return pair;
}).reduce(new HashSet<>(), (a, b) -> { }).reduce(new HashSet<>(), (a,b) -> { a.addAll(b); return a;} , (c,d) -> { c.addAll(d); return c;});
a.addAll(b);
return a;
}, (c, d) -> {
c.addAll(d);
return c;
});
ArrayList<PlaceholderType> phSetVariance = new ArrayList<>(phSet); ArrayList<PlaceholderType> phSetVariance = new ArrayList<>(phSet);
phSetVariance.removeIf(x -> (x.getVariance() == 0)); phSetVariance.removeIf(x -> (x.getVariance() == 0));
@@ -682,8 +605,7 @@ public class JavaTXCompiler {
//HashMap<PlaceholderType,Integer> ht = new HashMap<>(); //HashMap<PlaceholderType,Integer> ht = new HashMap<>();
//ht.put(a, a.getVariance()); //ht.put(a, a.getVariance());
//ConstraintSet<UnifyPair> eq1 = cons; //ConstraintSet<UnifyPair> eq1 = cons;
// eq1.removeIf(x -> !(x.getLhsType() instanceof PlaceholderType && //eq1.removeIf(x -> !(x.getLhsType() instanceof PlaceholderType && ((PlaceholderType)x.getLhsType()).equals(a)));
// ((PlaceholderType)x.getLhsType()).equals(a)));
//durch if-Abfrage im foreach geloest //durch if-Abfrage im foreach geloest
cons.forEach(x -> { cons.forEach(x -> {
if (x.getLhsType() instanceof PlaceholderType && ((PlaceholderType)x.getLhsType()).equals(a)) { if (x.getLhsType() instanceof PlaceholderType && ((PlaceholderType)x.getLhsType()).equals(a)) {
@@ -691,95 +613,38 @@ public class JavaTXCompiler {
} }
}); });
//` eq1 = new HashSet<>(eq); //` eq1 = new HashSet<>(eq);
// eq1.removeIf(x -> !(x.getRhsType() instanceof PlaceholderType && //eq1.removeIf(x -> !(x.getRhsType() instanceof PlaceholderType && ((PlaceholderType)x.getRhsType()).equals(a)));
// ((PlaceholderType)x.getRhsType()).equals(a)));
//durch if-Abfrage im foreach geloest //durch if-Abfrage im foreach geloest
cons.forEach(x -> { cons.forEach(x -> {
if (x.getRhsType() instanceof PlaceholderType && ((PlaceholderType)x.getRhsType()).equals(a)) { if (x.getRhsType() instanceof PlaceholderType && ((PlaceholderType)x.getRhsType()).equals(a)) {
x.getLhsType().accept(new distributeVariance(), a.getVariance()); x.getLhsType().accept(new distributeVariance(), a.getVariance());
} }
}); });
phSetVariance = new ArrayList<>(phSet); // macht vermutlich keinen Sinn PL 2018-10-18, doch, es koennen neue phSetVariance = new ArrayList<>(phSet); //macht vermutlich keinen Sinn PL 2018-10-18, doch, es koennen neue TPHs mit Variancen dazugekommen sein PL 2018-11-07
// TPHs mit Variancen dazugekommen sein PL 2018-11-07
phSetVariance.removeIf(x -> (x.getVariance() == 0 || usedTPH.contains(x))); phSetVariance.removeIf(x -> (x.getVariance() == 0 || usedTPH.contains(x)));
} }
return usedTPH; return usedTPH;
} }
private SourceFile parse(File sourceFile) throws IOException, java.lang.ClassNotFoundException { private SourceFile parse(File sourceFile) throws IOException, java.lang.ClassNotFoundException {
CompilationUnitContext tree = JavaTXParser.parse(sourceFile); CompilationUnitContext tree = JavaTXParser.parse(sourceFile);
SyntaxTreeGenerator generator = new SyntaxTreeGenerator(environment.getRegistry(sourceFile), SyntaxTreeGenerator generator = new SyntaxTreeGenerator(environment.getRegistry(sourceFile), new GenericsRegistry(null));
new GenericsRegistry(null));
SourceFile ret = generator.convert(tree, environment.packageCrawler); SourceFile ret = generator.convert(tree, environment.packageCrawler);
return ret; return ret;
} }
// um pfad erweitern
public synchronized void generateBytecodForFile(String path, /* HashMap<String, byte[]> classFiles,*/ SourceFile sf, public void generateBytecode(String path) throws ClassNotFoundException, IOException {
List<ResultSet> typeinferenceResult, List<GenericGenratorResultForSourceFile> genericResultsRet) throws IOException { for(File f : sourceFiles.keySet()) {
//genericResultsRet is empty; fuer die Rückgabe
try {
HashMap<String,byte[]> classFiles = new HashMap<>(); HashMap<String,byte[]> classFiles = new HashMap<>();
SourceFile sf = sourceFiles.get(f);
List<GenericGenratorResultForSourceFile> genericResults = getGeneratedGenericResultsForAllSourceFiles(typeinferenceResult); List<ResultSet> typeinferenceResult = this.typeInference();
genericResultsRet.addAll(genericResults);//fuer Rueckgabe BytecodeGen bytecodeGen = new BytecodeGen(classFiles,typeinferenceResult,sf,path);
BytecodeGen bytecodeGen = new BytecodeGen(classFiles,typeinferenceResult, genericResults, sf,path); // BytecodeGen bytecodeGen = new BytecodeGen(classFiles,typeinferenceResult.get(0));
bytecodeGen.visit(sf); bytecodeGen.visit(sf);
this.writeClassFile(bytecodeGen.getClassFiles(), path); this.writeClassFile(bytecodeGen.getClassFiles(), path);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public List<GenericGenratorResultForSourceFile> getGeneratedGenericResultsForAllSourceFiles()
throws ClassNotFoundException {
List<GenericGenratorResultForSourceFile> result = new ArrayList<>();
for (File f : sourceFiles.keySet()) {
SourceFile sf = sourceFiles.get(f);
List<ResultSet> typeinferenceResult = this.typeInference();
GeneratedGenericsFinder sResFinder = new GeneratedGenericsFinder(sf, typeinferenceResult);
GenericGenratorResultForSourceFile simplifyResOfSF = sResFinder.findGeneratedGenerics();
result.add(simplifyResOfSF);
}
return result;
}
public List<GenericGenratorResultForSourceFile> getGeneratedGenericResultsForAllSourceFiles(
List<ResultSet> typeinferenceResult) throws ClassNotFoundException {
List<GenericGenratorResultForSourceFile> result = new ArrayList<>();
for (File f : sourceFiles.keySet()) {
SourceFile sf = sourceFiles.get(f);
GeneratedGenericsFinder sResFinder = new GeneratedGenericsFinder(sf, typeinferenceResult);
GenericGenratorResultForSourceFile simplifyResOfSF = sResFinder.findGeneratedGenerics();
result.add(simplifyResOfSF);
}
return result;
}
// um pfad erweitern
public void generateBytecode(String path) throws ClassNotFoundException, IOException, BytecodeGeneratorError {
List<ResultSet> typeinferenceResult = this.typeInference();
List<GenericGenratorResultForSourceFile> simplifyResultsForAllSourceFiles = getGeneratedGenericResultsForAllSourceFiles(
typeinferenceResult);
generateBytecode(path, typeinferenceResult, simplifyResultsForAllSourceFiles);
}
/**
* @param path
* @param typeinferenceResult
* @param simplifyResultsForAllSourceFiles
* @throws IOException
*/
public void generateBytecode(String path, List<ResultSet> typeinferenceResult,
List<GenericGenratorResultForSourceFile> simplifyResultsForAllSourceFiles) throws IOException {
for (File f : sourceFiles.keySet()) {
HashMap<String, byte[]> classFiles = new HashMap<>();
SourceFile sf = sourceFiles.get(f);
BytecodeGen bytecodeGen = new BytecodeGen(classFiles, typeinferenceResult, simplifyResultsForAllSourceFiles,
sf, path);
bytecodeGen.visit(sf);
writeClassFile(bytecodeGen.getClassFiles(), path);
} }
} }
@@ -788,13 +653,11 @@ public class JavaTXCompiler {
for(String name : classFiles.keySet()) { for(String name : classFiles.keySet()) {
byte[] bytecode = classFiles.get(name); byte[] bytecode = classFiles.get(name);
System.out.println("generating "+name+ ".class file ..."); System.out.println("generating "+name+ ".class file ...");
// output = new FileOutputStream(new File(System.getProperty("user.dir") + //output = new FileOutputStream(new File(System.getProperty("user.dir") + "/testBytecode/generatedBC/" +name+".class"));
// "/testBytecode/generatedBC/" +name+".class"));
output = new FileOutputStream(new File(path +name+".class")); output = new FileOutputStream(new File(path +name+".class"));
output.write(bytecode); output.write(bytecode);
output.close(); output.close();
System.out.println(name+".class file generated"); System.out.println(name+".class file generated");
} }
} }
} }

View File

@@ -35,7 +35,7 @@ public class SyntaxTreeGenerator{
Set<JavaClassName> imports = new HashSet(); Set<JavaClassName> imports = new HashSet();
private Map<String, RefTypeOrTPHOrWildcardOrGeneric> fields = new HashMap<>(); //PL 2018-11-01 fields eingefuegt, damit die fields immer die gleiche TPH bekommen private Map<String, RefTypeOrTPHOrWildcardOrGeneric> fields = new HashMap<>(); //PL 2018-11-01 fields eingefuegt, damit die fields immer die gleiche TPH bekommen
List<Statement> fieldInitializations = new ArrayList<>(); //PL 2019-10-23: Muss für jede Klasse neu initilisiert werden List<Statement> fieldInitializations = new ArrayList<>();
public SyntaxTreeGenerator(JavaClassRegistry reg, GenericsRegistry globalGenerics){ public SyntaxTreeGenerator(JavaClassRegistry reg, GenericsRegistry globalGenerics){
//Die Generics müssen während des Bauens des AST erstellt werden, //Die Generics müssen während des Bauens des AST erstellt werden,
@@ -159,7 +159,6 @@ public class SyntaxTreeGenerator{
private ClassOrInterface convertClass(Java8Parser.ClassDeclarationContext ctx) { private ClassOrInterface convertClass(Java8Parser.ClassDeclarationContext ctx) {
ClassOrInterface newClass; ClassOrInterface newClass;
fieldInitializations = new ArrayList<>(); //PL 2019-10-22: muss für jede Klasse neu initilisiert werden
if(ctx.normalClassDeclaration() != null){ if(ctx.normalClassDeclaration() != null){
newClass = convertNormal(ctx.normalClassDeclaration()); newClass = convertNormal(ctx.normalClassDeclaration());
} }
@@ -359,7 +358,7 @@ public class SyntaxTreeGenerator{
&& fieldDeclarationContext.unannTypeOrAuto().unannType() != null){ && fieldDeclarationContext.unannTypeOrAuto().unannType() != null){
fieldType = TypeGenerator.convert(fieldDeclarationContext.unannTypeOrAuto().unannType(), reg, generics); fieldType = TypeGenerator.convert(fieldDeclarationContext.unannTypeOrAuto().unannType(), reg, generics);
}else{ }else{
fieldType = TypePlaceholder.fresh(fieldDeclarationContext.variableDeclaratorList().getStart()); //PL 2019-12-06: variableDeclaratorList() eingefuegt, um als Token nicht die Modifier zu bekommen fieldType = TypePlaceholder.fresh(fieldDeclarationContext.getStart());
} }
for(Java8Parser.VariableDeclaratorContext varCtx : fieldDeclarationContext.variableDeclaratorList().variableDeclarator()){ for(Java8Parser.VariableDeclaratorContext varCtx : fieldDeclarationContext.variableDeclaratorList().variableDeclarator()){
String fieldName = convert(varCtx.variableDeclaratorId()); String fieldName = convert(varCtx.variableDeclaratorId());

View File

@@ -3,37 +3,31 @@ package de.dhbwstuttgart.parser.SyntaxTreeGenerator;
import de.dhbwstuttgart.exceptions.NotImplementedException; import de.dhbwstuttgart.exceptions.NotImplementedException;
import de.dhbwstuttgart.exceptions.TypeinferenceException; import de.dhbwstuttgart.exceptions.TypeinferenceException;
import de.dhbwstuttgart.parser.antlr.Java8Parser; import de.dhbwstuttgart.parser.antlr.Java8Parser;
import de.dhbwstuttgart.parser.antlr.Java8Parser.UnannClassType_lfno_unannClassOrInterfaceTypeContext;
import de.dhbwstuttgart.parser.scope.GenericsRegistry; import de.dhbwstuttgart.parser.scope.GenericsRegistry;
import de.dhbwstuttgart.parser.scope.JavaClassName; import de.dhbwstuttgart.parser.scope.JavaClassName;
import de.dhbwstuttgart.parser.scope.JavaClassRegistry; import de.dhbwstuttgart.parser.scope.JavaClassRegistry;
import de.dhbwstuttgart.syntaxtree.GenericDeclarationList; import de.dhbwstuttgart.syntaxtree.GenericDeclarationList;
import de.dhbwstuttgart.syntaxtree.GenericTypeVar; import de.dhbwstuttgart.syntaxtree.GenericTypeVar;
import de.dhbwstuttgart.syntaxtree.factory.ASTFactory; import de.dhbwstuttgart.syntaxtree.factory.ASTFactory;
import de.dhbwstuttgart.syntaxtree.type.ExtendsWildcardType;
import de.dhbwstuttgart.syntaxtree.type.GenericRefType; import de.dhbwstuttgart.syntaxtree.type.GenericRefType;
import de.dhbwstuttgart.syntaxtree.type.RefType; import de.dhbwstuttgart.syntaxtree.type.RefType;
import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric; import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric;
import de.dhbwstuttgart.syntaxtree.type.SuperWildcardType;
import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder; import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder;
import org.antlr.v4.runtime.Token; import org.antlr.v4.runtime.Token;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TypeGenerator { public class TypeGenerator {
public static RefTypeOrTPHOrWildcardOrGeneric convert(Java8Parser.UnannClassOrInterfaceTypeContext unannClassOrInterfaceTypeContext, JavaClassRegistry reg, GenericsRegistry generics) { public static RefTypeOrTPHOrWildcardOrGeneric convert(Java8Parser.UnannClassOrInterfaceTypeContext unannClassOrInterfaceTypeContext, JavaClassRegistry reg, GenericsRegistry generics) {
Java8Parser.TypeArgumentsContext arguments=null; Java8Parser.TypeArgumentsContext arguments;
/* PL 2019-03-19 auskommentiert ANFANG
if(unannClassOrInterfaceTypeContext.unannClassType_lfno_unannClassOrInterfaceType() != null){ if(unannClassOrInterfaceTypeContext.unannClassType_lfno_unannClassOrInterfaceType() != null){
arguments = unannClassOrInterfaceTypeContext.unannClassType_lfno_unannClassOrInterfaceType().typeArguments(); arguments = unannClassOrInterfaceTypeContext.unannClassType_lfno_unannClassOrInterfaceType().typeArguments();
}else{// if(unannClassOrInterfaceTypeContext.unannInterfaceType_lfno_unannClassOrInterfaceType() != null){ }else{// if(unannClassOrInterfaceTypeContext.unannInterfaceType_lfno_unannClassOrInterfaceType() != null){
arguments = unannClassOrInterfaceTypeContext.unannInterfaceType_lfno_unannClassOrInterfaceType().unannClassType_lfno_unannClassOrInterfaceType().typeArguments(); arguments = unannClassOrInterfaceTypeContext.unannInterfaceType_lfno_unannClassOrInterfaceType().unannClassType_lfno_unannClassOrInterfaceType().typeArguments();
} }
PL 2019-03-19 auskommentiert ENDE */
/** /**
* Problem sind hier die verschachtelten Typen mit verschachtelten Typargumenten * Problem sind hier die verschachtelten Typen mit verschachtelten Typargumenten
* Beispiel: Typ<String>.InnererTyp<Integer> * Beispiel: Typ<String>.InnererTyp<Integer>
@@ -41,28 +35,6 @@ public class TypeGenerator {
String name = unannClassOrInterfaceTypeContext.getText(); String name = unannClassOrInterfaceTypeContext.getText();
if(name.contains("<")){ if(name.contains("<")){
name = name.split("<")[0]; //Der Typ ist alles vor den ersten Argumenten name = name.split("<")[0]; //Der Typ ist alles vor den ersten Argumenten
/* Fuer Debug-Zwecke
unannClassOrInterfaceTypeContext.unannInterfaceType_lfno_unannClassOrInterfaceType();
unannClassOrInterfaceTypeContext.unannClassType_lfno_unannClassOrInterfaceType().getText();
//unannClassOrInterfaceTypeContext.unannInterfaceType_lfno_unannClassOrInterfaceType().unannClassType_lfno_unannClassOrInterfaceType().typeArguments();
//UnannClassType_lfno_unannClassOrInterfaceTypeContext
unannClassOrInterfaceTypeContext.unannClassType_lf_unannClassOrInterfaceType(0);
unannClassOrInterfaceTypeContext.unannClassType_lf_unannClassOrInterfaceType(0).getText();
unannClassOrInterfaceTypeContext.unannClassType_lf_unannClassOrInterfaceType(1);
unannClassOrInterfaceTypeContext.unannClassType_lf_unannClassOrInterfaceType(1).getText();
unannClassOrInterfaceTypeContext.unannClassType_lfno_unannClassOrInterfaceType().getText();
//unannClassOrInterfaceTypeContext.unannInterfaceType_lf_unannClassOrInterfaceType();
//unannClassOrInterfaceTypeContext.unannInterfaceType_lf_unannClassOrInterfaceType(0).getText();
//unannClassOrInterfaceTypeContext.unannInterfaceType_lf_unannClassOrInterfaceType(1).getText();
//unannClassOrInterfaceTypeContext.unannInterfaceType_lfno_unannClassOrInterfaceType().getText();
*/
int lastElement = new ArrayList<>(unannClassOrInterfaceTypeContext.unannClassType_lf_unannClassOrInterfaceType()).size()-1;
if (lastElement >=0) {//qualifizierter Name z.B.: java.util.Vector
arguments = unannClassOrInterfaceTypeContext.unannClassType_lf_unannClassOrInterfaceType(lastElement).typeArguments();
}
else { //unqualifizierter Name z.B.: Vector
arguments = unannClassOrInterfaceTypeContext.unannClassType_lfno_unannClassOrInterfaceType().typeArguments();
}
} }
return convertTypeName(name, arguments, unannClassOrInterfaceTypeContext.getStart(), reg, generics); return convertTypeName(name, arguments, unannClassOrInterfaceTypeContext.getStart(), reg, generics);
} }
@@ -161,35 +133,18 @@ public class TypeGenerator {
} }
} }
public static RefTypeOrTPHOrWildcardOrGeneric convert(Java8Parser.WildcardContext wildcardContext, JavaClassRegistry reg, GenericsRegistry generics) {
if(wildcardContext.wildcardBounds() != null){
if(wildcardContext.wildcardBounds().getText().substring(0, 7).equals("extends")){
return new ExtendsWildcardType(convert(wildcardContext.wildcardBounds().referenceType(), reg, generics), wildcardContext.getStart());
}else{
return new SuperWildcardType(convert(wildcardContext.wildcardBounds().referenceType(), reg, generics), wildcardContext.getStart());
}
}else{
throw new NotImplementedException(); //Wildcard ohne Bound
}
}
public static RefTypeOrTPHOrWildcardOrGeneric convertTypeName(String name, Token offset, JavaClassRegistry reg, GenericsRegistry generics){ public static RefTypeOrTPHOrWildcardOrGeneric convertTypeName(String name, Token offset, JavaClassRegistry reg, GenericsRegistry generics){
return convertTypeName(name, null, offset, reg, generics); return convertTypeName(name, null, offset, reg, generics);
} }
public static RefTypeOrTPHOrWildcardOrGeneric convertTypeName( public static RefTypeOrTPHOrWildcardOrGeneric convertTypeName(
String name, Java8Parser.TypeArgumentsContext typeArguments, Token offset, JavaClassRegistry reg, GenericsRegistry generics){ String name, Java8Parser.TypeArgumentsContext typeArguments, Token offset, JavaClassRegistry reg, GenericsRegistry generics){
if(!reg.contains(name)){ //Dann könnte es ein generischer Type oder ein FunN$$-Type sein if(!reg.contains(name)){ //Dann könnte es ein Generische Type sein
if(generics.contains(name)){ if(generics.contains(name)){
return new GenericRefType(name, offset); return new GenericRefType(name, offset);
}else{
Pattern p = Pattern.compile("Fun(\\d+)[$][$]");
Matcher m = p.matcher(name);
if (m.matches()) {//es ist FunN$$-Type
return new RefType(new JavaClassName(name), convert(typeArguments, reg, generics), offset);
}else{ }else{
throw new TypeinferenceException("Der Typ "+ name + " ist nicht vorhanden",offset); throw new TypeinferenceException("Der Typ "+ name + " ist nicht vorhanden",offset);
}} }
} }
if(typeArguments == null){ if(typeArguments == null){
List<RefTypeOrTPHOrWildcardOrGeneric> params = new ArrayList<>(); List<RefTypeOrTPHOrWildcardOrGeneric> params = new ArrayList<>();
@@ -207,7 +162,7 @@ public class TypeGenerator {
List<RefTypeOrTPHOrWildcardOrGeneric> ret = new ArrayList<>(); List<RefTypeOrTPHOrWildcardOrGeneric> ret = new ArrayList<>();
for(Java8Parser.TypeArgumentContext arg : typeArguments.typeArgumentList().typeArgument()){ for(Java8Parser.TypeArgumentContext arg : typeArguments.typeArgumentList().typeArgument()){
if(arg.wildcard() != null){ if(arg.wildcard() != null){
ret.add(convert(arg.wildcard(), reg, generics)); throw new NotImplementedException();
}else{ }else{
ret.add(convert(arg.referenceType(), reg, generics)); ret.add(convert(arg.referenceType(), reg, generics));
} }

View File

@@ -80,9 +80,6 @@ public abstract class AbstractASTWalker implements ASTVisitor{
for(Field f : classOrInterface.getFieldDecl()){ for(Field f : classOrInterface.getFieldDecl()){
f.accept(this); f.accept(this);
} }
for(Constructor c : classOrInterface.getConstructors()){
c.accept(this);
}
for(Method m : classOrInterface.getMethods()){ for(Method m : classOrInterface.getMethods()){
m.accept(this); m.accept(this);
} }

View File

@@ -6,7 +6,7 @@ import org.antlr.v4.runtime.Token;
import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric; import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric;
/** /**
* Eine Feldinitialisation steht für eine Felddeklaration mit gleichzeitiger Wertzuweisung * Eine Feldinitialisation steht für eine Felddeklaration mit gleichzeitiger Wertzuweisung
* Beispiel: 'public Feld FeldVar = FeldWert;' * Beispiel: 'public Feld FeldVar = FeldWert;'
* @author janulrich * @author janulrich
* *
@@ -17,7 +17,7 @@ public class FieldDeclaration extends Field{
/** /**
* Dieser Konstruktor der FieldDeclaration erstellt den Syntaxknoten vollständig. * Dieser Konstruktor der FieldDeclaration erstellt den Syntaxknoten vollständig.
* Kein nachträgliches hinzfügen von Informationen oder aufrufen von parserPostProcessing ist notwendig. * Kein nachträgliches hinzfügen von Informationen oder aufrufen von parserPostProcessing ist notwendig.
*/ */
public FieldDeclaration(String name, RefTypeOrTPHOrWildcardOrGeneric typ, int modifier, Expression value, Token offset){ public FieldDeclaration(String name, RefTypeOrTPHOrWildcardOrGeneric typ, int modifier, Expression value, Token offset){
super(name, typ, modifier, offset);//Dieser Deklarator wird nicht vom Parser aufgerufen. Dadurch gibt es auch keinen Offset super(name, typ, modifier, offset);//Dieser Deklarator wird nicht vom Parser aufgerufen. Dadurch gibt es auch keinen Offset

View File

@@ -2,10 +2,6 @@ package de.dhbwstuttgart.syntaxtree;
import org.antlr.v4.runtime.Token; import org.antlr.v4.runtime.Token;
import com.google.common.collect.Lists;
import de.dhbwstuttgart.parser.NullToken;
import java.util.*; import java.util.*;
@@ -20,20 +16,10 @@ public class GenericDeclarationList extends SyntaxTreeNode implements Iterable<G
private Token offsetOfLastElement; private Token offsetOfLastElement;
private List<GenericTypeVar> gtvs = new ArrayList<>(); private List<GenericTypeVar> gtvs = new ArrayList<>();
@SuppressWarnings("unchecked") public GenericDeclarationList(List<GenericTypeVar> values, Token endOffset) {
public GenericDeclarationList(Iterable<? extends GenericTypeVar> values, Token endOffset) {
super(endOffset);
gtvs = isListOfGenericTypeVar(values) ? (List<GenericTypeVar>)values : Lists.newArrayList(values);
this.offsetOfLastElement = endOffset;
}
public GenericDeclarationList(ArrayList<GenericTypeVar> values, Token endOffset) {
super(endOffset); super(endOffset);
gtvs = values; gtvs = values;
this.offsetOfLastElement = endOffset; } this.offsetOfLastElement = endOffset;
private boolean isListOfGenericTypeVar(Iterable<? extends GenericTypeVar> values) {
return values instanceof List && ((List<?>)values).size() > 0 && ((List<?>)values).get(0) instanceof GenericTypeVar;
} }
@Override @Override

View File

@@ -63,7 +63,7 @@ public class Method extends SyntaxTreeNode implements IItemWithOffset, TypeScope
@Override @Override
public Token getOffset() { public Token getOffset() {
return super.getOffset(); return null;
} }
public String getName() { public String getName() {

View File

@@ -1,7 +1,6 @@
package de.dhbwstuttgart.syntaxtree.factory; package de.dhbwstuttgart.syntaxtree.factory;
import java.io.FileWriter; import java.io.FileWriter;
import java.io.Writer;
import java.util.*; import java.util.*;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
@@ -31,7 +30,7 @@ public class UnifyTypeFactory {
private static ArrayList<PlaceholderType> PLACEHOLDERS = new ArrayList<>(); private static ArrayList<PlaceholderType> PLACEHOLDERS = new ArrayList<>();
public static FiniteClosure generateFC(List<ClassOrInterface> fromClasses, Writer logFile) throws ClassNotFoundException { public static FiniteClosure generateFC(List<ClassOrInterface> fromClasses, FileWriter logFile) throws ClassNotFoundException {
/* /*
Die transitive Hülle muss funktionieren. Die transitive Hülle muss funktionieren.
Man darf schreiben List<A> extends AL<A> Man darf schreiben List<A> extends AL<A>
@@ -68,6 +67,9 @@ public class UnifyTypeFactory {
public static UnifyType convert(RefTypeOrTPHOrWildcardOrGeneric t, Boolean innerType){ public static UnifyType convert(RefTypeOrTPHOrWildcardOrGeneric t, Boolean innerType){
if(t instanceof GenericRefType){ if(t instanceof GenericRefType){
return UnifyTypeFactory.convert((GenericRefType)t, innerType); return UnifyTypeFactory.convert((GenericRefType)t, innerType);
}else
if(t instanceof FunN){
return UnifyTypeFactory.convert((FunN)t, innerType);
}else if(t instanceof TypePlaceholder){ }else if(t instanceof TypePlaceholder){
return UnifyTypeFactory.convert((TypePlaceholder)t, innerType); return UnifyTypeFactory.convert((TypePlaceholder)t, innerType);
}else if(t instanceof ExtendsWildcardType){ }else if(t instanceof ExtendsWildcardType){
@@ -83,13 +85,13 @@ public class UnifyTypeFactory {
public static UnifyType convert(RefType t, Boolean innerType){ public static UnifyType convert(RefType t, Boolean innerType){
//Check if it is a FunN Type: //Check if it is a FunN Type:
Pattern p = Pattern.compile("Fun(\\d+)[$][$]"); Pattern p = Pattern.compile("Fun(\\d+)");
Matcher m = p.matcher(t.getName().toString()); Matcher m = p.matcher(t.getName().toString());
boolean b = m.matches(); boolean b = m.matches();
if(b){ if(b){
Integer N = Integer.valueOf(m.group(1)); Integer N = Integer.valueOf(m.group(1));
if((N + 1) == t.getParaList().size()){ if((N + 1) == t.getParaList().size()){
return convertFunN(t.getParaList(), false); return convert(new FunN(t.getParaList()), false);
} }
} }
UnifyType ret; UnifyType ret;
@@ -100,16 +102,16 @@ public class UnifyTypeFactory {
} }
ret = new ReferenceType(t.getName().toString(),new TypeParams(params)); ret = new ReferenceType(t.getName().toString(),new TypeParams(params));
}else{ }else{
ret = new ReferenceType(t.getName().toString(), false); ret = new ReferenceType(t.getName().toString());
} }
return ret; return ret;
} }
public static UnifyType convertFunN(List<RefTypeOrTPHOrWildcardOrGeneric> paraList, Boolean innerType){ public static UnifyType convert(FunN t, Boolean innerType){
UnifyType ret; UnifyType ret;
List<UnifyType> params = new ArrayList<>(); List<UnifyType> params = new ArrayList<>();
if(paraList != null && paraList.size() > 0){ if(t.getParaList() != null && t.getParaList().size() > 0){
for(RefTypeOrTPHOrWildcardOrGeneric pT : paraList){ for(RefTypeOrTPHOrWildcardOrGeneric pT : t.getParaList()){
params.add(UnifyTypeFactory.convert(pT, false)); params.add(UnifyTypeFactory.convert(pT, false));
} }
} }
@@ -136,7 +138,7 @@ public class UnifyTypeFactory {
} }
public static UnifyType convert(GenericRefType t, Boolean innerType){ public static UnifyType convert(GenericRefType t, Boolean innerType){
return new ReferenceType(t.getParsedName(), true); return new ReferenceType(t.getParsedName());
} }
public static UnifyType convert(WildcardType t, Boolean innerType){ public static UnifyType convert(WildcardType t, Boolean innerType){
@@ -222,21 +224,18 @@ public class UnifyTypeFactory {
return new PairTPHequalRefTypeOrWildcardType((TypePlaceholder)tl, (RefType) tr); return new PairTPHequalRefTypeOrWildcardType((TypePlaceholder)tl, (RefType) tr);
}else if(tr instanceof WildcardType){ }else if(tr instanceof WildcardType){
return new PairTPHequalRefTypeOrWildcardType((TypePlaceholder)tl, (WildcardType) tr); return new PairTPHequalRefTypeOrWildcardType((TypePlaceholder)tl, (WildcardType) tr);
}else if(tr instanceof GenericRefType){
return new PairTPHequalRefTypeOrWildcardType((TypePlaceholder)tl, (GenericRefType) tr);
}else throw new NotImplementedException(); }else throw new NotImplementedException();
}else throw new NotImplementedException(); }else throw new NotImplementedException();
} }
public static RefTypeOrTPHOrWildcardOrGeneric convert(ReferenceType t, Map<String,TypePlaceholder> tphs) { public static RefTypeOrTPHOrWildcardOrGeneric convert(ReferenceType t, Map<String,TypePlaceholder> tphs) {
if(JavaClassName.Void.equals(t.getName()))return new Void(new NullToken()); if(JavaClassName.Void.equals(t.getName()))return new Void(new NullToken());
if (t.isGenTypeVar()) return new GenericRefType(t.getName(),new NullToken());
RefType ret = new RefType(new JavaClassName(t.getName()),convert(t.getTypeParams(), tphs),new NullToken()); RefType ret = new RefType(new JavaClassName(t.getName()),convert(t.getTypeParams(), tphs),new NullToken());
return ret; return ret;
} }
public static RefTypeOrTPHOrWildcardOrGeneric convert(FunNType t, Map<String,TypePlaceholder> tphs) { public static RefTypeOrTPHOrWildcardOrGeneric convert(FunNType t, Map<String,TypePlaceholder> tphs) {
RefType ret = new RefType(new JavaClassName(t.getName()), convert(t.getTypeParams(), tphs), new NullToken()); RefType ret = new RefType(new JavaClassName(t.getName()+"$$"), convert(t.getTypeParams(), tphs), new NullToken());
return ret; return ret;
} }

View File

@@ -19,8 +19,4 @@ public class This extends Expression
public void accept(StatementVisitor visitor) { public void accept(StatementVisitor visitor) {
visitor.visit(this); visitor.visit(this);
} }
public String toString() {
return "this: "+ this.getType();
}
} }

View File

@@ -0,0 +1,41 @@
package de.dhbwstuttgart.syntaxtree.type;
import de.dhbwstuttgart.parser.NullToken;
import de.dhbwstuttgart.parser.scope.JavaClassName;
import java.util.List;
/**
* @see Spezifikation "Complete Typeinference in Java 8" von Martin Plümicke
* "interface FunN<R,T1, T2, ... ,TN> { R apply(T1 arg1, T2 arg2, ... , TN argN); }"
* @author A10023 - Andreas Stadelmeier
*
* Bemerkung:
* FunN ist ein RefType. Der RefType ist nicht mit einem FunNInterface verbunden.
*
*/
public class FunN extends RefType {
/**
* @author Andreas Stadelmeier, a10023
* Benötigt für den Typinferenzalgorithmus für Java 8
* Generiert einen RefType auf eine FunN<R,T1,...,TN> - Klasse.
* @param params
* @return
*/
public FunN(List<RefTypeOrTPHOrWildcardOrGeneric> params) {
super(new JavaClassName("Fun"+(params.size()-1)), params, new NullToken());
}
/**
* Spezieller Konstruktor um eine FunN ohne Returntype zu generieren
protected FunN(List<? extends Type> list){
super("",0);
if(list==null)throw new NullPointerException();
setT(list);
this.name = new JavaClassName("Fun"+list.size());//getName();
}
*/
}

View File

@@ -36,7 +36,7 @@ public class TypePlaceholder extends RefTypeOrTPHOrWildcardOrGeneric
/** /**
* @author Andreas Stadelmeier, a10023 * @author Andreas Stadelmeier, a10023
* Ruft die TypePlaceholder.fresh()-Methode auf. * Ruft die TypePlaceholder.fresh()-Methode auf.
* Fügt zusätzlich einen Replacementlistener hinzu. * Fügt zusätzlich einen Replacementlistener hinzu.
* @return * @return
*/ */
public static TypePlaceholder fresh(Token position){ public static TypePlaceholder fresh(Token position){

View File

@@ -1,7 +0,0 @@
package de.dhbwstuttgart.typedeployment;
public enum KindOfTypeInsertPoint {
NORMAL_INSERT,
GENERIC_CLASS_INSERT,
GENERERIC_METHOD_INSERT
}

View File

@@ -1,16 +1,11 @@
package de.dhbwstuttgart.typedeployment; package de.dhbwstuttgart.typedeployment;
import org.antlr.v4.runtime.Token;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.HashSet;
import java.util.Comparator;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import java.util.TreeSet;
import org.antlr.v4.parse.BlockSetTransformer.setAlt_return;
import de.dhbwstuttgart.syntaxtree.statement.This;
import de.dhbwstuttgart.typeinference.result.ResultPair;
public class TypeInsert { public class TypeInsert {
/** /**
@@ -18,25 +13,18 @@ public class TypeInsert {
*/ */
public final TypeInsertPoint point; public final TypeInsertPoint point;
Set<TypeInsertPoint> inserts; Set<TypeInsertPoint> inserts;
ResultPair<?, ?> resultPair;
public TypeInsert(TypeInsertPoint point, Set<TypeInsertPoint> additionalPoints, ResultPair<?, ?> resultPair){ public TypeInsert(TypeInsertPoint point, Set<TypeInsertPoint> additionalPoints){
this.point = point; this.point = point;
inserts = additionalPoints; inserts = additionalPoints;
this.resultPair = resultPair;
} }
public String insert(String intoSource){ public String insert(String intoSource){
List<TypeInsertPoint> offsets = new ArrayList<>(); List<TypeInsertPoint> offsets = new ArrayList<>();
String ret = intoSource; String ret = point.insert(intoSource, offsets);
offsets.add(point);
List<TypeInsertPoint> insertsSorted = new ArrayList<>(); for(TypeInsertPoint insertPoint : inserts){
insertsSorted.add(point); ret = insertPoint.insert(ret, offsets);
insertsSorted.addAll(inserts);
Collections.sort(insertsSorted, new TypeInsertPoint.TypeInsertPointPositionComparator().reversed());
for(TypeInsertPoint insertPoint : insertsSorted) {
ret = insertPoint.insert(ret, new ArrayList<>());
offsets.add(insertPoint); offsets.add(insertPoint);
} }
return ret; return ret;
@@ -46,10 +34,6 @@ public class TypeInsert {
return point.getInsertString(); return point.getInsertString();
} }
public ResultPair<?, ?> getResultPair() {
return this.resultPair;
}
/* PL 2018-06-18 /* PL 2018-06-18
* Zwei TypeInsert's sind gleich, wenn ihre point's und ihre inserts' gleich sind * Zwei TypeInsert's sind gleich, wenn ihre point's und ihre inserts' gleich sind
* eingefuegt damit man TypeReplaceMarker vergleichen kann * eingefuegt damit man TypeReplaceMarker vergleichen kann
@@ -64,18 +48,6 @@ public class TypeInsert {
} }
} }
public Set<TypeInsertPoint> getAdditionalPoints() {
TypeInsertPoint.TypeInsertPointPositionComparator comparator = new TypeInsertPoint.TypeInsertPointPositionComparator();
TreeSet<TypeInsertPoint> result = new TreeSet<>(comparator.reversed());
result.addAll(inserts);
return result;
}
public Set<TypeInsertPoint> getAdditionalPointsUnsorted() {
return inserts;
}
public String toString() { public String toString() {
return point.toString(); return point.toString();
} }

View File

@@ -1,35 +1,11 @@
package de.dhbwstuttgart.typedeployment; package de.dhbwstuttgart.typedeployment;
import java.util.HashSet; import de.dhbwstuttgart.syntaxtree.*;
import java.util.Iterator; import de.dhbwstuttgart.syntaxtree.type.*;
import java.util.List; import de.dhbwstuttgart.typeinference.result.*;
import java.util.Optional;
import java.util.Set;
import org.antlr.v4.runtime.Token; import org.antlr.v4.runtime.Token;
import org.objectweb.asm.Type;
import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.GenericGenratorResultForSourceFile; import java.util.*;
import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.GenericsGeneratorResult;
import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.GenericsGeneratorResultForClass;
import de.dhbwstuttgart.bytecode.utilities.MethodUtility;
import de.dhbwstuttgart.bytecode.utilities.Resolver;
import de.dhbwstuttgart.core.JavaTXCompiler;
import de.dhbwstuttgart.syntaxtree.ClassOrInterface;
import de.dhbwstuttgart.syntaxtree.Method;
import de.dhbwstuttgart.syntaxtree.SourceFile;
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.typeinference.result.PairTPHEqualTPH;
import de.dhbwstuttgart.typeinference.result.PairTPHequalRefTypeOrWildcardType;
import de.dhbwstuttgart.typeinference.result.PairTPHsmallerTPH;
import de.dhbwstuttgart.typeinference.result.ResolvedType;
import de.dhbwstuttgart.typeinference.result.ResultSet;
import de.dhbwstuttgart.typeinference.result.ResultSetVisitor;
/** /**
* TODO: * TODO:
@@ -46,120 +22,75 @@ import de.dhbwstuttgart.typeinference.result.ResultSetVisitor;
*/ */
public class TypeInsertFactory { public class TypeInsertFactory {
private static List<ResultSet> newResults;
public static Set<TypeInsert> createTypeInsertPoints(SourceFile forSourcefile, ResultSet withResults, List<ResultSet> newResults, List<GenericGenratorResultForSourceFile> simplifyResultsForAllSourceFiles){ public static Set<TypeInsert> createTypeInsertPoints(SourceFile forSourcefile, ResultSet withResults){
TypeInsertFactory.newResults = newResults; return new TypeInsertPlacer().getTypeInserts(forSourcefile, withResults);
return new TypeInsertPlacer().getTypeInserts(forSourcefile, withResults, simplifyResultsForAllSourceFiles);
} }
public static TypeInsert createInsertPoints(RefTypeOrTPHOrWildcardOrGeneric type, Token offset, ClassOrInterface cl, Method m, public static TypeInsert createInsertPoints(RefTypeOrTPHOrWildcardOrGeneric type, Token offset, ClassOrInterface cl, Method m,
ResultSet resultSet, List<GenericsGeneratorResult> constraints, List<GenericsGeneratorResult> classConstraints) { ResultSet resultSet) {
/* PL 2020-04-11 auskommentiert
* try {
*/
ResolvedType resolvedType = resultSet.resolveType(type); ResolvedType resolvedType = resultSet.resolveType(type);
TypeInsertPoint insertPoint = new TypeInsertPoint(offset, TypeInsertPoint insertPoint = new TypeInsertPoint(offset,
new TypeToInsertString(resolvedType.resolvedType, constraints, classConstraints).insert, KindOfTypeInsertPoint.NORMAL_INSERT); new TypeToInsertString(resolvedType.resolvedType).insert);
/* PL 2020-04-11 auskommentiert return new TypeInsert(insertPoint, new HashSet<>(Arrays.asList(createGenericInsert(resolvedType.additionalGenerics, cl, m))));
List<GenericGenratorResultForSourceFile> simplifyResults = JavaTXCompiler.INSTANCE.getGeneratedGenericResultsForAllSourceFiles(newResults);
for (GenericGenratorResultForSourceFile simplifyResultsEntries : simplifyResults) {
GenericsGeneratorResultForClass genericResultsForClass = simplifyResultsEntries.getSimplifyResultsByName("", cl.getClassName().toString());
return new TypeInsert(insertPoint, createGenericInsert(genericResultsForClass, cl, m, resultSet, offset), resolvedType.getResultPair());
} }
return new TypeInsert(insertPoint, new HashSet<>(), resolvedType.getResultPair()); private static TypeInsertPoint createGenericInsert(Set<GenericInsertPair> toInsert, ClassOrInterface cl, Method m){
*/ //Momentan wird Methode ignoriert. Parameter werden immer als Klassenparameter angefügt:
//GenericsGeneratorResultForClass genericResultsForClass = genericResult.getSimplifyResultsByName("", cl.getClassName().toString()); //Offset zum Einstzen bestimmen:
return new TypeInsert(insertPoint, createGenericInsert(constraints, classConstraints, cl, m, resultSet, offset), resolvedType.getResultPair()); Token offset;
String insert = "";
/* PL 2020-04-11 auskommentiert String end;
} catch (ClassNotFoundException e) { if(cl.getGenerics().iterator().hasNext()){
e.printStackTrace(); //offset = cl.getGenerics().iterator().next().getOffset();
return null; offset = cl.getGenerics().getOffset();
} end=",";
*/
}
private static synchronized Set<TypeInsertPoint> createGenericInsert(List<GenericsGeneratorResult> methodConstraints, List<GenericsGeneratorResult> classConstraints,ClassOrInterface cl, Method m, ResultSet resultSet, Token mOffset){
Set<TypeInsertPoint> result = createGenericClassInserts(classConstraints, cl);
Resolver resolver = new Resolver(resultSet);
if (m != null) {
//List<GenericsGeneratorResult> methodConstraints = genericResult.getMethodConstraintsByID(MethodUtility.createID(resolver, m));
result.addAll(createMethodConstraints(methodConstraints, m.getOffset() != null ? m.getOffset() : mOffset));
}
return result;
}
private static Set<TypeInsertPoint> createMethodConstraints(List<GenericsGeneratorResult> constraints, Token mOffset) {
Set<TypeInsertPoint> result = new HashSet<>();
Token offset = mOffset;
if (constraints.size() == 0) {
return result;
}
String insert = " <";
for (GenericsGeneratorResult genericInsertConstraint : constraints) {
if (genericInsertConstraint.getConstraint().getRight().equals(Type.getInternalName(Object.class))) {
insert += genericInsertConstraint.getConstraint().getLeft();
}else{ }else{
insert += genericInsertConstraint.getConstraint().getLeft() + " extends " + genericInsertConstraint.getConstraint().getRight(); offset = cl.getGenerics().getOffset();
} insert += "<";
insert += ", "; end = ">";
} }
insert = insert.substring(0, insert.length() -2); //Alle einzusetzenden Generics und deren Bounds bestimmen:
insert += ">"; HashMap<TypePlaceholder, HashSet<TypePlaceholder>> genericsAndBounds = new HashMap<>();
for(GenericInsertPair p : toInsert){
result.add(new TypeInsertPoint(offset, insert, KindOfTypeInsertPoint.GENERERIC_METHOD_INSERT)); if(!genericsAndBounds.containsKey(p.TA1)){
return result; genericsAndBounds.put((TypePlaceholder) p.TA1, new HashSet<>());
}
if(p.TA2 != null){
genericsAndBounds.get(p.TA1).add((TypePlaceholder) p.TA2);
if(!genericsAndBounds.containsKey(p.TA2)){
genericsAndBounds.put((TypePlaceholder) p.TA2, new HashSet<>());
}
}
} }
private static Set<TypeInsertPoint> createGenericClassInserts(List<GenericsGeneratorResult> classConstraints, ClassOrInterface cl) { //String zum Einsetzen (Generics mit bounds) generieren:
Set<TypeInsertPoint> result = new HashSet<>(); Iterator<TypePlaceholder> it = genericsAndBounds.keySet().iterator();
Token offset = cl.getGenerics().getOffset(); if(! it.hasNext())return new TypeInsertPoint(offset, "");
while(it.hasNext()){
//List<GenericsGeneratorResult> classConstraints = genericResult.getClassConstraints(); TypePlaceholder tph = it.next();
insert += tph.getName();
if (classConstraints == null || classConstraints.size() == 0) { Set<TypePlaceholder> bounds = genericsAndBounds.get(tph);
return result; if(bounds.size() > 0){
insert += " extends ";
Iterator<TypePlaceholder> boundIt = bounds.iterator();
while(boundIt.hasNext()){
TypePlaceholder bound = boundIt.next();
insert += bound.getName();
if(boundIt.hasNext())insert += " & ";
} }
String insert = " <";
for (GenericsGeneratorResult genericInsertConstraint : classConstraints) {
if (genericInsertConstraint.getConstraint().getRight().equals(Type.getInternalName(Object.class))) {
insert += genericInsertConstraint.getConstraint().getLeft();
} else {
insert += genericInsertConstraint.getConstraint().getLeft() + " extends " + genericInsertConstraint.getConstraint().getRight();
} }
insert += ", "; if(it.hasNext())insert+=",";
} }
return new TypeInsertPoint(offset, insert + end);
insert = insert.substring(0, insert.length() -2);
insert += ">";
result.add(new TypeInsertPoint(offset, insert, KindOfTypeInsertPoint.GENERIC_CLASS_INSERT));
return result;
} }
} }
class TypeToInsertString implements ResultSetVisitor{ class TypeToInsertString implements ResultSetVisitor{
String insert = ""; String insert = "";
private List<GenericsGeneratorResult> constraints;
private List<GenericsGeneratorResult> classConstraints;
TypeToInsertString(RefTypeOrTPHOrWildcardOrGeneric type){
TypeToInsertString(RefTypeOrTPHOrWildcardOrGeneric type, List<GenericsGeneratorResult> constraints, List<GenericsGeneratorResult> classConstraints){
this.constraints = constraints;
this.classConstraints = classConstraints;
type.accept(this); type.accept(this);
} }
@@ -186,7 +117,7 @@ class TypeToInsertString implements ResultSetVisitor{
Iterator<RefTypeOrTPHOrWildcardOrGeneric> iterator = resolved.getParaList().iterator(); Iterator<RefTypeOrTPHOrWildcardOrGeneric> iterator = resolved.getParaList().iterator();
while(iterator.hasNext()){ while(iterator.hasNext()){
RefTypeOrTPHOrWildcardOrGeneric typeParam = iterator.next(); RefTypeOrTPHOrWildcardOrGeneric typeParam = iterator.next();
insert += new TypeToInsertString(typeParam, constraints, classConstraints).insert; insert += new TypeToInsertString(typeParam).insert;
if(iterator.hasNext())insert += ", "; if(iterator.hasNext())insert += ", ";
} }
insert += ">"; insert += ">";
@@ -200,37 +131,16 @@ class TypeToInsertString implements ResultSetVisitor{
@Override @Override
public void visit(SuperWildcardType superWildcardType) { public void visit(SuperWildcardType superWildcardType) {
insert += "? super " + new TypeToInsertString(superWildcardType.getInnerType(), constraints, classConstraints).insert; insert += "? super " + new TypeToInsertString(superWildcardType.getInnerType()).insert;
} }
@Override @Override
public void visit(TypePlaceholder typePlaceholder) { public void visit(TypePlaceholder typePlaceholder) {
String realName = typePlaceholder.getName(); insert += typePlaceholder.getName();
//String realName = sig2.substring(1, sig2.length() - 1);
//String toVisit = realName+SPECIAL_CHAR;
//if(!genericsAndBounds.containsKey(toVisit)) {//PL 202-04-1 vielleicht braucht man das, vgl. Signature.java
Optional<GenericsGeneratorResult> equalTPH = getEqualTPHFromClassConstraints(classConstraints, realName);
if(equalTPH.isPresent()){
insert += equalTPH.get().getConstraint().getLeft();// + SPECIAL_CHAR;
} else {
insert += getEqualTPH(constraints, realName);// + SPECIAL_CHAR;
}
} }
@Override @Override
public void visit(ExtendsWildcardType extendsWildcardType) { public void visit(ExtendsWildcardType extendsWildcardType) {
insert += "? extends " + new TypeToInsertString(extendsWildcardType.getInnerType(), constraints, classConstraints).insert; insert += "? extends " + new TypeToInsertString(extendsWildcardType.getInnerType()).insert;
}
private Optional<GenericsGeneratorResult> getEqualTPHFromClassConstraints(List<GenericsGeneratorResult> listOfConstraints, String tph) {
return listOfConstraints.stream()
.filter(c -> c.getConstraint().getLeft().equals(tph) || c.getEqualsTPHs().contains(tph))
.findFirst();
}
private String getEqualTPH(List<GenericsGeneratorResult> constraints2, String tph) {
return constraints2.stream()
.filter(c -> c.getConstraint().getLeft().equals(tph) || c.getEqualsTPHs().contains(tph))
.findFirst().get().getConstraint().getLeft();
} }
} }

View File

@@ -1,85 +1,59 @@
package de.dhbwstuttgart.typedeployment; package de.dhbwstuttgart.typedeployment;
import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.GenericGenratorResultForSourceFile; import de.dhbwstuttgart.exceptions.NotImplementedException;
import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.GenericsGeneratorResult;
import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.GenericsGeneratorResultForClass;
import de.dhbwstuttgart.bytecode.utilities.MethodUtility;
import de.dhbwstuttgart.bytecode.utilities.Resolver;
import de.dhbwstuttgart.syntaxtree.*; import de.dhbwstuttgart.syntaxtree.*;
import de.dhbwstuttgart.syntaxtree.statement.JavaInternalExpression;
import de.dhbwstuttgart.syntaxtree.statement.LambdaExpression; import de.dhbwstuttgart.syntaxtree.statement.LambdaExpression;
import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder; import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder;
import de.dhbwstuttgart.typeinference.result.ResultSet; import de.dhbwstuttgart.typeinference.result.ResultSet;
import java.util.ArrayList;
import java.util.HashSet; import java.util.HashSet;
import java.util.List;
import java.util.Set; import java.util.Set;
public class TypeInsertPlacer extends AbstractASTWalker{ public class TypeInsertPlacer extends AbstractASTWalker{
Set<TypeInsert> inserts = new HashSet<>(); Set<TypeInsert> inserts = new HashSet<>();
private ResultSet withResults; private ResultSet withResults;
String pkgName;
private List<GenericGenratorResultForSourceFile> simplifyResultsForAllSourceFiles;
public Set<TypeInsert> getTypeInserts(SourceFile forSourceFile, ResultSet withResults, List<GenericGenratorResultForSourceFile> simplifyResultsForAllSourceFiles){ public Set<TypeInsert> getTypeInserts(SourceFile forSourceFile, ResultSet withResults){
this.withResults = withResults; this.withResults = withResults;
this.simplifyResultsForAllSourceFiles = simplifyResultsForAllSourceFiles;
pkgName = forSourceFile.getPkgName();
forSourceFile.accept(this); forSourceFile.accept(this);
return inserts; return inserts;
} }
@Override @Override
public void visit(ClassOrInterface classOrInterface) { public void visit(ClassOrInterface classOrInterface) {
GenericsGeneratorResultForClass generatedGenerics = simplifyResultsForAllSourceFiles TypeInsertPlacerClass cl = new TypeInsertPlacerClass(classOrInterface, withResults);
.stream()
.map(sr->sr.getSimplifyResultsByName(pkgName, classOrInterface.getClassName().toString()))
.findFirst()
.get();
TypeInsertPlacerClass cl = new TypeInsertPlacerClass(classOrInterface, withResults, generatedGenerics);
this.inserts.addAll(cl.inserts); this.inserts.addAll(cl.inserts);
} }
} }
class TypeInsertPlacerClass extends AbstractASTWalker{ class TypeInsertPlacerClass extends AbstractASTWalker{
protected final ResultSet results; protected final ResultSet results;
private GenericsGeneratorResultForClass generatedGenerics;
protected final ClassOrInterface cl; protected final ClassOrInterface cl;
public final Set<TypeInsert> inserts = new HashSet<>(); public final Set<TypeInsert> inserts = new HashSet<>();
private Method method; private Method method;
private Resolver resolver; TypeInsertPlacerClass(ClassOrInterface forClass, ResultSet withResults){
List<GenericsGeneratorResult> constraints;
List<GenericsGeneratorResult> classConstraints;
TypeInsertPlacerClass(ClassOrInterface forClass, ResultSet withResults, GenericsGeneratorResultForClass generatedGenerics){
this.cl = forClass; this.cl = forClass;
this.method = null; this.method = null;
this.results = withResults; this.results = withResults;
this.generatedGenerics = generatedGenerics;
resolver = new Resolver(withResults); //PL 2020-04-12 Ob das stimmt weiss ich nicht
forClass.accept(this); forClass.accept(this);
} }
@Override @Override
public void visit(Method method) { public void visit(Method method) {
this.method = method; this.method = method;
String id = MethodUtility.createID(resolver, method);
constraints = generatedGenerics.getMethodConstraintsByID(id);
classConstraints = generatedGenerics.getClassConstraints();
if(method.getReturnType() instanceof TypePlaceholder) if(method.getReturnType() instanceof TypePlaceholder)
inserts.add(TypeInsertFactory.createInsertPoints( inserts.add(TypeInsertFactory.createInsertPoints(
method.getReturnType(), method.getReturnType().getOffset(), cl, method, results, constraints, classConstraints)); method.getReturnType(), method.getReturnType().getOffset(), cl, method, results));
super.visit(method); super.visit(method);
} }
@Override @Override
public void visit(Field field) { public void visit(Field field) {
if(field.getType() instanceof TypePlaceholder){ if(field.getType() instanceof TypePlaceholder){
classConstraints = generatedGenerics.getClassConstraints();
inserts.add(TypeInsertFactory.createInsertPoints( inserts.add(TypeInsertFactory.createInsertPoints(
field.getType(), field.getType().getOffset(), cl, method, results, new ArrayList<>(), classConstraints)); field.getType(), field.getType().getOffset(), cl, method, results));
} }
super.visit(field); super.visit(field);
} }
@@ -88,7 +62,7 @@ class TypeInsertPlacerClass extends AbstractASTWalker{
public void visit(FormalParameter param) { public void visit(FormalParameter param) {
if(param.getType() instanceof TypePlaceholder) if(param.getType() instanceof TypePlaceholder)
inserts.add(TypeInsertFactory.createInsertPoints( inserts.add(TypeInsertFactory.createInsertPoints(
param.getType(), param.getType().getOffset(), cl, method, results, constraints, classConstraints)); param.getType(), param.getType().getOffset(), cl, method, results));
super.visit(param); super.visit(param);
} }

View File

@@ -1,93 +1,49 @@
package de.dhbwstuttgart.typedeployment; package de.dhbwstuttgart.typedeployment;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import org.antlr.v4.runtime.Token; import org.antlr.v4.runtime.Token;
public class TypeInsertPoint { import de.dhbwstuttgart.typeinference.unify.model.ReferenceType;
public Token point;
private String insertString;
private int extraOffset = 0;
private KindOfTypeInsertPoint kind;
public TypeInsertPoint(Token point, String toInsert, KindOfTypeInsertPoint kind){ import java.util.List;
import java.util.stream.Collectors;
public class TypeInsertPoint {
public final Token point;
private String insertString;
public TypeInsertPoint(Token point, String toInsert){
this.point = point; this.point = point;
this.kind = kind;
this.insertString = (toInsert.endsWith(" ")) ? toInsert : toInsert + " " ; this.insertString = (toInsert.endsWith(" ")) ? toInsert : toInsert + " " ;
} }
public boolean isGenericClassInsertPoint() {
return kind == KindOfTypeInsertPoint.GENERIC_CLASS_INSERT;
}
public String insert(String intoSource, List<TypeInsertPoint> additionalOffset){ public String insert(String intoSource, List<TypeInsertPoint> additionalOffset){
return new StringBuilder(intoSource).insert(point.getStartIndex()+extraOffset, insertString).toString(); int offset = additionalOffset.stream().filter((token ->
//token.point.getLine() != point.getLine() && token.point.getCharPositionInLine() <= point.getCharPositionInLine()))
token.point.getStartIndex() <= point.getStartIndex()))
.mapToInt((typeInsertPoint -> typeInsertPoint.insertString.length())).sum();
return new StringBuilder(intoSource).insert(point.getStartIndex()+offset, insertString).toString();
} }
public String getInsertString() { public String getInsertString() {
return insertString; return insertString;
} }
public void addExtraOffset(int toAdd) {
this.extraOffset += toAdd;
}
public int getPositionInCode() {
return point.getStartIndex() + extraOffset;
}
/* PL 2018-06-19 /* PL 2018-06-19
* Zwei TypeInsertPoint's sind gleich, wenn ihre point's gleich sind * Zwei TypeInsertPoint's sind gleich, wenn ihre point's gleich sind
* eingefuegt damit man TypeReplaceMarker vergleichen kann * eingefuegt damit man TypeReplaceMarker vergleichen kann
* @see java.lang.Object#equals(java.lang.Object) * @see java.lang.Object#equals(java.lang.Object)
*/ */
public boolean equals(Object obj) { public boolean equals(Object obj) {
return this == obj;
/*
if(!(obj instanceof TypeInsertPoint)) { if(!(obj instanceof TypeInsertPoint)) {
return false; return false;
} }
else { else {
return return ((TypeInsertPoint)obj).point.equals(this.point) &&
((TypeInsertPoint)obj).getPositionInCode() == this.getPositionInCode() &&
((TypeInsertPoint)obj).insertString.equals(this.insertString); ((TypeInsertPoint)obj).insertString.equals(this.insertString);
} }
*/
}
public int hashCode() {
return getPositionInCode() * 11 * insertString.hashCode();
}
public Set<TypeInsertPoint> getAdditionalPoints() {
return this.getAdditionalPoints();
} }
public String toString() { public String toString() {
return point.getLine() + ":" + point.getCharPositionInLine() + ":" + insertString; return point.toString() + " " + insertString.toString();
}
public static final class TypeInsertPointPositionComparator implements Comparator<TypeInsertPoint> {
@Override
public int compare(TypeInsertPoint o1, TypeInsertPoint o2) {
if (o1.point == null && o2.point == null) {
return 0;
} else if (o2.point == null) {
return 1;
} else if (o1.point == null) {
return -1;
}
if (o1.getPositionInCode() > o2.getPositionInCode()) {
return 1;
} else if (o1.getPositionInCode() < o2.getPositionInCode()) {
return -1;
}
return 0;
}
} }
} }

View File

@@ -21,7 +21,7 @@ import java.util.Optional;
public class FunNClass extends ClassOrInterface { public class FunNClass extends ClassOrInterface {
public FunNClass(List<GenericRefType> funNParams) { public FunNClass(List<GenericRefType> funNParams) {
super(0, new JavaClassName("Fun"+(funNParams.size()-1)), new ArrayList<>(), Optional.empty() /* eingefuegt PL 2018-11-24 */, super(0, new JavaClassName("Fun"+(funNParams.size())), new ArrayList<>(), Optional.empty() /* eingefuegt PL 2018-11-24 */,
createMethods(funNParams), new ArrayList<>(), createGenerics(funNParams), createMethods(funNParams), new ArrayList<>(), createGenerics(funNParams),
ASTFactory.createObjectType(), true, new ArrayList<>(), new NullToken()); ASTFactory.createObjectType(), true, new ArrayList<>(), new NullToken());

View File

@@ -1,10 +1,10 @@
package de.dhbwstuttgart.typeinference.assumptions; package de.dhbwstuttgart.typeinference.assumptions;
import de.dhbwstuttgart.parser.NullToken; import de.dhbwstuttgart.parser.NullToken;
import de.dhbwstuttgart.parser.scope.JavaClassName;
import de.dhbwstuttgart.syntaxtree.ClassOrInterface; import de.dhbwstuttgart.syntaxtree.ClassOrInterface;
import de.dhbwstuttgart.syntaxtree.GenericTypeVar; import de.dhbwstuttgart.syntaxtree.GenericTypeVar;
import de.dhbwstuttgart.syntaxtree.TypeScope; import de.dhbwstuttgart.syntaxtree.TypeScope;
import de.dhbwstuttgart.syntaxtree.type.FunN;
import de.dhbwstuttgart.syntaxtree.type.GenericRefType; import de.dhbwstuttgart.syntaxtree.type.GenericRefType;
import de.dhbwstuttgart.syntaxtree.type.RefType; import de.dhbwstuttgart.syntaxtree.type.RefType;
import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric; import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric;
@@ -63,7 +63,7 @@ public class MethodAssumption extends Assumption{
} }
RefTypeOrTPHOrWildcardOrGeneric receiverType; RefTypeOrTPHOrWildcardOrGeneric receiverType;
if(receiver instanceof FunNClass){ if(receiver instanceof FunNClass){
receiverType = new RefType(new JavaClassName(receiver.getClassName().toString()+"$$"), params, new NullToken()); // new FunN(params); receiverType = new FunN(params);
}else{ }else{
receiverType = new RefType(receiver.getClassName(), params, new NullToken()); receiverType = new RefType(receiver.getClassName(), params, new NullToken());
} }

View File

@@ -23,9 +23,4 @@ public class GenericInsertPair {
if(TA2.equals(additionalTPH))return true; if(TA2.equals(additionalTPH))return true;
return false; return false;
} }
@Override
public String toString() {
return "GenIns(" + TA1.toString() + " < " + TA2.toString() + ")";
}
} }

View File

@@ -21,9 +21,4 @@ public class PairTPHequalRefTypeOrWildcardType extends ResultPair{
public void accept(ResultPairVisitor visitor) { public void accept(ResultPairVisitor visitor) {
visitor.visit(this); visitor.visit(this);
} }
@Override
public String toString() {
return "(" + left.toString() + " = " + right.toString() + ")";
}
} }

View File

@@ -20,9 +20,4 @@ public class PairTPHsmallerTPH extends ResultPair{
public void accept(ResultPairVisitor visitor) { public void accept(ResultPairVisitor visitor) {
visitor.visit(this); visitor.visit(this);
} }
@Override
public String toString() {
return "(" + left.toString() + " < " + right.toString() + ")";
}
} }

View File

@@ -7,21 +7,11 @@ import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder;
import java.util.Set; import java.util.Set;
public class ResolvedType{ public class ResolvedType{
private ResultPair<?, ?> resultPair;
public final RefTypeOrTPHOrWildcardOrGeneric resolvedType; public final RefTypeOrTPHOrWildcardOrGeneric resolvedType;
//public final Set<GenericInsertPair> additionalGenerics; public final Set<GenericInsertPair> additionalGenerics;
public ResolvedType(RefTypeOrTPHOrWildcardOrGeneric resolvedType, Set<GenericInsertPair> additionalGenerics){ public ResolvedType(RefTypeOrTPHOrWildcardOrGeneric resolvedType, Set<GenericInsertPair> additionalGenerics){
this.resolvedType = resolvedType; this.resolvedType = resolvedType;
//this.additionalGenerics = additionalGenerics; this.additionalGenerics = additionalGenerics;
}
public void setResultPair(ResultPair<?, ?> resultPair) {
this.resultPair = resultPair;
}
public ResultPair<?, ?> getResultPair() {
return resultPair;
} }
} }

View File

@@ -27,36 +27,4 @@ public abstract class ResultPair<A extends RefTypeOrTPHOrWildcardOrGeneric,B ext
public String toString() { public String toString() {
return "(" + left.toString() + ", " + right.toString() + ")"; return "(" + left.toString() + ", " + right.toString() + ")";
} }
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((left == null) ? 0 : left.getOffset().hashCode());
result = prime * result + ((right == null) ? 0 : right.getOffset().hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ResultPair<?,?> other = (ResultPair<?,?>) obj;
if (left == null) {
if (other.left != null)
return false;
} else if (!left.getOffset().equals(other.left.getOffset()))
return false;
if (right == null) {
if (other.right != null)
return false;
} else if (!right.getOffset().equals(other.right.getOffset()))
return false;
return true;
}
} }

View File

@@ -1,34 +1,16 @@
package de.dhbwstuttgart.typeinference.result; package de.dhbwstuttgart.typeinference.result;
import de.dhbwstuttgart.exceptions.NotImplementedException;
import de.dhbwstuttgart.syntaxtree.GenericTypeVar;
import de.dhbwstuttgart.syntaxtree.type.*;
import java.util.HashSet; import java.util.HashSet;
import java.util.Set; import java.util.Set;
import de.dhbwstuttgart.exceptions.NotImplementedException;
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;
@SuppressWarnings("rawtypes")
public class ResultSet { public class ResultSet {
public final Set<ResultPair> results; public final Set<ResultPair> results;
public Set<ResultPair<TypePlaceholder, TypePlaceholder>> genIns; public ResultSet(Set<ResultPair> results){
this.results = results;
public ResultSet(Set<ResultPair> set){
this.results = set;
this.genIns = new HashSet<>();
results.forEach(x -> { if (x instanceof PairTPHsmallerTPH) { this.genIns.add(x);}} );
}
public boolean contains(ResultPair toCheck) {
return this.results.contains(toCheck);
}
public void remove(ResultPair toCheck) {
results.remove(toCheck);
} }
public ResolvedType resolveType(RefTypeOrTPHOrWildcardOrGeneric type) { public ResolvedType resolveType(RefTypeOrTPHOrWildcardOrGeneric type) {
@@ -45,24 +27,12 @@ public class ResultSet {
} }
} }
//TODO Beim Einsetzen eines Generics, müssen die new und Methodenaufrufe verändert werden
public String toString() { public String toString() {
return results.toString(); return results.toString();
} }
@Override
public boolean equals(Object o) {
if (o instanceof ResultSet) {
ResultSet other = (ResultSet)o;
return this.results.equals(other.results);
} else {
return false;
}
}
@Override
public int hashCode() {
return results.hashCode();
}
} }
class Resolver implements ResultSetVisitor { class Resolver implements ResultSetVisitor {
@@ -70,7 +40,6 @@ class Resolver implements ResultSetVisitor {
private TypePlaceholder toResolve; private TypePlaceholder toResolve;
private RefTypeOrTPHOrWildcardOrGeneric resolved; private RefTypeOrTPHOrWildcardOrGeneric resolved;
private final Set<GenericInsertPair> additionalTPHs = new HashSet<>(); private final Set<GenericInsertPair> additionalTPHs = new HashSet<>();
private ResultPair<?,?> currentPair;
public Resolver(ResultSet resultPairs){ public Resolver(ResultSet resultPairs){
this.result = resultPairs; this.result = resultPairs;
@@ -80,28 +49,23 @@ class Resolver implements ResultSetVisitor {
toResolve = tph; toResolve = tph;
resolved = null; resolved = null;
System.out.println(tph.toString()); System.out.println(tph.toString());
for(ResultPair<?,?> resultPair : result.results) { for(ResultPair resultPair : result.results){
if(resultPair instanceof PairTPHEqualTPH && ((PairTPHEqualTPH) resultPair).getLeft().equals(toResolve)){ if(resultPair instanceof PairTPHEqualTPH && ((PairTPHEqualTPH) resultPair).getLeft().equals(toResolve)){
currentPair = resultPair;
return resolve(((PairTPHEqualTPH) resultPair).getRight()); return resolve(((PairTPHEqualTPH) resultPair).getRight());
} }
} }
for(ResultPair<?,?> resultPair : result.results){ for(ResultPair resultPair : result.results){
currentPair = resultPair;
resultPair.accept(this); resultPair.accept(this);
} }
if(resolved==null){//TPH kommt nicht im Result vor: if(resolved==null){//TPH kommt nicht im Result vor:
resolved = tph; resolved = tph;
} }
ResolvedType result = new ResolvedType(resolved, additionalTPHs);//resolved; return new ResolvedType(resolved, additionalTPHs);//resolved;
result.setResultPair(currentPair);
return result;
} }
@Override @Override
public void visit(PairTPHsmallerTPH p) { public void visit(PairTPHsmallerTPH p) {
currentPair = p;
if(p.left.equals(toResolve)){ if(p.left.equals(toResolve)){
additionalTPHs.add(new GenericInsertPair(p.left, p.right)); additionalTPHs.add(new GenericInsertPair(p.left, p.right));
additionalTPHs.addAll(new RelatedTypeWalker(p.right, result).relatedTPHs); additionalTPHs.addAll(new RelatedTypeWalker(p.right, result).relatedTPHs);
@@ -112,7 +76,6 @@ class Resolver implements ResultSetVisitor {
@Override @Override
public void visit(PairTPHequalRefTypeOrWildcardType p) { public void visit(PairTPHequalRefTypeOrWildcardType p) {
currentPair = p;
if(p.left.equals(toResolve)){ if(p.left.equals(toResolve)){
resolved = p.right; resolved = p.right;
RelatedTypeWalker related = new RelatedTypeWalker(null, result); RelatedTypeWalker related = new RelatedTypeWalker(null, result);
@@ -158,7 +121,6 @@ class Resolver implements ResultSetVisitor {
/** /**
* Sucht aus dem Result Set den Sub/supertyp für einen TPH * Sucht aus dem Result Set den Sub/supertyp für einen TPH
*/ */
@SuppressWarnings("rawtypes")
class TPHResolver implements ResultSetVisitor { class TPHResolver implements ResultSetVisitor {
private final TypePlaceholder tph; private final TypePlaceholder tph;
@@ -227,7 +189,6 @@ class TPHResolver implements ResultSetVisitor {
} }
} }
@SuppressWarnings("rawtypes")
class RelatedTypeWalker implements ResultSetVisitor { class RelatedTypeWalker implements ResultSetVisitor {
final Set<GenericInsertPair> relatedTPHs = new HashSet<>(); final Set<GenericInsertPair> relatedTPHs = new HashSet<>();

View File

@@ -65,9 +65,7 @@ public class TYPEStmt implements StatementVisitor{
//lambdaParams.add(0,tphRetType); //lambdaParams.add(0,tphRetType);
constraintsSet.addUndConstraint( constraintsSet.addUndConstraint(
new Pair(lambdaExpression.getType(), new Pair(lambdaExpression.getType(),
new RefType(new JavaClassName("Fun"+(lambdaParams.size()-1)+"$$"), lambdaParams, new NullToken()), new FunN(lambdaParams),PairOperator.EQUALSDOT));
//new FunN(lambdaParams),
PairOperator.EQUALSDOT));
constraintsSet.addUndConstraint( constraintsSet.addUndConstraint(
new Pair(lambdaExpression.getReturnType(), new Pair(lambdaExpression.getReturnType(),
tphRetType,PairOperator.EQUALSDOT)); tphRetType,PairOperator.EQUALSDOT));
@@ -312,9 +310,6 @@ public class TYPEStmt implements StatementVisitor{
numericAdditionOrStringConcatenation.add(stringConcat); numericAdditionOrStringConcatenation.add(stringConcat);
} }
} }
if(numericAdditionOrStringConcatenation.size()<1){
throw new TypeinferenceException("Kein Typ für " + binary.operation.toString() + " vorhanden", binary.getOffset());
}
constraintsSet.addOderConstraint(numericAdditionOrStringConcatenation); constraintsSet.addOderConstraint(numericAdditionOrStringConcatenation);
}else if(binary.operation.equals(BinaryExpr.Operator.LESSEQUAL) || }else if(binary.operation.equals(BinaryExpr.Operator.LESSEQUAL) ||
binary.operation.equals(BinaryExpr.Operator.BIGGEREQUAL) || binary.operation.equals(BinaryExpr.Operator.BIGGEREQUAL) ||
@@ -358,7 +353,6 @@ public class TYPEStmt implements StatementVisitor{
//***ACHTUNG: Moeglicherweise oder und und-Contraint falsch //***ACHTUNG: Moeglicherweise oder und und-Contraint falsch
*/ */
//Testeise eingefuegt PL 2018-05-24 //Testeise eingefuegt PL 2018-05-24
//Hier sollte evtl. noch importe angefragt werden PL 2019-05-07
constraintsSet.addUndConstraint(new Pair(binary.lexpr.getType(), number, PairOperator.SMALLERNEQDOT)); constraintsSet.addUndConstraint(new Pair(binary.lexpr.getType(), number, PairOperator.SMALLERNEQDOT));
constraintsSet.addUndConstraint(new Pair(binary.rexpr.getType(), number, PairOperator.SMALLERNEQDOT)); constraintsSet.addUndConstraint(new Pair(binary.rexpr.getType(), number, PairOperator.SMALLERNEQDOT));
//Rückgabetyp ist Boolean //Rückgabetyp ist Boolean

View File

@@ -0,0 +1,132 @@
package de.dhbwstuttgart.typeinference.unify;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.Vector;
import com.google.common.collect.Ordering;
public class PartialOrderSet<E, F extends Ordering<E>> implements Set<E> {
//HashSet<E> hs = new HashSet<>();
List<E> ve = new LinkedList<>();//new Vector<>();
F ordering;
PartialOrderSet(F ordering) {
this.ordering= ordering;
}
PartialOrderSet(F ordering, Set<E> s) {
this.ordering= ordering;
this.addAll(s);
}
PartialOrderSet(PartialOrderSet<E, F> pos) {
this.ordering= pos.ordering;
this.ve = new LinkedList<>(pos.ve);
}
@Override
public int size() {
return ve.size();
}
@Override
public boolean isEmpty() {
return ve.isEmpty();
}
@Override
public boolean contains(Object o) {
return ve.contains(o);
}
@Override
public Iterator<E> iterator() {
return ve.iterator();
}
@Override
public Object[] toArray() {
return ve.toArray();
}
@Override
public <T> T[] toArray(T[] a) {
return ve.toArray(a);
}
public ArrayList<E> toArrayList() {
return new ArrayList<>(ve);
}
public List<E> toList() {
return new LinkedList<>(ve);
}
@Override
public boolean add(E e) {
if (this.contains(e)) {
return false;
}
//hs.add(e);
for(int i = 0; i< ve.size(); i++) {
if (ordering.compare(e, ve.get(i)) == -1) {
ve.add(i,e);
return true;
}
}
ve.add(e);
return true;
}
@Override
public boolean remove(Object o) {
//hs.remove(o);
return ve.remove(o);
}
@Override
public boolean containsAll(Collection<?> c) {
return ve.containsAll(c);
}
@Override
public boolean addAll(Collection<? extends E> c) {
Boolean ret = false;
Iterator<? extends E> cit = c.iterator();
while(cit.hasNext()) {
Boolean retnew = this.add(cit.next());
ret = ret || retnew;
}
return ret;
}
@Override
public boolean retainAll(Collection<?> c) {
//hs.retainAll(c);
return ve.retainAll(c);
}
@Override
public boolean removeAll(Collection<?> c) {
//hs.removeAll(c);
return ve.removeAll(c);
}
@Override
public void clear() {
//hs.clear();
ve.clear();
}
@Override
public String toString() {
return ve.toString();
}
}

View File

@@ -4,12 +4,10 @@ import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.List;
import java.util.Optional; import java.util.Optional;
import java.util.Queue; import java.util.Queue;
import java.util.Set; import java.util.Set;
import java.util.Stack; import java.util.Stack;
import java.util.function.Function;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import de.dhbwstuttgart.exceptions.DebugException; import de.dhbwstuttgart.exceptions.DebugException;
@@ -30,7 +28,6 @@ import de.dhbwstuttgart.typeinference.unify.distributeVariance;
import java.io.FileWriter; import java.io.FileWriter;
import java.io.IOException; import java.io.IOException;
import java.io.Writer;
/** /**
* Implementation of the type inference rules. * Implementation of the type inference rules.
@@ -39,13 +36,13 @@ import java.io.Writer;
*/ */
public class RuleSet implements IRuleSet{ public class RuleSet implements IRuleSet{
Writer logFile; FileWriter logFile;
public RuleSet() { public RuleSet() {
super(); super();
} }
RuleSet(Writer logFile) { RuleSet(FileWriter logFile) {
this.logFile = logFile; this.logFile = logFile;
} }
@@ -622,12 +619,8 @@ public class RuleSet implements IRuleSet{
return succ ? permutation : new int[0]; return succ ? permutation : new int[0];
} }
public Optional<Set<UnifyPair>> subst(Set<UnifyPair> pairs) {
return subst(pairs, new ArrayList<>());
}
@Override @Override
public Optional<Set<UnifyPair>> subst(Set<UnifyPair> pairs, List<Set<Set<UnifyPair>>> oderConstraints) { public Optional<Set<UnifyPair>> subst(Set<UnifyPair> pairs) {
HashMap<UnifyType, Integer> typeMap = new HashMap<>(); HashMap<UnifyType, Integer> typeMap = new HashMap<>();
Stack<UnifyType> occuringTypes = new Stack<>(); Stack<UnifyType> occuringTypes = new Stack<>();
@@ -667,35 +660,13 @@ public class RuleSet implements IRuleSet{
if(lhsType != null if(lhsType != null
//&& !((rhsType = pair.getRhsType()) instanceof PlaceholderType) //PL geloescht am 2017-09-29 Begründung: auch Typvariablen muessen ersetzt werden. //&& !((rhsType = pair.getRhsType()) instanceof PlaceholderType) //PL geloescht am 2017-09-29 Begründung: auch Typvariablen muessen ersetzt werden.
&& typeMap.get(lhsType) > 1 // The type occurs in more pairs in the set than just the recent pair. && typeMap.get(lhsType) > 1 // The type occurs in more pairs in the set than just the recent pair.
&& !rhsType.getTypeParams().occurs(lhsType) && !rhsType.getTypeParams().occurs(lhsType)) {
&& !((rhsType instanceof WildcardType) && ((WildcardType)rhsType).getWildcardedType().equals(lhsType))) //PL eigefuegt 2018-02-18
{
Unifier uni = new Unifier(lhsType, rhsType); Unifier uni = new Unifier(lhsType, rhsType);
result = result.stream().map(x -> uni.apply(pair,x)).collect(Collectors.toCollection(ArrayList::new)); 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)); result1 = result1.stream().map(x -> uni.apply(pair,x)).collect(Collectors.toCollection(LinkedList::new));
Function<? super Set<UnifyPair>,? extends HashSet<UnifyPair>> applyUni = b -> b.stream().map(
x -> uni.apply(pair,x)).collect(Collectors.toCollection(HashSet::new));
List<Set<Set<UnifyPair>>> oderConstraintsRet = new ArrayList<>();
for(Set<Set<UnifyPair>> oc : oderConstraints) {
//Set<Set<UnifyPair>> ocRet = new HashSet<>();
//for(Set<UnifyPair> cs : oc) {
Set<Set<UnifyPair>> csRet = oc.stream().map(applyUni).collect(Collectors.toCollection(HashSet::new));
oderConstraintsRet.add(csRet);
//}
}
oderConstraints.replaceAll(oc -> oc.stream().map(applyUni).collect(Collectors.toCollection(HashSet::new)));
/*
oderConstraints = oderConstraints.stream().map(
a -> a.stream().map(applyUni
//b -> b.stream().map(
// x -> uni.apply(pair,x)).collect(Collectors.toCollection(HashSet::new) )
).collect(Collectors.toCollection(HashSet::new))
).collect(Collectors.toList(ArrayList::new));
}
*/
applied = true; applied = true;
} }
result.add(pair); result.add(pair);
} }
@@ -974,8 +945,6 @@ public class RuleSet implements IRuleSet{
UnifyType extendedType = ((ExtendsType)lhsType).getExtendedType(); UnifyType extendedType = ((ExtendsType)lhsType).getExtendedType();
if (extendedType.equals(rhsType)) return Optional.empty(); //PL 2019-02-18 eingefügt ? extends a <.? a
boolean isGen = extendedType instanceof PlaceholderType && !((PlaceholderType) extendedType).isGenerated(); boolean isGen = extendedType instanceof PlaceholderType && !((PlaceholderType) extendedType).isGenerated();
Set<UnifyPair> result = new HashSet<>(); Set<UnifyPair> result = new HashSet<>();
@@ -1002,8 +971,6 @@ public class RuleSet implements IRuleSet{
UnifyType superedType = ((SuperType)lhsType).getSuperedType(); UnifyType superedType = ((SuperType)lhsType).getSuperedType();
if (superedType.equals(rhsType)) return Optional.empty(); //PL 2019-02-18 eingefügt ? super a <.? a
boolean isGen = superedType instanceof PlaceholderType && !((PlaceholderType) superedType).isGenerated(); boolean isGen = superedType instanceof PlaceholderType && !((PlaceholderType) superedType).isGenerated();
Set<UnifyPair> result = new HashSet<>(); Set<UnifyPair> result = new HashSet<>();

View File

@@ -1,89 +1,47 @@
package de.dhbwstuttgart.typeinference.unify; package de.dhbwstuttgart.typeinference.unify;
import java.io.FileWriter; import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import java.util.concurrent.ForkJoinPool; import java.util.concurrent.ForkJoinPool;
import java.util.stream.Collectors;
import de.dhbwstuttgart.core.JavaTXCompiler;
import de.dhbwstuttgart.typeinference.constraints.Constraint; import de.dhbwstuttgart.typeinference.constraints.Constraint;
import de.dhbwstuttgart.typeinference.constraints.ConstraintSet; import de.dhbwstuttgart.typeinference.constraints.ConstraintSet;
import de.dhbwstuttgart.typeinference.constraints.Pair; import de.dhbwstuttgart.typeinference.constraints.Pair;
import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure; import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure;
import de.dhbwstuttgart.typeinference.unify.model.FiniteClosure; import de.dhbwstuttgart.typeinference.unify.model.FiniteClosure;
import de.dhbwstuttgart.typeinference.unify.model.OrderingUnifyPair;
import de.dhbwstuttgart.typeinference.unify.model.UnifyPair; import de.dhbwstuttgart.typeinference.unify.model.UnifyPair;
public class TypeUnify { public class TypeUnify {
public Set<Set<UnifyPair>> unify(Set<UnifyPair> undConstrains, List<Set<Set<UnifyPair>>> oderConstraints, IFiniteClosure fc, FileWriter logFile, Boolean log, ConstraintSet<Pair> cons) {
/** List<PartialOrderSet<Set<UnifyPair>,OrderingUnifyPair>> oderConstraintsPartial =
* unify parallel ohne result modell oderConstraints.stream().map(x -> new PartialOrderSet<Set<UnifyPair>,OrderingUnifyPair>(new OrderingUnifyPair(fc),x)).collect(Collectors.toList());
* @param undConstrains TypeUnifyTask unifyTask = new TypeUnifyTask(undConstrains, oderConstraintsPartial, fc, true, logFile, log, 0, new UnifyResultModel(), cons);
* @param oderConstraints
* @param fc
* @param logFile
* @param log
* @param cons
* @return
*/
public Set<Set<UnifyPair>> unify(Set<UnifyPair> undConstrains, List<Set<Set<UnifyPair>>> 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(); ForkJoinPool pool = new ForkJoinPool();
pool.invoke(unifyTask); pool.invoke(unifyTask);
Set<Set<UnifyPair>> res = unifyTask.join(); Set<Set<UnifyPair>> res = unifyTask.join();
try {
logFile.write("\nnoShortendElements: " + unifyTask.noShortendElements + "\n");
logFile.flush();
}
catch (IOException e) {
System.err.println("no log-File");
}
return res; return res;
} }
/** public UnifyResultModel unifyAsync(Set<UnifyPair> undConstrains, List<Set<Set<UnifyPair>>> oderConstraints, IFiniteClosure fc, FileWriter logFile, Boolean log, ConstraintSet<Pair> cons, UnifyResultModel ret) {
* unify asynchron mit Rückgabe UnifyResultModel ohne dass alle results gesammelt sind List<PartialOrderSet<Set<UnifyPair>,OrderingUnifyPair>> oderConstraintsPartial =
* @param undConstrains oderConstraints.stream().map(x -> new PartialOrderSet<Set<UnifyPair>,OrderingUnifyPair>(new OrderingUnifyPair(fc),x)).collect(Collectors.toList());
* @param oderConstraints TypeUnifyTask unifyTask = new TypeUnifyTask(undConstrains, oderConstraintsPartial, fc, true, logFile, log, 0, ret, cons);
* @param fc
* @param logFile
* @param log
* @param cons
* @param ret
* @return
*/
public UnifyResultModel unifyAsync(Set<UnifyPair> undConstrains, List<Set<Set<UnifyPair>>> 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(); ForkJoinPool pool = new ForkJoinPool();
pool.invoke(unifyTask); pool.invoke(unifyTask);
return ret; return ret;
} }
/** public UnifyResultModel unifyParallel(Set<UnifyPair> undConstrains, List<Set<Set<UnifyPair>>> oderConstraints, IFiniteClosure fc, FileWriter logFile, Boolean log, ConstraintSet<Pair> cons, UnifyResultModel ret) {
* unify parallel mit Rückgabe UnifyResultModel nachdem alle results gesammelt sind List<PartialOrderSet<Set<UnifyPair>,OrderingUnifyPair>> oderConstraintsPartial =
* @param undConstrains oderConstraints.stream().map(x -> new PartialOrderSet<Set<UnifyPair>,OrderingUnifyPair>(new OrderingUnifyPair(fc),x)).collect(Collectors.toList());
* @param oderConstraints TypeUnifyTask unifyTask = new TypeUnifyTask(undConstrains, oderConstraintsPartial, fc, true, logFile, log, 0, ret, cons);
* @param fc
* @param logFile
* @param log
* @param cons
* @param ret
* @return
*/
public UnifyResultModel unifyParallel(Set<UnifyPair> undConstrains, List<Set<Set<UnifyPair>>> 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(); ForkJoinPool pool = new ForkJoinPool();
pool.invoke(unifyTask); pool.invoke(unifyTask);
Set<Set<UnifyPair>> res = unifyTask.join(); Set<Set<UnifyPair>> res = unifyTask.join();
try {
logFile.write("\nnoShortendElements: " + unifyTask.noShortendElements +"\n");
logFile.flush();
}
catch (IOException e) {
System.err.println("no log-File");
}
return ret; return ret;
} }
@@ -95,26 +53,11 @@ public class TypeUnify {
} }
*/ */
/** public Set<Set<UnifyPair>> unifyOderConstraints(Set<UnifyPair> undConstrains, List<Set<Set<UnifyPair>>> oderConstraints, IFiniteClosure fc, FileWriter logFile, Boolean log, ConstraintSet<Pair> cons) {
* unify sequentiell mit oderconstraints List<PartialOrderSet<Set<UnifyPair>,OrderingUnifyPair>> oderConstraintsPartial =
* @param undConstrains oderConstraints.stream().map(x -> new PartialOrderSet<Set<UnifyPair>,OrderingUnifyPair>(new OrderingUnifyPair(fc),x)).collect(Collectors.toList());
* @param oderConstraints TypeUnifyTask unifyTask = new TypeUnifyTask(undConstrains, oderConstraintsPartial, fc, false, logFile, log, 0, new UnifyResultModel(), cons);
* @param fc
* @param logFile
* @param log
* @param cons
* @return
*/
public Set<Set<UnifyPair>> unifyOderConstraints(Set<UnifyPair> undConstrains, List<Set<Set<UnifyPair>>> 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<Set<UnifyPair>> res = unifyTask.compute(); Set<Set<UnifyPair>> res = unifyTask.compute();
try {
logFile.write("\nnoShortendElements: " + unifyTask.noShortendElements +"\n");
logFile.flush();
}
catch (IOException e) {
System.err.println("no log-File");
}
return res; return res;
} }

View File

@@ -1,9 +1,6 @@
package de.dhbwstuttgart.typeinference.unify; package de.dhbwstuttgart.typeinference.unify;
import java.io.FileWriter; import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashSet; import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
@@ -12,14 +9,15 @@ import de.dhbwstuttgart.typeinference.constraints.Constraint;
import de.dhbwstuttgart.typeinference.constraints.ConstraintSet; import de.dhbwstuttgart.typeinference.constraints.ConstraintSet;
import de.dhbwstuttgart.typeinference.constraints.Pair; import de.dhbwstuttgart.typeinference.constraints.Pair;
import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure; import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure;
import de.dhbwstuttgart.typeinference.unify.model.OrderingUnifyPair;
import de.dhbwstuttgart.typeinference.unify.model.UnifyPair; import de.dhbwstuttgart.typeinference.unify.model.UnifyPair;
public class TypeUnify2Task extends TypeUnifyTask { public class TypeUnify2Task extends TypeUnifyTask {
Set<Set<UnifyPair>> setToFlatten; Set<Set<UnifyPair>> setToFlatten;
public TypeUnify2Task(Set<Set<UnifyPair>> setToFlatten, Set<UnifyPair> eq, List<Set<Set<UnifyPair>>> oderConstraints, Set<UnifyPair> nextSetElement, IFiniteClosure fc, boolean parallel, Writer logFile, Boolean log, int rekTiefe, UnifyResultModel urm, UnifyTaskModel usedTasks) { public TypeUnify2Task(Set<Set<UnifyPair>> setToFlatten, Set<UnifyPair> eq, List<PartialOrderSet<Set<UnifyPair>,OrderingUnifyPair>> oderConstraints, Set<UnifyPair> nextSetElement, IFiniteClosure fc, boolean parallel, FileWriter logFile, Boolean log, int rekTiefe, UnifyResultModel urm, ConstraintSet<Pair> cons) {
super(eq, oderConstraints, fc, parallel, logFile, log, rekTiefe, urm, usedTasks); super(eq, oderConstraints, fc, parallel, logFile, log, rekTiefe, urm, cons);
this.setToFlatten = setToFlatten; this.setToFlatten = setToFlatten;
this.nextSetElement = nextSetElement; this.nextSetElement = nextSetElement;
} }
@@ -34,31 +32,12 @@ public class TypeUnify2Task extends TypeUnifyTask {
System.out.println("two"); System.out.println("two");
} }
one = true; one = true;
Set<Set<UnifyPair>> res = unify2(setToFlatten, eq, oderConstraintsField, fc, parallel, rekTiefeField, true); Set<Set<UnifyPair>> res = unify2(setToFlatten, eq, oderConstraintsField, fc, parallel, rekTiefeField);
/*if (isUndefinedPairSetSet(res)) { /*if (isUndefinedPairSetSet(res)) {
return new HashSet<>(); } return new HashSet<>(); }
else else
*/ */
//writeLog("xxx"); noOfThread--;
//noOfThread--;
synchronized (usedTasks) {
if (this.myIsCancelled()) {
return new HashSet<>();
}
else {
return res; return res;
} }
} }
}
public void closeLogFile() {
try {
logFile.close();
}
catch (IOException ioE) {
System.err.println("no log-File" + thNo);
}
}
}

View File

@@ -1,31 +1,13 @@
package de.dhbwstuttgart.typeinference.unify; package de.dhbwstuttgart.typeinference.unify;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Optional;
import java.util.Set; import java.util.Set;
import java.util.stream.Collectors;
import de.dhbwstuttgart.syntaxtree.factory.UnifyTypeFactory;
import de.dhbwstuttgart.typeinference.constraints.ConstraintSet;
import de.dhbwstuttgart.typeinference.result.ResultSet; import de.dhbwstuttgart.typeinference.result.ResultSet;
import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure;
import de.dhbwstuttgart.typeinference.unify.model.PairOperator;
import de.dhbwstuttgart.typeinference.unify.model.UnifyPair;
public class UnifyResultModel { public class UnifyResultModel {
ConstraintSet<de.dhbwstuttgart.typeinference.constraints.Pair> cons;
IFiniteClosure fc;
public UnifyResultModel(ConstraintSet<de.dhbwstuttgart.typeinference.constraints.Pair> cons,
IFiniteClosure fc) {
this.cons = cons;
this.fc = fc;
}
private List<UnifyResultListener> listeners = new ArrayList<>(); private List<UnifyResultListener> listeners = new ArrayList<>();
public void addUnifyResultListener(UnifyResultListener listenerToAdd) { public void addUnifyResultListener(UnifyResultListener listenerToAdd) {
@@ -36,20 +18,7 @@ public class UnifyResultModel {
listeners.remove(listenerToRemove); listeners.remove(listenerToRemove);
} }
public void notify(Set<Set<UnifyPair>> eqPrimePrimeSet) { public void notify(List<ResultSet> newResult) {
Set<Set<UnifyPair>> eqPrimePrimeSetRet = eqPrimePrimeSet.stream().map(x -> {
Optional<Set<UnifyPair>> res = new RuleSet().subst(x.stream().map(y -> {
if (y.getPairOp() == PairOperator.SMALLERDOTWC) y.setPairOp(PairOperator.EQUALSDOT);
return y; //alle Paare a <.? b erden durch a =. b ersetzt
}).collect(Collectors.toCollection(HashSet::new)));
if (res.isPresent()) {//wenn subst ein Erg liefert wurde was veraendert
return new TypeUnifyTask().applyTypeUnificationRules(res.get(), fc);
}
else return x; //wenn nichts veraendert wurde wird x zurueckgegeben
}).collect(Collectors.toCollection(HashSet::new));
List<ResultSet> newResult = eqPrimePrimeSetRet.stream().map(unifyPairs ->
new ResultSet(UnifyTypeFactory.convert(unifyPairs, de.dhbwstuttgart.typeinference.constraints.Pair.generateTPHMap(cons))))
.collect(Collectors.toList());
UnifyResultEvent evt = new UnifyResultEvent(newResult); UnifyResultEvent evt = new UnifyResultEvent(newResult);
for (UnifyResultListener listener : listeners) { for (UnifyResultListener listener : listeners) {

View File

@@ -1,18 +0,0 @@
package de.dhbwstuttgart.typeinference.unify;
import java.util.ArrayList;
public class UnifyTaskModel {
ArrayList<TypeUnifyTask> usedTasks = new ArrayList<>();
public synchronized void add(TypeUnifyTask t) {
usedTasks.add(t);
}
public synchronized void cancel() {
for(TypeUnifyTask t : usedTasks) {
t.myCancel(true);
}
}
}

View File

@@ -1,6 +1,5 @@
package de.dhbwstuttgart.typeinference.unify.interfaces; package de.dhbwstuttgart.typeinference.unify.interfaces;
import java.util.List;
import java.util.Optional; import java.util.Optional;
import java.util.Set; import java.util.Set;
@@ -86,13 +85,6 @@ public interface IRuleSet {
public Optional<UnifyPair> adaptExt(UnifyPair pair, IFiniteClosure fc); public Optional<UnifyPair> adaptExt(UnifyPair pair, IFiniteClosure fc);
public Optional<UnifyPair> adaptSup(UnifyPair pair, IFiniteClosure fc); public Optional<UnifyPair> adaptSup(UnifyPair pair, IFiniteClosure fc);
/**
* Applies the subst-Rule to a set of pairs (usually Eq').
* @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<Set<UnifyPair>> subst(Set<UnifyPair> pairs, List<Set<Set<UnifyPair>>> oderConstraints);
/** /**
* Applies the subst-Rule to a set of pairs (usually Eq'). * Applies the subst-Rule to a set of pairs (usually Eq').
* @param pairs The set of pairs where the subst rule should apply. * @param pairs The set of pairs where the subst rule should apply.

View File

@@ -2,7 +2,6 @@ package de.dhbwstuttgart.typeinference.unify.model;
import java.io.FileWriter; import java.io.FileWriter;
import java.io.IOException; import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
@@ -13,7 +12,6 @@ import java.util.Optional;
import java.util.Set; import java.util.Set;
import java.util.function.BiFunction; import java.util.function.BiFunction;
import java.util.function.BinaryOperator; import java.util.function.BinaryOperator;
import java.util.function.Predicate;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import com.google.common.collect.Ordering; import com.google.common.collect.Ordering;
@@ -34,7 +32,7 @@ import de.dhbwstuttgart.typeinference.unify.interfaces.IUnify;
public class FiniteClosure //extends Ordering<UnifyType> //entfernt PL 2018-12-11 public class FiniteClosure //extends Ordering<UnifyType> //entfernt PL 2018-12-11
implements IFiniteClosure { implements IFiniteClosure {
Writer logFile; FileWriter logFile;
static Boolean log = false; static Boolean log = false;
public void setLogTrue() { public void setLogTrue() {
log = true; log = true;
@@ -68,7 +66,7 @@ implements IFiniteClosure {
/** /**
* Creates a new instance using the inheritance tree defined in the pairs. * Creates a new instance using the inheritance tree defined in the pairs.
*/ */
public FiniteClosure(Set<UnifyPair> pairs, Writer logFile) { public FiniteClosure(Set<UnifyPair> pairs, FileWriter logFile) {
this.logFile = logFile; this.logFile = logFile;
this.pairs = new HashSet<>(pairs); this.pairs = new HashSet<>(pairs);
inheritanceGraph = new HashMap<UnifyType, Node<UnifyType>>(); inheritanceGraph = new HashMap<UnifyType, Node<UnifyType>>();
@@ -658,16 +656,11 @@ implements IFiniteClosure {
if (left.getName().equals("Matrix") || right.getName().equals("Matrix")) if (left.getName().equals("Matrix") || right.getName().equals("Matrix"))
System.out.println(""); System.out.println("");
/* /*
pairop = PairOperator.SMALLERDOTWC;
List<UnifyType> al = new ArrayList<>(); List<UnifyType> al = new ArrayList<>();
PlaceholderType xx =new PlaceholderType("xx"); PlaceholderType xx =new PlaceholderType("xx");
al.add(xx); al.add(xx);
left = new ExtendsType(new ReferenceType("Vector", new TypeParams(al))); left = new ExtendsType(new ReferenceType("Vector", new TypeParams(al)));
right = new ReferenceType("Vector", new TypeParams(new ArrayList<>(al)));
List<UnifyType> alr = new ArrayList<>();
UnifyType exx = new ExtendsType(xx);
alr.add(exx);
right = new ExtendsType(new ReferenceType("Vector", new TypeParams(alr)));
*/ */
/* /*
List<UnifyType> al = new ArrayList<>(); List<UnifyType> al = new ArrayList<>();
@@ -719,12 +712,7 @@ implements IFiniteClosure {
catch (IOException e) { catch (IOException e) {
System.err.println("no LogFile");}} System.err.println("no LogFile");}}
//Gleichungen der Form a <./=. Theta oder Theta <./=. a oder a <./=. b sind ok. //Gleichungen der Form a <./=. Theta oder Theta <./=. a oder a <./=. b sind ok.
Predicate<UnifyPair> delFun = x -> !((x.getLhsType() instanceof PlaceholderType || long smallerLen = smallerRes.stream().filter(x -> !(x.getLhsType() instanceof PlaceholderType || x.getRhsType() instanceof PlaceholderType)).count();
x.getRhsType() instanceof PlaceholderType)
&& !((x.getLhsType() instanceof WildcardType) && //? extends/super a <.? a
((WildcardType)x.getLhsType()).getWildcardedType().equals(x.getRhsType()))
);
long smallerLen = smallerRes.stream().filter(delFun).count();
if (smallerLen == 0) return -1; if (smallerLen == 0) return -1;
else { else {
up = new UnifyPair(right, left, pairop); up = new UnifyPair(right, left, pairop);
@@ -740,7 +728,7 @@ implements IFiniteClosure {
catch (IOException e) { catch (IOException e) {
System.err.println("no LogFile");}} System.err.println("no LogFile");}}
//Gleichungen der Form a <./=. Theta oder Theta <./=. a oder a <./=. b sind ok. //Gleichungen der Form a <./=. Theta oder Theta <./=. a oder a <./=. b sind ok.
long greaterLen = greaterRes.stream().filter(delFun).count(); long greaterLen = greaterRes.stream().filter(x -> !(x.getLhsType() instanceof PlaceholderType || x.getRhsType() instanceof PlaceholderType)).count();
if (greaterLen == 0) return 1; if (greaterLen == 0) return 1;
else return 0; else return 0;
} }

View File

@@ -22,7 +22,7 @@ public class FunNType extends UnifyType {
* Creates a FunN-Type with the specified TypeParameters. * Creates a FunN-Type with the specified TypeParameters.
*/ */
protected FunNType(TypeParams p) { protected FunNType(TypeParams p) {
super("Fun"+(p.size()-1)+"$$", p); super("Fun"+(p.size()-1), p);
} }
/** /**

View File

@@ -1,11 +1,9 @@
package de.dhbwstuttgart.typeinference.unify.model; package de.dhbwstuttgart.typeinference.unify.model;
import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.List;
import java.util.Optional; import java.util.Optional;
import java.util.Set; import java.util.Set;
import java.util.function.BinaryOperator; import java.util.function.BinaryOperator;
@@ -32,25 +30,14 @@ public class OrderingUnifyPair extends Ordering<Set<UnifyPair>> {
* in dem compare(Theta, Theta') aufgerufen wird. * in dem compare(Theta, Theta') aufgerufen wird.
*/ */
public int compareEq (UnifyPair left, UnifyPair right) { public int compareEq (UnifyPair left, UnifyPair right) {
try {
//if (left.getRhsType() instanceof WildcardType || right.getRhsType() instanceof WildcardType) {//PL 2019-01-12 ausgetauscht //if (left.getRhsType() instanceof WildcardType || right.getRhsType() instanceof WildcardType) {//PL 2019-01-12 ausgetauscht
if (((PlaceholderType)left.getLhsType()).isInnerType() && ((PlaceholderType)right.getLhsType()).isInnerType()) { if (((PlaceholderType)left.getLhsType()).isInnerType() && ((PlaceholderType)right.getLhsType()).isInnerType()) {
return fc.compare(left.getRhsType(), right.getRhsType(), PairOperator.SMALLERDOTWC); return fc.compare(left.getRhsType(), right.getRhsType(), PairOperator.SMALLERDOTWC);
} }
else { else {
return fc.compare(left.getRhsType(), right.getRhsType(), PairOperator.SMALLERDOT); return fc.compare(left.getRhsType(), right.getRhsType(), PairOperator.SMALLERDOT);
}}
catch (ClassCastException e) {
try {
((FiniteClosure)fc).logFile.write("ClassCastException: " + left.toString() +"\n\n");
((FiniteClosure)fc).logFile.flush();
}
catch (IOException ie) {
}
return -99;
} }
} }
/* /*
public int compareEq (UnifyPair left, UnifyPair right) { public int compareEq (UnifyPair left, UnifyPair right) {
if (left == null || right == null) if (left == null || right == null)
@@ -128,43 +115,6 @@ public class OrderingUnifyPair extends Ordering<Set<UnifyPair>> {
* @see com.google.common.collect.Ordering#compare(java.lang.Object, java.lang.Object) * @see com.google.common.collect.Ordering#compare(java.lang.Object, java.lang.Object)
*/ */
public int compare (Set<UnifyPair> left, Set<UnifyPair> right) { public int compare (Set<UnifyPair> left, Set<UnifyPair> right) {
/*
//pairop = PairOperator.SMALLERDOTWC;
List<UnifyType> al = new ArrayList<>();
PlaceholderType xx = PlaceholderType.freshPlaceholder();
al.add(xx);
UnifyType t1 = new ExtendsType(new ReferenceType("Vector", new TypeParams(al)));
//PlaceholderType yy =new PlaceholderType("yy");
List<UnifyType> alr = new ArrayList<>();
UnifyType exx = new ExtendsType(xx);
alr.add(exx);
UnifyType t2 = new ExtendsType(new ReferenceType("Vector", new TypeParams(alr)));
PlaceholderType a = PlaceholderType.freshPlaceholder();
a.setInnerType(true);
UnifyPair p1 = new UnifyPair(a, t1, PairOperator.SMALLERDOTWC);
PlaceholderType b = PlaceholderType.freshPlaceholder();
b.setInnerType(true);
UnifyPair p2 = new UnifyPair(b, t2, PairOperator.SMALLERDOTWC);
List<UnifyType> al3 = new ArrayList<>();
al3.add(a);
List<UnifyType> al4 = new ArrayList<>();
al4.add(b);
UnifyPair p3 = new UnifyPair(new PlaceholderType("c"), new ReferenceType("Vector", new TypeParams(al3)), PairOperator.EQUALSDOT);
UnifyPair p4 = new UnifyPair(new PlaceholderType("c"), new ReferenceType("Vector", new TypeParams(al4)), PairOperator.EQUALSDOT);
right = new HashSet<>();
right.add(p1);
right.add(p3);
left = new HashSet<>();
left.add(p2);
left.add(p4);
*/
if ((left.size() == 1) && right.size() == 1) { if ((left.size() == 1) && right.size() == 1) {
if (left.iterator().next().getLhsType().getName().equals("AFS")) { if (left.iterator().next().getLhsType().getName().equals("AFS")) {
System.out.println(""); System.out.println("");
@@ -248,9 +198,9 @@ public class OrderingUnifyPair extends Ordering<Set<UnifyPair>> {
//Set<PlaceholderType> varsleft = lefteq.stream().map(x -> (PlaceholderType)x.getLhsType()).collect(Collectors.toCollection(HashSet::new)); //Set<PlaceholderType> varsleft = lefteq.stream().map(x -> (PlaceholderType)x.getLhsType()).collect(Collectors.toCollection(HashSet::new));
//Set<PlaceholderType> varsright = righteq.stream().map(x -> (PlaceholderType)x.getLhsType()).collect(Collectors.toCollection(HashSet::new)); //Set<PlaceholderType> varsright = righteq.stream().map(x -> (PlaceholderType)x.getLhsType()).collect(Collectors.toCollection(HashSet::new));
//filtern des Paares a = Theta, das durch a <. Thata' generiert wurde (nur im Fall 1 relevant) andere Substitutioen werden rausgefiltert //filtern des Paares a = Theta, das durch a <. Thata' generiert wurde (nur im Fall 1 relevant) andere Substitutioen werden rausgefiltert
lefteq.removeIf(x -> (x.getBasePair()!=null) && !(x.getLhsType().getName().equals(x.getBasePair().getLhsType().getName()) lefteq.removeIf(x -> !(x.getLhsType().getName().equals(x.getBasePair().getLhsType().getName())
||x.getLhsType().getName().equals(x.getBasePair().getRhsType().getName())));//removeIf(x -> !varsright.contains(x.getLhsType())); ||x.getLhsType().getName().equals(x.getBasePair().getRhsType().getName())));//removeIf(x -> !varsright.contains(x.getLhsType()));
righteq.removeIf(x -> (x.getBasePair()!=null) && !(x.getLhsType().getName().equals(x.getBasePair().getLhsType().getName()) righteq.removeIf(x -> !(x.getLhsType().getName().equals(x.getBasePair().getLhsType().getName())
||x.getLhsType().getName().equals(x.getBasePair().getRhsType().getName())));//.removeIf(x -> !varsleft.contains(x.getLhsType())); ||x.getLhsType().getName().equals(x.getBasePair().getRhsType().getName())));//.removeIf(x -> !varsleft.contains(x.getLhsType()));
UnifyPair lseq = lefteq.iterator().next(); UnifyPair lseq = lefteq.iterator().next();
UnifyPair rseq = righteq.iterator().next(); UnifyPair rseq = righteq.iterator().next();

View File

@@ -11,43 +11,26 @@ import de.dhbwstuttgart.typeinference.unify.interfaces.UnifyTypeVisitor;
* @author Florian Steurer * @author Florian Steurer
* *
*/ */
public class ReferenceType extends UnifyType { public final class ReferenceType extends UnifyType {
/** /**
* The buffered hashCode * The buffered hashCode
*/ */
private final int hashCode; private final int hashCode;
/**
* gibt an, ob der ReferenceType eine generische Typvariable ist
*/
private final boolean genericTypeVar;
public <T> UnifyType accept(UnifyTypeVisitor<T> visitor, T ht) { public <T> UnifyType accept(UnifyTypeVisitor<T> visitor, T ht) {
return visitor.visit(this, ht); return visitor.visit(this, ht);
} }
public ReferenceType(String name, Boolean genericTypeVar) {
super(name, new TypeParams());
hashCode = 31 + 17 * typeName.hashCode() + 17 * typeParams.hashCode();
this.genericTypeVar = genericTypeVar;
}
public ReferenceType(String name, UnifyType... params) { public ReferenceType(String name, UnifyType... params) {
super(name, new TypeParams(params)); super(name, new TypeParams(params));
hashCode = 31 + 17 * typeName.hashCode() + 17 * typeParams.hashCode(); hashCode = 31 + 17 * typeName.hashCode() + 17 * typeParams.hashCode();
genericTypeVar = false;
} }
public ReferenceType(String name, TypeParams params) { public ReferenceType(String name, TypeParams params) {
super(name, params); super(name, params);
hashCode = 31 + 17 * typeName.hashCode() + 17 * typeParams.hashCode(); hashCode = 31 + 17 * typeName.hashCode() + 17 * typeParams.hashCode();
genericTypeVar = false;
}
public boolean isGenTypeVar () {
return genericTypeVar;
} }
@Override @Override

View File

@@ -137,7 +137,7 @@ public class UnifyPair {
undefinedPair = true; undefinedPair = true;
} }
public Set<UnifyPair> getSubstitution() { public Set<UnifyPair> getSubstitution() {
return new HashSet<>(substitution); return substitution;
} }
public UnifyPair getBasePair() { public UnifyPair getBasePair() {
@@ -149,9 +149,9 @@ public class UnifyPair {
public Set<UnifyPair> getAllSubstitutions () { public Set<UnifyPair> getAllSubstitutions () {
Set<UnifyPair> ret = new HashSet<>(); Set<UnifyPair> ret = new HashSet<>();
ret.addAll(new ArrayList<>(getSubstitution())); ret.addAll(getSubstitution());
if (basePair != null) { if (basePair != null) {
ret.addAll(new ArrayList<>(basePair.getAllSubstitutions())); ret.addAll(basePair.getAllSubstitutions());
} }
return ret; return ret;
} }
@@ -177,20 +177,6 @@ public class UnifyPair {
} }
} }
/**
* wenn in einem Paar bestehend aus 2 Typvariablen eine nicht wildcardtable ist,
* so beide auf nicht wildcardtable setzen
*/
public void disableCondWildcards() {
if (lhs instanceof PlaceholderType && rhs instanceof PlaceholderType
&& (!((PlaceholderType)lhs).isWildcardable() || !((PlaceholderType)rhs).isWildcardable()))
{
((PlaceholderType)lhs).disableWildcardtable();
((PlaceholderType)rhs).disableWildcardtable();
}
}
public Boolean wrongWildcard() { public Boolean wrongWildcard() {
return lhs.wrongWildcard() || rhs.wrongWildcard(); return lhs.wrongWildcard() || rhs.wrongWildcard();
} }
@@ -233,12 +219,10 @@ public class UnifyPair {
public String toString() { public String toString() {
String ret = ""; String ret = "";
if (lhs instanceof PlaceholderType) { if (lhs instanceof PlaceholderType) {
ret = new Integer(((PlaceholderType)lhs).getVariance()).toString() + " " + ((PlaceholderType)lhs).isInnerType() ret = new Integer(((PlaceholderType)lhs).getVariance()).toString() + " " + ((PlaceholderType)lhs).isInnerType();
+ " " + ((PlaceholderType)lhs).isWildcardable();
} }
if (rhs instanceof PlaceholderType) { if (rhs instanceof PlaceholderType) {
ret = ret + ", " + new Integer(((PlaceholderType)rhs).getVariance()).toString() + " " + ((PlaceholderType)rhs).isInnerType() ret = ret + ", " + new Integer(((PlaceholderType)rhs).getVariance()).toString() + " " + ((PlaceholderType)rhs).isInnerType();
+ " " + ((PlaceholderType)rhs).isWildcardable();
} }
return "(" + lhs + " " + pairOp + " " + rhs + ", " + ret + ")"; //+ ", [" + getfBounded().toString()+ "])"; return "(" + lhs + " " + pairOp + " " + rhs + ", " + ret + ")"; //+ ", [" + getfBounded().toString()+ "])";
} }

View File

@@ -37,14 +37,14 @@ public class BinaryTest {
public void test() throws Exception { public void test() throws Exception {
Method m2 = classToTest.getDeclaredMethod("m2", Integer.class,Integer.class); Method m2 = classToTest.getDeclaredMethod("m2", Integer.class,Integer.class);
Integer res = (Integer) m2.invoke(instanceOfClass, 2,3); Integer res = (Integer) m2.invoke(instanceOfClass, 2,3);
assertEquals(new Integer(6), res); assertEquals(6, res);
} }
@Test @Test
public void testM3() throws Exception { public void testM3() throws Exception {
Method m3 = classToTest.getDeclaredMethod("m3", Integer.class); Method m3 = classToTest.getDeclaredMethod("m3", Integer.class);
Integer res = (Integer) m3.invoke(instanceOfClass, 2); Integer res = (Integer) m3.invoke(instanceOfClass, 2);
assertEquals(new Integer(4), res); assertEquals(4, res);
} }
} }

View File

@@ -1,37 +0,0 @@
package bytecode;
import static org.junit.Assert.*;
import java.io.File;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import org.junit.BeforeClass;
import org.junit.Test;
import de.dhbwstuttgart.core.JavaTXCompiler;
public class ClassGenLamTest {
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 generateBC() throws Exception {
path = System.getProperty("user.dir")+"/src/test/resources/bytecode/javFiles/ClassGenLam.jav";
fileToTest = new File(path);
compiler = new JavaTXCompiler(fileToTest);
pathToClassFile = System.getProperty("user.dir")+"/src/test/resources/testBytecode/generatedBC/";
compiler.generateBytecode(pathToClassFile);
loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)});
classToTest = loader.loadClass("ClassGenLam");
instanceOfClass = classToTest.getDeclaredConstructor().newInstance();
}
}

View File

@@ -38,7 +38,7 @@ public class FacTest {
public void testInteger() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { public void testInteger() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Method getFac = classToTest.getDeclaredMethod("getFac", Integer.class); Method getFac = classToTest.getDeclaredMethod("getFac", Integer.class);
Integer result = (Integer) getFac.invoke(instanceOfClass,3); Integer result = (Integer) getFac.invoke(instanceOfClass,3);
assertEquals(result, new Integer(6)); assertEquals(result, 6);
} }
} }

View File

@@ -51,7 +51,7 @@ public class FacultyTest {
// Integer result = (Integer) apply.invoke(lambda,i); // Integer result = (Integer) apply.invoke(lambda,i);
Integer result = (Integer) getFact.invoke(instanceOfClass,i); Integer result = (Integer) getFact.invoke(instanceOfClass,i);
assertEquals(new Integer(6), result); assertEquals(6, result);
} }

View File

@@ -12,7 +12,7 @@ import org.junit.Test;
import de.dhbwstuttgart.core.JavaTXCompiler; import de.dhbwstuttgart.core.JavaTXCompiler;
public class TypedIDTest { public class FieldTph {
private static String path; private static String path;
private static File fileToTest; private static File fileToTest;
@@ -22,17 +22,22 @@ public class TypedIDTest {
private static String pathToClassFile; private static String pathToClassFile;
private static Object instanceOfClass; private static Object instanceOfClass;
@BeforeClass
@Test public static void setUpBeforeClass() throws Exception {
public void test() throws Exception { path = System.getProperty("user.dir")+"/src/test/resources/bytecode/javFiles/FieldTph.jav";
path = System.getProperty("user.dir")+"/src/test/resources/bytecode/javFiles/TypedID.jav";
fileToTest = new File(path); fileToTest = new File(path);
compiler = new JavaTXCompiler(fileToTest); compiler = new JavaTXCompiler(fileToTest);
compiler.generateBytecode(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/"; pathToClassFile = System.getProperty("user.dir")+"/src/test/resources/testBytecode/generatedBC/";
loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)});
classToTest = loader.loadClass("TypedID"); classToTest = loader.loadClass("FieldTph");
instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); instanceOfClass = classToTest.getDeclaredConstructor().newInstance();
} }
@Test
public void test() {
Field[] fields = classToTest.getFields();
assertEquals(1, fields.length);
}
} }

View File

@@ -32,19 +32,18 @@ public class FieldTphConsMethTest {
pathToClassFile = 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)}); loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)});
classToTest = loader.loadClass("FieldTphConsMeth"); classToTest = loader.loadClass("FieldTphConsMeth");
instanceOfClass = classToTest.getDeclaredConstructor().newInstance();
} }
@Test @Test
public void test() throws Exception { public void test() throws Exception {
instanceOfClass = classToTest.getConstructor(Object.class).newInstance("C");
Field a = classToTest.getDeclaredField("a"); Field a = classToTest.getDeclaredField("a");
a.setAccessible(true); a.setAccessible(true);
Method m = classToTest.getDeclaredMethod("id", Object.class); Method m = classToTest.getDeclaredMethod("m", Object.class);
Object result = m.invoke(instanceOfClass, 42); Object result = m.invoke(instanceOfClass, 42);
assertEquals(42,result); assertEquals(42,result);
assertEquals("C", a.get(instanceOfClass));
} }
} }

View File

@@ -1,66 +0,0 @@
package bytecode;
import static org.junit.Assert.*;
import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import org.junit.BeforeClass;
import org.junit.Test;
import de.dhbwstuttgart.core.JavaTXCompiler;
public class FieldTphMMethTest {
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;
private static Object instanceOfClass2;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
path = System.getProperty("user.dir")+"/src/test/resources/bytecode/javFiles/FieldTphMMeth.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("FieldTphMMeth");
instanceOfClass = classToTest.getConstructor(Object.class,Object.class,Boolean.class).newInstance("C",42,true);
instanceOfClass2 = classToTest.getConstructor(Object.class,Object.class,Boolean.class).newInstance("C",42,false);
}
@Test
public void testM() throws Exception {
Method m = classToTest.getDeclaredMethod("m", Object.class,Object.class,Boolean.class);
Object result = m.invoke(instanceOfClass, "C",42,false);
assertEquals(42,result);
}
@Test
public void testWithTrue() throws Exception {
Field a = classToTest.getDeclaredField("a");
a.setAccessible(true);
assertEquals("C", a.get(instanceOfClass));
}
@Test
public void testWithFalse() throws Exception {
Field a = classToTest.getDeclaredField("a");
a.setAccessible(true);
assertEquals(42, a.get(instanceOfClass2));
}
}

View File

@@ -12,7 +12,7 @@ import org.junit.Test;
import de.dhbwstuttgart.core.JavaTXCompiler; import de.dhbwstuttgart.core.JavaTXCompiler;
public class OLFunTest { public class FunOLTest {
private static String path; private static String path;
private static File fileToTest; private static File fileToTest;
private static JavaTXCompiler compiler; private static JavaTXCompiler compiler;
@@ -23,13 +23,13 @@ public class OLFunTest {
@Test @Test
public void generateBC() throws Exception { public void generateBC() throws Exception {
path = System.getProperty("user.dir")+"/src/test/resources/bytecode/javFiles/OLFun.jav"; path = System.getProperty("user.dir")+"/src/test/resources/bytecode/javFiles/FunOL.jav";
fileToTest = new File(path); fileToTest = new File(path);
compiler = new JavaTXCompiler(fileToTest); compiler = new JavaTXCompiler(fileToTest);
compiler.generateBytecode(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/"; pathToClassFile = System.getProperty("user.dir")+"/src/test/resources/testBytecode/generatedBC/";
loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)});
classToTest = loader.loadClass("OLFun"); classToTest = loader.loadClass("FunOL");
/* /*
instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); instanceOfClass = classToTest.getDeclaredConstructor().newInstance();

View File

@@ -8,10 +8,9 @@ import java.net.URL;
import java.net.URLClassLoader; import java.net.URLClassLoader;
import org.junit.BeforeClass; import org.junit.BeforeClass;
import org.junit.Test;
import de.dhbwstuttgart.core.JavaTXCompiler; import de.dhbwstuttgart.core.JavaTXCompiler;
import org.junit.Test;
public class IdTest { public class IdTest {

View File

@@ -1,37 +0,0 @@
package bytecode;
import static org.junit.Assert.*;
import java.io.File;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import org.junit.BeforeClass;
import org.junit.Test;
import de.dhbwstuttgart.core.JavaTXCompiler;
public class InfTest {
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 generateBC() throws Exception {
path = System.getProperty("user.dir")+"/src/test/resources/bytecode/javFiles/Inf.jav";
fileToTest = new File(path);
compiler = new JavaTXCompiler(fileToTest);
pathToClassFile = System.getProperty("user.dir")+"/src/test/resources/testBytecode/generatedBC/";
compiler.generateBytecode(pathToClassFile);
loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)});
classToTest = loader.loadClass("Inf");
instanceOfClass = classToTest.getDeclaredConstructor().newInstance();
}
}

View File

@@ -1,37 +0,0 @@
package bytecode;
import static org.junit.Assert.*;
import java.io.File;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import org.junit.BeforeClass;
import org.junit.Test;
import de.dhbwstuttgart.core.JavaTXCompiler;
public class KompTphTest {
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 generateBC() throws Exception {
path = System.getProperty("user.dir")+"/src/test/resources/bytecode/javFiles/KompTph.jav";
fileToTest = new File(path);
compiler = new JavaTXCompiler(fileToTest);
pathToClassFile = System.getProperty("user.dir")+"/src/test/resources/testBytecode/generatedBC/";
compiler.generateBytecode(pathToClassFile);
loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)});
classToTest = loader.loadClass("KompTph");
instanceOfClass = classToTest.getDeclaredConstructor().newInstance();
}
}

View File

@@ -43,7 +43,7 @@ public class LambdaTest {
System.out.println(m.invoke(instanceOfClass).toString()); System.out.println(m.invoke(instanceOfClass).toString());
Integer result = (Integer) apply.invoke(m.invoke(instanceOfClass), i); Integer result = (Integer) apply.invoke(m.invoke(instanceOfClass), i);
assertEquals(i, result); assertEquals(77, result);
} }

View File

@@ -4,7 +4,6 @@ import static org.junit.Assert.*;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.net.URL; import java.net.URL;
@@ -28,7 +27,7 @@ public class MatrixOpTest {
private static Object instanceOfClass_m3; private static Object instanceOfClass_m3;
@Test @Test
public void test() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, ClassNotFoundException, IOException, InstantiationException, NoSuchFieldException { public void test() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, ClassNotFoundException, IOException, InstantiationException {
path = System.getProperty("user.dir")+"/src/test/resources/bytecode/javFiles/MatrixOP.jav"; path = System.getProperty("user.dir")+"/src/test/resources/bytecode/javFiles/MatrixOP.jav";
fileToTest = new File(path); fileToTest = new File(path);
compiler = new JavaTXCompiler(fileToTest); compiler = new JavaTXCompiler(fileToTest);
@@ -36,7 +35,7 @@ public class MatrixOpTest {
compiler.generateBytecode(pathToClassFile); compiler.generateBytecode(pathToClassFile);
loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)});
classToTest = loader.loadClass("MatrixOP"); classToTest = loader.loadClass("MatrixOP");
/*
Vector<Vector<Integer>> vv = new Vector<Vector<Integer>>(); Vector<Vector<Integer>> vv = new Vector<Vector<Integer>>();
Vector<Integer> v1 = new Vector<Integer> (); Vector<Integer> v1 = new Vector<Integer> ();
v1.addElement(2); v1.addElement(2);
@@ -49,7 +48,6 @@ public class MatrixOpTest {
//m1.addElement(v2); //m1.addElement(v2);
vv.addElement(v1); vv.addElement(v1);
vv.addElement(v2); vv.addElement(v2);
instanceOfClass_m1 = classToTest.getDeclaredConstructor(Vector.class).newInstance(vv); //Matrix m1 = new Matrix(vv); instanceOfClass_m1 = classToTest.getDeclaredConstructor(Vector.class).newInstance(vv); //Matrix m1 = new Matrix(vv);
Vector<Vector<Integer>> vv1 = new Vector<Vector<Integer>>(); Vector<Vector<Integer>> vv1 = new Vector<Vector<Integer>>();
@@ -64,22 +62,13 @@ public class MatrixOpTest {
//m2.addElement(v4); //m2.addElement(v4);
vv1.addElement(v3); vv1.addElement(v3);
vv1.addElement(v4); vv1.addElement(v4);
instanceOfClass_m2 = classToTest.getDeclaredConstructor(Vector.class).newInstance(vv1);//Matrix m2 = new Matrix(vv1); instanceOfClass_m2 = classToTest.getDeclaredConstructor(Vector.class).newInstance(vv1);//Matrix m2 = new Matrix(vv1);
//Matrix m3 = m1.mul(vv1); //Matrix m3 = m1.mul(vv1);
// Method mul = classToTest.getDeclaredMethod("mul", Vector.class); Method mul = classToTest.getDeclaredMethod("mul", Vector.class);
// Object result = mul.invoke(instanceOfClass_m1, instanceOfClass_m2); Object result = mul.invoke(instanceOfClass_m1, instanceOfClass_m2);
Field mul = classToTest.getField("mul");
mul.setAccessible(true);
Class<?> lambda = mul.get(instanceOfClass_m1).getClass();
Method apply = lambda.getMethod("apply", Object.class, Object.class);
// Damit man auf die Methode zugreifen kann
apply.setAccessible(true);
Object result = apply.invoke(mul.get(instanceOfClass_m1), instanceOfClass_m1, instanceOfClass_m2);
System.out.println(instanceOfClass_m1.toString() + " * " + instanceOfClass_m2.toString() + " = " + result.toString()); System.out.println(instanceOfClass_m1.toString() + " * " + instanceOfClass_m2.toString() + " = " + result.toString());
Vector<Vector<Integer>> res = new Vector<Vector<Integer>>(); Vector<Vector<Integer>> res = new Vector<Vector<Integer>>();
@@ -96,7 +85,7 @@ public class MatrixOpTest {
res.addElement(v6); res.addElement(v6);
instanceOfClass_m3 = classToTest.getDeclaredConstructor(Vector.class).newInstance(res); instanceOfClass_m3 = classToTest.getDeclaredConstructor(Vector.class).newInstance(res);
assertEquals(result, instanceOfClass_m3); assertEquals(result, instanceOfClass_m3);
*/
} }
} }

1
src/test/java/bytecode/MatrixTest.java Executable file → Normal file
View File

@@ -85,6 +85,7 @@ public class MatrixTest {
res.addElement(v6); res.addElement(v6);
instanceOfClass_m3 = classToTest.getDeclaredConstructor(Vector.class).newInstance(res); instanceOfClass_m3 = classToTest.getDeclaredConstructor(Vector.class).newInstance(res);
assertEquals(result, instanceOfClass_m3); assertEquals(result, instanceOfClass_m3);
} }
} }

View File

@@ -7,14 +7,11 @@ import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.net.URL; import java.net.URL;
import java.net.URLClassLoader; import java.net.URLClassLoader;
import java.util.List;
import org.junit.BeforeClass; import org.junit.BeforeClass;
import org.junit.Test; import org.junit.Test;
import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.GenericGenratorResultForSourceFile;
import de.dhbwstuttgart.core.JavaTXCompiler; import de.dhbwstuttgart.core.JavaTXCompiler;
import de.dhbwstuttgart.typeinference.result.ResultSet;
public class OLTest { public class OLTest {
private static String path; private static String path;
@@ -33,9 +30,7 @@ public class OLTest {
fileToTest = new File(path); fileToTest = new File(path);
compiler = new JavaTXCompiler(fileToTest); compiler = new JavaTXCompiler(fileToTest);
pathToClassFile = System.getProperty("user.dir")+"/src/test/resources/testBytecode/generatedBC/"; pathToClassFile = System.getProperty("user.dir")+"/src/test/resources/testBytecode/generatedBC/";
List<ResultSet> typeinferenceResult = compiler.typeInference(); compiler.generateBytecode(pathToClassFile);
List<GenericGenratorResultForSourceFile> simplifyResultsForAllSourceFiles = compiler.getGeneratedGenericResultsForAllSourceFiles(typeinferenceResult);
compiler.generateBytecode(pathToClassFile,typeinferenceResult,simplifyResultsForAllSourceFiles);
loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)});
classToTest = loader.loadClass("OL"); classToTest = loader.loadClass("OL");
instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); instanceOfClass = classToTest.getDeclaredConstructor().newInstance();
@@ -52,14 +47,14 @@ public class OLTest {
public void testmInt() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { public void testmInt() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Method m = classToTest.getDeclaredMethod("m", Integer.class); Method m = classToTest.getDeclaredMethod("m", Integer.class);
Integer result = (Integer) m.invoke(instanceOfClass, 5); Integer result = (Integer) m.invoke(instanceOfClass, 5);
assertEquals(new Integer(10), result); assertEquals(10, result);
} }
@Test @Test
public void testmDouble() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { public void testmDouble() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Method m = classToTest.getDeclaredMethod("m", Double.class); Method m = classToTest.getDeclaredMethod("m", Double.class);
Double result = (Double) m.invoke(instanceOfClass, 5.0); Double result = (Double) m.invoke(instanceOfClass, 5.0);
assertEquals(new Double(10.0), result); assertEquals(10.0, result);
} }
@Test @Test
@@ -78,14 +73,14 @@ public class OLTest {
public void testmainInt() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { public void testmainInt() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Method main = classToTest1.getDeclaredMethod("main", Integer.class); Method main = classToTest1.getDeclaredMethod("main", Integer.class);
Integer result = (Integer) main.invoke(instanceOfClass1, 5); Integer result = (Integer) main.invoke(instanceOfClass1, 5);
assertEquals(new Integer(10), result); assertEquals(10, result);
} }
@Test @Test
public void testmainDouble() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { public void testmainDouble() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Method main = classToTest1.getDeclaredMethod("main", Double.class); Method main = classToTest1.getDeclaredMethod("main", Double.class);
Double result = (Double) main.invoke(instanceOfClass1, 5.0); Double result = (Double) main.invoke(instanceOfClass1, 5.0);
assertEquals(new Double(10.0), result); assertEquals(10.0, result);
} }
@Test @Test

View File

@@ -54,7 +54,7 @@ public class OpTest {
Integer result = (Integer) m.invoke(instanceOfClass, 7,3); Integer result = (Integer) m.invoke(instanceOfClass, 7,3);
assertEquals(new Integer(10), result); assertEquals(10, result);
} }

View File

@@ -38,28 +38,28 @@ public class PostIncTest {
public void testM1() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { public void testM1() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Method m = classToTest.getDeclaredMethod("m"); Method m = classToTest.getDeclaredMethod("m");
Integer res = (Integer) m.invoke(instanceOfClass); Integer res = (Integer) m.invoke(instanceOfClass);
assertEquals(new Integer(1), res); assertEquals(1, res);
} }
@Test @Test
public void testM2() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { public void testM2() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Method m = classToTest.getDeclaredMethod("m2"); Method m = classToTest.getDeclaredMethod("m2");
Integer res = (Integer) m.invoke(instanceOfClass); Integer res = (Integer) m.invoke(instanceOfClass);
assertEquals(new Integer(0), res); assertEquals(0, res);
} }
@Test @Test
public void testD1() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { public void testD1() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Method m = classToTest.getDeclaredMethod("d"); Method m = classToTest.getDeclaredMethod("d");
Integer res = (Integer) m.invoke(instanceOfClass); Integer res = (Integer) m.invoke(instanceOfClass);
assertEquals(new Integer(-1), res); assertEquals(-1, res);
} }
@Test @Test
public void testD2() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { public void testD2() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Method m = classToTest.getDeclaredMethod("d2"); Method m = classToTest.getDeclaredMethod("d2");
Integer res = (Integer) m.invoke(instanceOfClass); Integer res = (Integer) m.invoke(instanceOfClass);
assertEquals(new Integer(0), res); assertEquals(0, res);
} }
} }

View File

@@ -38,28 +38,28 @@ public class PreIncTest {
public void testM() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { public void testM() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Method m = classToTest.getDeclaredMethod("m"); Method m = classToTest.getDeclaredMethod("m");
Integer res = (Integer) m.invoke(instanceOfClass); Integer res = (Integer) m.invoke(instanceOfClass);
assertEquals(new Integer(1), res); assertEquals(1, res);
} }
@Test @Test
public void testM2() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { public void testM2() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Method m = classToTest.getDeclaredMethod("m2"); Method m = classToTest.getDeclaredMethod("m2");
Integer res = (Integer) m.invoke(instanceOfClass); Integer res = (Integer) m.invoke(instanceOfClass);
assertEquals(new Integer(1), res); assertEquals(1, res);
} }
@Test @Test
public void testD() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { public void testD() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Method m = classToTest.getDeclaredMethod("d"); Method m = classToTest.getDeclaredMethod("d");
Integer res = (Integer) m.invoke(instanceOfClass); Integer res = (Integer) m.invoke(instanceOfClass);
assertEquals(new Integer(-1), res); assertEquals(-1, res);
} }
@Test @Test
public void testD2() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { public void testD2() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Method m = classToTest.getDeclaredMethod("d2"); Method m = classToTest.getDeclaredMethod("d2");
Integer res = (Integer) m.invoke(instanceOfClass); Integer res = (Integer) m.invoke(instanceOfClass);
assertEquals(new Integer(-1), res); assertEquals(-1, res);
} }
} }

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