diff --git a/pom.xml b/pom.xml index f6a1fc87..98ea3933 100644 --- a/pom.xml +++ b/pom.xml @@ -14,7 +14,7 @@ http://maven.apache.org/maven-v4_0_0.xsd"> junit junit - 4.0 + 4.11 test diff --git a/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGen.java b/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGen.java index 1c289835..cce7262c 100644 --- a/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGen.java +++ b/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGen.java @@ -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 fieldNameSignature = new ArrayList<>(); - private List simplifyResultsForAllSourceFiles; - private SimplifyResult simplifyResult; + private List simplifyResultsForAllSourceFiles; + private GenericsGeneratorResultForClass generatedGenerics; - public BytecodeGen(HashMap classFiles, Collection listOfResultSets, List simplifyResultsForAllSourceFiles, SourceFile sf, + private Resolver resolver; + + public BytecodeGen(HashMap classFiles, Collection listOfResultSets, List 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 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 { * Superclass */ if (classOrInterface.getGenerics().iterator().hasNext() || classOrInterface.getSuperClass().acceptTV(new TypeToSignature()).contains("<") - || !tphsClass.isEmpty()) { - - List consClass = simplifyResult.getClassConstraints(); + || !generatedGenerics.getClassConstraints().isEmpty()) { + List 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 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> constraints = simplifyResult.getMethodConstraintsByID(methParamTypes); - Signature signature = new Signature(field, genericsAndBounds, methodParamsAndTypes, resultSet, constraints); - sig = signature.toString(); + List constraints = generatedGenerics.getClassConstraints(); +// Map> constraints = generatedGenerics.getMethodConstraintsByID(methParamTypes); +//// ArrayList pairs = simplifyPairs(method.name,tphExtractor.allPairs,tphExtractor.allCons); + Signature signature = new Signature(genericsAndBounds, + methodParamsAndTypes, resultSet, constraints); + + sig = signature.createSignatureForConstructor(field); +// Map> 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 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 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> constraints = simplifyResult.getMethodConstraintsByID(methParamTypes); -// ArrayList pairs = simplifyPairs(method.name,tphExtractor.allPairs,tphExtractor.allCons); - Signature signature = new Signature(method, genericsAndBoundsMethod, genericsAndBounds, - methodParamsAndTypes, resultSet, constraints); - sig = signature.toString(); + List constraints = generatedGenerics.getMethodConstraintsByID(id); + List classConstraints = generatedGenerics.getClassConstraints(); +// Map> constraints = generatedGenerics.getMethodConstraintsByID(methParamTypes); +//// ArrayList 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); diff --git a/src/main/java/de/dhbwstuttgart/bytecode/TPHExtractor.java b/src/main/java/de/dhbwstuttgart/bytecode/TPHExtractor.java index 9850d902..aded8fd0 100644 --- a/src/main/java/de/dhbwstuttgart/bytecode/TPHExtractor.java +++ b/src/main/java/de/dhbwstuttgart/bytecode/TPHExtractor.java @@ -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 allTPHS = new HashMap<>(); + public final List tphsClass = new ArrayList<>(); MethodAndTPH methodAndTph; Boolean inMethod = false; - boolean inLocalOrParam = false; + boolean inLocalOrParamOrReturn = false; public final ArrayList ListOfMethodsAndTph = new ArrayList<>(); final ArrayList> 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; } } \ No newline at end of file diff --git a/src/main/java/de/dhbwstuttgart/bytecode/genericsGenerator/ConstraintsSimplifier.java b/src/main/java/de/dhbwstuttgart/bytecode/genericsGenerator/ConstraintsSimplifier.java index 9f85a483..525bab3c 100644 --- a/src/main/java/de/dhbwstuttgart/bytecode/genericsGenerator/ConstraintsSimplifier.java +++ b/src/main/java/de/dhbwstuttgart/bytecode/genericsGenerator/ConstraintsSimplifier.java @@ -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 genericsGeneratorResults, List tphsClass) { + public static ConstraintsSimplierResult simplifyConstraints(final TPHExtractor tphExtractor, final List genericsGeneratorResults, final List tphsClass) { List allCons = tphExtractor.allCons; List equalCons = new ArrayList<>(); List simpleCycles = findSimpleCycles(allCons); - if(!simpleCycles.isEmpty()) { - handleSimpleCycles(allCons, simpleCycles); - equalCons.addAll(GenericsGeneratorUtility.getEqualConstraints(allCons)); - } - - /* Step 2 */ + /* Step 1 */ List foundCons = GenericsGeneratorUtility.findConstraintsWithLeftSameLeftSide(allCons); if(!foundCons.isEmpty()) { - List equalCons2 = GenericsGeneratorUtility.simplifyConstraintsWithSameLeftSide(foundCons,tphExtractor,tphsClass); + List 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 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 nameReplacementResults = GenericsGeneratorUtility.createNameReplacementResultsFromEqualConstraints(equalCons); + getEqualsFromNameReplacementResults(genericsGeneratorResults,nameReplacementResults); ConstraintsSimplierResult result = new ConstraintsSimplierResult(genericsGeneratorResults, nameReplacementResults); return result; } + private static void getEqualsFromNameReplacementResults(List genericsGeneratorResults, + List 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 nameReplacementResults, GenericsGeneratorResult g) { + Set equalsTPHs = g.getEqualsTPHs(); + Set tphsToAdd = getAllEqualTphs(equalsTPHs, nameReplacementResults); + while (!tphsToAdd.isEmpty()){ + equalsTPHs.addAll(tphsToAdd); + tphsToAdd = getAllEqualTphs(equalsTPHs, nameReplacementResults); + } + } + + private static Set getAllEqualTphs(Set equalsTPHs, List nameReplacementResults) { + Set tphsToAdd = new HashSet<>(); + equalsTPHs.forEach(e->{ + collectAllEquals(nameReplacementResults, tphsToAdd,e); + }); + return tphsToAdd; + } + + public static void collectAllEquals(List nameReplacementResults, Set tphsToAdd, + String tph) { + List toRemoveList = new ArrayList<>(); + Optional 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 nameReplacementResults, GenericsGeneratorResult g, + String tph) { + List toRemoveList = new ArrayList<>(); + Optional 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 genericsGeneratorResults, - List allCons, List longCycles) { + List allCons, List longCycles, TPHExtractor tphExtractor) { GenericsGeneratorUtility.modifyRelationForConstraintsinLongCycle(longCycles); - List nameReplacementResults = GenericsGeneratorUtility.substituteTPHSFormLongCycle(allCons, longCycles); + List 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 allCons, List simpleCycles) { + public static void handleSimpleCycles(List allCons, List simpleCycles, TPHExtractor tphExtractor) { GenericsGeneratorUtility.modifyRelation(simpleCycles); GenericsGeneratorUtility.removeAllReverseConstraints(allCons,simpleCycles); GenericsGeneratorUtility.substituteTPH(allCons, simpleCycles); + GenericsGeneratorUtility.replaceOldNames(simpleCycles,tphExtractor); } /** diff --git a/src/main/java/de/dhbwstuttgart/bytecode/genericsGenerator/ConstraintsWithSameLeftSide.java b/src/main/java/de/dhbwstuttgart/bytecode/genericsGenerator/ConstraintsWithSameLeftSide.java index 6d3cbac3..93636cb7 100644 --- a/src/main/java/de/dhbwstuttgart/bytecode/genericsGenerator/ConstraintsWithSameLeftSide.java +++ b/src/main/java/de/dhbwstuttgart/bytecode/genericsGenerator/ConstraintsWithSameLeftSide.java @@ -27,5 +27,9 @@ public class ConstraintsWithSameLeftSide { public void setConstraints(List constraints) { this.constraints = constraints; } - + + @Override + public String toString() { + return "[" + constraints.toString() + "]"; + } } diff --git a/src/main/java/de/dhbwstuttgart/bytecode/genericsGenerator/CyclesFinder.java b/src/main/java/de/dhbwstuttgart/bytecode/genericsGenerator/CyclesFinder.java index f2212843..cf8c0885 100644 --- a/src/main/java/de/dhbwstuttgart/bytecode/genericsGenerator/CyclesFinder.java +++ b/src/main/java/de/dhbwstuttgart/bytecode/genericsGenerator/CyclesFinder.java @@ -50,6 +50,8 @@ public class CyclesFinder { List vistedConstraints = new ArrayList<>(allCons.size()); List 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 longCycles) { @@ -99,7 +101,7 @@ public class CyclesFinder { private Optional getConstraintInRelation(List tphsInRelation, List maybeCycle) { - TPHConstraint constraint = getConstraintByLeftSide(tphsInRelation.get(tphsInRelation.size()-1)); + TPHConstraint constraint = getConstraintByLeftSide(tphsInRelation.get(tphsInRelation.size()-1),maybeCycle); Optional 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 maybeCycle) { for(TPHConstraint constraint : allCons) { + if(constraint.getRel()==Relation.EQUAL) + continue; + if(maybeCycle.contains(constraint)) + continue; if(constraint.getLeft().equals(left)) return constraint; } diff --git a/src/main/java/de/dhbwstuttgart/bytecode/genericsGenerator/GenericsGenerator.java b/src/main/java/de/dhbwstuttgart/bytecode/genericsGenerator/GenericsGenerator.java index 25a27a02..1e8f9f6e 100644 --- a/src/main/java/de/dhbwstuttgart/bytecode/genericsGenerator/GenericsGenerator.java +++ b/src/main/java/de/dhbwstuttgart/bytecode/genericsGenerator/GenericsGenerator.java @@ -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 generateConstraintsForMethod(Method method, TPHExtractor tphExtractor, - List tphsClass) { - List genericsGeneratorResults = new ArrayList<>(); + public static GenericsGeneratorResultForClass generateConstraints(final String className, final TPHExtractor tphExtractor, + final List tphsClass, final ConstraintsSimplierResult simplifiedConstraints) { + + List 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 allCons = tphExtractor.allCons; - String methodID = MethodUtility.createID(tphExtractor.getResolver(), method); - List 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 tphsClass) { + final List genericsGeneratorResults = new ArrayList<>(); + + ConstraintsSimplierResult simplifiedConstraints = ConstraintsSimplifier.simplifyConstraints(tphExtractor, + genericsGeneratorResults, tphsClass); + return simplifiedConstraints; } + + private static List generateConstraintsForClass(final TPHExtractor tphExtractor, + final ConstraintsSimplierResult simplifiedConstraints, final List tphsClass) { + final List constraints = new ArrayList<>(); + + if(tphsClass.isEmpty()) + return constraints; + + final List allCons = tphExtractor.allCons; + + final Set visitedTPHs = new HashSet<>(); + + final List 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 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 tphsInRel, + ConstraintsSimplierResult simplifiedConstraints, List tphsClass) { + String subType = tphsInRel.getFirst(); + + String superType = GenericsGeneratorUtility.getNextClassTph(tphsClass, tphsInRel); + + TPHConstraint constraint = new ExtendsConstraint(subType, superType); + + Set equalSet = GenericsGeneratorUtility + .createEqualSet(simplifiedConstraints.getNameReplacementResults(), subType); + + return new GenericsGeneratorResult(constraint, equalSet); + } + + private static GenericGeneratorResultsForAllMethods generateConstraintsForAllMethods( + final TPHExtractor tphExtractor, ConstraintsSimplierResult simplifiedConstraints, List tphsClass) { + + final List 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 allCons, + final MethodAndTPH m, final ConstraintsSimplierResult simplifiedConstraints, List tphsClass) { + final List localTphs = m.getLocalTphs(); + + List 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 visitedTPHs = new HashSet<>(); + + for (String tph : localTphs) { + + if (visitedTPHs.contains(tph)) + continue; + + final LinkedList 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 localTphs, + final List 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 nameReplacementResults) { + String superType = Type.getInternalName(Object.class); + TPHConstraint constraint = new ExtendsConstraint(tph, superType); + Set equalSet = GenericsGeneratorUtility.createEqualSet(nameReplacementResults, tph); + + return new GenericsGeneratorResult(constraint, equalSet); + } + + private static GenericsGeneratorResult generateGGResult(final LinkedList tphsInRel, + final ConstraintsSimplierResult simplifiedConstraints) { + + String subType = tphsInRel.getFirst(); + + if (tphsInRel.size() == 1) { + Optional 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 equalSet = GenericsGeneratorUtility + .createEqualSet(simplifiedConstraints.getNameReplacementResults(), subType); + + return new GenericsGeneratorResult(constraint, equalSet); + } + } diff --git a/src/main/java/de/dhbwstuttgart/bytecode/genericsGenerator/GenericsGeneratorUtility.java b/src/main/java/de/dhbwstuttgart/bytecode/genericsGenerator/GenericsGeneratorUtility.java index e5ad4ccc..9db65374 100644 --- a/src/main/java/de/dhbwstuttgart/bytecode/genericsGenerator/GenericsGeneratorUtility.java +++ b/src/main/java/de/dhbwstuttgart/bytecode/genericsGenerator/GenericsGeneratorUtility.java @@ -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 simplifyConstraintsWithSameLeftSide(List consWithSameLeftSide, - TPHExtractor tphExtractor, List tphsClass) { - List eqCons = new ArrayList<>(); + public static void simplifyConstraintsWithSameLeftSide(List consWithSameLeftSide, + TPHExtractor tphExtractor, List tphsClass, List equalCons) { List 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 allCons) { + List visited = new ArrayList<>(); + List toRemove = new ArrayList<>(); + checkForDuplicate(allCons, visited, toRemove); + removeConstraintsByIndex(allCons, toRemove); + } + + private static void removeConstraintsByIndex(List allCons, List toRemove) { + for(int index : toRemove) + allCons.remove(index); + } + + private static void checkForDuplicate(List allCons, List visited, List toRemove) { + for(int i = 0;i allCons, List visited, List 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 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 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 consWithSameLeftSide, List allCons) { + allCons.forEach(c->{ + Optional constraintsWithSameLeftSide = getConstraintsWithSameLeftSide(consWithSameLeftSide, c.getLeft()); + constraintsWithSameLeftSide.ifPresent(cls->{ + if(!cls.getConstraints().contains(c)) + cls.getConstraints().add(c); + }); + }); + } + + private static Optional getConstraintsWithSameLeftSide(List 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 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 allCons) { + List 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 equalNames, List 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 substituteTPHSFormLongCycle(List allCons, List longCycles) { + public static List substituteTPHSFormLongCycle(List allCons, List longCycles, TPHExtractor tphExtractor) { List results = new ArrayList<>(); longCycles.forEach(lc->{ Set names = getNamesFromCycle(lc); String newName = names.stream().findFirst().get(); List equalNames = new ArrayList<>(names); + + Stream> tphsOfMethods = tphExtractor.ListOfMethodsAndTph.stream().map(m->m.getTphs()); + Stream> 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 names, Stream> tphsOfMethods) { + tphsOfMethods.forEach(tphsMethod->{ + if(tphsMethod.removeAll(names)) + tphsMethod.add(newName); + }); + } + public static void substituteAll(List allCons, Set 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 getConstraintByLeftSide(List allCons, String tph) { + return allCons.stream().filter(c->c.getLeft().equals(tph)).findFirst(); + } + + public static Optional getConstraintByRightSide(List allCons, String tph) { + return allCons.stream().filter(c->c.getRight().equals(tph)).findFirst(); + } + + public static void replaceOldNames(List simpleCycles, TPHExtractor tphExtractor) { + simpleCycles.forEach(sc -> { + Stream> tphsOfMethods = tphExtractor.ListOfMethodsAndTph.stream().map(m->m.getTphs()); + Stream> localTphsOfMethods = tphExtractor.ListOfMethodsAndTph.stream().map(m->m.getLocalTphs()); + + String newName = sc.getConstraint().getRight(); + String oldName = sc.getConstraint().getLeft(); + + List names = new ArrayList<>(); + names.add(oldName); + names.add(newName); + + replaceOldNames(newName, names, tphsOfMethods); + replaceOldNames(newName, names, localTphsOfMethods); + }); + } + + public static boolean isTPHInGenericGeneratorResult(final List 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 createLinkedListForTPHsInRelation(final List allCons, + List tphsMethod, List tphsClass, final Set visitedTPHs, String tph) { + + final LinkedList tphsInRel = new LinkedList<>(); + List 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 allCons, List tphsList, Set visitedTPHs, String tph, + LinkedList tphsInRel) { + Optional 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 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 allCons, List tphsList, final Set visitedTPHs, String tph, + final LinkedList tphsInRel) { + Optional 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 visitedTPHs, String left) { + visitedTPHs.add(left); + } + + /** + * @param visitedTPHs + * @param right + * @param left + */ + public static void markAsVisited(final Set visitedTPHs, String left, String right) { + visitedTPHs.add(left); + visitedTPHs.add(right); + } + + /** + * @param tphsInRel + * @param right + * @param left + */ + public static void addTPHsToList(final LinkedList tphsInRel, String left, String right) { + if (tphsInRel.isEmpty()) + tphsInRel.add(left); + tphsInRel.add(right); + } + + public static void removeNotLocalTphs(final LinkedList tphsInRel, final List localTphs, + List 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 createEqualSet(final List nameReplacementResults, String subType) { + Optional equals = nameReplacementResults.stream() + .filter(n -> n.getName().equals(subType)).findFirst(); + + Set equalSet = equals.isPresent() ? new HashSet<>(equals.get().getOldNames()) : new HashSet<>(); + return equalSet; + } + + public static String getNextClassTph(List tphsClass, LinkedList tphsInRel) { + + for(int i = 1;i constraints, final List tphsClass) { + + List lefts = constraints.stream().map(r->r.getConstraint()).map(c->c.getLeft()).collect(Collectors.toList()); + List rights = constraints.stream().map(r->r.getConstraint()).map(c->c.getRight()).collect(Collectors.toList()); + List leftsAndRights = new ArrayList<>(lefts); + leftsAndRights.addAll(rights); + List shouldBeClassTphs = leftsAndRights.stream().distinct().collect(Collectors.toList()); + + for(String tph : shouldBeClassTphs) { + if(!tphsClass.contains(tph)) + tphsClass.add(tph); + } + } + + public static void removeClassTPHsFromMethodTPHs(List 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 createLinkedListForTPHsInRelationClass(List allCons, + List tphsClass, List methodTPHs, Set visitedTPHs, String tph) { + final LinkedList 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 constraints) { + return constraints.stream().map(r->r.getConstraint()).filter(c->c.getLeft().equals(first)).findFirst().isPresent(); + } + + public static Optional getGenericGeneratorResult(List list, + String tph) { + return list.stream().filter(g->g.getConstraint().getLeft().equals(tph)).findFirst(); + } + + public static void removeGenericGeneratorResult(List genericsGenResults, + GenericsGeneratorResult ggResult) { + genericsGenResults.remove(ggResult); + } + + public static Optional getMethodAndTphs(ArrayList listOfMethodsAndTph, String id) { + return listOfMethodsAndTph.stream().filter(m->m.getId().equals(id)).findFirst(); + } } diff --git a/src/main/java/de/dhbwstuttgart/bytecode/signature/Signature.java b/src/main/java/de/dhbwstuttgart/bytecode/signature/Signature.java index cb18e6b5..bad62616 100644 --- a/src/main/java/de/dhbwstuttgart/bytecode/signature/Signature.java +++ b/src/main/java/de/dhbwstuttgart/bytecode/signature/Signature.java @@ -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 genericsAndBounds; private HashMap genericsAndBoundsMethod; - private SignatureWriter sw; + private final SignatureWriter sw = new SignatureWriter();; private Constructor constructor; private Method method; - private HashMap methodParamsAndTypes; + private HashMap methodParamsAndTypes; private ResultSet resultSet; private Map> methodConstraints; - private List consClass; - - public Signature(ClassOrInterface classOrInterface, HashMap genericsAndBounds, - List consClass) { - this.classOrInterface = classOrInterface; - this.genericsAndBounds = genericsAndBounds; - this.consClass = consClass; - sw = new SignatureWriter(); - createSignatureForClassOrInterface(); - } + private List consClass; + private List constraints; - public Signature(Constructor constructor, HashMap genericsAndBounds, - HashMap methodParamsAndTypes,ResultSet resultSet, - Map> methodConstraints) { - this.constructor = constructor; +// public Signature(ClassOrInterface classOrInterface, HashMap genericsAndBounds, +// List consClass) { +// this.classOrInterface = classOrInterface; +// this.genericsAndBounds = genericsAndBounds; +// this.consClass = consClass; +// sw = new SignatureWriter(); +// createSignatureForClassOrInterface(); +// } + + public Signature(HashMap genericsAndBounds, + HashMap methodParamsAndTypes, ResultSet resultSet, + List 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 genericsAndBoundsMethod,HashMap genericsAndBounds, - HashMap methodParamsAndTypes, ResultSet resultSet, - Map> 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 genericsAndBounds, + List consClass) { + this.classOrInterface = classOrInterface; + this.genericsAndBounds = genericsAndBounds; + this.consClass = consClass; + createSignatureForClassOrInterface(); + } + + public Signature(HashMap genericsAndBoundsMethod, + HashMap genericsAndBounds, + HashMap methodParamsAndTypes, ResultSet resultSet, + List constraints,List 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(params L.. OR T.. Or basistape)ReturnType + * Creates signature for a method or constructor with @see + * {@link SignatureWriter} Signature looks like: (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 itr = method.getGenerics().iterator(); // visits all formal type parameter and visits their bounds - 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 allConsBeforeSimplify = new ArrayList<>(); - - Map> allConstraints = new HashMap<>(); - - if(ret.contains("<")) { - allConsBeforeSimplify = getAllConstraints((RefType) resultSet.resolveType(method.getReturnType()).resolvedType); + + Map> 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> allConstraints, ArrayList allConsBeforeSimplify) { - for(TPHConstraint tphCons : allConsBeforeSimplify) { + for (TPHConstraint tphCons : allConsBeforeSimplify) { allConstraints.put(tphCons, null); } } private String getEqualTPH(Map> 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> allConstraints, boolean doSimplify) { allConstraints.putAll(methodConstraints); - + Map> 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 getAllConstraints(RefType ref) { final ArrayList 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 constraints, TPHConstraint constr) { - for(int i=0; i 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 getEqualTPHFromClassConstraints(List consClass, String tph) { + return consClass.stream() + .filter(c -> c.getConstraint().getLeft().equals(tph) || c.getEqualsTPHs().contains(tph)) + .findFirst(); + } + + private String getEqualTPH(List 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: - * superclass + * Signature looks like: superclass */ private void createSignatureForClassOrInterface() { Iterator itr = classOrInterface.getGenerics().iterator(); - while(itr.hasNext()) { + while (itr.hasNext()) { GenericTypeVar g = itr.next(); - getBoundsOfTypeVar(g,genericsAndBounds); + visitTypeVarsAndTheirBounds(g, genericsAndBounds); } - - if(!consClass.isEmpty()) { - ArrayList types = new ArrayList<>(); - ArrayList 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 types = new ArrayList<>(); - ArrayList 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 constraints, HashMap 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 genAndBounds) { + private void visitTypeVarsAndTheirBounds(GenericTypeVar g, HashMap genAndBounds) { sw.visitFormalTypeParameter(g.getName()); - - Iterator bItr = g.getBounds().iterator(); - while(bItr.hasNext()) { - RefTypeOrTPHOrWildcardOrGeneric b =bItr.next(); + + Iterator 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(); } - + } diff --git a/src/main/java/de/dhbwstuttgart/bytecode/simplifyRes/SimplifyResultFinder.java b/src/main/java/de/dhbwstuttgart/bytecode/simplifyRes/GeneratedGenericsFinder.java similarity index 69% rename from src/main/java/de/dhbwstuttgart/bytecode/simplifyRes/SimplifyResultFinder.java rename to src/main/java/de/dhbwstuttgart/bytecode/simplifyRes/GeneratedGenericsFinder.java index 751947b7..372633e9 100644 --- a/src/main/java/de/dhbwstuttgart/bytecode/simplifyRes/SimplifyResultFinder.java +++ b/src/main/java/de/dhbwstuttgart/bytecode/simplifyRes/GeneratedGenericsFinder.java @@ -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 listOfResultSets; private SourceFile sf; private List tphsClass; - private SimplifyResultSourceFile simplifyResOfSourceFile; + private GenericGenratorResultForSourceFile generatedGenericsForSF; private ResultSet resultSet; - private List methodNameAndParamsT = new ArrayList<>(); - private Resolver resolver; + private final List methodNameAndParamsT = new ArrayList<>(); private String pkgName; private String className; - // stores generics and their bounds of class - private Map genericsAndBounds = new HashMap<>(); - private Map methodParamsAndTypes = new HashMap<>(); + private Resolver resolver; /** * @param sf * @param listOfResultSets */ - public SimplifyResultFinder(SourceFile sf, Collection listOfResultSets) { + public GeneratedGenericsFinder(SourceFile sf, Collection 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 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> constraints = Simplify.simplifyConstraintsClass(tphExtractor, tphsClass); - ArrayList 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 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 = 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 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 ggR = GenericsGenerator.generateConstraintsForMethod(method, tphExtractor, tphsClass); - Map> 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 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 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> constraints = Simplify.simplifyConstraints(field, tphExtractor, - tphsClass); - SimplifyResultMethod sResMethod = new SimplifyResultMethod(methParamTypes, constraints); - - simplifyResOfSourceFile.getSimplifyResultsByName(pkgName,className).getSimplifyResultForMethod().add(sResMethod); - } - + } /* diff --git a/src/main/java/de/dhbwstuttgart/bytecode/simplifyRes/GenericGeneratorResultsForAllMethods.java b/src/main/java/de/dhbwstuttgart/bytecode/simplifyRes/GenericGeneratorResultsForAllMethods.java new file mode 100644 index 00000000..bd3d224d --- /dev/null +++ b/src/main/java/de/dhbwstuttgart/bytecode/simplifyRes/GenericGeneratorResultsForAllMethods.java @@ -0,0 +1,30 @@ +/** + * + */ +package de.dhbwstuttgart.bytecode.simplifyRes; + +import java.util.List; + +/** + * @author fayez + * + */ +public class GenericGeneratorResultsForAllMethods { + private final List methodsAndConstraints; + + + /** + * @param methodsAndConstraints + */ + public GenericGeneratorResultsForAllMethods(List methodsAndConstraints) { + this.methodsAndConstraints = methodsAndConstraints; + } + + /** + * @return the methodsAndConstraints + */ + public List getMethodsAndConstraints() { + return methodsAndConstraints; + } + +} diff --git a/src/main/java/de/dhbwstuttgart/bytecode/simplifyRes/GenericGenratorResultForSourceFile.java b/src/main/java/de/dhbwstuttgart/bytecode/simplifyRes/GenericGenratorResultForSourceFile.java new file mode 100644 index 00000000..e1928893 --- /dev/null +++ b/src/main/java/de/dhbwstuttgart/bytecode/simplifyRes/GenericGenratorResultForSourceFile.java @@ -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 genericGeneratorResultForAllClasses = new ArrayList<>(); + + /** + * @param pkgName + */ + public GenericGenratorResultForSourceFile(String pkgName) { + this.pkgName = pkgName; + } + + public List 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"); + } +} diff --git a/src/main/java/de/dhbwstuttgart/bytecode/simplifyRes/GenericsGeneratorResultForClass.java b/src/main/java/de/dhbwstuttgart/bytecode/simplifyRes/GenericsGeneratorResultForClass.java new file mode 100644 index 00000000..5b53efcc --- /dev/null +++ b/src/main/java/de/dhbwstuttgart/bytecode/simplifyRes/GenericsGeneratorResultForClass.java @@ -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 classConstraints; + private final GenericGeneratorResultsForAllMethods methodsAndTheirConstraints; + + /** + * @param className + * @param classConstraints + * @param methodsAndTheirConstraints + */ + public GenericsGeneratorResultForClass(String className, List 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 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 getMethodConstraintsByID(String id) { + return methodsAndTheirConstraints.getMethodsAndConstraints().stream().filter(mc -> mc.getMethodID().equals(id)) + .findFirst().get().getConstraints(); + } + +} diff --git a/src/main/java/de/dhbwstuttgart/bytecode/simplifyRes/MethodAndConstraints.java b/src/main/java/de/dhbwstuttgart/bytecode/simplifyRes/MethodAndConstraints.java new file mode 100644 index 00000000..1c647285 --- /dev/null +++ b/src/main/java/de/dhbwstuttgart/bytecode/simplifyRes/MethodAndConstraints.java @@ -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 constraints; + /** + * @param methodID + * @param constraints + */ + public MethodAndConstraints(String methodID, List constraints) { + this.methodID = methodID; + this.constraints = constraints; + } + /** + * @return the methodID + */ + public String getMethodID() { + return methodID; + } + /** + * @return the constraints + */ + public List getConstraints() { + return constraints; + } + +} diff --git a/src/main/java/de/dhbwstuttgart/bytecode/simplifyRes/SimplifyResultSourceFile.java b/src/main/java/de/dhbwstuttgart/bytecode/simplifyRes/SimplifyResultSourceFile.java deleted file mode 100644 index 6d2cd4b2..00000000 --- a/src/main/java/de/dhbwstuttgart/bytecode/simplifyRes/SimplifyResultSourceFile.java +++ /dev/null @@ -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 simplifyResForSF = new ArrayList<>(); - - /** - * @param pkgName - */ - public SimplifyResultSourceFile(String pkgName) { - this.pkgName = pkgName; - } - - public List 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"); - } -} diff --git a/src/main/java/de/dhbwstuttgart/bytecode/simplifyRes/TypeVariableFinder.java b/src/main/java/de/dhbwstuttgart/bytecode/simplifyRes/TypeVariableFinder.java index 1da23b09..2b46e609 100644 --- a/src/main/java/de/dhbwstuttgart/bytecode/simplifyRes/TypeVariableFinder.java +++ b/src/main/java/de/dhbwstuttgart/bytecode/simplifyRes/TypeVariableFinder.java @@ -25,14 +25,12 @@ import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric; public class TypeVariableFinder { private ClassOrInterface classOrInterface; private Map genericsAndBounds; - private List tphsClass; private List consClass; public TypeVariableFinder(ClassOrInterface classOrInterface, Map genericsAndBounds, - List tphsClass, List consClass) { + List 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); - } - } } } diff --git a/src/main/java/de/dhbwstuttgart/bytecode/utilities/NameReplacer.java b/src/main/java/de/dhbwstuttgart/bytecode/utilities/NameReplacer.java index 2b995b5f..777955e6 100644 --- a/src/main/java/de/dhbwstuttgart/bytecode/utilities/NameReplacer.java +++ b/src/main/java/de/dhbwstuttgart/bytecode/utilities/NameReplacer.java @@ -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> tphsOfMethods = methodAndTPHs.stream().map(m->m.getTphs()); + Stream> 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 names, Stream> tphsOfMethods) { + tphsOfMethods.forEach(tphsMethod->{ + if(tphsMethod.removeAll(names)) + tphsMethod.add(newName); + }); + } public NameReplacementResult replaceNamesLocal() { String newName = NameGenerator.makeNewName(); diff --git a/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java b/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java index 5fc7f745..5650b8ef 100644 --- a/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java +++ b/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java @@ -1,12 +1,11 @@ //PL 2018-12-19: typeInferenceOld nach typeInference uebertragen package de.dhbwstuttgart.core; - import de.dhbwstuttgart.bytecode.BytecodeGen; import de.dhbwstuttgart.bytecode.Exception.BytecodeGeneratorError; import de.dhbwstuttgart.bytecode.simplifyRes.SimplifyResult; -import de.dhbwstuttgart.bytecode.simplifyRes.SimplifyResultFinder; -import de.dhbwstuttgart.bytecode.simplifyRes.SimplifyResultSourceFile; +import de.dhbwstuttgart.bytecode.simplifyRes.GeneratedGenericsFinder; +import de.dhbwstuttgart.bytecode.simplifyRes.GenericGenratorResultForSourceFile; import de.dhbwstuttgart.environment.CompilationEnvironment; import de.dhbwstuttgart.parser.JavaTXParser; import de.dhbwstuttgart.parser.NullToken; @@ -60,354 +59,372 @@ import org.apache.commons.io.output.NullOutputStream; public class JavaTXCompiler { - final CompilationEnvironment environment; - Boolean resultmodel = true; - public final Map sourceFiles = new HashMap<>(); - Boolean log = true; //gibt an ob ein Log-File nach System.getProperty("user.dir")+"src/test/java/logFiles" geschrieben werden soll? - public volatile UnifyTaskModel usedTasks = new UnifyTaskModel(); - - - public JavaTXCompiler(File sourceFile) throws IOException, ClassNotFoundException { - this(Arrays.asList(sourceFile)); - } + final CompilationEnvironment environment; + Boolean resultmodel = true; + public final Map sourceFiles = new HashMap<>(); + Boolean log = true; // gibt an ob ein Log-File nach + // System.getProperty("user.dir")+"src/test/java/logFiles" geschrieben werden + // soll? + public volatile UnifyTaskModel usedTasks = new UnifyTaskModel(); - public JavaTXCompiler(File sourceFile, Boolean log) throws IOException, ClassNotFoundException { - this(sourceFile); - this.log = log; - } - - public JavaTXCompiler(List sources) throws IOException, ClassNotFoundException { - environment = new CompilationEnvironment(sources); - for (File s : sources) { - sourceFiles.put(s, parse(s)); - } - } + public JavaTXCompiler(File sourceFile) throws IOException, ClassNotFoundException { + this(Arrays.asList(sourceFile)); + } - public ConstraintSet getConstraints() throws ClassNotFoundException { - List allClasses = new ArrayList<>();//environment.getAllAvailableClasses(); - for (SourceFile sf : sourceFiles.values()) { - allClasses.addAll(sf.getClasses()); - } - List importedClasses = new ArrayList<>(); - //Alle Importierten Klassen in allen geparsten Sourcefiles kommen ins FC - for (File forSourceFile : sourceFiles.keySet()) - for (JavaClassName name : sourceFiles.get(forSourceFile).getImports()) { - //TODO: Hier werden imports von eigenen (.jav) Klassen nicht beachtet - ClassOrInterface importedClass = ASTFactory.createClass( - ClassLoader.getSystemClassLoader().loadClass(name.toString())); - importedClasses.add(importedClass); - } - allClasses.addAll(importedClasses); + public JavaTXCompiler(File sourceFile, Boolean log) throws IOException, ClassNotFoundException { + this(sourceFile); + this.log = log; + } - return new TYPE(sourceFiles.values(), allClasses).getConstraints(); - } - - public List getAvailableClasses(SourceFile forSourceFile) throws ClassNotFoundException { - //PL 2018-09-18: List durch Set ersetzt, damit die Klassen nur einmal hinzugefuegt werden - //List allClasses = new ArrayList<>();//environment.getAllAvailableClasses(); - Set allClasses = new HashSet<>(); - - /* PL 2018-09-19 geloescht werden bereits in typeInference hinzugefuegt - for (SourceFile sf : sourceFiles.values()) { - allClasses.addAll(sf.getClasses()); - } - */ - - List importedClasses = new ArrayList<>(); - for (JavaClassName name : forSourceFile.getImports()) { - //TODO: Hier werden imports von eigenen (.jav) Klassen nicht beachtet - ClassOrInterface importedClass = ASTFactory.createClass( - ClassLoader.getSystemClassLoader().loadClass(name.toString())); - importedClasses.add(importedClass); - allClasses.addAll(importedClasses); - } - return new ArrayList<>(allClasses); - } - -/* - public List typeInferenceOld() throws ClassNotFoundException { - List allClasses = new ArrayList<>();//environment.getAllAvailableClasses(); - //Alle Importierten Klassen in allen geparsten Sourcefiles kommen ins FC - for(SourceFile sf : this.sourceFiles.values()) { - allClasses.addAll(getAvailableClasses(sf)); - allClasses.addAll(sf.getClasses()); - } - - final ConstraintSet cons = getConstraints(); - - FiniteClosure finiteClosure = UnifyTypeFactory.generateFC(allClasses); - System.out.println(finiteClosure); - ConstraintSet unifyCons = UnifyTypeFactory.convert(cons); - - TypeUnify unify = new TypeUnify(); - Set> results = new HashSet<>(); - try { - File logPath = new File(System.getProperty("user.dir")+"/target/logFiles/"); - logPath.mkdirs(); - FileWriter logFile = new FileWriter(new File(logPath, "log")); - logFile.write("FC:\\" + finiteClosure.toString()+"\n"); - for(SourceFile sf : this.sourceFiles.values()) { - logFile.write(ASTTypePrinter.print(sf)); - } - logFile.flush(); - Set>> cardProd = unifyCons.cartesianProduct(); - for (List> xCons : cardProd ){ - Set xConsSet = new HashSet<>(); - for (Constraint constraint : xCons) { - xConsSet.addAll(constraint); - } - //.collect(Collectors.toCollection(ArrayList::new)))) - System.out.println(xConsSet); - Set methodParaTypeVarNames = allClasses.stream().map(x -> x.getMethods().stream().map(y -> y.getParameterList().getFormalparalist() - .stream().filter(z -> z.getType() instanceof TypePlaceholder) - .map(z -> ((TypePlaceholder)z.getType()).getName()).collect(Collectors.toCollection(HashSet::new))) - .reduce(new HashSet(), (a,b) -> { a.addAll(b); return a;}, (a,b) -> { a.addAll(b); return a;} ) ) - .reduce(new HashSet(), (a,b) -> { a.addAll(b); return a;} ); - - Set constructorParaTypeVarNames = allClasses.stream().map(x -> x.getConstructors().stream().map(y -> y.getParameterList().getFormalparalist() - .stream().filter(z -> z.getType() instanceof TypePlaceholder) - .map(z -> ((TypePlaceholder)z.getType()).getName()).collect(Collectors.toCollection(HashSet::new))) - .reduce(new HashSet(), (a,b) -> { a.addAll(b); return a;}, (a,b) -> { a.addAll(b); return a;} ) ) - .reduce(new HashSet(), (a,b) -> { a.addAll(b); return a;} ); - - Set paraTypeVarNames = methodParaTypeVarNames; - paraTypeVarNames.addAll(constructorParaTypeVarNames); - - Set returnTypeVarNames = allClasses.stream().map(x -> x.getMethods().stream().filter(y -> y.getReturnType() instanceof TypePlaceholder) - .map(z -> ((TypePlaceholder)z.getReturnType()).getName()).collect(Collectors.toCollection(HashSet::new))).reduce((a,b) -> { a.addAll(b); return a;} ).get(); - - Set fieldTypeVarNames = allClasses.stream().map(x -> x.getFieldDecl().stream().filter(y -> y.getReturnType() instanceof TypePlaceholder) - .map(z -> ((TypePlaceholder)z.getReturnType()).getName()).collect(Collectors.toCollection(HashSet::new))).reduce((a,b) -> { a.addAll(b); return a;} ).get(); - - returnTypeVarNames.addAll(fieldTypeVarNames); - - xConsSet = xConsSet.stream().map(x -> { - //Hier muss ueberlegt werden, ob - //1. alle Argument- und Retuntyp-Variablen in allen UnifyPairs - // mit disableWildcardtable() werden. - //2. alle Typvariablen mit Argument- oder Retuntyp-Variablen - //in Beziehung auch auf disableWildcardtable() gesetzt werden muessen - //PL 2018-04-23 - if ((x.getLhsType() instanceof PlaceholderType)) { - if (paraTypeVarNames.contains(x.getLhsType().getName())) { - ((PlaceholderType)x.getLhsType()).setVariance((byte)1); - ((PlaceholderType)x.getLhsType()).disableWildcardtable(); - } - if (returnTypeVarNames.contains(x.getLhsType().getName())) { - ((PlaceholderType)x.getLhsType()).setVariance((byte)-1); - ((PlaceholderType)x.getLhsType()).disableWildcardtable(); - } - } - if ((x.getRhsType() instanceof PlaceholderType)) { - if (paraTypeVarNames.contains(x.getRhsType().getName())) { - ((PlaceholderType)x.getRhsType()).setVariance((byte)1); - ((PlaceholderType)x.getRhsType()).disableWildcardtable(); - } - if (returnTypeVarNames.contains(x.getRhsType().getName())) { - ((PlaceholderType)x.getRhsType()).setVariance((byte)-1); - ((PlaceholderType)x.getRhsType()).disableWildcardtable(); - } - } - return x;//HIER DIE JEWEILS RECHT BZW. LINKE SEITE AUF GLEICHE VARIANZ SETZEN WIE DIE JEWEILS ANDERE SEITE - }).map( y -> { - if ((y.getLhsType() instanceof PlaceholderType) && (y.getRhsType() instanceof PlaceholderType)) { - if (((PlaceholderType)y.getLhsType()).getVariance() != 0 && ((PlaceholderType)y.getRhsType()).getVariance() == 0) { - ((PlaceholderType)y.getRhsType()).setVariance(((PlaceholderType)y.getLhsType()).getVariance()); - } - if (((PlaceholderType)y.getLhsType()).getVariance() == 0 && ((PlaceholderType)y.getRhsType()).getVariance() != 0) { - ((PlaceholderType)y.getLhsType()).setVariance(((PlaceholderType)y.getRhsType()).getVariance()); - } - } - return y; } ) - .collect(Collectors.toCollection(HashSet::new)); - varianceInheritance(xConsSet); - Set> result = unify.unifySequential(xConsSet, finiteClosure, logFile, log); - //Set> result = unify.unify(xConsSet, finiteClosure); - System.out.println("RESULT: " + result); - logFile.write("RES: " + result.toString()+"\n"); - logFile.flush(); - results.addAll(result); - } - - results = results.stream().map(x -> { - Optional> res = new RuleSet().subst(x.stream().map(y -> { - if (y.getPairOp() == PairOperator.SMALLERDOTWC) y.setPairOp(PairOperator.EQUALSDOT); - return y; //alle Paare a <.? b erden durch a =. b ersetzt - }).collect(Collectors.toCollection(HashSet::new))); - if (res.isPresent()) {//wenn subst ein Erg liefert wurde was veraendert - return new TypeUnifyTask().applyTypeUnificationRules(res.get(), finiteClosure); - } - else return x; //wenn nichts veraendert wurde wird x zurueckgegeben - }).collect(Collectors.toCollection(HashSet::new)); - System.out.println("RESULT Final: " + results); - logFile.write("RES_FINAL: " + results.toString()+"\n"); - logFile.flush(); - logFile.write("PLACEHOLDERS: " + PlaceholderType.EXISTING_PLACEHOLDERS); - logFile.flush(); - } - catch (IOException e) { - e.printStackTrace(); - } - return results.stream().map((unifyPairs -> - new ResultSet(UnifyTypeFactory.convert(unifyPairs, generateTPHMap(cons))))).collect(Collectors.toList()); - } - */ - /** - * Vererbt alle Variancen bei Paaren (a <. theta) oder (Theta <. a) - * wenn a eine Variance !=0 hat auf alle Typvariablen in Theta. - * @param eq The set of constraints - */ - /* - private void varianceInheritance(Set eq) { - Set usedTPH = new HashSet<>(); - Set phSet = eq.stream().map(x -> { - Set pair = new HashSet<>(); - if (x.getLhsType() instanceof PlaceholderType) pair.add((PlaceholderType)x.getLhsType()); - if (x.getRhsType() instanceof PlaceholderType) pair.add((PlaceholderType)x.getRhsType()); - return pair; - }).reduce(new HashSet<>(), (a,b) -> { a.addAll(b); return a;} , (c,d) -> { c.addAll(d); return c;}); - - ArrayList phSetVariance = new ArrayList<>(phSet); - phSetVariance.removeIf(x -> (x.getVariance() == 0)); - while(!phSetVariance.isEmpty()) { - PlaceholderType a = phSetVariance.remove(0); - usedTPH.add(a); - //HashMap ht = new HashMap<>(); - //ht.put(a, a.getVariance()); - Set eq1 = new HashSet<>(eq); - eq1.removeIf(x -> !(x.getLhsType() instanceof PlaceholderType && ((PlaceholderType)x.getLhsType()).equals(a))); - eq1.stream().forEach(x -> { x.getRhsType().accept(new distributeVariance(), a.getVariance());}); - eq1 = new HashSet<>(eq); - eq1.removeIf(x -> !(x.getRhsType() instanceof PlaceholderType && ((PlaceholderType)x.getRhsType()).equals(a))); - eq1.stream().forEach(x -> { x.getLhsType().accept(new distributeVariance(), a.getVariance());}); - phSetVariance = new ArrayList<>(phSet); - phSetVariance.removeIf(x -> (x.getVariance() == 0 || usedTPH.contains(x))); + public JavaTXCompiler(List sources) throws IOException, ClassNotFoundException { + environment = new CompilationEnvironment(sources); + for (File s : sources) { + sourceFiles.put(s, parse(s)); } } - */ - - public UnifyResultModel typeInferenceAsync(UnifyResultListener resultListener, Writer logFile) throws ClassNotFoundException { - List allClasses = new ArrayList<>();//environment.getAllAvailableClasses(); - //Alle Importierten Klassen in allen geparsten Sourcefiles kommen ins FC - for(SourceFile sf : this.sourceFiles.values()) { - allClasses.addAll(getAvailableClasses(sf)); - allClasses.addAll(sf.getClasses()); - } - final ConstraintSet cons = getConstraints(); - Set> results = new HashSet<>(); - UnifyResultModel urm = null; - //urm.addUnifyResultListener(resultListener); - try { - logFile = logFile == null ? new FileWriter(new File("log_"+sourceFiles.keySet().iterator().next().getName())) : logFile; - IFiniteClosure finiteClosure = UnifyTypeFactory.generateFC(allClasses,logFile); + public ConstraintSet getConstraints() throws ClassNotFoundException { + List allClasses = new ArrayList<>();// environment.getAllAvailableClasses(); + for (SourceFile sf : sourceFiles.values()) { + allClasses.addAll(sf.getClasses()); + } + List importedClasses = new ArrayList<>(); + // Alle Importierten Klassen in allen geparsten Sourcefiles kommen ins FC + for (File forSourceFile : sourceFiles.keySet()) + for (JavaClassName name : sourceFiles.get(forSourceFile).getImports()) { + // TODO: Hier werden imports von eigenen (.jav) Klassen nicht beachtet + ClassOrInterface importedClass = ASTFactory + .createClass(ClassLoader.getSystemClassLoader().loadClass(name.toString())); + importedClasses.add(importedClass); + } + allClasses.addAll(importedClasses); + + return new TYPE(sourceFiles.values(), allClasses).getConstraints(); + } + + public List getAvailableClasses(SourceFile forSourceFile) throws ClassNotFoundException { + // PL 2018-09-18: List durch Set ersetzt, damit die Klassen nur einmal + // hinzugefuegt werden + // List allClasses = new + // ArrayList<>();//environment.getAllAvailableClasses(); + Set allClasses = new HashSet<>(); + + /* + * PL 2018-09-19 geloescht werden bereits in typeInference hinzugefuegt for + * (SourceFile sf : sourceFiles.values()) { allClasses.addAll(sf.getClasses()); + * } + */ + + List importedClasses = new ArrayList<>(); + for (JavaClassName name : forSourceFile.getImports()) { + // TODO: Hier werden imports von eigenen (.jav) Klassen nicht beachtet + ClassOrInterface importedClass = ASTFactory + .createClass(ClassLoader.getSystemClassLoader().loadClass(name.toString())); + importedClasses.add(importedClass); + allClasses.addAll(importedClasses); + } + return new ArrayList<>(allClasses); + } + + /* + * public List typeInferenceOld() throws ClassNotFoundException { + * List allClasses = new + * ArrayList<>();//environment.getAllAvailableClasses(); //Alle Importierten + * Klassen in allen geparsten Sourcefiles kommen ins FC for(SourceFile sf : + * this.sourceFiles.values()) { allClasses.addAll(getAvailableClasses(sf)); + * allClasses.addAll(sf.getClasses()); } + * + * final ConstraintSet cons = getConstraints(); + * + * FiniteClosure finiteClosure = UnifyTypeFactory.generateFC(allClasses); + * System.out.println(finiteClosure); ConstraintSet unifyCons = + * UnifyTypeFactory.convert(cons); + * + * TypeUnify unify = new TypeUnify(); Set> results = new + * HashSet<>(); try { File logPath = new + * File(System.getProperty("user.dir")+"/target/logFiles/"); logPath.mkdirs(); + * FileWriter logFile = new FileWriter(new File(logPath, "log")); + * logFile.write("FC:\\" + finiteClosure.toString()+"\n"); for(SourceFile sf : + * this.sourceFiles.values()) { logFile.write(ASTTypePrinter.print(sf)); } + * logFile.flush(); Set>> cardProd = + * unifyCons.cartesianProduct(); for (List> xCons : + * cardProd ){ Set xConsSet = new HashSet<>(); for + * (Constraint constraint : xCons) { xConsSet.addAll(constraint); } + * //.collect(Collectors.toCollection(ArrayList::new)))) + * System.out.println(xConsSet); Set methodParaTypeVarNames = + * allClasses.stream().map(x -> x.getMethods().stream().map(y -> + * y.getParameterList().getFormalparalist() .stream().filter(z -> z.getType() + * instanceof TypePlaceholder) .map(z -> + * ((TypePlaceholder)z.getType()).getName()).collect(Collectors.toCollection( + * HashSet::new))) .reduce(new HashSet(), (a,b) -> { a.addAll(b); return + * a;}, (a,b) -> { a.addAll(b); return a;} ) ) .reduce(new HashSet(), + * (a,b) -> { a.addAll(b); return a;} ); + * + * Set constructorParaTypeVarNames = allClasses.stream().map(x -> + * x.getConstructors().stream().map(y -> + * y.getParameterList().getFormalparalist() .stream().filter(z -> z.getType() + * instanceof TypePlaceholder) .map(z -> + * ((TypePlaceholder)z.getType()).getName()).collect(Collectors.toCollection( + * HashSet::new))) .reduce(new HashSet(), (a,b) -> { a.addAll(b); return + * a;}, (a,b) -> { a.addAll(b); return a;} ) ) .reduce(new HashSet(), + * (a,b) -> { a.addAll(b); return a;} ); + * + * Set paraTypeVarNames = methodParaTypeVarNames; + * paraTypeVarNames.addAll(constructorParaTypeVarNames); + * + * Set returnTypeVarNames = allClasses.stream().map(x -> + * x.getMethods().stream().filter(y -> y.getReturnType() instanceof + * TypePlaceholder) .map(z -> + * ((TypePlaceholder)z.getReturnType()).getName()).collect(Collectors. + * toCollection(HashSet::new))).reduce((a,b) -> { a.addAll(b); return a;} + * ).get(); + * + * Set fieldTypeVarNames = allClasses.stream().map(x -> + * x.getFieldDecl().stream().filter(y -> y.getReturnType() instanceof + * TypePlaceholder) .map(z -> + * ((TypePlaceholder)z.getReturnType()).getName()).collect(Collectors. + * toCollection(HashSet::new))).reduce((a,b) -> { a.addAll(b); return a;} + * ).get(); + * + * returnTypeVarNames.addAll(fieldTypeVarNames); + * + * xConsSet = xConsSet.stream().map(x -> { //Hier muss ueberlegt werden, ob //1. + * alle Argument- und Retuntyp-Variablen in allen UnifyPairs // mit + * disableWildcardtable() werden. //2. alle Typvariablen mit Argument- oder + * Retuntyp-Variablen //in Beziehung auch auf disableWildcardtable() gesetzt + * werden muessen //PL 2018-04-23 if ((x.getLhsType() instanceof + * PlaceholderType)) { if (paraTypeVarNames.contains(x.getLhsType().getName())) + * { ((PlaceholderType)x.getLhsType()).setVariance((byte)1); + * ((PlaceholderType)x.getLhsType()).disableWildcardtable(); } if + * (returnTypeVarNames.contains(x.getLhsType().getName())) { + * ((PlaceholderType)x.getLhsType()).setVariance((byte)-1); + * ((PlaceholderType)x.getLhsType()).disableWildcardtable(); } } if + * ((x.getRhsType() instanceof PlaceholderType)) { if + * (paraTypeVarNames.contains(x.getRhsType().getName())) { + * ((PlaceholderType)x.getRhsType()).setVariance((byte)1); + * ((PlaceholderType)x.getRhsType()).disableWildcardtable(); } if + * (returnTypeVarNames.contains(x.getRhsType().getName())) { + * ((PlaceholderType)x.getRhsType()).setVariance((byte)-1); + * ((PlaceholderType)x.getRhsType()).disableWildcardtable(); } } return x;//HIER + * DIE JEWEILS RECHT BZW. LINKE SEITE AUF GLEICHE VARIANZ SETZEN WIE DIE JEWEILS + * ANDERE SEITE }).map( y -> { if ((y.getLhsType() instanceof PlaceholderType) + * && (y.getRhsType() instanceof PlaceholderType)) { if + * (((PlaceholderType)y.getLhsType()).getVariance() != 0 && + * ((PlaceholderType)y.getRhsType()).getVariance() == 0) { + * ((PlaceholderType)y.getRhsType()).setVariance(((PlaceholderType)y.getLhsType( + * )).getVariance()); } if (((PlaceholderType)y.getLhsType()).getVariance() == 0 + * && ((PlaceholderType)y.getRhsType()).getVariance() != 0) { + * ((PlaceholderType)y.getLhsType()).setVariance(((PlaceholderType)y.getRhsType( + * )).getVariance()); } } return y; } ) + * .collect(Collectors.toCollection(HashSet::new)); + * varianceInheritance(xConsSet); Set> result = + * unify.unifySequential(xConsSet, finiteClosure, logFile, log); + * //Set> result = unify.unify(xConsSet, finiteClosure); + * System.out.println("RESULT: " + result); logFile.write("RES: " + + * result.toString()+"\n"); logFile.flush(); results.addAll(result); } + * + * results = results.stream().map(x -> { Optional> res = new + * RuleSet().subst(x.stream().map(y -> { if (y.getPairOp() == + * PairOperator.SMALLERDOTWC) y.setPairOp(PairOperator.EQUALSDOT); return y; + * //alle Paare a <.? b erden durch a =. b ersetzt + * }).collect(Collectors.toCollection(HashSet::new))); if (res.isPresent()) + * {//wenn subst ein Erg liefert wurde was veraendert return new + * TypeUnifyTask().applyTypeUnificationRules(res.get(), finiteClosure); } else + * return x; //wenn nichts veraendert wurde wird x zurueckgegeben + * }).collect(Collectors.toCollection(HashSet::new)); + * System.out.println("RESULT Final: " + results); logFile.write("RES_FINAL: " + + * results.toString()+"\n"); logFile.flush(); logFile.write("PLACEHOLDERS: " + + * PlaceholderType.EXISTING_PLACEHOLDERS); logFile.flush(); } catch (IOException + * e) { e.printStackTrace(); } return results.stream().map((unifyPairs -> new + * ResultSet(UnifyTypeFactory.convert(unifyPairs, + * generateTPHMap(cons))))).collect(Collectors.toList()); } + */ + /** + * Vererbt alle Variancen bei Paaren (a <. theta) oder (Theta <. a) wenn a eine + * Variance !=0 hat auf alle Typvariablen in Theta. + * + * + */ + /* + * private void varianceInheritance(Set eq) { Set + * usedTPH = new HashSet<>(); Set phSet = eq.stream().map(x -> + * { Set pair = new HashSet<>(); if (x.getLhsType() instanceof + * PlaceholderType) pair.add((PlaceholderType)x.getLhsType()); if + * (x.getRhsType() instanceof PlaceholderType) + * pair.add((PlaceholderType)x.getRhsType()); return pair; }).reduce(new + * HashSet<>(), (a,b) -> { a.addAll(b); return a;} , (c,d) -> { c.addAll(d); + * return c;}); + * + * ArrayList phSetVariance = new ArrayList<>(phSet); + * phSetVariance.removeIf(x -> (x.getVariance() == 0)); + * while(!phSetVariance.isEmpty()) { PlaceholderType a = + * phSetVariance.remove(0); usedTPH.add(a); //HashMap + * ht = new HashMap<>(); //ht.put(a, a.getVariance()); Set eq1 = new + * HashSet<>(eq); eq1.removeIf(x -> !(x.getLhsType() instanceof PlaceholderType + * && ((PlaceholderType)x.getLhsType()).equals(a))); eq1.stream().forEach(x -> { + * x.getRhsType().accept(new distributeVariance(), a.getVariance());}); eq1 = + * new HashSet<>(eq); eq1.removeIf(x -> !(x.getRhsType() instanceof + * PlaceholderType && ((PlaceholderType)x.getRhsType()).equals(a))); + * eq1.stream().forEach(x -> { x.getLhsType().accept(new distributeVariance(), + * a.getVariance());}); phSetVariance = new ArrayList<>(phSet); + * phSetVariance.removeIf(x -> (x.getVariance() == 0 || usedTPH.contains(x))); } + * } + */ + + public UnifyResultModel typeInferenceAsync(UnifyResultListener resultListener, Writer logFile) + throws ClassNotFoundException { + List allClasses = new ArrayList<>();// environment.getAllAvailableClasses(); + // Alle Importierten Klassen in allen geparsten Sourcefiles kommen ins FC + for (SourceFile sf : this.sourceFiles.values()) { + allClasses.addAll(getAvailableClasses(sf)); + allClasses.addAll(sf.getClasses()); + } + + final ConstraintSet cons = getConstraints(); + Set> results = new HashSet<>(); + UnifyResultModel urm = null; + // urm.addUnifyResultListener(resultListener); + try { + logFile = logFile == null + ? new FileWriter(new File("log_" + sourceFiles.keySet().iterator().next().getName())) + : logFile; + IFiniteClosure finiteClosure = UnifyTypeFactory.generateFC(allClasses, logFile); System.out.println(finiteClosure); urm = new UnifyResultModel(cons, finiteClosure); urm.addUnifyResultListener(resultListener); ConstraintSet unifyCons = UnifyTypeFactory.convert(cons); - - Function distributeInnerVars = - x -> { - UnifyType lhs, rhs; - if (((lhs = x.getLhsType()) instanceof PlaceholderType) - && ((rhs = x.getRhsType()) instanceof PlaceholderType) - && (((PlaceholderType)lhs).isInnerType() - || ((PlaceholderType)rhs).isInnerType())) - { - ((PlaceholderType)lhs).setInnerType(true); - ((PlaceholderType)rhs).setInnerType(true); - } - return x; - - }; - logFile.write(unifyCons.toString()); - unifyCons = unifyCons.map(distributeInnerVars); + + Function distributeInnerVars = x -> { + UnifyType lhs, rhs; + if (((lhs = x.getLhsType()) instanceof PlaceholderType) + && ((rhs = x.getRhsType()) instanceof PlaceholderType) + && (((PlaceholderType) lhs).isInnerType() || ((PlaceholderType) rhs).isInnerType())) { + ((PlaceholderType) lhs).setInnerType(true); + ((PlaceholderType) rhs).setInnerType(true); + } + return x; + + }; + logFile.write(unifyCons.toString()); + unifyCons = unifyCons.map(distributeInnerVars); logFile.write(unifyCons.toString()); TypeUnify unify = new TypeUnify(); - //Set> results = new HashSet<>(); Nach vorne gezogen - logFile.write("FC:\\" + finiteClosure.toString()+"\n"); - for(SourceFile sf : this.sourceFiles.values()) { + // Set> results = new HashSet<>(); Nach vorne gezogen + logFile.write("FC:\\" + finiteClosure.toString() + "\n"); + for (SourceFile sf : this.sourceFiles.values()) { logFile.write(ASTTypePrinter.print(sf)); } logFile.flush(); - - Set methodParaTypeVarNames = allClasses.stream().map(x -> x.getMethods().stream().map(y -> y.getParameterList().getFormalparalist() - .stream().filter(z -> z.getType() instanceof TypePlaceholder) - .map(z -> ((TypePlaceholder)z.getType()).getName()).collect(Collectors.toCollection(HashSet::new))) - .reduce(new HashSet(), (a,b) -> { a.addAll(b); return a;}, (a,b) -> { a.addAll(b); return a;} ) ) - .reduce(new HashSet(), (a,b) -> { a.addAll(b); return a;} ); - - Set constructorParaTypeVarNames = allClasses.stream().map(x -> x.getConstructors().stream().map(y -> y.getParameterList().getFormalparalist() - .stream().filter(z -> z.getType() instanceof TypePlaceholder) - .map(z -> ((TypePlaceholder)z.getType()).getName()).collect(Collectors.toCollection(HashSet::new))) - .reduce(new HashSet(), (a,b) -> { a.addAll(b); return a;}, (a,b) -> { a.addAll(b); return a;} ) ) - .reduce(new HashSet(), (a,b) -> { a.addAll(b); return a;} ); - + + Set methodParaTypeVarNames = allClasses.stream().map(x -> x.getMethods().stream() + .map(y -> y.getParameterList().getFormalparalist().stream() + .filter(z -> z.getType() instanceof TypePlaceholder) + .map(z -> ((TypePlaceholder) z.getType()).getName()) + .collect(Collectors.toCollection(HashSet::new))) + .reduce(new HashSet(), (a, b) -> { + a.addAll(b); + return a; + }, (a, b) -> { + a.addAll(b); + return a; + })).reduce(new HashSet(), (a, b) -> { + a.addAll(b); + return a; + }); + + Set constructorParaTypeVarNames = allClasses.stream().map(x -> x.getConstructors().stream() + .map(y -> y.getParameterList().getFormalparalist().stream() + .filter(z -> z.getType() instanceof TypePlaceholder) + .map(z -> ((TypePlaceholder) z.getType()).getName()) + .collect(Collectors.toCollection(HashSet::new))) + .reduce(new HashSet(), (a, b) -> { + a.addAll(b); + return a; + }, (a, b) -> { + a.addAll(b); + return a; + })).reduce(new HashSet(), (a, b) -> { + a.addAll(b); + return a; + }); + Set paraTypeVarNames = methodParaTypeVarNames; paraTypeVarNames.addAll(constructorParaTypeVarNames); - - Set returnTypeVarNames = allClasses.stream().map(x -> x.getMethods().stream().filter(y -> y.getReturnType() instanceof TypePlaceholder) - .map(z -> ((TypePlaceholder)z.getReturnType()).getName()).collect(Collectors.toCollection(HashSet::new))).reduce((a,b) -> { a.addAll(b); return a;} ).get(); - - Set fieldTypeVarNames = allClasses.stream().map(x -> x.getFieldDecl().stream().filter(y -> y.getReturnType() instanceof TypePlaceholder) - .map(z -> ((TypePlaceholder)z.getReturnType()).getName()).collect(Collectors.toCollection(HashSet::new))).reduce((a,b) -> { a.addAll(b); return a;} ).get(); + Set returnTypeVarNames = allClasses.stream() + .map(x -> x.getMethods().stream().filter(y -> y.getReturnType() instanceof TypePlaceholder) + .map(z -> ((TypePlaceholder) z.getReturnType()).getName()) + .collect(Collectors.toCollection(HashSet::new))) + .reduce((a, b) -> { + a.addAll(b); + return a; + }).get(); + + Set fieldTypeVarNames = allClasses.stream() + .map(x -> x.getFieldDecl().stream().filter(y -> y.getReturnType() instanceof TypePlaceholder) + .map(z -> ((TypePlaceholder) z.getReturnType()).getName()) + .collect(Collectors.toCollection(HashSet::new))) + .reduce((a, b) -> { + a.addAll(b); + return a; + }).get(); returnTypeVarNames.addAll(fieldTypeVarNames); - - unifyCons = unifyCons.map(x -> { - //Hier muss ueberlegt werden, ob - //1. alle Argument- und Retuntyp-Variablen in allen UnifyPairs - // mit disableWildcardtable() werden. - //2. alle Typvariablen mit Argument- oder Retuntyp-Variablen - //in Beziehung auch auf disableWildcardtable() gesetzt werden muessen - //PL 2018-04-23 + + unifyCons = unifyCons.map(x -> { + // Hier muss ueberlegt werden, ob + // 1. alle Argument- und Retuntyp-Variablen in allen UnifyPairs + // mit disableWildcardtable() werden. + // 2. alle Typvariablen mit Argument- oder Retuntyp-Variablen + // in Beziehung auch auf disableWildcardtable() gesetzt werden muessen + // PL 2018-04-23 if ((x.getLhsType() instanceof PlaceholderType)) { - if (paraTypeVarNames.contains(x.getLhsType().getName())) { - ((PlaceholderType)x.getLhsType()).setVariance((byte)1); - ((PlaceholderType)x.getLhsType()).disableWildcardtable(); + if (paraTypeVarNames.contains(x.getLhsType().getName())) { + ((PlaceholderType) x.getLhsType()).setVariance((byte) 1); + ((PlaceholderType) x.getLhsType()).disableWildcardtable(); } if (returnTypeVarNames.contains(x.getLhsType().getName())) { - ((PlaceholderType)x.getLhsType()).setVariance((byte)-1); - ((PlaceholderType)x.getLhsType()).disableWildcardtable(); + ((PlaceholderType) x.getLhsType()).setVariance((byte) -1); + ((PlaceholderType) x.getLhsType()).disableWildcardtable(); } } if ((x.getRhsType() instanceof PlaceholderType)) { if (paraTypeVarNames.contains(x.getRhsType().getName())) { - ((PlaceholderType)x.getRhsType()).setVariance((byte)1); - ((PlaceholderType)x.getRhsType()).disableWildcardtable(); + ((PlaceholderType) x.getRhsType()).setVariance((byte) 1); + ((PlaceholderType) x.getRhsType()).disableWildcardtable(); } if (returnTypeVarNames.contains(x.getRhsType().getName())) { - ((PlaceholderType)x.getRhsType()).setVariance((byte)-1); - ((PlaceholderType)x.getRhsType()).disableWildcardtable(); - } + ((PlaceholderType) x.getRhsType()).setVariance((byte) -1); + ((PlaceholderType) x.getRhsType()).disableWildcardtable(); + } } - return x;//HIER DIE JEWEILS RECHT BZW. LINKE SEITE AUF GLEICHE VARIANZ SETZEN WIE DIE JEWEILS ANDERE SEITE + return x;// HIER DIE JEWEILS RECHT BZW. LINKE SEITE AUF GLEICHE VARIANZ SETZEN WIE DIE + // JEWEILS ANDERE SEITE }); Set varianceTPHold; Set varianceTPH = new HashSet<>(); varianceTPH = varianceInheritanceConstraintSet(unifyCons); - - /* PL 2018-11-07 wird in varianceInheritanceConstraintSet erledigt - do { //PL 2018-11-05 Huellenbildung Variance auf alle TPHs der Terme auf der jeweiligen - //anderen Seite übertragen - varianceTPHold = new HashSet<>(varianceTPH); - varianceTPH = varianceInheritanceConstraintSet(unifyCons); - unifyCons.map( y -> { - if ((y.getLhsType() instanceof PlaceholderType) && (y.getRhsType() instanceof PlaceholderType)) { - if (((PlaceholderType)y.getLhsType()).getVariance() != 0 && ((PlaceholderType)y.getRhsType()).getVariance() == 0) { - ((PlaceholderType)y.getRhsType()).setVariance(((PlaceholderType)y.getLhsType()).getVariance()); - } - if (((PlaceholderType)y.getLhsType()).getVariance() == 0 && ((PlaceholderType)y.getRhsType()).getVariance() != 0) { - ((PlaceholderType)y.getLhsType()).setVariance(((PlaceholderType)y.getRhsType()).getVariance()); - } - } - return y; } ); } - while (!varianceTPHold.equals(varianceTPH)); - */ - - //Set> result = unify.unifySequential(xConsSet, finiteClosure, logFile, log); - //Set> result = unify.unify(xConsSet, finiteClosure); + + /* + * PL 2018-11-07 wird in varianceInheritanceConstraintSet erledigt do { //PL + * 2018-11-05 Huellenbildung Variance auf alle TPHs der Terme auf der jeweiligen + * //anderen Seite übertragen varianceTPHold = new HashSet<>(varianceTPH); + * varianceTPH = varianceInheritanceConstraintSet(unifyCons); unifyCons.map( y + * -> { if ((y.getLhsType() instanceof PlaceholderType) && (y.getRhsType() + * instanceof PlaceholderType)) { if + * (((PlaceholderType)y.getLhsType()).getVariance() != 0 && + * ((PlaceholderType)y.getRhsType()).getVariance() == 0) { + * ((PlaceholderType)y.getRhsType()).setVariance(((PlaceholderType)y.getLhsType( + * )).getVariance()); } if (((PlaceholderType)y.getLhsType()).getVariance() == 0 + * && ((PlaceholderType)y.getRhsType()).getVariance() != 0) { + * ((PlaceholderType)y.getLhsType()).setVariance(((PlaceholderType)y.getRhsType( + * )).getVariance()); } } return y; } ); } while + * (!varianceTPHold.equals(varianceTPH)); + */ + + // Set> result = unify.unifySequential(xConsSet, finiteClosure, + // logFile, log); + // Set> result = unify.unify(xConsSet, finiteClosure); List>> oderConstraints = unifyCons.getOderConstraints().stream().map(x -> { Set> ret = new HashSet<>(); for (Constraint y : x) { @@ -415,135 +432,165 @@ public class JavaTXCompiler { } return ret; }).collect(Collectors.toCollection(ArrayList::new)); - unify.unifyAsync(unifyCons.getUndConstraints(), oderConstraints, finiteClosure, logFile, log, urm, usedTasks); - } - catch (IOException e) { - System.err.println("kein LogFile"); - } - return urm; - } - - - public List typeInference() throws ClassNotFoundException { - List allClasses = new ArrayList<>();//environment.getAllAvailableClasses(); - //Alle Importierten Klassen in allen geparsten Sourcefiles kommen ins FC - for(SourceFile sf : this.sourceFiles.values()) { - allClasses.addAll(getAvailableClasses(sf)); - allClasses.addAll(sf.getClasses()); - } + unify.unifyAsync(unifyCons.getUndConstraints(), oderConstraints, finiteClosure, logFile, log, urm, + usedTasks); + } catch (IOException e) { + System.err.println("kein LogFile"); + } + return urm; + } - final ConstraintSet cons = getConstraints(); - Set> results = new HashSet<>(); - try { - Writer logFile = //new OutputStreamWriter(new NullOutputStream()); - //new FileWriter(new File(System.getProperty("user.dir")+"/src/test/resources/logFiles/"+"log_"+sourceFiles.keySet().iterator().next().getName())); - new FileWriter(new File(System.getProperty("user.dir")+"/logFiles/"+"log_"+sourceFiles.keySet().iterator().next().getName())); - IFiniteClosure finiteClosure = UnifyTypeFactory.generateFC(allClasses,logFile); + public List typeInference() throws ClassNotFoundException { + List allClasses = new ArrayList<>();// environment.getAllAvailableClasses(); + // Alle Importierten Klassen in allen geparsten Sourcefiles kommen ins FC + for (SourceFile sf : this.sourceFiles.values()) { + allClasses.addAll(getAvailableClasses(sf)); + allClasses.addAll(sf.getClasses()); + } + + final ConstraintSet cons = getConstraints(); + Set> results = new HashSet<>(); + try { + Writer logFile = // new OutputStreamWriter(new NullOutputStream()); + // new FileWriter(new + // File(System.getProperty("user.dir")+"/src/test/resources/logFiles/"+"log_"+sourceFiles.keySet().iterator().next().getName())); + new FileWriter(new File(System.getProperty("user.dir") + "/logFiles/" + "log_" + + sourceFiles.keySet().iterator().next().getName())); + IFiniteClosure finiteClosure = UnifyTypeFactory.generateFC(allClasses, logFile); System.out.println(finiteClosure); ConstraintSet unifyCons = UnifyTypeFactory.convert(cons); - - Function distributeInnerVars = - x -> { - UnifyType lhs, rhs; - if (((lhs = x.getLhsType()) instanceof PlaceholderType) - && ((rhs = x.getRhsType()) instanceof PlaceholderType) - && (((PlaceholderType)lhs).isInnerType() - || ((PlaceholderType)rhs).isInnerType())) - { - ((PlaceholderType)lhs).setInnerType(true); - ((PlaceholderType)rhs).setInnerType(true); - } - return x; - - }; - logFile.write(unifyCons.toString()); - unifyCons = unifyCons.map(distributeInnerVars); + + Function distributeInnerVars = x -> { + UnifyType lhs, rhs; + if (((lhs = x.getLhsType()) instanceof PlaceholderType) + && ((rhs = x.getRhsType()) instanceof PlaceholderType) + && (((PlaceholderType) lhs).isInnerType() || ((PlaceholderType) rhs).isInnerType())) { + ((PlaceholderType) lhs).setInnerType(true); + ((PlaceholderType) rhs).setInnerType(true); + } + return x; + + }; + logFile.write(unifyCons.toString()); + unifyCons = unifyCons.map(distributeInnerVars); logFile.write(unifyCons.toString()); TypeUnify unify = new TypeUnify(); - //Set> results = new HashSet<>(); Nach vorne gezogen - logFile.write("FC:\\" + finiteClosure.toString()+"\n"); - for(SourceFile sf : this.sourceFiles.values()) { + // Set> results = new HashSet<>(); Nach vorne gezogen + logFile.write("FC:\\" + finiteClosure.toString() + "\n"); + for (SourceFile sf : this.sourceFiles.values()) { logFile.write(ASTTypePrinter.print(sf)); } logFile.flush(); - - Set methodParaTypeVarNames = allClasses.stream().map(x -> x.getMethods().stream().map(y -> y.getParameterList().getFormalparalist() - .stream().filter(z -> z.getType() instanceof TypePlaceholder) - .map(z -> ((TypePlaceholder)z.getType()).getName()).collect(Collectors.toCollection(HashSet::new))) - .reduce(new HashSet(), (a,b) -> { a.addAll(b); return a;}, (a,b) -> { a.addAll(b); return a;} ) ) - .reduce(new HashSet(), (a,b) -> { a.addAll(b); return a;} ); - - Set constructorParaTypeVarNames = allClasses.stream().map(x -> x.getConstructors().stream().map(y -> y.getParameterList().getFormalparalist() - .stream().filter(z -> z.getType() instanceof TypePlaceholder) - .map(z -> ((TypePlaceholder)z.getType()).getName()).collect(Collectors.toCollection(HashSet::new))) - .reduce(new HashSet(), (a,b) -> { a.addAll(b); return a;}, (a,b) -> { a.addAll(b); return a;} ) ) - .reduce(new HashSet(), (a,b) -> { a.addAll(b); return a;} ); - + + Set methodParaTypeVarNames = allClasses.stream().map(x -> x.getMethods().stream() + .map(y -> y.getParameterList().getFormalparalist().stream() + .filter(z -> z.getType() instanceof TypePlaceholder) + .map(z -> ((TypePlaceholder) z.getType()).getName()) + .collect(Collectors.toCollection(HashSet::new))) + .reduce(new HashSet(), (a, b) -> { + a.addAll(b); + return a; + }, (a, b) -> { + a.addAll(b); + return a; + })).reduce(new HashSet(), (a, b) -> { + a.addAll(b); + return a; + }); + + Set constructorParaTypeVarNames = allClasses.stream().map(x -> x.getConstructors().stream() + .map(y -> y.getParameterList().getFormalparalist().stream() + .filter(z -> z.getType() instanceof TypePlaceholder) + .map(z -> ((TypePlaceholder) z.getType()).getName()) + .collect(Collectors.toCollection(HashSet::new))) + .reduce(new HashSet(), (a, b) -> { + a.addAll(b); + return a; + }, (a, b) -> { + a.addAll(b); + return a; + })).reduce(new HashSet(), (a, b) -> { + a.addAll(b); + return a; + }); + Set paraTypeVarNames = methodParaTypeVarNames; paraTypeVarNames.addAll(constructorParaTypeVarNames); - - Set returnTypeVarNames = allClasses.stream().map(x -> x.getMethods().stream().filter(y -> y.getReturnType() instanceof TypePlaceholder) - .map(z -> ((TypePlaceholder)z.getReturnType()).getName()).collect(Collectors.toCollection(HashSet::new))).reduce((a,b) -> { a.addAll(b); return a;} ).get(); - - Set fieldTypeVarNames = allClasses.stream().map(x -> x.getFieldDecl().stream().filter(y -> y.getReturnType() instanceof TypePlaceholder) - .map(z -> ((TypePlaceholder)z.getReturnType()).getName()).collect(Collectors.toCollection(HashSet::new))).reduce((a,b) -> { a.addAll(b); return a;} ).get(); + Set returnTypeVarNames = allClasses.stream() + .map(x -> x.getMethods().stream().filter(y -> y.getReturnType() instanceof TypePlaceholder) + .map(z -> ((TypePlaceholder) z.getReturnType()).getName()) + .collect(Collectors.toCollection(HashSet::new))) + .reduce((a, b) -> { + a.addAll(b); + return a; + }).get(); + + Set fieldTypeVarNames = allClasses.stream() + .map(x -> x.getFieldDecl().stream().filter(y -> y.getReturnType() instanceof TypePlaceholder) + .map(z -> ((TypePlaceholder) z.getReturnType()).getName()) + .collect(Collectors.toCollection(HashSet::new))) + .reduce((a, b) -> { + a.addAll(b); + return a; + }).get(); returnTypeVarNames.addAll(fieldTypeVarNames); - - unifyCons = unifyCons.map(x -> { - //Hier muss ueberlegt werden, ob - //1. alle Argument- und Retuntyp-Variablen in allen UnifyPairs - // mit disableWildcardtable() werden. - //2. alle Typvariablen mit Argument- oder Retuntyp-Variablen - //in Beziehung auch auf disableWildcardtable() gesetzt werden muessen - //PL 2018-04-23 + + unifyCons = unifyCons.map(x -> { + // Hier muss ueberlegt werden, ob + // 1. alle Argument- und Retuntyp-Variablen in allen UnifyPairs + // mit disableWildcardtable() werden. + // 2. alle Typvariablen mit Argument- oder Retuntyp-Variablen + // in Beziehung auch auf disableWildcardtable() gesetzt werden muessen + // PL 2018-04-23 if ((x.getLhsType() instanceof PlaceholderType)) { - if (paraTypeVarNames.contains(x.getLhsType().getName())) { - ((PlaceholderType)x.getLhsType()).setVariance((byte)1); - ((PlaceholderType)x.getLhsType()).disableWildcardtable(); + if (paraTypeVarNames.contains(x.getLhsType().getName())) { + ((PlaceholderType) x.getLhsType()).setVariance((byte) 1); + ((PlaceholderType) x.getLhsType()).disableWildcardtable(); } if (returnTypeVarNames.contains(x.getLhsType().getName())) { - ((PlaceholderType)x.getLhsType()).setVariance((byte)-1); - ((PlaceholderType)x.getLhsType()).disableWildcardtable(); + ((PlaceholderType) x.getLhsType()).setVariance((byte) -1); + ((PlaceholderType) x.getLhsType()).disableWildcardtable(); } } if ((x.getRhsType() instanceof PlaceholderType)) { if (paraTypeVarNames.contains(x.getRhsType().getName())) { - ((PlaceholderType)x.getRhsType()).setVariance((byte)1); - ((PlaceholderType)x.getRhsType()).disableWildcardtable(); + ((PlaceholderType) x.getRhsType()).setVariance((byte) 1); + ((PlaceholderType) x.getRhsType()).disableWildcardtable(); } if (returnTypeVarNames.contains(x.getRhsType().getName())) { - ((PlaceholderType)x.getRhsType()).setVariance((byte)-1); - ((PlaceholderType)x.getRhsType()).disableWildcardtable(); - } + ((PlaceholderType) x.getRhsType()).setVariance((byte) -1); + ((PlaceholderType) x.getRhsType()).disableWildcardtable(); + } } - return x;//HIER DIE JEWEILS RECHT BZW. LINKE SEITE AUF GLEICHE VARIANZ SETZEN WIE DIE JEWEILS ANDERE SEITE + return x;// HIER DIE JEWEILS RECHT BZW. LINKE SEITE AUF GLEICHE VARIANZ SETZEN WIE DIE + // JEWEILS ANDERE SEITE }); Set varianceTPHold; Set varianceTPH = new HashSet<>(); varianceTPH = varianceInheritanceConstraintSet(unifyCons); - - /* PL 2018-11-07 wird in varianceInheritanceConstraintSet erledigt - do { //PL 2018-11-05 Huellenbildung Variance auf alle TPHs der Terme auf der jeweiligen - //anderen Seite übertragen - varianceTPHold = new HashSet<>(varianceTPH); - varianceTPH = varianceInheritanceConstraintSet(unifyCons); - unifyCons.map( y -> { - if ((y.getLhsType() instanceof PlaceholderType) && (y.getRhsType() instanceof PlaceholderType)) { - if (((PlaceholderType)y.getLhsType()).getVariance() != 0 && ((PlaceholderType)y.getRhsType()).getVariance() == 0) { - ((PlaceholderType)y.getRhsType()).setVariance(((PlaceholderType)y.getLhsType()).getVariance()); - } - if (((PlaceholderType)y.getLhsType()).getVariance() == 0 && ((PlaceholderType)y.getRhsType()).getVariance() != 0) { - ((PlaceholderType)y.getLhsType()).setVariance(((PlaceholderType)y.getRhsType()).getVariance()); - } - } - return y; } ); } - while (!varianceTPHold.equals(varianceTPH)); - */ - - //Set> result = unify.unifySequential(xConsSet, finiteClosure, logFile, log); - //Set> result = unify.unify(xConsSet, finiteClosure); + + /* + * PL 2018-11-07 wird in varianceInheritanceConstraintSet erledigt do { //PL + * 2018-11-05 Huellenbildung Variance auf alle TPHs der Terme auf der jeweiligen + * //anderen Seite übertragen varianceTPHold = new HashSet<>(varianceTPH); + * varianceTPH = varianceInheritanceConstraintSet(unifyCons); unifyCons.map( y + * -> { if ((y.getLhsType() instanceof PlaceholderType) && (y.getRhsType() + * instanceof PlaceholderType)) { if + * (((PlaceholderType)y.getLhsType()).getVariance() != 0 && + * ((PlaceholderType)y.getRhsType()).getVariance() == 0) { + * ((PlaceholderType)y.getRhsType()).setVariance(((PlaceholderType)y.getLhsType( + * )).getVariance()); } if (((PlaceholderType)y.getLhsType()).getVariance() == 0 + * && ((PlaceholderType)y.getRhsType()).getVariance() != 0) { + * ((PlaceholderType)y.getLhsType()).setVariance(((PlaceholderType)y.getRhsType( + * )).getVariance()); } } return y; } ); } while + * (!varianceTPHold.equals(varianceTPH)); + */ + + // Set> result = unify.unifySequential(xConsSet, finiteClosure, + // logFile, log); + // Set> result = unify.unify(xConsSet, finiteClosure); List>> oderConstraints = unifyCons.getOderConstraints().stream().map(x -> { Set> ret = new HashSet<>(); for (Constraint y : x) { @@ -556,148 +603,177 @@ public class JavaTXCompiler { UnifyResultModel urm = new UnifyResultModel(cons, finiteClosure); UnifyResultListenerImpl li = new UnifyResultListenerImpl(); urm.addUnifyResultListener(li); - unify.unifyParallel(unifyCons.getUndConstraints(), oderConstraints, finiteClosure, logFile, log, urm, usedTasks); + unify.unifyParallel(unifyCons.getUndConstraints(), oderConstraints, finiteClosure, logFile, log, urm, + usedTasks); System.out.println("RESULT Final: " + li.getResults()); - logFile.write("RES_FINAL: " + li.getResults().toString()+"\n"); + logFile.write("RES_FINAL: " + li.getResults().toString() + "\n"); logFile.flush(); return li.getResults(); } /* UnifyResultModel End */ else { - //Set> result = unify.unify(unifyCons.getUndConstraints(), oderConstraints, finiteClosure, logFile, log, new UnifyResultModel(cons, finiteClosure)); - Set> result = unify.unifyOderConstraints(unifyCons.getUndConstraints(), oderConstraints, finiteClosure, logFile, log, new UnifyResultModel(cons, finiteClosure), usedTasks); + // Set> result = unify.unify(unifyCons.getUndConstraints(), + // oderConstraints, finiteClosure, logFile, log, new UnifyResultModel(cons, + // finiteClosure)); + Set> result = unify.unifyOderConstraints(unifyCons.getUndConstraints(), oderConstraints, + finiteClosure, logFile, log, new UnifyResultModel(cons, finiteClosure), usedTasks); System.out.println("RESULT: " + result); - logFile.write("RES: " + result.toString()+"\n"); + logFile.write("RES: " + result.toString() + "\n"); logFile.flush(); results.addAll(result); - - + results = results.stream().map(x -> { - Optional> res = new RuleSet().subst(x.stream().map(y -> { - if (y.getPairOp() == PairOperator.SMALLERDOTWC) y.setPairOp(PairOperator.EQUALSDOT); - return y; //alle Paare a <.? b erden durch a =. b ersetzt + Optional> res = new RuleSet().subst(x.stream().map(y -> { + if (y.getPairOp() == PairOperator.SMALLERDOTWC) + y.setPairOp(PairOperator.EQUALSDOT); + return y; // alle Paare a <.? b erden durch a =. b ersetzt }).collect(Collectors.toCollection(HashSet::new))); - if (res.isPresent()) {//wenn subst ein Erg liefert wurde was veraendert + if (res.isPresent()) {// wenn subst ein Erg liefert wurde was veraendert return new TypeUnifyTask().applyTypeUnificationRules(res.get(), finiteClosure); - } - else return x; //wenn nichts veraendert wurde wird x zurueckgegeben + } else + return x; // wenn nichts veraendert wurde wird x zurueckgegeben }).collect(Collectors.toCollection(HashSet::new)); System.out.println("RESULT Final: " + results); - logFile.write("RES_FINAL: " + results.toString()+"\n"); + logFile.write("RES_FINAL: " + results.toString() + "\n"); logFile.flush(); logFile.write("PLACEHOLDERS: " + PlaceholderType.EXISTING_PLACEHOLDERS); logFile.flush(); - }} - catch (IOException e) { - System.err.println("kein LogFile"); } - return results.stream().map((unifyPairs -> - new ResultSet(UnifyTypeFactory.convert(unifyPairs, Pair.generateTPHMap(cons))))).collect(Collectors.toList()); - } - + } catch (IOException e) { + System.err.println("kein LogFile"); + } + return results.stream() + .map((unifyPairs -> new ResultSet(UnifyTypeFactory.convert(unifyPairs, Pair.generateTPHMap(cons))))) + .collect(Collectors.toList()); + } - /** - * Vererbt alle Variancen bei Paaren (a <. theta) oder (Theta <. a) - * wenn a eine Variance !=0 hat auf alle Typvariablen in Theta. - * @param eq The set of constraints + * Vererbt alle Variancen bei Paaren (a <. theta) oder (Theta <. a) wenn a eine + * Variance !=0 hat auf alle Typvariablen in Theta. + * + * */ private Set varianceInheritanceConstraintSet(ConstraintSet cons) { Set eq = cons.getAll(); Set usedTPH = new HashSet<>(); - Set phSet = eq.stream().map(x -> { + Set phSet = eq.stream().map(x -> { Set pair = new HashSet<>(); - if (x.getLhsType() instanceof PlaceholderType) pair.add((PlaceholderType)x.getLhsType()); - if (x.getRhsType() instanceof PlaceholderType) pair.add((PlaceholderType)x.getRhsType()); + if (x.getLhsType() instanceof PlaceholderType) + pair.add((PlaceholderType) x.getLhsType()); + if (x.getRhsType() instanceof PlaceholderType) + pair.add((PlaceholderType) x.getRhsType()); return pair; - }).reduce(new HashSet<>(), (a,b) -> { a.addAll(b); return a;} , (c,d) -> { c.addAll(d); return c;}); - - ArrayList phSetVariance = new ArrayList<>(phSet); + }).reduce(new HashSet<>(), (a, b) -> { + a.addAll(b); + return a; + }, (c, d) -> { + c.addAll(d); + return c; + }); + + ArrayList phSetVariance = new ArrayList<>(phSet); phSetVariance.removeIf(x -> (x.getVariance() == 0)); - while(!phSetVariance.isEmpty()) { + while (!phSetVariance.isEmpty()) { PlaceholderType a = phSetVariance.remove(0); usedTPH.add(a); - //HashMap ht = new HashMap<>(); - //ht.put(a, a.getVariance()); - //ConstraintSet eq1 = cons; - //eq1.removeIf(x -> !(x.getLhsType() instanceof PlaceholderType && ((PlaceholderType)x.getLhsType()).equals(a))); - //durch if-Abfrage im foreach geloest - cons.forEach(x -> { - if (x.getLhsType() instanceof PlaceholderType && ((PlaceholderType)x.getLhsType()).equals(a)) { + // HashMap ht = new HashMap<>(); + // ht.put(a, a.getVariance()); + // ConstraintSet eq1 = cons; + // eq1.removeIf(x -> !(x.getLhsType() instanceof PlaceholderType && + // ((PlaceholderType)x.getLhsType()).equals(a))); + // durch if-Abfrage im foreach geloest + cons.forEach(x -> { + if (x.getLhsType() instanceof PlaceholderType && ((PlaceholderType) x.getLhsType()).equals(a)) { x.getRhsType().accept(new distributeVariance(), a.getVariance()); } - }); - //` eq1 = new HashSet<>(eq); - //eq1.removeIf(x -> !(x.getRhsType() instanceof PlaceholderType && ((PlaceholderType)x.getRhsType()).equals(a))); - //durch if-Abfrage im foreach geloest + }); + // ` eq1 = new HashSet<>(eq); + // eq1.removeIf(x -> !(x.getRhsType() instanceof PlaceholderType && + // ((PlaceholderType)x.getRhsType()).equals(a))); + // durch if-Abfrage im foreach geloest cons.forEach(x -> { - if (x.getRhsType() instanceof PlaceholderType && ((PlaceholderType)x.getRhsType()).equals(a)) { + if (x.getRhsType() instanceof PlaceholderType && ((PlaceholderType) x.getRhsType()).equals(a)) { x.getLhsType().accept(new distributeVariance(), a.getVariance()); - } - }); - phSetVariance = new ArrayList<>(phSet); //macht vermutlich keinen Sinn PL 2018-10-18, doch, es koennen neue TPHs mit Variancen dazugekommen sein PL 2018-11-07 + } + }); + phSetVariance = new ArrayList<>(phSet); // macht vermutlich keinen Sinn PL 2018-10-18, doch, es koennen neue + // TPHs mit Variancen dazugekommen sein PL 2018-11-07 phSetVariance.removeIf(x -> (x.getVariance() == 0 || usedTPH.contains(x))); } return usedTPH; } + private SourceFile parse(File sourceFile) throws IOException, java.lang.ClassNotFoundException { + CompilationUnitContext tree = JavaTXParser.parse(sourceFile); + SyntaxTreeGenerator generator = new SyntaxTreeGenerator(environment.getRegistry(sourceFile), + new GenericsRegistry(null)); + SourceFile ret = generator.convert(tree, environment.packageCrawler); + return ret; + } - - - private SourceFile parse(File sourceFile) throws IOException, java.lang.ClassNotFoundException { - CompilationUnitContext tree = JavaTXParser.parse(sourceFile); - SyntaxTreeGenerator generator = new SyntaxTreeGenerator(environment.getRegistry(sourceFile), new GenericsRegistry(null)); - SourceFile ret = generator.convert(tree, environment.packageCrawler); - return ret; - } - - public List getSimplifyResultsForAllSourceFiles() throws ClassNotFoundException{ - List result = new ArrayList<>(); - for(File f : sourceFiles.keySet()) { + public List getGeneratedGenericResultsForAllSourceFiles() + throws ClassNotFoundException { + List result = new ArrayList<>(); + for (File f : sourceFiles.keySet()) { SourceFile sf = sourceFiles.get(f); List typeinferenceResult = this.typeInference(); - SimplifyResultFinder sResFinder = new SimplifyResultFinder(sf, typeinferenceResult); - SimplifyResultSourceFile simplifyResOfSF = sResFinder.findSimplifyRes(); + GeneratedGenericsFinder sResFinder = new GeneratedGenericsFinder(sf, typeinferenceResult); + GenericGenratorResultForSourceFile simplifyResOfSF = sResFinder.findGeneratedGenerics(); result.add(simplifyResOfSF); } - return result; - } - - public List getSimplifyResultsForAllSourceFiles(List typeinferenceResult) throws ClassNotFoundException{ - List result = new ArrayList<>(); - for(File f : sourceFiles.keySet()) { + return result; + } + + public List getGeneratedGenericResultsForAllSourceFiles( + List typeinferenceResult) throws ClassNotFoundException { + List result = new ArrayList<>(); + for (File f : sourceFiles.keySet()) { SourceFile sf = sourceFiles.get(f); - SimplifyResultFinder sResFinder = new SimplifyResultFinder(sf, typeinferenceResult); - SimplifyResultSourceFile simplifyResOfSF = sResFinder.findSimplifyRes(); + GeneratedGenericsFinder sResFinder = new GeneratedGenericsFinder(sf, typeinferenceResult); + GenericGenratorResultForSourceFile simplifyResOfSF = sResFinder.findGeneratedGenerics(); result.add(simplifyResOfSF); } - return result; - } - - // um pfad erweitern - public void generateBytecode(String path) throws ClassNotFoundException, IOException, BytecodeGeneratorError { - for(File f : sourceFiles.keySet()) { - HashMap classFiles = new HashMap<>(); - SourceFile sf = sourceFiles.get(f); - List typeinferenceResult = this.typeInference(); - List simplifyResultsForAllSourceFiles = getSimplifyResultsForAllSourceFiles(typeinferenceResult); - BytecodeGen bytecodeGen = new BytecodeGen(classFiles,typeinferenceResult,simplifyResultsForAllSourceFiles,sf,path); - bytecodeGen.visit(sf); - this.writeClassFile(bytecodeGen.getClassFiles(), path); - } - } + return result; + } + + // um pfad erweitern + public void generateBytecode(String path) throws ClassNotFoundException, IOException, BytecodeGeneratorError { + List typeinferenceResult = this.typeInference(); + List simplifyResultsForAllSourceFiles = getGeneratedGenericResultsForAllSourceFiles( + typeinferenceResult); + generateBytecode(path, typeinferenceResult, simplifyResultsForAllSourceFiles); + } + + /** + * @param path + * @param typeinferenceResult + * @param simplifyResultsForAllSourceFiles + * @throws IOException + */ + public void generateBytecode(String path, List typeinferenceResult, + List simplifyResultsForAllSourceFiles) throws IOException { + for (File f : sourceFiles.keySet()) { + HashMap classFiles = new HashMap<>(); + SourceFile sf = sourceFiles.get(f); + BytecodeGen bytecodeGen = new BytecodeGen(classFiles, typeinferenceResult, simplifyResultsForAllSourceFiles, + sf, path); + bytecodeGen.visit(sf); + writeClassFile(bytecodeGen.getClassFiles(), path); + } + } private void writeClassFile(HashMap classFiles, String path) throws IOException { FileOutputStream output; - for(String name : classFiles.keySet()) { + for (String name : classFiles.keySet()) { byte[] bytecode = classFiles.get(name); - System.out.println("generating "+name+ ".class file ..."); - //output = new FileOutputStream(new File(System.getProperty("user.dir") + "/testBytecode/generatedBC/" +name+".class")); - output = new FileOutputStream(new File(path +name+".class")); + System.out.println("generating " + name + ".class file ..."); + // output = new FileOutputStream(new File(System.getProperty("user.dir") + + // "/testBytecode/generatedBC/" +name+".class")); + output = new FileOutputStream(new File(path + name + ".class")); output.write(bytecode); output.close(); - System.out.println(name+".class file generated"); + System.out.println(name + ".class file generated"); } } - + } diff --git a/src/test/java/bytecode/BinaryTest.java b/src/test/java/bytecode/BinaryTest.java index aad81def..b2b5d165 100644 --- a/src/test/java/bytecode/BinaryTest.java +++ b/src/test/java/bytecode/BinaryTest.java @@ -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); } } diff --git a/src/test/java/bytecode/FacTest.java b/src/test/java/bytecode/FacTest.java index fcc45ee2..12525eda 100644 --- a/src/test/java/bytecode/FacTest.java +++ b/src/test/java/bytecode/FacTest.java @@ -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)); } } diff --git a/src/test/java/bytecode/FacultyTest.java b/src/test/java/bytecode/FacultyTest.java index 44a0e1c5..2caffa8b 100644 --- a/src/test/java/bytecode/FacultyTest.java +++ b/src/test/java/bytecode/FacultyTest.java @@ -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); } diff --git a/src/test/java/bytecode/FieldTphConsMethTest.java b/src/test/java/bytecode/FieldTphConsMethTest.java index 4ef61617..9f01a3d3 100644 --- a/src/test/java/bytecode/FieldTphConsMethTest.java +++ b/src/test/java/bytecode/FieldTphConsMethTest.java @@ -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)}); diff --git a/src/test/java/bytecode/IdTest.java b/src/test/java/bytecode/IdTest.java index d8392e55..02ff1592 100644 --- a/src/test/java/bytecode/IdTest.java +++ b/src/test/java/bytecode/IdTest.java @@ -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 { diff --git a/src/test/java/bytecode/LambdaTest.java b/src/test/java/bytecode/LambdaTest.java index 5428b333..f75cd7f8 100644 --- a/src/test/java/bytecode/LambdaTest.java +++ b/src/test/java/bytecode/LambdaTest.java @@ -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); } diff --git a/src/test/java/bytecode/MatrixOpTest.java b/src/test/java/bytecode/MatrixOpTest.java index ea906853..389280ab 100644 --- a/src/test/java/bytecode/MatrixOpTest.java +++ b/src/test/java/bytecode/MatrixOpTest.java @@ -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> vv = new Vector>(); - Vector v1 = new Vector (); - v1.addElement(2); - v1.addElement(2); - Vector v2 = new Vector (); - 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 v1 = new Vector(); + v1.addElement(2); + v1.addElement(2); + Vector v2 = new Vector(); + v2.addElement(3); + v2.addElement(3); + //Matrix m1 = new Matrix(); + //m1.addElement(v1); + //m1.addElement(v2); + vv.addElement(v1); + vv.addElement(v2); - Vector> vv1 = new Vector>(); - Vector v3 = new Vector (); - v3.addElement(2); - v3.addElement(2); - Vector v4 = new Vector (); - 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> vv1 = new Vector>(); + Vector v3 = new Vector(); + v3.addElement(2); + v3.addElement(2); + Vector v4 = new Vector(); + 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> res = new Vector>(); - Vector v5 = new Vector (); - v5.addElement(10); - v5.addElement(10); - Vector v6 = new Vector (); - 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> res = new Vector>(); + Vector v5 = new Vector(); + v5.addElement(10); + v5.addElement(10); + Vector v6 = new Vector(); + 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); + } } diff --git a/src/test/java/bytecode/MatrixTest.java b/src/test/java/bytecode/MatrixTest.java index c5dae3df..ce356ece 100755 --- a/src/test/java/bytecode/MatrixTest.java +++ b/src/test/java/bytecode/MatrixTest.java @@ -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); - } } diff --git a/src/test/java/bytecode/OLTest.java b/src/test/java/bytecode/OLTest.java index e438e7f9..2b9ea40b 100644 --- a/src/test/java/bytecode/OLTest.java +++ b/src/test/java/bytecode/OLTest.java @@ -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 typeinferenceResult = compiler.typeInference(); + List 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 diff --git a/src/test/java/bytecode/OpTest.java b/src/test/java/bytecode/OpTest.java index eeef179b..43d2cc97 100644 --- a/src/test/java/bytecode/OpTest.java +++ b/src/test/java/bytecode/OpTest.java @@ -54,7 +54,7 @@ public class OpTest { Integer result = (Integer) m.invoke(instanceOfClass, 7,3); - assertEquals(10, result); + assertEquals(new Integer(10), result); } diff --git a/src/test/java/bytecode/PostIncTest.java b/src/test/java/bytecode/PostIncTest.java index 902fe221..6c11d5cd 100644 --- a/src/test/java/bytecode/PostIncTest.java +++ b/src/test/java/bytecode/PostIncTest.java @@ -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); } } diff --git a/src/test/java/bytecode/PreIncTest.java b/src/test/java/bytecode/PreIncTest.java index ac4e2b55..74982597 100644 --- a/src/test/java/bytecode/PreIncTest.java +++ b/src/test/java/bytecode/PreIncTest.java @@ -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); } } diff --git a/src/test/java/bytecode/TphTest.java b/src/test/java/bytecode/TphTest.java index 45bb698a..7fa8df48 100644 --- a/src/test/java/bytecode/TphTest.java +++ b/src/test/java/bytecode/TphTest.java @@ -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 diff --git a/src/test/java/bytecode/WhileTest.java b/src/test/java/bytecode/WhileTest.java index f18577d7..c266d076 100644 --- a/src/test/java/bytecode/WhileTest.java +++ b/src/test/java/bytecode/WhileTest.java @@ -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); } } diff --git a/src/test/resources/bytecode/javFiles/Id.jav b/src/test/resources/bytecode/javFiles/Id.jav index 081832aa..03cf2a09 100644 --- a/src/test/resources/bytecode/javFiles/Id.jav +++ b/src/test/resources/bytecode/javFiles/Id.jav @@ -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); + } } diff --git a/src/test/resources/bytecode/javFiles/SimpleCycle.jav b/src/test/resources/bytecode/javFiles/SimpleCycle.jav index 99d6e499..8e19ea41 100644 --- a/src/test/resources/bytecode/javFiles/SimpleCycle.jav +++ b/src/test/resources/bytecode/javFiles/SimpleCycle.jav @@ -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; */ } diff --git a/src/test/resources/bytecode/javFiles/Tph.jav b/src/test/resources/bytecode/javFiles/Tph.jav index 4a49ac46..9faa570c 100644 --- a/src/test/resources/bytecode/javFiles/Tph.jav +++ b/src/test/resources/bytecode/javFiles/Tph.jav @@ -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){