Generic generator algorithm v0.1

This commit is contained in:
Fayez Abu Alia 2019-07-25 22:24:06 +02:00
parent dfddc44f29
commit 7a4bc32974
35 changed files with 1967 additions and 1196 deletions

View File

@ -14,7 +14,7 @@ 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.0</version> <version>4.11</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>

View File

@ -25,10 +25,14 @@ 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.simplifyRes.SimplifyResult; import de.dhbwstuttgart.bytecode.simplifyRes.SimplifyResult;
import de.dhbwstuttgart.bytecode.simplifyRes.SimplifyResultSourceFile; import de.dhbwstuttgart.bytecode.simplifyRes.GenericGenratorResultForSourceFile;
import de.dhbwstuttgart.bytecode.simplifyRes.GenericsGeneratorResult;
import de.dhbwstuttgart.bytecode.simplifyRes.GenericsGeneratorResultForClass;
import de.dhbwstuttgart.bytecode.utilities.MethodAndTPH; import de.dhbwstuttgart.bytecode.utilities.MethodAndTPH;
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.bytecode.utilities.Simplify;
import de.dhbwstuttgart.exceptions.NotImplementedException; import de.dhbwstuttgart.exceptions.NotImplementedException;
import de.dhbwstuttgart.parser.SyntaxTreeGenerator.AssignToLocal; import de.dhbwstuttgart.parser.SyntaxTreeGenerator.AssignToLocal;
@ -119,10 +123,12 @@ public class BytecodeGen implements ASTVisitor {
private final ArrayList<String> fieldNameSignature = new ArrayList<>(); private final ArrayList<String> fieldNameSignature = new ArrayList<>();
private List<SimplifyResultSourceFile> simplifyResultsForAllSourceFiles; private List<GenericGenratorResultForSourceFile> simplifyResultsForAllSourceFiles;
private SimplifyResult simplifyResult; private GenericsGeneratorResultForClass generatedGenerics;
public BytecodeGen(HashMap<String, byte[]> classFiles, Collection<ResultSet> listOfResultSets, List<SimplifyResultSourceFile> simplifyResultsForAllSourceFiles, SourceFile sf, private Resolver resolver;
public BytecodeGen(HashMap<String, byte[]> classFiles, Collection<ResultSet> listOfResultSets, List<GenericGenratorResultForSourceFile> simplifyResultsForAllSourceFiles, SourceFile sf,
String path) { String path) {
this.classFiles = classFiles; this.classFiles = classFiles;
this.listOfResultSets = listOfResultSets; this.listOfResultSets = listOfResultSets;
@ -173,20 +179,19 @@ public class BytecodeGen implements ASTVisitor {
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); List<ResultSet> listOfResultSetsList = new ArrayList<>(listOfResultSets);
simplifyResult = simplifyResultsForAllSourceFiles.stream().map(sr->sr.getSimplifyResultsByName(pkgName, className)).findFirst().get(); generatedGenerics = simplifyResultsForAllSourceFiles.stream().map(sr->sr.getSimplifyResultsByName(pkgName, className)).findFirst().get();
for (int i = 0; i < listOfResultSetsList.size(); i++) { for (int i = 0; i < listOfResultSetsList.size(); i++) {
//for (ResultSet rs : listOfResultSets) { //for (ResultSet rs : listOfResultSets) {
superClass = classOrInterface.getSuperClass().acceptTV(new TypeToDescriptor()); superClass = classOrInterface.getSuperClass().acceptTV(new TypeToDescriptor());
resultSet = listOfResultSetsList.get(i); resultSet = listOfResultSetsList.get(i);
resolver = new Resolver(resultSet);
// tphExtractor.setResultSet(resultSet); // tphExtractor.setResultSet(resultSet);
// Nur einmal ausführen!! // Nur einmal ausführen!!
if (!isVisited) { if (!isVisited) {
tphsClass = simplifyResult.getTphsClass();
String sig = null; String sig = null;
/* /*
@ -194,10 +199,10 @@ public class BytecodeGen implements ASTVisitor {
* <E:Ljava/...>Superclass * <E:Ljava/...>Superclass
*/ */
if (classOrInterface.getGenerics().iterator().hasNext() || classOrInterface.getSuperClass().acceptTV(new TypeToSignature()).contains("<") if (classOrInterface.getGenerics().iterator().hasNext() || classOrInterface.getSuperClass().acceptTV(new TypeToSignature()).contains("<")
|| !tphsClass.isEmpty()) { || !generatedGenerics.getClassConstraints().isEmpty()) {
List<TPHConstraint> consClass = simplifyResult.getClassConstraints();
List<GenericsGeneratorResult> consClass = generatedGenerics.getClassConstraints();
//
Signature signature = new Signature(classOrInterface, genericsAndBounds, consClass); Signature signature = new Signature(classOrInterface, genericsAndBounds, consClass);
sig = signature.toString(); sig = signature.toString();
System.out.println("Signature: => " + sig); System.out.println("Signature: => " + sig);
@ -243,20 +248,13 @@ public class BytecodeGen implements ASTVisitor {
field.getParameterList().accept(this); field.getParameterList().accept(this);
String methParamTypes = field.name + "%%"; String id = MethodUtility.createID(resolver, field);
Iterator<FormalParameter> itr = field.getParameterList().iterator(); if (methodNameAndParamsT.contains(id)) {
while (itr.hasNext()) {
FormalParameter fp = itr.next();
methParamTypes += resultSet.resolveType(fp.getType()).resolvedType.acceptTV(new TypeToDescriptor()) + ";";
}
if (methodNameAndParamsT.contains(methParamTypes)) {
System.out.println("ignore - Method: " + field.name + " , paramsType: " + methParamTypes);
return; return;
} }
methodNameAndParamsT.add(methParamTypes); methodNameAndParamsT.add(id);
System.out.println("Method: " + field.name + " , paramsType: " + methParamTypes); System.out.println("Constructor: " + field.name + " , paramsType: " + id);
String desc = null; String desc = null;
boolean hasGen = false; boolean hasGen = false;
@ -271,9 +269,16 @@ public class BytecodeGen implements ASTVisitor {
} }
String sig = null; String sig = null;
if (hasGen) { if (hasGen) {
Map<TPHConstraint, Set<String>> constraints = simplifyResult.getMethodConstraintsByID(methParamTypes); List<GenericsGeneratorResult> constraints = generatedGenerics.getClassConstraints();
Signature signature = new Signature(field, genericsAndBounds, methodParamsAndTypes, resultSet, constraints); // Map<TPHConstraint, Set<String>> constraints = generatedGenerics.getMethodConstraintsByID(methParamTypes);
sig = signature.toString(); //// ArrayList<GenericInsertPair> pairs = simplifyPairs(method.name,tphExtractor.allPairs,tphExtractor.allCons);
Signature signature = new Signature(genericsAndBounds,
methodParamsAndTypes, resultSet, constraints);
sig = signature.createSignatureForConstructor(field);
// Map<TPHConstraint, Set<String>> constraints = generatedGenerics.getMethodConstraintsByID(methParamTypes);
// Signature signature = new Signature(field, genericsAndBounds, methodParamsAndTypes, resultSet, constraints);
// sig = signature.toString();
} }
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()));
@ -304,23 +309,19 @@ public class BytecodeGen implements ASTVisitor {
// 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 methParamTypes = retType + method.name + "%%";
method.getParameterList().accept(this);
Iterator<FormalParameter> itr = method.getParameterList().iterator(); String id = MethodUtility.createID(resolver, method);
while (itr.hasNext()) {
FormalParameter fp = itr.next();
methParamTypes += resultSet.resolveType(fp.getType()).resolvedType.acceptTV(new TypeToDescriptor()) + ";";
}
if (methodNameAndParamsT.contains(methParamTypes)) { if (methodNameAndParamsT.contains(id)) {
return; return;
} }
methodNameAndParamsT.add(methParamTypes); methodNameAndParamsT.add(id);
System.out.println("Method: " + method.name + " , paramsType: " + methParamTypes); System.out.println("Method: " + method.name + " , paramsType: " + id);
// 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<>();
method.getParameterList().accept(this);
String methDesc = null; String methDesc = null;
// Method getModifiers() ? // Method getModifiers() ?
@ -360,11 +361,13 @@ public class BytecodeGen implements ASTVisitor {
if (hasGen || resultSet.resolveType(method.getReturnType()).resolvedType.acceptTV(new TypeToString()) if (hasGen || resultSet.resolveType(method.getReturnType()).resolvedType.acceptTV(new TypeToString())
.equals("TPH")) { .equals("TPH")) {
Map<TPHConstraint, Set<String>> constraints = simplifyResult.getMethodConstraintsByID(methParamTypes); List<GenericsGeneratorResult> constraints = generatedGenerics.getMethodConstraintsByID(id);
// ArrayList<GenericInsertPair> pairs = simplifyPairs(method.name,tphExtractor.allPairs,tphExtractor.allCons); List<GenericsGeneratorResult> classConstraints = generatedGenerics.getClassConstraints();
Signature signature = new Signature(method, genericsAndBoundsMethod, genericsAndBounds, // Map<TPHConstraint, Set<String>> constraints = generatedGenerics.getMethodConstraintsByID(methParamTypes);
methodParamsAndTypes, resultSet, constraints); //// ArrayList<GenericInsertPair> pairs = simplifyPairs(method.name,tphExtractor.allPairs,tphExtractor.allCons);
sig = signature.toString(); Signature signature = new Signature(genericsAndBoundsMethod, genericsAndBounds,
methodParamsAndTypes, resultSet, constraints,classConstraints);
sig = signature.createSignatureForMethod(method);
} }
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);

View File

@ -18,6 +18,7 @@ import de.dhbwstuttgart.bytecode.utilities.MethodAndTPH;
import de.dhbwstuttgart.bytecode.utilities.MethodUtility; import de.dhbwstuttgart.bytecode.utilities.MethodUtility;
import de.dhbwstuttgart.bytecode.utilities.Resolver; 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.Constructor;
import de.dhbwstuttgart.syntaxtree.Field; import de.dhbwstuttgart.syntaxtree.Field;
import de.dhbwstuttgart.syntaxtree.FormalParameter; import de.dhbwstuttgart.syntaxtree.FormalParameter;
@ -41,10 +42,11 @@ 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<>(); public final HashMap<String, Boolean> allTPHS = new HashMap<>();
public final List<String> tphsClass = new ArrayList<>();
MethodAndTPH methodAndTph; MethodAndTPH methodAndTph;
Boolean inMethod = false; Boolean inMethod = false;
boolean inLocalOrParam = 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<ResultPair<TypePlaceholder, TypePlaceholder>> allPairs = new ArrayList<>();
@ -65,14 +67,23 @@ public class TPHExtractor extends AbstractASTWalker {
return resolver; 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 (inLocalOrParam) if (inLocalOrParamOrReturn)
methodAndTph.getLocalTphs().add(resolvedTPH.getName()); methodAndTph.getLocalTphs().add(resolvedTPH.getName());
}else {
tphsClass.add(resolvedTPH.getName());
} }
allTPHS.put(resolvedTPH.getName(), inMethod); allTPHS.put(resolvedTPH.getName(), inMethod);
@ -142,9 +153,11 @@ public class TPHExtractor extends AbstractASTWalker {
public void visit(GenericRefType genericRefType) { public void visit(GenericRefType genericRefType) {
String name = genericRefType.getParsedName(); String name = genericRefType.getParsedName();
if (inMethod) { if (inMethod) {
methodAndTph.getTphs().add(name);
if (inLocalOrParamOrReturn)
methodAndTph.getLocalTphs().add(name); methodAndTph.getLocalTphs().add(name);
if (inLocalOrParam) }else {
methodAndTph.getLocalTphs().add(name); tphsClass.add(name);
} }
allTPHS.put(name, inMethod); allTPHS.put(name, inMethod);
} }
@ -163,7 +176,15 @@ public class TPHExtractor extends AbstractASTWalker {
inMethod = true; inMethod = true;
String id = MethodUtility.createID(resolver,method); String id = MethodUtility.createID(resolver,method);
methodAndTph = new MethodAndTPH(id); 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);
} }
@ -177,23 +198,23 @@ public class TPHExtractor extends AbstractASTWalker {
@Override @Override
public void visit(LocalVarDecl localVarDecl) { public void visit(LocalVarDecl localVarDecl) {
inLocalOrParam = true; // inLocalOrParamOrReturn = inMethod;
super.visit(localVarDecl); super.visit(localVarDecl);
inLocalOrParam = false; // inLocalOrParamOrReturn = false;
} }
@Override @Override
public void visit(LocalVar localVar) { public void visit(LocalVar localVar) {
inLocalOrParam = true; // inLocalOrParamOrReturn = inMethod;
super.visit(localVar); super.visit(localVar);
inLocalOrParam = false; // inLocalOrParamOrReturn = false;
} }
@Override @Override
public void visit(ParameterList formalParameters) { public void visit(ParameterList formalParameters) {
inLocalOrParam = true; inLocalOrParamOrReturn = inMethod;
super.visit(formalParameters); super.visit(formalParameters);
inLocalOrParam = false; inLocalOrParamOrReturn = false;
} }
} }

View File

@ -3,8 +3,7 @@
*/ */
package de.dhbwstuttgart.bytecode.genericsGenerator; package de.dhbwstuttgart.bytecode.genericsGenerator;
import java.util.ArrayList; import java.util.*;
import java.util.List;
import de.dhbwstuttgart.bytecode.TPHExtractor; import de.dhbwstuttgart.bytecode.TPHExtractor;
import de.dhbwstuttgart.bytecode.constraint.TPHConstraint; import de.dhbwstuttgart.bytecode.constraint.TPHConstraint;
@ -16,44 +15,112 @@ import de.dhbwstuttgart.bytecode.simplifyRes.GenericsGeneratorResult;
* *
*/ */
public class ConstraintsSimplifier { public class ConstraintsSimplifier {
public static ConstraintsSimplierResult simplifyConstraints(TPHExtractor tphExtractor, List<GenericsGeneratorResult> genericsGeneratorResults, List<String> tphsClass) { public static ConstraintsSimplierResult simplifyConstraints(final TPHExtractor tphExtractor, final List<GenericsGeneratorResult> genericsGeneratorResults, final List<String> tphsClass) {
List<TPHConstraint> allCons = tphExtractor.allCons; List<TPHConstraint> allCons = tphExtractor.allCons;
List<TPHConstraint> equalCons = new ArrayList<>(); List<TPHConstraint> equalCons = new ArrayList<>();
List<SimpleCycle> simpleCycles = findSimpleCycles(allCons); List<SimpleCycle> simpleCycles = findSimpleCycles(allCons);
if(!simpleCycles.isEmpty()) { /* Step 1 */
handleSimpleCycles(allCons, simpleCycles);
equalCons.addAll(GenericsGeneratorUtility.getEqualConstraints(allCons));
}
/* Step 2 */
List<ConstraintsWithSameLeftSide> foundCons = GenericsGeneratorUtility.findConstraintsWithLeftSameLeftSide(allCons); List<ConstraintsWithSameLeftSide> foundCons = GenericsGeneratorUtility.findConstraintsWithLeftSameLeftSide(allCons);
if(!foundCons.isEmpty()) { if(!foundCons.isEmpty()) {
List<TPHConstraint> equalCons2 = GenericsGeneratorUtility.simplifyConstraintsWithSameLeftSide(foundCons,tphExtractor,tphsClass); List<TPHConstraint> equalCons2 = new ArrayList<>();
GenericsGeneratorUtility.simplifyConstraintsWithSameLeftSide(foundCons,tphExtractor,tphsClass,equalCons2);
equalCons.addAll(equalCons2); equalCons.addAll(equalCons2);
} }
// if(!simpleCycles.isEmpty()) {
// handleSimpleCycles(allCons, simpleCycles,tphExtractor);
// equalCons.addAll(GenericsGeneratorUtility.getEqualConstraints(allCons));
// }
//
List<LongCycle> longCycles = findLongCycles(allCons); List<LongCycle> longCycles = findLongCycles(allCons);
if(!longCycles.isEmpty()) { if(!longCycles.isEmpty()) {
handleLongCycle(genericsGeneratorResults, allCons, longCycles); handleLongCycle(genericsGeneratorResults, allCons, longCycles,tphExtractor);
} }
/* The right hand side of equal constraint is the new name in name replacement result */ /* The right hand side of equal constraint is the new name in name replacement result */
List<NameReplacementResult> nameReplacementResults = GenericsGeneratorUtility.createNameReplacementResultsFromEqualConstraints(equalCons); List<NameReplacementResult> nameReplacementResults = GenericsGeneratorUtility.createNameReplacementResultsFromEqualConstraints(equalCons);
getEqualsFromNameReplacementResults(genericsGeneratorResults,nameReplacementResults);
ConstraintsSimplierResult result = new ConstraintsSimplierResult(genericsGeneratorResults, nameReplacementResults); ConstraintsSimplierResult result = new ConstraintsSimplierResult(genericsGeneratorResults, nameReplacementResults);
return result; 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 genericsGeneratorResults
* @param allCons * @param allCons
* @param longCycles * @param longCycles
* @param tphExtractor
*/ */
public static void handleLongCycle(List<GenericsGeneratorResult> genericsGeneratorResults, public static void handleLongCycle(List<GenericsGeneratorResult> genericsGeneratorResults,
List<TPHConstraint> allCons, List<LongCycle> longCycles) { List<TPHConstraint> allCons, List<LongCycle> longCycles, TPHExtractor tphExtractor) {
GenericsGeneratorUtility.modifyRelationForConstraintsinLongCycle(longCycles); GenericsGeneratorUtility.modifyRelationForConstraintsinLongCycle(longCycles);
List<NameReplacementResult> nameReplacementResults = GenericsGeneratorUtility.substituteTPHSFormLongCycle(allCons, longCycles); List<NameReplacementResult> nameReplacementResults = GenericsGeneratorUtility.substituteTPHSFormLongCycle(allCons, longCycles,tphExtractor);
GenericsGeneratorUtility.createResults(genericsGeneratorResults,nameReplacementResults); GenericsGeneratorUtility.createResults(genericsGeneratorResults,nameReplacementResults);
GenericsGeneratorUtility.removeEqualConstraints(allCons); GenericsGeneratorUtility.removeEqualConstraints(allCons);
} }
@ -72,11 +139,13 @@ public class ConstraintsSimplifier {
/** /**
* @param allCons * @param allCons
* @param simpleCycles * @param simpleCycles
* @param tphExtractor
*/ */
public static void handleSimpleCycles(List<TPHConstraint> allCons, List<SimpleCycle> simpleCycles) { public static void handleSimpleCycles(List<TPHConstraint> allCons, List<SimpleCycle> simpleCycles, TPHExtractor tphExtractor) {
GenericsGeneratorUtility.modifyRelation(simpleCycles); GenericsGeneratorUtility.modifyRelation(simpleCycles);
GenericsGeneratorUtility.removeAllReverseConstraints(allCons,simpleCycles); GenericsGeneratorUtility.removeAllReverseConstraints(allCons,simpleCycles);
GenericsGeneratorUtility.substituteTPH(allCons, simpleCycles); GenericsGeneratorUtility.substituteTPH(allCons, simpleCycles);
GenericsGeneratorUtility.replaceOldNames(simpleCycles,tphExtractor);
} }
/** /**

View File

@ -28,4 +28,8 @@ public class ConstraintsWithSameLeftSide {
this.constraints = constraints; this.constraints = constraints;
} }
@Override
public String toString() {
return "[" + constraints.toString() + "]";
}
} }

View File

@ -50,6 +50,8 @@ public class CyclesFinder {
List<TPHConstraint> vistedConstraints = new ArrayList<>(allCons.size()); List<TPHConstraint> vistedConstraints = new ArrayList<>(allCons.size());
List<LongCycle> longCycles = new ArrayList<>(); List<LongCycle> longCycles = new ArrayList<>();
for (TPHConstraint constraint : allCons) { for (TPHConstraint constraint : allCons) {
if(constraint.getRel()==Relation.EQUAL)
continue;
if (!vistedConstraints.contains(constraint)) { if (!vistedConstraints.contains(constraint)) {
vistedConstraints.add(constraint); vistedConstraints.add(constraint);
checkConstraint(constraint, vistedConstraints, longCycles); checkConstraint(constraint, vistedConstraints, longCycles);
@ -70,16 +72,16 @@ public class CyclesFinder {
if(containsInLongCycle(nextConstraint.get(), longCycles)) { if(containsInLongCycle(nextConstraint.get(), longCycles)) {
break; break;
} }
nextConstraint = getConstraintInRelation(tphsInRelation, maybeCycle);
if (isCycle(tphsInRelation)) { if (isCycle(tphsInRelation)) {
addAllToVisitedConstraints(vistedConstraints, maybeCycle); addAllToVisitedConstraints(vistedConstraints, maybeCycle);
LongCycle cycle = new LongCycle(maybeCycle); LongCycle cycle = new LongCycle(maybeCycle);
longCycles.add(cycle); longCycles.add(cycle);
return; return;
} }
nextConstraint = getConstraintInRelation(tphsInRelation, maybeCycle);
} }
addAllToVisitedConstraints(vistedConstraints, maybeCycle); // addAllToVisitedConstraints(vistedConstraints, maybeCycle);
} }
private boolean containsInLongCycle(TPHConstraint c, List<LongCycle> longCycles) { private boolean containsInLongCycle(TPHConstraint c, List<LongCycle> longCycles) {
@ -99,7 +101,7 @@ public class CyclesFinder {
private Optional<TPHConstraint> getConstraintInRelation(List<String> tphsInRelation, private Optional<TPHConstraint> getConstraintInRelation(List<String> tphsInRelation,
List<TPHConstraint> maybeCycle) { List<TPHConstraint> maybeCycle) {
TPHConstraint constraint = getConstraintByLeftSide(tphsInRelation.get(tphsInRelation.size()-1)); TPHConstraint constraint = getConstraintByLeftSide(tphsInRelation.get(tphsInRelation.size()-1),maybeCycle);
Optional<TPHConstraint> nextConstraint = Optional.ofNullable(constraint); Optional<TPHConstraint> nextConstraint = Optional.ofNullable(constraint);
if(nextConstraint.isPresent()) { if(nextConstraint.isPresent()) {
maybeCycle.add(constraint); maybeCycle.add(constraint);
@ -108,8 +110,12 @@ public class CyclesFinder {
return nextConstraint; return nextConstraint;
} }
private TPHConstraint getConstraintByLeftSide(String left) { private TPHConstraint getConstraintByLeftSide(String left, List<TPHConstraint> maybeCycle) {
for(TPHConstraint constraint : allCons) { for(TPHConstraint constraint : allCons) {
if(constraint.getRel()==Relation.EQUAL)
continue;
if(maybeCycle.contains(constraint))
continue;
if(constraint.getLeft().equals(left)) if(constraint.getLeft().equals(left))
return constraint; return constraint;
} }

View File

@ -4,13 +4,24 @@
package de.dhbwstuttgart.bytecode.genericsGenerator; package de.dhbwstuttgart.bytecode.genericsGenerator;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import org.objectweb.asm.Type;
import de.dhbwstuttgart.bytecode.TPHExtractor; import de.dhbwstuttgart.bytecode.TPHExtractor;
import de.dhbwstuttgart.bytecode.constraint.ExtendsConstraint;
import de.dhbwstuttgart.bytecode.constraint.TPHConstraint; import de.dhbwstuttgart.bytecode.constraint.TPHConstraint;
import de.dhbwstuttgart.bytecode.simplifyRes.GenericGeneratorResultsForAllMethods;
import de.dhbwstuttgart.bytecode.simplifyRes.ConstraintsSimplierResult; import de.dhbwstuttgart.bytecode.simplifyRes.ConstraintsSimplierResult;
import de.dhbwstuttgart.bytecode.simplifyRes.GenericsGeneratorResult; import de.dhbwstuttgart.bytecode.simplifyRes.GenericsGeneratorResult;
import de.dhbwstuttgart.bytecode.utilities.MethodUtility; import de.dhbwstuttgart.bytecode.simplifyRes.GenericsGeneratorResultForClass;
import de.dhbwstuttgart.bytecode.simplifyRes.MethodAndConstraints;
import de.dhbwstuttgart.bytecode.utilities.MethodAndTPH;
import de.dhbwstuttgart.syntaxtree.Method; import de.dhbwstuttgart.syntaxtree.Method;
/** /**
@ -19,17 +30,185 @@ import de.dhbwstuttgart.syntaxtree.Method;
*/ */
public class GenericsGenerator { public class GenericsGenerator {
public static List<GenericsGeneratorResult> generateConstraintsForMethod(Method method, TPHExtractor tphExtractor, public static GenericsGeneratorResultForClass generateConstraints(final String className, final TPHExtractor tphExtractor,
List<String> tphsClass) { final List<String> tphsClass, final ConstraintsSimplierResult simplifiedConstraints) {
List<GenericsGeneratorResult> genericsGeneratorResults = new ArrayList<>();
ConstraintsSimplierResult simplifiedConstraints = ConstraintsSimplifier.simplifyConstraints(tphExtractor, genericsGeneratorResults,tphsClass); List<GenericsGeneratorResult> classConstraints = generateConstraintsForClass(tphExtractor,
simplifiedConstraints, tphsClass);
// GenericGeneratorResultsForAllMethods methodsAndConstraints = generateConstraintsForAllMethods(tphExtractor,
// simplifiedConstraints, tphsClass);
GenericGeneratorResultsForAllMethods methodsAndConstraints = new GenericGeneratorResultsForAllMethods(new ArrayList<>());
List<TPHConstraint> allCons = tphExtractor.allCons; return new GenericsGeneratorResultForClass(className, classConstraints, methodsAndConstraints);
String methodID = MethodUtility.createID(tphExtractor.getResolver(), method); }
List<String> methodTPHS = GenericsGeneratorUtility.getMethodTPHS(methodID ,tphExtractor.ListOfMethodsAndTph);
return null;
/**
* @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());
for (String tph : tphsClass) {
if (visitedTPHs.contains(tph))
continue;
final LinkedList<String> tphsInRel = GenericsGeneratorUtility
.createLinkedListForTPHsInRelationClass(allCons, tphsClass, methodTPHs, visitedTPHs, tph);
if(!tphsInRel.isEmpty()) {
GenericsGeneratorResult constraint = generateGGResultForClass(tphsInRel, simplifiedConstraints, tphsClass);
constraints.add(constraint);
}
}
GenericsGeneratorUtility.addTPHsToClassTPHs(constraints, tphsClass);
GenericsGeneratorUtility.removeClassTPHsFromMethodTPHs(tphsClass, tphExtractor);
generateGGConstraintsForTPH(tphsClass, constraints, simplifiedConstraints);
return constraints;
}
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

@ -5,11 +5,12 @@ package de.dhbwstuttgart.bytecode.genericsGenerator;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashSet; import java.util.HashSet;
import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.Optional; import java.util.Optional;
import java.util.Set; import java.util.Set;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.objectweb.asm.Type; import org.objectweb.asm.Type;
@ -118,30 +119,121 @@ public class GenericsGeneratorUtility {
} }
public static List<TPHConstraint> simplifyConstraintsWithSameLeftSide(List<ConstraintsWithSameLeftSide> consWithSameLeftSide, public static void simplifyConstraintsWithSameLeftSide(List<ConstraintsWithSameLeftSide> consWithSameLeftSide,
TPHExtractor tphExtractor, List<String> tphsClass) { TPHExtractor tphExtractor, List<String> tphsClass, List<TPHConstraint> equalCons) {
List<TPHConstraint> eqCons = new ArrayList<>();
List<TPHConstraint> allCons = tphExtractor.allCons; List<TPHConstraint> allCons = tphExtractor.allCons;
for (ConstraintsWithSameLeftSide list : consWithSameLeftSide) { for (ConstraintsWithSameLeftSide list : consWithSameLeftSide) {
if(!stillWithSameLeftSide(list))
continue;
NameReplacementResult replRes = modifyNames(allCons, list, tphExtractor.ListOfMethodsAndTph,tphsClass); NameReplacementResult replRes = modifyNames(allCons, list, tphExtractor.ListOfMethodsAndTph,tphsClass);
createEqualConstraintsForNames(replRes.getName(), replRes.getOldNames(),eqCons); createEqualConstraintsForNames(replRes.getName(), replRes.getOldNames(),equalCons);
for (TPHConstraint c : allCons) { for (TPHConstraint c : allCons) {
if (c.getRel() == Relation.EQUAL && replRes.getName().equals(c.getRight())) { if (c.getRel() == Relation.EQUAL && replRes.getName().equals(c.getRight())) {
eqCons.add(c); equalCons.add(c);
} }
} }
updateEqualCons(replRes, eqCons); updateEqualCons(replRes, equalCons);
TPHConstraint c = list.getConstraints().get(0); TPHConstraint c = list.getConstraints().get(0);
allCons.removeAll(list.getConstraints()); allCons.removeAll(list.getConstraints());
removeConstraintsWithSameLeftAndRightSide(allCons);
allCons.add(c); allCons.add(c);
removeDuplicate(allCons);
} }
return eqCons; 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) { private static void createEqualConstraintsForNames(String name, List<String> equalNames, List<TPHConstraint> eqCons) {
// create an equal constraint for each value in repres // create an equal constraint for each value in repres
for (String eName : equalNames) { for (String eName : equalNames) {
@ -191,13 +283,20 @@ public class GenericsGeneratorUtility {
longCycles.stream().map(lc->lc.getConstraints()).flatMap(e->e.stream()).forEach(c->c.setRel(Relation.EQUAL)); longCycles.stream().map(lc->lc.getConstraints()).flatMap(e->e.stream()).forEach(c->c.setRel(Relation.EQUAL));
} }
public static List<NameReplacementResult> substituteTPHSFormLongCycle(List<TPHConstraint> allCons, List<LongCycle> longCycles) { public static List<NameReplacementResult> substituteTPHSFormLongCycle(List<TPHConstraint> allCons, List<LongCycle> longCycles, TPHExtractor tphExtractor) {
List<NameReplacementResult> results = new ArrayList<>(); List<NameReplacementResult> results = new ArrayList<>();
longCycles.forEach(lc->{ longCycles.forEach(lc->{
Set<String> names = getNamesFromCycle(lc); Set<String> names = getNamesFromCycle(lc);
String newName = names.stream().findFirst().get(); String newName = names.stream().findFirst().get();
List<String> equalNames = new ArrayList<>(names); 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); NameReplacementResult res = new NameReplacementResult(newName, equalNames);
results.add(res); results.add(res);
substituteAll(allCons,names,newName); substituteAll(allCons,names,newName);
@ -205,6 +304,18 @@ public class GenericsGeneratorUtility {
return results; 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) { public static void substituteAll(List<TPHConstraint> allCons, Set<String> names, String newName) {
allCons.stream() allCons.stream()
.filter(c-> c.getRel()==Relation.EXTENDS) .filter(c-> c.getRel()==Relation.EXTENDS)
@ -268,4 +379,224 @@ public class GenericsGeneratorUtility {
return false; return false;
return nameReplacementResults.stream().map(r->r.getName()).filter(n->name.equals(n)).findFirst().isPresent(); 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 void replaceOldNames(List<SimpleCycle> simpleCycles, TPHExtractor tphExtractor) {
simpleCycles.forEach(sc -> {
Stream<ArrayList<String>> tphsOfMethods = tphExtractor.ListOfMethodsAndTph.stream().map(m->m.getTphs());
Stream<ArrayList<String>> localTphsOfMethods = tphExtractor.ListOfMethodsAndTph.stream().map(m->m.getLocalTphs());
String newName = sc.getConstraint().getRight();
String oldName = sc.getConstraint().getLeft();
List<String> names = new ArrayList<>();
names.add(oldName);
names.add(newName);
replaceOldNames(newName, names, tphsOfMethods);
replaceOldNames(newName, names, localTphsOfMethods);
});
}
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,12 +1,6 @@
package de.dhbwstuttgart.bytecode.signature; package de.dhbwstuttgart.bytecode.signature;
import java.util.ArrayList; import java.util.*;
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 org.objectweb.asm.Type; import org.objectweb.asm.Type;
import org.objectweb.asm.signature.SignatureVisitor; import org.objectweb.asm.signature.SignatureVisitor;
@ -16,6 +10,7 @@ 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.descriptor.TypeToDescriptor; import de.dhbwstuttgart.bytecode.descriptor.TypeToDescriptor;
import de.dhbwstuttgart.bytecode.simplifyRes.GenericsGeneratorResult;
import de.dhbwstuttgart.bytecode.utilities.Simplify; 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;
@ -32,61 +27,123 @@ 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 SignatureWriter sw; private final SignatureWriter sw = new SignatureWriter();;
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 Map<TPHConstraint, Set<String>> methodConstraints;
private List<TPHConstraint> consClass; private List<GenericsGeneratorResult> consClass;
private List<GenericsGeneratorResult> constraints;
public Signature(ClassOrInterface classOrInterface, HashMap<String, String> genericsAndBounds, // public Signature(ClassOrInterface classOrInterface, HashMap<String, String> genericsAndBounds,
List<TPHConstraint> consClass) { // List<TPHConstraint> consClass) {
this.classOrInterface = classOrInterface; // this.classOrInterface = classOrInterface;
this.genericsAndBounds = genericsAndBounds; // this.genericsAndBounds = genericsAndBounds;
this.consClass = consClass; // this.consClass = consClass;
sw = new SignatureWriter(); // sw = new SignatureWriter();
createSignatureForClassOrInterface(); // createSignatureForClassOrInterface();
} // }
public Signature(Constructor constructor, HashMap<String, String> genericsAndBounds, public Signature(HashMap<String, String> genericsAndBounds,
HashMap<String, RefTypeOrTPHOrWildcardOrGeneric> methodParamsAndTypes, ResultSet resultSet, HashMap<String, RefTypeOrTPHOrWildcardOrGeneric> methodParamsAndTypes, ResultSet resultSet,
Map<TPHConstraint,Set<String>> methodConstraints) { List<GenericsGeneratorResult> constraints) {
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.methodConstraints = methodConstraints; this.constraints = constraints;
sw = new SignatureWriter();
createSignatureForConsOrMethod(this.constructor,true);
}
public Signature(Method method, HashMap<String, String> genericsAndBoundsMethod,HashMap<String, String> genericsAndBounds,
HashMap<String, RefTypeOrTPHOrWildcardOrGeneric> methodParamsAndTypes, ResultSet resultSet,
Map<TPHConstraint, Set<String>> constraints) {
this.method = method;
this.genericsAndBoundsMethod = genericsAndBoundsMethod;
this.genericsAndBounds = genericsAndBounds;
this.methodParamsAndTypes = methodParamsAndTypes;
this.resultSet = resultSet;
this.methodConstraints = constraints;
sw = new SignatureWriter();
createSignatureForConsOrMethod(this.method,false);
} }
public Signature(int numberOfParams) { public Signature(int numberOfParams) {
sw = new SignatureWriter();
createSignatureForFunN(numberOfParams); createSignatureForFunN(numberOfParams);
} }
public Signature(int numberOfParams, String to, String[] paramTypes) { public Signature(int numberOfParams, String to, String[] paramTypes) {
sw = new SignatureWriter();
createSignatureForFunN(numberOfParams, to, 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;
createSignatureForClassOrInterface();
}
public Signature(HashMap<String, String> genericsAndBoundsMethod,
HashMap<String, String> genericsAndBounds,
HashMap<String, RefTypeOrTPHOrWildcardOrGeneric> methodParamsAndTypes, ResultSet resultSet,
List<GenericsGeneratorResult> constraints,List<GenericsGeneratorResult> consClass) {
//this.method = method;
this.genericsAndBoundsMethod = genericsAndBoundsMethod;
this.genericsAndBounds = genericsAndBounds;
this.methodParamsAndTypes = methodParamsAndTypes;
this.resultSet = resultSet;
this.constraints = constraints;
this.consClass = consClass;
//createSignatureForMethod(this.method);
}
public String createSignatureForConstructor(Constructor constructor) {
visitParams();
sw.visitReturnType().visitBaseType('V');
return sw.toString();
}
public String createSignatureForMethod(Method method) {
defineGenerics(method);
String ret = resultSet.resolveType(method.getReturnType()).resolvedType.acceptTV(new TypeToSignature());
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) { private void createSignatureForFunN(int numberOfParams, String to, String[] paramTypes) {
for (int i = 0; i < numberOfParams; i++) { for (int i = 0; i < numberOfParams; i++) {
int j = i + 1; int j = i + 1;
@ -97,11 +154,10 @@ public class Signature {
} }
sw.visitFormalTypeParameter("R"); sw.visitFormalTypeParameter("R");
// getBounds vom Return-Type visitClassBound(to);
sw.visitClassBound().visitClassType(to);
sw.visitClassBound().visitEnd();
// TODO: prüfe ob Return-Type = void, // TODO: prüfe ob Return-Type = void,
sw.visitSuperclass().visitClassType(Type.getInternalName(Object.class));; sw.visitSuperclass().visitClassType(Type.getInternalName(Object.class));
;
sw.visitEnd(); sw.visitEnd();
} }
@ -122,14 +178,15 @@ public class Signature {
sw.visitClassBound().visitClassType(Type.getInternalName(Object.class)); sw.visitClassBound().visitClassType(Type.getInternalName(Object.class));
sw.visitClassBound().visitEnd(); sw.visitClassBound().visitEnd();
// TODO: prüfe ob Return-Type = void, // TODO: prüfe ob Return-Type = void,
sw.visitSuperclass().visitClassType(Type.getInternalName(Object.class));; sw.visitSuperclass().visitClassType(Type.getInternalName(Object.class));
;
sw.visitEnd(); sw.visitEnd();
} }
/** /**
* Creates signature for a method or constructor with @see {@link SignatureWriter} * Creates signature for a method or constructor with @see
* Signature looks like: * {@link SignatureWriter} Signature looks like: <typevaliables
* <typevaliables (K:Ljava/lang/Object "Bounds")>(params L.. OR T.. Or basistape)ReturnType * (K:Ljava/lang/Object "Bounds")>(params L.. OR T.. Or basistape)ReturnType
* *
* @param method method or constructor * @param method method or constructor
* @param isConstructor true if constructor * @param isConstructor true if constructor
@ -140,11 +197,12 @@ public class Signature {
while (itr.hasNext()) { while (itr.hasNext()) {
System.out.println("HAS GENERICS!!"); System.out.println("HAS GENERICS!!");
GenericTypeVar g = itr.next(); GenericTypeVar g = itr.next();
getBoundsOfTypeVar(g,genericsAndBoundsMethod); visitTypeVarsAndTheirBounds(g, genericsAndBoundsMethod);
} }
// Wenn die RückgabeType eine TPH ist, wird als generic behandelt // 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 // z.B: Type = TPH K => wird eine Formal Type Parameter K$ erzeugt und Bound =
// Object
if (!isConstructor) { if (!isConstructor) {
String ret = resultSet.resolveType(method.getReturnType()).resolvedType.acceptTV(new TypeToSignature()); String ret = resultSet.resolveType(method.getReturnType()).resolvedType.acceptTV(new TypeToSignature());
ArrayList<TPHConstraint> allConsBeforeSimplify = new ArrayList<>(); ArrayList<TPHConstraint> allConsBeforeSimplify = new ArrayList<>();
@ -152,7 +210,8 @@ public class Signature {
Map<TPHConstraint, Set<String>> allConstraints = new HashMap<>(); Map<TPHConstraint, Set<String>> allConstraints = new HashMap<>();
if (ret.contains("<")) { if (ret.contains("<")) {
allConsBeforeSimplify = getAllConstraints((RefType) resultSet.resolveType(method.getReturnType()).resolvedType); allConsBeforeSimplify = getAllConstraints(
(RefType) resultSet.resolveType(method.getReturnType()).resolvedType);
} }
for (String paramName : methodParamsAndTypes.keySet()) { for (String paramName : methodParamsAndTypes.keySet()) {
@ -170,7 +229,7 @@ public class Signature {
createTypeVars(allConstraints, doSimplify); createTypeVars(allConstraints, doSimplify);
if (!ret.equals("V")) { if (!ret.equals("V")) {
if(ret.contains("$") && !ret.contains("$$") && !ret.contains("<")) { if (ret.contains(SPECIAL_CHAR) && !ret.contains(SPECIAL_CHAR_FOR_FUN) && !ret.contains("<")) {
if (genericsAndBounds.containsKey(ret)) { if (genericsAndBounds.containsKey(ret)) {
genericsAndBoundsMethod.put(ret.substring(1), genericsAndBounds.get(ret.substring(1))); genericsAndBoundsMethod.put(ret.substring(1), genericsAndBounds.get(ret.substring(1)));
} }
@ -179,19 +238,14 @@ public class Signature {
} }
} }
// visit each method-parameter to create the signature visitParams();
for(String paramName : methodParamsAndTypes.keySet()) { if (isConstructor || resultSet.resolveType(method.getReturnType()).resolvedType.acceptTV(new TypeToSignature())
RefTypeOrTPHOrWildcardOrGeneric t = methodParamsAndTypes.get(paramName); .equals("V")) {
// parameter type deswegen ist true
doVisitParamsOrReturn(t,true);
}
if(isConstructor ||
resultSet.resolveType(method.getReturnType()).resolvedType.acceptTV(new TypeToSignature()).equals("V")) {
sw.visitReturnType().visitBaseType('V'); sw.visitReturnType().visitBaseType('V');
} else { } else {
RefTypeOrTPHOrWildcardOrGeneric returnType = method.getReturnType(); RefTypeOrTPHOrWildcardOrGeneric returnType = method.getReturnType();
// return type deswegen ist false // return type deswegen ist false
doVisitParamsOrReturn(returnType, false); // doVisitParamsOrReturn(returnType, false);
} }
// sw.visitEnd(); // sw.visitEnd();
} }
@ -226,7 +280,7 @@ public class Signature {
for (TPHConstraint cons : simplifiedConstraints.keySet()) { for (TPHConstraint cons : simplifiedConstraints.keySet()) {
// need subst. // need subst.
String sub = cons.getLeft()+"$"; String sub = cons.getLeft() + SPECIAL_CHAR;
if (!genericsAndBoundsMethod.containsKey(sub) && !genericsAndBounds.containsKey(sub)) { if (!genericsAndBoundsMethod.containsKey(sub) && !genericsAndBounds.containsKey(sub)) {
sw.visitFormalTypeParameter(sub); sw.visitFormalTypeParameter(sub);
String bound = cons.getRight(); String bound = cons.getRight();
@ -235,7 +289,7 @@ public class Signature {
sw.visitClassBound().visitEnd(); sw.visitClassBound().visitEnd();
genericsAndBoundsMethod.put(sub, bound); genericsAndBoundsMethod.put(sub, bound);
} else { } else {
String boundName = bound+"$"; String boundName = bound + SPECIAL_CHAR;
sw.visitClassBound().visitTypeVariable(boundName); sw.visitClassBound().visitTypeVariable(boundName);
genericsAndBoundsMethod.put(sub, boundName); genericsAndBoundsMethod.put(sub, boundName);
} }
@ -282,6 +336,7 @@ public class Signature {
System.out.println("RES GIP === " + res.size()); System.out.println("RES GIP === " + res.size());
return res; return res;
} }
private boolean contains(ArrayList<TPHConstraint> constraints, TPHConstraint constr) { private boolean contains(ArrayList<TPHConstraint> constraints, TPHConstraint constr) {
for (int i = 0; i < constraints.size(); ++i) { for (int i = 0; i < constraints.size(); ++i) {
TPHConstraint p = constraints.get(i); TPHConstraint p = constraints.get(i);
@ -294,18 +349,13 @@ public class Signature {
/** /**
* 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 isParameterType true if t is type of parameter * @param sv true if t is type of parameter
*/ */
private void doVisitParamsOrReturn(RefTypeOrTPHOrWildcardOrGeneric t, boolean isParameterType) { private void doVisitParamsOrReturn(RefTypeOrTPHOrWildcardOrGeneric t, SignatureVisitor sv) {
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()); String sig = t.acceptTV(new TypeToSignature());
@ -322,13 +372,14 @@ public class Signature {
// 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 TypeToSignature()) // das braucht man nicht es reicht: sv.visitTypeVariable(r.acceptTV(new
// TypeToSignature())
// //
String sig2 = r.acceptTV(new TypeToSignature()); String sig2 = r.acceptTV(new TypeToSignature());
if (r instanceof GenericRefType) { if (r instanceof GenericRefType) {
sv.visitTypeVariable(sig2); sv.visitTypeVariable(sig2);
} else 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); System.out.println(" Signature FUN$$: " + r);
sv.visitInterface().visitClassType(sig2.substring(1, sig2.length())); sv.visitInterface().visitClassType(sig2.substring(1, sig2.length()));
} else { } else {
@ -345,9 +396,18 @@ public class Signature {
} }
} else { } else {
String eqTPH = getEqualTPH(methodConstraints, sig2.substring(1, sig2.length()-1))+"$"; String realName = sig2.substring(1, sig2.length() - 1);
String toVisit = realName+SPECIAL_CHAR;
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;
}
System.out.println(r.getClass() + " Signature TPH: " + r.acceptTV(new TypeToSignature())); System.out.println(r.getClass() + " Signature TPH: " + r.acceptTV(new TypeToSignature()));
sv.visitTypeVariable(eqTPH); }
sv.visitTypeVariable(toVisit);
} }
break; break;
@ -357,15 +417,15 @@ public class Signature {
SuperWildcardType swc = (SuperWildcardType) t; SuperWildcardType swc = (SuperWildcardType) t;
String sigInner = swc.getInnerType().acceptTV(new TypeToSignature()); String sigInner = swc.getInnerType().acceptTV(new TypeToSignature());
if (swc.getInnerType() instanceof TypePlaceholder) { if (swc.getInnerType() instanceof TypePlaceholder) {
sv.visitTypeArgument('-').visitTypeVariable(sigInner.substring(1, sigInner.length())); sv.visitTypeArgument(SUPER_CHAR).visitTypeVariable(sigInner.substring(1, sigInner.length()));
} else if (swc.getInnerType() instanceof RefType) { } else if (swc.getInnerType() instanceof RefType) {
if(sigInner.contains("$$")) { if (sigInner.contains(SPECIAL_CHAR_FOR_FUN)) {
sv.visitTypeArgument('-').visitInterface().visitClassType(sigInner.substring(1,sigInner.length())); sv.visitTypeArgument(SUPER_CHAR).visitInterface().visitClassType(sigInner.substring(1, sigInner.length()));
} else { } else {
sv.visitTypeArgument('-').visitClassType(sigInner.substring(1,sigInner.length())); sv.visitTypeArgument(SUPER_CHAR).visitClassType(sigInner.substring(1, sigInner.length()));
} }
} else { } else {
sv.visitTypeArgument('-').visitTypeVariable(sigInner.substring(1)); sv.visitTypeArgument(SUPER_CHAR).visitTypeVariable(sigInner.substring(1));
} }
break; break;
@ -376,113 +436,117 @@ public class Signature {
String esigInner = ewc.getInnerType().acceptTV(new TypeToSignature()); String esigInner = ewc.getInnerType().acceptTV(new TypeToSignature());
System.out.println(esigInner); System.out.println(esigInner);
if (ewc.getInnerType() instanceof TypePlaceholder) { if (ewc.getInnerType() instanceof TypePlaceholder) {
sv.visitTypeArgument('+').visitTypeVariable(esigInner.substring(1, esigInner.length())); sv.visitTypeArgument(EXTENDS_CHAR).visitTypeVariable(esigInner.substring(1, esigInner.length()));
} else if (ewc.getInnerType() instanceof RefType) { } else if (ewc.getInnerType() instanceof RefType) {
if(esigInner.contains("$$")) { if (esigInner.contains(SPECIAL_CHAR_FOR_FUN)) {
sv.visitTypeArgument('+').visitInterface().visitClassType(esigInner.substring(1,esigInner.length())); sv.visitTypeArgument(EXTENDS_CHAR).visitInterface()
.visitClassType(esigInner.substring(1, esigInner.length()));
} else { } else {
// sv.visitClassType(esigInner.substring(1,esigInner.length())); // sv.visitClassType(esigInner.substring(1,esigInner.length()));
sv.visitTypeArgument('+').visitClassType(esigInner.substring(1,esigInner.length())); sv.visitTypeArgument(EXTENDS_CHAR).visitClassType(esigInner.substring(1, esigInner.length()));
} }
} else { } else {
sv.visitTypeArgument('+').visitTypeVariable(esigInner.substring(1)); sv.visitTypeArgument(EXTENDS_CHAR).visitTypeVariable(esigInner.substring(1));
} }
break; break;
default: default:
if(!isParameterType) // if (!sv)
sv.visitBaseType('V'); // sv.visitBaseType('V');
break; break;
} }
} }
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();
}
/**
* @param isParameterType
* @return
*/
private SignatureVisitor getSignatureVisitor(boolean isParameterType) {
SignatureVisitor sv;
if (isParameterType) {
sv = sw.visitParameterType();
} else {
sv = sw.visitReturnType();
}
return sv;
}
/** /**
* Creates signature for class or interface with {@link SignatureWriter} * Creates signature for class or interface with {@link SignatureWriter}
* Signature looks like: * Signature looks like: <typevaliables (K:Ljava/lang/Object
* <typevaliables (K:Ljava/lang/Object "Bounds")>superclass * "Bounds")>superclass
*/ */
private void createSignatureForClassOrInterface() { private void createSignatureForClassOrInterface() {
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();
getBoundsOfTypeVar(g,genericsAndBounds); visitTypeVarsAndTheirBounds(g, genericsAndBounds);
} }
if(!consClass.isEmpty()) { defineGenericsFromConstraints(consClass,genericsAndBounds);
ArrayList<String> types = new ArrayList<>();
ArrayList<String> superTypes = new ArrayList<>();
for(TPHConstraint cons : consClass) {
types.add(cons.getLeft());
superTypes.add(cons.getRight());
}
for(TPHConstraint cons : consClass) {
String t = cons.getLeft()+"$";
String bound = cons.getRight()+"$";
sw.visitFormalTypeParameter(t);
sw.visitClassBound().visitTypeVariable(bound);
genericsAndBounds.put(t, bound);
}
for(TPHConstraint cons : consClass) {
if(!types.contains(cons.getRight()) && !genericsAndBounds.keySet().contains(cons.getRight()+"$")) {
String t = cons.getRight()+"$";
String bound = Type.getInternalName(Object.class);
sw.visitFormalTypeParameter(t);
sw.visitClassBound().visitClassType(bound);
genericsAndBounds.put(t, bound);
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()); String sClass = classOrInterface.getSuperClass().acceptTV(new TypeToSignature());
sw.visitSuperclass().visitClassType(sClass.substring(1, sClass.length() - 1)); sw.visitSuperclass().visitClassType(sClass.substring(1, sClass.length() - 1));
sw.visitEnd(); sw.visitEnd();
} }
/**
* @param genericsAndBounds2
*
*/
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();
bound = checkBound(bound);
genericsAndBounds2.put(typeVariable, bound);
});
}
/**
* @param bound
* @return
*/
private String checkBound(String bound) {
if (bound.equals(Type.getInternalName(Object.class))) {
visitClassBound(bound);
} else {
bound += SPECIAL_CHAR;
sw.visitClassBound().visitTypeVariable(bound);
}
return bound;
}
/**
* @param bound
*/
private void visitClassBound(String bound) {
sw.visitClassBound().visitClassType(bound);
sw.visitClassBound().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 getBoundsOfTypeVar(GenericTypeVar g, HashMap<String, String> genAndBounds) { private void visitTypeVarsAndTheirBounds(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();
@ -494,8 +558,7 @@ public class Signature {
if (b instanceof GenericRefType) { if (b instanceof GenericRefType) {
sw.visitClassBound().visitTypeVariable(boundDesc); sw.visitClassBound().visitTypeVariable(boundDesc);
} else { } else {
sw.visitClassBound().visitClassType(boundDesc); visitClassBound(boundDesc);
sw.visitClassBound().visitEnd();
} }
genAndBounds.put(g.getName(), boundDesc); genAndBounds.put(g.getName(), boundDesc);
} }

View File

@ -11,6 +11,7 @@ import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.NoSuchElementException; import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.Set; import java.util.Set;
import de.dhbwstuttgart.bytecode.BytecodeGen; import de.dhbwstuttgart.bytecode.BytecodeGen;
@ -18,10 +19,12 @@ import de.dhbwstuttgart.bytecode.TPHExtractor;
import de.dhbwstuttgart.bytecode.constraint.TPHConstraint; import de.dhbwstuttgart.bytecode.constraint.TPHConstraint;
import de.dhbwstuttgart.bytecode.descriptor.TypeToDescriptor; import de.dhbwstuttgart.bytecode.descriptor.TypeToDescriptor;
import de.dhbwstuttgart.bytecode.genericsGenerator.GenericsGenerator; import de.dhbwstuttgart.bytecode.genericsGenerator.GenericsGenerator;
import de.dhbwstuttgart.bytecode.genericsGenerator.GenericsGeneratorUtility;
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.utilities.MethodAndTPH; import de.dhbwstuttgart.bytecode.utilities.MethodAndTPH;
import de.dhbwstuttgart.bytecode.utilities.MethodUtility;
import de.dhbwstuttgart.bytecode.utilities.Resolver; import de.dhbwstuttgart.bytecode.utilities.Resolver;
import de.dhbwstuttgart.bytecode.utilities.Simplify; import de.dhbwstuttgart.bytecode.utilities.Simplify;
import de.dhbwstuttgart.parser.SyntaxTreeGenerator.AssignToLocal; import de.dhbwstuttgart.parser.SyntaxTreeGenerator.AssignToLocal;
@ -75,34 +78,31 @@ import de.dhbwstuttgart.typeinference.result.ResultSet;
* @author fayez * @author fayez
* *
*/ */
public class SimplifyResultFinder implements ASTVisitor { public class GeneratedGenericsFinder implements ASTVisitor {
private final TPHExtractor tphExtractor = new TPHExtractor(); private final TPHExtractor tphExtractor = new TPHExtractor();
private Collection<ResultSet> listOfResultSets; private Collection<ResultSet> listOfResultSets;
private SourceFile sf; private SourceFile sf;
private List<String> tphsClass; private List<String> tphsClass;
private SimplifyResultSourceFile simplifyResOfSourceFile; private GenericGenratorResultForSourceFile generatedGenericsForSF;
private ResultSet resultSet; private ResultSet resultSet;
private List<String> methodNameAndParamsT = new ArrayList<>(); private final List<String> methodNameAndParamsT = new ArrayList<>();
private Resolver resolver;
private String pkgName; private String pkgName;
private String className; private String className;
// stores generics and their bounds of class private Resolver resolver;
private Map<String, String> genericsAndBounds = new HashMap<>();
private Map<String, RefTypeOrTPHOrWildcardOrGeneric> methodParamsAndTypes = new HashMap<>();
/** /**
* @param sf * @param sf
* @param listOfResultSets * @param listOfResultSets
*/ */
public SimplifyResultFinder(SourceFile sf, Collection<ResultSet> listOfResultSets) { public GeneratedGenericsFinder(SourceFile sf, Collection<ResultSet> listOfResultSets) {
this.sf = sf; this.sf = sf;
this.listOfResultSets = listOfResultSets; this.listOfResultSets = listOfResultSets;
} }
public SimplifyResultSourceFile findSimplifyRes() { public GenericGenratorResultForSourceFile findGeneratedGenerics() {
sf.accept(this); sf.accept(this);
return simplifyResOfSourceFile; return generatedGenericsForSF;
} }
/* /*
@ -115,7 +115,7 @@ public class SimplifyResultFinder implements ASTVisitor {
@Override @Override
public void visit(SourceFile sourceFile) { public void visit(SourceFile sourceFile) {
pkgName = sf.getPkgName(); pkgName = sf.getPkgName();
simplifyResOfSourceFile = new SimplifyResultSourceFile(pkgName); generatedGenericsForSF = new GenericGenratorResultForSourceFile(pkgName);
for (ClassOrInterface cl : sourceFile.getClasses()) { for (ClassOrInterface cl : sourceFile.getClasses()) {
cl.accept(this); cl.accept(this);
} }
@ -131,99 +131,60 @@ public class SimplifyResultFinder implements ASTVisitor {
@Override @Override
public void visit(ClassOrInterface classOrInterface) { public void visit(ClassOrInterface classOrInterface) {
className = classOrInterface.getClassName().toString(); className = classOrInterface.getClassName().toString();
SimplifyResult sRes = new SimplifyResult();
SimplifyResultClass sResClass = new SimplifyResultClass(className);
List<ResultSet> listOfResultSetsList = new ArrayList<>(listOfResultSets); List<ResultSet> listOfResultSetsList = new ArrayList<>(listOfResultSets);
boolean isVisited = false;
ConstraintsSimplierResult simplifiedConstraints = null;
GenericsGeneratorResultForClass ggResult = null;
for (int i = 0; i < listOfResultSetsList.size(); i++) { for (int i = 0; i < listOfResultSetsList.size(); i++) {
resultSet = listOfResultSetsList.get(i); resultSet = listOfResultSetsList.get(i);
resolver = new Resolver(resultSet);
tphExtractor.setResultSet(resultSet); tphExtractor.setResultSet(resultSet);
resolver = new Resolver(resultSet);
classOrInterface.accept(tphExtractor); classOrInterface.accept(tphExtractor);
tphsClass = tphExtractor.tphsClass;
if(!isVisited) {
tphsClass = new ArrayList<>(); simplifiedConstraints = GenericsGenerator.simplifyConstraints(tphExtractor, tphsClass);
for (String t : tphExtractor.allTPHS.keySet()) { ggResult = GenericsGenerator.generateConstraints(className, tphExtractor, tphsClass,simplifiedConstraints);
if (!tphExtractor.allTPHS.get(t)) isVisited = true;
tphsClass.add(t);
} }
if (classOrInterface.getGenerics().iterator().hasNext() // for(Constructor m : classOrInterface.getConstructors()) {
|| classOrInterface.getSuperClass().acceptTV(new TypeToSignature()).contains("<") // addMethodConstraints(simplifiedConstraints, ggResult, m);
|| !tphsClass.isEmpty()) { // }
Map<TPHConstraint, Set<String>> constraints = Simplify.simplifyConstraintsClass(tphExtractor, tphsClass);
ArrayList<TPHConstraint> consClass = new ArrayList<>();
for (TPHConstraint cons : constraints.keySet()) {
String right = null;
boolean isToAdd = false;
for (String tph : tphsClass) {
if (cons.getLeft().equals(tph)) {
consClass.add(cons);
try {
right = getTPH(cons.getRight());
isToAdd = true;
} catch (NoSuchElementException e) {
continue;
}
}
}
if (isToAdd && !tphsClass.contains(right)) {
tphsClass.add(right);
removeFromMethod(right);
right = null;
isToAdd = false;
}
}
sRes.setClassConstraints(consClass);
sRes.setTphsClass(tphsClass);
TypeVariableFinder typeVariableFinder = new TypeVariableFinder(classOrInterface, genericsAndBounds, tphsClass,
consClass);
typeVariableFinder.findTV();
}
sResClass.setSimplifyResults(sRes);
simplifyResOfSourceFile.addSimplifyResultClass(sResClass);
for (Constructor c : classOrInterface.getConstructors()) {
c.accept(this);
}
for(Method m : classOrInterface.getMethods()) { for(Method m : classOrInterface.getMethods()) {
m.accept(this); addMethodConstraints(simplifiedConstraints, ggResult, m);
} }
if(ggResult != null)
generatedGenericsForSF.addGenericGeneratorResultClass(ggResult);
} }
} }
private void removeFromMethod(String name) { /**
for (MethodAndTPH m : tphExtractor.ListOfMethodsAndTph) { * @param simplifiedConstraints
ArrayList<String> toRemove = new ArrayList<>(); * @param ggResult
for (String tph : m.getTphs()) { * @param m
if (tph.equals(name)) { */
toRemove.add(tph); public void addMethodConstraints(ConstraintsSimplierResult simplifiedConstraints,
} GenericsGeneratorResultForClass ggResult, Method m) {
} String id = MethodUtility.createID(resolver, m);
boolean isInGGResult = (ggResult != null) && ggResult.contains(id);
if (!toRemove.isEmpty()) { if(methodNameAndParamsT.contains(id) || isInGGResult)
m.getTphs().removeAll(toRemove);
return; 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);
private String getTPH(String name) { });
for (String tph : tphExtractor.allTPHS.keySet()) {
if (tph.equals(name))
return tph;
}
throw new NoSuchElementException("TPH " + name + " does not exist");
} }
/* /*
@ -235,54 +196,7 @@ public class SimplifyResultFinder implements ASTVisitor {
*/ */
@Override @Override
public void visit(Method method) { public void visit(Method method) {
String retType = resolver.getResolvedType(method.getReturnType());
String methParamTypes = retType + method.name + "%%";
method.getParameterList().accept(this);
Iterator<FormalParameter> itr = method.getParameterList().iterator();
while (itr.hasNext()) {
FormalParameter fp = itr.next();
methParamTypes += resolver.getResolvedType(fp.getType()) + ";";
}
if (methodNameAndParamsT.contains(methParamTypes)) {
return;
}
methodNameAndParamsT.add(methParamTypes);
/* Prüfe, ob die Rückgabe-Type der Methode eine Type-Variable ist */
boolean hasGenInParameterList = genericsAndBounds.containsKey(retType) || retType.contains("TPH ")
|| resultSet.resolveType(method.getReturnType()).resolvedType.acceptTV(new TypeToSignature())
.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
*/
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;
}
}
}
/* if method has generics or return type is TPH, create signature */
// zwite operand muss weggelassen werden
if (hasGenInParameterList || resultSet.resolveType(method.getReturnType()).resolvedType.acceptTV(new TypeToString())
.equals("TPH")) {
List<GenericsGeneratorResult> ggR = GenericsGenerator.generateConstraintsForMethod(method, tphExtractor, tphsClass);
Map<TPHConstraint, Set<String>> constraints = Simplify.simplifyConstraints(method,
tphExtractor, tphsClass);
SimplifyResultMethod sResMethod = new SimplifyResultMethod(methParamTypes, constraints);
simplifyResOfSourceFile.getSimplifyResultsByName(pkgName,className).getSimplifyResultForMethod().add(sResMethod);
}
} }
/* /*
@ -294,17 +208,6 @@ public class SimplifyResultFinder implements ASTVisitor {
*/ */
@Override @Override
public void visit(ParameterList formalParameters) { public void visit(ParameterList formalParameters) {
if(!methodParamsAndTypes.isEmpty())
methodParamsAndTypes.clear();
Iterator<FormalParameter> itr = formalParameters.iterator();
int i = 1;
while (itr.hasNext()) {
FormalParameter fp = itr.next();
methodParamsAndTypes.put(fp.getName(), resultSet.resolveType(fp.getType()).resolvedType);
fp.accept(this);
i++;
}
} }
@ -317,38 +220,6 @@ public class SimplifyResultFinder implements ASTVisitor {
*/ */
@Override @Override
public void visit(Constructor field) { public void visit(Constructor field) {
field.getParameterList().accept(this);
String methParamTypes = field.name + "%%";
Iterator<FormalParameter> itr = field.getParameterList().iterator();
while (itr.hasNext()) {
FormalParameter fp = itr.next();
methParamTypes += resolver.getResolvedType(fp.getType()) + ";";
}
if (methodNameAndParamsT.contains(methParamTypes)) {
return;
}
methodNameAndParamsT.add(methParamTypes);
boolean hasGen = false;
for (String paramName : methodParamsAndTypes.keySet()) {
String typeOfParam = methodParamsAndTypes.get(paramName).acceptTV(new TypeToSignature());
System.out.println(typeOfParam);
if (genericsAndBounds.containsKey(typeOfParam) || typeOfParam.contains("$") || typeOfParam.contains("<")) {
hasGen = true;
break;
}
}
if (hasGen) {
Map<TPHConstraint, Set<String>> constraints = Simplify.simplifyConstraints(field, tphExtractor,
tphsClass);
SimplifyResultMethod sResMethod = new SimplifyResultMethod(methParamTypes, constraints);
simplifyResOfSourceFile.getSimplifyResultsByName(pkgName,className).getSimplifyResultForMethod().add(sResMethod);
}
} }

View File

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

View File

@ -0,0 +1,49 @@
/**
*
*/
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) {
if (this.pkgName.equals(pkgName)) {
return genericGeneratorResultForAllClasses.stream().filter(sr -> sr.getClassName().equals(name)).findAny()
.orElseThrow(() -> new NoSuchElementException(
"Simplify results for the class " + pkgName + "." + name + " are not found"));
}
throw new NoSuchElementException("Simplify results for the class " + pkgName + "." + name + " are not found");
}
}

