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>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.0</version>
<version>4.11</version>
<scope>test</scope>
</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.TypeToString;
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.MethodUtility;
import de.dhbwstuttgart.bytecode.utilities.NormalConstructor;
import de.dhbwstuttgart.bytecode.utilities.NormalMethod;
import de.dhbwstuttgart.bytecode.utilities.Resolver;
import de.dhbwstuttgart.bytecode.utilities.Simplify;
import de.dhbwstuttgart.exceptions.NotImplementedException;
import de.dhbwstuttgart.parser.SyntaxTreeGenerator.AssignToLocal;
@ -119,10 +123,12 @@ public class BytecodeGen implements ASTVisitor {
private final ArrayList<String> fieldNameSignature = new ArrayList<>();
private List<SimplifyResultSourceFile> simplifyResultsForAllSourceFiles;
private SimplifyResult simplifyResult;
private List<GenericGenratorResultForSourceFile> simplifyResultsForAllSourceFiles;
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) {
this.classFiles = classFiles;
this.listOfResultSets = listOfResultSets;
@ -173,20 +179,19 @@ public class BytecodeGen implements ASTVisitor {
fieldInitializations = classOrInterface.getfieldInitializations();
// resultSet = listOfResultSets.get(0);
boolean isConsWithNoParamsVisited = false;
boolean isVisited = false;
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 (ResultSet rs : listOfResultSets) {
superClass = classOrInterface.getSuperClass().acceptTV(new TypeToDescriptor());
resultSet = listOfResultSetsList.get(i);
resolver = new Resolver(resultSet);
// tphExtractor.setResultSet(resultSet);
// Nur einmal ausführen!!
if (!isVisited) {
tphsClass = simplifyResult.getTphsClass();
String sig = null;
/*
@ -194,10 +199,10 @@ public class BytecodeGen implements ASTVisitor {
* <E:Ljava/...>Superclass
*/
if (classOrInterface.getGenerics().iterator().hasNext() || classOrInterface.getSuperClass().acceptTV(new TypeToSignature()).contains("<")
|| !tphsClass.isEmpty()) {
List<TPHConstraint> consClass = simplifyResult.getClassConstraints();
|| !generatedGenerics.getClassConstraints().isEmpty()) {
List<GenericsGeneratorResult> consClass = generatedGenerics.getClassConstraints();
//
Signature signature = new Signature(classOrInterface, genericsAndBounds, consClass);
sig = signature.toString();
System.out.println("Signature: => " + sig);
@ -243,20 +248,13 @@ public class BytecodeGen implements ASTVisitor {
field.getParameterList().accept(this);
String methParamTypes = field.name + "%%";
String id = MethodUtility.createID(resolver, field);
Iterator<FormalParameter> itr = field.getParameterList().iterator();
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);
if (methodNameAndParamsT.contains(id)) {
return;
}
methodNameAndParamsT.add(methParamTypes);
System.out.println("Method: " + field.name + " , paramsType: " + methParamTypes);
methodNameAndParamsT.add(id);
System.out.println("Constructor: " + field.name + " , paramsType: " + id);
String desc = null;
boolean hasGen = false;
@ -271,9 +269,16 @@ public class BytecodeGen implements ASTVisitor {
}
String sig = null;
if (hasGen) {
Map<TPHConstraint, Set<String>> constraints = simplifyResult.getMethodConstraintsByID(methParamTypes);
Signature signature = new Signature(field, genericsAndBounds, methodParamsAndTypes, resultSet, constraints);
sig = signature.toString();
List<GenericsGeneratorResult> constraints = generatedGenerics.getClassConstraints();
// Map<TPHConstraint, Set<String>> constraints = generatedGenerics.getMethodConstraintsByID(methParamTypes);
//// 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())
System.out.println(field.getParameterList().iterator().next().getType().acceptTV(new TypeToDescriptor()));
@ -304,23 +309,19 @@ public class BytecodeGen implements ASTVisitor {
// 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 TypeToSignature());
String methParamTypes = retType + method.name + "%%";
method.getParameterList().accept(this);
Iterator<FormalParameter> itr = method.getParameterList().iterator();
while (itr.hasNext()) {
FormalParameter fp = itr.next();
methParamTypes += resultSet.resolveType(fp.getType()).resolvedType.acceptTV(new TypeToDescriptor()) + ";";
}
String id = MethodUtility.createID(resolver, method);
if (methodNameAndParamsT.contains(methParamTypes)) {
if (methodNameAndParamsT.contains(id)) {
return;
}
methodNameAndParamsT.add(methParamTypes);
System.out.println("Method: " + method.name + " , paramsType: " + methParamTypes);
methodNameAndParamsT.add(id);
System.out.println("Method: " + method.name + " , paramsType: " + id);
// stores generics and their bounds of method
HashMap<String, String> genericsAndBoundsMethod = new HashMap<>();
method.getParameterList().accept(this);
String methDesc = null;
// Method getModifiers() ?
@ -360,11 +361,13 @@ public class BytecodeGen implements ASTVisitor {
if (hasGen || resultSet.resolveType(method.getReturnType()).resolvedType.acceptTV(new TypeToString())
.equals("TPH")) {
Map<TPHConstraint, Set<String>> constraints = simplifyResult.getMethodConstraintsByID(methParamTypes);
// ArrayList<GenericInsertPair> pairs = simplifyPairs(method.name,tphExtractor.allPairs,tphExtractor.allCons);
Signature signature = new Signature(method, genericsAndBoundsMethod, genericsAndBounds,
methodParamsAndTypes, resultSet, constraints);
sig = signature.toString();
List<GenericsGeneratorResult> constraints = generatedGenerics.getMethodConstraintsByID(id);
List<GenericsGeneratorResult> classConstraints = generatedGenerics.getClassConstraints();
// Map<TPHConstraint, Set<String>> constraints = generatedGenerics.getMethodConstraintsByID(methParamTypes);
//// ArrayList<GenericInsertPair> pairs = simplifyPairs(method.name,tphExtractor.allPairs,tphExtractor.allCons);
Signature signature = new Signature(genericsAndBoundsMethod, genericsAndBounds,
methodParamsAndTypes, resultSet, constraints,classConstraints);
sig = signature.createSignatureForMethod(method);
}
System.out.println(method.getName() + " ==> " + sig);
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.Resolver;
import de.dhbwstuttgart.syntaxtree.AbstractASTWalker;
import de.dhbwstuttgart.syntaxtree.ClassOrInterface;
import de.dhbwstuttgart.syntaxtree.Constructor;
import de.dhbwstuttgart.syntaxtree.Field;
import de.dhbwstuttgart.syntaxtree.FormalParameter;
@ -41,10 +42,11 @@ public class TPHExtractor extends AbstractASTWalker {
// Alle TPHs der Felder werden iKopf der Klasse definiert
// alle TPHs der Klasse: (TPH, is in Method?)
public final HashMap<String, Boolean> allTPHS = new HashMap<>();
public final List<String> tphsClass = new ArrayList<>();
MethodAndTPH methodAndTph;
Boolean inMethod = false;
boolean inLocalOrParam = false;
boolean inLocalOrParamOrReturn = false;
public final ArrayList<MethodAndTPH> ListOfMethodsAndTph = new ArrayList<>();
final ArrayList<ResultPair<TypePlaceholder, TypePlaceholder>> allPairs = new ArrayList<>();
@ -65,14 +67,23 @@ public class TPHExtractor extends AbstractASTWalker {
return resolver;
}
// @Override
// public void visit(ClassOrInterface classOrInterface) {
// inMethod = false;
// classOrInterface.getfieldInitializations().ifPresent(c->c.block.accept(this));
// super.visit(classOrInterface);
// inMethod = true;
// }
@Override
public void visit(TypePlaceholder tph) {
if (resultSet.resolveType(tph).resolvedType instanceof TypePlaceholder) {
TypePlaceholder resolvedTPH = (TypePlaceholder) resultSet.resolveType(tph).resolvedType;
if (inMethod) {
methodAndTph.getTphs().add(resolvedTPH.getName());
if (inLocalOrParam)
if (inLocalOrParamOrReturn)
methodAndTph.getLocalTphs().add(resolvedTPH.getName());
}else {
tphsClass.add(resolvedTPH.getName());
}
allTPHS.put(resolvedTPH.getName(), inMethod);
@ -142,9 +153,11 @@ public class TPHExtractor extends AbstractASTWalker {
public void visit(GenericRefType genericRefType) {
String name = genericRefType.getParsedName();
if (inMethod) {
methodAndTph.getTphs().add(name);
if (inLocalOrParamOrReturn)
methodAndTph.getLocalTphs().add(name);
if (inLocalOrParam)
methodAndTph.getLocalTphs().add(name);
}else {
tphsClass.add(name);
}
allTPHS.put(name, inMethod);
}
@ -163,7 +176,15 @@ public class TPHExtractor extends AbstractASTWalker {
inMethod = true;
String id = MethodUtility.createID(resolver,method);
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;
ListOfMethodsAndTph.add(methodAndTph);
}
@ -177,23 +198,23 @@ public class TPHExtractor extends AbstractASTWalker {
@Override
public void visit(LocalVarDecl localVarDecl) {
inLocalOrParam = true;
// inLocalOrParamOrReturn = inMethod;
super.visit(localVarDecl);
inLocalOrParam = false;
// inLocalOrParamOrReturn = false;
}
@Override
public void visit(LocalVar localVar) {
inLocalOrParam = true;
// inLocalOrParamOrReturn = inMethod;
super.visit(localVar);
inLocalOrParam = false;
// inLocalOrParamOrReturn = false;
}
@Override
public void visit(ParameterList formalParameters) {
inLocalOrParam = true;
inLocalOrParamOrReturn = inMethod;
super.visit(formalParameters);
inLocalOrParam = false;
inLocalOrParamOrReturn = false;
}
}

View File

@ -3,8 +3,7 @@
*/
package de.dhbwstuttgart.bytecode.genericsGenerator;
import java.util.ArrayList;
import java.util.List;
import java.util.*;
import de.dhbwstuttgart.bytecode.TPHExtractor;
import de.dhbwstuttgart.bytecode.constraint.TPHConstraint;
@ -16,44 +15,112 @@ import de.dhbwstuttgart.bytecode.simplifyRes.GenericsGeneratorResult;
*
*/
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> equalCons = new ArrayList<>();
List<SimpleCycle> simpleCycles = findSimpleCycles(allCons);
if(!simpleCycles.isEmpty()) {
handleSimpleCycles(allCons, simpleCycles);
equalCons.addAll(GenericsGeneratorUtility.getEqualConstraints(allCons));
}
/* Step 2 */
/* Step 1 */
List<ConstraintsWithSameLeftSide> foundCons = GenericsGeneratorUtility.findConstraintsWithLeftSameLeftSide(allCons);
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);
}
// if(!simpleCycles.isEmpty()) {
// handleSimpleCycles(allCons, simpleCycles,tphExtractor);
// equalCons.addAll(GenericsGeneratorUtility.getEqualConstraints(allCons));
// }
//
List<LongCycle> longCycles = findLongCycles(allCons);
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 */
List<NameReplacementResult> nameReplacementResults = GenericsGeneratorUtility.createNameReplacementResultsFromEqualConstraints(equalCons);
getEqualsFromNameReplacementResults(genericsGeneratorResults,nameReplacementResults);
ConstraintsSimplierResult result = new ConstraintsSimplierResult(genericsGeneratorResults, nameReplacementResults);
return result;
}
private static void getEqualsFromNameReplacementResults(List<GenericsGeneratorResult> genericsGeneratorResults,
List<NameReplacementResult> nameReplacementResults) {
genericsGeneratorResults.forEach(g->{
String tph = g.getConstraint().getLeft();
if (!nameReplacementResults.isEmpty()) {
collectAllEquals(nameReplacementResults, g, tph);
}
if (!nameReplacementResults.isEmpty()) {
collectAllEquals(nameReplacementResults, g);
}
});
}
private static void collectAllEquals(List<NameReplacementResult> nameReplacementResults, GenericsGeneratorResult g) {
Set<String> equalsTPHs = g.getEqualsTPHs();
Set<String> tphsToAdd = getAllEqualTphs(equalsTPHs, nameReplacementResults);
while (!tphsToAdd.isEmpty()){
equalsTPHs.addAll(tphsToAdd);
tphsToAdd = getAllEqualTphs(equalsTPHs, nameReplacementResults);
}
}
private static Set<String> getAllEqualTphs(Set<String> equalsTPHs, List<NameReplacementResult> nameReplacementResults) {
Set<String> tphsToAdd = new HashSet<>();
equalsTPHs.forEach(e->{
collectAllEquals(nameReplacementResults, tphsToAdd,e);
});
return tphsToAdd;
}
public static void collectAllEquals(List<NameReplacementResult> nameReplacementResults, Set<String> tphsToAdd,
String tph) {
List<NameReplacementResult> toRemoveList = new ArrayList<>();
Optional<NameReplacementResult> nameReplacementResult = nameReplacementResults.stream().filter(n->n.getName().equals(tph)).findFirst();
nameReplacementResult.ifPresent(toRemove->{
tphsToAdd.addAll(toRemove.getOldNames());
toRemoveList.add(toRemove);
});
if(!toRemoveList.isEmpty()){
nameReplacementResults.remove(toRemoveList.get(0));
toRemoveList.clear();
}
}
/**
* @param nameReplacementResults
* @param g
* @param tph
*/
public static void collectAllEquals(List<NameReplacementResult> nameReplacementResults, GenericsGeneratorResult g,
String tph) {
List<NameReplacementResult> toRemoveList = new ArrayList<>();
Optional<NameReplacementResult> nameReplacementResult = nameReplacementResults.stream().filter(n->n.getName().equals(tph)).findFirst();
nameReplacementResult.ifPresent(toRemove->{
g.getEqualsTPHs().addAll(toRemove.getOldNames());
toRemoveList.add(toRemove);
});
if(!toRemoveList.isEmpty()){
nameReplacementResults.remove(toRemoveList.get(0));
toRemoveList.clear();
}
}
/**
* @param genericsGeneratorResults
* @param allCons
* @param longCycles
* @param tphExtractor
*/
public static void handleLongCycle(List<GenericsGeneratorResult> genericsGeneratorResults,
List<TPHConstraint> allCons, List<LongCycle> longCycles) {
List<TPHConstraint> allCons, List<LongCycle> longCycles, TPHExtractor tphExtractor) {
GenericsGeneratorUtility.modifyRelationForConstraintsinLongCycle(longCycles);
List<NameReplacementResult> nameReplacementResults = GenericsGeneratorUtility.substituteTPHSFormLongCycle(allCons, longCycles);
List<NameReplacementResult> nameReplacementResults = GenericsGeneratorUtility.substituteTPHSFormLongCycle(allCons, longCycles,tphExtractor);
GenericsGeneratorUtility.createResults(genericsGeneratorResults,nameReplacementResults);
GenericsGeneratorUtility.removeEqualConstraints(allCons);
}
@ -72,11 +139,13 @@ public class ConstraintsSimplifier {
/**
* @param allCons
* @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.removeAllReverseConstraints(allCons,simpleCycles);
GenericsGeneratorUtility.substituteTPH(allCons, simpleCycles);
GenericsGeneratorUtility.replaceOldNames(simpleCycles,tphExtractor);
}
/**

View File

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

View File

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

View File

@ -11,6 +11,7 @@ import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.Set;
import de.dhbwstuttgart.bytecode.BytecodeGen;
@ -18,10 +19,12 @@ import de.dhbwstuttgart.bytecode.TPHExtractor;
import de.dhbwstuttgart.bytecode.constraint.TPHConstraint;
import de.dhbwstuttgart.bytecode.descriptor.TypeToDescriptor;
import de.dhbwstuttgart.bytecode.genericsGenerator.GenericsGenerator;
import de.dhbwstuttgart.bytecode.genericsGenerator.GenericsGeneratorUtility;
import de.dhbwstuttgart.bytecode.signature.Signature;
import de.dhbwstuttgart.bytecode.signature.TypeToSignature;
import de.dhbwstuttgart.bytecode.signature.TypeToString;
import de.dhbwstuttgart.bytecode.utilities.MethodAndTPH;
import de.dhbwstuttgart.bytecode.utilities.MethodUtility;
import de.dhbwstuttgart.bytecode.utilities.Resolver;
import de.dhbwstuttgart.bytecode.utilities.Simplify;
import de.dhbwstuttgart.parser.SyntaxTreeGenerator.AssignToLocal;
@ -75,34 +78,31 @@ import de.dhbwstuttgart.typeinference.result.ResultSet;
* @author fayez
*
*/
public class SimplifyResultFinder implements ASTVisitor {
public class GeneratedGenericsFinder implements ASTVisitor {
private final TPHExtractor tphExtractor = new TPHExtractor();
private Collection<ResultSet> listOfResultSets;
private SourceFile sf;
private List<String> tphsClass;
private SimplifyResultSourceFile simplifyResOfSourceFile;
private GenericGenratorResultForSourceFile generatedGenericsForSF;
private ResultSet resultSet;
private List<String> methodNameAndParamsT = new ArrayList<>();
private Resolver resolver;
private final List<String> methodNameAndParamsT = new ArrayList<>();
private String pkgName;
private String className;
// stores generics and their bounds of class
private Map<String, String> genericsAndBounds = new HashMap<>();
private Map<String, RefTypeOrTPHOrWildcardOrGeneric> methodParamsAndTypes = new HashMap<>();
private Resolver resolver;
/**
* @param sf
* @param listOfResultSets
*/
public SimplifyResultFinder(SourceFile sf, Collection<ResultSet> listOfResultSets) {
public GeneratedGenericsFinder(SourceFile sf, Collection<ResultSet> listOfResultSets) {
this.sf = sf;
this.listOfResultSets = listOfResultSets;
}
public SimplifyResultSourceFile findSimplifyRes() {
public GenericGenratorResultForSourceFile findGeneratedGenerics() {
sf.accept(this);
return simplifyResOfSourceFile;
return generatedGenericsForSF;
}
/*
@ -115,7 +115,7 @@ public class SimplifyResultFinder implements ASTVisitor {
@Override
public void visit(SourceFile sourceFile) {
pkgName = sf.getPkgName();
simplifyResOfSourceFile = new SimplifyResultSourceFile(pkgName);
generatedGenericsForSF = new GenericGenratorResultForSourceFile(pkgName);
for (ClassOrInterface cl : sourceFile.getClasses()) {
cl.accept(this);
}
@ -131,99 +131,60 @@ public class SimplifyResultFinder implements ASTVisitor {
@Override
public void visit(ClassOrInterface classOrInterface) {
className = classOrInterface.getClassName().toString();
SimplifyResult sRes = new SimplifyResult();
SimplifyResultClass sResClass = new SimplifyResultClass(className);
List<ResultSet> listOfResultSetsList = new ArrayList<>(listOfResultSets);
boolean isVisited = false;
ConstraintsSimplierResult simplifiedConstraints = null;
GenericsGeneratorResultForClass ggResult = null;
for (int i = 0; i < listOfResultSetsList.size(); i++) {
resultSet = listOfResultSetsList.get(i);
resolver = new Resolver(resultSet);
tphExtractor.setResultSet(resultSet);
resolver = new Resolver(resultSet);
classOrInterface.accept(tphExtractor);
tphsClass = tphExtractor.tphsClass;
tphsClass = new ArrayList<>();
for (String t : tphExtractor.allTPHS.keySet()) {
if (!tphExtractor.allTPHS.get(t))
tphsClass.add(t);
if(!isVisited) {
simplifiedConstraints = GenericsGenerator.simplifyConstraints(tphExtractor, tphsClass);
ggResult = GenericsGenerator.generateConstraints(className, tphExtractor, tphsClass,simplifiedConstraints);
isVisited = true;
}
if (classOrInterface.getGenerics().iterator().hasNext()
|| classOrInterface.getSuperClass().acceptTV(new TypeToSignature()).contains("<")
|| !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(Constructor m : classOrInterface.getConstructors()) {
// addMethodConstraints(simplifiedConstraints, ggResult, m);
// }
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) {
ArrayList<String> toRemove = new ArrayList<>();
for (String tph : m.getTphs()) {
if (tph.equals(name)) {
toRemove.add(tph);
}
}
if (!toRemove.isEmpty()) {
m.getTphs().removeAll(toRemove);
/**
* @param simplifiedConstraints
* @param ggResult
* @param m
*/
public void addMethodConstraints(ConstraintsSimplierResult simplifiedConstraints,
GenericsGeneratorResultForClass ggResult, Method m) {
String id = MethodUtility.createID(resolver, m);
boolean isInGGResult = (ggResult != null) && ggResult.contains(id);
if(methodNameAndParamsT.contains(id) || isInGGResult)
return;
}
}
}
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");
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);
});
}
/*
@ -235,54 +196,7 @@ public class SimplifyResultFinder implements ASTVisitor {
*/
@Override
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
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
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 {
private ClassOrInterface classOrInterface;
private Map<String, String> genericsAndBounds;
private List<String> tphsClass;
private List<TPHConstraint> consClass;
public TypeVariableFinder(ClassOrInterface classOrInterface, Map<String, String> genericsAndBounds,
List<String> tphsClass, List<TPHConstraint> consClass) {
List<TPHConstraint> consClass) {
this.classOrInterface = classOrInterface;
this.genericsAndBounds = genericsAndBounds;
this.tphsClass = tphsClass;
this.consClass = consClass;
}
@ -55,17 +53,12 @@ public class TypeVariableFinder {
for(TPHConstraint cons : consClass) {
String t = cons.getLeft()+"$";
String bound = cons.getRight()+"$";
String bound = cons.getRight();
if(!bound.equals(Type.getInternalName(Object.class)))
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.List;
import java.util.Map;
import java.util.stream.Stream;
import de.dhbwstuttgart.bytecode.constraint.TPHConstraint;
import de.dhbwstuttgart.bytecode.genericsGenerator.NameReplacementResult;
@ -52,11 +53,11 @@ public class NameReplacer {
substituteRightSidesWithNewName(newName, names);
substituteNamesInAllConstraints(newName, names);
methodAndTPHs.stream().map(m->m.getTphs()).forEach(tphsMethod->{
if(tphsMethod.removeAll(names))
tphsMethod.add(newName);
});
Stream<ArrayList<String>> tphsOfMethods = methodAndTPHs.stream().map(m->m.getTphs());
Stream<ArrayList<String>> localTphsOfMethods = methodAndTPHs.stream().map(m->m.getLocalTphs());
replaceOldNames(newName, names, tphsOfMethods);
replaceOldNames(newName, names, localTphsOfMethods);
if(tphs.removeAll(names))
tphs.add(newName);
@ -66,6 +67,18 @@ public class NameReplacer {
return res;
}
/**
* @param newName
* @param names
* @param tphsOfMethods
*/
public void replaceOldNames(final String newName, final List<String> names, Stream<ArrayList<String>> tphsOfMethods) {
tphsOfMethods.forEach(tphsMethod->{
if(tphsMethod.removeAll(names))
tphsMethod.add(newName);
});
}
public NameReplacementResult replaceNamesLocal() {
String newName = NameGenerator.makeNewName();
List<String> names = new ArrayList<>();

View File

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

View File

@ -37,14 +37,14 @@ public class BinaryTest {
public void test() throws Exception {
Method m2 = classToTest.getDeclaredMethod("m2", Integer.class,Integer.class);
Integer res = (Integer) m2.invoke(instanceOfClass, 2,3);
assertEquals(6, res);
assertEquals(new Integer(6), res);
}
@Test
public void testM3() throws Exception {
Method m3 = classToTest.getDeclaredMethod("m3", Integer.class);
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 {
Method getFac = classToTest.getDeclaredMethod("getFac", Integer.class);
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) 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";
fileToTest = new File(path);
compiler = new JavaTXCompiler(fileToTest);
compiler.getSimplifyResultsForAllSourceFiles();
compiler.generateBytecode(System.getProperty("user.dir")+"/src/test/resources/testBytecode/generatedBC/");
pathToClassFile = System.getProperty("user.dir")+"/src/test/resources/testBytecode/generatedBC/";
loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)});

View File

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

View File

@ -43,7 +43,7 @@ public class LambdaTest {
System.out.println(m.invoke(instanceOfClass).toString());
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);
//Matrix m3 = m1.mul(vv1);
// Method mul = classToTest.getDeclaredMethod("mul", Vector.class);
// Object result = mul.invoke(instanceOfClass_m1, instanceOfClass_m2);

View File

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

View File

@ -7,11 +7,14 @@ import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.List;
import org.junit.BeforeClass;
import org.junit.Test;
import de.dhbwstuttgart.bytecode.simplifyRes.GenericGenratorResultForSourceFile;
import de.dhbwstuttgart.core.JavaTXCompiler;
import de.dhbwstuttgart.typeinference.result.ResultSet;
public class OLTest {
private static String path;
@ -30,7 +33,9 @@ public class OLTest {
fileToTest = new File(path);
compiler = new JavaTXCompiler(fileToTest);
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)});
classToTest = loader.loadClass("OL");
instanceOfClass = classToTest.getDeclaredConstructor().newInstance();
@ -47,14 +52,14 @@ public class OLTest {
public void testmInt() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Method m = classToTest.getDeclaredMethod("m", Integer.class);
Integer result = (Integer) m.invoke(instanceOfClass, 5);
assertEquals(10, result);
assertEquals(new Integer(10), result);
}
@Test
public void testmDouble() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Method m = classToTest.getDeclaredMethod("m", Double.class);
Double result = (Double) m.invoke(instanceOfClass, 5.0);
assertEquals(10.0, result);
assertEquals(new Double(10.0), result);
}
@Test
@ -73,14 +78,14 @@ public class OLTest {
public void testmainInt() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Method main = classToTest1.getDeclaredMethod("main", Integer.class);
Integer result = (Integer) main.invoke(instanceOfClass1, 5);
assertEquals(10, result);
assertEquals(new Integer(10), result);
}
@Test
public void testmainDouble() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Method main = classToTest1.getDeclaredMethod("main", Double.class);
Double result = (Double) main.invoke(instanceOfClass1, 5.0);
assertEquals(10.0, result);
assertEquals(new Double(10.0), result);
}
@Test

View File

@ -54,7 +54,7 @@ public class OpTest {
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 {
Method m = classToTest.getDeclaredMethod("m");
Integer res = (Integer) m.invoke(instanceOfClass);
assertEquals(1, res);
assertEquals(new Integer(1), res);
}
@Test
public void testM2() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Method m = classToTest.getDeclaredMethod("m2");
Integer res = (Integer) m.invoke(instanceOfClass);
assertEquals(0, res);
assertEquals(new Integer(0), res);
}
@Test
public void testD1() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Method m = classToTest.getDeclaredMethod("d");
Integer res = (Integer) m.invoke(instanceOfClass);
assertEquals(-1, res);
assertEquals(new Integer(-1), res);
}
@Test
public void testD2() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Method m = classToTest.getDeclaredMethod("d2");
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 {
Method m = classToTest.getDeclaredMethod("m");
Integer res = (Integer) m.invoke(instanceOfClass);
assertEquals(1, res);
assertEquals(new Integer(1), res);
}
@Test
public void testM2() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Method m = classToTest.getDeclaredMethod("m2");
Integer res = (Integer) m.invoke(instanceOfClass);
assertEquals(1, res);
assertEquals(new Integer(1), res);
}
@Test
public void testD() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Method m = classToTest.getDeclaredMethod("d");
Integer res = (Integer) m.invoke(instanceOfClass);
assertEquals(-1, res);
assertEquals(new Integer(-1), res);
}
@Test
public void testD2() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Method m = classToTest.getDeclaredMethod("d2");
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);
Object result = m.invoke(instanceOfClass, 1,2);
assertEquals(2,result);
assertEquals(1,result);
}
@Test
@ -47,7 +47,7 @@ public class TphTest {
Method m = classToTest.getDeclaredMethod("m", Object.class, Object.class);
Object result = m.invoke(instanceOfClass, 1, "sss");
assertEquals("sss",result);
assertEquals(1,result);
}
@Test

View File

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

View File

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

View File

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

View File

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