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);
String id = MethodUtility.createID(resolver, method);
Iterator<FormalParameter> itr = method.getParameterList().iterator();
while (itr.hasNext()) {
FormalParameter fp = itr.next();
methParamTypes += resultSet.resolveType(fp.getType()).resolvedType.acceptTV(new TypeToDescriptor()) + ";";
}
if (methodNameAndParamsT.contains(methParamTypes)) {
if (methodNameAndParamsT.contains(id)) {
return;
}
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<>();
@ -64,15 +66,24 @@ public class TPHExtractor extends AbstractASTWalker {
public Resolver getResolver() {
return resolver;
}
// @Override
// public void visit(ClassOrInterface classOrInterface) {
// inMethod = false;
// classOrInterface.getfieldInitializations().ifPresent(c->c.block.accept(this));
// super.visit(classOrInterface);
// inMethod = true;
// }
@Override
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.getLocalTphs().add(name);
if (inLocalOrParam)
methodAndTph.getTphs().add(name);
if (inLocalOrParamOrReturn)
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

@ -27,5 +27,9 @@ public class ConstraintsWithSameLeftSide {
public void setConstraints(List<TPHConstraint> constraints) {
this.constraints = constraints;
}
@Override
public String toString() {
return "[" + constraints.toString() + "]";
}
}

View File

@ -50,6 +50,8 @@ public class CyclesFinder {
List<TPHConstraint> vistedConstraints = new ArrayList<>(allCons.size());
List<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) {
List<GenericsGeneratorResult> classConstraints = generateConstraintsForClass(tphExtractor,
simplifiedConstraints, tphsClass);
// GenericGeneratorResultsForAllMethods methodsAndConstraints = generateConstraintsForAllMethods(tphExtractor,
// simplifiedConstraints, tphsClass);
GenericGeneratorResultsForAllMethods methodsAndConstraints = new GenericGeneratorResultsForAllMethods(new ArrayList<>());
ConstraintsSimplierResult simplifiedConstraints = ConstraintsSimplifier.simplifyConstraints(tphExtractor, genericsGeneratorResults,tphsClass);
List<TPHConstraint> allCons = tphExtractor.allCons;
String methodID = MethodUtility.createID(tphExtractor.getResolver(), method);
List<String> methodTPHS = GenericsGeneratorUtility.getMethodTPHS(methodID ,tphExtractor.ListOfMethodsAndTph);
return null;
return new GenericsGeneratorResultForClass(className, classConstraints, methodsAndConstraints);
}
/**
* @param tphExtractor
* @param tphsClass
* @return
*/
public static ConstraintsSimplierResult simplifyConstraints(final TPHExtractor tphExtractor,
final List<String> tphsClass) {
final List<GenericsGeneratorResult> genericsGeneratorResults = new ArrayList<>();
ConstraintsSimplierResult simplifiedConstraints = ConstraintsSimplifier.simplifyConstraints(tphExtractor,
genericsGeneratorResults, tphsClass);
return simplifiedConstraints;
}
private static List<GenericsGeneratorResult> generateConstraintsForClass(final TPHExtractor tphExtractor,
final ConstraintsSimplierResult simplifiedConstraints, final List<String> tphsClass) {
final List<GenericsGeneratorResult> constraints = new ArrayList<>();
if(tphsClass.isEmpty())
return constraints;
final List<TPHConstraint> allCons = tphExtractor.allCons;
final Set<String> visitedTPHs = new HashSet<>();
final List<String> methodTPHs = tphExtractor.ListOfMethodsAndTph.stream().map(m -> m.getLocalTphs())
.flatMap(l -> l.stream()).collect(Collectors.toList());
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,20 +283,39 @@ 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);
});
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,86 +27,147 @@ 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 HashMap<String, RefTypeOrTPHOrWildcardOrGeneric> methodParamsAndTypes;
private ResultSet resultSet;
private Map<TPHConstraint, Set<String>> methodConstraints;
private List<TPHConstraint> consClass;
public Signature(ClassOrInterface classOrInterface, HashMap<String, String> genericsAndBounds,
List<TPHConstraint> consClass) {
this.classOrInterface = classOrInterface;
this.genericsAndBounds = genericsAndBounds;
this.consClass = consClass;
sw = new SignatureWriter();
createSignatureForClassOrInterface();
}
private List<GenericsGeneratorResult> consClass;
private List<GenericsGeneratorResult> constraints;
public Signature(Constructor constructor, HashMap<String, String> genericsAndBounds,
HashMap<String,RefTypeOrTPHOrWildcardOrGeneric> methodParamsAndTypes,ResultSet resultSet,
Map<TPHConstraint,Set<String>> methodConstraints) {
this.constructor = constructor;
// 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(HashMap<String, String> genericsAndBounds,
HashMap<String, RefTypeOrTPHOrWildcardOrGeneric> methodParamsAndTypes, ResultSet resultSet,
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);
this.constraints = constraints;
}
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;
public Signature(int numberOfParams) {
createSignatureForFunN(numberOfParams);
}
public Signature(int numberOfParams, String to, String[] paramTypes) {
createSignatureForFunN(numberOfParams, to, paramTypes);
}
public Signature(ClassOrInterface classOrInterface, HashMap<String, String> genericsAndBounds,
List<GenericsGeneratorResult> consClass) {
this.classOrInterface = classOrInterface;
this.genericsAndBounds = genericsAndBounds;
this.consClass = consClass;
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.methodConstraints = constraints;
sw = new SignatureWriter();
createSignatureForConsOrMethod(this.method,false);
this.constraints = constraints;
this.consClass = consClass;
//createSignatureForMethod(this.method);
}
public Signature(int numberOfParams) {
sw = new SignatureWriter();
createSignatureForFunN(numberOfParams);
public String createSignatureForConstructor(Constructor constructor) {
visitParams();
sw.visitReturnType().visitBaseType('V');
return sw.toString();
}
public Signature(int numberOfParams, String to, String[] paramTypes) {
sw = new SignatureWriter();
createSignatureForFunN(numberOfParams, to, paramTypes);
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;
sw.visitFormalTypeParameter("T"+ j);
for (int i = 0; i < numberOfParams; i++) {
int j = i + 1;
sw.visitFormalTypeParameter("T" + j);
// getBounds von Params
sw.visitClassBound().visitClassType(paramTypes[i]);
sw.visitClassBound().visitEnd();
}
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();
}
private void createSignatureForFunN(int numberOfParams) {
// sw.visitClassBound().visitEnd();
for(int i = 0;i<numberOfParams;i++) {
int j = i+1;
sw.visitFormalTypeParameter("T"+ j);
for (int i = 0; i < numberOfParams; i++) {
int j = i + 1;
sw.visitFormalTypeParameter("T" + j);
// getBounds von Params
sw.visitClassBound().visitClassType(Type.getInternalName(Object.class));
sw.visitClassBound().visitEnd();
@ -122,91 +178,89 @@ 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 method method or constructor
* @param isConstructor true if constructor
*/
private void createSignatureForConsOrMethod(Method method, boolean isConstructor) {
Iterator<? extends GenericTypeVar> itr = method.getGenerics().iterator();
// visits all formal type parameter and visits their bounds <T:...;B:...;...>
while(itr.hasNext()) {
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
if(!isConstructor) {
// 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<>();
Map<TPHConstraint,Set<String>> allConstraints = new HashMap<>();
if(ret.contains("<")) {
allConsBeforeSimplify = getAllConstraints((RefType) resultSet.resolveType(method.getReturnType()).resolvedType);
Map<TPHConstraint, Set<String>> allConstraints = new HashMap<>();
if (ret.contains("<")) {
allConsBeforeSimplify = getAllConstraints(
(RefType) resultSet.resolveType(method.getReturnType()).resolvedType);
}
for(String paramName : methodParamsAndTypes.keySet()) {
for (String paramName : methodParamsAndTypes.keySet()) {
RefTypeOrTPHOrWildcardOrGeneric t = methodParamsAndTypes.get(paramName);
String pT = t.acceptTV(new TypeToSignature());
if(pT.contains("<"))
String pT = t.acceptTV(new TypeToSignature());
if (pT.contains("<"))
allConsBeforeSimplify = getAllConstraints((RefType) t);
}
boolean doSimplify = false;
if(!allConsBeforeSimplify.isEmpty()) {
addConstraintsToMap(allConstraints,allConsBeforeSimplify);
if (!allConsBeforeSimplify.isEmpty()) {
addConstraintsToMap(allConstraints, allConsBeforeSimplify);
doSimplify = true;
}
createTypeVars(allConstraints, doSimplify);
if(!ret.equals("V")) {
if(ret.contains("$") && !ret.contains("$$") && !ret.contains("<")) {
if(genericsAndBounds.containsKey(ret)) {
if (!ret.equals("V")) {
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)));
}
}
}
}
// 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 {
} else {
RefTypeOrTPHOrWildcardOrGeneric returnType = method.getReturnType();
// return type deswegen ist false
doVisitParamsOrReturn(returnType, false);
// doVisitParamsOrReturn(returnType, false);
}
// sw.visitEnd();
}
private void addConstraintsToMap(Map<TPHConstraint, Set<String>> allConstraints,
ArrayList<TPHConstraint> allConsBeforeSimplify) {
for(TPHConstraint tphCons : allConsBeforeSimplify) {
for (TPHConstraint tphCons : allConsBeforeSimplify) {
allConstraints.put(tphCons, null);
}
}
private String getEqualTPH(Map<TPHConstraint, Set<String>> methodConstraints2, String tph) {
for(TPHConstraint cons : methodConstraints2.keySet()) {
if(methodConstraints2.get(cons) != null) {
if(methodConstraints2.get(cons).contains(tph)) {
for (TPHConstraint cons : methodConstraints2.keySet()) {
if (methodConstraints2.get(cons) != null) {
if (methodConstraints2.get(cons).contains(tph)) {
return cons.getLeft();
}
}
@ -216,76 +270,77 @@ public class Signature {
private void createTypeVars(Map<TPHConstraint, Set<String>> allConstraints, boolean doSimplify) {
allConstraints.putAll(methodConstraints);
Map<TPHConstraint, Set<String>> simplifiedConstraints;
if(doSimplify) {
if (doSimplify) {
simplifiedConstraints = Simplify.simplifyContraints(allConstraints);
}else {
} else {
simplifiedConstraints = allConstraints;
}
for(TPHConstraint cons : simplifiedConstraints.keySet()) {
for (TPHConstraint cons : simplifiedConstraints.keySet()) {
// need subst.
String sub = cons.getLeft()+"$";
if(!genericsAndBoundsMethod.containsKey(sub) && !genericsAndBounds.containsKey(sub)) {
String sub = cons.getLeft() + SPECIAL_CHAR;
if (!genericsAndBoundsMethod.containsKey(sub) && !genericsAndBounds.containsKey(sub)) {
sw.visitFormalTypeParameter(sub);
String bound = cons.getRight();
if(bound.equals(Type.getInternalName(Object.class))) {
if (bound.equals(Type.getInternalName(Object.class))) {
sw.visitClassBound().visitClassType(Type.getInternalName(Object.class));
sw.visitClassBound().visitEnd();
genericsAndBoundsMethod.put(sub, bound);
} else {
String boundName = bound+"$";
String boundName = bound + SPECIAL_CHAR;
sw.visitClassBound().visitTypeVariable(boundName);
genericsAndBoundsMethod.put(sub, boundName);
}
}
}
}
private ArrayList<TPHConstraint> getAllConstraints(RefType ref) {
final ArrayList<TPHConstraint> res = new ArrayList<>();
for(RefTypeOrTPHOrWildcardOrGeneric p : ref.getParaList()) {
for (RefTypeOrTPHOrWildcardOrGeneric p : ref.getParaList()) {
ResolvedType resType;
if(p instanceof WildcardType) {
if (p instanceof WildcardType) {
resType = resultSet.resolveType(((WildcardType) p).getInnerType());
}else {
} else {
resType = resultSet.resolveType(p);
}
RefTypeOrTPHOrWildcardOrGeneric resolved = resType.resolvedType;
if(resolved instanceof TypePlaceholder) {
//resType.getAdditionalGenerics().forEach(ag ->{
resultSet.genIns.forEach(ag ->{
if (resolved instanceof TypePlaceholder) {
// resType.getAdditionalGenerics().forEach(ag ->{
resultSet.genIns.forEach(ag -> {
TPHConstraint constr = new ExtendsConstraint(ag.getLeft().getName(), ag.getRight().getName());
if(!contains(res,constr)) {
if (!contains(res, constr)) {
res.add(constr);
}
});
}
if(resolved instanceof WildcardType) {
if (resolved instanceof WildcardType) {
WildcardType resWC = (WildcardType) resolved;
ResolvedType resType2 = resultSet.resolveType(resWC.getInnerType());
if(resType2.resolvedType instanceof TypePlaceholder) {
//resType2.getAdditionalGenerics().forEach(ag ->{
resultSet.genIns.forEach(ag ->{
if (resType2.resolvedType instanceof TypePlaceholder) {
// resType2.getAdditionalGenerics().forEach(ag ->{
resultSet.genIns.forEach(ag -> {
TPHConstraint constr = new ExtendsConstraint(ag.getLeft().getName(), ag.getRight().getName());
if(!contains(res,constr)) {
if (!contains(res, constr)) {
res.add(constr);
}
});
});
}
}
}
System.out.println("RES GIP === " + res.size());
return res;
}
private boolean contains(ArrayList<TPHConstraint> constraints, TPHConstraint constr) {
for(int i=0; i<constraints.size();++i) {
for (int i = 0; i < constraints.size(); ++i) {
TPHConstraint p = constraints.get(i);
if(constr.getLeft().equals(p.getLeft()) && constr.getRight().equals(p.getRight()))
if (constr.getLeft().equals(p.getLeft()) && constr.getRight().equals(p.getRight()))
return true;
}
return false;
@ -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 t type of parameter or return type
* @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());
@ -321,189 +371,202 @@ public class Signature {
// der Fall wenn der Typ eine Interface ist, muss betrachtet werden
// 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) {
if (r instanceof GenericRefType) {
sv.visitTypeVariable(sig2);
}else if(!(r instanceof TypePlaceholder)) {
if(sig2.contains("$$")) {
System.out.println(" Signature FUN$$: "+r);
} else if (!(r instanceof TypePlaceholder)) {
if (sig2.contains(SPECIAL_CHAR_FOR_FUN)) {
System.out.println(" Signature FUN$$: " + r);
sv.visitInterface().visitClassType(sig2.substring(1, sig2.length()));
} else {
// Kann zwischen GenericRefType und RefType nicht unterscheiden
// Deswegen wird immer geprüft, ob der Name in Generic Maps liegt
String n = sig2.substring(1, sig2.length()-1);
String n = sig2.substring(1, sig2.length() - 1);
// if(genericsAndBoundsMethod.containsKey(n) || genericsAndBounds.containsKey(n)) {
// sv.visitTypeVariable(n);
// } else {
sv.visitClassType(n);
sv.visitEnd();
sv.visitClassType(n);
sv.visitEnd();
// }
// sv.visitClassType(n);
}
} else {
String eqTPH = getEqualTPH(methodConstraints, sig2.substring(1, sig2.length()-1))+"$";
System.out.println(r.getClass()+" Signature TPH: "+r.acceptTV(new TypeToSignature()));
sv.visitTypeVariable(eqTPH);
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(toVisit);
}
break;
case "SWC":
System.out.println("SWC---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()));
} else if(swc.getInnerType() instanceof RefType) {
if(sigInner.contains("$$")) {
sv.visitTypeArgument('-').visitInterface().visitClassType(sigInner.substring(1,sigInner.length()));
}else {
sv.visitTypeArgument('-').visitClassType(sigInner.substring(1,sigInner.length()));
if (swc.getInnerType() instanceof TypePlaceholder) {
sv.visitTypeArgument(SUPER_CHAR).visitTypeVariable(sigInner.substring(1, sigInner.length()));
} else if (swc.getInnerType() instanceof RefType) {
if (sigInner.contains(SPECIAL_CHAR_FOR_FUN)) {
sv.visitTypeArgument(SUPER_CHAR).visitInterface().visitClassType(sigInner.substring(1, sigInner.length()));
} else {
sv.visitTypeArgument(SUPER_CHAR).visitClassType(sigInner.substring(1, sigInner.length()));
}
}else {
sv.visitTypeArgument('-').visitTypeVariable(sigInner.substring(1));
} else {
sv.visitTypeArgument(SUPER_CHAR).visitTypeVariable(sigInner.substring(1));
}
break;
case "EWC":
System.out.println("EWC---Signature");
ExtendsWildcardType ewc = (ExtendsWildcardType) t;
String esigInner = ewc.getInnerType().acceptTV(new TypeToSignature());
System.out.println(esigInner);
if(ewc.getInnerType() instanceof TypePlaceholder) {
sv.visitTypeArgument('+').visitTypeVariable(esigInner.substring(1, esigInner.length()));
} else if(ewc.getInnerType() instanceof RefType) {
if(esigInner.contains("$$")) {
sv.visitTypeArgument('+').visitInterface().visitClassType(esigInner.substring(1,esigInner.length()));
}else {
if (ewc.getInnerType() instanceof TypePlaceholder) {
sv.visitTypeArgument(EXTENDS_CHAR).visitTypeVariable(esigInner.substring(1, esigInner.length()));
} else if (ewc.getInnerType() instanceof RefType) {
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));
} else {
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()) {
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<>();
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();
}*/
defineGenericsFromConstraints(consClass,genericsAndBounds);
String sClass = classOrInterface.getSuperClass().acceptTV(new TypeToSignature());
sw.visitSuperclass().visitClassType(sClass.substring(1, sClass.length()-1));
sw.visitSuperclass().visitClassType(sClass.substring(1, sClass.length() - 1));
sw.visitEnd();
}
/**
* @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
*
* @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();
while(bItr.hasNext()) {
RefTypeOrTPHOrWildcardOrGeneric b =bItr.next();
Iterator<? extends RefTypeOrTPHOrWildcardOrGeneric> bItr = g.getBounds().iterator();
while (bItr.hasNext()) {
RefTypeOrTPHOrWildcardOrGeneric b = bItr.next();
String boundDesc = b.acceptTV(new TypeToDescriptor());
// System.out.println("GetBounds: " + boundDesc);
// Ensure that <...> extends java.lang.Object OR ...
if(b instanceof GenericRefType) {
if (b instanceof GenericRefType) {
sw.visitClassBound().visitTypeVariable(boundDesc);
} else {
sw.visitClassBound().visitClassType(boundDesc);
sw.visitClassBound().visitEnd();
visitClassBound(boundDesc);
}
genAndBounds.put(g.getName(), boundDesc);
}
// sw.visitClassBound().visitEnd();
}
public String toString() {
return sw.toString();
}
}

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;
if(!isVisited) {
simplifiedConstraints = GenericsGenerator.simplifyConstraints(tphExtractor, tphsClass);
ggResult = GenericsGenerator.generateConstraints(className, tphExtractor, tphsClass,simplifiedConstraints);
isVisited = true;
}
// for(Constructor m : classOrInterface.getConstructors()) {
// addMethodConstraints(simplifiedConstraints, ggResult, m);
// }
tphsClass = new ArrayList<>();
for (String t : tphExtractor.allTPHS.keySet()) {
if (!tphExtractor.allTPHS.get(t))
tphsClass.add(t);
for(Method m : classOrInterface.getMethods()) {
addMethodConstraints(simplifiedConstraints, ggResult, m);
}
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();
}
if(ggResult != null)
generatedGenericsForSF.addGenericGeneratorResultClass(ggResult);
sResClass.setSimplifyResults(sRes);
simplifyResOfSourceFile.addSimplifyResultClass(sResClass);
for (Constructor c : classOrInterface.getConstructors()) {
c.accept(this);
}
for (Method m : classOrInterface.getMethods()) {
m.accept(this);
}
}
}
private void removeFromMethod(String name) {
for (MethodAndTPH m : tphExtractor.ListOfMethodsAndTph) {
ArrayList<String> toRemove = new ArrayList<>();
for (String tph : m.getTphs()) {
if (tph.equals(name)) {
toRemove.add(tph);
}
}
if (!toRemove.isEmpty()) {
m.getTphs().removeAll(toRemove);
return;
}
}
}
private String getTPH(String name) {
for (String tph : tphExtractor.allTPHS.keySet()) {
if (tph.equals(name))
return tph;
}
throw new NoSuchElementException("TPH " + name + " does not exist");
/**
* @param simplifiedConstraints
* @param ggResult
* @param m
*/
public void addMethodConstraints(ConstraintsSimplierResult simplifiedConstraints,
GenericsGeneratorResultForClass ggResult, Method m) {
String id = MethodUtility.createID(resolver, m);
boolean isInGGResult = (ggResult != null) && ggResult.contains(id);
if(methodNameAndParamsT.contains(id) || isInGGResult)
return;
methodNameAndParamsT.add(id);
Optional<MethodAndTPH> methodAndTPH = GenericsGeneratorUtility.getMethodAndTphs(tphExtractor.ListOfMethodsAndTph,id);
methodAndTPH.ifPresent(mt->{
MethodAndConstraints methodConstraints = GenericsGenerator.generateConstraintsForMethod(tphExtractor.allCons, mt , simplifiedConstraints, tphsClass);
ggResult.getMethodsAndTheirConstraints().getMethodsAndConstraints().add(methodConstraints);
});
}
/*
@ -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,18 +208,7 @@ 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,39 +220,7 @@ 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);
@ -65,6 +66,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();

File diff suppressed because it is too large Load Diff

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

@ -28,76 +28,75 @@ public class MatrixOpTest {
private static Object instanceOfClass_m3;
@Test
public void test() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, ClassNotFoundException, IOException, InstantiationException, NoSuchFieldException {
path = System.getProperty("user.dir")+"/src/test/resources/bytecode/javFiles/MatrixOP.jav";
public void test() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, ClassNotFoundException, IOException, InstantiationException, NoSuchFieldException {
path = System.getProperty("user.dir") + "/src/test/resources/bytecode/javFiles/MatrixOP.jav";
fileToTest = new File(path);
compiler = new JavaTXCompiler(fileToTest);
pathToClassFile = System.getProperty("user.dir")+"/src/test/resources/testBytecode/generatedBC/";
pathToClassFile = System.getProperty("user.dir") + "/src/test/resources/testBytecode/generatedBC/";
compiler.generateBytecode(pathToClassFile);
loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)});
classToTest = loader.loadClass("MatrixOP");
loader = new URLClassLoader(new URL[]{new URL("file://" + pathToClassFile)});
classToTest = loader.loadClass("MatrixOP");
Vector<Vector<Integer>> vv = new Vector<Vector<Integer>>();
Vector<Integer> v1 = new Vector<Integer> ();
v1.addElement(2);
v1.addElement(2);
Vector<Integer> v2 = new Vector<Integer> ();
v2.addElement(3);
v2.addElement(3);
//Matrix m1 = new Matrix();
//m1.addElement(v1);
//m1.addElement(v2);
vv.addElement(v1);
vv.addElement(v2);
instanceOfClass_m1 = classToTest.getDeclaredConstructor(Vector.class).newInstance(vv); //Matrix m1 = new Matrix(vv);
Vector<Integer> v1 = new Vector<Integer>();
v1.addElement(2);
v1.addElement(2);
Vector<Integer> v2 = new Vector<Integer>();
v2.addElement(3);
v2.addElement(3);
//Matrix m1 = new Matrix();
//m1.addElement(v1);
//m1.addElement(v2);
vv.addElement(v1);
vv.addElement(v2);
Vector<Vector<Integer>> vv1 = new Vector<Vector<Integer>>();
Vector<Integer> v3 = new Vector<Integer> ();
v3.addElement(2);
v3.addElement(2);
Vector<Integer> v4 = new Vector<Integer> ();
v4.addElement(3);
v4.addElement(3);
//Matrix m2 = new Matrix();
//m2.addElement(v3);
//m2.addElement(v4);
vv1.addElement(v3);
vv1.addElement(v4);
instanceOfClass_m2 = classToTest.getDeclaredConstructor(Vector.class).newInstance(vv1);//Matrix m2 = new Matrix(vv1);
instanceOfClass_m1 = classToTest.getDeclaredConstructor(Vector.class).newInstance(vv); //Matrix m1 = new Matrix(vv);
//Matrix m3 = m1.mul(vv1);
Vector<Vector<Integer>> vv1 = new Vector<Vector<Integer>>();
Vector<Integer> v3 = new Vector<Integer>();
v3.addElement(2);
v3.addElement(2);
Vector<Integer> v4 = new Vector<Integer>();
v4.addElement(3);
v4.addElement(3);
//Matrix m2 = new Matrix();
//m2.addElement(v3);
//m2.addElement(v4);
vv1.addElement(v3);
vv1.addElement(v4);
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);
Field mul = classToTest.getField("mul");
mul.setAccessible(true);
Class<?> lambda = mul.get(instanceOfClass_m1).getClass();
Method apply = lambda.getMethod("apply", Object.class,Object.class);
Field mul = classToTest.getField("mul");
mul.setAccessible(true);
Class<?> lambda = mul.get(instanceOfClass_m1).getClass();
Method apply = lambda.getMethod("apply", Object.class, Object.class);
// Damit man auf die Methode zugreifen kann
apply.setAccessible(true);
Object result = apply.invoke(mul.get(instanceOfClass_m1),instanceOfClass_m1, instanceOfClass_m2);
System.out.println(instanceOfClass_m1.toString() + " * " + instanceOfClass_m2.toString() + " = " + result.toString());
Vector<Vector<Integer>> res = new Vector<Vector<Integer>>();
Vector<Integer> v5 = new Vector<Integer> ();
v5.addElement(10);
v5.addElement(10);
Vector<Integer> v6 = new Vector<Integer> ();
v6.addElement(15);
v6.addElement(15);
//Matrix m2 = new Matrix();
//m2.addElement(v3);
//m2.addElement(v4);
res.addElement(v5);
res.addElement(v6);
instanceOfClass_m3 = classToTest.getDeclaredConstructor(Vector.class).newInstance(res);
assertEquals(result, instanceOfClass_m3);
apply.setAccessible(true);
Object result = apply.invoke(mul.get(instanceOfClass_m1), instanceOfClass_m1, instanceOfClass_m2);
System.out.println(instanceOfClass_m1.toString() + " * " + instanceOfClass_m2.toString() + " = " + result.toString());
Vector<Vector<Integer>> res = new Vector<Vector<Integer>>();
Vector<Integer> v5 = new Vector<Integer>();
v5.addElement(10);
v5.addElement(10);
Vector<Integer> v6 = new Vector<Integer>();
v6.addElement(15);
v6.addElement(15);
//Matrix m2 = new Matrix();
//m2.addElement(v3);
//m2.addElement(v4);
res.addElement(v5);
res.addElement(v6);
instanceOfClass_m3 = classToTest.getDeclaredConstructor(Vector.class).newInstance(res);
assertEquals(result, instanceOfClass_m3);
}
}

View File

@ -27,7 +27,7 @@ public class MatrixTest {
private static Object instanceOfClass_m3;
@Test
public void test() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, ClassNotFoundException, IOException, InstantiationException {
public void test() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, ClassNotFoundException, IOException, InstantiationException {
path = System.getProperty("user.dir")+"/src/test/resources/bytecode/javFiles/Matrix.jav";
fileToTest = new File(path);
compiler = new JavaTXCompiler(fileToTest);
@ -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){