View File

@ -0,0 +1,60 @@
/**
*
*/
package de.dhbwstuttgart.bytecode.simplifyRes;
import java.util.List;
/**
* @author fayez
*
*/
public class GenericsGeneratorResultForClass {
private final String className;
private final List<GenericsGeneratorResult> classConstraints;
private final GenericGeneratorResultsForAllMethods methodsAndTheirConstraints;
/**
* @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) {
return methodsAndTheirConstraints.getMethodsAndConstraints().stream().filter(mc -> mc.getMethodID().equals(id))
.findFirst().get().getConstraints();
}
}

View File

@ -0,0 +1,36 @@
/**
*
*/
package de.dhbwstuttgart.bytecode.simplifyRes;
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,45 +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 SimplifyResultSourceFile {
private String pkgName;
private final List<SimplifyResultClass> simplifyResForSF = new ArrayList<>();
/**
* @param pkgName
*/
public SimplifyResultSourceFile(String pkgName) {
this.pkgName = pkgName;
}
public List<SimplifyResultClass> getSimplifyResForSF() {
return simplifyResForSF;
}
/**
* Appends the simplify results of a class to simplifyResForSF
*
* @param sResClass simplify results of a class to added
*/
public void addSimplifyResultClass(SimplifyResultClass sResClass) {
simplifyResForSF.add(sResClass);
}
public SimplifyResult getSimplifyResultsByName(String pkgName, String name) {
if(this.pkgName.equals(pkgName))
return simplifyResForSF.stream().filter(sr->sr.getClassName().equals(name)).findAny().get().getSimplifyResults();
throw new NoSuchElementException("Simplify results for the class "+pkgName+"."+name+" are not found");
}
}

View File

@ -25,14 +25,12 @@ import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric;
public class TypeVariableFinder { public class TypeVariableFinder {
private ClassOrInterface classOrInterface; private ClassOrInterface classOrInterface;
private Map<String, String> genericsAndBounds; private Map<String, String> genericsAndBounds;
private List<String> tphsClass;
private List<TPHConstraint> consClass; private List<TPHConstraint> consClass;
public TypeVariableFinder(ClassOrInterface classOrInterface, Map<String, String> genericsAndBounds, public TypeVariableFinder(ClassOrInterface classOrInterface, Map<String, String> genericsAndBounds,
List<String> tphsClass, List<TPHConstraint> consClass) { List<TPHConstraint> consClass) {
this.classOrInterface = classOrInterface; this.classOrInterface = classOrInterface;
this.genericsAndBounds = genericsAndBounds; this.genericsAndBounds = genericsAndBounds;
this.tphsClass = tphsClass;
this.consClass = consClass; this.consClass = consClass;
} }
@ -55,17 +53,12 @@ public class TypeVariableFinder {
for(TPHConstraint cons : consClass) { for(TPHConstraint cons : consClass) {
String t = cons.getLeft()+"$"; String t = cons.getLeft()+"$";
String bound = cons.getRight()+"$"; String bound = cons.getRight();
if(!bound.equals(Type.getInternalName(Object.class)))
bound += "$";
genericsAndBounds.put(t, bound); genericsAndBounds.put(t, bound);
} }
for(TPHConstraint cons : consClass) {
if(!types.contains(cons.getRight()) && !genericsAndBounds.keySet().contains(cons.getRight()+"$")) {
String t = cons.getRight()+"$";
String bound = Type.getInternalName(Object.class);
genericsAndBounds.put(t, bound);
}
}
} }
} }

