From 672373fc8d5d0cf1179b5c2ba37853d9ed1e8de2 Mon Sep 17 00:00:00 2001 From: JanUlrich Date: Wed, 10 Jan 2018 12:11:51 +0100 Subject: [PATCH 01/24] --amend --- .../dhbwstuttgart/syntaxtree/type/RefType.java | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/src/de/dhbwstuttgart/syntaxtree/type/RefType.java b/src/de/dhbwstuttgart/syntaxtree/type/RefType.java index 4cf85297..edd0c49f 100644 --- a/src/de/dhbwstuttgart/syntaxtree/type/RefType.java +++ b/src/de/dhbwstuttgart/syntaxtree/type/RefType.java @@ -29,14 +29,16 @@ public class RefType extends RefTypeOrTPHOrWildcardOrGeneric @Override public String toString(){ - String params = "<"; - Iterator it = parameter.iterator(); - while(it.hasNext()){ - RefTypeOrTPHOrWildcardOrGeneric param = it.next(); - params += param.toString(); - if(it.hasNext())params += ", "; + String params = ""; + if(parameter.size()>0){ + Iterator it = parameter.iterator(); + while(it.hasNext()){ + RefTypeOrTPHOrWildcardOrGeneric param = it.next(); + params += param.toString(); + if(it.hasNext())params += ", "; + } + params += ">"; } - params += ">"; return this.name.toString() + params; } From b1b1cfdc54f259d987865f0f9663a88313333323 Mon Sep 17 00:00:00 2001 From: JanUlrich Date: Wed, 10 Jan 2018 12:14:20 +0100 Subject: [PATCH 02/24] --amend --- src/de/dhbwstuttgart/syntaxtree/type/RefType.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/de/dhbwstuttgart/syntaxtree/type/RefType.java b/src/de/dhbwstuttgart/syntaxtree/type/RefType.java index edd0c49f..3c9a5907 100644 --- a/src/de/dhbwstuttgart/syntaxtree/type/RefType.java +++ b/src/de/dhbwstuttgart/syntaxtree/type/RefType.java @@ -31,6 +31,7 @@ public class RefType extends RefTypeOrTPHOrWildcardOrGeneric public String toString(){ String params = ""; if(parameter.size()>0){ + params += "<"; Iterator it = parameter.iterator(); while(it.hasNext()){ RefTypeOrTPHOrWildcardOrGeneric param = it.next(); From 7b24e2d83f0664d71aa0c3bd2067d6b302db783c Mon Sep 17 00:00:00 2001 From: Fayez Abu Alia Date: Wed, 10 Jan 2018 15:37:50 +0100 Subject: [PATCH 03/24] =?UTF-8?q?bytecode=20f=C3=BCr=20Generics:=20LamAssi?= =?UTF-8?q?gnTest=20funktioniert=20richtig?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dhbwstuttgart/bytecode/BytecodeGen.java | 23 ++++---- .../bytecode/BytecodeGenMethod.java | 17 ++++-- src/de/dhbwstuttgart/bytecode/Signature.java | 12 +++-- .../bytecode/TypeToSignature.java | 53 +++++++++++++++++++ test/bytecode/DuMethodTest.java | 7 +++ test/bytecode/Exceptions.jav | 3 ++ test/bytecode/TestIfTest.java | 7 +++ 7 files changed, 101 insertions(+), 21 deletions(-) create mode 100644 src/de/dhbwstuttgart/bytecode/TypeToSignature.java create mode 100644 test/bytecode/DuMethodTest.java create mode 100644 test/bytecode/Exceptions.jav create mode 100644 test/bytecode/TestIfTest.java diff --git a/src/de/dhbwstuttgart/bytecode/BytecodeGen.java b/src/de/dhbwstuttgart/bytecode/BytecodeGen.java index f1994c20..88bf36c4 100644 --- a/src/de/dhbwstuttgart/bytecode/BytecodeGen.java +++ b/src/de/dhbwstuttgart/bytecode/BytecodeGen.java @@ -125,9 +125,13 @@ public class BytecodeGen implements ASTVisitor { String desc = null; boolean hasGen = false; + for(String paramName : methodParamsAndTypes.keySet()) { - genericsAndBounds.containsKey(paramName); - hasGen = true; + String typeOfParam = methodParamsAndTypes.get(paramName).acceptTV(new TypeToDescriptor()); + if(genericsAndBounds.containsKey(typeOfParam)) { + hasGen = true; + break; + } } String sig = null; if(hasGen) { @@ -166,7 +170,8 @@ public class BytecodeGen implements ASTVisitor { boolean hasGenInParameterList = genericsAndBounds.containsKey(method.getReturnType().acceptTV(new TypeToDescriptor())); if(!hasGenInParameterList) { for(String paramName : methodParamsAndTypes.keySet()) { - if(genericsAndBounds.containsKey(paramName)) { + String typeOfParam = methodParamsAndTypes.get(paramName).acceptTV(new TypeToDescriptor()); + if(genericsAndBounds.containsKey(typeOfParam)) { hasGenInParameterList = true; break; } @@ -174,15 +179,9 @@ public class BytecodeGen implements ASTVisitor { } String sig = null; boolean hasGen = method.getGenerics().iterator().hasNext() || hasGenInParameterList; - // Wenn ReturnType has Generics?? Fun1<...> wie testet man das generic hat?? - System.out.println(method.getReturnType().acceptTV(new TypeToString())); -// if(method.getReturnType().acceptTV(new TypeToString()).equals("TPH")) { -// Signature signature = new Signature(method, genericsAndBoundsMethod, methodParamsAndTypes,resultSet); -// sig = signature.toString(); -// System.out.println(sig); -// } - /* if method has generics, create signature */ - if(hasGen) { + + /* if method has generics or return type is TPH, create signature */ + if(hasGen||method.getReturnType().acceptTV(new TypeToString()).equals("TPH")) { // resultset hier zum testen Signature signature = new Signature(method, genericsAndBoundsMethod, methodParamsAndTypes,resultSet); sig = signature.toString(); diff --git a/src/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java b/src/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java index 5368cf93..ae1bf8b1 100644 --- a/src/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java +++ b/src/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java @@ -170,7 +170,7 @@ public class BytecodeGenMethod implements StatementVisitor{ this.lamCounter++; System.out.println("Lam Hs Gens: " + lambdaExpression.getGenerics().iterator().hasNext()); - System.out.println("Lam Hs Gens: " + lambdaExpression.getReturnType().acceptTV(new TypeToString())); + System.out.println("Lam Hs Gens: " + resultSet.resolveType(lambdaExpression.getReturnType()).resolvedType.acceptTV(new TypeToSignature())); 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 @@ -182,10 +182,19 @@ public class BytecodeGenMethod implements StatementVisitor{ Handle bootstrap = new Handle(Opcodes.H_INVOKESTATIC, "java/lang/invoke/LambdaMetafactory", "metafactory", mt.toMethodDescriptorString(), false); String methodName = "lambda$new$" + this.lamCounter; -// String typeErasure = "(Ljava/lang/Object;)Ljava/lang/Object;"; + + String typeErasure = "("; + Iterator itr = lambdaExpression.params.iterator(); + while(itr.hasNext()) { + itr.next(); + typeErasure += "L"+Type.getInternalName(Object.class) + ";"; + } + + System.out.println("LamReturnType: "+lambdaExpression.getReturnType().acceptTV(new TypeToString())); + typeErasure += ")L"+Type.getInternalName(Object.class) + ";"; // Type erasure -// Type arg1 = Type.getMethodType(typeErasure); - Type arg1 = Type.getMethodType(lamDesc); + Type arg1 = Type.getMethodType(typeErasure); +// Type arg1 = Type.getMethodType(lamDesc); // real Type Type arg3 = Type.getMethodType(lamDesc); diff --git a/src/de/dhbwstuttgart/bytecode/Signature.java b/src/de/dhbwstuttgart/bytecode/Signature.java index 362429a3..1a764afa 100644 --- a/src/de/dhbwstuttgart/bytecode/Signature.java +++ b/src/de/dhbwstuttgart/bytecode/Signature.java @@ -11,6 +11,7 @@ import de.dhbwstuttgart.syntaxtree.Constructor; import de.dhbwstuttgart.syntaxtree.GenericTypeVar; import de.dhbwstuttgart.syntaxtree.Method; import de.dhbwstuttgart.syntaxtree.type.GenericRefType; +import de.dhbwstuttgart.syntaxtree.type.RefType; import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric; import de.dhbwstuttgart.typeinference.result.ResultSet; @@ -96,16 +97,17 @@ public class Signature { } switch (type) { case "RT": - sv.visitClassType(t.acceptTV(new TypeToDescriptor())); +// sv.visitClassType(t.acceptTV(new TypeToDescriptor())); + sv.visitClassType(t.acceptTV(new TypeToSignature())); break; case "GRT": GenericRefType g = (GenericRefType) t; - sv.visitTypeVariable(g.getParsedName()); +// sv.visitTypeVariable(g.getParsedName()); + sv.visitTypeVariable(g.acceptTV(new TypeToSignature())); break; case "TPH": - System.out.println(resultSet.resolveType(t).resolvedType.acceptTV(new TypeToDescriptor())); -// sv.visitInterface().visitClassType(resultSet.resolveType(t).resolvedType.acceptTV(new TypeToDescriptor())+";"); - + RefType r = (RefType) resultSet.resolveType(t).resolvedType; + sv.visitInterface().visitClassType(r.acceptTV(new TypeToSignature())); break; default: if(!isParameterType) diff --git a/src/de/dhbwstuttgart/bytecode/TypeToSignature.java b/src/de/dhbwstuttgart/bytecode/TypeToSignature.java new file mode 100644 index 00000000..f40515a1 --- /dev/null +++ b/src/de/dhbwstuttgart/bytecode/TypeToSignature.java @@ -0,0 +1,53 @@ +package de.dhbwstuttgart.bytecode; + +import java.util.Iterator; + +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.RefTypeOrTPHOrWildcardOrGeneric; +import de.dhbwstuttgart.syntaxtree.type.SuperWildcardType; +import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder; +import de.dhbwstuttgart.syntaxtree.type.TypeVisitor; + +public class TypeToSignature implements TypeVisitor { + + @Override + public String visit(RefType refType) { +// return refType.toString().replace(".", "/"); + String params = ""; + if(refType.getParaList().size()>0){ + params += "<"; + Iterator it = refType.getParaList().iterator(); + while(it.hasNext()){ + RefTypeOrTPHOrWildcardOrGeneric param = it.next(); + params += "L"+param.toString().replace(".", "/"); + if(it.hasNext())params += ";"; + } + params += ";>;"; + } + return refType.getName().toString().replace(".", "/") + params; + } + + @Override + public String visit(SuperWildcardType superWildcardType) { + throw new NotImplementedException(); + } + + @Override + public String visit(TypePlaceholder typePlaceholder) { + return typePlaceholder.toString().replace(".", "/"); + } + + @Override + public String visit(ExtendsWildcardType extendsWildcardType) { + throw new NotImplementedException(); + } + + @Override + public String visit(GenericRefType genericRefType) { + return genericRefType.getParsedName().replace(".", "/"); + } + +} diff --git a/test/bytecode/DuMethodTest.java b/test/bytecode/DuMethodTest.java new file mode 100644 index 00000000..a4c8a226 --- /dev/null +++ b/test/bytecode/DuMethodTest.java @@ -0,0 +1,7 @@ +package bytecode; + +public class DuMethodTest extends JavaTXCompilerTest{ + public DuMethodTest() { + this.fileName = "DuMethod"; + } +} diff --git a/test/bytecode/Exceptions.jav b/test/bytecode/Exceptions.jav new file mode 100644 index 00000000..9903511c --- /dev/null +++ b/test/bytecode/Exceptions.jav @@ -0,0 +1,3 @@ +public class Exceptions { +// m(Integer i) throws +} \ No newline at end of file diff --git a/test/bytecode/TestIfTest.java b/test/bytecode/TestIfTest.java new file mode 100644 index 00000000..804a0616 --- /dev/null +++ b/test/bytecode/TestIfTest.java @@ -0,0 +1,7 @@ +package bytecode; + +public class TestIfTest extends JavaTXCompilerTest{ + public TestIfTest() { + this.fileName = "IfTest"; + } +} From 542f87e8a3c673102f58bb8e1e1b509c1301cac4 Mon Sep 17 00:00:00 2001 From: Fayez Abu Alia Date: Wed, 17 Jan 2018 13:49:18 +0100 Subject: [PATCH 04/24] =?UTF-8?q?erzeugt=20Klassendatei=20f=C3=BCr=20FunN?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dhbwstuttgart/bytecode/BytecodeGen.java | 18 ++- .../bytecode/BytecodeGenMethod.java | 70 +++++++- src/de/dhbwstuttgart/bytecode/ClassFile.java | 14 -- src/de/dhbwstuttgart/bytecode/Lambda.java | 1 + .../bytecode/MethodFromMethodCall.java | 1 + .../bytecode/NormalConstructor.java | 1 + .../dhbwstuttgart/bytecode/NormalMethod.java | 1 + src/de/dhbwstuttgart/bytecode/SamMethod.java | 1 + src/de/dhbwstuttgart/bytecode/Test.java | 150 ------------------ src/de/dhbwstuttgart/bytecode/TestClass.java | 8 - src/de/dhbwstuttgart/bytecode/TestFields.java | 59 ------- src/de/dhbwstuttgart/bytecode/TestIf.java | 11 -- src/de/dhbwstuttgart/bytecode/TestMeth.java | 18 --- src/de/dhbwstuttgart/bytecode/TetsF.java | 6 - .../{ => descriptor}/DescriptorToString.java | 8 +- .../{ => descriptor}/DescriptorVisitor.java | 8 +- .../{ => descriptor}/TypeToDescriptor.java | 2 +- .../bytecode/{ => signature}/Signature.java | 38 ++++- .../{ => signature}/TypeToSignature.java | 2 +- .../{ => signature}/TypeToString.java | 2 +- test/bytecode/LamAssign.jav | 6 +- 21 files changed, 134 insertions(+), 291 deletions(-) delete mode 100644 src/de/dhbwstuttgart/bytecode/ClassFile.java delete mode 100644 src/de/dhbwstuttgart/bytecode/Test.java delete mode 100644 src/de/dhbwstuttgart/bytecode/TestClass.java delete mode 100644 src/de/dhbwstuttgart/bytecode/TestFields.java delete mode 100644 src/de/dhbwstuttgart/bytecode/TestIf.java delete mode 100644 src/de/dhbwstuttgart/bytecode/TestMeth.java delete mode 100644 src/de/dhbwstuttgart/bytecode/TetsF.java rename src/de/dhbwstuttgart/bytecode/{ => descriptor}/DescriptorToString.java (95%) rename src/de/dhbwstuttgart/bytecode/{ => descriptor}/DescriptorVisitor.java (50%) rename src/de/dhbwstuttgart/bytecode/{ => descriptor}/TypeToDescriptor.java (95%) rename src/de/dhbwstuttgart/bytecode/{ => signature}/Signature.java (78%) rename src/de/dhbwstuttgart/bytecode/{ => signature}/TypeToSignature.java (97%) rename src/de/dhbwstuttgart/bytecode/{ => signature}/TypeToString.java (95%) diff --git a/src/de/dhbwstuttgart/bytecode/BytecodeGen.java b/src/de/dhbwstuttgart/bytecode/BytecodeGen.java index 88bf36c4..f6f14b4c 100644 --- a/src/de/dhbwstuttgart/bytecode/BytecodeGen.java +++ b/src/de/dhbwstuttgart/bytecode/BytecodeGen.java @@ -1,6 +1,5 @@ package de.dhbwstuttgart.bytecode; -import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; @@ -9,10 +8,11 @@ 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 org.objectweb.asm.signature.SignatureVisitor; -import org.objectweb.asm.signature.SignatureWriter; +import de.dhbwstuttgart.bytecode.descriptor.DescriptorToString; +import de.dhbwstuttgart.bytecode.descriptor.TypeToDescriptor; +import de.dhbwstuttgart.bytecode.signature.Signature; +import de.dhbwstuttgart.bytecode.signature.TypeToString; import de.dhbwstuttgart.parser.SyntaxTreeGenerator.AssignToLocal; import de.dhbwstuttgart.syntaxtree.*; import de.dhbwstuttgart.syntaxtree.statement.literal.Literal; @@ -56,8 +56,8 @@ public class BytecodeGen implements ASTVisitor { public void visit(SourceFile sourceFile) { for(ClassOrInterface cl : sourceFile.getClasses()) { BytecodeGen classGen = new BytecodeGen(classFiles, resultSet); - cl.accept(classGen); System.out.println("In CLASS: "+(cl.getClassName().toString())); + cl.accept(classGen); classGen.writeClass(cl.getClassName().toString()); } } @@ -83,6 +83,8 @@ public class BytecodeGen implements ASTVisitor { public void visit(ClassOrInterface classOrInterface) { className = classOrInterface.getClassName().toString(); + cw.visitSource(className +".jav", null); + isInterface = (classOrInterface.getModifiers()&512)==512; System.out.println("IS Interface = "+"modifiers= "+classOrInterface.getModifiers()+" ->"+(classOrInterface.getModifiers()&512) + isInterface); @@ -116,7 +118,6 @@ public class BytecodeGen implements ASTVisitor { for(Method m : classOrInterface.getMethods()) { m.accept(this); } - cw.visitSource(classOrInterface.getClassName().toString()+".jav", null); } @Override @@ -146,7 +147,7 @@ public class BytecodeGen implements ASTVisitor { mv.visitCode(); System.out.println("-----Constructor-----"); BytecodeGenMethod gen = new BytecodeGenMethod(className,resultSet,field, mv,paramsAndLocals,cw, - genericsAndBoundsMethod,genericsAndBounds,isInterface); + genericsAndBoundsMethod,genericsAndBounds,isInterface,classFiles); if(!field.getParameterList().iterator().hasNext()) { mv.visitInsn(Opcodes.RETURN); } @@ -196,7 +197,8 @@ public class BytecodeGen implements ASTVisitor { mv.visitCode(); - BytecodeGenMethod gen = new BytecodeGenMethod(className,resultSet,method, mv,paramsAndLocals,cw,genericsAndBounds,genericsAndBounds,isInterface); + BytecodeGenMethod gen = new BytecodeGenMethod(className,resultSet,method, mv,paramsAndLocals,cw, + genericsAndBounds,genericsAndBounds,isInterface,classFiles); mv.visitMaxs(0, 0); mv.visitEnd(); } diff --git a/src/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java b/src/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java index ae1bf8b1..756837b0 100644 --- a/src/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java +++ b/src/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java @@ -1,5 +1,9 @@ package de.dhbwstuttgart.bytecode; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; import java.lang.invoke.CallSite; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; @@ -14,7 +18,14 @@ import org.objectweb.asm.Handle; 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 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.parser.SyntaxTreeGenerator.AssignToLocal; import de.dhbwstuttgart.syntaxtree.FormalParameter; import de.dhbwstuttgart.syntaxtree.Method; @@ -45,12 +56,13 @@ public class BytecodeGenMethod implements StatementVisitor{ private String where; private boolean isRightSideALambda = false; private KindOfLambda kindOfLambda; + private HashMap classFiles; private ArrayList varsFunInterface; public BytecodeGenMethod(String className,ResultSet resultSet, Method m, MethodVisitor mv, - HashMap paramsAndLocals, ClassWriter cw, - HashMap genericsAndBoundsMethod, HashMap genericsAndBounds, boolean isInterface) { + HashMap paramsAndLocals, ClassWriter cw, HashMap genericsAndBoundsMethod, + HashMap genericsAndBounds, boolean isInterface, HashMap classFiles) { this.where = "<<<<<< NORMAL METHOD >>>>>>"; @@ -63,6 +75,7 @@ public class BytecodeGenMethod implements StatementVisitor{ this.genericsAndBoundsMethod = genericsAndBoundsMethod; this.genericsAndBounds = genericsAndBounds; this.isInterface = isInterface; + this.classFiles = classFiles; this.lamCounter = -1; this.varsFunInterface = new ArrayList<>(); @@ -79,13 +92,14 @@ public class BytecodeGenMethod implements StatementVisitor{ } public BytecodeGenMethod(LambdaExpression lambdaExpression,ResultSet resultSet ,MethodVisitor mv, - int indexOfFirstParamLam, boolean isInterface) { + int indexOfFirstParamLam, boolean isInterface, HashMap classFiles) { System.out.println("\t\t++++++IN LAMBDA -------"); this.where = "<<<<<< LAMBDA METHOD >>>>>>"; this.resultSet = resultSet; this.mv = mv; this.isInterface = isInterface; + this.classFiles = classFiles; this.lamCounter = -1; this.varsFunInterface = new ArrayList<>(); @@ -183,6 +197,8 @@ public class BytecodeGenMethod implements StatementVisitor{ "metafactory", mt.toMethodDescriptorString(), false); String methodName = "lambda$new$" + this.lamCounter; + // Für die Parameter-Typen und Return-Typ braucht man die Bounds (für die Typlöschung) + String typeErasure = "("; Iterator itr = lambdaExpression.params.iterator(); while(itr.hasNext()) { @@ -225,14 +241,60 @@ public class BytecodeGenMethod implements StatementVisitor{ MethodVisitor mvLambdaBody = cw.visitMethod(Opcodes.ACC_PRIVATE+ staticOrInstance + Opcodes.ACC_SYNTHETIC, methodName, arg3.toString(), null, null); - new BytecodeGenMethod(lambdaExpression,this.resultSet,mvLambdaBody,indexOfFirstParamLam,isInterface); + new BytecodeGenMethod(lambdaExpression,this.resultSet,mvLambdaBody,indexOfFirstParamLam,isInterface, + classFiles); 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); } + private void generateBCForFunN(LambdaExpression lambdaExpression) { + ClassWriter classWriter =new ClassWriter(ClassWriter.COMPUTE_FRAMES|ClassWriter.COMPUTE_MAXS); + + SignatureWriter methSig = new SignatureWriter(); + String methDesc = "("; + int numberOfParams = 0; + SignatureVisitor paramVisitor = methSig.visitParameterType(); + Iterator itr = lambdaExpression.params.iterator(); + while(itr.hasNext()) { + numberOfParams++; + // getBounds + methDesc += "L"+Type.getInternalName(Object.class)+";"; + paramVisitor.visitTypeVariable("T"+numberOfParams); + itr.next(); + } + methSig.visitReturnType().visitTypeVariable("R"); + // ")"+lam.getReturn.getBounds + methDesc += ")L"+Type.getInternalName(Object.class)+";"; + Signature sig = new Signature(lambdaExpression,numberOfParams); + String name = "Fun"+numberOfParams; + classWriter.visit(Opcodes.V1_8, 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); + } + + public void writeClassFile(byte[] bytecode, String name) { + FileOutputStream output; + try { + System.out.println("generating"+name+ ".class file"); + output = new FileOutputStream(new File(System.getProperty("user.dir") + "/testBytecode/generatedBC/" +name+".class")); + output.write(bytecode); + output.close(); + System.out.println(name+".class file generated"); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + +} + @Override public void visit(CastExpr castExpr) { // TODO Auto-generated method stub diff --git a/src/de/dhbwstuttgart/bytecode/ClassFile.java b/src/de/dhbwstuttgart/bytecode/ClassFile.java deleted file mode 100644 index fcbad90b..00000000 --- a/src/de/dhbwstuttgart/bytecode/ClassFile.java +++ /dev/null @@ -1,14 +0,0 @@ -package de.dhbwstuttgart.bytecode; - -public class ClassFile { - - String name; - byte[] bytecode; - - public ClassFile(String name, byte[] bytecode) { - this.name = name; - this.bytecode = bytecode; - } - - -} diff --git a/src/de/dhbwstuttgart/bytecode/Lambda.java b/src/de/dhbwstuttgart/bytecode/Lambda.java index 283b7393..c3b4e8f5 100644 --- a/src/de/dhbwstuttgart/bytecode/Lambda.java +++ b/src/de/dhbwstuttgart/bytecode/Lambda.java @@ -1,5 +1,6 @@ package de.dhbwstuttgart.bytecode; +import de.dhbwstuttgart.bytecode.descriptor.DescriptorVisitor; import de.dhbwstuttgart.syntaxtree.ParameterList; import de.dhbwstuttgart.syntaxtree.statement.LambdaExpression; import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric; diff --git a/src/de/dhbwstuttgart/bytecode/MethodFromMethodCall.java b/src/de/dhbwstuttgart/bytecode/MethodFromMethodCall.java index 330b0666..0f781b46 100644 --- a/src/de/dhbwstuttgart/bytecode/MethodFromMethodCall.java +++ b/src/de/dhbwstuttgart/bytecode/MethodFromMethodCall.java @@ -2,6 +2,7 @@ package de.dhbwstuttgart.bytecode; import java.util.HashMap; +import de.dhbwstuttgart.bytecode.descriptor.DescriptorVisitor; import de.dhbwstuttgart.syntaxtree.statement.ArgumentList; import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric; diff --git a/src/de/dhbwstuttgart/bytecode/NormalConstructor.java b/src/de/dhbwstuttgart/bytecode/NormalConstructor.java index d2174fd4..a9aa482a 100644 --- a/src/de/dhbwstuttgart/bytecode/NormalConstructor.java +++ b/src/de/dhbwstuttgart/bytecode/NormalConstructor.java @@ -2,6 +2,7 @@ package de.dhbwstuttgart.bytecode; import java.util.HashMap; +import de.dhbwstuttgart.bytecode.descriptor.DescriptorVisitor; import de.dhbwstuttgart.syntaxtree.Constructor; import de.dhbwstuttgart.syntaxtree.ParameterList; diff --git a/src/de/dhbwstuttgart/bytecode/NormalMethod.java b/src/de/dhbwstuttgart/bytecode/NormalMethod.java index 3f6bf2b4..b7320479 100644 --- a/src/de/dhbwstuttgart/bytecode/NormalMethod.java +++ b/src/de/dhbwstuttgart/bytecode/NormalMethod.java @@ -2,6 +2,7 @@ package de.dhbwstuttgart.bytecode; 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; diff --git a/src/de/dhbwstuttgart/bytecode/SamMethod.java b/src/de/dhbwstuttgart/bytecode/SamMethod.java index 9cf039a2..f14d5407 100644 --- a/src/de/dhbwstuttgart/bytecode/SamMethod.java +++ b/src/de/dhbwstuttgart/bytecode/SamMethod.java @@ -2,6 +2,7 @@ package de.dhbwstuttgart.bytecode; import java.util.List; +import de.dhbwstuttgart.bytecode.descriptor.DescriptorVisitor; import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric; public class SamMethod { diff --git a/src/de/dhbwstuttgart/bytecode/Test.java b/src/de/dhbwstuttgart/bytecode/Test.java deleted file mode 100644 index 333ec41f..00000000 --- a/src/de/dhbwstuttgart/bytecode/Test.java +++ /dev/null @@ -1,150 +0,0 @@ -package de.dhbwstuttgart.bytecode; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.lang.invoke.CallSite; -import java.lang.invoke.MethodHandle; -import java.lang.invoke.MethodHandles; -import java.lang.invoke.MethodType; -import java.lang.reflect.Method; -import java.net.URL; -import java.net.URLClassLoader; - -import org.objectweb.asm.ClassReader; -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; - - -public class Test { - private static final String rootDirectory = System.getProperty("user.dir") + "/bin/de/dhbwstuttgart/bytecode/"; - - protected static ClassLoader getClassLoader() throws Exception { - File file = new File(rootDirectory); - URL url = file.toURI().toURL(); - URL[] urls = new URL[] { url }; - System.out.println(urls[0]); - return new URLClassLoader(urls); - } - - public static void main(String[] args) { - // Test Lambda - ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); - cw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC + Opcodes.ACC_SUPER, "TestClass", null, "java/lang/Object", null); - - cw.visitSource("TestClass.java", null); - - // Create Constructor - MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "", "()V", null, null); - mv.visitVarInsn(Opcodes.ALOAD, 0); - - mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/Object", "", "()V"); - - // mv.visitMethodInsn(INVOKEDYNAMIC, "#0", "run", "()Ljava/lang/Runnable"); - //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()); - Handle arg2 = new Handle(Opcodes.H_INVOKESTATIC, "TestClass", "lambda$0", "()V"); - - mv.visitInvokeDynamicInsn("run", "()Ljava/lang/Runnable;", bootstrap, - Type.getMethodType("()V"), arg2, - Type.getMethodType("()V")); - - mv.visitVarInsn(Opcodes.ASTORE, 1); - mv.visitVarInsn(Opcodes.ALOAD, 1); - mv.visitMethodInsn(Opcodes.INVOKEINTERFACE, "java/lang/Runnable", "run", "()V"); - mv.visitInsn(Opcodes.RETURN); - - // creates bridge method, contains lambdas body - MethodVisitor mvl = cw.visitMethod(Opcodes.ACC_PRIVATE + Opcodes.ACC_STATIC + Opcodes.ACC_SYNTHETIC, "lambda$0", - "()V", null, null); - mvl.visitCode(); - mvl.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;"); - mvl.visitLdcInsn("lambda"); - mvl.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V"); - mvl.visitInsn(Opcodes.RETURN); - mvl.visitMaxs(2, 0); - mvl.visitEnd(); - - mv.visitMaxs(1, 2); - mv.visitEnd(); - - - cw.visitInnerClass("java/lang/invoke/MethodHandles$Lookup", "java/lang/invoke/MethodHandles", "Lookup", - Opcodes.ACC_PUBLIC + Opcodes.ACC_STATIC + Opcodes.ACC_FINAL); - cw.visitEnd(); - - byte[] b = cw.toByteArray(); - - // Test if statement - /* - * ClassWriter cw = new - * ClassWriter(ClassWriter.COMPUTE_FRAMES|ClassWriter.COMPUTE_MAXS); - * - * cw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC+Opcodes.ACC_SUPER, "TestIf", null, - * "java/lang/Object", null); MethodVisitor mv = - * cw.visitMethod(Opcodes.ACC_PUBLIC, "", "(Ljava/lang/Boolean;)V", null, - * null); mv.visitCode(); - * - * // Label l0 = new Label(); // mv.visitLabel(l0); - * - * mv.visitVarInsn(Opcodes.ALOAD, 0); - * - * mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/Object", "", - * "()V"); - * - * // Label l1 = new Label(); // mv.visitLabel(l1); - * mv.visitVarInsn(Opcodes.ALOAD, 1); mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, - * "java/lang/Boolean", "booleanValue", "()Z"); - * - * Label label = new Label(); mv.visitJumpInsn(Opcodes.IFEQ, label); - * - * mv.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/System", "out", - * "Ljava/io/PrintStream;"); mv.visitLdcInsn("1"); - * mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/io/PrintStream", "println", - * "(Ljava/lang/String;)V"); - * - * Label endLabel = new Label(); mv.visitJumpInsn(Opcodes.GOTO, endLabel); - * - * mv.visitLabel(label); mv.visitFieldInsn(Opcodes.GETSTATIC, - * "java/lang/System", "out", "Ljava/io/PrintStream;"); mv.visitLdcInsn("0"); - * mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/io/PrintStream", "println", - * "(Ljava/lang/String;)V"); - * - * - * - * mv.visitLabel(endLabel); mv.visitInsn(Opcodes.RETURN); - * - * // Label l2 = new Label(); // mv.visitLabel(l2); - * - * // mv.visitLocalVariable("this", "LTestIf;", null, l0, l2, 0); // - * mv.visitLocalVariable("b", "Ljava/lang/Boolean;", null, l0, l2, 1); - * mv.visitMaxs(2, 2); mv.visitEnd(); - * - * cw.visitEnd(); byte[] b = cw.toByteArray(); - */ - FileOutputStream output; - - try { - output = new FileOutputStream(new File(System.getProperty("user.dir") + "/testBytecode/TestClass.class")); - output.write(b); - output.close(); - } catch (FileNotFoundException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - } -} diff --git a/src/de/dhbwstuttgart/bytecode/TestClass.java b/src/de/dhbwstuttgart/bytecode/TestClass.java deleted file mode 100644 index 168447af..00000000 --- a/src/de/dhbwstuttgart/bytecode/TestClass.java +++ /dev/null @@ -1,8 +0,0 @@ -package de.dhbwstuttgart.bytecode; - -public class TestClass { - public TestClass() { - Runnable lam = () -> System.out.println("lambda"); - lam.run(); - } -} diff --git a/src/de/dhbwstuttgart/bytecode/TestFields.java b/src/de/dhbwstuttgart/bytecode/TestFields.java deleted file mode 100644 index 652b8d19..00000000 --- a/src/de/dhbwstuttgart/bytecode/TestFields.java +++ /dev/null @@ -1,59 +0,0 @@ -package de.dhbwstuttgart.bytecode; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; - -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; - -public class TestFields { - private static final String rootDirectory = System.getProperty("user.dir") + "/bin/de/dhbwstuttgart/bytecode/"; - - public static void main(String[] args) { - // TODO Auto-generated method stub - ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES|ClassWriter.COMPUTE_MAXS); - cw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC + Opcodes.ACC_SUPER, "TetsF", null, "java/lang/Object", null); - - cw.visitSource("TetsF.java", null); - - FieldVisitor fv = cw.visitField(Opcodes.ACC_PRIVATE, "z", Type.INT_TYPE.getDescriptor(), null, null); - fv.visitEnd(); - - FieldVisitor fvS = cw.visitField(Opcodes.ACC_PUBLIC, "s", "Ljava/lang/String;", null, null); - fvS.visitEnd(); - // Create Constructor - MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "", "()V", null, null); - mv.visitCode(); - - mv.visitVarInsn(Opcodes.ALOAD, 0); - mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/Object", "", "()V"); - mv.visitVarInsn(Opcodes.ALOAD, 0); - mv.visitLdcInsn(""); - mv.visitFieldInsn(Opcodes.PUTFIELD, "TetsF", "s", "Ljava/lang/String;"); - mv.visitInsn(Opcodes.RETURN); - mv.visitMaxs(2, 1); - mv.visitEnd(); - - byte[] b = cw.toByteArray(); - - FileOutputStream output; - - try { - output = new FileOutputStream(new File(System.getProperty("user.dir") + "/testBytecode/TetsF.class")); - output.write(b); - output.close(); - } catch (FileNotFoundException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - -} diff --git a/src/de/dhbwstuttgart/bytecode/TestIf.java b/src/de/dhbwstuttgart/bytecode/TestIf.java deleted file mode 100644 index 36e3c706..00000000 --- a/src/de/dhbwstuttgart/bytecode/TestIf.java +++ /dev/null @@ -1,11 +0,0 @@ -package de.dhbwstuttgart.bytecode; - -public class TestIf { - public TestIf(Boolean b) { - if(b) { - System.out.println("1"); - }else { - System.out.println("0"); - } - } -} diff --git a/src/de/dhbwstuttgart/bytecode/TestMeth.java b/src/de/dhbwstuttgart/bytecode/TestMeth.java deleted file mode 100644 index 51223ea1..00000000 --- a/src/de/dhbwstuttgart/bytecode/TestMeth.java +++ /dev/null @@ -1,18 +0,0 @@ -package de.dhbwstuttgart.bytecode; - -public class TestMeth { - private int z; - public String s; - public TestMeth(int temp) { - this.z = temp; - } - public void m1(int a, int b) { - int y = m2(1,2,3,4); - } - - public int m2(int a, int b, int x, int y) { - Integer c = 55; - Integer g; - return a+b+y+c; - } -} diff --git a/src/de/dhbwstuttgart/bytecode/TetsF.java b/src/de/dhbwstuttgart/bytecode/TetsF.java deleted file mode 100644 index af72a8d3..00000000 --- a/src/de/dhbwstuttgart/bytecode/TetsF.java +++ /dev/null @@ -1,6 +0,0 @@ -package de.dhbwstuttgart.bytecode; - -public class TetsF { - private int z; - public String s = ""; -} diff --git a/src/de/dhbwstuttgart/bytecode/DescriptorToString.java b/src/de/dhbwstuttgart/bytecode/descriptor/DescriptorToString.java similarity index 95% rename from src/de/dhbwstuttgart/bytecode/DescriptorToString.java rename to src/de/dhbwstuttgart/bytecode/descriptor/DescriptorToString.java index 481dbc5d..2ed48867 100644 --- a/src/de/dhbwstuttgart/bytecode/DescriptorToString.java +++ b/src/de/dhbwstuttgart/bytecode/descriptor/DescriptorToString.java @@ -1,7 +1,12 @@ -package de.dhbwstuttgart.bytecode; +package de.dhbwstuttgart.bytecode.descriptor; import java.util.Iterator; +import de.dhbwstuttgart.bytecode.Lambda; +import de.dhbwstuttgart.bytecode.MethodFromMethodCall; +import de.dhbwstuttgart.bytecode.NormalConstructor; +import de.dhbwstuttgart.bytecode.NormalMethod; +import de.dhbwstuttgart.bytecode.SamMethod; import de.dhbwstuttgart.syntaxtree.FormalParameter; import de.dhbwstuttgart.syntaxtree.statement.Expression; import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric; @@ -96,7 +101,6 @@ public class DescriptorToString implements DescriptorVisitor{ FormalParameter fp = itr.next(); desc = desc + "L"+resultSet.resolveType(fp.getType()).resolvedType.acceptTV(new TypeToDescriptor()) + ";"; } - System.out.println("LamReturnType: "+lambdaExpression.getReturnType().acceptTV(new TypeToString())); desc = addReturnType(desc, lambdaExpression.getReturnType(), resultSet); return desc; } diff --git a/src/de/dhbwstuttgart/bytecode/DescriptorVisitor.java b/src/de/dhbwstuttgart/bytecode/descriptor/DescriptorVisitor.java similarity index 50% rename from src/de/dhbwstuttgart/bytecode/DescriptorVisitor.java rename to src/de/dhbwstuttgart/bytecode/descriptor/DescriptorVisitor.java index 63198828..6bc57f21 100644 --- a/src/de/dhbwstuttgart/bytecode/DescriptorVisitor.java +++ b/src/de/dhbwstuttgart/bytecode/descriptor/DescriptorVisitor.java @@ -1,4 +1,10 @@ -package de.dhbwstuttgart.bytecode; +package de.dhbwstuttgart.bytecode.descriptor; + +import de.dhbwstuttgart.bytecode.Lambda; +import de.dhbwstuttgart.bytecode.MethodFromMethodCall; +import de.dhbwstuttgart.bytecode.NormalConstructor; +import de.dhbwstuttgart.bytecode.NormalMethod; +import de.dhbwstuttgart.bytecode.SamMethod; public interface DescriptorVisitor { public String visit(NormalMethod method); diff --git a/src/de/dhbwstuttgart/bytecode/TypeToDescriptor.java b/src/de/dhbwstuttgart/bytecode/descriptor/TypeToDescriptor.java similarity index 95% rename from src/de/dhbwstuttgart/bytecode/TypeToDescriptor.java rename to src/de/dhbwstuttgart/bytecode/descriptor/TypeToDescriptor.java index 5271e63d..e374bb93 100644 --- a/src/de/dhbwstuttgart/bytecode/TypeToDescriptor.java +++ b/src/de/dhbwstuttgart/bytecode/descriptor/TypeToDescriptor.java @@ -1,4 +1,4 @@ -package de.dhbwstuttgart.bytecode; +package de.dhbwstuttgart.bytecode.descriptor; import de.dhbwstuttgart.exceptions.NotImplementedException; import de.dhbwstuttgart.syntaxtree.type.ExtendsWildcardType; diff --git a/src/de/dhbwstuttgart/bytecode/Signature.java b/src/de/dhbwstuttgart/bytecode/signature/Signature.java similarity index 78% rename from src/de/dhbwstuttgart/bytecode/Signature.java rename to src/de/dhbwstuttgart/bytecode/signature/Signature.java index 1a764afa..1c208b85 100644 --- a/src/de/dhbwstuttgart/bytecode/Signature.java +++ b/src/de/dhbwstuttgart/bytecode/signature/Signature.java @@ -1,15 +1,19 @@ -package de.dhbwstuttgart.bytecode; +package de.dhbwstuttgart.bytecode.signature; import java.util.HashMap; import java.util.Iterator; +import org.objectweb.asm.Type; import org.objectweb.asm.signature.SignatureVisitor; import org.objectweb.asm.signature.SignatureWriter; +import de.dhbwstuttgart.bytecode.descriptor.TypeToDescriptor; import de.dhbwstuttgart.syntaxtree.ClassOrInterface; import de.dhbwstuttgart.syntaxtree.Constructor; +import de.dhbwstuttgart.syntaxtree.FormalParameter; import de.dhbwstuttgart.syntaxtree.GenericTypeVar; import de.dhbwstuttgart.syntaxtree.Method; +import de.dhbwstuttgart.syntaxtree.statement.LambdaExpression; import de.dhbwstuttgart.syntaxtree.type.GenericRefType; import de.dhbwstuttgart.syntaxtree.type.RefType; import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric; @@ -50,6 +54,31 @@ public class Signature { createSignatureForConsOrMethod(this.method,false); } + public Signature(LambdaExpression lambdaExpression,int numberOfParams) { + sw = new SignatureWriter(); + createSignatureForFunN(lambdaExpression, numberOfParams); + } + + private void createSignatureForFunN(LambdaExpression lambdaExpression, int numberOfParams) { + +// sw.visitReturnType().visitTypeVariable("R"); + sw.visitFormalTypeParameter("R"); + // getBounds vom Return-Type + sw.visitClassBound().visitClassType(Type.getInternalName(Object.class)); + sw.visitClassBound().visitEnd(); + for(int i = 0;i extends java.lang.Object OR ... sw.visitClassBound().visitClassType(boundDesc); genAndBounds.put(g.getParsedName(), boundDesc); diff --git a/src/de/dhbwstuttgart/bytecode/TypeToSignature.java b/src/de/dhbwstuttgart/bytecode/signature/TypeToSignature.java similarity index 97% rename from src/de/dhbwstuttgart/bytecode/TypeToSignature.java rename to src/de/dhbwstuttgart/bytecode/signature/TypeToSignature.java index f40515a1..bbc19c37 100644 --- a/src/de/dhbwstuttgart/bytecode/TypeToSignature.java +++ b/src/de/dhbwstuttgart/bytecode/signature/TypeToSignature.java @@ -1,4 +1,4 @@ -package de.dhbwstuttgart.bytecode; +package de.dhbwstuttgart.bytecode.signature; import java.util.Iterator; diff --git a/src/de/dhbwstuttgart/bytecode/TypeToString.java b/src/de/dhbwstuttgart/bytecode/signature/TypeToString.java similarity index 95% rename from src/de/dhbwstuttgart/bytecode/TypeToString.java rename to src/de/dhbwstuttgart/bytecode/signature/TypeToString.java index 86d4124a..94314afe 100644 --- a/src/de/dhbwstuttgart/bytecode/TypeToString.java +++ b/src/de/dhbwstuttgart/bytecode/signature/TypeToString.java @@ -1,4 +1,4 @@ -package de.dhbwstuttgart.bytecode; +package de.dhbwstuttgart.bytecode.signature; import de.dhbwstuttgart.exceptions.NotImplementedException; import de.dhbwstuttgart.syntaxtree.type.ExtendsWildcardType; diff --git a/test/bytecode/LamAssign.jav b/test/bytecode/LamAssign.jav index 3df81780..8f42d5ea 100644 --- a/test/bytecode/LamAssign.jav +++ b/test/bytecode/LamAssign.jav @@ -8,6 +8,6 @@ class LamAssign { } } -interface Fun1{ - A apply(B b); -} +//interface Fun1{ +// A apply(B b); +//} From 9a94ba2114e2bfa369c91fddf09b8a143ac4a521 Mon Sep 17 00:00:00 2001 From: Fayez Abu Alia Date: Wed, 31 Jan 2018 14:16:20 +0100 Subject: [PATCH 05/24] =?UTF-8?q?unn=C3=B6tige=20Kommentare=20wurden=20ent?= =?UTF-8?q?fernt?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dhbwstuttgart/bytecode/BytecodeGen.java | 26 ++---- .../bytecode/BytecodeGenMethod.java | 83 ++++++------------- .../descriptor/DescriptorToString.java | 12 ++- .../bytecode/signature/Signature.java | 6 +- test/bytecode/ATest.java | 8 ++ test/bytecode/DuMethod.jav | 2 +- test/bytecode/Example.jav | 7 ++ test/bytecode/Import.jav | 8 ++ test/bytecode/ImportTest.java | 7 ++ test/bytecode/JavaTXCompilerTest.java | 13 ++- test/bytecode/LamAssign.jav | 4 - test/bytecode/OverlaodGen.jav | 11 +++ test/bytecode/OverlaodGenTest.java | 7 ++ 13 files changed, 100 insertions(+), 94 deletions(-) create mode 100644 test/bytecode/ATest.java create mode 100644 test/bytecode/Example.jav create mode 100644 test/bytecode/Import.jav create mode 100644 test/bytecode/ImportTest.java create mode 100644 test/bytecode/OverlaodGen.jav create mode 100644 test/bytecode/OverlaodGenTest.java diff --git a/src/de/dhbwstuttgart/bytecode/BytecodeGen.java b/src/de/dhbwstuttgart/bytecode/BytecodeGen.java index f6f14b4c..25c06024 100644 --- a/src/de/dhbwstuttgart/bytecode/BytecodeGen.java +++ b/src/de/dhbwstuttgart/bytecode/BytecodeGen.java @@ -56,7 +56,6 @@ public class BytecodeGen implements ASTVisitor { public void visit(SourceFile sourceFile) { for(ClassOrInterface cl : sourceFile.getClasses()) { BytecodeGen classGen = new BytecodeGen(classFiles, resultSet); - System.out.println("In CLASS: "+(cl.getClassName().toString())); cl.accept(classGen); classGen.writeClass(cl.getClassName().toString()); } @@ -86,8 +85,7 @@ public class BytecodeGen implements ASTVisitor { cw.visitSource(className +".jav", null); isInterface = (classOrInterface.getModifiers()&512)==512; - System.out.println("IS Interface = "+"modifiers= "+classOrInterface.getModifiers()+" ->"+(classOrInterface.getModifiers()&512) + isInterface); - + int acc = isInterface?classOrInterface.getModifiers()+Opcodes.ACC_ABSTRACT:classOrInterface.getModifiers()+Opcodes.ACC_SUPER; String sig = null; /* if class has generics then creates signature @@ -96,8 +94,6 @@ public class BytecodeGen implements ASTVisitor { */ if(classOrInterface.getGenerics().iterator().hasNext()) { Signature signature = new Signature(classOrInterface, genericsAndBounds); - - System.out.println(signature.toString()); sig = signature.toString(); } // needs implemented Interfaces? @@ -106,8 +102,6 @@ public class BytecodeGen implements ASTVisitor { // for each field in the class for(Field f : classOrInterface.getFieldDecl()) { - System.out.println("get Fields"); - System.out.println(f.getName()); f.accept(this); } @@ -136,16 +130,13 @@ public class BytecodeGen implements ASTVisitor { } String sig = null; if(hasGen) { - System.out.println("IM IN CONST HAS Gens"); Signature signature = new Signature(field, genericsAndBounds,methodParamsAndTypes); sig = signature.toString(); - System.out.println(sig); } NormalConstructor constructor = new NormalConstructor(field,genericsAndBounds,hasGen); desc = constructor.accept(new DescriptorToString(resultSet)); MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "", desc, sig, null); mv.visitCode(); - System.out.println("-----Constructor-----"); BytecodeGenMethod gen = new BytecodeGenMethod(className,resultSet,field, mv,paramsAndLocals,cw, genericsAndBoundsMethod,genericsAndBounds,isInterface,classFiles); if(!field.getParameterList().iterator().hasNext()) { @@ -166,9 +157,7 @@ public class BytecodeGen implements ASTVisitor { // Method getModifiers() ? int acc = isInterface?Opcodes.ACC_ABSTRACT:0; - System.out.println("-----Method-----"); - - boolean hasGenInParameterList = genericsAndBounds.containsKey(method.getReturnType().acceptTV(new TypeToDescriptor())); + boolean hasGenInParameterList = genericsAndBounds.containsKey(resultSet.resolveType(method.getReturnType()).resolvedType.acceptTV(new TypeToDescriptor())); if(!hasGenInParameterList) { for(String paramName : methodParamsAndTypes.keySet()) { String typeOfParam = methodParamsAndTypes.get(paramName).acceptTV(new TypeToDescriptor()); @@ -178,6 +167,10 @@ public class BytecodeGen implements ASTVisitor { } } } + + //TODO: Test if the return-type or any of the parameter is a parameterized type. (VP) + //than create the descriptor with the new syntax. + String sig = null; boolean hasGen = method.getGenerics().iterator().hasNext() || hasGenInParameterList; @@ -186,13 +179,10 @@ public class BytecodeGen implements ASTVisitor { // resultset hier zum testen Signature signature = new Signature(method, genericsAndBoundsMethod, methodParamsAndTypes,resultSet); sig = signature.toString(); - System.out.println(sig); - } NormalMethod meth = new NormalMethod(method,genericsAndBounds,genericsAndBoundsMethod,hasGen); methDesc = meth.accept(new DescriptorToString(resultSet)); - System.out.println("methDesc" + methDesc); MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC+acc, method.getName(), methDesc, sig, null); mv.visitCode(); @@ -212,7 +202,7 @@ public class BytecodeGen implements ASTVisitor { while(itr.hasNext()) { FormalParameter fp = itr.next(); paramsAndLocals.put(fp.getName(), i); - methodParamsAndTypes.put(fp.getName(), fp.getType()); + methodParamsAndTypes.put(fp.getName(), resultSet.resolveType(fp.getType()).resolvedType); fp.accept(this); i++; } @@ -255,7 +245,6 @@ public class BytecodeGen implements ASTVisitor { // ?? @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(); @@ -264,7 +253,6 @@ public class BytecodeGen implements ASTVisitor { // access flages?? modifiers @Override public void visit(Field field) { - System.out.println("in field"); FieldVisitor fv = cw.visitField(Opcodes.ACC_PRIVATE, field.getName(), "L"+field.getType().toString().replace(".", "/")+";", null, null); fv.visitEnd(); } diff --git a/src/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java b/src/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java index 756837b0..c19315e8 100644 --- a/src/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java +++ b/src/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java @@ -32,7 +32,6 @@ import de.dhbwstuttgart.syntaxtree.Method; import de.dhbwstuttgart.syntaxtree.StatementVisitor; import de.dhbwstuttgart.syntaxtree.statement.literal.Literal; import de.dhbwstuttgart.syntaxtree.statement.literal.Null; -import de.dhbwstuttgart.syntaxtree.type.FunN; import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric; import de.dhbwstuttgart.typeinference.result.ResultSet; @@ -53,7 +52,7 @@ public class BytecodeGenMethod implements StatementVisitor{ private String fieldName; private String fieldDesc; private Expression rightSideTemp; - private String where; +// private String where; private boolean isRightSideALambda = false; private KindOfLambda kindOfLambda; private HashMap classFiles; @@ -64,7 +63,7 @@ public class BytecodeGenMethod implements StatementVisitor{ HashMap paramsAndLocals, ClassWriter cw, HashMap genericsAndBoundsMethod, HashMap genericsAndBounds, boolean isInterface, HashMap classFiles) { - this.where = "<<<<<< NORMAL METHOD >>>>>>"; +// this.where = "<<<<<< NORMAL METHOD >>>>>>"; this.className = className; this.resultSet = resultSet; @@ -79,23 +78,16 @@ public class BytecodeGenMethod implements StatementVisitor{ this.lamCounter = -1; this.varsFunInterface = new ArrayList<>(); - System.out.println("PARAMS = "+this.paramsAndLocals.size()); if(!isInterface) this.m.block.accept(this); -// System.out.println("PARAMS = "+this.paramsAndLocals.size()); -// for(int i = 0; i classFiles) { - System.out.println("\t\t++++++IN LAMBDA -------"); - this.where = "<<<<<< LAMBDA METHOD >>>>>>"; +// this.where = "<<<<<< LAMBDA METHOD >>>>>>"; this.resultSet = resultSet; this.mv = mv; this.isInterface = isInterface; @@ -114,7 +106,6 @@ public class BytecodeGenMethod implements StatementVisitor{ } private String getResolvedType(RefTypeOrTPHOrWildcardOrGeneric type) { -// return resultSet.resolveType(type).resolvedType.toString().replace(".", "/"); return resultSet.resolveType(type).resolvedType.acceptTV(new TypeToDescriptor()); } @@ -122,10 +113,8 @@ public class BytecodeGenMethod implements StatementVisitor{ @Override public void visit(Block block) { for(Statement stmt : block.getStatements()) { - System.out.println(where); - System.out.println("Stmt : " + stmt.toString()); +// System.out.println(where); stmt.accept(this); - System.out.println("--------------------------\n"); } } @@ -140,7 +129,7 @@ public class BytecodeGenMethod implements StatementVisitor{ // ?? @Override public void visit(LocalVar localVar) { - System.out.println("in Local Var: " + localVar.name); +// System.out.println("in Local Var: " + localVar.name); mv.visitVarInsn(Opcodes.ALOAD, paramsAndLocals.get(localVar.name)); } // ?? @@ -148,12 +137,12 @@ public class BytecodeGenMethod implements StatementVisitor{ public void visit(LocalVarDecl localVarDecl) { // Integer i; // paramsAndLocals.put(localVarDecl.getName(), paramsAndLocals.size()+1); - System.out.println("In localVarDecl :: "+localVarDecl.getName()); +// System.out.println("In localVarDecl :: "+localVarDecl.getName()); } @Override public void visit(Assign assign) { - System.out.println("Assign : \nright = "+assign.rightSide + "\nLeft = " + assign.lefSide); +// System.out.println("Assign : \nright = "+assign.rightSide + "\nLeft = " + assign.lefSide); // if the right side is a lambda => the left side must be a functional interface if(assign.rightSide.getClass().equals(LambdaExpression.class)) { @@ -162,7 +151,6 @@ public class BytecodeGenMethod implements StatementVisitor{ isRightSideALambda = false; } - System.out.println("\t isRight Side lambda: " + isRightSideALambda); if(assign.lefSide.getClass().equals(AssignToField.class)) { // load_0, ldc or .. then putfield this.rightSideTemp = assign.rightSide; @@ -175,16 +163,13 @@ public class BytecodeGenMethod implements StatementVisitor{ @Override public void visit(Binary binary) { - System.out.println("\t++ In Binary: "); + } @Override public void visit(LambdaExpression lambdaExpression) { - System.out.println("\n++ In Lambda: "); this.lamCounter++; - System.out.println("Lam Hs Gens: " + lambdaExpression.getGenerics().iterator().hasNext()); - System.out.println("Lam Hs Gens: " + resultSet.resolveType(lambdaExpression.getReturnType()).resolvedType.acceptTV(new TypeToSignature())); 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 @@ -206,7 +191,6 @@ public class BytecodeGenMethod implements StatementVisitor{ typeErasure += "L"+Type.getInternalName(Object.class) + ";"; } - System.out.println("LamReturnType: "+lambdaExpression.getReturnType().acceptTV(new TypeToString())); typeErasure += ")L"+Type.getInternalName(Object.class) + ";"; // Type erasure Type arg1 = Type.getMethodType(typeErasure); @@ -235,8 +219,7 @@ public class BytecodeGenMethod implements StatementVisitor{ 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); + mv.visitInvokeDynamicInsn("apply", fiMethodDesc, bootstrap, arg1, arg2,arg3); MethodVisitor mvLambdaBody = cw.visitMethod(Opcodes.ACC_PRIVATE+ staticOrInstance + Opcodes.ACC_SYNTHETIC, methodName, arg3.toString(), null, null); @@ -249,32 +232,31 @@ public class BytecodeGenMethod implements StatementVisitor{ cw.visitInnerClass("java/lang/invoke/MethodHandles$Lookup", "java/lang/invoke/MethodHandles", "Lookup", Opcodes.ACC_PUBLIC + Opcodes.ACC_STATIC + Opcodes.ACC_FINAL); - generateBCForFunN(lambdaExpression); + generateBCForFunN(lambdaExpression,typeErasure); } - private void generateBCForFunN(LambdaExpression lambdaExpression) { + private void generateBCForFunN(LambdaExpression lambdaExpression, String methDesc) { ClassWriter classWriter =new ClassWriter(ClassWriter.COMPUTE_FRAMES|ClassWriter.COMPUTE_MAXS); SignatureWriter methSig = new SignatureWriter(); - String methDesc = "("; + int numberOfParams = 0; SignatureVisitor paramVisitor = methSig.visitParameterType(); Iterator itr = lambdaExpression.params.iterator(); while(itr.hasNext()) { numberOfParams++; // getBounds - methDesc += "L"+Type.getInternalName(Object.class)+";"; paramVisitor.visitTypeVariable("T"+numberOfParams); itr.next(); } methSig.visitReturnType().visitTypeVariable("R"); // ")"+lam.getReturn.getBounds - methDesc += ")L"+Type.getInternalName(Object.class)+";"; Signature sig = new Signature(lambdaExpression,numberOfParams); String name = "Fun"+numberOfParams; classWriter.visit(Opcodes.V1_8, 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); + MethodVisitor mvApply = classWriter.visitMethod(Opcodes.ACC_PUBLIC+Opcodes.ACC_ABSTRACT, "apply", + methDesc, methSig.toString(), null); mvApply.visitEnd(); writeClassFile(classWriter.toByteArray(),name); } @@ -282,8 +264,8 @@ public class BytecodeGenMethod implements StatementVisitor{ public void writeClassFile(byte[] bytecode, String name) { FileOutputStream output; try { - System.out.println("generating"+name+ ".class file"); - output = new FileOutputStream(new File(System.getProperty("user.dir") + "/testBytecode/generatedBC/" +name+".class")); + System.out.println("generating "+name+ ".class file..."); + output = new FileOutputStream(new File(System.getProperty("user.dir") + "/testBytecode/generatedBC/examples/" +name+".class")); output.write(bytecode); output.close(); System.out.println(name+".class file generated"); @@ -309,7 +291,6 @@ public class BytecodeGenMethod implements StatementVisitor{ @Override public void visit(FieldVar fieldVar) { - System.out.println("in fieldVar " + fieldVar.fieldVarName + " ** receiver: "+fieldVar.receiver); fieldName = fieldVar.fieldVarName; fieldDesc = "L"+getResolvedType(fieldVar.getType())+";"; @@ -333,7 +314,7 @@ public class BytecodeGenMethod implements StatementVisitor{ @Override public void visit(IfStmt ifStmt) { - System.out.println("++ IF-Statment: "); + } @Override @@ -344,13 +325,11 @@ public class BytecodeGenMethod implements StatementVisitor{ @Override public void visit(MethodCall methodCall) { - System.out.println(" In Methodcall: (" +methodCall.name+")" ); - System.out.print("\t\tMethod-Receiver: "); - if(methodCall.receiver instanceof ExpressionReceiver){ - System.out.print(((ExpressionReceiver) methodCall.receiver).expr + "\n"); - }else{ - System.out.print(((StaticClassName) methodCall.receiver).getType().toString() + "\n"); - } +// if(methodCall.receiver instanceof ExpressionReceiver){ +// System.out.print(((ExpressionReceiver) methodCall.receiver).expr + "\n"); +// }else{ +// System.out.print(((StaticClassName) methodCall.receiver).getType().toString() + "\n"); +// } methodCall.receiver.accept(this); methodCall.arglist.accept(this); @@ -359,14 +338,13 @@ public class BytecodeGenMethod implements StatementVisitor{ genericsAndBoundsMethod,genericsAndBounds); String mDesc = method.accept(new DescriptorToString(resultSet)); - System.out.println("is Vars empty: "+varsFunInterface.isEmpty()); +// System.out.println("is Vars empty: "+varsFunInterface.isEmpty()); // is methodCall.receiver functional Interface)? if(varsFunInterface.contains(methodCall.receiver.getType())) { mv.visitMethodInsn(Opcodes.INVOKEINTERFACE, getResolvedType(methodCall.receiver.getType()), methodCall.name, mDesc, false); }else { - System.out.println("mDesc = " + mDesc); mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, getResolvedType(methodCall.receiver.getType()), methodCall.name, mDesc, isInterface); } @@ -378,8 +356,8 @@ public class BytecodeGenMethod implements StatementVisitor{ @Override public void visit(NewClass methodCall) { - System.out.println("In NewClass: "); - System.out.println("\t\tname: " + methodCall.name + " *** " + "Receiver: " + methodCall.receiver); +// System.out.println("In NewClass: "); +// System.out.println("\t\tname: " + methodCall.name + " *** " + "Receiver: " + methodCall.receiver); mv.visitTypeInsn(Opcodes.NEW, methodCall.name.replace(".", "/")); mv.visitInsn(Opcodes.DUP); @@ -402,8 +380,6 @@ public class BytecodeGenMethod implements StatementVisitor{ @Override public void visit(ExpressionReceiver receiver) { - System.out.println(" in Receiver"); - System.out.println(" expr : " + receiver.expr); receiver.expr.accept(this); } @@ -420,7 +396,6 @@ public class BytecodeGenMethod implements StatementVisitor{ @Override public void visit(StaticClassName staticClassName) { - System.out.println("In StaticClassName: "); // mv.visitMethodInsn(Opcodes.INVOKESTATIC, staticClassName.getType().toString().replace(".", "/"), // staticClassName.toString(), staticClassName.getType().toString(), false); mv.visitFieldInsn(Opcodes.GETSTATIC, getResolvedType(staticClassName.getType()), @@ -429,18 +404,17 @@ public class BytecodeGenMethod implements StatementVisitor{ @Override public void visit(Super aSuper) { - System.out.println(">> In Super: "); + } @Override public void visit(This aThis) { - System.out.println("-> IN This"); mv.visitVarInsn(Opcodes.ALOAD, 0); } @Override public void visit(UnaryPlus unaryPlus) { - System.out.println("++ In UnaryPlus: "); + } @Override @@ -468,11 +442,9 @@ public class BytecodeGenMethod implements StatementVisitor{ @Override public void visit(ArgumentList argumentList) { - System.out.println("in ArgumentList: "); for(Expression al : argumentList.getArguments()) { al.accept(this); } - System.out.println("out from Argumentlist"); } @Override @@ -491,7 +463,6 @@ public class BytecodeGenMethod implements StatementVisitor{ @Override public void visit(AssignToLocal assignLeftSide) { - System.out.println("In Assign To Local: "); if(isRightSideALambda) varsFunInterface.add(assignLeftSide.localVar.getType()); paramsAndLocals.put(assignLeftSide.localVar.name, paramsAndLocals.size()+1); diff --git a/src/de/dhbwstuttgart/bytecode/descriptor/DescriptorToString.java b/src/de/dhbwstuttgart/bytecode/descriptor/DescriptorToString.java index 2ed48867..c7c623b6 100644 --- a/src/de/dhbwstuttgart/bytecode/descriptor/DescriptorToString.java +++ b/src/de/dhbwstuttgart/bytecode/descriptor/DescriptorToString.java @@ -7,8 +7,10 @@ import de.dhbwstuttgart.bytecode.MethodFromMethodCall; import de.dhbwstuttgart.bytecode.NormalConstructor; import de.dhbwstuttgart.bytecode.NormalMethod; import de.dhbwstuttgart.bytecode.SamMethod; +import de.dhbwstuttgart.bytecode.signature.TypeToSignature; import de.dhbwstuttgart.syntaxtree.FormalParameter; import de.dhbwstuttgart.syntaxtree.statement.Expression; +import de.dhbwstuttgart.syntaxtree.type.RefType; import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric; import de.dhbwstuttgart.typeinference.result.ResultSet; @@ -35,6 +37,8 @@ public class DescriptorToString implements DescriptorVisitor{ 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)) { @@ -44,6 +48,8 @@ public class DescriptorToString implements DescriptorVisitor{ }else { desc += "L"+resultSet.resolveType(fp.getType()).resolvedType.acceptTV(new TypeToDescriptor())+ ";"; } + }else if(((RefType) fp.getType()).getParaList().size() > 0){ + desc += "L"+resultSet.resolveType(fp.getType()).resolvedType.toString().replace(".", "%").replace("<", "%%").replace(">", "%%")+ ";"; }else { desc += "L"+resultSet.resolveType(fp.getType()).resolvedType.acceptTV(new TypeToDescriptor())+ ";"; } @@ -76,16 +82,16 @@ public class DescriptorToString implements DescriptorVisitor{ while(itr.hasNext()) { FormalParameter fp = itr.next(); if(constructor.hasGen()) { - System.out.println("Cons has Gens"); +// System.out.println("Cons has Gens"); String fpDesc = fp.getType().acceptTV(new TypeToDescriptor()); - System.out.println(fpDesc); +// 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())+ ";"; } }else { - System.out.println("Cons has NOT Gens"); +// System.out.println("Cons has NOT Gens"); desc += "L"+resultSet.resolveType(fp.getType()).resolvedType.acceptTV(new TypeToDescriptor())+ ";"; } } diff --git a/src/de/dhbwstuttgart/bytecode/signature/Signature.java b/src/de/dhbwstuttgart/bytecode/signature/Signature.java index 1c208b85..fc9e2191 100644 --- a/src/de/dhbwstuttgart/bytecode/signature/Signature.java +++ b/src/de/dhbwstuttgart/bytecode/signature/Signature.java @@ -61,7 +61,6 @@ public class Signature { private void createSignatureForFunN(LambdaExpression lambdaExpression, int numberOfParams) { -// sw.visitReturnType().visitTypeVariable("R"); sw.visitFormalTypeParameter("R"); // getBounds vom Return-Type sw.visitClassBound().visitClassType(Type.getInternalName(Object.class)); @@ -73,7 +72,6 @@ public class Signature { sw.visitClassBound().visitClassType(Type.getInternalName(Object.class)); sw.visitClassBound().visitEnd(); } -// sw.visitClassBound().visitEnd(); // TODO: prüfe ob Return-Type = void, sw.visitSuperclass().visitClassType(Type.getInternalName(Object.class));; sw.visitEnd(); @@ -136,7 +134,7 @@ public class Signature { RefTypeOrTPHOrWildcardOrGeneric r = resultSet.resolveType(t).resolvedType; sv.visitInterface().visitClassType(r.acceptTV(new TypeToSignature())); // sv.visitClassType(r.acceptTV(new TypeToSignature())); - System.out.println(r.getClass()+" Signature TPH: "+r.acceptTV(new TypeToSignature())); +// System.out.println(r.getClass()+" Signature TPH: "+r.acceptTV(new TypeToSignature())); break; default: if(!isParameterType) @@ -172,7 +170,7 @@ public class Signature { while(bItr.hasNext()) { RefTypeOrTPHOrWildcardOrGeneric b =bItr.next(); String boundDesc = b.acceptTV(new TypeToDescriptor()); - System.out.println("GetBounds: " + boundDesc); +// System.out.println("GetBounds: " + boundDesc); // Ensure that <...> extends java.lang.Object OR ... sw.visitClassBound().visitClassType(boundDesc); genAndBounds.put(g.getParsedName(), boundDesc); diff --git a/test/bytecode/ATest.java b/test/bytecode/ATest.java new file mode 100644 index 00000000..9865825e --- /dev/null +++ b/test/bytecode/ATest.java @@ -0,0 +1,8 @@ +package bytecode; + +public class ATest extends JavaTXCompilerTest { + public ATest() { + fileName = "A"; + } + +} diff --git a/test/bytecode/DuMethod.jav b/test/bytecode/DuMethod.jav index b56f6c55..3898a7ba 100644 --- a/test/bytecode/DuMethod.jav +++ b/test/bytecode/DuMethod.jav @@ -1,7 +1,7 @@ public class DuMethod{ method(a){ - return a; + return a+a; } method(a){ diff --git a/test/bytecode/Example.jav b/test/bytecode/Example.jav new file mode 100644 index 00000000..451803ea --- /dev/null +++ b/test/bytecode/Example.jav @@ -0,0 +1,7 @@ +public class Example { + + public m() { + String x = "X"; + return x; + } +} \ No newline at end of file diff --git a/test/bytecode/Import.jav b/test/bytecode/Import.jav new file mode 100644 index 00000000..c658568f --- /dev/null +++ b/test/bytecode/Import.jav @@ -0,0 +1,8 @@ +import java.util.Vector; + +class Import { + void methode(){ + Vector v = new Vector<>(); + v.add("X"); + } +} \ No newline at end of file diff --git a/test/bytecode/ImportTest.java b/test/bytecode/ImportTest.java new file mode 100644 index 00000000..b7244e15 --- /dev/null +++ b/test/bytecode/ImportTest.java @@ -0,0 +1,7 @@ +package bytecode; + +public class ImportTest extends JavaTXCompilerTest{ + public ImportTest() { + this.fileName = "Import"; + } +} diff --git a/test/bytecode/JavaTXCompilerTest.java b/test/bytecode/JavaTXCompilerTest.java index f017e23e..2f832962 100644 --- a/test/bytecode/JavaTXCompilerTest.java +++ b/test/bytecode/JavaTXCompilerTest.java @@ -34,17 +34,16 @@ public class JavaTXCompilerTest { filesToTest.add(new File(rootDirectory+fileName+".jav")); System.out.println(rootDirectory+fileName+".jav"); JavaTXCompiler compiler = new JavaTXCompiler(filesToTest); - System.out.println("test"); for(File f : filesToTest){ String content = readFile(f.getPath(), StandardCharsets.UTF_8); List typeinferenceResult = compiler.typeInference(); HashMap bytecode = this.getBytecode(compiler.sourceFiles.get(f), typeinferenceResult.get(0)); - for(ResultPair ep : typeinferenceResult.get(0).results) { - System.out.println(ep.getLeft() + " ->" + ep.getRight()); - } +// for(ResultPair ep : typeinferenceResult.get(0).results) { +// System.out.println(ep.getLeft() + " ->" + ep.getRight()); +// } - String name = ""; + String name; int pos = f.getName().lastIndexOf("."); if(pos != -1) { name = f.getName().substring(0, pos); @@ -67,8 +66,8 @@ public class JavaTXCompilerTest { for(String name : classFiles.keySet()) { byte[] bytecode = classFiles.get(name); try { - System.out.println("generating"+name+ ".class file"); - output = new FileOutputStream(new File(System.getProperty("user.dir") + "/testBytecode/generatedBC/" +name+".class")); + System.out.println("generating "+name+ ".class file ..."); + output = new FileOutputStream(new File(System.getProperty("user.dir") + "/testBytecode/generatedBC/examples/" +name+".class")); output.write(bytecode); output.close(); System.out.println(name+".class file generated"); diff --git a/test/bytecode/LamAssign.jav b/test/bytecode/LamAssign.jav index 8f42d5ea..e522bd3b 100644 --- a/test/bytecode/LamAssign.jav +++ b/test/bytecode/LamAssign.jav @@ -7,7 +7,3 @@ class LamAssign { return lam1; } } - -//interface Fun1{ -// A apply(B b); -//} diff --git a/test/bytecode/OverlaodGen.jav b/test/bytecode/OverlaodGen.jav new file mode 100644 index 00000000..d5946496 --- /dev/null +++ b/test/bytecode/OverlaodGen.jav @@ -0,0 +1,11 @@ +import java.util.Vector; + +class OverlaodGen { + void method(Vector v) { +// Integer i = v.get(0); + } + + void method(Vector v) { +// String s = v.get(0); + } +} \ No newline at end of file diff --git a/test/bytecode/OverlaodGenTest.java b/test/bytecode/OverlaodGenTest.java new file mode 100644 index 00000000..72bde4f9 --- /dev/null +++ b/test/bytecode/OverlaodGenTest.java @@ -0,0 +1,7 @@ +package bytecode; + +public class OverlaodGenTest extends JavaTXCompilerTest { + public OverlaodGenTest() { + this.fileName = "OverlaodGen"; + } +} From 56d919f446216cd19ec8a5c55d9adf50d474a3af Mon Sep 17 00:00:00 2001 From: Fayez Abu Alia Date: Wed, 31 Jan 2018 15:55:02 +0100 Subject: [PATCH 06/24] bug fix --- src/de/dhbwstuttgart/bytecode/BytecodeGen.java | 2 +- src/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java | 6 +++--- .../bytecode/descriptor/DescriptorToString.java | 8 +++++--- .../dhbwstuttgart/bytecode/signature/TypeToSignature.java | 4 ++-- 4 files changed, 11 insertions(+), 9 deletions(-) diff --git a/src/de/dhbwstuttgart/bytecode/BytecodeGen.java b/src/de/dhbwstuttgart/bytecode/BytecodeGen.java index d4fee65f..8aa4c9e2 100644 --- a/src/de/dhbwstuttgart/bytecode/BytecodeGen.java +++ b/src/de/dhbwstuttgart/bytecode/BytecodeGen.java @@ -181,7 +181,7 @@ public class BytecodeGen implements ASTVisitor { Signature signature = new Signature(method, genericsAndBoundsMethod, methodParamsAndTypes,resultSet); sig = signature.toString(); } - + System.out.println(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); diff --git a/src/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java b/src/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java index 65834125..b2c38397 100644 --- a/src/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java +++ b/src/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java @@ -31,6 +31,7 @@ import de.dhbwstuttgart.parser.SyntaxTreeGenerator.AssignToLocal; import de.dhbwstuttgart.syntaxtree.FormalParameter; import de.dhbwstuttgart.syntaxtree.Method; import de.dhbwstuttgart.syntaxtree.StatementVisitor; +import de.dhbwstuttgart.syntaxtree.statement.literal.BoolLiteral; import de.dhbwstuttgart.syntaxtree.statement.literal.Literal; import de.dhbwstuttgart.syntaxtree.statement.literal.Null; import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric; @@ -420,8 +421,8 @@ public class BytecodeGenMethod implements StatementVisitor{ @Override public void visit(WhileStmt whileStmt) { - // TODO Auto-generated method stub - + whileStmt.expr.accept(this); + whileStmt.loopBlock.accept(this); } @Override @@ -437,7 +438,6 @@ public class BytecodeGenMethod implements StatementVisitor{ @Override public void visit(Literal literal) { - // value? mv.visitLdcInsn(getResolvedType(literal.getType())); } diff --git a/src/de/dhbwstuttgart/bytecode/descriptor/DescriptorToString.java b/src/de/dhbwstuttgart/bytecode/descriptor/DescriptorToString.java index c7c623b6..c9725a82 100644 --- a/src/de/dhbwstuttgart/bytecode/descriptor/DescriptorToString.java +++ b/src/de/dhbwstuttgart/bytecode/descriptor/DescriptorToString.java @@ -48,9 +48,11 @@ public class DescriptorToString implements DescriptorVisitor{ }else { desc += "L"+resultSet.resolveType(fp.getType()).resolvedType.acceptTV(new TypeToDescriptor())+ ";"; } - }else if(((RefType) fp.getType()).getParaList().size() > 0){ - desc += "L"+resultSet.resolveType(fp.getType()).resolvedType.toString().replace(".", "%").replace("<", "%%").replace(">", "%%")+ ";"; - }else { + } +// else if(((RefType) fp.getType()).getParaList().size() > 0){ +// desc += "L"+resultSet.resolveType(fp.getType()).resolvedType.toString().replace(".", "%").replace("<", "%%").replace(">", "%%")+ ";"; +// } + else { desc += "L"+resultSet.resolveType(fp.getType()).resolvedType.acceptTV(new TypeToDescriptor())+ ";"; } } diff --git a/src/de/dhbwstuttgart/bytecode/signature/TypeToSignature.java b/src/de/dhbwstuttgart/bytecode/signature/TypeToSignature.java index bbc19c37..78b2fb22 100644 --- a/src/de/dhbwstuttgart/bytecode/signature/TypeToSignature.java +++ b/src/de/dhbwstuttgart/bytecode/signature/TypeToSignature.java @@ -25,9 +25,9 @@ public class TypeToSignature implements TypeVisitor { params += "L"+param.toString().replace(".", "/"); if(it.hasNext())params += ";"; } - params += ";>;"; + params += ";>"; } - return refType.getName().toString().replace(".", "/") + params; + return refType.getName().toString().replace(".", "/") + params+";"; } @Override From b32e437a05fffc852dd303c6df68753cdadfab3d Mon Sep 17 00:00:00 2001 From: Fayez Abu Alia Date: Wed, 31 Jan 2018 16:16:05 +0100 Subject: [PATCH 07/24] Fehler --- src/de/dhbwstuttgart/bytecode/BytecodeGen.java | 4 ++-- test/bytecode/ATest.java | 2 +- test/bytecode/Example.jav | 4 ++-- test/bytecode/For.jav | 13 +++++++++++++ test/bytecode/ForTest.java | 9 +++++++++ test/bytecode/LamAssign.jav | 1 + 6 files changed, 28 insertions(+), 5 deletions(-) create mode 100644 test/bytecode/For.jav create mode 100644 test/bytecode/ForTest.java diff --git a/src/de/dhbwstuttgart/bytecode/BytecodeGen.java b/src/de/dhbwstuttgart/bytecode/BytecodeGen.java index 8ec49b8b..57aeecc3 100644 --- a/src/de/dhbwstuttgart/bytecode/BytecodeGen.java +++ b/src/de/dhbwstuttgart/bytecode/BytecodeGen.java @@ -155,7 +155,7 @@ public class BytecodeGen implements ASTVisitor { String methDesc = null; // Method getModifiers() ? - int acc = isInterface?Opcodes.ACC_ABSTRACT:0; + int acc = isInterface?Opcodes.ACC_ABSTRACT:method.modifier; boolean hasGenInParameterList = genericsAndBounds.containsKey(resultSet.resolveType(method.getReturnType()).resolvedType.acceptTV(new TypeToDescriptor())); if(!hasGenInParameterList) { @@ -183,7 +183,7 @@ public class BytecodeGen implements ASTVisitor { System.out.println(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); + MethodVisitor mv = cw.visitMethod(acc, method.getName(), methDesc, sig, null); mv.visitCode(); diff --git a/test/bytecode/ATest.java b/test/bytecode/ATest.java index 9865825e..14dbacbf 100644 --- a/test/bytecode/ATest.java +++ b/test/bytecode/ATest.java @@ -2,7 +2,7 @@ package bytecode; public class ATest extends JavaTXCompilerTest { public ATest() { - fileName = "A"; + fileName = "Example"; } } diff --git a/test/bytecode/Example.jav b/test/bytecode/Example.jav index 451803ea..8fc7a0a7 100644 --- a/test/bytecode/Example.jav +++ b/test/bytecode/Example.jav @@ -1,7 +1,7 @@ public class Example { - public m() { - String x = "X"; + public m(Integer x) { +// String x = "X"; return x; } } \ No newline at end of file diff --git a/test/bytecode/For.jav b/test/bytecode/For.jav new file mode 100644 index 00000000..c93b34c4 --- /dev/null +++ b/test/bytecode/For.jav @@ -0,0 +1,13 @@ +class For{ + m(Integer x){ + Boolean b = true; + while(x<2){ + x = x +1; + b = false; + } + return x; +// for(int i = 0;i<10;i++) { +// x = x + 5; +// } + } +} \ No newline at end of file diff --git a/test/bytecode/ForTest.java b/test/bytecode/ForTest.java new file mode 100644 index 00000000..7df68665 --- /dev/null +++ b/test/bytecode/ForTest.java @@ -0,0 +1,9 @@ +package bytecode; + +public class ForTest extends JavaTXCompilerTest { + + public ForTest() { + this.fileName = "For"; + } + +} diff --git a/test/bytecode/LamAssign.jav b/test/bytecode/LamAssign.jav index e522bd3b..7fd5bc64 100644 --- a/test/bytecode/LamAssign.jav +++ b/test/bytecode/LamAssign.jav @@ -1,3 +1,4 @@ + class LamAssign { m () { From 9c4f763c9af94761a682e7148d5540fb47abfd49 Mon Sep 17 00:00:00 2001 From: JanUlrich Date: Wed, 31 Jan 2018 16:42:25 +0100 Subject: [PATCH 08/24] =?UTF-8?q?java.lang.=20nicht=20standardm=C3=A4?= =?UTF-8?q?=C3=9Fig=20importieren?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/de/dhbwstuttgart/parser/scope/GatherNames.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/de/dhbwstuttgart/parser/scope/GatherNames.java b/src/de/dhbwstuttgart/parser/scope/GatherNames.java index cd508cde..69481508 100644 --- a/src/de/dhbwstuttgart/parser/scope/GatherNames.java +++ b/src/de/dhbwstuttgart/parser/scope/GatherNames.java @@ -72,7 +72,7 @@ public class GatherNames { public static Map getImports(Java8Parser.CompilationUnitContext ctx, PackageCrawler packages) throws ClassNotFoundException { Map ret = new HashMap<>(); ClassLoader classLoader = ClassLoader.getSystemClassLoader(); - ret.putAll(packages.getClassNames("java.lang")); + //ret.putAll(packages.getClassNames("java.lang")); for(Java8Parser.ImportDeclarationContext importDeclCtx : ctx.importDeclaration()){ if(importDeclCtx.singleTypeImportDeclaration() != null){ Class cl = classLoader.loadClass(importDeclCtx.singleTypeImportDeclaration().typeName().getText()); From 52487f3389431512294c244a1982a1a9400ce75a Mon Sep 17 00:00:00 2001 From: Fayez Abu Alia Date: Wed, 31 Jan 2018 16:47:08 +0100 Subject: [PATCH 09/24] test LamAssign --- test/bytecode/LamAssign.jav | 1 - 1 file changed, 1 deletion(-) diff --git a/test/bytecode/LamAssign.jav b/test/bytecode/LamAssign.jav index 7fd5bc64..e522bd3b 100644 --- a/test/bytecode/LamAssign.jav +++ b/test/bytecode/LamAssign.jav @@ -1,4 +1,3 @@ - class LamAssign { m () { From 6e770b5ec5dc5cd4b601545e6367ba931654b508 Mon Sep 17 00:00:00 2001 From: JanUlrich Date: Mon, 12 Feb 2018 22:32:03 +0100 Subject: [PATCH 10/24] =?UTF-8?q?Java=209:=20Classloader=20=C3=A4ndern=20*?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pom.xml | 8 +++++++ .../environment/CompilationEnvironment.java | 21 +++++++++++-------- src/de/dhbwstuttgart/parser/JavaTXParser.java | 2 +- .../dhbwstuttgart/sat/asp/model/ASPRule.java | 3 ++- .../sat/asp/writer/ASPGenerator.java | 6 +++--- .../sat/asp/writer/model/ASPFCType.java | 17 +++++++++++++++ .../sat/asp/writer/model/ASPPairSmaller.java | 2 +- .../sat/asp/writer/model/ASPRefType.java | 4 ++-- .../typeinference/assumptions/FunNClass.java | 1 - 9 files changed, 46 insertions(+), 18 deletions(-) create mode 100644 src/de/dhbwstuttgart/sat/asp/writer/model/ASPFCType.java diff --git a/pom.xml b/pom.xml index 9cce2d99..ea7be6b3 100644 --- a/pom.xml +++ b/pom.xml @@ -73,6 +73,14 @@ + + org.apache.maven.plugins + maven-compiler-plugin + + 9 + 9 + + diff --git a/src/de/dhbwstuttgart/environment/CompilationEnvironment.java b/src/de/dhbwstuttgart/environment/CompilationEnvironment.java index 7044da6b..5f294130 100644 --- a/src/de/dhbwstuttgart/environment/CompilationEnvironment.java +++ b/src/de/dhbwstuttgart/environment/CompilationEnvironment.java @@ -40,15 +40,18 @@ public class CompilationEnvironment { * @param sourceFiles die zu kompilierenden Dateien */ public CompilationEnvironment(List sourceFiles) { - String bootClassPath = System.getProperty("sun.boot.class.path"); - librarys = new ArrayList<>(); - for(String path : bootClassPath.split(File.pathSeparator)) { - try { - librarys.add(new URL("file:"+path)); - } catch (MalformedURLException e) { - new DebugException("Fehler im Classpath auf diesem System"); - } - } + /** + * Java 9 bringt einige Änderungen am Classloader + * So funktioniert der BootClassLoader nicht mehr. + * hier gibts ein paar Quellen zum nachlesen: + * http://java9.wtf/class-loading/ + * https://stackoverflow.com/questions/46494112/classloaders-hierarchy-in-java-9 + * + */ + //String bootClassPath = System.getProperty("sun.boot.class.path"); + ClassLoader cl = ClassLoader.getPlatformClassLoader(); + URLClassLoader loader = new URLClassLoader(new URL[0], cl); + librarys = Arrays.asList(loader.getURLs()); this.sourceFiles = sourceFiles; this.packageCrawler = new PackageCrawler(librarys); } diff --git a/src/de/dhbwstuttgart/parser/JavaTXParser.java b/src/de/dhbwstuttgart/parser/JavaTXParser.java index c860a6a7..aad0a575 100644 --- a/src/de/dhbwstuttgart/parser/JavaTXParser.java +++ b/src/de/dhbwstuttgart/parser/JavaTXParser.java @@ -29,7 +29,7 @@ public class JavaTXParser { */ } - /* Für das Typsystem ist es notwendig, dass sich der Source in einer Datei befindet: + /* Für das Typsystem ist es notwendig, dass sich der Source in einer Datei befindet: public SourceFile parse(String fileContent) throws IOException, java.lang.ClassNotFoundException { return this.parse(new ByteArrayInputStream(fileContent.getBytes(StandardCharsets.UTF_8))); } diff --git a/src/de/dhbwstuttgart/sat/asp/model/ASPRule.java b/src/de/dhbwstuttgart/sat/asp/model/ASPRule.java index 41237547..8d4d73f9 100644 --- a/src/de/dhbwstuttgart/sat/asp/model/ASPRule.java +++ b/src/de/dhbwstuttgart/sat/asp/model/ASPRule.java @@ -8,7 +8,8 @@ public enum ASPRule { ASP_PARAMLIST_NAME("param"), ASP_PARAMLISTNUMERATION_NAME("paramNum"), ASP_PARAMLIST_END_POINTER("null"), - ASP_TYPE("type") + ASP_TYPE("type"), + ASP_FCTYPE("type") ; private final String text; diff --git a/src/de/dhbwstuttgart/sat/asp/writer/ASPGenerator.java b/src/de/dhbwstuttgart/sat/asp/writer/ASPGenerator.java index 002e3c7f..66c206e1 100644 --- a/src/de/dhbwstuttgart/sat/asp/writer/ASPGenerator.java +++ b/src/de/dhbwstuttgart/sat/asp/writer/ASPGenerator.java @@ -36,8 +36,8 @@ public class ASPGenerator { private String toASP(List constraintSet, Collection fcClasses){ TypeConverter converter = new TypeConverter(); for(ClassOrInterface cl : fcClasses){ - ASPType superClass = cl.getSuperClass().acceptTV(converter); - ASPPairSmaller fcEntry = new ASPPairSmaller(convert(cl), superClass); + ASPRefType superClass = (ASPRefType) cl.getSuperClass().acceptTV(converter); + ASPPairSmaller fcEntry = new ASPPairSmaller(new ASPFCType(convert(cl)), new ASPFCType(superClass)); writer.add(new ASPStatement(fcEntry.toASP())); } for(Pair cons : constraintSet){ @@ -58,7 +58,7 @@ public class ASPGenerator { }else throw new NotImplementedException(); } - private ASPType convert(ClassOrInterface cl){ + private ASPRefType convert(ClassOrInterface cl){ List paramList = new ArrayList<>(); for(GenericTypeVar gtv : cl.getGenerics()){ paramList.add(new ASPGenericType(toConstant(gtv.getName()))); diff --git a/src/de/dhbwstuttgart/sat/asp/writer/model/ASPFCType.java b/src/de/dhbwstuttgart/sat/asp/writer/model/ASPFCType.java new file mode 100644 index 00000000..777a34a7 --- /dev/null +++ b/src/de/dhbwstuttgart/sat/asp/writer/model/ASPFCType.java @@ -0,0 +1,17 @@ +package de.dhbwstuttgart.sat.asp.writer.model; + +import de.dhbwstuttgart.sat.asp.model.ASPRule; + +public class ASPFCType extends ASPRefType { + public ASPFCType(String name, ASPParameterList params){ + super(name, params); + } + + public ASPFCType(ASPRefType refType){ + super(refType.name, refType.params); + } + + public String toString(){ + return ASPRule.ASP_FCTYPE + "(" + name +"," + params.name + ")"; + } +} diff --git a/src/de/dhbwstuttgart/sat/asp/writer/model/ASPPairSmaller.java b/src/de/dhbwstuttgart/sat/asp/writer/model/ASPPairSmaller.java index f57170f6..928acb49 100644 --- a/src/de/dhbwstuttgart/sat/asp/writer/model/ASPPairSmaller.java +++ b/src/de/dhbwstuttgart/sat/asp/writer/model/ASPPairSmaller.java @@ -5,7 +5,7 @@ import de.dhbwstuttgart.sat.asp.model.ASPRule; import java.util.Map; public class ASPPairSmaller extends ASPPair{ - public ASPPairSmaller(ASPType ls, ASPType rs){ + public ASPPairSmaller(ASPFCType ls, ASPFCType rs){ super(ls, rs); } diff --git a/src/de/dhbwstuttgart/sat/asp/writer/model/ASPRefType.java b/src/de/dhbwstuttgart/sat/asp/writer/model/ASPRefType.java index 6491ff33..bfbf27a0 100644 --- a/src/de/dhbwstuttgart/sat/asp/writer/model/ASPRefType.java +++ b/src/de/dhbwstuttgart/sat/asp/writer/model/ASPRefType.java @@ -3,8 +3,8 @@ package de.dhbwstuttgart.sat.asp.writer.model; import de.dhbwstuttgart.sat.asp.model.ASPRule; public class ASPRefType implements ASPType { - private final ASPParameterList params; - private final String name; + protected final ASPParameterList params; + protected final String name; public ASPRefType(String name, ASPParameterList params){ this.name = name; diff --git a/src/de/dhbwstuttgart/typeinference/assumptions/FunNClass.java b/src/de/dhbwstuttgart/typeinference/assumptions/FunNClass.java index 0eba225d..a04ce9bb 100644 --- a/src/de/dhbwstuttgart/typeinference/assumptions/FunNClass.java +++ b/src/de/dhbwstuttgart/typeinference/assumptions/FunNClass.java @@ -1,6 +1,5 @@ package de.dhbwstuttgart.typeinference.assumptions; -import com.sun.org.apache.regexp.internal.RE; import de.dhbwstuttgart.parser.NullToken; import de.dhbwstuttgart.parser.SyntaxTreeGenerator.GenericContext; import de.dhbwstuttgart.parser.scope.GenericTypeName; From 191a1166b9282eeadeaace5f3def6c16e5782432 Mon Sep 17 00:00:00 2001 From: JanUlrich Date: Tue, 13 Feb 2018 05:25:18 +0100 Subject: [PATCH 11/24] ASP Generator auf neues Format anpassen --- src/de/dhbwstuttgart/core/JavaTXCompiler.java | 2 +- .../environment/CompilationEnvironment.java | 16 +++++++++++++--- .../sat/asp/writer/ASPGenerator.java | 6 +++--- .../sat/asp/writer/model/ASPFCType.java | 5 +---- .../sat/asp/writer/model/ASPGenericType.java | 10 ++++++++++ .../sat/asp/writer/model/ASPPair.java | 8 ++++++-- .../sat/asp/writer/model/ASPPairEquals.java | 5 +++-- .../sat/asp/writer/model/ASPPairSmaller.java | 5 +++-- .../sat/asp/writer/model/ASPPairSmallerDot.java | 5 +++-- .../sat/asp/writer/model/ASPRefType.java | 10 ++++++++++ .../sat/asp/writer/model/ASPType.java | 3 +++ .../sat/asp/writer/model/ASPTypeVar.java | 10 ++++++++++ test/javFiles/Vector.jav | 1 + 13 files changed, 67 insertions(+), 19 deletions(-) diff --git a/src/de/dhbwstuttgart/core/JavaTXCompiler.java b/src/de/dhbwstuttgart/core/JavaTXCompiler.java index 86666a49..e8d74cb6 100644 --- a/src/de/dhbwstuttgart/core/JavaTXCompiler.java +++ b/src/de/dhbwstuttgart/core/JavaTXCompiler.java @@ -82,7 +82,7 @@ public class JavaTXCompiler { List allClasses = new ArrayList<>();//environment.getAllAvailableClasses(); //Alle Importierten Klassen in allen geparsten Sourcefiles kommen ins FC for(SourceFile sf : this.sourceFiles.values()) { - //allClasses.addAll(getAvailableClasses(sf)); + allClasses.addAll(getAvailableClasses(sf)); allClasses.addAll(sf.getClasses()); } diff --git a/src/de/dhbwstuttgart/environment/CompilationEnvironment.java b/src/de/dhbwstuttgart/environment/CompilationEnvironment.java index 5f294130..8a6976d6 100644 --- a/src/de/dhbwstuttgart/environment/CompilationEnvironment.java +++ b/src/de/dhbwstuttgart/environment/CompilationEnvironment.java @@ -49,9 +49,19 @@ public class CompilationEnvironment { * */ //String bootClassPath = System.getProperty("sun.boot.class.path"); - ClassLoader cl = ClassLoader.getPlatformClassLoader(); - URLClassLoader loader = new URLClassLoader(new URL[0], cl); - librarys = Arrays.asList(loader.getURLs()); + // ClassLoader cl = ClassLoader.getPlatformClassLoader(); + ClassLoader cl = ClassLoader.getSystemClassLoader(); + String bootClassPath = System.getProperty("java.class.path"); + librarys = new ArrayList<>(); + for(String path : bootClassPath.split(File.pathSeparator)) { + try { + librarys.add(new URL("file:"+path)); + } catch (MalformedURLException e) { + new DebugException("Fehler im Classpath auf diesem System"); + } + } + //URLClassLoader loader = new URLClassLoader(new URL[0], cl); + //librarys = Arrays.asList(loader.getURLs()); this.sourceFiles = sourceFiles; this.packageCrawler = new PackageCrawler(librarys); } diff --git a/src/de/dhbwstuttgart/sat/asp/writer/ASPGenerator.java b/src/de/dhbwstuttgart/sat/asp/writer/ASPGenerator.java index 66c206e1..ea162c11 100644 --- a/src/de/dhbwstuttgart/sat/asp/writer/ASPGenerator.java +++ b/src/de/dhbwstuttgart/sat/asp/writer/ASPGenerator.java @@ -37,7 +37,7 @@ public class ASPGenerator { TypeConverter converter = new TypeConverter(); for(ClassOrInterface cl : fcClasses){ ASPRefType superClass = (ASPRefType) cl.getSuperClass().acceptTV(converter); - ASPPairSmaller fcEntry = new ASPPairSmaller(new ASPFCType(convert(cl)), new ASPFCType(superClass)); + ASPPairSmaller fcEntry = new ASPPairSmaller(new ASPFCType(convert(cl)), new ASPFCType(superClass), writer); writer.add(new ASPStatement(fcEntry.toASP())); } for(Pair cons : constraintSet){ @@ -52,9 +52,9 @@ public class ASPGenerator { ASPType ls = pair.TA1.acceptTV(converter); ASPType rs = pair.TA2.acceptTV(converter); if(pair.OperatorEqual()){ - return new ASPPairEquals(ls, rs); + return new ASPPairEquals(ls, rs,writer); }else if(pair.OperatorSmallerDot()){ - return new ASPPairSmallerDot(ls, rs); + return new ASPPairSmallerDot(ls, rs, writer); }else throw new NotImplementedException(); } diff --git a/src/de/dhbwstuttgart/sat/asp/writer/model/ASPFCType.java b/src/de/dhbwstuttgart/sat/asp/writer/model/ASPFCType.java index 777a34a7..790fd5af 100644 --- a/src/de/dhbwstuttgart/sat/asp/writer/model/ASPFCType.java +++ b/src/de/dhbwstuttgart/sat/asp/writer/model/ASPFCType.java @@ -1,12 +1,9 @@ package de.dhbwstuttgart.sat.asp.writer.model; import de.dhbwstuttgart.sat.asp.model.ASPRule; +import de.dhbwstuttgart.sat.asp.writer.ASPWriter; public class ASPFCType extends ASPRefType { - public ASPFCType(String name, ASPParameterList params){ - super(name, params); - } - public ASPFCType(ASPRefType refType){ super(refType.name, refType.params); } diff --git a/src/de/dhbwstuttgart/sat/asp/writer/model/ASPGenericType.java b/src/de/dhbwstuttgart/sat/asp/writer/model/ASPGenericType.java index 57619edf..8e732d64 100644 --- a/src/de/dhbwstuttgart/sat/asp/writer/model/ASPGenericType.java +++ b/src/de/dhbwstuttgart/sat/asp/writer/model/ASPGenericType.java @@ -12,4 +12,14 @@ public class ASPGenericType implements ASPType{ public String toString(){ return ASPRule.ASP_GENERIC_TYPE_NAME + "(" + name + ")"; } + + @Override + public String toASP() { + return toString(); + } + + @Override + public String getPointer() { + return name; + } } diff --git a/src/de/dhbwstuttgart/sat/asp/writer/model/ASPPair.java b/src/de/dhbwstuttgart/sat/asp/writer/model/ASPPair.java index 662f995c..19730639 100644 --- a/src/de/dhbwstuttgart/sat/asp/writer/model/ASPPair.java +++ b/src/de/dhbwstuttgart/sat/asp/writer/model/ASPPair.java @@ -1,16 +1,20 @@ package de.dhbwstuttgart.sat.asp.writer.model; +import de.dhbwstuttgart.sat.asp.writer.ASPWriter; + public abstract class ASPPair { public final ASPType leftSide; public final ASPType rightSide; - public ASPPair(ASPType ls, ASPType rs){ + public ASPPair(ASPType ls, ASPType rs, ASPWriter writer){ this.leftSide = ls; this.rightSide = rs; + writer.add(new ASPStatement(ls.toASP())); + writer.add(new ASPStatement(rs.toASP())); } public String toASP(){ - return this.getRuleName() + "(" + leftSide + ","+ rightSide + ")"; + return this.getRuleName() + "(" + leftSide.getPointer() + ","+ rightSide.getPointer() + ")"; } public String toString(){ diff --git a/src/de/dhbwstuttgart/sat/asp/writer/model/ASPPairEquals.java b/src/de/dhbwstuttgart/sat/asp/writer/model/ASPPairEquals.java index 8806f2ce..bf6e2485 100644 --- a/src/de/dhbwstuttgart/sat/asp/writer/model/ASPPairEquals.java +++ b/src/de/dhbwstuttgart/sat/asp/writer/model/ASPPairEquals.java @@ -1,10 +1,11 @@ package de.dhbwstuttgart.sat.asp.writer.model; import de.dhbwstuttgart.sat.asp.model.ASPRule; +import de.dhbwstuttgart.sat.asp.writer.ASPWriter; public class ASPPairEquals extends ASPPair{ - public ASPPairEquals(ASPType ls, ASPType rs){ - super(ls, rs); + public ASPPairEquals(ASPType ls, ASPType rs, ASPWriter writer){ + super(ls, rs, writer); } @Override diff --git a/src/de/dhbwstuttgart/sat/asp/writer/model/ASPPairSmaller.java b/src/de/dhbwstuttgart/sat/asp/writer/model/ASPPairSmaller.java index 928acb49..610e5c56 100644 --- a/src/de/dhbwstuttgart/sat/asp/writer/model/ASPPairSmaller.java +++ b/src/de/dhbwstuttgart/sat/asp/writer/model/ASPPairSmaller.java @@ -1,12 +1,13 @@ package de.dhbwstuttgart.sat.asp.writer.model; import de.dhbwstuttgart.sat.asp.model.ASPRule; +import de.dhbwstuttgart.sat.asp.writer.ASPWriter; import java.util.Map; public class ASPPairSmaller extends ASPPair{ - public ASPPairSmaller(ASPFCType ls, ASPFCType rs){ - super(ls, rs); + public ASPPairSmaller(ASPFCType ls, ASPFCType rs, ASPWriter writer){ + super(ls, rs, writer); } @Override diff --git a/src/de/dhbwstuttgart/sat/asp/writer/model/ASPPairSmallerDot.java b/src/de/dhbwstuttgart/sat/asp/writer/model/ASPPairSmallerDot.java index e8482bfc..b572ed99 100644 --- a/src/de/dhbwstuttgart/sat/asp/writer/model/ASPPairSmallerDot.java +++ b/src/de/dhbwstuttgart/sat/asp/writer/model/ASPPairSmallerDot.java @@ -1,10 +1,11 @@ package de.dhbwstuttgart.sat.asp.writer.model; import de.dhbwstuttgart.sat.asp.model.ASPRule; +import de.dhbwstuttgart.sat.asp.writer.ASPWriter; public class ASPPairSmallerDot extends ASPPair{ - public ASPPairSmallerDot(ASPType ls, ASPType rs){ - super(ls, rs); + public ASPPairSmallerDot(ASPType ls, ASPType rs, ASPWriter writer){ + super(ls, rs, writer); } @Override diff --git a/src/de/dhbwstuttgart/sat/asp/writer/model/ASPRefType.java b/src/de/dhbwstuttgart/sat/asp/writer/model/ASPRefType.java index bfbf27a0..5eab65be 100644 --- a/src/de/dhbwstuttgart/sat/asp/writer/model/ASPRefType.java +++ b/src/de/dhbwstuttgart/sat/asp/writer/model/ASPRefType.java @@ -18,4 +18,14 @@ public class ASPRefType implements ASPType { public String toString(){ return ASPRule.ASP_TYPE + "(" + name +"," + params.name + ")"; } + + @Override + public String toASP() { + return toString(); + } + + @Override + public String getPointer() { + return name; + } } diff --git a/src/de/dhbwstuttgart/sat/asp/writer/model/ASPType.java b/src/de/dhbwstuttgart/sat/asp/writer/model/ASPType.java index da694218..6e715dba 100644 --- a/src/de/dhbwstuttgart/sat/asp/writer/model/ASPType.java +++ b/src/de/dhbwstuttgart/sat/asp/writer/model/ASPType.java @@ -1,4 +1,7 @@ package de.dhbwstuttgart.sat.asp.writer.model; public interface ASPType { + String toASP(); + + String getPointer(); } diff --git a/src/de/dhbwstuttgart/sat/asp/writer/model/ASPTypeVar.java b/src/de/dhbwstuttgart/sat/asp/writer/model/ASPTypeVar.java index 4b07d30b..8b3c1af6 100644 --- a/src/de/dhbwstuttgart/sat/asp/writer/model/ASPTypeVar.java +++ b/src/de/dhbwstuttgart/sat/asp/writer/model/ASPTypeVar.java @@ -11,4 +11,14 @@ public class ASPTypeVar implements ASPType{ public String toString() { return "typeVar("+ name +")"; } + + @Override + public String toASP() { + return toString(); + } + + @Override + public String getPointer() { + return name; + } } diff --git a/test/javFiles/Vector.jav b/test/javFiles/Vector.jav index f2a9cdae..1ea1ac41 100644 --- a/test/javFiles/Vector.jav +++ b/test/javFiles/Vector.jav @@ -1,3 +1,4 @@ +import java.util.Vector; class Vector{ From a45aa5057452d8e888dbeb0adaa692a694084741 Mon Sep 17 00:00:00 2001 From: Fayez Abu Alia Date: Wed, 14 Feb 2018 14:37:36 +0100 Subject: [PATCH 12/24] =?UTF-8?q?erzeugt=20bytecode=20f=C3=BCr=20Zuweisung?= =?UTF-8?q?=20von=20Literale?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dhbwstuttgart/bytecode/BytecodeGen.java | 4 +- .../bytecode/BytecodeGenMethod.java | 123 +++++++++++++++++- .../bytecode/signature/Signature.java | 2 +- test/bytecode/AssignToLit.jav | 30 +++++ test/bytecode/AssignToLitTest.java | 7 + test/bytecode/Example.jav | 6 +- test/bytecode/For.jav | 3 + test/bytecode/ForTest.java | 2 + test/bytecode/JavaTXCompilerTest.java | 2 +- test/bytecode/LamAssign.jav | 4 + 10 files changed, 176 insertions(+), 7 deletions(-) create mode 100644 test/bytecode/AssignToLit.jav create mode 100644 test/bytecode/AssignToLitTest.java diff --git a/src/de/dhbwstuttgart/bytecode/BytecodeGen.java b/src/de/dhbwstuttgart/bytecode/BytecodeGen.java index 57aeecc3..f24bb3fd 100644 --- a/src/de/dhbwstuttgart/bytecode/BytecodeGen.java +++ b/src/de/dhbwstuttgart/bytecode/BytecodeGen.java @@ -55,6 +55,7 @@ public class BytecodeGen implements ASTVisitor { @Override public void visit(SourceFile sourceFile) { for(ClassOrInterface cl : sourceFile.getClasses()) { + System.out.println("in Class: " + cl.getClassName().toString()); BytecodeGen classGen = new BytecodeGen(classFiles, resultSet); cl.accept(classGen); classGen.writeClass(cl.getClassName().toString()); @@ -183,7 +184,8 @@ public class BytecodeGen implements ASTVisitor { System.out.println(sig); NormalMethod meth = new NormalMethod(method,genericsAndBounds,genericsAndBoundsMethod,hasGen); methDesc = meth.accept(new DescriptorToString(resultSet)); - MethodVisitor mv = cw.visitMethod(acc, method.getName(), methDesc, sig, null); + System.out.println(methDesc); + MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC+acc, method.getName(), methDesc, sig, null); mv.visitCode(); diff --git a/src/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java b/src/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java index c5480ac0..f04711e8 100644 --- a/src/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java +++ b/src/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java @@ -236,7 +236,7 @@ public class BytecodeGenMethod implements StatementVisitor{ cw.visitInnerClass("java/lang/invoke/MethodHandles$Lookup", "java/lang/invoke/MethodHandles", "Lookup", Opcodes.ACC_PUBLIC + Opcodes.ACC_STATIC + Opcodes.ACC_FINAL); - generateBCForFunN(lambdaExpression,typeErasure); +// generateBCForFunN(lambdaExpression,typeErasure); } private void generateBCForFunN(LambdaExpression lambdaExpression, String methDesc) { @@ -435,7 +435,126 @@ public class BytecodeGenMethod implements StatementVisitor{ @Override public void visit(Literal literal) { - mv.visitLdcInsn(getResolvedType(literal.getType())); + System.out.println(resultSet.resolveType(literal.getType()).resolvedType.acceptTV(new TypeToDescriptor())); + Object value = literal.value; + switch (resultSet.resolveType(literal.getType()).resolvedType.acceptTV(new TypeToDescriptor())) { + case "java/lang/String": + mv.visitLdcInsn((String) value); + break; + case "java/lang/Boolean": + visitBooleanLiteral((Boolean) value); + break; + case "java/lang/Byte": + visitByteLiteral(((Double) value).byteValue(),false); + mv.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/Byte", "valueOf", + "(B)Ljava/lang/Byte;", false); + break; + case "java/lang/Short": + visitShortLiteral(((Double) value).shortValue(),false); + mv.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/Short", "valueOf", + "(S)Ljava/lang/Short;", false); + break; + case "java/lang/Integer": + //zweite Argument isLong + visitIntegerLiteral(((Double) value).intValue(), false); + mv.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/Integer", "valueOf", + "(I)Ljava/lang/Integer;", false); + break; + case "java/lang/Long": + visitLongLiteral(((Double) value).longValue(), true); + mv.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/Long", "valueOf", + "(J)Ljava/lang/Long;", false); + break; + case "java/lang/Float": + visitFloatLiteral(((Double) value).floatValue()); + break; + case "java/lang/Double": + visitDoubleLiteral((Double) value); + break; + case "java/lang/Character": + visitCharLiteral((Character) value); + break; + default: + break; + } + } + + private void visitCharLiteral(Character value) { + mv.visitIntInsn(Opcodes.BIPUSH, Character.getNumericValue(value.charValue())); + mv.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/Character", "valueOf", + "(C)Ljava/lang/Character;", false); + } + + 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); + } + mv.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/Double", "valueOf", + "(D)Ljava/lang/Double;", false); + } + + 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); + } + mv.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/Float", "valueOf", + "(F)Ljava/lang/Float;", false); + } + + private void visitLongLiteral(Long value, boolean isLong) { + if(value=-Math.pow(2, 15))&&value<-128) { + visitShortLiteral(value.shortValue(),isLong); + }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<-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<-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); + } + mv.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/Boolean", "valueOf", + "(Z)Ljava/lang/Boolean;", false); } @Override diff --git a/src/de/dhbwstuttgart/bytecode/signature/Signature.java b/src/de/dhbwstuttgart/bytecode/signature/Signature.java index fc9e2191..cc4a6a13 100644 --- a/src/de/dhbwstuttgart/bytecode/signature/Signature.java +++ b/src/de/dhbwstuttgart/bytecode/signature/Signature.java @@ -134,7 +134,7 @@ public class Signature { RefTypeOrTPHOrWildcardOrGeneric r = resultSet.resolveType(t).resolvedType; sv.visitInterface().visitClassType(r.acceptTV(new TypeToSignature())); // sv.visitClassType(r.acceptTV(new TypeToSignature())); -// System.out.println(r.getClass()+" Signature TPH: "+r.acceptTV(new TypeToSignature())); + System.out.println(r.getClass()+" Signature TPH: "+r.acceptTV(new TypeToSignature())); break; default: if(!isParameterType) diff --git a/test/bytecode/AssignToLit.jav b/test/bytecode/AssignToLit.jav new file mode 100644 index 00000000..4691a5da --- /dev/null +++ b/test/bytecode/AssignToLit.jav @@ -0,0 +1,30 @@ +import java.lang.Integer; +import java.lang.Boolean; +import java.lang.String; +import java.lang.Byte; +import java.lang.Short; +import java.lang.Long; +import java.lang.Float; +import java.lang.Double; +import java.lang.Character; + +class AssignToLit { + void m(){ + String s = "String"; + Boolean b = false; + Byte byte1 = 5; + Byte byte2 = 55; + Short short1 = 5; + Short short2 = 55; + Integer int1 = 5; + Integer int2 = 8888888; + Long long1 = 1; + Long long2 = 5; + Long long3 = 89989898; + Float float1 = 1; + Float float2 = 55; + Double d1 = 1; + Double d2 = 55; + Character c = 'A'; + } +} \ No newline at end of file diff --git a/test/bytecode/AssignToLitTest.java b/test/bytecode/AssignToLitTest.java new file mode 100644 index 00000000..dc5d397b --- /dev/null +++ b/test/bytecode/AssignToLitTest.java @@ -0,0 +1,7 @@ +package bytecode; + +public class AssignToLitTest extends JavaTXCompilerTest { + public AssignToLitTest() { + this.fileName = "AssignToLit"; + } +} diff --git a/test/bytecode/Example.jav b/test/bytecode/Example.jav index 8fc7a0a7..b7455a3f 100644 --- a/test/bytecode/Example.jav +++ b/test/bytecode/Example.jav @@ -1,7 +1,9 @@ +import java.lang.String; + public class Example { - public m(Integer x) { -// String x = "X"; + public m() { + String x = "X"; return x; } } \ No newline at end of file diff --git a/test/bytecode/For.jav b/test/bytecode/For.jav index c93b34c4..e14c62f8 100644 --- a/test/bytecode/For.jav +++ b/test/bytecode/For.jav @@ -1,3 +1,6 @@ +import java.lang.Integer; +import java.lang.Boolean; + class For{ m(Integer x){ Boolean b = true; diff --git a/test/bytecode/ForTest.java b/test/bytecode/ForTest.java index 7df68665..c95138d3 100644 --- a/test/bytecode/ForTest.java +++ b/test/bytecode/ForTest.java @@ -1,5 +1,7 @@ package bytecode; +import org.objectweb.asm.Opcodes; + public class ForTest extends JavaTXCompilerTest { public ForTest() { diff --git a/test/bytecode/JavaTXCompilerTest.java b/test/bytecode/JavaTXCompilerTest.java index 2f832962..623fc96e 100644 --- a/test/bytecode/JavaTXCompilerTest.java +++ b/test/bytecode/JavaTXCompilerTest.java @@ -67,7 +67,7 @@ public class JavaTXCompilerTest { byte[] bytecode = classFiles.get(name); try { System.out.println("generating "+name+ ".class file ..."); - output = new FileOutputStream(new File(System.getProperty("user.dir") + "/testBytecode/generatedBC/examples/" +name+".class")); + output = new FileOutputStream(new File(System.getProperty("user.dir") + "/testBytecode/generatedBC/" +name+".class")); output.write(bytecode); output.close(); System.out.println(name+".class file generated"); diff --git a/test/bytecode/LamAssign.jav b/test/bytecode/LamAssign.jav index 4a4f4f73..82bb31b1 100644 --- a/test/bytecode/LamAssign.jav +++ b/test/bytecode/LamAssign.jav @@ -9,3 +9,7 @@ class LamAssign { return lam1; } } + +interface Fun1{ + public A apply(B b); +} \ No newline at end of file From b7bb0fa1c454858b34e786b1651764a11b9177c2 Mon Sep 17 00:00:00 2001 From: JanUlrich Date: Mon, 19 Feb 2018 04:47:10 +0100 Subject: [PATCH 13/24] Vector Test Fehler beheben --- .../dhbwstuttgart/environment/CompilationEnvironment.java | 2 +- .../parser/SyntaxTreeGenerator/SyntaxTreeGenerator.java | 7 ++++++- test/javFiles/Vector.jav | 2 +- 3 files changed, 8 insertions(+), 3 deletions(-) diff --git a/src/de/dhbwstuttgart/environment/CompilationEnvironment.java b/src/de/dhbwstuttgart/environment/CompilationEnvironment.java index 44754e7c..3d450183 100644 --- a/src/de/dhbwstuttgart/environment/CompilationEnvironment.java +++ b/src/de/dhbwstuttgart/environment/CompilationEnvironment.java @@ -62,7 +62,7 @@ public class CompilationEnvironment { } //URLClassLoader loader = new URLClassLoader(new URL[0], cl); //librarys = Arrays.asList(loader.getURLs()); - + this.sourceFiles = sourceFiles; this.packageCrawler = new PackageCrawler(librarys); } diff --git a/src/de/dhbwstuttgart/parser/SyntaxTreeGenerator/SyntaxTreeGenerator.java b/src/de/dhbwstuttgart/parser/SyntaxTreeGenerator/SyntaxTreeGenerator.java index b681d9c3..ed96d2e6 100644 --- a/src/de/dhbwstuttgart/parser/SyntaxTreeGenerator/SyntaxTreeGenerator.java +++ b/src/de/dhbwstuttgart/parser/SyntaxTreeGenerator/SyntaxTreeGenerator.java @@ -164,7 +164,12 @@ public class SyntaxTreeGenerator{ modifiers += newModifier; } } - JavaClassName name = reg.getName(ctx.Identifier().getText()); + String className = this.pkgName + (this.pkgName.length()>0?".":"") + ctx.Identifier().getText(); + JavaClassName name = reg.getName(className); + if(! name.toString().equals(className)){ + throw new TypeinferenceException("Name " + className + " bereits vorhanden in " + reg.getName(className).toString() + ,ctx.getStart()); + } GenericsRegistry generics = createGenerics(ctx.typeParameters(), name, "", reg, new GenericsRegistry(globalGenerics)); Token offset = ctx.getStart(); GenericDeclarationList genericClassParameters; diff --git a/test/javFiles/Vector.jav b/test/javFiles/Vector.jav index 1ea1ac41..ef3533a6 100644 --- a/test/javFiles/Vector.jav +++ b/test/javFiles/Vector.jav @@ -1,6 +1,6 @@ import java.util.Vector; -class Vector{ +class MyVector{ id(x){ return id2(x); From d53faa0c86f393edcc9f47200866ab844ccecefe Mon Sep 17 00:00:00 2001 From: JanUlrich Date: Mon, 19 Feb 2018 11:33:08 +0100 Subject: [PATCH 14/24] FiniteClosure korrekt generieren --- .../SyntaxTreeGenerator/FCGenerator.java | 61 ++++++++++--------- .../sat/asp/writer/ASPGenerator.java | 16 +++-- .../syntaxtree/factory/UnifyTypeFactory.java | 4 +- test/asp/ClingoTest.java | 2 +- test/asp/typeinference/ASPTest.java | 6 +- 5 files changed, 48 insertions(+), 41 deletions(-) diff --git a/src/de/dhbwstuttgart/parser/SyntaxTreeGenerator/FCGenerator.java b/src/de/dhbwstuttgart/parser/SyntaxTreeGenerator/FCGenerator.java index 7863c8ed..ea2b17a6 100644 --- a/src/de/dhbwstuttgart/parser/SyntaxTreeGenerator/FCGenerator.java +++ b/src/de/dhbwstuttgart/parser/SyntaxTreeGenerator/FCGenerator.java @@ -2,6 +2,7 @@ package de.dhbwstuttgart.parser.SyntaxTreeGenerator; import de.dhbwstuttgart.exceptions.DebugException; import de.dhbwstuttgart.exceptions.NotImplementedException; +import de.dhbwstuttgart.parser.NullToken; import de.dhbwstuttgart.syntaxtree.ClassOrInterface; import de.dhbwstuttgart.syntaxtree.GenericTypeVar; import de.dhbwstuttgart.syntaxtree.factory.ASTFactory; @@ -11,6 +12,7 @@ import de.dhbwstuttgart.typeinference.constraints.Pair; import de.dhbwstuttgart.typeinference.unify.model.*; import java.util.*; +import java.util.stream.Collectors; public class FCGenerator { /** @@ -19,12 +21,15 @@ public class FCGenerator { * * @param availableClasses - Alle geparsten Klassen */ - public static Set toFC(Collection availableClasses) throws ClassNotFoundException { - HashSet pairs = new HashSet<>(); + public static Set toUnifyFC(Collection availableClasses) throws ClassNotFoundException { + return toFC(availableClasses).stream().map(t -> UnifyTypeFactory.convert(t)).collect(Collectors.toSet()); + } + + public static Set toFC(Collection availableClasses) throws ClassNotFoundException { + HashSet pairs = new HashSet<>(); for(ClassOrInterface cly : availableClasses){ pairs.addAll(getSuperTypes(cly, availableClasses)); } - System.out.println(pairs); return pairs; } @@ -35,20 +40,20 @@ public class FCGenerator { * @param forType * @return */ - private static List getSuperTypes(ClassOrInterface forType, Collection availableClasses) throws ClassNotFoundException { + private static List getSuperTypes(ClassOrInterface forType, Collection availableClasses) throws ClassNotFoundException { return getSuperTypes(forType, availableClasses, new HashMap<>()); } //TODO: implements Interface auch als superklassen beachten - private static List getSuperTypes(ClassOrInterface forType, Collection availableClasses, HashMap gtvs) throws ClassNotFoundException { - List params = new ArrayList<>(); + private static List getSuperTypes(ClassOrInterface forType, Collection availableClasses, HashMap gtvs) throws ClassNotFoundException { + List params = new ArrayList<>(); //Die GTVs, die in forType hinzukommen: - HashMap newGTVs = new HashMap<>(); + HashMap newGTVs = new HashMap<>(); //Generics mit gleichem Namen müssen den selben TPH bekommen for(GenericTypeVar gtv : forType.getGenerics()){ if(!gtvs.containsKey(gtv.getParsedName())){ - gtvs.put(gtv.getParsedName(), PlaceholderType.freshPlaceholder()); - newGTVs.put(gtv.getParsedName(), PlaceholderType.freshPlaceholder()); + gtvs.put(gtv.getParsedName(), TypePlaceholder.fresh(new NullToken())); + newGTVs.put(gtv.getParsedName(), TypePlaceholder.fresh(new NullToken())); } params.add(gtvs.get(gtv.getParsedName())); } @@ -73,27 +78,26 @@ public class FCGenerator { while(itGenParams.hasNext()){ RefTypeOrTPHOrWildcardOrGeneric setType = itSetParams.next(); //In diesem Typ die GTVs durch TPHs und Einsetzungen austauschen: - UnifyType setSetType = setType.acceptTV(new TypeExchanger(gtvs)); + RefTypeOrTPHOrWildcardOrGeneric setSetType = setType.acceptTV(new TypeExchanger(gtvs)); newGTVs.put(itGenParams.next().getParsedName(), setSetType); } - UnifyType superType = forType.getSuperClass().acceptTV(new TypeExchanger(newGTVs)); + RefTypeOrTPHOrWildcardOrGeneric superType = forType.getSuperClass().acceptTV(new TypeExchanger(newGTVs)); - TypeParams paramList = new TypeParams(params); - UnifyType t1 = new ReferenceType(forType.getClassName().toString(), paramList); - UnifyType t2 = superType; + RefTypeOrTPHOrWildcardOrGeneric t1 = new RefType(forType.getClassName(), params, new NullToken()); + RefTypeOrTPHOrWildcardOrGeneric t2 = superType; - UnifyPair ret = UnifyTypeFactory.generateSmallerPair(t1, t2); + Pair ret = new Pair(t1, t2, PairOperator.SMALLER); - List superTypes; + List superTypes; //Rekursiver Aufruf. Abbruchbedingung ist Object als Superklasse: if(superClass.getClassName().equals(ASTFactory.createObjectClass().getClassName())){ - superTypes = Arrays.asList(UnifyTypeFactory.generateSmallerPair(UnifyTypeFactory.convert(ASTFactory.createObjectType()), UnifyTypeFactory.convert(ASTFactory.createObjectType()))); + superTypes = Arrays.asList(new Pair(ASTFactory.createObjectType(), ASTFactory.createObjectType(), PairOperator.SMALLER)); }else{ superTypes = getSuperTypes(superClass, availableClasses, newGTVs); } - List retList = new ArrayList<>(); + List retList = new ArrayList<>(); retList.add(ret); retList.addAll(superTypes); @@ -103,42 +107,41 @@ public class FCGenerator { /** * Tauscht die GTVs in einem Typ gegen die entsprechenden Typen in der übergebenen Map aus. */ - private static class TypeExchanger implements TypeVisitor{ + private static class TypeExchanger implements TypeVisitor{ - private final HashMap gtvs; + private final HashMap gtvs; - TypeExchanger(HashMap gtvs){ + TypeExchanger(HashMap gtvs){ this.gtvs = gtvs; } @Override - public UnifyType visit(RefType refType) { - List params = new ArrayList<>(); + public RefTypeOrTPHOrWildcardOrGeneric visit(RefType refType) { + List params = new ArrayList<>(); for(RefTypeOrTPHOrWildcardOrGeneric param : refType.getParaList()){ params.add(param.acceptTV(this)); } - TypeParams paramList = new TypeParams(params); - UnifyType ret = new ReferenceType(refType.getName().toString(), paramList); + RefTypeOrTPHOrWildcardOrGeneric ret = new RefType(refType.getName(), params, new NullToken()); return ret; } @Override - public UnifyType visit(SuperWildcardType superWildcardType) { + public RefTypeOrTPHOrWildcardOrGeneric visit(SuperWildcardType superWildcardType) { throw new DebugException("Dieser Fall darf nicht auftreten"); } @Override - public UnifyType visit(TypePlaceholder typePlaceholder) { + public RefTypeOrTPHOrWildcardOrGeneric visit(TypePlaceholder typePlaceholder) { throw new DebugException("Dieser Fall darf nicht auftreten"); } @Override - public UnifyType visit(ExtendsWildcardType extendsWildcardType) { + public RefTypeOrTPHOrWildcardOrGeneric visit(ExtendsWildcardType extendsWildcardType) { throw new DebugException("Dieser Fall darf nicht auftreten"); } @Override - public UnifyType visit(GenericRefType genericRefType) { + public RefTypeOrTPHOrWildcardOrGeneric visit(GenericRefType genericRefType) { if(! gtvs.containsKey(genericRefType.getParsedName())) throw new DebugException("Dieser Fall darf nicht auftreten"); //TODO: Diesen Dirty-Hack beseitigen. Fehler tritt bei java.lang.invoke.LambdaFormEditor$Transform$Kind auf. diff --git a/src/de/dhbwstuttgart/sat/asp/writer/ASPGenerator.java b/src/de/dhbwstuttgart/sat/asp/writer/ASPGenerator.java index ea162c11..38652b43 100644 --- a/src/de/dhbwstuttgart/sat/asp/writer/ASPGenerator.java +++ b/src/de/dhbwstuttgart/sat/asp/writer/ASPGenerator.java @@ -1,6 +1,7 @@ package de.dhbwstuttgart.sat.asp.writer; import de.dhbwstuttgart.exceptions.NotImplementedException; +import de.dhbwstuttgart.parser.SyntaxTreeGenerator.FCGenerator; import de.dhbwstuttgart.parser.scope.JavaClassName; import de.dhbwstuttgart.sat.asp.writer.model.*; import de.dhbwstuttgart.syntaxtree.ClassOrInterface; @@ -19,25 +20,25 @@ public class ASPGenerator { ASPWriter writer = new ASPWriter(); private final String asp; - public ASPGenerator(ConstraintSet constraints, Collection fcClasses){ + public ASPGenerator(ConstraintSet constraints, Collection fcClasses) throws ClassNotFoundException { List> constraints1 = constraints.cartesianProduct().iterator().next(); List constraintPairs = new ArrayList<>(); for(Constraint constraint : constraints1){ System.out.println(UnifyTypeFactory.convert(constraint)); constraintPairs.addAll(constraint); } - asp = toASP(constraintPairs, fcClasses); + asp = toASP(constraintPairs, FCGenerator.toFC(fcClasses)); } public String getASP(){ return asp; } - private String toASP(List constraintSet, Collection fcClasses){ + private String toASP(List constraintSet, Collection fc){ TypeConverter converter = new TypeConverter(); - for(ClassOrInterface cl : fcClasses){ - ASPRefType superClass = (ASPRefType) cl.getSuperClass().acceptTV(converter); - ASPPairSmaller fcEntry = new ASPPairSmaller(new ASPFCType(convert(cl)), new ASPFCType(superClass), writer); + for(Pair fcp : fc){ + //Wenn dieser Cast fehlschlägt stimmt etwas nicht. Alle Paare in der FC müssen smaller Operatoren haen + ASPPairSmaller fcEntry = (ASPPairSmaller) convert(fcp); writer.add(new ASPStatement(fcEntry.toASP())); } for(Pair cons : constraintSet){ @@ -55,6 +56,9 @@ public class ASPGenerator { return new ASPPairEquals(ls, rs,writer); }else if(pair.OperatorSmallerDot()){ return new ASPPairSmallerDot(ls, rs, writer); + }else if(pair.OperatorSmaller()){ + //Diese Cast müssen auch immer funktionieren, da in smaller Constraints nur RefTypes vorkommen + return new ASPPairSmaller(new ASPFCType((ASPRefType) ls), new ASPFCType((ASPRefType) rs), writer); }else throw new NotImplementedException(); } diff --git a/src/de/dhbwstuttgart/syntaxtree/factory/UnifyTypeFactory.java b/src/de/dhbwstuttgart/syntaxtree/factory/UnifyTypeFactory.java index a962c2bc..4ecaa136 100644 --- a/src/de/dhbwstuttgart/syntaxtree/factory/UnifyTypeFactory.java +++ b/src/de/dhbwstuttgart/syntaxtree/factory/UnifyTypeFactory.java @@ -3,13 +3,11 @@ package de.dhbwstuttgart.syntaxtree.factory; import java.util.*; import java.util.stream.Collectors; -import de.dhbwstuttgart.exceptions.DebugException; import de.dhbwstuttgart.exceptions.NotImplementedException; import de.dhbwstuttgart.parser.NullToken; import de.dhbwstuttgart.parser.SyntaxTreeGenerator.FCGenerator; import de.dhbwstuttgart.parser.scope.JavaClassName; import de.dhbwstuttgart.syntaxtree.ClassOrInterface; -import de.dhbwstuttgart.syntaxtree.GenericTypeVar; import de.dhbwstuttgart.syntaxtree.type.*; import de.dhbwstuttgart.syntaxtree.type.Void; import de.dhbwstuttgart.syntaxtree.type.WildcardType; @@ -35,7 +33,7 @@ public class UnifyTypeFactory { Generell dürfen sie immer die gleichen Namen haben. TODO: die transitive Hülle bilden */ - return new FiniteClosure(FCGenerator.toFC(fromClasses)); + return new FiniteClosure(FCGenerator.toUnifyFC(fromClasses)); } public static UnifyPair generateSmallerPair(UnifyType tl, UnifyType tr){ diff --git a/test/asp/ClingoTest.java b/test/asp/ClingoTest.java index dbfa70d8..83f3a26f 100644 --- a/test/asp/ClingoTest.java +++ b/test/asp/ClingoTest.java @@ -19,7 +19,7 @@ public class ClingoTest { public static final String tempDirectory = "/tmp/"; @Test - public void test() throws IOException, InterruptedException { + public void test() throws IOException, InterruptedException, ClassNotFoundException { String content = ""; content = new ASPGenerator(this.getPairs(), this.getFC()).getASP(); diff --git a/test/asp/typeinference/ASPTest.java b/test/asp/typeinference/ASPTest.java index b41d9405..cea141f9 100644 --- a/test/asp/typeinference/ASPTest.java +++ b/test/asp/typeinference/ASPTest.java @@ -14,7 +14,9 @@ import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; +import java.util.HashSet; import java.util.List; +import java.util.Set; public class ASPTest { @@ -44,9 +46,9 @@ public class ASPTest { //filesToTest.add(new File(rootDirectory+"Matrix.jav")); //filesToTest.add(new File(rootDirectory+"Import.jav")); JavaTXCompiler compiler = new JavaTXCompiler(fileToTest); - List allClasses = new ArrayList<>(); + Set allClasses = new HashSet<>(); for(SourceFile sf : compiler.sourceFiles.values()) { - //allClasses.addAll(compiler.getAvailableClasses(sf)); + allClasses.addAll(compiler.getAvailableClasses(sf)); } for(SourceFile sf : compiler.sourceFiles.values()) { allClasses.addAll(sf.getClasses()); From c747ab08850989bc52048df8ea78a820be7dd92f Mon Sep 17 00:00:00 2001 From: JanUlrich Date: Wed, 21 Feb 2018 11:40:54 +0100 Subject: [PATCH 15/24] Additive Expression implementieren --- .../SyntaxTreeGenerator/StatementGenerator.java | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/src/de/dhbwstuttgart/parser/SyntaxTreeGenerator/StatementGenerator.java b/src/de/dhbwstuttgart/parser/SyntaxTreeGenerator/StatementGenerator.java index 1586ba3f..679b23df 100644 --- a/src/de/dhbwstuttgart/parser/SyntaxTreeGenerator/StatementGenerator.java +++ b/src/de/dhbwstuttgart/parser/SyntaxTreeGenerator/StatementGenerator.java @@ -599,8 +599,8 @@ public class StatementGenerator { } private BinaryExpr.Operator convertBinaryOperator(String operator) { - - return null; + //return BinaryExpr.Operator.ADD; + throw new NotImplementedException(); } private Expression convert(Java8Parser.ShiftExpressionContext expression) { @@ -612,12 +612,15 @@ public class StatementGenerator { } private Expression convert(Java8Parser.AdditiveExpressionContext expression) { - if(expression.additiveExpression() != null){ - return convert(expression.additiveExpression()); - }else if(expression.multiplicativeExpression() != null){ + + if(expression.additiveExpression() == null){ return convert(expression.multiplicativeExpression()); - }else{ - throw new NotImplementedException(); + }else { + Expression leftSide = convert(expression.additiveExpression()); + Expression rightSide = convert(expression.multiplicativeExpression()); + BinaryExpr.Operator op = convertBinaryOperator(expression.getChild(1).getText()); + Token offset = expression.getStart(); + return new BinaryExpr(op, TypePlaceholder.fresh(expression.getStart()), leftSide, rightSide, offset); } } From 7c2f7c54ddfaaf23c6895551a43aba99129df63c Mon Sep 17 00:00:00 2001 From: Fayez Abu Alia Date: Wed, 21 Feb 2018 11:44:03 +0100 Subject: [PATCH 16/24] =?UTF-8?q?Kleine=20=C3=84nderung?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dhbwstuttgart/bytecode/BytecodeGenMethod.java | 3 +-- .../bytecode/signature/Signature.java | 3 ++- test/bytecode/AssignToLit.jav | 2 +- test/bytecode/Methods.jav | 14 ++++++++++++++ test/bytecode/MethodsTest.java | 7 +++++++ 5 files changed, 25 insertions(+), 4 deletions(-) create mode 100644 test/bytecode/Methods.jav create mode 100644 test/bytecode/MethodsTest.java diff --git a/src/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java b/src/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java index f04711e8..402f578d 100644 --- a/src/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java +++ b/src/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java @@ -435,11 +435,10 @@ public class BytecodeGenMethod implements StatementVisitor{ @Override public void visit(Literal literal) { - System.out.println(resultSet.resolveType(literal.getType()).resolvedType.acceptTV(new TypeToDescriptor())); Object value = literal.value; switch (resultSet.resolveType(literal.getType()).resolvedType.acceptTV(new TypeToDescriptor())) { case "java/lang/String": - mv.visitLdcInsn((String) value); + mv.visitLdcInsn(value); break; case "java/lang/Boolean": visitBooleanLiteral((Boolean) value); diff --git a/src/de/dhbwstuttgart/bytecode/signature/Signature.java b/src/de/dhbwstuttgart/bytecode/signature/Signature.java index cc4a6a13..f9bcb369 100644 --- a/src/de/dhbwstuttgart/bytecode/signature/Signature.java +++ b/src/de/dhbwstuttgart/bytecode/signature/Signature.java @@ -132,7 +132,8 @@ public class Signature { break; case "TPH": RefTypeOrTPHOrWildcardOrGeneric r = resultSet.resolveType(t).resolvedType; - sv.visitInterface().visitClassType(r.acceptTV(new TypeToSignature())); + if(!r.acceptTV(new TypeToSignature()).substring(0, 4).equals("TPH ")) + sv.visitInterface().visitClassType(r.acceptTV(new TypeToSignature())); // sv.visitClassType(r.acceptTV(new TypeToSignature())); System.out.println(r.getClass()+" Signature TPH: "+r.acceptTV(new TypeToSignature())); break; diff --git a/test/bytecode/AssignToLit.jav b/test/bytecode/AssignToLit.jav index 4691a5da..46ec2b91 100644 --- a/test/bytecode/AssignToLit.jav +++ b/test/bytecode/AssignToLit.jav @@ -10,7 +10,7 @@ import java.lang.Character; class AssignToLit { void m(){ - String s = "String"; + String s = "Test"; Boolean b = false; Byte byte1 = 5; Byte byte2 = 55; diff --git a/test/bytecode/Methods.jav b/test/bytecode/Methods.jav new file mode 100644 index 00000000..3c46739d --- /dev/null +++ b/test/bytecode/Methods.jav @@ -0,0 +1,14 @@ +import java.lang.Integer; + +class Methods { + + m(a,b){ + var c=a+b; + return c; + } + + method2(x){ + Integer i = this.m(x,2); + return i; + } +} \ No newline at end of file diff --git a/test/bytecode/MethodsTest.java b/test/bytecode/MethodsTest.java new file mode 100644 index 00000000..11195b71 --- /dev/null +++ b/test/bytecode/MethodsTest.java @@ -0,0 +1,7 @@ +package bytecode; + +public class MethodsTest extends JavaTXCompilerTest { + public MethodsTest() { + this.fileName = "Methods"; + } +} From ac4a79f0e76f22a73334538d3a328cd1767ee40e Mon Sep 17 00:00:00 2001 From: Fayez Abu Alia Date: Wed, 21 Feb 2018 15:43:28 +0100 Subject: [PATCH 17/24] Additive/multiplicativeExpression und UnaryExpression implementiert --- .../bytecode/BytecodeGenMethod.java | 5 +- .../StatementGenerator.java | 47 +++++++++++++++---- test/bytecode/For.jav | 17 +++++++ test/parser/GeneralParserTest.java | 3 +- test/parser/OpratorTest.jav | 12 +++++ 5 files changed, 72 insertions(+), 12 deletions(-) create mode 100644 test/parser/OpratorTest.jav diff --git a/src/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java b/src/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java index c5480ac0..b13a1fb6 100644 --- a/src/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java +++ b/src/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java @@ -167,6 +167,7 @@ public class BytecodeGenMethod implements StatementVisitor{ public void visit(BinaryExpr binary) { System.out.println("\t++ In Binary: "); + System.out.println(binary.operation.toString()); } @@ -318,7 +319,7 @@ public class BytecodeGenMethod implements StatementVisitor{ @Override public void visit(IfStmt ifStmt) { - + System.out.println("If"); } @Override @@ -389,7 +390,7 @@ public class BytecodeGenMethod implements StatementVisitor{ @Override public void visit(UnaryExpr unaryExpr) { - throw new NotImplementedException(); + System.out.println(unaryExpr.operation.toString()); } @Override diff --git a/src/de/dhbwstuttgart/parser/SyntaxTreeGenerator/StatementGenerator.java b/src/de/dhbwstuttgart/parser/SyntaxTreeGenerator/StatementGenerator.java index 679b23df..2b0b1a4f 100644 --- a/src/de/dhbwstuttgart/parser/SyntaxTreeGenerator/StatementGenerator.java +++ b/src/de/dhbwstuttgart/parser/SyntaxTreeGenerator/StatementGenerator.java @@ -7,6 +7,7 @@ import de.dhbwstuttgart.parser.scope.GenericsRegistry; import de.dhbwstuttgart.parser.scope.JavaClassRegistry; import de.dhbwstuttgart.syntaxtree.*; import de.dhbwstuttgart.syntaxtree.statement.*; +import de.dhbwstuttgart.syntaxtree.statement.UnaryExpr.Operation; import de.dhbwstuttgart.syntaxtree.type.RefType; import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric; import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder; @@ -278,13 +279,14 @@ public class StatementGenerator { } private Statement convert(Java8Parser.PreIncrementExpressionContext stmt) { - //TODO - throw new NotImplementedException(); + Expression argument = convert(stmt.unaryExpression()); + Token offset = stmt.getStart(); + return new UnaryExpr(UnaryExpr.Operation.PREINCREMENT, argument, TypePlaceholder.fresh(offset), offset); } - private Statement convert(Java8Parser.PreDecrementExpressionContext stmt) { - //TODO - throw new NotImplementedException(); + private Statement convert(Java8Parser.PreDecrementExpressionContext stmt) { + return new UnaryExpr(UnaryExpr.Operation.PREDECREMENT, convert(stmt.unaryExpression()), + TypePlaceholder.fresh(stmt.getStart()), stmt.getStart()); } private Statement convert(Java8Parser.PostIncrementExpressionContext stmt) { @@ -293,8 +295,8 @@ public class StatementGenerator { } private Statement convert(Java8Parser.PostDecrementExpressionContext stmt) { - //TODO - throw new NotImplementedException(); + return new UnaryExpr(UnaryExpr.Operation.POSTDECREMENT, convert(stmt.postfixExpression()), + TypePlaceholder.fresh(stmt.getStart()), stmt.getStart()); } private Statement convert(Java8Parser.AssignmentContext stmt) { @@ -600,7 +602,30 @@ public class StatementGenerator { private BinaryExpr.Operator convertBinaryOperator(String operator) { //return BinaryExpr.Operator.ADD; - throw new NotImplementedException(); + if(operator.equals("+")) { + return BinaryExpr.Operator.ADD; + }else if(operator.equals("-")) { + return BinaryExpr.Operator.SUB; + }else if(operator.equals("*")) { + return BinaryExpr.Operator.MUL; + }else if(operator.equals("&")) { + return BinaryExpr.Operator.AND; + }else if(operator.equals("|")) { + return BinaryExpr.Operator.OR; + }else if(operator.equals("/")) { + return BinaryExpr.Operator.DIV; + }else if(operator.equals("<")) { + return BinaryExpr.Operator.LESSTHAN; + }else if(operator.equals(">")) { + return BinaryExpr.Operator.BIGGERTHAN; + }else if(operator.equals(">=")) { + return BinaryExpr.Operator.BIGGEREQUAL; + } else if(operator.equals("<=")) { + return BinaryExpr.Operator.LESSEQUAL; + } else { + throw new NotImplementedException(); + } +// throw new NotImplementedException(); } private Expression convert(Java8Parser.ShiftExpressionContext expression) { @@ -628,7 +653,11 @@ public class StatementGenerator { if(expression.multiplicativeExpression() == null){ return convert(expression.unaryExpression()); }else{ - throw new NotImplementedException(); + Expression leftSide = convert(expression.multiplicativeExpression()); + Expression rightSide = convert(expression.unaryExpression()); + BinaryExpr.Operator op = convertBinaryOperator(expression.getChild(1).getText()); + Token offset = expression.getStart(); + return new BinaryExpr(op, TypePlaceholder.fresh(offset), leftSide, rightSide, offset); } } diff --git a/test/bytecode/For.jav b/test/bytecode/For.jav index c93b34c4..04cb6a53 100644 --- a/test/bytecode/For.jav +++ b/test/bytecode/For.jav @@ -1,6 +1,15 @@ +import java.lang.Integer; +import java.lang.Boolean; + class For{ m(Integer x){ + Boolean b = true; + c = 5; + c++; + ++c; + c--; + --c; while(x<2){ x = x +1; b = false; @@ -10,4 +19,12 @@ class For{ // x = x + 5; // } } + +// m2(Integer x){ +// if(x<2) { +// return 1; +// }else { +// return 2; +// } +// } } \ No newline at end of file diff --git a/test/parser/GeneralParserTest.java b/test/parser/GeneralParserTest.java index c48e1320..b218347f 100644 --- a/test/parser/GeneralParserTest.java +++ b/test/parser/GeneralParserTest.java @@ -41,7 +41,8 @@ public class GeneralParserTest{ filenames.add("FieldVarTest.jav"); filenames.add("StructuralTypes.jav"); */ - filenames.add("ExtendsTest.jav"); +// filenames.add("ExtendsTest.jav"); + filenames.add("OpratorTest.jav"); try{ new JavaTXCompiler(filenames.stream().map(s -> new File(rootDirectory + s)).collect(Collectors.toList())); }catch(Exception exc){ diff --git a/test/parser/OpratorTest.jav b/test/parser/OpratorTest.jav new file mode 100644 index 00000000..f99734f6 --- /dev/null +++ b/test/parser/OpratorTest.jav @@ -0,0 +1,12 @@ +import java.lang.Integer; + +class OpratorTest { + m(Integer a, Integer b) { + c = a+b; + d = a-b; + e = a*b; + f = a/b; + + return c; + } +} \ No newline at end of file From 73c37027d9dd7390871fa032bf72de85a0c80a61 Mon Sep 17 00:00:00 2001 From: JanUlrich Date: Fri, 23 Feb 2018 09:16:12 +0100 Subject: [PATCH 18/24] Fehler in TypeStmt UnaryExpression beheben --- src/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java b/src/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java index a06062c0..3733b7dc 100644 --- a/src/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java +++ b/src/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java @@ -199,7 +199,7 @@ public class TYPEStmt implements StatementVisitor{ //@see: https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.14.2 //Expression muss zu Numeric Convertierbar sein. also von Numeric erben RefType number = new RefType(ASTFactory.createClass(Number.class).getClassName(), unaryExpr.getOffset()); - constraintsSet.addUndConstraint(new Pair(unaryExpr.expr.getType(), number, PairOperator.EQUALSDOT)); + constraintsSet.addUndConstraint(new Pair(unaryExpr.expr.getType(), number, PairOperator.SMALLERDOT)); //The type of the postfix increment expression is the type of the variable constraintsSet.addUndConstraint(new Pair(unaryExpr.expr.getType(), unaryExpr.getType(), PairOperator.EQUALSDOT)); }else{ From 4fbcf87e0c23888c4e9ea9dd5a2701ac608d1241 Mon Sep 17 00:00:00 2001 From: Fayez Abu Alia Date: Fri, 23 Feb 2018 20:10:11 +0100 Subject: [PATCH 19/24] =?UTF-8?q?Methoden=20visit(assign)/visit(literal)?= =?UTF-8?q?=20angepasst=20und=20generiert=20bytecode=20f=C3=BCr=20Binaryex?= =?UTF-8?q?pressions.=20noch=20nicht=20fertig?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../bytecode/BytecodeGenMethod.java | 145 +++++++++++++----- test/bytecode/AssignToLit.jav | 30 ++-- test/bytecode/For.jav | 26 ++-- test/bytecode/Op.jav | 12 ++ test/bytecode/OpTest.java | 7 + test/parser/OpratorTest.jav | 6 +- 6 files changed, 157 insertions(+), 69 deletions(-) create mode 100644 test/bytecode/Op.jav create mode 100644 test/bytecode/OpTest.java diff --git a/src/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java b/src/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java index b6a45bb1..df714015 100644 --- a/src/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java +++ b/src/de/dhbwstuttgart/bytecode/BytecodeGenMethod.java @@ -43,30 +43,28 @@ public class BytecodeGenMethod implements StatementVisitor{ private MethodVisitor mv; private HashMap paramsAndLocals = new HashMap<>(); private String className; - private int lamCounter; + private int lamCounter = -1; private ClassWriter cw; private ResultSet resultSet; private boolean isInterface; HashMap genericsAndBoundsMethod; private HashMap genericsAndBounds; + private boolean isBinaryExp = false; //for tests ** private String fieldName; private String fieldDesc; private Expression rightSideTemp; -// private String where; private boolean isRightSideALambda = false; private KindOfLambda kindOfLambda; private HashMap classFiles; - private ArrayList varsFunInterface; + private ArrayList varsFunInterface = new ArrayList<>();; public BytecodeGenMethod(String className,ResultSet resultSet, Method m, MethodVisitor mv, HashMap paramsAndLocals, ClassWriter cw, HashMap genericsAndBoundsMethod, HashMap genericsAndBounds, boolean isInterface, HashMap classFiles) { -// this.where = "<<<<<< NORMAL METHOD >>>>>>"; - this.className = className; this.resultSet = resultSet; this.m = m; @@ -77,9 +75,6 @@ public class BytecodeGenMethod implements StatementVisitor{ this.genericsAndBounds = genericsAndBounds; this.isInterface = isInterface; this.classFiles = classFiles; - this.lamCounter = -1; - - this.varsFunInterface = new ArrayList<>(); if(!isInterface) this.m.block.accept(this); @@ -89,13 +84,10 @@ public class BytecodeGenMethod implements StatementVisitor{ public BytecodeGenMethod(LambdaExpression lambdaExpression,ResultSet resultSet ,MethodVisitor mv, int indexOfFirstParamLam, boolean isInterface, HashMap classFiles) { -// this.where = "<<<<<< LAMBDA METHOD >>>>>>"; this.resultSet = resultSet; this.mv = mv; this.isInterface = isInterface; this.classFiles = classFiles; - this.lamCounter = -1; - this.varsFunInterface = new ArrayList<>(); Iterator itr = lambdaExpression.params.iterator(); int i = indexOfFirstParamLam; @@ -124,51 +116,61 @@ public class BytecodeGenMethod implements StatementVisitor{ public void visit(SuperCall superCall) { superCall.receiver.accept(this); superCall.arglist.accept(this); -// mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/Object", superCall.name, desc,false); mv.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(Object.class), superCall.name, "()V",isInterface); } // ?? @Override public void visit(LocalVar localVar) { -// System.out.println("in Local Var: " + localVar.name); mv.visitVarInsn(Opcodes.ALOAD, paramsAndLocals.get(localVar.name)); + if(isBinaryExp) { + getVlaue(getResolvedType(localVar.getType())); + } } // ?? @Override public void visit(LocalVarDecl localVarDecl) { -// Integer i; -// paramsAndLocals.put(localVarDecl.getName(), paramsAndLocals.size()+1); -// System.out.println("In localVarDecl :: "+localVarDecl.getName()); + } @Override public void visit(Assign assign) { -// System.out.println("Assign : \nright = "+assign.rightSide + "\nLeft = " + assign.lefSide); - // if the right side is a lambda => the left side must be a functional interface - if(assign.rightSide.getClass().equals(LambdaExpression.class)) { + if(assign.rightSide instanceof LambdaExpression) { isRightSideALambda = true; }else { isRightSideALambda = false; } - if(assign.lefSide.getClass().equals(AssignToField.class)) { + if(assign.rightSide instanceof BinaryExpr) + isBinaryExp = true; + + if(assign.lefSide instanceof AssignToField) { // load_0, ldc or .. then putfield this.rightSideTemp = assign.rightSide; - assign.lefSide.accept(this); }else { assign.rightSide.accept(this); - assign.lefSide.accept(this); } + if(isBinaryExp) { + doAssign(getResolvedType(assign.lefSide.getType())); + isBinaryExp = false; + } + assign.lefSide.accept(this); } @Override - public void visit(BinaryExpr binary) { - System.out.println("\t++ In Binary: "); - System.out.println(binary.operation.toString()); + binary.lexpr.accept(this); + binary.rexpr.accept(this); + switch (binary.operation.toString()) { + case "ADD": + mv.visitInsn(Opcodes.IADD); + break; + default: + break; + } + } @Override @@ -330,12 +332,6 @@ public class BytecodeGenMethod implements StatementVisitor{ @Override public void visit(MethodCall methodCall) { -// if(methodCall.receiver instanceof ExpressionReceiver){ -// System.out.print(((ExpressionReceiver) methodCall.receiver).expr + "\n"); -// }else{ -// System.out.print(((StaticClassName) methodCall.receiver).getType().toString() + "\n"); -// } - methodCall.receiver.accept(this); methodCall.arglist.accept(this); @@ -343,8 +339,6 @@ public class BytecodeGenMethod implements StatementVisitor{ genericsAndBoundsMethod,genericsAndBounds); String mDesc = method.accept(new DescriptorToString(resultSet)); -// System.out.println("is Vars empty: "+varsFunInterface.isEmpty()); - // is methodCall.receiver functional Interface)? if(varsFunInterface.contains(methodCall.receiver.getType())) { mv.visitMethodInsn(Opcodes.INVOKEINTERFACE, getResolvedType(methodCall.receiver.getType()), @@ -361,8 +355,6 @@ public class BytecodeGenMethod implements StatementVisitor{ @Override public void visit(NewClass methodCall) { -// System.out.println("In NewClass: "); -// System.out.println("\t\tname: " + methodCall.name + " *** " + "Receiver: " + methodCall.receiver); mv.visitTypeInsn(Opcodes.NEW, methodCall.name.replace(".", "/")); mv.visitInsn(Opcodes.DUP); @@ -437,9 +429,53 @@ public class BytecodeGenMethod implements StatementVisitor{ @Override public void visit(Literal literal) { Object value = literal.value; - switch (resultSet.resolveType(literal.getType()).resolvedType.acceptTV(new TypeToDescriptor())) { + String typeOfLiteral = resultSet.resolveType(literal.getType()).resolvedType.acceptTV(new TypeToDescriptor()); + if(this.isBinaryExp) { + getVlaue(typeOfLiteral); + }else { + doAssign(typeOfLiteral, value); + } + + + } + + private void getVlaue(String typeOfLiteral) { + switch (typeOfLiteral) { case "java/lang/String": - mv.visitLdcInsn(value); + break; + case "java/lang/Boolean": + break; + case "java/lang/Byte": + mv.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/Byte", "valueOf", + "(B)Ljava/lang/Byte;", false); + break; + case "java/lang/Short": + mv.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/Short", "valueOf", + "(S)Ljava/lang/Short;", false); + break; + case "java/lang/Integer": + mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Integer", "intValue", + "()I", false); + break; + case "java/lang/Long": + mv.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/Long", "valueOf", + "(J)Ljava/lang/Long;", false); + break; + case "java/lang/Float": + break; + case "java/lang/Double": + break; + case "java/lang/Character": + break; + default: + break; + } + } + + private void doAssign(String type, Object value) { + switch (type) { + case "java/lang/String": + mv.visitLdcInsn(String.valueOf(value)); break; case "java/lang/Boolean": visitBooleanLiteral((Boolean) value); @@ -479,8 +515,41 @@ public class BytecodeGenMethod implements StatementVisitor{ } } + private void doAssign(String type) { + switch (type) { + case "java/lang/String": + break; + case "java/lang/Boolean": + break; + case "java/lang/Byte": + mv.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/Byte", "valueOf", + "(B)Ljava/lang/Byte;", false); + break; + case "java/lang/Short": + mv.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/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 "java/lang/Long": + mv.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/Long", "valueOf", + "(J)Ljava/lang/Long;", false); + break; + case "java/lang/Float": + break; + case "java/lang/Double": + break; + case "java/lang/Character": + break; + default: + break; + } + } + private void visitCharLiteral(Character value) { - mv.visitIntInsn(Opcodes.BIPUSH, Character.getNumericValue(value.charValue())); + mv.visitIntInsn(Opcodes.BIPUSH, (int) value); mv.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/Character", "valueOf", "(C)Ljava/lang/Character;", false); } diff --git a/test/bytecode/AssignToLit.jav b/test/bytecode/AssignToLit.jav index 46ec2b91..873828ed 100644 --- a/test/bytecode/AssignToLit.jav +++ b/test/bytecode/AssignToLit.jav @@ -10,21 +10,21 @@ import java.lang.Character; class AssignToLit { void m(){ - String s = "Test"; - Boolean b = false; - Byte byte1 = 5; - Byte byte2 = 55; - Short short1 = 5; - Short short2 = 55; - Integer int1 = 5; - Integer int2 = 8888888; - Long long1 = 1; - Long long2 = 5; - Long long3 = 89989898; - Float float1 = 1; - Float float2 = 55; - Double d1 = 1; - Double d2 = 55; +// String s = "Test"; +// Boolean b = false; +// Byte byte1 = 5; +// Byte byte2 = 55; +// Short short1 = 5; +// Short short2 = 55; +// Integer int1 = 5; +// Integer int2 = 8888888; +// Long long1 = 1; +// Long long2 = 5; +// Long long3 = 89989898; +// Float float1 = 1; +// Float float2 = 55; +// Double d1 = 1; +// Double d2 = 55; Character c = 'A'; } } \ No newline at end of file diff --git a/test/bytecode/For.jav b/test/bytecode/For.jav index 04cb6a53..c4bd6677 100644 --- a/test/bytecode/For.jav +++ b/test/bytecode/For.jav @@ -2,19 +2,19 @@ import java.lang.Integer; import java.lang.Boolean; class For{ - m(Integer x){ - - Boolean b = true; - c = 5; - c++; - ++c; - c--; - --c; - while(x<2){ - x = x +1; - b = false; - } - return x; + Integer m(Integer x){ + var c = x + 2; +// Boolean b = true; +// c = 5; +// c++; +// ++c; +// c--; +// --c; +// while(x<2){ +// x = x +1; +// b = false; +// } + return c; // for(int i = 0;i<10;i++) { // x = x + 5; // } diff --git a/test/bytecode/Op.jav b/test/bytecode/Op.jav new file mode 100644 index 00000000..9c05b0a2 --- /dev/null +++ b/test/bytecode/Op.jav @@ -0,0 +1,12 @@ +import java.lang.Integer; + +class Op { + m(Integer a, Integer b) { + Integer c = a+b; +// d = a-b; +// e = a*b; +// f = a/b; + + return c; + } +} \ No newline at end of file diff --git a/test/bytecode/OpTest.java b/test/bytecode/OpTest.java new file mode 100644 index 00000000..cd8fee06 --- /dev/null +++ b/test/bytecode/OpTest.java @@ -0,0 +1,7 @@ +package bytecode; + +public class OpTest extends JavaTXCompilerTest { + public OpTest() { + this.fileName = "Op"; + } +} diff --git a/test/parser/OpratorTest.jav b/test/parser/OpratorTest.jav index f99734f6..2764adf4 100644 --- a/test/parser/OpratorTest.jav +++ b/test/parser/OpratorTest.jav @@ -3,9 +3,9 @@ import java.lang.Integer; class OpratorTest { m(Integer a, Integer b) { c = a+b; - d = a-b; - e = a*b; - f = a/b; +// d = a-b; +// e = a*b; +// f = a/b; return c; } From 59569380ed60d0f5ea5da2363a4e417c3ac57455 Mon Sep 17 00:00:00 2001 From: Fayez Abu Alia Date: Fri, 23 Feb 2018 20:17:32 +0100 Subject: [PATCH 20/24] Kleiner Bug beseitigt --- .../parser/SyntaxTreeGenerator/StatementGenerator.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/de/dhbwstuttgart/parser/SyntaxTreeGenerator/StatementGenerator.java b/src/de/dhbwstuttgart/parser/SyntaxTreeGenerator/StatementGenerator.java index 2b0b1a4f..5310d13b 100644 --- a/src/de/dhbwstuttgart/parser/SyntaxTreeGenerator/StatementGenerator.java +++ b/src/de/dhbwstuttgart/parser/SyntaxTreeGenerator/StatementGenerator.java @@ -825,7 +825,9 @@ public class StatementGenerator { }else if(literal.CharacterLiteral() != null){ RefType type = new RefType(reg.getName("java.lang.Character"),literal.getStart()); return new Literal(type, - literal.CharacterLiteral().getText().charAt(0), + // das gibt immer ' zurück, der Char befindet sich in Position 1 + //literal.CharacterLiteral().getText().charAt(0), + literal.CharacterLiteral().getText().charAt(1), literal.getStart()); }else if(literal.StringLiteral()!=null){ RefType type = new RefType(reg.getName("java.lang.String"),literal.getStart()); From 92b110a971b2566417e8e322533d2f2ebe27f5f9 Mon Sep 17 00:00:00 2001 From: JanUlrich Date: Tue, 27 Feb 2018 19:10:16 +0100 Subject: [PATCH 21/24] Funktionierender Clingo Test --- .../sat/asp/ASPStringConverter.java | 17 ++ src/de/dhbwstuttgart/sat/asp/Clingo.java | 8 +- .../dhbwstuttgart/sat/asp/model/ASPRule.java | 4 +- .../sat/asp/parser/ASPParser.java | 186 +++++++++++++++++- .../asp/parser/model/ParsedASPStatement.java | 7 - .../sat/asp/parser/model/ParsedType.java | 12 ++ .../sat/asp/writer/ASPGenerator.java | 20 +- .../asp/writer/model/ASPParameterList.java | 4 +- .../sat/asp/writer/model/ASPTypeVar.java | 4 +- .../typeinference/result/PairTPHEqualTPH.java | 2 +- .../PairTPHequalRefTypeOrWildcardType.java | 2 +- .../result/PairTPHsmallerTPH.java | 2 +- .../typeinference/result/ResultPair.java | 2 +- .../result/ResultPairVisitor.java | 7 + .../result/ResultSetVisitor.java | 5 +- test/asp/ClingoTest.java | 17 +- test/asp/UnifyWithoutWildcards.java | 29 +++ 17 files changed, 279 insertions(+), 49 deletions(-) create mode 100644 src/de/dhbwstuttgart/sat/asp/ASPStringConverter.java delete mode 100644 src/de/dhbwstuttgart/sat/asp/parser/model/ParsedASPStatement.java create mode 100644 src/de/dhbwstuttgart/sat/asp/parser/model/ParsedType.java create mode 100644 src/de/dhbwstuttgart/typeinference/result/ResultPairVisitor.java create mode 100644 test/asp/UnifyWithoutWildcards.java diff --git a/src/de/dhbwstuttgart/sat/asp/ASPStringConverter.java b/src/de/dhbwstuttgart/sat/asp/ASPStringConverter.java new file mode 100644 index 00000000..0497b09a --- /dev/null +++ b/src/de/dhbwstuttgart/sat/asp/ASPStringConverter.java @@ -0,0 +1,17 @@ +package de.dhbwstuttgart.sat.asp; + +import de.dhbwstuttgart.parser.scope.JavaClassName; + +public class ASPStringConverter { + public static String toConstant(JavaClassName name){ + return toConstant(name.toString().replace(".", "_")); + } + + public static String toConstant(String name){ + return "c" + name.toString().replace(".", "_"); + } + + public static String fromConstant(String s){ + return s.replace("_", ".").substring(1); + } +} diff --git a/src/de/dhbwstuttgart/sat/asp/Clingo.java b/src/de/dhbwstuttgart/sat/asp/Clingo.java index 85f6dc56..ed1e9f40 100644 --- a/src/de/dhbwstuttgart/sat/asp/Clingo.java +++ b/src/de/dhbwstuttgart/sat/asp/Clingo.java @@ -17,16 +17,20 @@ public class Clingo { private static final List programFiles = new ArrayList<>(); static{ programFiles.add(new File("/home/janulrich/Sync/HiwiJob/ResearchPapers/MasterarbeitStadelmeier/asp/unifyWithoutWildcards/basis.lp")); + programFiles.add(new File("/home/janulrich/Sync/HiwiJob/ResearchPapers/MasterarbeitStadelmeier/asp/unifyWithoutWildcards/finiteclosure.lp")); programFiles.add(new File("/home/janulrich/Sync/HiwiJob/ResearchPapers/MasterarbeitStadelmeier/asp/unifyWithoutWildcards/subst.lp")); - programFiles.add(new File("/home/janulrich/Sync/HiwiJob/ResearchPapers/MasterarbeitStadelmeier/asp/unifyWithoutWildcards/reduce1.lp")); - programFiles.add(new File("/home/janulrich/Sync/HiwiJob/ResearchPapers/MasterarbeitStadelmeier/asp/unifyWithoutWildcards/reduce2.lp")); + programFiles.add(new File("/home/janulrich/Sync/HiwiJob/ResearchPapers/MasterarbeitStadelmeier/asp/unifyWithoutWildcards/reduce.lp")); programFiles.add(new File("/home/janulrich/Sync/HiwiJob/ResearchPapers/MasterarbeitStadelmeier/asp/unifyWithoutWildcards/unify.lp")); + programFiles.add(new File("/home/janulrich/Sync/HiwiJob/ResearchPapers/MasterarbeitStadelmeier/asp/unifyWithoutWildcards/adapt.lp")); } public Clingo(List inputFiles){ this.input = inputFiles; } + /* + TODO: Clingo per Java Wrapper https://stackoverflow.com/questions/3356200/using-java-to-wrap-over-c + */ public String runClingo() throws IOException, InterruptedException { String pathToClingo = "/home/janulrich/Sync/HiwiJob/ResearchPapers/MasterarbeitStadelmeier/asp/clingo-5.2.1-linux-x86_64/clingo"; diff --git a/src/de/dhbwstuttgart/sat/asp/model/ASPRule.java b/src/de/dhbwstuttgart/sat/asp/model/ASPRule.java index 8d4d73f9..24ed9269 100644 --- a/src/de/dhbwstuttgart/sat/asp/model/ASPRule.java +++ b/src/de/dhbwstuttgart/sat/asp/model/ASPRule.java @@ -9,8 +9,8 @@ public enum ASPRule { ASP_PARAMLISTNUMERATION_NAME("paramNum"), ASP_PARAMLIST_END_POINTER("null"), ASP_TYPE("type"), - ASP_FCTYPE("type") - ; + ASP_FCTYPE("typeFC"), + ASP_TYPE_VAR("typeVar"); private final String text; diff --git a/src/de/dhbwstuttgart/sat/asp/parser/ASPParser.java b/src/de/dhbwstuttgart/sat/asp/parser/ASPParser.java index c7be7dbc..b3534f47 100644 --- a/src/de/dhbwstuttgart/sat/asp/parser/ASPParser.java +++ b/src/de/dhbwstuttgart/sat/asp/parser/ASPParser.java @@ -1,17 +1,187 @@ package de.dhbwstuttgart.sat.asp.parser; -import de.dhbwstuttgart.typeinference.result.ResultPair; -import de.dhbwstuttgart.typeinference.result.ResultSet; +import de.dhbwstuttgart.exceptions.DebugException; +import de.dhbwstuttgart.parser.NullToken; +import de.dhbwstuttgart.parser.scope.JavaClassName; +import de.dhbwstuttgart.sat.asp.ASPStringConverter; +import de.dhbwstuttgart.sat.asp.model.ASPRule; +import de.dhbwstuttgart.sat.asp.parser.model.ParsedType; +import de.dhbwstuttgart.sat.asp.writer.ASPGenerator; +import de.dhbwstuttgart.sat.asp.writer.model.ASPParameterList; +import de.dhbwstuttgart.sat.asp.writer.model.ASPRefType; +import de.dhbwstuttgart.sat.asp.writer.model.ASPType; +import de.dhbwstuttgart.syntaxtree.type.*; +import de.dhbwstuttgart.typeinference.result.*; -import java.util.HashSet; -import java.util.Set; +import javax.json.Json; +import javax.json.JsonArray; +import javax.json.JsonObject; +import java.io.StringReader; +import java.util.*; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +/** + * Ablauf: + * - Erst werden alle benötigten Statements eingelesen. Die Pointer bleiben als Strings erhalten + * - Anschließend müssen diese wieder zu einem Unify Ergebnis zurückgewandelt werden + * - Hier nicht die Typen aus dem unify.model packages verwenden. + * TODO: Ãœberlegen welche Informationen noch nach der Unifizierung gebraucht werden + * -> Eigentlich nur die korrekten Namen der Typen und TPHs + */ public class ASPParser { - ResultSet parse(String result){ - Set ret = new HashSet<>(); - for(String pair : result.split(",")){ + private final Collection originalTPHs; + private ResultSet resultSet; + private Map types = new HashMap<>(); + private Set tphs = new HashSet<>(); + private Map parameterLists = new HashMap<>(); + /** + * Parst clingo output welcher als JSON (option --outf=2) ausgibt + * @param toParse + * @return + */ + public static ResultSet parse(String toParse, Collection oldPlaceholders){ + return new ASPParser(toParse, oldPlaceholders).resultSet; + } + + + private ASPParser(String toParse, Collection oldPlaceholders){ + this.originalTPHs = oldPlaceholders; + JsonObject jsonResult = Json.createReader(new StringReader(toParse)).readObject(); + JsonArray results = jsonResult.getJsonArray("Call").getJsonObject(0). + getJsonArray("Witnesses").getJsonObject(0). + getJsonArray("Value"); + + /* + Diese Funktion läuft im folgenden mehrmals über das Result aus dem ASP Programm. + Dabei werden Schritt für Schritt die Felder dieser Klasse befüllt die am Schluss das ResultSet ergeben + */ + Set ret = new HashSet<>(); + //Zuerst die params und typeVars: + for(int i = 0; i params = new ArrayList<>(); + ParsedType t = types.get(name); + for(String param : t.params){ + params.add(this.getType(param)); + } + return new RefType(new JavaClassName(ASPStringConverter.fromConstant(t.name)), params, new NullToken()); + }else throw new DebugException("Der Typ " + name + " konnte nicht bestimmt werden"); + } + + private static class ParameterListNode{ + final String type; + final String nextNode; + + public ParameterListNode(String type, String next) { + this.type = type; + this.nextNode = next; + } + } + private void parseParameter(String statement){ + Pattern p = Pattern.compile(ASPRule.ASP_PARAMLIST_NAME+"\\(([^,]+),([^,]+),([^,]+)\\)"); + Matcher m = p.matcher(statement); + boolean b = m.matches(); + if(b){ + if(m.groupCount()<3)throw new DebugException("Fehler in Regex"); + String pointer = m.group(1); + String type = m.group(2); + String next = m.group(2); + if(next.equals(ASPRule.ASP_PARAMLIST_END_POINTER.toString()))next = null; + if(this.parameterLists.containsKey(pointer)){ + throw new DebugException("Fehler in Ergebnisparsen"); + } + this.parameterLists.put(pointer,new ParameterListNode(type, next)); + } + } + + private void parseTypeVar(String statement){ + Pattern p = Pattern.compile(ASPRule.ASP_TYPE_VAR+"\\(([^,]+)\\)"); + Matcher m = p.matcher(statement); + boolean b = m.matches(); + if(b){ + if(m.groupCount()<1)throw new DebugException("Fehler in Regex"); + String name = m.group(1); + this.tphs.add(name); + } + } + + private void parseType(String statement){ + Pattern p = Pattern.compile(ASPRule.ASP_TYPE+"\\(([^,]+),([^,]+)\\)"); + Matcher m = p.matcher(statement); + boolean b = m.matches(); + if(b){ + if(m.groupCount()<2)throw new DebugException("Fehler in Regex"); + String ls = m.group(1); + String rs = m.group(2); + List params = this.getParams(rs); + this.types.put(ls,new ParsedType(ls, params)); + } + } + + private List getParams(String pointer) { + List params = new ArrayList<>(); + if(pointer.equals(ASPRule.ASP_PARAMLIST_END_POINTER.toString()))return params; + while(pointer != null){ + if(!parameterLists.containsKey(pointer)) + throw new DebugException("Fehler in Ergebnisparsen"); + ParameterListNode param = parameterLists.get(pointer); + pointer = param.nextNode; + params.add(param.type); + } + return params; + //Optional ret = parameterLists.stream().filter(aspParameterList -> aspParameterList.name.equals(rs)).findAny(); + //return ret.get(); } } \ No newline at end of file diff --git a/src/de/dhbwstuttgart/sat/asp/parser/model/ParsedASPStatement.java b/src/de/dhbwstuttgart/sat/asp/parser/model/ParsedASPStatement.java deleted file mode 100644 index 614bddb0..00000000 --- a/src/de/dhbwstuttgart/sat/asp/parser/model/ParsedASPStatement.java +++ /dev/null @@ -1,7 +0,0 @@ -package de.dhbwstuttgart.sat.asp.parser.model; - -public class ParsedASPStatement { - public ParsedASPStatement(String statement){ - - } -} diff --git a/src/de/dhbwstuttgart/sat/asp/parser/model/ParsedType.java b/src/de/dhbwstuttgart/sat/asp/parser/model/ParsedType.java new file mode 100644 index 00000000..c49ce831 --- /dev/null +++ b/src/de/dhbwstuttgart/sat/asp/parser/model/ParsedType.java @@ -0,0 +1,12 @@ +package de.dhbwstuttgart.sat.asp.parser.model; + +import java.util.List; + +public class ParsedType { + public final String name; + public final List params; + public ParsedType(String name, List params){ + this.name = name; + this.params = params; + } +} diff --git a/src/de/dhbwstuttgart/sat/asp/writer/ASPGenerator.java b/src/de/dhbwstuttgart/sat/asp/writer/ASPGenerator.java index 38652b43..b1483423 100644 --- a/src/de/dhbwstuttgart/sat/asp/writer/ASPGenerator.java +++ b/src/de/dhbwstuttgart/sat/asp/writer/ASPGenerator.java @@ -3,6 +3,7 @@ package de.dhbwstuttgart.sat.asp.writer; import de.dhbwstuttgart.exceptions.NotImplementedException; import de.dhbwstuttgart.parser.SyntaxTreeGenerator.FCGenerator; import de.dhbwstuttgart.parser.scope.JavaClassName; +import de.dhbwstuttgart.sat.asp.ASPStringConverter; import de.dhbwstuttgart.sat.asp.writer.model.*; import de.dhbwstuttgart.syntaxtree.ClassOrInterface; import de.dhbwstuttgart.syntaxtree.GenericTypeVar; @@ -24,7 +25,6 @@ public class ASPGenerator { List> constraints1 = constraints.cartesianProduct().iterator().next(); List constraintPairs = new ArrayList<>(); for(Constraint constraint : constraints1){ - System.out.println(UnifyTypeFactory.convert(constraint)); constraintPairs.addAll(constraint); } asp = toASP(constraintPairs, FCGenerator.toFC(fcClasses)); @@ -65,18 +65,10 @@ public class ASPGenerator { private ASPRefType convert(ClassOrInterface cl){ List paramList = new ArrayList<>(); for(GenericTypeVar gtv : cl.getGenerics()){ - paramList.add(new ASPGenericType(toConstant(gtv.getName()))); + paramList.add(new ASPGenericType(ASPStringConverter.toConstant(gtv.getName()))); } ASPParameterList params = new ASPParameterList(paramList, writer); - return new ASPRefType(toConstant(cl.getClassName()), params); - } - - public static String toConstant(JavaClassName name){ - return toConstant(name.toString().replace(".", "_")); - } - - public static String toConstant(String name){ - return "c" + name.toString().replace(".", "_"); + return new ASPRefType(ASPStringConverter.toConstant(cl.getClassName()), params); } private class TypeConverter implements TypeVisitor{ @@ -88,7 +80,7 @@ public class ASPGenerator { paramList.add(gtv.acceptTV(this)); } ASPParameterList params = new ASPParameterList(paramList, writer); - return new ASPRefType(toConstant(type.getName()), params); + return new ASPRefType(ASPStringConverter.toConstant(type.getName()), params); } @Override @@ -98,7 +90,7 @@ public class ASPGenerator { @Override public ASPType visit(TypePlaceholder typePlaceholder) { - return new ASPTypeVar(toConstant(typePlaceholder.getName())); + return new ASPTypeVar(ASPStringConverter.toConstant(typePlaceholder.getName())); } @Override @@ -108,7 +100,7 @@ public class ASPGenerator { @Override public ASPType visit(GenericRefType genericRefType) { - return new ASPRefType(toConstant(genericRefType.getName()), + return new ASPRefType(ASPStringConverter.toConstant(genericRefType.getName()), new ASPParameterList(new ArrayList<>(), writer)); } } diff --git a/src/de/dhbwstuttgart/sat/asp/writer/model/ASPParameterList.java b/src/de/dhbwstuttgart/sat/asp/writer/model/ASPParameterList.java index 3c176e49..178bb8fa 100644 --- a/src/de/dhbwstuttgart/sat/asp/writer/model/ASPParameterList.java +++ b/src/de/dhbwstuttgart/sat/asp/writer/model/ASPParameterList.java @@ -1,5 +1,6 @@ package de.dhbwstuttgart.sat.asp.writer.model; +import de.dhbwstuttgart.sat.asp.ASPStringConverter; import de.dhbwstuttgart.sat.asp.model.ASPRule; import de.dhbwstuttgart.sat.asp.writer.ASPGenerator; import de.dhbwstuttgart.sat.asp.writer.ASPWriter; @@ -30,13 +31,12 @@ public class ASPParameterList { writer.add(new ASPStatement(ASPRule.ASP_PARAMLIST_NAME + "(" + param + ")")); writer.add(new ASPStatement(ASPRule.ASP_PARAMLISTNUMERATION_NAME + "(" + name + "," +t + "," + paramNum + ")")); paramNum++; - //paramDefinitions.add(new ASPStatement(ASP_PARAMLIST_NAME + "(" + param + ")")); } } } private String newName() { - return ASPGenerator.toConstant(NameGenerator.makeNewName()); + return ASPStringConverter.toConstant(NameGenerator.makeNewName()); } public String toString(){ diff --git a/src/de/dhbwstuttgart/sat/asp/writer/model/ASPTypeVar.java b/src/de/dhbwstuttgart/sat/asp/writer/model/ASPTypeVar.java index 8b3c1af6..24b33eaf 100644 --- a/src/de/dhbwstuttgart/sat/asp/writer/model/ASPTypeVar.java +++ b/src/de/dhbwstuttgart/sat/asp/writer/model/ASPTypeVar.java @@ -1,5 +1,7 @@ package de.dhbwstuttgart.sat.asp.writer.model; +import de.dhbwstuttgart.sat.asp.model.ASPRule; + public class ASPTypeVar implements ASPType{ private final String name; @@ -9,7 +11,7 @@ public class ASPTypeVar implements ASPType{ @Override public String toString() { - return "typeVar("+ name +")"; + return ASPRule.ASP_TYPE_VAR+"("+ name +")"; } @Override diff --git a/src/de/dhbwstuttgart/typeinference/result/PairTPHEqualTPH.java b/src/de/dhbwstuttgart/typeinference/result/PairTPHEqualTPH.java index 64d0ce0b..c24fe211 100644 --- a/src/de/dhbwstuttgart/typeinference/result/PairTPHEqualTPH.java +++ b/src/de/dhbwstuttgart/typeinference/result/PairTPHEqualTPH.java @@ -9,7 +9,7 @@ public class PairTPHEqualTPH extends ResultPair getFC() { Set ret = new HashSet<>(); - ret.add(ASTFactory.createObjectClass()); - ret.add(ASTFactory.createClass(java.util.List.class)); return ret; } public ConstraintSet getPairs() { ConstraintSet ret = new ConstraintSet<>(); - ret.addUndConstraint(new Pair(TypePlaceholder.fresh(new NullToken()), ASTFactory.createObjectType(), PairOperator.SMALLERDOT)); + ret.addUndConstraint(new Pair(testType, ASTFactory.createObjectType(), PairOperator.EQUALSDOT)); return ret; } } diff --git a/test/asp/UnifyWithoutWildcards.java b/test/asp/UnifyWithoutWildcards.java new file mode 100644 index 00000000..9e7c867d --- /dev/null +++ b/test/asp/UnifyWithoutWildcards.java @@ -0,0 +1,29 @@ +package asp; + +import de.dhbwstuttgart.parser.NullToken; +import de.dhbwstuttgart.syntaxtree.ClassOrInterface; +import de.dhbwstuttgart.syntaxtree.factory.ASTFactory; +import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder; +import de.dhbwstuttgart.typeinference.constraints.ConstraintSet; +import de.dhbwstuttgart.typeinference.constraints.Pair; +import de.dhbwstuttgart.typeinference.unify.model.PairOperator; + +import java.util.Collection; +import java.util.HashSet; +import java.util.Set; + +public class UnifyWithoutWildcards { + + public Collection getFC() { + Set ret = new HashSet<>(); + ret.add(ASTFactory.createObjectClass()); + ret.add(ASTFactory.createClass(java.util.List.class)); + return ret; + } + + public ConstraintSet getPairs() { + ConstraintSet ret = new ConstraintSet<>(); + ret.addUndConstraint(new Pair(TypePlaceholder.fresh(new NullToken()), ASTFactory.createObjectType(), PairOperator.SMALLERDOT)); + return ret; + } +} From 9f9a94b5cfb6ed8712ab241ccd9a8cd963653b05 Mon Sep 17 00:00:00 2001 From: JanUlrich Date: Wed, 28 Feb 2018 13:22:07 +0100 Subject: [PATCH 22/24] =?UTF-8?q?Testf=C3=A4lle=20bereinigen?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../syntaxtree/factory/UnifyTypeFactory.java | 5 +- test/javFiles/Expressions.jav | 8 +++ test/typeinference/FacultyTest.java | 9 --- test/typeinference/FiniteClosureTest.java | 9 --- test/typeinference/GenericsTest.java | 10 --- test/typeinference/JavaTXCompilerTest.java | 62 ++++++++++++++++--- test/typeinference/Lambda2Test.java | 9 --- test/typeinference/Lambda3Test.java | 9 --- test/typeinference/LambdaTest.java | 9 --- test/typeinference/MatrixTest.java | 9 --- test/typeinference/RunnableTest.java | 9 --- test/typeinference/VectorTest.java | 9 --- test/typeinference/mathStrucTest.java | 9 --- 13 files changed, 64 insertions(+), 102 deletions(-) create mode 100644 test/javFiles/Expressions.jav delete mode 100644 test/typeinference/FacultyTest.java delete mode 100644 test/typeinference/FiniteClosureTest.java delete mode 100644 test/typeinference/GenericsTest.java delete mode 100644 test/typeinference/Lambda2Test.java delete mode 100644 test/typeinference/Lambda3Test.java delete mode 100644 test/typeinference/LambdaTest.java delete mode 100644 test/typeinference/MatrixTest.java delete mode 100644 test/typeinference/RunnableTest.java delete mode 100644 test/typeinference/VectorTest.java delete mode 100644 test/typeinference/mathStrucTest.java diff --git a/src/de/dhbwstuttgart/syntaxtree/factory/UnifyTypeFactory.java b/src/de/dhbwstuttgart/syntaxtree/factory/UnifyTypeFactory.java index 4ecaa136..43fcf1b4 100644 --- a/src/de/dhbwstuttgart/syntaxtree/factory/UnifyTypeFactory.java +++ b/src/de/dhbwstuttgart/syntaxtree/factory/UnifyTypeFactory.java @@ -127,10 +127,13 @@ public class UnifyTypeFactory { UnifyPair ret = generateSmallerDotPair(UnifyTypeFactory.convert(p.TA1) , UnifyTypeFactory.convert(p.TA2)); return ret; - }else if(p.GetOperator().equals(PairOperator.EQUALSDOT)){ + }else if(p.GetOperator().equals(PairOperator.EQUALSDOT)) { UnifyPair ret = generateEqualDotPair(UnifyTypeFactory.convert(p.TA1) , UnifyTypeFactory.convert(p.TA2)); return ret; + }else if(p.GetOperator().equals(PairOperator.SMALLER)){ + return generateSmallerPair(UnifyTypeFactory.convert(p.TA1), + UnifyTypeFactory.convert(p.TA2)); }else throw new NotImplementedException(); } diff --git a/test/javFiles/Expressions.jav b/test/javFiles/Expressions.jav new file mode 100644 index 00000000..e2e992a1 --- /dev/null +++ b/test/javFiles/Expressions.jav @@ -0,0 +1,8 @@ +class Expressions{ + +void test(){ + var x = 2; + x = x + 2; +} + +} \ No newline at end of file diff --git a/test/typeinference/FacultyTest.java b/test/typeinference/FacultyTest.java deleted file mode 100644 index aadaf6e7..00000000 --- a/test/typeinference/FacultyTest.java +++ /dev/null @@ -1,9 +0,0 @@ -package typeinference; - -import java.io.File; - -public class FacultyTest extends JavaTXCompilerTest{ - public FacultyTest() { - this.fileToTest = new File(rootDirectory+"Faculty.jav"); - } -} \ No newline at end of file diff --git a/test/typeinference/FiniteClosureTest.java b/test/typeinference/FiniteClosureTest.java deleted file mode 100644 index 8b62e4e5..00000000 --- a/test/typeinference/FiniteClosureTest.java +++ /dev/null @@ -1,9 +0,0 @@ -package typeinference; - -import java.io.File; - -public class FiniteClosureTest extends JavaTXCompilerTest{ - public FiniteClosureTest() { -// this.fileToTest = new File(rootDirectory+"fc.jav"); - } -} \ No newline at end of file diff --git a/test/typeinference/GenericsTest.java b/test/typeinference/GenericsTest.java deleted file mode 100644 index abcef013..00000000 --- a/test/typeinference/GenericsTest.java +++ /dev/null @@ -1,10 +0,0 @@ -package typeinference; - -import java.io.File; - -//TODO: Hier gibt es einen Fehler. Das erstellte ConstraintSet stimmt nicht -public class GenericsTest extends JavaTXCompilerTest{ - public GenericsTest() { - this.fileToTest = new File(rootDirectory+"Generics.jav"); - } -} \ No newline at end of file diff --git a/test/typeinference/JavaTXCompilerTest.java b/test/typeinference/JavaTXCompilerTest.java index 03452018..3fe7c17d 100644 --- a/test/typeinference/JavaTXCompilerTest.java +++ b/test/typeinference/JavaTXCompilerTest.java @@ -23,19 +23,57 @@ import java.util.Set; public class JavaTXCompilerTest { public static final String rootDirectory = System.getProperty("user.dir")+"/test/javFiles/"; - private static final List filesToTest = new ArrayList<>(); - protected File fileToTest = null; - public JavaTXCompilerTest(){ + @Test + public void finiteClosure() throws IOException, ClassNotFoundException { + execute(new File(rootDirectory+"fc.jav")); } @Test - public void test() throws IOException, ClassNotFoundException { - if(fileToTest != null)filesToTest.add(fileToTest); - else return; - //filesToTest.add(new File(rootDirectory+"Faculty.jav")); - //filesToTest.add(new File(rootDirectory+"mathStruc.jav")); - //filesToTest.add(new File(rootDirectory+"test.jav")); - filesToTest.add(new File(rootDirectory+"EmptyMethod.jav")); + public void lambda() throws IOException, ClassNotFoundException { + execute(new File(rootDirectory+"Lambda.jav")); + } + @Test + public void lambda2() throws IOException, ClassNotFoundException { + execute(new File(rootDirectory+"Lambda2.jav")); + } + @Test + public void lambda3() throws IOException, ClassNotFoundException { + execute(new File(rootDirectory+"Lambda3.jav")); + } + @Test + public void mathStruc() throws IOException, ClassNotFoundException { + execute(new File(rootDirectory+"mathStruc.jav")); + } + @Test + public void generics() throws IOException, ClassNotFoundException { + execute(new File(rootDirectory+"Generics.jav")); + } + @Test + public void faculty() throws IOException, ClassNotFoundException { + execute(new File(rootDirectory+"Faculty.jav")); + } + @Test + public void matrix() throws IOException, ClassNotFoundException { + execute(new File(rootDirectory+"Matrix.jav")); + } + @Test + public void vector() throws IOException, ClassNotFoundException { + execute(new File(rootDirectory+"Vector.jav")); + } + @Test + public void lambdaRunnable() throws IOException, ClassNotFoundException { + execute(new File(rootDirectory+"LambdaRunnable.jav")); + } + @Test + public void expressions() throws IOException, ClassNotFoundException { + execute(new File(rootDirectory+"Expressions.jav")); + } + + private static class TestResultSet{ + + } + + public TestResultSet execute(File fileToTest) throws IOException, ClassNotFoundException { //filesToTest.add(new File(rootDirectory+"fc.jav")); //filesToTest.add(new File(rootDirectory+"Lambda.jav")); //filesToTest.add(new File(rootDirectory+"Lambda2.jav")); @@ -45,6 +83,9 @@ public class JavaTXCompilerTest { //filesToTest.add(new File(rootDirectory+"MethodsEasy.jav")); //filesToTest.add(new File(rootDirectory+"Matrix.jav")); //filesToTest.add(new File(rootDirectory+"Import.jav")); + // //filesToTest.add(new File(rootDirectory+"Faculty.jav")); + // //filesToTest.add(new File(rootDirectory+"mathStruc.jav")); + // //filesToTest.add(new File(rootDirectory+"test.jav")); JavaTXCompiler compiler = new JavaTXCompiler(fileToTest); List results = compiler.typeInference(); @@ -68,6 +109,7 @@ public class JavaTXCompilerTest { System.out.println(s); } } + return new TestResultSet(); } static String readFile(String path, Charset encoding) diff --git a/test/typeinference/Lambda2Test.java b/test/typeinference/Lambda2Test.java deleted file mode 100644 index 84867cd9..00000000 --- a/test/typeinference/Lambda2Test.java +++ /dev/null @@ -1,9 +0,0 @@ -package typeinference; - -import java.io.File; - -public class Lambda2Test extends JavaTXCompilerTest{ - public Lambda2Test() { - this.fileToTest = new File(rootDirectory+"Lambda2.jav"); - } -} \ No newline at end of file diff --git a/test/typeinference/Lambda3Test.java b/test/typeinference/Lambda3Test.java deleted file mode 100644 index 843eee10..00000000 --- a/test/typeinference/Lambda3Test.java +++ /dev/null @@ -1,9 +0,0 @@ -package typeinference; - -import java.io.File; - -public class Lambda3Test extends JavaTXCompilerTest{ - public Lambda3Test() { - this.fileToTest = new File(rootDirectory+"Lambda3.jav"); - } -} \ No newline at end of file diff --git a/test/typeinference/LambdaTest.java b/test/typeinference/LambdaTest.java deleted file mode 100644 index abdaa140..00000000 --- a/test/typeinference/LambdaTest.java +++ /dev/null @@ -1,9 +0,0 @@ -package typeinference; - -import java.io.File; - -public class LambdaTest extends JavaTXCompilerTest{ - public LambdaTest() { - this.fileToTest = new File(rootDirectory+"Lambda.jav"); - } -} \ No newline at end of file diff --git a/test/typeinference/MatrixTest.java b/test/typeinference/MatrixTest.java deleted file mode 100644 index 8cc587c9..00000000 --- a/test/typeinference/MatrixTest.java +++ /dev/null @@ -1,9 +0,0 @@ -package typeinference; - -import java.io.File; - -public class MatrixTest extends JavaTXCompilerTest{ - public MatrixTest() { - this.fileToTest = new File(rootDirectory+"Matrix.jav"); - } -} \ No newline at end of file diff --git a/test/typeinference/RunnableTest.java b/test/typeinference/RunnableTest.java deleted file mode 100644 index bc0c52ad..00000000 --- a/test/typeinference/RunnableTest.java +++ /dev/null @@ -1,9 +0,0 @@ -package typeinference; - -import java.io.File; - -public class RunnableTest extends JavaTXCompilerTest{ - public RunnableTest() { - this.fileToTest = new File(rootDirectory+"LambdaRunnable.jav"); - } -} \ No newline at end of file diff --git a/test/typeinference/VectorTest.java b/test/typeinference/VectorTest.java deleted file mode 100644 index 864535b3..00000000 --- a/test/typeinference/VectorTest.java +++ /dev/null @@ -1,9 +0,0 @@ -package typeinference; - -import java.io.File; - -public class VectorTest extends JavaTXCompilerTest{ - public VectorTest() { - this.fileToTest = new File(rootDirectory+"Vector.jav"); - } -} \ No newline at end of file diff --git a/test/typeinference/mathStrucTest.java b/test/typeinference/mathStrucTest.java deleted file mode 100644 index 0181be72..00000000 --- a/test/typeinference/mathStrucTest.java +++ /dev/null @@ -1,9 +0,0 @@ -package typeinference; - -import java.io.File; - -public class mathStrucTest extends JavaTXCompilerTest{ - public mathStrucTest() { - this.fileToTest = new File(rootDirectory+"mathStruc.jav"); - } -} \ No newline at end of file From f023754328320f0a46a6725b0b14716541757612 Mon Sep 17 00:00:00 2001 From: JanUlrich Date: Wed, 28 Feb 2018 14:50:16 +0100 Subject: [PATCH 23/24] =?UTF-8?q?TypeStmt=20f=C3=BCr=20+,-,/,*,%=20einf?= =?UTF-8?q?=C3=BChren?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../syntaxtree/statement/BinaryExpr.java | 21 +++++----- .../typeinference/typeAlgo/TYPEStmt.java | 41 +++++++++++++++---- 2 files changed, 45 insertions(+), 17 deletions(-) diff --git a/src/de/dhbwstuttgart/syntaxtree/statement/BinaryExpr.java b/src/de/dhbwstuttgart/syntaxtree/statement/BinaryExpr.java index f7db0481..bb631e04 100644 --- a/src/de/dhbwstuttgart/syntaxtree/statement/BinaryExpr.java +++ b/src/de/dhbwstuttgart/syntaxtree/statement/BinaryExpr.java @@ -13,16 +13,17 @@ public class BinaryExpr extends Expression } public enum Operator{ - ADD, - SUB, - MUL, - AND, - OR, - DIV, - LESSTHAN, - BIGGERTHAN, - LESSEQUAL, - BIGGEREQUAL + ADD, // + + SUB, // - + MUL, // * + MOD, // Modulo Operator % + AND, // && + OR, // || + DIV, // / + LESSTHAN, // < + BIGGERTHAN, // > + LESSEQUAL, // <= + BIGGEREQUAL // >= } public final Operator operation; diff --git a/src/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java b/src/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java index 3733b7dc..e6b82a10 100644 --- a/src/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java +++ b/src/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java @@ -81,11 +81,6 @@ public class TYPEStmt implements StatementVisitor{ assign.rightSide.getType(), assign.lefSide.getType(), PairOperator.SMALLERDOT)); } - @Override - public void visit(BinaryExpr binary) { - //TODO - } - @Override public void visit(Block block) { for(Statement stmt : block.getStatements()){ @@ -190,6 +185,8 @@ public class TYPEStmt implements StatementVisitor{ receiver.expr.accept(this); } + private final RefType number = new RefType(ASTFactory.createClass(Number.class).getClassName(), new NullToken()); + private final RefType string = new RefType(ASTFactory.createClass(String.class).getClassName(), new NullToken()); @Override public void visit(UnaryExpr unaryExpr) { if(unaryExpr.operation == UnaryExpr.Operation.POSTDECREMENT || @@ -198,7 +195,6 @@ public class TYPEStmt implements StatementVisitor{ unaryExpr.operation == UnaryExpr.Operation.PREINCREMENT){ //@see: https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.14.2 //Expression muss zu Numeric Convertierbar sein. also von Numeric erben - RefType number = new RefType(ASTFactory.createClass(Number.class).getClassName(), unaryExpr.getOffset()); constraintsSet.addUndConstraint(new Pair(unaryExpr.expr.getType(), number, PairOperator.SMALLERDOT)); //The type of the postfix increment expression is the type of the variable constraintsSet.addUndConstraint(new Pair(unaryExpr.expr.getType(), unaryExpr.getType(), PairOperator.EQUALSDOT)); @@ -207,9 +203,40 @@ public class TYPEStmt implements StatementVisitor{ } } + @Override + public void visit(BinaryExpr binary) { + if(binary.operation.equals(BinaryExpr.Operator.DIV) || + binary.operation.equals(BinaryExpr.Operator.MUL)|| + binary.operation.equals(BinaryExpr.Operator.MOD)|| + binary.operation.equals(BinaryExpr.Operator.ADD)){ + Set numericAdditionOrStringConcatenation = new HashSet<>(); + Constraint numeric = new Constraint<>(); + //Zuerst der Fall für Numerische AusdrücPairOpnumericeratorke, das sind Mul, Mod und Div immer: + //see: https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.17 + //Expression muss zu Numeric Convertierbar sein. also von Numeric erben + numeric.add(new Pair(binary.lexpr.getType(), number, PairOperator.SMALLERDOT)); + numeric.add(new Pair(binary.rexpr.getType(), number, PairOperator.SMALLERDOT)); + //The type of a multiplicative expression is the promoted type of its operands. + numeric.add(new Pair(binary.rexpr.getType(), binary.getType(), PairOperator.SMALLERDOT)); + numeric.add(new Pair(binary.lexpr.getType(), binary.getType(), PairOperator.SMALLERDOT)); + numericAdditionOrStringConcatenation.add(numeric); + if(binary.operation.equals(BinaryExpr.Operator.ADD)) { + //Dann kann der Ausdruck auch das aneinanderfügen zweier Strings sein: ("a" + "b") oder (1 + 2) + Constraint stringConcat = new Constraint<>(); + stringConcat.add(new Pair(binary.lexpr.getType(), string, PairOperator.EQUALSDOT)); + stringConcat.add(new Pair(binary.rexpr.getType(), string, PairOperator.EQUALSDOT)); + stringConcat.add(new Pair(binary.getType(), string, PairOperator.EQUALSDOT)); + numericAdditionOrStringConcatenation.add(stringConcat); + } + constraintsSet.addOderConstraint(numericAdditionOrStringConcatenation); + }else { + throw new NotImplementedException(); + } + } + @Override public void visit(Literal literal) { - //Nothing to do here. Literale kriegen beim parsen den korrekten Typ. + //Nothing to do here. Literale erzeugen keine Constraints } @Override From 327f36f1c2cb345c5ceef23907b1c659d44b9099 Mon Sep 17 00:00:00 2001 From: JanUlrich Date: Wed, 28 Feb 2018 15:21:12 +0100 Subject: [PATCH 24/24] =?UTF-8?q?Faculty=20Test=20=C3=A4ndern.=20UnifyType?= =?UTF-8?q?Factory=20konvertiert=20automatisch=20FunN=20Typen=20korrekt?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../syntaxtree/factory/UnifyTypeFactory.java | 15 +++++++++++++++ test/javFiles/Faculty.jav | 6 +----- test/javFiles/FacultyTyped.jav | 19 +++++++++++++++++++ test/typeinference/JavaTXCompilerTest.java | 4 ++++ 4 files changed, 39 insertions(+), 5 deletions(-) create mode 100644 test/javFiles/FacultyTyped.jav diff --git a/src/de/dhbwstuttgart/syntaxtree/factory/UnifyTypeFactory.java b/src/de/dhbwstuttgart/syntaxtree/factory/UnifyTypeFactory.java index 43fcf1b4..e58ce50f 100644 --- a/src/de/dhbwstuttgart/syntaxtree/factory/UnifyTypeFactory.java +++ b/src/de/dhbwstuttgart/syntaxtree/factory/UnifyTypeFactory.java @@ -1,12 +1,17 @@ package de.dhbwstuttgart.syntaxtree.factory; import java.util.*; +import java.util.regex.Matcher; +import java.util.regex.Pattern; import java.util.stream.Collectors; +import de.dhbwstuttgart.exceptions.DebugException; import de.dhbwstuttgart.exceptions.NotImplementedException; import de.dhbwstuttgart.parser.NullToken; import de.dhbwstuttgart.parser.SyntaxTreeGenerator.FCGenerator; import de.dhbwstuttgart.parser.scope.JavaClassName; +import de.dhbwstuttgart.sat.asp.model.ASPRule; +import de.dhbwstuttgart.sat.asp.parser.ASPParser; import de.dhbwstuttgart.syntaxtree.ClassOrInterface; import de.dhbwstuttgart.syntaxtree.type.*; import de.dhbwstuttgart.syntaxtree.type.Void; @@ -72,6 +77,16 @@ public class UnifyTypeFactory { } public static UnifyType convert(RefType t){ + //Check if it is a FunN Type: + Pattern p = Pattern.compile("Fun(\\d+)"); + Matcher m = p.matcher(t.getName().toString()); + boolean b = m.matches(); + if(b){ + Integer N = Integer.valueOf(m.group(1)); + if((N + 1) == t.getParaList().size()){ + return convert(new FunN(t.getParaList())); + } + } UnifyType ret; if(t.getParaList() != null && t.getParaList().size() > 0){ List params = new ArrayList<>(); diff --git a/test/javFiles/Faculty.jav b/test/javFiles/Faculty.jav index 089d2f33..ca539add 100644 --- a/test/javFiles/Faculty.jav +++ b/test/javFiles/Faculty.jav @@ -6,14 +6,10 @@ class Faculty { return x; } - Fun1 m () { + m () { var fact = (Integer x) -> { return mul(x, fact.apply(x)); }; return fact; } -} - -interface Fun1{ - B apply(A a); } \ No newline at end of file diff --git a/test/javFiles/FacultyTyped.jav b/test/javFiles/FacultyTyped.jav new file mode 100644 index 00000000..089d2f33 --- /dev/null +++ b/test/javFiles/FacultyTyped.jav @@ -0,0 +1,19 @@ +import java.lang.Integer; + +class Faculty { + + Integer mul(Integer x, Integer y) { + return x; + } + + Fun1 m () { + var fact = (Integer x) -> { + return mul(x, fact.apply(x)); + }; + return fact; + } +} + +interface Fun1{ + B apply(A a); +} \ No newline at end of file diff --git a/test/typeinference/JavaTXCompilerTest.java b/test/typeinference/JavaTXCompilerTest.java index 3fe7c17d..bf48a537 100644 --- a/test/typeinference/JavaTXCompilerTest.java +++ b/test/typeinference/JavaTXCompilerTest.java @@ -53,6 +53,10 @@ public class JavaTXCompilerTest { execute(new File(rootDirectory+"Faculty.jav")); } @Test + public void facultyTyped() throws IOException, ClassNotFoundException { + execute(new File(rootDirectory+"FacultyTyped.jav")); + } + @Test public void matrix() throws IOException, ClassNotFoundException { execute(new File(rootDirectory+"Matrix.jav")); }