diff --git a/pom.xml b/pom.xml index ca4bae64..8fe3f636 100644 --- a/pom.xml +++ b/pom.xml @@ -17,10 +17,11 @@ http://maven.apache.org/maven-v4_0_0.xsd"> 4.11 test + org.antlr antlr4 - 4.8-1 + 4.11.1 commons-io @@ -60,7 +61,7 @@ http://maven.apache.org/maven-v4_0_0.xsd"> org.antlr antlr4-maven-plugin - 4.8-1 + 4.11.1 antlr diff --git a/resources/AllgemeinTest/VectorNotObject.jav b/resources/AllgemeinTest/VectorNotObject.jav new file mode 100644 index 00000000..d8ea900b --- /dev/null +++ b/resources/AllgemeinTest/VectorNotObject.jav @@ -0,0 +1,9 @@ +import java.util.Vector; + +class VectorNotObject { + + vectorAddAll(v1, v2) { + v1.addAll(v2); + return v1; + } + } diff --git a/resources/AllgemeinTest/WildcardCaptureConversionTest.jav b/resources/AllgemeinTest/WildcardCaptureConversionTest.jav new file mode 100644 index 00000000..59016f7a --- /dev/null +++ b/resources/AllgemeinTest/WildcardCaptureConversionTest.jav @@ -0,0 +1,16 @@ +import java.util.Vector; +import java.lang.Integer; +import java.lang.String; + +class WildcardCaptureConversionTest { + + m(x, y ,z) { + x = new Vector(); + y = new Vector(); + x.add(1); + y.add("2"); + //Integer i = x.elementAt(0); + //String s = y.elementAt(0); + return z.vectorAddAll(x, y); + } +} \ No newline at end of file diff --git a/resources/bytecode/javFiles/Box.jav b/resources/bytecode/javFiles/Box.jav new file mode 100644 index 00000000..4859d611 --- /dev/null +++ b/resources/bytecode/javFiles/Box.jav @@ -0,0 +1,7 @@ +class B { } +class Box_Main extends B { + m(b) { + b.m(new Box_Main()); + b.m(new B()); + } +} diff --git a/resources/bytecode/javFiles/Box.java b/resources/bytecode/javFiles/Box.java new file mode 100644 index 00000000..581e7256 --- /dev/null +++ b/resources/bytecode/javFiles/Box.java @@ -0,0 +1,3 @@ +class Box { + void m(A a) { } +} \ No newline at end of file diff --git a/resources/bytecode/javFiles/Generics2.jav b/resources/bytecode/javFiles/Generics2.jav index 52d5caa2..762890bd 100644 --- a/resources/bytecode/javFiles/Generics2.jav +++ b/resources/bytecode/javFiles/Generics2.jav @@ -1,3 +1,6 @@ +import java.lang.String; +import java.lang.Integer; + class Generics2{ B m1(B b){ return b; diff --git a/resources/bytecode/javFiles/Generics3.jav b/resources/bytecode/javFiles/Generics3.jav new file mode 100644 index 00000000..fb354d43 --- /dev/null +++ b/resources/bytecode/javFiles/Generics3.jav @@ -0,0 +1,7 @@ +import java.lang.String; +import java.lang.Integer; +import java.util.List; + +class Generics3> { + +} \ No newline at end of file diff --git a/resources/bytecode/javFiles/Generics4.jav b/resources/bytecode/javFiles/Generics4.jav new file mode 100644 index 00000000..50b0b3e2 --- /dev/null +++ b/resources/bytecode/javFiles/Generics4.jav @@ -0,0 +1,12 @@ +import java.lang.String; +import java.lang.Integer; + +class Generics4 { + C m1(C b){ + return b; + } + + m2(x) { + return m1(x); + } +} \ No newline at end of file diff --git a/resources/bytecode/javFiles/Inf.jav b/resources/bytecode/javFiles/Inf.jav index 788fca8d..60029949 100644 --- a/resources/bytecode/javFiles/Inf.jav +++ b/resources/bytecode/javFiles/Inf.jav @@ -10,6 +10,10 @@ public class Inf { w=y; y=a; b=a; + var c; + var d; + c = v; + d = v; } } @@ -25,21 +29,27 @@ TPH M m(TPH N x, TPH O y, TPH P a)({ (w)::TPH S = (y)::TPH O; (y)::TPH O = (a)::TPH P; (b)::TPH T = (a)::TPH P; + TPH U c; + TPH V d; + (c)::TPH U = (v)::TPH R; + (d)::TPH V = (v)::TPH R; return; - })::TPH U +})::TPH W Inf()({ super(()); - })::TPH X + })::TPH Z } -// v::R w::S +// c::U d::V +// \ / +// v::R w::S // \ / // z::Q y::O b::T // \ / \ / // x::N a::P -RESULT Final: [[(TPH O < TPH S), (TPH P < TPH O), (TPH O < TPH R), (TPH P < TPH T), (TPH M = void), (TPH N < TPH O), (TPH N < TPH Q)]] +RESULT Final: [[(TPH N < TPH O), (TPH R < TPH V), (TPH N < TPH Q), (TPH P < TPH O), (TPH R < TPH U), (TPH M = void), (TPH O < TPH S), (TPH O < TPH R), (TPH P < TPH T)]] Simplified constraints: [(TPH O < TPH S), (TPH P < TPH O), (TPH O < TPH R), (TPH P < TPH T), (TPH N < TPH O), (TPH N < TPH Q)] m: [(TPH DDV = java.lang.Object), (TPH DDX = java.lang.Object), (TPH DDX < TPH DDV), (TPH N < TPH DDX), (TPH P < TPH DDX)] Class Inf: [] diff --git a/resources/bytecode/javFiles/OLFun.jav b/resources/bytecode/javFiles/OLFun.jav index adf8c6a8..50d30b73 100644 --- a/resources/bytecode/javFiles/OLFun.jav +++ b/resources/bytecode/javFiles/OLFun.jav @@ -9,5 +9,11 @@ public class OLFun { //f = x -> {return x + x;}; m(f, x) { x = f.apply(x+x); + return x; + } + + m2(y) { + m(x -> x * 2, y); + return; } } \ No newline at end of file diff --git a/resources/bytecode/javFiles/OLFun2.jav b/resources/bytecode/javFiles/OLFun2.jav index 406c0d98..6b6f38ac 100644 --- a/resources/bytecode/javFiles/OLFun2.jav +++ b/resources/bytecode/javFiles/OLFun2.jav @@ -8,6 +8,6 @@ public class OLFun2 { x; m(f){ - x = f.apply(x + x) + x = f.apply(x + x); } } \ No newline at end of file diff --git a/resources/bytecode/javFiles/SimpleCycle.jav b/resources/bytecode/javFiles/SimpleCycle.jav index 2f45aa18..92f505b5 100644 --- a/resources/bytecode/javFiles/SimpleCycle.jav +++ b/resources/bytecode/javFiles/SimpleCycle.jav @@ -1,6 +1,6 @@ public class SimpleCycle { - m(a,b,d){ + m(){ var g; var h; g = h; diff --git a/resources/bytecode/javFiles/VectorAdd.jav b/resources/bytecode/javFiles/VectorAdd.jav index d5e50157..2ad73aa9 100644 --- a/resources/bytecode/javFiles/VectorAdd.jav +++ b/resources/bytecode/javFiles/VectorAdd.jav @@ -1,6 +1,6 @@ import java.util.Vector; import java.lang.Integer; - +import java.lang.String; public class VectorAdd { vectorAdd(v1, v2) { @@ -13,4 +13,14 @@ public class VectorAdd { } return erg; } + + m(x, y, z) { + x = new Vector(); + y = new Vector(); + x.add(1); + y.add("2"); + //Integer i = x.elementAt(0); + //String s = y.elementAt(0); + return z.addAll(x); + } } diff --git a/resources/insertGenericsJav/TestTwoArgs.jav b/resources/insertGenericsJav/TestTwoArgs.jav index 84631151..b4754fe4 100644 --- a/resources/insertGenericsJav/TestTwoArgs.jav +++ b/resources/insertGenericsJav/TestTwoArgs.jav @@ -1,22 +1,29 @@ -public class TestTwoArgs { +public class TestTwoArgs // +{ + //AS a; + //AN -> AN id(b) { var c = b; return c; } + //T -> AS setA(x) { a = x; return a; } - + + //(AG,Z) -> AG m(x,y) { x = id(y); return x; } + // (AI, AH) -> AG main(x,y) { return m(id(x),setA(y)); } -} \ No newline at end of file +} + diff --git a/src/main/java/de/dhbwstuttgart/bytecode/AStatement.java b/src/main/java/de/dhbwstuttgart/bytecode/AStatement.java deleted file mode 100644 index 5c28bf43..00000000 --- a/src/main/java/de/dhbwstuttgart/bytecode/AStatement.java +++ /dev/null @@ -1,30 +0,0 @@ -package de.dhbwstuttgart.bytecode; - -import org.objectweb.asm.Label; -import org.objectweb.asm.MethodVisitor; -import org.objectweb.asm.Opcodes; - -import de.dhbwstuttgart.syntaxtree.statement.BinaryExpr; -import de.dhbwstuttgart.syntaxtree.statement.Expression; - -public abstract class AStatement implements IStatement { - protected Expression expr; - - public AStatement(Expression expr) { - this.expr = expr; - } - - @Override - public boolean isExprBinary() { - return (expr instanceof BinaryExpr); - } - - @Override - public void genBCForRelOp(MethodVisitor mv,Label branchLabel, Label endLabel, BytecodeGenMethod bytecodeGenMethod) { - mv.visitInsn(Opcodes.ICONST_1); - mv.visitJumpInsn(Opcodes.GOTO, endLabel); - mv.visitLabel(branchLabel); - mv.visitInsn(Opcodes.ICONST_0); - mv.visitLabel(endLabel); - } -} diff --git a/src/main/java/de/dhbwstuttgart/bytecode/ArgumentExpr.java b/src/main/java/de/dhbwstuttgart/bytecode/ArgumentExpr.java deleted file mode 100644 index b396e8d1..00000000 --- a/src/main/java/de/dhbwstuttgart/bytecode/ArgumentExpr.java +++ /dev/null @@ -1,11 +0,0 @@ -package de.dhbwstuttgart.bytecode; - -import de.dhbwstuttgart.syntaxtree.statement.Expression; - -public class ArgumentExpr extends AStatement { - - public ArgumentExpr(Expression expr) { - super(expr); - } - -} diff --git a/src/main/java/de/dhbwstuttgart/bytecode/ArgumentVisitor.java b/src/main/java/de/dhbwstuttgart/bytecode/ArgumentVisitor.java deleted file mode 100644 index 268e53b5..00000000 --- a/src/main/java/de/dhbwstuttgart/bytecode/ArgumentVisitor.java +++ /dev/null @@ -1,258 +0,0 @@ -package de.dhbwstuttgart.bytecode; - -import java.util.List; - -import de.dhbwstuttgart.parser.SyntaxTreeGenerator.AssignToLocal; -import de.dhbwstuttgart.syntaxtree.StatementVisitor; -import de.dhbwstuttgart.syntaxtree.statement.ArgumentList; -import de.dhbwstuttgart.syntaxtree.statement.Assign; -import de.dhbwstuttgart.syntaxtree.statement.AssignToField; -import de.dhbwstuttgart.syntaxtree.statement.BinaryExpr; -import de.dhbwstuttgart.syntaxtree.statement.Block; -import de.dhbwstuttgart.syntaxtree.statement.CastExpr; -import de.dhbwstuttgart.syntaxtree.statement.DoStmt; -import de.dhbwstuttgart.syntaxtree.statement.EmptyStmt; -import de.dhbwstuttgart.syntaxtree.statement.ExpressionReceiver; -import de.dhbwstuttgart.syntaxtree.statement.FieldVar; -import de.dhbwstuttgart.syntaxtree.statement.ForStmt; -import de.dhbwstuttgart.syntaxtree.statement.IfStmt; -import de.dhbwstuttgart.syntaxtree.statement.InstanceOf; -import de.dhbwstuttgart.syntaxtree.statement.LambdaExpression; -import de.dhbwstuttgart.syntaxtree.statement.Literal; -import de.dhbwstuttgart.syntaxtree.statement.LocalVar; -import de.dhbwstuttgart.syntaxtree.statement.LocalVarDecl; -import de.dhbwstuttgart.syntaxtree.statement.MethodCall; -import de.dhbwstuttgart.syntaxtree.statement.NewArray; -import de.dhbwstuttgart.syntaxtree.statement.NewClass; -import de.dhbwstuttgart.syntaxtree.statement.Return; -import de.dhbwstuttgart.syntaxtree.statement.ReturnVoid; -import de.dhbwstuttgart.syntaxtree.statement.StaticClassName; -import de.dhbwstuttgart.syntaxtree.statement.Super; -import de.dhbwstuttgart.syntaxtree.statement.SuperCall; -import de.dhbwstuttgart.syntaxtree.statement.This; -import de.dhbwstuttgart.syntaxtree.statement.UnaryExpr; -import de.dhbwstuttgart.syntaxtree.statement.WhileStmt; - -public class ArgumentVisitor implements StatementVisitor { - private List argListMethCall; - private BytecodeGenMethod bytecodeGenMethod; - - public ArgumentVisitor(List argListMethCall, BytecodeGenMethod bytecodeGenMethod) { - this.argListMethCall = argListMethCall; - this.bytecodeGenMethod = bytecodeGenMethod; - } - - @Override - public void visit(ArgumentList argumentList) { - // TODO Auto-generated method stub - - } - - @Override - public void visit(LambdaExpression lambdaExpression) { - lambdaExpression.accept(bytecodeGenMethod); - // Zieltype des Lambas ist Funktionale Interface - // kann nie primitiv sein => un-/boxing wird hier nicht gebraucht - argListMethCall.remove(0); - } - - @Override - public void visit(Assign assign) { - assign.accept(bytecodeGenMethod); - - if(argListMethCall.get(0)) - bytecodeGenMethod.doUnboxing(bytecodeGenMethod.getResolver().getResolvedType(assign.getType())); - argListMethCall.remove(0); - } - - @Override - public void visit(BinaryExpr binary) { - binary.accept(bytecodeGenMethod); - - if(argListMethCall.get(0)) { - bytecodeGenMethod.doUnboxing(bytecodeGenMethod.getResolver().getResolvedType(binary.getType())); - } else { - bytecodeGenMethod.doBoxing(bytecodeGenMethod.getResolver().getResolvedType(binary.getType())); - } - argListMethCall.remove(0); - } - - @Override - public void visit(Block block) { - // TODO Auto-generated method stub - - } - - @Override - public void visit(CastExpr castExpr) { - castExpr.accept(bytecodeGenMethod); - - if(argListMethCall.get(0)) - bytecodeGenMethod.doUnboxing(bytecodeGenMethod.getResolver().getResolvedType(castExpr.getType())); - argListMethCall.remove(0); - } - - @Override - public void visit(EmptyStmt emptyStmt) { - // TODO Auto-generated method stub - - } - - @Override - public void visit(FieldVar fieldVar) { - fieldVar.accept(bytecodeGenMethod); - - if(argListMethCall.get(0)) - bytecodeGenMethod.doUnboxing(bytecodeGenMethod.getResolver().getResolvedType(fieldVar.getType())); - argListMethCall.remove(0); - } - - @Override - public void visit(ForStmt forStmt) { - // TODO Auto-generated method stub - - } - - @Override - public void visit(IfStmt ifStmt) { - // TODO Auto-generated method stub - - } - - @Override - public void visit(InstanceOf instanceOf) { - instanceOf.accept(bytecodeGenMethod); - - if(argListMethCall.get(0)) - bytecodeGenMethod.doUnboxing(bytecodeGenMethod.getResolver().getResolvedType(instanceOf.getType())); - argListMethCall.remove(0); - } - - @Override - public void visit(LocalVar localVar) { - localVar.accept(bytecodeGenMethod); - if(!bytecodeGenMethod.isBinaryExp) { - if(argListMethCall.get(0)) - bytecodeGenMethod.doUnboxing(bytecodeGenMethod.getResolver().getResolvedType(localVar.getType())); - } - argListMethCall.remove(0); - } - - @Override - public void visit(LocalVarDecl localVarDecl) { - // TODO Auto-generated method stub - - } - - @Override - public void visit(MethodCall methodCall) { - methodCall.accept(bytecodeGenMethod); - - if(argListMethCall.get(0)) - bytecodeGenMethod.doUnboxing(bytecodeGenMethod.getResolver().getResolvedType(methodCall.getType())); - argListMethCall.remove(0); - } - - @Override - public void visit(NewClass methodCall) { - methodCall.accept(bytecodeGenMethod); - - if(argListMethCall.get(0)) - bytecodeGenMethod.doUnboxing(bytecodeGenMethod.getResolver().getResolvedType(methodCall.getType())); - argListMethCall.remove(0); - } - - @Override - public void visit(NewArray newArray) { - // TODO Auto-generated method stub - - } - - @Override - public void visit(Return aReturn) { - // TODO Auto-generated method stub - - } - - @Override - public void visit(ReturnVoid aReturn) { - // TODO Auto-generated method stub - - } - - @Override - public void visit(StaticClassName staticClassName) { - // TODO Auto-generated method stub - - } - - @Override - public void visit(Super aSuper) { - // TODO Auto-generated method stub - - } - - @Override - public void visit(This aThis) { - aThis.accept(bytecodeGenMethod); - - if(argListMethCall.get(0)) - bytecodeGenMethod.doUnboxing(bytecodeGenMethod.getResolver().getResolvedType(aThis.getType())); - argListMethCall.remove(0); - } - - @Override - public void visit(WhileStmt whileStmt) { - // TODO Auto-generated method stub - - } - - @Override - public void visit(DoStmt whileStmt) { - // TODO Auto-generated method stub - - } - - @Override - public void visit(AssignToField assignLeftSide) { - // TODO Auto-generated method stub - - } - - @Override - public void visit(AssignToLocal assignLeftSide) { - // TODO Auto-generated method stub - - } - - @Override - public void visit(SuperCall superCall) { - // TODO Auto-generated method stub - - } - - @Override - public void visit(ExpressionReceiver expressionReceiver) { - // TODO Auto-generated method stub - - } - - @Override - public void visit(UnaryExpr unaryExpr) { - unaryExpr.accept(bytecodeGenMethod); - - if(argListMethCall.get(0)) - bytecodeGenMethod.doUnboxing(bytecodeGenMethod.getResolver().getResolvedType(unaryExpr.getType())); - argListMethCall.remove(0); - } - - @Override - public void visit(Literal literal) { - literal.accept(bytecodeGenMethod); - - if(argListMethCall.get(0)) - bytecodeGenMethod.doUnboxing(bytecodeGenMethod.getResolver().getResolvedType(literal.getType())); - argListMethCall.remove(0); - } - -} diff --git a/src/main/java/de/dhbwstuttgart/bytecode/AssignStmt.java b/src/main/java/de/dhbwstuttgart/bytecode/AssignStmt.java deleted file mode 100644 index 366c450a..00000000 --- a/src/main/java/de/dhbwstuttgart/bytecode/AssignStmt.java +++ /dev/null @@ -1,11 +0,0 @@ -package de.dhbwstuttgart.bytecode; - -import de.dhbwstuttgart.syntaxtree.statement.Expression; - -public class AssignStmt extends AStatement { - - public AssignStmt(Expression rightSide) { - super(rightSide); - } - -} diff --git a/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGen.java b/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGen.java deleted file mode 100644 index 04f408af..00000000 --- a/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGen.java +++ /dev/null @@ -1,630 +0,0 @@ -package de.dhbwstuttgart.bytecode; - -import java.io.File; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Optional; - -import de.dhbwstuttgart.parser.scope.JavaClassName; -import org.objectweb.asm.ClassWriter; -import org.objectweb.asm.FieldVisitor; -import org.objectweb.asm.MethodVisitor; -import org.objectweb.asm.Opcodes; -import org.objectweb.asm.Type; - -import de.dhbwstuttgart.bytecode.Exception.BytecodeGeneratorError; -import de.dhbwstuttgart.bytecode.descriptor.DescriptorToString; -import de.dhbwstuttgart.bytecode.descriptor.TypeToDescriptor; -import de.dhbwstuttgart.bytecode.signature.Signature; -import de.dhbwstuttgart.bytecode.signature.TypeToSignature; -import de.dhbwstuttgart.bytecode.signature.TypeToString; -import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.GenericGenratorResultForSourceFile; -import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.GenericsGeneratorResult; -import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.GenericsGeneratorResultForClass; -import de.dhbwstuttgart.bytecode.utilities.MethodUtility; -import de.dhbwstuttgart.bytecode.utilities.NormalConstructor; -import de.dhbwstuttgart.bytecode.utilities.NormalMethod; -import de.dhbwstuttgart.bytecode.utilities.Resolver; -import de.dhbwstuttgart.exceptions.NotImplementedException; -import de.dhbwstuttgart.parser.SyntaxTreeGenerator.AssignToLocal; -import de.dhbwstuttgart.syntaxtree.ASTVisitor; -import de.dhbwstuttgart.syntaxtree.ClassOrInterface; -import de.dhbwstuttgart.syntaxtree.Constructor; -import de.dhbwstuttgart.syntaxtree.Field; -import de.dhbwstuttgart.syntaxtree.FormalParameter; -import de.dhbwstuttgart.syntaxtree.GenericDeclarationList; -import de.dhbwstuttgart.syntaxtree.GenericTypeVar; -import de.dhbwstuttgart.syntaxtree.Method; -import de.dhbwstuttgart.syntaxtree.ParameterList; -import de.dhbwstuttgart.syntaxtree.SourceFile; -import de.dhbwstuttgart.syntaxtree.statement.ArgumentList; -import de.dhbwstuttgart.syntaxtree.statement.Assign; -import de.dhbwstuttgart.syntaxtree.statement.AssignToField; -import de.dhbwstuttgart.syntaxtree.statement.BinaryExpr; -import de.dhbwstuttgart.syntaxtree.statement.Block; -import de.dhbwstuttgart.syntaxtree.statement.CastExpr; -import de.dhbwstuttgart.syntaxtree.statement.DoStmt; -import de.dhbwstuttgart.syntaxtree.statement.EmptyStmt; -import de.dhbwstuttgart.syntaxtree.statement.ExpressionReceiver; -import de.dhbwstuttgart.syntaxtree.statement.FieldVar; -import de.dhbwstuttgart.syntaxtree.statement.ForStmt; -import de.dhbwstuttgart.syntaxtree.statement.IfStmt; -import de.dhbwstuttgart.syntaxtree.statement.InstanceOf; -import de.dhbwstuttgart.syntaxtree.statement.LambdaExpression; -import de.dhbwstuttgart.syntaxtree.statement.Literal; -import de.dhbwstuttgart.syntaxtree.statement.LocalVar; -import de.dhbwstuttgart.syntaxtree.statement.LocalVarDecl; -import de.dhbwstuttgart.syntaxtree.statement.MethodCall; -import de.dhbwstuttgart.syntaxtree.statement.NewArray; -import de.dhbwstuttgart.syntaxtree.statement.NewClass; -import de.dhbwstuttgart.syntaxtree.statement.Return; -import de.dhbwstuttgart.syntaxtree.statement.ReturnVoid; -import de.dhbwstuttgart.syntaxtree.statement.StaticClassName; -import de.dhbwstuttgart.syntaxtree.statement.Super; -import de.dhbwstuttgart.syntaxtree.statement.SuperCall; -import de.dhbwstuttgart.syntaxtree.statement.This; -import de.dhbwstuttgart.syntaxtree.statement.UnaryExpr; -import de.dhbwstuttgart.syntaxtree.statement.WhileStmt; -import de.dhbwstuttgart.syntaxtree.type.ExtendsWildcardType; -import de.dhbwstuttgart.syntaxtree.type.GenericRefType; -import de.dhbwstuttgart.syntaxtree.type.RefType; -import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric; -import de.dhbwstuttgart.syntaxtree.type.SuperWildcardType; -import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder; -import de.dhbwstuttgart.typeinference.result.ResultSet; - -public class BytecodeGen implements ASTVisitor { - - ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS); - - String type; - - public static RefTypeOrTPHOrWildcardOrGeneric THISTYPE = null; - private JavaClassName className; - private String pkgName; - private boolean isInterface; - private Collection listOfResultSets; - private ResultSet resultSet; - private SourceFile sf; - private File path; - - private Optional fieldInitializations; - - private int indexOfFirstParam = 0; - - private String superClass; - - private List tphsClass; - - // stores parameter, local vars and the next index on the local variable table, - // which use for aload_i, astore_i,... - HashMap paramsAndLocals = new HashMap<>(); - // stores generics and their bounds of class - HashMap genericsAndBounds = new HashMap<>(); - - private int constructorPos = 0; - - HashMap methodParamsAndTypes = new HashMap<>(); - byte[] bytecode; - HashMap classFiles; - - private final ArrayList methodNameAndParamsT = new ArrayList<>(); - private final ArrayList fieldNameAndParamsT = new ArrayList<>(); - - private final ArrayList fieldNameSignature = new ArrayList<>(); - - private List simplifyResultsForAllSourceFiles; - private GenericsGeneratorResultForClass generatedGenerics; - - private Resolver resolver; - private final ClassLoader classLoader; - - public BytecodeGen(HashMap classFiles, Collection listOfResultSets, List simplifyResultsForAllSourceFiles, SourceFile sf, - File path, ClassLoader classLoader) { - this.classFiles = classFiles; - this.listOfResultSets = listOfResultSets; - this.simplifyResultsForAllSourceFiles = simplifyResultsForAllSourceFiles; - this.sf = sf; - this.path = path; - this.pkgName = sf.getPkgName(); - this.classLoader = classLoader; - } - - @Override - public void visit(SourceFile sourceFile) { - for (ClassOrInterface cl : sourceFile.getClasses()) { - System.out.println("in Class: " + cl.getClassName().toString()); - BytecodeGen classGen = new BytecodeGen(classFiles, listOfResultSets, simplifyResultsForAllSourceFiles, sf, path, classLoader); - cl.accept(classGen); - classGen.writeClass(cl.getClassName()); - } - } - - /** - * Associates the bytecode of the class that was build with the classWriter - * {@link #cw} with the class name in the map {@link #classFiles} - * - * @param name name of the class with which the bytecode is to be associated - */ - private void writeClass(JavaClassName name) { - bytecode = cw.toByteArray(); - classFiles.put(name, bytecode); - - } - - public HashMap getClassFiles() { - return classFiles; - } - - @Override - public void visit(ClassOrInterface classOrInterface) { - - className = classOrInterface.getClassName(); - - cw.visitSource(className.getClassName() + ".jav", null); - - isInterface = (classOrInterface.getModifiers() & 512) == 512; - - int acc = isInterface ? classOrInterface.getModifiers() + Opcodes.ACC_ABSTRACT - : classOrInterface.getModifiers() + Opcodes.ACC_SUPER; - - fieldInitializations = classOrInterface.getfieldInitializations(); - -// resultSet = listOfResultSets.get(0); - boolean isVisited = false; - List listOfResultSetsList = new ArrayList<>(listOfResultSets); - generatedGenerics = simplifyResultsForAllSourceFiles.stream().map(sr->sr.getSimplifyResultsByName(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) { - - String sig = null; - /* - * if class has generics then creates signature Signature looks like: - * Superclass - */ - if (classOrInterface.getGenerics().iterator().hasNext() || classOrInterface.getSuperClass().acceptTV(new TypeToSignature()).contains("<") - || !generatedGenerics.getClassConstraints().isEmpty()) { - - List consClass = generatedGenerics.getClassConstraints(); -// - Signature signature = new Signature(classOrInterface, genericsAndBounds, consClass); - sig = signature.createSignatureForClassOrInterface(); - System.out.println("Signature: => " + sig); - } - - cw.visit(Opcodes.V1_8, acc, classOrInterface.getClassName().toString().replace(".", "/"), sig, - classOrInterface.getSuperClass().acceptTV(new TypeToDescriptor()), null); - - isVisited = true; - } - - for (Field f : classOrInterface.getFieldDecl()) { - f.accept(this); - } - - for (Constructor c : classOrInterface.getConstructors()) { - c.accept(this); - } - - for (Method m : classOrInterface.getMethods()) { - m.accept(this); - } - - } - - } - - @Override - public void visit(Constructor field) { - // stores generics and their bounds of method - HashMap genericsAndBoundsMethod = new HashMap<>(); - - field.getParameterList().accept(this); - - String id = MethodUtility.createID(resolver, field); - - if (methodNameAndParamsT.contains(id)) { - return; - } - methodNameAndParamsT.add(id); - System.out.println("Constructor: " + field.name + " , paramsType: " + id); - - String desc = null; - 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; - } - } - String sig = null; - if (hasGen) { - List constraints = generatedGenerics.getClassConstraints(); - Signature signature = new Signature(genericsAndBounds, - methodParamsAndTypes, resultSet, constraints); - - sig = signature.createSignatureForConstructor(field); - } - if (field.getParameterList().iterator().hasNext()) - System.out.println(field.getParameterList().iterator().next().getType().acceptTV(new TypeToDescriptor())); - - NormalConstructor constructor = new NormalConstructor(field, genericsAndBounds, hasGen); - desc = constructor.accept(new DescriptorToString(resultSet)); - System.out.println("Constructor: " + field.getName() + " Sig: " + sig + " Desc: " + desc); - MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "", desc, sig, null); - mv.visitCode(); - - Block block = fieldInitializations.get().block; - - constructorPos += 1; - - BytecodeGenMethod gen = new BytecodeGenMethod(className, superClass, resultSet, field, mv, paramsAndLocals, cw, - genericsAndBoundsMethod, genericsAndBounds, isInterface, classFiles, sf, path, block, constructorPos, classLoader); - if (!field.getParameterList().iterator().hasNext() - && !(field.block.statements.get(field.block.statements.size() - 1) instanceof ReturnVoid)) { - mv.visitInsn(Opcodes.RETURN); - } - mv.visitMaxs(0, 0); - mv.visitEnd(); - } - - @Override - public void visit(Method method) { - // TODO: check if the method is static => if static then the first param will be - // stored in pos 0 - // else it will be stored in pos 1 and this will be stored in pos 0 - String retType = resultSet.resolveType(method.getReturnType()).resolvedType.acceptTV(new TypeToDescriptor()); - - String id = MethodUtility.createID(resolver, method); - - if (methodNameAndParamsT.contains(id)) { - return; - } - 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() ? - int acc = isInterface ? Opcodes.ACC_ABSTRACT : method.modifier; - System.out.println(acc); - - /* 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; - } - } - } - // TODO: Test if the return-type or any of the parameter is a parameterized - // type. (VP) - // then create the descriptor with the new syntax. - - String sig = null; - /* - * method.getGenerics: <....> RT method(..) - */ - boolean hasGen = method.getGenerics().iterator().hasNext() || hasGenInParameterList; - /* if method has generics or return type is TPH, create signature */ - // zwite operand muss weggelassen werden - if (hasGen || resultSet.resolveType(method.getReturnType()).resolvedType.acceptTV(new TypeToString()) - .equals("TPH")) { - - List constraints = generatedGenerics.getMethodConstraintsByID(id); - List classConstraints = generatedGenerics.getClassConstraints(); - 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); - methDesc = meth.accept(new DescriptorToString(resultSet)); - - MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC + acc, method.getName(), methDesc, sig, null); - - mv.visitCode(); - BytecodeGenMethod gen = new BytecodeGenMethod(className, superClass, resultSet, method, mv, paramsAndLocals, cw, - genericsAndBoundsMethod, genericsAndBounds, isInterface, classFiles, sf, path, classLoader); - - mv.visitMaxs(0, 0); - mv.visitEnd(); - } - - @Override - public void visit(ParameterList formalParameters) { - paramsAndLocals = new HashMap<>(); - methodParamsAndTypes = new HashMap<>(); - Iterator itr = formalParameters.iterator(); - int i = 1; - while (itr.hasNext()) { - FormalParameter fp = itr.next(); - paramsAndLocals.put(fp.getName(), i); - methodParamsAndTypes.put(fp.getName(), resultSet.resolveType(fp.getType()).resolvedType); - fp.accept(this); - i++; - } - } - - @Override - public void visit(FormalParameter formalParameter) { - formalParameter.getType().accept(this); - } - - @Override - public void visit(RefType refType) { - type = "L" + refType.toString() + ";"; - } - - @Override - public void visit(SuperWildcardType superWildcardType) { - // TODO Auto-generated method stub - - } - - @Override - public void visit(TypePlaceholder typePlaceholder) { - // TODO Auto-generated method stub - - } - - @Override - public void visit(ExtendsWildcardType extendsWildcardType) { - // TODO Auto-generated method stub - - } - - @Override - public void visit(GenericRefType genericRefType) { - // TODO Auto-generated method stub - - } - - // ?? - @Override - public void visit(FieldVar fieldVar) { - System.out.println("In FieldVar ---"); -// cw.newField(fieldVar.receiver.toString(), fieldVar.fieldVarName.toString(), fieldVar.getType().toString()); - FieldVisitor fv = cw.visitField(Opcodes.ACC_PRIVATE, fieldVar.fieldVarName, "L" + fieldVar.getType() + ";", - null, null); - fv.visitEnd(); - } - - @Override - public void visit(Field field) { - System.out.println("In Field ---"); - String des = "L"; - if (resultSet.resolveType(field.getType()).resolvedType instanceof TypePlaceholder) { - des += Type.getInternalName(Object.class); - } else { - des += resultSet.resolveType(field.getType()).resolvedType.acceptTV(new TypeToDescriptor()); - } - des += ";"; - System.out.println(des); - String sig = resultSet.resolveType(field.getType()).resolvedType.acceptTV(new TypeToSignature(generatedGenerics.getClassConstraints())); - System.out.println(sig); - if (sig.charAt(sig.length() - 1) != (";").charAt(0)) { - sig += ";"; - } - String nameAndDesc = field.getName() + "%%" + des; - String nameAndSig = field.getName() + "%%" + sig; - if (fieldNameAndParamsT.contains(nameAndDesc)) { - if (fieldNameSignature.contains(nameAndSig)) { - return; - } - throw new BytecodeGeneratorError("Bytecode generation aborted due to duplicate field name&signature"); - } - fieldNameAndParamsT.add(nameAndDesc); - fieldNameSignature.add(nameAndSig); - - cw.visitField(field.modifier, field.getName(), des, sig, null); - } - - @Override - public void visit(LambdaExpression lambdaExpression) { - // TODO Auto-generated method stub - - } - - @Override - public void visit(Assign assign) { - // TODO Auto-generated method stub - - } - - @Override - public void visit(BinaryExpr binary) { - - } - - @Override - public void visit(Block block) { - // TODO Auto-generated method stub - - } - - @Override - public void visit(CastExpr castExpr) { - // TODO Auto-generated method stub - - } - - @Override - public void visit(EmptyStmt emptyStmt) { - // TODO Auto-generated method stub - - } - - @Override - public void visit(ForStmt forStmt) { - // TODO Auto-generated method stub - - } - - @Override - public void visit(IfStmt ifStmt) { - // TODO Auto-generated method stub - - } - - @Override - public void visit(InstanceOf instanceOf) { - // TODO Auto-generated method stub - - } - - @Override - public void visit(LocalVar localVar) { - // TODO Auto-generated method stub - - } - - @Override - public void visit(LocalVarDecl localVarDecl) { - // TODO Auto-generated method stub - - } - - @Override - public void visit(MethodCall methodCall) { - // TODO Auto-generated method stub - - } - - @Override - public void visit(NewClass methodCall) { - // TODO Auto-generated method stub - - } - - @Override - public void visit(NewArray newArray) { - // TODO Auto-generated method stub - - } - - @Override - public void visit(Return aReturn) { - // TODO Auto-generated method stub - - } - - @Override - public void visit(ReturnVoid aReturn) { - // TODO Auto-generated method stub - - } - - @Override - public void visit(StaticClassName staticClassName) { - // TODO Auto-generated method stub - - } - - @Override - public void visit(Super aSuper) { - // TODO Auto-generated method stub - - } - - @Override - public void visit(This aThis) { - // TODO Auto-generated method stub - - } - - @Override - public void visit(WhileStmt whileStmt) { - // TODO Auto-generated method stub - - } - - @Override - public void visit(DoStmt whileStmt) { - // TODO Auto-generated method stub - - } - - // ??? - @Override - public void visit(Literal literal) { - // TODO Auto-generated method stub - - } - - @Override - public void visit(ArgumentList argumentList) { - // TODO Auto-generated method stub - - } - - @Override - public void visit(GenericTypeVar genericTypeVar) { - // TODO Auto-generated method stub - - } - - @Override - public void visit(GenericDeclarationList genericTypeVars) { - // TODO Auto-generated method stub - - } - - @Override - public void visit(AssignToField assignLeftSide) { - // TODO Auto-generated method stub - - } - - @Override - public void visit(AssignToLocal assignLeftSide) { - // TODO Auto-generated method stub - - } - - @Override - public void visit(SuperCall superCall) { - - } - - @Override - public void visit(ExpressionReceiver expressionReceiver) { - // TODO Auto-generated method stub - - } - - @Override - public void visit(UnaryExpr unaryExpr) { - throw new NotImplementedException(); - } - -} diff --git a/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java b/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java deleted file mode 100644 index 5cbcfca9..00000000 --- a/src/main/java/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java +++ /dev/null @@ -1,1527 +0,0 @@ -package de.dhbwstuttgart.bytecode; - -import java.io.File; -import java.lang.invoke.CallSite; -import java.lang.invoke.MethodHandle; -import java.lang.invoke.MethodHandles; -import java.lang.invoke.MethodType; -import java.lang.reflect.Parameter; -import java.net.URL; -import java.net.URLClassLoader; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.stream.Collectors; - -import de.dhbwstuttgart.bytecode.funN.FunNGenerator; -import de.dhbwstuttgart.bytecode.funN.FunNUtilities; -import de.dhbwstuttgart.bytecode.utilities.*; -import de.dhbwstuttgart.environment.DirectoryClassLoader; -import de.dhbwstuttgart.exceptions.NotImplementedException; -import de.dhbwstuttgart.parser.scope.JavaClassName; -import de.dhbwstuttgart.syntaxtree.statement.*; -import de.dhbwstuttgart.syntaxtree.statement.BinaryExpr.Operator; -import de.dhbwstuttgart.syntaxtree.statement.UnaryExpr.Operation; - -import org.objectweb.asm.ClassWriter; -import org.objectweb.asm.Handle; -import org.objectweb.asm.Label; -import org.objectweb.asm.MethodVisitor; -import org.objectweb.asm.Opcodes; -import org.objectweb.asm.Type; - -import de.dhbwstuttgart.bytecode.Exception.NotInCurrentPackageException; -import de.dhbwstuttgart.bytecode.descriptor.DescriptorToString; -import de.dhbwstuttgart.bytecode.descriptor.TypeToDescriptor; -import de.dhbwstuttgart.parser.SyntaxTreeGenerator.AssignToLocal; -import de.dhbwstuttgart.syntaxtree.FormalParameter; -import de.dhbwstuttgart.syntaxtree.Method; -import de.dhbwstuttgart.syntaxtree.SourceFile; -import de.dhbwstuttgart.syntaxtree.StatementVisitor; -import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric; -import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder; -import de.dhbwstuttgart.typeinference.result.ResultSet; -import javassist.NotFoundException; - -public class BytecodeGenMethod implements StatementVisitor { - - private Resolver resolver; - private Method m; - private MethodVisitor mv; - private HashMap paramsAndLocals = new HashMap<>(); - private JavaClassName className; - private int lamCounter; - private ClassWriter cw; - private ResultSet resultSet; - private boolean isInterface; - private HashMap genericsAndBoundsMethod; - private HashMap genericsAndBounds; - public boolean isBinaryExp = false; - private String superClass; - private File path; - private SourceFile sf; - private IStatement statement = null; - private boolean isReturnStmt = false; - private boolean isParentBinary = false; - - private boolean needDUP = false; - - private Block blockFieldInit = null; - private boolean isBlockFieldInitVisited = false; - // for tests ** - private String fieldName; - private String fieldDesc; - private Expression rightSideTemp; - - private boolean isRightSideALambda = false; - private KindOfLambda kindOfLambda; - private HashMap classFiles; - - private int constructorPos = 0; - - private ArrayList varsFunInterface = new ArrayList<>();; - private final ClassLoader classLoader; - - // generate bytecode for constructor - public BytecodeGenMethod(JavaClassName className, String superClass, ResultSet resultSet, Method m, MethodVisitor mv, - HashMap paramsAndLocals, ClassWriter cw, HashMap genericsAndBoundsMethod, - HashMap genericsAndBounds, boolean isInterface, HashMap classFiles, - SourceFile sf, File path, Block block, int constructorPos, ClassLoader classLoader) { - - this.className = className; - this.superClass = superClass; - this.resultSet = resultSet; - this.resolver = new Resolver(resultSet); - this.m = m; - this.mv = mv; - this.paramsAndLocals = paramsAndLocals; - this.cw = cw; - this.genericsAndBoundsMethod = genericsAndBoundsMethod; - this.genericsAndBounds = genericsAndBounds; - this.isInterface = isInterface; - this.classFiles = classFiles; - this.sf = sf; - this.path = path; - this.lamCounter = -1; - this.constructorPos = constructorPos; - this.classLoader = classLoader; - if(block != null) - this.blockFieldInit = block; - this.m.block.accept(this); - } - - public BytecodeGenMethod(JavaClassName className, String superClass,ResultSet resultSet, Method m, MethodVisitor mv, - HashMap paramsAndLocals, ClassWriter cw, HashMap genericsAndBoundsMethod, - HashMap genericsAndBounds, boolean isInterface, HashMap classFiles, SourceFile sf,File path, ClassLoader classLoader) { - - this.className = className; - this.superClass = superClass; - this.resultSet = resultSet; - this.resolver = new Resolver(resultSet); - this.m = m; - this.mv = mv; - this.paramsAndLocals = paramsAndLocals; - this.cw = cw; - this.genericsAndBoundsMethod = genericsAndBoundsMethod; - this.genericsAndBounds = genericsAndBounds; - this.isInterface = isInterface; - this.classFiles = classFiles; - this.sf = sf; - this.path = path; - this.lamCounter = -1; - this.classLoader = classLoader; - if (!isInterface) - this.m.block.accept(this); - } - - public BytecodeGenMethod(JavaClassName className, ClassWriter cw, LambdaExpression lambdaExpression, ArrayList usedVars, ResultSet resultSet, MethodVisitor mv, - int indexOfFirstParamLam, boolean isInterface, HashMap classFiles, File path, int lamCounter, SourceFile sf,HashMap genericsAndBoundsMethod, - HashMap genericsAndBounds, ClassLoader classLoader) { - this.className = className; - this.cw = cw; - this.resultSet = resultSet; - this.resolver = new Resolver(resultSet); - this.mv = mv; - this.isInterface = isInterface; - this.classFiles = classFiles; - this.path = path; - this.lamCounter = lamCounter; - this.sf = sf; - this.genericsAndBoundsMethod = genericsAndBoundsMethod; - this.genericsAndBounds = genericsAndBounds; - this.classLoader = classLoader; - - Iterator itr = lambdaExpression.params.iterator(); - int i = indexOfFirstParamLam; - - for(String var : usedVars) { - this.paramsAndLocals.put(var, i); - i++; - } - - while (itr.hasNext()) { - FormalParameter fp = itr.next(); - this.paramsAndLocals.put(fp.getName(), i); - i++; - } - lambdaExpression.methodBody.accept(this); - } - - public Resolver getResolver() { - return resolver; - } - - public void isBinary(boolean isBinary) { - this.isBinaryExp =isBinary; - } - - - @Override - public void visit(Block block) { - HashMap paramsAndLocalsOld = new HashMap<>(paramsAndLocals); - for (Statement stmt : block.getStatements()) { - stmt.accept(this); - if(stmt instanceof MethodCall) { - String ret = resolver.getResolvedType(((MethodCall) stmt).getType()); - if(!ret.equals(CONSTANTS.VOID)) - mv.visitInsn(Opcodes.POP); - } - } - paramsAndLocals = paramsAndLocalsOld; - } - - @Override - public void visit(SuperCall superCall) { - superCall.receiver.accept(this); - superCall.arglist.accept(this); - mv.visitMethodInsn(Opcodes.INVOKESPECIAL, this.superClass, superCall.name, "()V", - isInterface); - - if(blockFieldInit!=null && !isBlockFieldInitVisited) { - isBlockFieldInitVisited =true; - //blockFieldInit.accept(this); - for(Statement stmt : blockFieldInit.statements) { - if(stmt instanceof SuperCall) - continue; - - stmt.accept(this); - } - } - } - - // ?? - @Override - public void visit(LocalVar localVar) { - // wenn String + String zuerst wird ein StringBuilder initialisiert dann - // wird die lokale Var geladen. Sonst wird zuerst die lokale Var geladen. - System.out.println(localVar.name); - mv.visitVarInsn(Opcodes.ALOAD, paramsAndLocals.get(localVar.name)); - - if (isBinaryExp) { - doUnboxing(resolver.getResolvedType(localVar.getType())); - } - } - - // ?? - @Override - public void visit(LocalVarDecl localVarDecl) { - paramsAndLocals.put(localVarDecl.getName(), paramsAndLocals.size()+1); - } - - @Override - public void visit(Assign assign) { - statement = new AssignStmt(assign.rightSide); - // if the right side is a lambda => the left side must be a functional interface - if (assign.rightSide instanceof LambdaExpression) { - isRightSideALambda = true; - } else { - isRightSideALambda = false; - } - - isBinaryExp = statement.isExprBinary(); - - if (assign.lefSide instanceof AssignToField) { - // load_0, ldc or .. then putfield - this.rightSideTemp = assign.rightSide; - } else { - assign.rightSide.accept(this); - } - - statement = new AssignStmt(assign.rightSide); - isBinaryExp = statement.isExprBinary(); - - if (isBinaryExp) { - BinaryExpr binary = (BinaryExpr) assign.rightSide; - String binaryType = resolver.getResolvedType(binary.getType()); - doBoxing(binaryType); - isBinaryExp = false; - } - - System.out.println("ASSIGN TYPE R: " + resolver.getResolvedType(assign.rightSide.getType())); - String typeOfRightSide = resolver.getResolvedType(assign.rightSide.getType()); - if(typeOfRightSide.contains(CONSTANTS.ANGLEBRACKET)) { - mv.visitTypeInsn(Opcodes.CHECKCAST, typeOfRightSide.substring(0, typeOfRightSide.indexOf('<'))); - } - assign.lefSide.accept(this); - - statement = null; - } - - @Override - public void visit(BinaryExpr binary) { - isParentBinary = true; - String lexpType = resolver.getResolvedType(binary.lexpr.getType()); - String rexpType = resolver.getResolvedType(binary.rexpr.getType()); - - String largerType = getLargerType(lexpType, rexpType); - String typeOfBinary = resolver.getResolvedType(binary.getType()); - - if (typeOfBinary.equals(Type.getInternalName(String.class))) { - mv.visitTypeInsn(Opcodes.NEW, Type.getInternalName(StringBuilder.class)); - mv.visitInsn(Opcodes.DUP); - mv.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(StringBuilder.class), "", "()V", - false); - } - - Label endLabel = new Label(); - // this case for while loops and If statements - if (statement instanceof LoopStmt) - mv.visitLabel(endLabel); - - if(binary.lexpr instanceof UnaryExpr) - needDUP = true; - - binary.lexpr.accept(this); - - if(lexpType.equals(Type.getInternalName(String.class))) { - mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(StringBuilder.class), "append", - "(Ljava/lang/String;)Ljava/lang/StringBuilder;", false); - } - - if (!lexpType.equals(rexpType) && !lexpType.equals(largerType)) - doCast(lexpType, largerType); - - if(binary.rexpr instanceof UnaryExpr) - needDUP = true; - - binary.rexpr.accept(this); - if(rexpType.equals(Type.getInternalName(String.class))) { - mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(StringBuilder.class), "append", - "(Ljava/lang/String;)Ljava/lang/StringBuilder;", false); - } - isParentBinary = false; - - if (!lexpType.equals(rexpType) && !rexpType.equals(largerType)) - doCast(rexpType, largerType); - - Operator op = binary.operation; - - switch (op) { - case ADD: - doVisitAddOpInsn(largerType); - break; - - case SUB: - doVisitSubOpInsn(typeOfBinary); - break; - - case MUL: - doVisitMulOpInsn(typeOfBinary); - break; - - case DIV: - doVisitDivOpInsn(typeOfBinary); - break; - - case MOD: - doVisitModOpInsn(typeOfBinary); - break; - - case LESSTHAN: - case LESSEQUAL: - case BIGGERTHAN: - case BIGGEREQUAL: - case EQUAL: - case NOTEQUAL: - Label branchLabel = new Label(); - doVisitRelOpInsn(op, largerType, branchLabel, endLabel); - break; - - default: - break; - } - } - - private String getLargerType(String lexpType, String rexpType) { - if (lexpType.equals(Type.getInternalName(String.class)) - || rexpType.equals(Type.getInternalName(String.class))) { - return Type.getInternalName(String.class); - } else if (lexpType.equals(Type.getInternalName(Double.class)) - || rexpType.equals(Type.getInternalName(Double.class))) { - return Type.getInternalName(Double.class); - } else if (lexpType.equals(Type.getInternalName(Float.class)) - || rexpType.equals(Type.getInternalName(Float.class))) { - return Type.getInternalName(Float.class); - } else if (lexpType.equals(Type.getInternalName(Long.class)) - || rexpType.equals(Type.getInternalName(Long.class))) { - return Type.getInternalName(Long.class); - } else { - return Type.getInternalName(Integer.class); - } - } - - private void doCast(String sourceType, String dest) { - switch (dest) { - case CONSTANTS.REFTYPE_LONG: - mv.visitInsn(Opcodes.I2L); - break; - - case CONSTANTS.REFTYPE_DOUBLE: - if (sourceType.equals(Type.getInternalName(Long.class))) { - mv.visitInsn(Opcodes.L2D); - } else if (sourceType.equals(Type.getInternalName(Float.class))) { - mv.visitInsn(Opcodes.F2D); - } else { - mv.visitInsn(Opcodes.I2D); - } - break; - - case CONSTANTS.REFTYPE_FLOAT: - if (sourceType.equals(Type.getInternalName(Long.class))) { - mv.visitInsn(Opcodes.L2F); - } else { - mv.visitInsn(Opcodes.I2F); - } - break; - // braucht man eigentlich nicht, muss getestet werden - case CONSTANTS.REFTYPE_STRING: - if (sourceType.equals(Type.getInternalName(Double.class))) { - mv.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(String.class), "valueOf", - "(D)Ljava/lang/String;", false); - } else if (sourceType.equals(Type.getInternalName(Long.class))) { - mv.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(String.class), "valueOf", - "(J)Ljava/lang/String;", false); - } else if (sourceType.equals(Type.getInternalName(Float.class))) { - mv.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(String.class), "valueOf", - "(F)Ljava/lang/String;", false); - } else { - mv.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(String.class), "valueOf", - "(I)Ljava/lang/String;", false); - } - break; - default: - break; - } - } - - private void doVisitRelOpInsn(Operator op, String typeOfBinary, Label branchLabel, Label endLabel) { - System.out.println("TypeOfBinary: " + typeOfBinary); - switch (typeOfBinary) { - case CONSTANTS.REFTYPE_LONG: - mv.visitInsn(Opcodes.LCMP); - doVisitIfInRelOp(op, branchLabel, endLabel); - break; - case CONSTANTS.REFTYPE_DOUBLE: - mv.visitInsn(Opcodes.DCMPG); - doVisitIfInRelOp(op, branchLabel, endLabel); - break; - case CONSTANTS.REFTYPE_FLOAT: - mv.visitInsn(Opcodes.FCMPG); - doVisitIfInRelOp(op, branchLabel, endLabel); - break; - default: - switch (op) { - case LESSTHAN: - mv.visitJumpInsn(Opcodes.IF_ICMPGE, branchLabel); - break; - case LESSEQUAL: - mv.visitJumpInsn(Opcodes.IF_ICMPGT, branchLabel); - break; - case BIGGERTHAN: - mv.visitJumpInsn(Opcodes.IF_ICMPLE, branchLabel); - break; - case BIGGEREQUAL: - mv.visitJumpInsn(Opcodes.IF_ICMPLT, branchLabel); - break; - case EQUAL: - mv.visitJumpInsn(Opcodes.IF_ICMPNE, branchLabel); - break; - case NOTEQUAL: - mv.visitJumpInsn(Opcodes.IFEQ, branchLabel); - break; - default: - break; - } - - statement.genBCForRelOp(mv, branchLabel, endLabel, this); - - break; - } - } - - private void doVisitIfInRelOp(Operator op, Label branchLabel, Label endLabel) { - - switch (op) { - case LESSTHAN: - mv.visitJumpInsn(Opcodes.IFGE, branchLabel); - break; - case LESSEQUAL: - mv.visitJumpInsn(Opcodes.IFGT, branchLabel); - break; - case BIGGERTHAN: - mv.visitJumpInsn(Opcodes.IFLE, branchLabel); - break; - case BIGGEREQUAL: - mv.visitJumpInsn(Opcodes.IFLT, branchLabel); - break; - case EQUAL: - mv.visitJumpInsn(Opcodes.IFNE, branchLabel); - break; - case NOTEQUAL: - mv.visitJumpInsn(Opcodes.IFEQ, branchLabel); - break; - default: - break; - } - - statement.genBCForRelOp(mv, branchLabel, endLabel, this); - } - - private void doVisitModOpInsn(String typeOfBinary) { - switch (typeOfBinary) { - case CONSTANTS.REFTYPE_LONG: - mv.visitInsn(Opcodes.LREM); - break; - case CONSTANTS.REFTYPE_DOUBLE: - mv.visitInsn(Opcodes.DREM); - break; - case CONSTANTS.REFTYPE_FLOAT: - mv.visitInsn(Opcodes.FREM); - break; - default: - mv.visitInsn(Opcodes.IREM); - break; - } - } - - private void doVisitDivOpInsn(String typeOfBinary) { - switch (typeOfBinary) { - case CONSTANTS.REFTYPE_LONG: - mv.visitInsn(Opcodes.LDIV); - break; - case CONSTANTS.REFTYPE_DOUBLE: - mv.visitInsn(Opcodes.DDIV); - break; - case CONSTANTS.REFTYPE_FLOAT: - mv.visitInsn(Opcodes.FDIV); - break; - default: - mv.visitInsn(Opcodes.IDIV); - break; - } - } - - private void doVisitMulOpInsn(String typeOfBinary) { - switch (typeOfBinary) { - case CONSTANTS.REFTYPE_LONG: - mv.visitInsn(Opcodes.LMUL); - break; - case CONSTANTS.REFTYPE_DOUBLE: - mv.visitInsn(Opcodes.DMUL); - break; - case CONSTANTS.REFTYPE_FLOAT: - mv.visitInsn(Opcodes.FMUL); - break; - default: - mv.visitInsn(Opcodes.IMUL); - break; - } - } - - private void doVisitSubOpInsn(String typeOfBinary) { - switch (typeOfBinary) { - case CONSTANTS.REFTYPE_LONG: - mv.visitInsn(Opcodes.LSUB); - break; - case CONSTANTS.REFTYPE_DOUBLE: - mv.visitInsn(Opcodes.DSUB); - break; - case CONSTANTS.REFTYPE_FLOAT: - mv.visitInsn(Opcodes.FSUB); - break; - default: - mv.visitInsn(Opcodes.ISUB); - break; - } - - } - - private void doVisitAddOpInsn(String typeOfBinary) { - switch (typeOfBinary) { - case CONSTANTS.REFTYPE_BYTE: - mv.visitInsn(Opcodes.IADD); - break; - case CONSTANTS.REFTYPE_SHORT: - mv.visitInsn(Opcodes.IADD); - break; - case CONSTANTS.REFTYPE_INTEGER: - mv.visitInsn(Opcodes.IADD); - break; - case CONSTANTS.REFTYPE_LONG: - mv.visitInsn(Opcodes.LADD); - break; - case CONSTANTS.REFTYPE_DOUBLE: - mv.visitInsn(Opcodes.DADD); - break; - case CONSTANTS.REFTYPE_FLOAT: - mv.visitInsn(Opcodes.FADD); - break; - case CONSTANTS.REFTYPE_STRING: - mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/StringBuilder", CONSTANTS.TO_STRING, "()Ljava/lang/String;", - false); - break; - default: - break; - } - } - - @Override - public void visit(LambdaExpression lambdaExpression) { - this.lamCounter++; - - String typeErasure = createDescriptorWithTypeErasure(lambdaExpression); - //ToDo Etienne: Double Check - RefTypeOrTPHOrWildcardOrGeneric returnType = resolver.resolve(lambdaExpression.getReturnType()); - List argumentTypes = lambdaExpression - .params - .getFormalparalist() - .stream() - .map(FormalParameter::getType) - .map(resolver::resolve) - .collect(Collectors.toList()); - FunNUtilities funNUtilities = FunNGenerator.getInstance(); - FunNUtilities.writeClassFile(funNUtilities.getSuperClassName(argumentTypes.size()), - funNUtilities.generateSuperBytecode(argumentTypes.size()), path); - FunNUtilities.writeClassFile(funNUtilities.getSpecializedClassName(argumentTypes, returnType), - funNUtilities.generateSpecializedBytecode(argumentTypes, returnType), path); - - Lambda lam = new Lambda(lambdaExpression); - String lamDesc = lam.accept(new DescriptorToString(resultSet)); - // Call site, which, when invoked, returns an instance of the functional - // interface to which - // the lambda is being converted - MethodType mt = MethodType.methodType(CallSite.class, MethodHandles.Lookup.class, String.class, - MethodType.class, MethodType.class, MethodHandle.class, MethodType.class); - - Handle bootstrap = new Handle(Opcodes.H_INVOKESTATIC, "java/lang/invoke/LambdaMetafactory", "metafactory", - mt.toMethodDescriptorString(), false); - String desugaredMethodName = CONSTANTS.DESUGAREDMETHODNAME + this.lamCounter; - - // Für die Parameter-Typen und Return-Typ braucht man die Bounds (für die - // Typlöschung) - - // Type erasure - Type arg1 = Type.getMethodType(typeErasure); - // Type arg1 = Type.getMethodType(lamDesc); - // real Type - Type arg3 = Type.getMethodType(lamDesc); - - int staticOrSpecial, staticOrInstance = 0, indexOfFirstParamLam = 0; - - this.kindOfLambda = new KindOfLambda(lambdaExpression); - - if (kindOfLambda.isInstanceCapturingLambda()) { - mv.visitVarInsn(Opcodes.ALOAD, 0); - loadUsedVarsInLambda(); - staticOrSpecial = Opcodes.H_INVOKESPECIAL; - indexOfFirstParamLam = 1; - } else { - staticOrSpecial = Opcodes.H_INVOKESTATIC; - staticOrInstance = Opcodes.ACC_STATIC; - } - String newDesc = addUsedVarsToDesugaredMethodDescriptor(lamDesc); - // first check if capturing lambda then invokestatic or invokespecial - Handle arg2 = new Handle(staticOrSpecial, this.className.getClassName(), desugaredMethodName, newDesc, false); - // Descriptor of functional interface methode - SamMethod samMethod = new SamMethod(kindOfLambda.getArgumentList(), lambdaExpression.getType()); - // Desc: (this/nothing)TargetType - String fiMethodDesc = samMethod.accept(new DescriptorToString(resultSet)); - mv.visitInvokeDynamicInsn("apply", fiMethodDesc, bootstrap, arg1, arg2, arg3); - if(constructorPos<2) { - MethodVisitor mvLambdaBody = cw.visitMethod(Opcodes.ACC_PRIVATE + staticOrInstance + Opcodes.ACC_SYNTHETIC, - desugaredMethodName, newDesc, null, null); - - ArrayList usedVars = kindOfLambda.getUsedVars(); - - new BytecodeGenMethod(className, cw,lambdaExpression, usedVars,this.resultSet, mvLambdaBody, indexOfFirstParamLam, isInterface, - classFiles,this.path, lamCounter, sf, genericsAndBoundsMethod, - genericsAndBounds, classLoader); - - mvLambdaBody.visitMaxs(0, 0); - mvLambdaBody.visitEnd(); - cw.visitInnerClass("java/lang/invoke/MethodHandles$Lookup", "java/lang/invoke/MethodHandles", "Lookup", - Opcodes.ACC_PUBLIC + Opcodes.ACC_STATIC + Opcodes.ACC_FINAL); - } -// generateBCForFunN(lambdaExpression, typeErasure); - } - - private String addUsedVarsToDesugaredMethodDescriptor(String lamDesc) { - String newDesc = "("; - int pos = 0; - if(kindOfLambda.isThisUsed()) { - pos = 1; - } - - for(int i=pos;i itr = lambdaExpression.params.iterator(); - while (itr.hasNext()) { - itr.next(); - typeErasure += "L" + Type.getInternalName(Object.class) + ";"; - } - - typeErasure += ")L" + Type.getInternalName(Object.class) + ";"; - return typeErasure; - } - - - - @Override - public void visit(CastExpr castExpr) { - - } - - @Override - public void visit(EmptyStmt emptyStmt) { - // TODO Auto-generated method stub - - } - - @Override - public void visit(FieldVar fieldVar) { - fieldName = fieldVar.fieldVarName; - fieldDesc = "L"; - if(resultSet.resolveType(fieldVar.getType()).resolvedType instanceof TypePlaceholder) { - fieldDesc += Type.getInternalName(Object.class); - } else { - fieldDesc += resultSet.resolveType(fieldVar.getType()).resolvedType.acceptTV(new TypeToDescriptor()); - } - fieldDesc +=";"; - - fieldVar.receiver.accept(this); - // test (if) - if (!fieldVar.receiver.getClass().equals(StaticClassName.class)) { - mv.visitFieldInsn(Opcodes.GETFIELD, resolver.getResolvedType(fieldVar.receiver.getType()), fieldName, fieldDesc); - } - - if (isBinaryExp) { - doUnboxing(resolver.getResolvedType(fieldVar.getType())); - } - // mv.visitFieldInsn(Opcodes.GETSTATIC, - // fieldVar.receiver.getType().toString().replace(".", "/"), - // fieldVar.fieldVarName, fieldVar.getType().toString()); - } - - @Override - public void visit(ForStmt forStmt) { - // TODO Auto-generated method stub - - } - - @Override - public void visit(IfStmt ifStmt) { - statement = new IfStatement(ifStmt.expr, ifStmt.then_block, ifStmt.else_block); - isBinaryExp = statement.isExprBinary(); - ifStmt.expr.accept(this); - if(!(ifStmt.expr instanceof BinaryExpr)) { - doUnboxing(resolver.getResolvedType(ifStmt.expr.getType())); - Label branchLabel = new Label(); - Label endLabel = new Label(); - mv.visitJumpInsn(Opcodes.IFEQ, branchLabel); - statement.genBCForRelOp(mv, branchLabel, endLabel, this); - } - statement = null; - } - - @Override - public void visit(InstanceOf instanceOf) { - - } - - @Override - public void visit(MethodCall methodCall) { - boolean parentBinary = isParentBinary; - System.out.println("In MethodCall = " + methodCall.name); - String receiverName = resolver.getResolvedType(methodCall.receiver.getType()); - System.out.println("Methods of " + receiverName + " "); - java.lang.reflect.Method methodRefl = null; - String clazz = receiverName.replace("/", "."); - - String mDesc = ""; - - MethodCallHelper helper = new MethodCallHelper(methodCall, sf, resultSet, path); - - ClassLoader cLoader = this.classLoader; - // This will be used if the class is not standard class (not in API) - ClassLoader cLoader2; - - String methCallType = resultSet.resolveType(methodCall.getType()).resolvedType.acceptTV(new TypeToDescriptor()); - String[] typesOfParams = getTypes(methodCall.arglist.getArguments()); - try { - clazz = getRawClassName(receiverName, clazz); - - java.lang.reflect.Method[] methods = cLoader.loadClass(clazz).getMethods(); - System.out.println("Methods of " + receiverName + " "); - methodRefl = getMethod(methodCall.name, methodCall.arglist.getArguments().size(),methCallType, typesOfParams, methods); - - } catch (Exception e) { - String superClass = ""; - while(true) { - try { - superClass = helper.getSuperClass(receiverName.replace("/", ".")); - - try { - String superClazz = superClass.replace("/", "."); - superClazz = getRawClassName(superClass, superClazz); - java.lang.reflect.Method[] methods = cLoader.loadClass(superClazz).getMethods(); - System.out.println("Methods of " + superClass + " "); - - methodRefl = getMethod(methodCall.name, methodCall.arglist.getArguments().size(), methCallType, typesOfParams, methods); - - break; - } catch (Exception e3) { - receiverName = superClass; - continue; - } - } catch (NotInCurrentPackageException e2) { - break; - } - - } - - } - - if(methodRefl == null) { - boolean toCreate = !receiverName.equals(className.getClassName()) && helper.isInCurrPkg(clazz); - if(toCreate) { - try { - mDesc = helper.getDesc(clazz); - } catch (NotInCurrentPackageException | NotFoundException e) { - e.printStackTrace(); - } - } else if(!helper.isInCurrPkg(clazz)){ - if(clazz.contains(CONSTANTS.$$)) { - mDesc = helper.getDescriptorOfApplyMethod(methCallType); - //ToDo Etienne: Double Check - RefTypeOrTPHOrWildcardOrGeneric returnType = resolver.resolve(methodCall.getType()); - List argumentTypes = methodCall - .arglist - .getArguments() - .stream() - .map(TypableStatement::getType) - .map(resolver::resolve) - .collect(Collectors.toList()); - FunNUtilities funNUtilities = FunNGenerator.getInstance(); - FunNUtilities.writeClassFile(funNUtilities.getSuperClassName(argumentTypes.size()), - funNUtilities.generateSuperBytecode(argumentTypes.size()), path); - FunNUtilities.writeClassFile(funNUtilities.getSpecializedClassName(argumentTypes, returnType), - funNUtilities.generateSpecializedBytecode(argumentTypes, returnType), path); - }else { - try { - cLoader2 = new DirectoryClassLoader(path, classLoader); - java.lang.reflect.Method[] methods = cLoader2.loadClass(clazz).getMethods(); - System.out.println("Methods of " + receiverName + " "); - for(int i = 0; i argListMethCall = new LinkedList<>(); - String receiverRefl=""; - if(methodRefl == null && receiverName.equals(className.getClassName())) { - MethodFromMethodCall method = new MethodFromMethodCall(methodCall.arglist, methodCall.getType(), - receiverName, genericsAndBoundsMethod, genericsAndBounds); - mDesc = method.accept(new DescriptorToString(resultSet)); - methodCall.arglist.accept(this); - } else if(methodRefl != null) { - System.out.println(methodCall.name + " -> Refl != null"); - receiverRefl = methodRefl.getAnnotatedReceiverType().getType().toString(); - getBoolListOfType(methodRefl, argListMethCall); - System.out.println("Receiver = " + methodRefl.getAnnotatedReceiverType().getType().toString()); - mDesc = getMethodDesc(methodRefl); - visitArgumentListOfMethodCallFromStandardAPI(methodCall, argListMethCall); - } else { - methodCall.arglist.accept(this); - } - - System.out.println("Methodcall ("+ methodCall.name +") Desc : " + mDesc); - - -// methodCall.arglist.accept(this); - visitInvokeInsn(methodCall, receiverName, methodRefl, clazz, mDesc, receiverRefl); - - - if(methodRefl != null && !methodRefl.getReturnType().isPrimitive()) { - if(methodRefl.getReturnType().equals(Object.class)) { - helper.createCheckCast(methodCall,mv); - } - /*if(isBinaryExp) { - doUnboxing(resolver.getResolvedType(methodCall.getType())); - }*/ - if(parentBinary || isBinaryExp) { - doUnboxing(resolver.getResolvedType(methodCall.getType())); - } - } else if(receiverName.contains(CONSTANTS.$$) && !methCallType.equals(Type.getInternalName(Object.class))) { - helper.createCheckCast(methodCall,mv); - } - System.out.println("ISParent Binary = "+isParentBinary +" -> " + parentBinary); - if(methodRefl == null && (parentBinary || !isReturnStmt)) { - if(isBinaryExp) - doUnboxing(resolver.getResolvedType(methodCall.getType())); - } - - } - - private void getBoolListOfType(java.lang.reflect.Method methodRefl, List argListMethCall) { - for(Parameter p:methodRefl.getParameters()) { - System.out.println(p.getName() + " und is Primitive = " + p.getType().isPrimitive()); - argListMethCall.add(p.getType().isPrimitive()); - } - } - - private void visitArgumentListOfMethodCallFromStandardAPI(MethodCall methodCall, List argListMethCall) { - for (Expression al : methodCall.arglist.getArguments()) { - statement = new ArgumentExpr(al); - ArgumentVisitor argV = new ArgumentVisitor(argListMethCall,this); - al.accept(argV); - statement = null; - } - } - - private void visitInvokeInsn(MethodCall methodCall, String receiverName, java.lang.reflect.Method methodRefl, String clazz, String mDesc, String receiverRefl) { - // is methodCall.receiver functional Interface)? - if (varsFunInterface.contains(methodCall.receiver.getType()) || (methodRefl!= null && receiverRefl.contains("interface")) || - receiverName.contains(CONSTANTS.$$)) { - mv.visitMethodInsn(Opcodes.INVOKEINTERFACE, clazz.replace(".", "/"), methodCall.name, - mDesc, true); - } else { - mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, clazz.replace(".", "/"), methodCall.name, - mDesc, isInterface); - } - } - - private String getRawClassName(String receiverName, String clazz) { - if (receiverName.contains(CONSTANTS.ANGLEBRACKET)) { - clazz = clazz.substring(0, receiverName.indexOf(CONSTANTS.ANGLEBRACKET)); - } - return clazz; - } - - private String[] getTypes(List arguments) { - String[] types = new String[arguments.size()]; - for(int i = 0; i[] pTypes = m.getParameterTypes(); - for(int j = 0; j", d, isInterface); - } - - private String createDescriptorForInitMethod(NewClass methodCall) { - String d = "("; - for (Expression e : methodCall.arglist.getArguments()) { - String type = resolver.getResolvedType(e.getType()); - if(type.contains("TPH ")){ - type = Type.getInternalName(Object.class); - } - d = d + "L" + type + ";"; - } - d += ")V"; - return d; - } - - @Override - public void visit(NewArray newArray) { - // TODO Auto-generated method stub - - } - - @Override - public void visit(ExpressionReceiver receiver) { - receiver.expr.accept(this); - } - - @Override - public void visit(UnaryExpr unaryExpr) { - unaryExpr.expr.accept(this); - Operation op = unaryExpr.operation; - - String typeOfUnary = resolver.getResolvedType(unaryExpr.getType()); - - boolean isIncOrDec = false; - - switch (op) { - case POSTDECREMENT: - case POSTINCREMENT: - if (statement instanceof AssignStmt) - mv.visitInsn(Opcodes.DUP); - genBCForIncAndDec(op, typeOfUnary); - doBoxing(typeOfUnary); - isIncOrDec = true; - break; - case PREDECREMENT: - case PREINCREMENT: - genBCForIncAndDec(op, typeOfUnary); - doBoxing(typeOfUnary); - if (statement instanceof AssignStmt) - mv.visitInsn(Opcodes.DUP); - isIncOrDec = true; - break; - - case MINUS: - doVisitNegIns(typeOfUnary); - break; - default: - break; - } - - // Für Byte und Short muss noch einen Cast geben i2b, i2s - // das wird später gemacht, da bytecode für cast noch nicht erzeugt wird - - if (isIncOrDec && (unaryExpr.expr instanceof LocalVar)) { - if(needDUP) { - mv.visitInsn(Opcodes.DUP); - needDUP = false; - } - LocalVar local = (LocalVar) unaryExpr.expr; - mv.visitVarInsn(Opcodes.ASTORE, paramsAndLocals.get(local.name)); - } - } - - private void doVisitNegIns(String typeOfUnary) { - switch (typeOfUnary) { - case CONSTANTS.REFTYPE_LONG: - mv.visitInsn(Opcodes.LNEG); - break; - case CONSTANTS.REFTYPE_DOUBLE: - mv.visitInsn(Opcodes.DNEG); - break; - case CONSTANTS.REFTYPE_FLOAT: - mv.visitInsn(Opcodes.FNEG); - break; - default: - mv.visitInsn(Opcodes.INEG); - break; - } - - } - - private void genBCForIncAndDec(Operation op, String typeOfUnary) { - - doUnboxing(typeOfUnary); - loadValue(typeOfUnary, 1.0, true); - - switch (op) { - case POSTDECREMENT: - case PREDECREMENT: - doVisitSubOpInsn(typeOfUnary); - break; - - case POSTINCREMENT: - case PREINCREMENT: - doVisitAddOpInsn(typeOfUnary); - break; - - default: - break; - } - } - - @Override - public void visit(Return aReturn) { - statement = new ReturnStmt(aReturn.retexpr); - isReturnStmt = true; - isBinaryExp = statement.isExprBinary(); - boolean isBinary = isBinaryExp; - if(aReturn.retexpr instanceof UnaryExpr) - needDUP = true; - - aReturn.retexpr.accept(this); - - if (isBinary) { - BinaryExpr binary = (BinaryExpr) aReturn.retexpr; - doBoxing(resolver.getResolvedType(binary.getType())); -// isBinaryExp = false; - } - - mv.visitInsn(Opcodes.ARETURN); - isReturnStmt = false; - statement = null; - } - - @Override - public void visit(ReturnVoid aReturn) { - mv.visitInsn(Opcodes.RETURN); - } - - @Override - public void visit(StaticClassName staticClassName) { - // mv.visitMethodInsn(Opcodes.INVOKESTATIC, - // staticClassName.getType().toString().replace(".", "/"), - // staticClassName.toString(), staticClassName.getType().toString(), false); - // mv.visitFieldInsn(Opcodes.GETSTATIC, - // getResolvedType(staticClassName.getType()), fieldName, fieldDesc); - throw new NotImplementedException("Static noch nicht implementiert!"); - } - - @Override - public void visit(Super aSuper) { - - } - - @Override - public void visit(This aThis) { - - if(BytecodeGen.THISTYPE == null) - BytecodeGen.THISTYPE = aThis.getType(); - - mv.visitVarInsn(Opcodes.ALOAD, 0); - } - - @Override - public void visit(WhileStmt whileStmt) { - statement = new LoopStmt(whileStmt.expr, whileStmt.loopBlock); - isBinaryExp = statement.isExprBinary(); - whileStmt.expr.accept(this); -// isBinaryExp = false; - statement = null; - } - - @Override - public void visit(DoStmt whileStmt) { - whileStmt.expr.accept(this); - // TODO: - } - - @Override - public void visit(Literal literal) { - Object value = literal.value; - String typeOfLiteral = resolver.getResolvedType(literal.getType()); - System.out.println("typeOfLiteral :=> "+ typeOfLiteral); - // Der Wert des Literals wird auf den Stack geladen und - // geboxt, wenn es nötig ist. - loadValue(typeOfLiteral, value, false); - } - - // Unboxing: RefType -> prim - public void doUnboxing(String type) { - switch (type) { -// case "java/lang/String": -// mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(StringBuilder.class), "append", -// "(Ljava/lang/String;)Ljava/lang/StringBuilder;", false); -// -// break; - case "java/lang/Boolean": - mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Boolean", "booleanValue", "()Z", false); - break; - case CONSTANTS.REFTYPE_BYTE: - mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, CONSTANTS.REFTYPE_BYTE, "byteValue", "()B", false); - break; - case CONSTANTS.REFTYPE_SHORT: - mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, CONSTANTS.REFTYPE_SHORT, "shortValue", "()S", false); - break; - case "java/lang/Integer": - mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Integer", "intValue", "()I", false); - break; - case CONSTANTS.REFTYPE_LONG: - mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, CONSTANTS.REFTYPE_LONG, "longValue", "()J", false); - break; - case CONSTANTS.REFTYPE_FLOAT: - mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, CONSTANTS.REFTYPE_FLOAT, "floatValue", "()F", false); - break; - case CONSTANTS.REFTYPE_DOUBLE: - mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, CONSTANTS.REFTYPE_DOUBLE, "doubleValue", "()D", false); - break; - case "java/lang/Character": - break; - default: - // mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Integer", "intValue", - // "()I", false); - break; - } - } - - private void loadValue(String type, Object value, boolean isOperator) { - switch (type) { - case CONSTANTS.REFTYPE_STRING: - mv.visitLdcInsn(String.valueOf(value)); - break; - case "java/lang/Boolean": - visitBooleanLiteral((Boolean) value); - break; - case CONSTANTS.REFTYPE_BYTE: - if(value instanceof Double) - visitByteLiteral(((Double) value).byteValue(), false); - if(value instanceof Integer) - visitByteLiteral(((Integer) value).byteValue(), false); - break; - case CONSTANTS.REFTYPE_SHORT: - if(value instanceof Double) - visitShortLiteral(((Double) value).shortValue(), false); - if(value instanceof Integer) - visitShortLiteral(((Integer) value).shortValue(), false); - break; - case "java/lang/Integer": - // zweite Argument isLong -// visitIntegerLiteral(((Double) value).intValue(), false); - if(value instanceof Double) - visitIntegerLiteral(((Double) value).intValue(), false); - if(value instanceof Integer) - visitIntegerLiteral(((Integer) value).intValue(), false); - break; - case CONSTANTS.REFTYPE_LONG: - if(value instanceof Double) - visitLongLiteral(((Double) value).longValue(), true); - if(value instanceof Integer) - visitLongLiteral(((Integer) value).longValue(), true); - break; - case CONSTANTS.REFTYPE_FLOAT: - if(value instanceof Double) - visitFloatLiteral(((Double) value).floatValue()); - if(value instanceof Integer) - visitFloatLiteral(((Integer) value).floatValue()); - break; - case CONSTANTS.REFTYPE_DOUBLE: - if(value instanceof Double) - visitDoubleLiteral((Double) value); - if(value instanceof Integer) - visitDoubleLiteral(((Integer) value).doubleValue()); - break; - case "java/lang/Character": - visitCharLiteral((Character) value); - break; - default: - // wenn die Typ des Literals = Number ist, wird integer-value - // verwendet -// visitIntegerLiteral(((Double) value).intValue(), false); - break; - } - // Boxing - if (!type.equals(CONSTANTS.REFTYPE_STRING) && !type.equals("java/lang/Boolean")) { - if (!this.isBinaryExp && !isOperator) - doBoxing(type); - } - - } - - // Boxing: prim -> RefType - public void doBoxing(String type) { - switch (type) { -// case "java/lang/String": -// mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/StringBuilder", "toString", "()Ljava/lang/String;", -// false); -// break; - case "java/lang/Boolean": - mv.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/Boolean", "valueOf", "(Z)Ljava/lang/Boolean;", false); - break; - case CONSTANTS.REFTYPE_BYTE: - mv.visitMethodInsn(Opcodes.INVOKESTATIC, CONSTANTS.REFTYPE_BYTE, "valueOf", "(B)Ljava/lang/Byte;", false); - break; - case CONSTANTS.REFTYPE_SHORT: - mv.visitMethodInsn(Opcodes.INVOKESTATIC, CONSTANTS.REFTYPE_SHORT, "valueOf", "(S)Ljava/lang/Short;", false); - break; - case "java/lang/Integer": - mv.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/Integer", "valueOf", "(I)Ljava/lang/Integer;", false); - break; - case CONSTANTS.REFTYPE_LONG: - mv.visitMethodInsn(Opcodes.INVOKESTATIC, CONSTANTS.REFTYPE_LONG, "valueOf", "(J)Ljava/lang/Long;", false); - break; - case CONSTANTS.REFTYPE_FLOAT: - mv.visitMethodInsn(Opcodes.INVOKESTATIC, CONSTANTS.REFTYPE_FLOAT, "valueOf", "(F)Ljava/lang/Float;", false); - break; - case CONSTANTS.REFTYPE_DOUBLE: - mv.visitMethodInsn(Opcodes.INVOKESTATIC, CONSTANTS.REFTYPE_DOUBLE, "valueOf", "(D)Ljava/lang/Double;", false); - break; - case "java/lang/Character": - mv.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/Character", "valueOf", "(C)Ljava/lang/Character;", - false); - break; - default: - break; - } - } - - private void visitCharLiteral(Character value) { - mv.visitIntInsn(Opcodes.BIPUSH, (int) value); - - } - - private void visitDoubleLiteral(Double value) { - if (value == 0) { - mv.visitInsn(Opcodes.DCONST_0); - } else if (value == 1) { - mv.visitInsn(Opcodes.DCONST_1); - } else { - mv.visitLdcInsn(value); - } - } - - private void visitFloatLiteral(Float value) { - if (value.intValue() > -1 && value.intValue() < 3) { - // Opcodes.FCONST_0 = 11, Opcodes.FCONST_1 = 12, usw - mv.visitInsn(value.intValue() + 11); - } else { - mv.visitLdcInsn(value); - } - } - - private void visitLongLiteral(Long value, boolean isLong) { - if (value == 0) { - mv.visitInsn(Opcodes.LCONST_0); - } else if (value == 1) { - mv.visitInsn(Opcodes.LCONST_1); - } else { - mv.visitLdcInsn(value); - } - } - - private void visitShortLiteral(Short value, boolean isLong) { - if (value < 128 || (value > -129 && value < -1)) { - visitByteLiteral(value.byteValue(), isLong); - } else if (value < Math.pow(2, 15) || (value >= -Math.pow(2, 15)) && value < -128) { - mv.visitIntInsn(Opcodes.SIPUSH, value); - } - } - - private void visitByteLiteral(Byte value, boolean isLong) { - - if (!isLong && value < 6 && value > -1) { - // Opcodes.ICONST_0 = 3, Opcodes.ICONST_1 = 4, usw - mv.visitInsn(value + 3); - } else if (isLong && value > -1 && value < 2) { - // Opcodes.LCONST_0 = 9, Opcodes.LCONST_1 = 10 - mv.visitInsn(value + 9); - } else { - mv.visitIntInsn(Opcodes.BIPUSH, value); - } - - } - - private void visitIntegerLiteral(Integer value, boolean isLong) { - - if (value < Math.pow(2, 15) || (value >= -Math.pow(2, 15)) && value < -128) { - visitShortLiteral(value.shortValue(), isLong); - } else { - mv.visitLdcInsn(value); - } - } - - private void visitBooleanLiteral(Boolean b) { - if (b) { - mv.visitInsn(Opcodes.ICONST_1); - } else { - mv.visitInsn(Opcodes.ICONST_0); - } - // muss noch getestet werden. - mv.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/Boolean", "valueOf", "(Z)Ljava/lang/Boolean;", false); - } - - @Override - public void visit(ArgumentList argumentList) { - for (Expression al : argumentList.getArguments()) { - statement = new ArgumentExpr(al); - isBinaryExp = statement.isExprBinary(); - if(al instanceof UnaryExpr) - needDUP = true; - al.accept(this); - //TODO: teste, ob man das für unary braucht - if (isBinaryExp) { - BinaryExpr binary = (BinaryExpr) al; - String binaryType = resolver.getResolvedType(binary.getType()); - doBoxing(binaryType); - } - statement = null; - } - } - - @Override - public void visit(AssignToField assignLeftSide) { - // temporäre Lösung für testen, bis ich weiss wie man funktionale - // interfaces erkennt - if (isRightSideALambda) - varsFunInterface.add(assignLeftSide.field.getType()); - // Loads the an object reference from the local variable - // array slot onto the top of the operand stack. - assignLeftSide.field.receiver.accept(this); - this.rightSideTemp.accept(this); - String fDesc = "L"; - if(resultSet.resolveType(assignLeftSide.field.getType()).resolvedType instanceof TypePlaceholder) { - fDesc += Type.getInternalName(Object.class); - } else { - fDesc += resultSet.resolveType(assignLeftSide.field.getType()).resolvedType.acceptTV(new TypeToDescriptor()); - } - fDesc +=";"; - - - System.out.println("Receiver = " + resolver.getResolvedType(assignLeftSide.field.receiver.getType())); - mv.visitFieldInsn(Opcodes.PUTFIELD, resolver.getResolvedType(assignLeftSide.field.receiver.getType()), - assignLeftSide.field.fieldVarName, fDesc); - } - - @Override - public void visit(AssignToLocal assignLeftSide) { - if (isRightSideALambda) - varsFunInterface.add(assignLeftSide.localVar.getType()); - int index = paramsAndLocals.size(); - String var = assignLeftSide.localVar.name; - if (!paramsAndLocals.containsKey(var)) { - paramsAndLocals.put(var, index + 1); - } - - mv.visitVarInsn(Opcodes.ASTORE, paramsAndLocals.get(var)); - } - -} diff --git a/src/main/java/de/dhbwstuttgart/target/bytecode/CodeGenException.java b/src/main/java/de/dhbwstuttgart/bytecode/CodeGenException.java similarity index 75% rename from src/main/java/de/dhbwstuttgart/target/bytecode/CodeGenException.java rename to src/main/java/de/dhbwstuttgart/bytecode/CodeGenException.java index f517e767..633e0a10 100644 --- a/src/main/java/de/dhbwstuttgart/target/bytecode/CodeGenException.java +++ b/src/main/java/de/dhbwstuttgart/bytecode/CodeGenException.java @@ -1,4 +1,4 @@ -package de.dhbwstuttgart.target.bytecode; +package de.dhbwstuttgart.bytecode; public class CodeGenException extends RuntimeException { public CodeGenException(String cause) { diff --git a/src/main/java/de/dhbwstuttgart/target/bytecode/Codegen.java b/src/main/java/de/dhbwstuttgart/bytecode/Codegen.java old mode 100755 new mode 100644 similarity index 93% rename from src/main/java/de/dhbwstuttgart/target/bytecode/Codegen.java rename to src/main/java/de/dhbwstuttgart/bytecode/Codegen.java index 04bee492..df56b333 --- a/src/main/java/de/dhbwstuttgart/target/bytecode/Codegen.java +++ b/src/main/java/de/dhbwstuttgart/bytecode/Codegen.java @@ -1,6 +1,5 @@ -package de.dhbwstuttgart.target.bytecode; +package de.dhbwstuttgart.bytecode; -import de.dhbwstuttgart.syntaxtree.statement.Block; import de.dhbwstuttgart.target.tree.*; import de.dhbwstuttgart.target.tree.expression.*; import de.dhbwstuttgart.target.tree.type.*; @@ -59,8 +58,10 @@ public class Codegen { Scope scope = new Scope(null); int localCounter; MethodVisitor mv; + TargetType returnType; - State(MethodVisitor mv, int localCounter) { + State(TargetType returnType, MethodVisitor mv, int localCounter) { + this.returnType = returnType; this.mv = mv; this.localCounter = localCounter; } @@ -81,6 +82,13 @@ public class Codegen { } } + private void popValue(State state, TargetType type) { + if (type.equals(TargetType.Double) || type.equals(TargetType.Long)) + state.mv.visitInsn(POP2); + else + state.mv.visitInsn(POP); + } + private void boxPrimitive(State state, TargetType type) { var mv = state.mv; if (type.equals(TargetType.Boolean) || type.equals(TargetType.boolean_)) { @@ -236,7 +244,7 @@ public class Codegen { mv.visitInsn(I2F); else if (dest.equals(TargetType.Double)) mv.visitInsn(I2D); - } else { + } else if (!(dest instanceof TargetGenericType)) { boxPrimitive(state, source); mv.visitTypeInsn(CHECKCAST, dest.getInternalName()); unboxPrimitive(state, dest); @@ -704,11 +712,15 @@ public class Codegen { } else { var name = "lambda$" + lambdaCounter++; var parameters = new ArrayList<>(lambda.captures()); - parameters.addAll(lambda.params()); + parameters.addAll(lambda.params().stream() + .map(param -> param.type() instanceof TargetGenericType ? new MethodParameter(TargetType.Object, param.name()) : param) + .toList()); impl = new TargetMethod( - 0, name, Set.of(), - parameters, lambda.returnType(), lambda.block() + 0, name, Set.of(), Set.of(), + parameters, + lambda.returnType() instanceof TargetGenericType ? TargetType.Object : lambda.returnType(), + lambda.block() ); generateMethod(impl); lambdas.put(lambda, impl); @@ -735,7 +747,9 @@ public class Codegen { var params = new ArrayList(); params.add(new TargetRefType(clazz.qualifiedName())); - params.addAll(lambda.captures().stream().map(MethodParameter::type).toList()); + params.addAll(lambda.captures().stream() + .map(MethodParameter::type) + .toList()); var descriptor = TargetMethod.getDescriptor(lambda.type(), params.toArray(TargetType[]::new)); mv.visitVarInsn(ALOAD, 0); @@ -751,7 +765,7 @@ public class Codegen { private void generate(State state, TargetExpression expr) { var mv = state.mv; switch (expr) { - case TargetClassName className: + case TargetClassName ignored: break; // NOP case TargetBlock block: { var localCounter = state.localCounter; @@ -759,9 +773,11 @@ public class Codegen { for (var e : block.statements()) { generate(state, e); if (e instanceof TargetMethodCall) { - if (e.type() != null) mv.visitInsn(POP); - } else if (e instanceof TargetStatementExpression) { - mv.visitInsn(POP); + if (e.type() != null) popValue(state, e.type()); + } else if (e instanceof TargetAssign) { + mv.visitInsn(POP); // TODO Nasty fix, we don't know if it is a primitive double or long + } else if (e instanceof TargetStatementExpression se) { + popValue(state, se.type()); } } state.exitScope(); @@ -810,6 +826,9 @@ public class Codegen { generate(state, varDecl.value()); boxPrimitive(state, varDecl.varType()); mv.visitVarInsn(ASTORE, local.index()); + } else { + mv.visitInsn(ACONST_NULL); + mv.visitVarInsn(ASTORE, local.index()); } break; } @@ -830,13 +849,15 @@ public class Codegen { break; } case TargetFieldVar dot: { + var fieldType = dot.type(); generate(state, dot.left()); generate(state, assign.right()); - boxPrimitive(state, assign.right().type()); + convertTo(state, assign.right().type(), fieldType); + boxPrimitive(state, fieldType); if (dot.isStatic()) mv.visitInsn(DUP); else mv.visitInsn(DUP_X1); - mv.visitFieldInsn(dot.isStatic() ? PUTSTATIC : PUTFIELD, dot.owner().getInternalName(), dot.right(), dot.type().toSignature()); + mv.visitFieldInsn(dot.isStatic() ? PUTSTATIC : PUTFIELD, dot.owner().getInternalName(), dot.right(), fieldType.toSignature()); break; } default: @@ -867,12 +888,13 @@ public class Codegen { mv.visitLabel(start); if (_for.termination() != null) generate(state, _for.termination()); + else mv.visitInsn(ICONST_1); mv.visitJumpInsn(IFEQ, end); generate(state, _for.body()); if (_for.increment() != null) { generate(state, _for.increment()); if (_for.increment().type() != null) { - mv.visitInsn(POP); + popValue(state, _for.increment().type()); } } mv.visitJumpInsn(GOTO, start); @@ -907,9 +929,10 @@ public class Codegen { break; } case TargetReturn ret: { - if (ret.expression() != null) { + if (ret.expression() != null && state.returnType != null) { generate(state, ret.expression()); - boxPrimitive(state, ret.expression().type()); + convertTo(state, ret.expression().type(), state.returnType); + boxPrimitive(state, state.returnType); mv.visitInsn(ARETURN); } else mv.visitInsn(RETURN); break; @@ -941,7 +964,7 @@ public class Codegen { mv.visitMethodInsn(call.isInterface() ? INVOKEINTERFACE : call.isStatic() ? INVOKESTATIC: call.name().equals("") ? INVOKESPECIAL : INVOKEVIRTUAL, call.owner().getInternalName(), call.name(), descriptor, call.isInterface()); - if (call.returnType() != null && !(call.returnType() instanceof TargetPrimitiveType)) { + if (call.type() != null && call.returnType() != null && !(call.returnType() instanceof TargetPrimitiveType)) { if (!call.returnType().equals(call.type()) && !(call.type() instanceof TargetGenericType)) mv.visitTypeInsn(CHECKCAST, call.type().getInternalName()); unboxPrimitive(state, call.type()); @@ -967,13 +990,16 @@ public class Codegen { } private void generateField(TargetField field) { - cw.visitField(field.access() | ACC_PUBLIC, field.name(), field.type().toSignature(), field.type().toGenericSignature(), null); + cw.visitField(field.access() | ACC_PUBLIC, field.name(), field.type().toSignature(), field.type().toDescriptor(), null); } private void generateConstructor(TargetConstructor constructor) { MethodVisitor mv = cw.visitMethod(constructor.access() | ACC_PUBLIC, "", constructor.getDescriptor(), constructor.getSignature(), null); + if (!constructor.txGenerics().isEmpty()) + mv.visitAttribute(new JavaTXSignatureAttribute(constructor.getTXSignature())); + mv.visitCode(); - var state = new State(mv, 1); + var state = new State(null, mv, 1); for (var param: constructor.parameters()) state.createVariable(param.name(), param.type()); @@ -996,8 +1022,11 @@ public class Codegen { private void generateMethod(TargetMethod method) { // TODO The older codegen has set ACC_PUBLIC for all methods, good for testing but bad for everything else MethodVisitor mv = cw.visitMethod(method.access() | ACC_PUBLIC, method.name(), method.getDescriptor(), method.getSignature(), null); + if (!method.txGenerics().isEmpty()) + mv.visitAttribute(new JavaTXSignatureAttribute(method.getTXSignature())); + mv.visitCode(); - var state = new State(mv, method.isStatic() ? 0 : 1); + var state = new State(method.returnType(), mv, method.isStatic() ? 0 : 1); for (var param: method.parameters()) state.createVariable(param.name(), param.type()); generate(state, method.block()); @@ -1007,22 +1036,25 @@ public class Codegen { mv.visitEnd(); } - private static String generateSignature(TargetClass clazz) { + private static String generateSignature(TargetClass clazz, Set generics) { String ret = "<"; - for (var generic : clazz.generics()) { - ret += generic.name() + ":" + generic.bound().toGenericSignature(); + for (var generic : generics) { + ret += generic.name() + ":" + generic.bound().toDescriptor(); } ret += ">"; - ret += clazz.superType().toGenericSignature(); + ret += clazz.superType().toDescriptor(); return ret; } public byte[] generate() { - cw.visit(V1_8, clazz.modifiers() | ACC_PUBLIC, clazz.qualifiedName(), - generateSignature(clazz), clazz.superType() != null ? clazz.superType().getInternalName(): "java/lang/Object", + cw.visit(V1_8, clazz.modifiers() | ACC_PUBLIC | ACC_SUPER, clazz.qualifiedName(), + generateSignature(clazz, clazz.generics()), clazz.superType() != null ? clazz.superType().getInternalName(): "java/lang/Object", clazz.implementingInterfaces().stream().map(TargetType::toSignature).toArray(String[]::new) ); + if (!clazz.txGenerics().isEmpty()) + cw.visitAttribute(new JavaTXSignatureAttribute(generateSignature(clazz, clazz.txGenerics()))); + clazz.fields().forEach(this::generateField); clazz.constructors().forEach(this::generateConstructor); clazz.methods().forEach(this::generateMethod); diff --git a/src/main/java/de/dhbwstuttgart/bytecode/Exception/BytecodeGeneratorError.java b/src/main/java/de/dhbwstuttgart/bytecode/Exception/BytecodeGeneratorError.java deleted file mode 100644 index 7d26f66f..00000000 --- a/src/main/java/de/dhbwstuttgart/bytecode/Exception/BytecodeGeneratorError.java +++ /dev/null @@ -1,19 +0,0 @@ -/** - * - */ -package de.dhbwstuttgart.bytecode.Exception; - -/** - * @author fayez - * - */ -public class BytecodeGeneratorError extends RuntimeException { - - /** - * @param message - */ - public BytecodeGeneratorError(String message) { - super(message); - } - -} diff --git a/src/main/java/de/dhbwstuttgart/bytecode/Exception/NotFoundException.java b/src/main/java/de/dhbwstuttgart/bytecode/Exception/NotFoundException.java deleted file mode 100644 index 829d08a9..00000000 --- a/src/main/java/de/dhbwstuttgart/bytecode/Exception/NotFoundException.java +++ /dev/null @@ -1,25 +0,0 @@ -/** - * - */ -package de.dhbwstuttgart.bytecode.Exception; - -/** - * @author fayez - * - */ -public class NotFoundException extends Exception { - - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * @param message - */ - public NotFoundException(String message) { - super(message); - } - - -} diff --git a/src/main/java/de/dhbwstuttgart/bytecode/Exception/NotInCurrentPackageException.java b/src/main/java/de/dhbwstuttgart/bytecode/Exception/NotInCurrentPackageException.java deleted file mode 100644 index 4c3293a6..00000000 --- a/src/main/java/de/dhbwstuttgart/bytecode/Exception/NotInCurrentPackageException.java +++ /dev/null @@ -1,26 +0,0 @@ -/** - * - */ -package de.dhbwstuttgart.bytecode.Exception; - -/** - * @author fayez - * - */ -public class NotInCurrentPackageException extends Exception { - - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * @param message - */ - public NotInCurrentPackageException(String message) { - super(message); - } - - - -} diff --git a/src/main/java/de/dhbwstuttgart/bytecode/FunNGenerator.java b/src/main/java/de/dhbwstuttgart/bytecode/FunNGenerator.java new file mode 100644 index 00000000..49c9b736 --- /dev/null +++ b/src/main/java/de/dhbwstuttgart/bytecode/FunNGenerator.java @@ -0,0 +1,123 @@ +package de.dhbwstuttgart.bytecode; + +import de.dhbwstuttgart.target.tree.type.TargetGenericType; +import de.dhbwstuttgart.target.tree.type.TargetRefType; +import de.dhbwstuttgart.target.tree.type.TargetType; +import org.objectweb.asm.ClassWriter; +import org.objectweb.asm.MethodVisitor; +import org.objectweb.asm.Type; + +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static org.objectweb.asm.Opcodes.*; + +/** + * //ToDo beschreiben + * + * @since Studienarbeit Type Erasure + * @author etiennezink + */ +public class FunNGenerator { + + private static final String argumentGenericBase = "T"; + private static final String returnGeneric = "R"; + private static final String methodName = "apply"; + private static final int bytecodeVersion = V1_8; + + private static final String objectSuperType = Type.getInternalName(Object.class).replace('.','/'); + private static final String objectSignature = applySignature(TargetType.Object); + + private static String applyDescriptor(TargetType a) { return a.toDescriptor(); } + private static String applySignature(TargetType a) { return a.toSignature(); } + private static String applyNameDescriptor(TargetType a){ return a instanceof TargetGenericType ? "LTPH;" : String.format("%s;", applySignature(a)); } + + public static byte[] generateSuperBytecode(int numberArguments) { + StringBuilder superFunNClassSignature = new StringBuilder("<"); + StringBuilder superFunNMethodSignature = new StringBuilder("("); + StringBuilder superFunNMethodDescriptor = new StringBuilder("("); + + for (int currentParameter = 1; currentParameter <= numberArguments; currentParameter++){ + superFunNClassSignature.append(String.format("%s%d:%s",argumentGenericBase, currentParameter, objectSignature)); + superFunNMethodSignature.append(String.format("%s", applySignature(new TargetRefType(argumentGenericBase + currentParameter)))); + superFunNMethodDescriptor.append(objectSignature); + } + superFunNClassSignature.append(String.format("%s:%s>%s", returnGeneric, objectSignature, objectSignature)); + superFunNMethodSignature.append(String.format(")%s", applySignature(new TargetRefType(returnGeneric)))); + superFunNMethodDescriptor.append(String.format(")%s", objectSignature)); + + System.out.println(superFunNMethodSignature); + + ClassWriter classWriter = new ClassWriter(0); + MethodVisitor methodVisitor; + classWriter.visit(bytecodeVersion, ACC_PUBLIC | ACC_ABSTRACT | ACC_INTERFACE, getSuperClassName(numberArguments), superFunNClassSignature.toString(), objectSuperType, null); + methodVisitor = classWriter.visitMethod(ACC_PUBLIC | ACC_ABSTRACT, methodName, superFunNMethodDescriptor.toString(), superFunNMethodSignature.toString(), null); + methodVisitor.visitEnd(); + classWriter.visitEnd(); + return classWriter.toByteArray(); + } + + public static String getSuperClassName(int numberArguments) { + return String.format("Fun%d$$", numberArguments); + } + + public static byte[] generateSpecializedBytecode(List argumentTypes, TargetType returnType) { + List parameters = Stream + .concat(argumentTypes.stream(), Stream.of(returnType)) + .collect(Collectors.toList()); + StringBuilder funNClassSignature = new StringBuilder(objectSignature + applySignature(new TargetRefType(getSuperClassName(argumentTypes.size()), parameters))); + boolean containsGeneric = false; + + String genericSignature = "<"; + for (TargetType typeArgument : parameters) { + //ToDo Etienne: Refactor + if (typeArgument instanceof TargetGenericType generic){ + //if(genericSignature.contains(generic.name())) continue; + genericSignature += String.format("%s:%s", generic.name(), applyDescriptor(generic)); + containsGeneric = true; + } + } + genericSignature += ">"; + if (containsGeneric) funNClassSignature.insert(0, genericSignature); + System.out.println(funNClassSignature.toString()); + + ClassWriter classWriter = new ClassWriter(0); + classWriter.visit(bytecodeVersion, ACC_PUBLIC | ACC_ABSTRACT | ACC_INTERFACE, getSpecializedClassName(argumentTypes, returnType), funNClassSignature.toString(), objectSuperType, new String[]{getSuperClassName(argumentTypes.size())}); + classWriter.visitEnd(); + return classWriter.toByteArray(); + } + + public static String getSpecializedClassName(List argumentTypes, TargetType returnType) { + return String.format("Fun%d$$%s%s", + argumentTypes.size(), + argumentTypes + .stream() + .map(FunNGenerator::applyNameDescriptor) + .collect(Collectors.joining()), + applyNameDescriptor(returnType)) + .replace('/', '$') + .replace(";", "$_$"); + } + + public static String getSpecializedDescriptor(List argumentTypes, TargetType returnType) { + return applyDescriptor(new TargetRefType(getSpecializedClassName(argumentTypes, returnType))); + } + + public static String getSpecializedSignature(List argumentTypes, TargetType returnType) { + return applySignature(new TargetRefType(getSpecializedClassName(argumentTypes, returnType))); + } + + public static List getArguments(List list) { + return list + .stream() + .limit(Math.max(0, list.size() - 1)) + .collect(Collectors.toList()); + } + + public static TargetType getReturnType(List list) { + if(list.size() == 0) + throw new IndexOutOfBoundsException(); + return list.get(list.size() - 1); + } +} diff --git a/src/main/java/de/dhbwstuttgart/bytecode/IStatement.java b/src/main/java/de/dhbwstuttgart/bytecode/IStatement.java deleted file mode 100644 index f8d61097..00000000 --- a/src/main/java/de/dhbwstuttgart/bytecode/IStatement.java +++ /dev/null @@ -1,9 +0,0 @@ -package de.dhbwstuttgart.bytecode; - -import org.objectweb.asm.Label; -import org.objectweb.asm.MethodVisitor; - -public interface IStatement { - public boolean isExprBinary(); - public void genBCForRelOp(MethodVisitor mv, Label branchLabel, Label endLabel, BytecodeGenMethod bytecodeGenMethod); -} diff --git a/src/main/java/de/dhbwstuttgart/bytecode/IfStatement.java b/src/main/java/de/dhbwstuttgart/bytecode/IfStatement.java deleted file mode 100644 index dc548f01..00000000 --- a/src/main/java/de/dhbwstuttgart/bytecode/IfStatement.java +++ /dev/null @@ -1,29 +0,0 @@ -package de.dhbwstuttgart.bytecode; - -import org.objectweb.asm.Label; -import org.objectweb.asm.MethodVisitor; -import org.objectweb.asm.Opcodes; - -import de.dhbwstuttgart.syntaxtree.statement.Expression; -import de.dhbwstuttgart.syntaxtree.statement.Statement; - -public class IfStatement extends AStatement{ - - private Statement then_block; - private Statement else_block; - - public IfStatement(Expression expr, Statement then_block, Statement else_block) { - super(expr); - this.then_block = then_block; - this.else_block = else_block; - } - - @Override - public void genBCForRelOp(MethodVisitor mv,Label branchLabel, Label endLabel, BytecodeGenMethod bytecodeGenMethod) { - bytecodeGenMethod.isBinary(false); - this.then_block.accept(bytecodeGenMethod); - - mv.visitLabel(branchLabel); - this.else_block.accept(bytecodeGenMethod); - } -} diff --git a/src/main/java/de/dhbwstuttgart/bytecode/JavaTXSignatureAttribute.java b/src/main/java/de/dhbwstuttgart/bytecode/JavaTXSignatureAttribute.java new file mode 100644 index 00000000..cc9d1487 --- /dev/null +++ b/src/main/java/de/dhbwstuttgart/bytecode/JavaTXSignatureAttribute.java @@ -0,0 +1,29 @@ +package de.dhbwstuttgart.bytecode; + +import org.objectweb.asm.*; + +import java.io.UnsupportedEncodingException; +import java.nio.charset.StandardCharsets; + +public class JavaTXSignatureAttribute extends Attribute { + final String signature; + + protected JavaTXSignatureAttribute(String signature) { + super("JavaTXSignature"); + this.signature = signature; + } + + @Override + protected Attribute read(ClassReader classReader, int offset, int length, char[] charBuffer, int codeAttributeOffset, Label[] labels) { + var data = new byte[length]; + System.arraycopy(classReader.b, offset, data, 0, length); + return new JavaTXSignatureAttribute(new String(data, StandardCharsets.UTF_8)); + } + + @Override + protected ByteVector write(ClassWriter classWriter, byte[] code, int codeLength, int maxStack, int maxLocals) { + var data = new ByteVector(); + data.putUTF8(this.signature); + return data; + } +} diff --git a/src/main/java/de/dhbwstuttgart/bytecode/LoopStmt.java b/src/main/java/de/dhbwstuttgart/bytecode/LoopStmt.java deleted file mode 100644 index 0f7788d4..00000000 --- a/src/main/java/de/dhbwstuttgart/bytecode/LoopStmt.java +++ /dev/null @@ -1,26 +0,0 @@ -package de.dhbwstuttgart.bytecode; - -import org.objectweb.asm.Label; -import org.objectweb.asm.MethodVisitor; -import org.objectweb.asm.Opcodes; - -import de.dhbwstuttgart.syntaxtree.statement.Expression; -import de.dhbwstuttgart.syntaxtree.statement.Statement; - -public class LoopStmt extends AStatement { - - private Statement loopBlock; - - public LoopStmt(Expression expr, Statement loopBlock) { - super(expr); - this.loopBlock = loopBlock; - } - - @Override - public void genBCForRelOp(MethodVisitor mv,Label branchLabel, Label endLabel, BytecodeGenMethod bytecodeGenMethod) { - bytecodeGenMethod.isBinary(false); - this.loopBlock.accept(bytecodeGenMethod); - mv.visitJumpInsn(Opcodes.GOTO, endLabel); - mv.visitLabel(branchLabel); - } -} diff --git a/src/main/java/de/dhbwstuttgart/bytecode/ReturnStmt.java b/src/main/java/de/dhbwstuttgart/bytecode/ReturnStmt.java deleted file mode 100644 index bd747720..00000000 --- a/src/main/java/de/dhbwstuttgart/bytecode/ReturnStmt.java +++ /dev/null @@ -1,14 +0,0 @@ -package de.dhbwstuttgart.bytecode; - -import org.objectweb.asm.MethodVisitor; - -import de.dhbwstuttgart.syntaxtree.statement.BinaryExpr; -import de.dhbwstuttgart.syntaxtree.statement.Expression; - -public class ReturnStmt extends AStatement { - - public ReturnStmt(Expression retexpr) { - super(retexpr); - } - -} diff --git a/src/main/java/de/dhbwstuttgart/bytecode/TPHExtractor.java b/src/main/java/de/dhbwstuttgart/bytecode/TPHExtractor.java deleted file mode 100644 index 6f443a47..00000000 --- a/src/main/java/de/dhbwstuttgart/bytecode/TPHExtractor.java +++ /dev/null @@ -1,269 +0,0 @@ -/** - * - */ -package de.dhbwstuttgart.bytecode; - -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.function.Function; -import java.util.function.Predicate; -import java.util.stream.Collectors; - -import de.dhbwstuttgart.bytecode.constraint.ExtendsConstraint; -import de.dhbwstuttgart.bytecode.constraint.TPHConstraint; -import de.dhbwstuttgart.bytecode.constraint.TPHConstraint.Relation; -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; -import de.dhbwstuttgart.syntaxtree.Method; -import de.dhbwstuttgart.syntaxtree.ParameterList; -import de.dhbwstuttgart.syntaxtree.statement.LocalVar; -import de.dhbwstuttgart.syntaxtree.statement.LocalVarDecl; -import de.dhbwstuttgart.syntaxtree.type.GenericRefType; -import de.dhbwstuttgart.syntaxtree.type.RefType; -import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric; -import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder; -import de.dhbwstuttgart.typeinference.constraints.Constraint; -import de.dhbwstuttgart.typeinference.constraints.ConstraintSet; -import de.dhbwstuttgart.typeinference.constraints.Pair; -import de.dhbwstuttgart.typeinference.result.GenericInsertPair; -import de.dhbwstuttgart.typeinference.result.ResultPair; -import de.dhbwstuttgart.typeinference.result.ResultSet; - -/** - * @author Fayez Abu Alia - * - */ -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 inLocalOrParamOrReturn = false; - - public final ArrayList ListOfMethodsAndTph = new ArrayList<>(); - - // Alle Constraints in einer Menge (Und- & Oder-Constraints) - public Set oldConstraints = new HashSet<>(); - - final ArrayList> allPairs = new ArrayList<>(); - public final ArrayList allCons = new ArrayList<>(); - private ResultSet resultSet; - private Resolver resolver; - - public TPHExtractor() { - - } - - public void setResultSet(ResultSet resultSet) { - this.resultSet = resultSet; - this.resolver = new Resolver(resultSet); - } - - public Resolver getResolver() { - return resolver; - } - -// @Override -// public void visit(ClassOrInterface classOrInterface) { -// inMethod = false; -// classOrInterface.getfieldInitializations().ifPresent(c->c.block.accept(this)); -// super.visit(classOrInterface); -// inMethod = true; -// } - @Override - public void visit(TypePlaceholder tph) { - if (resultSet.resolveType(tph).resolvedType instanceof TypePlaceholder) { - TypePlaceholder resolvedTPH = (TypePlaceholder) resultSet.resolveType(tph).resolvedType; - String tphName = resolvedTPH.getName(); - if (inMethod && !tphsClass.contains(tphName)) { - ArrayList tphs = null; - if (!(tphs = methodAndTph.getTphs()).contains(tphName)) { - methodAndTph.addTph(tphName); - } - if (inLocalOrParamOrReturn) { - if (!(tphs = methodAndTph.getLocalTphs()).contains(tphName)) { - tphs.add(tphName); - } - } - } else { - if (!tphsClass.contains(tphName)) { - tphsClass.add(tphName); - } - } - if (!allTPHS.containsKey(tphName)) { - allTPHS.put(tphName, inMethod); - } -// final List cons = new ArrayList<>(); -// resultSet.resolveType(tph).additionalGenerics.forEach(ag -> { -// TPHConstraint con = new ExtendsConstraint(ag.TA1.getName(), ag.TA2.getName(), Relation.EXTENDS); -// cons.add(con); -// }); -// -// Map visitMap = new HashMap<>(); -// for(TPHConstraint cc : cons) { -// visitMap.put(cc, false); -// } -// -// String left = resolvedTPH.getName(); -// for (TPHConstraint cc : visitMap.keySet()) { -// -// if(visitMap.get(cc)) -// continue; -// -// if (cc.getLeft().equals(left)) { -// allCons.add(cc); -// List toVisit = getToVisitCons(cons,cc.getRight(), visitMap); -// } -// } - - //resultSet.resolveType(tph).getAdditionalGenerics().forEach(ag -> { - resultSet.genIns.forEach(ag -> { - -// if (ag.contains(resolvedTPH) /* && ag.TA1.equals(resolvedTPH) */ && !contains(allPairs, ag)) { - if (inMethod) - methodAndTph.getPairs().add(ag); - allPairs.add(ag); - TPHConstraint con = new ExtendsConstraint(ag.getLeft().getName(), ag.getRight().getName()); - if(!containsConstraint(allCons,con)) - allCons.add(con); -// } - }); - } else if (resultSet.resolveType(tph).resolvedType instanceof RefType) { - RefType rt = (RefType) resultSet.resolveType(tph).resolvedType; - rt.accept(this); - } - } - - private static boolean containsConstraint(ArrayList allCons, TPHConstraint c) { - for(TPHConstraint con:allCons) { - if(c.getLeft().equals(con.getLeft()) && c.getRight().equals(con.getRight())) { - return true; - } - } - return false; - } - - private List getToVisitCons(List cons, String right, Map visitMap) { - List res = new ArrayList<>(); - for(TPHConstraint cc : cons) { - if(cc.getLeft().equals(right)) { - res.add(cc); - if(visitMap.get(cc)) - visitMap.replace(cc, false); - } - } - return res; - } - - @Override - public void visit(GenericRefType genericRefType) { - String name = genericRefType.getParsedName(); - if (inMethod) { - methodAndTph.addTph(name); - if (inLocalOrParamOrReturn) - methodAndTph.getLocalTphs().add(name); - }else { - tphsClass.add(name); - } - allTPHS.put(name, inMethod); - } - - private boolean contains(ArrayList pairs, GenericInsertPair genPair) { - for (int i = 0; i < pairs.size(); ++i) { - GenericInsertPair p = pairs.get(i); - if (p.TA1.equals(genPair.TA1) && p.TA2.equals(genPair.TA2)) - return true; - } - return false; - } - - @Override - public void visit(Method method) { - inMethod = true; - String id = MethodUtility.createID(resolver,method); - Predicate filterUndConstraints = cs -> ((cs.TA1 instanceof TypePlaceholder) && (cs.TA2 instanceof TypePlaceholder) && - (resultSet.resolveType((TypePlaceholder)(cs.TA1)).resolvedType instanceof TypePlaceholder) && - (resultSet.resolveType((TypePlaceholder)(cs.TA2)).resolvedType instanceof TypePlaceholder)); - - Function, ConstraintSet> filterConstrRemainingTVar = - csS -> { - ConstraintSet ret = new ConstraintSet<>(); - ret.addAllUndConstraint( - csS.getUndConstraints() - .stream().filter(filterUndConstraints) - .collect(Collectors.toCollection(Constraint::new))); - - csS.getOderConstraints() - .forEach(oConSSet -> { Set> setCons = new HashSet<>(); - oConSSet.forEach(OConS -> { Constraint newConsPair = new Constraint(); - newConsPair.isStatement = OConS.isStatement; - setCons.add( - OConS.stream() - .filter(filterUndConstraints) - .collect(Collectors.toCollection(() -> newConsPair)) ); - } ); - ret.addOderConstraint(setCons);} ); - return ret; - }; - ConstraintSet filteredConstraints = filterConstrRemainingTVar.apply(method.getConstraints()); - methodAndTph = new MethodAndTPH(id, filteredConstraints); - oldConstraints.addAll(filteredConstraints.getAll()); - - 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); - } - - @Override - public void visit(Constructor cons) { - inMethod = false; - //super.visit(cons); - cons.getParameterList().accept(this); - if(cons.block != null) - cons.block.accept(this); - inMethod = true; - } - - @Override - public void visit(LocalVarDecl localVarDecl) { -// inLocalOrParamOrReturn = inMethod; - super.visit(localVarDecl); -// inLocalOrParamOrReturn = false; - } - - @Override - public void visit(LocalVar localVar) { -// inLocalOrParamOrReturn = inMethod; - super.visit(localVar); -// inLocalOrParamOrReturn = false; - } - - @Override - public void visit(ParameterList formalParameters) { - inLocalOrParamOrReturn = inMethod; - super.visit(formalParameters); - inLocalOrParamOrReturn = false; - } - -} \ No newline at end of file diff --git a/src/main/java/de/dhbwstuttgart/bytecode/descriptor/DescriptorToString.java b/src/main/java/de/dhbwstuttgart/bytecode/descriptor/DescriptorToString.java deleted file mode 100644 index c272c12f..00000000 --- a/src/main/java/de/dhbwstuttgart/bytecode/descriptor/DescriptorToString.java +++ /dev/null @@ -1,260 +0,0 @@ -package de.dhbwstuttgart.bytecode.descriptor; - -import java.util.HashMap; -import java.util.Iterator; - -import de.dhbwstuttgart.bytecode.utilities.*; -import de.dhbwstuttgart.syntaxtree.statement.ArgumentList; -import org.objectweb.asm.Type; - -import de.dhbwstuttgart.syntaxtree.FormalParameter; -import de.dhbwstuttgart.syntaxtree.statement.Expression; -import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric; -import de.dhbwstuttgart.typeinference.result.ResultSet; - -public class DescriptorToString implements DescriptorVisitor, CONSTANTS { - ResultSet resultSet; - - public DescriptorToString() { - } - - public DescriptorToString(ResultSet resultSet) { - this.resultSet = resultSet; - } - - private String addReturnType(String desc, RefTypeOrTPHOrWildcardOrGeneric returnType, ResultSet resultSet) { - if(resultSet.resolveType(returnType).resolvedType.toString().equals(CONSTANTS.VOID)){ - desc = desc + ")V"; - }else { - desc = desc + ")" + "L"+resultSet.resolveType(returnType).resolvedType.acceptTV(new TypeToDescriptor())+ ";"; - } - return desc; - } - - @Override - public String visit(NormalMethod method) { - - String desc = "("; - Iterator itr = method.getParameterList().iterator(); - while(itr.hasNext()) { - FormalParameter fp = itr.next(); -// System.out.println(resultSet.resolveType(fp.getType()).resolvedType.acceptTV(new TypeToSignature())); -// System.out.println("Parmetrisierte typ ? "+ ((RefType) fp.getType()).getParaList().size()); - if(method.hasGen()) { - String fpDesc = fp.getType().acceptTV(new TypeToDescriptor()); - if(method.getGenericsAndBoundsMethod().containsKey(fpDesc)) { - String bound = getBound(fpDesc, method.getGenericsAndBoundsMethod()); - desc += "L"+bound+ ";"; - }else if(method.getGenericsAndBounds().containsKey(fpDesc)){ - String bound = getBound(fpDesc, method.getGenericsAndBounds()); - desc += "L"+bound+ ";"; - }else { -// desc += "L"+resultSet.resolveType(fp.getType()).resolvedType.acceptTV(new TypeToDescriptor())+ ";"; - String resType = resultSet.resolveType(fp.getType()).resolvedType.acceptTV(new TypeToDescriptor()); - if(resType.contains(CONSTANTS.TPH)/*resType.subSequence(0, 4).equals("TPH ")*/) { - // Bound ist immer Object - desc += "L"+Type.getInternalName(Object.class)+ ";"; - } else { - // TODO:: - if(method.getGenericsAndBounds().containsKey(resType)) { - String bound = getBound(resType, method.getGenericsAndBounds()); - desc += "L"+bound+ ";"; - }else if(method.getGenericsAndBoundsMethod().containsKey(resType)) { - String bound = getBound(resType, method.getGenericsAndBoundsMethod()); - desc += "L"+bound+ ";"; - } else { - desc += "L"+resType+ ";"; - } - } - } - } - //TODO: generate a class java%% ... %% - else if(resultSet.resolveType(fp.getType()).resolvedType.acceptTV(new TypeToDescriptor()).contains(CONSTANTS.ANGLEBRACKET)){ - desc += "L"+resultSet.resolveType(fp.getType()).resolvedType.toString().replace(".", "$$").replace(CONSTANTS.ANGLEBRACKET, "$$$").replace(">", "$$$")+ ";"; - } - else { - desc += "L"+resultSet.resolveType(fp.getType()).resolvedType.acceptTV(new TypeToDescriptor())+ ";"; - } - } - - if(resultSet.resolveType(method.getReturnType()).resolvedType.toString().equals(CONSTANTS.VOID)) { - desc += ")V"; - }else { - if(method.hasGen()) { - String ret = method.getReturnType().acceptTV(new TypeToDescriptor()); - if(method.getGenericsAndBoundsMethod().containsKey(ret)) { - desc += ")L"+method.getGenericsAndBoundsMethod().get(ret)+ ";"; - }else if(method.getGenericsAndBounds().containsKey(ret)){ - desc += ")L"+method.getGenericsAndBounds().get(ret)+ ";"; - }else { - String resType = resultSet.resolveType(method.getReturnType()).resolvedType.acceptTV(new TypeToDescriptor()); - if(resType.contains(CONSTANTS.TPH)/*resType.subSequence(0, 4).equals("TPH ")*/) { -// desc += ")" + "L"+method.getGenericsAndBoundsMethod().get(resType.substring(4)+"$")+ ";"; - desc += ")" + "L"+Type.getInternalName(Object.class)+ ";"; - } else { - // TODO:: - if(method.getGenericsAndBounds().containsKey(resType)) { - String bound = getBound(resType, method.getGenericsAndBounds()); - desc += ")L"+bound+ ";"; - }else if(method.getGenericsAndBoundsMethod().containsKey(resType)) { - String bound = getBound(resType, method.getGenericsAndBoundsMethod()); - desc += ")L"+bound+ ";"; - } else { - desc += ")L"+resType+ ";"; - } -// desc += ")" + "L"+resType+ ";"; - } - } - }else { - desc += ")" + "L"+resultSet.resolveType(method.getReturnType()).resolvedType.acceptTV(new TypeToDescriptor())+ ";"; - } - } -// desc = addReturnType(desc,method.getReturnType(), resultSet); - return desc; - } - - private String getBound(String fpDesc, HashMap genericsAndBounds) { - String start = genericsAndBounds.get(fpDesc); - while(genericsAndBounds.containsKey(start)) { - start = genericsAndBounds.get(start); - } - - return start; - } - - @Override - public String visit(NormalConstructor constructor) { - String desc = "("; - Iterator itr = constructor.getParameterList().iterator(); - while(itr.hasNext()) { - FormalParameter fp = itr.next(); - if(constructor.hasGen()) { -// System.out.println("Cons has Gens"); - String fpDesc = fp.getType().acceptTV(new TypeToDescriptor()); -// System.out.println(fpDesc); - if(constructor.getGenericsAndBounds().containsKey(fpDesc)){ - desc += "L"+constructor.getGenericsAndBounds().get(fpDesc)+ ";"; - }else { -// desc += "L"+resultSet.resolveType(fp.getType()).resolvedType.acceptTV(new TypeToDescriptor())+ ";"; - String resType = resultSet.resolveType(fp.getType()).resolvedType.acceptTV(new TypeToDescriptor()); - if(resType.subSequence(0, 4).equals(CONSTANTS.TPH)) { - // Bound ist immer Object - desc += "L"+Type.getInternalName(Object.class)+ ";"; - } else { - desc += "L"+resType+ ";"; - } - } - }else { -// System.out.println("Cons has NO Gens"); - desc += "L"+resultSet.resolveType(fp.getType()).resolvedType.acceptTV(new TypeToDescriptor())+ ";"; - } - } - desc = desc + ")V"; - return desc; - } - - //ToDo Etienne: ändern - @Override - public String visit(Lambda lambdaExpression) { - String desc = "("; - Iterator itr = lambdaExpression.getParams().iterator(); - while(itr.hasNext()) { - FormalParameter fp = itr.next(); - String d = resultSet.resolveType(fp.getType()).resolvedType.acceptTV(new TypeToDescriptor()); - if(d.contains(CONSTANTS.TPH) ||d.contains(CONSTANTS.ANGLEBRACKET)) { - desc += "L"+Type.getInternalName(Object.class)+ ";"; - }else { - desc = desc + "L"+ d + ";"; - } - } - - String retType = resultSet.resolveType(lambdaExpression.getReturnType()).resolvedType.acceptTV(new TypeToDescriptor()); - - if(retType.contains(CONSTANTS.TPH)|| retType.contains(CONSTANTS.ANGLEBRACKET)){ - desc += ")L"+Type.getInternalName(Object.class)+ ";"; - }else { - desc = desc + ")"+"L"+retType+";"; - } - return desc; - } - - @Override - public String visit(SamMethod samMethod) { - String desc = "("; - Iterator itr = samMethod.getArgumentList().iterator(); - while(itr.hasNext()) { - RefTypeOrTPHOrWildcardOrGeneric rt = itr.next(); - String d = resultSet.resolveType(rt).resolvedType.acceptTV(new TypeToDescriptor()); - - if(d.contains(CONSTANTS.TPH) ||d.contains(CONSTANTS.ANGLEBRACKET)) { - desc += "L"+Type.getInternalName(Object.class)+ ";"; - }else { - desc += "L"+ d + ";"; - - } - } - String retType = resultSet.resolveType(samMethod.getReturnType()).resolvedType.acceptTV(new TypeToDescriptor()); - - if(retType.contains(CONSTANTS.TPH)|| retType.contains(CONSTANTS.ANGLEBRACKET)){ - desc += ")L"+Type.getInternalName(Object.class)+ ";"; - }else { - desc = desc + ")"+"L"+retType+";"; - } - return desc; - } - - @Override - public String visit(MethodFromMethodCall methodFromMethodCall) { - String desc = "("; - for(Expression e : methodFromMethodCall.getArgList().getArguments()) { - String d = resultSet.resolveType(e.getType()).resolvedType.acceptTV(new TypeToDescriptor()); - - if(d.contains(CONSTANTS.TPH) ||d.contains(CONSTANTS.ANGLEBRACKET) || methodFromMethodCall.getReceiverName().contains("$$")) { - desc += "L"+Type.getInternalName(Object.class)+ ";"; - }else { - if(methodFromMethodCall.getGenericsAndBoundsMethod().containsKey(d)) { - desc += "L"+methodFromMethodCall.getGenericsAndBoundsMethod().get(d)+ ";"; - }else if(methodFromMethodCall.getGenericsAndBounds().containsKey(d)) { - desc += "L"+methodFromMethodCall.getGenericsAndBounds().get(d)+ ";"; - }else { - desc += "L"+resultSet.resolveType(e.getType()).resolvedType.acceptTV(new TypeToDescriptor())+ ";"; - } - } - - } - String retType = resultSet.resolveType(methodFromMethodCall.getReturnType()).resolvedType.acceptTV(new TypeToDescriptor()); - System.out.println("DescriptorToString retType = " + retType); - if(retType.equals(CONSTANTS.VOID)) { - desc += ")V"; - }else if(retType.contains(CONSTANTS.TPH)|| retType.contains(CONSTANTS.ANGLEBRACKET) || methodFromMethodCall.getReceiverName().contains("$$")){ - desc += ")L"+Type.getInternalName(Object.class)+ ";"; - }else { - if(methodFromMethodCall.getGenericsAndBoundsMethod().containsKey(retType)) { - desc += ")L"+methodFromMethodCall.getGenericsAndBoundsMethod().get(retType)+ ";"; - }else if(methodFromMethodCall.getGenericsAndBounds().containsKey(retType)){ - desc += ")L"+methodFromMethodCall.getGenericsAndBounds().get(retType)+ ";"; - }else { - desc += ")" + "L"+retType+ ";"; - } - } -// desc = addReturnType(desc, methodFromMethodCall.getReturnType(), resultSet); - return desc; - } - - @Override - public String createDescForFunN(ArgumentList argumentList, String returnType) { - Iterator itr1 = argumentList.getArguments().iterator(); - String methDesc = "("; - while(itr1.hasNext()) { - methDesc += "L" + Type.getInternalName(Object.class) + ";"; - itr1.next(); - } - if (returnType.equals(CONSTANTS.VOID)){ - methDesc += ")V"; - } else { - methDesc += ")L" + Type.getInternalName(Object.class) + ";"; - } - return methDesc; - } - -} diff --git a/src/main/java/de/dhbwstuttgart/bytecode/descriptor/DescriptorVisitor.java b/src/main/java/de/dhbwstuttgart/bytecode/descriptor/DescriptorVisitor.java deleted file mode 100644 index d1576c76..00000000 --- a/src/main/java/de/dhbwstuttgart/bytecode/descriptor/DescriptorVisitor.java +++ /dev/null @@ -1,17 +0,0 @@ -package de.dhbwstuttgart.bytecode.descriptor; - -import de.dhbwstuttgart.bytecode.utilities.Lambda; -import de.dhbwstuttgart.bytecode.utilities.MethodFromMethodCall; -import de.dhbwstuttgart.bytecode.utilities.NormalConstructor; -import de.dhbwstuttgart.bytecode.utilities.NormalMethod; -import de.dhbwstuttgart.bytecode.utilities.SamMethod; -import de.dhbwstuttgart.syntaxtree.statement.ArgumentList; - -public interface DescriptorVisitor { - String visit(NormalMethod method); - String visit(NormalConstructor constructor); - String visit(Lambda lambdaExpression); - String visit(SamMethod samMethod); - String visit(MethodFromMethodCall methodFromMethodCall); - String createDescForFunN(ArgumentList argumentList, String returnType); -} diff --git a/src/main/java/de/dhbwstuttgart/bytecode/descriptor/TypeToDescriptor.java b/src/main/java/de/dhbwstuttgart/bytecode/descriptor/TypeToDescriptor.java deleted file mode 100644 index f10f8070..00000000 --- a/src/main/java/de/dhbwstuttgart/bytecode/descriptor/TypeToDescriptor.java +++ /dev/null @@ -1,52 +0,0 @@ -package de.dhbwstuttgart.bytecode.descriptor; - -import de.dhbwstuttgart.bytecode.funN.FunNGenerator; -import de.dhbwstuttgart.bytecode.funN.FunNUtilities; -import de.dhbwstuttgart.syntaxtree.type.*; - -public class TypeToDescriptor implements TypeVisitor{ - - private final boolean specializedFunN; - - public TypeToDescriptor(){ this(true); } - - public TypeToDescriptor(boolean specializedFunN) { this.specializedFunN = specializedFunN; } - - @Override - public String visit(RefType refType) { - if (refType.getName().toString().matches("Fun\\d+\\$\\$") && specializedFunN) { - FunNUtilities funNUtilities = FunNGenerator.getInstance(); - return funNUtilities.getSpecializedDescriptor(funNUtilities.getArguments(refType.getParaList()), funNUtilities.getReturnType(refType.getParaList())); - } - - return refType.getName().toString().replace(".", "/"); -// String t = refType.getName().toString().replace(".", "/"); -// return t.equals("Fun1")?(t+"$$"):t; - } - - @Override - public String visit(SuperWildcardType superWildcardType) { - System.out.println("\nWILDCARD ="+superWildcardType.getInnerType().toString().replace(".", "/")); - //return superWildcardType.getInnerType().toString().replace(".", "/"); - return superWildcardType.getInnerType().acceptTV(new TypeToDescriptor()); - //throw new NotImplementedException(); - } - - @Override - public String visit(TypePlaceholder typePlaceholder) { - return typePlaceholder.toString().replace(".", "/"); - } - - @Override - public String visit(ExtendsWildcardType extendsWildcardType) { - System.out.println("\nWILDCARD extends ="+extendsWildcardType.getInnerType().toString().replace(".", "/")); - //return extendsWildcardType.getInnerType().toString().replace(".", "/"); - return extendsWildcardType.getInnerType().acceptTV(new TypeToDescriptor()); - //throw new NotImplementedException(); - } - - @Override - public String visit(GenericRefType genericRefType) { - return genericRefType.getParsedName().replace(".", "/"); - } -} \ No newline at end of file diff --git a/src/main/java/de/dhbwstuttgart/bytecode/funN/FunNGenerator.java b/src/main/java/de/dhbwstuttgart/bytecode/funN/FunNGenerator.java deleted file mode 100644 index 3a651c93..00000000 --- a/src/main/java/de/dhbwstuttgart/bytecode/funN/FunNGenerator.java +++ /dev/null @@ -1,149 +0,0 @@ -package de.dhbwstuttgart.bytecode.funN; - -import de.dhbwstuttgart.bytecode.descriptor.TypeToDescriptor; -import de.dhbwstuttgart.bytecode.signature.TypeToSignature; -import de.dhbwstuttgart.bytecode.utilities.CONSTANTS; -import de.dhbwstuttgart.parser.scope.JavaClassName; -import de.dhbwstuttgart.syntaxtree.type.GenericRefType; -import de.dhbwstuttgart.syntaxtree.type.RefType; -import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric; -import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder; -import org.objectweb.asm.ClassWriter; -import org.objectweb.asm.MethodVisitor; -import org.objectweb.asm.Type; - -import java.io.File; -import java.io.FileOutputStream; -import java.util.List; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import static org.objectweb.asm.Opcodes.*; - -/** - * //ToDo beschreiben - * - * @since Studienarbeit Type Erasure - * @author etiennezink - */ -public class FunNGenerator implements FunNUtilities{ - - private static FunNGenerator funNGenerator = new FunNGenerator(); - - public static FunNGenerator getInstance(){ - return funNGenerator; - } - - private final String argumentGenericBase = "T"; - private final String returnGeneric = "R"; - private final String methodName = "apply"; - private final int bytecodeVersion = V1_8; - - private final String objectSuperType = Type.getInternalName(Object.class).replace('.','/'); - private final RefType objectRefType = new RefType(new JavaClassName(objectSuperType), null); - private final String objectSignature = applySignature(objectRefType); - - private String applyDescriptor(RefTypeOrTPHOrWildcardOrGeneric a) { return a.acceptTV(new TypeToDescriptor(true)); } - private String applySignature(RefTypeOrTPHOrWildcardOrGeneric a) { return a.acceptTV(new TypeToSignature(true)); } - private String applyNameDescriptor(RefTypeOrTPHOrWildcardOrGeneric a){ return a instanceof TypePlaceholder ? "LTPH;" : String.format("L%s;", applyDescriptor(a)); } - - @Override - public byte[] generateSuperBytecode(int numberArguments) { - StringBuilder superFunNClassSignature = new StringBuilder("<"); - StringBuilder superFunNMethodSignature = new StringBuilder("("); - StringBuilder superFunNMethodDescriptor = new StringBuilder("("); - - for (int currentParameter = 1; currentParameter <= numberArguments; currentParameter++){ - superFunNClassSignature.append(String.format("%s%d:%s",argumentGenericBase, currentParameter, objectSignature)); - superFunNMethodSignature.append(String.format("T%s;", applySignature( new GenericRefType(argumentGenericBase + currentParameter, null)))); - superFunNMethodDescriptor.append(objectSignature); - } - superFunNClassSignature.append(String.format("%s:%s>%s", returnGeneric, objectSignature, objectSignature)); - superFunNMethodSignature.append(String.format(")T%s;", applySignature(new GenericRefType(returnGeneric, null)))); - superFunNMethodDescriptor.append(String.format(")%s", objectSignature)); - - ClassWriter classWriter = new ClassWriter(0); - MethodVisitor methodVisitor; - classWriter.visit(bytecodeVersion, ACC_PUBLIC | ACC_ABSTRACT | ACC_INTERFACE, getSuperClassName(numberArguments), superFunNClassSignature.toString(), objectSuperType, null); - methodVisitor = classWriter.visitMethod(ACC_PUBLIC | ACC_ABSTRACT, methodName, superFunNMethodDescriptor.toString(), superFunNMethodSignature.toString(), null); - methodVisitor.visitEnd(); - classWriter.visitEnd(); - return classWriter.toByteArray(); - } - - @Override - public String getSuperClassName(int numberArguments) { - return String.format("Fun%d$$", numberArguments); - } - - @Override - public byte[] generateSpecializedBytecode(List argumentTypes, RefTypeOrTPHOrWildcardOrGeneric returnType) { - List parameters = Stream - .concat(argumentTypes.stream(), Stream.of(returnType)) - .collect(Collectors.toList()); - RefType superFunN = new RefType(new JavaClassName(getSuperClassName(argumentTypes.size())), parameters , null); - StringBuilder funNClassSignature = new StringBuilder(objectSignature + (superFunN.acceptTV(new TypeToSignature(false)))); - boolean containsGeneric = false; - - String genericSignature = "<"; - for (RefTypeOrTPHOrWildcardOrGeneric typeArgument : parameters) { - //ToDo Etienne: Refactor - if (typeArgument instanceof GenericRefType){ - GenericRefType generic = (GenericRefType) typeArgument; - if(genericSignature.contains(generic.getParsedName())) continue; - genericSignature += String.format("%s:%s", generic.getParsedName(), applyDescriptor(generic)); - containsGeneric = true; - } else if(typeArgument instanceof TypePlaceholder){ - TypePlaceholder placeholder = (TypePlaceholder) typeArgument; - if(genericSignature.contains(applySignature(placeholder).substring(1))) continue; - genericSignature += String.format("%s:%s", applySignature(placeholder).substring(1), objectSignature); - containsGeneric = true; - } - } - genericSignature += ">"; - if (containsGeneric) funNClassSignature.insert(0, genericSignature); - - ClassWriter classWriter = new ClassWriter(0); - classWriter.visit(bytecodeVersion, ACC_PUBLIC | ACC_ABSTRACT | ACC_INTERFACE, getSpecializedClassName(argumentTypes, returnType), funNClassSignature.toString(), objectSuperType, new String[]{getSuperClassName(argumentTypes.size())}); - classWriter.visitEnd(); - return classWriter.toByteArray(); - } - - @Override - public String getSpecializedClassName(List argumentTypes, RefTypeOrTPHOrWildcardOrGeneric returnType) { - return String.format("Fun%d$$%s%s", - argumentTypes.size(), - argumentTypes - .stream() - .map(this::applyNameDescriptor) - .collect(Collectors.joining()), - applyNameDescriptor(returnType)) - .replace('/', '$') - .replace(";", "$_$"); - } - - @Override - public String getSpecializedDescriptor(List argumentTypes, RefTypeOrTPHOrWildcardOrGeneric returnType) { - return applyDescriptor(new RefType(new JavaClassName(getSpecializedClassName(argumentTypes, returnType)), null)); - } - - @Override - public String getSpecializedSignature(List argumentTypes, RefTypeOrTPHOrWildcardOrGeneric returnType) { - return applySignature(new RefType(new JavaClassName(getSpecializedClassName(argumentTypes, returnType)), null)); - } - - @Override - public List getArguments(List list) { - return list - .stream() - .limit(Math.max(0, list.size() - 1)) - .collect(Collectors.toList()); - } - - @Override - public RefTypeOrTPHOrWildcardOrGeneric getReturnType(List list) { - if(list.size() == 0) - throw new IndexOutOfBoundsException(); - return list.get(list.size() - 1); - } -} diff --git a/src/main/java/de/dhbwstuttgart/bytecode/funN/FunNUtilities.java b/src/main/java/de/dhbwstuttgart/bytecode/funN/FunNUtilities.java deleted file mode 100644 index 7ae4da4d..00000000 --- a/src/main/java/de/dhbwstuttgart/bytecode/funN/FunNUtilities.java +++ /dev/null @@ -1,36 +0,0 @@ -package de.dhbwstuttgart.bytecode.funN; - -import de.dhbwstuttgart.bytecode.utilities.CONSTANTS; -import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric; - -import java.io.File; -import java.io.FileOutputStream; -import java.util.List; - -public interface FunNUtilities { - - byte[] generateSuperBytecode(int numberArguments); - String getSuperClassName(int numberArguments); - - byte[] generateSpecializedBytecode(List argumentTypes, RefTypeOrTPHOrWildcardOrGeneric returnType); - String getSpecializedClassName(List argumentTypes, RefTypeOrTPHOrWildcardOrGeneric returnType); - String getSpecializedDescriptor(List argumentTypes, RefTypeOrTPHOrWildcardOrGeneric returnType); - String getSpecializedSignature(List argumentTypes, RefTypeOrTPHOrWildcardOrGeneric returnType); - - List getArguments(List list); - RefTypeOrTPHOrWildcardOrGeneric getReturnType(List list); - - @Deprecated - public static boolean writeClassFile(String className, byte[] bytecode, File directory) { - try (FileOutputStream output = new FileOutputStream(new File(directory , className + CONSTANTS.EXTENSIONCLASS))){ - output.write(bytecode); - output.flush(); - return true; - } catch (Exception e) { - e.printStackTrace(); - } - return false; - } - - -} diff --git a/src/main/java/de/dhbwstuttgart/bytecode/genericsGenerator/ConstraintsSimplierResult.java b/src/main/java/de/dhbwstuttgart/bytecode/genericsGenerator/ConstraintsSimplierResult.java deleted file mode 100644 index 5ed0bd5e..00000000 --- a/src/main/java/de/dhbwstuttgart/bytecode/genericsGenerator/ConstraintsSimplierResult.java +++ /dev/null @@ -1,53 +0,0 @@ -/** - * - */ -package de.dhbwstuttgart.bytecode.genericsGenerator; - -import java.util.List; - -import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.NameReplacementResult; -import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.GenericsGeneratorResult; - -/** - * This class represents the result of the constraints simplifier. - * - * @author fayez - * - */ -public class ConstraintsSimplierResult { - private List genericsGenResults; - private List nameReplacementResults; - /** - * @param genericsGenResults - */ - public ConstraintsSimplierResult(List genericsGenResults, - List nameReplacementResults) { - this.genericsGenResults = genericsGenResults; - this.setNameReplacementResults(nameReplacementResults); - } - /** - * @return the genericsGenResults - */ - public List getGenericsGenResults() { - return genericsGenResults; - } - /** - * @param genericsGenResults the genericsGenResults to set - */ - public void setGenericsGenResults(List genericsGenResults) { - this.genericsGenResults = genericsGenResults; - } - /** - * @return the nameReplacementResults - */ - public List getNameReplacementResults() { - return nameReplacementResults; - } - /** - * @param nameReplacementResults the nameReplacementResults to set - */ - public void setNameReplacementResults(List nameReplacementResults) { - this.nameReplacementResults = nameReplacementResults; - } - -} diff --git a/src/main/java/de/dhbwstuttgart/bytecode/genericsGenerator/ConstraintsSimplifier.java b/src/main/java/de/dhbwstuttgart/bytecode/genericsGenerator/ConstraintsSimplifier.java deleted file mode 100644 index b510c71b..00000000 --- a/src/main/java/de/dhbwstuttgart/bytecode/genericsGenerator/ConstraintsSimplifier.java +++ /dev/null @@ -1,137 +0,0 @@ -/** - * - */ -package de.dhbwstuttgart.bytecode.genericsGenerator; - -import java.util.*; - -import de.dhbwstuttgart.bytecode.TPHExtractor; -import de.dhbwstuttgart.bytecode.constraint.TPHConstraint; -import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.*; - -/** - * @author fayez - * - */ -public class ConstraintsSimplifier { - public static ConstraintsSimplierResult simplifyConstraints(final TPHExtractor tphExtractor, final List genericsGeneratorResults, final List tphsClass) { - - List allCons = tphExtractor.allCons; - List equalCons = new ArrayList<>(); - - /* Step 1 */ - List foundCons = GenericsGeneratorUtility.findConstraintsWithLeftSameLeftSide(allCons); - if(!foundCons.isEmpty()) { - 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 cycles = findCycles(allCons); - - if(!cycles.isEmpty()) { - handleCycle(genericsGeneratorResults, allCons, cycles,tphExtractor); - } - /* The right hand side of equal constraint is the new name in name replacement result */ - List 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 cycles - * @param tphExtractor - */ - public static void handleCycle(List genericsGeneratorResults, - List allCons, List cycles, TPHExtractor tphExtractor) { - GenericsGeneratorUtility.modifyRelationForConstraintsInCycle(cycles); - List nameReplacementResults = GenericsGeneratorUtility.substituteTPHSFormCycle(allCons, cycles,tphExtractor); - GenericsGeneratorUtility.createResults(genericsGeneratorResults,nameReplacementResults); - GenericsGeneratorUtility.removeEqualConstraints(allCons); - } - - /** - * @param allCons - * @return - */ - public static List findCycles(List allCons) { - /* find all cycles */ - CyclesFinder cyclesFinder = new CyclesFinder(allCons); - List cycles = cyclesFinder.findCycles(); - return cycles; - } - -} diff --git a/src/main/java/de/dhbwstuttgart/bytecode/genericsGenerator/CyclesFinder.java b/src/main/java/de/dhbwstuttgart/bytecode/genericsGenerator/CyclesFinder.java deleted file mode 100644 index 9b0867f5..00000000 --- a/src/main/java/de/dhbwstuttgart/bytecode/genericsGenerator/CyclesFinder.java +++ /dev/null @@ -1,106 +0,0 @@ -/** - * - */ -package de.dhbwstuttgart.bytecode.genericsGenerator; - -import java.util.ArrayList; -import java.util.LinkedList; -import java.util.List; -import java.util.Optional; - -import de.dhbwstuttgart.bytecode.constraint.TPHConstraint; -import de.dhbwstuttgart.bytecode.constraint.TPHConstraint.Relation; -import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.Cycle; - -/** - * @author fayez - * - */ -public class CyclesFinder { - private final List allCons; - - public CyclesFinder(List allCons) { - this.allCons = allCons; - } - - public List findCycles() { - List vistedConstraints = new ArrayList<>(allCons.size()); - List cycles = new ArrayList<>(); - for (TPHConstraint constraint : allCons) { - if(constraint.getRel()==Relation.EQUAL) - continue; - if (!vistedConstraints.contains(constraint)) { - vistedConstraints.add(constraint); - checkConstraint(constraint, vistedConstraints, cycles); - } - } - return cycles; - } - - private void checkConstraint(TPHConstraint constraint, List vistedConstraints, - List cycles) { - List tphsInRelation = new LinkedList<>(); - List maybeCycle = new ArrayList<>(); - maybeCycle.add(constraint); - tphsInRelation.add(constraint.getLeft()); - tphsInRelation.add(constraint.getRight()); - Optional nextConstraint = getConstraintInRelation(tphsInRelation, maybeCycle); - while (nextConstraint.isPresent()) { - if(containsInLongCycle(nextConstraint.get(), cycles)) { - break; - } - if (isCycle(tphsInRelation)) { - addAllToVisitedConstraints(vistedConstraints, maybeCycle); - Cycle cycle = new Cycle(maybeCycle); - cycles.add(cycle); - return; - } - nextConstraint = getConstraintInRelation(tphsInRelation, maybeCycle); - } - -// addAllToVisitedConstraints(vistedConstraints, maybeCycle); - } - - private boolean containsInLongCycle(TPHConstraint c, List cycles) { - for(Cycle cycle : cycles) { - if(cycle.containConstraint(c)) - return true; - } - return false; - } - - private void addAllToVisitedConstraints(List vistedConstraints, List maybeCycle) { - for (TPHConstraint con : maybeCycle) { - if (!vistedConstraints.contains(con)) - vistedConstraints.add(con); - } - } - - private Optional getConstraintInRelation(List tphsInRelation, - List maybeCycle) { - TPHConstraint constraint = getConstraintByLeftSide(tphsInRelation.get(tphsInRelation.size()-1),maybeCycle); - Optional nextConstraint = Optional.ofNullable(constraint); - if(nextConstraint.isPresent()) { - maybeCycle.add(constraint); - tphsInRelation.add(constraint.getRight()); - } - return nextConstraint; - } - - 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; - } - return null; - } - - private boolean isCycle(List tphsInRelation) { - return tphsInRelation.get(0).equals(tphsInRelation.get(tphsInRelation.size() - 1)); - } - -} diff --git a/src/main/java/de/dhbwstuttgart/bytecode/genericsGenerator/GeneratedGenericsFinder.java b/src/main/java/de/dhbwstuttgart/bytecode/genericsGenerator/GeneratedGenericsFinder.java deleted file mode 100644 index e25958d1..00000000 --- a/src/main/java/de/dhbwstuttgart/bytecode/genericsGenerator/GeneratedGenericsFinder.java +++ /dev/null @@ -1,732 +0,0 @@ -/** - * - */ -package de.dhbwstuttgart.bytecode.genericsGenerator; - -import java.util.*; - -import de.dhbwstuttgart.bytecode.TPHExtractor; -import de.dhbwstuttgart.bytecode.constraint.ExtendsConstraint; -import de.dhbwstuttgart.bytecode.constraint.TPHConstraint; -import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.*; -import de.dhbwstuttgart.bytecode.insertGenerics.ClassConstraint; -import de.dhbwstuttgart.bytecode.insertGenerics.FamilyOfGeneratedGenerics; -import de.dhbwstuttgart.bytecode.utilities.MethodAndTPH; -import de.dhbwstuttgart.bytecode.utilities.MethodUtility; -import de.dhbwstuttgart.bytecode.utilities.Resolver; -import de.dhbwstuttgart.parser.SyntaxTreeGenerator.AssignToLocal; -import de.dhbwstuttgart.parser.scope.JavaClassName; -import de.dhbwstuttgart.syntaxtree.ASTVisitor; -import de.dhbwstuttgart.syntaxtree.ClassOrInterface; -import de.dhbwstuttgart.syntaxtree.Constructor; -import de.dhbwstuttgart.syntaxtree.Field; -import de.dhbwstuttgart.syntaxtree.FormalParameter; -import de.dhbwstuttgart.syntaxtree.GenericDeclarationList; -import de.dhbwstuttgart.syntaxtree.GenericTypeVar; -import de.dhbwstuttgart.syntaxtree.Method; -import de.dhbwstuttgart.syntaxtree.ParameterList; -import de.dhbwstuttgart.syntaxtree.SourceFile; -import de.dhbwstuttgart.syntaxtree.statement.ArgumentList; -import de.dhbwstuttgart.syntaxtree.statement.Assign; -import de.dhbwstuttgart.syntaxtree.statement.AssignToField; -import de.dhbwstuttgart.syntaxtree.statement.BinaryExpr; -import de.dhbwstuttgart.syntaxtree.statement.Block; -import de.dhbwstuttgart.syntaxtree.statement.CastExpr; -import de.dhbwstuttgart.syntaxtree.statement.DoStmt; -import de.dhbwstuttgart.syntaxtree.statement.EmptyStmt; -import de.dhbwstuttgart.syntaxtree.statement.ExpressionReceiver; -import de.dhbwstuttgart.syntaxtree.statement.FieldVar; -import de.dhbwstuttgart.syntaxtree.statement.ForStmt; -import de.dhbwstuttgart.syntaxtree.statement.IfStmt; -import de.dhbwstuttgart.syntaxtree.statement.InstanceOf; -import de.dhbwstuttgart.syntaxtree.statement.LambdaExpression; -import de.dhbwstuttgart.syntaxtree.statement.Literal; -import de.dhbwstuttgart.syntaxtree.statement.LocalVar; -import de.dhbwstuttgart.syntaxtree.statement.LocalVarDecl; -import de.dhbwstuttgart.syntaxtree.statement.MethodCall; -import de.dhbwstuttgart.syntaxtree.statement.NewArray; -import de.dhbwstuttgart.syntaxtree.statement.NewClass; -import de.dhbwstuttgart.syntaxtree.statement.Return; -import de.dhbwstuttgart.syntaxtree.statement.ReturnVoid; -import de.dhbwstuttgart.syntaxtree.statement.StaticClassName; -import de.dhbwstuttgart.syntaxtree.statement.Super; -import de.dhbwstuttgart.syntaxtree.statement.SuperCall; -import de.dhbwstuttgart.syntaxtree.statement.This; -import de.dhbwstuttgart.syntaxtree.statement.UnaryExpr; -import de.dhbwstuttgart.syntaxtree.statement.WhileStmt; -import de.dhbwstuttgart.syntaxtree.type.ExtendsWildcardType; -import de.dhbwstuttgart.syntaxtree.type.GenericRefType; -import de.dhbwstuttgart.syntaxtree.type.RefType; -import de.dhbwstuttgart.syntaxtree.type.SuperWildcardType; -import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder; -import de.dhbwstuttgart.typeinference.result.ResultSet; - -/** - * @author fayez - * - */ -public class GeneratedGenericsFinder implements ASTVisitor { - private final TPHExtractor tphExtractor = new TPHExtractor(); - private Collection listOfResultSets; - private SourceFile sf; - private List tphsClass; - private GenericGenratorResultForSourceFile generatedGenericsForSF;//Ergebnis des GGenerics - private ResultSet resultSet; - private final List methodNameAndParamsT = new ArrayList<>(); - private FamilyOfGeneratedGenerics fogg; - - private String pkgName; - private JavaClassName className; - private Resolver resolver; - - - /** - * @param sf - * @param listOfResultSets - */ - public GeneratedGenericsFinder(SourceFile sf, Collection listOfResultSets) { - this.sf = sf; - this.listOfResultSets = listOfResultSets; - } - - public GenericGenratorResultForSourceFile findGeneratedGenerics() { - sf.accept(this); - return generatedGenericsForSF; - } - - /** - * returns the family of Generated Generics - * insbesondere fuer Testzwecke - */ - public FamilyOfGeneratedGenerics getFogg() { - return fogg; - } - - /* - * (non-Javadoc) - * - * @see - * de.dhbwstuttgart.syntaxtree.ASTVisitor#visit(de.dhbwstuttgart.syntaxtree. - * SourceFile) - */ - @Override - public void visit(SourceFile sourceFile) { - pkgName = sf.getPkgName(); - generatedGenericsForSF = new GenericGenratorResultForSourceFile(pkgName); - for (ClassOrInterface cl : sourceFile.getClasses()) { - cl.accept(this); - } - } - - /* - * (non-Javadoc) - * - * @see - * de.dhbwstuttgart.syntaxtree.ASTVisitor#visit(de.dhbwstuttgart.syntaxtree. - * ClassOrInterface) - */ - @Override - public void visit(ClassOrInterface classOrInterface) { - className = classOrInterface.getClassName(); - List listOfResultSetsList = new ArrayList<>(listOfResultSets); - - boolean isVisited = false; - - ConstraintsSimplierResult simplifiedConstraints = null; - GenericsGeneratorResultForClass ggResult = null; - GenericsGeneratorResultForClass ggResultAlternative = null; - - for (int i = 0; i < listOfResultSetsList.size(); i++) { - resultSet = listOfResultSetsList.get(i); - tphExtractor.setResultSet(resultSet); - resolver = new Resolver(resultSet); - classOrInterface.accept(tphExtractor); - //PL 2020-10-16: Ab hier GGenerics implementieren durch Ali - //Rueckgabe an generatedGenericsForSF - fogg = new FamilyOfGeneratedGenerics(tphExtractor, resultSet); - - System.out.println("fogg.allConstraints: "+ fogg.allConstraints); - System.out.println("fogg.posOfTPHs: "+ fogg.posOfTPHs); - System.out.println("fogg.classConstraints: "+ fogg.classConstraints); - System.out.println("fogg.methodConstraintsWithPosition: "+ fogg.methodConstraintsWithPosition); - System.out.println(fogg); - - ///* - //Fayez Ansatz Anfang - tphsClass = tphExtractor.tphsClass; - //PL 2020-01-15 - //Es muss ggResult aus fogg gebildet werden - simplifiedConstraints = GenericsGenerator.simplifyConstraints(tphExtractor, tphsClass); - if(!isVisited) { - ggResult = GenericsGenerator.generateConstraints(className, tphExtractor, tphsClass,simplifiedConstraints); - isVisited = true; - } - - for(Method m : classOrInterface.getMethods()) { - addMethodConstraints(simplifiedConstraints, ggResult, m); - - } - - - if(ggResult != null) { //Hinzufuegen von Fayez ggResult - generatedGenericsForSF.addGenericGeneratorResultClass(ggResult); - } - // Fayez Ansatz Ende - //*/ - - //Ali Ansatz Anfang - List listOfClassCons = new ArrayList<>(); - for(TPHConstraint clCons: fogg.classConstraints) { -// ExtendsConstraint ec = new ExtendsConstraint(clCons.getLeft(), clCons.getRight()); - GenericsGeneratorResult ggR = new GenericsGeneratorResult(clCons, new HashSet<>()); - listOfClassCons.add(ggR); - } - - GenericGeneratorResultsForAllMethods ggRfaM = null; - List listOfMethAndCons = new ArrayList<>(); - for(String methID: fogg.methodConstraintsWithPosition.keySet()) { - List listOfGGR = new ArrayList<>(); - for(TPHConstraint methCons: fogg.methodConstraintsWithPosition.get(methID)) { -// ExtendsConstraint ec = new ExtendsConstraint(methCons.getLeft(),methCons.getRight()); - GenericsGeneratorResult ggR = new GenericsGeneratorResult(methCons, new HashSet<>()); - listOfGGR.add(ggR); - } - MethodAndConstraints mac = new MethodAndConstraints(methID, listOfGGR); - listOfMethAndCons.add(mac); - } - ggRfaM = new GenericGeneratorResultsForAllMethods(listOfMethAndCons); - ggResultAlternative = new GenericsGeneratorResultForClass(className, listOfClassCons, ggRfaM); - - if(ggResultAlternative != null) {//hinzufuegen von Alis ggResult - //generatedGenericsForSF.addGenericGeneratorResultClass(ggResultAlternative); - System.out.println(generatedGenericsForSF); - } - System.out.println(ggResultAlternative); - //Ali Ansatz Ende - - } - - } - - /** - * @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); - }); - } - - /* - * (non-Javadoc) - * - * @see - * de.dhbwstuttgart.syntaxtree.ASTVisitor#visit(de.dhbwstuttgart.syntaxtree. - * Method) - */ - @Override - public void visit(Method method) { - - } - - /* - * (non-Javadoc) - * - * @see - * de.dhbwstuttgart.syntaxtree.ASTVisitor#visit(de.dhbwstuttgart.syntaxtree. - * ParameterList) - */ - @Override - public void visit(ParameterList formalParameters) { - - } - - /* - * (non-Javadoc) - * - * @see - * de.dhbwstuttgart.syntaxtree.ASTVisitor#visit(de.dhbwstuttgart.syntaxtree. - * Constructor) - */ - @Override - public void visit(Constructor field) { - - } - - /* - * (non-Javadoc) - * - * @see de.dhbwstuttgart.syntaxtree.StatementVisitor#visit(de.dhbwstuttgart. - * syntaxtree.statement.ArgumentList) - */ - @Override - public void visit(ArgumentList argumentList) { - // TODO Auto-generated method stub - - } - - /* - * (non-Javadoc) - * - * @see de.dhbwstuttgart.syntaxtree.StatementVisitor#visit(de.dhbwstuttgart. - * syntaxtree.statement.LambdaExpression) - */ - @Override - public void visit(LambdaExpression lambdaExpression) { - // TODO Auto-generated method stub - - } - - /* - * (non-Javadoc) - * - * @see de.dhbwstuttgart.syntaxtree.StatementVisitor#visit(de.dhbwstuttgart. - * syntaxtree.statement.Assign) - */ - @Override - public void visit(Assign assign) { - // TODO Auto-generated method stub - - } - - /* - * (non-Javadoc) - * - * @see de.dhbwstuttgart.syntaxtree.StatementVisitor#visit(de.dhbwstuttgart. - * syntaxtree.statement.BinaryExpr) - */ - @Override - public void visit(BinaryExpr binary) { - // TODO Auto-generated method stub - - } - - /* - * (non-Javadoc) - * - * @see de.dhbwstuttgart.syntaxtree.StatementVisitor#visit(de.dhbwstuttgart. - * syntaxtree.statement.Block) - */ - @Override - public void visit(Block block) { - // TODO Auto-generated method stub - - } - - /* - * (non-Javadoc) - * - * @see de.dhbwstuttgart.syntaxtree.StatementVisitor#visit(de.dhbwstuttgart. - * syntaxtree.statement.CastExpr) - */ - @Override - public void visit(CastExpr castExpr) { - // TODO Auto-generated method stub - - } - - /* - * (non-Javadoc) - * - * @see de.dhbwstuttgart.syntaxtree.StatementVisitor#visit(de.dhbwstuttgart. - * syntaxtree.statement.EmptyStmt) - */ - @Override - public void visit(EmptyStmt emptyStmt) { - // TODO Auto-generated method stub - - } - - /* - * (non-Javadoc) - * - * @see de.dhbwstuttgart.syntaxtree.StatementVisitor#visit(de.dhbwstuttgart. - * syntaxtree.statement.FieldVar) - */ - @Override - public void visit(FieldVar fieldVar) { - // TODO Auto-generated method stub - - } - - /* - * (non-Javadoc) - * - * @see de.dhbwstuttgart.syntaxtree.StatementVisitor#visit(de.dhbwstuttgart. - * syntaxtree.statement.ForStmt) - */ - @Override - public void visit(ForStmt forStmt) { - // TODO Auto-generated method stub - - } - - /* - * (non-Javadoc) - * - * @see de.dhbwstuttgart.syntaxtree.StatementVisitor#visit(de.dhbwstuttgart. - * syntaxtree.statement.IfStmt) - */ - @Override - public void visit(IfStmt ifStmt) { - // TODO Auto-generated method stub - - } - - /* - * (non-Javadoc) - * - * @see de.dhbwstuttgart.syntaxtree.StatementVisitor#visit(de.dhbwstuttgart. - * syntaxtree.statement.InstanceOf) - */ - @Override - public void visit(InstanceOf instanceOf) { - // TODO Auto-generated method stub - - } - - /* - * (non-Javadoc) - * - * @see de.dhbwstuttgart.syntaxtree.StatementVisitor#visit(de.dhbwstuttgart. - * syntaxtree.statement.LocalVar) - */ - @Override - public void visit(LocalVar localVar) { - // TODO Auto-generated method stub - - } - - /* - * (non-Javadoc) - * - * @see de.dhbwstuttgart.syntaxtree.StatementVisitor#visit(de.dhbwstuttgart. - * syntaxtree.statement.LocalVarDecl) - */ - @Override - public void visit(LocalVarDecl localVarDecl) { - // TODO Auto-generated method stub - - } - - /* - * (non-Javadoc) - * - * @see de.dhbwstuttgart.syntaxtree.StatementVisitor#visit(de.dhbwstuttgart. - * syntaxtree.statement.MethodCall) - */ - @Override - public void visit(MethodCall methodCall) { - // TODO Auto-generated method stub - - } - - /* - * (non-Javadoc) - * - * @see de.dhbwstuttgart.syntaxtree.StatementVisitor#visit(de.dhbwstuttgart. - * syntaxtree.statement.NewClass) - */ - @Override - public void visit(NewClass methodCall) { - // TODO Auto-generated method stub - - } - - /* - * (non-Javadoc) - * - * @see de.dhbwstuttgart.syntaxtree.StatementVisitor#visit(de.dhbwstuttgart. - * syntaxtree.statement.NewArray) - */ - @Override - public void visit(NewArray newArray) { - // TODO Auto-generated method stub - - } - - /* - * (non-Javadoc) - * - * @see de.dhbwstuttgart.syntaxtree.StatementVisitor#visit(de.dhbwstuttgart. - * syntaxtree.statement.Return) - */ - @Override - public void visit(Return aReturn) { - // TODO Auto-generated method stub - - } - - /* - * (non-Javadoc) - * - * @see de.dhbwstuttgart.syntaxtree.StatementVisitor#visit(de.dhbwstuttgart. - * syntaxtree.statement.ReturnVoid) - */ - @Override - public void visit(ReturnVoid aReturn) { - // TODO Auto-generated method stub - - } - - /* - * (non-Javadoc) - * - * @see de.dhbwstuttgart.syntaxtree.StatementVisitor#visit(de.dhbwstuttgart. - * syntaxtree.statement.StaticClassName) - */ - @Override - public void visit(StaticClassName staticClassName) { - // TODO Auto-generated method stub - - } - - /* - * (non-Javadoc) - * - * @see de.dhbwstuttgart.syntaxtree.StatementVisitor#visit(de.dhbwstuttgart. - * syntaxtree.statement.Super) - */ - @Override - public void visit(Super aSuper) { - // TODO Auto-generated method stub - - } - - /* - * (non-Javadoc) - * - * @see de.dhbwstuttgart.syntaxtree.StatementVisitor#visit(de.dhbwstuttgart. - * syntaxtree.statement.This) - */ - @Override - public void visit(This aThis) { - // TODO Auto-generated method stub - - } - - /* - * (non-Javadoc) - * - * @see de.dhbwstuttgart.syntaxtree.StatementVisitor#visit(de.dhbwstuttgart. - * syntaxtree.statement.WhileStmt) - */ - @Override - public void visit(WhileStmt whileStmt) { - // TODO Auto-generated method stub - - } - - /* - * (non-Javadoc) - * - * @see de.dhbwstuttgart.syntaxtree.StatementVisitor#visit(de.dhbwstuttgart. - * syntaxtree.statement.DoStmt) - */ - @Override - public void visit(DoStmt whileStmt) { - // TODO Auto-generated method stub - - } - - /* - * (non-Javadoc) - * - * @see de.dhbwstuttgart.syntaxtree.StatementVisitor#visit(de.dhbwstuttgart. - * syntaxtree.statement.AssignToField) - */ - @Override - public void visit(AssignToField assignLeftSide) { - // TODO Auto-generated method stub - - } - - /* - * (non-Javadoc) - * - * @see - * de.dhbwstuttgart.syntaxtree.StatementVisitor#visit(de.dhbwstuttgart.parser. - * SyntaxTreeGenerator.AssignToLocal) - */ - @Override - public void visit(AssignToLocal assignLeftSide) { - // TODO Auto-generated method stub - - } - - /* - * (non-Javadoc) - * - * @see de.dhbwstuttgart.syntaxtree.StatementVisitor#visit(de.dhbwstuttgart. - * syntaxtree.statement.SuperCall) - */ - @Override - public void visit(SuperCall superCall) { - // TODO Auto-generated method stub - - } - - /* - * (non-Javadoc) - * - * @see de.dhbwstuttgart.syntaxtree.StatementVisitor#visit(de.dhbwstuttgart. - * syntaxtree.statement.ExpressionReceiver) - */ - @Override - public void visit(ExpressionReceiver expressionReceiver) { - // TODO Auto-generated method stub - - } - - /* - * (non-Javadoc) - * - * @see de.dhbwstuttgart.syntaxtree.StatementVisitor#visit(de.dhbwstuttgart. - * syntaxtree.statement.UnaryExpr) - */ - @Override - public void visit(UnaryExpr unaryExpr) { - // TODO Auto-generated method stub - - } - - /* - * (non-Javadoc) - * - * @see de.dhbwstuttgart.syntaxtree.StatementVisitor#visit(de.dhbwstuttgart. - * syntaxtree.statement.Literal) - */ - @Override - public void visit(Literal literal) { - // TODO Auto-generated method stub - - } - - /* - * (non-Javadoc) - * - * @see - * de.dhbwstuttgart.syntaxtree.ASTVisitor#visit(de.dhbwstuttgart.syntaxtree. - * GenericTypeVar) - */ - @Override - public void visit(GenericTypeVar genericTypeVar) { - // TODO Auto-generated method stub - - } - - /* - * (non-Javadoc) - * - * @see - * de.dhbwstuttgart.syntaxtree.ASTVisitor#visit(de.dhbwstuttgart.syntaxtree. - * FormalParameter) - */ - @Override - public void visit(FormalParameter formalParameter) { - // TODO Auto-generated method stub - - } - - /* - * (non-Javadoc) - * - * @see - * de.dhbwstuttgart.syntaxtree.ASTVisitor#visit(de.dhbwstuttgart.syntaxtree. - * GenericDeclarationList) - */ - @Override - public void visit(GenericDeclarationList genericTypeVars) { - // TODO Auto-generated method stub - - } - - /* - * (non-Javadoc) - * - * @see - * de.dhbwstuttgart.syntaxtree.ASTVisitor#visit(de.dhbwstuttgart.syntaxtree. - * Field) - */ - @Override - public void visit(Field field) { - // TODO Auto-generated method stub - - } - - /* - * (non-Javadoc) - * - * @see - * de.dhbwstuttgart.syntaxtree.ASTVisitor#visit(de.dhbwstuttgart.syntaxtree.type - * .RefType) - */ - @Override - public void visit(RefType refType) { - // TODO Auto-generated method stub - - } - - /* - * (non-Javadoc) - * - * @see - * de.dhbwstuttgart.syntaxtree.ASTVisitor#visit(de.dhbwstuttgart.syntaxtree.type - * .SuperWildcardType) - */ - @Override - public void visit(SuperWildcardType superWildcardType) { - // TODO Auto-generated method stub - - } - - /* - * (non-Javadoc) - * - * @see - * de.dhbwstuttgart.syntaxtree.ASTVisitor#visit(de.dhbwstuttgart.syntaxtree.type - * .TypePlaceholder) - */ - @Override - public void visit(TypePlaceholder typePlaceholder) { - // TODO Auto-generated method stub - - } - - /* - * (non-Javadoc) - * - * @see - * de.dhbwstuttgart.syntaxtree.ASTVisitor#visit(de.dhbwstuttgart.syntaxtree.type - * .ExtendsWildcardType) - */ - @Override - public void visit(ExtendsWildcardType extendsWildcardType) { - // TODO Auto-generated method stub - - } - - /* - * (non-Javadoc) - * - * @see - * de.dhbwstuttgart.syntaxtree.ASTVisitor#visit(de.dhbwstuttgart.syntaxtree.type - * .GenericRefType) - */ - @Override - public void visit(GenericRefType genericRefType) { - // TODO Auto-generated method stub - - } - -} diff --git a/src/main/java/de/dhbwstuttgart/bytecode/genericsGenerator/GenericsGenerator.java b/src/main/java/de/dhbwstuttgart/bytecode/genericsGenerator/GenericsGenerator.java deleted file mode 100644 index 8e5bd481..00000000 --- a/src/main/java/de/dhbwstuttgart/bytecode/genericsGenerator/GenericsGenerator.java +++ /dev/null @@ -1,256 +0,0 @@ -/** - * - */ -package de.dhbwstuttgart.bytecode.genericsGenerator; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Optional; -import java.util.Set; -import java.util.stream.Collectors; - -import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.*; -import de.dhbwstuttgart.parser.scope.JavaClassName; -import org.objectweb.asm.Type; - -import de.dhbwstuttgart.bytecode.TPHExtractor; -import de.dhbwstuttgart.bytecode.constraint.ExtendsConstraint; -import de.dhbwstuttgart.bytecode.constraint.TPHConstraint; -import de.dhbwstuttgart.bytecode.utilities.MethodAndTPH; - -/** - * @author fayez - * - */ -public class GenericsGenerator { - /*TODO: When generating generics for a class if we have the following: - tphClass < tphMeth1 < tphMeth2 - then we have to convert tphMeth1, tphMeth2 to tph class and generate the following - class constraints: tphClass < tphMeth1, tphMeth1 < tphMeth2, tphMeth2 < Object - */ - - public static GenericsGeneratorResultForClass generateConstraints(final JavaClassName 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<>()); - - 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()); - - createConstraintsForClassTphs(simplifiedConstraints, tphsClass, constraints, allCons, visitedTPHs, methodTPHs); - - GenericsGeneratorUtility.addTPHsToClassTPHs(constraints, tphsClass); - GenericsGeneratorUtility.removeClassTPHsFromMethodTPHs(tphsClass, tphExtractor); - - generateGGConstraintsForTPH(tphsClass, constraints, simplifiedConstraints); - - return constraints; - } - - private static void createConstraintsForClassTphs(ConstraintsSimplierResult simplifiedConstraints, List tphsClass, List constraints, List allCons, Set visitedTPHs, List methodTPHs) { - List classAndMethodTphs = new ArrayList<>(tphsClass); - classAndMethodTphs.addAll(methodTPHs); - - for (String tph : tphsClass) { - - if (visitedTPHs.contains(tph)) - continue; - - final LinkedList tphsInRel = GenericsGeneratorUtility - .createLinkedListForTPHsInRelationClass(allCons, tphsClass, methodTPHs, visitedTPHs, tph); - - generateConstraintsForClassFromList(tphsInRel,simplifiedConstraints,classAndMethodTphs,constraints); - } - } - - private static void generateConstraintsForClassFromList(LinkedList tphsInRel, ConstraintsSimplierResult simplifiedConstraints, List classAndMethodTphs, List constraints) { - - if(tphsInRel.isEmpty()) - return; - - List resultConstraints = new ArrayList<>(); - String subType = tphsInRel.getFirst(); - String superType = GenericsGeneratorUtility.getNextClassTph(classAndMethodTphs, tphsInRel); - - int idxOfSuper = tphsInRel.indexOf(superType); - int size = tphsInRel.size(); - while (size > 2 && idxOfSuper < size-1){ - GenericsGeneratorResult genericsGeneratorResult = getGenericsGeneratorResultForClass(simplifiedConstraints, subType, superType); - constraints.add(genericsGeneratorResult); - - tphsInRel = new LinkedList<>(tphsInRel.subList(idxOfSuper, size)); - subType = tphsInRel.getFirst(); - superType = GenericsGeneratorUtility.getNextClassTph(classAndMethodTphs, tphsInRel); - - idxOfSuper = tphsInRel.indexOf(superType); - size = tphsInRel.size(); - } - GenericsGeneratorResult genericsGeneratorResult = getGenericsGeneratorResultForClass(simplifiedConstraints, subType, superType); - constraints.add(genericsGeneratorResult); - } - - private static GenericsGeneratorResult getGenericsGeneratorResultForClass(ConstraintsSimplierResult simplifiedConstraints, String subType, String superType) { - TPHConstraint constraint = new ExtendsConstraint(subType, superType); - - Set equalSet = GenericsGeneratorUtility - .createEqualSet(simplifiedConstraints.getNameReplacementResults(), subType); - - return new GenericsGeneratorResult(constraint, equalSet); - } - /* TODO Remove this methoda*/ - 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 deleted file mode 100644 index f909734f..00000000 --- a/src/main/java/de/dhbwstuttgart/bytecode/genericsGenerator/GenericsGeneratorUtility.java +++ /dev/null @@ -1,571 +0,0 @@ -/** - * - */ -package de.dhbwstuttgart.bytecode.genericsGenerator; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Optional; -import java.util.Set; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.*; -import org.objectweb.asm.Type; - -import de.dhbwstuttgart.bytecode.TPHExtractor; -import de.dhbwstuttgart.bytecode.constraint.EqualConstraint; -import de.dhbwstuttgart.bytecode.constraint.ExtendsConstraint; -import de.dhbwstuttgart.bytecode.constraint.TPHConstraint; -import de.dhbwstuttgart.bytecode.constraint.TPHConstraint.Relation; -import de.dhbwstuttgart.bytecode.utilities.ConstraintsFinder; -import de.dhbwstuttgart.bytecode.utilities.MethodAndTPH; -import de.dhbwstuttgart.bytecode.utilities.NameReplacer; - -/** - * @author fayez - * - */ -public class GenericsGeneratorUtility { - /** - * Returns a list of type placeholders names of a specified method - * - * @param methodID The id of the method ReturnTypeMethodName(ParameterTypes) - * @param listOfMethodsAndTph List of all methods - * @return a list of type placehoders names - */ - public static List getMethodTPHS(String methodID, ArrayList listOfMethodsAndTph) { - return listOfMethodsAndTph.stream().filter(mt->mt.getId().equals(methodID)).findAny().get().getTphs(); - } - - /** - * Returns a reverse constraint of a specified constraint which is given by its left and right - * side - * - * @param allCons List of all constraints - * @param left The left side of the given constraint - * @param right The right side of the given constraint - * @return An Optional object which contains the reverse constraint if it is exist - */ - public static Optional getReverseConstraint(List allCons, String left, String right) { - return allCons.stream().filter(c->{ - return c.getRight().equals(left) && c.getLeft().equals(right); - }).findAny(); - } - - /** - * Substitutes the old name by the new name in all constraints - * - * @param allCons List of all constraints - * @param oldName The name to be replaced - * @param newName The new name - */ - public static void substituteTPH(List allCons, String oldName, String newName) { - allCons.stream() - .filter(c->c.getRel()==Relation.EXTENDS) - .forEach(c->{ - if(c.getLeft().equals(oldName)) - c.setLeft(newName); - if(c.getRight().equals(oldName)) - c.setRight(newName); - }); - - } - - public static List findConstraintsWithLeftSameLeftSide(List allCons) { - // finder looks for constraints that have the same left hand side - // and put them in a list - ConstraintsFinder finder = new ConstraintsFinder(allCons); - List foundCons = finder.findConstraints(); - return foundCons; - } - - public static void simplifyConstraintsWithSameLeftSide(List consWithSameLeftSide, - List allCons, List methodTPHS) { - List eqCons = new ArrayList<>(); - - for (ConstraintsWithSameLeftSide list : consWithSameLeftSide) { - NameReplacementResult replRes = modifyNames(allCons, methodTPHS, list); - createEqualConstraintsForNames(replRes.getName(), replRes.getOldNames(),eqCons); - - for (TPHConstraint c : allCons) { - if (c.getRel() == Relation.EQUAL && replRes.getName().equals(c.getRight())) { - eqCons.add(c); - } - } - updateEqualCons(replRes, eqCons); - - TPHConstraint c = list.getConstraints().get(0); - allCons.removeAll(list.getConstraints()); - allCons.add(c); - } - - } - - public static void simplifyConstraintsWithSameLeftSide(List 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(),equalCons); - - for (TPHConstraint c : allCons) { - if (c.getRel() == Relation.EQUAL && replRes.getName().equals(c.getRight())) { - equalCons.add(c); - } - } - updateEqualCons(replRes, equalCons); - - TPHConstraint c = list.getConstraints().get(0); - allCons.removeAll(list.getConstraints()); - removeConstraintsWithSameLeftAndRightSide(allCons); - allCons.add(c); - removeDuplicate(allCons); - } - consWithSameLeftSide.clear(); - consWithSameLeftSide = findConstraintsWithLeftSameLeftSide(allCons); - if(!consWithSameLeftSide.isEmpty()) - simplifyConstraintsWithSameLeftSide(consWithSameLeftSide,tphExtractor,tphsClass,equalCons); - - } - - private static void removeDuplicate(List 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) { - EqualConstraint ec = new EqualConstraint(eName, name); - eqCons.add(ec); - } - } - - /** - * @param allCons - * @param methodTPHS - * @param list - * @return - */ - public static NameReplacementResult modifyNames(List allCons, List methodTPHS, - ConstraintsWithSameLeftSide list) { - // generate a new name and replace the right hand side for each constraint - // in list with the new name - NameReplacer replacer = new NameReplacer(list.getConstraints(), allCons, methodTPHS); - // new name -> [all old names] - NameReplacementResult replRes = replacer.replaceNames(); - return replRes; - } - - public static NameReplacementResult modifyNames(List allCons, ConstraintsWithSameLeftSide list, List methodAndTPHs, List tphsClass) { - // generate a new name and replace the right hand side for each constraint - // in list with the new name - NameReplacer replacer = new NameReplacer(list.getConstraints(), allCons, methodAndTPHs, tphsClass); - // new name -> [all old names] - NameReplacementResult replRes = replacer.replaceNames(); - return replRes; - } - - public static void updateEqualCons(NameReplacementResult nameReplacementResult, List eqCons) { - List oldNames = nameReplacementResult.getOldNames(); - String newName = nameReplacementResult.getName(); - for (TPHConstraint c : eqCons) { -// if(oldNames.contains(c.getLeft())) -// c.setLeft(newName); - if (oldNames.contains(c.getRight())) - c.setRight(newName); - } - - } - - public static void modifyRelationForConstraintsInCycle(List cycles) { - cycles.stream().map(lc->lc.getConstraints()).flatMap(e->e.stream()).forEach(c->c.setRel(Relation.EQUAL)); - } - - public static List substituteTPHSFormCycle(List allCons, List cycles, TPHExtractor tphExtractor) { - List results = new ArrayList<>(); - cycles.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) - .forEach(c->{ - if(names.contains(c.getLeft())) { - c.setLeft(newName); - } else if(names.contains(c.getRight())) { - c.setRight(newName); - } - }); - } - - public static Set getNamesFromCycle(Cycle lc) { - Set names = new HashSet<>(); - lc.getConstraints().forEach(c->names.add(c.getLeft())); - return names; - } - - public static void createResults(List genericsGeneratorResults, - List nameReplacementResults) { - nameReplacementResults.forEach(n->{ - Set equals = new HashSet<>(n.getOldNames()); - TPHConstraint cons = new ExtendsConstraint(n.getName(), Type.getInternalName(Object.class)); - GenericsGeneratorResult ggRes = new GenericsGeneratorResult(cons, equals); - genericsGeneratorResults.add(ggRes); - }); - } - - public static void removeEqualConstraints(List allCons) { - List equalConstraints = getEqualConstraints(allCons); - allCons.removeAll(equalConstraints); - } - - public static List getEqualConstraints(List allCons) { - return allCons.stream().filter(c->c.getRel()==Relation.EQUAL).collect(Collectors.toList()); - } - - public static List createNameReplacementResultsFromEqualConstraints( - List equalCons) { - List nameReplacementResults = new ArrayList<>(); - equalCons.forEach(c->{ - if(isInNameReplacementResults(nameReplacementResults,c.getRight())) { - getNameReplacementByName(nameReplacementResults,c.getRight()).getOldNames().add(c.getLeft()); - } else { - List oldNames = new ArrayList<>(); - oldNames.add(c.getLeft()); - NameReplacementResult nrRes = new NameReplacementResult(c.getRight(), oldNames); - nameReplacementResults.add(nrRes); - } - }); - return nameReplacementResults; - } - - private static NameReplacementResult getNameReplacementByName(List nameReplacementResults, - String name) { - return nameReplacementResults.stream().filter(n->n.getName().equals(name)).findFirst().get(); - } - - public static boolean isInNameReplacementResults(List nameReplacementResults,String name){ - if(nameReplacementResults.isEmpty()) - return false; - return nameReplacementResults.stream().map(r->r.getName()).filter(n->name.equals(n)).findFirst().isPresent(); - } - - public static Optional 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 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/genericsGeneratorTypes/Cycle.java b/src/main/java/de/dhbwstuttgart/bytecode/genericsGeneratorTypes/Cycle.java deleted file mode 100644 index ff6521d8..00000000 --- a/src/main/java/de/dhbwstuttgart/bytecode/genericsGeneratorTypes/Cycle.java +++ /dev/null @@ -1,46 +0,0 @@ -/** - * - */ -package de.dhbwstuttgart.bytecode.genericsGeneratorTypes; - -import java.util.List; - -import de.dhbwstuttgart.bytecode.constraint.TPHConstraint; - -/** - * @author fayez - * - */ -public class Cycle { - private final List constraints; - - /** - * @param constraints - */ - public Cycle(List constraints) { - this.constraints = constraints; - } - - /** - * @return the constraints - */ - public List getConstraints() { - return constraints; - } - - public boolean containConstraint(TPHConstraint constraint) { - for(TPHConstraint c : constraints) { - if(c.equalConstraint(constraint)) - return true; - } - return false; - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - constraints.forEach(c->sb.append(c.getLeft()+" -> ")); - sb.append(constraints.get(constraints.size()-1).getRight()); - return sb.toString(); - } -} diff --git a/src/main/java/de/dhbwstuttgart/bytecode/genericsGeneratorTypes/MethodAndConstraints.java b/src/main/java/de/dhbwstuttgart/bytecode/genericsGeneratorTypes/MethodAndConstraints.java index bf582707..b9437c3a 100644 --- a/src/main/java/de/dhbwstuttgart/bytecode/genericsGeneratorTypes/MethodAndConstraints.java +++ b/src/main/java/de/dhbwstuttgart/bytecode/genericsGeneratorTypes/MethodAndConstraints.java @@ -24,7 +24,8 @@ public class MethodAndConstraints { * @return the methodID */ public String getMethodID() { - return methodID; + // FIXME + return null; } /** * @return the constraints diff --git a/src/main/java/de/dhbwstuttgart/bytecode/insertGenerics/ClassConstraint.java b/src/main/java/de/dhbwstuttgart/bytecode/insertGenerics/ClassConstraint.java deleted file mode 100644 index 130f0ac6..00000000 --- a/src/main/java/de/dhbwstuttgart/bytecode/insertGenerics/ClassConstraint.java +++ /dev/null @@ -1,16 +0,0 @@ -package de.dhbwstuttgart.bytecode.insertGenerics; - -import de.dhbwstuttgart.bytecode.constraint.TPHConstraint; -import de.dhbwstuttgart.bytecode.constraint.TPHConstraint.Relation; - -public class ClassConstraint extends TPHConstraint { - //private TPHConstraint constraint; - - public ClassConstraint(String left, String right, Relation rel) { - super(left, right, rel); - } - //besser? - /*public ClassConstraint(TPHConstraint constraint) { - this.constraint = constraint; - }*/ -} diff --git a/src/main/java/de/dhbwstuttgart/bytecode/insertGenerics/FamilyOfGeneratedGenerics.java b/src/main/java/de/dhbwstuttgart/bytecode/insertGenerics/FamilyOfGeneratedGenerics.java deleted file mode 100644 index ed46e816..00000000 --- a/src/main/java/de/dhbwstuttgart/bytecode/insertGenerics/FamilyOfGeneratedGenerics.java +++ /dev/null @@ -1,880 +0,0 @@ -package de.dhbwstuttgart.bytecode.insertGenerics; - -import de.dhbwstuttgart.bytecode.TPHExtractor; -import de.dhbwstuttgart.bytecode.constraint.TPHConstraint; -import de.dhbwstuttgart.bytecode.constraint.TPHConstraint.Relation; -import de.dhbwstuttgart.bytecode.utilities.MethodAndTPH; - -import java.util.*; -import java.util.function.Predicate; - -import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric; -import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder; -import de.dhbwstuttgart.typeinference.constraints.Constraint; -import de.dhbwstuttgart.typeinference.constraints.Pair; -import de.dhbwstuttgart.typeinference.result.ResultPair; -import de.dhbwstuttgart.typeinference.result.ResultSet; -import de.dhbwstuttgart.typeinference.unify.model.PairOperator; -import org.objectweb.asm.Type; - -public class FamilyOfGeneratedGenerics { - public List allConstraints = new ArrayList<>(); - // HashMap speichert ob TPH in einer Methode oder in der Klasse ist; und wenn es in der Methode ist, in welcher Methode - public HashMap>> posOfTPHs = new HashMap<>(); - public List classConstraints = new ArrayList<>(); - private HashMap mapMethodsAndTph = new HashMap<>(); - public List methodConstraints = new ArrayList<>(); - public HashMap> methodConstraintsWithPosition = new HashMap<>(); - public ResultSet resSet; - public Set oldCons = new HashSet<>(); - - private static final String objectType = Type.getInternalName(Object.class); - - public FamilyOfGeneratedGenerics(TPHExtractor tphExtractor, ResultSet resultSet) { - this.resSet = resultSet; - this.oldCons = tphExtractor.oldConstraints; - this.allConstraints = tphExtractor.allCons; - this.posOfTPHs = positionConverter(tphExtractor.allTPHS, tphExtractor.ListOfMethodsAndTph); - this.classConstraints = getClassConstraints(allConstraints,posOfTPHs); - tphExtractor.ListOfMethodsAndTph.forEach(matph -> this.mapMethodsAndTph.put(matph.getId(), matph)); - this.methodConstraints = getMethodConstraints(allConstraints,classConstraints,posOfTPHs, tphExtractor.ListOfMethodsAndTph); - this.methodConstraintsWithPosition = getMethodConstraintsWithPositionNew(allConstraints,classConstraints,posOfTPHs, tphExtractor.ListOfMethodsAndTph, resSet, oldCons); - } - - public static List getClassConstraints(List cs, HashMap>> posOfTphs) { //Inputparameter List constraintsSet weg - List cs_cl = new ArrayList<>(); - List classConstraints1 = typeOfANodeOfAField(cs, posOfTphs); - for (ClassConstraint cons: classConstraints1) { - if (!checkForDuplicates(cons, cs_cl)) { - cs_cl.add(cons); - } - } - - // if sth new is added to cs_cl, then do same step again - boolean addedToConstraintsListForCC2 = false; - do { - addedToConstraintsListForCC2 = false; - List classConstraints2 = transitiveSubtypeForClassTypes(cs, cs_cl); // in Klammer classConstraints1 oder constraintsSet? beides eher - for (ClassConstraint cons: classConstraints2) { - if (!checkForDuplicates(cons, cs_cl)) { - cs_cl.add(cons); - addedToConstraintsListForCC2 = true; - } - } - } while (addedToConstraintsListForCC2); - - List classConstraints3 = hasNoSupertypeForClassTypes(cs_cl, posOfTphs); - for (ClassConstraint cons: classConstraints3) { - if (!checkForDuplicates(cons, cs_cl)) { - cs_cl.add(cons); - } - } - return cs_cl; - } - - public List getMethodConstraints(List cs, List cs_cl, HashMap>> posOfTphs, List listOfMethodsAndTph) { - List cs_m = new ArrayList<>(); - List methodConstraints1 = typeOfTheMethodInClSigma(cs, posOfTphs); - for (MethodConstraint cons: methodConstraints1) { - if (!checkForDuplicates(cons, cs_m)) { - cs_m.add(cons); - } - } - - // if sth new is added to cs_cl, then do same step again - boolean addedToConstraintsListForMC2 = false; - do { - addedToConstraintsListForMC2 = false; - List methodConstraints2 = firstTransitiveSubtypeForMethodTypes(cs, cs_m); - for (MethodConstraint cons : methodConstraints2) { - if (!checkForDuplicates(cons, cs_m)) { - cs_m.add(cons); - addedToConstraintsListForMC2 = true; - } - } - } while (addedToConstraintsListForMC2); - - // if sth new is added to cs_cl, then do same step again - boolean addedToConstraintsListForMC3 = false; - do { - addedToConstraintsListForMC3 = false; - List methodConstraints3 = secondTransitiveSubtypeForMethodTypes(cs, cs_cl, cs_m); - for (MethodConstraint cons : methodConstraints3) { - if (!checkForDuplicates(cons, cs_m)) { - cs_m.add(cons); - addedToConstraintsListForMC3 = true; - } - } - } while (addedToConstraintsListForMC3); - List methodConstraints4 = hasNoSupertypeForMethodTypes(cs, cs_m, posOfTphs, listOfMethodsAndTph); - for (MethodConstraint cons: methodConstraints4) { - if (!checkForDuplicates(cons, cs_m)) { - cs_m.add(cons); - } - } - List methodConstraints5 = methodTypesWithoutClassTypes(cs_cl, cs_m); - cs_m = methodConstraints5; - return cs_m; - } - - public HashMap> getMethodConstraintsWithPosition(List cs, List cs_cl, HashMap>> posOfTphs, List listOfMethodsAndTph, ResultSet resSet, Set oldCons) { - HashMap> tempMethodConstraintsWithPosition = new HashMap<>(); - for(MethodAndTPH method: listOfMethodsAndTph){ - List methodsAddedToHashMap = new ArrayList<>(); - String currentMethod = method.getId(); - boolean containsCurrentMethod = false; - if(!containsCurrentMethod) { - methodsAddedToHashMap.add(currentMethod); - containsCurrentMethod = true; - List listOfThisMethod = new ArrayList<>(); - HashMap>> posOfTPHsForThisMethod = new HashMap<>(); - for(String s: posOfTphs.keySet()) { - for(PairTphMethod pair: posOfTphs.get(s)) { - if(pair.snd == currentMethod && pair.snd != null) { - posOfTPHsForThisMethod.put(s,posOfTphs.get(s)); - } - } - } - listOfThisMethod = getMethodConstraints(cs,cs_cl,posOfTPHsForThisMethod,listOfMethodsAndTph); - tempMethodConstraintsWithPosition.put(currentMethod, listOfThisMethod); - - List newMCList = firstLineMethodDefinition(cs, posOfTphs, method, resSet); - List newMCList2 = secondLineMethodDefinition(cs, posOfTphs, method, resSet, oldCons); - System.out.println(newMCList); - System.out.println(newMCList2); - } - } - - for(String curMeth: tempMethodConstraintsWithPosition.keySet()){ - for(int i=0; i tempList = new ArrayList<>(list); - for(TPHConstraint tphC: tempList) { - if(tph == tphC.getLeft()) { - return true; - } - } - return false; - } - - /** - * Def. FGG: erste Zeile von cs_cl - * {T < .T' | T is a type variable in a type of a node of a field} - */ - public static List typeOfANodeOfAField(List allConstraints, HashMap>> posOfTphs) { - //RuntimeException re = new RuntimeException("enthält EQUALS-Relation"); - List tempCC = new ArrayList<>(); - for(TPHConstraint allCons: allConstraints){ - if(posOfTphs.containsKey(allCons.getLeft()) && allCons.getRight()!=null && allCons.getRel()==Relation.EXTENDS) { - for(String tph: posOfTphs.keySet()) { - for(PairTphMethod pair: posOfTphs.get(tph)) { - if(tph == allCons.getLeft() && pair.fst == PositionFinder.Position.FIELD) { - ClassConstraint consToAdd = new ClassConstraint(tph, allCons.getRight(), allCons.getRel()); - if (!checkForDuplicates(consToAdd, tempCC)) { - tempCC.add(consToAdd); - } - /*}else if(pair.fst == PositionFinder.Position.FIELD){ - ClassConstraint consToAdd = new ClassConstraint(tph, objectType, Relation.EXTENDS); - if (!checkForDuplicates(consToAdd, tempCC)) { - tempCC.add(consToAdd); - }*/ - } - } - } - } - /*else if (allCons.getRel() != Relation.EXTENDS) { - throw re; - }*/ - } - return tempCC; - } - - /** - * Def. FGG: zweite Zeile von cs_cl - * {T' <. T'' | \exists T: (T <. T') \in cs_cl, (T' <. T'') \in cs } - */ - public static List transitiveSubtypeForClassTypes(List allConstraints, List cs_cl) { - List tempCC = new ArrayList<>(); - ClassConstraint consToAdd; - for(ClassConstraint cCons: cs_cl) { - if(cCons.getLeft() != null && cCons.getRel()==Relation.EXTENDS) { - for(TPHConstraint allCons: allConstraints) { - if(cCons.getRight() == allCons.getLeft() && allCons.getRight() != null && allCons.getRel()==Relation.EXTENDS){ - consToAdd = new ClassConstraint(allCons.getLeft(), allCons.getRight(), allCons.getRel()); - if (!checkForDuplicates(consToAdd, tempCC)) { - tempCC.add(consToAdd); - } - } - } - } - } - return tempCC; - } - - /** - * Def. FGG: dritte Zeile von cs_cl - * {T <. Object | ((T is a type variable in a type of a node of a field - * or (\exists T~: (T~ <. T) \in cs_cl)) and (\existsnot T': T <. T') \in cs)} - */ - public static List hasNoSupertypeForClassTypes(List cs_cl, HashMap>> posOfTphs) { - List tempCC= new ArrayList<>(); - List clCons = new ArrayList<>(cs_cl); - for(String tph: posOfTphs.keySet()) { - for(PairTphMethod pair: posOfTphs.get(tph)) { - boolean tvInField = pair.fst == PositionFinder.Position.FIELD; - boolean hasSmallerTVInClCons = hasSmallerTVInClCons(tph, cs_cl); - if ((tvInField || hasSmallerTVInClCons) && - !checkUpperBound(clCons, tph)) { - ClassConstraint consToAdd = new ClassConstraint(tph, objectType, Relation.EXTENDS); - if (!checkForDuplicates(consToAdd, tempCC)) { - tempCC.add(consToAdd); - } - } - } - } - return tempCC; - } - - public static boolean hasSmallerTVInClCons(String tph, List cs_cl) { - for(ClassConstraint cC: cs_cl) { - if(tph == cC.getRight() && cC.getRel() == Relation.EXTENDS) { - return true; - } - } - return false; - } - - /** - * Def. FGG: erste Zeile von cs_m - * {T < .T' | T is a type variable in a type of the method/constructor m in cl_\sigma, (T <. T') \in cs} - */ - public static List typeOfTheMethodInClSigma(List allConstraints, HashMap>> posOfTphs) { // cl_\sigma?? - //TODO: - List tempMC= new ArrayList<>(); - for(TPHConstraint allCons: allConstraints){ - if(posOfTphs.containsKey(allCons.getLeft()) && allCons.getRight()!=null && allCons.getRel()==Relation.EXTENDS) { - for(String tph: posOfTphs.keySet()) { - for(PairTphMethod pair: posOfTphs.get(tph)) { - if(tph == allCons.getLeft() && (pair.fst == PositionFinder.Position.METHOD || pair.fst == PositionFinder.Position.CONSTRUCTOR)) { - MethodConstraint consToAdd = new MethodConstraint(allCons.getLeft(), allCons.getRight(), allCons.getRel()); - if (!checkForDuplicates(consToAdd, tempMC)) { - tempMC.add(consToAdd); - } - } - } - } - } - } - return tempMC; - } - - - /** - * Def. FGG: zweite Zeile von cs_m - * {R' <. S | (R <. R'), (S <. S') \in cs_m and (R',S) is in the transitive closure of cs} - */ - public List firstTransitiveSubtypeForMethodTypes(List allConstraints, List cs_m) { //transitive closure of cs - //TODO: - List tempMC= new ArrayList<>(); - List tcOfCs = buildTransitiveClosure(allConstraints); - for(MethodConstraint mC1 : cs_m) { //(R <. R') - for(MethodConstraint mC2 : cs_m) { //(S <. S') - String lSide = mC1.getRight(); //R' - String rSide = mC2.getLeft(); //S - for(TPHConstraint tphC : tcOfCs) { - if(tphC.getLeft().equals(lSide)&&tphC.getRight().equals(rSide)) { //is it (R',S) - MethodConstraint consToAdd = new MethodConstraint(lSide, rSide, tphC.getRel()); //create (R'<.S) - if (!checkForDuplicates(consToAdd, tempMC)) { - tempMC.add(consToAdd); - } - } - } - } - } - return tempMC; - } - - /** - * Def. FGG: dritte Zeile von cs_m - * {R' <. S | (R <. R') \in cs_m, (S <. S') \in cs_cl and (R',S) is in the transitive closure of cs} - */ - public List secondTransitiveSubtypeForMethodTypes(List allConstraints, List cs_cl, List cs_m) { - //TODO: - List tempMC= new ArrayList<>(); - List tcOfCs = buildTransitiveClosure(allConstraints); - for(ClassConstraint cC : cs_cl) { - for(MethodConstraint mC : cs_m) { - String leftSide = mC.getRight(); - String rightSide = cC.getLeft(); - for(TPHConstraint tphC : tcOfCs) { - if(tphC.getLeft().equals(leftSide)&&tphC.getRight().equals(rightSide)) { - MethodConstraint consToAdd = new MethodConstraint(tphC.getLeft(), tphC.getRight(), tphC.getRel()); - if (!checkForDuplicates(consToAdd, tempMC)) { - tempMC.add(consToAdd); - } - - } - } - } - } - return tempMC; - } - -/** - * Def. FGG: vierte Zeile von cs_m - * {T <. Object | (T is a type variable in a type of a node of the method/constructor m in cl_\sigma), - * (\existsnot T': T <. T') \in cs)} - */ - public static List hasNoSupertypeForMethodTypes(List allConstraints, List cs_m, HashMap>> posOfTphs, List listOfMethodsAndTph) { - //TODO: - List tempMC= new ArrayList<>(); - for(String tph: posOfTphs.keySet()) { - for(PairTphMethod pair: posOfTphs.get(tph)) { - for(TPHConstraint allCons: allConstraints) { - if((pair.fst.equals(PositionFinder.Position.METHOD) || pair.fst.equals(PositionFinder.Position.CONSTRUCTOR)) && !checkUpperBound(allConstraints,tph)) { - MethodConstraint consToAdd = new MethodConstraint(tph, objectType, Relation.EXTENDS); - if (!checkForDuplicates(consToAdd, tempMC)) { - tempMC.add(consToAdd); - } - } - } - List tempMCObject1 = new ArrayList<>(cs_m); - String currentMethod = ""; - for(MethodAndTPH mat: listOfMethodsAndTph) { - if(mat.getId().equals(pair.snd)) { - currentMethod = mat.getId(); - } - for(TPHConstraint mc1: tempMCObject1) { - if(tph==mc1.getRight() && !checkUpperBound(tempMCObject1,tph)) { - MethodConstraint consToAdd = new MethodConstraint(tph, objectType, Relation.EXTENDS); - if (!checkForDuplicates(consToAdd, tempMC)) { - tempMC.add(consToAdd); - } - } - } - } - } - } - return tempMC; - } - -/** - * nimm die Menge cs_cl aus cs_m raus - */ - public List methodTypesWithoutClassTypes(List cs_cl, List cs_m) { - // erstelle Kopie der Liste cs_cl - List tempCC = new ArrayList<>(); - for(ClassConstraint cc: cs_cl) { - TPHConstraint tphC = new TPHConstraint(cc.getLeft(), cc.getRight(), cc.getRel()); - tempCC.add(tphC); - } - // Transitive Hülle von cs_cl - List tcOfCsCl = buildTransitiveClosure(tempCC); - - List tempMC = new ArrayList<>(); - for(MethodConstraint mc: cs_m) { - TPHConstraint tphC = new TPHConstraint(mc.getLeft(), mc.getRight(), mc.getRel()); - tempMC.add(tphC); - } - List tempMC2 = new ArrayList<>(); - tempMC2.addAll(tempMC); - List tempMCToReturn = new ArrayList<>(); - - for(TPHConstraint cc: tcOfCsCl) { - for(TPHConstraint mc: tempMC) { - if(cc.getLeft().equals(mc.getLeft()) && cc.getRight().equals(mc.getRight())) { - tempMC2.remove(mc); - } - } - } - for(TPHConstraint tphC: tempMC2) { - MethodConstraint mCons = new MethodConstraint(tphC.getLeft(), tphC.getRight(), tphC.getRel()); - tempMCToReturn.add(mCons); - } - return tempMCToReturn; - } - - public static boolean checkForDuplicates(TPHConstraint constraint, List list) { - List tempList = list; - boolean hasSame = false; - for (TPHConstraint tphC: tempList) { - hasSame = constraint.getLeft() == tphC.getLeft() && - constraint.getRight() == tphC.getRight() && - constraint.getRel() == tphC.getRel(); //constraint already in ArrayList if true - if (hasSame) - return true; - } - return false; - } - - public List buildTransitiveClosure(List list) { - List iterList = new ArrayList<>(list); - List runList = new ArrayList<>(list); - List tcList = new ArrayList<>(list); - boolean addedConToList = false; - for (TPHConstraint cons: iterList) { - for (TPHConstraint cons2: runList) { - if(cons.getRight() == cons2.getLeft()) { - TPHConstraint consToAdd = new TPHConstraint(cons.getLeft(), cons2.getRight(), Relation.EXTENDS); - if (!checkForDuplicates(consToAdd,tcList)) { - tcList.add(consToAdd); - addedConToList = true; - if (addedConToList) { - return buildTransitiveClosure(tcList); - } - } - } - } - } - return tcList; - } - - public static boolean checkUpperBound(List cs, String tph) { - for(int i=0; i>> positionConverter(HashMap allTphs, List listOfMethodsAndTphs) { - HashMap>> convertedPositions = new HashMap<>(); - for(String tph: allTphs.keySet()) { - List> currMeth = new ArrayList<>(); - if(allTphs.get(tph)) { //if true, then tph is a method-TPH - for(MethodAndTPH methTph: listOfMethodsAndTphs) { - if (methTph.getTphs().contains(tph)) { - currMeth.add(new PairTphMethod<>(PositionFinder.Position.METHOD, methTph.getId())); - } - } - } else { // else it is in the class-TPH - currMeth.add(new PairTphMethod<>(PositionFinder.Position.FIELD, null)); - } - convertedPositions.put(tph, currMeth); - } - return convertedPositions; - } - -/* public PositionFinder.Position positionConverter(TPHExtractor tphExtractor) { - if(tphExtractor.allTPHS.keySet()) - }*/ - - - - - -/* GeneratedGenericsFinder genGenFinder; - ConstraintsSimplierResult simplifiedConstraints = null; - GenericsGeneratorResultForClass ggResult = null; - Method m; - - public void addMethodConstraints(List cs_m) { - genGenFinder.addMethodConstraints(simplifiedConstraints, ggResult, m); - cs_m.add(); - } -*/ - - public static List firstLineMethodDefinition(List allConstraints, HashMap>> posOfTphs, MethodAndTPH methodAndTPH, ResultSet resSet) { - List tempMC= new ArrayList<>(); - MethodAndTPH methAndTphs = methodAndTPH; - Set undCons = methAndTphs.constraints.getUndConstraints(); - List>> orCons = methAndTphs.constraints.getOderConstraints(); - Iterator it = undCons.iterator(); - while(it.hasNext()) { - Pair p = it.next(); - String ta1 = ((TypePlaceholder) (resSet.resolveType(((TypePlaceholder) p.TA1)).resolvedType)).getName(); - String ta2 = ((TypePlaceholder) (resSet.resolveType(((TypePlaceholder) p.TA2)).resolvedType)).getName(); - Relation r = null; - if(p.GetOperator() == PairOperator.SMALLERDOT) { - r = Relation.EXTENDS; - } else if(p.GetOperator() == PairOperator.EQUALSDOT) { - r = Relation.EQUAL; - } - MethodConstraint mc = new MethodConstraint(ta1, ta2, r); - if(mc.getRel() == Relation.EXTENDS) { - if (!mc.getLeft().equals(mc.getRight())) { //eliminieren der Fälle wie AA<.AA - if(!checkForDuplicates(mc, tempMC)) { - tempMC.add(mc); - } - } - } - } - return tempMC; - } - - public List secondLineMethodDefinition(List allConstraints, HashMap>> posOfTphs, MethodAndTPH methodAndTPH, ResultSet resSet, Set oldCons) { - List tempMC = new ArrayList<>(); //für Ergebnisse basierend auf der neuen Datenstruktur (Ali) - Set tempSet = new HashSet<>(); //für Ergebnisse des ersten Teils der Bedinung basierend auf der alten Datenstruktur - Set tempSet2 = new HashSet<>(); //für Ergebnisse des zweiten Teils der Bedingung basierend auf der alten Datenstruktur - Set tcOfoldConsSet = buildTransitiveClosureForCP(oldCons, resSet); - List tcOfCs = buildTransitiveClosure(allConstraints); - MethodAndTPH methAndTphs = methodAndTPH; - Set undCons = methAndTphs.constraints.getUndConstraints(); - List>> orCons = methAndTphs.constraints.getOderConstraints(); - List>> orConsListConverted = new ArrayList<>(); - //gehe die OrConstraints der aktuellen Methode durch und teile nach Operator auf ( - for(int i=0; i orConsWithEQUAL = new ArrayList(); - List orConsWithEXTENDS = new ArrayList(); - HashMap> orConsInternal = new HashMap<>(); - for(Constraint con: orCons.get(i)) { - Iterator it = con.iterator(); - while(it.hasNext()) { - Pair p = it.next(); - Relation r = null; - if(p.GetOperator() == PairOperator.SMALLERDOT) { - r = Relation.EXTENDS; - orConsWithEXTENDS.add(new TPHConstraint(((TypePlaceholder) p.TA1).getName(), ((TypePlaceholder) p.TA2).getName(), r)); - /*MethodConstraint mc = new MethodConstraint(((TypePlaceholder) (resSet.resolveType(((TypePlaceholder) p.TA1)).resolvedType)).getName(), ((TypePlaceholder) (resSet.resolveType(((TypePlaceholder) p.TA2)).resolvedType)).getName(), r); - if(!checkForDuplicates(mc, tempMC)) { - tempMC.add(mc); - }*/ - } else if(p.GetOperator() == PairOperator.EQUALSDOT) { - r = Relation.EQUAL; - orConsWithEQUAL.add(new TPHConstraint(((TypePlaceholder) p.TA1).getName(), ((TypePlaceholder) p.TA2).getName(), r)); - /*MethodConstraint mc = new MethodConstraint(((TypePlaceholder) (resSet.resolveType(((TypePlaceholder) p.TA1)).resolvedType)).getName(), ((TypePlaceholder) (resSet.resolveType(((TypePlaceholder) p.TA2)).resolvedType)).getName(), r); - if(!checkForDuplicates(mc, tempMC)) { - tempMC.add(mc); - }*/ - } - } - } - orConsInternal.put(Relation.EXTENDS, orConsWithEXTENDS); - orConsInternal.put(Relation.EQUAL, orConsWithEQUAL); - orConsListConverted.add(orConsInternal); - } - - // oldCons sind alle Und- und Oder-Constraints - // zunächst in meine Datenstruktur(Ali) konvertieren - List oldConsList = new ArrayList<>(oldCons); - List oldConsListConverted = new ArrayList<>(); - for(Pair pair: oldConsList) { - Relation r = null; - if(pair.GetOperator() == PairOperator.SMALLERDOT) { - r = Relation.EXTENDS; - } else if(pair.GetOperator() == PairOperator.EQUALSDOT) { - r = Relation.EQUAL; - } - oldConsListConverted.add(new TPHConstraint(((TypePlaceholder) pair.TA1).getName(), ((TypePlaceholder) pair.TA2).getName(), r)); - } - - - // Berechnung des zweiten Teils der Bedingung der Regel - for(int i=0; i extendsSet = new Constraint(); - Constraint equalSet = new Constraint(); - //für jede einzelne OrConstraint-Menge gehe durch - for (Constraint con : orCons.get(i)) { - Iterator it = con.iterator(); - while (it.hasNext()) { - Pair p = it.next(); - if (p.OperatorSmallerDot()) { - extendsSet.add(p); - } else if (p.OperatorEqual()) { - equalSet.add(p); - } - } - Iterator itExtends2 = extendsSet.iterator(); - while(itExtends2.hasNext()) { - Pair pairExtends2 = itExtends2.next(); - Set containedVars = new HashSet<>(methodAndTPH.getTphs()); - String pairExtends2RHSName = ((TypePlaceholder)((resSet.resolveType((TypePlaceholder)pairExtends2.TA2)).resolvedType)).getName(); - Iterator itEqual2 = equalSet.iterator(); - while (itEqual2.hasNext()) { - boolean transClo = false; - Pair pairEqual2 = itEqual2.next(); - //TODO: Auf trans.FamilyOfGeneratedGenerics Huelle pruefen - Pair newPairOld = new Pair(pairExtends2.TA2, pairEqual2.TA1); - Pair newPair2 = new Pair(resSet.resolveType((TypePlaceholder) (pairExtends2.TA2)).resolvedType, resSet.resolveType((TypePlaceholder) (pairEqual2.TA1)).resolvedType, PairOperator.SMALLERDOT); - TPHConstraint newPairTPHConstraint = new TPHConstraint(newPair2); - if (tcOfCs.contains(newPairTPHConstraint)|| (newPairTPHConstraint.getLeft().equals(newPairTPHConstraint.getRight()))) { - transClo = true; - } - TypePlaceholder tphR = (TypePlaceholder) pairEqual2.TA2; - Iterator itUndCons = undCons.iterator(); - boolean rEqExRtilde = false; - while (itUndCons.hasNext()) { - Pair pairUndCons2 = itUndCons.next(); - rEqExRtilde = rEqExRtilde || (tphR == pairUndCons2.TA1); - } - boolean isPairInTExTapostrophe = false; - for(Set> scp: orCons) { - Iterator> itSCP = scp.iterator(); - while(itSCP.hasNext()) { - Constraint cp = itSCP.next(); - Iterator itCP = cp.iterator(); - while(itCP.hasNext()) { - Pair p = itCP.next(); - if(p.OperatorSmallerDot()) { - isPairInTExTapostrophe = isPairInTExTapostrophe || tphR.equals(p.TA1); - } - } - } - - } - - if (transClo && (rEqExRtilde || isPairInTExTapostrophe)) { - if (!newPair2.TA1.equals(newPair2.TA2)) { //eliminieren der Fälle wie AA<.AA - if (!checkForDuplicatesForSets(newPair2, tempSet2)) { - tempSet2.add(newPair2); - } - } - if (!checkForDuplicatesForSets(pairExtends2, tempSet2)) { - tempSet2.add(pairExtends2); - } - } - else { - //containedVars.remove(((TypePlaceholder)newPair2.TA2).getName()); - } - - } - - //String key = ((TypePlaceholder)((resSet.resolveType((TypePlaceholder)pairExtends2.TA2)).resolvedType)).getName(); - //TODO: containedVars stimmt noch nicht. Ueberpruefen, ob ggf. mit den containedVars möglicherweise auch die anderen Faelle - // rEqExRtilde isPairInTExTapostrophe abgedeckt sind => ggf. integrieren - /* - posOfTphs.forEach((x,y) -> { - if (y.contains(new PairTphMethod<>(PositionFinder.Position.METHOD, methodAndTPH.getId()))) { - containedVars.add(x); - }; - } - ); - */ - //Referenzbeispiel Put.jav - if (containedVars.stream().filter(v -> tcOfCs.contains(new TPHConstraint(pairExtends2RHSName, v, Relation.EXTENDS))) - .count() > 0) { - System.out.println(); - //tempSet2.add(pairExtends2); - } - if (posOfTphs.containsKey(pairExtends2RHSName)) {//Refrenzbeispiel TestVector.jav - if (posOfTphs.get(pairExtends2RHSName).contains(new PairTphMethod<>(PositionFinder.Position.METHOD, methodAndTPH.getId()))) { - tempSet2.add(pairExtends2); - } - } - } - } - } - - - // aus der alten Datenstruktur in die neue Datenstruktur (von Ali) für ersten Teil - Iterator itTemp = tempSet.iterator(); - while(itTemp.hasNext()) { - Pair p = itTemp.next(); - String ta1 = ((TypePlaceholder) (resSet.resolveType(((TypePlaceholder) p.TA1)).resolvedType)).getName(); - String ta2 = ((TypePlaceholder) (resSet.resolveType(((TypePlaceholder) p.TA2)).resolvedType)).getName(); - Relation r = null; - if(p.GetOperator() == PairOperator.SMALLERDOT) { - r = Relation.EXTENDS; - } else if(p.GetOperator() == PairOperator.EQUALSDOT) { - r = Relation.EQUAL; - } - MethodConstraint mc = new MethodConstraint(ta1, ta2, r); - if(mc.getRel() == Relation.EXTENDS) { - if(!checkForDuplicates(mc, tempMC)) { - tempMC.add(mc); - } - } - } - - // aus der alten Datenstruktur in die neue Datenstruktur (von Ali) für zweiten Teil - Iterator itTemp2 = tempSet2.iterator(); - while(itTemp2.hasNext()) { - Pair p = itTemp2.next(); - String ta1 = ((TypePlaceholder) (resSet.resolveType(((TypePlaceholder) p.TA1)).resolvedType)).getName(); - String ta2 = ((TypePlaceholder) (resSet.resolveType(((TypePlaceholder) p.TA2)).resolvedType)).getName(); - Relation r = null; - if (p.GetOperator() == PairOperator.SMALLERDOT) { - r = Relation.EXTENDS; - } else if (p.GetOperator() == PairOperator.EQUALSDOT) { - r = Relation.EQUAL; - } - for(TPHConstraint tphCons: tcOfCs) {//TODO: hier werden Elemente der Trans. clo herausgenommen, aber die dazugehoerigen OrCons nicht. - if(ta1 == tphCons.getLeft() && ta2 == tphCons.getRight() && r==Relation.EXTENDS) { - MethodConstraint mc = new MethodConstraint(ta1, ta2, r); - if(!checkForDuplicates(mc, tempMC)) { - tempMC.add(mc); - } - } - } - } - - return tempMC; - } - - - public static Set buildTransitiveClosureForCP(Set constraint, ResultSet resSet) { - Set iterSet = new HashSet<>(constraint); - Set runSet = new HashSet<>(constraint); - Set tcSet = new HashSet<>(constraint); - boolean addedConToList = false; -// for (TPHConstraint cons: iterList) { - Iterator itIterSet = iterSet.iterator(); - while(itIterSet.hasNext()) { - Pair pairIterSet = itIterSet.next(); -// for (TPHConstraint cons2: runList) { - Iterator itRunSet = runSet.iterator(); - while (itRunSet.hasNext()) { - Pair pairRunSet = itRunSet.next(); -// if(cons.getRight() == cons2.getLeft()) { - if(pairIterSet.TA2 == pairRunSet.TA1 && pairIterSet.OperatorSmallerDot() && pairRunSet.OperatorSmallerDot()) { -// TPHConstraint consToAdd = new TPHConstraint(cons.getLeft(), cons2.getRight(), Relation.EXTENDS); - Pair p = new Pair(resSet.resolveType((TypePlaceholder)(pairIterSet.TA1)).resolvedType, resSet.resolveType((TypePlaceholder)(pairRunSet.TA2)).resolvedType, PairOperator.SMALLERDOT); -// if (!checkForDuplicates(consToAdd,tcList)) { - if(!checkForDuplicatesForSets(p, tcSet)) { -// tcList.add(consToAdd); - tcSet.add(p); - addedConToList = true; - if (addedConToList) { - return buildTransitiveClosureForCP(tcSet, resSet); - } - } - } - } - } - System.out.println("tcSet: " + tcSet); - return tcSet; - } - - public static boolean checkForDuplicatesForSets(Pair pair, Set set) { - Set tempSet = set; - boolean hasSame = false; -// for (TPHConstraint tphC: tempList) { - Iterator it = tempSet.iterator(); - while (it.hasNext()) { - Pair p = it.next(); -// hasSame = constraint.getLeft() == tphC.getLeft() && -// constraint.getRight() == tphC.getRight() && -// constraint.getRel() == tphC.getRel(); //constraint already in ArrayList if true - hasSame = pair.TA1 == p.TA1 && - pair.TA2 == p.TA2 && - pair.OperatorSmallerDot() && p.OperatorSmallerDot(); //constraint already in Set if true - if (hasSame) - return true; - } - return false; - } - - public static List hasNoSupertypeForMethodTypesNew(HashMap>> posOfTphs, MethodAndTPH methodAndTPH, List cs_m) { - List tempMC = new ArrayList<>(); - List methCons = new ArrayList<>(cs_m); - MethodAndTPH methAndTphs = methodAndTPH; - for(String tph: posOfTphs.keySet()) { - for(int i=0; i methodTypesWithoutClassTypesNEW(List tphsToCompute, List cs_m) { - List tempMC = new ArrayList<>(cs_m); - List tempMC2 = new ArrayList<>(cs_m); - List toRemove = new ArrayList<>(); - for(String tph: tphsToCompute) { - for(TPHConstraint tphCons: tempMC) { - if(tphCons.getLeft() == tph) { - toRemove.add(tphCons.getRight()); - tempMC2.remove(tphCons); - tempMC2 = methodTypesWithoutClassTypesNEW(toRemove,tempMC2); - } - } - } - return tempMC2; - } - - - - public HashMap> getMethodConstraintsWithPositionNew(List cs, List cs_cl, HashMap>> posOfTphs, List listOfMethodsAndTph, ResultSet resSet, Set oldCons) { - HashMap> tempMethodConstraintsWithPosition = new HashMap<>(); - List newMCList = new ArrayList<>(); - List newMCList2 = new ArrayList<>(); - List hasNoSupType = new ArrayList<>(); - List mcWithoutCc = new ArrayList<>(); - - List methodsAddedToHashMap = new ArrayList<>(); - for(MethodAndTPH method: listOfMethodsAndTph){ - String currentMethod = method.getId(); - boolean containsCurrentMethod = false; - if(!containsCurrentMethod) { - methodsAddedToHashMap.add(currentMethod); - containsCurrentMethod = true; - List listToAdd = new ArrayList<>(); - HashMap>> posOfTPHsForThisMethod = new HashMap<>(); - for(String s: posOfTphs.keySet()) { - for(PairTphMethod pair: posOfTphs.get(s)) { - if(pair.snd == currentMethod && pair.snd != null) { - posOfTPHsForThisMethod.put(s,posOfTphs.get(s)); - } - } - } - - newMCList = firstLineMethodDefinition(cs, posOfTphs, method, resSet); - for(int i=0; i tphs = new ArrayList<>(); - for(String tph: posOfTphs.keySet()) { - for (PairTphMethod p : posOfTphs.get(tph)) { - if(p.fst == PositionFinder.Position.FIELD) { - tphs.add(tph); - mcWithoutCc = methodTypesWithoutClassTypesNEW(tphs, listToAdd); - } - } - } - - tempMethodConstraintsWithPosition.put(currentMethod, mcWithoutCc); - } - for(String curMeth: tempMethodConstraintsWithPosition.keySet()){ - for(int i=0; i input = new ArrayList<>(); - List classpath = new ArrayList<>(); - - JavaTXCompiler compiler = new JavaTXCompiler(input, classpath); - compiler.typeInference(); - - public List getResultOfTypeInference() { - return null; - } - - -} -*/ diff --git a/src/main/java/de/dhbwstuttgart/bytecode/insertGenerics/MethodConstraint.java b/src/main/java/de/dhbwstuttgart/bytecode/insertGenerics/MethodConstraint.java deleted file mode 100644 index 89533594..00000000 --- a/src/main/java/de/dhbwstuttgart/bytecode/insertGenerics/MethodConstraint.java +++ /dev/null @@ -1,10 +0,0 @@ -package de.dhbwstuttgart.bytecode.insertGenerics; - -import de.dhbwstuttgart.bytecode.constraint.TPHConstraint; -import de.dhbwstuttgart.bytecode.constraint.TPHConstraint.Relation; - -public class MethodConstraint extends TPHConstraint { - public MethodConstraint(String left, String right, Relation rel) { - super(left, right, rel); - } -} diff --git a/src/main/java/de/dhbwstuttgart/bytecode/insertGenerics/PairMethodAndConstraint.java b/src/main/java/de/dhbwstuttgart/bytecode/insertGenerics/PairMethodAndConstraint.java deleted file mode 100644 index c8f44ea6..00000000 --- a/src/main/java/de/dhbwstuttgart/bytecode/insertGenerics/PairMethodAndConstraint.java +++ /dev/null @@ -1,47 +0,0 @@ -package de.dhbwstuttgart.bytecode.insertGenerics; - -import java.util.Objects; - -/** A generic class for pairs. - * - *

This is NOT part of any supported API. - * If you write code that depends on this, you do so at your own risk. - * This code and its internal interfaces are subject to change or - * deletion without notice. - */ - - -public class PairMethodAndConstraint { - public final A fst; - public final B snd; - - public PairMethodAndConstraint(A fst, B snd) { - this.fst = fst; - this.snd = snd; - } - - public String toString() { - return "PairTphMethod[" + fst + "," + snd + "]"; - } - - public boolean equals(Object other) { - return - other instanceof PairMethodAndConstraint && - Objects.equals(fst, ((PairMethodAndConstraint)other).fst) && - Objects.equals(snd, ((PairMethodAndConstraint)other).snd); - } - - public int hashCode() { - if (fst == null) return (snd == null) ? 0 : snd.hashCode() + 1; - else if (snd == null) return fst.hashCode() + 2; - else return fst.hashCode() * 17 + snd.hashCode(); - } - - public static PairMethodAndConstraint of(A a, B b) { - return new PairMethodAndConstraint<>(a,b); - } - - public PairMethodAndConstraint add(A fst, B snd){ - return new PairMethodAndConstraint<>(fst,snd); - } -} diff --git a/src/main/java/de/dhbwstuttgart/bytecode/insertGenerics/PairTphMethod.java b/src/main/java/de/dhbwstuttgart/bytecode/insertGenerics/PairTphMethod.java deleted file mode 100644 index 75313ba9..00000000 --- a/src/main/java/de/dhbwstuttgart/bytecode/insertGenerics/PairTphMethod.java +++ /dev/null @@ -1,43 +0,0 @@ -package de.dhbwstuttgart.bytecode.insertGenerics; - -import java.util.Objects; - -/** A generic class for pairs. - * - *

This is NOT part of any supported API. - * If you write code that depends on this, you do so at your own risk. - * This code and its internal interfaces are subject to change or - * deletion without notice. - */ - - -public class PairTphMethod { - public final A fst; - public final B snd; - - public PairTphMethod(A fst, B snd) { - this.fst = fst; - this.snd = snd; - } - - public String toString() { - return "PairTphMethod[" + fst + "," + snd + "]"; - } - - public boolean equals(Object other) { - return - other instanceof PairTphMethod && - Objects.equals(fst, ((PairTphMethod)other).fst) && - Objects.equals(snd, ((PairTphMethod)other).snd); - } - - public int hashCode() { - if (fst == null) return (snd == null) ? 0 : snd.hashCode() + 1; - else if (snd == null) return fst.hashCode() + 2; - else return fst.hashCode() * 17 + snd.hashCode(); - } - - public static PairTphMethod of(A a, B b) { - return new PairTphMethod<>(a,b); - } -} diff --git a/src/main/java/de/dhbwstuttgart/bytecode/insertGenerics/PositionFinder.java b/src/main/java/de/dhbwstuttgart/bytecode/insertGenerics/PositionFinder.java deleted file mode 100644 index 33ecfbc6..00000000 --- a/src/main/java/de/dhbwstuttgart/bytecode/insertGenerics/PositionFinder.java +++ /dev/null @@ -1,79 +0,0 @@ -package de.dhbwstuttgart.bytecode.insertGenerics; - -import de.dhbwstuttgart.syntaxtree.*; -import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder; - -import java.util.HashMap; -import java.util.Set; - -public class PositionFinder{ - static HashMap> posOfTphs = new HashMap>(); - - static PairTphMethod whichMethod; // gibt an, in welcher Methode sich TPH befindet (Position.METHOD, id_of_method) - - public enum Position{ - METHOD, - CONSTRUCTOR, - FIELD - } - - public static HashMap> getPositionOfTPH(SourceFile sf, Set tphs) { - - new Walker().visit(sf); - for (String tph: posOfTphs.keySet()) { - System.out.println(tph + " " + posOfTphs.get(tph)); - } - - return null; - } - public static void putPositionInMethod(String tph, String methodId) { - posOfTphs.put(tph, new PairTphMethod<>(Position.METHOD, methodId)); - } - - public static void putPositionInField(String tph) { - posOfTphs.put(tph, new PairTphMethod<>(Position.FIELD, null)); - } - - public static void putPositionInConstructor(String tph, String id) { - posOfTphs.put(tph, new PairTphMethod<>(Position.CONSTRUCTOR, id)); - } - - - - static class Walker extends AbstractASTWalker{ - Boolean inMethod = false; - Boolean inConstructor = false; - - @Override - public void visit(TypePlaceholder tph) { - if (inMethod) { - if (inConstructor) { -// System.out.println(tph); -// putPositionInConstructor(tph.getName(),); - } -// System.out.println(tph); -// putPositionInMethod(tph.getName(),); - } else { - putPositionInField(tph.getName()); - } - } - - @Override - public void visit(Field field) { - super.visit(field); - } - - @Override - public void visit(Method method) { - inMethod = true; - super.visit(method); - } - - @Override - public void visit(Constructor cons) { - inConstructor = true; - super.visit(cons); - } - } - -} diff --git a/src/main/java/de/dhbwstuttgart/bytecode/insertGenerics/preGGenerics.java b/src/main/java/de/dhbwstuttgart/bytecode/insertGenerics/preGGenerics.java deleted file mode 100644 index 088a435b..00000000 --- a/src/main/java/de/dhbwstuttgart/bytecode/insertGenerics/preGGenerics.java +++ /dev/null @@ -1,9 +0,0 @@ -package de.dhbwstuttgart.bytecode.insertGenerics; - -import de.dhbwstuttgart.typeinference.result.ResultSet; - -import java.util.List; - -interface preGGenerics { - public List getResultOfTypeInference(); -} \ No newline at end of file diff --git a/src/main/java/de/dhbwstuttgart/bytecode/signature/Signature.java b/src/main/java/de/dhbwstuttgart/bytecode/signature/Signature.java deleted file mode 100644 index 47254170..00000000 --- a/src/main/java/de/dhbwstuttgart/bytecode/signature/Signature.java +++ /dev/null @@ -1,379 +0,0 @@ -package de.dhbwstuttgart.bytecode.signature; - -import java.util.*; - -import org.objectweb.asm.Type; -import org.objectweb.asm.signature.SignatureVisitor; -import org.objectweb.asm.signature.SignatureWriter; - -import de.dhbwstuttgart.bytecode.constraint.TPHConstraint; -import de.dhbwstuttgart.bytecode.descriptor.TypeToDescriptor; -import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.GenericsGeneratorResult; -import de.dhbwstuttgart.syntaxtree.ClassOrInterface; -import de.dhbwstuttgart.syntaxtree.Constructor; -import de.dhbwstuttgart.syntaxtree.GenericTypeVar; -import de.dhbwstuttgart.syntaxtree.Method; -import de.dhbwstuttgart.syntaxtree.type.ExtendsWildcardType; -import de.dhbwstuttgart.syntaxtree.type.GenericRefType; -import de.dhbwstuttgart.syntaxtree.type.RefType; -import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric; -import de.dhbwstuttgart.syntaxtree.type.SuperWildcardType; -import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder; -import de.dhbwstuttgart.typeinference.result.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 final SignatureWriter sw = new SignatureWriter();; - private Constructor constructor; - private Method method; - private HashMap methodParamsAndTypes; - private ResultSet resultSet; - private Map> methodConstraints; - private List consClass; - private List constraints; - -// 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.constraints = constraints; - } - - 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; - } - - public Signature(HashMap genericsAndBoundsMethod, - HashMap genericsAndBounds, - HashMap methodParamsAndTypes, ResultSet resultSet, - List constraints,List consClass) { - this.genericsAndBoundsMethod = genericsAndBoundsMethod; - this.genericsAndBounds = genericsAndBounds; - this.methodParamsAndTypes = methodParamsAndTypes; - this.resultSet = resultSet; - this.constraints = constraints; - this.consClass = consClass; - } - - public String createSignatureForConstructor(Constructor constructor) { - visitParams(); - sw.visitReturnType().visitBaseType('V'); - return sw.toString(); - } - - public String createSignatureForMethod(Method method) { - defineGenerics(method); - - String ret = resultSet.resolveType(method.getReturnType()).resolvedType.acceptTV(new TypeToSignature()); - - visitParams(); - visitReturnType(method, ret); - return sw.toString(); - } - - /** - * @param method - * @param ret - */ - private void visitReturnType(Method method, String ret) { - if (ret.equals("V")) { - sw.visitReturnType().visitBaseType('V'); - } else { - RefTypeOrTPHOrWildcardOrGeneric returnType = method.getReturnType(); - SignatureVisitor sv = sw.visitReturnType(); - doVisitParamsOrReturn(returnType, sv); - } - } - - /** - * - */ - private void visitParams() { - for (String paramName : methodParamsAndTypes.keySet()) { - RefTypeOrTPHOrWildcardOrGeneric t = methodParamsAndTypes.get(paramName); - SignatureVisitor sv = sw.visitParameterType(); - doVisitParamsOrReturn(t, sv); - } - } - - /** - * - * @param method - */ - private void defineGenerics(Method method) { - method.getGenerics().forEach(g -> { - visitTypeVarsAndTheirBounds(g, genericsAndBoundsMethod); - }); - defineGenericsFromConstraints(constraints,genericsAndBoundsMethod); - } - - private void createSignatureForFunN(int numberOfParams, String to, String[] paramTypes) { - defineTypeVariablesForParametersOfFunN(numberOfParams); - - sw.visitFormalTypeParameter("R"); - visitClassBound(to); - // TODO: prüfe ob Return-Type = void, - sw.visitSuperclass().visitClassType(Type.getInternalName(Object.class)); - sw.visitEnd(); - - } - - private void createSignatureForFunN(int numberOfParams) { - - defineTypeVariablesForParametersOfFunN(numberOfParams); - - sw.visitFormalTypeParameter("R"); - // getBounds vom Return-Type - sw.visitClassBound().visitClassType(Type.getInternalName(Object.class)); - sw.visitClassBound().visitEnd(); - // TODO: prüfe ob Return-Type = void, - sw.visitSuperclass().visitClassType(Type.getInternalName(Object.class)); - sw.visitEnd(); - } - - private void defineTypeVariablesForParametersOfFunN(int numberOfParams) { - for (int i = 0; i < numberOfParams; i++) { - int j = i + 1; - sw.visitFormalTypeParameter("T" + j); - // getBounds von Params - sw.visitClassBound().visitClassType(Type.getInternalName(Object.class)); - sw.visitClassBound().visitEnd(); - } - } - - /** - * Visits parameter type or return type with {@link SignatureVisitor} to create - * the method signature - * - * @param t type of parameter or return type - * @param sv true if t is type of parameter - */ - private void doVisitParamsOrReturn(RefTypeOrTPHOrWildcardOrGeneric t, SignatureVisitor sv) { - String type = t.acceptTV(new TypeToString()); - - switch (type) { - case "RT": - String sig = t.acceptTV(new TypeToSignature(constraints)); - sv.visitClassType(sig.substring(1, sig.length())); - break; - case "GRT": - GenericRefType g = (GenericRefType) t; - sv.visitTypeVariable(g.acceptTV(new TypeToSignature(constraints))); - break; - case "TPH": - RefTypeOrTPHOrWildcardOrGeneric r = resultSet.resolveType(t).resolvedType; - // der Fall wenn der Typ eine Interface ist, muss betrachtet werden - // Deswegen muss in ResutSet noch enthalten werden, ob die Type eine - // Interface oder eine Klasse ist. - - // das braucht man nicht es reicht: sv.visitTypeVariable(r.acceptTV(new - // TypeToSignature()) - // - String sig2 = r.acceptTV(new TypeToSignature(constraints)); - if (r instanceof GenericRefType) { - sv.visitTypeVariable(sig2); - } else if (!(r instanceof TypePlaceholder)) { - if (sig2.contains(SPECIAL_CHAR_FOR_FUN)) { - sv.visitInterface().visitClassType(sig2.substring(1)); - } else { - // Kann zwischen GenericRefType und RefType nicht unterscheiden - // Deswegen wird immer geprüft, ob der Name in Generic Maps liegt - String n = sig2.substring(1, sig2.length() - 1); -// if(genericsAndBoundsMethod.containsKey(n) || genericsAndBounds.containsKey(n)) { -// sv.visitTypeVariable(n); -// } else { - sv.visitClassType(n); - sv.visitEnd(); -// } -// sv.visitClassType(n); - } - - } else { - String realName = sig2.substring(1, sig2.length() - 1); - String toVisit = realName+SPECIAL_CHAR; - if(!genericsAndBounds.containsKey(toVisit)) { - Optional equalTPH = getEqualTPHFromClassConstraints(consClass, realName); - if(equalTPH.isPresent()){ - toVisit = equalTPH.get().getConstraint().getLeft() + SPECIAL_CHAR; - } else { - toVisit = getEqualTPH(constraints, realName) + SPECIAL_CHAR; - } - } - sv.visitTypeVariable(toVisit); - } - - break; - - case "SWC": - SuperWildcardType swc = (SuperWildcardType) t; - String sigInner = swc.getInnerType().acceptTV(new TypeToSignature(constraints)); - int length = sigInner.length(); - visitWildCard(sv, sigInner, length, swc.getInnerType(), SUPER_CHAR); - - break; - - case "EWC": - ExtendsWildcardType ewc = (ExtendsWildcardType) t; - String esigInner = ewc.getInnerType().acceptTV(new TypeToSignature(constraints)); - int lengthEWCSig = esigInner.length(); - visitWildCard(sv, esigInner, lengthEWCSig, ewc.getInnerType(), EXTENDS_CHAR); - - break; - default: -// if (!sv) -// sv.visitBaseType('V'); - break; - } - } - - private void visitWildCard(SignatureVisitor sv, String sigInner, int length, RefTypeOrTPHOrWildcardOrGeneric innerType, char superOrExtendsChar) { - if (innerType instanceof TypePlaceholder) { - sv.visitTypeArgument(superOrExtendsChar).visitTypeVariable(sigInner.substring(1, length)); - } else if (innerType instanceof RefType) { - checkInnerSignatureOfWildCard(sv, sigInner, length, superOrExtendsChar); - } else { - sv.visitTypeArgument(superOrExtendsChar).visitTypeVariable(sigInner.substring(1)); - } - } - - private void checkInnerSignatureOfWildCard(SignatureVisitor sv, String sigInner, int length, char superOrExtendsChar) { - if (sigInner.contains(SPECIAL_CHAR_FOR_FUN)) { - sv.visitTypeArgument(superOrExtendsChar).visitInterface().visitClassType(sigInner.substring(1, length)); - } else { - sv.visitTypeArgument(superOrExtendsChar).visitClassType(sigInner.substring(1, length)); - } - } - - private Optional 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(); - } - - /** - * Creates signature for class or interface with {@link SignatureWriter} - * Signature looks like: superclass - */ - public String createSignatureForClassOrInterface() { - defineTypeVariablesForClassOrInterface(); - - defineGenericsFromConstraints(consClass,genericsAndBounds); - - String sClass = classOrInterface.getSuperClass().acceptTV(new TypeToSignature()); - sw.visitSuperclass().visitClassType(sClass.substring(1, sClass.length() - 1)); - sw.visitEnd(); - return sw.toString(); - } - - private void defineTypeVariablesForClassOrInterface() { - Iterator itr = classOrInterface.getGenerics().iterator(); - - while (itr.hasNext()) { - GenericTypeVar g = itr.next(); - visitTypeVarsAndTheirBounds(g, genericsAndBounds); - } - } - - /** - * @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 - */ - private void visitTypeVarsAndTheirBounds(GenericTypeVar g, HashMap genAndBounds) { - sw.visitFormalTypeParameter(g.getName()); - - Iterator bItr = g.getBounds().iterator(); - while (bItr.hasNext()) { - RefTypeOrTPHOrWildcardOrGeneric b = bItr.next(); - String boundDesc = b.acceptTV(new TypeToDescriptor()); - // Ensure that <...> extends java.lang.Object OR ... - if (b instanceof GenericRefType) { - sw.visitClassBound().visitTypeVariable(boundDesc); - } else { - visitClassBound(boundDesc); - } - genAndBounds.put(g.getName(), boundDesc); - } - } - - @Override - public String toString() { - if(sw == null) - return super.toString(); - return sw.toString(); - } -} diff --git a/src/main/java/de/dhbwstuttgart/bytecode/signature/TypeToSignature.java b/src/main/java/de/dhbwstuttgart/bytecode/signature/TypeToSignature.java deleted file mode 100644 index 0026b85f..00000000 --- a/src/main/java/de/dhbwstuttgart/bytecode/signature/TypeToSignature.java +++ /dev/null @@ -1,115 +0,0 @@ -package de.dhbwstuttgart.bytecode.signature; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.Optional; - -import de.dhbwstuttgart.bytecode.funN.FunNGenerator; -import de.dhbwstuttgart.bytecode.funN.FunNUtilities; -import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.GenericsGeneratorResult; -import de.dhbwstuttgart.syntaxtree.type.ExtendsWildcardType; -import de.dhbwstuttgart.syntaxtree.type.GenericRefType; -import de.dhbwstuttgart.syntaxtree.type.RefType; -import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric; -import de.dhbwstuttgart.syntaxtree.type.SuperWildcardType; -import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder; -import de.dhbwstuttgart.syntaxtree.type.TypeVisitor; - -public class TypeToSignature implements TypeVisitor { - private List constraints; - - private final boolean specializedFunN; - - public TypeToSignature() { this(new ArrayList<>(), true); } - - public TypeToSignature(boolean specializedFunN) { this(new ArrayList<>(), specializedFunN); } - - public TypeToSignature(List constraints) { - this(constraints, true); - } - - public TypeToSignature(List constraints, boolean specializedFunN){ - this.constraints = constraints; - this.specializedFunN = specializedFunN; - } - - @Override - public String visit(RefType refType) { - if(refType.getName().toString().equals("void")) - return "V"; - if (refType.getName().toString().matches("Fun\\d+\\$\\$") && specializedFunN){ - FunNUtilities funNUtilities = FunNGenerator.getInstance(); - return funNUtilities.getSpecializedSignature(funNUtilities.getArguments(refType.getParaList()), funNUtilities.getReturnType(refType.getParaList())); - } -// return refType.toString().replace(".", "/"); - String params = ""; - if(refType.getParaList().size()>0){ - params += "<"; - Iterator it = refType.getParaList().iterator(); - while(it.hasNext()){ - RefTypeOrTPHOrWildcardOrGeneric param = it.next(); -// if(param instanceof TypePlaceholder) { -// params += "T" + ((TypePlaceholder) param).getName() + "$"; -// } else if(param instanceof ExtendsWildcardType) { -// params += "+" + ((ExtendsWildcardType) param).getInnerType().acceptTV(new TypeToSignature()); -// } else if(param instanceof SuperWildcardType) { -// params += "-" + ((SuperWildcardType) param).getInnerType().acceptTV(new TypeToSignature()); -// } else { -// params += "L"+param.toString().replace(".", "/"); -// } - params += param.acceptTV(new TypeToSignature(constraints)); - - if(param instanceof TypePlaceholder) - params += ";"; - } - params += ">"; - } -// String t = refType.getName().toString().replace(".", "/"); -// return t.equals("Fun1")?t+"$$"+params+";":t+params+";"; - return "L"+refType.getName().toString().replace(".", "/") + params+";"; - } - - @Override - public String visit(SuperWildcardType superWildcardType) { -// throw new NotImplementedException(); - String sig = "-" + superWildcardType.getInnerType().acceptTV(new TypeToSignature(constraints)); - if(superWildcardType.getInnerType() instanceof TypePlaceholder) - sig += ";"; - return sig; - } - - @Override - public String visit(TypePlaceholder typePlaceholder) { -// return typePlaceholder.toString().replace(".", "/"); - String name = typePlaceholder.getName(); - - if(!constraints.isEmpty()){ - Optional equalName = getEqualTPHFromClassConstraints(constraints, name); - if(equalName.isPresent()) - name = equalName.get().getConstraint().getLeft(); - } - - return "T" + name + "$"; - } - - @Override - public String visit(ExtendsWildcardType extendsWildcardType) { -// throw new NotImplementedException(); - String sig = "+" + extendsWildcardType.getInnerType().acceptTV(new TypeToSignature(constraints)); - if(extendsWildcardType.getInnerType() instanceof TypePlaceholder) - sig += ";"; - return sig; - } - - @Override - public String visit(GenericRefType genericRefType) { - return genericRefType.getParsedName().replace(".", "/"); - } - - private Optional getEqualTPHFromClassConstraints(List listOfConstraints, String tph) { - return listOfConstraints.stream() - .filter(c -> c.getConstraint().getLeft().equals(tph) || c.getEqualsTPHs().contains(tph)) - .findFirst(); - } -} diff --git a/src/main/java/de/dhbwstuttgart/bytecode/signature/TypeToString.java b/src/main/java/de/dhbwstuttgart/bytecode/signature/TypeToString.java deleted file mode 100644 index a0e280c2..00000000 --- a/src/main/java/de/dhbwstuttgart/bytecode/signature/TypeToString.java +++ /dev/null @@ -1,38 +0,0 @@ -package de.dhbwstuttgart.bytecode.signature; - -import de.dhbwstuttgart.exceptions.NotImplementedException; -import de.dhbwstuttgart.syntaxtree.type.ExtendsWildcardType; -import de.dhbwstuttgart.syntaxtree.type.GenericRefType; -import de.dhbwstuttgart.syntaxtree.type.RefType; -import de.dhbwstuttgart.syntaxtree.type.SuperWildcardType; -import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder; -import de.dhbwstuttgart.syntaxtree.type.TypeVisitor; - -public class TypeToString implements TypeVisitor{ - - @Override - public String visit(RefType refType) { - return "RT"; - } - - @Override - public String visit(SuperWildcardType superWildcardType) { - return "SWC"; - } - - @Override - public String visit(TypePlaceholder typePlaceholder) { - return "TPH"; - } - - @Override - public String visit(ExtendsWildcardType extendsWildcardType) { - return "EWC"; - } - - @Override - public String visit(GenericRefType genericRefType) { - return "GRT"; - } - -} diff --git a/src/main/java/de/dhbwstuttgart/bytecode/simplifyRes/GenericGenratorResultForSourceFile.java b/src/main/java/de/dhbwstuttgart/bytecode/simplifyRes/GenericGenratorResultForSourceFile.java deleted file mode 100644 index a36f6e07..00000000 --- a/src/main/java/de/dhbwstuttgart/bytecode/simplifyRes/GenericGenratorResultForSourceFile.java +++ /dev/null @@ -1,50 +0,0 @@ -/** - * - */ -package de.dhbwstuttgart.bytecode.simplifyRes; - -import java.util.ArrayList; -import java.util.List; -import java.util.NoSuchElementException; - -/** - * The simplify results of a source file (package) - * - * @author fayez - * - */ -public class GenericGenratorResultForSourceFile { - private String pkgName; - private final List 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) { - for (int i = 0; i < genericGeneratorResultForAllClasses.size(); i++) { - GenericsGeneratorResultForClass genericsGeneratorResult = genericGeneratorResultForAllClasses.get(i); - if (genericsGeneratorResult.getClassName().equals(name)) { - return genericsGeneratorResult; - } - } - - return new GenericsGeneratorResultForClass(name); - } -} diff --git a/src/main/java/de/dhbwstuttgart/bytecode/simplifyRes/GenericsGeneratorResultForClass.java b/src/main/java/de/dhbwstuttgart/bytecode/simplifyRes/GenericsGeneratorResultForClass.java deleted file mode 100644 index ff575b67..00000000 --- a/src/main/java/de/dhbwstuttgart/bytecode/simplifyRes/GenericsGeneratorResultForClass.java +++ /dev/null @@ -1,75 +0,0 @@ -/** - * - */ -package de.dhbwstuttgart.bytecode.simplifyRes; - -import java.util.Collections; -import java.util.List; - -import com.google.common.base.Optional; - -import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.GenericGeneratorResultsForAllMethods; -import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.GenericsGeneratorResult; -import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.MethodAndConstraints; - -/** - * @author fayez - * - */ -public class GenericsGeneratorResultForClass { - private final String className; - private final List classConstraints; - private final GenericGeneratorResultsForAllMethods methodsAndTheirConstraints; - - public GenericsGeneratorResultForClass(String className) { - this(className, Collections.emptyList(), new GenericGeneratorResultsForAllMethods()); - } - /** - * @param className - * @param classConstraints - * @param methodsAndTheirConstraints - */ - public GenericsGeneratorResultForClass(String className, List 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) { - java.util.Optional methodAndConstraints = methodsAndTheirConstraints.getMethodsAndConstraints().stream().filter(mc -> mc.getMethodID().equals(id)) - .findFirst(); - - return methodAndConstraints.isPresent() ? methodAndConstraints.get().getConstraints() : Collections.emptyList(); - } - -} diff --git a/src/main/java/de/dhbwstuttgart/bytecode/utilities/ByteCodeForFunNGenerator.java b/src/main/java/de/dhbwstuttgart/bytecode/utilities/ByteCodeForFunNGenerator.java deleted file mode 100644 index 24b5f627..00000000 --- a/src/main/java/de/dhbwstuttgart/bytecode/utilities/ByteCodeForFunNGenerator.java +++ /dev/null @@ -1,94 +0,0 @@ -package de.dhbwstuttgart.bytecode.utilities; - -import de.dhbwstuttgart.bytecode.signature.Signature; -import de.dhbwstuttgart.syntaxtree.FormalParameter; -import de.dhbwstuttgart.syntaxtree.statement.ArgumentList; -import de.dhbwstuttgart.syntaxtree.statement.Expression; -import de.dhbwstuttgart.syntaxtree.statement.LambdaExpression; -import org.objectweb.asm.ClassWriter; -import org.objectweb.asm.MethodVisitor; -import org.objectweb.asm.Opcodes; -import org.objectweb.asm.Type; -import org.objectweb.asm.signature.SignatureVisitor; -import org.objectweb.asm.signature.SignatureWriter; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.Iterator; - -public class ByteCodeForFunNGenerator { - - public static void generateBCForFunN(LambdaExpression lambdaExpression, String methDesc, File path) { - ClassWriter classWriter = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS); - - SignatureWriter methSig = new SignatureWriter(); - - int numberOfParams = 0; - SignatureVisitor paramVisitor = methSig.visitParameterType(); - Iterator itr = lambdaExpression.params.iterator(); - while (itr.hasNext()) { - numberOfParams++; - // getBounds - paramVisitor.visitTypeVariable(CONSTANTS.T + numberOfParams); - itr.next(); - } - methSig.visitReturnType().visitTypeVariable(CONSTANTS.R); - // ")"+lam.getReturn.getBounds - Signature sig = new Signature(numberOfParams); - String name = CONSTANTS.FUN + numberOfParams + CONSTANTS.$$; - classWriter.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC+Opcodes.ACC_INTERFACE + Opcodes.ACC_ABSTRACT, name, sig.toString(), - Type.getInternalName(Object.class), null); - MethodVisitor mvApply = classWriter.visitMethod(Opcodes.ACC_PUBLIC + Opcodes.ACC_ABSTRACT, "apply", methDesc, - methSig.toString(), null); - mvApply.visitEnd(); - writeClassFile(classWriter.toByteArray(), name, path); - } - - public static void generateBCForFunN(ArgumentList argumentList, String methDesc, File path) { - ClassWriter classWriter = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS); - - SignatureWriter methSig = new SignatureWriter(); - - int numberOfParams = 0; - SignatureVisitor paramVisitor = methSig.visitParameterType(); - Iterator itr1 = argumentList.getArguments().iterator(); - - while(itr1.hasNext()) { - numberOfParams++; - // getBounds - paramVisitor.visitTypeVariable(CONSTANTS.T + numberOfParams); - itr1.next(); - } - - methSig.visitReturnType().visitTypeVariable(CONSTANTS.R); - // ")"+lam.getReturn.getBounds - Signature sig = new Signature(numberOfParams); - String name = CONSTANTS.FUN + numberOfParams + CONSTANTS.$$; - classWriter.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC+Opcodes.ACC_INTERFACE + Opcodes.ACC_ABSTRACT, name, sig.toString(), - Type.getInternalName(Object.class), null); - MethodVisitor mvApply = classWriter.visitMethod(Opcodes.ACC_PUBLIC + Opcodes.ACC_ABSTRACT, "apply", methDesc, - methSig.toString(), null); - mvApply.visitEnd(); - writeClassFile(classWriter.toByteArray(), name, path); - } - - - public static void writeClassFile(byte[] bytecode, String name, File path) { - FileOutputStream output; - try { - System.out.println("generating " + name + ".class file..."); - output = new FileOutputStream( - new File(path , name + CONSTANTS.EXTENSIONCLASS)); - output.write(bytecode); - output.close(); - System.out.println(name + ".class file generated"); - } catch (FileNotFoundException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - - } -} diff --git a/src/main/java/de/dhbwstuttgart/bytecode/utilities/CONSTANTS.java b/src/main/java/de/dhbwstuttgart/bytecode/utilities/CONSTANTS.java deleted file mode 100644 index da05e82e..00000000 --- a/src/main/java/de/dhbwstuttgart/bytecode/utilities/CONSTANTS.java +++ /dev/null @@ -1,22 +0,0 @@ -package de.dhbwstuttgart.bytecode.utilities; - -public interface CONSTANTS { - - String VOID = "void"; - String TPH = "TPH "; - String ANGLEBRACKET = "<"; - String FUN = "Fun"; - String EXTENSIONCLASS = ".class"; - String $$ = "$$"; - String T = "T"; - String R = "R"; - String DESUGAREDMETHODNAME = "lambda$new$"; - String REFTYPE_BYTE = "java/lang/Byte"; - String REFTYPE_SHORT = "java/lang/Short"; - String REFTYPE_INTEGER = "java/lang/Integer"; - String REFTYPE_LONG = "java/lang/Long"; - String REFTYPE_DOUBLE = "java/lang/Double"; - String REFTYPE_FLOAT = "java/lang/Float"; - String REFTYPE_STRING = "java/lang/String"; - String TO_STRING = "toString"; -} diff --git a/src/main/java/de/dhbwstuttgart/bytecode/utilities/ConstraintsFinder.java b/src/main/java/de/dhbwstuttgart/bytecode/utilities/ConstraintsFinder.java deleted file mode 100644 index 8597abfb..00000000 --- a/src/main/java/de/dhbwstuttgart/bytecode/utilities/ConstraintsFinder.java +++ /dev/null @@ -1,53 +0,0 @@ -package de.dhbwstuttgart.bytecode.utilities; - -import java.util.ArrayList; -import java.util.List; - -import de.dhbwstuttgart.bytecode.constraint.TPHConstraint; -import de.dhbwstuttgart.bytecode.constraint.TPHConstraint.Relation; -import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.ConstraintsWithSameLeftSide; - -public class ConstraintsFinder { - private List allConstaints; - - public ConstraintsFinder(List allConstaints) { - this.allConstaints = allConstaints; - } - - public List findConstraints() { - List result = new ArrayList<>(); - - List visitedCons = new ArrayList<>(); - for(TPHConstraint c : allConstaints) { - if(c.getRel() == Relation.EXTENDS) { - // get constraints with the same left side - List cons = getConstraints(c,visitedCons); - if(cons.size()>1) { - ConstraintsWithSameLeftSide consWithSameLeftSide = new ConstraintsWithSameLeftSide(cons); - result.add(consWithSameLeftSide); - } - } - } - - return result; - } - - private List getConstraints(TPHConstraint c, List visitedCons) { - List res = new ArrayList<>(); - for(TPHConstraint cons : allConstaints) { - if(!isVisited(cons,visitedCons) && cons.getLeft().equals(c.getLeft())) { - res.add(cons); - visitedCons.add(cons); - } - } - return res; - } - - private boolean isVisited(TPHConstraint cons, List visitedCons) { - for(TPHConstraint c : visitedCons) { - if(c.getLeft().equals(cons.getLeft()) && c.getRight().equals(cons.getRight())) - return true; - } - return false; - } -} diff --git a/src/main/java/de/dhbwstuttgart/bytecode/utilities/KindOfLambda.java b/src/main/java/de/dhbwstuttgart/bytecode/utilities/KindOfLambda.java deleted file mode 100644 index 39339cbe..00000000 --- a/src/main/java/de/dhbwstuttgart/bytecode/utilities/KindOfLambda.java +++ /dev/null @@ -1,243 +0,0 @@ -package de.dhbwstuttgart.bytecode.utilities; - -import de.dhbwstuttgart.syntaxtree.statement.*; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import de.dhbwstuttgart.parser.SyntaxTreeGenerator.AssignToLocal; -import de.dhbwstuttgart.syntaxtree.FormalParameter; -import de.dhbwstuttgart.syntaxtree.ParameterList; -import de.dhbwstuttgart.syntaxtree.StatementVisitor; -import de.dhbwstuttgart.syntaxtree.statement.Literal; -import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric; - -public class KindOfLambda implements StatementVisitor{ - private ParameterList params; - private boolean isInstanceCapturingLambda = false; - private List argumentList = new ArrayList<>(); - private ArrayList usedVars = new ArrayList<>(); - private ArrayList varsFromInnerLambdas = new ArrayList<>(); - private boolean thisUsed = false; - private ArrayList definedLocals = new ArrayList<>(); - - public KindOfLambda(LambdaExpression lambdaExpression) { - this.params = lambdaExpression.params; - lambdaExpression.methodBody.accept(this); - - } - - public ArrayList getUsedVars() { - return usedVars; - } - - public boolean isInstanceCapturingLambda() { - return this.isInstanceCapturingLambda; - } - - public List getArgumentList() { - return argumentList; - } - - public boolean isThisUsed() { - return thisUsed; - } - - @Override - public void visit(ArgumentList argumentList) { - argumentList.getArguments().forEach(a->a.accept(this)); - - } - - @Override - public void visit(LambdaExpression lambdaExpression) { - lambdaExpression.params.getFormalparalist().forEach(p->varsFromInnerLambdas.add(p.getName())); - lambdaExpression.methodBody.accept(this); - } - - @Override - public void visit(Assign assign) { - assign.rightSide.accept(this); - } - - @Override - public void visit(BinaryExpr binary) { - binary.lexpr.accept(this); - binary.rexpr.accept(this); - } - - @Override - public void visit(Block block) { - for(Statement stmt : block.getStatements()) { - stmt.accept(this); - } - } - - @Override - public void visit(CastExpr castExpr) { - // TODO Auto-generated method stub - - } - - @Override - public void visit(EmptyStmt emptyStmt) { - // TODO Auto-generated method stub - - } - - @Override - public void visit(FieldVar fieldVar) { - fieldVar.receiver.accept(this); - } - - @Override - public void visit(ForStmt forStmt) { - // TODO Auto-generated method stub - - } - - @Override - public void visit(IfStmt ifStmt) { - ifStmt.expr.accept(this); - ifStmt.then_block.accept(this); - ifStmt.else_block.accept(this); - } - - @Override - public void visit(InstanceOf instanceOf) { - // TODO Auto-generated method stub - - } - - @Override - public void visit(LocalVar localVar) { - boolean addVar = !contain(params, localVar.name) && !definedLocals.contains(localVar.name) && - !varsFromInnerLambdas.contains(localVar.name) && !usedVars.contains(localVar.name); - if(addVar) { - argumentList.add(localVar.getType()); - if(thisUsed) { - usedVars.add(1, localVar.name); - } else { - usedVars.add(0, localVar.name); - } - if(!isInstanceCapturingLambda) - isInstanceCapturingLambda=true; - } - } - - private boolean contain(ParameterList params2, String name) { - Iterator itr = params2.iterator(); - while(itr.hasNext()) { - FormalParameter fp = itr.next(); - if(fp.getName().equals(name)) - return true; - } - return false; - } - - @Override - public void visit(LocalVarDecl localVarDecl) { - definedLocals.add(localVarDecl.getName()); - } - - @Override - public void visit(MethodCall methodCall) { - methodCall.receiver.accept(this); - methodCall.arglist.accept(this); - } - - @Override - public void visit(NewClass methodCall) { - methodCall.receiver.accept(this); - methodCall.arglist.accept(this); - } - - @Override - public void visit(NewArray newArray) { - // TODO Auto-generated method stub - - } - - @Override - public void visit(ExpressionReceiver receiver) { - receiver.expr.accept(this); - } - - @Override - public void visit(UnaryExpr unaryExpr) { - - } - - @Override - public void visit(Return aReturn) { - aReturn.retexpr.accept(this); - } - - @Override - public void visit(ReturnVoid aReturn) { - // TODO Auto-generated method stub - - } - - @Override - public void visit(StaticClassName staticClassName) { - // TODO Auto-generated method stub - - } - - @Override - public void visit(Super aSuper) { - // TODO Auto-generated method stub - - } - - @Override - public void visit(This aThis) { - if(!thisUsed) { - thisUsed = true; - this.argumentList.add(0,aThis.getType()); - } - if(!isInstanceCapturingLambda) { - this.isInstanceCapturingLambda = true; - - } - } - - @Override - public void visit(WhileStmt whileStmt) { - whileStmt.expr.accept(this); - whileStmt.loopBlock.accept(this); - - } - - @Override - public void visit(DoStmt whileStmt) { - // TODO Auto-generated method stub - - } - - @Override - public void visit(Literal literal) { - // TODO Auto-generated method stub - - } - - @Override - public void visit(AssignToField assignLeftSide) { - // TODO Auto-generated method stub - - } - - @Override - public void visit(AssignToLocal assignLeftSide) { - // TODO Auto-generated method stub - - } - - @Override - public void visit(SuperCall superCall) { - // TODO Auto-generated method stub - - } -} diff --git a/src/main/java/de/dhbwstuttgart/bytecode/utilities/Lambda.java b/src/main/java/de/dhbwstuttgart/bytecode/utilities/Lambda.java deleted file mode 100644 index 6371c618..00000000 --- a/src/main/java/de/dhbwstuttgart/bytecode/utilities/Lambda.java +++ /dev/null @@ -1,26 +0,0 @@ -package de.dhbwstuttgart.bytecode.utilities; - -import de.dhbwstuttgart.bytecode.descriptor.DescriptorVisitor; -import de.dhbwstuttgart.syntaxtree.ParameterList; -import de.dhbwstuttgart.syntaxtree.statement.LambdaExpression; -import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric; - -public class Lambda { - private LambdaExpression lambdaExpression; - - public Lambda(LambdaExpression lambdaExpression) { - this.lambdaExpression = lambdaExpression; - } - - public ParameterList getParams() { - return lambdaExpression.params; - } - - public RefTypeOrTPHOrWildcardOrGeneric getReturnType() { - return lambdaExpression.getReturnType(); - } - - public String accept(DescriptorVisitor descVisitor) { - return descVisitor.visit(this); - } -} diff --git a/src/main/java/de/dhbwstuttgart/bytecode/utilities/MethodAndTPH.java b/src/main/java/de/dhbwstuttgart/bytecode/utilities/MethodAndTPH.java deleted file mode 100644 index caaad1be..00000000 --- a/src/main/java/de/dhbwstuttgart/bytecode/utilities/MethodAndTPH.java +++ /dev/null @@ -1,59 +0,0 @@ -package de.dhbwstuttgart.bytecode.utilities; - -import java.util.ArrayList; - -import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric; -import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder; -import de.dhbwstuttgart.typeinference.constraints.ConstraintSet; -import de.dhbwstuttgart.typeinference.constraints.Pair; -import de.dhbwstuttgart.typeinference.result.GenericInsertPair; -import de.dhbwstuttgart.typeinference.result.ResultPair; - -public class MethodAndTPH { - - private String id; - private final ArrayList tphs = new ArrayList<>(); - //private final ArrayList pairs = new ArrayList<>(); - private final ArrayList> pairs = new ArrayList<>(); - // tphs of local variables and parameters - private final ArrayList localTphs = new ArrayList<>(); - /* - * its Constraints - * eingefuegt PL 2021-02-15 - */ - public final ConstraintSet constraints; - - public MethodAndTPH(String name, ConstraintSet constraints) { - this.id = name; - this.constraints = constraints; - } - - public void addTph(String tph) { - tphs.add(tph); - } - - public ArrayList getTphs() { - return tphs; - } - -// public ArrayList getPairs(){ -// return pairs; -// } - public ArrayList> getPairs(){ - return pairs; - } - - public String getId() { - return id; - } - - public ArrayList getLocalTphs() { - return localTphs; - } - - @Override - public String toString() { - return id; - } - -} diff --git a/src/main/java/de/dhbwstuttgart/bytecode/utilities/MethodCallHelper.java b/src/main/java/de/dhbwstuttgart/bytecode/utilities/MethodCallHelper.java deleted file mode 100644 index ad3e28fa..00000000 --- a/src/main/java/de/dhbwstuttgart/bytecode/utilities/MethodCallHelper.java +++ /dev/null @@ -1,244 +0,0 @@ -/** - * - */ -package de.dhbwstuttgart.bytecode.utilities; - -import de.dhbwstuttgart.bytecode.Exception.NotInCurrentPackageException; -import de.dhbwstuttgart.bytecode.descriptor.DescriptorToString; -import de.dhbwstuttgart.bytecode.descriptor.TypeToDescriptor; -import de.dhbwstuttgart.bytecode.signature.TypeToSignature; -import de.dhbwstuttgart.syntaxtree.*; -import de.dhbwstuttgart.syntaxtree.statement.Expression; -import de.dhbwstuttgart.syntaxtree.statement.MethodCall; -import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric; -import de.dhbwstuttgart.typeinference.result.ResultSet; -import javassist.NotFoundException; -import org.objectweb.asm.MethodVisitor; -import org.objectweb.asm.Opcodes; - -import java.io.File; -import java.util.*; - -/** - * @author fayez - * - */ -public class MethodCallHelper { - private MethodCall methCall; - private SourceFile sourceFile; - private ResultSet resultSet; - private File path; - - /** - * @param methCall - * @param sourceFile - * @param resultSet - * @param path TODO - */ - public MethodCallHelper(MethodCall methCall, SourceFile sourceFile, ResultSet resultSet, File path) { - this.methCall = methCall; - this.sourceFile = sourceFile; - this.resultSet = resultSet; - this.path = path; - } - - public String getResolvedType(RefTypeOrTPHOrWildcardOrGeneric type) { - return resultSet.resolveType(type).resolvedType.acceptTV(new TypeToDescriptor()); - } - - public boolean isInCurrPkg(String className) { - for (ClassOrInterface cl : sourceFile.KlassenVektor) { - if (className.equals(cl.getClassName().toString())) - return true; - } - return false; - } - - public String getSuperClass(String className) throws NotInCurrentPackageException { - - for (ClassOrInterface cl : sourceFile.getClasses()) { - if (className.equals(cl.getClassName().toString())) { - return cl.getSuperClass().getName().toString(); - } - } - throw new NotInCurrentPackageException("Class " + className + " is not in the current package."); - } - - public ClassOrInterface getClassFromCurrPkg(String className) throws NotInCurrentPackageException { - for (ClassOrInterface cl : sourceFile.KlassenVektor) { - if (className.equals(cl.getClassName().toString())) - return cl; - } - throw new NotInCurrentPackageException("Class of " + className + " is not in the current package."); - } - - public String getDesc(String className) throws NotInCurrentPackageException, NotFoundException { - String name = methCall.name; - ClassOrInterface clazz = getClassFromCurrPkg(className); - String retType = getResolvedType(methCall.getType()); - ArrayList params = getTypes(methCall.arglist.getArguments()); - - Map genAndBoundsClass = getGenericsAndBounds(clazz.getGenerics()); - modifyGenAndBounds(genAndBoundsClass); - for (Method m : clazz.getMethods()) { - if (name.equals(m.getName()) && retType.equals(getResolvedType(m.getReturnType()))) { - ArrayList paramsOfM = getTypes(m.getParameterList()); - if(areEquals(params,paramsOfM)) { - Map genAndBoundsMethod = getGenericsAndBoundsMethod(m.getGenerics()); - modifyGenAndBounds(genAndBoundsMethod); - boolean hasGen = hasGen(m, genAndBoundsClass); - NormalMethod nm = new NormalMethod(m, (HashMap) genAndBoundsClass, - (HashMap) genAndBoundsMethod, hasGen); - return nm.accept(new DescriptorToString(resultSet)); - } - } - } - - throw new NotFoundException("Method " + name + " is not found"); - } - - private boolean areEquals(ArrayList params, ArrayList paramsOfM) { - if(params.size() != paramsOfM.size()) - return false; - - for(String t : params) { - for(String t2 : paramsOfM) { - if(!t.equals(t2)) - return false; - } - } - return true; - } - - private ArrayList getTypes(ParameterList parameterList) { - Iterator itr = parameterList.iterator(); - ArrayList typeList = new ArrayList<>(); - while (itr.hasNext()) { - FormalParameter fp = itr.next(); - String t = getResolvedType(fp.getType()); - typeList.add(t); - } - - return typeList; - } - - private ArrayList getTypes(List arguments) { - ArrayList types = new ArrayList<>(); - for(int i = 0; i genericsAndBounds) { - String retType = resultSet.resolveType(m.getReturnType()).resolvedType.acceptTV(new TypeToSignature()); - /*Prüfe, ob die Rückgabe-Type der Methode eine Type-Variable ist*/ - boolean hasGenInParameterList = genericsAndBounds.containsKey(retType) || retType.contains("TPH ") || retType.contains("<"); - - Map methodParamsAndTypes = new HashMap<>(); - Iterator itr = m.getParameterList().iterator(); - while(itr.hasNext()) { - FormalParameter fp = itr.next(); - methodParamsAndTypes.put(fp.getName(), resultSet.resolveType(fp.getType()).resolvedType); - } - /*Wenn die Rückgabe-Type eine Typ-variable ist, erzeuge direkt die Signature, wenn nicht, - * prüfe, ob einer der Parameter Typ-Variable als Typ hat*/ - if(!hasGenInParameterList) { - for(String paramName : methodParamsAndTypes.keySet()) { - String typeOfParam = methodParamsAndTypes.get(paramName).acceptTV(new TypeToDescriptor()); - String sigOfParam = methodParamsAndTypes.get(paramName).acceptTV(new TypeToSignature()); - if(genericsAndBounds.containsKey(typeOfParam)||typeOfParam.contains("TPH ")||sigOfParam.contains("<")) { - hasGenInParameterList = true; - break; - } - } - } - return m.getGenerics().iterator().hasNext() || hasGenInParameterList; - } - - private Map getGenericsAndBoundsMethod(Iterable generics) { - Map genAndBounds = new HashMap<>(); - Iterator itr = generics.iterator(); - while (itr.hasNext()) { - GenericTypeVar gtv = itr.next(); - getBoundsOfTypeVar(gtv, genAndBounds); - } - return genAndBounds; - } - - private void modifyGenAndBounds(Map genAndBoundsClass) { - List visited = new ArrayList<>(genAndBoundsClass.size()); - Map toReplace = new HashMap<>(); - for (String tv : genAndBoundsClass.keySet()) { - - if (visited.contains(tv)) - continue; - - List types = new LinkedList<>(); - String bound = genAndBoundsClass.get(tv); - types.add(tv); - visited.add(tv); - boolean doReplace = false; - while (genAndBoundsClass.keySet().contains(bound)) { - doReplace = true; - types.add(bound); - visited.add(bound); - bound = genAndBoundsClass.get(bound); - } - - if (doReplace) { - for (String tt : types) { - toReplace.put(tt, bound); - } - } - } - - for (String key : toReplace.keySet()) { - genAndBoundsClass.replace(key, toReplace.get(key)); - } - - } - - private Map getGenericsAndBounds(GenericDeclarationList generics) { - Map genAndBounds = new HashMap<>(); - Iterator itr = generics.iterator(); - while (itr.hasNext()) { - GenericTypeVar gtv = itr.next(); - getBoundsOfTypeVar(gtv, genAndBounds); - } - return genAndBounds; - } - - private void getBoundsOfTypeVar(GenericTypeVar g, Map genAndBounds) { - - Iterator bItr = g.getBounds().iterator(); - while (bItr.hasNext()) { - RefTypeOrTPHOrWildcardOrGeneric b = bItr.next(); - String boundDesc = b.acceptTV(new TypeToDescriptor()); - genAndBounds.put(g.getName(), boundDesc); - } - } - - public void generateBCForFunN(String methodDescriptor) { - ByteCodeForFunNGenerator.generateBCForFunN(methCall.arglist,methodDescriptor,path); - } - - public String getDescriptorOfApplyMethod(String methodCallType) { - return new DescriptorToString().createDescForFunN(methCall.arglist, methodCallType); - } - - /** - * @param methodCall - */ - public void createCheckCast(MethodCall methodCall, MethodVisitor mv) { - String checkCast = getResolvedType(methodCall.getType()); - if(!checkCast.contains("TPH ")) { - int pos = checkCast.length(); - if(checkCast.contains("<")) - pos = checkCast.indexOf("<"); - mv.visitTypeInsn(Opcodes.CHECKCAST,checkCast.substring(0,pos)); - } - } - -} diff --git a/src/main/java/de/dhbwstuttgart/bytecode/utilities/MethodFromMethodCall.java b/src/main/java/de/dhbwstuttgart/bytecode/utilities/MethodFromMethodCall.java deleted file mode 100644 index 28d135e6..00000000 --- a/src/main/java/de/dhbwstuttgart/bytecode/utilities/MethodFromMethodCall.java +++ /dev/null @@ -1,50 +0,0 @@ -package de.dhbwstuttgart.bytecode.utilities; - -import java.util.HashMap; - -import de.dhbwstuttgart.bytecode.descriptor.DescriptorVisitor; -import de.dhbwstuttgart.syntaxtree.statement.ArgumentList; -import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric; - -public class MethodFromMethodCall { - private ArgumentList argList; - private RefTypeOrTPHOrWildcardOrGeneric returnType; - private String receiverName; - private HashMap genericsAndBoundsMethod; - private HashMap genericsAndBounds; - - public MethodFromMethodCall(ArgumentList argList,RefTypeOrTPHOrWildcardOrGeneric returnType, - String receiverName, HashMap genericsAndBoundsMethod, - HashMap genericsAndBounds) { - this.argList = argList; - this.returnType = returnType; - this.receiverName = receiverName; - this.genericsAndBoundsMethod = genericsAndBoundsMethod; - this.genericsAndBounds = genericsAndBounds; - } - - - public ArgumentList getArgList() { - return argList; - } - - public RefTypeOrTPHOrWildcardOrGeneric getReturnType() { - return returnType; - } - - public String getReceiverName() { - return receiverName; - } - - public HashMap getGenericsAndBoundsMethod(){ - return genericsAndBoundsMethod; - } - - public HashMap getGenericsAndBounds(){ - return genericsAndBounds; - } - - public String accept(DescriptorVisitor descVisitor) { - return descVisitor.visit(this); - } -} diff --git a/src/main/java/de/dhbwstuttgart/bytecode/utilities/MethodUtility.java b/src/main/java/de/dhbwstuttgart/bytecode/utilities/MethodUtility.java deleted file mode 100644 index 6a84e97c..00000000 --- a/src/main/java/de/dhbwstuttgart/bytecode/utilities/MethodUtility.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * - */ -package de.dhbwstuttgart.bytecode.utilities; - -import java.util.Iterator; - -import de.dhbwstuttgart.syntaxtree.FormalParameter; -import de.dhbwstuttgart.syntaxtree.Method; - -/** - * @author fayez - * - */ -public class MethodUtility { - /** - * Creates an ID for a method - * - * @param resolver type Resolver - * @param method for which the ID will be generated - * @return ID for the given method. - * ID = ReturntypeMethodname(Parametertypes) - */ - public static String createID(Resolver resolver, Method method) { - String id = resolver.getResolvedType(method.getReturnType()) + method.name + "("; - Iterator itr = method.getParameterList().iterator(); - while (itr.hasNext()) { - FormalParameter fp = itr.next(); - id += resolver.getResolvedType(fp.getType()); - } - id += ")"; - return id; - } -} diff --git a/src/main/java/de/dhbwstuttgart/bytecode/utilities/NameReplacer.java b/src/main/java/de/dhbwstuttgart/bytecode/utilities/NameReplacer.java deleted file mode 100644 index 89654239..00000000 --- a/src/main/java/de/dhbwstuttgart/bytecode/utilities/NameReplacer.java +++ /dev/null @@ -1,145 +0,0 @@ -package de.dhbwstuttgart.bytecode.utilities; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.stream.Stream; - -import de.dhbwstuttgart.bytecode.constraint.TPHConstraint; -import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.NameReplacementResult; -import de.dhbwstuttgart.syntaxtree.factory.NameGenerator; - -public class NameReplacer { - //TODO rename - private List constraints; - private List allConstraints; - private List methodAndTPHs; - // TODO rename into tphClass - private List tphs; - private List localTphs; - - public NameReplacer(List constraints, List allConstraints,List tphs, ArrayList localTphs) { - super(); - this.constraints = constraints; - this.allConstraints = allConstraints; - this.tphs = tphs; - this.localTphs = localTphs; - } - - public NameReplacer(List constraints, List allConstraints,List tphs) { - super(); - this.constraints = constraints; - this.allConstraints = allConstraints; - this.tphs = tphs; - } - - public NameReplacer(List constraints, List allConstraints) { - this.constraints = constraints; - this.allConstraints = allConstraints; - } - - public NameReplacer(List constraints, List allConstraints, List methodAndTPHs, - List tphsClass) { - this.constraints = constraints; - this.allConstraints = allConstraints; - this.methodAndTPHs = methodAndTPHs; - this.tphs = tphsClass; - } - - public NameReplacementResult replaceNames() { - String newName = NameGenerator.makeNewName(); - List names = new ArrayList<>(); - substituteRightSidesWithNewName(newName, names); - - substituteNamesInAllConstraints(newName, names); - 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); - - NameReplacementResult res = new NameReplacementResult(newName, names); - - 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(); - List names = new ArrayList<>(); - substituteRightSidesWithNewName(newName, names); - - substituteNamesInAllConstraints(newName, names); - - tphs.removeAll(names); - tphs.add(newName); - - NameReplacementResult res = new NameReplacementResult(newName, names); - - return res; - } - - /** - * @param newName - * @param names - */ - public void substituteNamesInAllConstraints(String newName, List names) { - for(TPHConstraint cons : allConstraints) { - if(names.contains(cons.getLeft())) - cons.setLeft(newName); - if(names.contains(cons.getRight())) - cons.setRight(newName); - } - } - - /** - * @param newName - * @param names - */ - public void substituteRightSidesWithNewName(String newName, List names) { - for(TPHConstraint cons : constraints) { - names.add(cons.getRight()); - cons.setRight(newName); - } - } - - public Map> replaceNamesWithLocals() { - String newName = NameGenerator.makeNewName(); - ArrayList names = new ArrayList<>(); - for(TPHConstraint cons : constraints) { - names.add(cons.getRight()); - cons.setRight(newName); - } - - for(TPHConstraint cons : allConstraints) { - if(names.contains(cons.getLeft())) - cons.setLeft(newName); - if(names.contains(cons.getRight())) - cons.setRight(newName); - } - - tphs.removeAll(names); - tphs.add(newName); - localTphs.removeAll(names); - localTphs.add(newName); - - HashMap> res = new HashMap<>(); - res.put(newName, names); - return res; - } -} diff --git a/src/main/java/de/dhbwstuttgart/bytecode/utilities/NormalConstructor.java b/src/main/java/de/dhbwstuttgart/bytecode/utilities/NormalConstructor.java deleted file mode 100644 index 3a16fb00..00000000 --- a/src/main/java/de/dhbwstuttgart/bytecode/utilities/NormalConstructor.java +++ /dev/null @@ -1,40 +0,0 @@ -package de.dhbwstuttgart.bytecode.utilities; - -import java.util.HashMap; - -import de.dhbwstuttgart.bytecode.descriptor.DescriptorVisitor; -import de.dhbwstuttgart.syntaxtree.Constructor; -import de.dhbwstuttgart.syntaxtree.ParameterList; - -public class NormalConstructor { - private Constructor constructor; - private HashMap genericsAndBounds; - private boolean hasGenerics; - - public NormalConstructor(Constructor constructor, boolean hasGenerics) { - this.constructor = constructor; - this.hasGenerics = hasGenerics; - } - - public NormalConstructor(Constructor constructor, HashMap genericsAndBounds, boolean hasGenerics) { - this.constructor = constructor; - this.genericsAndBounds = genericsAndBounds; - this.hasGenerics = hasGenerics; - } - - public HashMap getGenericsAndBounds() { - return genericsAndBounds; - } - - public boolean hasGen() { - return hasGenerics; - } - - public ParameterList getParameterList() { - return constructor.getParameterList(); - } - - public String accept(DescriptorVisitor descVisitor) { - return descVisitor.visit(this); - } -} diff --git a/src/main/java/de/dhbwstuttgart/bytecode/utilities/NormalMethod.java b/src/main/java/de/dhbwstuttgart/bytecode/utilities/NormalMethod.java deleted file mode 100644 index 4e5bc887..00000000 --- a/src/main/java/de/dhbwstuttgart/bytecode/utilities/NormalMethod.java +++ /dev/null @@ -1,56 +0,0 @@ -package de.dhbwstuttgart.bytecode.utilities; - -import java.util.HashMap; - -import de.dhbwstuttgart.bytecode.descriptor.DescriptorVisitor; -import de.dhbwstuttgart.syntaxtree.Method; -import de.dhbwstuttgart.syntaxtree.ParameterList; -import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric; - -public class NormalMethod { - private Method method; - private HashMap genericsAndBounds; - private HashMap genericsAndBoundsMethod; - private boolean hasGenerics; - - public NormalMethod(Method method, boolean hasGenerics) { - this.method = method; - this.hasGenerics = hasGenerics; - } - - public NormalMethod(Method method, HashMap genericsAndBounds, - HashMap genericsAndBoundsMethod,boolean hasGenerics) { - this.method = method; - this.genericsAndBounds = genericsAndBounds; - this.genericsAndBoundsMethod = genericsAndBoundsMethod; - this.hasGenerics = hasGenerics; - } - - public Method getMethod() { - return method; - } - - public ParameterList getParameterList() { - return method.getParameterList(); - } - - public HashMap getGenericsAndBounds(){ - return genericsAndBounds; - } - - public HashMap getGenericsAndBoundsMethod(){ - return genericsAndBoundsMethod; - } - - public RefTypeOrTPHOrWildcardOrGeneric getReturnType() { - return method.getReturnType(); - } - - public boolean hasGen() { - return this.hasGenerics; - } - - public String accept(DescriptorVisitor descVisitor) { - return descVisitor.visit(this); - } -} diff --git a/src/main/java/de/dhbwstuttgart/bytecode/utilities/Resolver.java b/src/main/java/de/dhbwstuttgart/bytecode/utilities/Resolver.java deleted file mode 100644 index 684fdd4b..00000000 --- a/src/main/java/de/dhbwstuttgart/bytecode/utilities/Resolver.java +++ /dev/null @@ -1,33 +0,0 @@ -/** - * - */ -package de.dhbwstuttgart.bytecode.utilities; - -import de.dhbwstuttgart.bytecode.descriptor.TypeToDescriptor; -import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric; -import de.dhbwstuttgart.typeinference.result.ResultSet; - -/** - * @author fayez - * - */ -public class Resolver { - - private ResultSet resultSet; - - /** - * @param resultSet - */ - public Resolver(ResultSet resultSet) { - this.resultSet = resultSet; - } - - public String getResolvedType(RefTypeOrTPHOrWildcardOrGeneric type) { - return resultSet.resolveType(type).resolvedType.acceptTV(new TypeToDescriptor()); - } - - //ToDo Etienne: Check ob benötigt - public RefTypeOrTPHOrWildcardOrGeneric resolve(RefTypeOrTPHOrWildcardOrGeneric type) { - return resultSet.resolveType(type).resolvedType; - } -} diff --git a/src/main/java/de/dhbwstuttgart/bytecode/utilities/SamMethod.java b/src/main/java/de/dhbwstuttgart/bytecode/utilities/SamMethod.java deleted file mode 100644 index 1c1b883c..00000000 --- a/src/main/java/de/dhbwstuttgart/bytecode/utilities/SamMethod.java +++ /dev/null @@ -1,32 +0,0 @@ -package de.dhbwstuttgart.bytecode.utilities; - -import java.util.List; - -import de.dhbwstuttgart.bytecode.descriptor.DescriptorVisitor; -import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric; - -public class SamMethod { - private List argumentList; - private RefTypeOrTPHOrWildcardOrGeneric returnType; - - public SamMethod(List argumentList, RefTypeOrTPHOrWildcardOrGeneric returnType) { - this.argumentList = argumentList; - this.returnType = returnType; - } - - public List getArgumentList() { - return argumentList; - } - - - - public RefTypeOrTPHOrWildcardOrGeneric getReturnType() { - return returnType; - } - - - - public String accept(DescriptorVisitor descVisitor) { - return descVisitor.visit(this); - } -} diff --git a/src/main/java/de/dhbwstuttgart/core/ConsoleInterface.java b/src/main/java/de/dhbwstuttgart/core/ConsoleInterface.java index 946d7f10..b1e60070 100644 --- a/src/main/java/de/dhbwstuttgart/core/ConsoleInterface.java +++ b/src/main/java/de/dhbwstuttgart/core/ConsoleInterface.java @@ -36,7 +36,7 @@ public class ConsoleInterface { } } JavaTXCompiler compiler = new JavaTXCompiler(input, classpath); - compiler.typeInference(); + //compiler.typeInference(); compiler.generateBytecode(outputPath); } diff --git a/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java b/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java index a62eb263..0fc6e18a 100644 --- a/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java +++ b/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java @@ -2,11 +2,8 @@ package de.dhbwstuttgart.core; import com.google.common.collect.Lists; -import de.dhbwstuttgart.bytecode.BytecodeGen; -import de.dhbwstuttgart.bytecode.Exception.BytecodeGeneratorError; -import de.dhbwstuttgart.bytecode.genericsGenerator.GeneratedGenericsFinder; +import de.dhbwstuttgart.bytecode.Codegen; import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.GenericGenratorResultForSourceFile; -import de.dhbwstuttgart.bytecode.insertGenerics.FamilyOfGeneratedGenerics; import de.dhbwstuttgart.environment.CompilationEnvironment; import de.dhbwstuttgart.environment.DirectoryClassLoader; import de.dhbwstuttgart.exceptions.DebugException; @@ -21,12 +18,10 @@ import de.dhbwstuttgart.syntaxtree.GenericTypeVar; import de.dhbwstuttgart.syntaxtree.Method; import de.dhbwstuttgart.syntaxtree.ParameterList; import de.dhbwstuttgart.syntaxtree.SourceFile; -import de.dhbwstuttgart.syntaxtree.TypeScope; import de.dhbwstuttgart.syntaxtree.FormalParameter; import de.dhbwstuttgart.syntaxtree.GenericDeclarationList; import de.dhbwstuttgart.syntaxtree.factory.ASTFactory; import de.dhbwstuttgart.syntaxtree.factory.UnifyTypeFactory; -import de.dhbwstuttgart.syntaxtree.statement.Block; import de.dhbwstuttgart.syntaxtree.type.ExtendsWildcardType; import de.dhbwstuttgart.syntaxtree.type.GenericRefType; import de.dhbwstuttgart.syntaxtree.type.RefType; @@ -35,6 +30,8 @@ import de.dhbwstuttgart.syntaxtree.type.SuperWildcardType; import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder; import de.dhbwstuttgart.syntaxtree.type.TypeVisitor; import de.dhbwstuttgart.syntaxtree.visual.ASTTypePrinter; +import de.dhbwstuttgart.target.generate.ASTToTargetAST; +import de.dhbwstuttgart.target.generate.GenericsResult; import de.dhbwstuttgart.typeinference.constraints.Constraint; import de.dhbwstuttgart.typeinference.constraints.ConstraintSet; import de.dhbwstuttgart.typeinference.constraints.Pair; @@ -48,6 +45,7 @@ import de.dhbwstuttgart.typeinference.unify.model.PairOperator; import de.dhbwstuttgart.typeinference.unify.model.PlaceholderType; import de.dhbwstuttgart.typeinference.unify.model.UnifyPair; import de.dhbwstuttgart.typeinference.unify.model.UnifyType; +import de.dhbwstuttgart.util.BiRelation; import de.dhbwstuttgart.typeinference.unify.TypeUnifyTask; import de.dhbwstuttgart.typeinference.unify.UnifyResultListener; import de.dhbwstuttgart.typeinference.unify.UnifyResultListenerImpl; @@ -59,16 +57,10 @@ import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; -import java.io.OutputStreamWriter; -import java.net.URL; -import java.net.URLClassLoader; import java.util.*; import java.util.function.Function; import java.util.stream.Collectors; -import org.antlr.v4.runtime.Token; -import org.apache.commons.io.output.NullOutputStream; - public class JavaTXCompiler { @@ -78,13 +70,8 @@ public class JavaTXCompiler { 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(); - private final ClassLoader classLoader; - - //nur fuer Testzwecke of Generated Generics - //wieder loeschen PL 2021-03-22 - public FamilyOfGeneratedGenerics fogg; - - + private final DirectoryClassLoader classLoader; + public JavaTXCompiler(File sourceFile) throws IOException, ClassNotFoundException { this(Arrays.asList(sourceFile), null); } @@ -141,7 +128,8 @@ public class JavaTXCompiler { allClasses.addAll(sf.getClasses()); } allClasses.addAll(importedClasses); - return new TYPE(sourceFiles.values(), allClasses).getConstraints(); + TYPE ty = new TYPE(sourceFiles.values(), allClasses); + return ty.getConstraints(); } void addMethods(SourceFile sf, ClassOrInterface cl, List importedClasses, ClassOrInterface objectClass) { @@ -739,6 +727,7 @@ public class JavaTXCompiler { unify.unifyParallel(unifyCons.getUndConstraints(), oderConstraints, finiteClosure, logFile, log, urm, usedTasks); System.out.println("RESULT Final: " + li.getResults()); + System.out.println("Constraints for Generated Generics: " + " ???"); logFile.write("RES_FINAL: " + li.getResults().toString() + "\n"); logFile.flush(); return li.getResults(); @@ -767,6 +756,7 @@ public class JavaTXCompiler { return x; // wenn nichts veraendert wurde wird x zurueckgegeben }).collect(Collectors.toCollection(HashSet::new)); System.out.println("RESULT Final: " + results); + System.out.println("Constraints for Generated Generics: " + " ???"); logFile.write("RES_FINAL: " + results.toString() + "\n"); logFile.flush(); logFile.write("PLACEHOLDERS: " + PlaceholderType.EXISTING_PLACEHOLDERS); @@ -844,54 +834,15 @@ public class JavaTXCompiler { return ret; } - public void generateBytecodForFile(File path, HashMap classFiles, SourceFile sf, - List typeinferenceResult) throws IOException { - try { - List genericResults = getGeneratedGenericResultsForAllSourceFiles(typeinferenceResult); - BytecodeGen bytecodeGen = new BytecodeGen(classFiles,typeinferenceResult, genericResults, sf,path, classLoader); - bytecodeGen.visit(sf); - this.writeClassFile(bytecodeGen.getClassFiles(), path); - } catch (ClassNotFoundException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - public List getGeneratedGenericResultsForAllSourceFiles() - throws ClassNotFoundException, IOException { - List result = new ArrayList<>(); - for (File f : sourceFiles.keySet()) { - SourceFile sf = sourceFiles.get(f); - List typeinferenceResult = this.typeInference(); - GeneratedGenericsFinder sResFinder = new GeneratedGenericsFinder(sf, typeinferenceResult); - GenericGenratorResultForSourceFile simplifyResOfSF = sResFinder.findGeneratedGenerics(); - result.add(simplifyResOfSF); - } - return result; - } - - public List getGeneratedGenericResultsForAllSourceFiles( - List typeinferenceResult) throws ClassNotFoundException { - List result = new ArrayList<>(); - for (File f : sourceFiles.keySet()) { - SourceFile sf = sourceFiles.get(f); - GeneratedGenericsFinder sResFinder = new GeneratedGenericsFinder(sf, typeinferenceResult); - GenericGenratorResultForSourceFile simplifyResOfSF = sResFinder.findGeneratedGenerics(); - this.fogg = sResFinder.getFogg(); - result.add(simplifyResOfSF); - } - return result; - } - - public void generateBytecode() throws ClassNotFoundException, IOException, BytecodeGeneratorError { + public void generateBytecode() throws ClassNotFoundException, IOException { generateBytecode((File) null); } /** * @param path - can be null, then class file output is in the same directory as the parsed source files */ - public void generateBytecode(String path) throws ClassNotFoundException, IOException, BytecodeGeneratorError { + public void generateBytecode(String path) throws ClassNotFoundException, IOException { if(path != null) generateBytecode(new File(path)); else @@ -899,23 +850,26 @@ public class JavaTXCompiler { } /** - * @param path - can be null, then class file output is in the same directory as the parsed source files + * @param path - output-Directory can be null, then class file output is in the same directory as the parsed source files */ - public void generateBytecode(File path) throws ClassNotFoundException, IOException, BytecodeGeneratorError { + public void generateBytecode(File path) throws ClassNotFoundException, IOException { List typeinferenceResult = this.typeInference(); - List simplifyResultsForAllSourceFiles = getGeneratedGenericResultsForAllSourceFiles( - typeinferenceResult); - generateBytecode(path, typeinferenceResult, simplifyResultsForAllSourceFiles); + generateBytecode(path, typeinferenceResult); + } + + private Map> generatedGenerics = new HashMap<>(); + + // TODO This is a temporary solution, we should integrate with the old API for getting Generics + public Map> getGeneratedGenerics() { + return generatedGenerics; } /** * @param outputPath - can be null, then class file output is in the same directory as the parsed source files * @param typeinferenceResult - * @param simplifyResultsForAllSourceFiles * @throws IOException */ - public void generateBytecode(File outputPath, List typeinferenceResult, - List simplifyResultsForAllSourceFiles) throws IOException { + public void generateBytecode(File outputPath, List typeinferenceResult) throws IOException { for (File f : sourceFiles.keySet()) { HashMap classFiles = new HashMap<>(); SourceFile sf = sourceFiles.get(f); @@ -925,10 +879,19 @@ public class JavaTXCompiler { }else{ path = new File(outputPath ,sf.getPkgName().replace(".","/")); //add package path to root path } - BytecodeGen bytecodeGen = new BytecodeGen(classFiles, typeinferenceResult, simplifyResultsForAllSourceFiles, - sf, path, classLoader); - bytecodeGen.visit(sf); - writeClassFile(bytecodeGen.getClassFiles(), path); + + var converter = new ASTToTargetAST(typeinferenceResult); + var generatedClasses = new HashMap(); + for (var clazz : sf.getClasses()) { + var codegen = new Codegen(converter.convert(clazz)); + var code = codegen.generate(); + generatedClasses.put(clazz.getClassName(), code); + converter.auxiliaries.forEach((name, source) -> { + generatedClasses.put(new JavaClassName(name), source); + }); + } + generatedGenerics.put(f, converter.computedGenerics()); + writeClassFile(generatedClasses, path); } } @@ -947,8 +910,13 @@ public class JavaTXCompiler { System.out.println(name + ".class file generated"); } } - - /* PL 2020-03-17 mit TypeExchanger in FCGenerator.java zusammenfuehren */ + + public List getGeneratedGenericResultsForAllSourceFiles(List results) { + // FIXME + return null; + } + + /* PL 2020-03-17 mit TypeExchanger in FCGenerator.java zusammenfuehren */ /** * Tauscht die GTVs in einem Typ gegen die entsprechenden Typen in der übergebenen Map aus. */ diff --git a/src/main/java/de/dhbwstuttgart/environment/ByteArrayClassLoader.java b/src/main/java/de/dhbwstuttgart/environment/ByteArrayClassLoader.java new file mode 100644 index 00000000..8e060e83 --- /dev/null +++ b/src/main/java/de/dhbwstuttgart/environment/ByteArrayClassLoader.java @@ -0,0 +1,8 @@ +package de.dhbwstuttgart.environment; + +public class ByteArrayClassLoader extends ClassLoader implements IByteArrayClassLoader { + @Override + public Class _defineClass(String name, byte[] code, int i, int length) throws ClassFormatError { + return defineClass(name, code, i, length); + } +} diff --git a/src/main/java/de/dhbwstuttgart/environment/DirectoryClassLoader.java b/src/main/java/de/dhbwstuttgart/environment/DirectoryClassLoader.java index a74dbc49..4cfaf434 100644 --- a/src/main/java/de/dhbwstuttgart/environment/DirectoryClassLoader.java +++ b/src/main/java/de/dhbwstuttgart/environment/DirectoryClassLoader.java @@ -1,13 +1,16 @@ package de.dhbwstuttgart.environment; import java.io.File; +import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; +import java.nio.file.Files; +import java.nio.file.Path; import java.util.List; import java.util.stream.Collectors; -public class DirectoryClassLoader extends URLClassLoader { +public class DirectoryClassLoader extends URLClassLoader implements IByteArrayClassLoader { public DirectoryClassLoader(File directory, java.lang.ClassLoader parent) { super(generateURLArray(dirToURL(directory)), parent); } @@ -28,4 +31,9 @@ public class DirectoryClassLoader extends URLClassLoader { throw new RuntimeException(e); } } + + @Override + public Class _defineClass(String name, byte[] code, int i, int length) throws ClassFormatError { + return defineClass(name, code, i, length); + } } diff --git a/src/main/java/de/dhbwstuttgart/environment/IByteArrayClassLoader.java b/src/main/java/de/dhbwstuttgart/environment/IByteArrayClassLoader.java new file mode 100644 index 00000000..032bc401 --- /dev/null +++ b/src/main/java/de/dhbwstuttgart/environment/IByteArrayClassLoader.java @@ -0,0 +1,21 @@ +package de.dhbwstuttgart.environment; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; + +public interface IByteArrayClassLoader { + + Class loadClass(String path) throws ClassNotFoundException; + + default Class loadClass(byte[] code) { + return this._defineClass(null, code, 0, code.length); + } + + default Class loadClass(Path path) throws IOException { + var code = Files.readAllBytes(path); + return this._defineClass(null, code, 0, code.length); + } + + Class _defineClass(String name, byte[] code, int i, int length) throws ClassFormatError; +} diff --git a/src/main/java/de/dhbwstuttgart/parser/SyntaxTreeGenerator/StatementGenerator.java b/src/main/java/de/dhbwstuttgart/parser/SyntaxTreeGenerator/StatementGenerator.java index bcc4f841..fd750afd 100644 --- a/src/main/java/de/dhbwstuttgart/parser/SyntaxTreeGenerator/StatementGenerator.java +++ b/src/main/java/de/dhbwstuttgart/parser/SyntaxTreeGenerator/StatementGenerator.java @@ -210,12 +210,13 @@ public class StatementGenerator { }else throw new NotImplementedException(); ArgumentList argumentList = convert(methodInvocationContext.argumentList()); - ArrayList argTypes = argumentList.getArguments().stream() + ArrayList signature = argumentList.getArguments().stream() .map(x -> TypePlaceholder.fresh(methodInvocationContext.getStart())) .collect(Collectors.toCollection(ArrayList::new)); + signature.add(TypePlaceholder.fresh(methodInvocationContext.getStart())); //ReturnType MethodCall ret = new MethodCall(TypePlaceholder.fresh(methodInvocationContext.getStart()), getReceiver(receiver), name, argumentList, TypePlaceholder.fresh(methodInvocationContext.getStart()), - argTypes, methodInvocationContext.getStart()); + signature, methodInvocationContext.getStart()); ret.setStatement(); return ret; } @@ -302,10 +303,11 @@ public class StatementGenerator { RefType newClass = (RefType) TypeGenerator.convertTypeName(identifier.getText(),genericArgs,identifier.getSymbol(),reg,generics); ArgumentList args = convert(newExpression.argumentList()); - ArrayList argTypes = args.getArguments().stream() + ArrayList signature = args.getArguments().stream() .map(x -> TypePlaceholder.fresh(newExpression.getStart())) .collect(Collectors.toCollection(ArrayList::new)); - Statement ret = new NewClass(newClass, args, null, argTypes, newExpression.getStart()); + signature.add(TypePlaceholder.fresh(newExpression.getStart())); //ReturnType + Statement ret = new NewClass(newClass, args, null, signature, newExpression.getStart()); ret.setStatement(); return ret; } @@ -803,11 +805,12 @@ public class StatementGenerator { }else { Java8Parser.MethodInvocation_lf_primaryContext ctxt = e.methodInvocation_lf_primary(); String methodName = ctxt.Identifier().toString(); - ArrayList argTypes = ctxt.argumentList().expression().stream() + ArrayList signature = ctxt.argumentList().expression().stream() .map(x -> TypePlaceholder.fresh(e.getStart())) .collect(Collectors.toCollection(ArrayList::new)); + signature.add(TypePlaceholder.fresh(e.getStart())); //ReturnType return new MethodCall(TypePlaceholder.fresh(e.getStart()), getReceiver(expr), methodName, - convert(ctxt.argumentList()), TypePlaceholder.fresh(e.getStart()), argTypes, e.getStart()); + convert(ctxt.argumentList()), TypePlaceholder.fresh(e.getStart()), signature, e.getStart()); } } @@ -861,10 +864,11 @@ public class StatementGenerator { RefType newClass = (RefType) TypeGenerator.convertTypeName(identifier.getText(),genericArgs,identifier.getSymbol(),reg,generics); ArgumentList args = convert(newExpression.argumentList()); - ArrayList argTypes = args.getArguments().stream() + ArrayList signature = args.getArguments().stream() .map(x -> TypePlaceholder.fresh(newExpression.getStart())) .collect(Collectors.toCollection(ArrayList::new)); - return new NewClass(newClass, args, null, argTypes, newExpression.getStart()); + signature.add(TypePlaceholder.fresh(newExpression.getStart())); //ReturnType + return new NewClass(newClass, args, null, signature, newExpression.getStart()); } private Expression convert(Java8Parser.LiteralContext literal) { @@ -922,12 +926,13 @@ public class StatementGenerator { } ArgumentList argumentList = convert(methodInvocationContext.argumentList()); - ArrayList argTypes = argumentList.getArguments().stream() + ArrayList signature = argumentList.getArguments().stream() .map(x -> TypePlaceholder.fresh(methodInvocationContext.getStart())) .collect(Collectors.toCollection(ArrayList::new)); + signature.add(TypePlaceholder.fresh(methodInvocationContext.getStart())); //ReturnType MethodCall ret = new MethodCall(TypePlaceholder.fresh(methodInvocationContext.getStart()), getReceiver(receiver), name, argumentList, TypePlaceholder.fresh(methodInvocationContext.getStart()), - argTypes, methodInvocationContext.getStart()); + signature, methodInvocationContext.getStart()); return ret; } diff --git a/src/main/java/de/dhbwstuttgart/parser/SyntaxTreeGenerator/TypeGenerator.java b/src/main/java/de/dhbwstuttgart/parser/SyntaxTreeGenerator/TypeGenerator.java index d55e9349..0bf04247 100644 --- a/src/main/java/de/dhbwstuttgart/parser/SyntaxTreeGenerator/TypeGenerator.java +++ b/src/main/java/de/dhbwstuttgart/parser/SyntaxTreeGenerator/TypeGenerator.java @@ -2,6 +2,7 @@ package de.dhbwstuttgart.parser.SyntaxTreeGenerator; import de.dhbwstuttgart.exceptions.NotImplementedException; import de.dhbwstuttgart.exceptions.TypeinferenceException; +import de.dhbwstuttgart.parser.NullToken; import de.dhbwstuttgart.parser.antlr.Java8Parser; import de.dhbwstuttgart.parser.antlr.Java8Parser.UnannClassType_lfno_unannClassOrInterfaceTypeContext; import de.dhbwstuttgart.parser.scope.GenericsRegistry; @@ -169,7 +170,7 @@ public class TypeGenerator { return new SuperWildcardType(convert(wildcardContext.wildcardBounds().referenceType(), reg, generics), wildcardContext.getStart()); } }else{ - throw new NotImplementedException(); //Wildcard ohne Bound + return new ExtendsWildcardType(new RefType(new JavaClassName("Object"), new NullToken()), wildcardContext.getStart()); } } diff --git a/src/main/java/de/dhbwstuttgart/syntaxtree/factory/UnifyTypeFactory.java b/src/main/java/de/dhbwstuttgart/syntaxtree/factory/UnifyTypeFactory.java index 468f9647..0f1017ed 100644 --- a/src/main/java/de/dhbwstuttgart/syntaxtree/factory/UnifyTypeFactory.java +++ b/src/main/java/de/dhbwstuttgart/syntaxtree/factory/UnifyTypeFactory.java @@ -152,12 +152,12 @@ public class UnifyTypeFactory { } //NEVER USED - public static Constraint convert(Constraint constraint){ - Constraint unifyPairConstraint = constraint.stream() - .map(UnifyTypeFactory::convert) - .collect(Collectors.toCollection( () -> new Constraint (constraint.isInherited(), convert(constraint.getExtendConstraint())))); - return unifyPairConstraint; - } + //public static Constraint convert(Constraint constraint){ + // Constraint unifyPairConstraint = constraint.stream() + // .map(UnifyTypeFactory::convert) + // .collect(Collectors.toCollection( () -> new Constraint (constraint.isInherited(), convert(constraint.getExtendConstraint())))); + // return unifyPairConstraint; + //} public static UnifyPair convert(Pair p) { UnifyPair ret = null; diff --git a/src/main/java/de/dhbwstuttgart/syntaxtree/statement/MethodCall.java b/src/main/java/de/dhbwstuttgart/syntaxtree/statement/MethodCall.java index 4ef09d86..a7aea577 100644 --- a/src/main/java/de/dhbwstuttgart/syntaxtree/statement/MethodCall.java +++ b/src/main/java/de/dhbwstuttgart/syntaxtree/statement/MethodCall.java @@ -25,16 +25,18 @@ public class MethodCall extends Statement public final ArgumentList arglist; public RefTypeOrTPHOrWildcardOrGeneric receiverType; - public final ArrayList argTypes; + + //sind Tphs, repraesentieren im Resultset die Signatur der aufgerufenen Methoden, letztes Element ist der Returntyp + public final ArrayList signature; public MethodCall(RefTypeOrTPHOrWildcardOrGeneric retType, Receiver receiver, String methodName, ArgumentList argumentList, - RefTypeOrTPHOrWildcardOrGeneric receiverType, ArrayList argTypes, Token offset){ + RefTypeOrTPHOrWildcardOrGeneric receiverType, ArrayList signature, Token offset){ super(retType,offset); this.arglist = argumentList; this.name = methodName; this.receiver = receiver; this.receiverType = receiverType; - this.argTypes = argTypes; + this.signature = signature; } diff --git a/src/main/java/de/dhbwstuttgart/syntaxtree/type/TypePlaceholder.java b/src/main/java/de/dhbwstuttgart/syntaxtree/type/TypePlaceholder.java index 38932247..2aaa8068 100644 --- a/src/main/java/de/dhbwstuttgart/syntaxtree/type/TypePlaceholder.java +++ b/src/main/java/de/dhbwstuttgart/syntaxtree/type/TypePlaceholder.java @@ -1,6 +1,7 @@ package de.dhbwstuttgart.syntaxtree.type; import java.util.Hashtable; +import de.dhbwstuttgart.parser.NullToken; import de.dhbwstuttgart.syntaxtree.ASTVisitor; import de.dhbwstuttgart.syntaxtree.SyntaxTreeNode; import de.dhbwstuttgart.syntaxtree.factory.NameGenerator; @@ -47,6 +48,10 @@ public class TypePlaceholder extends RefTypeOrTPHOrWildcardOrGeneric return new TypePlaceholder(NameGenerator.makeNewName(), position); } + public static RefTypeOrTPHOrWildcardOrGeneric of(String name) { + return new TypePlaceholder(name, new NullToken()); + } + /** * Author: J�rg B�uerle
diff --git a/src/main/java/de/dhbwstuttgart/syntaxtree/visual/OutputGenerator.java b/src/main/java/de/dhbwstuttgart/syntaxtree/visual/OutputGenerator.java index 9a3228fe..b25aa30b 100644 --- a/src/main/java/de/dhbwstuttgart/syntaxtree/visual/OutputGenerator.java +++ b/src/main/java/de/dhbwstuttgart/syntaxtree/visual/OutputGenerator.java @@ -271,6 +271,7 @@ public class OutputGenerator implements ASTVisitor{ public void visit(MethodCall methodCall) { methodCall.receiver.accept(this); out.append("."+methodCall.name); + out.append(" Signature: "+methodCall.signature); methodCall.getArgumentList().accept(this); } diff --git a/src/main/java/de/dhbwstuttgart/target/ByteArrayClassLoader.java b/src/main/java/de/dhbwstuttgart/target/ByteArrayClassLoader.java deleted file mode 100644 index 428e214d..00000000 --- a/src/main/java/de/dhbwstuttgart/target/ByteArrayClassLoader.java +++ /dev/null @@ -1,16 +0,0 @@ -package de.dhbwstuttgart.target; - -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; - -public class ByteArrayClassLoader extends ClassLoader { - public Class loadClass(byte[] code) { - return this.defineClass(null, code, 0, code.length); - } - - public Class loadClass(Path path) throws IOException { - var code = Files.readAllBytes(path); - return this.defineClass(null, code, 0, code.length); - } -} diff --git a/src/main/java/de/dhbwstuttgart/target/generate/ASTToTargetAST.java b/src/main/java/de/dhbwstuttgart/target/generate/ASTToTargetAST.java index 61be1e8c..86c94f7e 100644 --- a/src/main/java/de/dhbwstuttgart/target/generate/ASTToTargetAST.java +++ b/src/main/java/de/dhbwstuttgart/target/generate/ASTToTargetAST.java @@ -1,111 +1,88 @@ package de.dhbwstuttgart.target.generate; -import com.google.j2objc.annotations.LoopTranslation; -import de.dhbwstuttgart.bytecode.funN.FunNGenerator; -import de.dhbwstuttgart.core.JavaTXCompiler; +import de.dhbwstuttgart.bytecode.FunNGenerator; +import de.dhbwstuttgart.environment.ByteArrayClassLoader; +import de.dhbwstuttgart.environment.IByteArrayClassLoader; import de.dhbwstuttgart.parser.NullToken; +import de.dhbwstuttgart.parser.SyntaxTreeGenerator.AssignToLocal; import de.dhbwstuttgart.syntaxtree.*; import de.dhbwstuttgart.syntaxtree.factory.ASTFactory; import de.dhbwstuttgart.syntaxtree.statement.*; import de.dhbwstuttgart.syntaxtree.type.*; +import de.dhbwstuttgart.syntaxtree.type.Void; import de.dhbwstuttgart.target.tree.*; import de.dhbwstuttgart.target.tree.expression.TargetBlock; import de.dhbwstuttgart.target.tree.expression.TargetExpression; import de.dhbwstuttgart.target.tree.type.*; +import de.dhbwstuttgart.typeinference.constraints.Pair; import de.dhbwstuttgart.typeinference.result.*; -import de.dhbwstuttgart.target.ByteArrayClassLoader; import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; +/** + * @author dholle + */ public class ASTToTargetAST { - static RefType OBJECT = ASTFactory.createObjectType(); // TODO It would be better if I could call this directly but the hashcode seems to change + public static RefType OBJECT = ASTFactory.createObjectType(); // TODO It would be better if I could call this directly but the hashcode seems to change protected List all; protected Sigma sigma; - protected ClassOrInterface currentClass; // TODO This is only needed because of SuperCall, maybe there's a better way? + protected ClassOrInterface currentClass; // TODO This is only needed because of SuperCall, maybe there's - private class Sigma { - Map>> computedGenericsOfMethods = new HashMap<>(); + public List computedGenerics() { + return all.stream().map(GenericsResult::new).toList(); + } + + record Generics(Set> javaGenerics, Set> txGenerics) {} + + class Sigma { + Map computedGenericsOfMethods = new HashMap<>(); + Map computedGenericsOfClasses = new HashMap<>(); Map> usedTPHsOfMethods = new HashMap<>(); - Map>> computedGenericsOfClasses = new HashMap<>(); Set simplifiedConstraints = new HashSet<>(); Map concreteTypes = new HashMap<>(); Map equality = new HashMap<>(); + Map txEquality = new HashMap<>(); Sigma(ResultSet constraints) { ASTToTargetAST.this.sigma = this; - Set> equalitySet = new HashSet<>(); - Map> unified = new HashMap<>(); - - for (var constraint : constraints.results) { - if (constraint instanceof PairTPHEqualTPH p) { - if (unified.containsKey(p.getLeft())) { - var equals = unified.get(p.getLeft()); - equals.add(p.getRight()); - unified.put(p.getLeft(), equals); - } else if (unified.containsKey(p.getRight())) { - var equals = unified.get(p.getRight()); - equals.add(p.getLeft()); - unified.put(p.getRight(), equals); - } else { - List equals = new ArrayList<>(); - equals.add(p.getLeft()); - equals.add(p.getRight()); - unified.put(p.getLeft(), equals); - unified.put(p.getRight(), equals); - equalitySet.add(equals); - } - } - } - for (var constraint : constraints.results) { if (constraint instanceof PairTPHsmallerTPH p) { - var left = p.left; - var right = p.right; - if (unified.containsKey(left)) - left = unified.get(left).get(0); - if (unified.containsKey(right)) - right = unified.get(right).get(0); - - simplifiedConstraints.add(new PairTPHsmallerTPH(left, right)); - } - } - System.out.println("Simplified constraints: " + simplifiedConstraints); - - for (var equality : equalitySet) { - var first = equality.get(0); - for (var i = 1; i < equality.size(); i++) - this.equality.put(equality.get(i), first); - } - - for (var constraint : constraints.results) { - if (constraint instanceof PairTPHequalRefTypeOrWildcardType p) { + simplifiedConstraints.add(p); + } else if (constraint instanceof PairTPHEqualTPH p) { + equality.put(p.getLeft(), p.getRight()); + txEquality.put(p.getLeft(), p.getRight()); + } else if (constraint instanceof PairTPHequalRefTypeOrWildcardType p) { concreteTypes.put(this.equality.getOrDefault(p.left, p.left), p.right); } } + + System.out.println("Simplified constraints: " + simplifiedConstraints); } - void findTypeVariables(RefTypeOrTPHOrWildcardOrGeneric type, Set typeVariables) { + Set findTypeVariables(RefTypeOrTPHOrWildcardOrGeneric type, Map equality) { + var result = new HashSet(); if (type instanceof TypePlaceholder tph) { tph = equality.getOrDefault(tph, tph); if (concreteTypes.containsKey(tph)) { - findTypeVariables(concreteTypes.get(tph), typeVariables); - return; + result.addAll(findTypeVariables(concreteTypes.get(tph), equality)); + return result; } - typeVariables.add(tph); + result.add(tph); } else if (type instanceof RefType refType) { for (var t : refType.getParaList()) - findTypeVariables(t, typeVariables); + result.addAll(findTypeVariables(t, equality)); + } else if (type instanceof ExtendsWildcardType wildcardType) { + result.addAll(findTypeVariables(wildcardType.getInnerType(), equality)); + } else if (type instanceof SuperWildcardType wildcardType) { + result.addAll(findTypeVariables(wildcardType.getInnerType(), equality)); } - } - - boolean hasBound(TypePlaceholder name, Set> generics) { - return generics.stream().anyMatch(generic -> generic.getLeft().equals(name)); + return result; } boolean containsRelation(Set> result, PairTPHsmallerTPH pair) { @@ -127,98 +104,112 @@ public class ASTToTargetAST { return containsLeft && containsRight; } - // Family of generated Generics - Set> generics(ClassOrInterface owner, Method method) { - if (computedGenericsOfMethods.containsKey(method)) - return computedGenericsOfMethods.get(method); - - Set> result = new HashSet<>(); - computedGenericsOfMethods.put(method, result); - - var genericsOfClass = generics(owner); - var simplifiedConstraints = new HashSet<>(this.simplifiedConstraints); - - HashSet typeVariables = new HashSet<>(); - HashSet typeVariablesOfFields = new HashSet<>(); - HashSet allTypeVariables = new HashSet<>(); - - for (var field : owner.getFieldDecl()) { - findTypeVariables(field.getType(), typeVariablesOfFields); + static void addToPairs(Set> input, ResultPair pair) { + if (pair instanceof PairTPHsmallerTPH) { + input.removeIf(pair2 -> { + if (pair2 instanceof PairTPHequalRefTypeOrWildcardType) { + return pair2.getLeft().equals(pair.getLeft()) && pair2.getRight().equals(OBJECT); + } + return false; + }); } - //findTypeVariables(method.getReturnType(), typeVariables); - for (var arg : method.getParameterList().getFormalparalist()) { - findTypeVariables(arg.getType(), typeVariables); - } + input.add(pair); + } - method.block.accept(new TracingStatementVisitor() { - @Override - public void visit(LocalVarDecl localVarDecl) { - findTypeVariables(localVarDecl.getType(), typeVariables); + static Set> transitiveClosure(Set> generics) { + Set> all = new HashSet<>(generics); + HashSet> toAdd = new HashSet<>(); + int sizeBefore; + do { + sizeBefore = all.size(); + toAdd.clear(); + for (var g1 : all) { + for (var g2 : all) { + if (g1 instanceof PairTPHsmallerTPH pair) { + if (g2.getLeft().equals(pair.getRight()) && g2.getRight() instanceof TypePlaceholder right) + toAdd.add(new PairTPHsmallerTPH(pair.left, right)); + } + } } + all.addAll(toAdd); + } while (sizeBefore < all.size()); + return all; + } - @Override - public void visit(MethodCall methodCall) { - super.visit(methodCall); - findTypeVariables(methodCall.getType(), typeVariables); - } - - @Override - public void visit(Assign assign) {} - }); - + private void methodFindConstraints( + ClassOrInterface owner, Method method, + Set simplifiedConstraints, + HashSet typeVariables, + HashSet typeVariablesOfClass, + Set> result, + Map equality + ) { // Type variables with bounds that are also type variables of the method for (var typeVariable : new HashSet<>(typeVariables)) { + if (typeVariablesOfClass.contains(typeVariable)) continue; for (var pair : simplifiedConstraints) { if (pair.left.equals(typeVariable) && typeVariables.contains(pair.right)) { - result.add(new PairTPHsmallerTPH(pair.left, equality.getOrDefault(pair.right, pair.right))); + addToPairs(result, new PairTPHsmallerTPH(pair.left, equality.getOrDefault(pair.right, pair.right))); typeVariables.add(pair.right); } } } - var visitedMethods = new HashSet(); method.block.accept(new TracingStatementVisitor() { + + private RefTypeOrTPHOrWildcardOrGeneric superType = new Void(new NullToken()); + @Override public void visit(MethodCall methodCall) { - super.visit(methodCall); + //Anfang es werden Paare von TPHs gespeichert, die bei den Generated Generics ueber die Methodengrenzen hinweg + //betrachtet werden muessen + //Definition 7.2 (Family of generated generics). T1 <. R1 <.^∗ R2 <. T2 + Set T1s = + methodCall.getArgumentList() + .getArguments() + .stream() + .map(TypableStatement::getType) + .collect(Collectors.toCollection(HashSet::new)) + .stream().filter(x -> x instanceof TypePlaceholder) + .map(tph -> equality.getOrDefault(tph, (TypePlaceholder) tph)) + .collect(Collectors.toCollection(HashSet::new)); + RefTypeOrTPHOrWildcardOrGeneric T2 = superType; + if (T2 instanceof TypePlaceholder tph) T2 = equality.getOrDefault(tph, tph); + + System.out.println("T1s: " + T1s + "\nT2: " + T2); + //Ende + + superType = methodCall.receiverType; + methodCall.receiver.accept(this); + for(int i = 0;i> all = new HashSet<>(generics); + var generics = generics(owner, method).javaGenerics(); - // Reflexive and Transitive closure - HashSet> toAdd = new HashSet<>(); - int sizeBefore; - do { - sizeBefore = all.size(); - toAdd.clear(); - for (var g1 : all) { - for (var g2 : all) { - if (g1 instanceof PairTPHsmallerTPH pair) { - if (g2.getLeft().equals(pair.getLeft()) && generics.stream().anyMatch(generic -> generic.getLeft().equals(pair.getRight()))) - toAdd.add(new PairTPHsmallerTPH((TypePlaceholder) g1.getLeft(), (TypePlaceholder) g2.getRight())); - } - } - } - all.addAll(toAdd); - } while (sizeBefore < all.size()); + // transitive and + var all = transitiveClosure(generics); + // reflexive + var toAdd = new HashSet>(); for (var generic : all) { toAdd.add(new PairTPHsmallerTPH((TypePlaceholder) generic.getLeft(), (TypePlaceholder) generic.getLeft())); } all.addAll(toAdd); HashSet newPairs = new HashSet<>(); + // Loop from hell outer: for (var tph : typeVariables) { + if (typeVariablesOfClass.contains(tph)) continue; for (var generic : all) { if (!(generic.getRight() instanceof TypePlaceholder type)) continue; @@ -232,12 +223,13 @@ public class ASTToTargetAST { if (!(pair2.right.equals(tph2) && pair2.left.equals(type))) continue; if (tph.equals(tph2)) continue; + if (!T1s.contains(tph) || !tph2.equals(T2)) continue; var newPair = new PairTPHsmallerTPH(tph, tph2); newPairs.add(newPair); if (!containsRelation(result, newPair)) - result.add(newPair); + addToPairs(result, newPair); continue outer; } } @@ -248,27 +240,221 @@ public class ASTToTargetAST { } } } - }); - // Type variables with bounds that are also type variables of fields - for (var typeVariable : new HashSet<>(typeVariables)) { - for (var pair : simplifiedConstraints) { - if (pair.left.equals(typeVariable) && typeVariablesOfFields.contains(pair.right)) { - result.add(new PairTPHsmallerTPH(pair.left, equality.getOrDefault(pair.right, pair.right))); - typeVariables.add(pair.right); + + @Override + public void visit(LambdaExpression lambdaExpression) { + superType = new Void(new NullToken()); + lambdaExpression.methodBody.accept(this); + } + + @Override + public void visit(Assign assign) { + superType = assign.lefSide.getType(); + assign.rightSide.accept(this); + } + + @Override + public void visit(BinaryExpr binary) { + superType = new Void(new NullToken()); + binary.lexpr.accept(this); + superType = new Void(new NullToken()); + binary.rexpr.accept(this); + } + + @Override + public void visit(Block block) { + for (var expr : block.statements) { + superType = new Void(new NullToken()); + expr.accept(this); } } + + @Override + public void visit(CastExpr castExpr) { + + } + + @Override + public void visit(EmptyStmt emptyStmt) { + + } + + @Override + public void visit(FieldVar fieldVar) { + + } + + @Override + public void visit(ForStmt forStmt) { + forStmt.body_Loop_block.accept(this); + } + + @Override + public void visit(IfStmt ifStmt) { + superType = new Void(new NullToken()); + ifStmt.expr.accept(this); + superType = new Void(new NullToken()); + ifStmt.then_block.accept(this); + superType = new Void(new NullToken()); + ifStmt.else_block.accept(this); + } + + @Override + public void visit(InstanceOf instanceOf) { + + } + + @Override + public void visit(LocalVar localVar) { + + } + + @Override + public void visit(LocalVarDecl localVarDecl) { + + } + + @Override + public void visit(NewClass newClass) { + this.visit((MethodCall) newClass); + } + + @Override + public void visit(NewArray newArray) { + newArray.expr.forEach(expr -> expr.accept(this)); + } + + @Override + public void visit(Return aReturn) { + superType = aReturn.getType(); + aReturn.retexpr.accept(this); + } + + @Override + public void visit(ReturnVoid aReturn) { + + } + + @Override + public void visit(StaticClassName staticClassName) { + + } + + @Override + public void visit(Super aSuper) { + + } + + @Override + public void visit(This aThis) { + + } + + @Override + public void visit(WhileStmt whileStmt) { + superType = new Void(new NullToken()); + whileStmt.expr.accept(this); + superType = new Void(new NullToken()); + whileStmt.loopBlock.accept(this); + } + + @Override + public void visit(DoStmt whileStmt) { + whileStmt.loopBlock.accept(this); + } + + @Override + public void visit(AssignToField assignLeftSide) { + + } + + @Override + public void visit(AssignToLocal assignLeftSide) { + + } + + @Override + public void visit(SuperCall superCall) { + + } + + @Override + public void visit(ExpressionReceiver expressionReceiver) { + expressionReceiver.expr.accept(this); + } + + @Override + public void visit(UnaryExpr unaryExpr) { + unaryExpr.expr.accept(this); + } + + @Override + public void visit(Literal literal) { + + } + @Override + public void visit(ArgumentList arglist) { + for(int i = 0;i(typeVariables)) { + if (typeVariablesOfClass.contains(typeVariable)) continue; + + var pairs = new HashSet(); + for (var pair : closure) { + if (!(pair instanceof PairTPHsmallerTPH ptph)) continue; + if (ptph.left.equals(typeVariable) && typeVariablesOfClass.contains(ptph.right)) { + pairs.add(new PairTPHsmallerTPH(ptph.left, equality.getOrDefault(ptph.right, ptph.right))); + } + } + + // Find the closest pair with the minimum amount of steps + PairTPHsmallerTPH minimalPair = null; + var minSteps = Integer.MAX_VALUE; + for (var pair : pairs) { + var left = pair.left; + var visited = new HashSet(); + var steps = 0; + while (!left.equals(pair.right)) { + visited.add(left); + var found = false; + for (var pair2 : simplifiedConstraints) { + if (left.equals(pair2.left) && !visited.contains(pair2.right)) { + left = pair2.right; + steps += 1; + found = true; + break; + } + } + if (!found) break; + } + if (steps < minSteps) { + minSteps = steps; + minimalPair = pair; + } + } + + if (minimalPair != null) + addToPairs(result, minimalPair); } - // All unbounded type variables + + // All unbounded type variables (bounds not in method) outer: for (var typeVariable : typeVariables) { - for (var pair : simplifiedConstraints) { - if (pair.left.equals(typeVariable) && typeVariables.contains(pair.right)) + if (typeVariablesOfClass.contains(typeVariable)) continue; + for (var pair : result) { + if (pair.getLeft().equals(typeVariable)) continue outer; } - if (!hasBound(typeVariable, genericsOfClass)) - result.add(new PairTPHequalRefTypeOrWildcardType(typeVariable, OBJECT)); + addToPairs(result, new PairTPHequalRefTypeOrWildcardType(typeVariable, OBJECT)); } // All unbounded bounds @@ -278,31 +464,117 @@ public class ASTToTargetAST { if (pair.right.equals(pair2.left)) continue outer; } - if (!hasBound(pair.right, genericsOfClass) && typeVariables.contains(pair.right)) - result.add(new PairTPHequalRefTypeOrWildcardType(pair.right, OBJECT)); + if (!typeVariablesOfClass.contains(pair.right) && typeVariables.contains(pair.right)) { + addToPairs(result, new PairTPHequalRefTypeOrWildcardType(pair.right, OBJECT)); + } } - - eliminateCyclesAndInfima(result); - System.out.println(method.name + ": " + result); - - Set allUsedTPHs = new HashSet<>(); - allUsedTPHs.addAll(typeVariables); - allUsedTPHs.addAll(typeVariablesOfFields); - usedTPHsOfMethods.put(method, allUsedTPHs); - - return result; } - void findAllBounds(RefTypeOrTPHOrWildcardOrGeneric type, Set> generics) { + private void methodFindTypeVariables( + Method method, + Set> genericsOfClass, + Set typeVariablesOfClass, + Set typeVariables, + Map equality + ) { + + for (var pair : genericsOfClass) { + typeVariablesOfClass.add((TypePlaceholder) pair.getLeft()); + } + + typeVariables.addAll(findTypeVariables(method.getReturnType(), equality)); + for (var arg : method.getParameterList().getFormalparalist()) { + typeVariables.addAll(findTypeVariables(arg.getType(), equality)); + } + + method.block.accept(new TracingStatementVisitor() { + @Override + public void visit(LocalVarDecl localVarDecl) { + typeVariables.addAll(findTypeVariables(localVarDecl.getType(), equality)); + } + + @Override + public void visit(MethodCall methodCall) { + super.visit(methodCall); + typeVariables.addAll(findTypeVariables(methodCall.getType(), equality)); + } + + @Override + public void visit(Assign assign) {} + }); + } + + // Family of generated Generics + Generics generics(ClassOrInterface owner, Method method) { + if (computedGenericsOfMethods.containsKey(method)) + return computedGenericsOfMethods.get(method); + + Set> txResult = new HashSet<>(); + Set> javaResult = new HashSet<>(); + var generics = new Generics(javaResult, txResult); + computedGenericsOfMethods.put(method, generics); + + var genericsOfClass = generics(owner).javaGenerics(); + var simplifiedConstraints = new HashSet<>(this.simplifiedConstraints); + + HashSet txTypeVariables = new HashSet<>(); + HashSet javaTypeVariables = new HashSet<>(); + HashSet txTypeVariablesOfClass = new HashSet<>(); + HashSet javaTypeVariablesOfClass = new HashSet<>(); + + methodFindTypeVariables(method, genericsOfClass, javaTypeVariablesOfClass, javaTypeVariables, equality); + methodFindTypeVariables(method, genericsOfClass, txTypeVariablesOfClass, txTypeVariables, txEquality); + + methodFindConstraints(owner, method, simplifiedConstraints, javaTypeVariables, javaTypeVariablesOfClass, javaResult, equality); + methodFindConstraints(owner, method, simplifiedConstraints, txTypeVariables, txTypeVariablesOfClass, txResult, txEquality); + + { // Java Generics + eliminateCycles(javaResult, equality); + eliminateInfima(javaResult, equality); + + var usedTphs = new HashSet(); + // For eliminating inner type variables we need to figure out which ones are actually used + // TODO Maybe don't do this twice? + for (var param : method.getParameterList().getFormalparalist()) { + usedTphs.addAll(findTypeVariables(param.getType(), equality)); + } + usedTphs.addAll(findTypeVariables(method.getReturnType(), equality)); + var referenced = new HashSet<>(usedTphs); + referenced.addAll(javaTypeVariablesOfClass); + + eliminateInnerTypeVariables(referenced, javaResult); + equalizeTypeVariables(javaResult, equality); + usedTPHsOfMethods.put(method, usedTphs); + } + { // JavaTX Generics + eliminateInfima(txResult, txEquality); + + var referenced = new HashSet(); + for (var param : method.getParameterList().getFormalparalist()) { + referenced.addAll(findTypeVariables(param.getType(), txEquality)); + } + referenced.addAll(findTypeVariables(method.getReturnType(), txEquality)); + referenced.addAll(txTypeVariablesOfClass); + + eliminateInnerTypeVariables(referenced, txResult); + } + + System.out.println(method.name + ": " + txResult + " & " + javaResult); + + return generics; + } + + void findAllBounds(RefTypeOrTPHOrWildcardOrGeneric type, Set> generics, Map equality) { if (type instanceof TypePlaceholder tph) { tph = equality.getOrDefault(tph, tph); var concreteType = concreteTypes.get(tph); if (concreteType != null) { - findAllBounds(concreteType, generics); + findAllBounds(concreteType, generics, equality); return; } + var found = false; for (var rsp : simplifiedConstraints) { var left = equality.getOrDefault(rsp.left, rsp.left); var right = equality.getOrDefault(rsp.right, rsp.right); @@ -310,35 +582,48 @@ public class ASTToTargetAST { var pair = new PairTPHsmallerTPH(tph, right); if (!generics.contains(pair)) { generics.add(pair); - findAllBounds(right, generics); + findAllBounds(right, generics, equality); + found = true; } - return; } } - generics.add(new PairTPHequalRefTypeOrWildcardType(tph, OBJECT)); + if (!found) + generics.add(new PairTPHequalRefTypeOrWildcardType(tph, OBJECT)); } else if (type instanceof RefType refType) { - refType.getParaList().forEach(t -> findAllBounds(t, generics)); + refType.getParaList().forEach(t -> findAllBounds(t, generics, equality)); } } - Set> generics(ClassOrInterface classOrInterface) { + Generics generics(ClassOrInterface classOrInterface) { if (computedGenericsOfClasses.containsKey(classOrInterface)) return computedGenericsOfClasses.get(classOrInterface); - Set> result = new HashSet<>(); - for (var field : classOrInterface.getFieldDecl()) { - findAllBounds(field.getType(), result); - } - computedGenericsOfClasses.put(classOrInterface, result); - eliminateCyclesAndInfima(result); - eliminateInnerTypeVariables(classOrInterface, result); - equalizeTypeVariables(result); + Set> txResult = new HashSet<>(); + Set> javaResult = new HashSet<>(); + var generics = new Generics(javaResult, txResult); + computedGenericsOfClasses.put(classOrInterface, generics); - System.out.println("Class " + classOrInterface.getClassName().getClassName() + ": " + result); - return result; + for (var field : classOrInterface.getFieldDecl()) { + findAllBounds(field.getType(), javaResult, equality); + findAllBounds(field.getType(), txResult, txEquality); + } + + { // Java Generics + eliminateCycles(javaResult, equality); + eliminateInfima(javaResult, equality); + eliminateInnerTypeVariablesOfClass(classOrInterface, javaResult, equality); + equalizeTypeVariables(javaResult, equality); + } + { // TX Generics + eliminateInfima(txResult, txEquality); + eliminateInnerTypeVariablesOfClass(classOrInterface, txResult, txEquality); + } + + System.out.println("Class " + classOrInterface.getClassName().getClassName() + ": " + txResult); + return generics; } - void equalizeTypeVariables(Set> input) { + void equalizeTypeVariables(Set> input, Map equality) { for (var pair : new HashSet<>(input)) { if (pair instanceof PairTPHsmallerTPH ptph) { if (ptph.left.getVariance() == 1 && ptph.right.getVariance() == -1) { @@ -347,7 +632,7 @@ public class ASTToTargetAST { for (var pair2 : new HashSet<>(input)) { if (pair2 instanceof PairTPHsmallerTPH ptph2 && ptph2.right.equals(ptph.left)) { input.remove(pair2); - input.add(new PairTPHsmallerTPH(ptph2.left, ptph.right)); + addToPairs(input, new PairTPHsmallerTPH(ptph2.left, ptph.right)); } } } @@ -355,53 +640,80 @@ public class ASTToTargetAST { } } - void findTphs(RefTypeOrTPHOrWildcardOrGeneric type, Set tphs) { + void findTphs(RefTypeOrTPHOrWildcardOrGeneric type, Set tphs, Map equality) { if (type instanceof RefType refType) { - refType.getParaList().forEach(t -> findTphs(t, tphs)); + refType.getParaList().forEach(t -> findTphs(t, tphs, equality)); } else if (type instanceof TypePlaceholder tph) { tph = equality.getOrDefault(tph, tph); var concreteType = concreteTypes.get(tph); if (concreteType != null) { - findTphs(concreteType, tphs); + findTphs(concreteType, tphs, equality); return; } tphs.add(tph); } } - void eliminateInnerTypeVariables(ClassOrInterface classOrInterface, Set> input) { + void eliminateInnerTypeVariablesOfClass(ClassOrInterface classOrInterface, Set> input, Map equality) { Set referenced = new HashSet<>(); for (var field : classOrInterface.getFieldDecl()) { - findTphs(field.getType(), referenced); + findTphs(field.getType(), referenced, equality); } for (var method : classOrInterface.getMethods()) { generics(classOrInterface, method); referenced.addAll(usedTPHsOfMethods.get(method)); } + eliminateInnerTypeVariables(referenced, input); + } - var oldInput = new HashSet<>(input); - for (var pair : oldInput) { - if (!referenced.contains(pair.getLeft())) { - input.remove(pair); - for (var pair2 : oldInput) { - if (pair2.getRight().equals(pair.getLeft())) { - input.remove(pair2); - if (pair instanceof PairTPHsmallerTPH) - input.add(new PairTPHsmallerTPH((TypePlaceholder) pair2.getLeft(), (TypePlaceholder) pair.getRight())); - else - input.add(new PairTPHequalRefTypeOrWildcardType((TypePlaceholder) pair2.getLeft(), pair.getRight())); - } - } + private void findChain(Set referenced, Set> input, Set> output, TypePlaceholder start, TypePlaceholder end, Set chain) { + if (referenced.contains(end)) { + var pair = new PairTPHsmallerTPH(start, end); + output.add(pair); + return; + } + var foundNext = false; + for (var pair : input) { + if (pair instanceof PairTPHsmallerTPH ptph && ptph.left.equals(end)) { + if (chain.contains(ptph.right)) return; + chain = new HashSet<>(chain); + chain.add(ptph.right); + findChain(referenced, input, output, start, ptph.right, chain); + foundNext = true; } } + if (!foundNext) { + output.add(new PairTPHequalRefTypeOrWildcardType(start, OBJECT)); + } } - void eliminateCyclesAndInfima(Set> input) { - // Eliminate cycles + void eliminateInnerTypeVariables(Set referenced, Set> input) { + var output = new HashSet>(); + for (var tph : referenced) { + for (var pair : input) { + if (pair instanceof PairTPHsmallerTPH pthp && pthp.left.equals(tph)) { + var chain = new HashSet(); + chain.add(tph); + findChain(referenced, input, output, tph, pthp.right, chain); + } + } + } + for (var pair : input) { + if (pair instanceof PairTPHequalRefTypeOrWildcardType rtph) { + if (referenced.contains(rtph.left)) + output.add(rtph); + } + } + + input.clear(); + input.addAll(output); + } + + void eliminateCycles(Set> input, Map equality) { var cycles = findCycles(input); for (var cycle : cycles) { var newTph = TypePlaceholder.fresh(new NullToken()); - input.add(new PairTPHequalRefTypeOrWildcardType(newTph, OBJECT)); + addToPairs(input, new PairTPHequalRefTypeOrWildcardType(newTph, OBJECT)); cycle.add(cycle.get(0)); // Make it a complete cycle for (var i = 0; i < cycle.size() - 1; i++) { var left = cycle.get(i); @@ -411,7 +723,9 @@ public class ASTToTargetAST { equality.put(left, newTph); } } - // Eliminate infima + } + + void eliminateInfima(Set> input, Map equality) { var foundInfima = false; do { foundInfima = false; @@ -426,7 +740,7 @@ public class ASTToTargetAST { if (infima.size() > 1) { foundInfima = true; var newTph = TypePlaceholder.fresh(new NullToken()); - input.add(new PairTPHsmallerTPH(left, newTph)); + addToPairs(input, new PairTPHsmallerTPH(left, newTph)); input.removeAll(infima); for (var infimum : infima) { equality.put(infimum.right, newTph); @@ -434,14 +748,16 @@ public class ASTToTargetAST { if (pair.getLeft().equals(infimum.right)) { input.remove(pair); if (pair instanceof PairTPHsmallerTPH stph) { - input.add(new PairTPHsmallerTPH(newTph, stph.right)); + if (!newTph.equals(stph.right)) + addToPairs(input, new PairTPHsmallerTPH(newTph, stph.right)); } else if (pair instanceof PairTPHequalRefTypeOrWildcardType rtph) { - input.add(new PairTPHequalRefTypeOrWildcardType(newTph, rtph.getRight())); + addToPairs(input, new PairTPHequalRefTypeOrWildcardType(newTph, rtph.getRight())); } } else if (pair.getRight().equals(infimum.right)) { input.remove(pair); if (pair instanceof PairTPHsmallerTPH stph) { - input.add(new PairTPHsmallerTPH(stph.left, newTph)); + if (!newTph.equals(stph.left)) + addToPairs(input, new PairTPHsmallerTPH(stph.left, newTph)); } } }); @@ -451,9 +767,19 @@ public class ASTToTargetAST { } while (foundInfima); } - TargetType get(TypePlaceholder tph) { + RefTypeOrTPHOrWildcardOrGeneric getType(RefTypeOrTPHOrWildcardOrGeneric type, Map equality) { + if (type instanceof TypePlaceholder tph) { + if (equality.containsKey(tph)) { + return getType(equality.get(tph), equality); + } + return concreteTypes.getOrDefault(tph, tph); + } + return type; + } + + TargetType getTargetType(TypePlaceholder tph, Map equality) { if (equality.containsKey(tph)) { - return get(equality.get(tph)); + return getTargetType(equality.get(tph), equality); } var type = concreteTypes.get(tph); if (type == null) return new TargetGenericType(tph.getName()); @@ -461,14 +787,14 @@ public class ASTToTargetAST { } } - protected ByteArrayClassLoader classLoader; + protected IByteArrayClassLoader classLoader; protected SourceFile sourceFile; public ASTToTargetAST(List resultSets) { this(resultSets, null, new ByteArrayClassLoader()); } - public ASTToTargetAST(List resultSets, SourceFile sourceFile, ByteArrayClassLoader classLoader) { + public ASTToTargetAST(List resultSets, SourceFile sourceFile, IByteArrayClassLoader classLoader) { this.classLoader = classLoader; this.sourceFile = sourceFile; @@ -594,7 +920,7 @@ public class ASTToTargetAST { Set convert(Set> result) { return result.stream().map(p -> { if (p instanceof PairTPHsmallerTPH pair) { - return new TargetGeneric(pair.left.getName(), new TargetGenericType(pair.right.getName())); + return new TargetGeneric(pair.left.getName(), convert(pair.right)); } else if (p instanceof PairTPHequalRefTypeOrWildcardType pair) { return new TargetGeneric(pair.left.getName(), convert(pair.right)); } else { @@ -603,15 +929,40 @@ public class ASTToTargetAST { }).collect(Collectors.toSet()); } + public List convert(GenericTypeVar typeVar) { + var ret = new ArrayList(); + for (var bound : typeVar.getBounds()) { + ret.add(new TargetGeneric(typeVar.getName(), convert(bound))); + } + return ret; + } + public TargetClass convert(ClassOrInterface input) { currentClass = input; + Set javaGenerics = new HashSet<>(); + Set txGenerics = new HashSet<>(); + var genericsIter = input.getGenerics().iterator(); + if (genericsIter.hasNext()) { + // Add empty set of generics to cache so that it doesn't try to calculate it later + sigma.computedGenericsOfClasses.put(input, new Generics(new HashSet<>(), new HashSet<>())); + while (genericsIter.hasNext()) { + var next = genericsIter.next(); + javaGenerics.addAll(convert(next)); + } + } else { + // Generate generics only if there are no user defined ones + var generics = sigma.generics(input); + javaGenerics = convert(generics.javaGenerics()); + txGenerics = convert(generics.txGenerics()); + } + TargetBlock fieldInitializer = null; if (input.getfieldInitializations().isPresent()) fieldInitializer = convert(input.getfieldInitializations().get().block); TargetBlock finalFieldInitializer = fieldInitializer; return new TargetClass(input.getModifiers(), input.getClassName().toString(), convert(input.getSuperClass()), - convert(sigma.generics(input)), + javaGenerics, txGenerics, input.getSuperInterfaces().stream().map(this::convert).toList(), input.getConstructors().stream().map(constructor -> this.convert(constructor, finalFieldInitializer)).flatMap(List::stream).toList(), input.getFieldDecl().stream().map(this::convert).toList(), @@ -624,6 +975,35 @@ public class ASTToTargetAST { .map(param -> new MethodParameter(convert(param.getType()), param.getName())).toList(); } + private boolean hasGeneric(Set generics, GenericRefType type) { + return generics.stream().anyMatch(g -> g.name().equals(type.getParsedName())); + } + + private Set collectMethodGenerics(Set> generics, Map equality, Method input) { + var convertedGenerics = new HashSet<>(convert(generics)); + outer: + for (GenericTypeVar typeVar : input.getGenerics()) { + for (var classGeneric : currentClass.getGenerics()) { + if (classGeneric.equals(typeVar)) { + continue outer; + } + } + convertedGenerics.addAll(convert(typeVar)); + } + var returnType = sigma.getType(input.getReturnType(), equality); + if ((returnType instanceof GenericRefType refType) && !hasGeneric(convertedGenerics, refType)) { + convertedGenerics.add(new TargetGeneric(refType.getParsedName(), convert(OBJECT))); + } + for (var param : input.getParameterList()) { + var type = sigma.getType(param.getType(), equality); + if (type instanceof GenericRefType refType && !hasGeneric(convertedGenerics, refType)) { + convertedGenerics.add(new TargetGeneric(refType.getParsedName(), convert(OBJECT))); + } + } + + return convertedGenerics; + } + private List convert(Constructor input, TargetBlock fieldInitializer) { sigma = all.get(0); List result = new ArrayList<>(); @@ -634,7 +1014,10 @@ public class ASTToTargetAST { var generics = sigma.generics(currentClass, input); List params = convert(input.getParameterList()); if (parameterSet.stream().noneMatch(p -> p.equals(params))) { - result.add(new TargetConstructor(input.modifier, convert(generics), params, convert(input.block), fieldInitializer)); + var javaGenerics = collectMethodGenerics(generics.javaGenerics(), sigma.equality, input); + var txGenerics = collectMethodGenerics(generics.txGenerics(), sigma.txEquality, input); + + result.add(new TargetConstructor(input.modifier, javaGenerics, txGenerics, params, convert(input.block), fieldInitializer)); parameterSet.add(params); } } @@ -652,9 +1035,12 @@ public class ASTToTargetAST { var generics = sigma.generics(currentClass, input); List params = convert(input.getParameterList()); if (parameterSet.stream().noneMatch(p -> p.equals(params))) { + var javaGenerics = collectMethodGenerics(generics.javaGenerics(), sigma.equality, input); + var txGenerics = collectMethodGenerics(generics.txGenerics(), sigma.txEquality, input); + result.add(new TargetMethod( input.modifier, - input.name, convert(generics), params, + input.name, javaGenerics, txGenerics, params, convert(input.getReturnType()), convert(input.block) )); @@ -683,7 +1069,10 @@ public class ASTToTargetAST { ); } - private final Set usedFunN = new HashSet<>(); + private final Set usedFunN = new HashSet<>(); + private final Set usedFunNSuperTypes = new HashSet<>(); + + public Map auxiliaries = new HashMap<>(); protected TargetType convert(RefTypeOrTPHOrWildcardOrGeneric input) { return input.acceptTV(new TypeVisitor<>() { @@ -693,10 +1082,19 @@ public class ASTToTargetAST { if (name.equals("void")) return null; var params = refType.getParaList().stream().map(ASTToTargetAST.this::convert).toList(); - if (name.matches("Fun\\d\\$\\$")) { // TODO This seems like a bad idea - if (!usedFunN.contains(params.size() - 1)) { - usedFunN.add(params.size() - 1); - classLoader.loadClass(FunNGenerator.getInstance().generateSuperBytecode(params.size() - 1)); + if (name.matches("Fun\\d+\\$\\$")) { // TODO This seems like a bad idea + var className = FunNGenerator.getSpecializedClassName(FunNGenerator.getArguments(params), FunNGenerator.getReturnType(params)); + if (!usedFunNSuperTypes.contains(params.size())) { + usedFunNSuperTypes.add(params.size()); + var code = FunNGenerator.generateSuperBytecode(params.size() - 1); + var clazz = classLoader.loadClass(code); + auxiliaries.put(clazz.getName(), code); + } + if (!usedFunN.contains(className)) { + usedFunN.add(className); + var code = FunNGenerator.generateSpecializedBytecode(FunNGenerator.getArguments(params), FunNGenerator.getReturnType(params)); + var clazz = classLoader.loadClass(code); + auxiliaries.put(clazz.getName(), code); } return new TargetFunNType(params.size() - 1, params); } @@ -710,7 +1108,7 @@ public class ASTToTargetAST { @Override public TargetType visit(TypePlaceholder typePlaceholder) { - return sigma.get(typePlaceholder); + return sigma.getTargetType(typePlaceholder, sigma.equality); } @Override diff --git a/src/main/java/de/dhbwstuttgart/target/generate/Bound.java b/src/main/java/de/dhbwstuttgart/target/generate/Bound.java new file mode 100644 index 00000000..1b39df6c --- /dev/null +++ b/src/main/java/de/dhbwstuttgart/target/generate/Bound.java @@ -0,0 +1,10 @@ +package de.dhbwstuttgart.target.generate; + +import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric; +import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder; + +import java.util.List; + +public record Bound(boolean isOnMethod, RefTypeOrTPHOrWildcardOrGeneric bound) { + +} diff --git a/src/main/java/de/dhbwstuttgart/target/generate/BoundsList.java b/src/main/java/de/dhbwstuttgart/target/generate/BoundsList.java new file mode 100644 index 00000000..b92394d6 --- /dev/null +++ b/src/main/java/de/dhbwstuttgart/target/generate/BoundsList.java @@ -0,0 +1,44 @@ +package de.dhbwstuttgart.target.generate; + +import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder; + +import java.util.AbstractList; +import java.util.List; + +public class BoundsList extends AbstractList { + private final List bounds; + + public BoundsList(List bounds) { + this.bounds = bounds; + } + public BoundsList(Bound... bounds) { + this.bounds = List.of(bounds); + } + + @Override + public Bound get(int index) { + return bounds.get(index); + } + + @Override + public int size() { + return bounds.size(); + } + + @Override + public boolean equals(Object other) { + if (!(other instanceof BoundsList right)) return false; + if (size() != right.size()) return false; + for (var i = 0; i < size(); i++) { + var l = get(i); + var r = right.get(i); + if (l.isOnMethod() != r.isOnMethod()) return false; + if (i == size() - 1) { + if (!(l.bound() instanceof TypePlaceholder)) { + if (!(l.bound().equals(r.bound()))) return false; + } + } + } + return true; + } +} diff --git a/src/main/java/de/dhbwstuttgart/target/generate/GenericsResult.java b/src/main/java/de/dhbwstuttgart/target/generate/GenericsResult.java new file mode 100644 index 00000000..e350707e --- /dev/null +++ b/src/main/java/de/dhbwstuttgart/target/generate/GenericsResult.java @@ -0,0 +1,79 @@ +package de.dhbwstuttgart.target.generate; + +import de.dhbwstuttgart.syntaxtree.ClassOrInterface; +import de.dhbwstuttgart.syntaxtree.Method; +import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric; +import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder; +import de.dhbwstuttgart.typeinference.result.ResultPair; + +import java.util.*; + +public class GenericsResult { + final ASTToTargetAST.Sigma sigma; + + GenericsResult(ASTToTargetAST.Sigma sigma) { + this.sigma = sigma; + } + + public Set> get(ClassOrInterface clazz) { + var generics = this.sigma.computedGenericsOfClasses.get(clazz); + if (generics == null) return Set.of(); + return generics.txGenerics(); + } + + // TODO Compute generics if not present? + public Set> get(Method method) { + var generics = this.sigma.computedGenericsOfMethods.get(method); + if (generics == null) return Set.of(); + return generics.txGenerics(); + } + + public BoundsList getBounds(RefTypeOrTPHOrWildcardOrGeneric type, ClassOrInterface clazz) { + return getBounds(type, clazz, null); + } + + public BoundsList getBounds(RefTypeOrTPHOrWildcardOrGeneric type, ClassOrInterface clazz, Method method) { + type = resolve(type); + if (type instanceof TypePlaceholder) { + var methodGenerics = get(method); + var classGenerics = get(clazz); + List result = new ArrayList<>(); + + Optional bound = Optional.empty(); + do { + bound = Optional.empty(); + for (var pair : methodGenerics) { + if (pair.getLeft().equals(type)) { + type = resolve(pair.getRight()); + bound = Optional.of(new Bound(true, type)); + break; + } + } + if (bound.isEmpty()) { + for (var pair : classGenerics) { + if (pair.getLeft().equals(type)) { + type = resolve(pair.getRight()); + bound = Optional.of(new Bound(false, type)); + break; + } + } + } + bound.ifPresent(result::add); + } while (bound.isPresent()); + return new BoundsList(result); + } + return new BoundsList(List.of()); + } + + public RefTypeOrTPHOrWildcardOrGeneric resolve(RefTypeOrTPHOrWildcardOrGeneric type) { + if (type instanceof TypePlaceholder tph) + return this.sigma.getType(tph, sigma.equality); + return type; + } + + public RefTypeOrTPHOrWildcardOrGeneric resolveTx(RefTypeOrTPHOrWildcardOrGeneric type) { + if (type instanceof TypePlaceholder tph) + return this.sigma.getType(tph, sigma.txEquality); + return type; + } +} diff --git a/src/main/java/de/dhbwstuttgart/target/generate/StatementToTargetExpression.java b/src/main/java/de/dhbwstuttgart/target/generate/StatementToTargetExpression.java index 8ca6e052..b6a8f12f 100644 --- a/src/main/java/de/dhbwstuttgart/target/generate/StatementToTargetExpression.java +++ b/src/main/java/de/dhbwstuttgart/target/generate/StatementToTargetExpression.java @@ -9,10 +9,7 @@ import de.dhbwstuttgart.syntaxtree.statement.*; import de.dhbwstuttgart.syntaxtree.type.RefType; import de.dhbwstuttgart.target.tree.MethodParameter; import de.dhbwstuttgart.target.tree.expression.*; -import de.dhbwstuttgart.target.tree.type.TargetFunNType; -import de.dhbwstuttgart.target.tree.type.TargetRefType; -import de.dhbwstuttgart.target.tree.type.TargetSpecializedType; -import de.dhbwstuttgart.target.tree.type.TargetType; +import de.dhbwstuttgart.target.tree.type.*; import java.lang.reflect.Method; import java.util.*; @@ -79,7 +76,7 @@ public class StatementToTargetExpression implements StatementVisitor { }); result = new TargetLambdaExpression( - new TargetFunNType(parameters.size(), parameters.stream().map(MethodParameter::type).toList()), + converter.convert(lambdaExpression.getType()), captures, parameters, converter.convert(lambdaExpression.getReturnType()), converter.convert(lambdaExpression.methodBody) ); } @@ -172,7 +169,7 @@ public class StatementToTargetExpression implements StatementVisitor { } static boolean convertsTo(TargetType from, TargetType to) { - if (to.equals(TargetType.Object)) return true; // TODO Consider type coercion and suptyping + if (to.equals(TargetType.Object)) return true; // TODO Consider type coercion and subtyping return to.equals(from); } @@ -213,9 +210,10 @@ public class StatementToTargetExpression implements StatementVisitor { public void visit(MethodCall methodCall) { var receiverType = converter.convert(methodCall.receiver.getType()); var isFunNType = receiverType instanceof TargetFunNType; - var returnType = isFunNType ? TargetType.Object : converter.convert(methodCall.getType()); + var returnType = isFunNType ? TargetType.Object : converter.convert(methodCall.signature.get(methodCall.signature.size() - 1)); var receiverName = new JavaClassName(converter.convert(methodCall.receiver.getType()).name()); - var argList = methodCall.arglist.getArguments().stream().map(expr -> converter.convert(expr.getType())).toList(); + var argList = methodCall.signature.stream().map(converter::convert).toList(); + argList = argList.subList(0, argList.size() - 1); Method foundMethod = null; if (methodCall.receiver instanceof ExpressionReceiver expressionReceiver && expressionReceiver.expr instanceof This) { @@ -306,9 +304,11 @@ public class StatementToTargetExpression implements StatementVisitor { public void visit(SuperCall superCall) { var aSuper = converter.convert(converter.currentClass.getSuperClass()); var type = converter.convert(superCall.getType()); + var parameters = superCall.arglist.getArguments().stream().map(par -> converter.convert(par.getType())).toList(); + result = new TargetMethodCall( type, type, - superCall.argTypes == null ? List.of() : superCall.argTypes.stream().map(converter::convert).toList(), + parameters, new TargetSuper(aSuper), superCall.getArgumentList().getArguments().stream().map(converter::convert).toList(), aSuper, diff --git a/src/main/java/de/dhbwstuttgart/target/tree/TargetClass.java b/src/main/java/de/dhbwstuttgart/target/tree/TargetClass.java index 50cb9f71..781df996 100644 --- a/src/main/java/de/dhbwstuttgart/target/tree/TargetClass.java +++ b/src/main/java/de/dhbwstuttgart/target/tree/TargetClass.java @@ -10,14 +10,14 @@ import java.util.HashSet; import java.util.List; import java.util.Set; -public record TargetClass(int modifiers, String qualifiedName, TargetType superType, Set generics, List implementingInterfaces, +public record TargetClass(int modifiers, String qualifiedName, TargetType superType, Set generics, Set txGenerics, List implementingInterfaces, List constructors, List fields, List methods) { public TargetClass(int modifiers, String qualifiedName) { - this(modifiers, qualifiedName, TargetType.Object, new HashSet<>(), new ArrayList<>(), new ArrayList<>(), new ArrayList<>(), new ArrayList<>()); + this(modifiers, qualifiedName, TargetType.Object, new HashSet<>(), new HashSet<>(), new ArrayList<>(), new ArrayList<>(), new ArrayList<>(), new ArrayList<>()); } public TargetClass(int modifiers, String qualifiedName, List implementingInterfaces) { - this(modifiers, qualifiedName, TargetType.Object, new HashSet<>(), implementingInterfaces, new ArrayList<>(), new ArrayList<>(), new ArrayList<>()); + this(modifiers, qualifiedName, TargetType.Object, new HashSet<>(), new HashSet<>(), implementingInterfaces, new ArrayList<>(), new ArrayList<>(), new ArrayList<>()); } public String getName() { @@ -25,7 +25,7 @@ public record TargetClass(int modifiers, String qualifiedName, TargetType superT } public void addMethod(int access, String name, Set generics, List parameterTypes, TargetType returnType, TargetBlock block) { - this.methods.add(new TargetMethod(access, name, generics, parameterTypes, returnType, block)); + this.methods.add(new TargetMethod(access, name, generics, Set.of(), parameterTypes, returnType, block)); } public void addMethod(int access, String name, List parameterTypes, TargetType returnType, TargetBlock block) { @@ -33,7 +33,7 @@ public record TargetClass(int modifiers, String qualifiedName, TargetType superT } public void addConstructor(int access, Set generics, List paramterTypes, TargetBlock block) { - this.constructors.add(new TargetConstructor(access, generics, paramterTypes, block, null)); + this.constructors.add(new TargetConstructor(access, generics, Set.of(), paramterTypes, block, null)); } public void addConstructor(int access, List paramterTypes, TargetBlock block) { diff --git a/src/main/java/de/dhbwstuttgart/target/tree/TargetConstructor.java b/src/main/java/de/dhbwstuttgart/target/tree/TargetConstructor.java index 4d2cca14..7d3aa389 100644 --- a/src/main/java/de/dhbwstuttgart/target/tree/TargetConstructor.java +++ b/src/main/java/de/dhbwstuttgart/target/tree/TargetConstructor.java @@ -6,7 +6,7 @@ import de.dhbwstuttgart.target.tree.type.TargetType; import java.util.List; import java.util.Set; -public record TargetConstructor(int access, Set generics, List parameters, TargetBlock block, TargetBlock fieldInitializer) { +public record TargetConstructor(int access, Set generics, Set txGenerics, List parameters, TargetBlock block, TargetBlock fieldInitializer) { public String getDescriptor() { return TargetMethod.getDescriptor(null, parameters.stream().map(MethodParameter::type).toArray(TargetType[]::new)); @@ -15,5 +15,9 @@ public record TargetConstructor(int access, Set generics, List generics, List parameters, TargetType returnType, TargetBlock block) { +public record TargetMethod(int access, String name, Set generics, Set txGenerics, List parameters, TargetType returnType, TargetBlock block) { public static String getDescriptor(TargetType returnType, TargetType... parameters) { String ret = "("; for (var parameterType : parameters) { @@ -22,15 +22,15 @@ public record TargetMethod(int access, String name, Set generics, public static String getSignature(Set generics, List parameters, TargetType returnType) { String ret = "<"; for (var generic : generics) { - ret += generic.name() + ":" + generic.bound().toGenericSignature(); + ret += generic.name() + ":" + generic.bound().toDescriptor(); } ret += ">("; for (var param : parameters) { - ret += param.type().toGenericSignature(); + ret += param.type().toDescriptor(); } ret += ")"; if (returnType == null) ret += "V"; - else ret += returnType.toGenericSignature(); + else ret += returnType.toDescriptor(); return ret; } @@ -42,6 +42,10 @@ public record TargetMethod(int access, String name, Set generics, return getSignature(generics, parameters, returnType); } + public String getTXSignature() { + return getSignature(txGenerics, parameters, returnType); + } + public boolean isStatic() { return (access & Opcodes.ACC_STATIC) != 0; } diff --git a/src/main/java/de/dhbwstuttgart/target/tree/type/TargetExtendsWildcard.java b/src/main/java/de/dhbwstuttgart/target/tree/type/TargetExtendsWildcard.java index 7e5ab002..db7c1eee 100644 --- a/src/main/java/de/dhbwstuttgart/target/tree/type/TargetExtendsWildcard.java +++ b/src/main/java/de/dhbwstuttgart/target/tree/type/TargetExtendsWildcard.java @@ -7,8 +7,8 @@ public record TargetExtendsWildcard(TargetType innerType) implements TargetType } @Override - public String toGenericSignature() { - return innerType.toGenericSignature(); + public String toDescriptor() { + return "+" + innerType.toDescriptor(); } @Override diff --git a/src/main/java/de/dhbwstuttgart/target/tree/type/TargetFunNType.java b/src/main/java/de/dhbwstuttgart/target/tree/type/TargetFunNType.java index e9379de6..afbf9f4e 100644 --- a/src/main/java/de/dhbwstuttgart/target/tree/type/TargetFunNType.java +++ b/src/main/java/de/dhbwstuttgart/target/tree/type/TargetFunNType.java @@ -1,11 +1,14 @@ package de.dhbwstuttgart.target.tree.type; +import de.dhbwstuttgart.bytecode.FunNGenerator; + import java.util.List; public record TargetFunNType(int N, List params) implements TargetSpecializedType { + @Override public String getInternalName() { - return "Fun" + N + "$$"; + return FunNGenerator.getSpecializedClassName(FunNGenerator.getArguments(params), FunNGenerator.getReturnType(params)); } @Override diff --git a/src/main/java/de/dhbwstuttgart/target/tree/type/TargetGenericType.java b/src/main/java/de/dhbwstuttgart/target/tree/type/TargetGenericType.java index 15900fb4..f3f49823 100644 --- a/src/main/java/de/dhbwstuttgart/target/tree/type/TargetGenericType.java +++ b/src/main/java/de/dhbwstuttgart/target/tree/type/TargetGenericType.java @@ -7,7 +7,7 @@ public record TargetGenericType(String name) implements TargetType { } @Override - public String toGenericSignature() { + public String toDescriptor() { return "T" + getInternalName() + ";"; } diff --git a/src/main/java/de/dhbwstuttgart/target/tree/type/TargetPrimitiveType.java b/src/main/java/de/dhbwstuttgart/target/tree/type/TargetPrimitiveType.java index 9d3bbf46..fe41a342 100644 --- a/src/main/java/de/dhbwstuttgart/target/tree/type/TargetPrimitiveType.java +++ b/src/main/java/de/dhbwstuttgart/target/tree/type/TargetPrimitiveType.java @@ -8,7 +8,7 @@ public record TargetPrimitiveType(String name) implements TargetType { } @Override - public String toGenericSignature() { + public String toDescriptor() { return toSignature(); } diff --git a/src/main/java/de/dhbwstuttgart/target/tree/type/TargetSpecializedType.java b/src/main/java/de/dhbwstuttgart/target/tree/type/TargetSpecializedType.java index 2a74307c..45e84fde 100644 --- a/src/main/java/de/dhbwstuttgart/target/tree/type/TargetSpecializedType.java +++ b/src/main/java/de/dhbwstuttgart/target/tree/type/TargetSpecializedType.java @@ -6,12 +6,12 @@ public sealed interface TargetSpecializedType extends TargetType permits TargetF List params(); @Override - default String toGenericSignature() { + default String toDescriptor() { String ret = "L" + getInternalName(); if (params().size() > 0) { ret += "<"; for (var param : params()) { - ret += param.toGenericSignature(); + ret += param.toDescriptor(); } ret += ">"; } diff --git a/src/main/java/de/dhbwstuttgart/target/tree/type/TargetSuperWildcard.java b/src/main/java/de/dhbwstuttgart/target/tree/type/TargetSuperWildcard.java index bf16e143..594ee2df 100644 --- a/src/main/java/de/dhbwstuttgart/target/tree/type/TargetSuperWildcard.java +++ b/src/main/java/de/dhbwstuttgart/target/tree/type/TargetSuperWildcard.java @@ -7,8 +7,8 @@ public record TargetSuperWildcard(TargetType innerType) implements TargetType { } @Override - public String toGenericSignature() { - return innerType.toGenericSignature(); + public String toDescriptor() { + return "-" + innerType.toDescriptor(); } @Override diff --git a/src/main/java/de/dhbwstuttgart/target/tree/type/TargetType.java b/src/main/java/de/dhbwstuttgart/target/tree/type/TargetType.java index 36d71af1..50ea6293 100644 --- a/src/main/java/de/dhbwstuttgart/target/tree/type/TargetType.java +++ b/src/main/java/de/dhbwstuttgart/target/tree/type/TargetType.java @@ -53,7 +53,7 @@ public sealed interface TargetType } String toSignature(); - String toGenericSignature(); + String toDescriptor(); String getInternalName(); String name(); } diff --git a/src/main/java/de/dhbwstuttgart/typedeployment/TypeInsertFactory.java b/src/main/java/de/dhbwstuttgart/typedeployment/TypeInsertFactory.java index 54a988c6..c185018f 100644 --- a/src/main/java/de/dhbwstuttgart/typedeployment/TypeInsertFactory.java +++ b/src/main/java/de/dhbwstuttgart/typedeployment/TypeInsertFactory.java @@ -6,15 +6,11 @@ import java.util.List; import java.util.Optional; import java.util.Set; +import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.GenericGenratorResultForSourceFile; import org.antlr.v4.runtime.Token; import org.objectweb.asm.Type; -import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.GenericGenratorResultForSourceFile; import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.GenericsGeneratorResult; -import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.GenericsGeneratorResultForClass; -import de.dhbwstuttgart.bytecode.utilities.MethodUtility; -import de.dhbwstuttgart.bytecode.utilities.Resolver; -import de.dhbwstuttgart.core.JavaTXCompiler; import de.dhbwstuttgart.syntaxtree.ClassOrInterface; import de.dhbwstuttgart.syntaxtree.Method; import de.dhbwstuttgart.syntaxtree.SourceFile; @@ -48,6 +44,7 @@ public class TypeInsertFactory { private static List newResults; + public static Set createTypeInsertPoints(SourceFile forSourcefile, ResultSet withResults, List newResults, List simplifyResultsForAllSourceFiles){ TypeInsertFactory.newResults = newResults; return new TypeInsertPlacer().getTypeInserts(forSourcefile, withResults, simplifyResultsForAllSourceFiles); @@ -84,8 +81,6 @@ public class TypeInsertFactory { private static synchronized Set createGenericInsert(List methodConstraints, List classConstraints,ClassOrInterface cl, Method m, ResultSet resultSet, Token mOffset){ Set result = createGenericClassInserts(classConstraints, cl); - - Resolver resolver = new Resolver(resultSet); if (m != null) { //List methodConstraints = genericResult.getMethodConstraintsByID(MethodUtility.createID(resolver, m)); diff --git a/src/main/java/de/dhbwstuttgart/typedeployment/TypeInsertPlacer.java b/src/main/java/de/dhbwstuttgart/typedeployment/TypeInsertPlacer.java index 042a76eb..aba0e72e 100644 --- a/src/main/java/de/dhbwstuttgart/typedeployment/TypeInsertPlacer.java +++ b/src/main/java/de/dhbwstuttgart/typedeployment/TypeInsertPlacer.java @@ -3,8 +3,6 @@ package de.dhbwstuttgart.typedeployment; import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.GenericGenratorResultForSourceFile; import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.GenericsGeneratorResult; import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.GenericsGeneratorResultForClass; -import de.dhbwstuttgart.bytecode.utilities.MethodUtility; -import de.dhbwstuttgart.bytecode.utilities.Resolver; import de.dhbwstuttgart.syntaxtree.*; import de.dhbwstuttgart.syntaxtree.statement.LambdaExpression; import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder; @@ -48,8 +46,6 @@ class TypeInsertPlacerClass extends AbstractASTWalker{ public final Set inserts = new HashSet<>(); private Method method; - private Resolver resolver; - List constraints; List classConstraints; @@ -58,15 +54,13 @@ class TypeInsertPlacerClass extends AbstractASTWalker{ this.method = null; this.results = withResults; this.generatedGenerics = generatedGenerics; - resolver = new Resolver(withResults); //PL 2020-04-12 Ob das stimmt weiss ich nicht forClass.accept(this); } @Override public void visit(Method method) { this.method = method; - String id = MethodUtility.createID(resolver, method); - constraints = generatedGenerics.getMethodConstraintsByID(id); + //constraints = generatedGenerics.getMethodConstraintsByID(id); classConstraints = generatedGenerics.getClassConstraints(); if(method.getReturnType() instanceof TypePlaceholder) inserts.add(TypeInsertFactory.createInsertPoints( diff --git a/src/main/java/de/dhbwstuttgart/typeinference/assumptions/MethodAssumption.java b/src/main/java/de/dhbwstuttgart/typeinference/assumptions/MethodAssumption.java index 6e6c5c5a..23f08039 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/assumptions/MethodAssumption.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/assumptions/MethodAssumption.java @@ -38,6 +38,14 @@ public class MethodAssumption extends Assumption{ public ClassOrInterface getReceiver(){ return receiver; } + + public RefTypeOrTPHOrWildcardOrGeneric getReturnType() { + return retType; + } + + public List getArgTypes(){ + return params; + } public RefTypeOrTPHOrWildcardOrGeneric getReturnType(GenericsResolver resolver) { return resolver.resolve(retType); diff --git a/src/main/java/de/dhbwstuttgart/typeinference/constraints/Constraint.java b/src/main/java/de/dhbwstuttgart/typeinference/constraints/Constraint.java index 6ebb9404..ffac994b 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/constraints/Constraint.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/constraints/Constraint.java @@ -10,10 +10,11 @@ public class Constraint
extends HashSet { private static final long serialVersionUID = 1L; private Boolean isInherited = false;//wird nur für die Method-Constraints benoetigt - /* es darf kein Constraint für den Return-Type erstellt werden, sonst gibt - * es Probleme beim Generated Generics - */ - public boolean isStatement = false; + /* + * wird verwendet um bei der Codegenerierung die richtige Methoden - Signatur + * auszuwaehlen + */ + /*private*/ Set methodSignatureConstraint = new HashSet<>(); private Constraint extendConstraint = null; @@ -25,9 +26,10 @@ public class Constraint extends HashSet { this.isInherited = isInherited; } - public Constraint(Boolean isInherited, Constraint extendConstraint) { + public Constraint(Boolean isInherited, Constraint extendConstraint, Set methodSignatureConstraint) { this.isInherited = isInherited; this.extendConstraint = extendConstraint; + this.methodSignatureConstraint = methodSignatureConstraint; } public void setIsInherited(Boolean isInherited) { @@ -45,9 +47,17 @@ public class Constraint extends HashSet { public void setExtendConstraint(Constraint c) { extendConstraint = c; } + + public Set getmethodSignatureConstraint() { + return methodSignatureConstraint; + } + + public void setmethodSignatureConstraint(Set c) { + methodSignatureConstraint = c; + } public String toString() { - return super.toString() + "\nisInherited = " + isInherited + "\nisStatement = " + isStatement + return super.toString() + "\nisInherited = " + isInherited //" + extendsContraint: " + (extendConstraint != null ? extendConstraint.toStringBase() : "null" ) + "\n" ; } diff --git a/src/main/java/de/dhbwstuttgart/typeinference/constraints/ConstraintSet.java b/src/main/java/de/dhbwstuttgart/typeinference/constraints/ConstraintSet.java index 1c7b7439..cd3301c1 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/constraints/ConstraintSet.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/constraints/ConstraintSet.java @@ -77,7 +77,8 @@ public class ConstraintSet { .map(o) .collect(Collectors.toCollection((as.getExtendConstraint() != null) ? () -> new Constraint (as.isInherited(), - as.getExtendConstraint().stream().map(o).collect(Collectors.toCollection(Constraint::new))) + as.getExtendConstraint().stream().map(o).collect(Collectors.toCollection(Constraint::new)), + as.getmethodSignatureConstraint().stream().map(o).collect(Collectors.toCollection(HashSet::new))) : () -> new Constraint (as.isInherited()) )); diff --git a/src/main/java/de/dhbwstuttgart/typeinference/constraints/Pair.java b/src/main/java/de/dhbwstuttgart/typeinference/constraints/Pair.java index 0c8ad7a5..78513531 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/constraints/Pair.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/constraints/Pair.java @@ -14,6 +14,7 @@ public class Pair implements Serializable public final RefTypeOrTPHOrWildcardOrGeneric TA2; private PairOperator eOperator = PairOperator.SMALLER; + private Boolean noUnification = false; public Pair(RefTypeOrTPHOrWildcardOrGeneric TA1, RefTypeOrTPHOrWildcardOrGeneric TA2 ) @@ -31,7 +32,16 @@ public class Pair implements Serializable this(TA1,TA2); this.eOperator = eOp; } - + + + public Pair(RefTypeOrTPHOrWildcardOrGeneric TA1, RefTypeOrTPHOrWildcardOrGeneric TA2, PairOperator eOp, Boolean noUnification) + { + // Konstruktor + this(TA1,TA2); + this.eOperator = eOp; + this.noUnification = noUnification; + } + public String toString() { // otth: Gibt ein Paar als String aus --> zum Debuggen und Vergleichen diff --git a/src/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPE.java b/src/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPE.java index 685ac9f6..dba8f6c0 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPE.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPE.java @@ -5,22 +5,24 @@ import de.dhbwstuttgart.parser.scope.JavaClassName; import de.dhbwstuttgart.syntaxtree.*; import de.dhbwstuttgart.syntaxtree.factory.ASTFactory; import de.dhbwstuttgart.syntaxtree.statement.Statement; +import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric; import de.dhbwstuttgart.typeinference.assumptions.TypeInferenceBlockInformation; import de.dhbwstuttgart.typeinference.assumptions.TypeInferenceInformation; import de.dhbwstuttgart.typeinference.constraints.ConstraintSet; +import de.dhbwstuttgart.util.BiRelation; + import java.util.*; public class TYPE { private final Collection sfs; private final TypeInferenceInformation typeInferenceInformation; - + public TYPE(Collection sourceFiles, Collection allAvailableClasses){ sfs = sourceFiles; this.typeInferenceInformation = new TypeInferenceInformation(allAvailableClasses); } - public ConstraintSet getConstraints() { ConstraintSet ret = new ConstraintSet(); for(SourceFile sf : sfs) diff --git a/src/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java b/src/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java index ddc2dc92..198b0f4c 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java @@ -21,6 +21,7 @@ import de.dhbwstuttgart.typeinference.unify.model.ExtendsType; import de.dhbwstuttgart.typeinference.unify.model.PairOperator; import de.dhbwstuttgart.typeinference.unify.model.PlaceholderType; import de.dhbwstuttgart.typeinference.unify.model.UnifyPair; +import de.dhbwstuttgart.util.BiRelation; import java.util.*; import java.util.stream.Collectors; @@ -57,7 +58,7 @@ public class TYPEStmt implements StatementVisitor{ @Override public void visit(ArgumentList arglist) { for(int i = 0;i> methodConstraints = new HashSet<>(); for(MethodAssumption m : this.getMethods(methodCall.name, methodCall.arglist, info)){ GenericsResolver resolver = getResolverInstance(); - Constraint oneMethodConstraint = generateConstraint(methodCall, m, info, resolver); - methodConstraints.add(oneMethodConstraint); + Set> oneMethodConstraints = generateConstraint(methodCall, m, info, resolver); + methodConstraints.addAll(oneMethodConstraints); + /* pl 2023-01-20: in generateConstraint bereits umgesetzt Constraint extendsOneMethodConstraint = oneMethodConstraint.stream() .map(x -> (x.TA1 instanceof TypePlaceholder && x.GetOperator() == PairOperator.EQUALSDOT && @@ -181,10 +184,10 @@ public class TYPEStmt implements StatementVisitor{ ? new Pair(x.TA1, new ExtendsWildcardType(x.TA2, x.TA2.getOffset()), PairOperator.EQUALSDOT) : x) .collect(Collectors.toCollection(() -> new Constraint(oneMethodConstraint.isInherited()))); - extendsOneMethodConstraint.isStatement = oneMethodConstraint.isStatement; oneMethodConstraint.setExtendConstraint(extendsOneMethodConstraint); extendsOneMethodConstraint.setExtendConstraint(oneMethodConstraint); methodConstraints.add(extendsOneMethodConstraint); + */ } if(methodConstraints.size()<1){ throw new TypeinferenceException("Methode "+methodCall.name+" ist nicht vorhanden!",methodCall.getOffset()); @@ -244,8 +247,8 @@ public class TYPEStmt implements StatementVisitor{ //Es wird in OderConstraints davon ausgegangen dass die Bedingungen für die Typen der Argumente links stehen //und die Typen der Rückgabewerte immer rechts stehen (vgl. JavaTXCompiler) public void visit(BinaryExpr binary) { - binary.lexpr.accept(this); - binary.rexpr.accept(this); + binary.lexpr.accept(this); + binary.rexpr.accept(this); if(binary.operation.equals(BinaryExpr.Operator.DIV) || binary.operation.equals(BinaryExpr.Operator.MUL)|| binary.operation.equals(BinaryExpr.Operator.MOD)|| @@ -574,9 +577,12 @@ public class TYPEStmt implements StatementVisitor{ METHOD CALL Section: */ - protected Constraint generateConstraint(MethodCall forMethod, MethodAssumption assumption, + protected Set> generateConstraint(MethodCall forMethod, MethodAssumption assumption, TypeInferenceBlockInformation info, GenericsResolver resolver){ - Constraint methodConstraint = new Constraint<>(assumption.isInherited()); + Constraint methodConstraint, extendsMethodConstraint; + methodConstraint = new Constraint<>(assumption.isInherited()); + extendsMethodConstraint = new Constraint<>(assumption.isInherited());// PL 2023-01-24: Ersetzt die Dopplung in visit(MethodCall) + ClassOrInterface receiverCl = assumption.getReceiver(); /* List params = new ArrayList<>(); @@ -588,21 +594,41 @@ public class TYPEStmt implements StatementVisitor{ RefTypeOrTPHOrWildcardOrGeneric receiverType = new RefType(assumption.getReceiver().getClassName(), params, forMethod.getOffset()); */ - RefTypeOrTPHOrWildcardOrGeneric retType = assumption.getReceiverType(resolver); - methodConstraint.add(new Pair(forMethod.receiver.getType(), retType, - PairOperator.EQUALSDOT));//PL 2020-03-17 SMALLERDOT in EQUALSDOT umgewandelt, weil alle geerbten Methoden in den jeweilen Klassen enthalten sind. - + RefTypeOrTPHOrWildcardOrGeneric receiverType = assumption.getReceiverType(resolver); + methodConstraint.add(new Pair(forMethod.receiver.getType(), receiverType, PairOperator.EQUALSDOT));//PL 2020-03-17 SMALLERDOT in EQUALSDOT umgewandelt, weil alle geerbten Methoden in den jeweilen Klassen enthalten sind. + + //PL 2023-01-24: dafuer ? extends receiverType noch ergaenzt + extendsMethodConstraint.add(new Pair(forMethod.receiver.getType(), new ExtendsWildcardType(receiverType, receiverType.getOffset()), PairOperator.EQUALSDOT)); + + //gegenseite Verschraenkung der beiden Mengen von Typannahmen + methodConstraint.setExtendConstraint(extendsMethodConstraint); + extendsMethodConstraint.setExtendConstraint(methodConstraint); + //Fuer Bytecodegenerierung PL 2020-03-09 wird derzeit nicht benutzt ANFANG //methodConstraint.add(new Pair(forMethod.receiverType, retType, // PairOperator.EQUALSDOT)); //Fuer Bytecodegenerierung PL 2020-03-09 wird derzeit nicht benutzt ENDE - methodConstraint.isStatement = forMethod.getStatement(); - methodConstraint.add(new Pair(assumption.getReturnType(resolver), forMethod.getType(), - PairOperator.EQUALSDOT)); - methodConstraint.addAll(generateParameterConstraints(forMethod, assumption, info, resolver)); - return methodConstraint; + methodConstraint.add(new Pair(assumption.getReturnType(resolver), forMethod.getType(), PairOperator.EQUALSDOT)); + extendsMethodConstraint.add(new Pair(assumption.getReturnType(resolver), forMethod.getType(), PairOperator.EQUALSDOT)); + + Set parameterContraints = generateParameterConstraints(forMethod, assumption, info, resolver); + + methodConstraint.addAll(parameterContraints); + extendsMethodConstraint.addAll(parameterContraints); + + Set methodSignatureConstraint = generatemethodSignatureConstraint(forMethod, assumption, info, resolver); + + System.out.println("methodSignatureConstraint; " + methodSignatureConstraint); + + methodConstraint.setmethodSignatureConstraint(methodSignatureConstraint); + extendsMethodConstraint.setmethodSignatureConstraint(methodSignatureConstraint); + + Set> ret = new HashSet<>(); + ret.add(methodConstraint); + ret.add(extendsMethodConstraint); + return ret; } protected Set generateParameterConstraints(MethodCall foMethod, MethodAssumption assumption, @@ -612,6 +638,9 @@ public class TYPEStmt implements StatementVisitor{ foMethod.arglist.getArguments().get(i).accept(this); RefTypeOrTPHOrWildcardOrGeneric argType = foMethod.arglist.getArguments().get(i).getType(); RefTypeOrTPHOrWildcardOrGeneric assType = assumption.getArgTypes(resolver).get(i); + + + ret.add(new Pair(argType, assType, PairOperator.SMALLERDOT)); //Fuer Bytecodegenerierung PL 2020-03-09 wird derzeit nicht benutzt ANFANG @@ -620,7 +649,24 @@ public class TYPEStmt implements StatementVisitor{ } return ret; } - + + + protected Set generatemethodSignatureConstraint(MethodCall foMethod, MethodAssumption assumption, + TypeInferenceBlockInformation info, GenericsResolver resolver) { + Set ret = new HashSet<>(); + + for(int i = 0; i getMethods(String name, int numArgs, TypeInferenceBlockInformation info) { List ret = new ArrayList<>(); diff --git a/src/main/java/de/dhbwstuttgart/typeinference/unify/RuleSet.java b/src/main/java/de/dhbwstuttgart/typeinference/unify/RuleSet.java index 50ea9a2e..d120e483 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/unify/RuleSet.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/unify/RuleSet.java @@ -683,7 +683,8 @@ public class RuleSet implements IRuleSet{ x -> uni.apply(pair,x)).collect(Collectors.toCollection((b.getExtendConstraint() != null) ? () -> new Constraint( b.isInherited(), - b.getExtendConstraint().stream().map(x -> uni.apply(pair,x)).collect(Collectors.toCollection(Constraint::new))) + b.getExtendConstraint().stream().map(x -> uni.apply(pair,x)).collect(Collectors.toCollection(Constraint::new)), + b.getmethodSignatureConstraint().stream().map(x -> uni.apply(pair,x)).collect(Collectors.toCollection(HashSet::new))) : () -> new Constraint(b.isInherited()) )); oderConstraints.replaceAll(oc -> oc.stream().map(applyUni).collect(Collectors.toCollection(HashSet::new))); diff --git a/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnify2Task.java b/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnify2Task.java index 317f3660..20820eef 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnify2Task.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnify2Task.java @@ -17,11 +17,13 @@ import de.dhbwstuttgart.typeinference.unify.model.UnifyPair; public class TypeUnify2Task extends TypeUnifyTask { Set> setToFlatten; + Set methodSignatureConstraintUebergabe; - public TypeUnify2Task(Set> setToFlatten, Set eq, List>> oderConstraints, Set nextSetElement, IFiniteClosure fc, boolean parallel, Writer logFile, Boolean log, int rekTiefe, UnifyResultModel urm, UnifyTaskModel usedTasks) { + public TypeUnify2Task(Set> setToFlatten, Set eq, List>> oderConstraints, Set nextSetElement, IFiniteClosure fc, boolean parallel, Writer logFile, Boolean log, int rekTiefe, UnifyResultModel urm, UnifyTaskModel usedTasks, Set methodSignatureConstraintUebergabe) { super(eq, oderConstraints, fc, parallel, logFile, log, rekTiefe, urm, usedTasks); this.setToFlatten = setToFlatten; this.nextSetElement = nextSetElement; + this.methodSignatureConstraintUebergabe = methodSignatureConstraintUebergabe; } Set getNextSetElement() { @@ -34,7 +36,7 @@ public class TypeUnify2Task extends TypeUnifyTask { System.out.println("two"); } one = true; - Set> res = unify2(setToFlatten, eq, oderConstraintsField, fc, parallel, rekTiefeField); + Set> res = unify2(setToFlatten, eq, oderConstraintsField, fc, parallel, rekTiefeField, methodSignatureConstraintUebergabe); /*if (isUndefinedPairSetSet(res)) { return new HashSet<>(); } else diff --git a/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java b/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java index abe48103..fd18b4d5 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/unify/TypeUnifyTask.java @@ -44,8 +44,8 @@ import de.dhbwstuttgart.typeinference.unify.model.Unifier; import de.dhbwstuttgart.typeinference.unify.model.UnifyPair; import de.dhbwstuttgart.typeinference.unify.model.UnifyType; import de.dhbwstuttgart.typeinference.unify.model.WildcardType; +import de.dhbwstuttgart.util.Pair; import de.dhbwstuttgart.typeinference.unify.model.OrderingUnifyPair; -import de.dhbwstuttgart.typeinference.unify.model.Pair; import java.io.File; import java.io.FileWriter; @@ -260,7 +260,7 @@ public class TypeUnifyTask extends RecursiveTask>> { ArrayList>> remainingOderconstraints = oderConstraintsField.stream() .filter(x -> x.size()>1) .collect(Collectors.toCollection(ArrayList::new)); - Set> res = unify(neweq, remainingOderconstraints, fc, parallel, rekTiefeField); + Set> res = unify(neweq, remainingOderconstraints, fc, parallel, rekTiefeField, new HashSet<>()); noOfThread--; try { logFile.close(); @@ -305,7 +305,7 @@ public class TypeUnifyTask extends RecursiveTask>> { * @param fc The finite closure * @return The set of all principal type unifiers */ - protected Set> unify(final Set eq, List>> oderConstraints, IFiniteClosure fc, boolean parallel, int rekTiefe) { + protected Set> unify(final Set eq, List>> oderConstraints, IFiniteClosure fc, boolean parallel, int rekTiefe, Set methodSignatureConstraint) { //Set aas = eq.stream().filter(x -> x.getLhsType().getName().equals("AA") //&& x.getPairOp().equals(PairOperator.SMALLERDOT) // ).collect(Collectors.toCollection(HashSet::new)); //writeLog(nOfUnify.toString() + " AA: " + aas.toString()); @@ -484,12 +484,12 @@ public class TypeUnifyTask extends RecursiveTask>> { //Aufruf von computeCartesianRecursive ANFANG //writeLog("topLevelSets: " + topLevelSets.toString()); - return computeCartesianRecursive(new ArrayList<>(topLevelSets), eq, oderConstraintsOutput, fc, parallel, rekTiefe); + return computeCartesianRecursive(new ArrayList<>(topLevelSets), eq, oderConstraintsOutput, fc, parallel, rekTiefe, methodSignatureConstraint); } - Set> unify2(Set> setToFlatten, Set eq, List>> oderConstraints, IFiniteClosure fc, boolean parallel, int rekTiefe) { + Set> unify2(Set> setToFlatten, Set eq, List>> oderConstraints, IFiniteClosure fc, boolean parallel, int rekTiefe, Set methodSignatureConstraint) { //Aufruf von computeCartesianRecursive ENDE //keine Ahnung woher das kommt @@ -574,16 +574,34 @@ public class TypeUnifyTask extends RecursiveTask>> { eqPrimePrimeSet.add(eqPrime); if (finalresult && isSolvedForm(eqPrime)) { writeLog("eqPrime:" + eqPrime.toString()+"\n"); + + /* methodconstraintsets werden zum Ergebnis hinzugefuegt + * Anfang + */ + //System.out.println("methodSignatureConstraint Return: " + methodSignatureConstraint); + eqPrimePrimeSet.forEach(x -> x.addAll(methodSignatureConstraint)); + + //Substitutionen in methodcontraintsets werdne ausgeführt + eqPrimePrimeSet = eqPrimePrimeSet.stream().map( + x -> { Optional> help = rules.subst(x); + return help.isPresent() ? + help.get(): + x; }).collect(Collectors.toSet()); + /* + * Ende + */ + + urm.notify(eqPrimePrimeSet); } } else if(eqPrimePrime.isPresent()) { - Set> unifyres = unifyres1 = unify(eqPrimePrime.get(), newOderConstraints, fc, parallel, rekTiefe); + Set> unifyres = unifyres1 = unify(eqPrimePrime.get(), newOderConstraints, fc, parallel, rekTiefe, methodSignatureConstraint); eqPrimePrimeSet.addAll(unifyres); } else { - Set> unifyres = unifyres2 = unify(eqPrime, newOderConstraints, fc, parallel, rekTiefe); + Set> unifyres = unifyres2 = unify(eqPrime, newOderConstraints, fc, parallel, rekTiefe, methodSignatureConstraint); eqPrimePrimeSet.addAll(unifyres); @@ -625,7 +643,7 @@ public class TypeUnifyTask extends RecursiveTask>> { * @param rekTiefe Deep of recursive calls * @return The set of all principal type unifiers */ - Set> computeCartesianRecursive(ArrayList>> topLevelSets, Set eq, List>> oderConstraints, IFiniteClosure fc, boolean parallel, int rekTiefe) { + Set> computeCartesianRecursive(ArrayList>> topLevelSets, Set eq, List>> oderConstraints, IFiniteClosure fc, boolean parallel, int rekTiefe, Set methodSignatureConstraint) { //oneElems: Alle 1-elementigen Mengen, die nur ein Paar //a <. theta, theta <. a oder a =. theta enthalten @@ -639,7 +657,7 @@ public class TypeUnifyTask extends RecursiveTask>> { Optional>> optNextSet = topLevelSets.stream().filter(x -> x.size()>1).findAny(); if (!optNextSet.isPresent()) {//Alle Elemente sind 1-elementig - Set> result = unify2(oneElems, eq, oderConstraints, fc, parallel, rekTiefe); + Set> result = unify2(oneElems, eq, oderConstraints, fc, parallel, rekTiefe, methodSignatureConstraint); return result; } @@ -705,7 +723,10 @@ public class TypeUnifyTask extends RecursiveTask>> { x.getPairOp() == PairOperator.EQUALSDOT) .map(x -> ((PlaceholderType)x.getGroundBasePair().getLhsType()).getVariance()) - .findAny(); + .reduce((n,m) -> { if ((n == 0) && (m==0)) return 0; + else if (n !=0) return n; //es muss mindestens eine Variance != 0 sein + else return m; + }); //Fuer Operatorenaufrufe wird variance auf 2 gesetzt. //da kein Receiver existiert also kein x.getGroundBasePair().getLhsType() instanceof PlaceholderType //Bei Varianz = 2 werden alle Elemente des Kartesischen Produkts abgearbeitet @@ -846,6 +867,11 @@ public class TypeUnifyTask extends RecursiveTask>> { } } + if (oderConstraint) {//Methodconstraints werden abgespeichert für die Bytecodegenerierung von Methodenaufrufen + methodSignatureConstraint.addAll(((Constraint)a).getmethodSignatureConstraint()); + //System.out.println("ERSTELLUNG: " +methodSignatureConstraint); + } + i++; Set> elems = new HashSet>(oneElems); writeLog("a1: " + rekTiefe + " "+ "variance: "+ variance + " " + a.toString()+ "\n"); @@ -879,7 +905,7 @@ public class TypeUnifyTask extends RecursiveTask>> { newElemsOrig.add(a); /* FORK ANFANG */ - TypeUnify2Task forkOrig = new TypeUnify2Task(newElemsOrig, newEqOrig, newOderConstraintsOrig, a, fc, parallel, logFile, log, rekTiefe, urm, usedTasks); + TypeUnify2Task forkOrig = new TypeUnify2Task(newElemsOrig, newEqOrig, newOderConstraintsOrig, a, fc, parallel, logFile, log, rekTiefe, urm, usedTasks, methodSignatureConstraint); //forks.add(forkOrig); synchronized(usedTasks) { if (this.myIsCancelled()) { @@ -914,7 +940,7 @@ public class TypeUnifyTask extends RecursiveTask>> { Set> newElems = new HashSet<>(elems); List>> newOderConstraints = new ArrayList<>(oderConstraints); newElems.add(nSaL); - TypeUnify2Task fork = new TypeUnify2Task(newElems, newEq, newOderConstraints, nSaL, fc, parallel, logFile, log, rekTiefe, urm, usedTasks); + TypeUnify2Task fork = new TypeUnify2Task(newElems, newEq, newOderConstraints, nSaL, fc, parallel, logFile, log, rekTiefe, urm, usedTasks, new HashSet<>(methodSignatureConstraint)); forks.add(fork); synchronized(usedTasks) { if (this.myIsCancelled()) { @@ -978,7 +1004,7 @@ public class TypeUnifyTask extends RecursiveTask>> { newElemsOrig.add(a); /* FORK ANFANG */ - TypeUnify2Task forkOrig = new TypeUnify2Task(newElemsOrig, newEqOrig, newOderConstraintsOrig, a, fc, parallel, logFile, log, rekTiefe, urm, usedTasks); + TypeUnify2Task forkOrig = new TypeUnify2Task(newElemsOrig, newEqOrig, newOderConstraintsOrig, a, fc, parallel, logFile, log, rekTiefe, urm, usedTasks, new HashSet<>(methodSignatureConstraint)); //forks.add(forkOrig); synchronized(usedTasks) { if (this.myIsCancelled()) { @@ -1013,7 +1039,7 @@ public class TypeUnifyTask extends RecursiveTask>> { Set> newElems = new HashSet<>(elems); List>> newOderConstraints = new ArrayList<>(oderConstraints); newElems.add(nSaL); - TypeUnify2Task fork = new TypeUnify2Task(newElems, newEq, newOderConstraints, nSaL, fc, parallel, logFile, log, rekTiefe, urm, usedTasks); + TypeUnify2Task fork = new TypeUnify2Task(newElems, newEq, newOderConstraints, nSaL, fc, parallel, logFile, log, rekTiefe, urm, usedTasks, new HashSet<>(methodSignatureConstraint)); forks.add(fork); synchronized(usedTasks) { if (this.myIsCancelled()) { @@ -1078,7 +1104,7 @@ public class TypeUnifyTask extends RecursiveTask>> { newElemsOrig.add(a); /* FORK ANFANG */ - TypeUnify2Task forkOrig = new TypeUnify2Task(newElemsOrig, newEqOrig, newOderConstraintsOrig, a, fc, parallel, logFile, log, rekTiefe, urm, usedTasks); + TypeUnify2Task forkOrig = new TypeUnify2Task(newElemsOrig, newEqOrig, newOderConstraintsOrig, a, fc, parallel, logFile, log, rekTiefe, urm, usedTasks, new HashSet<>(methodSignatureConstraint)); //forks.add(forkOrig); synchronized(usedTasks) { if (this.myIsCancelled()) { @@ -1099,7 +1125,7 @@ public class TypeUnifyTask extends RecursiveTask>> { Set> newElems = new HashSet<>(elems); List>> newOderConstraints = new ArrayList<>(oderConstraints); newElems.add(nSaL); - TypeUnify2Task fork = new TypeUnify2Task(newElems, newEq, newOderConstraints, nSaL, fc, parallel, logFile, log, rekTiefe, urm, usedTasks); + TypeUnify2Task fork = new TypeUnify2Task(newElems, newEq, newOderConstraints, nSaL, fc, parallel, logFile, log, rekTiefe, urm, usedTasks, methodSignatureConstraint); forks.add(fork); synchronized(usedTasks) { if (this.myIsCancelled()) { @@ -1150,11 +1176,15 @@ public class TypeUnifyTask extends RecursiveTask>> { //noOfThread++; } else {//parallel = false oder MaxNoOfThreads ist erreicht, sequentiell weiterarbeiten elems.add(a); //PL 2019-01-16 muss das wirklich hin steht schon in Zeile 859 ja braucht man siehe Zeile 859 - res = unify2(elems, eq, oderConstraints, fc, parallel, rekTiefe); + res = unify2(elems, eq, oderConstraints, fc, parallel, rekTiefe, new HashSet<>(methodSignatureConstraint)); }}} //Ab hier alle parallele Berechnungen wieder zusammengeführt. - if (!isUndefinedPairSetSet(res) && isUndefinedPairSetSet(result)) { + if (oderConstraint) {//Wenn weiteres Element nextSetasList genommen wird, muss die vorherige methodsignatur geloescht werden + methodSignatureConstraint.removeAll(((Constraint)a).getmethodSignatureConstraint()); + //System.out.println("REMOVE: " +methodSignatureConstraint); + } + if (!isUndefinedPairSetSet(res) && isUndefinedPairSetSet(result)) { //wenn korrektes Ergebnis gefunden alle Fehlerfaelle loeschen result = res; } @@ -1446,14 +1476,16 @@ public class TypeUnifyTask extends RecursiveTask>> { System.out.println(); } writeLog("nextSetasList vor filter-Aufruf: " + nextSetasList); - nextSetasList = nextSetasList.stream().filter(x -> { - //Boolean ret = false; - //for (PlaceholderType var : vars) { - // ret = ret || x.stream().map(b -> b.getLhsType().equals(var)).reduce((c,d) -> c || d).get(); - //} - return (!x.containsAll(durchschnitt)); - })//.filter(y -> couldBecorrect(reducedUndefResSubstGroundedBasePair, y)) //fuer testzwecke auskommentiert um nofstred zu bestimmen PL 2018-10-10 + if (!oderConstraint) {//PL 2023-02-08 eingefuegt: Bei oderconstraints sind Subststitutionen nicht als Substitutionen in idesem Sinne zu sehen + nextSetasList = nextSetasList.stream().filter(x -> { + //Boolean ret = false; + //for (PlaceholderType var : vars) { + // ret = ret || x.stream().map(b -> b.getLhsType().equals(var)).reduce((c,d) -> c || d).get(); + //} + return (!x.containsAll(durchschnitt)); + })//.filter(y -> couldBecorrect(reducedUndefResSubstGroundedBasePair, y)) //fuer testzwecke auskommentiert um nofstred zu bestimmen PL 2018-10-10 .collect(Collectors.toCollection(ArrayList::new)); + } writeLog("nextSetasList nach filter-Aufruf: " + nextSetasList); nofstred = nextSetasList.size(); //NOCH NICHT korrekt PL 2018-10-12 @@ -1521,7 +1553,7 @@ public class TypeUnifyTask extends RecursiveTask>> { unitedSubst.addAll(sameEq.getAllBases()); localEq.add(new UnifyPair(aPair.getRhsType(), sameEq.getRhsType(), sameEq.getPairOp(), unitedSubst, null)); finalresult = false; - Set> localRes = unify(localEq, new ArrayList<>(), fc, false, 0); + Set> localRes = unify(localEq, new ArrayList<>(), fc, false, 0, new HashSet<>()); finalresult = true; if (isUndefinedPairSetSet(localRes)) { if (result.isEmpty() || isUndefinedPairSetSet(result)) { @@ -1539,7 +1571,7 @@ public class TypeUnifyTask extends RecursiveTask>> { unitedSubst.addAll(sameEq.getAllBases()); localEq.add(new UnifyPair(sameEq.getLhsType(), aPair.getRhsType(), sameEq.getPairOp(), unitedSubst, null)); finalresult = false; - Set> localRes = unify(localEq, new ArrayList<>(), fc, false, 0); + Set> localRes = unify(localEq, new ArrayList<>(), fc, false, 0, new HashSet<>()); finalresult = true; if (isUndefinedPairSetSet(localRes)) { if (result.isEmpty() || isUndefinedPairSetSet(result)) { @@ -1950,6 +1982,7 @@ public class TypeUnifyTask extends RecursiveTask>> { .findAny()).isPresent() && optElem.get().getRhsType() instanceof ExtendsType);}) .collect(Collectors.toSet()); + ret.stream().forEach(x -> x.stream().forEach(y -> { Set x_new = new HashSet<>(x); //PL 2020-03-18: y selbst darf nicht in die Substitutionen x_new.remove(y); y.addSubstitutions(x_new); diff --git a/src/main/java/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java b/src/main/java/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java index a48db2aa..5f047d0c 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/unify/model/FiniteClosure.java @@ -26,6 +26,7 @@ import de.dhbwstuttgart.typeinference.unify.Match; import de.dhbwstuttgart.typeinference.unify.TypeUnifyTask; import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure; import de.dhbwstuttgart.typeinference.unify.interfaces.IUnify; +import de.dhbwstuttgart.util.Pair; /** * The finite closure for the type unification diff --git a/src/main/java/de/dhbwstuttgart/typeinference/unify/model/OrderingUnifyPair.java b/src/main/java/de/dhbwstuttgart/typeinference/unify/model/OrderingUnifyPair.java index ce2fbd21..35eee0eb 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/unify/model/OrderingUnifyPair.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/unify/model/OrderingUnifyPair.java @@ -19,6 +19,7 @@ import com.google.common.collect.Ordering; import de.dhbwstuttgart.typeinference.unify.Match; import de.dhbwstuttgart.typeinference.unify.TypeUnifyTask; import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure; +import de.dhbwstuttgart.util.Pair; diff --git a/src/main/java/de/dhbwstuttgart/util/BiRelation.java b/src/main/java/de/dhbwstuttgart/util/BiRelation.java new file mode 100644 index 00000000..ba4eec57 --- /dev/null +++ b/src/main/java/de/dhbwstuttgart/util/BiRelation.java @@ -0,0 +1,19 @@ +package de.dhbwstuttgart.util; + +import java.util.ArrayList; + +public class BiRelation extends ArrayList>{ + + public void put(X x, Y y) { + this.add(new Pair<>(x,y)); + } + + public void put(Pair p) { + this.add(p); + } + + + public void putAll(BiRelation br) { + this.addAll(br); + } +} diff --git a/src/main/java/de/dhbwstuttgart/typeinference/unify/model/Pair.java b/src/main/java/de/dhbwstuttgart/util/Pair.java similarity index 74% rename from src/main/java/de/dhbwstuttgart/typeinference/unify/model/Pair.java rename to src/main/java/de/dhbwstuttgart/util/Pair.java index de05c97d..3046afda 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/unify/model/Pair.java +++ b/src/main/java/de/dhbwstuttgart/util/Pair.java @@ -1,4 +1,4 @@ -package de.dhbwstuttgart.typeinference.unify.model; +package de.dhbwstuttgart.util; import java.util.Optional; @@ -20,6 +20,6 @@ public class Pair { } public String toString() { - return "(" + key.toString() + "," + "," + value.toString() + ")\n"; + return "(" + key.toString() + "," + value.toString() + ")\n"; } } diff --git a/src/test/java/AllgemeinTest.java b/src/test/java/AllgemeinTest.java index 46203361..2dfc4dbf 100644 --- a/src/test/java/AllgemeinTest.java +++ b/src/test/java/AllgemeinTest.java @@ -48,7 +48,9 @@ public class AllgemeinTest { //String className = "Box"; //String className = "Box_Main"; //String className = "wildcardPair"; - String className = "VectorConstAdd"; + //String className = "VectorConstAdd"; + String className = "VectorNotObject"; + //String className = "WildcardCaptureConversionTest"; //PL 2019-10-24: genutzt fuer unterschiedliche Tests path = System.getProperty("user.dir")+"/resources/AllgemeinTest/" + className + ".jav"; //path = System.getProperty("user.dir")+"/src/test/resources/AllgemeinTest/Overloading_Generics.jav"; diff --git a/src/test/java/bytecode/BinaryTest.java b/src/test/java/bytecode/BinaryTest.java deleted file mode 100644 index a2396106..00000000 --- a/src/test/java/bytecode/BinaryTest.java +++ /dev/null @@ -1,50 +0,0 @@ -package bytecode; - -import static org.junit.Assert.*; - -import java.io.File; -import java.lang.reflect.Method; -import java.net.URL; -import java.net.URLClassLoader; - -import org.junit.BeforeClass; -import org.junit.Test; - -import de.dhbwstuttgart.core.JavaTXCompiler; - -public class BinaryTest { - private static String path; - private static File fileToTest; - private static JavaTXCompiler compiler; - private static ClassLoader loader; - private static Class classToTest; - private static String pathToClassFile; - private static Object instanceOfClass; - - @BeforeClass - public static void setUpBeforeClass() throws Exception { - path = System.getProperty("user.dir")+"/resources/bytecode/javFiles/BinaryInMeth.jav"; - fileToTest = new File(path); - compiler = new JavaTXCompiler(fileToTest); - pathToClassFile = System.getProperty("user.dir")+"/resources/testBytecode/generatedBC/"; - compiler.generateBytecode(pathToClassFile); - loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); - classToTest = loader.loadClass("BinaryInMeth"); - instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); - } - - @Test - public void test() throws Exception { - Method m2 = classToTest.getDeclaredMethod("m2", Integer.class,Integer.class); - Integer res = (Integer) m2.invoke(instanceOfClass, 2,3); - 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(new Integer(4), res); - } - -} diff --git a/src/test/java/bytecode/ClassGenLamTest.java b/src/test/java/bytecode/ClassGenLamTest.java deleted file mode 100644 index 3fc81e64..00000000 --- a/src/test/java/bytecode/ClassGenLamTest.java +++ /dev/null @@ -1,37 +0,0 @@ -package bytecode; - -import static org.junit.Assert.*; - -import java.io.File; -import java.lang.reflect.Method; -import java.net.URL; -import java.net.URLClassLoader; - -import org.junit.BeforeClass; -import org.junit.Test; - -import de.dhbwstuttgart.core.JavaTXCompiler; - -public class ClassGenLamTest { - - private static String path; - private static File fileToTest; - private static JavaTXCompiler compiler; - private static ClassLoader loader; - private static Class classToTest; - private static String pathToClassFile; - private static Object instanceOfClass; - - @Test - public void generateBC() throws Exception { - path = System.getProperty("user.dir")+"/resources/bytecode/javFiles/ClassGenLam.jav"; - fileToTest = new File(path); - compiler = new JavaTXCompiler(fileToTest); - pathToClassFile = System.getProperty("user.dir")+"/resources/testBytecode/generatedBC/"; - compiler.generateBytecode(pathToClassFile); - loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); - classToTest = loader.loadClass("ClassGenLam"); - instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); - } - -} diff --git a/src/test/java/bytecode/FacTest.java b/src/test/java/bytecode/FacTest.java deleted file mode 100644 index 7f5c1b97..00000000 --- a/src/test/java/bytecode/FacTest.java +++ /dev/null @@ -1,44 +0,0 @@ -package bytecode; - -import static org.junit.Assert.*; - -import java.io.File; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.net.URL; -import java.net.URLClassLoader; - -import org.junit.BeforeClass; -import org.junit.Test; - -import de.dhbwstuttgart.core.JavaTXCompiler; - -public class FacTest { - private static String path; - private static File fileToTest; - private static JavaTXCompiler compiler; - private static ClassLoader loader; - private static Class classToTest; - private static String pathToClassFile; - private static Object instanceOfClass; - - @BeforeClass - public static void setUpBeforeClass() throws Exception { - path = System.getProperty("user.dir")+"/resources/bytecode/javFiles/Fac.jav"; - fileToTest = new File(path); - compiler = new JavaTXCompiler(fileToTest); - pathToClassFile = System.getProperty("user.dir")+"/resources/testBytecode/generatedBC/"; - compiler.generateBytecode(pathToClassFile); - loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); - classToTest = loader.loadClass("Fac"); - instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); - } - - @Test - 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, new Integer(6)); - } - -} diff --git a/src/test/java/bytecode/FacultyTest.java b/src/test/java/bytecode/FacultyTest.java deleted file mode 100644 index 10207262..00000000 --- a/src/test/java/bytecode/FacultyTest.java +++ /dev/null @@ -1,58 +0,0 @@ -package bytecode; - -import static org.junit.Assert.assertEquals; - -import java.io.File; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.net.URL; -import java.net.URLClassLoader; - -import org.junit.Test; - -import de.dhbwstuttgart.core.JavaTXCompiler; - -public class FacultyTest { - private static String path; - private static File fileToTest; - private static JavaTXCompiler compiler; - private static ClassLoader loader; - private static Class classToTest; - private static String pathToClassFile; - private static Object instanceOfClass; - - @Test - public void generateBC() throws Exception { - path = System.getProperty("user.dir")+"/resources/bytecode/javFiles/Faculty.jav"; - fileToTest = new File(path); - compiler = new JavaTXCompiler(fileToTest); - compiler.generateBytecode(System.getProperty("user.dir")+"/resources/testBytecode/generatedBC/"); - pathToClassFile = System.getProperty("user.dir")+"/resources/testBytecode/generatedBC/"; - loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); - classToTest = loader.loadClass("Faculty"); - instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); - - Method getFact = classToTest.getDeclaredMethod("getFact", Integer.class); -// Field fact = classToTest.getDeclaredField("fact"); -// Class lambda = m.invoke(instanceOfClass).getClass(); -// Class lambda = fact.getType(); -// System.out.println(fact.getType().getName()); -// Method apply = lambda.getMethod("apply", Object.class); -// System.out.println(lambda.getMethods()[0]); -// System.out.println(instanceOfClass.toString()); -// // Damit man auf die Methode zugreifen kann -// apply.setAccessible(true); - // Field value -// Object fieldVal = fact.get(instanceOfClass); - Integer i = 3; -// Method applyFromField = fieldVal.getClass().getDeclaredMethod("apply", Object.class); -// applyFromField.setAccessible(true); -// Integer result = (Integer) apply.invoke(lambda,i); - Integer result = (Integer) getFact.invoke(instanceOfClass,i); - - assertEquals(new Integer(6), result); - } - - -} diff --git a/src/test/java/bytecode/FieldTest.java b/src/test/java/bytecode/FieldTest.java deleted file mode 100644 index e0b98ff0..00000000 --- a/src/test/java/bytecode/FieldTest.java +++ /dev/null @@ -1,43 +0,0 @@ -package bytecode; - -import static org.junit.Assert.*; - -import java.io.File; -import java.lang.reflect.Field; - -import org.junit.BeforeClass; -import org.junit.Test; -import java.net.URL; -import java.net.URLClassLoader; - -import de.dhbwstuttgart.core.JavaTXCompiler; - -public class FieldTest { - - private static String path; - private static File fileToTest; - private static JavaTXCompiler compiler; - private static ClassLoader loader; - private static Class classToTest; - private static String pathToClassFile; - private static Object instanceOfClass; - - @BeforeClass - public static void setUpBeforeClass() throws Exception { - path = System.getProperty("user.dir")+"/resources/bytecode/javFiles/Field.jav"; - fileToTest = new File(path); - compiler = new JavaTXCompiler(fileToTest); - compiler.generateBytecode(System.getProperty("user.dir")+"/resources/testBytecode/generatedBC/"); - pathToClassFile = System.getProperty("user.dir")+"/resources/testBytecode/generatedBC/"; - loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); - classToTest = loader.loadClass("Field"); - instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); - } - - @Test - public void test() { - Field[] fields = classToTest.getFields(); - assertEquals(1, fields.length); - } - -} diff --git a/src/test/java/bytecode/FieldTph2Test.java b/src/test/java/bytecode/FieldTph2Test.java deleted file mode 100644 index 509e00f8..00000000 --- a/src/test/java/bytecode/FieldTph2Test.java +++ /dev/null @@ -1,52 +0,0 @@ -package bytecode; - -import static org.junit.Assert.*; - -import java.io.File; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.net.URL; -import java.net.URLClassLoader; - -import org.junit.BeforeClass; -import org.junit.Test; - -import de.dhbwstuttgart.core.JavaTXCompiler; - -public class FieldTph2Test { - - private static String path; - private static File fileToTest; - private static JavaTXCompiler compiler; - private static ClassLoader loader; - private static Class classToTest; - private static String pathToClassFile; - private static Object instanceOfClass; - - @BeforeClass - public static void setUpBeforeClass() throws Exception { - path = System.getProperty("user.dir")+"/resources/bytecode/javFiles/FieldTph2.jav"; - fileToTest = new File(path); - compiler = new JavaTXCompiler(fileToTest); - compiler.generateBytecode(System.getProperty("user.dir")+"/resources/testBytecode/generatedBC/"); - pathToClassFile = System.getProperty("user.dir")+"/resources/testBytecode/generatedBC/"; - loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); - classToTest = loader.loadClass("FieldTph2"); - instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); - } - - @Test - public void test() throws Exception { - Field a = classToTest.getDeclaredField("a"); - a.setAccessible(true); - - Method m2 = classToTest.getDeclaredMethod("m2", Object.class); - m2.invoke(instanceOfClass, 1); - - Method m = classToTest.getDeclaredMethod("m", Object.class); - Object result = m.invoke(instanceOfClass, 1); - - assertEquals(1,result); - } - -} diff --git a/src/test/java/bytecode/FieldTphConsMethTest.java b/src/test/java/bytecode/FieldTphConsMethTest.java deleted file mode 100644 index 3d5dbe7a..00000000 --- a/src/test/java/bytecode/FieldTphConsMethTest.java +++ /dev/null @@ -1,50 +0,0 @@ -package bytecode; - -import static org.junit.Assert.*; - -import java.io.File; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.net.URL; -import java.net.URLClassLoader; - -import org.junit.BeforeClass; -import org.junit.Test; - -import de.dhbwstuttgart.core.JavaTXCompiler; - -public class FieldTphConsMethTest { - - private static String path; - private static File fileToTest; - private static JavaTXCompiler compiler; - private static ClassLoader loader; - private static Class classToTest; - private static String pathToClassFile; - private static Object instanceOfClass; - - @BeforeClass - public static void setUpBeforeClass() throws Exception { - path = System.getProperty("user.dir")+"/resources/bytecode/javFiles/FieldTphConsMeth.jav"; - fileToTest = new File(path); - compiler = new JavaTXCompiler(fileToTest); - compiler.generateBytecode(System.getProperty("user.dir")+"/resources/testBytecode/generatedBC/"); - pathToClassFile = System.getProperty("user.dir")+"/resources/testBytecode/generatedBC/"; - loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); - classToTest = loader.loadClass("FieldTphConsMeth"); - } - - @Test - public void test() throws Exception { - instanceOfClass = classToTest.getConstructor(Object.class).newInstance("C"); - Field a = classToTest.getDeclaredField("a"); - a.setAccessible(true); - - Method m = classToTest.getDeclaredMethod("id", Object.class); - Object result = m.invoke(instanceOfClass, 42); - - assertEquals(42,result); - assertEquals("C", a.get(instanceOfClass)); - } - -} diff --git a/src/test/java/bytecode/FieldTphMMethTest.java b/src/test/java/bytecode/FieldTphMMethTest.java deleted file mode 100644 index ae04383b..00000000 --- a/src/test/java/bytecode/FieldTphMMethTest.java +++ /dev/null @@ -1,66 +0,0 @@ -package bytecode; - -import static org.junit.Assert.*; - -import java.io.File; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.net.URL; -import java.net.URLClassLoader; - -import org.junit.BeforeClass; -import org.junit.Test; - -import de.dhbwstuttgart.core.JavaTXCompiler; - -public class FieldTphMMethTest { - - private static String path; - private static File fileToTest; - private static JavaTXCompiler compiler; - private static ClassLoader loader; - private static Class classToTest; - private static String pathToClassFile; - private static Object instanceOfClass; - private static Object instanceOfClass2; - - @BeforeClass - public static void setUpBeforeClass() throws Exception { - path = System.getProperty("user.dir")+"/resources/bytecode/javFiles/FieldTphMMeth.jav"; - fileToTest = new File(path); - compiler = new JavaTXCompiler(fileToTest); - compiler.generateBytecode(System.getProperty("user.dir")+"/resources/testBytecode/generatedBC/"); - pathToClassFile = System.getProperty("user.dir")+"/resources/testBytecode/generatedBC/"; - loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); - classToTest = loader.loadClass("FieldTphMMeth"); - instanceOfClass = classToTest.getConstructor(Object.class,Object.class,Boolean.class).newInstance("C",42,true); - instanceOfClass2 = classToTest.getConstructor(Object.class,Object.class,Boolean.class).newInstance("C",42,false); - } - - @Test - public void testM() throws Exception { - - Method m = classToTest.getDeclaredMethod("m", Object.class,Object.class,Boolean.class); - Object result = m.invoke(instanceOfClass, "C",42,false); - - assertEquals(42,result); - } - - @Test - public void testWithTrue() throws Exception { - Field a = classToTest.getDeclaredField("a"); - a.setAccessible(true); - - assertEquals("C", a.get(instanceOfClass)); - - } - - @Test - public void testWithFalse() throws Exception { - Field a = classToTest.getDeclaredField("a"); - a.setAccessible(true); - - assertEquals(42, a.get(instanceOfClass2)); - } - -} diff --git a/src/test/java/bytecode/GenTest.java b/src/test/java/bytecode/GenTest.java deleted file mode 100644 index a830aac0..00000000 --- a/src/test/java/bytecode/GenTest.java +++ /dev/null @@ -1,30 +0,0 @@ -package bytecode; - -import static org.junit.Assert.*; - -import java.io.File; -import java.net.URL; -import java.net.URLClassLoader; - -import org.junit.BeforeClass; -import org.junit.Test; - -import de.dhbwstuttgart.core.JavaTXCompiler; - -public class GenTest { - - private static String path; - private static File fileToTest; - private static JavaTXCompiler compiler; - private static String pathToClassFile; - - @Test - public void generateBC() throws Exception { - path = System.getProperty("user.dir")+"/resources/bytecode/javFiles/Gen.jav"; - fileToTest = new File(path); - compiler = new JavaTXCompiler(fileToTest); - pathToClassFile = System.getProperty("user.dir")+"/resources/testBytecode/generatedBC/"; - compiler.generateBytecode(pathToClassFile); - } - -} diff --git a/src/test/java/bytecode/GreaterEqualTest.java b/src/test/java/bytecode/GreaterEqualTest.java deleted file mode 100644 index bbc7d844..00000000 --- a/src/test/java/bytecode/GreaterEqualTest.java +++ /dev/null @@ -1,140 +0,0 @@ -package bytecode; - -import static org.junit.Assert.*; - -import java.io.File; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.net.URL; -import java.net.URLClassLoader; - -import org.junit.BeforeClass; -import org.junit.Test; - -import de.dhbwstuttgart.core.JavaTXCompiler; - -public class GreaterEqualTest { - - private static String path; - private static File fileToTest; - private static JavaTXCompiler compiler; - private static ClassLoader loader; - private static Class classToTest; - private static String pathToClassFile; - private static Object instanceOfClass; - - @BeforeClass - public static void setUpBeforeClass() throws Exception { - path = System.getProperty("user.dir")+"/resources/bytecode/javFiles/GreaterEqual.jav"; - fileToTest = new File(path); - compiler = new JavaTXCompiler(fileToTest); - pathToClassFile = System.getProperty("user.dir")+"/resources/testBytecode/generatedBC/"; - compiler.generateBytecode(pathToClassFile); - loader = new URLClassLoader(new URL[] {new URL("File://"+pathToClassFile)}); - classToTest = loader.loadClass("GreaterEqual"); - instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); - } - - @Test - public void testName() { - assertEquals("GreaterEqual", classToTest.getName()); - } - @Test - public void testIntegers() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method gE = classToTest.getDeclaredMethod("gE", Integer.class, Integer.class); - Boolean result = (Boolean) gE.invoke(instanceOfClass, 7, 5); - assertTrue(result); - } - - @Test - public void testIntegers2() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method gE = classToTest.getDeclaredMethod("gE", Integer.class, Integer.class); - Boolean result = (Boolean) gE.invoke(instanceOfClass, 5, 7); - assertFalse(result); - } - - @Test - public void testEqIntegers() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method gE = classToTest.getDeclaredMethod("gE", Integer.class, Integer.class); - Boolean result = (Boolean) gE.invoke(instanceOfClass, 5, 5); - assertTrue(result); - } - - @Test - public void testLongs() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method gE = classToTest.getDeclaredMethod("gE", Long.class, Long.class); - Boolean result = (Boolean) gE.invoke(instanceOfClass, 10L,7L); - assertTrue(result); - } - - @Test - public void testFloats() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method gE = classToTest.getDeclaredMethod("gE", Float.class, Float.class); - Boolean result = (Boolean) gE.invoke(instanceOfClass, 5F,7F); - assertFalse(result); - } - - @Test - public void testDoubles() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method gE = classToTest.getDeclaredMethod("gE", Double.class, Double.class); - Boolean result = (Boolean) gE.invoke(instanceOfClass, 5.0,7.0); - assertFalse(result); - } - - @Test - public void testLongInt() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method gE = classToTest.getDeclaredMethod("gE", Long.class, Integer.class); - Boolean result = (Boolean) gE.invoke(instanceOfClass, 15L,7); - assertTrue(result); - } - - @Test - public void testFloatInt() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method gE = classToTest.getDeclaredMethod("gE", Float.class, Integer.class); - Boolean result = (Boolean) gE.invoke(instanceOfClass, 5F,7); - assertFalse(result); - } - - @Test - public void testDoubleInt() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method gE = classToTest.getDeclaredMethod("gE", Double.class, Integer.class); - Boolean result = (Boolean) gE.invoke(instanceOfClass, 25.0,17); - assertTrue(result); - } - - @Test - public void testFloatLong() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method gE = classToTest.getDeclaredMethod("gE", Float.class, Long.class); - Boolean result = (Boolean) gE.invoke(instanceOfClass, 75F,70L); - assertTrue(result); - } - - @Test - public void testDoubleLong() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method gE = classToTest.getDeclaredMethod("gE", Double.class, Long.class); - Boolean result = (Boolean) gE.invoke(instanceOfClass, 5.0,7L); - assertFalse(result); - } - - @Test - public void testEqDoubleFloat() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method gE = classToTest.getDeclaredMethod("gE", Double.class, Float.class); - Boolean result = (Boolean) gE.invoke(instanceOfClass, 7.0,7F); - assertTrue(result); - } - - @Test - public void testDoubleFloat() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method gE = classToTest.getDeclaredMethod("gE", Double.class, Float.class); - Boolean result = (Boolean) gE.invoke(instanceOfClass, 15.0,7F); - assertTrue(result); - } - - @Test - public void testDoubleFloat3() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method gE = classToTest.getDeclaredMethod("gE", Double.class, Float.class); - Boolean result = (Boolean) gE.invoke(instanceOfClass, 9.0,17F); - assertFalse(result); - } - -} diff --git a/src/test/java/bytecode/GreaterThanTest.java b/src/test/java/bytecode/GreaterThanTest.java deleted file mode 100644 index 001ebbc9..00000000 --- a/src/test/java/bytecode/GreaterThanTest.java +++ /dev/null @@ -1,139 +0,0 @@ -package bytecode; - -import static org.junit.Assert.*; - -import java.io.File; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.net.URL; -import java.net.URLClassLoader; - -import org.junit.BeforeClass; -import org.junit.Test; - -import de.dhbwstuttgart.core.JavaTXCompiler; - -public class GreaterThanTest { - - private static String path; - private static File fileToTest; - private static JavaTXCompiler compiler; - private static ClassLoader loader; - private static Class classToTest; - private static String pathToClassFile; - private static Object instanceOfClass; - - @BeforeClass - public static void setUpBeforeClass() throws Exception { - path = System.getProperty("user.dir")+"/resources/bytecode/javFiles/GreaterThan.jav"; - fileToTest = new File(path); - compiler = new JavaTXCompiler(fileToTest); - pathToClassFile = System.getProperty("user.dir")+"/resources/testBytecode/generatedBC/"; - compiler.generateBytecode(pathToClassFile); - loader = new URLClassLoader(new URL[] {new URL("File://"+pathToClassFile)}); - classToTest = loader.loadClass("GreaterThan"); - instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); - } - - @Test - public void testName() { - assertEquals("GreaterThan", classToTest.getName()); - } - - public void testIntegers() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method gT = classToTest.getDeclaredMethod("gT", Integer.class, Integer.class); - Boolean result = (Boolean) gT.invoke(instanceOfClass, 7, 5); - assertTrue(result); - } - - @Test - public void testIntegers2() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method gT = classToTest.getDeclaredMethod("gT", Integer.class, Integer.class); - Boolean result = (Boolean) gT.invoke(instanceOfClass, 5, 7); - assertFalse(result); - } - - @Test - public void testEqIntegers() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method gT = classToTest.getDeclaredMethod("gT", Integer.class, Integer.class); - Boolean result = (Boolean) gT.invoke(instanceOfClass, 5, 5); - assertFalse(result); - } - - @Test - public void testLongs() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method gT = classToTest.getDeclaredMethod("gT", Long.class, Long.class); - Boolean result = (Boolean) gT.invoke(instanceOfClass, 10L,7L); - assertTrue(result); - }@Test - - public void testFloats() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method gT = classToTest.getDeclaredMethod("gT", Float.class, Float.class); - Boolean result = (Boolean) gT.invoke(instanceOfClass, 5F,7F); - assertFalse(result); - } - - @Test - public void testDoubles() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method gT = classToTest.getDeclaredMethod("gT", Double.class, Double.class); - Boolean result = (Boolean) gT.invoke(instanceOfClass, 5.0,7.0); - assertFalse(result); - } - - @Test - public void testLongInt() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method gT = classToTest.getDeclaredMethod("gT", Long.class, Integer.class); - Boolean result = (Boolean) gT.invoke(instanceOfClass, 15L,7); - assertTrue(result); - } - - @Test - public void testFloatInt() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method gT = classToTest.getDeclaredMethod("gT", Float.class, Integer.class); - Boolean result = (Boolean) gT.invoke(instanceOfClass, 5F,7); - assertFalse(result); - } - - @Test - public void testDoubleInt() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method gT = classToTest.getDeclaredMethod("gT", Double.class, Integer.class); - Boolean result = (Boolean) gT.invoke(instanceOfClass, 25.0,17); - assertTrue(result); - } - - @Test - public void testFloatLong() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method gT = classToTest.getDeclaredMethod("gT", Float.class, Long.class); - Boolean result = (Boolean) gT.invoke(instanceOfClass, 75F,70L); - assertTrue(result); - } - - @Test - public void testDoubleLong() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method gT = classToTest.getDeclaredMethod("gT", Double.class, Long.class); - Boolean result = (Boolean) gT.invoke(instanceOfClass, 5.0,7L); - assertFalse(result); - } - - @Test - public void testEqDoubleFloat() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method gT = classToTest.getDeclaredMethod("gT", Double.class, Float.class); - Boolean result = (Boolean) gT.invoke(instanceOfClass, 7.0,7F); - assertFalse(result); - } - - @Test - public void testDoubleFloat() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method gT = classToTest.getDeclaredMethod("gT", Double.class, Float.class); - Boolean result = (Boolean) gT.invoke(instanceOfClass, 15.0,7F); - assertTrue(result); - } - - @Test - public void testDoubleFloat3() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method gT = classToTest.getDeclaredMethod("gT", Double.class, Float.class); - Boolean result = (Boolean) gT.invoke(instanceOfClass, 9.0,17F); - assertFalse(result); - } - -} diff --git a/src/test/java/bytecode/IdTest.java b/src/test/java/bytecode/IdTest.java deleted file mode 100644 index 6e252aed..00000000 --- a/src/test/java/bytecode/IdTest.java +++ /dev/null @@ -1,39 +0,0 @@ -package bytecode; - -import static org.junit.Assert.*; - -import java.io.File; -import java.lang.reflect.Field; -import java.net.URL; -import java.net.URLClassLoader; - -import org.junit.BeforeClass; - - -import de.dhbwstuttgart.core.JavaTXCompiler; -import org.junit.Test; - -public class IdTest { - - private static String path; - private static File fileToTest; - private static JavaTXCompiler compiler; - private static ClassLoader loader; - private static Class classToTest; - private static String pathToClassFile; - private static Object instanceOfClass; - - - @Test - public void test() throws Exception { - path = System.getProperty("user.dir")+"/resources/bytecode/javFiles/Id.jav"; - fileToTest = new File(path); - compiler = new JavaTXCompiler(fileToTest); - compiler.generateBytecode(System.getProperty("user.dir")+"/resources/testBytecode/generatedBC/"); - pathToClassFile = System.getProperty("user.dir")+"/resources/testBytecode/generatedBC/"; - loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); - classToTest = loader.loadClass("Id"); - instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); - } - -} diff --git a/src/test/java/bytecode/InfTest.java b/src/test/java/bytecode/InfTest.java deleted file mode 100644 index cc6a7a25..00000000 --- a/src/test/java/bytecode/InfTest.java +++ /dev/null @@ -1,37 +0,0 @@ -package bytecode; - -import static org.junit.Assert.*; - -import java.io.File; -import java.lang.reflect.Method; -import java.net.URL; -import java.net.URLClassLoader; - -import org.junit.BeforeClass; -import org.junit.Test; - -import de.dhbwstuttgart.core.JavaTXCompiler; - -public class InfTest { - - private static String path; - private static File fileToTest; - private static JavaTXCompiler compiler; - private static ClassLoader loader; - private static Class classToTest; - private static String pathToClassFile; - private static Object instanceOfClass; - - @Test - public void generateBC() throws Exception { - path = System.getProperty("user.dir")+"/resources/bytecode/javFiles/Inf.jav"; - fileToTest = new File(path); - compiler = new JavaTXCompiler(fileToTest); - pathToClassFile = System.getProperty("user.dir")+"/resources/testBytecode/generatedBC/"; - compiler.generateBytecode(pathToClassFile); - loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); - classToTest = loader.loadClass("Inf"); - instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); - } - -} diff --git a/src/test/java/bytecode/InheritTest.java b/src/test/java/bytecode/InheritTest.java deleted file mode 100644 index 74db5b85..00000000 --- a/src/test/java/bytecode/InheritTest.java +++ /dev/null @@ -1,193 +0,0 @@ -package bytecode; - -import static org.junit.Assert.*; - -import java.io.File; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.Field; -import java.net.MalformedURLException; -import java.net.URL; -import java.net.URLClassLoader; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Stack; -import java.util.Vector; -import java.util.stream.Collectors; - -import org.junit.BeforeClass; -import org.junit.Test; - -import com.google.common.collect.Lists; - -import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.GenericGenratorResultForSourceFile; -import de.dhbwstuttgart.core.JavaTXCompiler; -import de.dhbwstuttgart.typeinference.result.ResultSet; - -public class InheritTest { - private static String path; - private static File fileToTest; - private static JavaTXCompiler compiler; - private static ClassLoader loader; - private static Class classToTest; - private static Class classToTestAA, classToTestBB, classToTestCC, classToTestDD; - private static String pathToClassFile = System.getProperty("user.dir")+"/resources/bytecode/javFiles/";; - //private static String pathToClassFile1 = System.getProperty("user.dir") + "/resources/testBytecode/generatedBC/"; - private static Object instanceOfClass; - private static Object instanceOfClassAA, instanceOfClassBB, instanceOfClassCC, instanceOfClassDD; - private static HashMap, Method> hm = new HashMap<>(); - private static List typeinferenceResult; - private static List simplifyResultsForAllSourceFiles; - - @BeforeClass - public static void setUpBeforeClass() throws Exception { - path = System.getProperty("user.dir")+"/resources/bytecode/javFiles/AA.jav"; - fileToTest = new File(path); - compiler = new JavaTXCompiler(fileToTest); - List typeinferenceResult = compiler.typeInference(); - List simplifyResultsForAllSourceFiles = compiler.getGeneratedGenericResultsForAllSourceFiles(typeinferenceResult); - compiler.generateBytecode(new File(pathToClassFile),typeinferenceResult,simplifyResultsForAllSourceFiles); - loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); - classToTestAA = loader.loadClass("AA"); - instanceOfClassAA = classToTestAA.getDeclaredConstructor().newInstance(); - - - - path = System.getProperty("user.dir")+"/resources/bytecode/javFiles/BB.jav"; - fileToTest = new File(path); - compiler = new JavaTXCompiler(fileToTest); - typeinferenceResult = compiler.typeInference(); - simplifyResultsForAllSourceFiles = compiler.getGeneratedGenericResultsForAllSourceFiles(typeinferenceResult); - compiler.generateBytecode(new File(pathToClassFile),typeinferenceResult,simplifyResultsForAllSourceFiles); - classToTestBB = loader.loadClass("BB"); - instanceOfClassBB = classToTestBB.getDeclaredConstructor().newInstance(); - - path = System.getProperty("user.dir")+"/resources/bytecode/javFiles/CC.jav"; - fileToTest = new File(path); - compiler = new JavaTXCompiler(fileToTest); - typeinferenceResult = compiler.typeInference(); - simplifyResultsForAllSourceFiles = compiler.getGeneratedGenericResultsForAllSourceFiles(typeinferenceResult); - compiler.generateBytecode(new File(pathToClassFile),typeinferenceResult,simplifyResultsForAllSourceFiles); - classToTestCC = loader.loadClass("CC"); - instanceOfClassCC = classToTestCC.getDeclaredConstructor().newInstance(); - - path = System.getProperty("user.dir")+"/resources/bytecode/javFiles/DD.jav"; - fileToTest = new File(path); - compiler = new JavaTXCompiler(fileToTest); - typeinferenceResult = compiler.typeInference(); - simplifyResultsForAllSourceFiles = compiler.getGeneratedGenericResultsForAllSourceFiles(typeinferenceResult); - compiler.generateBytecode(new File(pathToClassFile),typeinferenceResult,simplifyResultsForAllSourceFiles); - classToTestDD = loader.loadClass("DD"); - instanceOfClassDD = classToTestDD.getDeclaredConstructor().newInstance(); - - - path = System.getProperty("user.dir")+"/resources/bytecode/javFiles/Inherit.jav"; - fileToTest = new File(path); - compiler = new JavaTXCompiler(fileToTest); - typeinferenceResult = compiler.typeInference(); - simplifyResultsForAllSourceFiles = compiler.getGeneratedGenericResultsForAllSourceFiles(typeinferenceResult); - compiler.generateBytecode(new File(pathToClassFile),typeinferenceResult,simplifyResultsForAllSourceFiles); - classToTest = loader.loadClass("Inherit"); - instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); - } - - @Test - public void testInheritClassName() { - assertEquals("Inherit", classToTest.getName()); - } - - - @Test - public void testAAName() { - assertEquals("AA", classToTestAA.getName()); - } - - @Test - public void testBBName() { - assertEquals("BB", classToTestBB.getName()); - } - - @Test - public void testCCName() { - assertEquals("CC", classToTestCC.getName()); - } - - @Test - public void testDDName() { - assertEquals("DD", classToTestDD.getName()); - } - - @Test - public void testmainAA() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException, MalformedURLException, ClassNotFoundException, NoSuchFieldException { - Method m = classToTestAA.getDeclaredMethod("m", Integer.class); - assertEquals(m.invoke(instanceOfClassAA, 5), "AA"); - Method main = classToTest.getDeclaredMethod("main", classToTestAA, Integer.class); - assertEquals(main.invoke(instanceOfClass, instanceOfClassAA, 5), "AA"); - } - - @Test - public void testmainBB() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException, MalformedURLException, ClassNotFoundException, NoSuchFieldException { - Method m = classToTestAA.getDeclaredMethod("m", Integer.class); - assertEquals(m.invoke(instanceOfClassBB, 5), "AA"); - Method main = classToTest.getDeclaredMethod("main", classToTestAA, Integer.class); - assertEquals(main.invoke(instanceOfClass, instanceOfClassBB, 5), "AA"); - } - - @Test - public void testmainCC() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException, MalformedURLException, ClassNotFoundException, NoSuchFieldException { - Method m = classToTestCC.getDeclaredMethod("m", Integer.class); - assertEquals(m.invoke(instanceOfClassCC, 5), "CC"); - Method main = classToTest.getDeclaredMethod("main", classToTestCC, Integer.class); - assertEquals(main.invoke(instanceOfClass, instanceOfClassCC, 5), "CC"); - } - - @Test - public void testmainDD() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException, MalformedURLException, ClassNotFoundException, NoSuchFieldException { - Method m = classToTestCC.getDeclaredMethod("m", Integer.class); - assertEquals(m.invoke(instanceOfClassDD, 5), "CC"); - Method main = classToTest.getDeclaredMethod("main", classToTestCC, Integer.class); - assertEquals(main.invoke(instanceOfClass, instanceOfClassDD, 5), "CC"); - } - - @Test - public void testmainVectorAA() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException, MalformedURLException, ClassNotFoundException, NoSuchFieldException { - Method m = classToTestAA.getDeclaredMethod("m", Integer.class); - assertEquals(m.invoke(instanceOfClassAA, 5), "AA"); - Vector v = new Vector<>(); - v.add(instanceOfClassAA); - Method main = classToTest.getDeclaredMethod("main", Vector.class, Integer.class); - assertEquals(main.invoke(instanceOfClass, v, 5), "AA"); - } - - @Test - public void testmainVectorBB() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException, MalformedURLException, ClassNotFoundException, NoSuchFieldException { - Method m = classToTestAA.getDeclaredMethod("m", Integer.class); - assertEquals(m.invoke(instanceOfClassBB, 5), "AA"); - Vector v = new Vector<>(); - v.add(instanceOfClassBB); - Method main = classToTest.getDeclaredMethod("main", Vector.class, Integer.class); - assertEquals(main.invoke(instanceOfClass, v, 5), "AA"); - } - - @Test - public void testmainVectorCC() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException, MalformedURLException, ClassNotFoundException, NoSuchFieldException { - Method m = classToTestCC.getDeclaredMethod("m", Integer.class); - assertEquals(m.invoke(instanceOfClassCC, 5), "CC"); - Vector v = new Vector<>(); - v.add(instanceOfClassCC); - Method main = classToTest.getDeclaredMethod("main", Vector.class, Integer.class); - assertEquals(main.invoke(instanceOfClass, v, 5), "CC"); - } - - @Test - public void testmainVectorDD() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException, MalformedURLException, ClassNotFoundException, NoSuchFieldException { - Method m = classToTestCC.getDeclaredMethod("m", Integer.class); - assertEquals(m.invoke(instanceOfClassDD, 5), "CC"); - Vector v = new Vector<>(); - v.add(instanceOfClassDD); - Method main = classToTest.getDeclaredMethod("main", Vector.class, Integer.class); - assertEquals(main.invoke(instanceOfClass, v, 5), "CC"); - } -} diff --git a/src/test/java/bytecode/InheritTest2.java b/src/test/java/bytecode/InheritTest2.java deleted file mode 100644 index 4d0c5d6c..00000000 --- a/src/test/java/bytecode/InheritTest2.java +++ /dev/null @@ -1,211 +0,0 @@ -package bytecode; - -import static org.junit.Assert.*; - -import java.io.File; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.Field; -import java.net.MalformedURLException; -import java.net.URL; -import java.net.URLClassLoader; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Stack; -import java.util.Vector; -import java.util.stream.Collectors; - -import org.junit.BeforeClass; -import org.junit.Test; - -import com.google.common.collect.Lists; - -import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.GenericGenratorResultForSourceFile; -import de.dhbwstuttgart.core.JavaTXCompiler; -import de.dhbwstuttgart.typeinference.result.ResultSet; - -public class InheritTest2 { - private static String path; - private static File fileToTest; - private static JavaTXCompiler compiler; - private static ClassLoader loader; - private static Class classToTest; - private static Class classToTestAA, classToTestBB, classToTestCC, classToTestDD; - private static String pathToClassFile = System.getProperty("user.dir")+"/resources/bytecode/javFiles/";; - //private static String pathToClassFile1 = System.getProperty("user.dir") + "/resources/testBytecode/generatedBC/"; - private static Object instanceOfClass; - private static Object instanceOfClassAA, instanceOfClassBB, instanceOfClassCC, instanceOfClassDD; - private static HashMap, Method> hm = new HashMap<>(); - private static List typeinferenceResult; - private static List simplifyResultsForAllSourceFiles; - - @BeforeClass - public static void setUpBeforeClass() throws Exception { - path = System.getProperty("user.dir")+"/resources/bytecode/javFiles/AA.jav"; - fileToTest = new File(path); - compiler = new JavaTXCompiler(fileToTest); - List typeinferenceResult = compiler.typeInference(); - List simplifyResultsForAllSourceFiles = compiler.getGeneratedGenericResultsForAllSourceFiles(typeinferenceResult); - compiler.generateBytecode(new File(pathToClassFile),typeinferenceResult,simplifyResultsForAllSourceFiles); - loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); - classToTestAA = loader.loadClass("AA"); - instanceOfClassAA = classToTestAA.getDeclaredConstructor().newInstance(); - - - - path = System.getProperty("user.dir")+"/resources/bytecode/javFiles/BB.jav"; - fileToTest = new File(path); - compiler = new JavaTXCompiler(fileToTest); - typeinferenceResult = compiler.typeInference(); - simplifyResultsForAllSourceFiles = compiler.getGeneratedGenericResultsForAllSourceFiles(typeinferenceResult); - compiler.generateBytecode(new File(pathToClassFile),typeinferenceResult,simplifyResultsForAllSourceFiles); - classToTestBB = loader.loadClass("BB"); - instanceOfClassBB = classToTestBB.getDeclaredConstructor().newInstance(); - - path = System.getProperty("user.dir")+"/resources/bytecode/javFiles/CC.jav"; - fileToTest = new File(path); - compiler = new JavaTXCompiler(fileToTest); - typeinferenceResult = compiler.typeInference(); - simplifyResultsForAllSourceFiles = compiler.getGeneratedGenericResultsForAllSourceFiles(typeinferenceResult); - compiler.generateBytecode(new File(pathToClassFile),typeinferenceResult,simplifyResultsForAllSourceFiles); - classToTestCC = loader.loadClass("CC"); - instanceOfClassCC = classToTestCC.getDeclaredConstructor().newInstance(); - - path = System.getProperty("user.dir")+"/resources/bytecode/javFiles/DD.jav"; - fileToTest = new File(path); - compiler = new JavaTXCompiler(fileToTest); - typeinferenceResult = compiler.typeInference(); - simplifyResultsForAllSourceFiles = compiler.getGeneratedGenericResultsForAllSourceFiles(typeinferenceResult); - compiler.generateBytecode(new File(pathToClassFile),typeinferenceResult,simplifyResultsForAllSourceFiles); - classToTestDD = loader.loadClass("DD"); - instanceOfClassDD = classToTestDD.getDeclaredConstructor().newInstance(); - - - path = System.getProperty("user.dir")+"/resources/bytecode/javFiles/Inherit2.jav"; - fileToTest = new File(path); - compiler = new JavaTXCompiler(fileToTest); - typeinferenceResult = compiler.typeInference(); - simplifyResultsForAllSourceFiles = compiler.getGeneratedGenericResultsForAllSourceFiles(typeinferenceResult); - compiler.generateBytecode(new File(pathToClassFile),typeinferenceResult,simplifyResultsForAllSourceFiles); - classToTest = loader.loadClass("Inherit2"); - instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); - } - - @Test - public void testInheritClassName() { - assertEquals("Inherit2", classToTest.getName()); - } - - - @Test - public void testAAName() { - assertEquals("AA", classToTestAA.getName()); - } - - @Test - public void testBBName() { - assertEquals("BB", classToTestBB.getName()); - } - - @Test - public void testCCName() { - assertEquals("CC", classToTestCC.getName()); - } - - @Test - public void testDDName() { - assertEquals("DD", classToTestDD.getName()); - } - - @Test - public void testmainAA() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException, MalformedURLException, ClassNotFoundException, NoSuchFieldException { - Method m2 = classToTestAA.getDeclaredMethod("m2", classToTestAA); - assertEquals(m2.invoke(instanceOfClassAA, instanceOfClassAA), "AA"); - Method main = classToTest.getDeclaredMethod("main", classToTestAA); - assertEquals(main.invoke(instanceOfClass, instanceOfClassAA), "AA"); - } - - @Test - public void testmainBB() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException, MalformedURLException, ClassNotFoundException, NoSuchFieldException { - Method m2 = classToTestAA.getDeclaredMethod("m2", classToTestAA); - assertEquals(m2.invoke(instanceOfClassAA, instanceOfClassAA), "AA"); - Method main = classToTest.getDeclaredMethod("main", classToTestAA); - assertEquals(main.invoke(instanceOfClass, instanceOfClassBB), "AA"); - } - - @Test - public void testmainCC() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException, MalformedURLException, ClassNotFoundException, NoSuchFieldException { - Method m2 = classToTestCC.getDeclaredMethod("m2", classToTestCC); - assertEquals(m2.invoke(instanceOfClassCC, instanceOfClassCC), "CC"); - Method main = classToTest.getDeclaredMethod("main", classToTestCC); - assertEquals(main.invoke(instanceOfClass, instanceOfClassCC), "CC"); - } - - @Test - public void testmainDD() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException, MalformedURLException, ClassNotFoundException, NoSuchFieldException { - Method m2 = classToTestCC.getDeclaredMethod("m2", classToTestCC); - assertEquals(m2.invoke(instanceOfClassCC, instanceOfClassCC), "CC"); - Method main = classToTest.getDeclaredMethod("main", classToTestCC); - assertEquals(main.invoke(instanceOfClass, instanceOfClassDD), "CC"); - } - - - //PL 2020-05-12: Die folgenden Test funktionieren erst, wenn Generics im Bytecode implementiert sind - @Test - public void testmainVectorAA() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException, MalformedURLException, ClassNotFoundException, NoSuchFieldException { - Method m2 = classToTestAA.getDeclaredMethod("m2", classToTestAA); - assertEquals(m2.invoke(instanceOfClassAA, instanceOfClassAA), "AA"); - Vector v = new Vector<>(); - v.add(instanceOfClassAA); - Method main = classToTest.getDeclaredMethod("main", Vector.class); - try { - assertEquals(main.invoke(instanceOfClass, v), "AA"); - } - catch (java.lang.reflect.InvocationTargetException e) { - testmainVectorCC(); - } - } - - @Test - public void testmainVectorBB() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException, MalformedURLException, ClassNotFoundException, NoSuchFieldException { - Method m2 = classToTestAA.getDeclaredMethod("m2", classToTestAA); - assertEquals(m2.invoke(instanceOfClassAA, instanceOfClassAA), "AA"); - Vector v = new Vector<>(); - v.add(instanceOfClassBB); - Method main = classToTest.getDeclaredMethod("main", Vector.class); - try { - assertEquals(main.invoke(instanceOfClass, v), "AA"); - } - catch (java.lang.reflect.InvocationTargetException e) { - testmainVectorCC(); - } - } - - @Test - public void testmainVectorCC() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException, MalformedURLException, ClassNotFoundException, NoSuchFieldException { - Method m2 = classToTestCC.getDeclaredMethod("m2", classToTestCC); - assertEquals(m2.invoke(instanceOfClassCC, instanceOfClassCC), "CC"); - Vector v = new Vector<>(); - v.add(instanceOfClassCC); - Method main = classToTest.getDeclaredMethod("main", Vector.class); - String erg; - assertEquals(erg= (String) main.invoke(instanceOfClass, v), - erg.equals("CC")? "CC": "AA"); - } - - @Test - public void testmainVectorDD() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException, MalformedURLException, ClassNotFoundException, NoSuchFieldException { - Method m2 = classToTestCC.getDeclaredMethod("m2", classToTestCC); - assertEquals(m2.invoke(instanceOfClassCC, instanceOfClassCC), "CC"); - Vector v = new Vector<>(); - v.add(instanceOfClassDD); - Method main = classToTest.getDeclaredMethod("main", Vector.class); - String erg; - assertEquals(erg= (String) main.invoke(instanceOfClass, v), - erg.equals("CC")? "CC": "AA"); - } - - -} diff --git a/src/test/java/bytecode/KompTphTest.java b/src/test/java/bytecode/KompTphTest.java deleted file mode 100644 index 0ecaed01..00000000 --- a/src/test/java/bytecode/KompTphTest.java +++ /dev/null @@ -1,37 +0,0 @@ -package bytecode; - -import static org.junit.Assert.*; - -import java.io.File; -import java.lang.reflect.Method; -import java.net.URL; -import java.net.URLClassLoader; - -import org.junit.BeforeClass; -import org.junit.Test; - -import de.dhbwstuttgart.core.JavaTXCompiler; - -public class KompTphTest { - - private static String path; - private static File fileToTest; - private static JavaTXCompiler compiler; - private static ClassLoader loader; - private static Class classToTest; - private static String pathToClassFile; - private static Object instanceOfClass; - - @Test - public void generateBC() throws Exception { - path = System.getProperty("user.dir")+"/resources/bytecode/javFiles/KompTph.jav"; - fileToTest = new File(path); - compiler = new JavaTXCompiler(fileToTest); - pathToClassFile = System.getProperty("user.dir")+"/resources/testBytecode/generatedBC/"; - compiler.generateBytecode(pathToClassFile); - loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); - classToTest = loader.loadClass("KompTph"); - instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); - } - -} diff --git a/src/test/java/bytecode/LambdaCapturetest.java b/src/test/java/bytecode/LambdaCapturetest.java deleted file mode 100644 index f3f5e341..00000000 --- a/src/test/java/bytecode/LambdaCapturetest.java +++ /dev/null @@ -1,43 +0,0 @@ -/** - * - */ -package bytecode; - -import static org.junit.Assert.*; - -import java.io.File; -import java.io.IOException; -import java.net.URL; -import java.net.URLClassLoader; - -import org.junit.BeforeClass; -import org.junit.Test; - -import de.dhbwstuttgart.core.JavaTXCompiler; - -/** - * @author fayez - * - */ -public class LambdaCapturetest { - private static String path; - private static File fileToTest; - private static JavaTXCompiler compiler; - private static ClassLoader loader; - private static Class classToTest; - private static String pathToClassFile; - private static Object instanceOfClass; - - @Test - public void generateBC() throws Exception { - path = System.getProperty("user.dir")+"/resources/bytecode/javFiles/LambdaCapture.jav"; - fileToTest = new File(path); - compiler = new JavaTXCompiler(fileToTest); - compiler.generateBytecode(System.getProperty("user.dir")+"/resources/testBytecode/generatedBC/"); - pathToClassFile = System.getProperty("user.dir")+"/resources/testBytecode/generatedBC/"; - loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); - classToTest = loader.loadClass("LambdaCapture"); - instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); - } - -} diff --git a/src/test/java/bytecode/LambdaTest.java b/src/test/java/bytecode/LambdaTest.java deleted file mode 100644 index 79665697..00000000 --- a/src/test/java/bytecode/LambdaTest.java +++ /dev/null @@ -1,50 +0,0 @@ -package bytecode; - -import static org.junit.Assert.assertEquals; - -import java.io.File; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.net.URL; -import java.net.URLClassLoader; - -import org.junit.Test; - -import de.dhbwstuttgart.core.JavaTXCompiler; - -public class LambdaTest { - private static String path; - private static File fileToTest; - private static JavaTXCompiler compiler; - private static ClassLoader loader; - private static Class classToTest; - private static String pathToClassFile; - private static Object instanceOfClass; - - @Test - public void generateBC() throws Exception { - path = System.getProperty("user.dir")+"/resources/bytecode/javFiles/Lambda.jav"; - fileToTest = new File(path); - compiler = new JavaTXCompiler(fileToTest); - compiler.generateBytecode(System.getProperty("user.dir")+"/resources/testBytecode/generatedBC/"); - pathToClassFile = System.getProperty("user.dir")+"/resources/testBytecode/generatedBC/"; - loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); - classToTest = loader.loadClass("Lambda"); - instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); - - Method m = classToTest.getDeclaredMethod("m"); - Class lambda = m.invoke(instanceOfClass).getClass(); - Method apply = lambda.getMethod("apply", Object.class); - - // Damit man auf die Methode zugreifen kann - apply.setAccessible(true); - - Integer i = 77; - System.out.println(m.invoke(instanceOfClass).toString()); - Integer result = (Integer) apply.invoke(m.invoke(instanceOfClass), i); - - assertEquals(i, result); - } - - -} diff --git a/src/test/java/bytecode/LambdaVoidTest.java b/src/test/java/bytecode/LambdaVoidTest.java deleted file mode 100644 index e2c09204..00000000 --- a/src/test/java/bytecode/LambdaVoidTest.java +++ /dev/null @@ -1,47 +0,0 @@ -package bytecode; - -import static org.junit.Assert.assertEquals; - -import java.io.File; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.net.URL; -import java.net.URLClassLoader; - -import org.junit.Test; - -import de.dhbwstuttgart.core.JavaTXCompiler; - -public class LambdaVoidTest { - private static String path; - private static File fileToTest; - private static JavaTXCompiler compiler; - private static ClassLoader loader; - private static Class classToTest; - private static String pathToClassFile; - private static Object instanceOfClass; - - @Test - public void generateBC() throws Exception { - path = System.getProperty("user.dir")+"/resources/bytecode/javFiles/Lambda.jav"; - fileToTest = new File(path); - compiler = new JavaTXCompiler(fileToTest); - compiler.generateBytecode(System.getProperty("user.dir")+"/resources/testBytecode/generatedBC/"); - pathToClassFile = System.getProperty("user.dir")+"/resources/testBytecode/generatedBC/"; - loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); - classToTest = loader.loadClass("Lambda"); - instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); - - Method m = classToTest.getDeclaredMethod("m"); - Class lambda = m.invoke(instanceOfClass).getClass(); - Method apply = lambda.getMethod("apply", Object.class); - - // Damit man auf die Methode zugreifen kann - apply.setAccessible(true); - - Integer i = 77; - apply.invoke(m.invoke(instanceOfClass), i); - } - - -} diff --git a/src/test/java/bytecode/LessEqualTest.java b/src/test/java/bytecode/LessEqualTest.java deleted file mode 100644 index ce2cc46c..00000000 --- a/src/test/java/bytecode/LessEqualTest.java +++ /dev/null @@ -1,133 +0,0 @@ -package bytecode; - -import static org.junit.Assert.*; - -import java.io.File; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.net.URL; -import java.net.URLClassLoader; - -import org.junit.BeforeClass; -import org.junit.Test; - -import de.dhbwstuttgart.core.JavaTXCompiler; - -public class LessEqualTest { - - private static String path; - private static File fileToTest; - private static JavaTXCompiler compiler; - private static ClassLoader loader; - private static Class classToTest; - private static String pathToClassFile; - private static Object instanceOfClass; - - @BeforeClass - public static void setUpBeforeClass() throws Exception { - path = System.getProperty("user.dir")+"/resources/bytecode/javFiles/LessEqual.jav"; - fileToTest = new File(path); - compiler = new JavaTXCompiler(fileToTest); - pathToClassFile = System.getProperty("user.dir")+"/resources/testBytecode/generatedBC/"; - compiler.generateBytecode(pathToClassFile); - loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); - classToTest = loader.loadClass("LessEqual"); - instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); - } - - @Test - public void testName() { - assertEquals("LessEqual", classToTest.getName()); - } - - @Test - public void testIntegers() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method lessEqual = classToTest.getDeclaredMethod("lessEqual", Integer.class, Integer.class); - Boolean result = (Boolean) lessEqual.invoke(instanceOfClass, 5,7); - assertTrue(result); - } - - @Test - public void testEqualIntegers() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method lessEqual = classToTest.getDeclaredMethod("lessEqual", Integer.class, Integer.class); - Boolean result = (Boolean) lessEqual.invoke(instanceOfClass, 5,5); - assertTrue(result); - } - - @Test - public void testLongs() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method lessEqual = classToTest.getDeclaredMethod("lessEqual", Long.class, Long.class); - Boolean result = (Boolean) lessEqual.invoke(instanceOfClass, 5L,7L); - assertTrue(result); - }@Test - - public void testFloats() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method lessEqual = classToTest.getDeclaredMethod("lessEqual", Float.class, Float.class); - Boolean result = (Boolean) lessEqual.invoke(instanceOfClass, 5F,7F); - assertTrue(result); - } - - @Test - public void testDoubles() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method lessEqual = classToTest.getDeclaredMethod("lessEqual", Double.class, Double.class); - Boolean result = (Boolean) lessEqual.invoke(instanceOfClass, 5.0,7.0); - assertTrue(result); - } - - @Test - public void testLongInt() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method lessEqual = classToTest.getDeclaredMethod("lessEqual", Long.class, Integer.class); - Boolean result = (Boolean) lessEqual.invoke(instanceOfClass, 5L,7); - assertTrue(result); - } - - @Test - public void testFloatInt() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method lessEqual = classToTest.getDeclaredMethod("lessEqual", Float.class, Integer.class); - Boolean result = (Boolean) lessEqual.invoke(instanceOfClass, 5F,7); - assertTrue(result); - } - - @Test - public void testDoubleInt() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method lessEqual = classToTest.getDeclaredMethod("lessEqual", Double.class, Integer.class); - Boolean result = (Boolean) lessEqual.invoke(instanceOfClass, 5.0,7); - assertTrue(result); - } - - @Test - public void testFloatLong() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method lessEqual = classToTest.getDeclaredMethod("lessEqual", Float.class, Long.class); - Boolean result = (Boolean) lessEqual.invoke(instanceOfClass, 5F,7L); - assertTrue(result); - } - - @Test - public void testDoubleLong() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method lessEqual = classToTest.getDeclaredMethod("lessEqual", Double.class, Long.class); - Boolean result = (Boolean) lessEqual.invoke(instanceOfClass, 5.0,7L); - assertTrue(result); - } - - @Test - public void testEqDoubleFloat() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method lessEqual = classToTest.getDeclaredMethod("lessEqual", Double.class, Float.class); - Boolean result = (Boolean) lessEqual.invoke(instanceOfClass, 7.0,7F); - assertTrue(result); - } - - @Test - public void testDoubleFloat() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method lessEqual = classToTest.getDeclaredMethod("lessEqual", Double.class, Float.class); - Boolean result = (Boolean) lessEqual.invoke(instanceOfClass, 5.0,7F); - assertTrue(result); - } - - @Test - public void testDoubleFloat3() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method lessEqual = classToTest.getDeclaredMethod("lessEqual", Double.class, Float.class); - Boolean result = (Boolean) lessEqual.invoke(instanceOfClass, 9.0,7F); - assertFalse(result); - } - -} diff --git a/src/test/java/bytecode/LessThanTest.java b/src/test/java/bytecode/LessThanTest.java deleted file mode 100644 index bdc6b8bd..00000000 --- a/src/test/java/bytecode/LessThanTest.java +++ /dev/null @@ -1,141 +0,0 @@ -package bytecode; - -import static org.junit.Assert.*; - -import java.io.File; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.net.URL; -import java.net.URLClassLoader; - -import org.junit.BeforeClass; -import org.junit.Test; - -import de.dhbwstuttgart.core.JavaTXCompiler; - -public class LessThanTest { - - private static String path; - private static File fileToTest; - private static JavaTXCompiler compiler; - private static ClassLoader loader; - private static Class classToTest; - private static String pathToClassFile; - private static Object instanceOfClass; - - @BeforeClass - public static void setUpBeforeClass() throws Exception { - path = System.getProperty("user.dir")+"/resources/bytecode/javFiles/LessThan.jav"; - fileToTest = new File(path); - compiler = new JavaTXCompiler(fileToTest); - pathToClassFile = System.getProperty("user.dir")+"/resources/testBytecode/generatedBC/"; - compiler.generateBytecode(pathToClassFile); - loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); - classToTest = loader.loadClass("LessThan"); - instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); - } - - @Test - public void testClassName() { - assertEquals("LessThan", classToTest.getName()); - } - - @Test - public void testLessThanInt() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method lessThan = classToTest.getDeclaredMethod("lessThan", Integer.class,Integer.class); - Boolean result = (Boolean) lessThan.invoke(instanceOfClass, 5, 7); - assertTrue(result); - } - - @Test - public void testLessThanInt2() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method lessThan = classToTest.getDeclaredMethod("lessThan", Integer.class, Integer.class); - Boolean result = (Boolean) lessThan.invoke(instanceOfClass, 7, 5); - assertFalse(result); - } - - @Test - public void testLessThanInt3() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method lessThan = classToTest.getDeclaredMethod("lessThan", Integer.class, Integer.class); - Boolean result = (Boolean) lessThan.invoke(instanceOfClass, 5, 5); - assertFalse(result); - } - - @Test - public void testLessThanLong() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method lessThan = classToTest.getDeclaredMethod("lessThan", Long.class,Long.class); - Boolean result = (Boolean) lessThan.invoke(instanceOfClass, 5L, 7L); - assertTrue(result); - } - - @Test - public void testLessThanLong2() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method lessThan = classToTest.getDeclaredMethod("lessThan", Long.class, Long.class); - Boolean result = (Boolean) lessThan.invoke(instanceOfClass, 7L, 5L); - assertFalse(result); - } - - @Test - public void testLessThanLong3() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method lessThan = classToTest.getDeclaredMethod("lessThan", Long.class, Long.class); - Boolean result = (Boolean) lessThan.invoke(instanceOfClass, 5L, 5L); - assertFalse(result); - } - - @Test - public void testLessThanFloat() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method lessThan = classToTest.getDeclaredMethod("lessThan", Float.class, Float.class); - Boolean result = (Boolean) lessThan.invoke(instanceOfClass, 7F, 5F); - assertFalse(result); - } - - @Test - public void testLessThanDouble() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method lessThan = classToTest.getDeclaredMethod("lessThan", Double.class, Double.class); - Boolean result = (Boolean) lessThan.invoke(instanceOfClass, 7.0, 5.0); - assertFalse(result); - } - - @Test - public void testLessThanLongInt() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method lessThan = classToTest.getDeclaredMethod("lessThan", Long.class, Integer.class); - Boolean result = (Boolean) lessThan.invoke(instanceOfClass, 7L, 5); - assertFalse(result); - } - - @Test - public void testLessThanFloatInt() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method lessThan = classToTest.getDeclaredMethod("lessThan", Float.class, Integer.class); - Boolean result = (Boolean) lessThan.invoke(instanceOfClass, 7F, 5); - assertFalse(result); - } - - @Test - public void testLessThanDoubleInt() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method lessThan = classToTest.getDeclaredMethod("lessThan", Double.class, Integer.class); - Boolean result = (Boolean) lessThan.invoke(instanceOfClass, 7.0, 5); - assertFalse(result); - } - - @Test - public void testLessThanFloatLong() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method lessThan = classToTest.getDeclaredMethod("lessThan", Float.class, Long.class); - Boolean result = (Boolean) lessThan.invoke(instanceOfClass, 7F, 5L); - assertFalse(result); - } - - @Test - public void testLessThanDoubleLong() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method lessThan = classToTest.getDeclaredMethod("lessThan", Double.class, Long.class); - Boolean result = (Boolean) lessThan.invoke(instanceOfClass, 7.0, 5L); - assertFalse(result); - } - - @Test - public void testLessThanDoubleFloat() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method lessThan = classToTest.getDeclaredMethod("lessThan", Double.class, Float.class); - Boolean result = (Boolean) lessThan.invoke(instanceOfClass, 7.0, 5F); - assertFalse(result); - } - -} diff --git a/src/test/java/bytecode/MatrixOpTest.java b/src/test/java/bytecode/MatrixOpTest.java deleted file mode 100644 index 01c12372..00000000 --- a/src/test/java/bytecode/MatrixOpTest.java +++ /dev/null @@ -1,102 +0,0 @@ -package bytecode; - -import static org.junit.Assert.*; - -import java.io.File; -import java.io.IOException; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.net.URL; -import java.net.URLClassLoader; -import java.util.Vector; - -import org.junit.BeforeClass; -import org.junit.Test; - -import de.dhbwstuttgart.core.JavaTXCompiler; - -public class MatrixOpTest { - private static String path; - private static File fileToTest; - private static JavaTXCompiler compiler; - private static ClassLoader loader; - private static Class classToTest; - private static String pathToClassFile; - private static Object instanceOfClass_m1; - private static Object instanceOfClass_m2; - private static Object instanceOfClass_m3; - - @Test - public void test() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, ClassNotFoundException, IOException, InstantiationException, NoSuchFieldException { - path = System.getProperty("user.dir") + "/resources/bytecode/javFiles/MatrixOP.jav"; - fileToTest = new File(path); - compiler = new JavaTXCompiler(fileToTest); - pathToClassFile = System.getProperty("user.dir") + "/resources/testBytecode/generatedBC/"; - compiler.generateBytecode(pathToClassFile); - 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> 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); - // 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); - - } - -} diff --git a/src/test/java/bytecode/MatrixTest.java b/src/test/java/bytecode/MatrixTest.java deleted file mode 100755 index 0689f490..00000000 --- a/src/test/java/bytecode/MatrixTest.java +++ /dev/null @@ -1,90 +0,0 @@ -package bytecode; - -import static org.junit.Assert.*; - -import java.io.File; -import java.io.IOException; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.net.URL; -import java.net.URLClassLoader; -import java.util.Vector; - -import org.junit.BeforeClass; -import org.junit.Test; - -import de.dhbwstuttgart.core.JavaTXCompiler; - -public class MatrixTest { - private static String path; - private static File fileToTest; - private static JavaTXCompiler compiler; - private static ClassLoader loader; - private static Class classToTest; - private static String pathToClassFile; - private static Object instanceOfClass_m1; - private static Object instanceOfClass_m2; - private static Object instanceOfClass_m3; - - @Test - public void test() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, ClassNotFoundException, IOException, InstantiationException { - path = System.getProperty("user.dir")+"/resources/bytecode/javFiles/Matrix.jav"; - fileToTest = new File(path); - compiler = new JavaTXCompiler(fileToTest); - pathToClassFile = System.getProperty("user.dir")+"/resources/testBytecode/generatedBC/"; - compiler.generateBytecode(pathToClassFile); - loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); - classToTest = loader.loadClass("Matrix"); - - 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> 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); - 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/MergeTest.java b/src/test/java/bytecode/MergeTest.java deleted file mode 100644 index b0bc9a89..00000000 --- a/src/test/java/bytecode/MergeTest.java +++ /dev/null @@ -1,41 +0,0 @@ -package bytecode; - - -import static org.junit.Assert.assertEquals; - -import java.io.File; -import java.lang.reflect.Method; -import java.net.URL; -import java.net.URLClassLoader; - -import org.junit.Test; - -import de.dhbwstuttgart.core.JavaTXCompiler; - -public class MergeTest { - private static String path; - private static File fileToTest; - private static JavaTXCompiler compiler; - private static ClassLoader loader; - private static Class classToTest; - private static String pathToClassFile; - private static Object instanceOfClass; - - - @Test - public void generateBC() throws Exception { - path = System.getProperty("user.dir")+"/resources/bytecode/javFiles/Merge.jav"; - fileToTest = new File(path); - compiler = new JavaTXCompiler(fileToTest); - compiler.generateBytecode(System.getProperty("user.dir")+"/resources/testBytecode/generatedBC/"); -// pathToClassFile = System.getProperty("user.dir")+"/testBytecode/generatedBC/"; -// loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); -// classToTest = loader.loadClass("Merge"); - //instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); - - //Method m = classToTest.getDeclaredMethod("m"); - //Object result = m.invoke(instanceOfClass); - - //assertEquals(result.getClass(), loader.loadClass("Apply")); - } -} diff --git a/src/test/java/bytecode/OLFun2Test.java b/src/test/java/bytecode/OLFun2Test.java deleted file mode 100644 index 6ec8701b..00000000 --- a/src/test/java/bytecode/OLFun2Test.java +++ /dev/null @@ -1,69 +0,0 @@ -package bytecode; - -import java.io.File; -import java.lang.reflect.Method; -import java.net.URL; -import java.net.URLClassLoader; -import java.util.function.Function; - -import general.TestCleanUp; -import org.junit.*; -import de.dhbwstuttgart.core.JavaTXCompiler; -import static org.junit.Assert.*; - -/** - * //ToDo Etienne: Beschreiben - * - * @since Studienarbeit Type Erasure - * @author etiennezink - */ -public class OLFun2Test { - private static String path; - private static File fileToTest; - private static JavaTXCompiler compiler; - private static ClassLoader loader; - private static Class classToTest; - private static Class classFun1IntInt; - private static Class classFun1DoubleDouble; - private static Class classFun1StringString; - - private static String generatedByteCodeDirectory = System.getProperty("user.dir") + "/src/test/resources/testBytecode/generatedBC/"; - - //ToDo Etienne: Nach Anpassung des Bytecode die Tests hinzufügen - //ToDo Etienne: Aufruf von m testen - @BeforeClass - public static void setUp() throws Exception { - path = System.getProperty("user.dir")+"/src/test/resources/bytecode/javFiles/OLFun2.jav"; - fileToTest = new File(path); - compiler = new JavaTXCompiler(fileToTest); - compiler.generateBytecode(generatedByteCodeDirectory); - loader = new URLClassLoader(new URL[] {new URL("file://"+generatedByteCodeDirectory)}); - classToTest = loader.loadClass("OLFun2"); - classFun1IntInt = loader.loadClass("Fun1$$Ljava$lang$Integer$_$Ljava$lang$Integer$_$"); - classFun1DoubleDouble = loader.loadClass("Fun1$$Ljava$lang$Double$_$Ljava$lang$Double$_$"); - classFun1StringString = loader.loadClass("Fun1$$Ljava$lang$String$_$Ljava$lang$String$_$"); - } - - @Test - public void mExistsWithInteger() throws Exception{ - Method m = classToTest.getDeclaredMethod("m", classFun1IntInt); - assertNotNull(m); - } - - @Test - public void mExistsWithDouble() throws Exception{ - Method m = classToTest.getDeclaredMethod("m", classFun1DoubleDouble); - assertNotNull(m); - } - - @Test - public void mExistsWithString() throws Exception{ - Method m = classToTest.getDeclaredMethod("m", classFun1StringString); - assertNotNull(m); - } - - //@AfterClass - public static void cleanUp(){ - TestCleanUp.cleanUpDirectory(new File(generatedByteCodeDirectory), f -> f.getName().contains(".class")); - } -} diff --git a/src/test/java/bytecode/OLFunTest.java b/src/test/java/bytecode/OLFunTest.java deleted file mode 100644 index d1910e07..00000000 --- a/src/test/java/bytecode/OLFunTest.java +++ /dev/null @@ -1,68 +0,0 @@ -package bytecode; - -import java.io.File; -import java.lang.reflect.Method; -import java.net.URL; -import java.net.URLClassLoader; - -import general.TestCleanUp; -import org.junit.*; -import de.dhbwstuttgart.core.JavaTXCompiler; -import static org.junit.Assert.*; - -/** - * //ToDo Etienne: Beschreiben - * - * @since Studienarbeit Type Erasure - * @author etiennezink - */ -public class OLFunTest { - private static String path; - private static File fileToTest; - private static JavaTXCompiler compiler; - private static ClassLoader loader; - private static Class classToTest; - private static Class classFun1IntInt; - private static Class classFun1DoubleDouble; - private static Class classFun1StringString; - - private static String generatedByteCodeDirectory = System.getProperty("user.dir") + "/src/test/resources/testBytecode/generatedBC/"; - - //ToDo Etienne: Nach Anpassung des Bytecode die Tests hinzufügen - //ToDo Etienne: Aufruf von m testen - @BeforeClass - public static void setUp() throws Exception { - path = System.getProperty("user.dir")+"/src/test/resources/bytecode/javFiles/OLFun.jav"; - fileToTest = new File(path); - compiler = new JavaTXCompiler(fileToTest); - compiler.generateBytecode(generatedByteCodeDirectory); - loader = new URLClassLoader(new URL[] {new URL("file://"+generatedByteCodeDirectory)}); - classToTest = loader.loadClass("OLFun"); - classFun1IntInt = loader.loadClass("Fun1$$Ljava$lang$Integer$_$Ljava$lang$Integer$_$"); - classFun1DoubleDouble = loader.loadClass("Fun1$$Ljava$lang$Double$_$Ljava$lang$Double$_$"); - classFun1StringString = loader.loadClass("Fun1$$Ljava$lang$String$_$Ljava$lang$String$_$"); - } - - @Test - public void mExistsWithInteger() throws Exception{ - Method m = classToTest.getDeclaredMethod("m", classFun1IntInt ,Integer.class); - assertNotNull(m); - } - - @Test - public void mExistsWithDouble() throws Exception{ - Method m = classToTest.getDeclaredMethod("m", classFun1DoubleDouble ,Double.class); - assertNotNull(m); - } - - @Test - public void mExistsWithString() throws Exception{ - Method m = classToTest.getDeclaredMethod("m", classFun1StringString ,String.class); - assertNotNull(m); - } - - //@AfterClass - public static void cleanUp(){ - TestCleanUp.cleanUpDirectory(new File(generatedByteCodeDirectory), f -> f.getName().contains(".class")); - } -} diff --git a/src/test/java/bytecode/OLTest.java b/src/test/java/bytecode/OLTest.java deleted file mode 100644 index 7cf2508f..00000000 --- a/src/test/java/bytecode/OLTest.java +++ /dev/null @@ -1,97 +0,0 @@ -package bytecode; - -import static org.junit.Assert.*; - -import java.io.File; -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.genericsGeneratorTypes.GenericGenratorResultForSourceFile; -import de.dhbwstuttgart.core.JavaTXCompiler; -import de.dhbwstuttgart.typeinference.result.ResultSet; - -public class OLTest { - private static String path; - private static File fileToTest; - private static JavaTXCompiler compiler; - private static ClassLoader loader; - private static Class classToTest; - private static Class classToTest1; - private static String pathToClassFile; - private static Object instanceOfClass; - private static Object instanceOfClass1; - - @BeforeClass - public static void setUpBeforeClass() throws Exception { - path = System.getProperty("user.dir")+"/resources/bytecode/javFiles/OL.jav"; - fileToTest = new File(path); - compiler = new JavaTXCompiler(fileToTest); - pathToClassFile = System.getProperty("user.dir")+"/resources/testBytecode/generatedBC/"; - List typeinferenceResult = compiler.typeInference(); - List simplifyResultsForAllSourceFiles = compiler.getGeneratedGenericResultsForAllSourceFiles(typeinferenceResult); - compiler.generateBytecode(new File(pathToClassFile),typeinferenceResult,simplifyResultsForAllSourceFiles); - loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); - classToTest = loader.loadClass("OL"); - instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); - classToTest1 = loader.loadClass("OLMain"); - instanceOfClass1 = classToTest1.getDeclaredConstructor().newInstance(); - } - - @Test - public void testOLClassName() { - assertEquals("OL", classToTest.getName()); - } - - @Test - public void testmInt() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method m = classToTest.getDeclaredMethod("m", Integer.class); - Integer result = (Integer) m.invoke(instanceOfClass, 5); - 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(new Double(10.0), result); - } - - @Test - public void testmString() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method m = classToTest.getDeclaredMethod("m", String.class); - String result = (String) m.invoke(instanceOfClass, "xxx"); - assertEquals("xxxxxx", result); - } - - @Test - public void testOLMainClassName() { - assertEquals("OLMain", classToTest1.getName()); - } - - @Test - public void testmainInt() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method main = classToTest1.getDeclaredMethod("main", Integer.class); - Integer result = (Integer) main.invoke(instanceOfClass1, 5); - 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(new Double(10.0), result); - } - - @Test - public void testmainString() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method main = classToTest1.getDeclaredMethod("main", String.class); - String result = (String) main.invoke(instanceOfClass1, "xxx"); - assertEquals("xxxxxx", result); - } -} diff --git a/src/test/java/bytecode/OpTest.java b/src/test/java/bytecode/OpTest.java deleted file mode 100644 index ce4d77df..00000000 --- a/src/test/java/bytecode/OpTest.java +++ /dev/null @@ -1,61 +0,0 @@ -package bytecode; - -import static org.junit.Assert.*; - -import java.io.File; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.net.URL; -import java.net.URLClassLoader; - -import org.junit.BeforeClass; -import org.junit.Test; -import org.objectweb.asm.Opcodes; - -import de.dhbwstuttgart.core.JavaTXCompiler; - -public class OpTest { - private static String path; - private static File fileToTest; - private static JavaTXCompiler compiler; - private static ClassLoader loader; - private static Class classToTest; - private static String pathToClassFile; - private static Object instanceOfClass; - - @BeforeClass - public static void setUpBeforeClass() throws Exception { - path = System.getProperty("user.dir")+"/resources/bytecode/javFiles/Op.jav"; - fileToTest = new File(path); - compiler = new JavaTXCompiler(fileToTest); - pathToClassFile = System.getProperty("user.dir")+"/resources/testBytecode/generatedBC/"; - compiler.generateBytecode(pathToClassFile); - loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); - classToTest = loader.loadClass("Op"); - instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); - } - - @Test - public void testAddString() throws NoSuchMethodException, SecurityException, IllegalAccessException, - IllegalArgumentException, InvocationTargetException, InstantiationException { - - Method m = classToTest.getDeclaredMethod("m", String.class,String.class); - - String result = (String) m.invoke(instanceOfClass, "Byte","Code"); - - assertEquals("ByteCode", result); - } - - @Test - public void testAddInt() throws NoSuchMethodException, SecurityException, IllegalAccessException, - IllegalArgumentException, InvocationTargetException, InstantiationException { - - Method m = classToTest.getDeclaredMethod("m", Integer.class,Integer.class); - - Integer result = (Integer) m.invoke(instanceOfClass, 7,3); - - assertEquals(new Integer(10), result); - } - - -} diff --git a/src/test/java/bytecode/OverloadingSortingTest.java b/src/test/java/bytecode/OverloadingSortingTest.java deleted file mode 100644 index c64f1f2a..00000000 --- a/src/test/java/bytecode/OverloadingSortingTest.java +++ /dev/null @@ -1,51 +0,0 @@ -package bytecode; - -import de.dhbwstuttgart.core.JavaTXCompiler; -import org.junit.BeforeClass; -import org.junit.Test; - -import java.io.File; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.net.URL; -import java.net.URLClassLoader; - -import static org.junit.Assert.assertEquals; - -public class OverloadingSortingTest { - private static String path; - private static File fileToTest; - private static JavaTXCompiler compiler; - private static ClassLoader loader; - private static Class classToTest; - private static String pathToClassFile; - private static Object instanceOfClass; - - private static Class classOL2; - private static Object instanceOfClassOL2; - - @Test - public void generateBC() throws Exception { - path = System.getProperty("user.dir")+"/resources/bytecode/javFiles/Sorting.jav"; - fileToTest = new File(path); - compiler = new JavaTXCompiler(fileToTest); - pathToClassFile = System.getProperty("user.dir")+"/resources/testBytecode/generatedBC/"; - compiler.generateBytecode(pathToClassFile); -// loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); -// classToTest = loader.loadClass("Sorting"); -// instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); - } - -// @Test -// public void test() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { -// Method meth = classToTest.getDeclaredMethod("merge", classToTest); -// } -// -// @Test -// public void test2() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { -// Method meth = classToTest.getDeclaredMethod("test", classOL2); -// String res = (String) meth.invoke(instanceOfClass, instanceOfClassOL2); -// assertEquals("Overloading2", res); -// } - -} diff --git a/src/test/java/bytecode/OverloadingTest.java b/src/test/java/bytecode/OverloadingTest.java deleted file mode 100644 index f93f0166..00000000 --- a/src/test/java/bytecode/OverloadingTest.java +++ /dev/null @@ -1,57 +0,0 @@ -package bytecode; - -import static org.junit.Assert.*; - -import java.io.File; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.net.URL; -import java.net.URLClassLoader; - -import org.junit.BeforeClass; -import org.junit.Test; - -import de.dhbwstuttgart.core.JavaTXCompiler; - -public class OverloadingTest { - private static String path; - private static File fileToTest; - private static JavaTXCompiler compiler; - private static ClassLoader loader; - private static Class classToTest; - private static String pathToClassFile; - private static Object instanceOfClass; - - private static Class classOL2; - private static Object instanceOfClassOL2; - - @BeforeClass - public static void setUpBeforeClass() throws Exception { - path = System.getProperty("user.dir")+"/resources/bytecode/javFiles/Overloading.jav"; - fileToTest = new File(path); - compiler = new JavaTXCompiler(fileToTest); - pathToClassFile = System.getProperty("user.dir")+"/resources/testBytecode/generatedBC/"; - compiler.generateBytecode(pathToClassFile); - loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); - classToTest = loader.loadClass("Overloading"); - instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); - - classOL2 = loader.loadClass("Overloading2"); - instanceOfClassOL2 = classOL2.getDeclaredConstructor().newInstance(); - } - - @Test - public void test() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method meth = classToTest.getDeclaredMethod("test", classToTest); - String res = (String) meth.invoke(instanceOfClass, instanceOfClass); - assertEquals("Overloading", res); - } - - @Test - public void test2() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method meth = classToTest.getDeclaredMethod("test", classOL2); - String res = (String) meth.invoke(instanceOfClass, instanceOfClassOL2); - assertEquals("Overloading2", res); - } - -} diff --git a/src/test/java/bytecode/PlusTest.java b/src/test/java/bytecode/PlusTest.java deleted file mode 100644 index a11d505e..00000000 --- a/src/test/java/bytecode/PlusTest.java +++ /dev/null @@ -1,53 +0,0 @@ -package bytecode; - -import static org.junit.Assert.*; - -import java.io.File; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.net.URL; -import java.net.URLClassLoader; - -import org.junit.BeforeClass; -import org.junit.Test; - -import de.dhbwstuttgart.core.JavaTXCompiler; - -public class PlusTest { - private static String path; - private static File fileToTest; - private static JavaTXCompiler compiler; - private static ClassLoader loader; - private static Class classToTest; - private static String pathToClassFile; - private static Object instanceOfClass; - - @BeforeClass - public static void setUpBeforeClass() throws Exception { - path = System.getProperty("user.dir")+"/resources/bytecode/javFiles/Plus.jav"; - fileToTest = new File(path); - compiler = new JavaTXCompiler(fileToTest); - pathToClassFile = System.getProperty("user.dir")+"/resources/testBytecode/generatedBC/"; - compiler.generateBytecode(pathToClassFile); - loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); - classToTest = loader.loadClass("Plus"); - instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); - } - - @Test - public void testAddInt() throws NoSuchMethodException, SecurityException, IllegalAccessException, - IllegalArgumentException, InvocationTargetException, InstantiationException { - Method addInt = classToTest.getDeclaredMethod("m", Integer.class,Integer.class); - Number result = (Number) addInt.invoke(instanceOfClass, 7,3); - assertEquals(10, result); - } - - @Test - public void testAddString() throws NoSuchMethodException, SecurityException, IllegalAccessException, - IllegalArgumentException, InvocationTargetException, InstantiationException { - Method addString = classToTest.getDeclaredMethod("m", String.class,String.class); - String result = (String) addString.invoke(instanceOfClass, "Byte","Code"); - assertEquals("ByteCode", result); - } - -} diff --git a/src/test/java/bytecode/PostIncTest.java b/src/test/java/bytecode/PostIncTest.java deleted file mode 100644 index 9ecabd23..00000000 --- a/src/test/java/bytecode/PostIncTest.java +++ /dev/null @@ -1,65 +0,0 @@ -package bytecode; - -import static org.junit.Assert.*; - -import java.io.File; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.net.URL; -import java.net.URLClassLoader; - -import org.junit.BeforeClass; -import org.junit.Test; - -import de.dhbwstuttgart.core.JavaTXCompiler; - -public class PostIncTest { - private static String path; - private static File fileToTest; - private static JavaTXCompiler compiler; - private static ClassLoader loader; - private static Class classToTest; - private static String pathToClassFile; - private static Object instanceOfClass; - - @BeforeClass - public static void setUpBeforeClass() throws Exception { - path = System.getProperty("user.dir")+"/resources/bytecode/javFiles/PostIncDec.jav"; - fileToTest = new File(path); - compiler = new JavaTXCompiler(fileToTest); - pathToClassFile = System.getProperty("user.dir")+"/resources/testBytecode/generatedBC/"; - compiler.generateBytecode(pathToClassFile); - loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); - classToTest = loader.loadClass("PostIncDec"); - instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); - } - - @Test - public void testM1() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method m = classToTest.getDeclaredMethod("m"); - Integer res = (Integer) m.invoke(instanceOfClass); - 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(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(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(new Integer(0), res); - } - -} diff --git a/src/test/java/bytecode/PreIncTest.java b/src/test/java/bytecode/PreIncTest.java deleted file mode 100644 index 3c30e27f..00000000 --- a/src/test/java/bytecode/PreIncTest.java +++ /dev/null @@ -1,65 +0,0 @@ -package bytecode; - -import static org.junit.Assert.*; - -import java.io.File; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.net.URL; -import java.net.URLClassLoader; - -import org.junit.BeforeClass; -import org.junit.Test; - -import de.dhbwstuttgart.core.JavaTXCompiler; - -public class PreIncTest { - private static String path; - private static File fileToTest; - private static JavaTXCompiler compiler; - private static ClassLoader loader; - private static Class classToTest; - private static String pathToClassFile; - private static Object instanceOfClass; - - @BeforeClass - public static void setUpBeforeClass() throws Exception { - path = System.getProperty("user.dir")+"/resources/bytecode/javFiles/PreInc.jav"; - fileToTest = new File(path); - compiler = new JavaTXCompiler(fileToTest); - pathToClassFile = System.getProperty("user.dir")+"/resources/testBytecode/generatedBC/"; - compiler.generateBytecode(pathToClassFile); - loader = new URLClassLoader(new URL[] {new URL("file://" + pathToClassFile)}); - classToTest = loader.loadClass("PreInc"); - instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); - } - - @Test - public void testM() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method m = classToTest.getDeclaredMethod("m"); - Integer res = (Integer) m.invoke(instanceOfClass); - 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(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(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(new Integer(-1), res); - } - -} diff --git a/src/test/java/bytecode/PutTest.java b/src/test/java/bytecode/PutTest.java deleted file mode 100644 index cf3e83d3..00000000 --- a/src/test/java/bytecode/PutTest.java +++ /dev/null @@ -1,86 +0,0 @@ -package bytecode; - -import static org.junit.Assert.*; - -import java.io.File; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.net.URL; -import java.net.URLClassLoader; -import java.util.List; -import java.util.Stack; -import java.util.Vector; - -import org.junit.BeforeClass; -import org.junit.Test; - -import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.GenericGenratorResultForSourceFile; -import de.dhbwstuttgart.core.JavaTXCompiler; -import de.dhbwstuttgart.typeinference.result.ResultSet; - -public class PutTest { - private static String path; - private static File fileToTest; - private static JavaTXCompiler compiler; - private static ClassLoader loader; - private static Class classToTest; - private static Class classToTest1; - private static String pathToClassFile; - private static Object instanceOfClass; - private static Object instanceOfClass1; - - @BeforeClass - public static void setUpBeforeClass() throws Exception { - path = System.getProperty("user.dir")+"/resources/bytecode/javFiles/Put.jav"; - fileToTest = new File(path); - compiler = new JavaTXCompiler(fileToTest); - pathToClassFile = System.getProperty("user.dir")+"/resources/testBytecode/generatedBC/"; - List typeinferenceResult = compiler.typeInference(); - List simplifyResultsForAllSourceFiles = compiler.getGeneratedGenericResultsForAllSourceFiles(typeinferenceResult); - compiler.generateBytecode(new File(pathToClassFile),typeinferenceResult,simplifyResultsForAllSourceFiles); - loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); - classToTest = loader.loadClass("Put"); - instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); - } - - @Test - public void testPutClassName() { - assertEquals("Put", classToTest.getName()); - } - - @Test - public void testPutElementVector() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method m = classToTest.getDeclaredMethod("putElement", Object.class, Vector.class); - Vector v_invoke = new Vector<>(); - m.invoke(instanceOfClass, 5, v_invoke); - Vector v = new Vector<>(); - v.add(5); - assertEquals(v, v_invoke); - } - - @Test - public void testPutElementStack() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method m = classToTest.getDeclaredMethod("putElement", Object.class, Stack.class); - Stack s_invoke = new Stack<>(); - m.invoke(instanceOfClass, 5, s_invoke); - assertEquals(new Integer(5), s_invoke.pop()); - } - - @Test - public void testMainVector() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method m = classToTest.getDeclaredMethod("main", Object.class, Vector.class); - Vector v_invoke = new Vector<>(); - m.invoke(instanceOfClass, 6, v_invoke); - Vector v = new Vector<>(); - v.add(6); - assertEquals(v, v_invoke); - } - - @Test - public void testMainStack() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method m = classToTest.getDeclaredMethod("main", Object.class, Stack.class); - Stack s_invoke = new Stack<>(); - m.invoke(instanceOfClass, 6, s_invoke); - assertEquals(new Integer(6), s_invoke.pop()); - } -} diff --git a/src/test/java/bytecode/RelOpsTest.java b/src/test/java/bytecode/RelOpsTest.java deleted file mode 100644 index 52774327..00000000 --- a/src/test/java/bytecode/RelOpsTest.java +++ /dev/null @@ -1,44 +0,0 @@ -package bytecode; - -import static org.junit.Assert.*; - -import java.io.File; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.net.URL; -import java.net.URLClassLoader; - -import org.junit.BeforeClass; -import org.junit.Test; - -import de.dhbwstuttgart.core.JavaTXCompiler; - -public class RelOpsTest { - private static String path; - private static File fileToTest; - private static JavaTXCompiler compiler; - private static ClassLoader loader; - private static Class classToTest; - private static String pathToClassFile; - private static Object instanceOfClass; - - @BeforeClass - public static void setUpBeforeClass() throws Exception { - path = System.getProperty("user.dir")+"/resources/bytecode/javFiles/RelOps.jav"; - fileToTest = new File(path); - compiler = new JavaTXCompiler(fileToTest); - pathToClassFile = System.getProperty("user.dir")+"/resources/testBytecode/generatedBC/"; - compiler.generateBytecode(pathToClassFile); - loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); - classToTest = loader.loadClass("RelOps"); - instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); - } - - @Test - public void test() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method m = classToTest.getDeclaredMethod("m", Integer.class,Integer.class); - Boolean result = (Boolean) m.invoke(instanceOfClass, 7,3); - assertFalse(result); - } - -} diff --git a/src/test/java/bytecode/SimpleCycleTest.java b/src/test/java/bytecode/SimpleCycleTest.java deleted file mode 100644 index 45a63e44..00000000 --- a/src/test/java/bytecode/SimpleCycleTest.java +++ /dev/null @@ -1,38 +0,0 @@ -package bytecode; - -import static org.junit.Assert.*; - -import java.io.File; -import java.lang.reflect.Method; -import java.net.URL; -import java.net.URLClassLoader; - -import org.junit.BeforeClass; -import org.junit.Test; - -import de.dhbwstuttgart.core.JavaTXCompiler; - -public class SimpleCycleTest { - - private static String path; - private static File fileToTest; - private static JavaTXCompiler compiler; - private static ClassLoader loader; - private static Class classToTest; - private static String pathToClassFile; - private static Object instanceOfClass; - - @Test - public void generateGen() throws Exception { - path = System.getProperty("user.dir")+"/resources/bytecode/javFiles/SimpleCycle.jav"; - fileToTest = new File(path); - compiler = new JavaTXCompiler(fileToTest); - pathToClassFile = System.getProperty("user.dir")+"/resources/testBytecode/generatedBC/"; - compiler.generateBytecode(pathToClassFile); - loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); - classToTest = loader.loadClass("SimpleCycle"); - instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); - } - - -} diff --git a/src/test/java/bytecode/SortingTest.java b/src/test/java/bytecode/SortingTest.java deleted file mode 100644 index 9220bb81..00000000 --- a/src/test/java/bytecode/SortingTest.java +++ /dev/null @@ -1,52 +0,0 @@ -package bytecode; - -import static org.junit.Assert.assertEquals; - -import java.io.File; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.net.URL; -import java.net.URLClassLoader; - -import org.junit.Test; - -import de.dhbwstuttgart.core.JavaTXCompiler; - -public class SortingTest { - private static String path; - private static File fileToTest; - private static JavaTXCompiler compiler; - private static ClassLoader loader; - private static Class classToTest; - private static String pathToClassFile; - private static Object instanceOfClass; - - @Test - public void generateBC() throws Exception { - path = System.getProperty("user.dir")+"/resources/bytecode/javFiles/Sorting.jav"; - fileToTest = new File(path); - compiler = new JavaTXCompiler(fileToTest); - compiler.generateBytecode(System.getProperty("user.dir")+"/resources/testBytecode/generatedBC/"); - pathToClassFile = System.getProperty("user.dir")+"/resources/testBytecode/generatedBC/"; - loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); - classToTest = loader.loadClass("Sorting"); - /* - instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); - - Method m = classToTest.getDeclaredMethod("m"); - Class lambda = m.invoke(instanceOfClass).getClass(); - Method apply = lambda.getMethod("apply", Object.class); - - // Damit man auf die Methode zugreifen kann - apply.setAccessible(true); - - Integer i = 77; - - Integer result = (Integer) apply.invoke(m.invoke(instanceOfClass), i); - - assertEquals(77, result); - */ - } - - -} diff --git a/src/test/java/bytecode/SubMatTest.java b/src/test/java/bytecode/SubMatTest.java deleted file mode 100644 index e3988697..00000000 --- a/src/test/java/bytecode/SubMatTest.java +++ /dev/null @@ -1,27 +0,0 @@ -package bytecode; - -import static org.junit.Assert.*; - -import java.io.File; -import java.io.IOException; - -import org.junit.Test; - -import de.dhbwstuttgart.core.JavaTXCompiler; - -public class SubMatTest { - private static String path; - private static File fileToTest; - private static JavaTXCompiler compiler; - private static String pathToClassFile; - - @Test - public void test() throws ClassNotFoundException, IOException { - path = System.getProperty("user.dir")+"/resources/bytecode/javFiles/SubMatrix.jav"; - fileToTest = new File(path); - compiler = new JavaTXCompiler(fileToTest); - pathToClassFile = System.getProperty("user.dir")+"/resources/testBytecode/generatedBC/"; - compiler.generateBytecode(pathToClassFile); - } - -} diff --git a/src/test/java/bytecode/Tph2Test.java b/src/test/java/bytecode/Tph2Test.java deleted file mode 100644 index a6acf5b2..00000000 --- a/src/test/java/bytecode/Tph2Test.java +++ /dev/null @@ -1,69 +0,0 @@ -package bytecode; - -import static org.junit.Assert.*; - -import java.io.File; -import java.lang.reflect.Method; -import java.net.URL; -import java.net.URLClassLoader; - -import org.junit.BeforeClass; -import org.junit.Test; - -import de.dhbwstuttgart.core.JavaTXCompiler; - -public class Tph2Test { - - private static String path; - private static File fileToTest; - private static JavaTXCompiler compiler; - private static ClassLoader loader; - private static Class classToTest; - private static String pathToClassFile; - private static Object instanceOfClass; - - @BeforeClass - public static void setUpBeforeClass() throws Exception { - path = System.getProperty("user.dir")+"/resources/bytecode/javFiles/Tph2.jav"; - fileToTest = new File(path); - compiler = new JavaTXCompiler(fileToTest); - pathToClassFile = System.getProperty("user.dir")+"/resources/testBytecode/generatedBC/"; - compiler.generateBytecode(pathToClassFile); - loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); - classToTest = loader.loadClass("Tph2"); - instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); - } - - @Test - public void test1() throws Exception { - Method m = classToTest.getDeclaredMethod("m", Object.class, Object.class); - Object result = m.invoke(instanceOfClass, 1,2); - - assertEquals(1,result); - } - - @Test - public void test2() throws Exception { - Method m = classToTest.getDeclaredMethod("m", Object.class, Object.class); - Object result = m.invoke(instanceOfClass, "sss",2); - - assertEquals("sss",result); - } - - @Test - public void test3() throws Exception { - Method m = classToTest.getDeclaredMethod("m2", Object.class, Object.class); - Object result = m.invoke(instanceOfClass, 1,2); - - assertEquals(2,result); - } - - @Test - public void test4() throws Exception { - Method m = classToTest.getDeclaredMethod("m2", Object.class, Object.class); - Object result = m.invoke(instanceOfClass, 1,"xxx"); - - assertEquals("xxx",result); - } - -} diff --git a/src/test/java/bytecode/Tph3Test.java b/src/test/java/bytecode/Tph3Test.java deleted file mode 100644 index ba76e3c0..00000000 --- a/src/test/java/bytecode/Tph3Test.java +++ /dev/null @@ -1,31 +0,0 @@ -package bytecode; - -import static org.junit.Assert.*; - -import java.io.File; -import java.lang.reflect.Method; -import java.net.URL; -import java.net.URLClassLoader; - -import org.junit.BeforeClass; -import org.junit.Test; - -import de.dhbwstuttgart.core.JavaTXCompiler; - -public class Tph3Test { - - private static String path; - private static File fileToTest; - private static JavaTXCompiler compiler; - private static String pathToClassFile; - - @Test - public void generateBC() throws Exception { - path = System.getProperty("user.dir")+"/resources/bytecode/javFiles/Tph3.jav"; - fileToTest = new File(path); - compiler = new JavaTXCompiler(fileToTest); - pathToClassFile = System.getProperty("user.dir")+"/resources/testBytecode/generatedBC/"; - compiler.generateBytecode(pathToClassFile); - } - -} diff --git a/src/test/java/bytecode/Tph5Test.java b/src/test/java/bytecode/Tph5Test.java deleted file mode 100644 index de028469..00000000 --- a/src/test/java/bytecode/Tph5Test.java +++ /dev/null @@ -1,45 +0,0 @@ -package bytecode; - -import static org.junit.Assert.*; - -import java.io.File; -import java.lang.reflect.Method; -import java.net.URL; -import java.net.URLClassLoader; - -import org.junit.BeforeClass; -import org.junit.Test; - -import de.dhbwstuttgart.core.JavaTXCompiler; - -public class Tph5Test { - - private static String path; - private static File fileToTest; - private static JavaTXCompiler compiler; - private static ClassLoader loader; - private static Class classToTest; - private static String pathToClassFile; - private static Object instanceOfClass; - - @BeforeClass - public static void setUpBeforeClass() throws Exception { - path = System.getProperty("user.dir")+"/resources/bytecode/javFiles/Tph5.jav"; - fileToTest = new File(path); - compiler = new JavaTXCompiler(fileToTest); - pathToClassFile = System.getProperty("user.dir")+"/resources/testBytecode/generatedBC/"; - compiler.generateBytecode(pathToClassFile); - loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); - classToTest = loader.loadClass("Tph5"); - instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); - } - - @Test - public void test() throws Exception { -// Method m = classToTest.getDeclaredMethod("m", Object.class, Object.class, Object.class); - Method m = classToTest.getDeclaredMethod("m", Object.class, Object.class); -// Object result = m.invoke(instanceOfClass, "xx",2,3); - - //assertEquals(2,result); - } -} diff --git a/src/test/java/bytecode/Tph6Test.java b/src/test/java/bytecode/Tph6Test.java deleted file mode 100644 index 39580320..00000000 --- a/src/test/java/bytecode/Tph6Test.java +++ /dev/null @@ -1,45 +0,0 @@ -package bytecode; - -import static org.junit.Assert.*; - -import java.io.File; -import java.lang.reflect.Method; -import java.net.URL; -import java.net.URLClassLoader; - -import org.junit.BeforeClass; -import org.junit.Test; - -import de.dhbwstuttgart.core.JavaTXCompiler; - -public class Tph6Test { - - private static String path; - private static File fileToTest; - private static JavaTXCompiler compiler; - private static ClassLoader loader; - private static Class classToTest; - private static String pathToClassFile; - private static Object instanceOfClass; - - @BeforeClass - public static void setUpBeforeClass() throws Exception { - path = System.getProperty("user.dir")+"/resources/bytecode/javFiles/Tph6.jav"; - fileToTest = new File(path); - compiler = new JavaTXCompiler(fileToTest); - pathToClassFile = System.getProperty("user.dir")+"/resources/testBytecode/generatedBC/"; - compiler.generateBytecode(pathToClassFile); - loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); - classToTest = loader.loadClass("Tph6"); - instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); - } - - @Test - public void test() throws Exception { -// Method m = classToTest.getDeclaredMethod("m", Object.class, Object.class, Object.class); - Method m = classToTest.getDeclaredMethod("m", Object.class, Object.class); -// Object result = m.invoke(instanceOfClass, "xx",2,3); - - //assertEquals(2,result); - } -} diff --git a/src/test/java/bytecode/TphTest.java b/src/test/java/bytecode/TphTest.java deleted file mode 100644 index 6effa069..00000000 --- a/src/test/java/bytecode/TphTest.java +++ /dev/null @@ -1,69 +0,0 @@ -package bytecode; - -import static org.junit.Assert.*; - -import java.io.File; -import java.lang.reflect.Method; -import java.net.URL; -import java.net.URLClassLoader; - -import org.junit.BeforeClass; -import org.junit.Test; - -import de.dhbwstuttgart.core.JavaTXCompiler; - -public class TphTest { - - private static String path; - private static File fileToTest; - private static JavaTXCompiler compiler; - private static ClassLoader loader; - private static Class classToTest; - private static String pathToClassFile; - private static Object instanceOfClass; - - @BeforeClass - public static void setUpBeforeClass() throws Exception { - path = System.getProperty("user.dir")+"/resources/bytecode/javFiles/Tph.jav"; - fileToTest = new File(path); - compiler = new JavaTXCompiler(fileToTest); - pathToClassFile = System.getProperty("user.dir")+"/resources/testBytecode/generatedBC/"; - compiler.generateBytecode(pathToClassFile); - loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); - classToTest = loader.loadClass("Tph"); - instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); - } - - @Test - public void test1() throws Exception { - Method m = classToTest.getDeclaredMethod("m", Object.class, Object.class); - Object result = m.invoke(instanceOfClass, 1,2); - - assertEquals(1,result); - } - - @Test - public void test2() throws Exception { - Method m = classToTest.getDeclaredMethod("m", Object.class, Object.class); - Object result = m.invoke(instanceOfClass, 1, "sss"); - - assertEquals(1,result); - } - - @Test - public void test3() throws Exception { - Method m = classToTest.getDeclaredMethod("m2", Object.class); - Object result = m.invoke(instanceOfClass, 2); - - assertEquals(2,result); - } - - @Test - public void test4() throws Exception { - Method m = classToTest.getDeclaredMethod("m2", Object.class); - Object result = m.invoke(instanceOfClass,"xxx"); - - assertEquals("xxx",result); - } - -} diff --git a/src/test/java/bytecode/TypedIDTest.java b/src/test/java/bytecode/TypedIDTest.java deleted file mode 100644 index 99a9995f..00000000 --- a/src/test/java/bytecode/TypedIDTest.java +++ /dev/null @@ -1,38 +0,0 @@ -package bytecode; - -import static org.junit.Assert.*; - -import java.io.File; -import java.lang.reflect.Field; -import java.net.URL; -import java.net.URLClassLoader; - -import org.junit.BeforeClass; -import org.junit.Test; - -import de.dhbwstuttgart.core.JavaTXCompiler; - -public class TypedIDTest { - - private static String path; - private static File fileToTest; - private static JavaTXCompiler compiler; - private static ClassLoader loader; - private static Class classToTest; - private static String pathToClassFile; - private static Object instanceOfClass; - - - @Test - public void test() throws Exception { - path = System.getProperty("user.dir")+"/resources/bytecode/javFiles/TypedID.jav"; - fileToTest = new File(path); - compiler = new JavaTXCompiler(fileToTest); - compiler.generateBytecode(System.getProperty("user.dir")+"/resources/testBytecode/generatedBC/"); - pathToClassFile = System.getProperty("user.dir")+"/resources/testBytecode/generatedBC/"; - loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); - classToTest = loader.loadClass("TypedID"); - instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); - } - -} diff --git a/src/test/java/bytecode/VectorAddTest.java b/src/test/java/bytecode/VectorAddTest.java deleted file mode 100644 index 120bd7a0..00000000 --- a/src/test/java/bytecode/VectorAddTest.java +++ /dev/null @@ -1,38 +0,0 @@ -package bytecode; - -import static org.junit.Assert.*; - -import java.io.File; -import java.lang.reflect.Method; -import java.net.URL; -import java.net.URLClassLoader; -import java.util.Vector; - -import org.junit.BeforeClass; -import org.junit.Test; - -import de.dhbwstuttgart.core.JavaTXCompiler; - -public class VectorAddTest { - - private static String path; - private static File fileToTest; - private static JavaTXCompiler compiler; - private static ClassLoader loader; - private static Class classToTest; - private static String pathToClassFile; - private static Object instanceOfClass; - - @Test - public void test() throws Exception { - path = System.getProperty("user.dir")+"/resources/bytecode/javFiles/VectorAdd.jav"; - fileToTest = new File(path); - compiler = new JavaTXCompiler(fileToTest); - pathToClassFile = System.getProperty("user.dir")+"/resources/testBytecode/generatedBC/"; - compiler.generateBytecode(pathToClassFile); - loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); - classToTest = loader.loadClass("VectorAdd"); - instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); - } - -} diff --git a/src/test/java/bytecode/VectorSuperTest.java b/src/test/java/bytecode/VectorSuperTest.java deleted file mode 100644 index e7015b51..00000000 --- a/src/test/java/bytecode/VectorSuperTest.java +++ /dev/null @@ -1,45 +0,0 @@ -package bytecode; - -import static org.junit.Assert.*; - -import java.io.File; -import java.lang.reflect.Method; -import java.net.URL; -import java.net.URLClassLoader; -import java.util.Vector; - -import org.junit.BeforeClass; -import org.junit.Test; - -import de.dhbwstuttgart.core.JavaTXCompiler; - -public class VectorSuperTest { - - private static String path; - private static File fileToTest; - private static JavaTXCompiler compiler; - private static ClassLoader loader; - private static Class classToTest; - private static String pathToClassFile; - private static Object instanceOfClass; - - @BeforeClass - public static void setUpBeforeClass() throws Exception { - path = System.getProperty("user.dir")+"/resources/bytecode/javFiles/VectorSuper.jav"; - fileToTest = new File(path); - compiler = new JavaTXCompiler(fileToTest); - pathToClassFile = System.getProperty("user.dir")+"/resources/testBytecode/generatedBC/"; - compiler.generateBytecode(pathToClassFile); - loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); - classToTest = loader.loadClass("VectorSuper"); - instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); - } - - @Test - public void test1() throws Exception { - Method m = classToTest.getDeclaredMethod("m", Vector.class); - //Object result = m.invoke(instanceOfClass, 1); - - //assertEquals(1,result); - } -} diff --git a/src/test/java/bytecode/WhileTest.java b/src/test/java/bytecode/WhileTest.java deleted file mode 100644 index 2adaff4a..00000000 --- a/src/test/java/bytecode/WhileTest.java +++ /dev/null @@ -1,58 +0,0 @@ -package bytecode; - -import static org.junit.Assert.*; - -import java.io.File; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.net.URL; -import java.net.URLClassLoader; - -import org.junit.BeforeClass; -import org.junit.Test; - -import de.dhbwstuttgart.core.JavaTXCompiler; - -public class WhileTest { - private static String path; - private static File fileToTest; - private static JavaTXCompiler compiler; - private static ClassLoader loader; - private static Class classToTest; - private static String pathToClassFile; - private static Object instanceOfClass; - - @BeforeClass - public static void setUpBeforeClass() throws Exception { - path = System.getProperty("user.dir")+"/resources/bytecode/javFiles/While.jav"; - fileToTest = new File(path); - compiler = new JavaTXCompiler(fileToTest); - pathToClassFile = System.getProperty("user.dir")+"/resources/testBytecode/generatedBC/"; - compiler.generateBytecode(pathToClassFile); - loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); - classToTest = loader.loadClass("While"); - instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); - } - - @Test - public void test() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method m = classToTest.getDeclaredMethod("m", Integer.class); - Integer result = (Integer) m.invoke(instanceOfClass, 0); - 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(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(new Long(2l), result); - } - -} diff --git a/src/test/java/bytecode/YTest.java b/src/test/java/bytecode/YTest.java deleted file mode 100644 index bb78a204..00000000 --- a/src/test/java/bytecode/YTest.java +++ /dev/null @@ -1,52 +0,0 @@ -package bytecode; - -import static org.junit.Assert.assertEquals; - -import java.io.File; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.net.URL; -import java.net.URLClassLoader; - -import org.junit.Test; - -import de.dhbwstuttgart.core.JavaTXCompiler; - -public class YTest { - private static String path; - private static File fileToTest; - private static JavaTXCompiler compiler; - private static ClassLoader loader; - private static Class classToTest; - private static String pathToClassFile; - private static Object instanceOfClass; - - @Test - public void generateBC() throws Exception { - path = System.getProperty("user.dir")+"/resources/bytecode/javFiles/Y.jav"; - fileToTest = new File(path); - compiler = new JavaTXCompiler(fileToTest); - compiler.generateBytecode(System.getProperty("user.dir")+"/resources/testBytecode/generatedBC/"); - pathToClassFile = System.getProperty("user.dir")+"/resources/testBytecode/generatedBC/"; - loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); - classToTest = loader.loadClass("Y"); - /* - instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); - - Method m = classToTest.getDeclaredMethod("m"); - Class lambda = m.invoke(instanceOfClass).getClass(); - Method apply = lambda.getMethod("apply", Object.class); - - // Damit man auf die Methode zugreifen kann - apply.setAccessible(true); - - Integer i = 77; - - Integer result = (Integer) apply.invoke(m.invoke(instanceOfClass), i); - - assertEquals(77, result); - */ - } - - -} diff --git a/src/test/java/bytecode/applyLambdaTest.java b/src/test/java/bytecode/applyLambdaTest.java deleted file mode 100644 index ada25547..00000000 --- a/src/test/java/bytecode/applyLambdaTest.java +++ /dev/null @@ -1,40 +0,0 @@ - -package bytecode; - -import static org.junit.Assert.assertEquals; - -import java.io.File; -import java.lang.reflect.Method; -import java.net.URL; -import java.net.URLClassLoader; - -import org.junit.Test; - -import de.dhbwstuttgart.core.JavaTXCompiler; - -public class applyLambdaTest { - private static String path; - private static File fileToTest; - private static JavaTXCompiler compiler; - private static ClassLoader loader; - private static Class classToTest; - private static String pathToClassFile; - private static Object instanceOfClass; - - @Test - public void generateBC() throws Exception { - path = System.getProperty("user.dir")+"/resources/bytecode/javFiles/applyLambda.jav"; - fileToTest = new File(path); - compiler = new JavaTXCompiler(fileToTest); - compiler.generateBytecode(System.getProperty("user.dir")+"/resources/testBytecode/generatedBC/"); - pathToClassFile = System.getProperty("user.dir")+"/resources/testBytecode/generatedBC/"; - loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); - classToTest = loader.loadClass("applyLambda"); - instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); - - Method m = classToTest.getDeclaredMethod("m"); - Object result = m.invoke(instanceOfClass); - - assertEquals(result.getClass(), loader.loadClass("Apply")); - } -} diff --git a/src/test/java/bytecode/mathStrucIntegerTest.java b/src/test/java/bytecode/mathStrucIntegerTest.java deleted file mode 100644 index ee614db4..00000000 --- a/src/test/java/bytecode/mathStrucIntegerTest.java +++ /dev/null @@ -1,38 +0,0 @@ -package bytecode; - -import static org.junit.Assert.*; - -import java.io.File; -import java.lang.reflect.Field; -import java.net.URL; -import java.net.URLClassLoader; - -import org.junit.BeforeClass; -import org.junit.Test; - -import de.dhbwstuttgart.core.JavaTXCompiler; - -public class mathStrucIntegerTest { - - private static String path; - private static File fileToTest; - private static JavaTXCompiler compiler; - private static ClassLoader loader; - private static Class classToTest; - private static String pathToClassFile; - private static Object instanceOfClass; - - - @Test - public void test() throws Exception { - path = System.getProperty("user.dir")+"/resources/bytecode/javFiles/mathStrucInteger.jav"; - fileToTest = new File(path); - compiler = new JavaTXCompiler(fileToTest); - compiler.generateBytecode(System.getProperty("user.dir")+"/resources/testBytecode/generatedBC/"); - pathToClassFile = System.getProperty("user.dir")+"/resources/testBytecode/generatedBC/"; - loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); - classToTest = loader.loadClass("mathStrucInteger"); - //instanceOfClass = classToTest.getDeclaredConstructor(Integer.class).newInstance("A"); - } - -} diff --git a/src/test/java/bytecode/mathStrucMatrixOPTest.java.txt b/src/test/java/bytecode/mathStrucMatrixOPTest.java.txt deleted file mode 100644 index 50bb30ad..00000000 --- a/src/test/java/bytecode/mathStrucMatrixOPTest.java.txt +++ /dev/null @@ -1,40 +0,0 @@ -package bytecode; - -import static org.junit.Assert.*; - -import java.io.File; -import java.lang.reflect.Field; -import java.net.URL; -import java.net.URLClassLoader; - -import org.junit.BeforeClass; -import org.junit.Test; - -import de.dhbwstuttgart.core.JavaTXCompiler; - -public class mathStrucMatrixOPTest { - - private static String path; - private static File fileToTest; - private static JavaTXCompiler compiler; - private static ClassLoader loader; - private static Class classToTest; - private static String pathToClassFile; - private static Object instanceOfClass; - - - @Test - public void test() throws Exception { - //PL 2019-10-24: laeuft nicht durch deshalb ersetzt - path = System.getProperty("user.dir")+"/resources/bytecode/javFiles/mathStrucMatrixOp.jav"; - //path = System.getProperty("user.dir")+"/resources/bytecode/javFiles/mathStrucInteger.jav"; - fileToTest = new File(path); - compiler = new JavaTXCompiler(fileToTest); - compiler.generateBytecode(System.getProperty("user.dir")+"/resources/testBytecode/generatedBC/"); - pathToClassFile = System.getProperty("user.dir")+"/resources/testBytecode/generatedBC/"; - loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); - classToTest = loader.loadClass("mathStrucMatrixOP"); - instanceOfClass = classToTest.getDeclaredConstructor(Object.class).newInstance("A"); - } - -} diff --git a/src/test/java/bytecode/mathStrucTest.java b/src/test/java/bytecode/mathStrucTest.java deleted file mode 100644 index d472b403..00000000 --- a/src/test/java/bytecode/mathStrucTest.java +++ /dev/null @@ -1,38 +0,0 @@ -package bytecode; - -import static org.junit.Assert.*; - -import java.io.File; -import java.lang.reflect.Field; -import java.net.URL; -import java.net.URLClassLoader; - -import org.junit.BeforeClass; -import org.junit.Test; - -import de.dhbwstuttgart.core.JavaTXCompiler; - -public class mathStrucTest { - - private static String path; - private static File fileToTest; - private static JavaTXCompiler compiler; - private static ClassLoader loader; - private static Class classToTest; - private static String pathToClassFile; - private static Object instanceOfClass; - - - @Test - public void test() throws Exception { - path = System.getProperty("user.dir")+"/resources/bytecode/javFiles/mathStruc.jav"; - fileToTest = new File(path); - compiler = new JavaTXCompiler(fileToTest); - compiler.generateBytecode(System.getProperty("user.dir")+"/resources/testBytecode/generatedBC/"); - pathToClassFile = System.getProperty("user.dir")+"/resources/testBytecode/generatedBC/"; - loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); - classToTest = loader.loadClass("mathStruc"); - instanceOfClass = classToTest.getDeclaredConstructor(Object.class).newInstance("A"); - } - -} diff --git a/src/test/java/bytecode/mathStrucVectorAddTest.java.txt b/src/test/java/bytecode/mathStrucVectorAddTest.java.txt deleted file mode 100644 index 61130cf1..00000000 --- a/src/test/java/bytecode/mathStrucVectorAddTest.java.txt +++ /dev/null @@ -1,38 +0,0 @@ -package bytecode; - -import static org.junit.Assert.*; - -import java.io.File; -import java.lang.reflect.Field; -import java.net.URL; -import java.net.URLClassLoader; - -import org.junit.BeforeClass; -import org.junit.Test; - -import de.dhbwstuttgart.core.JavaTXCompiler; - -public class mathStrucVectorAddTest { - - private static String path; - private static File fileToTest; - private static JavaTXCompiler compiler; - private static ClassLoader loader; - private static Class classToTest; - private static String pathToClassFile; - private static Object instanceOfClass; - - - @Test - public void test() throws Exception { - path = System.getProperty("user.dir")+"/resources/bytecode/javFiles/mathStrucVector.jav"; - fileToTest = new File(path); - compiler = new JavaTXCompiler(fileToTest); - compiler.generateBytecode(System.getProperty("user.dir")+"/resources/testBytecode/generatedBC/"); - pathToClassFile = System.getProperty("user.dir")+"/resources/testBytecode/generatedBC/"; - loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); - classToTest = loader.loadClass("mathStrucVector"); - //instanceOfClass = classToTest.getDeclaredConstructor(Integer.class).newInstance("A"); - } - -} diff --git a/src/test/java/constraintSimplify/FamilyOfGenerics.java b/src/test/java/constraintSimplify/FamilyOfGenerics.java index e5c9ad13..c7b97773 100644 --- a/src/test/java/constraintSimplify/FamilyOfGenerics.java +++ b/src/test/java/constraintSimplify/FamilyOfGenerics.java @@ -1,32 +1,27 @@ package constraintSimplify; -import de.dhbwstuttgart.bytecode.TPHExtractor; -import de.dhbwstuttgart.bytecode.insertGenerics.PositionFinder; -import de.dhbwstuttgart.bytecode.genericsGenerator.GeneratedGenericsFinder; import de.dhbwstuttgart.parser.NullToken; import de.dhbwstuttgart.parser.scope.JavaClassName; import de.dhbwstuttgart.syntaxtree.*; import de.dhbwstuttgart.syntaxtree.statement.Block; import de.dhbwstuttgart.syntaxtree.type.RefType; import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder; -import de.dhbwstuttgart.typeinference.result.ResultSet; import org.junit.Test; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.HashSet; -import java.util.List; import java.util.Optional; public class FamilyOfGenerics { @Test public void generateBC() throws Exception { - SourceFile sf = generateAST(); + /*SourceFile sf = generateAST(); PositionFinder.getPositionOfTPH(sf, null); TPHExtractor tphExtractor = new TPHExtractor(); List results = new ArrayList(); - GeneratedGenericsFinder generatedGenericsFinder = new GeneratedGenericsFinder(sf, results); + GeneratedGenericsFinder generatedGenericsFinder = new GeneratedGenericsFinder(sf, results);*/ } public static SourceFile generateAST(){ diff --git a/src/test/java/insertGenerics/FamilyOfGeneratedGenericsTest.java b/src/test/java/insertGenerics/FamilyOfGeneratedGenericsTest.java deleted file mode 100644 index 53122862..00000000 --- a/src/test/java/insertGenerics/FamilyOfGeneratedGenericsTest.java +++ /dev/null @@ -1,228 +0,0 @@ -/* -package insertGenerics; - -import de.dhbwstuttgart.bytecode.constraint.TPHConstraint; -import de.dhbwstuttgart.bytecode.insertGenerics.*; -import de.dhbwstuttgart.bytecode.utilities.MethodAndTPH; -import junit.framework.TestCase; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -public class FamilyOfGeneratedGenericsTest extends TestCase { - - public void testIdentityMethod(){ - */ -/* - Example method: - A id(B i) return i; - gives constraint: B <. A and A <. Object, which are method constraints - *//* - - - List inputConstraints = new ArrayList<>(); - inputConstraints.add(new TPHConstraint("B", "A", TPHConstraint.Relation.EXTENDS)); - - HashMap> tphPositions = new HashMap<>(); - PairTphMethod meth1 = new PairTphMethod(PositionFinder.Position.METHOD, "m1"); - tphPositions.put("A", meth1); - tphPositions.put("B", meth1); - - List classConstraints = FamilyOfGeneratedGenerics.getClassConstraints(inputConstraints, tphPositions); - assertTrue(classConstraints.isEmpty()); - - */ -/* - MethodConstraints should be the same as the input constraint - *//* - -// List methodConstraints = FamilyOfGeneratedGenerics.getMethodConstraints(inputConstraints, new ArrayList(), tphPositions); -// assertTrue(methodConstraints.size() == 2); -// assertTrue(methodConstraints.get(0).getLeft().equals("B")); -// assertTrue(methodConstraints.get(0).getRight().equals("A")); - } - - public void testClassField(){ - */ -/* - class Example{ - A f; - B fReturn(){ - return f; - } - } - gives constraint: A <. B and B <. Object which are class constraints - *//* - - - List inputConstraints = new ArrayList<>(); - inputConstraints.add(new TPHConstraint("A", "B", TPHConstraint.Relation.EXTENDS)); - - HashMap> tphPositions = new HashMap<>(); - PairTphMethod posOfA = new PairTphMethod<>(PositionFinder.Position.FIELD, null); - tphPositions.put("A", posOfA); - PairTphMethod posOfB = new PairTphMethod<>(PositionFinder.Position.METHOD, "fReturn"); - tphPositions.put("B", posOfB); - - */ -/* - ClassConstraints should not be the same as the input constraint - *//* - - List classConstraints = FamilyOfGeneratedGenerics.getClassConstraints(inputConstraints, tphPositions); - System.out.println(classConstraints); - assertTrue(classConstraints.size() == 2); - //assertTrue(classConstraints.get(0).getLeft().equals("A")); - //assertTrue(classConstraints.get(0).getRight().equals("B")); -// HashMap> methodConstraintsWithPosition = FamilyOfGeneratedGenerics.getMethodConstraintsWithPosition(inputConstraints,classConstraints,tphPositions,) - } - - public void testSecondLineOfClassConstraints() { - */ -/* - class Example() { - A a; - B b = a; - C anyMethod() { - F f; - return f; - } - D otherMethod(E e) { - this.b = e; - e = this.a; - return e; - } - } - *//* - - - List inputConstraints = new ArrayList<>(); - inputConstraints.add(new TPHConstraint("A", "B", TPHConstraint.Relation.EXTENDS)); - inputConstraints.add(new TPHConstraint("F", "C", TPHConstraint.Relation.EXTENDS)); - inputConstraints.add(new TPHConstraint("E", "B", TPHConstraint.Relation.EXTENDS)); - inputConstraints.add(new TPHConstraint("A", "E", TPHConstraint.Relation.EXTENDS)); - inputConstraints.add(new TPHConstraint("E", "D", TPHConstraint.Relation.EXTENDS)); - - HashMap> tphPositions = new HashMap<>(); - PairTphMethod posOfA = new PairTphMethod<>(PositionFinder.Position.FIELD, null); - PairTphMethod posOfB = new PairTphMethod<>(PositionFinder.Position.FIELD, null); - PairTphMethod posOfC = new PairTphMethod<>(PositionFinder.Position.METHOD, "anyMethod"); - PairTphMethod posOfD = new PairTphMethod<>(PositionFinder.Position.METHOD, "otherMethod"); - PairTphMethod posOfE = new PairTphMethod<>(PositionFinder.Position.METHOD, "otherMethod"); - PairTphMethod posOfF = new PairTphMethod<>(PositionFinder.Position.METHOD, "anyMethod"); - - tphPositions.put("A", posOfA); - tphPositions.put("B", posOfB); - tphPositions.put("C", posOfC); - tphPositions.put("F", posOfF); - tphPositions.put("D", posOfD); - tphPositions.put("E", posOfE); - - List classConstraints = FamilyOfGeneratedGenerics.getClassConstraints(inputConstraints, tphPositions); - System.out.println(classConstraints); -// List methodConstraints = FamilyOfGeneratedGenerics.getMethodConstraints(inputConstraints, classConstraints, tphPositions); -// System.out.println(methodConstraints); - assertFalse(classConstraints.isEmpty()); - assertTrue(classConstraints.size() == 6); -// assertFalse(methodConstraints.isEmpty()); -// assertTrue(methodConstraints.size() == 2); - - } - - public void testTPHsAndGenerics() { - */ -/* - class TPHsAndGenerics { - Fun1 id = x -> x; - C id2 (D x) { - return id.apply(x); - } - E m(F a, G b){ - var c = m2(a,b); - return a; - } - H m2(I a, J b){ - return b; - } - } - *//* - - - List inputConstraints = new ArrayList<>(); - inputConstraints.add(new TPHConstraint("A","B", TPHConstraint.Relation.EXTENDS)); - inputConstraints.add(new TPHConstraint("B","C", TPHConstraint.Relation.EXTENDS)); - inputConstraints.add(new TPHConstraint("D","A", TPHConstraint.Relation.EXTENDS)); - inputConstraints.add(new TPHConstraint("F","E", TPHConstraint.Relation.EXTENDS)); - inputConstraints.add(new TPHConstraint("F","I", TPHConstraint.Relation.EXTENDS)); - inputConstraints.add(new TPHConstraint("G","J", TPHConstraint.Relation.EXTENDS)); - inputConstraints.add(new TPHConstraint("J","H", TPHConstraint.Relation.EXTENDS)); - - HashMap> tphPositions = new HashMap<>(); - PairTphMethod posOfA = new PairTphMethod<>(PositionFinder.Position.FIELD, null); - PairTphMethod posOfB = new PairTphMethod<>(PositionFinder.Position.FIELD, null); - PairTphMethod posOfC = new PairTphMethod<>(PositionFinder.Position.METHOD, "id2"); - PairTphMethod posOfD = new PairTphMethod<>(PositionFinder.Position.METHOD, "id2"); - PairTphMethod posOfE = new PairTphMethod<>(PositionFinder.Position.METHOD, "m"); - PairTphMethod posOfF = new PairTphMethod<>(PositionFinder.Position.METHOD, "m"); - PairTphMethod posOfG = new PairTphMethod<>(PositionFinder.Position.METHOD, "m"); - PairTphMethod posOfH = new PairTphMethod<>(PositionFinder.Position.METHOD, "m2"); - PairTphMethod posOfI = new PairTphMethod<>(PositionFinder.Position.METHOD, "m2"); - PairTphMethod posOfJ = new PairTphMethod<>(PositionFinder.Position.METHOD, "m2"); - - tphPositions.put("A", posOfA); - tphPositions.put("B", posOfB); - tphPositions.put("C", posOfC); - tphPositions.put("D", posOfD); - tphPositions.put("E", posOfE); - tphPositions.put("F", posOfF); - tphPositions.put("G", posOfG); - tphPositions.put("H", posOfH); - tphPositions.put("I", posOfI); - tphPositions.put("J", posOfJ); - - List classConstraints = FamilyOfGeneratedGenerics.getClassConstraints(inputConstraints, tphPositions); - System.out.println(classConstraints); -// List methodConstraints = FamilyOfGeneratedGenerics.getMethodConstraints(inputConstraints, classConstraints, tphPositions); -// System.out.println(methodConstraints); - - assertFalse(classConstraints.isEmpty()); - assertTrue(classConstraints.size() == 3); -// assertFalse(methodConstraints.isEmpty()); -// assertTrue(methodConstraints.size()==9); - } - - - public void testPositionConverter() { - HashMap allTphsOld = new HashMap<>(); - List listOfMethodsAndTphs = new ArrayList<>(); - allTphsOld.put("A", true); - allTphsOld.put("B", false); - MethodAndTPH m1 = new MethodAndTPH("m1"); - m1.getTphs().add("A"); - MethodAndTPH bla = new MethodAndTPH("bla"); - MethodAndTPH blubb = new MethodAndTPH("blubb"); -// blubb.getTphs().add("A"); - listOfMethodsAndTphs.add(bla); - listOfMethodsAndTphs.add(blubb); - listOfMethodsAndTphs.add(m1); - - - - HashMap>> allTphsNew = FamilyOfGeneratedGenerics.positionConverter(allTphsOld, listOfMethodsAndTphs); - System.out.println(allTphsNew); - //was tun wenn zwei (oder mehr) Methoden gleiches TPH enthalten? - //ist dies möglich oder werden die TPHs immer verschieden initialisiert und dann erst am Ende gemappt? - //überarbeiten oder lassen? - - - assertTrue(allTphsNew.get("A").fst.equals(PositionFinder.Position.METHOD)); - assertTrue(allTphsNew.get("B").fst.equals(PositionFinder.Position.FIELD)); - } - - - public void testFirstTransitiveSubtypeForMethodTypes(){ - - } - -}*/ diff --git a/src/test/java/insertGenerics/TestAny.java b/src/test/java/insertGenerics/TestAny.java deleted file mode 100644 index 5865e16b..00000000 --- a/src/test/java/insertGenerics/TestAny.java +++ /dev/null @@ -1,112 +0,0 @@ -package insertGenerics; - -import de.dhbwstuttgart.bytecode.constraint.TPHConstraint.Relation; -import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.GenericGenratorResultForSourceFile; -import de.dhbwstuttgart.bytecode.insertGenerics.ClassConstraint; -import de.dhbwstuttgart.bytecode.insertGenerics.FamilyOfGeneratedGenerics; -import de.dhbwstuttgart.bytecode.insertGenerics.MethodConstraint; -import de.dhbwstuttgart.core.JavaTXCompiler; -import de.dhbwstuttgart.syntaxtree.SourceFile; -import de.dhbwstuttgart.syntaxtree.visual.ASTPrinter; -import de.dhbwstuttgart.syntaxtree.visual.ASTTypePrinter; -import de.dhbwstuttgart.typedeployment.TypeInsert; -import de.dhbwstuttgart.typedeployment.TypeInsertFactory; -import de.dhbwstuttgart.typeinference.result.ResultSet; - -import org.junit.BeforeClass; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; - -import java.io.File; -import java.io.IOException; -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -public class TestAny { - - public static final String rootDirectory = System.getProperty("user.dir")+"/resources/insertGenericsJav/"; - - @BeforeClass - public static void resetNamesOfTypePlaceholder() { - de.dhbwstuttgart.syntaxtree.factory.NameGenerator.reset(); - } - - @Test - public void ggFinder() throws IOException, ClassNotFoundException { - execute(new File(rootDirectory+"TestAny.jav")); - } - - private static class TestResultSet{ - - } - - public TestResultSet execute(File fileToTest) throws IOException, ClassNotFoundException { - JavaTXCompiler compiler = new JavaTXCompiler(fileToTest); - for(File f : compiler.sourceFiles.keySet()){ - SourceFile sf = compiler.sourceFiles.get(f); - } - List results = compiler.typeInference(); - List simplifyResultsForAllSourceFiles = compiler.getGeneratedGenericResultsForAllSourceFiles(results); - - List classConstraintsTest = new ArrayList<>(); - classConstraintsTest.add(new ClassConstraint("N", "O", Relation.EXTENDS)); - classConstraintsTest.add(new ClassConstraint("N", "U", Relation.EXTENDS)); - classConstraintsTest.add(new ClassConstraint("U", "O", Relation.EXTENDS)); - classConstraintsTest.add(new ClassConstraint("O", "java/lang/Object", Relation.EXTENDS)); - HashMap> methodConstraintsWithPositionTest = new HashMap<>(); - Set lmc; - lmc = new HashSet<>(); - lmc.add(new MethodConstraint("R", "java/lang/Object", Relation.EXTENDS)); - methodConstraintsWithPositionTest.put("TPH RanyMethod()", lmc); - lmc = new HashSet<>(); - methodConstraintsWithPositionTest.put("TPH UotherMethod(TPH U)", lmc); - - FamilyOfGeneratedGenerics fogg = compiler.fogg; - Set computedClassCons = new HashSet<>(fogg.classConstraints); - Set expectedClassCons = new HashSet<>(classConstraintsTest); - - assertEquals(expectedClassCons, computedClassCons); - - HashMap> methodConstraintsWithPositionComputed = new HashMap<>(); - fogg.methodConstraintsWithPosition.forEach((s, l) -> methodConstraintsWithPositionComputed.put(s,new HashSet<>(l))); - - assertEquals(methodConstraintsWithPositionTest, methodConstraintsWithPositionComputed); - - //compiler.generateBytecode(rootDirectory+"xxx.class", results, simplifyResultsForAllSourceFiles); - for(File f : compiler.sourceFiles.keySet()){ - SourceFile sf = compiler.sourceFiles.get(f); - System.out.println(ASTTypePrinter.print(sf)); - System.out.println(ASTPrinter.print(sf)); - //List results = compiler.typeInference(); PL 2017-10-03 vor die For-Schleife gezogen - assert results.size()>0; - Set insertedTypes = new HashSet<>(); - for(ResultSet resultSet : results){ - Set result = TypeInsertFactory.createTypeInsertPoints(sf, resultSet, results, simplifyResultsForAllSourceFiles); - assert result.size()>0; - String content = readFile(f.getPath(), StandardCharsets.UTF_8); - for(TypeInsert tip : result){ - insertedTypes.add(tip.insert(content)); - } - } - for(String s : insertedTypes){ - System.out.println(s); - } - } - return new TestResultSet(); - } - - static String readFile(String path, Charset encoding) - throws IOException - { - byte[] encoded = Files.readAllBytes(Paths.get(path)); - return new String(encoded, encoding); - } -} diff --git a/src/test/java/insertGenerics/TestClassField.java b/src/test/java/insertGenerics/TestClassField.java deleted file mode 100644 index 4f03ceb0..00000000 --- a/src/test/java/insertGenerics/TestClassField.java +++ /dev/null @@ -1,79 +0,0 @@ -package insertGenerics; - -import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.GenericGenratorResultForSourceFile; -import de.dhbwstuttgart.core.JavaTXCompiler; -import de.dhbwstuttgart.syntaxtree.SourceFile; -import de.dhbwstuttgart.syntaxtree.visual.ASTPrinter; -import de.dhbwstuttgart.syntaxtree.visual.ASTTypePrinter; -import de.dhbwstuttgart.typedeployment.TypeInsert; -import de.dhbwstuttgart.typedeployment.TypeInsertFactory; -import de.dhbwstuttgart.typeinference.result.ResultSet; - -import org.junit.BeforeClass; -import org.junit.Test; - -import java.io.File; -import java.io.IOException; -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -public class TestClassField { - - public static final String rootDirectory = System.getProperty("user.dir")+"/resources/insertGenericsJav/"; - - @BeforeClass - public static void resetNamesOfTypePlaceholder() { - de.dhbwstuttgart.syntaxtree.factory.NameGenerator.reset(); - } - - @Test - public void ggFinder() throws IOException, ClassNotFoundException { - execute(new File(rootDirectory+"TestClassField.jav")); - } - - private static class TestResultSet{ - - } - - public TestResultSet execute(File fileToTest) throws IOException, ClassNotFoundException { - JavaTXCompiler compiler = new JavaTXCompiler(fileToTest); - for(File f : compiler.sourceFiles.keySet()){ - SourceFile sf = compiler.sourceFiles.get(f); - } - List results = compiler.typeInference(); - List simplifyResultsForAllSourceFiles = compiler.getGeneratedGenericResultsForAllSourceFiles(results); - //compiler.generateBytecode(rootDirectory+"xxx.class", results, simplifyResultsForAllSourceFiles); - for(File f : compiler.sourceFiles.keySet()){ - SourceFile sf = compiler.sourceFiles.get(f); - System.out.println(ASTTypePrinter.print(sf)); - System.out.println(ASTPrinter.print(sf)); - //List results = compiler.typeInference(); PL 2017-10-03 vor die For-Schleife gezogen - assert results.size()>0; - Set insertedTypes = new HashSet<>(); - for(ResultSet resultSet : results){ - Set result = TypeInsertFactory.createTypeInsertPoints(sf, resultSet, results, simplifyResultsForAllSourceFiles); - assert result.size()>0; - String content = readFile(f.getPath(), StandardCharsets.UTF_8); - for(TypeInsert tip : result){ - insertedTypes.add(tip.insert(content)); - } - } - for(String s : insertedTypes){ - System.out.println(s); - } - } - return new TestResultSet(); - } - - static String readFile(String path, Charset encoding) - throws IOException - { - byte[] encoded = Files.readAllBytes(Paths.get(path)); - return new String(encoded, encoding); - } -} diff --git a/src/test/java/insertGenerics/TestContraVariant.java b/src/test/java/insertGenerics/TestContraVariant.java deleted file mode 100644 index 3e04a6ae..00000000 --- a/src/test/java/insertGenerics/TestContraVariant.java +++ /dev/null @@ -1,112 +0,0 @@ -package insertGenerics; - -import de.dhbwstuttgart.bytecode.constraint.TPHConstraint.Relation; -import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.GenericGenratorResultForSourceFile; -import de.dhbwstuttgart.bytecode.insertGenerics.ClassConstraint; -import de.dhbwstuttgart.bytecode.insertGenerics.FamilyOfGeneratedGenerics; -import de.dhbwstuttgart.bytecode.insertGenerics.MethodConstraint; -import de.dhbwstuttgart.core.JavaTXCompiler; -import de.dhbwstuttgart.syntaxtree.SourceFile; -import de.dhbwstuttgart.syntaxtree.visual.ASTPrinter; -import de.dhbwstuttgart.syntaxtree.visual.ASTTypePrinter; -import de.dhbwstuttgart.typedeployment.TypeInsert; -import de.dhbwstuttgart.typedeployment.TypeInsertFactory; -import de.dhbwstuttgart.typeinference.result.ResultSet; - -import org.junit.BeforeClass; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; - -import java.io.File; -import java.io.IOException; -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -public class TestContraVariant { - - public static final String rootDirectory = System.getProperty("user.dir")+"/resources/insertGenericsJav/"; - - @BeforeClass - public static void resetNamesOfTypePlaceholder() { - de.dhbwstuttgart.syntaxtree.factory.NameGenerator.reset(); - } - - @Test - public void ggFinder() throws IOException, ClassNotFoundException { - execute(new File(rootDirectory+"TestContraVariant.jav")); - } - - private static class TestResultSet{ - - } - - public TestResultSet execute(File fileToTest) throws IOException, ClassNotFoundException { - JavaTXCompiler compiler = new JavaTXCompiler(fileToTest); - for(File f : compiler.sourceFiles.keySet()){ - SourceFile sf = compiler.sourceFiles.get(f); - } - List results = compiler.typeInference(); - List simplifyResultsForAllSourceFiles = compiler.getGeneratedGenericResultsForAllSourceFiles(results); - - List classConstraintsTest = new ArrayList<>(); - HashMap> methodConstraintsWithPositionTest = new HashMap<>(); - Set lmc; - lmc = new HashSet<>(); - lmc.add(new MethodConstraint("R", "O", Relation.EXTENDS)); - lmc.add(new MethodConstraint("O", "java/lang/Object", Relation.EXTENDS)); - methodConstraintsWithPositionTest.put("TPH Rm(TPH O)", lmc); - lmc = new HashSet<>(); - //lmc.add(new MethodConstraint("S", "O", Relation.EXTENDS)); - lmc.add(new MethodConstraint("S", "java/lang/Object", Relation.EXTENDS)); - lmc.add(new MethodConstraint("R", "java/lang/Object", Relation.EXTENDS)); - methodConstraintsWithPositionTest.put("TPH Rmain(TPH S)", lmc); - - FamilyOfGeneratedGenerics fogg = compiler.fogg; - Set computedClassCons = new HashSet<>(fogg.classConstraints); - Set expectedClassCons = new HashSet<>(classConstraintsTest); - - assertEquals(expectedClassCons, computedClassCons); - - HashMap> methodConstraintsWithPositionComputed = new HashMap<>(); - fogg.methodConstraintsWithPosition.forEach((s, l) -> methodConstraintsWithPositionComputed.put(s,new HashSet<>(l))); - - assertEquals(methodConstraintsWithPositionTest, methodConstraintsWithPositionComputed); - - //compiler.generateBytecode(rootDirectory+"xxx.class", results, simplifyResultsForAllSourceFiles); - for(File f : compiler.sourceFiles.keySet()){ - SourceFile sf = compiler.sourceFiles.get(f); - System.out.println(ASTTypePrinter.print(sf)); - System.out.println(ASTPrinter.print(sf)); - //List results = compiler.typeInference(); PL 2017-10-03 vor die For-Schleife gezogen - assert results.size()>0; - Set insertedTypes = new HashSet<>(); - for(ResultSet resultSet : results){ - Set result = TypeInsertFactory.createTypeInsertPoints(sf, resultSet, results, simplifyResultsForAllSourceFiles); - assert result.size()>0; - String content = readFile(f.getPath(), StandardCharsets.UTF_8); - for(TypeInsert tip : result){ - insertedTypes.add(tip.insert(content)); - } - } - for(String s : insertedTypes){ - System.out.println(s); - } - } - return new TestResultSet(); - } - - static String readFile(String path, Charset encoding) - throws IOException - { - byte[] encoded = Files.readAllBytes(Paths.get(path)); - return new String(encoded, encoding); - } -} diff --git a/src/test/java/insertGenerics/TestExample42.java b/src/test/java/insertGenerics/TestExample42.java deleted file mode 100644 index a052bacf..00000000 --- a/src/test/java/insertGenerics/TestExample42.java +++ /dev/null @@ -1,62 +0,0 @@ -package insertGenerics; - -import de.dhbwstuttgart.bytecode.constraint.TPHConstraint; -import de.dhbwstuttgart.bytecode.constraint.TPHConstraint.Relation; -import de.dhbwstuttgart.bytecode.insertGenerics.*; -import org.junit.Test; -import static org.junit.Assert.assertEquals; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -public class TestExample42 { - public List fillConstraintsList() { - List cs = new ArrayList<>(); - cs.add(new TPHConstraint("M", "N", Relation.EXTENDS)); - cs.add(new TPHConstraint("N", "Z", Relation.EXTENDS)); - cs.add(new TPHConstraint("Q", "K", Relation.EXTENDS)); - cs.add(new TPHConstraint("K", "P", Relation.EXTENDS)); - cs.add(new TPHConstraint("W", "M", Relation.EXTENDS)); - cs.add(new TPHConstraint("Z", "V", Relation.EXTENDS)); - return cs; - } - - public HashMap> fillPosOfTphs() { - HashMap> posOfTphs = new HashMap<>(); - - // TPHs "U" und "L" auskommentiert, da nach Vorgaben L zu Z umbenannt und U als void interpretiert wird - PairTphMethod posOfK = new PairTphMethod<>(PositionFinder.Position.FIELD, null); -// PairTphMethod posOfL = new PairTphMethod<>(PositionFinder.Position.METHOD, "id"); - PairTphMethod posOfM = new PairTphMethod<>(PositionFinder.Position.METHOD, "id"); - PairTphMethod posOfN = new PairTphMethod<>(PositionFinder.Position.METHOD, "id"); - PairTphMethod posOfP = new PairTphMethod<>(PositionFinder.Position.METHOD, "setA"); - PairTphMethod posOfQ = new PairTphMethod<>(PositionFinder.Position.METHOD, "setA"); -// PairTphMethod posOfU = new PairTphMethod<>(PositionFinder.Position.METHOD, "m"); - PairTphMethod posOfV = new PairTphMethod<>(PositionFinder.Position.METHOD, "m"); - PairTphMethod posOfW = new PairTphMethod<>(PositionFinder.Position.METHOD, "m"); - PairTphMethod posOfZ = new PairTphMethod<>(PositionFinder.Position.METHOD, "m"); - - posOfTphs.put("K", posOfK); -// posOfTphs.put("L", posOfL); - posOfTphs.put("M", posOfM); - posOfTphs.put("N", posOfN); - posOfTphs.put("P", posOfP); - posOfTphs.put("Q", posOfQ); -// posOfTphs.put("U", posOfU); - posOfTphs.put("V", posOfV); - posOfTphs.put("W", posOfW); - posOfTphs.put("Z", posOfZ); - return posOfTphs; - } - - @Test - public void genericTest() { -// List classConstraints = FamilyOfGeneratedGenerics.getClassConstraints(fillConstraintsList(),fillPosOfTphs()); -// System.out.println("ClassConstraints: " + classConstraints); -// List methodConstraints = FamilyOfGeneratedGenerics.getMethodConstraints(fillConstraintsList(),classConstraints,fillPosOfTphs()); -// System.out.println("MethodConstraints: " + methodConstraints); - - List testCons; - } -} diff --git a/src/test/java/insertGenerics/TestExample42_allInOneMethod.java b/src/test/java/insertGenerics/TestExample42_allInOneMethod.java deleted file mode 100644 index f3fe7213..00000000 --- a/src/test/java/insertGenerics/TestExample42_allInOneMethod.java +++ /dev/null @@ -1,61 +0,0 @@ -package insertGenerics; - -import de.dhbwstuttgart.bytecode.constraint.TPHConstraint; -import de.dhbwstuttgart.bytecode.constraint.TPHConstraint.Relation; -import de.dhbwstuttgart.bytecode.insertGenerics.*; -import org.junit.Test; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -public class TestExample42_allInOneMethod { - public List fillConstraintsList() { - List cs = new ArrayList<>(); - cs.add(new TPHConstraint("M", "N", Relation.EXTENDS)); - cs.add(new TPHConstraint("N", "Z", Relation.EXTENDS)); - cs.add(new TPHConstraint("Q", "K", Relation.EXTENDS)); - cs.add(new TPHConstraint("K", "P", Relation.EXTENDS)); - cs.add(new TPHConstraint("W", "M", Relation.EXTENDS)); - cs.add(new TPHConstraint("Z", "V", Relation.EXTENDS)); - return cs; - } - - public HashMap> fillPosOfTphs() { - HashMap> posOfTphs = new HashMap<>(); - - // TPHs "U" und "L" auskommentiert, da nach Vorgaben L zu Z umbenannt und U als void interpretiert wird - PairTphMethod posOfK = new PairTphMethod<>(PositionFinder.Position.FIELD, null); -// PairTphMethod posOfL = new PairTphMethod<>(PositionFinder.Position.METHOD, "sameMethod"); - PairTphMethod posOfM = new PairTphMethod<>(PositionFinder.Position.METHOD, "sameMethod"); - PairTphMethod posOfN = new PairTphMethod<>(PositionFinder.Position.METHOD, "sameMethod"); - PairTphMethod posOfP = new PairTphMethod<>(PositionFinder.Position.METHOD, "sameMethod"); - PairTphMethod posOfQ = new PairTphMethod<>(PositionFinder.Position.METHOD, "sameMethod"); -// PairTphMethod posOfU = new PairTphMethod<>(PositionFinder.Position.METHOD, "sameMethod"); - PairTphMethod posOfV = new PairTphMethod<>(PositionFinder.Position.METHOD, "sameMethod"); - PairTphMethod posOfW = new PairTphMethod<>(PositionFinder.Position.METHOD, "sameMethod"); - PairTphMethod posOfZ = new PairTphMethod<>(PositionFinder.Position.METHOD, "sameMethod"); - - posOfTphs.put("K", posOfK); -// posOfTphs.put("L", posOfL); - posOfTphs.put("M", posOfM); - posOfTphs.put("N", posOfN); - posOfTphs.put("P", posOfP); - posOfTphs.put("Q", posOfQ); -// posOfTphs.put("U", posOfU); - posOfTphs.put("V", posOfV); - posOfTphs.put("W", posOfW); - posOfTphs.put("Z", posOfZ); - return posOfTphs; - } - - @Test - public void genericTest() { -// List classConstraints = FamilyOfGeneratedGenerics.getClassConstraints(fillConstraintsList(),fillPosOfTphs()); -// System.out.println("ClassConstraints: " + classConstraints); -// List methodConstraints = FamilyOfGeneratedGenerics.getMethodConstraints(fillConstraintsList(),classConstraints,fillPosOfTphs(),); -// System.out.println("MethodConstraints: " + methodConstraints); - - List testCons; - } -} diff --git a/src/test/java/insertGenerics/TestGGFinder.java b/src/test/java/insertGenerics/TestGGFinder.java deleted file mode 100644 index cc4fdcc6..00000000 --- a/src/test/java/insertGenerics/TestGGFinder.java +++ /dev/null @@ -1,99 +0,0 @@ -package insertGenerics; - -import de.dhbwstuttgart.bytecode.constraint.TPHConstraint.Relation; -import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.GenericGenratorResultForSourceFile; -import de.dhbwstuttgart.bytecode.insertGenerics.ClassConstraint; -import de.dhbwstuttgart.bytecode.insertGenerics.FamilyOfGeneratedGenerics; -import de.dhbwstuttgart.bytecode.insertGenerics.MethodConstraint; -import de.dhbwstuttgart.core.JavaTXCompiler; -import de.dhbwstuttgart.syntaxtree.SourceFile; -import de.dhbwstuttgart.syntaxtree.visual.ASTPrinter; -import de.dhbwstuttgart.syntaxtree.visual.ASTTypePrinter; -import de.dhbwstuttgart.typedeployment.TypeInsert; -import de.dhbwstuttgart.typedeployment.TypeInsertFactory; -import de.dhbwstuttgart.typeinference.result.ResultSet; - -import org.junit.BeforeClass; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; - -import java.io.File; -import java.io.IOException; -import java.lang.reflect.InvocationTargetException; -import java.net.URL; -import java.net.URLClassLoader; -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -public class TestGGFinder { - - private static final String rootDirectory = System.getProperty("user.dir")+"/resources/insertGenericsJav/"; - private String pathToClassFile = System.getProperty("user.dir")+"/resources/testBytecode/generatedBC/"; - private static ClassLoader loader; - private static Class classToTest; - private static Object instanceOfClass; - private static String className = "TestGGFinder"; - - @BeforeClass - public static void resetNamesOfTypePlaceholder() { - de.dhbwstuttgart.syntaxtree.factory.NameGenerator.reset(); - } - - @Test - public void ggFinder() throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { - execute(new File(rootDirectory+className+".jav")); - } - - private static class TestResultSet{ - - } - - public TestResultSet execute(File fileToTest) throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { - JavaTXCompiler compiler = new JavaTXCompiler(fileToTest); - List results = compiler.typeInference(); - List simplifyResultsForAllSourceFiles = compiler.getGeneratedGenericResultsForAllSourceFiles(results); - - List classConstraintsTest = new ArrayList<>(); - classConstraintsTest.add(new ClassConstraint("S", "java/lang/Object", Relation.EXTENDS)); - HashMap> methodConstraintsWithPositionTest = new HashMap<>(); - Set lmc; - lmc = new HashSet<>(); - lmc.add(new MethodConstraint("P", "AC", Relation.EXTENDS)); - lmc.add(new MethodConstraint("AC", "java/lang/Object", Relation.EXTENDS)); - methodConstraintsWithPositionTest.put("TPH ACid(TPH P)", lmc); - lmc = new HashSet<>(); - lmc.add(new MethodConstraint("T", "S", Relation.EXTENDS)); - methodConstraintsWithPositionTest.put("TPH SsetA(TPH T)", lmc); - lmc = new HashSet<>(); - lmc.add(new MethodConstraint("AC", "Y", Relation.EXTENDS)); - lmc.add(new MethodConstraint("Z", "P", Relation.EXTENDS)); - lmc.add(new MethodConstraint("P", "AC", Relation.EXTENDS)); - lmc.add(new MethodConstraint("Y", "java/lang/Object", Relation.EXTENDS)); - methodConstraintsWithPositionTest.put("voidm(TPH YTPH Z)", lmc); - - FamilyOfGeneratedGenerics fogg = compiler.fogg; - Set computedClassCons = new HashSet<>(fogg.classConstraints); - Set expectedClassCons = new HashSet<>(classConstraintsTest); - - assertEquals(expectedClassCons, computedClassCons); - - HashMap> methodConstraintsWithPositionComputed = new HashMap<>(); - fogg.methodConstraintsWithPosition.forEach((s, l) -> methodConstraintsWithPositionComputed.put(s,new HashSet<>(l))); - - assertEquals(methodConstraintsWithPositionTest, methodConstraintsWithPositionComputed); - - compiler.generateBytecode(new File(pathToClassFile), results, simplifyResultsForAllSourceFiles); - loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); - classToTest = loader.loadClass(className); - instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); - return new TestResultSet(); - } -} diff --git a/src/test/java/insertGenerics/TestLocalVarLambda.java b/src/test/java/insertGenerics/TestLocalVarLambda.java deleted file mode 100644 index 8fc87a82..00000000 --- a/src/test/java/insertGenerics/TestLocalVarLambda.java +++ /dev/null @@ -1,112 +0,0 @@ -package insertGenerics; - -import de.dhbwstuttgart.bytecode.constraint.TPHConstraint.Relation; -import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.GenericGenratorResultForSourceFile; -import de.dhbwstuttgart.bytecode.insertGenerics.ClassConstraint; -import de.dhbwstuttgart.bytecode.insertGenerics.FamilyOfGeneratedGenerics; -import de.dhbwstuttgart.bytecode.insertGenerics.MethodConstraint; -import de.dhbwstuttgart.core.JavaTXCompiler; -import de.dhbwstuttgart.syntaxtree.SourceFile; -import de.dhbwstuttgart.syntaxtree.visual.ASTPrinter; -import de.dhbwstuttgart.syntaxtree.visual.ASTTypePrinter; -import de.dhbwstuttgart.typedeployment.TypeInsert; -import de.dhbwstuttgart.typedeployment.TypeInsertFactory; -import de.dhbwstuttgart.typeinference.result.ResultSet; - -import org.junit.BeforeClass; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; - -import java.io.File; -import java.io.IOException; -import java.lang.reflect.InvocationTargetException; -import java.net.URL; -import java.net.URLClassLoader; -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -public class TestLocalVarLambda { - - private static final String rootDirectory = System.getProperty("user.dir")+"/resources/insertGenericsJav/"; - private String pathToClassFile = System.getProperty("user.dir")+"/resources/testBytecode/generatedBC/"; - private static ClassLoader loader; - private static Class classToTest; - private static Object instanceOfClass; - private static String className = "TestLocalVarLambda"; - - @BeforeClass - public static void resetNamesOfTypePlaceholder() { - de.dhbwstuttgart.syntaxtree.factory.NameGenerator.reset(); - } - - @Test - public void ggFinder() throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { - execute(new File(rootDirectory+className+".jav")); - } - - private static class TestResultSet{ - - } - - public TestResultSet execute(File fileToTest) throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { - JavaTXCompiler compiler = new JavaTXCompiler(fileToTest); - List results = compiler.typeInference(); - List simplifyResultsForAllSourceFiles = compiler.getGeneratedGenericResultsForAllSourceFiles(results); - - List classConstraintsTest = new ArrayList<>(); - HashMap> methodConstraintsWithPositionTest = new HashMap<>(); - - FamilyOfGeneratedGenerics fogg = compiler.fogg; - - Set lmc; - lmc = new HashSet<>(); - - if (fogg.allConstraints.contains((new MethodConstraint("O", "ALU", Relation.EXTENDS)))) { - lmc.add(new MethodConstraint("O", "ALU", Relation.EXTENDS)); - lmc.add(new MethodConstraint("DIU", "java/lang/Object", Relation.EXTENDS)); - lmc.add(new MethodConstraint("ALU", "DIU", Relation.EXTENDS)); - lmc.add(new MethodConstraint("SY", "java/lang/Object", Relation.EXTENDS)); - methodConstraintsWithPositionTest.put("TPH DIUm(TPH O)", lmc); - } - else if (fogg.allConstraints.contains((new MethodConstraint("O", "DIV", Relation.EXTENDS)))) { - lmc.add(new MethodConstraint("O", "DIV", Relation.EXTENDS)); - lmc.add(new MethodConstraint("N", "java/lang/Object", Relation.EXTENDS)); - lmc.add(new MethodConstraint("DIV", "N", Relation.EXTENDS)); - lmc.add(new MethodConstraint("SY", "java/lang/Object", Relation.EXTENDS)); - methodConstraintsWithPositionTest.put("TPH Nm(TPH O)", lmc); - } - else - { - lmc.add(new MethodConstraint("O", "DIU", Relation.EXTENDS)); - lmc.add(new MethodConstraint("N", "java/lang/Object", Relation.EXTENDS)); - lmc.add(new MethodConstraint("DIU", "N", Relation.EXTENDS)); - lmc.add(new MethodConstraint("SY", "java/lang/Object", Relation.EXTENDS)); - methodConstraintsWithPositionTest.put("TPH Nm(TPH O)", lmc); - } - - - Set computedClassCons = new HashSet<>(fogg.classConstraints); - Set expectedClassCons = new HashSet<>(classConstraintsTest); - - assertEquals(expectedClassCons, computedClassCons); - - HashMap> methodConstraintsWithPositionComputed = new HashMap<>(); - fogg.methodConstraintsWithPosition.forEach((s, l) -> methodConstraintsWithPositionComputed.put(s,new HashSet<>(l))); - - assertEquals(methodConstraintsWithPositionTest, methodConstraintsWithPositionComputed); - - compiler.generateBytecode(new File(pathToClassFile), results, simplifyResultsForAllSourceFiles); - loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); - classToTest = loader.loadClass(className); - instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); - return new TestResultSet(); - } -} diff --git a/src/test/java/insertGenerics/TestMutualRecursion.java b/src/test/java/insertGenerics/TestMutualRecursion.java deleted file mode 100644 index a1345f6b..00000000 --- a/src/test/java/insertGenerics/TestMutualRecursion.java +++ /dev/null @@ -1,126 +0,0 @@ -package insertGenerics; - -import de.dhbwstuttgart.bytecode.constraint.TPHConstraint.Relation; -import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.GenericGenratorResultForSourceFile; -import de.dhbwstuttgart.bytecode.insertGenerics.ClassConstraint; -import de.dhbwstuttgart.bytecode.insertGenerics.FamilyOfGeneratedGenerics; -import de.dhbwstuttgart.bytecode.insertGenerics.MethodConstraint; -import de.dhbwstuttgart.core.JavaTXCompiler; -import de.dhbwstuttgart.syntaxtree.SourceFile; -import de.dhbwstuttgart.syntaxtree.visual.ASTPrinter; -import de.dhbwstuttgart.syntaxtree.visual.ASTTypePrinter; -import de.dhbwstuttgart.typedeployment.TypeInsert; -import de.dhbwstuttgart.typedeployment.TypeInsertFactory; -import de.dhbwstuttgart.typeinference.result.ResultSet; - -import org.junit.BeforeClass; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; - -import java.io.File; -import java.io.IOException; -import java.lang.reflect.InvocationTargetException; -import java.net.URL; -import java.net.URLClassLoader; -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -public class TestMutualRecursion { - - private static final String rootDirectory = System.getProperty("user.dir")+"/resources/insertGenericsJav/"; - private String pathToClassFile = System.getProperty("user.dir")+"/resources/testBytecode/generatedBC/"; - private static ClassLoader loader; - private static Class classToTest; - private static Object instanceOfClass; - private static String className; - - @BeforeClass - public static void resetNamesOfTypePlaceholder() { - de.dhbwstuttgart.syntaxtree.factory.NameGenerator.reset(); - } - - @Test - public void TestMutualRecursion1() throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { - className = "TestMutualRecursion"; - JavaTXCompiler compiler = new JavaTXCompiler(new File(rootDirectory+className+".jav")); - List results = compiler.typeInference(); - List simplifyResultsForAllSourceFiles = compiler.getGeneratedGenericResultsForAllSourceFiles(results); - - - List classConstraintsTest = new ArrayList<>(); - classConstraintsTest.add(new ClassConstraint("N", "java/lang/Object", Relation.EXTENDS)); - HashMap> methodConstraintsWithPositionTest = new HashMap<>(); - Set lmc; - lmc = new HashSet<>(); - lmc.add(new MethodConstraint("P", "Q", Relation.EXTENDS)); - lmc.add(new MethodConstraint("Q", "java/lang/Object", Relation.EXTENDS)); - lmc.add(new MethodConstraint("AL", "java/lang/Object", Relation.EXTENDS)); - methodConstraintsWithPositionTest.put("TPH ALid(TPH P)", lmc); - lmc = new HashSet<>(); - lmc.add(new MethodConstraint("AL", "java/lang/Object", Relation.EXTENDS)); - lmc.add(new MethodConstraint("Z", "java/lang/Object", Relation.EXTENDS)); - methodConstraintsWithPositionTest.put("TPH ALm(TPH ALTPH Z)", lmc); - lmc = new HashSet<>(); - lmc.add(new MethodConstraint("AG", "java/lang/Object", Relation.EXTENDS)); - lmc.add(new MethodConstraint("AH", "java/lang/Object", Relation.EXTENDS)); - lmc.add(new MethodConstraint("AL", "java/lang/Object", Relation.EXTENDS)); - methodConstraintsWithPositionTest.put("TPH ALmain(TPH AGTPH AH)", lmc); - - FamilyOfGeneratedGenerics fogg = compiler.fogg; - Set computedClassCons = new HashSet<>(fogg.classConstraints); - Set expectedClassCons = new HashSet<>(classConstraintsTest); - - assertEquals(expectedClassCons, computedClassCons); - - HashMap> methodConstraintsWithPositionComputed = new HashMap<>(); - fogg.methodConstraintsWithPosition.forEach((s, l) -> methodConstraintsWithPositionComputed.put(s,new HashSet<>(l))); - - assertEquals(methodConstraintsWithPositionTest, methodConstraintsWithPositionComputed); - - compiler.generateBytecode(new File(pathToClassFile), results, simplifyResultsForAllSourceFiles); - loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); - classToTest = loader.loadClass(className); - instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); - } - - @Test - public void TestMutualRecursionWithField() throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { - className = "TestMutualRecursionWithField"; - execute(new File(rootDirectory+className+".jav")); - } - - @Test - public void TestMutualRecursionWithField2() throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { - className = "TestMutualRecursionWithField2"; - execute(new File(rootDirectory+className+".jav")); - } - - @Test - public void TestMutualRecursionWithField3() throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { - className = "TestMutualRecursionWithField3"; - execute(new File(rootDirectory+className+".jav")); - } - - private static class TestResultSet{ - - } - - public TestResultSet execute(File fileToTest) throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { - JavaTXCompiler compiler = new JavaTXCompiler(fileToTest); - List results = compiler.typeInference(); - List simplifyResultsForAllSourceFiles = compiler.getGeneratedGenericResultsForAllSourceFiles(results); - compiler.generateBytecode(new File(pathToClassFile), results, simplifyResultsForAllSourceFiles); - loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); - classToTest = loader.loadClass(className); - instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); - return new TestResultSet(); - } -} diff --git a/src/test/java/insertGenerics/TestReturnVar.java b/src/test/java/insertGenerics/TestReturnVar.java deleted file mode 100644 index 6c66cc73..00000000 --- a/src/test/java/insertGenerics/TestReturnVar.java +++ /dev/null @@ -1,79 +0,0 @@ -package insertGenerics; - -import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.GenericGenratorResultForSourceFile; -import de.dhbwstuttgart.core.JavaTXCompiler; -import de.dhbwstuttgart.syntaxtree.SourceFile; -import de.dhbwstuttgart.syntaxtree.visual.ASTPrinter; -import de.dhbwstuttgart.syntaxtree.visual.ASTTypePrinter; -import de.dhbwstuttgart.typedeployment.TypeInsert; -import de.dhbwstuttgart.typedeployment.TypeInsertFactory; -import de.dhbwstuttgart.typeinference.result.ResultSet; - -import org.junit.BeforeClass; -import org.junit.Test; - -import java.io.File; -import java.io.IOException; -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -public class TestReturnVar { - - public static final String rootDirectory = System.getProperty("user.dir")+"/resources/insertGenericsJav/"; - - @BeforeClass - public static void resetNamesOfTypePlaceholder() { - de.dhbwstuttgart.syntaxtree.factory.NameGenerator.reset(); - } - - @Test - public void ggFinder() throws IOException, ClassNotFoundException { - execute(new File(rootDirectory+"TestReturnVar.jav")); - } - - private static class TestResultSet{ - - } - - public TestResultSet execute(File fileToTest) throws IOException, ClassNotFoundException { - JavaTXCompiler compiler = new JavaTXCompiler(fileToTest); - for(File f : compiler.sourceFiles.keySet()){ - SourceFile sf = compiler.sourceFiles.get(f); - } - List results = compiler.typeInference(); - List simplifyResultsForAllSourceFiles = compiler.getGeneratedGenericResultsForAllSourceFiles(results); - //compiler.generateBytecode(rootDirectory+"xxx.class", results, simplifyResultsForAllSourceFiles); - for(File f : compiler.sourceFiles.keySet()){ - SourceFile sf = compiler.sourceFiles.get(f); - System.out.println(ASTTypePrinter.print(sf)); - System.out.println(ASTPrinter.print(sf)); - //List results = compiler.typeInference(); PL 2017-10-03 vor die For-Schleife gezogen - assert results.size()>0; - Set insertedTypes = new HashSet<>(); - for(ResultSet resultSet : results){ - Set result = TypeInsertFactory.createTypeInsertPoints(sf, resultSet, results, simplifyResultsForAllSourceFiles); - assert result.size()>0; - String content = readFile(f.getPath(), StandardCharsets.UTF_8); - for(TypeInsert tip : result){ - insertedTypes.add(tip.insert(content)); - } - } - for(String s : insertedTypes){ - System.out.println(s); - } - } - return new TestResultSet(); - } - - static String readFile(String path, Charset encoding) - throws IOException - { - byte[] encoded = Files.readAllBytes(Paths.get(path)); - return new String(encoded, encoding); - } -} diff --git a/src/test/java/insertGenerics/TestSecondLineOfClassConstraints.java b/src/test/java/insertGenerics/TestSecondLineOfClassConstraints.java deleted file mode 100644 index 73a72ed4..00000000 --- a/src/test/java/insertGenerics/TestSecondLineOfClassConstraints.java +++ /dev/null @@ -1,79 +0,0 @@ -package insertGenerics; - -import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.GenericGenratorResultForSourceFile; -import de.dhbwstuttgart.core.JavaTXCompiler; -import de.dhbwstuttgart.syntaxtree.SourceFile; -import de.dhbwstuttgart.syntaxtree.visual.ASTPrinter; -import de.dhbwstuttgart.syntaxtree.visual.ASTTypePrinter; -import de.dhbwstuttgart.typedeployment.TypeInsert; -import de.dhbwstuttgart.typedeployment.TypeInsertFactory; -import de.dhbwstuttgart.typeinference.result.ResultSet; - -import org.junit.BeforeClass; -import org.junit.Test; - -import java.io.File; -import java.io.IOException; -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -public class TestSecondLineOfClassConstraints { - - public static final String rootDirectory = System.getProperty("user.dir")+"/resources/insertGenericsJav/"; - - @BeforeClass - public static void resetNamesOfTypePlaceholder() { - de.dhbwstuttgart.syntaxtree.factory.NameGenerator.reset(); - } - - @Test - public void ggFinder() throws IOException, ClassNotFoundException { - execute(new File(rootDirectory+"TestSecondLineOfClassConstraints.jav")); - } - - private static class TestResultSet{ - - } - - public TestResultSet execute(File fileToTest) throws IOException, ClassNotFoundException { - JavaTXCompiler compiler = new JavaTXCompiler(fileToTest); - for(File f : compiler.sourceFiles.keySet()){ - SourceFile sf = compiler.sourceFiles.get(f); - } - List results = compiler.typeInference(); - List simplifyResultsForAllSourceFiles = compiler.getGeneratedGenericResultsForAllSourceFiles(results); - //compiler.generateBytecode(rootDirectory+"xxx.class", results, simplifyResultsForAllSourceFiles); - for(File f : compiler.sourceFiles.keySet()){ - SourceFile sf = compiler.sourceFiles.get(f); - System.out.println(ASTTypePrinter.print(sf)); - System.out.println(ASTPrinter.print(sf)); - //List results = compiler.typeInference(); PL 2017-10-03 vor die For-Schleife gezogen - assert results.size()>0; - Set insertedTypes = new HashSet<>(); - for(ResultSet resultSet : results){ - Set result = TypeInsertFactory.createTypeInsertPoints(sf, resultSet, results, simplifyResultsForAllSourceFiles); - assert result.size()>0; - String content = readFile(f.getPath(), StandardCharsets.UTF_8); - for(TypeInsert tip : result){ - insertedTypes.add(tip.insert(content)); - } - } - for(String s : insertedTypes){ - System.out.println(s); - } - } - return new TestResultSet(); - } - - static String readFile(String path, Charset encoding) - throws IOException - { - byte[] encoded = Files.readAllBytes(Paths.get(path)); - return new String(encoded, encoding); - } -} diff --git a/src/test/java/insertGenerics/TestTPHsAndGenerics.java b/src/test/java/insertGenerics/TestTPHsAndGenerics.java deleted file mode 100644 index 17318b84..00000000 --- a/src/test/java/insertGenerics/TestTPHsAndGenerics.java +++ /dev/null @@ -1,154 +0,0 @@ -package insertGenerics; - - import de.dhbwstuttgart.bytecode.constraint.TPHConstraint.Relation; -import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.GenericGenratorResultForSourceFile; -import de.dhbwstuttgart.bytecode.insertGenerics.ClassConstraint; -import de.dhbwstuttgart.bytecode.insertGenerics.FamilyOfGeneratedGenerics; -import de.dhbwstuttgart.bytecode.insertGenerics.MethodConstraint; -import de.dhbwstuttgart.core.JavaTXCompiler; - import de.dhbwstuttgart.syntaxtree.SourceFile; - import de.dhbwstuttgart.syntaxtree.visual.ASTPrinter; - import de.dhbwstuttgart.syntaxtree.visual.ASTTypePrinter; - import de.dhbwstuttgart.typedeployment.TypeInsert; - import de.dhbwstuttgart.typedeployment.TypeInsertFactory; - import de.dhbwstuttgart.typeinference.result.ResultSet; - -import org.junit.BeforeClass; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; - -import java.io.File; - import java.io.IOException; - import java.lang.reflect.InvocationTargetException; - import java.net.URL; - import java.net.URLClassLoader; - import java.nio.charset.Charset; - import java.nio.charset.StandardCharsets; - import java.nio.file.Files; - import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; - import java.util.List; - import java.util.Set; - - -public class TestTPHsAndGenerics { - - private static final String rootDirectory = System.getProperty("user.dir")+"/resources/insertGenericsJav/"; - private String pathToClassFile = System.getProperty("user.dir")+"/resources/testBytecode/generatedBC/"; - private static ClassLoader loader; - private static Class classToTest; - private static Object instanceOfClass; - private static String className = "TestTPHsAndGenerics"; - - @BeforeClass - public static void resetNamesOfTypePlaceholder() { - de.dhbwstuttgart.syntaxtree.factory.NameGenerator.reset(); - } - - @Test - public void ggFinder() throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { - execute(new File(rootDirectory+className+".jav")); - } - - private static class TestResultSet{ - - } - - public TestResultSet execute(File fileToTest) throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { - JavaTXCompiler compiler = new JavaTXCompiler(fileToTest); - List results = compiler.typeInference(); - List simplifyResultsForAllSourceFiles = compiler.getGeneratedGenericResultsForAllSourceFiles(results); - - List classConstraintsTest = new ArrayList<>(); - HashMap> methodConstraintsWithPositionTest = new HashMap<>(); - - FamilyOfGeneratedGenerics fogg = compiler.fogg; - - Set lmc; - lmc = new HashSet<>(); - - if (fogg.allConstraints.contains((new MethodConstraint("DZP", "ETW", Relation.EXTENDS)))) { - classConstraintsTest.add(new ClassConstraint("UD", "DZP", Relation.EXTENDS)); - classConstraintsTest.add(new ClassConstraint("DZP", "ETW", Relation.EXTENDS)); - classConstraintsTest.add(new ClassConstraint("ETW", "java/lang/Object", Relation.EXTENDS)); - - lmc.add(new MethodConstraint("AI", "AE", Relation.EXTENDS)); - lmc.add(new MethodConstraint("AD", "AI", Relation.EXTENDS)); - //lmc.add(new MethodConstraint("AB", "AM", Relation.EXTENDS)); - lmc.add(new MethodConstraint("AE", "java/lang/Object", Relation.EXTENDS)); - lmc.add(new MethodConstraint("AB", "java/lang/Object", Relation.EXTENDS)); - methodConstraintsWithPositionTest.put("TPH ABm(TPH ABTPH AD)", lmc); - lmc = new HashSet<>(); - lmc.add(new MethodConstraint("V", "UD", Relation.EXTENDS)); - methodConstraintsWithPositionTest.put("TPH ETWid2(TPH V)", lmc); - lmc = new HashSet<>(); - lmc.add(new MethodConstraint("AM", "java/lang/Object", Relation.EXTENDS)); - lmc.add(new MethodConstraint("AI", "java/lang/Object", Relation.EXTENDS)); - methodConstraintsWithPositionTest.put("TPH AIm2(TPH AMTPH AI)", lmc); - } else { - if (fogg.allConstraints.contains((new MethodConstraint("DZP", "U", Relation.EXTENDS)))) { - classConstraintsTest.add(new ClassConstraint("ETW", "DZP", Relation.EXTENDS)); - classConstraintsTest.add(new ClassConstraint("DZP", "U", Relation.EXTENDS)); - classConstraintsTest.add(new ClassConstraint("U", "java/lang/Object", Relation.EXTENDS)); - - lmc.add(new MethodConstraint("AI", "AE", Relation.EXTENDS)); - lmc.add(new MethodConstraint("AD", "AI", Relation.EXTENDS)); - //lmc.add(new MethodConstraint("AB", "AM", Relation.EXTENDS)); - lmc.add(new MethodConstraint("AE", "java/lang/Object", Relation.EXTENDS)); - lmc.add(new MethodConstraint("AB", "java/lang/Object", Relation.EXTENDS)); - methodConstraintsWithPositionTest.put("TPH ABm(TPH ABTPH AD)", lmc); - lmc = new HashSet<>(); - lmc.add(new MethodConstraint("V", "ETW", Relation.EXTENDS)); - methodConstraintsWithPositionTest.put("TPH Uid2(TPH V)", lmc); - lmc = new HashSet<>(); - lmc.add(new MethodConstraint("AM", "java/lang/Object", Relation.EXTENDS)); - lmc.add(new MethodConstraint("AI", "java/lang/Object", Relation.EXTENDS)); - methodConstraintsWithPositionTest.put("TPH AIm2(TPH AMTPH AI)", lmc); - } else { - if (fogg.allConstraints.contains((new MethodConstraint("EIM", "FEA", Relation.EXTENDS)))) { - classConstraintsTest.add(new ClassConstraint("VK", "EIM", Relation.EXTENDS)); - classConstraintsTest.add(new ClassConstraint("EIM", "FEA", Relation.EXTENDS)); - classConstraintsTest.add(new ClassConstraint("FEA", "java/lang/Object", Relation.EXTENDS)); - - lmc.add(new MethodConstraint("AI", "AE", Relation.EXTENDS)); - lmc.add(new MethodConstraint("AD", "AI", Relation.EXTENDS)); - //lmc.add(new MethodConstraint("AB", "AM", Relation.EXTENDS)); - lmc.add(new MethodConstraint("AE", "java/lang/Object", Relation.EXTENDS)); - lmc.add(new MethodConstraint("AB", "java/lang/Object", Relation.EXTENDS)); - methodConstraintsWithPositionTest.put("TPH ABm(TPH ABTPH AD)", lmc); - lmc = new HashSet<>(); - lmc.add(new MethodConstraint("V", "VK", Relation.EXTENDS)); - methodConstraintsWithPositionTest.put("TPH FEAid2(TPH V)", lmc); - lmc = new HashSet<>(); - lmc.add(new MethodConstraint("AM", "java/lang/Object", Relation.EXTENDS)); - lmc.add(new MethodConstraint("AI", "java/lang/Object", Relation.EXTENDS)); - methodConstraintsWithPositionTest.put("TPH AIm2(TPH AMTPH AI)", lmc); - } - } - - } - - - Set computedClassCons = new HashSet<>(fogg.classConstraints); - Set expectedClassCons = new HashSet<>(classConstraintsTest); - - assertEquals(expectedClassCons, computedClassCons); - - HashMap> methodConstraintsWithPositionComputed = new HashMap<>(); - fogg.methodConstraintsWithPosition.forEach((s, l) -> methodConstraintsWithPositionComputed.put(s,new HashSet<>(l))); - - assertEquals(methodConstraintsWithPositionTest, methodConstraintsWithPositionComputed); - - /* - compiler.generateBytecode(new File(pathToClassFile), results, simplifyResultsForAllSourceFiles); - loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); - classToTest = loader.loadClass(className); - instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); - */ - return new TestResultSet(); - - } - } diff --git a/src/test/java/insertGenerics/TestTPHsAndGenerics2.java b/src/test/java/insertGenerics/TestTPHsAndGenerics2.java deleted file mode 100644 index cd24b974..00000000 --- a/src/test/java/insertGenerics/TestTPHsAndGenerics2.java +++ /dev/null @@ -1,79 +0,0 @@ -package insertGenerics; - -import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.GenericGenratorResultForSourceFile; -import de.dhbwstuttgart.core.JavaTXCompiler; -import de.dhbwstuttgart.syntaxtree.SourceFile; -import de.dhbwstuttgart.syntaxtree.visual.ASTPrinter; -import de.dhbwstuttgart.syntaxtree.visual.ASTTypePrinter; -import de.dhbwstuttgart.typedeployment.TypeInsert; -import de.dhbwstuttgart.typedeployment.TypeInsertFactory; -import de.dhbwstuttgart.typeinference.result.ResultSet; - -import org.junit.BeforeClass; -import org.junit.Test; - -import java.io.File; -import java.io.IOException; -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -public class TestTPHsAndGenerics2 { - - public static final String rootDirectory = System.getProperty("user.dir")+"/resources/insertGenericsJav/"; - - @BeforeClass - public static void resetNamesOfTypePlaceholder() { - de.dhbwstuttgart.syntaxtree.factory.NameGenerator.reset(); - } - - @Test - public void ggFinder() throws IOException, ClassNotFoundException { - execute(new File(rootDirectory+"TestTPHSAndGenerics2.jav")); - } - - private static class TestResultSet{ - - } - - public TestResultSet execute(File fileToTest) throws IOException, ClassNotFoundException { - JavaTXCompiler compiler = new JavaTXCompiler(fileToTest); - for(File f : compiler.sourceFiles.keySet()){ - SourceFile sf = compiler.sourceFiles.get(f); - } - List results = compiler.typeInference(); - List simplifyResultsForAllSourceFiles = compiler.getGeneratedGenericResultsForAllSourceFiles(results); - //compiler.generateBytecode(rootDirectory+"xxx.class", results, simplifyResultsForAllSourceFiles); - for(File f : compiler.sourceFiles.keySet()){ - SourceFile sf = compiler.sourceFiles.get(f); - System.out.println(ASTTypePrinter.print(sf)); - System.out.println(ASTPrinter.print(sf)); - //List results = compiler.typeInference(); PL 2017-10-03 vor die For-Schleife gezogen - assert results.size()>0; - Set insertedTypes = new HashSet<>(); - for(ResultSet resultSet : results){ - Set result = TypeInsertFactory.createTypeInsertPoints(sf, resultSet, results, simplifyResultsForAllSourceFiles); - assert result.size()>0; - String content = readFile(f.getPath(), StandardCharsets.UTF_8); - for(TypeInsert tip : result){ - insertedTypes.add(tip.insert(content)); - } - } - for(String s : insertedTypes){ - System.out.println(s); - } - } - return new TestResultSet(); - } - - static String readFile(String path, Charset encoding) - throws IOException - { - byte[] encoded = Files.readAllBytes(Paths.get(path)); - return new String(encoded, encoding); - } -} diff --git a/src/test/java/insertGenerics/TestThreeArgs.java b/src/test/java/insertGenerics/TestThreeArgs.java deleted file mode 100644 index a7c0c09e..00000000 --- a/src/test/java/insertGenerics/TestThreeArgs.java +++ /dev/null @@ -1,99 +0,0 @@ -package insertGenerics; - -import de.dhbwstuttgart.bytecode.constraint.TPHConstraint.Relation; -import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.GenericGenratorResultForSourceFile; -import de.dhbwstuttgart.bytecode.insertGenerics.ClassConstraint; -import de.dhbwstuttgart.bytecode.insertGenerics.FamilyOfGeneratedGenerics; -import de.dhbwstuttgart.bytecode.insertGenerics.MethodConstraint; -import de.dhbwstuttgart.core.JavaTXCompiler; -import de.dhbwstuttgart.syntaxtree.SourceFile; -import de.dhbwstuttgart.syntaxtree.visual.ASTPrinter; -import de.dhbwstuttgart.syntaxtree.visual.ASTTypePrinter; -import de.dhbwstuttgart.typedeployment.TypeInsert; -import de.dhbwstuttgart.typedeployment.TypeInsertFactory; -import de.dhbwstuttgart.typeinference.result.ResultSet; - -import org.junit.BeforeClass; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; - -import java.io.File; -import java.io.IOException; -import java.lang.reflect.InvocationTargetException; -import java.net.URL; -import java.net.URLClassLoader; -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -public class TestThreeArgs { - - private static final String rootDirectory = System.getProperty("user.dir")+"/resources/insertGenericsJav/"; - private String pathToClassFile = System.getProperty("user.dir")+"/resources/testBytecode/generatedBC/"; - private static ClassLoader loader; - private static Class classToTest; - private static Object instanceOfClass; - private static String className = "TestThreeArgs"; - - @BeforeClass - public static void resetNamesOfTypePlaceholder() { - de.dhbwstuttgart.syntaxtree.factory.NameGenerator.reset(); - } - - @Test - public void ggFinder() throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { - execute(new File(rootDirectory+className+".jav")); - } - - private static class TestResultSet{ - - } - - public TestResultSet execute(File fileToTest) throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { - JavaTXCompiler compiler = new JavaTXCompiler(fileToTest); - List results = compiler.typeInference(); - List simplifyResultsForAllSourceFiles = compiler.getGeneratedGenericResultsForAllSourceFiles(results); - - List classConstraintsTest = new ArrayList<>(); - classConstraintsTest.add(new ClassConstraint("N", "java/lang/Object", Relation.EXTENDS)); - HashMap> methodConstraintsWithPositionTest = new HashMap<>(); - Set lmc; - lmc = new HashSet<>(); - lmc.add(new MethodConstraint("P", "AF", Relation.EXTENDS)); - lmc.add(new MethodConstraint("Q", "java/lang/Object", Relation.EXTENDS)); - lmc.add(new MethodConstraint("AF", "java/lang/Object", Relation.EXTENDS)); - methodConstraintsWithPositionTest.put("TPH AFid(TPH P)", lmc); - lmc = new HashSet<>(); - lmc.add(new MethodConstraint("AF", "W", Relation.EXTENDS)); - lmc.add(new MethodConstraint("AB", "P", Relation.EXTENDS)); - lmc.add(new MethodConstraint("P", "AF", Relation.EXTENDS)); - lmc.add(new MethodConstraint("AC", "java/lang/Object", Relation.EXTENDS)); - lmc.add(new MethodConstraint("W", "java/lang/Object", Relation.EXTENDS)); - methodConstraintsWithPositionTest.put("TPH Wm(TPH WTPH ABTPH AC)", lmc); - - FamilyOfGeneratedGenerics fogg = compiler.fogg; - Set computedClassCons = new HashSet<>(fogg.classConstraints); - Set expectedClassCons = new HashSet<>(classConstraintsTest); - - assertEquals(expectedClassCons, computedClassCons); - - HashMap> methodConstraintsWithPositionComputed = new HashMap<>(); - fogg.methodConstraintsWithPosition.forEach((s, l) -> methodConstraintsWithPositionComputed.put(s,new HashSet<>(l))); - - assertEquals(methodConstraintsWithPositionTest, methodConstraintsWithPositionComputed); - - compiler.generateBytecode(new File(pathToClassFile), results, simplifyResultsForAllSourceFiles); - loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); - classToTest = loader.loadClass(className); - //liefert Fehler, da Variable "a" nicht initialisiert ist. - //instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); - return new TestResultSet(); - } -} diff --git a/src/test/java/insertGenerics/TestTransitiveClosure.java b/src/test/java/insertGenerics/TestTransitiveClosure.java deleted file mode 100644 index 4eaf0527..00000000 --- a/src/test/java/insertGenerics/TestTransitiveClosure.java +++ /dev/null @@ -1,28 +0,0 @@ -package insertGenerics; - -import de.dhbwstuttgart.bytecode.constraint.TPHConstraint; -import de.dhbwstuttgart.bytecode.constraint.TPHConstraint.Relation; -import de.dhbwstuttgart.bytecode.insertGenerics.FamilyOfGeneratedGenerics; -import org.junit.Test; -import static org.junit.Assert.assertEquals; - -import java.util.ArrayList; -import java.util.List; - -public class TestTransitiveClosure { - public List fillList() { - List list = new ArrayList<>(); - list.add(new TPHConstraint("A", "B", Relation.EXTENDS)); - list.add(new TPHConstraint("B", "C", Relation.EXTENDS)); - list.add(new TPHConstraint("C", "D", Relation.EXTENDS)); - - return list; - } - - @Test - public void genericTest() { - //List testCons = FamilyOfGeneratedGenerics.buildTransitiveClosure(fillList()); - //System.out.println(testCons); - - } -} diff --git a/src/test/java/insertGenerics/TestTwoArgs.java b/src/test/java/insertGenerics/TestTwoArgs.java deleted file mode 100644 index b21bb99b..00000000 --- a/src/test/java/insertGenerics/TestTwoArgs.java +++ /dev/null @@ -1,111 +0,0 @@ -package insertGenerics; - -import static org.junit.Assert.*; - -import de.dhbwstuttgart.bytecode.constraint.TPHConstraint; -import de.dhbwstuttgart.bytecode.constraint.TPHConstraint.Relation; -import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.GenericGenratorResultForSourceFile; -import de.dhbwstuttgart.bytecode.insertGenerics.ClassConstraint; -import de.dhbwstuttgart.bytecode.insertGenerics.FamilyOfGeneratedGenerics; -import de.dhbwstuttgart.bytecode.insertGenerics.MethodConstraint; -import de.dhbwstuttgart.core.JavaTXCompiler; -import de.dhbwstuttgart.syntaxtree.SourceFile; -import de.dhbwstuttgart.syntaxtree.visual.ASTPrinter; -import de.dhbwstuttgart.syntaxtree.visual.ASTTypePrinter; -import de.dhbwstuttgart.typedeployment.TypeInsert; -import de.dhbwstuttgart.typedeployment.TypeInsertFactory; -import de.dhbwstuttgart.typeinference.result.ResultSet; - -import org.junit.BeforeClass; -import org.junit.Test; - -import java.io.File; -import java.io.IOException; -import java.lang.reflect.InvocationTargetException; -import java.net.URL; -import java.net.URLClassLoader; -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -public class TestTwoArgs { - - private static final String rootDirectory = System.getProperty("user.dir")+"/resources/insertGenericsJav/"; - private String pathToClassFile = System.getProperty("user.dir")+"/resources/testBytecode/generatedBC/"; - private static ClassLoader loader; - private static Class classToTest; - private static Object instanceOfClass; - private static String className = "TestTwoArgs"; - - @BeforeClass - public static void resetNamesOfTypePlaceholder() { - de.dhbwstuttgart.syntaxtree.factory.NameGenerator.reset(); - } - - @Test - public void ggFinder() throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { - execute(new File(rootDirectory+className+".jav")); - } - - private static class TestResultSet{ - - } - - public TestResultSet execute(File fileToTest) throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { - JavaTXCompiler compiler = new JavaTXCompiler(fileToTest); - List results = compiler.typeInference(); - List simplifyResultsForAllSourceFiles = compiler.getGeneratedGenericResultsForAllSourceFiles(results); - - List classConstraintsTest = new ArrayList<>(); - classConstraintsTest.add(new ClassConstraint("AP", "Z", Relation.EXTENDS)); - classConstraintsTest.add(new ClassConstraint("Z", "P", Relation.EXTENDS)); - classConstraintsTest.add(new ClassConstraint("P", "AL", Relation.EXTENDS)); - classConstraintsTest.add(new ClassConstraint("AL", "AF", Relation.EXTENDS)); - classConstraintsTest.add(new ClassConstraint("AF", "java/lang/Object", Relation.EXTENDS)); - HashMap> methodConstraintsWithPositionTest = new HashMap<>(); - Set lmc; - lmc = new HashSet<>(); - lmc.add(new MethodConstraint("P", "AL", Relation.EXTENDS)); - lmc.add(new MethodConstraint("AL", "java/lang/Object", Relation.EXTENDS)); - methodConstraintsWithPositionTest.put("TPH ALid(TPH P)", lmc); - lmc = new HashSet<>(); - lmc.add(new MethodConstraint("AL", "AF", Relation.EXTENDS)); - lmc.add(new MethodConstraint("Z", "P", Relation.EXTENDS)); - lmc.add(new MethodConstraint("P", "AL", Relation.EXTENDS)); - lmc.add(new MethodConstraint("AF", "java/lang/Object", Relation.EXTENDS)); - methodConstraintsWithPositionTest.put("TPH AFm(TPH AFTPH Z)", lmc); - lmc = new HashSet<>(); - lmc.add(new MethodConstraint("T", "AP", Relation.EXTENDS)); - methodConstraintsWithPositionTest.put("TPH APsetA(TPH T)", lmc); - lmc = new HashSet<>(); - lmc.add(new MethodConstraint("AG", "P", Relation.EXTENDS)); - lmc.add(new MethodConstraint("AH", "T", Relation.EXTENDS)); - lmc.add(new MethodConstraint("T", "AP", Relation.EXTENDS)); - lmc.add(new MethodConstraint("AL", "AF", Relation.EXTENDS)); - lmc.add(new MethodConstraint("P", "AL", Relation.EXTENDS)); - methodConstraintsWithPositionTest.put("TPH AFmain(TPH AGTPH AH)", lmc); - - FamilyOfGeneratedGenerics fogg = compiler.fogg; - Set computedClassCons = new HashSet<>(fogg.classConstraints); - Set expectedClassCons = new HashSet<>(classConstraintsTest); - - assertEquals(expectedClassCons, computedClassCons); - - HashMap> methodConstraintsWithPositionComputed = new HashMap<>(); - fogg.methodConstraintsWithPosition.forEach((s, l) -> methodConstraintsWithPositionComputed.put(s,new HashSet<>(l))); - - assertEquals(methodConstraintsWithPositionTest, methodConstraintsWithPositionComputed); - - compiler.generateBytecode(new File(pathToClassFile), results, simplifyResultsForAllSourceFiles); - loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); - classToTest = loader.loadClass(className); - instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); - return new TestResultSet(); - } -} diff --git a/src/test/java/insertGenerics/TestTwoArgs2.java b/src/test/java/insertGenerics/TestTwoArgs2.java deleted file mode 100644 index f9168a20..00000000 --- a/src/test/java/insertGenerics/TestTwoArgs2.java +++ /dev/null @@ -1,105 +0,0 @@ -package insertGenerics; - -import de.dhbwstuttgart.bytecode.constraint.TPHConstraint.Relation; -import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.GenericGenratorResultForSourceFile; -import de.dhbwstuttgart.bytecode.insertGenerics.ClassConstraint; -import de.dhbwstuttgart.bytecode.insertGenerics.FamilyOfGeneratedGenerics; -import de.dhbwstuttgart.bytecode.insertGenerics.MethodConstraint; -import de.dhbwstuttgart.core.JavaTXCompiler; -import de.dhbwstuttgart.syntaxtree.SourceFile; -import de.dhbwstuttgart.syntaxtree.visual.ASTPrinter; -import de.dhbwstuttgart.syntaxtree.visual.ASTTypePrinter; -import de.dhbwstuttgart.typedeployment.TypeInsert; -import de.dhbwstuttgart.typedeployment.TypeInsertFactory; -import de.dhbwstuttgart.typeinference.result.ResultSet; - -import org.junit.BeforeClass; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; - -import java.io.File; -import java.io.IOException; -import java.lang.reflect.InvocationTargetException; -import java.net.URL; -import java.net.URLClassLoader; -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -public class TestTwoArgs2 { - - private static final String rootDirectory = System.getProperty("user.dir")+"/resources/insertGenericsJav/"; - private String pathToClassFile = System.getProperty("user.dir")+"/resources/testBytecode/generatedBC/"; - private static ClassLoader loader; - private static Class classToTest; - private static Object instanceOfClass; - private static String className = "TestTwoArgs2"; - - @BeforeClass - public static void resetNamesOfTypePlaceholder() { - de.dhbwstuttgart.syntaxtree.factory.NameGenerator.reset(); - } - - @Test - public void ggFinder() throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { - execute(new File(rootDirectory+className+".jav")); - } - - private static class TestResultSet{ - - } - - public TestResultSet execute(File fileToTest) throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { - JavaTXCompiler compiler = new JavaTXCompiler(fileToTest); - List results = compiler.typeInference(); - List simplifyResultsForAllSourceFiles = compiler.getGeneratedGenericResultsForAllSourceFiles(results); - - List classConstraintsTest = new ArrayList<>(); - classConstraintsTest.add(new ClassConstraint("N", "java/lang/Object", Relation.EXTENDS)); - HashMap> methodConstraintsWithPositionTest = new HashMap<>(); - Set lmc; - lmc = new HashSet<>(); - lmc.add(new MethodConstraint("AG", "AA", Relation.EXTENDS)); - lmc.add(new MethodConstraint("U", "P", Relation.EXTENDS)); - lmc.add(new MethodConstraint("P", "AG", Relation.EXTENDS)); - lmc.add(new MethodConstraint("AA", "java/lang/Object", Relation.EXTENDS)); - methodConstraintsWithPositionTest.put("TPH AAm(TPH AATPH U)", lmc); - lmc = new HashSet<>(); - lmc.add(new MethodConstraint("AB", "P", Relation.EXTENDS)); - lmc.add(new MethodConstraint("AC", "U", Relation.EXTENDS)); - lmc.add(new MethodConstraint("AB", "AA", Relation.EXTENDS)); - lmc.add(new MethodConstraint("AA", "U", Relation.EXTENDS)); - lmc.add(new MethodConstraint("AG", "AA", Relation.EXTENDS)); - lmc.add(new MethodConstraint("U", "AA", Relation.EXTENDS)); - lmc.add(new MethodConstraint("P", "AG", Relation.EXTENDS)); - methodConstraintsWithPositionTest.put("TPH AAmain(TPH ABTPH AC)", lmc); - lmc = new HashSet<>(); - lmc.add(new MethodConstraint("P", "AG", Relation.EXTENDS)); - lmc.add(new MethodConstraint("AG", "java/lang/Object", Relation.EXTENDS)); - methodConstraintsWithPositionTest.put("TPH AGid(TPH P)", lmc); - - FamilyOfGeneratedGenerics fogg = compiler.fogg; - Set computedClassCons = new HashSet<>(fogg.classConstraints); - Set expectedClassCons = new HashSet<>(classConstraintsTest); - - assertEquals(expectedClassCons, computedClassCons); - - HashMap> methodConstraintsWithPositionComputed = new HashMap<>(); - fogg.methodConstraintsWithPosition.forEach((s, l) -> methodConstraintsWithPositionComputed.put(s,new HashSet<>(l))); - - assertEquals(methodConstraintsWithPositionTest, methodConstraintsWithPositionComputed); - - compiler.generateBytecode(new File(pathToClassFile), results, simplifyResultsForAllSourceFiles); - loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); - classToTest = loader.loadClass(className); - instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); - return new TestResultSet(); - } -} diff --git a/src/test/java/insertGenerics/TestTwoCalls.java b/src/test/java/insertGenerics/TestTwoCalls.java deleted file mode 100644 index e5331fca..00000000 --- a/src/test/java/insertGenerics/TestTwoCalls.java +++ /dev/null @@ -1,95 +0,0 @@ -package insertGenerics; - -import de.dhbwstuttgart.bytecode.constraint.TPHConstraint.Relation; -import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.GenericGenratorResultForSourceFile; -import de.dhbwstuttgart.bytecode.insertGenerics.ClassConstraint; -import de.dhbwstuttgart.bytecode.insertGenerics.FamilyOfGeneratedGenerics; -import de.dhbwstuttgart.bytecode.insertGenerics.MethodConstraint; -import de.dhbwstuttgart.core.JavaTXCompiler; -import de.dhbwstuttgart.syntaxtree.SourceFile; -import de.dhbwstuttgart.syntaxtree.visual.ASTPrinter; -import de.dhbwstuttgart.syntaxtree.visual.ASTTypePrinter; -import de.dhbwstuttgart.typedeployment.TypeInsert; -import de.dhbwstuttgart.typedeployment.TypeInsertFactory; -import de.dhbwstuttgart.typeinference.result.ResultSet; - -import org.junit.BeforeClass; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; - -import java.io.File; -import java.io.IOException; -import java.lang.reflect.InvocationTargetException; -import java.net.URL; -import java.net.URLClassLoader; -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -public class TestTwoCalls { - - private static final String rootDirectory = System.getProperty("user.dir")+"/resources/insertGenericsJav/"; - private String pathToClassFile = System.getProperty("user.dir")+"/resources/testBytecode/generatedBC/"; - private static ClassLoader loader; - private static Class classToTest; - private static Object instanceOfClass; - private static String className = "TestTwoCalls"; - - @BeforeClass - public static void resetNamesOfTypePlaceholder() { - de.dhbwstuttgart.syntaxtree.factory.NameGenerator.reset(); - } - - @Test - public void ggFinder() throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { - execute(new File(rootDirectory+className+".jav")); - } - - private static class TestResultSet{ - - } - - public TestResultSet execute(File fileToTest) throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { - JavaTXCompiler compiler = new JavaTXCompiler(fileToTest); - List results = compiler.typeInference(); - List simplifyResultsForAllSourceFiles = compiler.getGeneratedGenericResultsForAllSourceFiles(results); - - List classConstraintsTest = new ArrayList<>(); - HashMap> methodConstraintsWithPositionTest = new HashMap<>(); - Set lmc; - lmc = new HashSet<>(); - lmc.add(new MethodConstraint("O", "R", Relation.EXTENDS)); - lmc.add(new MethodConstraint("R", "java/lang/Object", Relation.EXTENDS)); - methodConstraintsWithPositionTest.put("TPH Rid(TPH O)", lmc); - lmc = new HashSet<>(); - lmc.add(new MethodConstraint("T", "O", Relation.EXTENDS)); - lmc.add(new MethodConstraint("O", "R", Relation.EXTENDS)); - lmc.add(new MethodConstraint("R", "java/lang/Object", Relation.EXTENDS)); - lmc.add(new MethodConstraint("S", "java/lang/Object", Relation.EXTENDS)); - methodConstraintsWithPositionTest.put("TPH Rmain(TPH STPH T)", lmc); - - FamilyOfGeneratedGenerics fogg = compiler.fogg; - Set computedClassCons = new HashSet<>(fogg.classConstraints); - Set expectedClassCons = new HashSet<>(classConstraintsTest); - - assertEquals(expectedClassCons, computedClassCons); - - HashMap> methodConstraintsWithPositionComputed = new HashMap<>(); - fogg.methodConstraintsWithPosition.forEach((s, l) -> methodConstraintsWithPositionComputed.put(s,new HashSet<>(l))); - - assertEquals(methodConstraintsWithPositionTest, methodConstraintsWithPositionComputed); - - compiler.generateBytecode(new File(pathToClassFile), results, simplifyResultsForAllSourceFiles); - loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); - classToTest = loader.loadClass(className); - instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); - return new TestResultSet(); - } -} diff --git a/src/test/java/insertGenerics/TestVector.java b/src/test/java/insertGenerics/TestVector.java deleted file mode 100644 index b8e42c21..00000000 --- a/src/test/java/insertGenerics/TestVector.java +++ /dev/null @@ -1,92 +0,0 @@ -package insertGenerics; - -import de.dhbwstuttgart.bytecode.constraint.TPHConstraint.Relation; -import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.GenericGenratorResultForSourceFile; -import de.dhbwstuttgart.bytecode.insertGenerics.ClassConstraint; -import de.dhbwstuttgart.bytecode.insertGenerics.FamilyOfGeneratedGenerics; -import de.dhbwstuttgart.bytecode.insertGenerics.MethodConstraint; -import de.dhbwstuttgart.core.JavaTXCompiler; -import de.dhbwstuttgart.syntaxtree.SourceFile; -import de.dhbwstuttgart.syntaxtree.visual.ASTPrinter; -import de.dhbwstuttgart.syntaxtree.visual.ASTTypePrinter; -import de.dhbwstuttgart.typedeployment.TypeInsert; -import de.dhbwstuttgart.typedeployment.TypeInsertFactory; -import de.dhbwstuttgart.typeinference.result.ResultSet; - -import org.junit.BeforeClass; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; - -import java.io.File; -import java.io.IOException; -import java.lang.reflect.InvocationTargetException; -import java.net.URL; -import java.net.URLClassLoader; -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -public class TestVector { - - private static final String rootDirectory = System.getProperty("user.dir")+"/resources/insertGenericsJav/"; - private String pathToClassFile = System.getProperty("user.dir")+"/resources/testBytecode/generatedBC/"; - private static ClassLoader loader; - private static Class classToTest; - private static Object instanceOfClass; - private static String className = "TestVector"; - - @BeforeClass - public static void resetNamesOfTypePlaceholder() { - de.dhbwstuttgart.syntaxtree.factory.NameGenerator.reset(); - } - - @Test - public void ggFinder() throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { - execute(new File(rootDirectory+className+".jav")); - } - - private static class TestResultSet{ - - } - - public TestResultSet execute(File fileToTest) throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { - JavaTXCompiler compiler = new JavaTXCompiler(fileToTest); - List results = compiler.typeInference(); - List simplifyResultsForAllSourceFiles = compiler.getGeneratedGenericResultsForAllSourceFiles(results); - - List classConstraintsTest = new ArrayList<>(); - HashMap> methodConstraintsWithPositionTest = new HashMap<>(); - Set lmc; - lmc = new HashSet<>(); - lmc.add(new MethodConstraint("T", "W", Relation.EXTENDS)); - lmc.add(new MethodConstraint("W", "ZU", Relation.EXTENDS)); - lmc.add(new MethodConstraint("ZU", "java/lang/Object", Relation.EXTENDS)); - methodConstraintsWithPositionTest.put("voidm(java/util/Vectorjava/util/Vector)", lmc); - lmc = new HashSet<>(); - lmc.add(new MethodConstraint("W", "java/lang/Object", Relation.EXTENDS)); - methodConstraintsWithPositionTest.put("TPH Wid(TPH W)", lmc); - - FamilyOfGeneratedGenerics fogg = compiler.fogg; - Set computedClassCons = new HashSet<>(fogg.classConstraints); - Set expectedClassCons = new HashSet<>(classConstraintsTest); - - assertEquals(expectedClassCons, computedClassCons); - - HashMap> methodConstraintsWithPositionComputed = new HashMap<>(); - fogg.methodConstraintsWithPosition.forEach((s, l) -> methodConstraintsWithPositionComputed.put(s,new HashSet<>(l))); - - assertEquals(methodConstraintsWithPositionTest, methodConstraintsWithPositionComputed); - compiler.generateBytecode(new File(pathToClassFile), results, simplifyResultsForAllSourceFiles); - loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); - classToTest = loader.loadClass(className); - instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); - return new TestResultSet(); - } -} diff --git a/src/test/java/insertGenerics/TestVectorArg.java b/src/test/java/insertGenerics/TestVectorArg.java deleted file mode 100644 index ff1a1b99..00000000 --- a/src/test/java/insertGenerics/TestVectorArg.java +++ /dev/null @@ -1,92 +0,0 @@ -package insertGenerics; - -import de.dhbwstuttgart.bytecode.constraint.TPHConstraint.Relation; -import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.GenericGenratorResultForSourceFile; -import de.dhbwstuttgart.bytecode.insertGenerics.ClassConstraint; -import de.dhbwstuttgart.bytecode.insertGenerics.FamilyOfGeneratedGenerics; -import de.dhbwstuttgart.bytecode.insertGenerics.MethodConstraint; -import de.dhbwstuttgart.core.JavaTXCompiler; -import de.dhbwstuttgart.syntaxtree.SourceFile; -import de.dhbwstuttgart.syntaxtree.visual.ASTPrinter; -import de.dhbwstuttgart.syntaxtree.visual.ASTTypePrinter; -import de.dhbwstuttgart.typedeployment.TypeInsert; -import de.dhbwstuttgart.typedeployment.TypeInsertFactory; -import de.dhbwstuttgart.typeinference.result.ResultSet; - -import org.junit.BeforeClass; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; - -import java.io.File; -import java.io.IOException; -import java.lang.reflect.InvocationTargetException; -import java.net.URL; -import java.net.URLClassLoader; -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -public class TestVectorArg { - - private static final String rootDirectory = System.getProperty("user.dir")+"/resources/insertGenericsJav/"; - private String pathToClassFile = System.getProperty("user.dir")+"/resources/testBytecode/generatedBC/"; - private static ClassLoader loader; - private static Class classToTest; - private static Object instanceOfClass; - private static String className = "TestVectorArg"; - - @BeforeClass - public static void resetNamesOfTypePlaceholder() { - de.dhbwstuttgart.syntaxtree.factory.NameGenerator.reset(); - } - - @Test - public void ggFinder() throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { - execute(new File(rootDirectory+className+".jav")); - } - - private static class TestResultSet{ - - } - - public TestResultSet execute(File fileToTest) throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { - JavaTXCompiler compiler = new JavaTXCompiler(fileToTest); - List results = compiler.typeInference(); - List simplifyResultsForAllSourceFiles = compiler.getGeneratedGenericResultsForAllSourceFiles(results); - - List classConstraintsTest = new ArrayList<>(); - HashMap> methodConstraintsWithPositionTest = new HashMap<>(); - Set lmc; - lmc = new HashSet<>(); - lmc.add(new MethodConstraint("T", "W", Relation.EXTENDS)); - lmc.add(new MethodConstraint("W", "ZU", Relation.EXTENDS)); - lmc.add(new MethodConstraint("ZU", "java/lang/Object", Relation.EXTENDS)); - methodConstraintsWithPositionTest.put("voidm(java/util/Vectorjava/util/Vector)", lmc); - lmc = new HashSet<>(); - lmc.add(new MethodConstraint("W", "java/lang/Object", Relation.EXTENDS)); - methodConstraintsWithPositionTest.put("TPH Wid(TPH W)", lmc); - - FamilyOfGeneratedGenerics fogg = compiler.fogg; - Set computedClassCons = new HashSet<>(fogg.classConstraints); - Set expectedClassCons = new HashSet<>(classConstraintsTest); - - //assertEquals(expectedClassCons, computedClassCons); - - HashMap> methodConstraintsWithPositionComputed = new HashMap<>(); - fogg.methodConstraintsWithPosition.forEach((s, l) -> methodConstraintsWithPositionComputed.put(s,new HashSet<>(l))); - - //assertEquals(methodConstraintsWithPositionTest, methodConstraintsWithPositionComputed); - compiler.generateBytecode(new File(pathToClassFile), results, simplifyResultsForAllSourceFiles); - loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); - classToTest = loader.loadClass(className); - instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); - return new TestResultSet(); - } -} diff --git a/src/test/java/insertGenerics/TestVoidMeth.java b/src/test/java/insertGenerics/TestVoidMeth.java deleted file mode 100644 index 3b4c1984..00000000 --- a/src/test/java/insertGenerics/TestVoidMeth.java +++ /dev/null @@ -1,79 +0,0 @@ -package insertGenerics; - -import de.dhbwstuttgart.bytecode.genericsGeneratorTypes.GenericGenratorResultForSourceFile; -import de.dhbwstuttgart.core.JavaTXCompiler; -import de.dhbwstuttgart.syntaxtree.SourceFile; -import de.dhbwstuttgart.syntaxtree.visual.ASTPrinter; -import de.dhbwstuttgart.syntaxtree.visual.ASTTypePrinter; -import de.dhbwstuttgart.typedeployment.TypeInsert; -import de.dhbwstuttgart.typedeployment.TypeInsertFactory; -import de.dhbwstuttgart.typeinference.result.ResultSet; - -import org.junit.BeforeClass; -import org.junit.Test; - -import java.io.File; -import java.io.IOException; -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -public class TestVoidMeth { - - public static final String rootDirectory = System.getProperty("user.dir")+"/resources/insertGenericsJav/"; - - @BeforeClass - public static void resetNamesOfTypePlaceholder() { - de.dhbwstuttgart.syntaxtree.factory.NameGenerator.reset(); - } - - @Test - public void ggFinder() throws IOException, ClassNotFoundException { - execute(new File(rootDirectory+"TestVoidMeth.jav")); - } - - private static class TestResultSet{ - - } - - public TestResultSet execute(File fileToTest) throws IOException, ClassNotFoundException { - JavaTXCompiler compiler = new JavaTXCompiler(fileToTest); - for(File f : compiler.sourceFiles.keySet()){ - SourceFile sf = compiler.sourceFiles.get(f); - } - List results = compiler.typeInference(); - List simplifyResultsForAllSourceFiles = compiler.getGeneratedGenericResultsForAllSourceFiles(results); - //compiler.generateBytecode(rootDirectory+"xxx.class", results, simplifyResultsForAllSourceFiles); - for(File f : compiler.sourceFiles.keySet()){ - SourceFile sf = compiler.sourceFiles.get(f); - System.out.println(ASTTypePrinter.print(sf)); - System.out.println(ASTPrinter.print(sf)); - //List results = compiler.typeInference(); PL 2017-10-03 vor die For-Schleife gezogen - assert results.size()>0; - Set insertedTypes = new HashSet<>(); - for(ResultSet resultSet : results){ - Set result = TypeInsertFactory.createTypeInsertPoints(sf, resultSet, results, simplifyResultsForAllSourceFiles); - assert result.size()>0; - String content = readFile(f.getPath(), StandardCharsets.UTF_8); - for(TypeInsert tip : result){ - insertedTypes.add(tip.insert(content)); - } - } - for(String s : insertedTypes){ - System.out.println(s); - } - } - return new TestResultSet(); - } - - static String readFile(String path, Charset encoding) - throws IOException - { - byte[] encoded = Files.readAllBytes(Paths.get(path)); - return new String(encoded, encoding); - } -} diff --git a/src/test/java/packages/OLOneFileTest.java b/src/test/java/packages/OLOneFileTest.java index 6e91fef7..9050d133 100644 --- a/src/test/java/packages/OLOneFileTest.java +++ b/src/test/java/packages/OLOneFileTest.java @@ -42,8 +42,8 @@ public class OLOneFileTest { Lists.newArrayList(new File(rootDirectory+"de/test/output/"))); pathToClassFile = System.getProperty("user.dir")+"/resources/javFiles/packageTest/"; List typeinferenceResult = compiler.typeInference(); - List simplifyResultsForAllSourceFiles = compiler.getGeneratedGenericResultsForAllSourceFiles(typeinferenceResult); - compiler.generateBytecode(new File(pathToClassFile),typeinferenceResult,simplifyResultsForAllSourceFiles); + //List simplifyResultsForAllSourceFiles = compiler.getGeneratedGenericResultsForAllSourceFiles(typeinferenceResult); + //compiler.generateBytecode(new File(pathToClassFile),typeinferenceResult,simplifyResultsForAllSourceFiles); loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); classToTest = loader.loadClass("OLOneFile"); instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); diff --git a/src/test/java/targetast/ASTToTypedTargetAST.java b/src/test/java/targetast/ASTToTypedTargetAST.java index 94b56bd4..6d5a08c0 100644 --- a/src/test/java/targetast/ASTToTypedTargetAST.java +++ b/src/test/java/targetast/ASTToTypedTargetAST.java @@ -1,20 +1,23 @@ package targetast; +import com.google.common.reflect.TypeToken; import de.dhbwstuttgart.core.JavaTXCompiler; +import de.dhbwstuttgart.environment.ByteArrayClassLoader; import de.dhbwstuttgart.parser.NullToken; import de.dhbwstuttgart.parser.scope.JavaClassName; import de.dhbwstuttgart.syntaxtree.*; import de.dhbwstuttgart.syntaxtree.type.RefType; -import de.dhbwstuttgart.target.ByteArrayClassLoader; import de.dhbwstuttgart.target.generate.ASTToTargetAST; import de.dhbwstuttgart.target.tree.TargetClass; import de.dhbwstuttgart.typeinference.result.ResultSet; +import org.junit.Ignore; import org.junit.Test; import java.nio.file.Path; import java.util.ArrayList; import java.util.HashSet; import java.util.List; +import java.util.Vector; import static org.junit.Assert.*; @@ -33,7 +36,7 @@ public class ASTToTypedTargetAST { @Test public void overloading() throws Exception { - var file = Path.of(System.getProperty("user.dir"), "/src/test/resources/bytecode/javFiles/Overloading.jav").toFile(); + var file = Path.of(System.getProperty("user.dir"), "/resources/bytecode/javFiles/Overloading.jav").toFile(); var compiler = new JavaTXCompiler(file); var resultSet = compiler.typeInference(); var converter = new ASTToTargetAST(resultSet); @@ -55,7 +58,7 @@ public class ASTToTypedTargetAST { @Test public void tphsAndGenerics() throws Exception { - var file = Path.of(System.getProperty("user.dir"), "/src/test/resources/bytecode/javFiles/Tph2.jav").toFile(); + var file = Path.of(System.getProperty("user.dir"), "/resources/bytecode/javFiles/Tph2.jav").toFile(); var compiler = new JavaTXCompiler(file); var resultSet = compiler.typeInference(); var converter = new ASTToTargetAST(resultSet); @@ -66,7 +69,7 @@ public class ASTToTypedTargetAST { @Test public void cycles() throws Exception { - var file = Path.of(System.getProperty("user.dir"), "/src/test/resources/bytecode/javFiles/Cycle.jav").toFile(); + var file = Path.of(System.getProperty("user.dir"), "/resources/bytecode/javFiles/Cycle.jav").toFile(); var compiler = new JavaTXCompiler(file); var resultSet = compiler.typeInference(); var converter = new ASTToTargetAST(resultSet); @@ -77,7 +80,7 @@ public class ASTToTypedTargetAST { @Test public void infimum() throws Exception { - var file = Path.of(System.getProperty("user.dir"), "/src/test/resources/bytecode/javFiles/Infimum.jav").toFile(); + var file = Path.of(System.getProperty("user.dir"), "/resources/bytecode/javFiles/Infimum.jav").toFile(); var compiler = new JavaTXCompiler(file); var resultSet = compiler.typeInference(); var converter = new ASTToTargetAST(resultSet); @@ -85,4 +88,79 @@ public class ASTToTypedTargetAST { var infimum = TestCodegen.generateClass(converter.convert(classes.get(0)), new ByteArrayClassLoader()); } + + @Test + public void gen() throws Exception { + var file = Path.of(System.getProperty("user.dir"), "/resources/bytecode/javFiles/Gen.jav").toFile(); + var compiler = new JavaTXCompiler(file); + var resultSet = compiler.typeInference(); + var converter = new ASTToTargetAST(resultSet); + var classes = compiler.sourceFiles.get(file).getClasses(); + + var generics = TestCodegen.generateClass(converter.convert(classes.get(0)), new ByteArrayClassLoader()); + var m = generics.getDeclaredMethod("m", Vector.class); + var mReturnType = m.getGenericReturnType(); + assertEquals(mReturnType, m.getParameters()[0].getParameterizedType()); + assertEquals(mReturnType, new TypeToken>(){}.getType()); + } + + @Test + public void definedGenerics() throws Exception { + var file = Path.of(System.getProperty("user.dir"), "/resources/bytecode/javFiles/Generics.jav").toFile(); + var compiler = new JavaTXCompiler(file); + var resultSet = compiler.typeInference(); + var converter = new ASTToTargetAST(resultSet); + var classes = compiler.sourceFiles.get(file).getClasses(); + + var generics = TestCodegen.generateClass(converter.convert(classes.get(0)), new ByteArrayClassLoader()); + var B = generics.getTypeParameters()[0]; + var mt1 = generics.getDeclaredMethod("mt1", Object.class); + var constructor = generics.getDeclaredConstructor(Object.class); + + assertEquals(B, mt1.getGenericReturnType()); + assertEquals(B, mt1.getParameters()[0].getParameterizedType()); + assertEquals(B, constructor.getParameters()[0].getParameterizedType()); + } + + @Test + public void definedGenerics2() throws Exception { + var file = Path.of(System.getProperty("user.dir"), "/resources/bytecode/javFiles/Generics2.jav").toFile(); + var compiler = new JavaTXCompiler(file); + var resultSet = compiler.typeInference(); + var converter = new ASTToTargetAST(resultSet); + var classes = compiler.sourceFiles.get(file).getClasses(); + + var generics2 = TestCodegen.generateClass(converter.convert(classes.get(0)), new ByteArrayClassLoader()); + assertEquals(generics2.getTypeParameters()[0].getBounds()[0], String.class); + var m = generics2.getDeclaredMethod("m1", Object.class); + assertEquals(m.getTypeParameters()[0].getBounds()[0], Integer.class); + var param = m.getTypeParameters()[0]; + } + + @Test + @Ignore("Not implemented") + public void definedGenerics3() throws Exception { + var file = Path.of(System.getProperty("user.dir"), "/resources/bytecode/javFiles/Generics3.jav").toFile(); + var compiler = new JavaTXCompiler(file); + var resultSet = compiler.typeInference(); + var converter = new ASTToTargetAST(resultSet); + var classes = compiler.sourceFiles.get(file).getClasses(); + + var generics3 = TestCodegen.generateClass(converter.convert(classes.get(0)), new ByteArrayClassLoader()); + } + + @Test + public void definedGenerics4() throws Exception { + var file = Path.of(System.getProperty("user.dir"), "/resources/bytecode/javFiles/Generics4.jav").toFile(); + var compiler = new JavaTXCompiler(file); + var resultSet = compiler.typeInference(); + var converter = new ASTToTargetAST(resultSet); + var classes = compiler.sourceFiles.get(file).getClasses(); + + var generics4 = TestCodegen.generateClass(converter.convert(classes.get(0)), new ByteArrayClassLoader()); + + //var instance = generics4.getDeclaredConstructor().newInstance(); + //var method = generics4.getDeclaredMethod("m2", Object.class); + //method.invoke(instance, new Object()); + } } diff --git a/src/test/java/targetast/GreaterEqualTest.java b/src/test/java/targetast/GreaterEqualTest.java index 2a4c6b0d..c104433f 100644 --- a/src/test/java/targetast/GreaterEqualTest.java +++ b/src/test/java/targetast/GreaterEqualTest.java @@ -1,6 +1,6 @@ package targetast; -import de.dhbwstuttgart.target.ByteArrayClassLoader; +import de.dhbwstuttgart.environment.ByteArrayClassLoader; import org.junit.BeforeClass; import org.junit.Test; diff --git a/src/test/java/targetast/GreaterThanTest.java b/src/test/java/targetast/GreaterThanTest.java index 3d7ce1cf..fd1d654a 100644 --- a/src/test/java/targetast/GreaterThanTest.java +++ b/src/test/java/targetast/GreaterThanTest.java @@ -1,6 +1,6 @@ package targetast; -import de.dhbwstuttgart.target.ByteArrayClassLoader; +import de.dhbwstuttgart.environment.ByteArrayClassLoader; import org.junit.BeforeClass; import org.junit.Test; diff --git a/src/test/java/targetast/InheritTest.java b/src/test/java/targetast/InheritTest.java index 7c99cc66..9e9fff71 100644 --- a/src/test/java/targetast/InheritTest.java +++ b/src/test/java/targetast/InheritTest.java @@ -1,10 +1,11 @@ package targetast; -import de.dhbwstuttgart.target.ByteArrayClassLoader; +import de.dhbwstuttgart.environment.ByteArrayClassLoader; import org.junit.BeforeClass; import org.junit.Test; import java.lang.reflect.Method; +import java.nio.file.Path; import java.util.Vector; import static org.junit.Assert.assertEquals; @@ -16,6 +17,9 @@ public class InheritTest { @BeforeClass public static void setUpBeforeClass() throws Exception { var classLoader = new ByteArrayClassLoader(); + // TODO Box is loaded and has a method called m so it is generating overloads for it + classLoader.loadClass(Path.of(System.getProperty("user.dir"), "/src/test/resources/target/Box.class")); + classToTest = TestCodegen.generateClassFiles("Inherit.jav", classLoader).get("Inherit"); classToTestAA = TestCodegen.generateClassFiles("AA.jav", classLoader).get("AA"); classToTestBB = TestCodegen.generateClassFiles("BB.jav", classLoader).get("BB"); diff --git a/src/test/java/targetast/InheritTest2.java b/src/test/java/targetast/InheritTest2.java index c4c48ed5..87e052f1 100644 --- a/src/test/java/targetast/InheritTest2.java +++ b/src/test/java/targetast/InheritTest2.java @@ -1,6 +1,6 @@ package targetast; -import de.dhbwstuttgart.target.ByteArrayClassLoader; +import de.dhbwstuttgart.environment.ByteArrayClassLoader; import org.junit.BeforeClass; import org.junit.Test; diff --git a/src/test/java/targetast/LessEqualTest.java b/src/test/java/targetast/LessEqualTest.java index 617a3f0b..af5237cc 100644 --- a/src/test/java/targetast/LessEqualTest.java +++ b/src/test/java/targetast/LessEqualTest.java @@ -1,6 +1,6 @@ package targetast; -import de.dhbwstuttgart.target.ByteArrayClassLoader; +import de.dhbwstuttgart.environment.ByteArrayClassLoader; import org.junit.BeforeClass; import org.junit.Test; diff --git a/src/test/java/targetast/LessThanTest.java b/src/test/java/targetast/LessThanTest.java index 3ed46908..7b0d45c8 100644 --- a/src/test/java/targetast/LessThanTest.java +++ b/src/test/java/targetast/LessThanTest.java @@ -1,6 +1,6 @@ package targetast; -import de.dhbwstuttgart.target.ByteArrayClassLoader; +import de.dhbwstuttgart.environment.ByteArrayClassLoader; import org.junit.BeforeClass; import org.junit.Test; diff --git a/src/test/java/targetast/OLTest.java b/src/test/java/targetast/OLTest.java index 30957a09..8afcc669 100644 --- a/src/test/java/targetast/OLTest.java +++ b/src/test/java/targetast/OLTest.java @@ -1,6 +1,6 @@ package targetast; -import de.dhbwstuttgart.target.ByteArrayClassLoader; +import de.dhbwstuttgart.environment.ByteArrayClassLoader; import org.junit.BeforeClass; import org.junit.Test; diff --git a/src/test/java/targetast/PostIncTest.java b/src/test/java/targetast/PostIncTest.java index 9fbbb965..d0d0a02d 100644 --- a/src/test/java/targetast/PostIncTest.java +++ b/src/test/java/targetast/PostIncTest.java @@ -1,6 +1,6 @@ package targetast; -import de.dhbwstuttgart.target.ByteArrayClassLoader; +import de.dhbwstuttgart.environment.ByteArrayClassLoader; import org.junit.BeforeClass; import org.junit.Test; diff --git a/src/test/java/targetast/PreIncTest.java b/src/test/java/targetast/PreIncTest.java index a48cea2c..d946b0e3 100644 --- a/src/test/java/targetast/PreIncTest.java +++ b/src/test/java/targetast/PreIncTest.java @@ -1,6 +1,6 @@ package targetast; -import de.dhbwstuttgart.target.ByteArrayClassLoader; +import de.dhbwstuttgart.environment.ByteArrayClassLoader; import org.junit.BeforeClass; import org.junit.Test; diff --git a/src/test/java/targetast/PutTest.java b/src/test/java/targetast/PutTest.java index a67ad03a..66600337 100644 --- a/src/test/java/targetast/PutTest.java +++ b/src/test/java/targetast/PutTest.java @@ -1,6 +1,6 @@ package targetast; -import de.dhbwstuttgart.target.ByteArrayClassLoader; +import de.dhbwstuttgart.environment.ByteArrayClassLoader; import org.junit.BeforeClass; import org.junit.Test; diff --git a/src/test/java/targetast/TestCodegen.java b/src/test/java/targetast/TestCodegen.java index 46c4c834..73d3dfdf 100644 --- a/src/test/java/targetast/TestCodegen.java +++ b/src/test/java/targetast/TestCodegen.java @@ -1,8 +1,9 @@ package targetast; import de.dhbwstuttgart.core.JavaTXCompiler; -import de.dhbwstuttgart.target.ByteArrayClassLoader; -import de.dhbwstuttgart.target.bytecode.Codegen; +import de.dhbwstuttgart.bytecode.Codegen; +import de.dhbwstuttgart.environment.ByteArrayClassLoader; +import de.dhbwstuttgart.environment.IByteArrayClassLoader; import de.dhbwstuttgart.target.generate.ASTToTargetAST; import de.dhbwstuttgart.target.tree.MethodParameter; import de.dhbwstuttgart.target.tree.TargetClass; @@ -10,6 +11,7 @@ import de.dhbwstuttgart.target.tree.expression.*; import de.dhbwstuttgart.target.tree.type.TargetFunNType; import de.dhbwstuttgart.target.tree.type.TargetRefType; import de.dhbwstuttgart.target.tree.type.TargetType; +import org.junit.Ignore; import org.junit.Test; import static org.junit.Assert.*; import org.objectweb.asm.Opcodes; @@ -26,30 +28,41 @@ import java.util.stream.Collectors; public class TestCodegen { - public static Class generateClass(TargetClass clazz, ByteArrayClassLoader classLoader) throws IOException { - var codegen = new Codegen(clazz); - var bytes = codegen.generate(); + private static void writeClassFile(String name, byte[] code) throws IOException { var path = Path.of(System.getProperty("user.dir"), "src/test/resources/target/"); Files.createDirectories(path); - Files.write(path.resolve(clazz.qualifiedName() + ".class"), bytes, StandardOpenOption.CREATE); - return classLoader.loadClass(bytes); + Files.write(path.resolve(name + ".class"), code); } - public static Map> generateClassFiles(String filename, ByteArrayClassLoader classLoader) throws IOException, ClassNotFoundException { - var file = Path.of(System.getProperty("user.dir"), "/src/test/resources/bytecode/javFiles/", filename).toFile(); - var compiler = new JavaTXCompiler(file); + public static Class generateClass(TargetClass clazz, IByteArrayClassLoader classLoader) throws IOException { + var codegen = new Codegen(clazz); + var code = codegen.generate(); + writeClassFile(clazz.qualifiedName(), code); + return classLoader.loadClass(code); + } + + public static Map> generateClassFiles(String filename, IByteArrayClassLoader classLoader) throws IOException, ClassNotFoundException { + var file = Path.of(System.getProperty("user.dir"), "/resources/bytecode/javFiles/", filename).toFile(); + var compiler = new JavaTXCompiler(List.of(file), List.of(file.getParentFile())); var resultSet = compiler.typeInference(); + var sourceFile = compiler.sourceFiles.get(file); var converter = new ASTToTargetAST(resultSet, sourceFile, classLoader); var classes = compiler.sourceFiles.get(file).getClasses(); - return classes.stream().map(cli -> { + var result = classes.stream().map(cli -> { try { return generateClass(converter.convert(cli), classLoader); } catch (IOException exception) { throw new RuntimeException(exception); } }).collect(Collectors.toMap(Class::getName, Function.identity())); + + for (var entry : converter.auxiliaries.entrySet()) { + writeClassFile(entry.getKey(), entry.getValue()); + } + + return result; } @Test @@ -318,10 +331,11 @@ public class TestCodegen { } @Test + @Ignore("The lambda class is not generated because we don't call ASTToTargetAST") public void testLambda() throws Exception { var classLoader = new ByteArrayClassLoader(); - var fun = classLoader.loadClass(Path.of(System.getProperty("user.dir"), "src/test/java/targetast/Fun1$$.class")); - var interfaceType = new TargetFunNType(1, List.of()); + //var fun = classLoader.loadClass(Path.of(System.getProperty("user.dir"), "src/test/java/targetast/Fun1$$.class")); + var interfaceType = new TargetFunNType(1, List.of(TargetType.Integer)); var targetClass = new TargetClass(Opcodes.ACC_PUBLIC, "CGLambda"); targetClass.addConstructor(Opcodes.ACC_PUBLIC, List.of(), new TargetBlock(List.of( diff --git a/src/test/java/targetast/TestComplete.java b/src/test/java/targetast/TestComplete.java index cf8cdac8..b8fc0b8d 100644 --- a/src/test/java/targetast/TestComplete.java +++ b/src/test/java/targetast/TestComplete.java @@ -1,10 +1,11 @@ package targetast; -import de.dhbwstuttgart.target.ByteArrayClassLoader; +import de.dhbwstuttgart.environment.ByteArrayClassLoader; import org.junit.Ignore; import org.junit.Test; import java.lang.reflect.Method; +import java.lang.reflect.ParameterizedType; import java.lang.reflect.TypeVariable; import java.util.Arrays; import java.util.Vector; @@ -13,7 +14,6 @@ import static org.junit.Assert.*; import static targetast.TestCodegen.generateClassFiles; public class TestComplete { - @Test public void applyLambdaTest() throws Exception { var classFiles = generateClassFiles("applyLambda.jav", new ByteArrayClassLoader()); @@ -135,6 +135,7 @@ public class TestComplete { public void infTest() throws Exception { var classFiles = generateClassFiles("Inf.jav", new ByteArrayClassLoader()); var instance = classFiles.get("Inf").getDeclaredConstructor().newInstance(); + // TODO check generics } @Test @@ -231,7 +232,6 @@ public class TestComplete { assertEquals(result, instanceOfClass_m3); } - @Ignore("Thread blocking for some reason") @Test public void matrixTest() throws Exception { var classFiles = generateClassFiles("Matrix.jav", new ByteArrayClassLoader()); @@ -339,17 +339,65 @@ public class TestComplete { var classFiles = generateClassFiles("SubMatrix.jav", new ByteArrayClassLoader()); var instance = classFiles.get("SubMatrix").getDeclaredConstructor().newInstance(); } + + @Test + public void tphTest() throws Exception { + var classFiles = generateClassFiles("Tph.jav", new ByteArrayClassLoader()); + var tph = classFiles.get("Tph"); + var instance = tph.getDeclaredConstructor().newInstance(); + } @Test public void tph2Test() throws Exception { var classFiles = generateClassFiles("Tph2.jav", new ByteArrayClassLoader()); - var instance = classFiles.get("Tph2").getDeclaredConstructor().newInstance(); + var tph2 = classFiles.get("Tph2"); + var instance = tph2.getDeclaredConstructor().newInstance(); + + assertEquals(1, tph2.getTypeParameters().length); + // public class Tph2 + var DZG = tph2.getTypeParameters()[0]; + + var id = tph2.getDeclaredField("id"); + // public Fun1$$ id + var idParams = ((ParameterizedType) id.getGenericType()).getActualTypeArguments(); + assertEquals(2, idParams.length); + assertEquals(DZG, idParams[0]); + assertEquals(DZG, idParams[1]); + + var id3 = tph2.getDeclaredMethod("id3", Object.class); + // public DZG id3(U var1) + var paraTypes = id3.getGenericParameterTypes(); + var typeParaTypes = id3.getTypeParameters(); + + var U = Arrays.stream(typeParaTypes).filter(t -> t.equals(paraTypes[0])).findFirst().get(); + assertEquals(DZG, U.getBounds()[0]); + assertEquals(DZG, id3.getGenericReturnType()); } @Test public void tph3Test() throws Exception { var classFiles = generateClassFiles("Tph3.jav", new ByteArrayClassLoader()); - var instance = classFiles.get("Tph3").getDeclaredConstructor().newInstance(); + var tph3 = classFiles.get("Tph3"); + var instance = tph3.getDeclaredConstructor().newInstance(); + var m1 = tph3.getDeclaredMethod("m1", Object.class, Object.class); + + // public void m1(DXBD var1, DXBE var2) + var paraTypes = m1.getGenericParameterTypes(); + var typeParaTypes = m1.getTypeParameters(); + + var DXBD = Arrays.stream(typeParaTypes).filter(t -> t.equals(paraTypes[0])).findFirst().get(); + assertEquals(Object.class, DXBD.getBounds()[0]); + var DXBE = Arrays.stream(typeParaTypes).filter(t -> t.equals(paraTypes[1])).findFirst().get(); + assertEquals(DXBD, DXBE.getBounds()[0]); + + var m2 = tph3.getDeclaredMethod("m2", Object.class); + + // public void m2(V var1) + var paraTypes2 = m2.getGenericParameterTypes(); + var typeParaTypes2 = m2.getTypeParameters(); + + var V = Arrays.stream(typeParaTypes2).filter(t -> t.equals(paraTypes2[0])).findFirst().get(); + assertEquals(Object.class, V.getBounds()[0]); } @Test @@ -357,6 +405,30 @@ public class TestComplete { var classFiles = generateClassFiles("Tph4.jav", new ByteArrayClassLoader()); var tph4 = classFiles.get("Tph4"); var instance = tph4.getDeclaredConstructor().newInstance(); + var m = tph4.getDeclaredMethod("m", Object.class, Object.class); + + // public N m(O var1, N var2) { + var paraTypes = m.getGenericParameterTypes(); + var typeParaTypes = m.getTypeParameters(); + + var N = Arrays.stream(typeParaTypes).filter(t -> t.equals(m.getGenericReturnType())).findFirst().get(); + assertEquals(Object.class, N.getBounds()[0]); + + var O = Arrays.stream(typeParaTypes).filter(t -> t.equals(paraTypes[0])).findFirst().get(); + var N2 = Arrays.stream(typeParaTypes).filter(t -> t.equals(paraTypes[1])).findFirst().get(); + assertEquals(N, N2); + assertEquals(N.getBounds()[0], Object.class); + assertEquals(O.getBounds()[0], Object.class); + + var m2 = tph4.getDeclaredMethod("m2", Object.class); + + // public X m2(X var1) + var paraTypes2 = m2.getGenericParameterTypes(); + var typeParaTypes2 = m2.getTypeParameters(); + + var X = Arrays.stream(typeParaTypes2).filter(t -> t.equals(paraTypes2[0])).findFirst().get(); + assertEquals(Object.class, X.getBounds()[0]); + assertEquals(X, m2.getGenericReturnType()); } @Test @@ -365,6 +437,26 @@ public class TestComplete { var tph5 = classFiles.get("Tph5"); var instance = tph5.getDeclaredConstructor().newInstance(); var m = tph5.getDeclaredMethod("m", Object.class, Object.class); + + // public void m(N var1, O var2) + var paraTypes = m.getGenericParameterTypes(); + var typeParaTypes = m.getTypeParameters(); + + var N = Arrays.stream(typeParaTypes).filter(t -> t.equals(paraTypes[0])).findFirst().get(); + var O = Arrays.stream(typeParaTypes).filter(t -> t.equals(paraTypes[1])).findFirst().get(); + + assertEquals(O.getBounds()[0], N); + assertEquals(Object.class, N.getBounds()[0]); + + var m2 = tph5.getDeclaredMethod("m2", Object.class); + + // public R m2(R var1) + var paraTypes2 = m2.getGenericParameterTypes(); + var typeParaTypes2 = m2.getTypeParameters(); + + var R = Arrays.stream(typeParaTypes2).filter(t -> t.equals(paraTypes2[0])).findFirst().get(); + assertEquals(Object.class, R.getBounds()[0]); + assertEquals(R, m2.getGenericReturnType()); } @Test @@ -373,73 +465,89 @@ public class TestComplete { var tph5 = classFiles.get("Tph6"); var instance = tph5.getDeclaredConstructor().newInstance(); var m = tph5.getDeclaredMethod("m", Object.class, Object.class); + + // public void m(O var1, P var2) + var paraTypes = m.getGenericParameterTypes(); + var typeParaTypes = m.getTypeParameters(); + + var P = Arrays.stream(typeParaTypes).filter(t -> t.equals(paraTypes[0])).findFirst().get(); + var O = Arrays.stream(typeParaTypes).filter(t -> t.equals(paraTypes[1])).findFirst().get(); + + assertEquals(P.getBounds()[0], Object.class); + assertEquals(O.getBounds()[0], Object.class); + + var m2 = tph5.getDeclaredMethod("m2", Object.class); + + // public W m2(W var1) + var paraTypes2 = m2.getGenericParameterTypes(); + var typeParaTypes2 = m2.getTypeParameters(); + + var W = Arrays.stream(typeParaTypes2).filter(t -> t.equals(paraTypes2[0])).findFirst().get(); + assertEquals(Object.class, W.getBounds()[0]); + assertEquals(W, m2.getGenericReturnType()); } - @Test - public void Tph7Test() throws Exception { - var classFiles = TestCodegen.generateClassFiles("Tph7.jav", new ByteArrayClassLoader()); - var classToTest = classFiles.get("Tph7"); - var instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); + @Test + public void Tph7Test() throws Exception { + var classFiles = TestCodegen.generateClassFiles("Tph7.jav", new ByteArrayClassLoader()); + var classToTest = classFiles.get("Tph7"); + var instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); - //public DZU m(DZL, DZM); - Method m = classToTest.getDeclaredMethod("m", Object.class, Object.class); + // public N m(O var1, N var2) + Method m = classToTest.getDeclaredMethod("m", Object.class, Object.class); - //System.out.println(m.toString()); + //System.out.println(m.toString()); - //Argumenttypes of the method m - var paraTypes = m.getGenericParameterTypes(); + //Argumenttypes of the method m + var paraTypes = m.getGenericParameterTypes(); - //Typeparameters of the method m - var typeParaTypes = m.getTypeParameters(); + //Typeparameters of the method m + var typeParaTypes = m.getTypeParameters(); - //Typeparameters are extracted from the argumenttypes - //Conditions for the extracted typeparameters are set + //Typeparameters are extracted from the argumenttypes + //Conditions for the extracted typeparameters are set - //paraTypes[0] = DLZ - var boundFstArg = Arrays.stream(typeParaTypes) - .filter(x -> x.equals(paraTypes[0])).findFirst().get().getBounds(); + //paraTypes[0] = O + var boundFstArg = Arrays.stream(typeParaTypes) + .filter(x -> x.equals(paraTypes[0])).findFirst().get().getBounds(); - //Bound of DLZ has to be Object - assertEquals(Object.class, Arrays.stream(boundFstArg).findFirst().get()); + //Bound of O has to be Object + assertEquals(Object.class, Arrays.stream(boundFstArg).findFirst().get()); - //paraTypes[0] = DZM - var boundSndArg = Arrays.stream(typeParaTypes) - .filter(x -> x.equals(paraTypes[1])).findFirst().get().getBounds(); + //paraTypes[1] = N + var N = Arrays.stream(typeParaTypes) + .filter(x -> x.equals(paraTypes[1])).findFirst().get(); + var boundSndArg = N.getBounds(); - //Bound of DZM has to be the return type of m - assertEquals(Arrays.stream(boundSndArg).findFirst().get(), m.getGenericReturnType()); + //Bound of H has to be Object + assertEquals(Object.class, Arrays.stream(boundSndArg).findFirst().get()); - //Bound of the bound of DZM - var boundBoundSndArg = Arrays.stream(typeParaTypes).filter(x -> x.equals(Arrays.stream(boundSndArg) - .findFirst().get())).findFirst().get().getBounds(); + //N has to be the return type of m + assertEquals(N, m.getGenericReturnType()); - //boundBoundSndArg have to be a type variable (type of the local variable c) - assertEquals(true, Arrays.stream(boundBoundSndArg).findFirst().get() instanceof TypeVariable); - m.getGenericParameterTypes(); + //public DZU m2(DZU); + Method m2 = classToTest.getDeclaredMethod("m2", Object.class); - //public DZU m2(DZU); - Method m2 = classToTest.getDeclaredMethod("m2", Object.class); + //Argumenttypes of the method m2 + var paraTypesm2 = m2.getGenericParameterTypes(); - //Argumenttypes of the method m2 - var paraTypesm2 = m2.getGenericParameterTypes(); + //Typeparameters of the method m2 + var typeParaTypesm2 = m2.getTypeParameters(); - //Typeparameters of the method m2 - var typeParaTypesm2 = m2.getTypeParameters(); + //Typeparameters are extracted from the argumenttypes + //Conditions for the extracted typeparameters are set - //Typeparameters are extracted from the argumenttypes - //Conditions for the extracted typeparameters are set + //paraTypes[0] = DZU + var fstArgm2 = Arrays.stream(typeParaTypesm2) + .filter(x -> x.equals(paraTypesm2[0])).findFirst().get(); - //paraTypes[0] = DZU - var fstArgm2 = Arrays.stream(typeParaTypesm2) - .filter(x -> x.equals(paraTypesm2[0])).findFirst().get(); + //Bound of DZU has to be Object + assertEquals(Object.class, Arrays.stream(fstArgm2.getBounds()).findFirst().get()); - //Bound of DZU has to be Object - assertEquals(Object.class, Arrays.stream(fstArgm2.getBounds()).findFirst().get()); - - //DZU has to be the return type of m - assertEquals(fstArgm2, m2.getGenericReturnType()); - } + //DZU has to be the return type of m + assertEquals(fstArgm2, m2.getGenericReturnType()); + } @Test @@ -465,4 +573,29 @@ public class TestComplete { var classFiles = generateClassFiles("Y.jav", new ByteArrayClassLoader()); var instance = classFiles.get("Y").getDeclaredConstructor().newInstance(); } + + @Test + @Ignore("This one isn't working") + public void boxTest() throws Exception { + var classFiles = generateClassFiles("Box.jav", new ByteArrayClassLoader()); + var instance = classFiles.get("Box_Main").getDeclaredConstructor().newInstance(); + } + + @Test + public void cycleTest() throws Exception { + var classFiles = generateClassFiles("Cycle.jav", new ByteArrayClassLoader()); + var instance = classFiles.get("Cycle").getDeclaredConstructor().newInstance(); + } + + @Test + public void olFunTest() throws Exception { + var classFiles = generateClassFiles("OLFun.jav", new ByteArrayClassLoader()); + var instance = classFiles.get("OLFun").getDeclaredConstructor().newInstance(); + } + + @Test + public void olFun2Test() throws Exception { + var classFiles = generateClassFiles("OLFun2.jav", new ByteArrayClassLoader()); + var instance = classFiles.get("OLFun2").getDeclaredConstructor().newInstance(); + } } diff --git a/src/test/java/targetast/TestGenerics.java b/src/test/java/targetast/TestGenerics.java new file mode 100644 index 00000000..1131e076 --- /dev/null +++ b/src/test/java/targetast/TestGenerics.java @@ -0,0 +1,364 @@ +package targetast; + +import de.dhbwstuttgart.core.JavaTXCompiler; +import de.dhbwstuttgart.syntaxtree.ClassOrInterface; +import de.dhbwstuttgart.syntaxtree.Field; +import de.dhbwstuttgart.syntaxtree.Method; +import de.dhbwstuttgart.syntaxtree.type.RefType; +import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder; +import de.dhbwstuttgart.target.generate.ASTToTargetAST; +import de.dhbwstuttgart.target.generate.Bound; +import de.dhbwstuttgart.target.generate.BoundsList; +import de.dhbwstuttgart.target.generate.GenericsResult; +import org.junit.Ignore; +import org.junit.Test; +import static org.junit.Assert.*; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; + + +public class TestGenerics { + + private static final String rootDirectory = System.getProperty("user.dir") + "/resources/insertGenericsJav/"; + private static final String bytecodeDirectory = System.getProperty("user.dir") + "/src/test/resources/testBytecode/generatedBC/"; + + private record Result(List genericsResults, ClassOrInterface clazz) { + Method findMethod(String name) { + return clazz.getMethods().stream().filter(m -> m.getName().equals(name)).findFirst().orElse(null); + } + + Field findField(String name) { + return clazz.getFieldDecl().stream().filter(field -> field.getName().equals(name)).findFirst().orElse(null); + } + } + + private static Result computeGenerics(String filename) throws IOException, ClassNotFoundException { + var file = Path.of(rootDirectory + filename).toFile(); + var compiler = new JavaTXCompiler(List.of(file), List.of(file.getParentFile())); + var inference = compiler.typeInference(); + compiler.generateBytecode(new File(bytecodeDirectory), inference); + var clazz = compiler.sourceFiles.get(file).getClasses().get(0); + return new Result(compiler.getGeneratedGenerics().get(file), clazz); + } + + @Test + public void testAny() throws Exception { + var result = computeGenerics("TestAny.jav"); + var anyMethod = result.findMethod("anyMethod"); + var otherMethod = result.findMethod("otherMethod"); + var a = result.findField("a"); + + var generics = result.genericsResults.get(0); + assertEquals(1, generics.get(anyMethod).size()); + assertEquals(2, generics.get(result.clazz).size()); + + var ECK1 = generics.getBounds(otherMethod.getParameterList().getParameterAt(0).getType(), result.clazz, anyMethod); + var ECK2 = generics.getBounds(otherMethod.getReturnType(), result.clazz, anyMethod); + var ECKChain = new BoundsList(new Bound(false, ASTToTargetAST.OBJECT)); + assertEquals(ECK1, ECK2); + assertEquals(ECK2, ECKChain); + + var M = generics.getBounds(a.getType(), result.clazz); + var MChain = new BoundsList(new Bound(false, TypePlaceholder.of("ECK")), new Bound(false, ASTToTargetAST.OBJECT)); + assertEquals(M, MChain); + } + + @Test + public void testClassField() throws Exception { + var result = computeGenerics("TestClassField.jav"); + var fReturn = result.findMethod("fReturn"); + + var generics = result.genericsResults.get(0); + assertEquals(1, generics.get(result.clazz).size()); + assertEquals(0, generics.get(fReturn).size()); + + var N = generics.getBounds(fReturn.getReturnType(), result.clazz); + var NChain = new BoundsList(new Bound(false, ASTToTargetAST.OBJECT)); + assertEquals(N, NChain); + } + + @Test + public void testContraVariant() throws Exception { + var result = computeGenerics("TestContraVariant.jav"); + var m = result.findMethod("m"); + var main = result.findMethod("main"); + + var generics = result.genericsResults.get(0); + assertEquals(0, generics.get(result.clazz).size()); + assertEquals(2, generics.get(m).size()); + assertEquals(2, generics.get(main).size()); + + var N = generics.getBounds(m.getParameterList().getParameterAt(0).getType(), result.clazz, m); + var NChain = new BoundsList(new Bound(true, ASTToTargetAST.OBJECT)); + assertEquals(N, NChain); + + var Q = generics.getBounds(m.getReturnType(), result.clazz, m); + var QChain = new BoundsList(new Bound(true, TypePlaceholder.of("N")), new Bound(true, ASTToTargetAST.OBJECT)); + assertEquals(Q, QChain); + + var R = generics.getBounds(main.getParameterList().getParameterAt(0).getType(), result.clazz, main); + assertEquals(R, NChain); + + var Q2 = generics.getBounds(main.getReturnType(), result.clazz, main); + assertEquals(Q2, NChain); + } + + @Test + public void testGGFinder() throws Exception { + var result = computeGenerics("TestGGFinder.jav"); + var id = result.findMethod("id"); + var setA = result.findMethod("setA"); + var m = result.findMethod("m"); + var a = result.findField("a"); + + var generics = result.genericsResults.get(0); + assertEquals(1, generics.get(result.clazz).size()); + assertEquals(2, generics.get(id).size()); + assertEquals(1, generics.get(setA).size()); + assertEquals(2, generics.get(m).size()); + + var R = generics.getBounds(a.getType(), result.clazz); + var RChain = new BoundsList(new Bound(false, ASTToTargetAST.OBJECT)); + assertEquals(R, RChain); + + var O = generics.getBounds(id.getParameterList().getParameterAt(0).getType(), result.clazz, id); + var OChain = new BoundsList(new Bound(true, TypePlaceholder.of("AB")), new Bound(true, ASTToTargetAST.OBJECT)); + assertEquals(O, OChain); + var AB = generics.getBounds(id.getReturnType(), result.clazz, id); + assertEquals(AB, new BoundsList(new Bound(true, ASTToTargetAST.OBJECT))); + + var S = generics.getBounds(setA.getParameterList().getParameterAt(0).getType(), result.clazz, setA); + var SChain = new BoundsList(new Bound(true, TypePlaceholder.of("R")), new Bound(false, ASTToTargetAST.OBJECT)); + assertEquals(S, SChain); + assertEquals(generics.getBounds(setA.getReturnType(), result.clazz, setA), RChain); + + var X = generics.getBounds(m.getParameterList().getParameterAt(0).getType(), result.clazz, m); + var Y = generics.getBounds(m.getParameterList().getParameterAt(1).getType(), result.clazz, m); + var XChain = new BoundsList(new Bound(true, ASTToTargetAST.OBJECT)); + var YChain = new BoundsList(new Bound(true, TypePlaceholder.of("Y")), new Bound(true, ASTToTargetAST.OBJECT)); + assertEquals(X, XChain); + assertEquals(Y, YChain); + } + + @Test + @Ignore("Not implemented") + public void testLocalVarLambda() throws Exception { + var result = computeGenerics("TestLocalVarLambda.jav"); + // TODO Generics of lambdas + } + + @Test + public void testMutualRecursion() throws Exception { + var result = computeGenerics("TestMutualRecursion.jav"); + var id = result.findMethod("id"); + var m = result.findMethod("m"); + var main = result.findMethod("main"); + var a = result.findField("a"); + + var generics = result.genericsResults.get(0); + assertEquals(1, generics.get(result.clazz).size()); + assertEquals(3, generics.get(id).size()); + assertEquals(2, generics.get(m).size()); + assertEquals(3, generics.get(main).size()); + + var M = generics.getBounds(a.getType(), result.clazz); + assertEquals(M, new BoundsList(new Bound(false, ASTToTargetAST.OBJECT))); + + var O = generics.getBounds(id.getParameterList().getParameterAt(0).getType(), result.clazz, id); + var OChain = new BoundsList(new Bound(true, TypePlaceholder.of("P")), new Bound(true, ASTToTargetAST.OBJECT)); + assertEquals(O, OChain); + var AK = generics.getBounds(id.getReturnType(), result.clazz, id); + var AKChain = new BoundsList(new Bound(true, ASTToTargetAST.OBJECT)); + assertEquals(AK, AKChain); + + // TODO Shouldn't AK and AK2 be the same and on the class? + var AK2 = generics.getBounds(m.getParameterList().getParameterAt(0).getType(), result.clazz, m); + var Y = generics.getBounds(m.getParameterList().getParameterAt(0).getType(), result.clazz, m); + assertEquals(AK2, AKChain); + assertEquals(Y, AKChain); + + var AF = generics.getBounds(main.getParameterList().getParameterAt(0).getType(), result.clazz, main); + var AG= generics.getBounds(main.getParameterList().getParameterAt(1).getType(), result.clazz, main); + var AK3 = generics.getBounds(main.getReturnType(), result.clazz, main); + var AFChain = new BoundsList(new Bound(true, TypePlaceholder.of("AG")), new Bound(true, ASTToTargetAST.OBJECT)); + assertEquals(AF, AFChain); + assertEquals(AG, AKChain); + assertEquals(AK3, AKChain); + } + + @Test + public void testReturnVar() throws Exception { + var result = computeGenerics("TestReturnVar.jav"); + var anyMethod = result.findMethod("anyMethod"); + + var generics = result.genericsResults.get(0); + assertEquals(1, generics.get(anyMethod).size()); + + var M = generics.getBounds(anyMethod.getReturnType(), result.clazz, anyMethod); + assertEquals(M, new BoundsList(new Bound(true, ASTToTargetAST.OBJECT))); + } + + @Test + public void testSecondLineOfClassConstraints() throws Exception { + var result = computeGenerics("TestSecondLineOfClassConstraints.jav"); + var a = result.findField("a"); + var b = result.findField("b"); + var anyMethod = result.findMethod("anyMethod"); + var otherMethod = result.findMethod("otherMethod"); + + var generics = result.genericsResults.get(0); + var M = generics.getBounds(a.getType(), result.clazz); + var DYX = generics.getBounds(b.getType(), result.clazz); + var MChain = new BoundsList(new Bound(false, TypePlaceholder.of("DYX")), new Bound(false, ASTToTargetAST.OBJECT)); + var DYXChain = new BoundsList(new Bound(false, ASTToTargetAST.OBJECT)); + assertEquals(M, MChain); + + var Q = generics.getBounds(anyMethod.getReturnType(), result.clazz, anyMethod); + assertEquals(Q, new BoundsList(new Bound(true, ASTToTargetAST.OBJECT))); + + var DYX2 = generics.getBounds(otherMethod.getReturnType(), result.clazz, otherMethod); + assertEquals(DYX, DYX2); + assertEquals(DYX2, DYXChain); + } + + @Test + public void testThreeArgs() throws Exception { + var result = computeGenerics("TestThreeArgs.jav"); + } + + @Test + public void testTPHsAndGenerics() throws Exception { + var result = computeGenerics("TestTPHsAndGenerics.jav"); + var id2 = result.findMethod("id2"); + var m = result.findMethod("m"); + var m2 = result.findMethod("m2"); + + var generics = result.genericsResults.get(0); + var U = generics.getBounds(id2.getParameterList().getParameterAt(0).getType(), result.clazz, id2); + var FPT = generics.getBounds(id2.getReturnType(), result.clazz, id2); + assertEquals(U, new BoundsList(new Bound(true, TypePlaceholder.of("FPT")), new Bound(false, ASTToTargetAST.OBJECT))); + assertEquals(FPT, new BoundsList(new Bound(false, ASTToTargetAST.OBJECT))); + + var AA = generics.getBounds(m.getReturnType(), result.clazz, m); + var AC = generics.getBounds(m.getParameterList().getParameterAt(1).getType(), result.clazz, m); + assertEquals(AA, new BoundsList(new Bound(true, ASTToTargetAST.OBJECT))); + assertEquals(AC, new BoundsList(new Bound(true, TypePlaceholder.of("AD")), new Bound(true, ASTToTargetAST.OBJECT))); + + var AH = generics.getBounds(m2.getReturnType(), result.clazz, m2); + var AL = generics.getBounds(m2.getParameterList().getParameterAt(0).getType(), result.clazz, m2); + assertEquals(AH, new BoundsList(new Bound(true, ASTToTargetAST.OBJECT))); + assertEquals(AH, AL); + } + + @Test + public void testTwoArgs() throws Exception { + var result = computeGenerics("TestTwoArgs.jav"); + + var a = result.findField("a"); + var id = result.findMethod("id"); + var setA = result.findMethod("setA"); + var m = result.findMethod("m"); + var main = result.findMethod("main"); + + var generics = result.genericsResults.get(0); + var AO = generics.getBounds(a.getType(), result.clazz); + var AOBound = new BoundsList( + new Bound(false, TypePlaceholder.of("Y")), + new Bound(false, TypePlaceholder.of("AK")), + new Bound(false, TypePlaceholder.of("AE")), + new Bound(false, ASTToTargetAST.OBJECT) + ); + assertEquals(AO, AOBound); + + var S = generics.getBounds(setA.getParameterList().getParameterAt(0).getType(), result.clazz, setA); + var c = new ArrayList(); + c.add(new Bound(true, TypePlaceholder.of("AO"))); + c.addAll(AOBound); + var SChain = new BoundsList(c); + assertEquals(S, SChain); + + var Y = generics.getBounds(m.getParameterList().getParameterAt(1).getType(), result.clazz, m); + var YChain = new BoundsList(new Bound(true, TypePlaceholder.of("AE")), new Bound(false, ASTToTargetAST.OBJECT)); + var AE = generics.getBounds(m.getReturnType(), result.clazz, m); + assertEquals(Y, YChain); + assertEquals(AE, new BoundsList(new Bound(false, ASTToTargetAST.OBJECT))); + + // TODO main seems to change between runs + /*var AE2 = generics.getBounds(main.getReturnType(), result.clazz, main); + var AF = generics.getBounds(main.getParameterList().getParameterAt(0).getType(), result.clazz, main); + var AG = generics.getBounds(main.getParameterList().getParameterAt(1).getType(), result.clazz, main); + assertEquals(AE, AE2)); + assertEquals(AF, new BoundsList(new Bound(true, TypePlaceholder.of("AK")), new Bound(true, TypePlaceholder.of("AE")), new Bound(false, ASTToTargetAST.OBJECT)))); + assertEquals(AG, SChain));*/ + } + + @Test + @Ignore("main changes in between runs") + public void testTwoArgs2() throws Exception { + var result = computeGenerics("TestTwoArgs2.jav"); + } + + @Test + public void testTwoCalls() throws Exception { + var result = computeGenerics("TestTwoCalls.jav"); + var id = result.findMethod("id"); + var main = result.findMethod("main"); + + var generics = result.genericsResults.get(0); + var Q = generics.getBounds(id.getReturnType(), result.clazz, id); + var N = generics.getBounds(id.getParameterList().getParameterAt(0).getType(), result.clazz, id); + assertEquals(Q, new BoundsList(new Bound(true, ASTToTargetAST.OBJECT))); + assertEquals(N, new BoundsList(new Bound(true, TypePlaceholder.of("Q")), new Bound(true, ASTToTargetAST.OBJECT))); + + var Q2 = generics.getBounds(main.getReturnType(), result.clazz, main); + var R = generics.getBounds(main.getParameterList().getParameterAt(0).getType(), result.clazz, main); + var S = generics.getBounds(main.getParameterList().getParameterAt(1).getType(), result.clazz, main); + assertEquals(Q2, new BoundsList(new Bound(true, ASTToTargetAST.OBJECT))); + assertEquals(R, new BoundsList(new Bound(true, TypePlaceholder.of("Q")), new Bound(true, ASTToTargetAST.OBJECT))); + assertEquals(S, new BoundsList(new Bound(true, TypePlaceholder.of("Q")), new Bound(true, ASTToTargetAST.OBJECT))); + } + + @Test + public void testVector() throws Exception { + var result = computeGenerics("TestVector.jav"); + var m = result.findMethod("m"); + + var generics = result.genericsResults.get(0); + var par1 = generics.resolve(m.getParameterList().getParameterAt(0).getType()); + var par2 = generics.resolve(m.getParameterList().getParameterAt(1).getType()); + + var S = generics.getBounds(((RefType) par1).getParaList().get(0), result.clazz, m); + var ACM = generics.getBounds(((RefType) par2).getParaList().get(0), result.clazz, m); + assertEquals(S, new BoundsList(new Bound(true, TypePlaceholder.of("V")), new Bound(true, TypePlaceholder.of("ACM")), new Bound(true, ASTToTargetAST.OBJECT))); + assertEquals(ACM, new BoundsList(new Bound(true, ASTToTargetAST.OBJECT))); + } + + @Test + public void testVectorArg() throws Exception { + var result = computeGenerics("TestVectorArg.jav"); + var add = result.findMethod("add"); + var main = result.findMethod("main"); + + var generics = result.genericsResults.get(0); + var par1 = generics.resolve(add.getParameterList().getParameterAt(0).getType()); + var ACK = generics.getBounds(((RefType) par1).getParaList().get(0), result.clazz, add); + var O = generics.getBounds(add.getParameterList().getParameterAt(1).getType(), result.clazz, add); + assertEquals(ACK, new BoundsList(new Bound(true, ASTToTargetAST.OBJECT))); + assertEquals(O, new BoundsList(new Bound(true, TypePlaceholder.of("ACK")), new Bound(true, ASTToTargetAST.OBJECT))); + + var par2 = generics.resolve(main.getParameterList().getParameterAt(0).getType()); + var ACK2 = generics.getBounds(((RefType) par2).getParaList().get(0), result.clazz, add); + var V = generics.getBounds(add.getParameterList().getParameterAt(1).getType(), result.clazz, add); + assertEquals(ACK2, ACK); + assertEquals(V, O); + } + + @Test + public void testVoidMeth() throws Exception { + var result = computeGenerics("TestVoidMeth.jav"); + } +} diff --git a/src/test/java/targetast/TphTest.java b/src/test/java/targetast/TphTest.java index c3f29c7f..b902b155 100644 --- a/src/test/java/targetast/TphTest.java +++ b/src/test/java/targetast/TphTest.java @@ -1,12 +1,10 @@ package targetast; -import de.dhbwstuttgart.target.ByteArrayClassLoader; +import de.dhbwstuttgart.environment.ByteArrayClassLoader; import org.junit.BeforeClass; import org.junit.Test; import java.lang.reflect.Method; -import java.lang.reflect.TypeVariable; -import java.util.Arrays; import static org.junit.Assert.assertEquals; @@ -24,67 +22,10 @@ public class TphTest { @Test public void test1() throws Exception { - var classFiles = TestCodegen.generateClassFiles("Tph7.jav", new ByteArrayClassLoader()); - var classToTest = classFiles.get("Tph7"); - var instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); - - //public DZU m(DZL, DZM); Method m = classToTest.getDeclaredMethod("m", Object.class, Object.class); + Object result = m.invoke(instanceOfClass, 1,2); - //System.out.println(m.toString()); - - //Argumenttypes of the method m - var paraTypes = m.getGenericParameterTypes(); - - //Typeparameters of the method m - var typeParaTypes = m.getTypeParameters(); - - //Typeparameters are extracted from the argumenttypes - //Conditions for the extracted typeparameters are set - - //paraTypes[0] = DLZ - var boundFstArg = Arrays.stream(typeParaTypes) - .filter(x -> x.equals(paraTypes[0])).findFirst().get().getBounds(); - - //Bound of DLZ has to be Object - assertEquals(Object.class, Arrays.stream(boundFstArg).findFirst().get()); - - //paraTypes[0] = DZM - var boundSndArg = Arrays.stream(typeParaTypes) - .filter(x -> x.equals(paraTypes[1])).findFirst().get().getBounds(); - - //Bound of DZM has to be the return type of m - assertEquals(Arrays.stream(boundSndArg).findFirst().get(), m.getGenericReturnType()); - - //Bound of the bound of DZM - var boundBoundSndArg = Arrays.stream(typeParaTypes).filter(x -> x.equals(Arrays.stream(boundSndArg) - .findFirst().get())).findFirst().get().getBounds(); - - //boundBoundSndArg have to be a type variable (type of the local variable c) - assertEquals(true, Arrays.stream(boundBoundSndArg).findFirst().get() instanceof TypeVariable); - m.getGenericParameterTypes(); - - //public DZU m2(DZU); - Method m2 = classToTest.getDeclaredMethod("m2", Object.class); - - //Argumenttypes of the method m2 - var paraTypesm2 = m2.getGenericParameterTypes(); - - //Typeparameters of the method m2 - var typeParaTypesm2 = m2.getTypeParameters(); - - //Typeparameters are extracted from the argumenttypes - //Conditions for the extracted typeparameters are set - - //paraTypes[0] = DZU - var fstArgm2 = Arrays.stream(typeParaTypesm2) - .filter(x -> x.equals(paraTypesm2[0])).findFirst().get(); - - //Bound of DZU has to be Object - assertEquals(Object.class, Arrays.stream(fstArgm2.getBounds()).findFirst().get()); - - //DZU has to be the return type of m - assertEquals(fstArgm2, m2.getGenericReturnType()); + assertEquals(1,result); } @Test diff --git a/src/test/java/targetast/WhileTest.java b/src/test/java/targetast/WhileTest.java index 0321c90f..7b496f15 100644 --- a/src/test/java/targetast/WhileTest.java +++ b/src/test/java/targetast/WhileTest.java @@ -1,6 +1,6 @@ package targetast; -import de.dhbwstuttgart.target.ByteArrayClassLoader; +import de.dhbwstuttgart.environment.ByteArrayClassLoader; import org.junit.BeforeClass; import org.junit.Test; diff --git a/src/test/resources/target/Test.java b/src/test/resources/target/Test.java deleted file mode 100644 index f7e1a0bc..00000000 --- a/src/test/resources/target/Test.java +++ /dev/null @@ -1,9 +0,0 @@ -public class Test { - public void lambda() { - Interface mul2 = (Integer a) -> a * 2; - } -} - -interface Interface { - R apply(T t); -} \ No newline at end of file