View File

@ -4,6 +4,7 @@ import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.stream.Stream;
import de.dhbwstuttgart.bytecode.constraint.TPHConstraint; import de.dhbwstuttgart.bytecode.constraint.TPHConstraint;
import de.dhbwstuttgart.bytecode.genericsGenerator.NameReplacementResult; import de.dhbwstuttgart.bytecode.genericsGenerator.NameReplacementResult;
@ -52,11 +53,11 @@ public class NameReplacer {
substituteRightSidesWithNewName(newName, names); substituteRightSidesWithNewName(newName, names);
substituteNamesInAllConstraints(newName, names); substituteNamesInAllConstraints(newName, names);
methodAndTPHs.stream().map(m->m.getTphs()).forEach(tphsMethod->{ Stream<ArrayList<String>> tphsOfMethods = methodAndTPHs.stream().map(m->m.getTphs());
if(tphsMethod.removeAll(names)) Stream<ArrayList<String>> localTphsOfMethods = methodAndTPHs.stream().map(m->m.getLocalTphs());
tphsMethod.add(newName);
});
replaceOldNames(newName, names, tphsOfMethods);
replaceOldNames(newName, names, localTphsOfMethods);
if(tphs.removeAll(names)) if(tphs.removeAll(names))
tphs.add(newName); tphs.add(newName);
@ -66,6 +67,18 @@ public class NameReplacer {
return res; 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() { public NameReplacementResult replaceNamesLocal() {
String newName = NameGenerator.makeNewName(); String newName = NameGenerator.makeNewName();
List<String> names = new ArrayList<>(); List<String> names = new ArrayList<>();

View File

@ -1,12 +1,11 @@
//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.Exception.BytecodeGeneratorError;
import de.dhbwstuttgart.bytecode.simplifyRes.SimplifyResult; import de.dhbwstuttgart.bytecode.simplifyRes.SimplifyResult;
import de.dhbwstuttgart.bytecode.simplifyRes.SimplifyResultFinder; import de.dhbwstuttgart.bytecode.simplifyRes.GeneratedGenericsFinder;
import de.dhbwstuttgart.bytecode.simplifyRes.SimplifyResultSourceFile; import de.dhbwstuttgart.bytecode.simplifyRes.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.NullToken;
@ -63,10 +62,11 @@ public class JavaTXCompiler {
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 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));
} }
@ -93,8 +93,8 @@ public class JavaTXCompiler {
for (File forSourceFile : sourceFiles.keySet()) for (File forSourceFile : sourceFiles.keySet())
for (JavaClassName name : sourceFiles.get(forSourceFile).getImports()) { for (JavaClassName name : sourceFiles.get(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.createClass( ClassOrInterface importedClass = ASTFactory
ClassLoader.getSystemClassLoader().loadClass(name.toString())); .createClass(ClassLoader.getSystemClassLoader().loadClass(name.toString()));
importedClasses.add(importedClass); importedClasses.add(importedClass);
} }
allClasses.addAll(importedClasses); allClasses.addAll(importedClasses);
@ -103,21 +103,23 @@ public class JavaTXCompiler {
} }
public List<ClassOrInterface> getAvailableClasses(SourceFile forSourceFile) throws ClassNotFoundException { public List<ClassOrInterface> getAvailableClasses(SourceFile forSourceFile) throws ClassNotFoundException {
//PL 2018-09-18: List durch Set ersetzt, damit die Klassen nur einmal hinzugefuegt werden // PL 2018-09-18: List durch Set ersetzt, damit die Klassen nur einmal
//List<ClassOrInterface> allClasses = new ArrayList<>();//environment.getAllAvailableClasses(); // hinzugefuegt werden
// List<ClassOrInterface> allClasses = new
// ArrayList<>();//environment.getAllAvailableClasses();
Set<ClassOrInterface> allClasses = new HashSet<>(); Set<ClassOrInterface> allClasses = new HashSet<>();
/* PL 2018-09-19 geloescht werden bereits in typeInference hinzugefuegt /*
for (SourceFile sf : sourceFiles.values()) { * PL 2018-09-19 geloescht werden bereits in typeInference hinzugefuegt for
allClasses.addAll(sf.getClasses()); * (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.createClass( ClassOrInterface importedClass = ASTFactory
ClassLoader.getSystemClassLoader().loadClass(name.toString())); .createClass(ClassLoader.getSystemClassLoader().loadClass(name.toString()));
importedClasses.add(importedClass); importedClasses.add(importedClass);
allClasses.addAll(importedClasses); allClasses.addAll(importedClasses);
} }
@ -125,168 +127,152 @@ public class JavaTXCompiler {
} }
/* /*
public List<ResultSet> typeInferenceOld() throws ClassNotFoundException { * public List<ResultSet> typeInferenceOld() throws ClassNotFoundException {
List<ClassOrInterface> allClasses = new ArrayList<>();//environment.getAllAvailableClasses(); * List<ClassOrInterface> allClasses = new
//Alle Importierten Klassen in allen geparsten Sourcefiles kommen ins FC * ArrayList<>();//environment.getAllAvailableClasses(); //Alle Importierten
for(SourceFile sf : this.sourceFiles.values()) { * Klassen in allen geparsten Sourcefiles kommen ins FC for(SourceFile sf :
allClasses.addAll(getAvailableClasses(sf)); * this.sourceFiles.values()) { 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);
FiniteClosure finiteClosure = UnifyTypeFactory.generateFC(allClasses); * System.out.println(finiteClosure); ConstraintSet<UnifyPair> unifyCons =
System.out.println(finiteClosure); * UnifyTypeFactory.convert(cons);
ConstraintSet<UnifyPair> unifyCons = UnifyTypeFactory.convert(cons); *
* TypeUnify unify = new TypeUnify(); Set<Set<UnifyPair>> results = new
TypeUnify unify = new TypeUnify(); * HashSet<>(); try { File logPath = new
Set<Set<UnifyPair>> results = new HashSet<>(); * File(System.getProperty("user.dir")+"/target/logFiles/"); logPath.mkdirs();
try { * FileWriter logFile = new FileWriter(new File(logPath, "log"));
File logPath = new File(System.getProperty("user.dir")+"/target/logFiles/"); * logFile.write("FC:\\" + finiteClosure.toString()+"\n"); for(SourceFile sf :
logPath.mkdirs(); * this.sourceFiles.values()) { logFile.write(ASTTypePrinter.print(sf)); }
FileWriter logFile = new FileWriter(new File(logPath, "log")); * logFile.flush(); Set<List<Constraint<UnifyPair>>> cardProd =
logFile.write("FC:\\" + finiteClosure.toString()+"\n"); * unifyCons.cartesianProduct(); for (List<Constraint<UnifyPair>> xCons :
for(SourceFile sf : this.sourceFiles.values()) { * cardProd ){ Set<UnifyPair> xConsSet = new HashSet<>(); for
logFile.write(ASTTypePrinter.print(sf)); * (Constraint<UnifyPair> constraint : xCons) { xConsSet.addAll(constraint); }
} * //.collect(Collectors.toCollection(ArrayList::new))))
logFile.flush(); * System.out.println(xConsSet); Set<String> methodParaTypeVarNames =
Set<List<Constraint<UnifyPair>>> cardProd = unifyCons.cartesianProduct(); * allClasses.stream().map(x -> x.getMethods().stream().map(y ->
for (List<Constraint<UnifyPair>> xCons : cardProd ){ * y.getParameterList().getFormalparalist() .stream().filter(z -> z.getType()
Set<UnifyPair> xConsSet = new HashSet<>(); * instanceof TypePlaceholder) .map(z ->
for (Constraint<UnifyPair> constraint : xCons) { * ((TypePlaceholder)z.getType()).getName()).collect(Collectors.toCollection(
xConsSet.addAll(constraint); * HashSet::new))) .reduce(new HashSet<String>(), (a,b) -> { a.addAll(b); return
} * a;}, (a,b) -> { a.addAll(b); return a;} ) ) .reduce(new HashSet<String>(),
//.collect(Collectors.toCollection(ArrayList::new)))) * (a,b) -> { a.addAll(b); return a;} );
System.out.println(xConsSet); *
Set<String> methodParaTypeVarNames = allClasses.stream().map(x -> x.getMethods().stream().map(y -> y.getParameterList().getFormalparalist() * Set<String> constructorParaTypeVarNames = allClasses.stream().map(x ->
.stream().filter(z -> z.getType() instanceof TypePlaceholder) * x.getConstructors().stream().map(y ->
.map(z -> ((TypePlaceholder)z.getType()).getName()).collect(Collectors.toCollection(HashSet::new))) * y.getParameterList().getFormalparalist() .stream().filter(z -> z.getType()
.reduce(new HashSet<String>(), (a,b) -> { a.addAll(b); return a;}, (a,b) -> { a.addAll(b); return a;} ) ) * instanceof TypePlaceholder) .map(z ->
.reduce(new HashSet<String>(), (a,b) -> { a.addAll(b); return a;} ); * ((TypePlaceholder)z.getType()).getName()).collect(Collectors.toCollection(
* HashSet::new))) .reduce(new HashSet<String>(), (a,b) -> { a.addAll(b); return
Set<String> constructorParaTypeVarNames = allClasses.stream().map(x -> x.getConstructors().stream().map(y -> y.getParameterList().getFormalparalist() * a;}, (a,b) -> { a.addAll(b); return a;} ) ) .reduce(new HashSet<String>(),
.stream().filter(z -> z.getType() instanceof TypePlaceholder) * (a,b) -> { a.addAll(b); return a;} );
.map(z -> ((TypePlaceholder)z.getType()).getName()).collect(Collectors.toCollection(HashSet::new))) *
.reduce(new HashSet<String>(), (a,b) -> { a.addAll(b); return a;}, (a,b) -> { a.addAll(b); return a;} ) ) * Set<String> paraTypeVarNames = methodParaTypeVarNames;
.reduce(new HashSet<String>(), (a,b) -> { a.addAll(b); return a;} ); * paraTypeVarNames.addAll(constructorParaTypeVarNames);
*
Set<String> paraTypeVarNames = methodParaTypeVarNames; * Set<String> returnTypeVarNames = allClasses.stream().map(x ->
paraTypeVarNames.addAll(constructorParaTypeVarNames); * x.getMethods().stream().filter(y -> y.getReturnType() instanceof
* TypePlaceholder) .map(z ->
Set<String> returnTypeVarNames = allClasses.stream().map(x -> x.getMethods().stream().filter(y -> y.getReturnType() instanceof TypePlaceholder) * ((TypePlaceholder)z.getReturnType()).getName()).collect(Collectors.
.map(z -> ((TypePlaceholder)z.getReturnType()).getName()).collect(Collectors.toCollection(HashSet::new))).reduce((a,b) -> { a.addAll(b); return a;} ).get(); * toCollection(HashSet::new))).reduce((a,b) -> { a.addAll(b); return a;}
* ).get();
Set<String> fieldTypeVarNames = allClasses.stream().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(); * Set<String> fieldTypeVarNames = allClasses.stream().map(x ->
* x.getFieldDecl().stream().filter(y -> y.getReturnType() instanceof
returnTypeVarNames.addAll(fieldTypeVarNames); * TypePlaceholder) .map(z ->
* ((TypePlaceholder)z.getReturnType()).getName()).collect(Collectors.
xConsSet = xConsSet.stream().map(x -> { * toCollection(HashSet::new))).reduce((a,b) -> { a.addAll(b); return a;}
//Hier muss ueberlegt werden, ob * ).get();
//1. alle Argument- und Retuntyp-Variablen in allen UnifyPairs *
// mit disableWildcardtable() werden. * returnTypeVarNames.addAll(fieldTypeVarNames);
//2. alle Typvariablen mit Argument- oder Retuntyp-Variablen *
//in Beziehung auch auf disableWildcardtable() gesetzt werden muessen * xConsSet = xConsSet.stream().map(x -> { //Hier muss ueberlegt werden, ob //1.
//PL 2018-04-23 * alle Argument- und Retuntyp-Variablen in allen UnifyPairs // mit
if ((x.getLhsType() instanceof PlaceholderType)) { * disableWildcardtable() werden. //2. alle Typvariablen mit Argument- oder
if (paraTypeVarNames.contains(x.getLhsType().getName())) { * Retuntyp-Variablen //in Beziehung auch auf disableWildcardtable() gesetzt
((PlaceholderType)x.getLhsType()).setVariance((byte)1); * werden muessen //PL 2018-04-23 if ((x.getLhsType() instanceof
((PlaceholderType)x.getLhsType()).disableWildcardtable(); * PlaceholderType)) { if (paraTypeVarNames.contains(x.getLhsType().getName()))
} * { ((PlaceholderType)x.getLhsType()).setVariance((byte)1);
if (returnTypeVarNames.contains(x.getLhsType().getName())) { * ((PlaceholderType)x.getLhsType()).disableWildcardtable(); } if
((PlaceholderType)x.getLhsType()).setVariance((byte)-1); * (returnTypeVarNames.contains(x.getLhsType().getName())) {
((PlaceholderType)x.getLhsType()).disableWildcardtable(); * ((PlaceholderType)x.getLhsType()).setVariance((byte)-1);
} * ((PlaceholderType)x.getLhsType()).disableWildcardtable(); } } if
} * ((x.getRhsType() instanceof PlaceholderType)) { if
if ((x.getRhsType() instanceof PlaceholderType)) { * (paraTypeVarNames.contains(x.getRhsType().getName())) {
if (paraTypeVarNames.contains(x.getRhsType().getName())) { * ((PlaceholderType)x.getRhsType()).setVariance((byte)1);
((PlaceholderType)x.getRhsType()).setVariance((byte)1); * ((PlaceholderType)x.getRhsType()).disableWildcardtable(); } if
((PlaceholderType)x.getRhsType()).disableWildcardtable(); * (returnTypeVarNames.contains(x.getRhsType().getName())) {
} * ((PlaceholderType)x.getRhsType()).setVariance((byte)-1);
if (returnTypeVarNames.contains(x.getRhsType().getName())) { * ((PlaceholderType)x.getRhsType()).disableWildcardtable(); } } return x;//HIER
((PlaceholderType)x.getRhsType()).setVariance((byte)-1); * DIE JEWEILS RECHT BZW. LINKE SEITE AUF GLEICHE VARIANZ SETZEN WIE DIE JEWEILS
((PlaceholderType)x.getRhsType()).disableWildcardtable(); * ANDERE SEITE }).map( y -> { if ((y.getLhsType() instanceof PlaceholderType)
} * && (y.getRhsType() instanceof PlaceholderType)) { if
} * (((PlaceholderType)y.getLhsType()).getVariance() != 0 &&
return x;//HIER DIE JEWEILS RECHT BZW. LINKE SEITE AUF GLEICHE VARIANZ SETZEN WIE DIE JEWEILS ANDERE SEITE * ((PlaceholderType)y.getRhsType()).getVariance() == 0) {
}).map( y -> { * ((PlaceholderType)y.getRhsType()).setVariance(((PlaceholderType)y.getLhsType(
if ((y.getLhsType() instanceof PlaceholderType) && (y.getRhsType() instanceof PlaceholderType)) { * )).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.getRhsType()).setVariance(((PlaceholderType)y.getLhsType()).getVariance()); * ((PlaceholderType)y.getLhsType()).setVariance(((PlaceholderType)y.getRhsType(
} * )).getVariance()); } } return y; } )
if (((PlaceholderType)y.getLhsType()).getVariance() == 0 && ((PlaceholderType)y.getRhsType()).getVariance() != 0) { * .collect(Collectors.toCollection(HashSet::new));
((PlaceholderType)y.getLhsType()).setVariance(((PlaceholderType)y.getRhsType()).getVariance()); * varianceInheritance(xConsSet); Set<Set<UnifyPair>> result =
} * unify.unifySequential(xConsSet, finiteClosure, logFile, log);
} * //Set<Set<UnifyPair>> result = unify.unify(xConsSet, finiteClosure);
return y; } ) * System.out.println("RESULT: " + result); logFile.write("RES: " +
.collect(Collectors.toCollection(HashSet::new)); * result.toString()+"\n"); logFile.flush(); results.addAll(result); }
varianceInheritance(xConsSet); *
Set<Set<UnifyPair>> result = unify.unifySequential(xConsSet, finiteClosure, logFile, log); * results = results.stream().map(x -> { Optional<Set<UnifyPair>> res = new
//Set<Set<UnifyPair>> result = unify.unify(xConsSet, finiteClosure); * RuleSet().subst(x.stream().map(y -> { if (y.getPairOp() ==
System.out.println("RESULT: " + result); * PairOperator.SMALLERDOTWC) y.setPairOp(PairOperator.EQUALSDOT); return y;
logFile.write("RES: " + result.toString()+"\n"); * //alle Paare a <.? b erden durch a =. b ersetzt
logFile.flush(); * }).collect(Collectors.toCollection(HashSet::new))); if (res.isPresent())
results.addAll(result); * {//wenn subst ein Erg liefert wurde was veraendert return new
} * TypeUnifyTask().applyTypeUnificationRules(res.get(), finiteClosure); } else
* return x; //wenn nichts veraendert wurde wird x zurueckgegeben
results = results.stream().map(x -> { * }).collect(Collectors.toCollection(HashSet::new));
Optional<Set<UnifyPair>> res = new RuleSet().subst(x.stream().map(y -> { * System.out.println("RESULT Final: " + results); logFile.write("RES_FINAL: " +
if (y.getPairOp() == PairOperator.SMALLERDOTWC) y.setPairOp(PairOperator.EQUALSDOT); * results.toString()+"\n"); logFile.flush(); logFile.write("PLACEHOLDERS: " +
return y; //alle Paare a <.? b erden durch a =. b ersetzt * PlaceholderType.EXISTING_PLACEHOLDERS); logFile.flush(); } catch (IOException
}).collect(Collectors.toCollection(HashSet::new))); * e) { e.printStackTrace(); } return results.stream().map((unifyPairs -> new
if (res.isPresent()) {//wenn subst ein Erg liefert wurde was veraendert * ResultSet(UnifyTypeFactory.convert(unifyPairs,
return new TypeUnifyTask().applyTypeUnificationRules(res.get(), finiteClosure); * generateTPHMap(cons))))).collect(Collectors.toList()); }
}
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) * Vererbt alle Variancen bei Paaren (a <. theta) oder (Theta <. a) wenn a eine
* wenn a eine Variance !=0 hat auf alle Typvariablen in Theta. * Variance !=0 hat auf alle Typvariablen in Theta.
* @param eq The set of constraints *
*
*/ */
/* /*
private void varianceInheritance(Set<UnifyPair> eq) { * private void varianceInheritance(Set<UnifyPair> eq) { Set<PlaceholderType>
Set<PlaceholderType> usedTPH = new HashSet<>(); * usedTPH = new HashSet<>(); Set<PlaceholderType> phSet = eq.stream().map(x ->
Set<PlaceholderType> phSet = eq.stream().map(x -> { * { Set<PlaceholderType> pair = new HashSet<>(); if (x.getLhsType() instanceof
Set<PlaceholderType> pair = new HashSet<>(); * PlaceholderType) pair.add((PlaceholderType)x.getLhsType()); if
if (x.getLhsType() instanceof PlaceholderType) pair.add((PlaceholderType)x.getLhsType()); * (x.getRhsType() instanceof PlaceholderType)
if (x.getRhsType() instanceof PlaceholderType) pair.add((PlaceholderType)x.getRhsType()); * pair.add((PlaceholderType)x.getRhsType()); return pair; }).reduce(new
return pair; * HashSet<>(), (a,b) -> { a.addAll(b); return a;} , (c,d) -> { c.addAll(d);
}).reduce(new HashSet<>(), (a,b) -> { a.addAll(b); return a;} , (c,d) -> { c.addAll(d); return c;}); * 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()) { * while(!phSetVariance.isEmpty()) { PlaceholderType a =
PlaceholderType a = phSetVariance.remove(0); * phSetVariance.remove(0); usedTPH.add(a); //HashMap<PlaceholderType,Integer>
usedTPH.add(a); * ht = new HashMap<>(); //ht.put(a, a.getVariance()); Set<UnifyPair> eq1 = new
//HashMap<PlaceholderType,Integer> ht = new HashMap<>(); * HashSet<>(eq); eq1.removeIf(x -> !(x.getLhsType() instanceof PlaceholderType
//ht.put(a, a.getVariance()); * && ((PlaceholderType)x.getLhsType()).equals(a))); eq1.stream().forEach(x -> {
Set<UnifyPair> eq1 = new HashSet<>(eq); * x.getRhsType().accept(new distributeVariance(), a.getVariance());}); eq1 =
eq1.removeIf(x -> !(x.getLhsType() instanceof PlaceholderType && ((PlaceholderType)x.getLhsType()).equals(a))); * new HashSet<>(eq); eq1.removeIf(x -> !(x.getRhsType() instanceof
eq1.stream().forEach(x -> { x.getRhsType().accept(new distributeVariance(), a.getVariance());}); * PlaceholderType && ((PlaceholderType)x.getRhsType()).equals(a)));
eq1 = new HashSet<>(eq); * eq1.stream().forEach(x -> { x.getLhsType().accept(new distributeVariance(),
eq1.removeIf(x -> !(x.getRhsType() instanceof PlaceholderType && ((PlaceholderType)x.getRhsType()).equals(a))); * a.getVariance());}); phSetVariance = new ArrayList<>(phSet);
eq1.stream().forEach(x -> { x.getLhsType().accept(new distributeVariance(), a.getVariance());}); * phSetVariance.removeIf(x -> (x.getVariance() == 0 || usedTPH.contains(x))); }
phSetVariance = new ArrayList<>(phSet); * }
phSetVariance.removeIf(x -> (x.getVariance() == 0 || usedTPH.contains(x)));
}
}
*/ */
public UnifyResultModel typeInferenceAsync(UnifyResultListener resultListener, Writer logFile) throws ClassNotFoundException { public UnifyResultModel typeInferenceAsync(UnifyResultListener resultListener, Writer logFile)
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()) {
@ -299,21 +285,20 @@ public class JavaTXCompiler {
UnifyResultModel urm = null; UnifyResultModel urm = null;
// urm.addUnifyResultListener(resultListener); // urm.addUnifyResultListener(resultListener);
try { try {
logFile = logFile == null ? new FileWriter(new File("log_"+sourceFiles.keySet().iterator().next().getName())) : logFile; logFile = logFile == null
? new FileWriter(new File("log_" + sourceFiles.keySet().iterator().next().getName()))
: logFile;
IFiniteClosure finiteClosure = UnifyTypeFactory.generateFC(allClasses, logFile); IFiniteClosure finiteClosure = UnifyTypeFactory.generateFC(allClasses, logFile);
System.out.println(finiteClosure); System.out.println(finiteClosure);
urm = new UnifyResultModel(cons, finiteClosure); urm = new UnifyResultModel(cons, finiteClosure);
urm.addUnifyResultListener(resultListener); urm.addUnifyResultListener(resultListener);
ConstraintSet<UnifyPair> unifyCons = UnifyTypeFactory.convert(cons); ConstraintSet<UnifyPair> unifyCons = UnifyTypeFactory.convert(cons);
Function<UnifyPair, UnifyPair> distributeInnerVars = Function<UnifyPair, UnifyPair> distributeInnerVars = x -> {
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) lhs).isInnerType() || ((PlaceholderType) rhs).isInnerType())) {
|| ((PlaceholderType)rhs).isInnerType()))
{
((PlaceholderType) lhs).setInnerType(true); ((PlaceholderType) lhs).setInnerType(true);
((PlaceholderType) rhs).setInnerType(true); ((PlaceholderType) rhs).setInnerType(true);
} }
@ -331,27 +316,58 @@ public class JavaTXCompiler {
} }
logFile.flush(); logFile.flush();
Set<String> methodParaTypeVarNames = allClasses.stream().map(x -> x.getMethods().stream().map(y -> y.getParameterList().getFormalparalist() Set<String> methodParaTypeVarNames = allClasses.stream().map(x -> x.getMethods().stream()
.stream().filter(z -> z.getType() instanceof TypePlaceholder) .map(y -> y.getParameterList().getFormalparalist().stream()
.map(z -> ((TypePlaceholder)z.getType()).getName()).collect(Collectors.toCollection(HashSet::new))) .filter(z -> z.getType() instanceof TypePlaceholder)
.reduce(new HashSet<String>(), (a,b) -> { a.addAll(b); return a;}, (a,b) -> { a.addAll(b); return a;} ) ) .map(z -> ((TypePlaceholder) z.getType()).getName())
.reduce(new HashSet<String>(), (a,b) -> { a.addAll(b); return a;} ); .collect(Collectors.toCollection(HashSet::new)))
.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().map(y -> y.getParameterList().getFormalparalist() Set<String> constructorParaTypeVarNames = allClasses.stream().map(x -> x.getConstructors().stream()
.stream().filter(z -> z.getType() instanceof TypePlaceholder) .map(y -> y.getParameterList().getFormalparalist().stream()
.map(z -> ((TypePlaceholder)z.getType()).getName()).collect(Collectors.toCollection(HashSet::new))) .filter(z -> z.getType() instanceof TypePlaceholder)
.reduce(new HashSet<String>(), (a,b) -> { a.addAll(b); return a;}, (a,b) -> { a.addAll(b); return a;} ) ) .map(z -> ((TypePlaceholder) z.getType()).getName())
.reduce(new HashSet<String>(), (a,b) -> { a.addAll(b); return a;} ); .collect(Collectors.toCollection(HashSet::new)))
.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> returnTypeVarNames = allClasses.stream().map(x -> x.getMethods().stream().filter(y -> y.getReturnType() instanceof TypePlaceholder) Set<String> fieldTypeVarNames = allClasses.stream()
.map(z -> ((TypePlaceholder)z.getReturnType()).getName()).collect(Collectors.toCollection(HashSet::new))).reduce((a,b) -> { a.addAll(b); return a;} ).get(); .map(x -> x.getFieldDecl().stream().filter(y -> y.getReturnType() instanceof TypePlaceholder)
.map(z -> ((TypePlaceholder) z.getReturnType()).getName())
Set<String> fieldTypeVarNames = allClasses.stream().map(x -> x.getFieldDecl().stream().filter(y -> y.getReturnType() instanceof TypePlaceholder) .collect(Collectors.toCollection(HashSet::new)))
.map(z -> ((TypePlaceholder)z.getReturnType()).getName()).collect(Collectors.toCollection(HashSet::new))).reduce((a,b) -> { a.addAll(b); return a;} ).get(); .reduce((a, b) -> {
a.addAll(b);
return a;
}).get();
returnTypeVarNames.addAll(fieldTypeVarNames); returnTypeVarNames.addAll(fieldTypeVarNames);
@ -382,31 +398,32 @@ 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 JEWEILS ANDERE SEITE return x;// HIER DIE JEWEILS RECHT BZW. LINKE SEITE AUF GLEICHE VARIANZ SETZEN WIE DIE
// 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 /*
do { //PL 2018-11-05 Huellenbildung Variance auf alle TPHs der Terme auf der jeweiligen * PL 2018-11-07 wird in varianceInheritanceConstraintSet erledigt do { //PL
//anderen Seite übertragen * 2018-11-05 Huellenbildung Variance auf alle TPHs der Terme auf der jeweiligen
varianceTPHold = new HashSet<>(varianceTPH); * //anderen Seite übertragen varianceTPHold = new HashSet<>(varianceTPH);
varianceTPH = varianceInheritanceConstraintSet(unifyCons); * varianceTPH = varianceInheritanceConstraintSet(unifyCons); unifyCons.map( y
unifyCons.map( y -> { * -> { if ((y.getLhsType() instanceof PlaceholderType) && (y.getRhsType()
if ((y.getLhsType() instanceof PlaceholderType) && (y.getRhsType() instanceof PlaceholderType)) { * instanceof PlaceholderType)) { if
if (((PlaceholderType)y.getLhsType()).getVariance() != 0 && ((PlaceholderType)y.getRhsType()).getVariance() == 0) { * (((PlaceholderType)y.getLhsType()).getVariance() != 0 &&
((PlaceholderType)y.getRhsType()).setVariance(((PlaceholderType)y.getLhsType()).getVariance()); * ((PlaceholderType)y.getRhsType()).getVariance() == 0) {
} * ((PlaceholderType)y.getRhsType()).setVariance(((PlaceholderType)y.getLhsType(
if (((PlaceholderType)y.getLhsType()).getVariance() == 0 && ((PlaceholderType)y.getRhsType()).getVariance() != 0) { * )).getVariance()); } if (((PlaceholderType)y.getLhsType()).getVariance() == 0
((PlaceholderType)y.getLhsType()).setVariance(((PlaceholderType)y.getRhsType()).getVariance()); * && ((PlaceholderType)y.getRhsType()).getVariance() != 0) {
} * ((PlaceholderType)y.getLhsType()).setVariance(((PlaceholderType)y.getRhsType(
} * )).getVariance()); } } return y; } ); } while
return y; } ); } * (!varianceTPHold.equals(varianceTPH));
while (!varianceTPHold.equals(varianceTPH));
*/ */
//Set<Set<UnifyPair>> result = unify.unifySequential(xConsSet, finiteClosure, logFile, log); // Set<Set<UnifyPair>> result = unify.unifySequential(xConsSet, finiteClosure,
// 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<>();
@ -415,15 +432,14 @@ 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, usedTasks); unify.unifyAsync(unifyCons.getUndConstraints(), oderConstraints, finiteClosure, logFile, log, 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
@ -436,20 +452,19 @@ public class JavaTXCompiler {
Set<Set<UnifyPair>> results = new HashSet<>(); Set<Set<UnifyPair>> results = new HashSet<>();
try { try {
Writer logFile = // new OutputStreamWriter(new NullOutputStream()); Writer logFile = // new OutputStreamWriter(new NullOutputStream());
//new FileWriter(new File(System.getProperty("user.dir")+"/src/test/resources/logFiles/"+"log_"+sourceFiles.keySet().iterator().next().getName())); // new FileWriter(new
new FileWriter(new File(System.getProperty("user.dir")+"/logFiles/"+"log_"+sourceFiles.keySet().iterator().next().getName())); // 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 = Function<UnifyPair, UnifyPair> distributeInnerVars = x -> {
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) lhs).isInnerType() || ((PlaceholderType) rhs).isInnerType())) {
|| ((PlaceholderType)rhs).isInnerType()))
{
((PlaceholderType) lhs).setInnerType(true); ((PlaceholderType) lhs).setInnerType(true);
((PlaceholderType) rhs).setInnerType(true); ((PlaceholderType) rhs).setInnerType(true);
} }
@ -467,27 +482,58 @@ public class JavaTXCompiler {
} }
logFile.flush(); logFile.flush();
Set<String> methodParaTypeVarNames = allClasses.stream().map(x -> x.getMethods().stream().map(y -> y.getParameterList().getFormalparalist() Set<String> methodParaTypeVarNames = allClasses.stream().map(x -> x.getMethods().stream()
.stream().filter(z -> z.getType() instanceof TypePlaceholder) .map(y -> y.getParameterList().getFormalparalist().stream()
.map(z -> ((TypePlaceholder)z.getType()).getName()).collect(Collectors.toCollection(HashSet::new))) .filter(z -> z.getType() instanceof TypePlaceholder)
.reduce(new HashSet<String>(), (a,b) -> { a.addAll(b); return a;}, (a,b) -> { a.addAll(b); return a;} ) ) .map(z -> ((TypePlaceholder) z.getType()).getName())
.reduce(new HashSet<String>(), (a,b) -> { a.addAll(b); return a;} ); .collect(Collectors.toCollection(HashSet::new)))
.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().map(y -> y.getParameterList().getFormalparalist() Set<String> constructorParaTypeVarNames = allClasses.stream().map(x -> x.getConstructors().stream()
.stream().filter(z -> z.getType() instanceof TypePlaceholder) .map(y -> y.getParameterList().getFormalparalist().stream()
.map(z -> ((TypePlaceholder)z.getType()).getName()).collect(Collectors.toCollection(HashSet::new))) .filter(z -> z.getType() instanceof TypePlaceholder)
.reduce(new HashSet<String>(), (a,b) -> { a.addAll(b); return a;}, (a,b) -> { a.addAll(b); return a;} ) ) .map(z -> ((TypePlaceholder) z.getType()).getName())
.reduce(new HashSet<String>(), (a,b) -> { a.addAll(b); return a;} ); .collect(Collectors.toCollection(HashSet::new)))
.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> returnTypeVarNames = allClasses.stream().map(x -> x.getMethods().stream().filter(y -> y.getReturnType() instanceof TypePlaceholder) Set<String> fieldTypeVarNames = allClasses.stream()
.map(z -> ((TypePlaceholder)z.getReturnType()).getName()).collect(Collectors.toCollection(HashSet::new))).reduce((a,b) -> { a.addAll(b); return a;} ).get(); .map(x -> x.getFieldDecl().stream().filter(y -> y.getReturnType() instanceof TypePlaceholder)
.map(z -> ((TypePlaceholder) z.getReturnType()).getName())
Set<String> fieldTypeVarNames = allClasses.stream().map(x -> x.getFieldDecl().stream().filter(y -> y.getReturnType() instanceof TypePlaceholder) .collect(Collectors.toCollection(HashSet::new)))
.map(z -> ((TypePlaceholder)z.getReturnType()).getName()).collect(Collectors.toCollection(HashSet::new))).reduce((a,b) -> { a.addAll(b); return a;} ).get(); .reduce((a, b) -> {
a.addAll(b);
return a;
}).get();
returnTypeVarNames.addAll(fieldTypeVarNames); returnTypeVarNames.addAll(fieldTypeVarNames);
@ -518,31 +564,32 @@ 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 JEWEILS ANDERE SEITE return x;// HIER DIE JEWEILS RECHT BZW. LINKE SEITE AUF GLEICHE VARIANZ SETZEN WIE DIE
// 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 /*
do { //PL 2018-11-05 Huellenbildung Variance auf alle TPHs der Terme auf der jeweiligen * PL 2018-11-07 wird in varianceInheritanceConstraintSet erledigt do { //PL
//anderen Seite übertragen * 2018-11-05 Huellenbildung Variance auf alle TPHs der Terme auf der jeweiligen
varianceTPHold = new HashSet<>(varianceTPH); * //anderen Seite übertragen varianceTPHold = new HashSet<>(varianceTPH);
varianceTPH = varianceInheritanceConstraintSet(unifyCons); * varianceTPH = varianceInheritanceConstraintSet(unifyCons); unifyCons.map( y
unifyCons.map( y -> { * -> { if ((y.getLhsType() instanceof PlaceholderType) && (y.getRhsType()
if ((y.getLhsType() instanceof PlaceholderType) && (y.getRhsType() instanceof PlaceholderType)) { * instanceof PlaceholderType)) { if
if (((PlaceholderType)y.getLhsType()).getVariance() != 0 && ((PlaceholderType)y.getRhsType()).getVariance() == 0) { * (((PlaceholderType)y.getLhsType()).getVariance() != 0 &&
((PlaceholderType)y.getRhsType()).setVariance(((PlaceholderType)y.getLhsType()).getVariance()); * ((PlaceholderType)y.getRhsType()).getVariance() == 0) {
} * ((PlaceholderType)y.getRhsType()).setVariance(((PlaceholderType)y.getLhsType(
if (((PlaceholderType)y.getLhsType()).getVariance() == 0 && ((PlaceholderType)y.getRhsType()).getVariance() != 0) { * )).getVariance()); } if (((PlaceholderType)y.getLhsType()).getVariance() == 0
((PlaceholderType)y.getLhsType()).setVariance(((PlaceholderType)y.getRhsType()).getVariance()); * && ((PlaceholderType)y.getRhsType()).getVariance() != 0) {
} * ((PlaceholderType)y.getLhsType()).setVariance(((PlaceholderType)y.getRhsType(
} * )).getVariance()); } } return y; } ); } while
return y; } ); } * (!varianceTPHold.equals(varianceTPH));
while (!varianceTPHold.equals(varianceTPH));
*/ */
//Set<Set<UnifyPair>> result = unify.unifySequential(xConsSet, finiteClosure, logFile, log); // Set<Set<UnifyPair>> result = unify.unifySequential(xConsSet, finiteClosure,
// 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<>();
@ -556,7 +603,8 @@ public class JavaTXCompiler {
UnifyResultModel urm = new UnifyResultModel(cons, finiteClosure); UnifyResultModel urm = new UnifyResultModel(cons, finiteClosure);
UnifyResultListenerImpl li = new UnifyResultListenerImpl(); UnifyResultListenerImpl li = new UnifyResultListenerImpl();
urm.addUnifyResultListener(li); urm.addUnifyResultListener(li);
unify.unifyParallel(unifyCons.getUndConstraints(), oderConstraints, finiteClosure, logFile, log, urm, usedTasks); unify.unifyParallel(unifyCons.getUndConstraints(), oderConstraints, finiteClosure, logFile, log, 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();
@ -564,53 +612,64 @@ public class JavaTXCompiler {
} }
/* UnifyResultModel End */ /* UnifyResultModel End */
else { else {
//Set<Set<UnifyPair>> result = unify.unify(unifyCons.getUndConstraints(), oderConstraints, finiteClosure, logFile, log, new UnifyResultModel(cons, finiteClosure)); // Set<Set<UnifyPair>> result = unify.unify(unifyCons.getUndConstraints(),
Set<Set<UnifyPair>> result = unify.unifyOderConstraints(unifyCons.getUndConstraints(), oderConstraints, finiteClosure, logFile, log, new UnifyResultModel(cons, finiteClosure), usedTasks); // oderConstraints, finiteClosure, logFile, log, new UnifyResultModel(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) y.setPairOp(PairOperator.EQUALSDOT); if (y.getPairOp() == PairOperator.SMALLERDOTWC)
y.setPairOp(PairOperator.EQUALSDOT);
return y; // alle Paare a <.? b erden durch a =. b ersetzt return y; // alle Paare a <.? b erden durch a =. b ersetzt
}).collect(Collectors.toCollection(HashSet::new))); }).collect(Collectors.toCollection(HashSet::new)));
if (res.isPresent()) {// wenn subst ein Erg liefert wurde was veraendert if (res.isPresent()) {// wenn subst ein Erg liefert wurde was veraendert
return new TypeUnifyTask().applyTypeUnificationRules(res.get(), finiteClosure); return new TypeUnifyTask().applyTypeUnificationRules(res.get(), finiteClosure);
} } else
else return x; //wenn nichts veraendert wurde wird x zurueckgegeben return x; // wenn nichts veraendert wurde wird x zurueckgegeben
}).collect(Collectors.toCollection(HashSet::new)); }).collect(Collectors.toCollection(HashSet::new));
System.out.println("RESULT Final: " + results); System.out.println("RESULT Final: " + results);
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().map((unifyPairs -> return results.stream()
new ResultSet(UnifyTypeFactory.convert(unifyPairs, Pair.generateTPHMap(cons))))).collect(Collectors.toList()); .map((unifyPairs -> new ResultSet(UnifyTypeFactory.convert(unifyPairs, Pair.generateTPHMap(cons)))))
.collect(Collectors.toList());
} }
/** /**
* Vererbt alle Variancen bei Paaren (a <. theta) oder (Theta <. a) * Vererbt alle Variancen bei Paaren (a <. theta) oder (Theta <. a) wenn a eine
* wenn a eine Variance !=0 hat auf alle Typvariablen in Theta. * 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) pair.add((PlaceholderType)x.getLhsType()); if (x.getLhsType() instanceof PlaceholderType)
if (x.getRhsType() instanceof PlaceholderType) pair.add((PlaceholderType)x.getRhsType()); pair.add((PlaceholderType) x.getLhsType());
if (x.getRhsType() instanceof PlaceholderType)
pair.add((PlaceholderType) x.getRhsType());
return pair; return pair;
}).reduce(new HashSet<>(), (a,b) -> { a.addAll(b); return a;} , (c,d) -> { c.addAll(d); 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));
@ -620,7 +679,8 @@ 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 && ((PlaceholderType)x.getLhsType()).equals(a))); // eq1.removeIf(x -> !(x.getLhsType() instanceof PlaceholderType &&
// ((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)) {
@ -628,47 +688,49 @@ public class JavaTXCompiler {
} }
}); });
// ` eq1 = new HashSet<>(eq); // ` eq1 = new HashSet<>(eq);
//eq1.removeIf(x -> !(x.getRhsType() instanceof PlaceholderType && ((PlaceholderType)x.getRhsType()).equals(a))); // eq1.removeIf(x -> !(x.getRhsType() instanceof PlaceholderType &&
// ((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 TPHs mit Variancen dazugekommen sein PL 2018-11-07 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
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), new GenericsRegistry(null)); SyntaxTreeGenerator generator = new SyntaxTreeGenerator(environment.getRegistry(sourceFile),
new GenericsRegistry(null));
SourceFile ret = generator.convert(tree, environment.packageCrawler); SourceFile ret = generator.convert(tree, environment.packageCrawler);
return ret; return ret;
} }
public List<SimplifyResultSourceFile> getSimplifyResultsForAllSourceFiles() throws ClassNotFoundException{ public List<GenericGenratorResultForSourceFile> getGeneratedGenericResultsForAllSourceFiles()
List<SimplifyResultSourceFile> result = new ArrayList<>(); throws ClassNotFoundException {
List<GenericGenratorResultForSourceFile> result = new ArrayList<>();
for (File f : sourceFiles.keySet()) { for (File f : sourceFiles.keySet()) {
SourceFile sf = sourceFiles.get(f); SourceFile sf = sourceFiles.get(f);
List<ResultSet> typeinferenceResult = this.typeInference(); List<ResultSet> typeinferenceResult = this.typeInference();
SimplifyResultFinder sResFinder = new SimplifyResultFinder(sf, typeinferenceResult); GeneratedGenericsFinder sResFinder = new GeneratedGenericsFinder(sf, typeinferenceResult);
SimplifyResultSourceFile simplifyResOfSF = sResFinder.findSimplifyRes(); GenericGenratorResultForSourceFile simplifyResOfSF = sResFinder.findGeneratedGenerics();
result.add(simplifyResOfSF); result.add(simplifyResOfSF);
} }
return result; return result;
} }
public List<SimplifyResultSourceFile> getSimplifyResultsForAllSourceFiles(List<ResultSet> typeinferenceResult) throws ClassNotFoundException{ public List<GenericGenratorResultForSourceFile> getGeneratedGenericResultsForAllSourceFiles(
List<SimplifyResultSourceFile> result = new ArrayList<>(); List<ResultSet> typeinferenceResult) throws ClassNotFoundException {
List<GenericGenratorResultForSourceFile> result = new ArrayList<>();
for (File f : sourceFiles.keySet()) { for (File f : sourceFiles.keySet()) {
SourceFile sf = sourceFiles.get(f); SourceFile sf = sourceFiles.get(f);
SimplifyResultFinder sResFinder = new SimplifyResultFinder(sf, typeinferenceResult); GeneratedGenericsFinder sResFinder = new GeneratedGenericsFinder(sf, typeinferenceResult);
SimplifyResultSourceFile simplifyResOfSF = sResFinder.findSimplifyRes(); GenericGenratorResultForSourceFile simplifyResOfSF = sResFinder.findGeneratedGenerics();
result.add(simplifyResOfSF); result.add(simplifyResOfSF);
} }
return result; return result;
@ -676,14 +738,27 @@ public class JavaTXCompiler {
// um pfad erweitern // um pfad erweitern
public void generateBytecode(String path) throws ClassNotFoundException, IOException, BytecodeGeneratorError { 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()) { for (File f : sourceFiles.keySet()) {
HashMap<String, byte[]> classFiles = new HashMap<>(); HashMap<String, byte[]> classFiles = new HashMap<>();
SourceFile sf = sourceFiles.get(f); SourceFile sf = sourceFiles.get(f);
List<ResultSet> typeinferenceResult = this.typeInference(); BytecodeGen bytecodeGen = new BytecodeGen(classFiles, typeinferenceResult, simplifyResultsForAllSourceFiles,
List<SimplifyResultSourceFile> simplifyResultsForAllSourceFiles = getSimplifyResultsForAllSourceFiles(typeinferenceResult); sf, path);
BytecodeGen bytecodeGen = new BytecodeGen(classFiles,typeinferenceResult,simplifyResultsForAllSourceFiles,sf,path);
bytecodeGen.visit(sf); bytecodeGen.visit(sf);
this.writeClassFile(bytecodeGen.getClassFiles(), path); writeClassFile(bytecodeGen.getClassFiles(), path);
} }
} }
@ -692,7 +767,8 @@ 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") + "/testBytecode/generatedBC/" +name+".class")); // output = new FileOutputStream(new File(System.getProperty("user.dir") +
// "/testBytecode/generatedBC/" +name+".class"));
output = new FileOutputStream(new File(path + name + ".class")); output = new FileOutputStream(new File(path + name + ".class"));
output.write(bytecode); output.write(bytecode);
output.close(); output.close();

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(6, res); assertEquals(new Integer(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(4, res); assertEquals(new Integer(4), res);
} }
} }

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, 6); assertEquals(result, new Integer(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(6, result); assertEquals(new Integer(6), result);
} }

View File

@ -28,7 +28,6 @@ public class FieldTphConsMethTest {
path = System.getProperty("user.dir")+"/src/test/resources/bytecode/javFiles/FieldTphConsMeth.jav"; path = System.getProperty("user.dir")+"/src/test/resources/bytecode/javFiles/FieldTphConsMeth.jav";
fileToTest = new File(path); fileToTest = new File(path);
compiler = new JavaTXCompiler(fileToTest); compiler = new JavaTXCompiler(fileToTest);
compiler.getSimplifyResultsForAllSourceFiles();
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)});

View File

@ -8,9 +8,10 @@ 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

@ -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(77, result); assertEquals(i, result);
} }

View File

@ -68,7 +68,6 @@ public class MatrixOpTest {
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);

View File

@ -85,7 +85,6 @@ 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,11 +7,14 @@ 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.simplifyRes.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;
@ -30,7 +33,9 @@ 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/";
compiler.generateBytecode(pathToClassFile); List<ResultSet> typeinferenceResult = compiler.typeInference();
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();
@ -47,14 +52,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(10, result); assertEquals(new Integer(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(10.0, result); assertEquals(new Double(10.0), result);
} }
@Test @Test
@ -73,14 +78,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(10, result); assertEquals(new Integer(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(10.0, result); assertEquals(new Double(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(10, result); assertEquals(new Integer(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(1, res); assertEquals(new Integer(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(0, res); assertEquals(new Integer(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(-1, res); assertEquals(new Integer(-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(0, res); assertEquals(new Integer(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(1, res); assertEquals(new Integer(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(1, res); assertEquals(new Integer(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(-1, res); assertEquals(new Integer(-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(-1, res); assertEquals(new Integer(-1), res);
} }
} }

View File

@ -39,7 +39,7 @@ public class TphTest {
Method m = classToTest.getDeclaredMethod("m", Object.class, Object.class); Method m = classToTest.getDeclaredMethod("m", Object.class, Object.class);
Object result = m.invoke(instanceOfClass, 1,2); Object result = m.invoke(instanceOfClass, 1,2);
assertEquals(2,result); assertEquals(1,result);
} }
@Test @Test
@ -47,7 +47,7 @@ public class TphTest {
Method m = classToTest.getDeclaredMethod("m", Object.class, Object.class); Method m = classToTest.getDeclaredMethod("m", Object.class, Object.class);
Object result = m.invoke(instanceOfClass, 1, "sss"); Object result = m.invoke(instanceOfClass, 1, "sss");
assertEquals("sss",result); assertEquals(1,result);
} }
@Test @Test

View File

@ -38,21 +38,21 @@ public class WhileTest {
public void test() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { public void test() 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, 0); Integer result = (Integer) m.invoke(instanceOfClass, 0);
assertEquals(2, result); assertEquals(new Integer(2), result);
} }
@Test @Test
public void testDouble() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { public void testDouble() 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, 0.0); Double result = (Double) m.invoke(instanceOfClass, 0.0);
assertEquals(2.0, result); assertEquals(new Double(2.0), result);
} }
@Test @Test
public void testLong() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { public void testLong() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Method m = classToTest.getDeclaredMethod("m", Long.class); Method m = classToTest.getDeclaredMethod("m", Long.class);
Long result = (Long) m.invoke(instanceOfClass, 0l); Long result = (Long) m.invoke(instanceOfClass, 0l);
assertEquals(2l, result); assertEquals(new Long(2l), result);
} }
} }

View File

@ -1,11 +1,20 @@
public class Id { public class Id {
// a;
// id(b){ // id(b){
// return b; // return b;
// } // }
id2 = x -> x; id2 = x -> x;
// id2 = () -> {
// var x = m(a);
// var y = x;
// var z = y;
// };
//
// m(a){
// return a;
// }
id3 (x) { id3 (x) {
return id2.apply(x) return id2.apply(x);
}
} }

View File

@ -1,7 +1,7 @@
public class SimpleCycle { public class SimpleCycle {
m(a,b,d){ m(a,b,d){
var g; /* var g;
var h; var h;
g = h; g = h;
h = g; h = g;
@ -18,7 +18,7 @@ public class SimpleCycle {
var f = d; var f = d;
b = x; b = x;
var l = c; var l = c;
a = l; a = l; */
} }

View File

@ -2,8 +2,8 @@ public class Tph {
m(a,b){ m(a,b){
var c = m2(b); var c = m2(b);
// return a; return a;
return m2(b); // return m2(b);
} }
m2(b){ m2(b){