diff --git a/.gitignore b/.gitignore index d3e21505..07778e4c 100644 --- a/.gitignore +++ b/.gitignore @@ -19,6 +19,7 @@ bin .DS_Store .project .settings/ +.vscode/ /target/ settings.json diff --git a/pom.xml b/pom.xml index ade9b85d..f347874a 100644 --- a/pom.xml +++ b/pom.xml @@ -51,13 +51,28 @@ http://maven.apache.org/maven-v4_0_0.xsd"> org.apache.maven.plugins maven-compiler-plugin - 3.8.0 + 3.11.0 --enable-preview +<<<<<<< HEAD 20 20 +======= + 20 +>>>>>>> patternMatching + + org.apache.maven.plugins + maven-surefire-plugin + 3.1.0 + + --enable-preview + + **/JavaTXCompilerTest.java + + + org.antlr antlr4-maven-plugin @@ -112,8 +127,11 @@ http://maven.apache.org/maven-v4_0_0.xsd"> +<<<<<<< HEAD 20 20 +======= +>>>>>>> patternMatching de.dhbwstuttgart.core.ConsoleInterface @@ -123,4 +141,4 @@ http://maven.apache.org/maven-v4_0_0.xsd"> file:///${project.basedir}/maven-repository/ - + \ No newline at end of file diff --git a/resources/AllgemeinTest/Box.jav b/resources/AllgemeinTest/Box.jav deleted file mode 100644 index 411f0551..00000000 --- a/resources/AllgemeinTest/Box.jav +++ /dev/null @@ -1,13 +0,0 @@ -class Box{ -void m(A a){} -} - -class B { } - -class Box_Main extends B { - - m(b) { - b.m(new Box_Main()); - b.m(new B()); - } -} diff --git a/resources/AllgemeinTest/Box_Main.jav b/resources/AllgemeinTest/Box_Main.jav deleted file mode 100644 index 0ba86f19..00000000 --- a/resources/AllgemeinTest/Box_Main.jav +++ /dev/null @@ -1,13 +0,0 @@ -class Box{ - A f; -} - -class B { } - -class Box_Main extends B {//Fehler Bugzilla Bug 230 - - m(b) { - b.f = new Box_Main(); - b.f = new B(); - } -} diff --git a/resources/AllgemeinTest/FCTest1.jav b/resources/AllgemeinTest/FCTest1.jav deleted file mode 100644 index 98647278..00000000 --- a/resources/AllgemeinTest/FCTest1.jav +++ /dev/null @@ -1,12 +0,0 @@ -import java.util.Vector; -import java.util.List; -import java.lang.Integer; - -class FCTest1 extends Vector> { - fc1() { - var y; - var z; - y.add(z); - return y; - } -} \ No newline at end of file diff --git a/resources/AllgemeinTest/FCTest2.jav b/resources/AllgemeinTest/FCTest2.jav deleted file mode 100644 index c3f892dd..00000000 --- a/resources/AllgemeinTest/FCTest2.jav +++ /dev/null @@ -1,11 +0,0 @@ -import java.util.Vector; -import java.util.List; -import java.lang.Integer; - -class FCTest2 extends Vector> { - fc2(y) { - var z; - y.add(z); - return y; - } -} \ No newline at end of file diff --git a/resources/AllgemeinTest/FCTest3.jav b/resources/AllgemeinTest/FCTest3.jav deleted file mode 100644 index e862c4b8..00000000 --- a/resources/AllgemeinTest/FCTest3.jav +++ /dev/null @@ -1,19 +0,0 @@ -import java.util.Vector; -import java.lang.Integer; - -class FCTest3 extends Pair, Vector> { - - - fc2(x) { - x.snd().addElement(2); - } - - - - fc2a() { - var y; - y.snd().addElement(2); - return y; - } - -} \ No newline at end of file diff --git a/resources/AllgemeinTest/GenTest.jav b/resources/AllgemeinTest/GenTest.jav deleted file mode 100644 index 409838ae..00000000 --- a/resources/AllgemeinTest/GenTest.jav +++ /dev/null @@ -1,10 +0,0 @@ -import java.lang.Integer; -import java.util.Vector; - -public class GenTest { - - main(x) { - var v = new Vector(); - return 1 + v.elementAt(0); - } -} diff --git a/resources/AllgemeinTest/Generics.jav b/resources/AllgemeinTest/Generics.jav deleted file mode 100644 index efed04f0..00000000 --- a/resources/AllgemeinTest/Generics.jav +++ /dev/null @@ -1,9 +0,0 @@ -class Generics { - a; - id(b) { return b; } - setA(x) { - a = x; - return a; - } - m(x,y) { x = id(y); } -} diff --git a/resources/AllgemeinTest/M.jav b/resources/AllgemeinTest/M.jav deleted file mode 100755 index 39e6d482..00000000 --- a/resources/AllgemeinTest/M.jav +++ /dev/null @@ -1,7 +0,0 @@ -import java.util.List; -class M { -void m(p, p2){ - - new addList().addLists(p, p2); -} -} diff --git a/resources/AllgemeinTest/OverloadingMain.jav b/resources/AllgemeinTest/OverloadingMain.jav deleted file mode 100644 index 960f01db..00000000 --- a/resources/AllgemeinTest/OverloadingMain.jav +++ /dev/null @@ -1,9 +0,0 @@ -import java.util.Stack; -import java.util.Vector; - -class OverloadingMain { - - mmMain(x) { var y; return new O1().mm(y); } - -} - diff --git a/resources/AllgemeinTest/Overloading_Generics.jav b/resources/AllgemeinTest/Overloading_Generics.jav deleted file mode 100644 index d5691152..00000000 --- a/resources/AllgemeinTest/Overloading_Generics.jav +++ /dev/null @@ -1,20 +0,0 @@ -import java.lang.Integer; - - -public class Overloading_Generics { - - id1 (x) { return x; } - - //Integer id (Integer x) { return x; } -} - - -class Overloading_Generics1 { - main(x) { - var olg = new Overloading_Generics(); - return olg.id1(1); - } -} - - - diff --git a/resources/AllgemeinTest/OverrideMain.jav b/resources/AllgemeinTest/OverrideMain.jav deleted file mode 100644 index 0ede39ae..00000000 --- a/resources/AllgemeinTest/OverrideMain.jav +++ /dev/null @@ -1,25 +0,0 @@ -import java.util.Vector; -import java.util.Stack; - -class OverrideMain { - ovrMain(x) { - var overide; - overide.ovr(x); - } -} - -/* - [ - [(TPH L = java.util.Stack), (TPH N = java.lang.String), (TPH M = ? extends Override2), (TPH FTN, TPH FTM), (TPH K = void)], -[(TPH FTO, TPH FTP), (TPH M = ? extends Override2), (TPH N = java.lang.String), (TPH L = java.util.Stack), (TPH K = void)], -[(TPH M = ? extends Override2), (TPH N = java.lang.String), (TPH K = void), (TPH FTR, TPH FTQ), (TPH L = java.util.Vector)], -[(TPH FTT, TPH FTS), (TPH M = ? extends Override2), (TPH L = java.util.Vector), (TPH K = void), (TPH N = java.lang.String)], -[(TPH L = java.util.Vector), (TPH M = ? extends Override2), (TPH N = java.lang.String), (TPH FTU, TPH FTV), (TPH K = void)], -[(TPH FTX, TPH FTW), (TPH M = ? extends Override2), (TPH L = java.util.Vector), (TPH K = void), (TPH N = java.lang.String)], -[(TPH M = ? extends Override2), (TPH L = java.util.Stack), (TPH K = void), (TPH FTY, TPH FTZ), (TPH N = java.lang.String)], -[(TPH FUB, TPH FUA), (TPH K = void), (TPH M = ? extends Override2), (TPH N = java.lang.String), (TPH L = java.util.Vector)], -[(TPH N = java.lang.String), (TPH L = java.util.Vector), (TPH FUD, TPH FUC), (TPH M = ? extends Override2), (TPH K = void)], -[(TPH N = java.lang.String), (TPH FUF, TPH FUE), (TPH M = ? extends Override2), (TPH K = void), (TPH L = java.util.Vector)]] - - [[(TPH M = ? extends Override2), (TPH MNX, TPH MNY), (TPH N = java.lang.String), (TPH K = void), (TPH L = java.util.Stack)], [(TPH L = java.util.Stack), (TPH N = java.lang.String), (TPH M = ? extends Override2), (TPH K = void), (TPH MOB, TPH MOC)], [(TPH M = ? extends Override2), (TPH N = java.lang.String), (TPH MNZ, TPH MOA), (TPH L = java.util.Vector), (TPH K = void)], [(TPH L = java.util.Vector), (TPH K = void), (TPH M = ? extends Override2), (TPH MOD, TPH MOE), (TPH N = java.lang.String)], [(TPH M = ? extends Override2), (TPH K = void), (TPH N = java.lang.String), (TPH MOF, TPH MOG), (TPH L = java.util.Stack)], [(TPH L = java.util.Vector), (TPH K = void), (TPH MOH, TPH MOI), (TPH M = ? extends Override2), (TPH N = java.lang.String)], [(TPH L = java.util.Vector), (TPH MOJ, TPH MOK), (TPH K = void), (TPH M = ? extends Override2), (TPH N = java.lang.String)], [(TPH MOL, TPH MOM), (TPH L = java.util.Stack), (TPH M = ? extends Override2), (TPH K = void), (TPH N = java.lang.String)], [(TPH L = java.util.Vector), (TPH MON, TPH MOO), (TPH N = java.lang.String), (TPH K = void), (TPH M = ? extends Override2)], [(TPH L = java.util.Stack), (TPH N = java.lang.String), (TPH M = ? extends Override2), (TPH MOQ, TPH MOP), (TPH K = void)]] -*/ diff --git a/resources/AllgemeinTest/OverrideMainRet.jav b/resources/AllgemeinTest/OverrideMainRet.jav deleted file mode 100644 index 44759c81..00000000 --- a/resources/AllgemeinTest/OverrideMainRet.jav +++ /dev/null @@ -1,11 +0,0 @@ -import java.util.Vector; -import java.util.Stack; - -class OverrideMainRet { - ovrMain() { - var overide; - var x; - overide.ovr(x); - return x; - } -} \ No newline at end of file diff --git a/resources/AllgemeinTest/Pair.java b/resources/AllgemeinTest/Pair.java deleted file mode 100644 index b47b1d84..00000000 --- a/resources/AllgemeinTest/Pair.java +++ /dev/null @@ -1,18 +0,0 @@ -class Pair { - T x; - U y; - - public Pair() { } - public Pair(T x, U y) { - this.x = x; - this.y = y; - } - - public T fst () { - return x; - } - - public U snd () { - return y; - } -} diff --git a/resources/AllgemeinTest/Put.jav b/resources/AllgemeinTest/Put.jav deleted file mode 100644 index b22977c6..00000000 --- a/resources/AllgemeinTest/Put.jav +++ /dev/null @@ -1,19 +0,0 @@ -import java.util.Vector; -import java.util.Stack; - -class Put { - - putElement(ele, v) { - v.addElement(ele); - } - - putElement(ele, s) { - s.push(ele); - } - - - main(ele, x) { - putElement(ele, x); - } - -} \ No newline at end of file diff --git a/resources/AllgemeinTest/Test.jav b/resources/AllgemeinTest/Test.jav deleted file mode 100644 index 3d505a85..00000000 --- a/resources/AllgemeinTest/Test.jav +++ /dev/null @@ -1,4 +0,0 @@ -class Test { - a; - Test b; -} \ No newline at end of file diff --git a/resources/AllgemeinTest/TestSubTypless.jav b/resources/AllgemeinTest/TestSubTypless.jav deleted file mode 100644 index 667fe6e7..00000000 --- a/resources/AllgemeinTest/TestSubTypless.jav +++ /dev/null @@ -1,12 +0,0 @@ -import java.util.ArrayList; - -class TestSubTypless { - m(a){ - var l = new ArrayList<>(); - l.add(a); - return m2(l).get(0); - } - m2(a){ - return m(a); - } -} \ No newline at end of file diff --git a/resources/AllgemeinTest/Twice.jav b/resources/AllgemeinTest/Twice.jav deleted file mode 100644 index 396bc5e2..00000000 --- a/resources/AllgemeinTest/Twice.jav +++ /dev/null @@ -1,3 +0,0 @@ -class Twice { - twice = f -> x -> f.apply(f.apply(x)); -} diff --git a/resources/AllgemeinTest/Var.jav b/resources/AllgemeinTest/Var.jav deleted file mode 100644 index b95b3667..00000000 --- a/resources/AllgemeinTest/Var.jav +++ /dev/null @@ -1,5 +0,0 @@ -class Var { - - var(x) { var y; } - -} \ No newline at end of file diff --git a/resources/AllgemeinTest/VectorConstAdd.jav b/resources/AllgemeinTest/VectorConstAdd.jav deleted file mode 100644 index b179bdcc..00000000 --- a/resources/AllgemeinTest/VectorConstAdd.jav +++ /dev/null @@ -1,15 +0,0 @@ -import java.util.Vector; -import java.lang.Integer; - - -public class VectorConstAdd { - vectorAdd(v1) { - var i = 0; - var erg = new Vector<>(); - while (i < v1.size()) { - erg.addElement(v1.elementAt(i) + 1); - i++; - } - return erg; - } -} diff --git a/resources/AllgemeinTest/VectorNotObject.jav b/resources/AllgemeinTest/VectorNotObject.jav deleted file mode 100644 index d8ea900b..00000000 --- a/resources/AllgemeinTest/VectorNotObject.jav +++ /dev/null @@ -1,9 +0,0 @@ -import java.util.Vector; - -class VectorNotObject { - - vectorAddAll(v1, v2) { - v1.addAll(v2); - return v1; - } - } diff --git a/resources/AllgemeinTest/WildcardCaptureConversionTest.jav b/resources/AllgemeinTest/WildcardCaptureConversionTest.jav deleted file mode 100644 index 59016f7a..00000000 --- a/resources/AllgemeinTest/WildcardCaptureConversionTest.jav +++ /dev/null @@ -1,16 +0,0 @@ -import java.util.Vector; -import java.lang.Integer; -import java.lang.String; - -class WildcardCaptureConversionTest { - - m(x, y ,z) { - x = new Vector(); - y = new Vector(); - x.add(1); - y.add("2"); - //Integer i = x.elementAt(0); - //String s = y.elementAt(0); - return z.vectorAddAll(x, y); - } -} \ No newline at end of file diff --git a/resources/AllgemeinTest/Wildcard_Andi.jav b/resources/AllgemeinTest/Wildcard_Andi.jav deleted file mode 100644 index e6160437..00000000 --- a/resources/AllgemeinTest/Wildcard_Andi.jav +++ /dev/null @@ -1,8 +0,0 @@ -class Wildcard_Andi { - - Test ex = new Test<>(); - - Test sup = new Test<>(); -} - - diff --git a/resources/AllgemeinTest/addList.jav b/resources/AllgemeinTest/addList.jav deleted file mode 100755 index a72023ea..00000000 --- a/resources/AllgemeinTest/addList.jav +++ /dev/null @@ -1,8 +0,0 @@ -import java.util.List; - -class addList { - addLists(a, b){ -a.add(b.get(0)); -b.add(a.get(0)); -} -} diff --git a/resources/AllgemeinTest/wildcardPair.jav b/resources/AllgemeinTest/wildcardPair.jav deleted file mode 100644 index 73f310f4..00000000 --- a/resources/AllgemeinTest/wildcardPair.jav +++ /dev/null @@ -1,22 +0,0 @@ -import java.util.List; -import java.lang.Integer; -import java.lang.Object; -import java.lang.Boolean; - -class wildcardPair { - - make(l) { - var p = new Pair(l.get(0), l.get(1)); - return p; - } - //Boolean compare(Pair x) { return true; } - void m(l) { - Object o = l.get(0); - - //Pair p; - //List b; - //this.compare(p); //1, type incorrect - make(l); - //this.compare(this.make(b)); //2, OK - } -} \ No newline at end of file diff --git a/resources/javFiles/AddLong.jav b/resources/bytecode/javFiles/AddLong.jav similarity index 100% rename from resources/javFiles/AddLong.jav rename to resources/bytecode/javFiles/AddLong.jav diff --git a/resources/javFiles/EmptyClass.jav b/resources/bytecode/javFiles/EmptyClass.jav similarity index 100% rename from resources/javFiles/EmptyClass.jav rename to resources/bytecode/javFiles/EmptyClass.jav diff --git a/resources/javFiles/Expressions.jav b/resources/bytecode/javFiles/Expressions.jav similarity index 100% rename from resources/javFiles/Expressions.jav rename to resources/bytecode/javFiles/Expressions.jav diff --git a/resources/javFiles/FC_Matrix.jav b/resources/bytecode/javFiles/FC_Matrix.jav similarity index 100% rename from resources/javFiles/FC_Matrix.jav rename to resources/bytecode/javFiles/FC_Matrix.jav diff --git a/resources/javFiles/FacultyIf.jav b/resources/bytecode/javFiles/FacultyIf.jav similarity index 100% rename from resources/javFiles/FacultyIf.jav rename to resources/bytecode/javFiles/FacultyIf.jav diff --git a/resources/javFiles/FacultyTyped.jav b/resources/bytecode/javFiles/FacultyTyped.jav similarity index 100% rename from resources/javFiles/FacultyTyped.jav rename to resources/bytecode/javFiles/FacultyTyped.jav diff --git a/resources/javFiles/FieldAccess.jav b/resources/bytecode/javFiles/FieldAccess.jav similarity index 100% rename from resources/javFiles/FieldAccess.jav rename to resources/bytecode/javFiles/FieldAccess.jav diff --git a/resources/javFiles/Fields.jav b/resources/bytecode/javFiles/Fields.jav similarity index 100% rename from resources/javFiles/Fields.jav rename to resources/bytecode/javFiles/Fields.jav diff --git a/resources/javFiles/LambdaField.jav b/resources/bytecode/javFiles/LambdaField.jav similarity index 100% rename from resources/javFiles/LambdaField.jav rename to resources/bytecode/javFiles/LambdaField.jav diff --git a/resources/javFiles/LambdaRunnable.jav b/resources/bytecode/javFiles/LambdaRunnable.jav similarity index 100% rename from resources/javFiles/LambdaRunnable.jav rename to resources/bytecode/javFiles/LambdaRunnable.jav diff --git a/resources/javFiles/ListenerOverload.jav b/resources/bytecode/javFiles/ListenerOverload.jav similarity index 100% rename from resources/javFiles/ListenerOverload.jav rename to resources/bytecode/javFiles/ListenerOverload.jav diff --git a/resources/javFiles/Meth_Gen.jav b/resources/bytecode/javFiles/Meth_Gen.jav similarity index 100% rename from resources/javFiles/Meth_Gen.jav rename to resources/bytecode/javFiles/Meth_Gen.jav diff --git a/resources/javFiles/MethodCallGenerics.jav b/resources/bytecode/javFiles/MethodCallGenerics.jav similarity index 100% rename from resources/javFiles/MethodCallGenerics.jav rename to resources/bytecode/javFiles/MethodCallGenerics.jav diff --git a/resources/javFiles/MethodWildcardGen.jav b/resources/bytecode/javFiles/MethodWildcardGen.jav similarity index 100% rename from resources/javFiles/MethodWildcardGen.jav rename to resources/bytecode/javFiles/MethodWildcardGen.jav diff --git a/resources/javFiles/MethodsEasy.jav b/resources/bytecode/javFiles/MethodsEasy.jav similarity index 100% rename from resources/javFiles/MethodsEasy.jav rename to resources/bytecode/javFiles/MethodsEasy.jav diff --git a/resources/bytecode/javFiles/OL.jav b/resources/bytecode/javFiles/OL.jav index 4eab848f..afeaa2f5 100644 --- a/resources/bytecode/javFiles/OL.jav +++ b/resources/bytecode/javFiles/OL.jav @@ -1,32 +1,15 @@ +import java.lang.Double; import java.lang.String; -import java.lang.Integer; -import java.lang.Double; -import java.lang.Boolean; -//import java.util.Vector; +import java.lang.Long; - -public class OL { - - java.lang.Double m(java.lang.Double x) { return x + x; } - java.lang.Integer m(java.lang.Integer x) { return x + x; } - java.lang.String m(java.lang.String x) { return x + x; } - java.lang.Boolean m(Boolean x) { return x; } - -// if the class contains just this method, then correct BC will be generated. -// But if another methods are contained then the generated BC is not correct -// m(x) { -// //x.add(1); -// x.addAll(x); -// return x; -// } - +class OL { + m (x) { return x + x; } } -public class OLMain { - - main(x) { +class OLMain { + main(x) { var ol; - ol = new OL(); - return ol.m(x); - } + ol = new OL(); + return ol.m(x); + } } diff --git a/resources/javFiles/Op1.jav b/resources/bytecode/javFiles/Op1.jav similarity index 100% rename from resources/javFiles/Op1.jav rename to resources/bytecode/javFiles/Op1.jav diff --git a/resources/javFiles/Package.jav b/resources/bytecode/javFiles/Package.jav similarity index 100% rename from resources/javFiles/Package.jav rename to resources/bytecode/javFiles/Package.jav diff --git a/resources/javFiles/Subclass.jav b/resources/bytecode/javFiles/Subclass.jav similarity index 100% rename from resources/javFiles/Subclass.jav rename to resources/bytecode/javFiles/Subclass.jav diff --git a/resources/javFiles/Superclass.jav b/resources/bytecode/javFiles/Superclass.jav similarity index 100% rename from resources/javFiles/Superclass.jav rename to resources/bytecode/javFiles/Superclass.jav diff --git a/resources/javFiles/Vector.jav b/resources/bytecode/javFiles/Vector.jav similarity index 100% rename from resources/javFiles/Vector.jav rename to resources/bytecode/javFiles/Vector.jav diff --git a/resources/javFiles/fc.jav b/resources/bytecode/javFiles/fc.jav similarity index 100% rename from resources/javFiles/fc.jav rename to resources/bytecode/javFiles/fc.jav diff --git a/resources/javFiles/test.jav b/resources/bytecode/javFiles/test.jav similarity index 100% rename from resources/javFiles/test.jav rename to resources/bytecode/javFiles/test.jav diff --git a/resources/javFiles/test1.jav b/resources/bytecode/javFiles/test1.jav similarity index 100% rename from resources/javFiles/test1.jav rename to resources/bytecode/javFiles/test1.jav diff --git a/resources/javFiles/EmptyMethod.jav b/resources/javFiles/EmptyMethod.jav deleted file mode 100644 index dd28fc69..00000000 --- a/resources/javFiles/EmptyMethod.jav +++ /dev/null @@ -1,37 +0,0 @@ -public class EmptyMethod{ - static String s1 =""; - String s2; - public void m1(){ - //String s = ""; - System.out.println("test"); - //Integer ab = Math.abs(1); - //Math.abs(1); - //String lV = "local"; - //s1 = "1"; - //s1.concat("2"); - s2 = s1; - //m2(); - Clazz i = new Clazz(); - Integer i = new Integer(1); - } - - public void m2(){} -} - -class Clazz{} -/* -public class EmptyMethod2{ - public static test = "5"; - public void m1(Integer i, String j, Boolean b){ - //String s = ""; - EmptyMethod em = new EmptyMethod(); - em.m1(); - em.s1 = ""; - //Integer ab = Math.abs(1); - //Math.abs(1); - //String lV = "local"; - //s1 = "1"; - //s1.concat("2"); - //s2 = s1; - } -}*/ \ No newline at end of file diff --git a/resources/javFiles/Faculty.jav b/resources/javFiles/Faculty.jav deleted file mode 100644 index ed201ff9..00000000 --- a/resources/javFiles/Faculty.jav +++ /dev/null @@ -1,16 +0,0 @@ -import java.lang.Integer; - -class Faculty { - //fact; - - Integer mul(Integer x, Integer y) { - return x; - } - - m () { - var fact = (Integer x) -> { - return mul(x, fact.apply(x)); - }; - return fact; - } -} \ No newline at end of file diff --git a/resources/javFiles/Generics.jav b/resources/javFiles/Generics.jav deleted file mode 100644 index dd7b4eba..00000000 --- a/resources/javFiles/Generics.jav +++ /dev/null @@ -1,22 +0,0 @@ -import java.lang.String; - -class Generics { - // A mt1(A a, B b){ - B mt1(B a, B b){ - return mt1(a, a); - } -} - -class Test { - methode(String s){ - return new Generics().mt1(s,s); - } -} - -/* -Problem: -auto test = new List(); -auto test2 = new List(); -... //code, welcher möglicherweise test und test2 vertauscht -test.add("hallo"); -*/ \ No newline at end of file diff --git a/resources/javFiles/IfTest.jav b/resources/javFiles/IfTest.jav deleted file mode 100644 index 88885561..00000000 --- a/resources/javFiles/IfTest.jav +++ /dev/null @@ -1,14 +0,0 @@ -import java.lang.Integer; -import java.lang.Boolean; -import java.lang.Object; - -public class IfTest { - Object m1(b) { - Integer i; - if(b) { - return i; - }else{ - return b; - } - } -} \ No newline at end of file diff --git a/resources/javFiles/Import.jav b/resources/javFiles/Import.jav deleted file mode 100644 index 2fc3a8b3..00000000 --- a/resources/javFiles/Import.jav +++ /dev/null @@ -1,8 +0,0 @@ -import java.util.Vector; - -class Import { - void methode(){ - var v; - v.add(v); - } -} \ No newline at end of file diff --git a/resources/javFiles/Lambda.jav b/resources/javFiles/Lambda.jav deleted file mode 100644 index 296fd7ef..00000000 --- a/resources/javFiles/Lambda.jav +++ /dev/null @@ -1,12 +0,0 @@ - -class Apply { } - -public class Lambda { - - m () { - var lam1 = (x) -> { - return x; - }; - return lam1.apply(new Apply()); - } -} diff --git a/resources/javFiles/Lambda2.jav b/resources/javFiles/Lambda2.jav deleted file mode 100644 index cf1e910b..00000000 --- a/resources/javFiles/Lambda2.jav +++ /dev/null @@ -1,33 +0,0 @@ -import java.lang.String; - -public class Lambda2 -{ - public static void main(List args){ - var listOfStrings = new List(); - var listOfObjects; - listOfObjects = map(listOfStrings, (a) -> a); -} - -public map(a , b){ - b.apply(a); - return a; -} - -/* -public static List map(List input, Function func) { - List output; - output = new List(); - output.add(func.apply(input.get())); - return output; -} -*/ -} - -class List{ - A get(); - void add(A); -} - -class Function{ - B apply(A a); -} \ No newline at end of file diff --git a/resources/javFiles/Lambda3.jav b/resources/javFiles/Lambda3.jav deleted file mode 100644 index 9e22f302..00000000 --- a/resources/javFiles/Lambda3.jav +++ /dev/null @@ -1,24 +0,0 @@ -import java.lang.String; - -public class Lambda2 -{ - /* - public static List map(List input, - Function func){ - input.add(func.apply(input.get())); - } - */ - public map(input,func){ - input.add(func.apply(input.get())); - return map(new List(), func); - } -} - -class List{ - A get(); - void add(A); -} - -class Function{ - B apply(A a); -} \ No newline at end of file diff --git a/resources/javFiles/Matrix.jav b/resources/javFiles/Matrix.jav deleted file mode 100644 index 5e1eac08..00000000 --- a/resources/javFiles/Matrix.jav +++ /dev/null @@ -1,28 +0,0 @@ -import java.util.Vector; -import java.lang.Integer; - -class Matrix extends Vector> { - Integer mul1(Integer x, Integer y) { return x;} - Integer add1(Integer x, Integer y) { return x;} - mul(m) { - var ret = new Matrix(); - var i = 0; - while(i < size()) { - var v1 = this.elementAt(i); - var v2 = new Vector(); - var j = 0; - while(j < v1.size()) { - var erg = 0; - var k = 0; - while(k < v1.size()) { - erg = erg + v1.elementAt(k) * m.elementAt(k).elementAt(j); - //erg = add1(erg, mul1(v1.elementAt(k), - // m.elementAt(k).elementAt(j))); - k++; } - v2.addElement(new Integer(erg)); - j++; } - ret.addElement(v2); - i++; } - return ret; - } -} diff --git a/resources/javFiles/Methods.jav b/resources/javFiles/Methods.jav deleted file mode 100644 index e45d9830..00000000 --- a/resources/javFiles/Methods.jav +++ /dev/null @@ -1,17 +0,0 @@ - -class Methods { - mt4(a,b,c) { return a.add(b).sub(c) ; } - - mt1(a) {return a;} - - mt2(a) {return a.f; } - - mt3(a) {return a.add(); } -} - -class Test { - java.lang.Object f; - add(){} - add(b){return b;} - sub(b){} -} \ No newline at end of file diff --git a/resources/javFiles/OL.jav b/resources/javFiles/OL.jav deleted file mode 100644 index 0a3f82ec..00000000 --- a/resources/javFiles/OL.jav +++ /dev/null @@ -1,15 +0,0 @@ -import java.lang.Double; -import java.lang.String; -import java.lang.Long; - -class OL { - m (x) { return x + x; } -} - -class OLMain { - main(x) { - var ol; - ol = new OL(); - return ol.m(x); - } -} \ No newline at end of file diff --git a/resources/javFiles/Sorting.jav b/resources/javFiles/Sorting.jav deleted file mode 100644 index e5897914..00000000 --- a/resources/javFiles/Sorting.jav +++ /dev/null @@ -1,15 +0,0 @@ -import java.util.List; -import java.util.Collection; - -class Sorting{ - void merge(a, b){ - a.addAll(b); - return a; - } - - sort(in){ - var firstHalf = in; - var secondHalf = in; - return merge(sort(firstHalf), sort(secondHalf)); - } -} \ No newline at end of file diff --git a/resources/javFiles/mathStruc.jav b/resources/javFiles/mathStruc.jav deleted file mode 100644 index c8518e5d..00000000 --- a/resources/javFiles/mathStruc.jav +++ /dev/null @@ -1,8 +0,0 @@ -class MathStruc { - - A model; - - innerOp = o -> ms -> new MathStruc(o.apply(this.model, ms.model)); - - MathStruc(A m) { model=m; } - } \ No newline at end of file diff --git a/resources/javFiles/packageTest/Gen.jav b/resources/javFiles/packageTest/Gen.jav deleted file mode 100644 index 3b58b188..00000000 --- a/resources/javFiles/packageTest/Gen.jav +++ /dev/null @@ -1,8 +0,0 @@ -import java.lang.Integer; -import java.util.Vector; - -public class Gen{ - Vector m(Vector v){ - return v; - } -} diff --git a/resources/javFiles/packageTest/OLMain.jav b/resources/javFiles/packageTest/OLMain.jav deleted file mode 100644 index 0cdb0b4f..00000000 --- a/resources/javFiles/packageTest/OLMain.jav +++ /dev/null @@ -1,12 +0,0 @@ -import java.lang.String; -import java.lang.Integer; -import java.lang.Double; - -public class OLMain { - - main(x) { - var ol; - ol = new OLextends(); - return ol.m(x); - } -} diff --git a/resources/javFiles/packageTest/OLOneFile.jav b/resources/javFiles/packageTest/OLOneFile.jav deleted file mode 100644 index eb865d61..00000000 --- a/resources/javFiles/packageTest/OLOneFile.jav +++ /dev/null @@ -1,22 +0,0 @@ -import java.lang.String; -import java.lang.Integer; -import java.lang.Double; -import java.lang.Boolean; - - -public class OLOneFile { - - m2(x) { return x + x; } - -} - -public class OLextendsOneFile extends OLOneFile { } - -public class OLMainOneFile { - - main(x) { - var ol; - ol = new OLextendsOneFile(); - return ol.m2(x); - } -} diff --git a/resources/javFiles/packageTest/OLTest.txt b/resources/javFiles/packageTest/OLTest.txt deleted file mode 100644 index d91b58d7..00000000 --- a/resources/javFiles/packageTest/OLTest.txt +++ /dev/null @@ -1,6 +0,0 @@ -java -jar ~/eclipse-workspace/JavaCompilerCore/target/JavaTXcompiler-0.2-jar-with-dependencies.jar de/test/OL.jav -d de/test/output -java -jar ~/eclipse-workspace/JavaCompilerCore/target/JavaTXcompiler-0.2-jar-with-dependencies.jar OLextends.jav -cp de/test/output -java -jar ~/eclipse-workspace/JavaCompilerCore/target/JavaTXcompiler-0.2-jar-with-dependencies.jar OLMain.jav -cp .:de/test/output -javac UseOLMain.java -java -cp .:de/test/output UseOLMain -rm -f UseOLMain.class diff --git a/resources/javFiles/packageTest/OLextends.jav b/resources/javFiles/packageTest/OLextends.jav deleted file mode 100644 index b3c055df..00000000 --- a/resources/javFiles/packageTest/OLextends.jav +++ /dev/null @@ -1,7 +0,0 @@ -import de.test.OL; - - -public class OLextends extends OL { - - -} diff --git a/resources/javFiles/packageTest/Pair2.jav b/resources/javFiles/packageTest/Pair2.jav deleted file mode 100644 index d62474ea..00000000 --- a/resources/javFiles/packageTest/Pair2.jav +++ /dev/null @@ -1,14 +0,0 @@ -import de.test.Pair; - -class Pairs { - setfst(fst) { - return new Pair<>(snd, fst); - } - - swap () { - return new Pair<> (snd, fst); } - - polyrec(p) { - return polyrec (p.swap()); - } -} \ No newline at end of file diff --git a/resources/javFiles/packageTest/Test.jav b/resources/javFiles/packageTest/Test.jav deleted file mode 100644 index 2f6429a1..00000000 --- a/resources/javFiles/packageTest/Test.jav +++ /dev/null @@ -1,3 +0,0 @@ - -public class Test{ -} diff --git a/resources/javFiles/packageTest/UseOLMain.java b/resources/javFiles/packageTest/UseOLMain.java deleted file mode 100644 index 2d7d6fd8..00000000 --- a/resources/javFiles/packageTest/UseOLMain.java +++ /dev/null @@ -1,5 +0,0 @@ -class UseOLMain { - public static void main(String[] arg) { - System.out.println(new OLMain().main(1+1)); - } -} diff --git a/resources/javFiles/packageTest/de/test/ImportTest.jav b/resources/javFiles/packageTest/de/test/ImportTest.jav deleted file mode 100644 index 58b6fc0b..00000000 --- a/resources/javFiles/packageTest/de/test/ImportTest.jav +++ /dev/null @@ -1,9 +0,0 @@ -package de.test; - -import de.test.ToImport; - -class ImportTest{ - void methode(){ - new ToImport(); - } -} \ No newline at end of file diff --git a/resources/javFiles/packageTest/de/test/ImportTest2.jav b/resources/javFiles/packageTest/de/test/ImportTest2.jav deleted file mode 100644 index 3526abc8..00000000 --- a/resources/javFiles/packageTest/de/test/ImportTest2.jav +++ /dev/null @@ -1,11 +0,0 @@ -package de.test; - -import de.test.subpackage1.ToImport2; -import de.test.subpackage2.ToImport3; - -class ImportTest2{ - void methode(){ - new ToImport2().m1(); - new ToImport3().m2(); - } -} \ No newline at end of file diff --git a/resources/javFiles/packageTest/de/test/ImportTestDefault.jav b/resources/javFiles/packageTest/de/test/ImportTestDefault.jav deleted file mode 100644 index ecd8d7c5..00000000 --- a/resources/javFiles/packageTest/de/test/ImportTestDefault.jav +++ /dev/null @@ -1,7 +0,0 @@ -package de.test; - -class ImportTestDefault{ - void methode(){ - new ToImport(); - } -} \ No newline at end of file diff --git a/resources/javFiles/packageTest/de/test/OL.jav b/resources/javFiles/packageTest/de/test/OL.jav deleted file mode 100644 index 7f1ba512..00000000 --- a/resources/javFiles/packageTest/de/test/OL.jav +++ /dev/null @@ -1,13 +0,0 @@ -package de.test; -import java.lang.String; -import java.lang.Integer; -import java.lang.Double; -import java.lang.Boolean; -//import java.util.Vector; - - -public class OL { - - public m(x) { return x + x; } - -} diff --git a/resources/javFiles/packageTest/de/test/Pair.jav b/resources/javFiles/packageTest/de/test/Pair.jav deleted file mode 100644 index dbde6636..00000000 --- a/resources/javFiles/packageTest/de/test/Pair.jav +++ /dev/null @@ -1,12 +0,0 @@ -package de.test; - -class Pair { - fst; - snd; - - Pair(fst, snd) { - this.fst = fst; - this.snd = snd; - } -} - diff --git a/resources/javFiles/packageTest/de/test/TestClass.jav b/resources/javFiles/packageTest/de/test/TestClass.jav deleted file mode 100644 index 6681b36a..00000000 --- a/resources/javFiles/packageTest/de/test/TestClass.jav +++ /dev/null @@ -1,3 +0,0 @@ -package de.test; - -public class TestClass{} \ No newline at end of file diff --git a/resources/javFiles/packageTest/de/test/ToImport.jav b/resources/javFiles/packageTest/de/test/ToImport.jav deleted file mode 100644 index 3afdba54..00000000 --- a/resources/javFiles/packageTest/de/test/ToImport.jav +++ /dev/null @@ -1,4 +0,0 @@ -package de.test; - -class ToImport{ -} \ No newline at end of file diff --git a/resources/javFiles/packageTest/de/test/mathStruc.jav b/resources/javFiles/packageTest/de/test/mathStruc.jav deleted file mode 100644 index 28db5db8..00000000 --- a/resources/javFiles/packageTest/de/test/mathStruc.jav +++ /dev/null @@ -1,18 +0,0 @@ -package de.test; - - -import java.util.Vector; -import java.lang.Integer; - -public class mathStruc { - model; - - //Fun1*, Fun1*,MathStruc >> - innerOp = (o) -> (ms) -> new mathStruc<>(o.apply(model,ms.model)); - - public mathStruc(m) { - model =m; - //innerOp = (o) -> (ms) -> new mathStruc<>(o.apply(this.model,ms.model)); - } -} - diff --git a/resources/javFiles/packageTest/de/test/mathStrucVector.jav b/resources/javFiles/packageTest/de/test/mathStrucVector.jav deleted file mode 100644 index fe6d6055..00000000 --- a/resources/javFiles/packageTest/de/test/mathStrucVector.jav +++ /dev/null @@ -1,33 +0,0 @@ -package de.test; - -import java.util.Vector; -import java.lang.Integer; -import java.lang.Boolean; - -import de.test.mathStruc; -import de.test.vectorAdd; - - -public class mathStrucVector { - - public main() { - Vector v1 = new Vector(); - v1.addElement(2); - v1.addElement(2); - Vector v2 = new Vector(); - v2.addElement(3); - v2.addElement(3); - - vectorAdd va = new vectorAdd(); - - var ms; - ms = new mathStruc<>(v1); - var ms2; - ms2 = new mathStruc<>(v2); - var ms3; - - ms3 = ms.innerOp.apply(va.add).apply(ms2); - return ms3; - - } -} diff --git a/resources/javFiles/packageTest/de/test/output/de/test/mathStrucVectoruse.java b/resources/javFiles/packageTest/de/test/output/de/test/mathStrucVectoruse.java deleted file mode 100644 index 54b9e45b..00000000 --- a/resources/javFiles/packageTest/de/test/output/de/test/mathStrucVectoruse.java +++ /dev/null @@ -1,10 +0,0 @@ -package de.test; -import de.test.mathStrucVector; - - -class mathStrucVectorUse { - - public static void main(String[] args) { - new mathStrucVector().main(); - } -} diff --git a/resources/javFiles/packageTest/de/test/output/mathStrucVectoruse.java b/resources/javFiles/packageTest/de/test/output/mathStrucVectoruse.java deleted file mode 100644 index 9a9b2e75..00000000 --- a/resources/javFiles/packageTest/de/test/output/mathStrucVectoruse.java +++ /dev/null @@ -1,8 +0,0 @@ - - -class mathStrucVectorUse { - - public static void main(String[] args) { - new mathStrucVector().main(); - } -} diff --git a/resources/javFiles/packageTest/de/test/packageNameTestWrongPackage.jav b/resources/javFiles/packageTest/de/test/packageNameTestWrongPackage.jav deleted file mode 100644 index a86d22aa..00000000 --- a/resources/javFiles/packageTest/de/test/packageNameTestWrongPackage.jav +++ /dev/null @@ -1,3 +0,0 @@ -package de.tesst; - -class TestClass{} \ No newline at end of file diff --git a/resources/javFiles/packageTest/de/test/subpackage1/Test1.jav b/resources/javFiles/packageTest/de/test/subpackage1/Test1.jav deleted file mode 100644 index a7011169..00000000 --- a/resources/javFiles/packageTest/de/test/subpackage1/Test1.jav +++ /dev/null @@ -1,4 +0,0 @@ -package de.test.subpackage1; - -class Test1{ -} \ No newline at end of file diff --git a/resources/javFiles/packageTest/de/test/subpackage1/ToImport2.jav b/resources/javFiles/packageTest/de/test/subpackage1/ToImport2.jav deleted file mode 100644 index bcc67b95..00000000 --- a/resources/javFiles/packageTest/de/test/subpackage1/ToImport2.jav +++ /dev/null @@ -1,5 +0,0 @@ -package de.test.subpackage1; - -class ToImport2{ -void m1(){} -} \ No newline at end of file diff --git a/resources/javFiles/packageTest/de/test/subpackage2/Test2.jav b/resources/javFiles/packageTest/de/test/subpackage2/Test2.jav deleted file mode 100644 index 750f7612..00000000 --- a/resources/javFiles/packageTest/de/test/subpackage2/Test2.jav +++ /dev/null @@ -1,4 +0,0 @@ -package de.test.subpackage2; - -class Test2{ -} \ No newline at end of file diff --git a/resources/javFiles/packageTest/de/test/subpackage2/ToImport3.jav b/resources/javFiles/packageTest/de/test/subpackage2/ToImport3.jav deleted file mode 100644 index 3efd8fff..00000000 --- a/resources/javFiles/packageTest/de/test/subpackage2/ToImport3.jav +++ /dev/null @@ -1,5 +0,0 @@ -package de.test.subpackage2; - -class ToImport3{ -void m2(){} -} \ No newline at end of file diff --git a/resources/javFiles/packageTest/de/test/vectorAdd.jav b/resources/javFiles/packageTest/de/test/vectorAdd.jav deleted file mode 100644 index 727a83a9..00000000 --- a/resources/javFiles/packageTest/de/test/vectorAdd.jav +++ /dev/null @@ -1,20 +0,0 @@ -package de.test; - -import java.util.Vector; -import java.lang.Integer; -import java.lang.Boolean; - - -public class vectorAdd { - - public add = (v1, v2) -> { - var ret = new Vector(); - var i = 0; - while(i < v1.size()) { - //if (i < v2.size()) { - ret.addElement(v1.elementAt(i) + v2.elementAt(i)); - //} - } - return ret; - }; -} diff --git a/resources/packageTest/Gen.jav b/resources/packageTest/Gen.jav new file mode 100644 index 00000000..e69de29b diff --git a/resources/packageTest/OLMain.jav b/resources/packageTest/OLMain.jav new file mode 100644 index 00000000..e69de29b diff --git a/resources/packageTest/OLOneFile.jav b/resources/packageTest/OLOneFile.jav new file mode 100644 index 00000000..e69de29b diff --git a/resources/packageTest/OLTest.txt b/resources/packageTest/OLTest.txt new file mode 100644 index 00000000..e69de29b diff --git a/resources/packageTest/OLextends.jav b/resources/packageTest/OLextends.jav new file mode 100644 index 00000000..e69de29b diff --git a/resources/packageTest/Pair2.jav b/resources/packageTest/Pair2.jav new file mode 100644 index 00000000..e69de29b diff --git a/resources/packageTest/Test.jav b/resources/packageTest/Test.jav new file mode 100644 index 00000000..e69de29b diff --git a/resources/packageTest/UseOLMain.java b/resources/packageTest/UseOLMain.java new file mode 100644 index 00000000..e69de29b diff --git a/resources/packageTest/de/test/ImportTest.jav b/resources/packageTest/de/test/ImportTest.jav new file mode 100644 index 00000000..e69de29b diff --git a/resources/packageTest/de/test/ImportTest2.jav b/resources/packageTest/de/test/ImportTest2.jav new file mode 100644 index 00000000..e69de29b diff --git a/resources/packageTest/de/test/ImportTestDefault.jav b/resources/packageTest/de/test/ImportTestDefault.jav new file mode 100644 index 00000000..e69de29b diff --git a/resources/packageTest/de/test/OL.jav b/resources/packageTest/de/test/OL.jav new file mode 100644 index 00000000..e69de29b diff --git a/resources/packageTest/de/test/Pair.jav b/resources/packageTest/de/test/Pair.jav new file mode 100644 index 00000000..e69de29b diff --git a/resources/packageTest/de/test/TestClass.jav b/resources/packageTest/de/test/TestClass.jav new file mode 100644 index 00000000..e69de29b diff --git a/resources/packageTest/de/test/ToImport.jav b/resources/packageTest/de/test/ToImport.jav new file mode 100644 index 00000000..e69de29b diff --git a/resources/packageTest/de/test/mathStruc.jav b/resources/packageTest/de/test/mathStruc.jav new file mode 100644 index 00000000..e69de29b diff --git a/resources/packageTest/de/test/mathStrucVector.jav b/resources/packageTest/de/test/mathStrucVector.jav new file mode 100644 index 00000000..e69de29b diff --git a/resources/packageTest/de/test/output/de/test/mathStrucVectoruse.java b/resources/packageTest/de/test/output/de/test/mathStrucVectoruse.java new file mode 100644 index 00000000..e69de29b diff --git a/resources/packageTest/de/test/output/mathStrucVectoruse.java b/resources/packageTest/de/test/output/mathStrucVectoruse.java new file mode 100644 index 00000000..e69de29b diff --git a/resources/packageTest/de/test/packageNameTestWrongPackage.jav b/resources/packageTest/de/test/packageNameTestWrongPackage.jav new file mode 100644 index 00000000..e69de29b diff --git a/resources/packageTest/de/test/subpackage1/Test1.jav b/resources/packageTest/de/test/subpackage1/Test1.jav new file mode 100644 index 00000000..e69de29b diff --git a/resources/packageTest/de/test/subpackage1/ToImport2.jav b/resources/packageTest/de/test/subpackage1/ToImport2.jav new file mode 100644 index 00000000..e69de29b diff --git a/resources/packageTest/de/test/subpackage2/Test2.jav b/resources/packageTest/de/test/subpackage2/Test2.jav new file mode 100644 index 00000000..e69de29b diff --git a/resources/packageTest/de/test/subpackage2/ToImport3.jav b/resources/packageTest/de/test/subpackage2/ToImport3.jav new file mode 100644 index 00000000..e69de29b diff --git a/resources/packageTest/de/test/vectorAdd.jav b/resources/packageTest/de/test/vectorAdd.jav new file mode 100644 index 00000000..e69de29b diff --git a/resources/syntaxtreegenerator/BinaryInMeth.ast b/resources/syntaxtreegenerator/BinaryInMeth.ast new file mode 100644 index 00000000..5bb1379c --- /dev/null +++ b/resources/syntaxtreegenerator/BinaryInMeth.ast @@ -0,0 +1,22 @@ +class BinaryInMeth { + +BinaryInMeth(){ + super(()); + } + TPH CMNB m(TPH CMNC a){ + return ++a; + } + + TPH CMNF m2(TPH CMNG a, TPH CMNH b){ + return this.m Signature: [TPH CMNK, TPH CMNL](a op b); + } + + TPH CMNP m3(TPH CMNQ a){ + return this.m Signature: [TPH CMNT, TPH CMNU](++a); + } + + BinaryInMeth(){ + super(()); + } + +} \ No newline at end of file diff --git a/resources/syntaxtreegenerator/Box.ast b/resources/syntaxtreegenerator/Box.ast new file mode 100644 index 00000000..1bc437b3 --- /dev/null +++ b/resources/syntaxtreegenerator/Box.ast @@ -0,0 +1,25 @@ +class B { + +B(){ + super(()); + } + B(){ + super(()); + } + +}class Box_Main { + +Box_Main(){ + super(()); + } + TPH T m(TPH U b){ + b.m Signature: [TPH W, TPH X](new Box_Main()); + b.m Signature: [TPH AB, TPH AC](new B()); + return; + } + + Box_Main(){ + super(()); + } + +} \ No newline at end of file diff --git a/resources/syntaxtreegenerator/ClassGenLam.ast b/resources/syntaxtreegenerator/ClassGenLam.ast new file mode 100644 index 00000000..30b43454 --- /dev/null +++ b/resources/syntaxtreegenerator/ClassGenLam.ast @@ -0,0 +1,14 @@ +class ClassGenLam { + + TPH HWDB lam; +ClassGenLam(){ + super(()); + this.lam = (TPH HWDC x) -> { + return x; + }; + } + ClassGenLam(){ + super(()); + } + +} \ No newline at end of file diff --git a/resources/syntaxtreegenerator/Cycle.ast b/resources/syntaxtreegenerator/Cycle.ast new file mode 100644 index 00000000..18b435a8 --- /dev/null +++ b/resources/syntaxtreegenerator/Cycle.ast @@ -0,0 +1,16 @@ +class Cycle { + +Cycle(){ + super(()); + } + TPH GGXG m(TPH GGXH x, TPH GGXI y){ + y = x; + x = y; + return; + } + + Cycle(){ + super(()); + } + +} \ No newline at end of file diff --git a/resources/syntaxtreegenerator/Fac.ast b/resources/syntaxtreegenerator/Fac.ast new file mode 100644 index 00000000..b15ecdd5 --- /dev/null +++ b/resources/syntaxtreegenerator/Fac.ast @@ -0,0 +1,22 @@ +class Fac { + +Fac(){ + super(()); + } + TPH BSTE getFac(TPH BSTF n){ + TPH BSTG res; + res = 1; + TPH BSTI i; + i = 1; + while(i op n){ + res = res op i; + i++; + }; + return res; + } + + Fac(){ + super(()); + } + +} \ No newline at end of file diff --git a/resources/syntaxtreegenerator/Faculty.ast b/resources/syntaxtreegenerator/Faculty.ast new file mode 100644 index 00000000..66c777a8 --- /dev/null +++ b/resources/syntaxtreegenerator/Faculty.ast @@ -0,0 +1,25 @@ +class Faculty { + + TPH DDAL fact; +Faculty(){ + super(()); + } + TPH DDBK getFact(java.lang.Integer x){ + return this.fact.apply Signature: [TPH DDBM, TPH DDBN](x); + } + + Faculty(){ + super(()); + this.fact = (TPH DDAO x) -> { + if(x op 1) + { + return 1; + } + else + { + return x op this.fact.apply Signature: [TPH DDAW, TPH DDAX](x op 1); + }; + }; + } + +} \ No newline at end of file diff --git a/resources/syntaxtreegenerator/Field.ast b/resources/syntaxtreegenerator/Field.ast new file mode 100644 index 00000000..43ffa1a6 --- /dev/null +++ b/resources/syntaxtreegenerator/Field.ast @@ -0,0 +1,16 @@ +class Field { + + TPH JBCG x; +Field(){ + super(()); + this.x = 5; + } + TPH JBCJ m(){ + return this.x; + } + + Field(){ + super(()); + } + +} \ No newline at end of file diff --git a/resources/syntaxtreegenerator/FieldTph2.ast b/resources/syntaxtreegenerator/FieldTph2.ast new file mode 100644 index 00000000..23c7c163 --- /dev/null +++ b/resources/syntaxtreegenerator/FieldTph2.ast @@ -0,0 +1,21 @@ +class FieldTph2 { + + TPH DJBG a; +FieldTph2(){ + super(()); + } + TPH DJBH m(TPH DJBI b){ + b = this.a; + return b; + } + + TPH DJBL m2(TPH DJBM c){ + this.a = c; + return; + } + + FieldTph2(){ + super(()); + } + +} \ No newline at end of file diff --git a/resources/syntaxtreegenerator/FieldTphConsMeth.ast b/resources/syntaxtreegenerator/FieldTphConsMeth.ast new file mode 100644 index 00000000..9ada6011 --- /dev/null +++ b/resources/syntaxtreegenerator/FieldTphConsMeth.ast @@ -0,0 +1,27 @@ +class FieldTphConsMeth { + + TPH AINS a; +FieldTphConsMeth(){ + super(()); + } + TPH AIOE id(TPH AIOF b){ + return b; + } + + TPH AIOH setA(TPH AIOI x){ + this.a = x; + return this.a; + } + + TPH AIOM m(TPH AION x, TPH AIOO y){ + x = this.id Signature: [TPH AIOQ, TPH AIOR](y); + return; + } + + FieldTphConsMeth(TPH AINU c){ + super(()); + this.a = this.id Signature: [TPH AINX, TPH AINY](c); + return; + } + +} \ No newline at end of file diff --git a/resources/syntaxtreegenerator/FieldTphMMeth.ast b/resources/syntaxtreegenerator/FieldTphMMeth.ast new file mode 100644 index 00000000..3a0cacd1 --- /dev/null +++ b/resources/syntaxtreegenerator/FieldTphMMeth.ast @@ -0,0 +1,33 @@ +class FieldTphMMeth { + + TPH HBWQ a; +FieldTphMMeth(){ + super(()); + } + TPH HBXG m(TPH HBXH b, TPH HBXI d, TPH HBXJ e){ + if(e) + { + return this.m3 Signature: [TPH HBXL, TPH HBXM](b); + } + else + { + return this.m3 Signature: [TPH HBXR, TPH HBXS](d); + }; + } + + TPH HBXY m2(TPH HBXZ b){ + this.a = this.m3 Signature: [TPH HBYC, TPH HBYD](b); + return; + } + + TPH HBYH m3(TPH HBYI b){ + return b; + } + + FieldTphMMeth(TPH HBWS c, TPH HBWT d, TPH HBWU e){ + super(()); + this.a = this.m Signature: [TPH HBWX, TPH HBWY, TPH HBWZ, TPH HBXA](c, d, e); + return; + } + +} \ No newline at end of file diff --git a/resources/syntaxtreegenerator/Gen.ast b/resources/syntaxtreegenerator/Gen.ast new file mode 100644 index 00000000..20f54843 --- /dev/null +++ b/resources/syntaxtreegenerator/Gen.ast @@ -0,0 +1,14 @@ +class Gen { + +Gen(){ + super(()); + } + java.util.Vector m(java.util.Vector v){ + return v; + } + + Gen(){ + super(()); + } + +} \ No newline at end of file diff --git a/resources/syntaxtreegenerator/Id.ast b/resources/syntaxtreegenerator/Id.ast new file mode 100644 index 00000000..4b375d27 --- /dev/null +++ b/resources/syntaxtreegenerator/Id.ast @@ -0,0 +1,18 @@ +class Id { + + TPH BDGF id2; +Id(){ + super(()); + this.id2 = (TPH BDGG x) -> { + return x; + }; + } + TPH BDGM id3(TPH BDGN x){ + return this.id2.apply Signature: [TPH BDGP, TPH BDGQ](x); + } + + Id(){ + super(()); + } + +} \ No newline at end of file diff --git a/resources/syntaxtreegenerator/Inf.ast b/resources/syntaxtreegenerator/Inf.ast new file mode 100644 index 00000000..5425c25d --- /dev/null +++ b/resources/syntaxtreegenerator/Inf.ast @@ -0,0 +1,28 @@ +class Inf { + +Inf(){ + super(()); + } + TPH KYAM m(TPH KYAN x, TPH KYAO y, TPH KYAP a){ + TPH KYAQ z; + TPH KYAR v; + TPH KYAS w; + TPH KYAT b; + y = x; + z = x; + v = y; + w = y; + y = a; + b = a; + TPH KYAU c; + TPH KYAV d; + c = v; + d = v; + return; + } + + Inf(){ + super(()); + } + +} \ No newline at end of file diff --git a/resources/syntaxtreegenerator/KompTph.ast b/resources/syntaxtreegenerator/KompTph.ast new file mode 100644 index 00000000..0cde6326 --- /dev/null +++ b/resources/syntaxtreegenerator/KompTph.ast @@ -0,0 +1,26 @@ +class KompTph { + +KompTph(){ + super(()); + } + TPH EOGX m(TPH EOGY a, TPH EOGZ b, TPH EOHA c){ + TPH EOHB d; + d = a; + TPH EOHC e; + e = a; + a = b; + c = b; + this.m2 Signature: [TPH EOHE, TPH EOHF, TPH EOHG](a, c); + return; + } + + TPH EOHK m2(TPH EOHL a, TPH EOHM b){ + this.m Signature: [TPH EOHO, TPH EOHP, TPH EOHQ, TPH EOHR](a, a, b); + return; + } + + KompTph(){ + super(()); + } + +} \ No newline at end of file diff --git a/resources/syntaxtreegenerator/Lambda.ast b/resources/syntaxtreegenerator/Lambda.ast new file mode 100644 index 00000000..1cdc8f14 --- /dev/null +++ b/resources/syntaxtreegenerator/Lambda.ast @@ -0,0 +1,18 @@ +class Lambda { + +Lambda(){ + super(()); + } + TPH KIZQ m(){ + TPH KIZR lam1; + lam1 = (TPH KIZS x) -> { + return x; + }; + return lam1; + } + + Lambda(){ + super(()); + } + +} \ No newline at end of file diff --git a/resources/syntaxtreegenerator/LambdaCapture.ast b/resources/syntaxtreegenerator/LambdaCapture.ast new file mode 100644 index 00000000..de4944bf --- /dev/null +++ b/resources/syntaxtreegenerator/LambdaCapture.ast @@ -0,0 +1,18 @@ +class LambdaCapture { + + java.lang.Integer i; + TPH BIMD f; +LambdaCapture(){ + super(()); + this.i = 8; + } + LambdaCapture(){ + super(()); + java.lang.Integer w; + w = 7; + this.f = (TPH BIMH j) -> { + return w op this.i; + }; + } + +} \ No newline at end of file diff --git a/resources/syntaxtreegenerator/Matrix.ast b/resources/syntaxtreegenerator/Matrix.ast new file mode 100644 index 00000000..f4779af2 --- /dev/null +++ b/resources/syntaxtreegenerator/Matrix.ast @@ -0,0 +1,52 @@ +class Matrix { + +Matrix(){ + super(()); + } + TPH SBB mul(TPH SBC m){ + TPH SBD ret; + ret = new Matrix(); + TPH SBF i; + i = 0; + while(i op this.size Signature: [TPH SBJ]()){ + TPH SBM v1; + v1 = this.elementAt Signature: [TPH SBO, TPH SBP](i); + TPH SBS v2; + v2 = new java.util.Vector(); + TPH SBU j; + j = 0; + while(j op v1.size Signature: [TPH SBX]()){ + TPH SCA erg; + erg = 0; + TPH SCC k; + k = 0; + while(k op v1.size Signature: [TPH SCF]()){ + erg = erg op v1.elementAt Signature: [TPH SCI, TPH SCJ](k) op m.elementAt Signature: [TPH SCM, TPH SCN](k).elementAt Signature: [TPH SCQ, TPH SCR](j); + k++; + }; + v2.addElement Signature: [TPH SCZ, TPH SDA](erg); + j++; + }; + ret.addElement Signature: [TPH SDG, TPH SDH](v2); + i++; + }; + return ret; + } + + Matrix(){ + super(()); + return; + } + + Matrix(TPH SAF vv){ + super(()); + java.lang.Integer i; + i = 0; + while(i op vv.size Signature: [TPH SAI]()){ + this.add Signature: [TPH SAQ, TPH SAR](vv.elementAt Signature: [TPH SAM, TPH SAN](i)); + i = i op 1; + }; + return; + } + +} \ No newline at end of file diff --git a/resources/syntaxtreegenerator/MatrixOP.ast b/resources/syntaxtreegenerator/MatrixOP.ast new file mode 100644 index 00000000..4ea4d5e0 --- /dev/null +++ b/resources/syntaxtreegenerator/MatrixOP.ast @@ -0,0 +1,52 @@ +class MatrixOP { + + TPH JGDT mul; +MatrixOP(){ + super(()); + this.mul = (TPH JGDU m1, TPH JGDV m2) -> { + TPH JGDW ret; + ret = new MatrixOP(); + TPH JGDY i; + i = 0; + while(i op m1.size Signature: [TPH JGEB]()){ + TPH JGEE v1; + v1 = m1.elementAt Signature: [TPH JGEF, TPH JGEG](i); + TPH JGEJ v2; + v2 = new java.util.Vector(); + TPH JGEL j; + j = 0; + while(j op v1.size Signature: [TPH JGEO]()){ + TPH JGER erg; + erg = 0; + TPH JGET k; + k = 0; + while(k op v1.size Signature: [TPH JGEW]()){ + erg = erg op v1.elementAt Signature: [TPH JGEZ, TPH JGFA](k) op m2.elementAt Signature: [TPH JGFD, TPH JGFE](k).elementAt Signature: [TPH JGFH, TPH JGFI](j); + k++; + }; + v2.addElement Signature: [TPH JGFQ, TPH JGFR](erg); + j++; + }; + ret.addElement Signature: [TPH JGFX, TPH JGFY](v2); + i++; + }; + return ret; + }; + } + MatrixOP(){ + super(()); + return; + } + + MatrixOP(TPH JGGP vv){ + super(()); + java.lang.Integer i; + i = 0; + while(i op vv.size Signature: [TPH JGGS]()){ + this.add Signature: [TPH JGHA, TPH JGHB](vv.elementAt Signature: [TPH JGGW, TPH JGGX](i)); + i = i op 1; + }; + return; + } + +} \ No newline at end of file diff --git a/resources/syntaxtreegenerator/Merge.ast b/resources/syntaxtreegenerator/Merge.ast new file mode 100644 index 00000000..c3632d11 --- /dev/null +++ b/resources/syntaxtreegenerator/Merge.ast @@ -0,0 +1,23 @@ +class Merge { + +Merge(){ + super(()); + } + TPH JQYM merge(TPH JQYN a, TPH JQYO b){ + a.addAll Signature: [TPH JQYP, TPH JQYQ](b); + return a; + } + + TPH JQYU sort(TPH JQYV in){ + TPH JQYW firstHalf; + firstHalf = in.subList Signature: [TPH JQYZ, TPH JQZA, TPH JQZB](1, 2); + TPH JQZE secondHalf; + secondHalf = in.subList Signature: [TPH JQZH, TPH JQZI, TPH JQZJ](1, 2); + return this.merge Signature: [TPH JQZX, TPH JQZY, TPH JQZZ](this.sort Signature: [TPH JQZO, TPH JQZP](firstHalf), this.sort Signature: [TPH JQZT, TPH JQZU](secondHalf)); + } + + Merge(){ + super(()); + } + +} \ No newline at end of file diff --git a/resources/syntaxtreegenerator/OL.ast b/resources/syntaxtreegenerator/OL.ast new file mode 100644 index 00000000..96ea1505 --- /dev/null +++ b/resources/syntaxtreegenerator/OL.ast @@ -0,0 +1,41 @@ +class OL { + +OL(){ + super(()); + } + java.lang.Double m(java.lang.Double x){ + return x op x; + } + + java.lang.Integer m(java.lang.Integer x){ + return x op x; + } + + java.lang.String m(java.lang.String x){ + return x op x; + } + + java.lang.Boolean m(java.lang.Boolean x){ + return x; + } + + OL(){ + super(()); + } + +}class OLMain { + +OLMain(){ + super(()); + } + TPH BYOF main(TPH BYOG x){ + TPH BYOH ol; + ol = new OL(); + return ol.m Signature: [TPH BYOJ, TPH BYOK](x); + } + + OLMain(){ + super(()); + } + +} \ No newline at end of file diff --git a/resources/syntaxtreegenerator/OLFun.ast b/resources/syntaxtreegenerator/OLFun.ast new file mode 100644 index 00000000..4f5e08f1 --- /dev/null +++ b/resources/syntaxtreegenerator/OLFun.ast @@ -0,0 +1,22 @@ +class OLFun { + +OLFun(){ + super(()); + } + TPH JXJR m(TPH JXJS f, TPH JXJT x){ + x = f.apply Signature: [TPH JXJV, TPH JXJW](x op x); + return x; + } + + TPH JXKA m2(TPH JXKB y){ + this.m Signature: [TPH JXKK, TPH JXKL, TPH JXKM]((TPH JXKD x) -> { + return x op 2; + }, y); + return; + } + + OLFun(){ + super(()); + } + +} \ No newline at end of file diff --git a/resources/syntaxtreegenerator/OLFun2.ast b/resources/syntaxtreegenerator/OLFun2.ast new file mode 100644 index 00000000..57415e3d --- /dev/null +++ b/resources/syntaxtreegenerator/OLFun2.ast @@ -0,0 +1,16 @@ +class OLFun2 { + + TPH CTXA x; +OLFun2(){ + super(()); + } + TPH CTXB m(TPH CTXC f){ + this.x = f.apply Signature: [TPH CTXH, TPH CTXI](this.x op this.x); + return; + } + + OLFun2(){ + super(()); + } + +} \ No newline at end of file diff --git a/resources/syntaxtreegenerator/Overloading.ast b/resources/syntaxtreegenerator/Overloading.ast new file mode 100644 index 00000000..29fd0bb1 --- /dev/null +++ b/resources/syntaxtreegenerator/Overloading.ast @@ -0,0 +1,31 @@ +class Overloading { + +Overloading(){ + super(()); + } + TPH N test(TPH O x){ + return x.methode Signature: [TPH P](); + } + + TPH T methode(){ + return Overloading; + } + + Overloading(){ + super(()); + } + +}class Overloading2 { + +Overloading2(){ + super(()); + } + TPH AO methode(){ + return Overloading2; + } + + Overloading2(){ + super(()); + } + +} \ No newline at end of file diff --git a/resources/syntaxtreegenerator/Pair.ast b/resources/syntaxtreegenerator/Pair.ast new file mode 100644 index 00000000..67a01833 --- /dev/null +++ b/resources/syntaxtreegenerator/Pair.ast @@ -0,0 +1,20 @@ +class Pair { + + U a; + T b; +Pair(){ + super(()); + } + TPH IURS make(TPH IURT x){ + TPH IURU ret; + ret = new Pair(); + ret.a = x.elementAt Signature: [TPH IUSA, TPH IUSB](0); + ret.b = x.elementAt Signature: [TPH IUSG, TPH IUSH](1); + return ret; + } + + Pair(){ + super(()); + } + +} \ No newline at end of file diff --git a/resources/syntaxtreegenerator/Plus.ast b/resources/syntaxtreegenerator/Plus.ast new file mode 100644 index 00000000..c395f007 --- /dev/null +++ b/resources/syntaxtreegenerator/Plus.ast @@ -0,0 +1,14 @@ +class Plus { + +Plus(){ + super(()); + } + TPH ACHZ m(TPH ACIA a, TPH ACIB b){ + return a op b; + } + + Plus(){ + super(()); + } + +} \ No newline at end of file diff --git a/resources/syntaxtreegenerator/RelOps.ast b/resources/syntaxtreegenerator/RelOps.ast new file mode 100644 index 00000000..4b8fa1dd --- /dev/null +++ b/resources/syntaxtreegenerator/RelOps.ast @@ -0,0 +1,14 @@ +class RelOps { + +RelOps(){ + super(()); + } + TPH IPBY m(TPH IPBZ a, TPH IPCA b){ + return a op b; + } + + RelOps(){ + super(()); + } + +} \ No newline at end of file diff --git a/resources/syntaxtreegenerator/Scalar.ast b/resources/syntaxtreegenerator/Scalar.ast new file mode 100644 index 00000000..fddde3ad --- /dev/null +++ b/resources/syntaxtreegenerator/Scalar.ast @@ -0,0 +1,29 @@ +class Scalar { + +Scalar(){ + super(()); + } + TPH KOXT mul(TPH KOXU v){ + TPH KOXV ret; + ret = 0; + TPH KOXX i; + i = 0; + while(i op this.size Signature: [TPH KOYB]()){ + ret = ret op this.elementAt Signature: [TPH KOYF, TPH KOYG](i) op v.elementAt Signature: [TPH KOYJ, TPH KOYK](i); + i = i op 1; + }; + return ret; + } + + Scalar(TPH KOWX v){ + super(()); + java.lang.Integer i; + i = 0; + while(i op v.size Signature: [TPH KOXA]()){ + this.add Signature: [TPH KOXI, TPH KOXJ](v.elementAt Signature: [TPH KOXE, TPH KOXF](i)); + i = i op 1; + }; + return; + } + +} \ No newline at end of file diff --git a/resources/syntaxtreegenerator/SimpleCycle.ast b/resources/syntaxtreegenerator/SimpleCycle.ast new file mode 100644 index 00000000..771757a9 --- /dev/null +++ b/resources/syntaxtreegenerator/SimpleCycle.ast @@ -0,0 +1,18 @@ +class SimpleCycle { + +SimpleCycle(){ + super(()); + } + TPH ETMJ m(){ + TPH ETMK g; + TPH ETML h; + g = h; + h = g; + return; + } + + SimpleCycle(){ + super(()); + } + +} \ No newline at end of file diff --git a/resources/syntaxtreegenerator/Sorting.ast b/resources/syntaxtreegenerator/Sorting.ast new file mode 100644 index 00000000..979d2687 --- /dev/null +++ b/resources/syntaxtreegenerator/Sorting.ast @@ -0,0 +1,23 @@ +class Sorting { + +Sorting(){ + super(()); + } + TPH JNN merge(TPH JNO a, TPH JNP b){ + a.addAll Signature: [TPH JNQ, TPH JNR](b); + return a; + } + + TPH JNV sort(TPH JNW in){ + TPH JNX firstHalf; + firstHalf = in; + TPH JNY secondHalf; + secondHalf = in; + return this.merge Signature: [TPH JOK, TPH JOL, TPH JOM](this.sort Signature: [TPH JOB, TPH JOC](firstHalf), this.sort Signature: [TPH JOG, TPH JOH](secondHalf)); + } + + Sorting(){ + super(()); + } + +} \ No newline at end of file diff --git a/resources/syntaxtreegenerator/SubMatrix.ast b/resources/syntaxtreegenerator/SubMatrix.ast new file mode 100644 index 00000000..61ab2f22 --- /dev/null +++ b/resources/syntaxtreegenerator/SubMatrix.ast @@ -0,0 +1,26 @@ +class Matrix2 { + +Matrix2(){ + super(()); + } + Matrix2(){ + super(()); + } + +}class SubMatrix { + +SubMatrix(){ + super(()); + } + TPH DOFK m(){ + java.util.Vector v; + v = new java.util.Vector(); + v.add Signature: [TPH DOFN, TPH DOFO](1); + return; + } + + SubMatrix(){ + super(()); + } + +} \ No newline at end of file diff --git a/resources/syntaxtreegenerator/TXGenerics.ast b/resources/syntaxtreegenerator/TXGenerics.ast new file mode 100644 index 00000000..1c4a0eab --- /dev/null +++ b/resources/syntaxtreegenerator/TXGenerics.ast @@ -0,0 +1,19 @@ +class TXGenerics { + + TPH GLEG a; + TPH GLEH b; +TXGenerics(){ + super(()); + } + TPH GLEI test(){ + TPH GLEJ c; + c = new Cycle(); + c.m Signature: [TPH GLEN, TPH GLEO, TPH GLEP](this.a, this.b); + return; + } + + TXGenerics(){ + super(()); + } + +} \ No newline at end of file diff --git a/resources/syntaxtreegenerator/Tph.ast b/resources/syntaxtreegenerator/Tph.ast new file mode 100644 index 00000000..939f9a57 --- /dev/null +++ b/resources/syntaxtreegenerator/Tph.ast @@ -0,0 +1,20 @@ +class Tph { + +Tph(){ + super(()); + } + TPH BNOP m(TPH BNOQ a, TPH BNOR b){ + TPH BNOS c; + c = this.m2 Signature: [TPH BNOU, TPH BNOV](b); + return a; + } + + TPH BNOZ m2(TPH BNPA b){ + return b; + } + + Tph(){ + super(()); + } + +} \ No newline at end of file diff --git a/resources/syntaxtreegenerator/Tph2.ast b/resources/syntaxtreegenerator/Tph2.ast new file mode 100644 index 00000000..f138866a --- /dev/null +++ b/resources/syntaxtreegenerator/Tph2.ast @@ -0,0 +1,18 @@ +class Tph2 { + + TPH FGYW id; +Tph2(){ + super(()); + this.id = (TPH FGYX x) -> { + return x; + }; + } + TPH FGZD id3(TPH FGZE x){ + return this.id.apply Signature: [TPH FGZG, TPH FGZH](x); + } + + Tph2(){ + super(()); + } + +} \ No newline at end of file diff --git a/resources/syntaxtreegenerator/Tph3.ast b/resources/syntaxtreegenerator/Tph3.ast new file mode 100644 index 00000000..cfbf0bc3 --- /dev/null +++ b/resources/syntaxtreegenerator/Tph3.ast @@ -0,0 +1,21 @@ +class Tph3 { + +Tph3(){ + super(()); + } + TPH FMEJ m1(TPH FMEK x, TPH FMEL y){ + this.m2 Signature: [TPH FMEN, TPH FMEO](x); + x = y; + return; + } + + TPH FMES m2(TPH FMET y){ + this.m1 Signature: [TPH FMEV, TPH FMEW, TPH FMEX](y, y); + return; + } + + Tph3(){ + super(()); + } + +} \ No newline at end of file diff --git a/resources/syntaxtreegenerator/Tph4.ast b/resources/syntaxtreegenerator/Tph4.ast new file mode 100644 index 00000000..2ed453b8 --- /dev/null +++ b/resources/syntaxtreegenerator/Tph4.ast @@ -0,0 +1,22 @@ +class Tph4 { + +Tph4(){ + super(()); + } + TPH FRJD m(TPH FRJE a, TPH FRJF b){ + TPH FRJG c; + c = this.m2 Signature: [TPH FRJI, TPH FRJJ](b); + TPH FRJM d; + d = this.m2 Signature: [TPH FRJO, TPH FRJP](c); + return d; + } + + TPH FRJT m2(TPH FRJU b){ + return b; + } + + Tph4(){ + super(()); + } + +} \ No newline at end of file diff --git a/resources/syntaxtreegenerator/Tph5.ast b/resources/syntaxtreegenerator/Tph5.ast new file mode 100644 index 00000000..dfdda9d1 --- /dev/null +++ b/resources/syntaxtreegenerator/Tph5.ast @@ -0,0 +1,19 @@ +class Tph5 { + +Tph5(){ + super(()); + } + TPH FWNY m(TPH FWNZ x, TPH FWOA y){ + x = this.m2 Signature: [TPH FWOC, TPH FWOD](y); + return; + } + + TPH FWOH m2(TPH FWOI y){ + return y; + } + + Tph5(){ + super(()); + } + +} \ No newline at end of file diff --git a/resources/syntaxtreegenerator/Tph6.ast b/resources/syntaxtreegenerator/Tph6.ast new file mode 100644 index 00000000..eba65bc1 --- /dev/null +++ b/resources/syntaxtreegenerator/Tph6.ast @@ -0,0 +1,21 @@ +class Tph6 { + +Tph6(){ + super(()); + } + TPH GBSM m(TPH GBSN x, TPH GBSO y){ + TPH GBSP c; + c = this.m2 Signature: [TPH GBSR, TPH GBSS](y); + c = this.m2 Signature: [TPH GBSW, TPH GBSX](x); + return; + } + + TPH GBTB m2(TPH GBTC y){ + return y; + } + + Tph6(){ + super(()); + } + +} \ No newline at end of file diff --git a/resources/syntaxtreegenerator/Tph7.ast b/resources/syntaxtreegenerator/Tph7.ast new file mode 100644 index 00000000..8d2ebe4b --- /dev/null +++ b/resources/syntaxtreegenerator/Tph7.ast @@ -0,0 +1,20 @@ +class Tph7 { + +Tph7(){ + super(()); + } + TPH GQRI m(TPH GQRJ a, TPH GQRK b){ + TPH GQRL c; + c = this.m2 Signature: [TPH GQRN, TPH GQRO](b); + return this.m2 Signature: [TPH GQRS, TPH GQRT](b); + } + + TPH GQRX m2(TPH GQRY b){ + return b; + } + + Tph7(){ + super(()); + } + +} \ No newline at end of file diff --git a/resources/syntaxtreegenerator/TypedID.ast b/resources/syntaxtreegenerator/TypedID.ast new file mode 100644 index 00000000..0a56861d --- /dev/null +++ b/resources/syntaxtreegenerator/TypedID.ast @@ -0,0 +1,22 @@ +class TypedID { + + TPH GVWK lam; +TypedID(){ + super(()); + this.lam = (TPH GVWL x) -> { + return x; + }; + } + TPH GVWR id(TPH GVWS b){ + return b; + } + + TPH GVWU m(){ + return this.lam; + } + + TypedID(){ + super(()); + } + +} \ No newline at end of file diff --git a/resources/syntaxtreegenerator/VectorAdd.ast b/resources/syntaxtreegenerator/VectorAdd.ast new file mode 100644 index 00000000..992c9c1e --- /dev/null +++ b/resources/syntaxtreegenerator/VectorAdd.ast @@ -0,0 +1,31 @@ +class VectorAdd { + +VectorAdd(){ + super(()); + } + TPH EXVJ vectorAdd(TPH EXVK v1, TPH EXVL v2){ + TPH EXVM i; + i = 0; + v1 = new java.util.Vector(); + TPH EXVP erg; + erg = new java.util.Vector(); + while(i op v1.size Signature: [TPH EXVT]()){ + erg.addElement Signature: [TPH EXWF, TPH EXWG](v1.elementAt Signature: [TPH EXVW, TPH EXVX](i) op v2.elementAt Signature: [TPH EXWA, TPH EXWB](i)); + i++; + }; + return erg; + } + + TPH EXWN m(TPH EXWO x, TPH EXWP y, TPH EXWQ z){ + x = new java.util.Vector(); + y = new java.util.Vector(); + x.add Signature: [TPH EXWU, TPH EXWV](1); + y.add Signature: [TPH EXWY, TPH EXWZ](2); + return z.addAll Signature: [TPH EXXC, TPH EXXD](x); + } + + VectorAdd(){ + super(()); + } + +} \ No newline at end of file diff --git a/resources/syntaxtreegenerator/VectorSuper.ast b/resources/syntaxtreegenerator/VectorSuper.ast new file mode 100644 index 00000000..ec2faf35 --- /dev/null +++ b/resources/syntaxtreegenerator/VectorSuper.ast @@ -0,0 +1,17 @@ +class VectorSuper { + +VectorSuper(){ + super(()); + } + TPH HPGR m(TPH HPGS x){ + java.lang.Integer y; + y = 1; + x.addElement Signature: [TPH HPGU, TPH HPGV](y); + return; + } + + VectorSuper(){ + super(()); + } + +} \ No newline at end of file diff --git a/resources/syntaxtreegenerator/Y.ast b/resources/syntaxtreegenerator/Y.ast new file mode 100644 index 00000000..6a736191 --- /dev/null +++ b/resources/syntaxtreegenerator/Y.ast @@ -0,0 +1,16 @@ +class Y { + + TPH IBFH y; +Y(){ + super(()); + } + Y(){ + super(()); + this.y = (TPH IBFK f) -> { + return (TPH IBFL t) -> { + return f.apply Signature: [TPH IBFR, TPH IBFS](this.y.apply Signature: [TPH IBFN, TPH IBFO](f)).apply Signature: [TPH IBFV, TPH IBFW](t); + }; + }; + } + +} \ No newline at end of file diff --git a/resources/syntaxtreegenerator/applyLambda.ast b/resources/syntaxtreegenerator/applyLambda.ast new file mode 100644 index 00000000..504dddec --- /dev/null +++ b/resources/syntaxtreegenerator/applyLambda.ast @@ -0,0 +1,27 @@ +class Apply { + +Apply(){ + super(()); + } + Apply(){ + super(()); + } + +}class applyLambda { + +applyLambda(){ + super(()); + } + TPH ASWH m(){ + TPH ASWI lam1; + lam1 = (TPH ASWJ x) -> { + return x; + }; + return lam1.apply Signature: [TPH ASWP, TPH ASWQ](new Apply()); + } + + applyLambda(){ + super(()); + } + +} \ No newline at end of file diff --git a/resources/syntaxtreegenerator/mathStruc.ast b/resources/syntaxtreegenerator/mathStruc.ast new file mode 100644 index 00000000..85318505 --- /dev/null +++ b/resources/syntaxtreegenerator/mathStruc.ast @@ -0,0 +1,19 @@ +class mathStruc { + + TPH IHHZ model; + TPH IHIA innerOp; +mathStruc(){ + super(()); + this.innerOp = (TPH IHIB o) -> { + return (TPH IHIC ms) -> { + return new mathStruc(o.apply Signature: [TPH IHIF, TPH IHIG, TPH IHIH](this.model, ms.model)); + }; + }; + } + mathStruc(TPH IHIW m){ + super(()); + this.model = m; + return; + } + +} \ No newline at end of file diff --git a/resources/syntaxtreegenerator/mathStrucInteger.ast b/resources/syntaxtreegenerator/mathStrucInteger.ast new file mode 100644 index 00000000..c36d537a --- /dev/null +++ b/resources/syntaxtreegenerator/mathStrucInteger.ast @@ -0,0 +1,38 @@ +class mathStrucInteger { + + TPH EBJW model; + TPH EBJX innerOp; +mathStrucInteger(){ + super(()); + this.innerOp = (TPH EBJY o) -> { + return (TPH EBJZ ms) -> { + return new mathStrucInteger(o.apply Signature: [TPH EBKC, TPH EBKD, TPH EBKE](this.model, ms.model)); + }; + }; + } + mathStrucInteger(TPH EBKT m){ + super(()); + this.model = m; + return; + } + +}class mathStrucIntegerUse { + +mathStrucIntegerUse(){ + super(()); + } + TPH EBLO main(){ + TPH EBLP ms; + ms = new mathStrucInteger(2); + TPH EBLT ms2; + ms2 = ms.innerOp.apply Signature: [TPH EBMD, TPH EBME]((TPH EBLV x, TPH EBLW y) -> { + return x op y; + }).apply Signature: [TPH EBMH, TPH EBMI](ms); + return ms2; + } + + mathStrucIntegerUse(){ + super(()); + } + +} \ No newline at end of file diff --git a/resources/testBytecode/generatedBC/.gitignore b/resources/testBytecode/generatedBC/.gitignore deleted file mode 100644 index 5e7d2734..00000000 --- a/resources/testBytecode/generatedBC/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -# Ignore everything in this directory -* -# Except this file -!.gitignore diff --git a/resources/testBytecode/public b/resources/testBytecode/public deleted file mode 100644 index 8b137891..00000000 --- a/resources/testBytecode/public +++ /dev/null @@ -1 +0,0 @@ - diff --git a/src/main/antlr4/de/dhbwstuttgart/parser/antlr/Java17Lexer.g4 b/src/main/antlr4/de/dhbwstuttgart/parser/antlr/Java17Lexer.g4 new file mode 100644 index 00000000..7be32dad --- /dev/null +++ b/src/main/antlr4/de/dhbwstuttgart/parser/antlr/Java17Lexer.g4 @@ -0,0 +1,241 @@ +/* + [The "BSD licence"] + Copyright (c) 2013 Terence Parr, Sam Harwell + Copyright (c) 2017 Ivan Kochurkin (upgrade to Java 8) + Copyright (c) 2021 Michał Lorek (upgrade to Java 11) + Copyright (c) 2022 Michał Lorek (upgrade to Java 17) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. The name of the author may not be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +lexer grammar Java17Lexer; + +// Keywords + +ABSTRACT: 'abstract'; +ASSERT: 'assert'; +BOOLEAN: 'boolean'; +BREAK: 'break'; +BYTE: 'byte'; +CASE: 'case'; +CATCH: 'catch'; +CHAR: 'char'; +CLASS: 'class'; +CONST: 'const'; +CONTINUE: 'continue'; +DEFAULT: 'default'; +DO: 'do'; +DOUBLE: 'double'; +ELSE: 'else'; +ENUM: 'enum'; +EXTENDS: 'extends'; +FINAL: 'final'; +FINALLY: 'finally'; +FLOAT: 'float'; +FOR: 'for'; +IF: 'if'; +GOTO: 'goto'; +IMPLEMENTS: 'implements'; +IMPORT: 'import'; +INSTANCEOF: 'instanceof'; +INT: 'int'; +INTERFACE: 'interface'; +LONG: 'long'; +NATIVE: 'native'; +NEW: 'new'; +PACKAGE: 'package'; +PRIVATE: 'private'; +PROTECTED: 'protected'; +PUBLIC: 'public'; +RETURN: 'return'; +SHORT: 'short'; +STATIC: 'static'; +STRICTFP: 'strictfp'; +SUPER: 'super'; +SWITCH: 'switch'; +SYNCHRONIZED: 'synchronized'; +THIS: 'this'; +THROW: 'throw'; +THROWS: 'throws'; +TRANSIENT: 'transient'; +TRY: 'try'; +VOID: 'void'; +VOLATILE: 'volatile'; +WHILE: 'while'; + +// Module related keywords +MODULE: 'module'; +OPEN: 'open'; +REQUIRES: 'requires'; +EXPORTS: 'exports'; +OPENS: 'opens'; +TO: 'to'; +USES: 'uses'; +PROVIDES: 'provides'; +WITH: 'with'; +TRANSITIVE: 'transitive'; + +// Local Variable Type Inference +VAR: 'var'; // reserved type name + +// Switch Expressions +YIELD: 'yield'; // reserved type name from Java 14 + +// Records +RECORD: 'record'; + +// Sealed Classes +SEALED: 'sealed'; +PERMITS: 'permits'; +NON_SEALED: 'non-sealed'; + +// Literals + +DECIMAL_LITERAL: ('0' | [1-9] (Digits? | '_'+ Digits)) [lL]?; +HEX_LITERAL: '0' [xX] [0-9a-fA-F] ([0-9a-fA-F_]* [0-9a-fA-F])? [lL]?; +OCT_LITERAL: '0' '_'* [0-7] ([0-7_]* [0-7])? [lL]?; +BINARY_LITERAL: '0' [bB] [01] ([01_]* [01])? [lL]?; + +FLOAT_LITERAL: (Digits '.' Digits? | '.' Digits) ExponentPart? [fFdD]? + | Digits (ExponentPart [fFdD]? | [fFdD]) + ; + +HEX_FLOAT_LITERAL: '0' [xX] (HexDigits '.'? | HexDigits? '.' HexDigits) [pP] [+-]? Digits [fFdD]?; + +BOOL_LITERAL: 'true' + | 'false' + ; + +CHAR_LITERAL: '\'' (~['\\\r\n] | EscapeSequence) '\''; + +STRING_LITERAL: '"' (~["\\\r\n] | EscapeSequence)* '"'; + +TEXT_BLOCK: '"""' [ \t]* [\r\n] (. | EscapeSequence)*? '"""'; + +NULL_LITERAL: 'null'; + +// Separators + +LPAREN: '('; +RPAREN: ')'; +LBRACE: '{'; +RBRACE: '}'; +LBRACK: '['; +RBRACK: ']'; +SEMI: ';'; +COMMA: ','; +DOT: '.'; + +// Operators + +ASSIGN: '='; +GT: '>'; +LT: '<'; +BANG: '!'; +TILDE: '~'; +QUESTION: '?'; +COLON: ':'; +EQUAL: '=='; +LE: '<='; +GE: '>='; +NOTEQUAL: '!='; +AND: '&&'; +OR: '||'; +INC: '++'; +DEC: '--'; +ADD: '+'; +SUB: '-'; +MUL: '*'; +DIV: '/'; +BITAND: '&'; +BITOR: '|'; +CARET: '^'; +MOD: '%'; + +ADD_ASSIGN: '+='; +SUB_ASSIGN: '-='; +MUL_ASSIGN: '*='; +DIV_ASSIGN: '/='; +AND_ASSIGN: '&='; +OR_ASSIGN: '|='; +XOR_ASSIGN: '^='; +MOD_ASSIGN: '%='; +LSHIFT_ASSIGN: '<<='; +RSHIFT_ASSIGN: '>>='; +URSHIFT_ASSIGN: '>>>='; + +// Java 8 tokens + +ARROW: '->'; +COLONCOLON: '::'; + +// Additional symbols not defined in the lexical specification + +AT: '@'; +ELLIPSIS: '...'; + +// Whitespace and comments + +WS: [ \t\r\n\u000C]+ -> channel(HIDDEN); +COMMENT: '/*' .*? '*/' -> channel(HIDDEN); +LINE_COMMENT: '//' ~[\r\n]* -> channel(HIDDEN); + +// Identifiers + +IDENTIFIER: Letter LetterOrDigit*; + +// Fragment rules + +fragment ExponentPart + : [eE] [+-]? Digits + ; + +fragment EscapeSequence + : '\\' [btnfr"'\\] + | '\\' ([0-3]? [0-7])? [0-7] + | '\\' 'u'+ HexDigit HexDigit HexDigit HexDigit + ; + +fragment HexDigits + : HexDigit ((HexDigit | '_')* HexDigit)? + ; + +fragment HexDigit + : [0-9a-fA-F] + ; + +fragment Digits + : [0-9] ([0-9_]* [0-9])? + ; + +fragment LetterOrDigit + : Letter + | [0-9] + ; + +fragment Letter + : [a-zA-Z$_] // these are the "java letters" below 0x7F + | ~[\u0000-\u007F\uD800-\uDBFF] // covers all characters above 0x7F which are not a surrogate + | [\uD800-\uDBFF] [\uDC00-\uDFFF] // covers UTF-16 surrogate pairs encodings for U+10000 to U+10FFFF + ; \ No newline at end of file diff --git a/src/main/antlr4/de/dhbwstuttgart/parser/antlr/Java17Parser.g4 b/src/main/antlr4/de/dhbwstuttgart/parser/antlr/Java17Parser.g4 new file mode 100644 index 00000000..966b4458 --- /dev/null +++ b/src/main/antlr4/de/dhbwstuttgart/parser/antlr/Java17Parser.g4 @@ -0,0 +1,812 @@ +/* + [The "BSD licence"] + Copyright (c) 2013 Terence Parr, Sam Harwell + Copyright (c) 2017 Ivan Kochurkin (upgrade to Java 8) + Copyright (c) 2021 Michał Lorek (upgrade to Java 11) + Copyright (c) 2022 Michał Lorek (upgrade to Java 17) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. The name of the author may not be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +parser grammar Java17Parser; + +options { tokenVocab=Java17Lexer; } + +sourceFile + : packageDeclaration? importDeclaration* classOrInterface* # srcfile + | moduleDeclaration EOF # moduledecl + ; + +packageDeclaration + : annotation* PACKAGE qualifiedName ';' + ; + +importDeclaration + : IMPORT STATIC? qualifiedName ('.' '*')? ';' + ; + +classOrInterface + : classOrInterfaceModifier* + (classDeclaration | enumDeclaration | interfaceDeclaration | annotationTypeDeclaration | recordDeclaration) # classorinterfacedecl + | ';' # noclassorinterface + ; + +modifier + : classOrInterfaceModifier + | NATIVE + | SYNCHRONIZED + | TRANSIENT + | VOLATILE + ; + +classOrInterfaceModifier + : annotation + | PUBLIC + | PROTECTED + | PRIVATE + | STATIC + | ABSTRACT + | FINAL // FINAL for class only -- does not apply to interfaces + | STRICTFP + | SEALED // Java17 + | NON_SEALED // Java17 + ; + +variableModifier + : FINAL # finalvarmod + | annotation # annotationvarmod + ; + +classDeclaration + : CLASS identifier genericDeclarationList? + (EXTENDS typeType)? + (IMPLEMENTS typeList)? + (PERMITS typeList)? // Java17 + classBody + ; + +genericDeclarationList + : '<' genericTypeVar (',' genericTypeVar)* '>' + ; + +genericTypeVar + : annotation* identifier ((EXTENDS | IMPLEMENTS) annotation* typeBound)? + ; + +typeBound + : typeType ('&' typeType)* + ; + +enumDeclaration + : ENUM identifier (IMPLEMENTS typeList)? '{' enumConstants? ','? enumBodyDeclarations? '}' + ; + +enumConstants + : enumConstant (',' enumConstant)* + ; + +enumConstant + : annotation* identifier arguments? classBody? + ; + +enumBodyDeclarations + : ';' classBodyDeclaration* + ; + +interfaceDeclaration + : INTERFACE identifier genericDeclarationList? (EXTENDS typeList)? (PERMITS typeList)? interfaceBody + ; + +classBody + : '{' classBodyDeclaration* '}' + ; + +interfaceBody + : '{' interfaceBodyDeclaration* '}' + ; + +classBodyDeclaration + : ';' # emptyclassbody + | STATIC? block # classblock + | modifier* memberDeclaration # memberdecl + ; + +memberDeclaration + : classOrInterface # memberclassorinterface + | fieldDeclaration # memberfield + | method # membermethod + | constructor # memberconstructor + ; + +method + : methodDeclaration # methoddecl + | genericMethodDeclaration # genericmethod + ; + +/* We use rule this even for void methods which cannot have [] after parameters. + This simplifies grammar and we can consider void to be a type, which + renders the [] matching as a context-sensitive issue or a semantic check + for invalid return type after parsing. + */ +methodDeclaration + : methodHeader + (THROWS exceptionList)? + methodBody + ; + +methodHeader + : refType? identifier formalParameters ('[' ']')* + ; + +methodBody + : block # methodblock + | ';' # emptymethod + ; + +refType + : typeType # reftype + | VOID # refvoid + ; + +genericMethodDeclaration + : genericDeclarationList methodDeclaration + ; + +constructor + : genericConstructorDeclaration # genericconstructor + | constructorDeclaration # constructordecl + ; + +genericConstructorDeclaration + : genericDeclarationList constructorDeclaration + ; + +constructorDeclaration + : identifier formalParameters (THROWS exceptionList)? constructorBody=block + ; + +fieldDeclaration + : typeType? variableDeclarators ';' + ; + +interfaceBodyDeclaration + : modifier* interfaceMemberDeclaration # interfacemember + | ';' # emptyinterface + ; + +interfaceMemberDeclaration + : constDeclaration # interfaceconst + | interfaceMethodDeclaration # interfacemethod + | genericInterfaceMethodDeclaration # genericinterfacemethod + | interfaceDeclaration # subinterface + | annotationTypeDeclaration # interfaceannotationtype + | classDeclaration # interfaceclass + | enumDeclaration # interfaceenum + | recordDeclaration # interfacerecord // Java17 + ; + +constDeclaration + : typeType? constantDeclarator (',' constantDeclarator)* ';' + ; + +constantDeclarator + : identifier ('[' ']')* '=' variableInitializer + ; + +// Early versions of Java allows brackets after the method name, eg. +// public int[] return2DArray() [] { ... } +// is the same as +// public int[][] return2DArray() { ... } +interfaceMethodDeclaration + : interfaceMethodModifier* interfaceCommonBodyDeclaration + ; + +// Java8 +interfaceMethodModifier + : annotation + | PUBLIC + | ABSTRACT + | DEFAULT + | STATIC + | STRICTFP + ; + +genericInterfaceMethodDeclaration + : interfaceMethodModifier* genericDeclarationList interfaceCommonBodyDeclaration + ; + +interfaceCommonBodyDeclaration + : annotation* refType? identifier formalParameters ('[' ']')* (THROWS exceptionList)? methodBody + ; + +variableDeclarators + : variableDeclarator (',' variableDeclarator)* + ; + +variableDeclarator + : variableDeclaratorId ('=' variableInitializer)? + ; + +variableDeclaratorId + : identifier ('[' ']')* + ; + +variableInitializer + : arrayInitializer + | expression + ; + +arrayInitializer + : '{' (variableInitializer (',' variableInitializer)* (',')? )? '}' + ; + +classOrInterfaceType + : (identifier typeArguments? '.')* typeIdentifier typeArguments? + ; + +typeArgument + : typeType + | wildcardType + ; + +wildcardType + : annotation* '?' (extendsWildcardType | superWildcardType)? + ; + +extendsWildcardType + : EXTENDS typeType + ; + +superWildcardType + : SUPER typeType + ; + +qualifiedNameList + : qualifiedName (',' qualifiedName)* + ; + +exceptionList + : qualifiedNameList + ; + +formalParameters + : '(' ( receiverParameter? + | receiverParameter (',' formalParameterList)? + | formalParameterList? + ) ')' + ; + +receiverParameter + : typeType? (identifier '.')* THIS + ; + +formalParameterList + : formalParameter (',' formalParameter)* (',' lastFormalParameter)? + | lastFormalParameter + ; + +formalParameter + : variableModifier* typeType? variableDeclaratorId + ; + +lastFormalParameter + : variableModifier* typeType? annotation* '...' variableDeclaratorId + ; + +// local variable type inference +lambdaLVTIList + : lambdaLVTIParameter (',' lambdaLVTIParameter)* + ; + +lambdaLVTIParameter + : variableModifier* VAR identifier + ; + +qualifiedName + : identifier ('.' identifier)* + ; + +literal + : integerLiteral # intLiteral + | floatLiteral # fltLiteral + | CHAR_LITERAL # charLiteral + | STRING_LITERAL # stringLiteral + | BOOL_LITERAL # boolLiteral + | NULL_LITERAL # nullLiteral + | TEXT_BLOCK # textBlock // Java17 + ; + +integerLiteral + : DECIMAL_LITERAL + | HEX_LITERAL + | OCT_LITERAL + | BINARY_LITERAL + ; + +floatLiteral + : FLOAT_LITERAL + | HEX_FLOAT_LITERAL + ; + +// ANNOTATIONS +altAnnotationQualifiedName + : (identifier DOT)* '@' identifier + ; + +annotation + : ('@' qualifiedName | altAnnotationQualifiedName) ('(' ( elementValuePairs | elementValue )? ')')? + ; + +elementValuePairs + : elementValuePair (',' elementValuePair)* + ; + +elementValuePair + : identifier '=' elementValue + ; + +elementValue + : expression + | annotation + | elementValueArrayInitializer + ; + +elementValueArrayInitializer + : '{' (elementValue (',' elementValue)*)? (',')? '}' + ; + +annotationTypeDeclaration + : '@' INTERFACE identifier annotationTypeBody + ; + +annotationTypeBody + : '{' (annotationTypeElementDeclaration)* '}' + ; + +annotationTypeElementDeclaration + : modifier* annotationTypeElementRest + | ';' // this is not allowed by the grammar, but apparently allowed by the actual compiler + ; + +annotationTypeElementRest + : typeType annotationMethodOrConstantRest ';' + | classDeclaration ';'? + | interfaceDeclaration ';'? + | enumDeclaration ';'? + | annotationTypeDeclaration ';'? + | recordDeclaration ';'? // Java17 + ; + +annotationMethodOrConstantRest + : annotationMethodRest + | annotationConstantRest + ; + +annotationMethodRest + : identifier '(' ')' defaultValue? + ; + +annotationConstantRest + : variableDeclarators + ; + +defaultValue + : DEFAULT elementValue + ; + +// MODULES - Java9 + +moduleDeclaration + : OPEN? MODULE qualifiedName moduleBody + ; + +moduleBody + : '{' moduleDirective* '}' + ; + +moduleDirective + : REQUIRES requiresModifier* qualifiedName ';' + | EXPORTS qualifiedName (TO qualifiedName)? ';' + | OPENS qualifiedName (TO qualifiedName)? ';' + | USES qualifiedName ';' + | PROVIDES qualifiedName WITH qualifiedName ';' + ; + +requiresModifier + : TRANSITIVE + | STATIC + ; + +// RECORDS - Java 17 + +recordDeclaration + : RECORD identifier genericDeclarationList? recordHeader + (IMPLEMENTS typeList)? + recordBody + ; + +recordHeader + : '(' recordComponentList? ')' + ; + +recordComponentList + : recordComponent (',' recordComponent)* + ; + +recordComponent + : typeType? identifier + ; + +recordBody + : '{' classBodyDeclaration* '}' + ; + +// STATEMENTS / BLOCKS + +block + : '{' blockStatement* '}' + ; + +blockStatement + : localVariableDeclaration ';' + | localTypeDeclaration + | statement + ; + +localVariableDeclaration + : variableModifier* (VAR | typeType) variableDeclarators + ; + +identifier + : IDENTIFIER + | MODULE + | OPEN + | REQUIRES + | EXPORTS + | OPENS + | TO + | USES + | PROVIDES + | WITH + | TRANSITIVE + | YIELD + | SEALED + | PERMITS + | RECORD + | VAR + ; + +typeIdentifier // Identifiers that are not restricted for type declarations + : IDENTIFIER + | MODULE + | OPEN + | REQUIRES + | EXPORTS + | OPENS + | TO + | USES + | PROVIDES + | WITH + | TRANSITIVE + | SEALED + | PERMITS + | RECORD + ; + +localTypeDeclaration + : classOrInterfaceModifier* + (classDeclaration | interfaceDeclaration | recordDeclaration) + | ';' + ; + +statement + : blockLabel=block #blockstmt + | ASSERT expression (':' expression)? ';' #assertstmt + | IF parExpression statement (ELSE statement)? #conditionalstmt + | FOR '(' forControl ')' statement #forloop + | WHILE parExpression statement #whileloop + | DO statement WHILE parExpression ';' #dowhileloop + | TRY block (catchClause+ finallyBlock? | finallyBlock) #trycatchblock + | TRY resourceSpecification block catchClause* finallyBlock? #trycatchresource + | SWITCH parExpression '{' switchBlockStatementGroup* switchLabel* '}' #switchstmt + | SYNCHRONIZED parExpression block #synchronizedstmt + | RETURN expression? ';' #returnstmt + | THROW expression ';' #throwstmt + | BREAK identifier? ';' #breakstmt + | CONTINUE identifier? ';' #continuestmt + | YIELD expression ';' #yieldstmt // Java17 + | SEMI #semistmt + | statementExpression=expression ';' #stmtexpression + | switchExpression ';'? #switchexpressionstmt // Java17 + | identifierLabel=identifier ':' statement #labeledstmt + ; + +catchClause + : CATCH '(' variableModifier* catchType? identifier ')' block + ; + +catchType + : qualifiedName ('|' qualifiedName)* + ; + +finallyBlock + : FINALLY block + ; + +resourceSpecification + : '(' resources ';'? ')' + ; + +resources + : resource (';' resource)* + ; + +resource + : variableModifier* ( classOrInterfaceType? variableDeclaratorId | VAR identifier ) '=' expression + | identifier + ; + +/** Matches cases then statements, both of which are mandatory. + * To handle empty cases at the end, we add switchLabel* to statement. + */ +switchBlockStatementGroup + : switchLabel+ blockStatement+ + ; + +switchLabel + : CASE (constantExpression=expression | enumConstantName=IDENTIFIER | pattern) ':' + | DEFAULT ':' + ; + +forControl + : enhancedForControl + | forInit? ';' expression? ';' forUpdate=expressionList? + ; + +forInit + : localVariableDeclaration + | expressionList + ; + +enhancedForControl + : variableModifier* (typeType? | VAR) variableDeclaratorId ':' expression + ; + +// EXPRESSIONS + +parExpression + : '(' expression ')' + ; + +expressionList + : expression (',' expression)* + ; + +methodCall + : identifier '(' expressionList? ')' + | THIS '(' expressionList? ')' + | SUPER '(' expressionList? ')' + ; + +expression + : primary #primaryexpression + | expression bop='.' + ( + identifier + | methodCall + | THIS + | NEW nonWildcardTypeArguments? innerCreator + | SUPER superSuffix + | explicitGenericInvocation + ) # dottedexpression + | expression '[' expression ']' #arrayaccessexpression + | methodCall #methodcallexpression + | NEW creator #newinstanceexpression + | '(' annotation* typeType ('&' typeType)* ')' expression #castexpression + | expression postfix=('++' | '--') #postfixexpression + | prefix=('+'|'-'|'++'|'--'|'~'|'!') expression #prefixexpression + | expression bop=('*'|'/'|'%') expression #mathmuldivmodexpression + | expression bop=('+'|'-') expression #mathaddsubexpression + | expression ('<' '<' | '>' '>' '>' | '>' '>') expression #shiftexpression + | expression bop=('<=' | '>=' | '>' | '<') expression #relationalexpression + | expression bop=INSTANCEOF (typeType | pattern) #instanceofexpression + | expression bop=('==' | '!=') expression #equalityexpression + | expression bop='&' expression #bitwiseandexpression + | expression bop='^' expression #bitwisexorexpression + | expression bop='|' expression #bitwiseorexpression + | expression bop='&&' expression #andexpression + | expression bop='||' expression #orexpression + | expression bop='?' expression ':' expression #conditionalassignexpression + | expression + bop=('=' | '+=' | '-=' | '*=' | '/=' | '&=' | '|=' | '^=' | '>>=' | '>>>=' | '<<=' | '%=') + expression #assignexpression + | lambdaExpression #lambdaexpression // Java8 + | switchExpression #switchexpression // Java17 + + // Java 8 methodReference + | expression '::' typeArguments? identifier #methodreferenceexpression + | typeType '::' (typeArguments? identifier | NEW) #methodorcreatorreferenceexpression + | classType '::' typeArguments? NEW #creatorreferenceexpression + ; + +// Java17 +pattern + : primaryPattern + | guardedPattern + ; + +primaryPattern + : typePattern + | recordPattern + | '(' pattern ')' + ; + +recordPattern + : typeType recordStructurePattern identifier? + ; + +typePattern + : variableModifier* typeType? identifier + ; + +recordStructurePattern + : '(' recordComponentPatternList? ')' + ; + +recordComponentPatternList + : pattern (',' pattern)* + ; + +// Java8 +lambdaExpression + : lambdaParameters '->' lambdaBody + ; + +// Java8 +lambdaParameters + : identifier + | '(' formalParameterList? ')' + | '(' identifier (',' identifier)* ')' + | '(' lambdaLVTIList? ')' + ; + +// Java8 +lambdaBody + : expression + | block + ; + +primary + : '(' expression ')' # primaryExpression + | THIS # primaryThis + | SUPER # primarySuper + | literal # primaryLiteral + | identifier # primaryIdentifier + | refType '.' CLASS # primaryClassref + | nonWildcardTypeArguments (explicitGenericInvocationSuffix | THIS arguments) # primaryInvocation + ; + +// Java17 +switchExpression + : SWITCH parExpression '{' switchLabeledRule* '}' + ; + +// Java17 +switchLabeledRule + : CASE (expressionList | NULL_LITERAL | pattern) (ARROW | COLON) switchRuleOutcome + | DEFAULT (ARROW | COLON) switchRuleOutcome + ; + +// Java17 +guardedPattern + : variableModifier* typeType? annotation* identifier ('&&' expression)* + | guardedPattern '&&' expression + ; + +// Java17 +switchRuleOutcome + : block + | blockStatement* + ; + +classType + : (classOrInterfaceType '.')? annotation* identifier typeArguments? + ; + +creator + : nonWildcardTypeArguments createdName classCreatorRest + | createdName (arrayCreatorRest | classCreatorRest) + ; + +createdName + : identifier typeArgumentsOrDiamond? + | primitiveType + ; + +innerCreator + : identifier nonWildcardTypeArgumentsOrDiamond? classCreatorRest + ; + +arrayCreatorRest + : '[' (']' ('[' ']')* arrayInitializer | expression ']' ('[' expression ']')* ('[' ']')*) + ; + +classCreatorRest + : arguments classBody? + ; + +explicitGenericInvocation + : nonWildcardTypeArguments explicitGenericInvocationSuffix + ; + +typeArgumentsOrDiamond + : '<' '>' + | typeArguments + ; + +nonWildcardTypeArgumentsOrDiamond + : '<' '>' + | nonWildcardTypeArguments + ; + +nonWildcardTypeArguments + : '<' typeList '>' + ; + +typeList + : typeType (',' typeType)* + ; + +typeType + : annotation* (classOrInterfaceType | primitiveType) (annotation* '[' ']')* + ; + +primitiveType + : BOOLEAN + | CHAR + | BYTE + | SHORT + | INT + | LONG + | FLOAT + | DOUBLE + ; + +typeArguments + : '<' typeArgument (',' typeArgument)* '>' + ; + +superSuffix + : arguments + | '.' typeArguments? identifier arguments? + ; + +explicitGenericInvocationSuffix + : SUPER superSuffix + | identifier arguments + ; + +arguments + : '(' expressionList? ')' + ; \ No newline at end of file diff --git a/src/main/antlr4/de/dhbwstuttgart/parser/antlr/Java8.g4 b/src/main/antlr4/de/dhbwstuttgart/parser/antlr/Java8.g4 deleted file mode 100644 index 5188ddf6..00000000 --- a/src/main/antlr4/de/dhbwstuttgart/parser/antlr/Java8.g4 +++ /dev/null @@ -1,1872 +0,0 @@ -/* - * [The "BSD license"] - * Copyright (c) 2014 Terence Parr - * Copyright (c) 2014 Sam Harwell - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. The name of the author may not be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -/** - * A Java 8 grammar for ANTLR 4 derived from the Java Language Specification - * chapter 19. - * - * NOTE: This grammar results in a generated parser that is much slower - * than the Java 7 grammar in the grammars-v4/java directory. This - * one is, however, extremely close to the spec. - * - * You can test with - * - * $ antlr4 Java8.g4 - * $ javac *.java - * $ grun Java8 compilationUnit *.java - * - * Or, -~/antlr/code/grammars-v4/java8 $ java Test . -/Users/parrt/antlr/code/grammars-v4/java8/./Java8BaseListener.java -/Users/parrt/antlr/code/grammars-v4/java8/./Java8Lexer.java -/Users/parrt/antlr/code/grammars-v4/java8/./Java8Listener.java -/Users/parrt/antlr/code/grammars-v4/java8/./Java8Parser.java -/Users/parrt/antlr/code/grammars-v4/java8/./Test.java -Total lexer+parser time 30844ms. - */ -grammar Java8; - -/* - * Productions from §3 (Lexical Structure) - */ - -literal - : IntegerLiteral - | FloatingPointLiteral - | BooleanLiteral - | CharacterLiteral - | StringLiteral - | NullLiteral - ; - -/* - * Productions from §4 (Types, Values, and Variables) - */ - -type - : primitiveType - | referenceType - ; - -primitiveType - : annotation* numericType - | annotation* 'boolean' - ; - -numericType - : integralType - | floatingPointType - ; - -integralType - : 'byte' - | 'short' - | 'int' - | 'long' - | 'char' - ; - -floatingPointType - : 'float' - | 'double' - ; - -referenceType - : classOrInterfaceType - | typeVariable - | arrayType - ; - -classOrInterfaceType - : ( classType_lfno_classOrInterfaceType - | interfaceType_lfno_classOrInterfaceType - ) - ( classType_lf_classOrInterfaceType - | interfaceType_lf_classOrInterfaceType - )* - ; - -classType - : annotation* Identifier typeArguments? - | classOrInterfaceType '.' annotation* Identifier typeArguments? - ; - -classTypeList - : classType (',' classType)* - ; - -classType_lf_classOrInterfaceType - : '.' annotation* Identifier typeArguments? - ; - -classType_lfno_classOrInterfaceType - : annotation* Identifier typeArguments? - ; - -interfaceType - : classType - ; - -interfaceType_lf_classOrInterfaceType - : classType_lf_classOrInterfaceType - ; - -interfaceType_lfno_classOrInterfaceType - : classType_lfno_classOrInterfaceType - ; - -typeVariable - : annotation* Identifier - ; - -arrayType - : primitiveType dims - | classOrInterfaceType dims - | typeVariable dims - ; - -dims - : annotation* '[' ']' (annotation* '[' ']')* - ; - -typeParameter - : typeParameterModifier* Identifier typeBound? - ; - -typeParameterModifier - : annotation - ; - -typeBound - : 'extends' typeVariable - | 'extends' classOrInterfaceType additionalBound* - ; - -additionalBound - : '&' interfaceType - ; - -typeArguments - : '<' typeArgumentList '>' - ; - -typeArgumentList - : typeArgument (',' typeArgument)* - ; - -typeArgument - : referenceType - | wildcard - ; - -wildcard - : annotation* '?' wildcardBounds? - ; - -wildcardBounds - : 'extends' referenceType - | 'super' referenceType - ; - -/* - * Productions from §6 (Names) - */ - -packageName - : Identifier - | packageName '.' Identifier - ; - -typeName - : Identifier - | packageOrTypeName '.' Identifier - ; - -packageOrTypeName - : Identifier - | packageOrTypeName '.' Identifier - ; - -expressionName - : Identifier - | ambiguousName '.' Identifier - ; - -methodName - : Identifier - ; - -ambiguousName - : Identifier - | ambiguousName '.' Identifier - ; - -/* - * Productions from §7 (Packages) - */ - -compilationUnit - : packageDeclaration? importDeclaration* typeDeclaration* EOF - ; - -packageDeclaration - : packageModifier* 'package' Identifier ('.' Identifier)* ';' - ; - -packageModifier - : annotation - ; - -importDeclaration - : singleTypeImportDeclaration - | typeImportOnDemandDeclaration - | singleStaticImportDeclaration - | staticImportOnDemandDeclaration - ; - -singleTypeImportDeclaration - : 'import' typeName ';' - ; - -typeImportOnDemandDeclaration - : 'import' packageOrTypeName '.' '*' ';' - ; - -singleStaticImportDeclaration - : 'import' 'static' typeName '.' Identifier ';' - ; - -staticImportOnDemandDeclaration - : 'import' 'static' typeName '.' '*' ';' - ; - -typeDeclaration - : classDeclaration - | interfaceDeclaration - | ';' - ; - -/* - * Productions from §8 (Classes) - */ - -classDeclaration - : normalClassDeclaration - | enumDeclaration - | recordDeclaration - ; - -normalClassDeclaration - : classModifier* 'class' Identifier typeParameters? superclass? superinterfaces? permittedsubclasses? classBody - ; - -classModifier - : annotation - | 'public' - | 'protected' - | 'private' - | 'abstract' - | 'static' - | 'sealed' - | 'final' - | 'non-sealed' - | 'strictfp' - ; - -typeParameters - : '<' typeParameterList '>' - ; - -typeParameterList - : typeParameter (',' typeParameter)* - ; - -superclass - : 'extends' classType - ; - -superinterfaces - : 'implements' interfaceTypeList - ; - -permittedsubclasses - : 'permits' classTypeList - ; - -interfaceTypeList - : interfaceType (',' interfaceType)* - ; - -classBody - : '{' classBodyDeclaration* '}' - ; - -classBodyDeclaration - : classMemberDeclaration - | instanceInitializer - | staticInitializer -// | constructorDeclaration - ; - -classMemberDeclaration - : fieldDeclaration - | methodDeclaration - | classDeclaration - | interfaceDeclaration - | ';' - ; - -fieldDeclaration - : fieldModifier* unannTypeOrAuto? variableDeclaratorList ';' - ; - -fieldModifier - : annotation - | 'public' - | 'protected' - | 'private' - | 'static' - | 'final' - | 'transient' - | 'volatile' - ; - -variableDeclaratorList - : variableDeclarator (',' variableDeclarator)* - ; - -variableDeclarator - : variableDeclaratorId ('=' variableInitializer)? //auskommentiert, weil variablenDecklaration sonst nicht eindeutig - ; - -variableDeclaratorId - : Identifier dims? - ; - -variableInitializer - : expression - | arrayInitializer - ; - -unannType - : unannPrimitiveType - | unannReferenceType - ; - -unannPrimitiveType - : numericType - | 'boolean' - ; - -unannReferenceType - : unannClassOrInterfaceType - | unannTypeVariable - | unannArrayType - ; - -unannClassOrInterfaceType - : ( unannClassType_lfno_unannClassOrInterfaceType - | unannInterfaceType_lfno_unannClassOrInterfaceType - ) - ( unannClassType_lf_unannClassOrInterfaceType - | unannInterfaceType_lf_unannClassOrInterfaceType - )* - ; - -unannClassType - : Identifier typeArguments? - | unannClassOrInterfaceType '.' annotation* Identifier typeArguments? - ; - -unannClassType_lf_unannClassOrInterfaceType - : '.' annotation* Identifier typeArguments? - ; - -unannClassType_lfno_unannClassOrInterfaceType - : Identifier typeArguments? - ; - -unannInterfaceType - : unannClassType - ; - -unannInterfaceType_lf_unannClassOrInterfaceType - : unannClassType_lf_unannClassOrInterfaceType - ; - -unannInterfaceType_lfno_unannClassOrInterfaceType - : unannClassType_lfno_unannClassOrInterfaceType - ; - -unannTypeVariable - : Identifier - ; - -unannArrayType - : unannPrimitiveType dims - | unannClassOrInterfaceType dims - | unannTypeVariable dims - ; - -methodDeclaration - : methodModifier* methodHeader methodBody - ; - -methodModifier - : annotation - | 'public' - | 'protected' - | 'private' - | 'abstract' - | 'static' - | 'final' - | 'synchronized' - | 'native' - | 'strictfp' - ; - -methodHeader - : result? methodDeclarator throws_? - | typeParameters annotation* result? methodDeclarator throws_? - ; - -result - : unannType - | 'void' - ; - -methodDeclarator - : Identifier '(' formalParameterList? ')' dims? - ; - -formalParameterList - : formalParameters ',' lastFormalParameter - | lastFormalParameter - ; - -formalParameters - : formalParameter (',' formalParameter)* - | receiverParameter (',' formalParameter)* - ; - -formalParameter - : variableModifier* unannType? variableDeclaratorId - ; - -variableModifier - : annotation - | 'final' - ; - -lastFormalParameter - : variableModifier* unannType annotation* '...' variableDeclaratorId - | formalParameter - ; - -receiverParameter - : annotation* unannType (Identifier '.')? 'this' - ; - -throws_ - : 'throws' exceptionTypeList - ; - -exceptionTypeList - : exceptionType (',' exceptionType)* - ; - -exceptionType - : classType - | typeVariable - ; - -methodBody - : block - | ';' - ; - -instanceInitializer - : block - ; - -staticInitializer - : 'static' block - ; - -constructorDeclaration - : constructorModifier* constructorDeclarator throws_? constructorBody - ; - -constructorModifier - : annotation - | 'public' - | 'protected' - | 'private' - ; - -constructorDeclarator - : typeParameters? simpleTypeName '(' formalParameterList? ')' - ; - -simpleTypeName - : Identifier - ; - -constructorBody - : '{' explicitConstructorInvocation? blockStatements? '}' - ; - -explicitConstructorInvocation - : typeArguments? 'this' '(' argumentList? ')' ';' - | typeArguments? 'super' '(' argumentList? ')' ';' - | expressionName '.' typeArguments? 'super' '(' argumentList? ')' ';' - | primary '.' typeArguments? 'super' '(' argumentList? ')' ';' - ; - -enumDeclaration - : classModifier* 'enum' Identifier superinterfaces? enumBody - ; - -enumBody - : '{' enumConstantList? ','? enumBodyDeclarations? '}' - ; - -enumConstantList - : enumConstant (',' enumConstant)* - ; - -enumConstant - : enumConstantModifier* Identifier ('(' argumentList? ')')? classBody? - ; - -enumConstantModifier - : annotation - ; - -enumBodyDeclarations - : ';' classBodyDeclaration* - ; - -recordDeclaration - : classModifier* 'record' Identifier typeParameters? recordHeader superinterfaces? recordBody - ; - -recordHeader - : '(' recordComponentList? ')' - ; - -recordComponentList - : recordComponent (',' recordComponent)* - ; - -recordComponent - : annotation* unannType Identifier - | variableArityRecordComponent - ; - -variableArityRecordComponent - : annotation* unannType annotation* '...' Identifier - ; - -recordBody - : '{' recordBodyDeclaration* '}' - ; - -recordBodyDeclaration - : classBodyDeclaration - | compactConstructorDeclaration - ; - -compactConstructorDeclaration - : constructorModifier* simpleTypeName constructorBody - ; - -/* - * Productions from §9 (Interfaces) - */ - -interfaceDeclaration - : normalInterfaceDeclaration - | annotationTypeDeclaration - ; - -normalInterfaceDeclaration - : interfaceModifier* 'interface' Identifier typeParameters? extendsInterfaces? interfaceBody - ; - -interfaceModifier - : annotation - | 'public' - | 'protected' - | 'private' - | 'abstract' - | 'static' - | 'strictfp' - ; - -extendsInterfaces - : 'extends' interfaceTypeList - ; - -interfaceBody - : '{' interfaceMemberDeclaration* '}' - ; - -interfaceMemberDeclaration - : constantDeclaration - | interfaceMethodDeclaration - | classDeclaration - | interfaceDeclaration - | ';' - ; - -constantDeclaration - : constantModifier* unannType variableDeclaratorList ';' - ; - -constantModifier - : annotation - | 'public' - | 'static' - | 'final' - ; - -interfaceMethodDeclaration - : interfaceMethodModifier* methodHeader methodBody - ; - -interfaceMethodModifier - : annotation - | 'public' - | 'abstract' - | 'default' - | 'static' - | 'strictfp' - ; - -annotationTypeDeclaration - : interfaceModifier* '@' 'interface' Identifier annotationTypeBody - ; - -annotationTypeBody - : '{' annotationTypeMemberDeclaration* '}' - ; - -annotationTypeMemberDeclaration - : annotationTypeElementDeclaration - | constantDeclaration - | classDeclaration - | interfaceDeclaration - | ';' - ; - -annotationTypeElementDeclaration - : annotationTypeElementModifier* unannType Identifier '(' ')' dims? defaultValue? ';' - ; - -annotationTypeElementModifier - : annotation - | 'public' - | 'abstract' - ; - -defaultValue - : 'default' elementValue - ; - -annotation - : normalAnnotation - | markerAnnotation - | singleElementAnnotation - ; - -normalAnnotation - : '@' typeName '(' elementValuePairList? ')' - ; - -elementValuePairList - : elementValuePair (',' elementValuePair)* - ; - -elementValuePair - : Identifier '=' elementValue - ; - -elementValue - : conditionalExpression - | elementValueArrayInitializer - | annotation - ; - -elementValueArrayInitializer - : '{' elementValueList? ','? '}' - ; - -elementValueList - : elementValue (',' elementValue)* - ; - -markerAnnotation - : '@' typeName - ; - -singleElementAnnotation - : '@' typeName '(' elementValue ')' - ; - -/* - * Productions from §10 (Arrays) - */ - -arrayInitializer - : '{' variableInitializerList? ','? '}' - ; - -variableInitializerList - : variableInitializer (',' variableInitializer)* - ; - -/* - * Productions from §14 (Blocks and Statements) - */ - -block - : '{' blockStatements? '}' - ; - -blockStatements - : blockStatement blockStatement* - ; - -blockStatement - : localVariableDeclarationStatement - | classDeclaration - | statement - ; - -localVariableDeclarationStatement - : localVariableDeclaration ';' - ; - -unannTypeOrAuto - : unannType - | 'var' - ; - -localVariableDeclaration - : variableModifier* unannTypeOrAuto variableDeclaratorList - ; - -statement - : statementWithoutTrailingSubstatement - | labeledStatement - | ifThenStatement - | ifThenElseStatement - | whileStatement - | forStatement - | switchExpression ';'? - ; - -statementNoShortIf - : statementWithoutTrailingSubstatement - | labeledStatementNoShortIf - | ifThenElseStatementNoShortIf - | whileStatementNoShortIf - | forStatementNoShortIf - ; - -statementWithoutTrailingSubstatement - : block - | emptyStatement - | expressionStatement - | assertStatement - | switchStatement - | doStatement - | breakStatement - | yieldStatement - | continueStatement - | returnStatement - | synchronizedStatement - | throwStatement - | tryStatement - ; - -emptyStatement - : ';' - ; - -labeledStatement - : Identifier ':' statement - ; - -labeledStatementNoShortIf - : Identifier ':' statementNoShortIf - ; - -expressionStatement - : statementExpression ';' - ; - -statementExpression - : assignment - | preIncrementExpression - | preDecrementExpression - | postIncrementExpression - | postDecrementExpression - | methodInvocation - | classInstanceCreationExpression - ; - -ifThenStatement - : 'if' '(' expression ')' statement - ; - -ifThenElseStatement - : 'if' parExpression statementNoShortIf 'else' statement - ; - -ifThenElseStatementNoShortIf - : 'if' parExpression statementNoShortIf 'else' statementNoShortIf - ; - -assertStatement - : 'assert' expression ';' - | 'assert' expression ':' expression ';' - ; - -switchStatement - : 'switch' parExpression switchBlock - ; - -switchBlock - : '{' switchBlockStatementGroup* switchLabel* '}' - ; - -switchBlockStatementGroup - : switchLabels blockStatements - ; - -switchLabels - : switchLabel switchLabel* - ; - -switchLabel - : 'case' constantExpression ':' - | 'case' enumConstantName ':' - | 'default' ':' - ; - -switchExpression - : 'switch' parExpression '{' switchLabeledRule* '}' - ; - -switchLabeledRule - : CASE (expressionList | NullLiteral | guardedPattern) (ARROW|COLON) switchRuleOutcome - | DEFAULT (ARROW|COLON) switchRuleOutcome - ; - -guardedPattern - : '(' guardedPattern ')' - | variableModifier* annotation* Identifier ('&&' expression)* - | guardedPattern '&&' expression - ; - -switchRuleOutcome - : block - | blockStatement* - ; - -enumConstantName - : Identifier - ; - -enumConstantNameList - : enumConstantName (',' enumConstantName)* - ; - -whileStatement - : 'while' parExpression statement - ; - -whileStatementNoShortIf - : 'while' parExpression statementNoShortIf - ; - -doStatement - : 'do' statement 'while' parExpression ';' - ; - -forStatement - : basicForStatement - | enhancedForStatement - ; - -forStatementNoShortIf - : basicForStatementNoShortIf - | enhancedForStatementNoShortIf - ; - -basicForStatement - : 'for' '(' forInit? ';' expression? ';' forUpdate? ')' statement - ; - -basicForStatementNoShortIf - : 'for' '(' forInit? ';' expression? ';' forUpdate? ')' statementNoShortIf - ; - -forInit - : statementExpressionList - | localVariableDeclaration - ; - -forUpdate - : statementExpressionList - ; - -statementExpressionList - : statementExpression (',' statementExpression)* - ; - -enhancedForStatement - : 'for' '(' variableModifier* unannType variableDeclaratorId ':' expression ')' statement - ; - -enhancedForStatementNoShortIf - : 'for' '(' variableModifier* unannType variableDeclaratorId ':' expression ')' statementNoShortIf - ; - -breakStatement - : 'break' Identifier? ';' - ; - -yieldStatement - : 'yield' Identifier? ';' - ; - -continueStatement - : 'continue' Identifier? ';' - ; - -returnStatement - : 'return' expression? ';' - ; - -throwStatement - : 'throw' expression ';' - ; - -synchronizedStatement - : 'synchronized' parExpression block - ; - -tryStatement - : 'try' block catches - | 'try' block catches? finally_ - | tryWithResourcesStatement - ; - -catches - : catchClause catchClause* - ; - -catchClause - : 'catch' '(' catchFormalParameter ')' block - ; - -catchFormalParameter - : variableModifier* catchType variableDeclaratorId - ; - -catchType - : unannClassType ('|' classType)* - ; - -finally_ - : 'finally' block - ; - -tryWithResourcesStatement - : 'try' resourceSpecification block catches? finally_? - ; - -resourceSpecification - : '(' resourceList ';'? ')' - ; - -resourceList - : resource (';' resource)* - ; - -resource - : variableModifier* unannType variableDeclaratorId '=' expression - ; - -/* - * Productions from §15 (Expressions) - */ - -primary - : ( primaryNoNewArray_lfno_primary - | arrayCreationExpression - ) - ( primaryNoNewArray_lf_primary - )* - ; - -primaryNoNewArray - : literal - | typeName ('[' ']')* '.' 'class' - | 'void' '.' 'class' - | 'this' - | typeName '.' 'this' - | parExpression - | classInstanceCreationExpression - | fieldAccess - | arrayAccess - | methodInvocation - | methodReference - ; - -primaryNoNewArray_lf_arrayAccess - : - ; - -primaryNoNewArray_lfno_arrayAccess - : literal - | typeName ('[' ']')* '.' 'class' - | 'void' '.' 'class' - | 'this' - | typeName '.' 'this' - | parExpression - | classInstanceCreationExpression - | fieldAccess - | methodInvocation - | methodReference - ; - -primaryNoNewArray_lf_primary - : classInstanceCreationExpression_lf_primary - | fieldAccess_lf_primary - | arrayAccess_lf_primary - | methodInvocation_lf_primary - | methodReference_lf_primary - ; - -primaryNoNewArray_lf_primary_lf_arrayAccess_lf_primary - : - ; - -primaryNoNewArray_lf_primary_lfno_arrayAccess_lf_primary - : classInstanceCreationExpression_lf_primary - | fieldAccess_lf_primary - | methodInvocation_lf_primary - | methodReference_lf_primary - ; - -primaryNoNewArray_lfno_primary - : literal //done - | typeName ('[' ']')* '.' 'class' - | unannPrimitiveType ('[' ']')* '.' 'class' - | 'void' '.' 'class' - | 'this' - | typeName '.' 'this' - | parExpression //done - | classInstanceCreationExpression_lfno_primary //done - | fieldAccess_lfno_primary - | arrayAccess_lfno_primary - | methodInvocation_lfno_primary //done - | methodReference_lfno_primary - ; - -primaryNoNewArray_lfno_primary_lf_arrayAccess_lfno_primary - : - ; - -primaryNoNewArray_lfno_primary_lfno_arrayAccess_lfno_primary - : literal - | typeName ('[' ']')* '.' 'class' - | unannPrimitiveType ('[' ']')* '.' 'class' - | 'void' '.' 'class' - | 'this' - | typeName '.' 'this' - | parExpression - | classInstanceCreationExpression_lfno_primary - | fieldAccess_lfno_primary - | methodInvocation_lfno_primary - | methodReference_lfno_primary - ; - -classInstanceCreationExpression - : 'new' typeArguments? annotation* Identifier ('.' annotation* Identifier)* typeArgumentsOrDiamond? '(' argumentList? ')' classBody? - | expressionName '.' 'new' typeArguments? annotation* Identifier typeArgumentsOrDiamond? '(' argumentList? ')' classBody? - | primary '.' 'new' typeArguments? annotation* Identifier typeArgumentsOrDiamond? '(' argumentList? ')' classBody? - ; - -classInstanceCreationExpression_lf_primary - : '.' 'new' typeArguments? annotation* Identifier typeArgumentsOrDiamond? '(' argumentList? ')' classBody? - ; - -classInstanceCreationExpression_lfno_primary - : 'new' typeArguments? annotation* Identifier ('.' annotation* Identifier)* typeArgumentsOrDiamond? '(' argumentList? ')' classBody? - | expressionName '.' 'new' typeArguments? annotation* Identifier typeArgumentsOrDiamond? '(' argumentList? ')' classBody? - ; - -typeArgumentsOrDiamond - : typeArguments - | '<' '>' - ; - -fieldAccess - : primary '.' Identifier - | 'super' '.' Identifier - | typeName '.' 'super' '.' Identifier - ; - -fieldAccess_lf_primary - : '.' Identifier - ; - -fieldAccess_lfno_primary - : 'super' '.' Identifier - | typeName '.' 'super' '.' Identifier - ; - -arrayAccess - : ( expressionName '[' expression ']' - | primaryNoNewArray_lfno_arrayAccess '[' expression ']' - ) - ( primaryNoNewArray_lf_arrayAccess '[' expression ']' - )* - ; - -arrayAccess_lf_primary - : ( primaryNoNewArray_lf_primary_lfno_arrayAccess_lf_primary '[' expression ']' - ) - ( primaryNoNewArray_lf_primary_lf_arrayAccess_lf_primary '[' expression ']' - )* - ; - -arrayAccess_lfno_primary - : ( expressionName '[' expression ']' - | primaryNoNewArray_lfno_primary_lfno_arrayAccess_lfno_primary '[' expression ']' - ) - ( primaryNoNewArray_lfno_primary_lf_arrayAccess_lfno_primary '[' expression ']' - )* - ; - -methodInvocation - : methodName '(' argumentList? ')' - | typeName '.' typeArguments? Identifier '(' argumentList? ')' - | expressionName '.' typeArguments? Identifier '(' argumentList? ')' - | primary '.' typeArguments? Identifier '(' argumentList? ')' - | 'super' '.' typeArguments? Identifier '(' argumentList? ')' - | typeName '.' 'super' '.' typeArguments? Identifier '(' argumentList? ')' - ; - -methodInvocation_lf_primary - : '.' typeArguments? Identifier '(' argumentList? ')' - ; - -methodInvocation_lfno_primary - : methodName '(' argumentList? ')' - | typeName '.' typeArguments? Identifier '(' argumentList? ')' - | expressionName '.' typeArguments? Identifier '(' argumentList? ')' - | 'super' '.' typeArguments? Identifier '(' argumentList? ')' - | typeName '.' 'super' '.' typeArguments? Identifier '(' argumentList? ')' - ; - -argumentList - : expression (',' expression)* - ; - -methodReference - : expressionName '::' typeArguments? Identifier - | referenceType '::' typeArguments? Identifier - | primary '::' typeArguments? Identifier - | 'super' '::' typeArguments? Identifier - | typeName '.' 'super' '::' typeArguments? Identifier - | classType '::' typeArguments? 'new' - | arrayType '::' 'new' - ; - -methodReference_lf_primary - : '::' typeArguments? Identifier - ; - -methodReference_lfno_primary - : expressionName '::' typeArguments? Identifier - | referenceType '::' typeArguments? Identifier - | 'super' '::' typeArguments? Identifier - | typeName '.' 'super' '::' typeArguments? Identifier - | classType '::' typeArguments? 'new' - | arrayType '::' 'new' - ; - -arrayCreationExpression - : 'new' primitiveType dimExprs dims? - | 'new' classOrInterfaceType dimExprs dims? - | 'new' primitiveType dims arrayInitializer - | 'new' classOrInterfaceType dims arrayInitializer - ; - -dimExprs - : dimExpr dimExpr* - ; - -dimExpr - : annotation* '[' expression ']' - ; - -constantExpression - : expression - ; - -constantExpressionList - : constantExpression (',' constantExpression)* - ; - -expression - : lambdaExpression - | assignmentExpression - | switchExpression - ; - -expressionList - : expression (',' expression)* - ; - -parExpression - : '(' expression ')' - ; - -lambdaExpression - : lambdaParameters '->' lambdaBody - ; - -lambdaParameters - : Identifier - | '(' formalParameterList? ')' - //| '(' inferredFormalParameterList ')' - ; - -inferredFormalParameterList - : Identifier (',' Identifier)* - ; - -lambdaBody - : expression - | block - ; - -assignmentExpression - : conditionalExpression - | assignment - ; - -assignment - : leftHandSide assignmentOperator expression - ; - -leftHandSide - : expressionName - | fieldAccess - | arrayAccess - ; - -assignmentOperator - : '=' - | '*=' - | '/=' - | '%=' - | '+=' - | '-=' - | '<<=' - | '>>=' - | '>>>=' - | '&=' - | '^=' - | '|=' - ; - -conditionalExpression - : conditionalOrExpression - | conditionalOrExpression '?' expression ':' conditionalExpression - ; - -conditionalOrExpression - : conditionalAndExpression - | conditionalOrExpression '||' conditionalAndExpression - ; - -conditionalAndExpression - : inclusiveOrExpression - | conditionalAndExpression '&&' inclusiveOrExpression - ; - -inclusiveOrExpression - : exclusiveOrExpression - | inclusiveOrExpression '|' exclusiveOrExpression - ; - -exclusiveOrExpression - : andExpression - | exclusiveOrExpression '^' andExpression - ; - -andExpression - : equalityExpression - | andExpression '&' equalityExpression - ; - -equalityExpression - : relationalExpression - | equalityExpression '==' relationalExpression - | equalityExpression '!=' relationalExpression - ; - -relationalExpression - : shiftExpression - | relationalExpression '<' shiftExpression - | relationalExpression '>' shiftExpression - | relationalExpression '<=' shiftExpression - | relationalExpression '>=' shiftExpression - | relationalExpression 'instanceof' referenceType - ; - -shiftExpression - : additiveExpression - | shiftExpression '<' '<' additiveExpression - | shiftExpression '>' '>' additiveExpression - | shiftExpression '>' '>' '>' additiveExpression - ; - -additiveExpression - : multiplicativeExpression - | additiveExpression '+' multiplicativeExpression - | additiveExpression '-' multiplicativeExpression - ; - -multiplicativeExpression - : unaryExpression - | multiplicativeExpression '*' unaryExpression - | multiplicativeExpression '/' unaryExpression - | multiplicativeExpression '%' unaryExpression - ; - -unaryExpression - : preIncrementExpression - | preDecrementExpression - | '+' unaryExpression - | '-' unaryExpression - | unaryExpressionNotPlusMinus - ; - -preIncrementExpression - : '++' unaryExpression - ; - -preDecrementExpression - : '--' unaryExpression - ; - -unaryExpressionNotPlusMinus - : postfixExpression - | '~' unaryExpression - | '!' unaryExpression - | castExpression - ; - -postfixExpression - : ( primary - | expressionName - ) - ( postIncrementExpression_lf_postfixExpression - | postDecrementExpression_lf_postfixExpression - )* - ; - -postIncrementExpression - : postfixExpression '++' - ; - -postIncrementExpression_lf_postfixExpression - : '++' - ; - -postDecrementExpression - : postfixExpression '--' - ; - -postDecrementExpression_lf_postfixExpression - : '--' - ; - -castExpression - : '(' primitiveType ')' unaryExpression - | '(' referenceType additionalBound* ')' unaryExpressionNotPlusMinus - | '(' referenceType additionalBound* ')' lambdaExpression - ; - -// LEXER - -// §3.9 Keywords - -ABSTRACT : 'abstract'; -ASSERT : 'assert'; -BOOLEAN : 'boolean'; -BREAK : 'break'; -BYTE : 'byte'; -CASE : 'case'; -CATCH : 'catch'; -CHAR : 'char'; -CLASS : 'class'; -CONST : 'const'; -CONTINUE : 'continue'; -DEFAULT : 'default'; -DO : 'do'; -DOUBLE : 'double'; -ELSE : 'else'; -ENUM : 'enum'; -EXTENDS : 'extends'; -FINAL : 'final'; -FINALLY : 'finally'; -FLOAT : 'float'; -FOR : 'for'; -IF : 'if'; -GOTO : 'goto'; -IMPLEMENTS : 'implements'; -IMPORT : 'import'; -INSTANCEOF : 'instanceof'; -INT : 'int'; -INTERFACE : 'interface'; -LONG : 'long'; -NATIVE : 'native'; -NEW : 'new'; -PACKAGE : 'package'; -PRIVATE : 'private'; -PROTECTED : 'protected'; -PUBLIC : 'public'; -RETURN : 'return'; -SHORT : 'short'; -STATIC : 'static'; -STRICTFP : 'strictfp'; -SUPER : 'super'; -SWITCH : 'switch'; -SYNCHRONIZED : 'synchronized'; -THIS : 'this'; -THROW : 'throw'; -THROWS : 'throws'; -TRANSIENT : 'transient'; -TRY : 'try'; -VOID : 'void'; -VOLATILE : 'volatile'; -WHILE : 'while'; - -// §3.10.1 Integer Literals - -IntegerLiteral - : DecimalIntegerLiteral - | HexIntegerLiteral - | OctalIntegerLiteral - | BinaryIntegerLiteral - ; - -fragment -DecimalIntegerLiteral - : DecimalNumeral IntegerTypeSuffix? - ; - -fragment -HexIntegerLiteral - : HexNumeral IntegerTypeSuffix? - ; - -fragment -OctalIntegerLiteral - : OctalNumeral IntegerTypeSuffix? - ; - -fragment -BinaryIntegerLiteral - : BinaryNumeral IntegerTypeSuffix? - ; - -fragment -IntegerTypeSuffix - : [lL] - ; - -fragment -DecimalNumeral - : '0' - | NonZeroDigit (Digits? | Underscores Digits) - ; - -fragment -Digits - : Digit (DigitsAndUnderscores? Digit)? - ; - -fragment -Digit - : '0' - | NonZeroDigit - ; - -fragment -NonZeroDigit - : [1-9] - ; - -fragment -DigitsAndUnderscores - : DigitOrUnderscore+ - ; - -fragment -DigitOrUnderscore - : Digit - | '_' - ; - -fragment -Underscores - : '_'+ - ; - -fragment -HexNumeral - : '0' [xX] HexDigits - ; - -fragment -HexDigits - : HexDigit (HexDigitsAndUnderscores? HexDigit)? - ; - -fragment -HexDigit - : [0-9a-fA-F] - ; - -fragment -HexDigitsAndUnderscores - : HexDigitOrUnderscore+ - ; - -fragment -HexDigitOrUnderscore - : HexDigit - | '_' - ; - -fragment -OctalNumeral - : '0' Underscores? OctalDigits - ; - -fragment -OctalDigits - : OctalDigit (OctalDigitsAndUnderscores? OctalDigit)? - ; - -fragment -OctalDigit - : [0-7] - ; - -fragment -OctalDigitsAndUnderscores - : OctalDigitOrUnderscore+ - ; - -fragment -OctalDigitOrUnderscore - : OctalDigit - | '_' - ; - -fragment -BinaryNumeral - : '0' [bB] BinaryDigits - ; - -fragment -BinaryDigits - : BinaryDigit (BinaryDigitsAndUnderscores? BinaryDigit)? - ; - -fragment -BinaryDigit - : [01] - ; - -fragment -BinaryDigitsAndUnderscores - : BinaryDigitOrUnderscore+ - ; - -fragment -BinaryDigitOrUnderscore - : BinaryDigit - | '_' - ; - -// §3.10.2 Floating-Point Literals - -FloatingPointLiteral - : DecimalFloatingPointLiteral - | HexadecimalFloatingPointLiteral - ; - -fragment -DecimalFloatingPointLiteral - : Digits '.' Digits? ExponentPart? FloatTypeSuffix? - | '.' Digits ExponentPart? FloatTypeSuffix? - | Digits ExponentPart FloatTypeSuffix? - | Digits FloatTypeSuffix - ; - -fragment -ExponentPart - : ExponentIndicator SignedInteger - ; - -fragment -ExponentIndicator - : [eE] - ; - -fragment -SignedInteger - : Sign? Digits - ; - -fragment -Sign - : [+-] - ; - -fragment -FloatTypeSuffix - : [fFdD] - ; - -fragment -HexadecimalFloatingPointLiteral - : HexSignificand BinaryExponent FloatTypeSuffix? - ; - -fragment -HexSignificand - : HexNumeral '.'? - | '0' [xX] HexDigits? '.' HexDigits - ; - -fragment -BinaryExponent - : BinaryExponentIndicator SignedInteger - ; - -fragment -BinaryExponentIndicator - : [pP] - ; - -// §3.10.3 Boolean Literals - -BooleanLiteral - : 'true' - | 'false' - ; - -// §3.10.4 Character Literals - -CharacterLiteral - : '\'' SingleCharacter '\'' - | '\'' EscapeSequence '\'' - ; - -fragment -SingleCharacter - : ~['\\] - ; - -// §3.10.5 String Literals - -StringLiteral - : '"' StringCharacters? '"' - ; - -fragment -StringCharacters - : StringCharacter+ - ; - -fragment -StringCharacter - : ~["\\] - | EscapeSequence - ; - -// §3.10.6 Escape Sequences for Character and String Literals - -fragment -EscapeSequence - : '\\' [btnfr"'\\] - | OctalEscape - | UnicodeEscape // This is not in the spec but prevents having to preprocess the input - ; - -fragment -OctalEscape - : '\\' OctalDigit - | '\\' OctalDigit OctalDigit - | '\\' ZeroToThree OctalDigit OctalDigit - ; - -fragment -ZeroToThree - : [0-3] - ; - -// This is not in the spec but prevents having to preprocess the input -fragment -UnicodeEscape - : '\\' 'u' HexDigit HexDigit HexDigit HexDigit - ; - -// §3.10.7 The Null Literal - -NullLiteral - : 'null' - ; - -// §3.11 Separators - -LPAREN : '('; -RPAREN : ')'; -LBRACE : '{'; -RBRACE : '}'; -LBRACK : '['; -RBRACK : ']'; -SEMI : ';'; -COMMA : ','; -DOT : '.'; - -// §3.12 Operators - -ASSIGN : '='; -GT : '>'; -LT : '<'; -BANG : '!'; -TILDE : '~'; -QUESTION : '?'; -COLON : ':'; -EQUAL : '=='; -LE : '<='; -GE : '>='; -NOTEQUAL : '!='; -AND : '&&'; -OR : '||'; -INC : '++'; -DEC : '--'; -ADD : '+'; -SUB : '-'; -MUL : '*'; -DIV : '/'; -BITAND : '&'; -BITOR : '|'; -CARET : '^'; -MOD : '%'; -ARROW : '->'; -COLONCOLON : '::'; - -ADD_ASSIGN : '+='; -SUB_ASSIGN : '-='; -MUL_ASSIGN : '*='; -DIV_ASSIGN : '/='; -AND_ASSIGN : '&='; -OR_ASSIGN : '|='; -XOR_ASSIGN : '^='; -MOD_ASSIGN : '%='; -LSHIFT_ASSIGN : '<<='; -RSHIFT_ASSIGN : '>>='; -URSHIFT_ASSIGN : '>>>='; - -// §3.8 Identifiers (must appear after all keywords in the grammar) - -Identifier - : JavaLetter JavaLetterOrDigit* - ; - -fragment -JavaLetter - : [a-zA-Z$_] // these are the "java letters" below 0x7F - | // covers all characters above 0x7F which are not a surrogate - ~[\u0000-\u007F\uD800-\uDBFF] - {Character.isJavaIdentifierStart(_input.LA(-1))}? - | // covers UTF-16 surrogate pairs encodings for U+10000 to U+10FFFF - [\uD800-\uDBFF] [\uDC00-\uDFFF] - {Character.isJavaIdentifierStart(Character.toCodePoint((char)_input.LA(-2), (char)_input.LA(-1)))}? - ; - -fragment -JavaLetterOrDigit - : [a-zA-Z0-9$_] // these are the "java letters or digits" below 0x7F - | // covers all characters above 0x7F which are not a surrogate - ~[\u0000-\u007F\uD800-\uDBFF] - {Character.isJavaIdentifierPart(_input.LA(-1))}? - | // covers UTF-16 surrogate pairs encodings for U+10000 to U+10FFFF - [\uD800-\uDBFF] [\uDC00-\uDFFF] - {Character.isJavaIdentifierPart(Character.toCodePoint((char)_input.LA(-2), (char)_input.LA(-1)))}? - ; - -// -// Additional symbols not defined in the lexical specification -// - -AT : '@'; -ELLIPSIS : '...'; - -// -// Whitespace and comments -// - -WS : [ \t\r\n\u000C]+ -> skip - ; - -COMMENT - : '/*' .*? '*/' -> skip - ; - -LINE_COMMENT - : '//' ~[\r\n]* -> skip - ; diff --git a/src/main/java/de/dhbwstuttgart/bytecode/Codegen.java b/src/main/java/de/dhbwstuttgart/bytecode/Codegen.java index 61b3a71e..29699d83 100644 --- a/src/main/java/de/dhbwstuttgart/bytecode/Codegen.java +++ b/src/main/java/de/dhbwstuttgart/bytecode/Codegen.java @@ -28,7 +28,8 @@ public class Codegen { this.cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS); } - private record LocalVar(int index, String name, TargetType type) {} + private record LocalVar(int index, String name, TargetType type) { + } private static class Scope { Scope parent; @@ -196,9 +197,7 @@ public class Codegen { mv.visitInsn(L2F); else if (dest.equals(TargetType.Double)) mv.visitInsn(L2D); - else if (dest.equals(TargetType.Byte) - || dest.equals(TargetType.Char) - || dest.equals(TargetType.Short)) { + else if (dest.equals(TargetType.Byte) || dest.equals(TargetType.Char) || dest.equals(TargetType.Short)) { mv.visitInsn(L2I); convertTo(state, TargetType.Integer, dest); } @@ -209,9 +208,7 @@ public class Codegen { mv.visitInsn(F2D); else if (dest.equals(TargetType.Long)) mv.visitInsn(F2L); - else if (dest.equals(TargetType.Byte) - || dest.equals(TargetType.Char) - || dest.equals(TargetType.Short)) { + else if (dest.equals(TargetType.Byte) || dest.equals(TargetType.Char) || dest.equals(TargetType.Short)) { mv.visitInsn(F2I); convertTo(state, TargetType.Integer, dest); } @@ -222,16 +219,11 @@ public class Codegen { mv.visitInsn(D2F); else if (dest.equals(TargetType.Long)) mv.visitInsn(D2L); - else if (dest.equals(TargetType.Byte) - || dest.equals(TargetType.Char) - || dest.equals(TargetType.Short)) { + else if (dest.equals(TargetType.Byte) || dest.equals(TargetType.Char) || dest.equals(TargetType.Short)) { mv.visitInsn(D2I); convertTo(state, TargetType.Integer, dest); } - } else if (source.equals(TargetType.Byte) - || source.equals(TargetType.Char) - || source.equals(TargetType.Short) - || source.equals(TargetType.Integer)) { + } else if (source.equals(TargetType.Byte) || source.equals(TargetType.Char) || source.equals(TargetType.Short) || source.equals(TargetType.Integer)) { if (dest.equals(TargetType.Byte)) mv.visitInsn(I2B); else if (dest.equals(TargetType.Char)) @@ -268,309 +260,293 @@ public class Codegen { private void generateBinaryOp(State state, TargetBinaryOp op) { var mv = state.mv; switch (op) { - case Add add: { - if (add.type().equals(TargetType.String)) { - mv.visitTypeInsn(NEW, "java/lang/StringBuilder"); - mv.visitInsn(DUP); - generate(state, add.left()); - convertToString(state, add.left().type()); - mv.visitMethodInsn(INVOKESPECIAL, "java/lang/StringBuilder", "", "(Ljava/lang/String;)V", false); - } else { - generate(state, add.left()); - convertTo(state, add.left().type(), add.type()); - generate(state, add.right()); - convertTo(state, add.right().type(), add.type()); - var type = add.type(); - if (type.equals(TargetType.Byte) - || type.equals(TargetType.Char) - || type.equals(TargetType.Integer) - || type.equals(TargetType.Short)) { - mv.visitInsn(IADD); - } else if (type.equals(TargetType.Long)) { - mv.visitInsn(LADD); - } else if (type.equals(TargetType.Float)) { - mv.visitInsn(FADD); - } else if (type.equals(TargetType.Double)) { - mv.visitInsn(DADD); - } else { - throw new CodeGenException("Invalid argument to Add expression"); - } - } - if (add.type().equals(TargetType.String)) { - generate(state, add.right()); - convertToString(state, add.right().type()); - mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "append", "(Ljava/lang/String;)Ljava/lang/StringBuilder;", false); - mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "toString", "()Ljava/lang/String;", false); - } - break; - } - case Sub sub: { - generate(state, sub.left()); - convertTo(state, sub.left().type(), op.type()); - generate(state, sub.right()); - convertTo(state, sub.right().type(), op.type()); - var type = sub.type(); - if (type.equals(TargetType.Byte) - || type.equals(TargetType.Char) - || type.equals(TargetType.Integer) - || type.equals(TargetType.Short)) { - mv.visitInsn(ISUB); + case Add add: { + if (add.type().equals(TargetType.String)) { + mv.visitTypeInsn(NEW, "java/lang/StringBuilder"); + mv.visitInsn(DUP); + generate(state, add.left()); + convertToString(state, add.left().type()); + mv.visitMethodInsn(INVOKESPECIAL, "java/lang/StringBuilder", "", "(Ljava/lang/String;)V", false); + } else { + generate(state, add.left()); + convertTo(state, add.left().type(), add.type()); + generate(state, add.right()); + convertTo(state, add.right().type(), add.type()); + var type = add.type(); + if (type.equals(TargetType.Byte) || type.equals(TargetType.Char) || type.equals(TargetType.Integer) || type.equals(TargetType.Short)) { + mv.visitInsn(IADD); } else if (type.equals(TargetType.Long)) { - mv.visitInsn(LSUB); + mv.visitInsn(LADD); } else if (type.equals(TargetType.Float)) { - mv.visitInsn(FSUB); + mv.visitInsn(FADD); } else if (type.equals(TargetType.Double)) { - mv.visitInsn(DSUB); + mv.visitInsn(DADD); } else { - throw new CodeGenException("Invalid argument to Sub expression"); + throw new CodeGenException("Invalid argument to Add expression"); } - break; } - case Div div: { - generate(state, div.left()); - convertTo(state, div.left().type(), op.type()); - generate(state, div.right()); - convertTo(state, div.right().type(), op.type()); - var type = div.type(); - if (type.equals(TargetType.Byte) - || type.equals(TargetType.Char) - || type.equals(TargetType.Integer) - || type.equals(TargetType.Short)) { - mv.visitInsn(IDIV); - } else if (type.equals(TargetType.Long)) { - mv.visitInsn(LDIV); - } else if (type.equals(TargetType.Float)) { - mv.visitInsn(FDIV); - } else if (type.equals(TargetType.Double)) { - mv.visitInsn(DDIV); - } else { - throw new CodeGenException("Invalid argument to Div expression"); - } - break; + if (add.type().equals(TargetType.String)) { + generate(state, add.right()); + convertToString(state, add.right().type()); + mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "append", "(Ljava/lang/String;)Ljava/lang/StringBuilder;", false); + mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "toString", "()Ljava/lang/String;", false); } - case Mul mul: { - generate(state, mul.left()); - convertTo(state, mul.left().type(), op.type()); - generate(state, mul.right()); - convertTo(state, mul.right().type(), op.type()); - var type = mul.type(); - if (type.equals(TargetType.Byte) - || type.equals(TargetType.Char) - || type.equals(TargetType.Integer) - || type.equals(TargetType.Short)) { - mv.visitInsn(IMUL); - } else if (type.equals(TargetType.Long)) { - mv.visitInsn(LMUL); - } else if (type.equals(TargetType.Float)) { - mv.visitInsn(FMUL); - } else if (type.equals(TargetType.Double)) { - mv.visitInsn(DMUL); - } else { - throw new CodeGenException("Invalid argument to Mul expression"); - } - break; + break; + } + case Sub sub: { + generate(state, sub.left()); + convertTo(state, sub.left().type(), op.type()); + generate(state, sub.right()); + convertTo(state, sub.right().type(), op.type()); + var type = sub.type(); + if (type.equals(TargetType.Byte) || type.equals(TargetType.Char) || type.equals(TargetType.Integer) || type.equals(TargetType.Short)) { + mv.visitInsn(ISUB); + } else if (type.equals(TargetType.Long)) { + mv.visitInsn(LSUB); + } else if (type.equals(TargetType.Float)) { + mv.visitInsn(FSUB); + } else if (type.equals(TargetType.Double)) { + mv.visitInsn(DSUB); + } else { + throw new CodeGenException("Invalid argument to Sub expression"); } - case Rem rem: { - generate(state, rem.left()); - convertTo(state, rem.left().type(), op.type()); - generate(state, rem.right()); - convertTo(state, rem.right().type(), op.type()); - var type = rem.type(); - if (type.equals(TargetType.Byte) - || type.equals(TargetType.Char) - || type.equals(TargetType.Integer) - || type.equals(TargetType.Short)) { - mv.visitInsn(IREM); - } else if (type.equals(TargetType.Long)) { - mv.visitInsn(LREM); - } else if (type.equals(TargetType.Float)) { - mv.visitInsn(FREM); - } else if (type.equals(TargetType.Double)) { - mv.visitInsn(DREM); - } else { - throw new CodeGenException("Invalid argument to Rem expression"); - } - break; + break; + } + case Div div: { + generate(state, div.left()); + convertTo(state, div.left().type(), op.type()); + generate(state, div.right()); + convertTo(state, div.right().type(), op.type()); + var type = div.type(); + if (type.equals(TargetType.Byte) || type.equals(TargetType.Char) || type.equals(TargetType.Integer) || type.equals(TargetType.Short)) { + mv.visitInsn(IDIV); + } else if (type.equals(TargetType.Long)) { + mv.visitInsn(LDIV); + } else if (type.equals(TargetType.Float)) { + mv.visitInsn(FDIV); + } else if (type.equals(TargetType.Double)) { + mv.visitInsn(DDIV); + } else { + throw new CodeGenException("Invalid argument to Div expression"); } - case Or or: { - Label or_false = new Label(); - Label or_true = new Label(); - Label end = new Label(); - generate(state, or.left()); - mv.visitJumpInsn(IFNE, or_true); - generate(state, or.right()); - mv.visitJumpInsn(IFEQ, or_false); - mv.visitLabel(or_true); - mv.visitInsn(ICONST_1); - mv.visitJumpInsn(GOTO, end); - mv.visitLabel(or_false); - mv.visitInsn(ICONST_0); - mv.visitLabel(end); - break; + break; + } + case Mul mul: { + generate(state, mul.left()); + convertTo(state, mul.left().type(), op.type()); + generate(state, mul.right()); + convertTo(state, mul.right().type(), op.type()); + var type = mul.type(); + if (type.equals(TargetType.Byte) || type.equals(TargetType.Char) || type.equals(TargetType.Integer) || type.equals(TargetType.Short)) { + mv.visitInsn(IMUL); + } else if (type.equals(TargetType.Long)) { + mv.visitInsn(LMUL); + } else if (type.equals(TargetType.Float)) { + mv.visitInsn(FMUL); + } else if (type.equals(TargetType.Double)) { + mv.visitInsn(DMUL); + } else { + throw new CodeGenException("Invalid argument to Mul expression"); } - case And and: { - Label and_false = new Label(); - Label end = new Label(); - generate(state, and.left()); - mv.visitJumpInsn(IFEQ, and_false); - generate(state, and.right()); - mv.visitJumpInsn(IFEQ, and_false); - mv.visitInsn(ICONST_1); - mv.visitJumpInsn(GOTO, end); - mv.visitLabel(and_false); - mv.visitInsn(ICONST_0); - mv.visitLabel(end); - break; + break; + } + case Rem rem: { + generate(state, rem.left()); + convertTo(state, rem.left().type(), op.type()); + generate(state, rem.right()); + convertTo(state, rem.right().type(), op.type()); + var type = rem.type(); + if (type.equals(TargetType.Byte) || type.equals(TargetType.Char) || type.equals(TargetType.Integer) || type.equals(TargetType.Short)) { + mv.visitInsn(IREM); + } else if (type.equals(TargetType.Long)) { + mv.visitInsn(LREM); + } else if (type.equals(TargetType.Float)) { + mv.visitInsn(FREM); + } else if (type.equals(TargetType.Double)) { + mv.visitInsn(DREM); + } else { + throw new CodeGenException("Invalid argument to Rem expression"); } - case BAnd band: { - generate(state, band.left()); - convertTo(state, band.left().type(), op.type()); - generate(state, band.right()); - convertTo(state, band.right().type(), op.type()); - if (band.type().equals(TargetType.Long)) - mv.visitInsn(LAND); - else mv.visitInsn(IAND); - break; + break; + } + case Or or: { + Label or_false = new Label(); + Label or_true = new Label(); + Label end = new Label(); + generate(state, or.left()); + mv.visitJumpInsn(IFNE, or_true); + generate(state, or.right()); + mv.visitJumpInsn(IFEQ, or_false); + mv.visitLabel(or_true); + mv.visitInsn(ICONST_1); + mv.visitJumpInsn(GOTO, end); + mv.visitLabel(or_false); + mv.visitInsn(ICONST_0); + mv.visitLabel(end); + break; + } + case And and: { + Label and_false = new Label(); + Label end = new Label(); + generate(state, and.left()); + mv.visitJumpInsn(IFEQ, and_false); + generate(state, and.right()); + mv.visitJumpInsn(IFEQ, and_false); + mv.visitInsn(ICONST_1); + mv.visitJumpInsn(GOTO, end); + mv.visitLabel(and_false); + mv.visitInsn(ICONST_0); + mv.visitLabel(end); + break; + } + case BAnd band: { + generate(state, band.left()); + convertTo(state, band.left().type(), op.type()); + generate(state, band.right()); + convertTo(state, band.right().type(), op.type()); + if (band.type().equals(TargetType.Long)) + mv.visitInsn(LAND); + else + mv.visitInsn(IAND); + break; + } + case BOr bor: { + generate(state, bor.left()); + convertTo(state, bor.left().type(), op.type()); + generate(state, bor.right()); + convertTo(state, bor.right().type(), op.type()); + if (bor.type().equals(TargetType.Long)) + mv.visitInsn(LOR); + else + mv.visitInsn(IOR); + break; + } + case XOr xor: { + generate(state, xor.left()); + convertTo(state, xor.left().type(), op.type()); + generate(state, xor.right()); + convertTo(state, xor.right().type(), op.type()); + if (xor.type().equals(TargetType.Long)) + mv.visitInsn(LXOR); + else + mv.visitInsn(IXOR); + break; + } + case Shl shl: { + generate(state, shl.left()); + convertTo(state, shl.left().type(), op.type()); + generate(state, shl.right()); + convertTo(state, shl.right().type(), op.type()); + if (shl.type().equals(TargetType.Long)) + mv.visitInsn(LSHL); + else + mv.visitInsn(ISHL); + break; + } + case Shr shr: { + generate(state, shr.left()); + convertTo(state, shr.left().type(), op.type()); + generate(state, shr.right()); + convertTo(state, shr.right().type(), op.type()); + if (shr.type().equals(TargetType.Long)) + mv.visitInsn(LSHR); + else + mv.visitInsn(ISHR); + break; + } + case UShr ushr: { + generate(state, ushr.left()); + convertTo(state, ushr.left().type(), op.type()); + generate(state, ushr.right()); + convertTo(state, ushr.right().type(), op.type()); + if (ushr.type().equals(TargetType.Long)) + mv.visitInsn(LUSHR); + else + mv.visitInsn(IUSHR); + break; + } + case Greater greater: { + var type = largerType(greater.left().type(), greater.right().type()); + if (type.equals(TargetType.Long)) { + generateRelationalOperator(state, greater, type, LCMP, IFGT); + } else if (type.equals(TargetType.Float)) { + generateRelationalOperator(state, greater, type, FCMPL, IFGT); + } else if (type.equals(TargetType.Double)) { + generateRelationalOperator(state, greater, type, DCMPL, IFGT); + } else { + generateRelationalOperator(state, greater, type, IF_ICMPGT); } - case BOr bor: { - generate(state, bor.left()); - convertTo(state, bor.left().type(), op.type()); - generate(state, bor.right()); - convertTo(state, bor.right().type(), op.type()); - if (bor.type().equals(TargetType.Long)) - mv.visitInsn(LOR); - else mv.visitInsn(IOR); - break; + break; + } + case Less less: { + var type = largerType(less.left().type(), less.right().type()); + if (type.equals(TargetType.Long)) { + generateRelationalOperator(state, less, type, LCMP, IFLT); + } else if (type.equals(TargetType.Float)) { + generateRelationalOperator(state, less, type, FCMPL, IFLT); + } else if (type.equals(TargetType.Double)) { + generateRelationalOperator(state, less, type, DCMPL, IFLT); + } else { + generateRelationalOperator(state, less, type, IF_ICMPLT); } - case XOr xor: { - generate(state, xor.left()); - convertTo(state, xor.left().type(), op.type()); - generate(state, xor.right()); - convertTo(state, xor.right().type(), op.type()); - if (xor.type().equals(TargetType.Long)) - mv.visitInsn(LXOR); - else mv.visitInsn(IXOR); - break; + break; + } + case GreaterOrEqual greaterOrEqual: { + var type = largerType(greaterOrEqual.left().type(), greaterOrEqual.right().type()); + if (type.equals(TargetType.Long)) { + generateRelationalOperator(state, greaterOrEqual, type, LCMP, IFGE); + } else if (type.equals(TargetType.Float)) { + generateRelationalOperator(state, greaterOrEqual, type, FCMPL, IFGE); + } else if (type.equals(TargetType.Double)) { + generateRelationalOperator(state, greaterOrEqual, type, DCMPL, IFGE); + } else { + generateRelationalOperator(state, greaterOrEqual, type, IF_ICMPGE); } - case Shl shl: { - generate(state, shl.left()); - convertTo(state, shl.left().type(), op.type()); - generate(state, shl.right()); - convertTo(state, shl.right().type(), op.type()); - if (shl.type().equals(TargetType.Long)) - mv.visitInsn(LSHL); - else mv.visitInsn(ISHL); - break; + break; + } + case LessOrEqual lessOrEqual: { + var type = largerType(lessOrEqual.left().type(), lessOrEqual.right().type()); + if (type.equals(TargetType.Long)) { + generateRelationalOperator(state, lessOrEqual, type, LCMP, IFLE); + } else if (type.equals(TargetType.Float)) { + generateRelationalOperator(state, lessOrEqual, type, FCMPL, IFLE); + } else if (type.equals(TargetType.Double)) { + generateRelationalOperator(state, lessOrEqual, type, DCMPL, IFLE); + } else { + generateRelationalOperator(state, lessOrEqual, type, IF_ICMPLE); } - case Shr shr: { - generate(state, shr.left()); - convertTo(state, shr.left().type(), op.type()); - generate(state, shr.right()); - convertTo(state, shr.right().type(), op.type()); - if (shr.type().equals(TargetType.Long)) - mv.visitInsn(LSHR); - else mv.visitInsn(ISHR); - break; + break; + } + case Equal equal: { + var type = largerType(equal.left().type(), equal.right().type()); + if (type.equals(TargetType.Long)) { + generateRelationalOperator(state, equal, type, LCMP, IFEQ); + } else if (type.equals(TargetType.Float)) { + generateRelationalOperator(state, equal, type, FCMPL, IFEQ); + } else if (type.equals(TargetType.Double)) { + generateRelationalOperator(state, equal, type, DCMPL, IFEQ); + } else if (type.equals(TargetType.Char) || type.equals(TargetType.Short) || type.equals(TargetType.Byte) || type.equals(TargetType.Integer) || type.equals(TargetType.Boolean)) { + generateRelationalOperator(state, equal, type, IF_ICMPEQ); + } else { + generateRelationalOperator(state, equal, type, IF_ACMPEQ); } - case UShr ushr: { - generate(state, ushr.left()); - convertTo(state, ushr.left().type(), op.type()); - generate(state, ushr.right()); - convertTo(state, ushr.right().type(), op.type()); - if (ushr.type().equals(TargetType.Long)) - mv.visitInsn(LUSHR); - else mv.visitInsn(IUSHR); - break; - } - case Greater greater: { - var type = largerType(greater.left().type(), greater.right().type()); - if (type.equals(TargetType.Long)) { - generateRelationalOperator(state, greater, type, LCMP, IFGT); - } else if (type.equals(TargetType.Float)) { - generateRelationalOperator(state, greater, type, FCMPL, IFGT); - } else if (type.equals(TargetType.Double)) { - generateRelationalOperator(state, greater, type, DCMPL, IFGT); - } else { - generateRelationalOperator(state, greater, type, IF_ICMPGT); - } - break; - } - case Less less: { - var type = largerType(less.left().type(), less.right().type()); - if (type.equals(TargetType.Long)) { - generateRelationalOperator(state, less, type, LCMP, IFLT); - } else if (type.equals(TargetType.Float)) { - generateRelationalOperator(state, less, type, FCMPL, IFLT); - } else if (type.equals(TargetType.Double)) { - generateRelationalOperator(state, less, type, DCMPL, IFLT); - } else { - generateRelationalOperator(state, less, type, IF_ICMPLT); - } - break; - } - case GreaterOrEqual greaterOrEqual: { - var type = largerType(greaterOrEqual.left().type(), greaterOrEqual.right().type()); - if (type.equals(TargetType.Long)) { - generateRelationalOperator(state, greaterOrEqual, type, LCMP, IFGE); - } else if (type.equals(TargetType.Float)) { - generateRelationalOperator(state, greaterOrEqual, type, FCMPL, IFGE); - } else if (type.equals(TargetType.Double)) { - generateRelationalOperator(state, greaterOrEqual, type, DCMPL, IFGE); - } else { - generateRelationalOperator(state, greaterOrEqual, type, IF_ICMPGE); - } - break; - } - case LessOrEqual lessOrEqual: { - var type = largerType(lessOrEqual.left().type(), lessOrEqual.right().type()); - if (type.equals(TargetType.Long)) { - generateRelationalOperator(state, lessOrEqual, type, LCMP, IFLE); - } else if (type.equals(TargetType.Float)) { - generateRelationalOperator(state, lessOrEqual, type, FCMPL, IFLE); - } else if (type.equals(TargetType.Double)) { - generateRelationalOperator(state, lessOrEqual, type, DCMPL, IFLE); - } else { - generateRelationalOperator(state, lessOrEqual, type, IF_ICMPLE); - } - break; - } - case Equal equal: { - var type = largerType(equal.left().type(), equal.right().type()); - if (type.equals(TargetType.Long)) { - generateRelationalOperator(state, equal, type, LCMP, IFEQ); - } else if (type.equals(TargetType.Float)) { - generateRelationalOperator(state, equal, type, FCMPL, IFEQ); - } else if (type.equals(TargetType.Double)) { - generateRelationalOperator(state, equal, type, DCMPL, IFEQ); - } else if (type.equals(TargetType.Char) - || type.equals(TargetType.Short) - || type.equals(TargetType.Byte) - || type.equals(TargetType.Integer) - || type.equals(TargetType.Boolean)) { - generateRelationalOperator(state, equal, type, IF_ICMPEQ); - } else { - generateRelationalOperator(state, equal, type, IF_ACMPEQ); - } - break; - } - case NotEqual notEqual: { - var type = largerType(notEqual.left().type(), notEqual.right().type()); - if (type.equals(TargetType.Long)) { - generateRelationalOperator(state, notEqual, type, LCMP, IFNE); - } else if (type.equals(TargetType.Float)) { - generateRelationalOperator(state, notEqual, type, FCMPL, IFNE); - } else if (type.equals(TargetType.Double)) { - generateRelationalOperator(state, notEqual, type, DCMPL, IFNE); - } else if (type.equals(TargetType.Char) - || type.equals(TargetType.Short) - || type.equals(TargetType.Byte) - || type.equals(TargetType.Integer)) { - generateRelationalOperator(state, notEqual, type, IF_ICMPNE); - } else { - generateRelationalOperator(state, notEqual, type, IF_ACMPNE); - } - break; + break; + } + case NotEqual notEqual: { + var type = largerType(notEqual.left().type(), notEqual.right().type()); + if (type.equals(TargetType.Long)) { + generateRelationalOperator(state, notEqual, type, LCMP, IFNE); + } else if (type.equals(TargetType.Float)) { + generateRelationalOperator(state, notEqual, type, FCMPL, IFNE); + } else if (type.equals(TargetType.Double)) { + generateRelationalOperator(state, notEqual, type, DCMPL, IFNE); + } else if (type.equals(TargetType.Char) || type.equals(TargetType.Short) || type.equals(TargetType.Byte) || type.equals(TargetType.Integer)) { + generateRelationalOperator(state, notEqual, type, IF_ICMPNE); + } else { + generateRelationalOperator(state, notEqual, type, IF_ACMPNE); } + break; + } } } @@ -588,118 +564,119 @@ public class Codegen { private void generateUnaryOp(State state, TargetUnaryOp op) { var mv = state.mv; switch (op) { - case TargetUnaryOp.Add add: - // This literally does nothing - generate(state, add.expr()); - break; - case TargetUnaryOp.Negate negate: - generate(state, negate.expr()); - if (negate.type().equals(TargetType.Double)) - mv.visitInsn(DNEG); - else if (negate.type().equals(TargetType.Float)) - mv.visitInsn(FNEG); - else if (negate.type().equals(TargetType.Long)) - mv.visitInsn(LNEG); - else mv.visitInsn(INEG); - break; - case TargetUnaryOp.Not not: - generate(state, not.expr()); - if (not.type().equals(TargetType.Long)) { - mv.visitLdcInsn(-1L); - mv.visitInsn(LXOR); - } else { - mv.visitInsn(ICONST_M1); - mv.visitInsn(IXOR); - } - break; - case TargetUnaryOp.PreIncrement preIncrement: - generate(state, preIncrement.expr()); - if (preIncrement.type().equals(TargetType.Float)) { - mv.visitLdcInsn(1F); - mv.visitInsn(FADD); - mv.visitInsn(DUP); - } else if (preIncrement.type().equals(TargetType.Double)) { - mv.visitLdcInsn(1D); - mv.visitInsn(DADD); - mv.visitInsn(DUP2); - } else if (preIncrement.type().equals(TargetType.Long)) { - mv.visitLdcInsn(1L); - mv.visitInsn(LADD); - mv.visitInsn(DUP2); - } else { - mv.visitLdcInsn(1); - mv.visitInsn(IADD); - mv.visitInsn(DUP); - } - boxPrimitive(state, preIncrement.type()); - afterIncDec(state, preIncrement); - break; - case TargetUnaryOp.PreDecrement preDecrement: - generate(state, preDecrement.expr()); - if (preDecrement.type().equals(TargetType.Float)) { - mv.visitLdcInsn(1F); - mv.visitInsn(FSUB); - mv.visitInsn(DUP); - } else if (preDecrement.type().equals(TargetType.Double)) { - mv.visitLdcInsn(1D); - mv.visitInsn(DSUB); - mv.visitInsn(DUP2); - } else if (preDecrement.type().equals(TargetType.Long)) { - mv.visitLdcInsn(1L); - mv.visitInsn(LSUB); - mv.visitInsn(DUP2); - } else { - mv.visitLdcInsn(1); - mv.visitInsn(ISUB); - mv.visitInsn(DUP); - } - boxPrimitive(state, preDecrement.type()); - afterIncDec(state, preDecrement); - break; - case TargetUnaryOp.PostIncrement postIncrement: - generate(state, postIncrement.expr()); - if (postIncrement.type().equals(TargetType.Float)) { - mv.visitInsn(DUP); - mv.visitLdcInsn(1F); - mv.visitInsn(FADD); - } else if (postIncrement.type().equals(TargetType.Double)) { - mv.visitInsn(DUP2); - mv.visitLdcInsn(1D); - mv.visitInsn(DADD); - } else if (postIncrement.type().equals(TargetType.Long)) { - mv.visitInsn(DUP2); - mv.visitLdcInsn(1L); - mv.visitInsn(LADD); - } else { - mv.visitInsn(DUP); - mv.visitLdcInsn(1); - mv.visitInsn(IADD); - } - boxPrimitive(state, postIncrement.type()); - afterIncDec(state, postIncrement); - break; - case TargetUnaryOp.PostDecrement postDecrement: - generate(state, postDecrement.expr()); - if (postDecrement.type().equals(TargetType.Float)) { - mv.visitInsn(DUP); - mv.visitLdcInsn(1F); - mv.visitInsn(FSUB); - } else if (postDecrement.type().equals(TargetType.Double)) { - mv.visitInsn(DUP2); - mv.visitLdcInsn(1D); - mv.visitInsn(DSUB); - } else if (postDecrement.type().equals(TargetType.Long)) { - mv.visitInsn(DUP2); - mv.visitLdcInsn(1L); - mv.visitInsn(LSUB); - } else { - mv.visitInsn(DUP); - mv.visitLdcInsn(1); - mv.visitInsn(ISUB); - } - boxPrimitive(state, postDecrement.type()); - afterIncDec(state, postDecrement); - break; + case TargetUnaryOp.Add add: + // This literally does nothing + generate(state, add.expr()); + break; + case TargetUnaryOp.Negate negate: + generate(state, negate.expr()); + if (negate.type().equals(TargetType.Double)) + mv.visitInsn(DNEG); + else if (negate.type().equals(TargetType.Float)) + mv.visitInsn(FNEG); + else if (negate.type().equals(TargetType.Long)) + mv.visitInsn(LNEG); + else + mv.visitInsn(INEG); + break; + case TargetUnaryOp.Not not: + generate(state, not.expr()); + if (not.type().equals(TargetType.Long)) { + mv.visitLdcInsn(-1L); + mv.visitInsn(LXOR); + } else { + mv.visitInsn(ICONST_M1); + mv.visitInsn(IXOR); + } + break; + case TargetUnaryOp.PreIncrement preIncrement: + generate(state, preIncrement.expr()); + if (preIncrement.type().equals(TargetType.Float)) { + mv.visitLdcInsn(1F); + mv.visitInsn(FADD); + mv.visitInsn(DUP); + } else if (preIncrement.type().equals(TargetType.Double)) { + mv.visitLdcInsn(1D); + mv.visitInsn(DADD); + mv.visitInsn(DUP2); + } else if (preIncrement.type().equals(TargetType.Long)) { + mv.visitLdcInsn(1L); + mv.visitInsn(LADD); + mv.visitInsn(DUP2); + } else { + mv.visitLdcInsn(1); + mv.visitInsn(IADD); + mv.visitInsn(DUP); + } + boxPrimitive(state, preIncrement.type()); + afterIncDec(state, preIncrement); + break; + case TargetUnaryOp.PreDecrement preDecrement: + generate(state, preDecrement.expr()); + if (preDecrement.type().equals(TargetType.Float)) { + mv.visitLdcInsn(1F); + mv.visitInsn(FSUB); + mv.visitInsn(DUP); + } else if (preDecrement.type().equals(TargetType.Double)) { + mv.visitLdcInsn(1D); + mv.visitInsn(DSUB); + mv.visitInsn(DUP2); + } else if (preDecrement.type().equals(TargetType.Long)) { + mv.visitLdcInsn(1L); + mv.visitInsn(LSUB); + mv.visitInsn(DUP2); + } else { + mv.visitLdcInsn(1); + mv.visitInsn(ISUB); + mv.visitInsn(DUP); + } + boxPrimitive(state, preDecrement.type()); + afterIncDec(state, preDecrement); + break; + case TargetUnaryOp.PostIncrement postIncrement: + generate(state, postIncrement.expr()); + if (postIncrement.type().equals(TargetType.Float)) { + mv.visitInsn(DUP); + mv.visitLdcInsn(1F); + mv.visitInsn(FADD); + } else if (postIncrement.type().equals(TargetType.Double)) { + mv.visitInsn(DUP2); + mv.visitLdcInsn(1D); + mv.visitInsn(DADD); + } else if (postIncrement.type().equals(TargetType.Long)) { + mv.visitInsn(DUP2); + mv.visitLdcInsn(1L); + mv.visitInsn(LADD); + } else { + mv.visitInsn(DUP); + mv.visitLdcInsn(1); + mv.visitInsn(IADD); + } + boxPrimitive(state, postIncrement.type()); + afterIncDec(state, postIncrement); + break; + case TargetUnaryOp.PostDecrement postDecrement: + generate(state, postDecrement.expr()); + if (postDecrement.type().equals(TargetType.Float)) { + mv.visitInsn(DUP); + mv.visitLdcInsn(1F); + mv.visitInsn(FSUB); + } else if (postDecrement.type().equals(TargetType.Double)) { + mv.visitInsn(DUP2); + mv.visitLdcInsn(1D); + mv.visitInsn(DSUB); + } else if (postDecrement.type().equals(TargetType.Long)) { + mv.visitInsn(DUP2); + mv.visitLdcInsn(1L); + mv.visitInsn(LSUB); + } else { + mv.visitInsn(DUP); + mv.visitLdcInsn(1); + mv.visitInsn(ISUB); + } + boxPrimitive(state, postDecrement.type()); + afterIncDec(state, postDecrement); + break; } } @@ -712,33 +689,17 @@ public class Codegen { } else { var name = "lambda$" + lambdaCounter++; var parameters = new ArrayList<>(lambda.captures()); - parameters.addAll(lambda.params().stream() - .map(param -> param.type() instanceof TargetGenericType ? new MethodParameter(TargetType.Object, param.name()) : param) - .toList()); + parameters.addAll(lambda.params().stream().map(param -> param.type() instanceof TargetGenericType ? new MethodParameter(TargetType.Object, param.name()) : param).toList()); - impl = new TargetMethod( - 0, name, - lambda.block(), - new TargetMethod.Signature( - Set.of(), - parameters, - lambda.returnType() instanceof TargetGenericType ? TargetType.Object : lambda.returnType() - ), - null - ); + impl = new TargetMethod(0, name, lambda.block(), new TargetMethod.Signature(Set.of(), parameters, lambda.returnType() instanceof TargetGenericType ? TargetType.Object : lambda.returnType()), null); generateMethod(impl); lambdas.put(lambda, impl); } - var mt = MethodType.methodType(CallSite.class, MethodHandles.Lookup.class, String.class, - MethodType.class, MethodType.class, MethodHandle.class, MethodType.class); + var mt = MethodType.methodType(CallSite.class, MethodHandles.Lookup.class, String.class, MethodType.class, MethodType.class, MethodHandle.class, MethodType.class); - var bootstrap = new Handle(H_INVOKESTATIC, "java/lang/invoke/LambdaMetafactory", "metafactory", - mt.toMethodDescriptorString(), false); - var handle = new Handle( - H_INVOKEVIRTUAL, clazz.getName(), impl.name(), - impl.getDescriptor(), false - ); + var bootstrap = new Handle(H_INVOKESTATIC, "java/lang/invoke/LambdaMetafactory", "metafactory", mt.toMethodDescriptorString(), false); + var handle = new Handle(H_INVOKEVIRTUAL, clazz.getName(), impl.name(), impl.getDescriptor(), false); // TODO maybe make this a function? var desugared = "("; @@ -747,250 +708,234 @@ public class Codegen { desugared += ")"; if (lambda.returnType() != null) desugared += "Ljava/lang/Object;"; - else desugared += "V"; + else + desugared += "V"; var params = new ArrayList(); params.add(new TargetRefType(clazz.qualifiedName())); - params.addAll(lambda.captures().stream() - .map(MethodParameter::type) - .toList()); + params.addAll(lambda.captures().stream().map(MethodParameter::type).toList()); var descriptor = TargetMethod.getDescriptor(lambda.type(), params.toArray(TargetType[]::new)); mv.visitVarInsn(ALOAD, 0); for (var capture : lambda.captures()) mv.visitVarInsn(ALOAD, state.scope.get(capture.name()).index); - mv.visitInvokeDynamicInsn("apply", descriptor, - bootstrap, Type.getType(desugared), handle, - Type.getType(TargetMethod.getDescriptor(impl.signature().returnType(), lambda.params().stream().map(MethodParameter::type).toArray(TargetType[]::new))) - ); + mv.visitInvokeDynamicInsn("apply", descriptor, bootstrap, Type.getType(desugared), handle, Type.getType(TargetMethod.getDescriptor(impl.signature().returnType(), lambda.params().stream().map(MethodParameter::type).toArray(TargetType[]::new)))); } private void generate(State state, TargetExpression expr) { var mv = state.mv; switch (expr) { - case TargetClassName ignored: - break; // NOP - case TargetBlock block: { - var localCounter = state.localCounter; - state.enterScope(); - for (var e : block.statements()) { - generate(state, e); - if (e instanceof TargetMethodCall) { - if (e.type() != null) popValue(state, e.type()); - } else if (e instanceof TargetAssign) { - mv.visitInsn(POP); // TODO Nasty fix, we don't know if it is a primitive double or long - } else if (e instanceof TargetStatementExpression se) { - popValue(state, se.type()); - } + case TargetClassName ignored: + break; // NOP + case TargetBlock block: { + var localCounter = state.localCounter; + state.enterScope(); + for (var e : block.statements()) { + generate(state, e); + if (e instanceof TargetMethodCall) { + if (e.type() != null) + popValue(state, e.type()); + } else if (e instanceof TargetAssign) { + mv.visitInsn(POP); // TODO Nasty fix, we don't know if it is a primitive double or long + } else if (e instanceof TargetStatementExpression se) { + popValue(state, se.type()); } - state.exitScope(); - state.localCounter = localCounter; - break; } - case TargetCast cast: - generate(state, cast.expr()); - convertTo(state, cast.expr().type(), cast.type()); + state.exitScope(); + state.localCounter = localCounter; + break; + } + case TargetCast cast: + generate(state, cast.expr()); + convertTo(state, cast.expr().type(), cast.type()); + break; + case TargetInstanceOf instanceOf: + mv.visitTypeInsn(INSTANCEOF, instanceOf.right().getInternalName()); + break; + case TargetLiteral literal: + switch (literal) { + case IntLiteral intLiteral: + mv.visitLdcInsn(intLiteral.value()); break; - case TargetInstanceOf instanceOf: - mv.visitTypeInsn(INSTANCEOF, instanceOf.right().getInternalName()); + case FloatLiteral floatLiteral: + mv.visitLdcInsn(floatLiteral.value()); break; - case TargetLiteral literal: - switch (literal) { - case IntLiteral intLiteral: - mv.visitLdcInsn(intLiteral.value()); - break; - case FloatLiteral floatLiteral: - mv.visitLdcInsn(floatLiteral.value()); - break; - case LongLiteral longLiteral: - mv.visitLdcInsn(longLiteral.value()); - break; - case StringLiteral stringLiteral: - mv.visitLdcInsn(stringLiteral.value()); - break; - case CharLiteral charLiteral: - mv.visitIntInsn(BIPUSH, charLiteral.value()); - break; - case DoubleLiteral doubleLiteral: - mv.visitLdcInsn(doubleLiteral.value()); - break; - case BooleanLiteral booleanLiteral: - if (booleanLiteral.value()) { - mv.visitInsn(ICONST_1); - } else { - mv.visitInsn(ICONST_0); - } - break; - } + case LongLiteral longLiteral: + mv.visitLdcInsn(longLiteral.value()); break; - case TargetVarDecl varDecl: { - var local = state.createVariable(varDecl.name(), varDecl.varType()); - if (varDecl.value() != null) { - generate(state, varDecl.value()); - boxPrimitive(state, varDecl.varType()); - mv.visitVarInsn(ASTORE, local.index()); + case StringLiteral stringLiteral: + mv.visitLdcInsn(stringLiteral.value()); + break; + case CharLiteral charLiteral: + mv.visitIntInsn(BIPUSH, charLiteral.value()); + break; + case DoubleLiteral doubleLiteral: + mv.visitLdcInsn(doubleLiteral.value()); + break; + case BooleanLiteral booleanLiteral: + if (booleanLiteral.value()) { + mv.visitInsn(ICONST_1); } else { - mv.visitInsn(ACONST_NULL); - mv.visitVarInsn(ASTORE, local.index()); - } - break; - } - case TargetBinaryOp op: - generateBinaryOp(state, op); - break; - case TargetUnaryOp op: - generateUnaryOp(state, op); - break; - case TargetAssign assign: { - switch (assign.left()) { - case TargetLocalVar localVar: { - generate(state, assign.right()); - convertTo(state, assign.right().type(), localVar.type()); - boxPrimitive(state, localVar.type()); - var local = state.scope.get(localVar.name()); - mv.visitInsn(DUP); - mv.visitVarInsn(ASTORE, local.index()); - break; - } - case TargetFieldVar dot: { - var fieldType = dot.type(); - generate(state, dot.left()); - generate(state, assign.right()); - convertTo(state, assign.right().type(), fieldType); - boxPrimitive(state, fieldType); - if (dot.isStatic()) - mv.visitInsn(DUP); - else mv.visitInsn(DUP_X1); - mv.visitFieldInsn(dot.isStatic() ? PUTSTATIC : PUTFIELD, dot.owner().getInternalName(), dot.right(), fieldType.toSignature()); - break; - } - default: - throw new CodeGenException("Invalid assignment"); + mv.visitInsn(ICONST_0); } break; } + break; + case TargetBinaryOp op: + generateBinaryOp(state, op); + break; + case TargetUnaryOp op: + generateUnaryOp(state, op); + break; + case TargetAssign assign: { + switch (assign.left()) { case TargetLocalVar localVar: { - LocalVar local = state.scope.get(localVar.name()); - mv.visitVarInsn(ALOAD, local.index()); - unboxPrimitive(state, local.type()); + generate(state, assign.right()); + convertTo(state, assign.right().type(), localVar.type()); + boxPrimitive(state, localVar.type()); + var local = state.scope.get(localVar.name()); + mv.visitInsn(DUP); + mv.visitVarInsn(ASTORE, local.index()); break; } case TargetFieldVar dot: { - if (!dot.isStatic()) - generate(state, dot.left()); - mv.visitFieldInsn(dot.isStatic() ? GETSTATIC : GETFIELD, dot.left().type().getInternalName(), dot.right(), dot.type().toSignature()); - unboxPrimitive(state, dot.type()); - break; - } - case TargetFor _for: { - state.enterScope(); - var localCounter = state.localCounter; - if (_for.init() != null) - generate(state, _for.init()); - Label start = new Label(); - Label end = new Label(); - mv.visitLabel(start); - if (_for.termination() != null) - generate(state, _for.termination()); - else mv.visitInsn(ICONST_1); - mv.visitJumpInsn(IFEQ, end); - generate(state, _for.body()); - if (_for.increment() != null) { - generate(state, _for.increment()); - if (_for.increment().type() != null) { - popValue(state, _for.increment().type()); - } - } - mv.visitJumpInsn(GOTO, start); - mv.visitLabel(end); - state.exitScope(); - state.localCounter = localCounter; - break; - } - case TargetWhile _while: { - Label start = new Label(); - Label end = new Label(); - mv.visitLabel(start); - generate(state, _while.cond()); - mv.visitJumpInsn(IFEQ, end); - generate(state, _while.body()); - mv.visitJumpInsn(GOTO, start); - mv.visitLabel(end); - break; - } - case TargetIf _if: { - generate(state, _if.cond()); - Label _else = new Label(); - Label end = new Label(); - mv.visitJumpInsn(IFEQ, _else); - generate(state, _if.if_body()); - mv.visitJumpInsn(GOTO, end); - mv.visitLabel(_else); - if (_if.else_body() != null) { - generate(state, _if.else_body()); - } - mv.visitLabel(end); - break; - } - case TargetReturn ret: { - if (ret.expression() != null && state.returnType != null) { - generate(state, ret.expression()); - convertTo(state, ret.expression().type(), state.returnType); - boxPrimitive(state, state.returnType); - mv.visitInsn(ARETURN); - } else mv.visitInsn(RETURN); - break; - } - case TargetThis _this: { - mv.visitVarInsn(ALOAD, 0); - break; - } - case TargetSuper _super: { - mv.visitVarInsn(ALOAD, 0); - break; - } - case TargetMethodCall call: { - generate(state, call.expr()); - for (var i = 0; i < call.args().size(); i++) { - var e = call.args().get(i); - var arg = call.parameterTypes().get(i); - generate(state, e); - if (!(arg instanceof TargetPrimitiveType)) - boxPrimitive(state, e.type()); - } - var descriptor = call.getDescriptor(); - if (call.owner() instanceof TargetFunNType) // Decay FunN - descriptor = TargetMethod.getDescriptor( - call.returnType() == null ? null : TargetType.Object, - call.parameterTypes().stream().map(x -> TargetType.Object).toArray(TargetType[]::new) - ); - - mv.visitMethodInsn(call.isInterface() ? INVOKEINTERFACE : call.isStatic() ? INVOKESTATIC: call.name().equals("") ? INVOKESPECIAL : INVOKEVIRTUAL, - call.owner().getInternalName(), call.name(), descriptor, call.isInterface()); - - if (call.type() != null && call.returnType() != null && !(call.returnType() instanceof TargetPrimitiveType)) { - if (!call.returnType().equals(call.type()) && !(call.type() instanceof TargetGenericType)) - mv.visitTypeInsn(CHECKCAST, call.type().getInternalName()); - unboxPrimitive(state, call.type()); - } - break; - } - case TargetLambdaExpression lambda: - generateLambdaExpression(state, lambda); - break; - case TargetNew _new: { - mv.visitTypeInsn(NEW, _new.type().getInternalName()); - mv.visitInsn(DUP); - for (TargetExpression e : _new.params()) { - generate(state, e); - boxPrimitive(state, e.type()); - } - mv.visitMethodInsn(INVOKESPECIAL, _new.type().getInternalName(), "", _new.getDescriptor(), false); + var fieldType = dot.type(); + generate(state, dot.left()); + generate(state, assign.right()); + convertTo(state, assign.right().type(), fieldType); + boxPrimitive(state, fieldType); + if (dot.isStatic()) + mv.visitInsn(DUP); + else + mv.visitInsn(DUP_X1); + mv.visitFieldInsn(dot.isStatic() ? PUTSTATIC : PUTFIELD, dot.owner().getInternalName(), dot.right(), fieldType.toSignature()); break; } default: - throw new CodeGenException("Unexpected value: " + expr); + throw new CodeGenException("Invalid assignment"); + } + break; + } + case TargetLocalVar localVar: { + LocalVar local = state.scope.get(localVar.name()); + mv.visitVarInsn(ALOAD, local.index()); + unboxPrimitive(state, local.type()); + break; + } + case TargetFieldVar dot: { + if (!dot.isStatic()) + generate(state, dot.left()); + mv.visitFieldInsn(dot.isStatic() ? GETSTATIC : GETFIELD, dot.left().type().getInternalName(), dot.right(), dot.type().toSignature()); + unboxPrimitive(state, dot.type()); + break; + } + case TargetFor _for: { + state.enterScope(); + var localCounter = state.localCounter; + if (_for.init() != null) + generate(state, _for.init()); + Label start = new Label(); + Label end = new Label(); + mv.visitLabel(start); + if (_for.termination() != null) + generate(state, _for.termination()); + else + mv.visitInsn(ICONST_1); + mv.visitJumpInsn(IFEQ, end); + generate(state, _for.body()); + if (_for.increment() != null) { + generate(state, _for.increment()); + if (_for.increment().type() != null) { + popValue(state, _for.increment().type()); + } + } + mv.visitJumpInsn(GOTO, start); + mv.visitLabel(end); + state.exitScope(); + state.localCounter = localCounter; + break; + } + case TargetWhile _while: { + Label start = new Label(); + Label end = new Label(); + mv.visitLabel(start); + generate(state, _while.cond()); + mv.visitJumpInsn(IFEQ, end); + generate(state, _while.body()); + mv.visitJumpInsn(GOTO, start); + mv.visitLabel(end); + break; + } + case TargetIf _if: { + generate(state, _if.cond()); + Label _else = new Label(); + Label end = new Label(); + mv.visitJumpInsn(IFEQ, _else); + generate(state, _if.if_body()); + mv.visitJumpInsn(GOTO, end); + mv.visitLabel(_else); + if (_if.else_body() != null) { + generate(state, _if.else_body()); + } + mv.visitLabel(end); + break; + } + case TargetReturn ret: { + if (ret.expression() != null && state.returnType != null) { + generate(state, ret.expression()); + convertTo(state, ret.expression().type(), state.returnType); + boxPrimitive(state, state.returnType); + mv.visitInsn(ARETURN); + } else + mv.visitInsn(RETURN); + break; + } + case TargetThis _this: { + mv.visitVarInsn(ALOAD, 0); + break; + } + case TargetSuper _super: { + mv.visitVarInsn(ALOAD, 0); + break; + } + case TargetMethodCall call: { + generate(state, call.expr()); + for (var i = 0; i < call.args().size(); i++) { + var e = call.args().get(i); + var arg = call.parameterTypes().get(i); + generate(state, e); + if (!(arg instanceof TargetPrimitiveType)) + boxPrimitive(state, e.type()); + } + var descriptor = call.getDescriptor(); + if (call.owner() instanceof TargetFunNType) // Decay FunN + descriptor = TargetMethod.getDescriptor(call.returnType() == null ? null : TargetType.Object, call.parameterTypes().stream().map(x -> TargetType.Object).toArray(TargetType[]::new)); + + mv.visitMethodInsn(call.isInterface() ? INVOKEINTERFACE : call.isStatic() ? INVOKESTATIC : call.name().equals("") ? INVOKESPECIAL : INVOKEVIRTUAL, call.owner().getInternalName(), call.name(), descriptor, call.isInterface()); + + if (call.type() != null && call.returnType() != null && !(call.returnType() instanceof TargetPrimitiveType)) { + if (!call.returnType().equals(call.type()) && !(call.type() instanceof TargetGenericType)) + mv.visitTypeInsn(CHECKCAST, call.type().getInternalName()); + unboxPrimitive(state, call.type()); + } + break; + } + case TargetLambdaExpression lambda: + generateLambdaExpression(state, lambda); + break; + case TargetNew _new: { + mv.visitTypeInsn(NEW, _new.type().getInternalName()); + mv.visitInsn(DUP); + for (TargetExpression e : _new.params()) { + generate(state, e); + boxPrimitive(state, e.type()); + } + mv.visitMethodInsn(INVOKESPECIAL, _new.type().getInternalName(), "", _new.getDescriptor(), false); + break; + } + default: + throw new CodeGenException("Unexpected value: " + expr); } } @@ -1005,7 +950,7 @@ public class Codegen { mv.visitCode(); var state = new State(null, mv, 1); - for (var param: constructor.parameters()) + for (var param : constructor.parameters()) state.createVariable(param.name(), param.type()); var stmts = constructor.block().statements(); @@ -1033,7 +978,7 @@ public class Codegen { mv.visitCode(); var state = new State(method.signature().returnType(), mv, method.isStatic() ? 0 : 1); - for (var param: method.signature().parameters()) + for (var param : method.signature().parameters()) state.createVariable(param.name(), param.type()); generate(state, method.block()); if (method.signature().returnType() == null) @@ -1057,10 +1002,7 @@ public class Codegen { } public byte[] generate() { - cw.visit(V1_8, clazz.modifiers() | ACC_PUBLIC | ACC_SUPER, clazz.qualifiedName(), - generateSignature(clazz, clazz.generics()), clazz.superType() != null ? clazz.superType().getInternalName(): "java/lang/Object", - clazz.implementingInterfaces().stream().map(TargetType::toSignature).toArray(String[]::new) - ); + cw.visit(V1_8, clazz.modifiers() | ACC_PUBLIC | ACC_SUPER, clazz.qualifiedName(), generateSignature(clazz, clazz.generics()), clazz.superType() != null ? clazz.superType().getInternalName() : "java/lang/Object", clazz.implementingInterfaces().stream().map(TargetType::toSignature).toArray(String[]::new)); if (clazz.txGenerics() != null) cw.visitAttribute(new JavaTXSignatureAttribute(generateSignature(clazz, clazz.txGenerics()))); diff --git a/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java b/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java index 04537c2c..f2353709 100644 --- a/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java +++ b/src/main/java/de/dhbwstuttgart/core/JavaTXCompiler.java @@ -10,7 +10,7 @@ import de.dhbwstuttgart.parser.JavaTXParser; import de.dhbwstuttgart.parser.NullToken; import de.dhbwstuttgart.parser.scope.GenericsRegistry; import de.dhbwstuttgart.parser.SyntaxTreeGenerator.SyntaxTreeGenerator; -import de.dhbwstuttgart.parser.antlr.Java8Parser.CompilationUnitContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.SourceFileContext; import de.dhbwstuttgart.parser.scope.JavaClassName; import de.dhbwstuttgart.syntaxtree.ClassOrInterface; import de.dhbwstuttgart.syntaxtree.GenericTypeVar; @@ -58,148 +58,121 @@ import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.*; +import java.util.Map.Entry; import java.util.function.Function; import java.util.stream.Collectors; +import org.antlr.v4.runtime.Token; import org.apache.commons.io.output.NullOutputStream; - public class JavaTXCompiler { - //public static JavaTXCompiler INSTANCE; - final CompilationEnvironment environment; + // public static JavaTXCompiler INSTANCE; + final CompilationEnvironment environment; Boolean resultmodel = false; - public final Map sourceFiles = new HashMap<>(); - Boolean log = false; //gibt an ob ein Log-File nach System.getProperty("user.dir")+""/logFiles/"" geschrieben werden soll? - public volatile UnifyTaskModel usedTasks = new UnifyTaskModel(); - private final DirectoryClassLoader classLoader; - + public final Map sourceFiles = new HashMap<>(); + Boolean log = false; // gibt an ob ein Log-File nach System.getProperty("user.dir")+""/logFiles/"" geschrieben werden soll? + public volatile UnifyTaskModel usedTasks = new UnifyTaskModel(); + private final DirectoryClassLoader classLoader; + public JavaTXCompiler(File sourceFile) throws IOException, ClassNotFoundException { this(Arrays.asList(sourceFile), null); } - public JavaTXCompiler(File sourceFile, Boolean log) throws IOException, ClassNotFoundException { - this(sourceFile); - this.log = log; - } + + public JavaTXCompiler(File sourceFile, Boolean log) throws IOException, ClassNotFoundException { + this(sourceFile); + this.log = log; + } + public JavaTXCompiler(List sourceFiles) throws IOException, ClassNotFoundException { this(sourceFiles, null); } - public JavaTXCompiler(List sources, List contextPath) throws IOException, ClassNotFoundException { - if(contextPath == null || contextPath.isEmpty()){ - //When no contextPaths are given, the working directory is the sources root + + public JavaTXCompiler(List sources, List contextPath) throws IOException, ClassNotFoundException { + if (contextPath == null || contextPath.isEmpty()) { + // When no contextPaths are given, the working directory is the sources root contextPath = Lists.newArrayList(new File(System.getProperty("user.dir"))); } - classLoader = new DirectoryClassLoader(contextPath, ClassLoader.getSystemClassLoader()); + classLoader = new DirectoryClassLoader(contextPath, ClassLoader.getSystemClassLoader()); environment = new CompilationEnvironment(sources); - for (File s : sources) { - sourceFiles.put(s, parse(s)); - } - //INSTANCE = this; - } + for (File s : sources) { + sourceFiles.put(s, parse(s)); + } + // INSTANCE = this; + } - public ConstraintSet getConstraints() throws ClassNotFoundException, IOException { - List allClasses = new ArrayList<>();//environment.getAllAvailableClasses(); - List importedClasses = new ArrayList<>(); - ClassOrInterface objectClass = ASTFactory.createClass( - classLoader.loadClass(new JavaClassName("java.lang.Object").toString())); - //Alle Importierten Klassen in allen geparsten Sourcefiles kommen ins FC - for (File forSourceFile : sourceFiles.keySet()){ - for (JavaClassName name : sourceFiles.get(forSourceFile).getImports()) { - //TODO: Hier werden imports von eigenen (.jav) Klassen nicht beachtet - ClassOrInterface importedClass = ASTFactory.createClass( - classLoader.loadClass(name.toString())); - importedClasses.add(importedClass); - } - for(Class c : CompilationEnvironment.loadDefaultPackageClasses(forSourceFile, classLoader)){ + public ConstraintSet getConstraints() throws ClassNotFoundException, IOException { + List allClasses = new ArrayList<>();// environment.getAllAvailableClasses(); + List importedClasses = new ArrayList<>(); + ClassOrInterface objectClass = ASTFactory.createClass(classLoader.loadClass(new JavaClassName("java.lang.Object").toString())); + // Alle Importierten Klassen in allen geparsten Sourcefiles kommen ins FC + for (Entry source : sourceFiles.entrySet()) { + for (JavaClassName name : source.getValue().getImports()) { + // TODO: Hier werden imports von eigenen (.jav) Klassen nicht beachtet + ClassOrInterface importedClass = ASTFactory.createClass(classLoader.loadClass(name.toString())); + importedClasses.add(importedClass); + } + for (Class c : CompilationEnvironment.loadDefaultPackageClasses(source.getValue().getPkgName(), source.getKey(), classLoader)) { ClassOrInterface importedClass = ASTFactory.createClass(c); importedClasses.add(importedClass); } - } - for (File f : this.sourceFiles.keySet()) { + } + for (File f : this.sourceFiles.keySet()) { SourceFile sf = sourceFiles.get(f); - sf = new SourceFile(sf.getPkgName(), - sf.KlassenVektor.stream() - .map(cl -> new ClassOrInterface(cl)) - .collect(Collectors.toCollection(ArrayList::new)), - sf.imports); - //sf enthaelt neues Source-File, neue Klassen-Objekte und neue - //ArrayListen-Objekte fuer Fields, Construktoren und Methoden - //Alle anderen Objekte werden nur kopiert. + sf = new SourceFile(sf.getPkgName(), sf.KlassenVektor.stream().map(cl -> new ClassOrInterface(cl)).collect(Collectors.toCollection(ArrayList::new)), sf.imports); + // sf enthaelt neues Source-File, neue Klassen-Objekte und neue + // ArrayListen-Objekte fuer Fields, Construktoren und Methoden + // Alle anderen Objekte werden nur kopiert. SourceFile sf_new = sf; sf.KlassenVektor.forEach(cl -> addMethods(sf_new, cl, importedClasses, objectClass)); allClasses.addAll(sf.getClasses()); } - allClasses.addAll(importedClasses); - TYPE ty = new TYPE(sourceFiles.values(), allClasses); - return ty.getConstraints(); - } - - void addMethods(SourceFile sf, ClassOrInterface cl, List importedClasses, ClassOrInterface objectClass) { + allClasses.addAll(importedClasses); + TYPE ty = new TYPE(sourceFiles.values(), allClasses); + return ty.getConstraints(); + } + + void addMethods(SourceFile sf, ClassOrInterface cl, List importedClasses, ClassOrInterface objectClass) { if (!cl.areMethodsAdded()) { ClassOrInterface superclass = null; if (cl.getSuperClass().getName().equals(new JavaClassName("java.lang.Object"))) { superclass = objectClass; - } - else { - Optional optSuperclass = - importedClasses.stream().filter(x -> x.getClassName().equals( - cl.getSuperClass().getName())).findFirst(); + } else { + Optional optSuperclass = importedClasses.stream().filter(x -> x.getClassName().equals(cl.getSuperClass().getName())).findFirst(); if (optSuperclass.isPresent()) { superclass = optSuperclass.get(); - } - else { - optSuperclass = - sf.KlassenVektor.stream().filter(x -> x.getClassName().equals( - cl.getSuperClass().getName())).findFirst(); + } else { + optSuperclass = sf.KlassenVektor.stream().filter(x -> x.getClassName().equals(cl.getSuperClass().getName())).findFirst(); if (optSuperclass.isPresent()) { superclass = optSuperclass.get(); - addMethods(sf, superclass, importedClasses, objectClass); - } - else { - //throw new ClassNotFoundException(""); + addMethods(sf, superclass, importedClasses, objectClass); + } else { + // throw new ClassNotFoundException(""); } } } - Iterator paraIt= cl.getSuperClass().getParaList().iterator(); + Iterator paraIt = cl.getSuperClass().getParaList().iterator(); Iterator tvarVarIt = superclass.getGenerics().iterator(); - + HashMap gtvs = new HashMap<>(); - while (paraIt.hasNext()) { + while (paraIt.hasNext()) { gtvs.put(tvarVarIt.next().getName(), paraIt.next()); } Iterator methodIt = superclass.getMethods().iterator(); - //TODO: PL 2020-05-06: Hier müssen ueberschriebene Methoden noch rausgefiltert werden - while(methodIt.hasNext()) { + // TODO: PL 2020-05-06: Hier müssen ueberschriebene Methoden noch rausgefiltert + // werden + while (methodIt.hasNext()) { Method m = methodIt.next(); - ParameterList newParaList = new ParameterList( - m.getParameterList() - .getFormalparalist() - .stream() - .map(fp -> new FormalParameter(fp.getName(), fp.getType().acceptTV(new TypeExchanger(gtvs)), fp.getOffset())) - .collect(Collectors.toCollection(ArrayList::new)), m.getParameterList().getOffset()); + ParameterList newParaList = new ParameterList(m.getParameterList().getFormalparalist().stream().map(fp -> new FormalParameter(fp.getName(), fp.getType().acceptTV(new TypeExchanger(gtvs)), fp.getOffset())).collect(Collectors.toCollection(ArrayList::new)), m.getParameterList().getOffset()); cl.getMethods().add(new Method(m.modifier, m.name, m.getReturnType().acceptTV(new TypeExchanger(gtvs)), newParaList, m.block, - //new GenericDeclarationList(newGenericsList, ((GenericDeclarationList)m.getGenerics()).getOffset()), - (GenericDeclarationList)m.getGenerics(), - m.getOffset(), true)); + // new GenericDeclarationList(newGenericsList, + // ((GenericDeclarationList)m.getGenerics()).getOffset()), + (GenericDeclarationList) m.getGenerics(), m.getOffset(), true)); } - + } cl.setMethodsAdded(); } - - - - public List getAvailableClasses(SourceFile forSourceFile) throws ClassNotFoundException { - //PL 2018-09-18: List durch Set ersetzt, damit die Klassen nur einmal hinzugefuegt werden - //List allClasses = new ArrayList<>();//environment.getAllAvailableClasses(); - Set allClasses = new HashSet<>(); - - /* PL 2018-09-19 geloescht werden bereits in typeInference hinzugefuegt - } - allClasses.addAll(importedClasses); - - return new TYPE(sourceFiles.values(), allClasses).getConstraints(); - } public List getAvailableClasses(SourceFile forSourceFile) throws ClassNotFoundException { // PL 2018-09-18: List durch Set ersetzt, damit die Klassen nur einmal @@ -209,16 +182,19 @@ public class JavaTXCompiler { Set allClasses = new HashSet<>(); /* - * PL 2018-09-19 geloescht werden bereits in typeInference hinzugefuegt for - * (SourceFile sf : sourceFiles.values()) { allClasses.addAll(sf.getClasses()); - * } + * PL 2018-09-19 geloescht werden bereits in typeInference hinzugefuegt } allClasses.addAll(importedClasses); + * + * return new TYPE(sourceFiles.values(), allClasses).getConstraints(); } + * + * public List getAvailableClasses(SourceFile forSourceFile) throws ClassNotFoundException { // PL 2018-09-18: List durch Set ersetzt, damit die Klassen nur einmal // hinzugefuegt werden // List allClasses = new // ArrayList<>();//environment.getAllAvailableClasses(); Set allClasses = new HashSet<>(); + * + * /* PL 2018-09-19 geloescht werden bereits in typeInference hinzugefuegt for (SourceFile sf : sourceFiles.values()) { allClasses.addAll(sf.getClasses()); } */ List importedClasses = new ArrayList<>(); for (JavaClassName name : forSourceFile.getImports()) { // TODO: Hier werden imports von eigenen (.jav) Klassen nicht beachtet - ClassOrInterface importedClass = ASTFactory - .createClass(classLoader.loadClass(name.toString())); + ClassOrInterface importedClass = ASTFactory.createClass(classLoader.loadClass(name.toString())); importedClasses.add(importedClass); allClasses.addAll(importedClasses); } @@ -226,159 +202,56 @@ public class JavaTXCompiler { } /* - * public List typeInferenceOld() throws ClassNotFoundException { - * List allClasses = new - * ArrayList<>();//environment.getAllAvailableClasses(); //Alle Importierten - * Klassen in allen geparsten Sourcefiles kommen ins FC for(SourceFile sf : - * this.sourceFiles.values()) { allClasses.addAll(getAvailableClasses(sf)); - * allClasses.addAll(sf.getClasses()); } + * public List typeInferenceOld() throws ClassNotFoundException { List allClasses = new ArrayList<>();//environment.getAllAvailableClasses(); //Alle Importierten Klassen in allen geparsten Sourcefiles kommen ins FC for(SourceFile sf : this.sourceFiles.values()) { allClasses.addAll(getAvailableClasses(sf)); allClasses.addAll(sf.getClasses()); } * * final ConstraintSet cons = getConstraints(); * - * FiniteClosure finiteClosure = UnifyTypeFactory.generateFC(allClasses); - * System.out.println(finiteClosure); ConstraintSet unifyCons = - * UnifyTypeFactory.convert(cons); + * FiniteClosure finiteClosure = UnifyTypeFactory.generateFC(allClasses); System.out.println(finiteClosure); ConstraintSet unifyCons = UnifyTypeFactory.convert(cons); * - * TypeUnify unify = new TypeUnify(); Set> results = new - * HashSet<>(); try { File logPath = new - * File(System.getProperty("user.dir")+"/target/logFiles/"); logPath.mkdirs(); - * FileWriter logFile = new FileWriter(new File(logPath, "log")); - * logFile.write("FC:\\" + finiteClosure.toString()+"\n"); for(SourceFile sf : - * this.sourceFiles.values()) { logFile.write(ASTTypePrinter.print(sf)); } - * logFile.flush(); Set>> cardProd = - * unifyCons.cartesianProduct(); for (List> xCons : - * cardProd ){ Set xConsSet = new HashSet<>(); for - * (Constraint constraint : xCons) { xConsSet.addAll(constraint); } - * //.collect(Collectors.toCollection(ArrayList::new)))) - * System.out.println(xConsSet); Set methodParaTypeVarNames = - * allClasses.stream().map(x -> x.getMethods().stream().map(y -> - * y.getParameterList().getFormalparalist() .stream().filter(z -> z.getType() - * instanceof TypePlaceholder) .map(z -> - * ((TypePlaceholder)z.getType()).getName()).collect(Collectors.toCollection( - * HashSet::new))) .reduce(new HashSet(), (a,b) -> { a.addAll(b); return - * a;}, (a,b) -> { a.addAll(b); return a;} ) ) .reduce(new HashSet(), - * (a,b) -> { a.addAll(b); return a;} ); + * TypeUnify unify = new TypeUnify(); Set> results = new HashSet<>(); try { File logPath = new File(System.getProperty("user.dir")+"/target/logFiles/"); logPath.mkdirs(); FileWriter logFile = new FileWriter(new File(logPath, "log")); logFile.write("FC:\\" + finiteClosure.toString()+"\n"); for(SourceFile sf : this.sourceFiles.values()) { logFile.write(ASTTypePrinter.print(sf)); } logFile.flush(); Set>> cardProd = unifyCons.cartesianProduct(); for + * (List> xCons : cardProd ){ Set xConsSet = new HashSet<>(); for (Constraint constraint : xCons) { xConsSet.addAll(constraint); } //.collect(Collectors.toCollection(ArrayList::new)))) System.out.println(xConsSet); Set methodParaTypeVarNames = allClasses.stream().map(x -> x.getMethods().stream().map(y -> y.getParameterList().getFormalparalist() .stream().filter(z -> z.getType() instanceof TypePlaceholder) .map(z -> + * ((TypePlaceholder)z.getType()).getName()).collect(Collectors.toCollection( HashSet::new))) .reduce(new HashSet(), (a,b) -> { a.addAll(b); return a;}, (a,b) -> { a.addAll(b); return a;} ) ) .reduce(new HashSet(), (a,b) -> { a.addAll(b); return a;} ); * - * Set constructorParaTypeVarNames = allClasses.stream().map(x -> - * x.getConstructors().stream().map(y -> - * y.getParameterList().getFormalparalist() .stream().filter(z -> z.getType() - * instanceof TypePlaceholder) .map(z -> - * ((TypePlaceholder)z.getType()).getName()).collect(Collectors.toCollection( - * HashSet::new))) .reduce(new HashSet(), (a,b) -> { a.addAll(b); return - * a;}, (a,b) -> { a.addAll(b); return a;} ) ) .reduce(new HashSet(), - * (a,b) -> { a.addAll(b); return a;} ); + * Set constructorParaTypeVarNames = allClasses.stream().map(x -> x.getConstructors().stream().map(y -> y.getParameterList().getFormalparalist() .stream().filter(z -> z.getType() instanceof TypePlaceholder) .map(z -> ((TypePlaceholder)z.getType()).getName()).collect(Collectors.toCollection( HashSet::new))) .reduce(new HashSet(), (a,b) -> { a.addAll(b); return a;}, (a,b) -> { a.addAll(b); return a;} ) ) .reduce(new HashSet(), (a,b) -> { a.addAll(b); return a;} ); * - * Set paraTypeVarNames = methodParaTypeVarNames; - * paraTypeVarNames.addAll(constructorParaTypeVarNames); + * Set paraTypeVarNames = methodParaTypeVarNames; paraTypeVarNames.addAll(constructorParaTypeVarNames); * - * Set returnTypeVarNames = allClasses.stream().map(x -> - * x.getMethods().stream().filter(y -> y.getReturnType() instanceof - * TypePlaceholder) .map(z -> - * ((TypePlaceholder)z.getReturnType()).getName()).collect(Collectors. - * toCollection(HashSet::new))).reduce((a,b) -> { a.addAll(b); return a;} - * ).get(); + * Set returnTypeVarNames = allClasses.stream().map(x -> x.getMethods().stream().filter(y -> y.getReturnType() instanceof TypePlaceholder) .map(z -> ((TypePlaceholder)z.getReturnType()).getName()).collect(Collectors. toCollection(HashSet::new))).reduce((a,b) -> { a.addAll(b); return a;} ).get(); * - * Set fieldTypeVarNames = allClasses.stream().map(x -> - * x.getFieldDecl().stream().filter(y -> y.getReturnType() instanceof - * TypePlaceholder) .map(z -> - * ((TypePlaceholder)z.getReturnType()).getName()).collect(Collectors. - * toCollection(HashSet::new))).reduce((a,b) -> { a.addAll(b); return a;} - * ).get(); + * Set fieldTypeVarNames = allClasses.stream().map(x -> x.getFieldDecl().stream().filter(y -> y.getReturnType() instanceof TypePlaceholder) .map(z -> ((TypePlaceholder)z.getReturnType()).getName()).collect(Collectors. toCollection(HashSet::new))).reduce((a,b) -> { a.addAll(b); return a;} ).get(); * * returnTypeVarNames.addAll(fieldTypeVarNames); * - * xConsSet = xConsSet.stream().map(x -> { //Hier muss ueberlegt werden, ob //1. - * alle Argument- und Retuntyp-Variablen in allen UnifyPairs // mit - * disableWildcardtable() werden. //2. alle Typvariablen mit Argument- oder - * Retuntyp-Variablen //in Beziehung auch auf disableWildcardtable() gesetzt - * werden muessen //PL 2018-04-23 if ((x.getLhsType() instanceof - * PlaceholderType)) { if (paraTypeVarNames.contains(x.getLhsType().getName())) - * { ((PlaceholderType)x.getLhsType()).setVariance((byte)1); - * ((PlaceholderType)x.getLhsType()).disableWildcardtable(); } if - * (returnTypeVarNames.contains(x.getLhsType().getName())) { - * ((PlaceholderType)x.getLhsType()).setVariance((byte)-1); - * ((PlaceholderType)x.getLhsType()).disableWildcardtable(); } } if - * ((x.getRhsType() instanceof PlaceholderType)) { if - * (paraTypeVarNames.contains(x.getRhsType().getName())) { - * ((PlaceholderType)x.getRhsType()).setVariance((byte)1); - * ((PlaceholderType)x.getRhsType()).disableWildcardtable(); } if - * (returnTypeVarNames.contains(x.getRhsType().getName())) { - * ((PlaceholderType)x.getRhsType()).setVariance((byte)-1); - * ((PlaceholderType)x.getRhsType()).disableWildcardtable(); } } return x;//HIER - * DIE JEWEILS RECHT BZW. LINKE SEITE AUF GLEICHE VARIANZ SETZEN WIE DIE JEWEILS - * ANDERE SEITE }).map( y -> { if ((y.getLhsType() instanceof PlaceholderType) - * && (y.getRhsType() instanceof PlaceholderType)) { if - * (((PlaceholderType)y.getLhsType()).getVariance() != 0 && - * ((PlaceholderType)y.getRhsType()).getVariance() == 0) { - * ((PlaceholderType)y.getRhsType()).setVariance(((PlaceholderType)y.getLhsType( - * )).getVariance()); } if (((PlaceholderType)y.getLhsType()).getVariance() == 0 - * && ((PlaceholderType)y.getRhsType()).getVariance() != 0) { - * ((PlaceholderType)y.getLhsType()).setVariance(((PlaceholderType)y.getRhsType( - * )).getVariance()); } } return y; } ) - * .collect(Collectors.toCollection(HashSet::new)); - * varianceInheritance(xConsSet); Set> result = - * unify.unifySequential(xConsSet, finiteClosure, logFile, log); - * //Set> result = unify.unify(xConsSet, finiteClosure); - * System.out.println("RESULT: " + result); logFile.write("RES: " + - * result.toString()+"\n"); logFile.flush(); results.addAll(result); } + * xConsSet = xConsSet.stream().map(x -> { //Hier muss ueberlegt werden, ob //1. alle Argument- und Retuntyp-Variablen in allen UnifyPairs // mit disableWildcardtable() werden. //2. alle Typvariablen mit Argument- oder Retuntyp-Variablen //in Beziehung auch auf disableWildcardtable() gesetzt werden muessen //PL 2018-04-23 if ((x.getLhsType() instanceof PlaceholderType)) { if (paraTypeVarNames.contains(x.getLhsType().getName())) { ((PlaceholderType)x.getLhsType()).setVariance((byte)1); + * ((PlaceholderType)x.getLhsType()).disableWildcardtable(); } if (returnTypeVarNames.contains(x.getLhsType().getName())) { ((PlaceholderType)x.getLhsType()).setVariance((byte)-1); ((PlaceholderType)x.getLhsType()).disableWildcardtable(); } } if ((x.getRhsType() instanceof PlaceholderType)) { if (paraTypeVarNames.contains(x.getRhsType().getName())) { ((PlaceholderType)x.getRhsType()).setVariance((byte)1); ((PlaceholderType)x.getRhsType()).disableWildcardtable(); } if + * (returnTypeVarNames.contains(x.getRhsType().getName())) { ((PlaceholderType)x.getRhsType()).setVariance((byte)-1); ((PlaceholderType)x.getRhsType()).disableWildcardtable(); } } return x;//HIER DIE JEWEILS RECHT BZW. LINKE SEITE AUF GLEICHE VARIANZ SETZEN WIE DIE JEWEILS ANDERE SEITE }).map( y -> { if ((y.getLhsType() instanceof PlaceholderType) && (y.getRhsType() instanceof PlaceholderType)) { if (((PlaceholderType)y.getLhsType()).getVariance() != 0 && + * ((PlaceholderType)y.getRhsType()).getVariance() == 0) { ((PlaceholderType)y.getRhsType()).setVariance(((PlaceholderType)y.getLhsType( )).getVariance()); } if (((PlaceholderType)y.getLhsType()).getVariance() == 0 && ((PlaceholderType)y.getRhsType()).getVariance() != 0) { ((PlaceholderType)y.getLhsType()).setVariance(((PlaceholderType)y.getRhsType( )).getVariance()); } } return y; } ) .collect(Collectors.toCollection(HashSet::new)); varianceInheritance(xConsSet); Set> result = + * unify.unifySequential(xConsSet, finiteClosure, logFile, log); //Set> result = unify.unify(xConsSet, finiteClosure); System.out.println("RESULT: " + result); logFile.write("RES: " + result.toString()+"\n"); logFile.flush(); results.addAll(result); } * - * results = results.stream().map(x -> { Optional> res = new - * RuleSet().subst(x.stream().map(y -> { if (y.getPairOp() == - * PairOperator.SMALLERDOTWC) y.setPairOp(PairOperator.EQUALSDOT); return y; - * //alle Paare a <.? b erden durch a =. b ersetzt - * }).collect(Collectors.toCollection(HashSet::new))); if (res.isPresent()) - * {//wenn subst ein Erg liefert wurde was veraendert return new - * TypeUnifyTask().applyTypeUnificationRules(res.get(), finiteClosure); } else - * return x; //wenn nichts veraendert wurde wird x zurueckgegeben - * }).collect(Collectors.toCollection(HashSet::new)); - * System.out.println("RESULT Final: " + results); logFile.write("RES_FINAL: " + - * results.toString()+"\n"); logFile.flush(); logFile.write("PLACEHOLDERS: " + - * PlaceholderType.EXISTING_PLACEHOLDERS); logFile.flush(); } catch (IOException - * e) { e.printStackTrace(); } return results.stream().map((unifyPairs -> new - * ResultSet(UnifyTypeFactory.convert(unifyPairs, + * results = results.stream().map(x -> { Optional> res = new RuleSet().subst(x.stream().map(y -> { if (y.getPairOp() == PairOperator.SMALLERDOTWC) y.setPairOp(PairOperator.EQUALSDOT); return y; //alle Paare a <.? b erden durch a =. b ersetzt }).collect(Collectors.toCollection(HashSet::new))); if (res.isPresent()) {//wenn subst ein Erg liefert wurde was veraendert return new TypeUnifyTask().applyTypeUnificationRules(res.get(), finiteClosure); } else return x; //wenn nichts + * veraendert wurde wird x zurueckgegeben }).collect(Collectors.toCollection(HashSet::new)); System.out.println("RESULT Final: " + results); logFile.write("RES_FINAL: " + results.toString()+"\n"); logFile.flush(); logFile.write("PLACEHOLDERS: " + PlaceholderType.EXISTING_PLACEHOLDERS); logFile.flush(); } catch (IOException e) { e.printStackTrace(); } return results.stream().map((unifyPairs -> new ResultSet(UnifyTypeFactory.convert(unifyPairs, * generateTPHMap(cons))))).collect(Collectors.toList()); } */ /** - * Vererbt alle Variancen bei Paaren (a <. theta) oder (Theta <. a) wenn a eine - * Variance !=0 hat auf alle Typvariablen in Theta. + * Vererbt alle Variancen bei Paaren (a <. theta) oder (Theta <. a) wenn a eine Variance !=0 hat auf alle Typvariablen in Theta. * * */ /* - * private void varianceInheritance(Set eq) { Set - * usedTPH = new HashSet<>(); Set phSet = eq.stream().map(x -> - * { Set pair = new HashSet<>(); if (x.getLhsType() instanceof - * PlaceholderType) pair.add((PlaceholderType)x.getLhsType()); if - * (x.getRhsType() instanceof PlaceholderType) - * pair.add((PlaceholderType)x.getRhsType()); return pair; }).reduce(new - * HashSet<>(), (a,b) -> { a.addAll(b); return a;} , (c,d) -> { c.addAll(d); - * return c;}); + * private void varianceInheritance(Set eq) { Set usedTPH = new HashSet<>(); Set phSet = eq.stream().map(x -> { Set pair = new HashSet<>(); if (x.getLhsType() instanceof PlaceholderType) pair.add((PlaceholderType)x.getLhsType()); if (x.getRhsType() instanceof PlaceholderType) pair.add((PlaceholderType)x.getRhsType()); return pair; }).reduce(new HashSet<>(), (a,b) -> { a.addAll(b); return a;} , (c,d) -> { c.addAll(d); return c;}); * - * ArrayList phSetVariance = new ArrayList<>(phSet); - * phSetVariance.removeIf(x -> (x.getVariance() == 0)); - * while(!phSetVariance.isEmpty()) { PlaceholderType a = - * phSetVariance.remove(0); usedTPH.add(a); //HashMap - * ht = new HashMap<>(); //ht.put(a, a.getVariance()); Set eq1 = new - * HashSet<>(eq); eq1.removeIf(x -> !(x.getLhsType() instanceof PlaceholderType - * && ((PlaceholderType)x.getLhsType()).equals(a))); eq1.stream().forEach(x -> { - * x.getRhsType().accept(new distributeVariance(), a.getVariance());}); eq1 = - * new HashSet<>(eq); eq1.removeIf(x -> !(x.getRhsType() instanceof - * PlaceholderType && ((PlaceholderType)x.getRhsType()).equals(a))); - * eq1.stream().forEach(x -> { x.getLhsType().accept(new distributeVariance(), - * a.getVariance());}); phSetVariance = new ArrayList<>(phSet); - * phSetVariance.removeIf(x -> (x.getVariance() == 0 || usedTPH.contains(x))); } - * } + * ArrayList phSetVariance = new ArrayList<>(phSet); phSetVariance.removeIf(x -> (x.getVariance() == 0)); while(!phSetVariance.isEmpty()) { PlaceholderType a = phSetVariance.remove(0); usedTPH.add(a); //HashMap ht = new HashMap<>(); //ht.put(a, a.getVariance()); Set eq1 = new HashSet<>(eq); eq1.removeIf(x -> !(x.getLhsType() instanceof PlaceholderType && ((PlaceholderType)x.getLhsType()).equals(a))); eq1.stream().forEach(x -> { + * x.getRhsType().accept(new distributeVariance(), a.getVariance());}); eq1 = new HashSet<>(eq); eq1.removeIf(x -> !(x.getRhsType() instanceof PlaceholderType && ((PlaceholderType)x.getRhsType()).equals(a))); eq1.stream().forEach(x -> { x.getLhsType().accept(new distributeVariance(), a.getVariance());}); phSetVariance = new ArrayList<>(phSet); phSetVariance.removeIf(x -> (x.getVariance() == 0 || usedTPH.contains(x))); } } */ - public UnifyResultModel typeInferenceAsync(UnifyResultListener resultListener, Writer logFile) - throws ClassNotFoundException, IOException { + public UnifyResultModel typeInferenceAsync(UnifyResultListener resultListener, Writer logFile) throws ClassNotFoundException, IOException { List allClasses = new ArrayList<>();// environment.getAllAvailableClasses(); // Alle Importierten Klassen in allen geparsten Sourcefiles kommen ins FC - for (File f : this.sourceFiles.keySet()) { - SourceFile sf = sourceFiles.get(f); + for (Entry source : this.sourceFiles.entrySet()) { + SourceFile sf = source.getValue(); allClasses.addAll(getAvailableClasses(sf)); allClasses.addAll(sf.getClasses()); - allClasses.addAll(CompilationEnvironment.loadDefaultPackageClasses(f,classLoader).stream().map(ASTFactory::createClass).collect(Collectors.toList())); + allClasses.addAll(CompilationEnvironment.loadDefaultPackageClasses(sf.getPkgName(), source.getKey(), classLoader).stream().map(ASTFactory::createClass).collect(Collectors.toList())); } final ConstraintSet cons = getConstraints(); @@ -386,9 +259,7 @@ public class JavaTXCompiler { UnifyResultModel urm = null; // urm.addUnifyResultListener(resultListener); try { - logFile = logFile == null - ? new FileWriter(new File("log_" + sourceFiles.keySet().iterator().next().getName())) - : logFile; + logFile = logFile == null ? new FileWriter(new File("log_" + sourceFiles.keySet().iterator().next().getName())) : logFile; IFiniteClosure finiteClosure = UnifyTypeFactory.generateFC(allClasses, logFile, classLoader); System.out.println(finiteClosure); urm = new UnifyResultModel(cons, finiteClosure); @@ -397,9 +268,7 @@ public class JavaTXCompiler { Function distributeInnerVars = x -> { UnifyType lhs, rhs; - if (((lhs = x.getLhsType()) instanceof PlaceholderType) - && ((rhs = x.getRhsType()) instanceof PlaceholderType) - && (((PlaceholderType) lhs).isInnerType() || ((PlaceholderType) rhs).isInnerType())) { + if (((lhs = x.getLhsType()) instanceof PlaceholderType) && ((rhs = x.getRhsType()) instanceof PlaceholderType) && (((PlaceholderType) lhs).isInnerType() || ((PlaceholderType) rhs).isInnerType())) { ((PlaceholderType) lhs).setInnerType(true); ((PlaceholderType) rhs).setInnerType(true); } @@ -417,58 +286,40 @@ public class JavaTXCompiler { } logFile.flush(); - Set methodParaTypeVarNames = allClasses.stream().map(x -> x.getMethods().stream() - .map(y -> y.getParameterList().getFormalparalist().stream() - .filter(z -> z.getType() instanceof TypePlaceholder) - .map(z -> ((TypePlaceholder) z.getType()).getName()) - .collect(Collectors.toCollection(HashSet::new))) - .reduce(new HashSet(), (a, b) -> { - a.addAll(b); - return a; - }, (a, b) -> { - a.addAll(b); - return a; - })).reduce(new HashSet(), (a, b) -> { - a.addAll(b); - return a; - }); + Set methodParaTypeVarNames = allClasses.stream().map(x -> x.getMethods().stream().map(y -> y.getParameterList().getFormalparalist().stream().filter(z -> z.getType() instanceof TypePlaceholder).map(z -> ((TypePlaceholder) z.getType()).getName()).collect(Collectors.toCollection(HashSet::new))).reduce(new HashSet(), (a, b) -> { + a.addAll(b); + return a; + }, (a, b) -> { + a.addAll(b); + return a; + })).reduce(new HashSet(), (a, b) -> { + a.addAll(b); + return a; + }); - Set constructorParaTypeVarNames = allClasses.stream().map(x -> x.getConstructors().stream() - .map(y -> y.getParameterList().getFormalparalist().stream() - .filter(z -> z.getType() instanceof TypePlaceholder) - .map(z -> ((TypePlaceholder) z.getType()).getName()) - .collect(Collectors.toCollection(HashSet::new))) - .reduce(new HashSet(), (a, b) -> { - a.addAll(b); - return a; - }, (a, b) -> { - a.addAll(b); - return a; - })).reduce(new HashSet(), (a, b) -> { - a.addAll(b); - return a; - }); + Set constructorParaTypeVarNames = allClasses.stream().map(x -> x.getConstructors().stream().map(y -> y.getParameterList().getFormalparalist().stream().filter(z -> z.getType() instanceof TypePlaceholder).map(z -> ((TypePlaceholder) z.getType()).getName()).collect(Collectors.toCollection(HashSet::new))).reduce(new HashSet(), (a, b) -> { + a.addAll(b); + return a; + }, (a, b) -> { + a.addAll(b); + return a; + })).reduce(new HashSet(), (a, b) -> { + a.addAll(b); + return a; + }); Set paraTypeVarNames = methodParaTypeVarNames; paraTypeVarNames.addAll(constructorParaTypeVarNames); - Set returnTypeVarNames = allClasses.stream() - .map(x -> x.getMethods().stream().filter(y -> y.getReturnType() instanceof TypePlaceholder) - .map(z -> ((TypePlaceholder) z.getReturnType()).getName()) - .collect(Collectors.toCollection(HashSet::new))) - .reduce((a, b) -> { - a.addAll(b); - return a; - }).get(); + Set returnTypeVarNames = allClasses.stream().map(x -> x.getMethods().stream().filter(y -> y.getReturnType() instanceof TypePlaceholder).map(z -> ((TypePlaceholder) z.getReturnType()).getName()).collect(Collectors.toCollection(HashSet::new))).reduce((a, b) -> { + a.addAll(b); + return a; + }).get(); - Set fieldTypeVarNames = allClasses.stream() - .map(x -> x.getFieldDecl().stream().filter(y -> y.getReturnType() instanceof TypePlaceholder) - .map(z -> ((TypePlaceholder) z.getReturnType()).getName()) - .collect(Collectors.toCollection(HashSet::new))) - .reduce((a, b) -> { - a.addAll(b); - return a; - }).get(); + Set fieldTypeVarNames = allClasses.stream().map(x -> x.getFieldDecl().stream().filter(y -> y.getReturnType() instanceof TypePlaceholder).map(z -> ((TypePlaceholder) z.getReturnType()).getName()).collect(Collectors.toCollection(HashSet::new))).reduce((a, b) -> { + a.addAll(b); + return a; + }).get(); returnTypeVarNames.addAll(fieldTypeVarNames); @@ -500,41 +351,24 @@ public class JavaTXCompiler { } } return x;// HIER DIE JEWEILS RECHT BZW. LINKE SEITE AUF GLEICHE VARIANZ SETZEN WIE DIE - // JEWEILS ANDERE SEITE + // JEWEILS ANDERE SEITE }); Set varianceTPHold; Set varianceTPH = new HashSet<>(); varianceTPH = varianceInheritanceConstraintSet(unifyCons); /* - * PL 2018-11-07 wird in varianceInheritanceConstraintSet erledigt do { //PL - * 2018-11-05 Huellenbildung Variance auf alle TPHs der Terme auf der jeweiligen - * //anderen Seite übertragen varianceTPHold = new HashSet<>(varianceTPH); - * varianceTPH = varianceInheritanceConstraintSet(unifyCons); unifyCons.map( y - * -> { if ((y.getLhsType() instanceof PlaceholderType) && (y.getRhsType() - * instanceof PlaceholderType)) { if - * (((PlaceholderType)y.getLhsType()).getVariance() != 0 && - * ((PlaceholderType)y.getRhsType()).getVariance() == 0) { - * ((PlaceholderType)y.getRhsType()).setVariance(((PlaceholderType)y.getLhsType( - * )).getVariance()); } if (((PlaceholderType)y.getLhsType()).getVariance() == 0 - * && ((PlaceholderType)y.getRhsType()).getVariance() != 0) { - * ((PlaceholderType)y.getLhsType()).setVariance(((PlaceholderType)y.getRhsType( - * )).getVariance()); } } return y; } ); } while - * (!varianceTPHold.equals(varianceTPH)); + * PL 2018-11-07 wird in varianceInheritanceConstraintSet erledigt do { //PL 2018-11-05 Huellenbildung Variance auf alle TPHs der Terme auf der jeweiligen //anderen Seite übertragen varianceTPHold = new HashSet<>(varianceTPH); varianceTPH = varianceInheritanceConstraintSet(unifyCons); unifyCons.map( y -> { if ((y.getLhsType() instanceof PlaceholderType) && (y.getRhsType() instanceof PlaceholderType)) { if (((PlaceholderType)y.getLhsType()).getVariance() != 0 && + * ((PlaceholderType)y.getRhsType()).getVariance() == 0) { ((PlaceholderType)y.getRhsType()).setVariance(((PlaceholderType)y.getLhsType( )).getVariance()); } if (((PlaceholderType)y.getLhsType()).getVariance() == 0 && ((PlaceholderType)y.getRhsType()).getVariance() != 0) { ((PlaceholderType)y.getLhsType()).setVariance(((PlaceholderType)y.getRhsType( )).getVariance()); } } return y; } ); } while (!varianceTPHold.equals(varianceTPH)); */ // Set> result = unify.unifySequential(xConsSet, finiteClosure, // logFile, log); // Set> result = unify.unify(xConsSet, finiteClosure); - List>> oderConstraints = unifyCons.getOderConstraints()/*.stream().map(x -> { - Set> ret = new HashSet<>(); - for (Constraint y : x) { - ret.add(new HashSet<>(y)); - } - return ret; - }).collect(Collectors.toCollection(ArrayList::new))*/; - unify.unifyAsync(unifyCons.getUndConstraints(), oderConstraints, finiteClosure, logFile, log, urm, - usedTasks); + List>> oderConstraints = unifyCons.getOderConstraints()/* + * .stream().map(x -> { Set> ret = new HashSet<>(); for (Constraint y : x) { ret.add(new HashSet<>(y)); } return ret; }).collect(Collectors. toCollection(ArrayList::new)) + */; + unify.unifyAsync(unifyCons.getUndConstraints(), oderConstraints, finiteClosure, logFile, log, urm, usedTasks); } catch (IOException e) { System.err.println("kein LogFile"); } @@ -544,11 +378,11 @@ public class JavaTXCompiler { public List typeInference() throws ClassNotFoundException, IOException { List allClasses = new ArrayList<>();// environment.getAllAvailableClasses(); // Alle Importierten Klassen in allen geparsten Sourcefiles kommen ins FC - for (File f : this.sourceFiles.keySet()) { - SourceFile sf = sourceFiles.get(f); + for (Entry source : this.sourceFiles.entrySet()) { + SourceFile sf = source.getValue(); allClasses.addAll(getAvailableClasses(sf)); allClasses.addAll(sf.getClasses()); - var newClasses = CompilationEnvironment.loadDefaultPackageClasses(f,classLoader).stream().map(ASTFactory::createClass).collect(Collectors.toList()); + var newClasses = CompilationEnvironment.loadDefaultPackageClasses(sf.getPkgName(), source.getKey(), classLoader).stream().map(ASTFactory::createClass).collect(Collectors.toList()); for (var clazz : newClasses) { var found = false; for (var old : allClasses) { @@ -557,31 +391,29 @@ public class JavaTXCompiler { break; } } - if (!found) allClasses.add(clazz); + if (!found) + allClasses.add(clazz); } } final ConstraintSet cons = getConstraints(); Set> results = new HashSet<>(); try { - Writer logFile = log ? new FileWriter(new File(System.getProperty("user.dir") + "/logFiles/" + "log_" + sourceFiles.keySet().iterator().next().getName())) - : new OutputStreamWriter(new NullOutputStream()); + Writer logFile = log ? new FileWriter(new File(System.getProperty("user.dir") + "/logFiles/" + "log_" + sourceFiles.keySet().iterator().next().getName())) : new OutputStreamWriter(new NullOutputStream()); IFiniteClosure finiteClosure = UnifyTypeFactory.generateFC(allClasses, logFile, classLoader); System.out.println(finiteClosure); ConstraintSet unifyCons = UnifyTypeFactory.convert(cons); System.out.println("xxx1"); Function distributeInnerVars = x -> { UnifyType lhs, rhs; - if (((lhs = x.getLhsType()) instanceof PlaceholderType) - && ((rhs = x.getRhsType()) instanceof PlaceholderType) - && (((PlaceholderType) lhs).isInnerType() || ((PlaceholderType) rhs).isInnerType())) { + if (((lhs = x.getLhsType()) instanceof PlaceholderType) && ((rhs = x.getRhsType()) instanceof PlaceholderType) && (((PlaceholderType) lhs).isInnerType() || ((PlaceholderType) rhs).isInnerType())) { ((PlaceholderType) lhs).setInnerType(true); ((PlaceholderType) rhs).setInnerType(true); } return x; }; - + logFile.write("Unify:" + unifyCons.toString()); System.out.println("Unify:" + unifyCons.toString()); unifyCons = unifyCons.map(distributeInnerVars); @@ -595,58 +427,40 @@ public class JavaTXCompiler { } logFile.flush(); - Set methodParaTypeVarNames = allClasses.stream().map(x -> x.getMethods().stream() - .map(y -> y.getParameterList().getFormalparalist().stream() - .filter(z -> z.getType() instanceof TypePlaceholder) - .map(z -> ((TypePlaceholder) z.getType()).getName()) - .collect(Collectors.toCollection(HashSet::new))) - .reduce(new HashSet(), (a, b) -> { - a.addAll(b); - return a; - }, (a, b) -> { - a.addAll(b); - return a; - })).reduce(new HashSet(), (a, b) -> { - a.addAll(b); - return a; - }); + Set methodParaTypeVarNames = allClasses.stream().map(x -> x.getMethods().stream().map(y -> y.getParameterList().getFormalparalist().stream().filter(z -> z.getType() instanceof TypePlaceholder).map(z -> ((TypePlaceholder) z.getType()).getName()).collect(Collectors.toCollection(HashSet::new))).reduce(new HashSet(), (a, b) -> { + a.addAll(b); + return a; + }, (a, b) -> { + a.addAll(b); + return a; + })).reduce(new HashSet(), (a, b) -> { + a.addAll(b); + return a; + }); - Set constructorParaTypeVarNames = allClasses.stream().map(x -> x.getConstructors().stream() - .map(y -> y.getParameterList().getFormalparalist().stream() - .filter(z -> z.getType() instanceof TypePlaceholder) - .map(z -> ((TypePlaceholder) z.getType()).getName()) - .collect(Collectors.toCollection(HashSet::new))) - .reduce(new HashSet(), (a, b) -> { - a.addAll(b); - return a; - }, (a, b) -> { - a.addAll(b); - return a; - })).reduce(new HashSet(), (a, b) -> { - a.addAll(b); - return a; - }); + Set constructorParaTypeVarNames = allClasses.stream().map(x -> x.getConstructors().stream().map(y -> y.getParameterList().getFormalparalist().stream().filter(z -> z.getType() instanceof TypePlaceholder).map(z -> ((TypePlaceholder) z.getType()).getName()).collect(Collectors.toCollection(HashSet::new))).reduce(new HashSet(), (a, b) -> { + a.addAll(b); + return a; + }, (a, b) -> { + a.addAll(b); + return a; + })).reduce(new HashSet(), (a, b) -> { + a.addAll(b); + return a; + }); Set paraTypeVarNames = methodParaTypeVarNames; paraTypeVarNames.addAll(constructorParaTypeVarNames); - Set returnTypeVarNames = allClasses.stream() - .map(x -> x.getMethods().stream().filter(y -> y.getReturnType() instanceof TypePlaceholder) - .map(z -> ((TypePlaceholder) z.getReturnType()).getName()) - .collect(Collectors.toCollection(HashSet::new))) - .reduce((a, b) -> { - a.addAll(b); - return a; - }).get(); + Set returnTypeVarNames = allClasses.stream().map(x -> x.getMethods().stream().filter(y -> y.getReturnType() instanceof TypePlaceholder).map(z -> ((TypePlaceholder) z.getReturnType()).getName()).collect(Collectors.toCollection(HashSet::new))).reduce((a, b) -> { + a.addAll(b); + return a; + }).get(); - Set fieldTypeVarNames = allClasses.stream() - .map(x -> x.getFieldDecl().stream().filter(y -> y.getReturnType() instanceof TypePlaceholder) - .map(z -> ((TypePlaceholder) z.getReturnType()).getName()) - .collect(Collectors.toCollection(HashSet::new))) - .reduce((a, b) -> { - a.addAll(b); - return a; - }).get(); + Set fieldTypeVarNames = allClasses.stream().map(x -> x.getFieldDecl().stream().filter(y -> y.getReturnType() instanceof TypePlaceholder).map(z -> ((TypePlaceholder) z.getReturnType()).getName()).collect(Collectors.toCollection(HashSet::new))).reduce((a, b) -> { + a.addAll(b); + return a; + }).get(); returnTypeVarNames.addAll(fieldTypeVarNames); @@ -678,63 +492,42 @@ public class JavaTXCompiler { } } return x;// HIER DIE JEWEILS RECHT BZW. LINKE SEITE AUF GLEICHE VARIANZ SETZEN WIE DIE - // JEWEILS ANDERE SEITE + // JEWEILS ANDERE SEITE }); - - //PL 2020-02-05 alle Oder-Constraints Receiver und Parameter werden auf variance 1 gesetzt - //Es wird davon ausgegangen, dass in OderConstraints in Bedingungen für Parameter die Typen der Argumente links stehen - //und die Typen der Rückgabewerte immer rechts stehen - + + // PL 2020-02-05 alle Oder-Constraints Receiver und Parameter werden auf + // variance 1 gesetzt + // Es wird davon ausgegangen, dass in OderConstraints in Bedingungen für + // Parameter die Typen der Argumente links stehen + // und die Typen der Rückgabewerte immer rechts stehen + /* - unifyCons.getOderConstraints().forEach(z -> z.forEach(y -> y.forEach(x -> { - if ((x.getLhsType() instanceof PlaceholderType) && x.getPairOp().compareTo(PairOperator.SMALLERDOT) == 0) { - ((PlaceholderType) x.getLhsType()).setVariance((byte)1); - } - else if ((x.getRhsType() instanceof PlaceholderType) && x.getPairOp().compareTo(PairOperator.EQUALSDOT) == 0) { - ((PlaceholderType) x.getRhsType()).setVariance((byte)-1); - } - }))); - */ - + * unifyCons.getOderConstraints().forEach(z -> z.forEach(y -> y.forEach(x -> { if ((x.getLhsType() instanceof PlaceholderType) && x.getPairOp().compareTo(PairOperator.SMALLERDOT) == 0) { ((PlaceholderType) x.getLhsType()).setVariance((byte)1); } else if ((x.getRhsType() instanceof PlaceholderType) && x.getPairOp().compareTo(PairOperator.EQUALSDOT) == 0) { ((PlaceholderType) x.getRhsType()).setVariance((byte)-1); } }))); + */ + System.out.println("Unify nach Oder-Constraints-Anpassung:" + unifyCons.toString()); Set varianceTPHold; Set varianceTPH = new HashSet<>(); varianceTPH = varianceInheritanceConstraintSet(unifyCons); /* - * PL 2018-11-07 wird in varianceInheritanceConstraintSet erledigt do { //PL - * 2018-11-05 Huellenbildung Variance auf alle TPHs der Terme auf der jeweiligen - * //anderen Seite übertragen varianceTPHold = new HashSet<>(varianceTPH); - * varianceTPH = varianceInheritanceConstraintSet(unifyCons); unifyCons.map( y - * -> { if ((y.getLhsType() instanceof PlaceholderType) && (y.getRhsType() - * instanceof PlaceholderType)) { if - * (((PlaceholderType)y.getLhsType()).getVariance() != 0 && - * ((PlaceholderType)y.getRhsType()).getVariance() == 0) { - * ((PlaceholderType)y.getRhsType()).setVariance(((PlaceholderType)y.getLhsType( - * )).getVariance()); } if (((PlaceholderType)y.getLhsType()).getVariance() == 0 - * && ((PlaceholderType)y.getRhsType()).getVariance() != 0) { - * ((PlaceholderType)y.getLhsType()).setVariance(((PlaceholderType)y.getRhsType( - * )).getVariance()); } } return y; } ); } while - * (!varianceTPHold.equals(varianceTPH)); + * PL 2018-11-07 wird in varianceInheritanceConstraintSet erledigt do { //PL 2018-11-05 Huellenbildung Variance auf alle TPHs der Terme auf der jeweiligen //anderen Seite übertragen varianceTPHold = new HashSet<>(varianceTPH); varianceTPH = varianceInheritanceConstraintSet(unifyCons); unifyCons.map( y -> { if ((y.getLhsType() instanceof PlaceholderType) && (y.getRhsType() instanceof PlaceholderType)) { if (((PlaceholderType)y.getLhsType()).getVariance() != 0 && + * ((PlaceholderType)y.getRhsType()).getVariance() == 0) { ((PlaceholderType)y.getRhsType()).setVariance(((PlaceholderType)y.getLhsType( )).getVariance()); } if (((PlaceholderType)y.getLhsType()).getVariance() == 0 && ((PlaceholderType)y.getRhsType()).getVariance() != 0) { ((PlaceholderType)y.getLhsType()).setVariance(((PlaceholderType)y.getRhsType( )).getVariance()); } } return y; } ); } while (!varianceTPHold.equals(varianceTPH)); */ // Set> result = unify.unifySequential(xConsSet, finiteClosure, // logFile, log); // Set> result = unify.unify(xConsSet, finiteClosure); - List>> oderConstraints = unifyCons.getOderConstraints()//.stream().map(x -> { - /*Set> ret = new HashSet<>(); - for (Constraint y : x) { - ret.add(new HashSet<>(y)); - } - return ret; - }).collect(Collectors.toCollection(ArrayList::new))*/; + List>> oderConstraints = unifyCons.getOderConstraints()// .stream().map(x -> { + /* + * Set> ret = new HashSet<>(); for (Constraint y : x) { ret.add(new HashSet<>(y)); } return ret; }).collect(Collectors.toCollection(ArrayList::new)) + */; if (resultmodel) { /* UnifyResultModel Anfang */ UnifyResultModel urm = new UnifyResultModel(cons, finiteClosure); UnifyResultListenerImpl li = new UnifyResultListenerImpl(); urm.addUnifyResultListener(li); - unify.unifyParallel(unifyCons.getUndConstraints(), oderConstraints, finiteClosure, logFile, log, urm, - usedTasks); + unify.unifyParallel(unifyCons.getUndConstraints(), oderConstraints, finiteClosure, logFile, log, urm, usedTasks); System.out.println("RESULT Final: " + li.getResults()); System.out.println("Constraints for Generated Generics: " + " ???"); logFile.write("RES_FINAL: " + li.getResults().toString() + "\n"); @@ -746,8 +539,7 @@ public class JavaTXCompiler { // Set> result = unify.unify(unifyCons.getUndConstraints(), // oderConstraints, finiteClosure, logFile, log, new UnifyResultModel(cons, // finiteClosure)); - Set> result = unify.unifyOderConstraints(unifyCons.getUndConstraints(), oderConstraints, - finiteClosure, logFile, log, new UnifyResultModel(cons, finiteClosure), usedTasks); + Set> result = unify.unifyOderConstraints(unifyCons.getUndConstraints(), oderConstraints, finiteClosure, logFile, log, new UnifyResultModel(cons, finiteClosure), usedTasks); System.out.println("RESULT: " + result); logFile.write("RES: " + result.toString() + "\n"); logFile.flush(); @@ -774,14 +566,11 @@ public class JavaTXCompiler { } catch (IOException e) { System.err.println("kein LogFile"); } - return results.stream() - .map((unifyPairs -> new ResultSet(UnifyTypeFactory.convert(unifyPairs, Pair.generateTPHMap(cons))))) - .collect(Collectors.toList()); + return results.stream().map((unifyPairs -> new ResultSet(UnifyTypeFactory.convert(unifyPairs, Pair.generateTPHMap(cons))))).collect(Collectors.toList()); } /** - * Vererbt alle Variancen bei Paaren (a <. theta) oder (Theta <. a) wenn a eine - * Variance !=0 hat auf alle Typvariablen in Theta. + * Vererbt alle Variancen bei Paaren (a <. theta) oder (Theta <. a) wenn a eine Variance !=0 hat auf alle Typvariablen in Theta. * * */ @@ -829,21 +618,19 @@ public class JavaTXCompiler { } }); phSetVariance = new ArrayList<>(phSet); // macht vermutlich keinen Sinn PL 2018-10-18, doch, es koennen neue - // TPHs mit Variancen dazugekommen sein PL 2018-11-07 + // TPHs mit Variancen dazugekommen sein PL 2018-11-07 phSetVariance.removeIf(x -> (x.getVariance() == 0 || usedTPH.contains(x))); } return usedTPH; } private SourceFile parse(File sourceFile) throws IOException, java.lang.ClassNotFoundException { - CompilationUnitContext tree = JavaTXParser.parse(sourceFile); - SyntaxTreeGenerator generator = new SyntaxTreeGenerator(environment.getRegistry(sourceFile, classLoader), - new GenericsRegistry(null)); + SourceFileContext tree = JavaTXParser.parse(sourceFile); + SyntaxTreeGenerator generator = new SyntaxTreeGenerator(environment.getRegistry(tree, sourceFile, classLoader), new GenericsRegistry(null)); SourceFile ret = generator.convert(tree, environment.packageCrawler, classLoader); return ret; } - public void generateBytecode() throws ClassNotFoundException, IOException { generateBytecode((File) null); } @@ -852,7 +639,7 @@ public class JavaTXCompiler { * @param path - can be null, then class file output is in the same directory as the parsed source files */ public void generateBytecode(String path) throws ClassNotFoundException, IOException { - if(path != null) + if (path != null) generateBytecode(new File(path)); else generateBytecode(); @@ -873,7 +660,7 @@ public class JavaTXCompiler { } /** - * @param outputPath - can be null, then class file output is in the same directory as the parsed source files + * @param outputPath - can be null, then class file output is in the same directory as the parsed source files * @param typeinferenceResult * @throws IOException */ @@ -882,10 +669,10 @@ public class JavaTXCompiler { HashMap classFiles = new HashMap<>(); SourceFile sf = sourceFiles.get(f); File path; - if(outputPath == null){ - path = f.getParentFile(); //Set path to path of the parsed .jav file - }else{ - path = new File(outputPath ,sf.getPkgName().replace(".","/")); //add package path to root path + if (outputPath == null) { + path = f.getParentFile(); // Set path to path of the parsed .jav file + } else { + path = new File(outputPath, sf.getPkgName().replace(".", "/")); // add package path to root path } var generatedClasses = generateBytecode(sf, typeinferenceResult); @@ -924,52 +711,53 @@ public class JavaTXCompiler { } } - /* PL 2020-03-17 mit TypeExchanger in FCGenerator.java zusammenfuehren */ + /* PL 2020-03-17 mit TypeExchanger in FCGenerator.java zusammenfuehren */ /** - * Tauscht die GTVs in einem Typ gegen die entsprechenden Typen in der übergebenen Map aus. - */ - private static class TypeExchanger implements TypeVisitor{ + * Tauscht die GTVs in einem Typ gegen die entsprechenden Typen in der übergebenen Map aus. + */ + private static class TypeExchanger implements TypeVisitor { - private final HashMap gtvs; + private final HashMap gtvs; - TypeExchanger(HashMap gtvs){ - this.gtvs = gtvs; - } + TypeExchanger(HashMap gtvs) { + this.gtvs = gtvs; + } - @Override - public RefTypeOrTPHOrWildcardOrGeneric visit(RefType refType) { - List params = new ArrayList<>(); - for(RefTypeOrTPHOrWildcardOrGeneric param : refType.getParaList()){ - params.add(param.acceptTV(this)); - } - RefTypeOrTPHOrWildcardOrGeneric ret = new RefType(refType.getName(), params, new NullToken()); - return ret; - } + @Override + public RefTypeOrTPHOrWildcardOrGeneric visit(RefType refType) { + List params = new ArrayList<>(); + for (RefTypeOrTPHOrWildcardOrGeneric param : refType.getParaList()) { + params.add(param.acceptTV(this)); + } + RefTypeOrTPHOrWildcardOrGeneric ret = new RefType(refType.getName(), params, new NullToken()); + return ret; + } - @Override - public RefTypeOrTPHOrWildcardOrGeneric visit(SuperWildcardType superWildcardType) { - SuperWildcardType ret = new SuperWildcardType(superWildcardType.getInnerType().acceptTV(this), superWildcardType.getOffset()); - return ret; - } + @Override + public RefTypeOrTPHOrWildcardOrGeneric visit(SuperWildcardType superWildcardType) { + SuperWildcardType ret = new SuperWildcardType(superWildcardType.getInnerType().acceptTV(this), superWildcardType.getOffset()); + return ret; + } - @Override - public RefTypeOrTPHOrWildcardOrGeneric visit(TypePlaceholder typePlaceholder) { - return typePlaceholder; //TypePlaceholder der vererbert wird kann bei der Vererbung nicht instanziert werden. - } + @Override + public RefTypeOrTPHOrWildcardOrGeneric visit(TypePlaceholder typePlaceholder) { + return typePlaceholder; // TypePlaceholder der vererbert wird kann bei der Vererbung nicht instanziert + // werden. + } - @Override - public RefTypeOrTPHOrWildcardOrGeneric visit(ExtendsWildcardType extendsWildcardType) { - ExtendsWildcardType ret = new ExtendsWildcardType(extendsWildcardType.getInnerType().acceptTV(this), extendsWildcardType.getOffset()); - return ret; - } + @Override + public RefTypeOrTPHOrWildcardOrGeneric visit(ExtendsWildcardType extendsWildcardType) { + ExtendsWildcardType ret = new ExtendsWildcardType(extendsWildcardType.getInnerType().acceptTV(this), extendsWildcardType.getOffset()); + return ret; + } - @Override - public RefTypeOrTPHOrWildcardOrGeneric visit(GenericRefType genericRefType) { - if(! gtvs.containsKey(genericRefType.getParsedName())) - throw new DebugException("Dieser Fall darf nicht auftreten"); - return gtvs.get(genericRefType.getParsedName()); - } + @Override + public RefTypeOrTPHOrWildcardOrGeneric visit(GenericRefType genericRefType) { + if (!gtvs.containsKey(genericRefType.getParsedName())) + throw new DebugException("Dieser Fall darf nicht auftreten"); + return gtvs.get(genericRefType.getParsedName()); + } - } + } } diff --git a/src/main/java/de/dhbwstuttgart/environment/CompilationEnvironment.java b/src/main/java/de/dhbwstuttgart/environment/CompilationEnvironment.java index 9ca471cb..79c89760 100644 --- a/src/main/java/de/dhbwstuttgart/environment/CompilationEnvironment.java +++ b/src/main/java/de/dhbwstuttgart/environment/CompilationEnvironment.java @@ -9,17 +9,17 @@ import java.util.*; import com.google.common.collect.Lists; import de.dhbwstuttgart.syntaxtree.ClassOrInterface; import de.dhbwstuttgart.syntaxtree.factory.ASTFactory; -import org.antlr.v4.runtime.tree.TerminalNode; import de.dhbwstuttgart.exceptions.DebugException; +import de.dhbwstuttgart.exceptions.NotImplementedException; import de.dhbwstuttgart.parser.JavaTXParser; -import de.dhbwstuttgart.parser.antlr.Java8Parser.CompilationUnitContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.SourceFileContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.SrcfileContext; import de.dhbwstuttgart.parser.scope.GatherNames; import de.dhbwstuttgart.parser.scope.JavaClassRegistry; /** - * Stellt die Java-Environment dar und speichert alle Binarys, Librarys und Sourcefiles im zu kompilierenden Projekt - * Sie erstellt anhand dieser Informationen die JavaClassNameRegistry + * Stellt die Java-Environment dar und speichert alle Binarys, Librarys und Sourcefiles im zu kompilierenden Projekt Sie erstellt anhand dieser Informationen die JavaClassNameRegistry * * TODO: Zur Initialisierung der CompilationEnvironment sollten alle SourceFiles mit ANTLR geparst werden und alle Klassen Generics und Typen herausgefunden werden */ @@ -29,79 +29,79 @@ public class CompilationEnvironment { public final PackageCrawler packageCrawler; /** - * Imitiert die Environment beim Aufruf des JavaCompilers auf einer Menge von java-Dateien - * Die Environment enth�lt automatisch die Java Standard Library + * Imitiert die Environment beim Aufruf des JavaCompilers auf einer Menge von java-Dateien Die Environment enth�lt automatisch die Java Standard Library + * * @param sourceFiles die zu kompilierenden Dateien */ public CompilationEnvironment(List sourceFiles) { /** - * 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 + * 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"); - // DirectoryClassLoader cl = DirectoryClassLoader.getPlatformClassLoader(); - String bootClassPath = System.getProperty("java.class.path"); + // String bootClassPath = System.getProperty("sun.boot.class.path"); + // DirectoryClassLoader cl = DirectoryClassLoader.getPlatformClassLoader(); + 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"); - } + 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()); + } + // URLClassLoader loader = new URLClassLoader(new URL[0], cl); + // librarys = Arrays.asList(loader.getURLs()); this.sourceFiles = sourceFiles; - this.packageCrawler = new PackageCrawler(librarys); + this.packageCrawler = new PackageCrawler(librarys); } - public JavaClassRegistry getRegistry(File forSourceFile, ClassLoader classLoader) throws ClassNotFoundException, IOException { + public JavaClassRegistry getRegistry(SourceFileContext tree, File sourceFile, ClassLoader classLoader) throws ClassNotFoundException, IOException { Map allNames; - CompilationUnitContext tree = JavaTXParser.parse(forSourceFile); - allNames = GatherNames.getNames(tree, packageCrawler, classLoader); - for(Class c : loadDefaultPackageClasses(forSourceFile, classLoader)){ - allNames.put(c.getName(), c.getTypeParameters().length); + if (tree instanceof SrcfileContext srcfile) { + allNames = GatherNames.getNames((SrcfileContext) tree, packageCrawler, classLoader); + for (Class c : loadDefaultPackageClasses(getPackageName(srcfile), sourceFile, classLoader)) { + allNames.put(c.getName(), c.getTypeParameters().length); + } + return new JavaClassRegistry(allNames); + } else { + throw new NotImplementedException(); } - return new JavaClassRegistry(allNames); + } - public static List loadDefaultPackageClasses(File forSourceFile, ClassLoader classLoader) throws IOException, ClassNotFoundException { + public static List loadDefaultPackageClasses(String packageName, File sourceFile, ClassLoader classLoader) throws IOException, ClassNotFoundException { List ret = new ArrayList<>(); - String packageName = getPackageName(JavaTXParser.parse(forSourceFile)); - //Set classLoader to include default package for this specific source file - File dir = new File(forSourceFile.getAbsoluteFile().getParent()); + // Set classLoader to include default package for this specific source file + File dir = sourceFile.getParentFile(); String dirPath = dir.toString() + "/"; - if(packageName.length()>0)dirPath = dirPath.substring(0,dirPath.length() - packageName.length()); + if (packageName.length() > 0) + dirPath = dirPath.substring(0, dirPath.length() - packageName.length() - 1); String path = dirPath; ArrayList defaultPath = Lists.newArrayList(new File(path)); classLoader = new DirectoryClassLoader(defaultPath, classLoader); - //Gather all names in the default package for this source file (classes that are imported by default) - File [] files = dir.listFiles((dir1, name) -> name.endsWith(".class")); - if(files != null)for (File classFile : files) { - String className = classFile.getName().substring(0,classFile.getName().length()-6); - if (className.matches("Fun\\d+\\$\\$.*")) continue; - ret.add(classLoader.loadClass(packageName + className)); - } + // Gather all names in the default package for this source file (classes that are imported by default) + File[] files = dir.listFiles((dir1, name) -> name.endsWith(".class")); + if (files != null) + for (File classFile : files) { + String className = classFile.getName().substring(0, classFile.getName().length() - 6); + if (className.matches("Fun\\d+\\$\\$.*")) + continue; + ret.add(classLoader.loadClass(packageName + className)); + } return ret; } - private static String getPackageName(CompilationUnitContext forTree){ + private static String getPackageName(SrcfileContext forTree) { String packageName = ""; - if(forTree.packageDeclaration() != null && forTree.packageDeclaration().Identifier() != null) - for(TerminalNode subPackage : forTree.packageDeclaration().Identifier()){ - packageName += subPackage.toString() + "."; - } + if (forTree.packageDeclaration() != null && !forTree.packageDeclaration().qualifiedName().identifier().isEmpty()) + packageName = forTree.packageDeclaration().qualifiedName().getText(); return packageName; } public List getAllAvailableClasses() { List ret = new ArrayList<>(); - for(Class c : new PackageCrawler(librarys).getAllAvailableClasses()){ + for (Class c : new PackageCrawler(librarys).getAllAvailableClasses()) { ret.add(ASTFactory.createClass(c)); } return ret; diff --git a/src/main/java/de/dhbwstuttgart/parser/JavaTXParser.java b/src/main/java/de/dhbwstuttgart/parser/JavaTXParser.java index aad0a575..eb5db14e 100644 --- a/src/main/java/de/dhbwstuttgart/parser/JavaTXParser.java +++ b/src/main/java/de/dhbwstuttgart/parser/JavaTXParser.java @@ -2,12 +2,13 @@ package de.dhbwstuttgart.parser; import de.dhbwstuttgart.environment.CompilationEnvironment; import de.dhbwstuttgart.parser.SyntaxTreeGenerator.SyntaxTreeGenerator; -import de.dhbwstuttgart.parser.antlr.Java8Lexer; -import de.dhbwstuttgart.parser.antlr.Java8Parser; +import de.dhbwstuttgart.parser.antlr.Java17Lexer; +import de.dhbwstuttgart.parser.antlr.Java17Parser; import de.dhbwstuttgart.parser.scope.JavaClassRegistry; import de.dhbwstuttgart.syntaxtree.SourceFile; -import org.antlr.v4.runtime.ANTLRInputStream; +import org.antlr.v4.runtime.CharStream; +import org.antlr.v4.runtime.CharStreams; import org.antlr.v4.runtime.CommonTokenStream; import java.io.*; @@ -15,23 +16,21 @@ import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; -public class JavaTXParser { - public static Java8Parser.CompilationUnitContext parse(File source) throws IOException, java.lang.ClassNotFoundException { +public class JavaTXParser { + public static Java17Parser.SourceFileContext parse(File source) throws IOException, java.lang.ClassNotFoundException { InputStream stream = new FileInputStream(source); - ANTLRInputStream input = new ANTLRInputStream(stream); - Java8Lexer lexer = new Java8Lexer(input); + // DEPRECATED: ANTLRInputStream input = new ANTLRInputStream(stream); + CharStream input = CharStreams.fromStream(stream); + Java17Lexer lexer = new Java17Lexer(input); CommonTokenStream tokens = new CommonTokenStream(lexer); - Java8Parser parser = new Java8Parser(tokens); - return parser.compilationUnit(); + Java17Parser parser = new Java17Parser(tokens); + return parser.sourceFile(); /* - SyntaxTreeGenerator generator = new SyntaxTreeGenerator(environment.getRegistry(source)); - return generator.convert(tree); - */ + * SyntaxTreeGenerator generator = new SyntaxTreeGenerator(environment.getRegistry(source)); return generator.convert(tree); + */ } - - /* 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))); - } - */ + + /* + * 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/main/java/de/dhbwstuttgart/parser/SyntaxTreeGenerator/StatementGenerator.java b/src/main/java/de/dhbwstuttgart/parser/SyntaxTreeGenerator/StatementGenerator.java index f156114b..b22ef7b2 100644 --- a/src/main/java/de/dhbwstuttgart/parser/SyntaxTreeGenerator/StatementGenerator.java +++ b/src/main/java/de/dhbwstuttgart/parser/SyntaxTreeGenerator/StatementGenerator.java @@ -1,28 +1,114 @@ package de.dhbwstuttgart.parser.SyntaxTreeGenerator; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.stream.Collectors; + +import org.antlr.v4.runtime.Token; + import de.dhbwstuttgart.exceptions.NotImplementedException; import de.dhbwstuttgart.parser.NullToken; -import de.dhbwstuttgart.parser.antlr.Java8Parser; +import de.dhbwstuttgart.parser.antlr.Java17Parser; +import de.dhbwstuttgart.parser.antlr.Java17Parser.AndexpressionContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.ArrayaccessexpressionContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.AssertstmtContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.AssignexpressionContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.BitwiseandexpressionContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.BitwiseorexpressionContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.BitwisexorexpressionContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.BlockstmtContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.BoolLiteralContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.BreakstmtContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.CastexpressionContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.CharLiteralContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.ConditionalassignexpressionContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.ConditionalstmtContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.ContinuestmtContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.DottedexpressionContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.DowhileloopContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.EqualityexpressionContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.ExpressionContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.FltLiteralContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.ForloopContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.IdentifierContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.IntLiteralContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.LabeledstmtContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.LambdaLVTIParameterContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.LambdaexpressionContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.MathaddsubexpressionContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.MathmuldivmodexpressionContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.MethodCallContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.MethodcallexpressionContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.NewinstanceexpressionContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.NullLiteralContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.OrexpressionContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.PostfixexpressionContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.PrefixexpressionContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.PrimaryClassrefContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.PrimaryExpressionContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.PrimaryIdentifierContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.PrimaryLiteralContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.PrimarySuperContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.PrimaryThisContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.PrimaryexpressionContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.RelationalexpressionContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.ReturnstmtContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.SemistmtContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.ShiftexpressionContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.StmtexpressionContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.StringLiteralContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.SwitchexpressionstmtContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.SwitchstmtContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.SynchronizedstmtContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.ThrowstmtContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.TrycatchblockContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.TrycatchresourceContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.WhileloopContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.YieldstmtContext; 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.FormalParameter; +import de.dhbwstuttgart.syntaxtree.ParameterList; +import de.dhbwstuttgart.syntaxtree.statement.ArgumentList; +import de.dhbwstuttgart.syntaxtree.statement.Assign; +import de.dhbwstuttgart.syntaxtree.statement.AssignLeftSide; +import de.dhbwstuttgart.syntaxtree.statement.AssignToField; +import de.dhbwstuttgart.syntaxtree.statement.BinaryExpr; +import de.dhbwstuttgart.syntaxtree.statement.Block; +import de.dhbwstuttgart.syntaxtree.statement.CastExpr; +import de.dhbwstuttgart.syntaxtree.statement.DoStmt; +import de.dhbwstuttgart.syntaxtree.statement.Expression; +import de.dhbwstuttgart.syntaxtree.statement.ExpressionReceiver; +import de.dhbwstuttgart.syntaxtree.statement.FieldVar; +import de.dhbwstuttgart.syntaxtree.statement.IfStmt; +import de.dhbwstuttgart.syntaxtree.statement.LambdaExpression; +import de.dhbwstuttgart.syntaxtree.statement.Literal; +import de.dhbwstuttgart.syntaxtree.statement.LocalVar; +import de.dhbwstuttgart.syntaxtree.statement.LocalVarDecl; +import de.dhbwstuttgart.syntaxtree.statement.MethodCall; +import de.dhbwstuttgart.syntaxtree.statement.NewClass; +import de.dhbwstuttgart.syntaxtree.statement.Receiver; +import de.dhbwstuttgart.syntaxtree.statement.Return; +import de.dhbwstuttgart.syntaxtree.statement.ReturnVoid; +import de.dhbwstuttgart.syntaxtree.statement.Statement; +import de.dhbwstuttgart.syntaxtree.statement.StaticClassName; +import de.dhbwstuttgart.syntaxtree.statement.Super; +import de.dhbwstuttgart.syntaxtree.statement.This; +import de.dhbwstuttgart.syntaxtree.statement.UnaryExpr; +import de.dhbwstuttgart.syntaxtree.statement.WhileStmt; import de.dhbwstuttgart.syntaxtree.type.RefType; import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric; import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder; -import de.dhbwstuttgart.syntaxtree.type.Void; - -import org.antlr.v4.runtime.Token; -import org.antlr.v4.runtime.tree.TerminalNode; - -import java.util.*; -import java.util.stream.Collectors; public class StatementGenerator { private JavaClassRegistry reg; - private Map fields; // PL 2018-11-01 fields eingefuegt, damit die fields immer die gleiche TPH bekommen + private Map fields; // PL 2018-11-01 fields eingefuegt, damit die fields + // immer die gleiche TPH bekommen private Map localVars; private GenericsRegistry generics; @@ -33,25 +119,24 @@ public class StatementGenerator { this.localVars = localVars; } - public ParameterList convert(Java8Parser.FormalParameterListContext formalParameterListContext) { + public ParameterList convert(Java17Parser.FormalParameterListContext formalParameterListContext) { List ret = new ArrayList<>(); - List fps = new ArrayList<>(); - if (formalParameterListContext == null || formalParameterListContext.lastFormalParameter() == null) + List fps = new ArrayList<>(); + if (Objects.isNull(formalParameterListContext)) return new ParameterList(ret, new NullToken()); // Dann ist die Parameterliste leer - - if (formalParameterListContext.lastFormalParameter().formalParameter() == null) - throw new NotImplementedException(); - - if (formalParameterListContext != null && formalParameterListContext.formalParameters() != null && formalParameterListContext.formalParameters().formalParameter() != null) { - fps = new ArrayList<>(formalParameterListContext.formalParameters().formalParameter()); + if (!Objects.isNull(formalParameterListContext.lastFormalParameter())) { + /* + * Der '...' Operator wird noch nicht unterstützt, da dafür benötigte Typen (List oder Array) nicht vom Typinferenzalgo. verarbeitet werden können + */ + throw new NotImplementedException("Formale Parameter variabler Länge nicht unterstützt."); } - fps.add(formalParameterListContext.lastFormalParameter().formalParameter()); - for (Java8Parser.FormalParameterContext fp : fps) { + fps = formalParameterListContext.formalParameter(); + for (Java17Parser.FormalParameterContext fp : fps) { String paramName = SyntaxTreeGenerator.convert(fp.variableDeclaratorId()); RefTypeOrTPHOrWildcardOrGeneric type; - if (fp.unannType() != null) { - type = TypeGenerator.convert(fp.unannType(), reg, generics); + if (fp.typeType() != null) { + type = TypeGenerator.convert(fp.typeType(), reg, generics); } else { type = TypePlaceholder.fresh(fp.getStart()); } @@ -65,125 +150,421 @@ public class StatementGenerator { * StatementGeneration: */ - private Statement convert(Java8Parser.StatementContext stmt) { - if (stmt.statementWithoutTrailingSubstatement() != null) { - return convert(stmt.statementWithoutTrailingSubstatement()); - } else if (stmt.whileStatement() != null) { - return convert(stmt.whileStatement()); - } else if (stmt.forStatement() != null) { - return convert(stmt.forStatement()); - } else if (stmt.ifThenElseStatement() != null) { - return convert(stmt.ifThenElseStatement()); - } else if (stmt.ifThenStatement() != null) { - return convert(stmt.ifThenStatement()); - } else if (stmt.labeledStatement() != null) { - return convert(stmt.labeledStatement()); - } else + private Statement convert(Java17Parser.StatementContext stmt) { + switch (stmt) { + case BlockstmtContext blockstmt: + return convert(blockstmt.block(), false); + case ConditionalstmtContext condition: + return convert(condition); + case WhileloopContext whileloop: + return convert(whileloop); + case DowhileloopContext dowhileloop: + return convert(dowhileloop); + case SwitchstmtContext switchstmt: + return convert(switchstmt); + case SwitchexpressionstmtContext switchexpression: + return convert(switchexpression); + case ReturnstmtContext returnstmt: + return convert(returnstmt); + case YieldstmtContext yieldstmt: + return convert(yieldstmt); + case StmtexpressionContext stmtexpression: + return convert(stmtexpression); + case AssertstmtContext assertstmt: + return convert(assertstmt); + case ForloopContext forloop: + return convert(forloop); + case TrycatchblockContext trycatchblock: + return convert(trycatchblock); + case TrycatchresourceContext trycatchresource: + return convert(trycatchresource); + case SynchronizedstmtContext synchronizedstmt: + return convert(synchronizedstmt); + case ThrowstmtContext throwstmt: + return convert(throwstmt); + case BreakstmtContext breakstmt: + return convert(breakstmt); + case ContinuestmtContext continuestmt: + return convert(continuestmt); + case SemistmtContext semistmt: + return convert(semistmt); + case LabeledstmtContext labeledstmt: + return convert(labeledstmt); + default: throw new NotImplementedException(); + } } - private Statement convert(Java8Parser.StatementNoShortIfContext stmt) { - if (stmt.statementWithoutTrailingSubstatement() != null) { - return convert(stmt.statementWithoutTrailingSubstatement()); - } else if (stmt.labeledStatementNoShortIf() != null) { - return convert(stmt.labeledStatementNoShortIf()); - } else if (stmt.ifThenElseStatementNoShortIf() != null) { - return convert(stmt.ifThenElseStatementNoShortIf()); - } else if (stmt.whileStatementNoShortIf() != null) { - return convert(stmt.whileStatementNoShortIf()); - } else if (stmt.forStatementNoShortIf() != null) { - return convert(stmt.forStatementNoShortIf()); - } else - throw new NotImplementedException(); - } - - private Statement convert(Java8Parser.StatementWithoutTrailingSubstatementContext stmt) { - if (stmt.block() != null) { - return convert(stmt.block(), false); - } else if (stmt.emptyStatement() != null) { - return new EmptyStmt(stmt.getStart()); - } else if (stmt.expressionStatement() != null) { - return convert(stmt.expressionStatement()); - } else if (stmt.assertStatement() != null) { - return convert(stmt.assertStatement()); - } else if (stmt.switchStatement() != null) { - return convert(stmt.switchStatement()); - } else if (stmt.doStatement() != null) { - return convert(stmt.doStatement()); - } else if (stmt.breakStatement() != null) { - return convert(stmt.breakStatement()); - } else if (stmt.continueStatement() != null) { - return convert(stmt.continueStatement()); - } else if (stmt.returnStatement() != null) { - return convert(stmt.returnStatement()); - } else if (stmt.synchronizedStatement() != null) { - return convert(stmt.synchronizedStatement()); - } else if (stmt.throwStatement() != null) { - return convert(stmt.throwStatement()); - } else if (stmt.tryStatement() != null) { - return convert(stmt.tryStatement()); - } else - throw new NotImplementedException(); - } - - public Block convert(Java8Parser.BlockContext block, boolean addTrailingReturn) { + public Block convert(Java17Parser.BlockContext block, boolean addTrailingReturn) { List statements = new ArrayList<>(); - if (block.blockStatements() != null) - for (Java8Parser.BlockStatementContext statementContext : block.blockStatements().blockStatement()) { - List stmt = convert(statementContext); - statements.addAll(stmt); + if (block.blockStatement().size() > 0) + for (Java17Parser.BlockStatementContext statementContext : block.blockStatement()) { + statements.addAll(convert(statementContext)); } if (addTrailingReturn) statements = SyntacticSugar.addTrailingReturn(statements); return new Block(statements, block.getStart()); } - private List convert(Java8Parser.BlockStatementContext statementContext) { - if (statementContext.localVariableDeclarationStatement() != null) { - return convert(statementContext.localVariableDeclarationStatement()); - } else if (statementContext.classDeclaration() != null) { + private List convert(Java17Parser.BlockStatementContext statementContext) { + if (!Objects.isNull(statementContext.localVariableDeclaration())) { + return convert(statementContext.localVariableDeclaration()); + } else if (!Objects.isNull(statementContext.localTypeDeclaration())) { throw new NotImplementedException(); } else { return Arrays.asList(convert(statementContext.statement())); } } - private List convert(Java8Parser.LocalVariableDeclarationStatementContext stmt) { - Java8Parser.LocalVariableDeclarationContext declaration = stmt.localVariableDeclaration(); - return convert(declaration); - } - - private Statement convert(Java8Parser.LabeledStatementContext labeledStatementContext) { + private Statement convert(Java17Parser.LabeledstmtContext labeledStatementContext) { throw new NotImplementedException(); // return convert(labeledStatementContext.statement()); } - private Statement convert(Java8Parser.LabeledStatementNoShortIfContext stmt) { - throw new NotImplementedException(); - // return convert(stmt.statementNoShortIf()); - } - - private Statement convert(Java8Parser.ExpressionStatementContext stmt) { - return convert(stmt.statementExpression()); - } - - private Statement convert(Java8Parser.StatementExpressionContext stmt) { - if (stmt.assignment() != null) { - return convert(stmt.assignment()); - } else if (stmt.preIncrementExpression() != null) { - return convert(stmt.preIncrementExpression()); - } else if (stmt.preDecrementExpression() != null) { - return convert(stmt.preDecrementExpression()); - } else if (stmt.postIncrementExpression() != null) { - return convert(stmt.postIncrementExpression()); - } else if (stmt.postDecrementExpression() != null) { - return convert(stmt.postDecrementExpression()); - } else if (stmt.methodInvocation() != null) { - return convert(stmt.methodInvocation()); - } else if (stmt.classInstanceCreationExpression() != null) { - return convert(stmt.classInstanceCreationExpression()); - } else + private Statement convert(Java17Parser.StmtexpressionContext stmt) { + ExpressionContext expr = stmt.statementExpression; + Token offset = stmt.getStart(); + switch (expr) { + case DottedexpressionContext dotted: + return convertToStatement(dotted, offset); + case MethodcallexpressionContext methodc: + return convert(methodc.methodCall(), offset); + case NewinstanceexpressionContext newinstance: + return convert(newinstance.creator()); + case AssignexpressionContext assignment: + Statement ret = convert(assignment); + ret.setStatement(); + return ret; + case PostfixexpressionContext postfix: + ret = convert(postfix); + ret.setStatement(); + return ret; + case PrefixexpressionContext prefix: + ret = convert(prefix); + ret.setStatement(); + return ret; + default: throw new NotImplementedException(); + } + } + + private Statement convertToStatement(DottedexpressionContext expr, Token offset) { + if (!Objects.isNull(expr.methodCall())) { + return convert(expr.methodCall(), expr.expression(), offset); + } else if (!Objects.isNull(expr.NEW())) { + return convert(expr.innerCreator()); + } else { + throw new NotImplementedException(); + } + } + + private Statement convert(Java17Parser.CreatorContext creator) { + if (creator.nonWildcardTypeArguments() != null) + throw new NotImplementedException(); + + RefType newclass = convert(creator.createdName()); + + if (!Objects.isNull(creator.classCreatorRest())) { + ArgumentList args = convertArguments(creator.classCreatorRest().arguments().expressionList()); + ArrayList argTypes = args.getArguments().stream().map(x -> TypePlaceholder.fresh(creator.getStart())).collect(Collectors.toCollection(ArrayList::new)); + Statement ret = new NewClass(newclass, args, null, argTypes, creator.getStart()); + ret.setStatement(); + return ret; + } else { + return convert(creator.arrayCreatorRest()); + } + } + + private Statement convert(Java17Parser.ArrayCreatorRestContext expression) { + throw new NotImplementedException(); + } + + private RefType convert(Java17Parser.CreatedNameContext createdname) { + Java17Parser.TypeArgumentsContext genericArgs = null; + genericArgs = null; + if (createdname.typeArgumentsOrDiamond() != null) + genericArgs = createdname.typeArgumentsOrDiamond().typeArguments(); + IdentifierContext identifier = createdname.identifier(); + return (RefType) TypeGenerator.convertTypeName(identifier.getText(), genericArgs, identifier.getStart(), reg, generics); + } + + private Statement convert(Java17Parser.InnerCreatorContext innercreator) { + Java17Parser.NonWildcardTypeArgumentsContext genericArgs = null; + + if (!Objects.isNull(innercreator.nonWildcardTypeArgumentsOrDiamond())) { + genericArgs = innercreator.nonWildcardTypeArgumentsOrDiamond().nonWildcardTypeArguments(); + } + IdentifierContext identifier = innercreator.identifier(); + RefType newclass = (RefType) TypeGenerator.convertTypeName(identifier.getText(), genericArgs, identifier.getStart(), reg, generics); + ArgumentList args = convertArguments(innercreator.classCreatorRest().arguments().expressionList()); + ArrayList argTypes = args.getArguments().stream().map(x -> TypePlaceholder.fresh(innercreator.getStart())).collect(Collectors.toCollection(ArrayList::new)); + Statement ret = new NewClass(newclass, args, null, argTypes, innercreator.getStart()); + ret.setStatement(); + return ret; + + } + + private Statement convert(Java17Parser.ConditionalstmtContext stmt) { + Expression expr = convert(stmt.parExpression().expression()); + Statement thenBlock = convert(stmt.statement(0)); + Statement elseBlock = (stmt.statement().size() >= 2) ? convert(stmt.statement(1)) : null; + return new IfStmt(TypePlaceholder.fresh(stmt.getStart()), expr, thenBlock, elseBlock, stmt.getStart()); + } + + private Statement convert(Java17Parser.AssertstmtContext stmt) { + // TODO + throw new NotImplementedException(); + } + + private Statement convert(Java17Parser.SwitchstmtContext stmt) { + // TODO + throw new NotImplementedException(); + } + + private Statement convert(Java17Parser.SwitchexpressionstmtContext switchexpression) { + // TODO + throw new NotImplementedException(); + } + + private Statement convert(Java17Parser.YieldstmtContext yieldstmt) { + // TODO + throw new NotImplementedException(); + } + + private Statement convert(Java17Parser.SwitchBlockStatementGroupContext stmt) { + // TODO + throw new NotImplementedException(); + } + + private Statement convert(Java17Parser.WhileloopContext stmt) { + Expression expr = convert(stmt.parExpression().expression()); + Statement block = convert(stmt.statement()); + return new WhileStmt(expr, block, stmt.getStart()); + } + + private Statement convert(Java17Parser.DowhileloopContext stmt) { + Statement block = convert(stmt.statement()); + Expression expr = convert(stmt.parExpression().expression()); + return new DoStmt(expr, block, stmt.getStart()); + } + + private Statement convert(Java17Parser.ForloopContext stmt) { + throw new NotImplementedException(); + } + + private ArgumentList convertArguments(Java17Parser.ExpressionListContext arglist) { + if (arglist == null) + return new ArgumentList(new ArrayList<>(), new NullToken()); + Token offset = new NullToken(); + List arguments = new ArrayList(); + for (ExpressionContext arg : arglist.expression()) { + arguments.add(convert(arg)); + } + if (arguments.size() > 0) + offset = arguments.get(0).getOffset(); + return new ArgumentList(arguments, offset); + } + + private List convert(Java17Parser.LocalVariableDeclarationContext declaration) { + List ret = new ArrayList<>(); + if (declaration.variableModifier() != null && declaration.variableModifier().size() > 0) { + // TODO + throw new NotImplementedException(); + } + RefTypeOrTPHOrWildcardOrGeneric type; + if (Objects.isNull(declaration.typeType()) || !Objects.isNull(declaration.VAR())) { + type = TypePlaceholder.fresh(declaration.getStart()); + } else { + type = TypeGenerator.convert(declaration.typeType(), reg, generics); + } + if (!Objects.isNull(declaration.variableDeclarators())) + ret.addAll(generateLocalVariableAssignments(declaration.variableDeclarators().variableDeclarator(), type)); + return ret; + } + + private List generateLocalVariableAssignments(List varDeclarators, RefTypeOrTPHOrWildcardOrGeneric type) { + List ret = new ArrayList<>(); + for (Java17Parser.VariableDeclaratorContext varDecl : varDeclarators) { + IdentifierContext name = varDecl.variableDeclaratorId().identifier(); + + ret.add(new LocalVarDecl(name.getText(), type, name.getStart())); + this.localVars.put(name.getText(), type); + if (varDecl.variableInitializer() != null) { + Expression initValue; + if (varDecl.variableInitializer().arrayInitializer() != null) { + throw new NotImplementedException(); + } else { + initValue = convert(varDecl.variableInitializer().expression()); + } + ret.add(new Assign(new AssignToLocal(new LocalVar(name.getText(), type, name.getStart())), initValue, name.getStart())); + } + } + return ret; + } + + public Statement generateFieldAssignment(Java17Parser.VariableDeclaratorContext varDecl, RefTypeOrTPHOrWildcardOrGeneric type) { + IdentifierContext name = varDecl.variableDeclaratorId().identifier(); + Expression initValue; + if (varDecl.variableInitializer().arrayInitializer() != null) { + throw new NotImplementedException(); + } else { + initValue = convert(varDecl.variableInitializer().expression()); + } + return (new Assign(new AssignToField(new FieldVar(new This(varDecl.getStart()), name.getText(), type, varDecl.getStart())), initValue, name.getStart())); + } + + private Statement convert(Java17Parser.BreakstmtContext stmt) { + // TODO + throw new NotImplementedException(); + } + + private Statement convert(Java17Parser.ContinuestmtContext stmt) { + // TODO + throw new NotImplementedException(); + } + + private Statement convert(Java17Parser.SemistmtContext stmt) { + // TODO + throw new NotImplementedException(); + } + + private Statement convert(Java17Parser.ReturnstmtContext stmt) { + if (stmt.expression() != null) { + return new Return(convert(stmt.expression()), stmt.getStart()); + } else { + return new ReturnVoid(stmt.getStart()); + } + } + + private Statement convert(Java17Parser.ThrowstmtContext stmt) { + // TODO + throw new NotImplementedException(); + } + + private Statement convert(Java17Parser.SynchronizedstmtContext stmt) { + // TODO + throw new NotImplementedException(); + } + + private Statement convert(Java17Parser.TrycatchblockContext stmt) { + // TODO + throw new NotImplementedException(); + } + + private Statement convert(Java17Parser.TrycatchresourceContext stmt) { + // TODO + throw new NotImplementedException(); + } + + /* + *************** + Expression Conversions: + */ + + private Expression convert(Java17Parser.ExpressionContext expression) { + switch (expression) { + case PrimaryexpressionContext primary: + return convert(primary.primary()); + case DottedexpressionContext dotted: + return convert(dotted, expression.getStart()); + case MethodcallexpressionContext methodcall: + return convert(methodcall.methodCall(), methodcall.getStart()); + case NewinstanceexpressionContext newinstance: + return convert(newinstance.creator()); + case CastexpressionContext castexpr: + return convert(castexpr); + case PostfixexpressionContext postfexpr: + return convert(postfexpr); + case PrefixexpressionContext prefexpr: + return convert(prefexpr); + case MathmuldivmodexpressionContext mathexpr: + return convert(mathexpr); + case MathaddsubexpressionContext mathexpr: + return convert(mathexpr); + case RelationalexpressionContext comparison: + return convert(comparison); + /* + * TODO: syntaxtree for instanceof vorbereiten case InstanceofexpressionContext instanceof: case SwitchexpressionContext switchexpression: + */ + case EqualityexpressionContext equal: + return convert(equal); + case AssignexpressionContext assignment: + return convert(assignment); + case LambdaexpressionContext lambdaexpr: + return convert(lambdaexpr.lambdaExpression()); + case ArrayaccessexpressionContext arrayaccess: + return convert(arrayaccess); + case ShiftexpressionContext shiftexpr: + return convert(shiftexpr); + case BitwiseandexpressionContext bitwiseand: + return convert(bitwiseand); + case BitwisexorexpressionContext bitwisexor: + return convert(bitwisexor); + case BitwiseorexpressionContext bitwiseor: + return convert(bitwiseor); + case AndexpressionContext andexpr: + return convert(andexpr); + case OrexpressionContext orexpr: + return convert(orexpr); + case ConditionalassignexpressionContext condassign: + return convert(condassign); + default: + throw new NotImplementedException(); + } + } + + private Expression convert(DottedexpressionContext expr, Token offset) { + if (!Objects.isNull(expr.methodCall())) { + return convert(expr.methodCall(), expr.expression(), offset); + } else if (!Objects.isNull(expr.identifier())) { + return generateLocalOrFieldVarOrClassName(expr.getText(), offset); + } else { + // Für alle anderen Optionen, wie Feldzugriff, Aufrufe von super oder explizite + // generische Invokationen + throw new NotImplementedException(); + } + } + + private MethodCall convert(MethodCallContext expr, Token offset) { + String name = "this"; + Expression receiver = new This(offset); + if (expr.identifier() != null) { + name = expr.identifier().getText(); + } else if (!Objects.isNull(expr.SUPER())) { + // if(methodInvocationContext.Identifier() != null){ + name = expr.SUPER().getText(); + receiver = new Super(offset); + } + + ArgumentList argumentList = convertArguments(expr.expressionList()); + ArrayList signature = argumentList.getArguments().stream().map(x -> (RefTypeOrTPHOrWildcardOrGeneric) TypePlaceholder.fresh(offset)).collect(Collectors.toCollection(ArrayList::new)); + signature.add(TypePlaceholder.fresh(offset)); // return type + MethodCall ret = new MethodCall(TypePlaceholder.fresh(offset), getReceiver(receiver), name, argumentList, TypePlaceholder.fresh(offset), signature, offset); + ret.setStatement(); + return ret; + } + + private MethodCall convert(MethodCallContext expr, ExpressionContext receiver, Token offset) { + String name = "this"; + if (expr.identifier() != null) { + name = expr.identifier().getText(); + } else if (!Objects.isNull(expr.SUPER())) { + // if(methodInvocationContext.Identifier() != null){ + name = expr.SUPER().getText(); + } + ArgumentList argumentList = convertArguments(expr.expressionList()); + ArrayList signature = argumentList.getArguments().stream().map(x -> (RefTypeOrTPHOrWildcardOrGeneric) TypePlaceholder.fresh(offset)).collect(Collectors.toCollection(ArrayList::new)); + signature.add(TypePlaceholder.fresh(offset)); // return type + MethodCall ret = new MethodCall(TypePlaceholder.fresh(offset), getReceiver(receiver), name, argumentList, TypePlaceholder.fresh(offset), signature, offset); + ret.setStatement(); + return ret; + } + + public Receiver getReceiver(ExpressionContext expr) { + Expression expression = convert(expr); + /* + * if (expr instanceof PrimaryexpressionContext pc) { expression = convert(pc.primary()); } else { expression = generateLocalOrFieldVarOrClassName(expr.getText(), expr.getStart()); } + */ + return getReceiver(expression); } public Receiver getReceiver(Expression expr) { @@ -194,50 +575,6 @@ public class StatementGenerator { } } - private Statement convert(Java8Parser.MethodInvocationContext methodInvocationContext) { - String name; - if (methodInvocationContext.methodName() != null) { - name = methodInvocationContext.methodName().Identifier().getText(); - } else {// if(methodInvocationContext.Identifier() != null){ - name = methodInvocationContext.Identifier().getText(); - } - Expression receiver; - if (methodInvocationContext.typeName() != null) { - receiver = generateLocalOrFieldVarOrClassName(methodInvocationContext.typeName().getText(), methodInvocationContext.typeName().getStart()); - } else if (methodInvocationContext.expressionName() != null) { - receiver = convert(methodInvocationContext.expressionName()); - } else if (methodInvocationContext.primary() != null) { - receiver = convert(methodInvocationContext.primary()); - } else if (methodInvocationContext.toString().startsWith("super")) { - receiver = new Super(methodInvocationContext.getStart()); - } else if (methodInvocationContext.methodName() != null) { - receiver = new This(methodInvocationContext.getStart()); - } else - throw new NotImplementedException(); - - ArgumentList argumentList = convert(methodInvocationContext.argumentList()); - ArrayList signature = argumentList.getArguments().stream().map(x -> TypePlaceholder.fresh(methodInvocationContext.getStart())).collect(Collectors.toCollection(ArrayList::new)); - signature.add(TypePlaceholder.fresh(methodInvocationContext.getStart())); // ReturnType - MethodCall ret = new MethodCall(TypePlaceholder.fresh(methodInvocationContext.getStart()), getReceiver(receiver), name, argumentList, TypePlaceholder.fresh(methodInvocationContext.getStart()), signature, methodInvocationContext.getStart()); - ret.setStatement(); - return ret; - } - - private ArgumentList convert(Java8Parser.ArgumentListContext argumentListContext) { - if (argumentListContext == null) - return new ArgumentList(new ArrayList<>(), new NullToken()); - List args = new ArrayList<>(); - - Token offset = new NullToken(); - for (Java8Parser.ExpressionContext expr : argumentListContext.expression()) { - args.add(convert(expr)); - } - if (args.size() > 0) - offset = args.get(0).getOffset(); - - return new ArgumentList(args, offset); - } - /** * Der Parser kann nicht zwischen einer lokalen Variable, einem Feldzugriff und einer Klassenangabe unterscheiden. * @@ -252,7 +589,8 @@ public class StatementGenerator { if (localVars.get(expression) != null) { return new LocalVar(expression, localVars.get(expression), offset); } else { - if (fields.get(expression) != null) {// PL 2018-11-01 fields eingefuegt, damit die fields immer die gleiche TPH bekommen + if (fields.get(expression) != null) {// PL 2018-11-01 fields eingefuegt, damit die fields immer die + // gleiche TPH bekommen return new FieldVar(new This(offset), expression, fields.get(expression), offset); } else { @@ -289,68 +627,47 @@ public class StatementGenerator { return new FieldVar(receiver, parts[parts.length - 1], TypePlaceholder.fresh(offset), offset); } - private Expression convert(Java8Parser.ExpressionNameContext expressionNameContext) { - return generateLocalOrFieldVarOrClassName(expressionNameContext.getText(), expressionNameContext.getStart()); + private Expression convert(Java17Parser.ArrayaccessexpressionContext arrayaccess) { + throw new NotImplementedException(); } - private Statement convert(Java8Parser.ClassInstanceCreationExpressionContext newExpression) { - Java8Parser.TypeArgumentsContext genericArgs = null; - if (newExpression.expressionName() != null) + private Expression convert(Java17Parser.ConditionalassignexpressionContext expression) { + throw new NotImplementedException(); + } + + private Expression convert(Java17Parser.OrexpressionContext expression) { + throw new NotImplementedException(); + } + + private Expression convert(Java17Parser.AndexpressionContext expression) { + throw new NotImplementedException(); + } + + private Statement convert(AssignexpressionContext expr) { + switch (expr.bop.getText()) { + case "=": + ExpressionContext leftside = expr.expression(0); + AssignLeftSide leftHandSide = convert(leftside.getText(), leftside.getStart()); + Statement ret = new Assign(leftHandSide, convert(expr.expression(1)), expr.getStart()); + return ret; + case "+=": + case "-=": + case "*=": + case "/=": + case "&=": + case "|=": + case "^=": + case ">>=": + case ">>>=": + case "<<=": + case "%=": + default: throw new NotImplementedException(); - if (newExpression.typeArgumentsOrDiamond() != null) { - if (newExpression.typeArgumentsOrDiamond().typeArguments() != null) { - genericArgs = newExpression.typeArgumentsOrDiamond().typeArguments(); - } } - if (newExpression.typeArguments() != null) - throw new NotImplementedException(); - - TerminalNode identifier = newExpression.Identifier(0); - RefType newClass = (RefType) TypeGenerator.convertTypeName(identifier.getText(), genericArgs, identifier.getSymbol(), reg, generics); - - ArgumentList args = convert(newExpression.argumentList()); - ArrayList signature = args.getArguments().stream().map(x -> TypePlaceholder.fresh(newExpression.getStart())).collect(Collectors.toCollection(ArrayList::new)); - signature.add(TypePlaceholder.fresh(newExpression.getStart())); // ReturnType - Statement ret = new NewClass(newClass, args, null, signature, newExpression.getStart()); - ret.setStatement(); - return ret; } - private Statement convert(Java8Parser.PreIncrementExpressionContext stmt) { - Expression argument = convert(stmt.unaryExpression()); - Token offset = stmt.getStart(); - Statement ret = new UnaryExpr(UnaryExpr.Operation.PREINCREMENT, argument, TypePlaceholder.fresh(offset), offset); - ret.setStatement(); - return ret; - } - - private Statement convert(Java8Parser.PreDecrementExpressionContext stmt) { - Statement ret = new UnaryExpr(UnaryExpr.Operation.PREDECREMENT, convert(stmt.unaryExpression()), TypePlaceholder.fresh(stmt.getStart()), stmt.getStart()); - ret.setStatement(); - return ret; - } - - private Statement convert(Java8Parser.PostIncrementExpressionContext stmt) { - Statement ret = new UnaryExpr(UnaryExpr.Operation.POSTINCREMENT, convert(stmt.postfixExpression()), TypePlaceholder.fresh(stmt.getStart()), stmt.getStart()); - ret.setStatement(); - return ret; - } - - private Statement convert(Java8Parser.PostDecrementExpressionContext stmt) { - Statement ret = new UnaryExpr(UnaryExpr.Operation.POSTDECREMENT, convert(stmt.postfixExpression()), TypePlaceholder.fresh(stmt.getStart()), stmt.getStart()); - ret.setStatement(); - return ret; - } - - private Statement convert(Java8Parser.AssignmentContext stmt) { - AssignLeftSide leftHandSide = convert(stmt.leftHandSide()); - Statement ret = new Assign(leftHandSide, convert(stmt.expression()), stmt.getStart()); - ret.setStatement(); - return ret; - } - - private AssignLeftSide convert(Java8Parser.LeftHandSideContext leftHandSide) { - Expression leftSide = generateLocalOrFieldVarOrClassName(leftHandSide.getText(), leftHandSide.getStart()); + private AssignLeftSide convert(String leftHandSide, Token start) { + Expression leftSide = generateLocalOrFieldVarOrClassName(leftHandSide, start); if (leftSide instanceof FieldVar) return new AssignToField((FieldVar) leftSide); else if (leftSide instanceof LocalVar) @@ -359,293 +676,28 @@ public class StatementGenerator { throw new NotImplementedException(); } - private Statement convert(Java8Parser.IfThenStatementContext stmt) { - // TODO + private Expression convert(Java17Parser.BitwiseorexpressionContext expression) { throw new NotImplementedException(); } - private Statement convert(Java8Parser.IfThenElseStatementContext stmt) { - Expression expr = convert(stmt.parExpression().expression()); - Statement thenBlock = convert(stmt.statementNoShortIf()); - Statement elseBlock = convert(stmt.statement()); - return new IfStmt(TypePlaceholder.fresh(stmt.getStart()), expr, thenBlock, elseBlock, stmt.getStart()); - } - - private Statement convert(Java8Parser.IfThenElseStatementNoShortIfContext stmt) { - // TODO + private Expression convert(Java17Parser.BitwisexorexpressionContext expression) { throw new NotImplementedException(); } - private Statement convert(Java8Parser.AssertStatementContext stmt) { - // TODO + private Expression convert(Java17Parser.BitwiseandexpressionContext expression) { throw new NotImplementedException(); } - private Statement convert(Java8Parser.SwitchStatementContext stmt) { - // TODO - throw new NotImplementedException(); + private Expression convert(Java17Parser.EqualityexpressionContext expression) { + String operator = expression.bop.getText(); + Expression leftSide = convert(expression.expression(0)); + Expression rightSide = convert(expression.expression(1)); + return new BinaryExpr(convertBinaryOperator(operator), TypePlaceholder.fresh(expression.getStart()), leftSide, rightSide, expression.getStart()); } - private Statement convert(Java8Parser.SwitchBlockContext stmt) { - // TODO - throw new NotImplementedException(); - } - - private Statement convert(Java8Parser.SwitchBlockStatementGroupContext stmt) { - // TODO - throw new NotImplementedException(); - } - - private Statement convert(Java8Parser.WhileStatementContext stmt) { - Expression expr = convert(stmt.parExpression().expression()); - Statement block = convert(stmt.statement()); - return new WhileStmt(expr, block, stmt.getStart()); - } - - private Statement convert(Java8Parser.WhileStatementNoShortIfContext stmt) { - // TODO - throw new NotImplementedException(); - } - - private Statement convert(Java8Parser.DoStatementContext stmt) { - Statement block = convert(stmt.statement()); - Expression expr = convert(stmt.parExpression().expression()); - return new DoStmt(expr, block, stmt.getStart()); - } - - private Statement convert(Java8Parser.ForStatementContext stmt) { - if (stmt.basicForStatement() != null) { - return convert(stmt.basicForStatement()); - } else if (stmt.enhancedForStatement() != null) { - return convert(stmt.enhancedForStatement()); - } else - throw new NotImplementedException(); - } - - private Statement convert(Java8Parser.ForStatementNoShortIfContext stmt) { - if (stmt.basicForStatementNoShortIf() != null) { - return convert(stmt.basicForStatementNoShortIf()); - } else if (stmt.enhancedForStatementNoShortIf() != null) { - return convert(stmt.enhancedForStatementNoShortIf()); - } else - throw new NotImplementedException(); - } - - private Statement convert(Java8Parser.BasicForStatementContext stmt) { - // TODO - throw new NotImplementedException(); - } - - private Statement convert(Java8Parser.BasicForStatementNoShortIfContext stmt) { - // TODO - throw new NotImplementedException(); - } - - private List convert(Java8Parser.ForInitContext stmt) { - if (stmt.statementExpressionList() != null) { - return Arrays.asList(convert(stmt.statementExpressionList())); - } else if (stmt.localVariableDeclaration() != null) { - return convert(stmt.localVariableDeclaration()); - } else - throw new NotImplementedException(); - } - - private List convert(Java8Parser.LocalVariableDeclarationContext declaration) { - List ret = new ArrayList<>(); - if (declaration.variableModifier() != null && declaration.variableModifier().size() > 0) { - // TODO - throw new NotImplementedException(); - } - RefTypeOrTPHOrWildcardOrGeneric type; - if (declaration.unannTypeOrAuto().unannType() == null) { - type = TypePlaceholder.fresh(declaration.getStart()); - } else { - type = TypeGenerator.convert(declaration.unannTypeOrAuto().unannType(), reg, generics); - } - ret.addAll(generateLocalVariableAssignments(declaration.variableDeclaratorList().variableDeclarator(), type)); - return ret; - } - - private List generateLocalVariableAssignments(List varDeclarators, RefTypeOrTPHOrWildcardOrGeneric type) { - List ret = new ArrayList<>(); - for (Java8Parser.VariableDeclaratorContext varDecl : varDeclarators) { - TerminalNode name = varDecl.variableDeclaratorId().Identifier(); - - ret.add(new LocalVarDecl(name.getText(), type, name.getSymbol())); - this.localVars.put(name.getText(), type); - if (varDecl.variableInitializer() != null) { - Expression initValue; - if (varDecl.variableInitializer().arrayInitializer() != null) { - throw new NotImplementedException(); - } else { - initValue = convert(varDecl.variableInitializer().expression()); - } - ret.add(new Assign(new AssignToLocal(new LocalVar(name.getText(), type, name.getSymbol())), initValue, name.getSymbol())); - } - } - return ret; - } - - public Statement generateFieldAssignment(Java8Parser.VariableDeclaratorContext varDecl, RefTypeOrTPHOrWildcardOrGeneric type) { - TerminalNode name = varDecl.variableDeclaratorId().Identifier(); - Expression initValue; - if (varDecl.variableInitializer().arrayInitializer() != null) { - throw new NotImplementedException(); - } else { - initValue = convert(varDecl.variableInitializer().expression()); - } - return (new Assign(new AssignToField(new FieldVar(new This(varDecl.getStart()), name.getText(), type, varDecl.getStart())), initValue, name.getSymbol())); - } - - private Statement convert(Java8Parser.ForUpdateContext stmt) { - return convert(stmt.statementExpressionList()); - } - - private Statement convert(Java8Parser.StatementExpressionListContext stmt) { - // TODO - throw new NotImplementedException(); - } - - private Statement convert(Java8Parser.EnhancedForStatementContext stmt) { - // TODO - throw new NotImplementedException(); - } - - private Statement convert(Java8Parser.EnhancedForStatementNoShortIfContext stmt) { - // TODO - throw new NotImplementedException(); - } - - private Statement convert(Java8Parser.BreakStatementContext stmt) { - // TODO - throw new NotImplementedException(); - } - - private Statement convert(Java8Parser.ContinueStatementContext stmt) { - // TODO - throw new NotImplementedException(); - } - - private Statement convert(Java8Parser.ReturnStatementContext stmt) { - if (stmt.expression() != null) { - return new Return(convert(stmt.expression()), stmt.getStart()); - } else { - return new ReturnVoid(stmt.getStart()); - } - } - - private Statement convert(Java8Parser.ThrowStatementContext stmt) { - // TODO - throw new NotImplementedException(); - } - - private Statement convert(Java8Parser.SynchronizedStatementContext stmt) { - // TODO - throw new NotImplementedException(); - } - - private Statement convert(Java8Parser.TryStatementContext stmt) { - // TODO - throw new NotImplementedException(); - } - - private Statement convert(Java8Parser.CatchesContext stmt) { - // TODO - throw new NotImplementedException(); - } - - private Statement convert(Java8Parser.CatchClauseContext stmt) { - // TODO - throw new NotImplementedException(); - } - - /* - *************** + Expression Conversions: - */ - - private Expression convert(Java8Parser.ExpressionContext expression) { - if (expression.lambdaExpression() != null) { - return convert(expression.lambdaExpression()); - } else { - return convert(expression.assignmentExpression()); - } - } - - private Expression convert(Java8Parser.AssignmentExpressionContext expression) { - if (expression.conditionalExpression() != null) { - return convert(expression.conditionalExpression()); - } else { - return convert(expression.assignment()); - } - } - - private Expression convert(Java8Parser.ConditionalExpressionContext expression) { - if (expression.conditionalOrExpression() != null) { - return convert(expression.conditionalOrExpression()); - } else { - throw new NotImplementedException(); - } - } - - private Expression convert(Java8Parser.ConditionalOrExpressionContext expression) { - if (expression.conditionalOrExpression() == null) { - return convert(expression.conditionalAndExpression()); - } else { - throw new NotImplementedException(); - } - } - - private Expression convert(Java8Parser.ConditionalAndExpressionContext expression) { - if (expression.conditionalAndExpression() == null) { - return convert(expression.inclusiveOrExpression()); - } else { - throw new NotImplementedException(); - } - } - - private Expression convert(Java8Parser.InclusiveOrExpressionContext expression) { - if (expression.inclusiveOrExpression() == null) { - return convert(expression.exclusiveOrExpression()); - } else { - throw new NotImplementedException(); - } - } - - private Expression convert(Java8Parser.ExclusiveOrExpressionContext expression) { - if (expression.exclusiveOrExpression() == null) { - return convert(expression.andExpression()); - } else { - throw new NotImplementedException(); - } - } - - private Expression convert(Java8Parser.AndExpressionContext expression) { - if (expression.andExpression() == null) { - return convert(expression.equalityExpression()); - } else { - throw new NotImplementedException(); - } - } - - private Expression convert(Java8Parser.EqualityExpressionContext expression) { - if (expression.equalityExpression() == null) { - return convert(expression.relationalExpression()); - } else { - String operator = expression.getChild(1).getText(); - Expression leftSide = convert(expression.equalityExpression()); - Expression rightSide = convert(expression.relationalExpression()); - return new BinaryExpr(convertBinaryOperator(operator), TypePlaceholder.fresh(expression.getStart()), leftSide, rightSide, expression.getStart()); - } - } - - private Expression convert(Java8Parser.RelationalExpressionContext expression) { - if (expression.relationalExpression() == null) { - return convert(expression.shiftExpression()); - } else { - String operator = expression.getChild(1).getText(); - return new BinaryExpr(convertBinaryOperator(operator), TypePlaceholder.fresh(expression.getStart()), convert(expression.relationalExpression()), convert(expression.shiftExpression()), expression.getStart()); - } - // }else throw new NotImplementedException(); + private Expression convert(Java17Parser.RelationalexpressionContext expression) { + String operator = expression.bop.getText(); + return new BinaryExpr(convertBinaryOperator(operator), TypePlaceholder.fresh(expression.getStart()), convert(expression.expression(0)), convert(expression.expression(1)), expression.getStart()); } private BinaryExpr.Operator convertBinaryOperator(String operator) { @@ -680,255 +732,127 @@ public class StatementGenerator { // throw new NotImplementedException(); } - private Expression convert(Java8Parser.ShiftExpressionContext expression) { - if (expression.shiftExpression() == null) { - return convert(expression.additiveExpression()); - } else { - throw new NotImplementedException(); - } - } - - private Expression convert(Java8Parser.AdditiveExpressionContext expression) { - - if (expression.additiveExpression() == null) { - return convert(expression.multiplicativeExpression()); - } 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); - } - } - - private Expression convert(Java8Parser.MultiplicativeExpressionContext expression) { - if (expression.multiplicativeExpression() == null) { - return convert(expression.unaryExpression()); - } else { - 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); - } - } - - private Expression convert(Java8Parser.UnaryExpressionContext expression) { - if (expression.preIncrementExpression() != null) { - return convert(expression.preIncrementExpression()); - } else if (expression.preDecrementExpression() != null) { - return convert(expression.preDecrementExpression()); - } else if (expression.unaryExpressionNotPlusMinus() != null) { - return convert(expression.unaryExpressionNotPlusMinus()); - } else if (expression.getText().startsWith("+")) { - return new UnaryExpr(UnaryExpr.Operation.PLUS, convert(expression.unaryExpression()), TypePlaceholder.fresh(expression.getStart()), expression.getStart()); - } else if (expression.getText().startsWith("-")) { - return new UnaryExpr(UnaryExpr.Operation.MINUS, convert(expression.unaryExpression()), TypePlaceholder.fresh(expression.getStart()), expression.getStart()); - } else { - // Diese Exceptions sollte nie geworfen werden. - // Der Code wurde nur noch nicht getestet. Sollte zur Sicherheit drin bleiben. - throw new NotImplementedException(); - } - } - - private Expression convert(Java8Parser.UnaryExpressionNotPlusMinusContext expression) { - if (expression.postfixExpression() != null) { - return convert(expression.postfixExpression()); - } else if (expression.castExpression() != null) { - return convert(expression.castExpression()); - } else { - throw new NotImplementedException(); - } - } - - private Expression convert(Java8Parser.CastExpressionContext expressionContext) { - Expression expr = null; - if (expressionContext.unaryExpression() != null) { - throw new NotImplementedException(); - } else if (expressionContext.unaryExpressionNotPlusMinus() != null) { - expr = convert(expressionContext.unaryExpressionNotPlusMinus()); - } else if (expressionContext.lambdaExpression() != null) { - expr = convert(expressionContext.lambdaExpression()); - } - return new CastExpr(TypeGenerator.convert(expressionContext.referenceType(), reg, generics), expr, expressionContext.getStart()); - } - - private Expression convert(Java8Parser.PostfixExpressionContext expression) { - Expression expr; - if (expression.primary() != null) { - expr = convert(expression.primary()); - } else { - expr = convert(expression.expressionName()); - } - if (expression.postDecrementExpression_lf_postfixExpression() == null && expression.postIncrementExpression_lf_postfixExpression() == null) { - return expr; - } - - for (Java8Parser.PostIncrementExpression_lf_postfixExpressionContext inc : expression.postIncrementExpression_lf_postfixExpression()) { - expr = new UnaryExpr(UnaryExpr.Operation.POSTINCREMENT, expr, TypePlaceholder.fresh(inc.getStart()), inc.getStart()); - } - for (Java8Parser.PostDecrementExpression_lf_postfixExpressionContext dec : expression.postDecrementExpression_lf_postfixExpression()) { - expr = new UnaryExpr(UnaryExpr.Operation.POSTDECREMENT, expr, TypePlaceholder.fresh(dec.getStart()), dec.getStart()); - } - - return expr; - } - - private Expression convert(Java8Parser.PrimaryContext primary) { - Expression expr; - if (primary.primaryNoNewArray_lfno_primary() != null) { - expr = convert(primary.primaryNoNewArray_lfno_primary()); - } else { - expr = convert(primary.arrayCreationExpression()); - } - - if (primary.primaryNoNewArray_lf_primary() != null && primary.primaryNoNewArray_lf_primary().size() > 0) { - for (Java8Parser.PrimaryNoNewArray_lf_primaryContext e : primary.primaryNoNewArray_lf_primary()) { - expr = convert(expr, e); - } - } - return expr; - } - - private Expression convert(Expression expr, Java8Parser.PrimaryNoNewArray_lf_primaryContext e) { - if (e.classInstanceCreationExpression_lf_primary() != null) { - throw new NotImplementedException(); - } else if (e.fieldAccess_lf_primary() != null) { - - throw new NotImplementedException(); - } else if (e.arrayAccess_lf_primary() != null) { - throw new NotImplementedException(); - } else if (e.methodReference_lf_primary() != null) { - throw new NotImplementedException(); - } else { - Java8Parser.MethodInvocation_lf_primaryContext ctxt = e.methodInvocation_lf_primary(); - String methodName = ctxt.Identifier().toString(); - ArrayList signature = ctxt.argumentList().expression().stream().map(x -> TypePlaceholder.fresh(e.getStart())).collect(Collectors.toCollection(ArrayList::new)); - signature.add(TypePlaceholder.fresh(e.getStart())); // ReturnType - return new MethodCall(TypePlaceholder.fresh(e.getStart()), getReceiver(expr), methodName, convert(ctxt.argumentList()), TypePlaceholder.fresh(e.getStart()), signature, e.getStart()); - } - } - - private Expression convert(Java8Parser.ArrayCreationExpressionContext expression) { + private Expression convert(Java17Parser.ShiftexpressionContext expression) { throw new NotImplementedException(); } - private Expression convert(Java8Parser.PrimaryNoNewArray_lfno_primaryContext expression) { - if (expression.literal() != null) { - return convert(expression.literal()); - } else if (expression.parExpression() != null) { - return convert(expression.parExpression().expression()); - } else if (expression.methodInvocation_lfno_primary() != null) { - return convert(expression.methodInvocation_lfno_primary()); - } else if (expression.classInstanceCreationExpression_lfno_primary() != null) { - return convert(expression.classInstanceCreationExpression_lfno_primary()); - } else if (expression.getText().equals("this")) { - return new This(expression.getStart()); - } else if (expression.fieldAccess_lfno_primary() != null) { - return convert(expression.fieldAccess_lfno_primary()); - } else if (expression.methodReference_lfno_primary() != null) { - throw new NotImplementedException(); - } else if (expression.typeName() != null) { - throw new NotImplementedException(); - } else if (expression.unannPrimitiveType() != null) { - throw new NotImplementedException(); - } else if (expression.arrayAccess_lfno_primary() != null) { - throw new NotImplementedException(); - } else if (expression.fieldAccess_lfno_primary() != null) { - throw new NotImplementedException(); + private Expression convert(Java17Parser.MathaddsubexpressionContext expression) { + Expression leftSide = convert(expression.expression(0)); + Expression rightSide = convert(expression.expression(1)); + BinaryExpr.Operator op = convertBinaryOperator(expression.bop.getText()); + Token offset = expression.getStart(); + return new BinaryExpr(op, TypePlaceholder.fresh(expression.getStart()), leftSide, rightSide, offset); + } + + private Expression convert(Java17Parser.MathmuldivmodexpressionContext expression) { + Expression leftSide = convert(expression.expression(0)); + Expression rightSide = convert(expression.expression(1)); + BinaryExpr.Operator op = convertBinaryOperator(expression.bop.getText()); + Token offset = expression.getStart(); + return new BinaryExpr(op, TypePlaceholder.fresh(offset), leftSide, rightSide, offset); + } + + private Statement convert(PrefixexpressionContext prefixexpr) { + Expression expr = convert(prefixexpr.expression()); + Token op = prefixexpr.prefix; + Statement ret; + if (op.getText().equals("++")) { + ret = new UnaryExpr(UnaryExpr.Operation.PREINCREMENT, expr, TypePlaceholder.fresh(op), op); + ret.setStatement(); + return ret; + } else if (op.getText().equals("--")) { + ret = new UnaryExpr(UnaryExpr.Operation.PREDECREMENT, expr, TypePlaceholder.fresh(op), op); + ret.setStatement(); + return ret; } else { throw new NotImplementedException(); } } - private Expression convert(Java8Parser.FieldAccess_lfno_primaryContext fieldAccess_lfno_primaryContext) { - throw new NotImplementedException(); - } - - private Expression convert(Java8Parser.ClassInstanceCreationExpression_lfno_primaryContext newExpression) { - Java8Parser.TypeArgumentsContext genericArgs = null; - if (newExpression.expressionName() != null) - throw new NotImplementedException(); - if (newExpression.typeArgumentsOrDiamond() != null) { - if (newExpression.typeArgumentsOrDiamond().typeArguments() != null) { - genericArgs = newExpression.typeArgumentsOrDiamond().typeArguments(); - } - } - if (newExpression.typeArguments() != null) - throw new NotImplementedException(); - - TerminalNode identifier = newExpression.Identifier(0); - RefType newClass = (RefType) TypeGenerator.convertTypeName(identifier.getText(), genericArgs, identifier.getSymbol(), reg, generics); - - ArgumentList args = convert(newExpression.argumentList()); - ArrayList signature = args.getArguments().stream().map(x -> TypePlaceholder.fresh(newExpression.getStart())).collect(Collectors.toCollection(ArrayList::new)); - signature.add(TypePlaceholder.fresh(newExpression.getStart())); // ReturnType - return new NewClass(newClass, args, null, signature, newExpression.getStart()); - } - - private Expression convert(Java8Parser.LiteralContext literal) { - if (literal.IntegerLiteral() != null) { - Number value = Integer.parseInt(literal.IntegerLiteral().getText()); - return new Literal(TypePlaceholder.fresh(literal.getStart()), value, literal.getStart()); - } else if (literal.FloatingPointLiteral() != null) { - Number value = Double.parseDouble(literal.FloatingPointLiteral().getText()); - return new Literal(TypePlaceholder.fresh(literal.getStart()), value, literal.getStart()); - } else if (literal.BooleanLiteral() != null) { - RefType type = new RefType(reg.getName("java.lang.Boolean"), literal.getStart()); - return new Literal(type, Boolean.parseBoolean(literal.BooleanLiteral().getText()), literal.getStart()); - } else if (literal.CharacterLiteral() != null) { - RefType type = new RefType(reg.getName("java.lang.Character"), literal.getStart()); - return new Literal(type, - // 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()); - return new Literal(type, literal.StringLiteral().getText().substring(1, literal.StringLiteral().getText().length() - 1), literal.getStart()); - } else if (literal.NullLiteral() != null) { - return new Literal(TypePlaceholder.fresh(literal.getStart()), null, literal.getStart()); - } else { + private Statement convert(Java17Parser.PostfixexpressionContext postfixexpr) { + Expression expr = convert(postfixexpr.expression()); + Token op = postfixexpr.postfix; + switch (op.getText()) { + case "++": + return new UnaryExpr(UnaryExpr.Operation.POSTINCREMENT, expr, TypePlaceholder.fresh(op), op); + case "--": + return new UnaryExpr(UnaryExpr.Operation.POSTDECREMENT, expr, TypePlaceholder.fresh(op), op); + default: throw new NotImplementedException(); } } - private Expression convert(Java8Parser.MethodInvocation_lfno_primaryContext methodInvocationContext) { - String name; - if (methodInvocationContext.methodName() != null) { - name = methodInvocationContext.methodName().Identifier().getText(); - } else {// if(methodInvocationContext.Identifier() != null){ - name = methodInvocationContext.Identifier().getText(); - } - Expression receiver; - if (methodInvocationContext.typeName() != null) { - receiver = generateLocalOrFieldVarOrClassName(methodInvocationContext.typeName().getText(), methodInvocationContext.typeName().getStart()); - } else if (methodInvocationContext.expressionName() != null) { - receiver = convert(methodInvocationContext.expressionName()); - } else if (methodInvocationContext.toString().startsWith("super")) { - receiver = new Super(methodInvocationContext.getStart()); - } else if (methodInvocationContext.methodName() != null) { - receiver = new This(methodInvocationContext.methodName().getStart()); - } else { + private Expression convert(Java17Parser.CastexpressionContext castexpr) { + ExpressionContext expr = castexpr.expression(); + if (expr instanceof PrefixexpressionContext pfe) { throw new NotImplementedException(); } - - ArgumentList argumentList = convert(methodInvocationContext.argumentList()); - ArrayList signature = argumentList.getArguments().stream().map(x -> TypePlaceholder.fresh(methodInvocationContext.getStart())).collect(Collectors.toCollection(ArrayList::new)); - signature.add(TypePlaceholder.fresh(methodInvocationContext.getStart())); // ReturnType - MethodCall ret = new MethodCall(TypePlaceholder.fresh(methodInvocationContext.getStart()), getReceiver(receiver), name, argumentList, TypePlaceholder.fresh(methodInvocationContext.getStart()), signature, methodInvocationContext.getStart()); - return ret; + return new CastExpr(TypeGenerator.convert(castexpr.typeType(0), reg, generics), convert(expr), expr.getStart()); } - private Expression convert(Java8Parser.LambdaExpressionContext expression) { - Java8Parser.LambdaParametersContext lambdaParams = expression.lambdaParameters(); + private Expression convert(Java17Parser.PrimaryContext primary) { + switch (primary) { + case PrimaryExpressionContext primexpression: + return convert(primexpression.expression()); + case PrimaryThisContext primthis: + return new This(primthis.getStart()); + case PrimarySuperContext primsuper: + throw new NotImplementedException(); + case PrimaryLiteralContext primliteral: + return convert(primliteral.literal()); + case PrimaryIdentifierContext primidentifier: + return generateLocalOrFieldVarOrClassName(primidentifier.getText(), primidentifier.getStart()); + case PrimaryClassrefContext primclassref: + throw new NotImplementedException(); + default: + throw new NotImplementedException(); + } + } + + private Expression convert(Java17Parser.LiteralContext literal) { + switch (literal) { + case IntLiteralContext intliteral: + Number value = Integer.parseInt(intliteral.getText()); + return new Literal(TypePlaceholder.fresh(literal.getStart()), value, intliteral.getStart()); + case FltLiteralContext floatliteral: + value = Double.parseDouble(floatliteral.getText()); + return new Literal(TypePlaceholder.fresh(literal.getStart()), value, floatliteral.getStart()); + case CharLiteralContext charliteral: + RefType type = new RefType(reg.getName("java.lang.Character"), charliteral.getStart()); + return new Literal(type, charliteral.getText().charAt(1), charliteral.getStart()); + case StringLiteralContext stringliteral: + type = new RefType(reg.getName("java.lang.String"), stringliteral.getStart()); + return new Literal(type, stringliteral.getText().substring(1, stringliteral.getText().length() - 1), stringliteral.getStart()); + case BoolLiteralContext boolliteral: + type = new RefType(reg.getName("java.lang.Boolean"), boolliteral.getStart()); + return new Literal(type, Boolean.parseBoolean(boolliteral.getText()), boolliteral.getStart()); + case NullLiteralContext nullliteral: + return new Literal(TypePlaceholder.fresh(nullliteral.getStart()), null, nullliteral.getStart()); + default: + throw new NotImplementedException(); + } + } + + private Expression convert(Java17Parser.LambdaExpressionContext expression) { + Java17Parser.LambdaParametersContext lambdaParams = expression.lambdaParameters(); ParameterList params; - if (lambdaParams.Identifier() != null) { + if (lambdaParams.identifier().size() > 0) { List parameterList = new ArrayList<>(); - parameterList.add(new FormalParameter(lambdaParams.Identifier().getText(), TypePlaceholder.fresh(lambdaParams.getStart()), lambdaParams.getStart())); + for (IdentifierContext identifier : lambdaParams.identifier()) { + Token offset = identifier.getStart(); + parameterList.add(new FormalParameter(identifier.getText(), TypePlaceholder.fresh(offset), offset)); + } params = new ParameterList(parameterList, lambdaParams.getStart()); } else if (lambdaParams.formalParameterList() != null) { params = convert(lambdaParams.formalParameterList()); // }else if( lambdaParams.inferredFormalParameterList != null){ + } else if (!Objects.isNull(lambdaParams.lambdaLVTIList())) { + List parameterList = new ArrayList<>(); + for (LambdaLVTIParameterContext param : lambdaParams.lambdaLVTIList().lambdaLVTIParameter()) { + Token offset = param.getStart(); + parameterList.add(new FormalParameter(param.identifier().getText(), TypePlaceholder.fresh(offset), offset)); + } + params = new ParameterList(parameterList, lambdaParams.getStart()); } else { params = new ParameterList(new ArrayList<>(), expression.getStart()); } @@ -953,7 +877,8 @@ public class StatementGenerator { params.getFormalparalist().forEach(formalParameter -> // Für jeden Parameter einen TPH anfügen: funNParams.add(TypePlaceholder.fresh(expression.getStart()))); RefTypeOrTPHOrWildcardOrGeneric lambdaType = TypePlaceholder.fresh(expression.getStart()); - // RefType lambdaType = new RefType(reg.getName("Fun"+params.getFormalparalist().size()), + // RefType lambdaType = new + // RefType(reg.getName("Fun"+params.getFormalparalist().size()), // funNParams, name.getStart()); return new LambdaExpression(lambdaType, params, block, expression.getStart()); } diff --git a/src/main/java/de/dhbwstuttgart/parser/SyntaxTreeGenerator/SyntacticSugar.java b/src/main/java/de/dhbwstuttgart/parser/SyntaxTreeGenerator/SyntacticSugar.java index d7926004..a564c49c 100644 --- a/src/main/java/de/dhbwstuttgart/parser/SyntaxTreeGenerator/SyntacticSugar.java +++ b/src/main/java/de/dhbwstuttgart/parser/SyntaxTreeGenerator/SyntacticSugar.java @@ -10,19 +10,21 @@ import java.util.List; public class SyntacticSugar { - public static List addTrailingReturn(List statements){ - if(statements.size()!=0) { + public static List addTrailingReturn(List statements) { + if (statements.size() != 0) { Statement lastStmt = statements.get(statements.size() - 1); ReturnFinder hasReturn = new ReturnFinder(); lastStmt.accept(hasReturn); - if(hasReturn.hasReturn)return statements; + if (hasReturn.hasReturn) + return statements; } statements.add(new ReturnVoid(new NullToken())); return statements; } - private static class ReturnFinder extends AbstractASTWalker{ + private static class ReturnFinder extends AbstractASTWalker { public boolean hasReturn = false; + @Override public void visit(Return aReturn) { hasReturn = true; @@ -34,9 +36,10 @@ public class SyntacticSugar { } } - private static boolean hasReturn(Block block){ - for(Statement s : block.getStatements()) - if(s instanceof Return)return true; + private static boolean hasReturn(Block block) { + for (Statement s : block.getStatements()) + if (s instanceof Return) + return true; return false; } diff --git a/src/main/java/de/dhbwstuttgart/parser/SyntaxTreeGenerator/SyntaxTreeGenerator.java b/src/main/java/de/dhbwstuttgart/parser/SyntaxTreeGenerator/SyntaxTreeGenerator.java index 33559a8e..5a8735c1 100644 --- a/src/main/java/de/dhbwstuttgart/parser/SyntaxTreeGenerator/SyntaxTreeGenerator.java +++ b/src/main/java/de/dhbwstuttgart/parser/SyntaxTreeGenerator/SyntaxTreeGenerator.java @@ -1,516 +1,604 @@ package de.dhbwstuttgart.parser.SyntaxTreeGenerator; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; + +import org.antlr.v4.runtime.CommonToken; +import org.antlr.v4.runtime.Token; + +import com.google.common.graph.ElementOrder.Type; + import de.dhbwstuttgart.environment.PackageCrawler; import de.dhbwstuttgart.exceptions.NotImplementedException; -import java.lang.ClassNotFoundException; - import de.dhbwstuttgart.exceptions.TypeinferenceException; -import de.dhbwstuttgart.parser.NullToken; -import de.dhbwstuttgart.parser.antlr.Java8Parser; +import de.dhbwstuttgart.parser.antlr.Java17Parser; +import de.dhbwstuttgart.parser.antlr.Java17Parser.ClassBodyDeclarationContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.ClassOrInterfaceTypeContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.ClassorinterfacedeclContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.ConstructorDeclarationContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.ConstructordeclContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.EmptymethodContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.GenericConstructorDeclarationContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.GenericDeclarationListContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.GenericInterfaceMethodDeclarationContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.GenericconstructorContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.GenericinterfacemethodContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.GenericmethodContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.InterfaceBodyDeclarationContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.InterfaceCommonBodyDeclarationContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.InterfaceMethodDeclarationContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.InterfaceMethodModifierContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.InterfaceconstContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.InterfacememberContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.InterfacemethodContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.MemberclassorinterfaceContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.MemberconstructorContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.MemberdeclContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.MemberfieldContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.MembermethodContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.MethodBodyContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.MethodDeclarationContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.MethodHeaderContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.MethodblockContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.MethoddeclContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.ModifierContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.NoclassorinterfaceContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.RecordComponentContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.RecordDeclarationContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.ReftypeContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.SrcfileContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.TypeArgumentsContext; import de.dhbwstuttgart.parser.scope.GatherNames; import de.dhbwstuttgart.parser.scope.GenericsRegistry; import de.dhbwstuttgart.parser.scope.JavaClassName; import de.dhbwstuttgart.parser.scope.JavaClassRegistry; -import de.dhbwstuttgart.syntaxtree.*; +import de.dhbwstuttgart.syntaxtree.ClassOrInterface; +import de.dhbwstuttgart.syntaxtree.Constructor; +import de.dhbwstuttgart.syntaxtree.Field; +import de.dhbwstuttgart.syntaxtree.FormalParameter; +import de.dhbwstuttgart.syntaxtree.GenericDeclarationList; +import de.dhbwstuttgart.syntaxtree.Method; +import de.dhbwstuttgart.syntaxtree.ParameterList; +import de.dhbwstuttgart.syntaxtree.Record; +import de.dhbwstuttgart.syntaxtree.SourceFile; import de.dhbwstuttgart.syntaxtree.factory.ASTFactory; -import de.dhbwstuttgart.syntaxtree.statement.*; +import de.dhbwstuttgart.syntaxtree.statement.Assign; +import de.dhbwstuttgart.syntaxtree.statement.AssignLeftSide; +import de.dhbwstuttgart.syntaxtree.statement.AssignToField; +import de.dhbwstuttgart.syntaxtree.statement.Block; +import de.dhbwstuttgart.syntaxtree.statement.FieldVar; +import de.dhbwstuttgart.syntaxtree.statement.LocalVar; +import de.dhbwstuttgart.syntaxtree.statement.Return; +import de.dhbwstuttgart.syntaxtree.statement.Statement; +import de.dhbwstuttgart.syntaxtree.statement.This; import de.dhbwstuttgart.syntaxtree.type.RefType; import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric; import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder; +import de.dhbwstuttgart.syntaxtree.type.Void; +import de.dhbwstuttgart.typeinference.constraints.GenericsResolver; -import java.lang.reflect.Modifier; -import java.net.URL; -import java.sql.Ref; -import java.util.*; -import java.util.stream.Collectors; - -//import jdk.internal.dynalink.support.TypeConverterFactory; -import org.antlr.v4.runtime.CommonToken; -import org.antlr.v4.runtime.Token; -import org.antlr.v4.runtime.tree.TerminalNode; - -public class SyntaxTreeGenerator{ +public class SyntaxTreeGenerator { private JavaClassRegistry reg; private final GenericsRegistry globalGenerics; private String pkgName = ""; - Set imports = new HashSet(); - private Map fields = new HashMap<>(); //PL 2018-11-01 fields eingefuegt, damit die fields immer die gleiche TPH bekommen + Set imports = new HashSet<>(); + HashMap allmodifiers = new HashMap<>(); + // PL 2018-11-01 fields eingefuegt, damit die fields immer die gleiche TPH + // bekommen + private Map fields = new HashMap<>(); + // PL 2019-10-23: Muss für jede Klasse neu initilisiert werden + List fieldInitializations = new ArrayList<>(); - List fieldInitializations = new ArrayList<>(); //PL 2019-10-23: Muss für jede Klasse neu initilisiert werden - - public SyntaxTreeGenerator(JavaClassRegistry reg, GenericsRegistry globalGenerics){ - //Die Generics müssen während des Bauens des AST erstellt werden, + public SyntaxTreeGenerator(JavaClassRegistry reg, GenericsRegistry globalGenerics) { + // Die Generics müssen während des Bauens des AST erstellt werden, // da diese mit der Methode oder Klasse, in welcher sie deklariert werden - // verknüpft sein müssen. Dennoch werden die Namen aller Generics in einer globalen Datenbank benötigt. + // verknüpft sein müssen. Dennoch werden die Namen aller Generics in einer + // globalen Datenbank benötigt. this.globalGenerics = globalGenerics; this.reg = reg; + this.allmodifiers.put(Modifier.toString(Modifier.PUBLIC), Modifier.PUBLIC); + this.allmodifiers.put(Modifier.toString(Modifier.PRIVATE), Modifier.PRIVATE); + this.allmodifiers.put(Modifier.toString(Modifier.PROTECTED), Modifier.PROTECTED); + this.allmodifiers.put(Modifier.toString(Modifier.ABSTRACT), Modifier.ABSTRACT); + this.allmodifiers.put(Modifier.toString(Modifier.STATIC), Modifier.STATIC); + this.allmodifiers.put(Modifier.toString(Modifier.STRICT), Modifier.STRICT); + this.allmodifiers.put(Modifier.toString(Modifier.FINAL), Modifier.FINAL); + this.allmodifiers.put(Modifier.toString(Modifier.TRANSIENT), Modifier.TRANSIENT); + this.allmodifiers.put(Modifier.toString(Modifier.VOLATILE), Modifier.VOLATILE); + this.allmodifiers.put(Modifier.toString(Modifier.SYNCHRONIZED), Modifier.SYNCHRONIZED); + this.allmodifiers.put(Modifier.toString(Modifier.NATIVE), Modifier.NATIVE); + this.allmodifiers.put(Modifier.toString(Modifier.INTERFACE), Modifier.INTERFACE); + this.allmodifiers.put("sealed", 4096); + this.allmodifiers.put("non-sealed", 8192); + this.allmodifiers.put("default", 16384); + this.allmodifiers.put("strictfp", 32768); } - - public JavaClassRegistry getReg(){ + public JavaClassRegistry getReg() { return this.reg; } - // Converts type name to String. - public String convertTypeName(Java8Parser.TypeNameContext ctx){ - String ret; - if(ctx.packageOrTypeName() == null){ - ret = ctx.Identifier().toString(); - } - else{ - ret = convertPackageOrTypeName(ctx.packageOrTypeName()) + "." + ctx.Identifier().toString(); - } - return ret; + public String convertQualifiedName(Java17Parser.QualifiedNameContext ctx) { + /* + * String ret = ""; for (Java17Parser.IdentifierContext ident : ctx.identifier()) { ret += ident.getText(); if (ctx.identifier().iterator().hasNext()) { ret += '.'; } } + */ + return ctx.getText(); } - - // Converts PackageOrTypeName to String. - public String convertPackageOrTypeName(Java8Parser.PackageOrTypeNameContext ctx){ - String ret; - if(ctx.packageOrTypeName() == null){ - ret = ctx.Identifier().toString(); - } - else{ - ret = convertPackageOrTypeName(ctx.packageOrTypeName()) + "." + ctx.Identifier().toString(); - } - return ret; - } - - public SourceFile convert(Java8Parser.CompilationUnitContext ctx, PackageCrawler packageCrawler, ClassLoader classLoader) throws ClassNotFoundException{ - if(ctx.packageDeclaration()!=null)this.pkgName = convert(ctx.packageDeclaration()); + + public SourceFile convert(Java17Parser.SourceFileContext ctx, PackageCrawler packageCrawler, ClassLoader classLoader) throws ClassNotFoundException, NotImplementedException { + SrcfileContext srcfile; List classes = new ArrayList<>(); - Map imports = GatherNames.getImports(ctx, packageCrawler, classLoader); + if (ctx instanceof Java17Parser.SrcfileContext) { + srcfile = (SrcfileContext) ctx; + } else { + return new SourceFile(this.pkgName, classes, this.imports); + } + if (srcfile.packageDeclaration() != null) + this.pkgName = convert(srcfile.packageDeclaration()); + Map imports = GatherNames.getImports(srcfile, packageCrawler, classLoader); this.imports = imports.keySet().stream().map(name -> reg.getName(name)).collect(Collectors.toSet()); - for(Java8Parser.TypeDeclarationContext typeDecl : ctx.typeDeclaration()){ - ClassOrInterface newClass; - if(typeDecl.classDeclaration() != null){ - newClass = convertClass(typeDecl.classDeclaration()); + for (Java17Parser.ClassOrInterfaceContext type : srcfile.classOrInterface()) { + ClassorinterfacedeclContext clsoif; + if (type instanceof NoclassorinterfaceContext) { + continue; + } else { + clsoif = (ClassorinterfacedeclContext) type; } - else{ - newClass = convertInterface(typeDecl.interfaceDeclaration()); + ClassOrInterface newClass; + int modifiers = 0; + if (!clsoif.classOrInterfaceModifier().isEmpty()) { + for (Java17Parser.ClassOrInterfaceModifierContext mod : clsoif.classOrInterfaceModifier()) { + modifiers += allmodifiers.get(mod.getText()); + } + } + fieldInitializations = new ArrayList<>(); // PL 2019-10-22: muss für jede Klasse neu initilisiert werden + if (!Objects.isNull(clsoif.classDeclaration())) { + newClass = convertClass(clsoif.classDeclaration(), modifiers); + } else if (!Objects.isNull(clsoif.interfaceDeclaration())) { + newClass = convertInterface(clsoif.interfaceDeclaration(), modifiers); + } else if (!Objects.isNull(clsoif.recordDeclaration())) { + newClass = convertRecord(clsoif.recordDeclaration(), modifiers); + } else { + throw new NotImplementedException(); } classes.add(newClass); } - return new SourceFile(this.pkgName, classes, this.imports); - } - - private String convert(Java8Parser.PackageDeclarationContext packageDeclarationContext) { - String ret = ""; - for(TerminalNode identifier : packageDeclarationContext.Identifier()){ - ret += identifier.getText()+"."; - } - ret = ret.substring(0, ret.length()-1); - return ret; - } - - public Method convert(Java8Parser.MethodDeclarationContext methodDeclarationContext, JavaClassName parentClass, RefType superClass, GenericsRegistry generics) { - Java8Parser.MethodHeaderContext header = methodDeclarationContext.methodHeader(); - int modifiers = SyntaxTreeGenerator.convert(methodDeclarationContext.methodModifier()); - GenericsRegistry localGenerics = createGenerics(methodDeclarationContext.methodHeader().typeParameters(), - parentClass, header.methodDeclarator().Identifier().getText(), reg, generics); - localGenerics.putAll(generics); - return convert(modifiers, header, methodDeclarationContext.methodBody(),parentClass, superClass, localGenerics); - } - - public Method convert(Java8Parser.InterfaceMethodDeclarationContext ctx, JavaClassName parentClass, RefType superClass, GenericsRegistry generics) { - Java8Parser.MethodHeaderContext header = ctx.methodHeader(); - int modifiers = SyntaxTreeGenerator.convertInterfaceModifier(ctx.interfaceMethodModifier()); - - GenericsRegistry localGenerics = createGenerics(header.typeParameters(), parentClass, header.methodDeclarator().Identifier().getText(), reg, generics); - localGenerics.putAll(generics); - - return convert(modifiers, header, ctx.methodBody(),parentClass, superClass, localGenerics); - } - - private Method convert(int modifiers, Java8Parser.MethodHeaderContext header, Java8Parser.MethodBodyContext body, - JavaClassName parentClass, RefType superClass, GenericsRegistry localGenerics) { - - StatementGenerator stmtGen = new StatementGenerator(reg, localGenerics, fields, new HashMap<>()); - - String name = header.methodDeclarator().Identifier().getText(); - GenericDeclarationList gtvDeclarations = new GenericDeclarationList(new ArrayList<>(), header.getStart()); - if(header.typeParameters() != null){ - gtvDeclarations = TypeGenerator.convert(header.typeParameters(), parentClass, name, reg, localGenerics); - }else{ - gtvDeclarations = new GenericDeclarationList(new ArrayList<>(), header.getStart()); - } - RefTypeOrTPHOrWildcardOrGeneric retType; - if(header.result() != null){ - if(header.result().unannType() != null){ - retType = TypeGenerator.convert(header.result().unannType(), reg, localGenerics); - } - else retType = new de.dhbwstuttgart.syntaxtree.type.Void(header.result().getStart()); - }else{ - retType = TypePlaceholder.fresh(header.getStart()); - } - ParameterList parameterList = stmtGen.convert(header.methodDeclarator().formalParameterList()); - Block block = null; - if(body.block() == null){ - if(! Modifier.isAbstract(modifiers)){ - //TODO: Error! Abstrakte Methode ohne abstrakt Keyword - } - }else{ - block = stmtGen.convert(body.block(),true); - } - if(parentClass.equals(new JavaClassName(name))){ - return new Constructor(modifiers, name, retType, parameterList, block, gtvDeclarations, header.getStart() /*, fieldInitializations geloescht PL 2018-11-24 */); - }else{ - return new Method(modifiers, name, retType, parameterList,block, gtvDeclarations, header.getStart()); + if (classes.size() > 0) { + return new SourceFile(this.pkgName, classes, this.imports); + } else { + throw new NotImplementedException("SourceFile enthält keine Klassen"); } } - private ClassOrInterface convertClass(Java8Parser.ClassDeclarationContext ctx) { - ClassOrInterface newClass; - fieldInitializations = new ArrayList<>(); //PL 2019-10-22: muss für jede Klasse neu initilisiert werden - if(ctx.normalClassDeclaration() != null){ - newClass = convertNormal(ctx.normalClassDeclaration()); - } - else{ - newClass = convertEnum(ctx.enumDeclaration()); - } - return newClass; + private String convert(Java17Parser.PackageDeclarationContext ctx) { + return convertQualifiedName(ctx.qualifiedName()); } - - private ClassOrInterface convertNormal(Java8Parser.NormalClassDeclarationContext ctx) { - int modifiers = 0; - if(ctx.classModifier() != null){ - for(Java8Parser.ClassModifierContext mod : ctx.classModifier()){ - int newModifier = convert(mod); - modifiers += newModifier; - } + + private ClassOrInterface convertClass(Java17Parser.ClassDeclarationContext ctx, int modifiers) { + String className = this.pkgName + (this.pkgName.length() > 0 ? "." : "") + ctx.identifier().getText(); + JavaClassName name = reg.getName(className); // Holt den Package Namen mit dazu + if (!name.toString().equals(className)) { // Kommt die Klasse schon in einem anderen Package vor? + throw new TypeinferenceException("Name " + className + " bereits vorhanden in " + reg.getName(className).toString(), ctx.getStart()); } - String className = this.pkgName + (this.pkgName.length()>0?".":"") + ctx.Identifier().getText(); - JavaClassName name = reg.getName(className); //Holt den Package Namen mit dazu - if(! name.toString().equals(className)){ //Kommt die Klasse schon in einem anderen Package vor? - throw new TypeinferenceException("Name " + className + " bereits vorhanden in " + reg.getName(className).toString() - ,ctx.getStart()); - } - GenericsRegistry generics = createGenerics(ctx.typeParameters(), name, "", reg, new GenericsRegistry(globalGenerics)); + GenericsRegistry generics = createGenerics(ctx.genericDeclarationList(), name, "", reg, new GenericsRegistry(globalGenerics)); Token offset = ctx.getStart(); GenericDeclarationList genericClassParameters; - if(ctx.typeParameters() == null){ - genericClassParameters = createEmptyGenericDeclarationList(ctx.Identifier()); - }else{ - genericClassParameters = TypeGenerator.convert(ctx.typeParameters(), name, "",reg, generics); + if (ctx.genericDeclarationList() == null) { + genericClassParameters = new GenericDeclarationList(new ArrayList<>(), ctx.identifier().getStop()); + } else { + genericClassParameters = TypeGenerator.convert(ctx.genericDeclarationList(), name, "", reg, generics); } - RefType superClass ; - if(ctx.superclass() != null){ - superClass = convert(ctx.superclass()); - }else{ + RefType superClass; + if (ctx.EXTENDS() != null) { + superClass = convertSuperType(ctx.typeType()); + } else { superClass = new RefType(ASTFactory.createObjectClass().getClassName(), ctx.getStart()); } - List fielddecl = convertFields(ctx.classBody(), generics); - //fieldInitializations = generateFieldInitializations(ctx.classBody(), generics); - List methodsAndConstructors = convertMethods(ctx.classBody(), name, superClass, generics); + List fielddecl = new ArrayList<>(); List methods = new ArrayList<>(); - List konstruktoren = new ArrayList<>(); - //int noOfMethods = methods.size(); - for(int i = 0; i < methodsAndConstructors.size(); i++){ - Method m = methodsAndConstructors.get(i); - if(m instanceof Constructor){ - konstruktoren.add((Constructor) m); - } - else { - methods.add(m); - } - } - if(konstruktoren.size()<1){//Standardkonstruktor anfügen: - konstruktoren.add( - generateStandardConstructor( - ctx.Identifier().getText(), name, superClass, - genericClassParameters, offset) - ); - } - + List constructors = new ArrayList<>(); Boolean isInterface = false; - List implementedInterfaces = convert(ctx.superinterfaces(), generics); - - return new ClassOrInterface(modifiers, name, fielddecl, - Optional.of(this.generatePseudoConstructor(ctx.Identifier().getText(), name, superClass, genericClassParameters, offset)), - methods, konstruktoren, genericClassParameters, superClass, - isInterface, implementedInterfaces, offset); + List implementedInterfaces = new ArrayList<>(); + List permittedSubtypes = new ArrayList<>(); + for (ClassBodyDeclarationContext clsbodydecl : ctx.classBody().classBodyDeclaration()) { + convert(clsbodydecl, fielddecl, constructors, methods, name, superClass, generics); + } + if (constructors.isEmpty()) { + constructors.add(generateStandardConstructor(ctx.identifier().getText(), name, superClass, genericClassParameters, offset)); + } + if (ctx.IMPLEMENTS() != null) { + implementedInterfaces.addAll(convert(ctx.typeList(0), generics)); + } + // Ist Bit für 'sealed'-Modifier gesetzt + if ((modifiers & 4096) != 0) { + switch (ctx.typeList().size()) { + case 1: { + permittedSubtypes.addAll(convert(ctx.typeList(0), generics)); + break; + } + case 2: { + permittedSubtypes.addAll(convert(ctx.typeList(1), generics)); + break; + } + default: { + break; + } + } + } + return new ClassOrInterface(modifiers, name, fielddecl, Optional.of(this.generatePseudoConstructor(ctx.identifier().getText(), name, superClass, genericClassParameters, offset)), methods, constructors, genericClassParameters, superClass, isInterface, implementedInterfaces, offset); } - /* - private List generateFieldInitializations(Java8Parser.ClassBodyContext classBodyContext, GenericsRegistry generics) { - List ret = new ArrayList<>(); - for(Java8Parser.ClassBodyDeclarationContext classMember : classBodyContext.classBodyDeclaration()){ - if(classMember.classMemberDeclaration() != null){ - Java8Parser.ClassMemberDeclarationContext classMemberDeclarationContext = classMember.classMemberDeclaration(); - if(classMemberDeclarationContext.fieldDeclaration() != null - && classMemberDeclarationContext.fieldDeclaration().variableDeclaratorList() != null){ - for(Java8Parser.VariableDeclaratorContext ctx : classMemberDeclarationContext.fieldDeclaration().variableDeclaratorList().variableDeclarator()) { - String fieldName = ctx.variableDeclaratorId().Identifier().getText(); - if(ctx.variableDeclaratorId().dims() != null)throw new NotImplementedException(); - Token offset = ctx.getStart(); - RefTypeOrTPHOrWildcardOrGeneric fieldType; - for(Field f : fields) - AssignToField leftSide = new AssignToField(new FieldVar(new This(offset), fieldName, )); - ret.addAll(); + private de.dhbwstuttgart.syntaxtree.Record convertRecord(RecordDeclarationContext recordDeclaration, int modifiers) { + String identifier = recordDeclaration.identifier().getText(); + String className = this.pkgName + (this.pkgName.length() > 0 ? "." : "") + identifier; + JavaClassName name = reg.getName(className); // Holt den Package Namen mit dazu + Token offset = recordDeclaration.getStart(); + GenericsRegistry generics = createGenerics(recordDeclaration.genericDeclarationList(), name, "", reg, new GenericsRegistry(globalGenerics)); + if (!name.toString().equals(className)) { // Kommt die Klasse schon in einem anderen Package vor? + throw new TypeinferenceException("Name " + className + " bereits vorhanden in " + reg.getName(className).toString(), recordDeclaration.getStart()); + } + GenericDeclarationList genericClassParameters; + if (recordDeclaration.genericDeclarationList() == null) { + genericClassParameters = new GenericDeclarationList(new ArrayList<>(), recordDeclaration.identifier().getStop()); + } else { + genericClassParameters = TypeGenerator.convert(recordDeclaration.genericDeclarationList(), name, "", reg, generics); + } + RefType superClass = new RefType(ASTFactory.createObjectClass().getClassName(), offset); + List fielddecl = new ArrayList<>(); + List methods = new ArrayList<>(); + List constructors = new ArrayList<>(); + Boolean isInterface = false; + List implementedInterfaces = new ArrayList<>(); + List constructorParameters = new ArrayList<>(); + List constructorStatements = new ArrayList<>(); + for (RecordComponentContext component : recordDeclaration.recordHeader().recordComponentList().recordComponent()) { + int fieldmodifiers = allmodifiers.get("private") + allmodifiers.get("final"); + String fieldname = component.identifier().getText(); + Token fieldoffset = component.getStart(); + RefTypeOrTPHOrWildcardOrGeneric fieldtype = null; + if (Objects.isNull(component.typeType())) { + fieldtype = TypePlaceholder.fresh(offset); + } else { + fieldtype = TypeGenerator.convert(component.typeType(), reg, generics); + } + fielddecl.add(new Field(fieldname, fieldtype, fieldmodifiers, fieldoffset)); + constructorParameters.add(new FormalParameter(fieldname, fieldtype, fieldoffset)); + FieldVar fieldvar = new FieldVar(new This(offset), fieldname, fieldtype, fieldoffset); + constructorStatements.add(new Assign(new AssignToField(fieldvar), new LocalVar(fieldname, fieldtype, fieldoffset), offset)); + Statement returnStatement = new Return(fieldvar, offset); + methods.add(new Method(allmodifiers.get("public"), fieldname, fieldtype, new ParameterList(new ArrayList<>(), offset), new Block(Arrays.asList(returnStatement), offset), new GenericDeclarationList(new ArrayList<>(), offset), offset)); + } + RefType classType = ClassOrInterface.generateTypeOfClass(reg.getName(className), genericClassParameters, offset); + Constructor implicitConstructor = new Constructor(allmodifiers.get("public"), identifier, classType, new ParameterList(constructorParameters, offset), new Block(constructorStatements, offset), genericClassParameters, offset); + Optional initializations = Optional.of(implicitConstructor); + constructors.add(implicitConstructor); + for (ClassBodyDeclarationContext bodyDeclaration : recordDeclaration.recordBody().classBodyDeclaration()) { + convert(bodyDeclaration, fielddecl, constructors, methods, name, superClass, generics); + } + if (!Objects.isNull(recordDeclaration.IMPLEMENTS())) { + implementedInterfaces.addAll(convert(recordDeclaration.typeList(), generics)); + } + return new Record(modifiers, name, fielddecl, initializations, methods, constructors, genericClassParameters, superClass, isInterface, implementedInterfaces, offset); + } + + private void convert(ClassBodyDeclarationContext classBody, List fields, List constructors, List methods, JavaClassName name, RefType superClass, GenericsRegistry generics) { + MemberdeclContext member; + // Statement-Blöcke und "leere Zeilen" (;) werden noch nicht berücksichtigt + if (classBody instanceof MemberdeclContext) { + member = (MemberdeclContext) classBody; + Integer membermodifiers = 0; + for (ModifierContext mod : member.modifier()) { + membermodifiers += allmodifiers.get(mod.getText()); + } + switch (member.memberDeclaration()) { + case MemberclassorinterfaceContext memberclsoif: { + break; + } + case MemberfieldContext memberfield: { + fields.addAll(convert(memberfield.fieldDeclaration(), membermodifiers, generics)); + break; + } + case MembermethodContext membermethod: { + Method convertedMethod = convert(membermodifiers, membermethod.method(), name, superClass, generics); + if (convertedMethod instanceof Constructor constructor) { + constructors.add(constructor); + } else { + methods.add(convertedMethod); + } + break; + } + case MemberconstructorContext memberconstructor: { + constructors.add(convert(membermodifiers, memberconstructor.constructor(), name, superClass, generics)); + break; + } + default: + break; + } + } + } + + private ClassOrInterface convertInterface(Java17Parser.InterfaceDeclarationContext ctx, int modifiers) { + String className = this.pkgName.length() > 0 ? this.pkgName + "." : "" + ctx.identifier().getText(); + JavaClassName name = reg.getName(className); // Holt den Package Namen mit dazu + if (!name.toString().equals(className)) { // Kommt die Klasse schon in einem anderen Package vor? + throw new TypeinferenceException("Name " + className + " bereits vorhanden in " + reg.getName(className).toString(), ctx.getStart()); + } + if (!Modifier.isInterface(modifiers)) + modifiers += Modifier.INTERFACE; + + GenericsRegistry generics = createGenerics(ctx.genericDeclarationList(), name, "", reg, new GenericsRegistry(globalGenerics)); + + GenericDeclarationList genericParams; + if (!Objects.isNull(ctx.genericDeclarationList())) { + genericParams = TypeGenerator.convert(ctx.genericDeclarationList(), name, "", reg, generics); + } else { + genericParams = createEmptyGenericDeclarationList(ctx.identifier().getStart()); + } + RefType superClass = ASTFactory.createObjectType(); + + List fields = new ArrayList<>(); + List methods = new ArrayList<>(); + for (InterfaceBodyDeclarationContext interfacebody : ctx.interfaceBody().interfaceBodyDeclaration()) { + if (interfacebody instanceof Java17Parser.EmptyinterfaceContext) { + continue; + } else { + InterfacememberContext interfacemember = (InterfacememberContext) interfacebody; + int membermodifiers = 0; + for (ModifierContext mod : interfacemember.modifier()) { + membermodifiers += allmodifiers.get(mod.getText()); + } + int methodmodifiers = membermodifiers; + switch (interfacemember.interfaceMemberDeclaration()) { + case InterfaceconstContext constant: + fields.add(convert(constant)); + break; + case InterfacemethodContext method: + InterfaceMethodDeclarationContext declaration = method.interfaceMethodDeclaration(); + for (InterfaceMethodModifierContext mod : declaration.interfaceMethodModifier()) { + methodmodifiers += allmodifiers.get(mod.getText()); } - }else if(classMemberDeclarationContext.methodDeclaration()!= null){ - //Do nothing! + InterfaceCommonBodyDeclarationContext commonbody = declaration.interfaceCommonBodyDeclaration(); + methods.add(convert(methodmodifiers, commonbody, new GenericDeclarationList(new ArrayList<>(), commonbody.getStart()), generics)); + break; + case GenericinterfacemethodContext genericmethod: + GenericInterfaceMethodDeclarationContext genericdeclaration = genericmethod.genericInterfaceMethodDeclaration(); + int genericmethodmodifiers = 0; + for (InterfaceMethodModifierContext mod : genericdeclaration.interfaceMethodModifier()) { + genericmethodmodifiers += allmodifiers.get(mod.getText()); + } + commonbody = genericdeclaration.interfaceCommonBodyDeclaration(); + GenericDeclarationList gtv = TypeGenerator.convert(genericdeclaration.genericDeclarationList(), name, commonbody.identifier().getText(), reg, generics); + methods.add(convert(genericmethodmodifiers, commonbody, gtv, generics)); + break; + default: + throw new NotImplementedException(); } } } - return ret; - } -*/ - - private List convert(Java8Parser.SuperinterfacesContext ctx, GenericsRegistry generics) { - if(ctx == null)return new ArrayList<>(); - return convert(ctx.interfaceTypeList(), generics); - } - - private List convert(Java8Parser.InterfaceTypeListContext ctx, GenericsRegistry generics) { - List ret = new ArrayList<>(); - for(Java8Parser.InterfaceTypeContext interfaceType : ctx.interfaceType()){ - ret.add((RefType) TypeGenerator.convert(interfaceType.classType(), reg, generics)); + List extendedInterfaces = new ArrayList<>(); + if (!Objects.isNull(ctx.EXTENDS())) { + extendedInterfaces.addAll(convert(ctx.typeList(0), generics)); } - return ret; + return new ClassOrInterface(modifiers, name, fields, Optional.empty(), methods, new ArrayList<>(), genericParams, superClass, true, extendedInterfaces, ctx.getStart()); + } + + private GenericDeclarationList createEmptyGenericDeclarationList(Token classNameIdentifier) { + CommonToken gtvOffset = new CommonToken(classNameIdentifier); + gtvOffset.setCharPositionInLine(gtvOffset.getCharPositionInLine() + classNameIdentifier.getText().length()); + gtvOffset.setStartIndex(gtvOffset.getStopIndex() + 1); + return new GenericDeclarationList(new ArrayList<>(), gtvOffset); + } + + private Field convert(InterfaceconstContext constant) { + // TODO: Erstelle hier ein Feld! + throw new NotImplementedException(); + } + + private Method convert(int modifiers, InterfaceCommonBodyDeclarationContext bodydeclaration, GenericDeclarationList gtvDeclarations, GenericsRegistry generics) { + String name = bodydeclaration.identifier().getText(); + + RefTypeOrTPHOrWildcardOrGeneric retType; + if (Objects.isNull(bodydeclaration.refType())) { + retType = TypePlaceholder.fresh(bodydeclaration.getStart()); + } else { + if (bodydeclaration.refType() instanceof ReftypeContext reftype) { + retType = TypeGenerator.convert(reftype.typeType(), reg, generics); + } else { + retType = new Void(bodydeclaration.refType().getStart()); + } + } + StatementGenerator stmtgen = new StatementGenerator(reg, generics, fields, new HashMap<>()); + ParameterList paramlist = stmtgen.convert(bodydeclaration.formalParameters().formalParameterList()); + MethodBodyContext body = bodydeclaration.methodBody(); + Block block = null; + if (!(body instanceof EmptymethodContext)) { + MethodblockContext methodblock = (MethodblockContext) body; + block = stmtgen.convert(methodblock.block(), true); + } + return new Method(modifiers, name, retType, paramlist, block, gtvDeclarations, bodydeclaration.getStart()); } /** * http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.8.9 */ - private Constructor generateStandardConstructor(String className, JavaClassName parentClass, RefType superClass, GenericDeclarationList classGenerics, Token offset){ + private Constructor generateStandardConstructor(String className, JavaClassName parentClass, RefType superClass, GenericDeclarationList classGenerics, Token offset) { RefType classType = ClassOrInterface.generateTypeOfClass(reg.getName(className), classGenerics, offset); ParameterList params = new ParameterList(new ArrayList<>(), offset); Block block = new Block(new ArrayList<>(), offset); - return new Constructor(Modifier.PUBLIC, className, classType, params, block, classGenerics, offset /*, fieldInitializations geloescht PL 2018-11-24 */); + // + // + return new Constructor(Modifier.PUBLIC, className, classType, params, block, classGenerics, offset); // fieldInitializations + // geloescht PL + // 2018-11-24 } - - /* fieldInitializations werden in einem Psedokonstruktor in der abstrakten Syntax gespeichert */ - private Constructor generatePseudoConstructor(String className, JavaClassName parentClass, RefType superClass, GenericDeclarationList classGenerics, Token offset){ - RefType classType = ClassOrInterface.generateTypeOfClass(reg.getName(className), classGenerics, offset); - ParameterList params = new ParameterList(new ArrayList<>(), offset); - Block block = new Block(new ArrayList<>(fieldInitializations), offset); - return new Constructor(Modifier.PUBLIC, className, classType, params, block, classGenerics, offset /*, fieldInitializations geloescht PL 2018-11-24 */); - } - private RefType convert(Java8Parser.SuperclassContext superclass) { - if(superclass.classType().classOrInterfaceType() != null){ + /* + * fieldInitializations werden in einem Psedokonstruktor in der abstrakten Syntax gespeichert + */ + private Constructor generatePseudoConstructor(String className, JavaClassName parentClass, RefType superClass, GenericDeclarationList classGenerics, Token offset) { + RefType classType = ClassOrInterface.generateTypeOfClass(reg.getName(className), classGenerics, offset); + ParameterList params = new ParameterList(new ArrayList<>(), offset); + Block block = new Block(new ArrayList<>(fieldInitializations), offset); + return new Constructor(Modifier.PUBLIC, className, classType, params, block, classGenerics, offset /* + * fieldInitializations geloescht PL 2018-11-24 + */); + } + + private RefType convertSuperType(Java17Parser.TypeTypeContext typeType) { + ClassOrInterfaceTypeContext supertypecontext = typeType.classOrInterfaceType(); + if (supertypecontext != null && supertypecontext.DOT().size() > 0) { throw new NotImplementedException(); - }else{ - RefTypeOrTPHOrWildcardOrGeneric ret = TypeGenerator.convertTypeName(superclass.classType().Identifier().getText(), superclass.classType().typeArguments(), - superclass.getStart(), reg, globalGenerics); - if(ret instanceof RefType){ + } else { + TypeArgumentsContext typeArguments = (typeType.classOrInterfaceType().typeArguments().size() > 0) ? typeType.classOrInterfaceType().typeArguments().get(typeType.classOrInterfaceType().typeArguments().size() - 1) : null; + RefTypeOrTPHOrWildcardOrGeneric ret = TypeGenerator.convertTypeName(typeType.classOrInterfaceType().typeIdentifier().getText(), typeArguments, typeType.getStart(), reg, globalGenerics); + if (ret instanceof RefType) { return (RefType) ret; - }else{ - throw new TypeinferenceException(superclass.getText() + " ist kein gültiger Supertyp", superclass.getStart()); + } else { + throw new TypeinferenceException(typeType.getText() + " ist kein gültiger Supertyp", typeType.getStart()); } } } - private List convertMethods(Java8Parser.ClassBodyContext classBodyContext, - JavaClassName parentClass, RefType superClass, GenericsRegistry generics) { - List ret = new ArrayList<>(); - for(Java8Parser.ClassBodyDeclarationContext classMember : classBodyContext.classBodyDeclaration()){ - if(classMember.classMemberDeclaration() != null){ - Java8Parser.ClassMemberDeclarationContext classMemberDeclarationContext = classMember.classMemberDeclaration(); - if(classMemberDeclarationContext.fieldDeclaration() != null){ - //Do nothing! - }else if(classMemberDeclarationContext.methodDeclaration()!= null){ - - ret.add(this.convert(classMemberDeclarationContext.methodDeclaration(), parentClass, superClass, generics)); - } - } + private List convert(Java17Parser.TypeListContext ctx, GenericsRegistry generics) { + List ret = new ArrayList<>(); + for (Java17Parser.TypeTypeContext type : ctx.typeType()) { + ret.add((RefType) TypeGenerator.convert(type, reg, generics)); } return ret; } - private List convertFields(Java8Parser.ClassBodyContext classBodyContext, GenericsRegistry generics) { + public Method convert(int modifiers, Java17Parser.MethodContext methodContext, JavaClassName parentClass, RefType superClass, GenericsRegistry generics) { + GenericsRegistry localgenerics = generics; + MethodDeclarationContext methoddeclaration; + GenericDeclarationListContext genericdeclarations; + GenericDeclarationList gtvDeclarations; + MethodHeaderContext header; + String name; + if (methodContext instanceof GenericmethodContext) { + GenericmethodContext gmc = (GenericmethodContext) methodContext; + genericdeclarations = gmc.genericMethodDeclaration().genericDeclarationList(); + methoddeclaration = gmc.genericMethodDeclaration().methodDeclaration(); + header = methoddeclaration.methodHeader(); + name = header.identifier().getText(); + localgenerics.putAll(createGenerics(genericdeclarations, parentClass, name, reg, generics)); + gtvDeclarations = TypeGenerator.convert(genericdeclarations, parentClass, name, reg, localgenerics); + } else { + MethoddeclContext mdc = (MethoddeclContext) methodContext; + methoddeclaration = mdc.methodDeclaration(); + header = methoddeclaration.methodHeader(); + gtvDeclarations = new GenericDeclarationList(new ArrayList<>(), header.getStart()); + name = header.identifier().getText(); + } + + RefTypeOrTPHOrWildcardOrGeneric retType; + if (Objects.isNull(header.refType())) { + retType = TypePlaceholder.fresh(header.getStart()); + } else { + if (header.refType() instanceof ReftypeContext reftype) { + retType = TypeGenerator.convert(reftype.typeType(), reg, generics); + } else { + retType = new Void(header.refType().getStart()); + } + } + StatementGenerator stmtgen = new StatementGenerator(reg, localgenerics, fields, new HashMap<>()); + ParameterList paramlist = stmtgen.convert(header.formalParameters().formalParameterList()); + MethodBodyContext body = methoddeclaration.methodBody(); + Block block = null; + if (body instanceof EmptymethodContext emptymethod) { + if (!Modifier.isAbstract(modifiers)) { + // TODO: Error! Abstrakte Methode ohne abstrakt Keyword + } + } else { + MethodblockContext methodblock = (MethodblockContext) body; + block = stmtgen.convert(methodblock.block(), true); + } + if (name.equals(parentClass.getClassName())) { + return new Constructor(modifiers, name, retType, paramlist, block, gtvDeclarations, methoddeclaration.getStart()); + } else { + return new Method(modifiers, name, retType, paramlist, block, gtvDeclarations, methoddeclaration.getStart()); + } + } + + public Constructor convert(int modifiers, Java17Parser.ConstructorContext constructorContext, JavaClassName parentClass, RefType superClass, GenericsRegistry generics) { + GenericsRegistry localgenerics = generics; + GenericDeclarationListContext genericdeclarations; + GenericDeclarationList gtvDeclarations; + ConstructorDeclarationContext constructordeclaration; + String name; + if (constructorContext instanceof GenericconstructorContext) { + GenericconstructorContext genericconstructor = (GenericconstructorContext) constructorContext; + GenericConstructorDeclarationContext gcdeclaration = genericconstructor.genericConstructorDeclaration(); + name = gcdeclaration.constructorDeclaration().identifier().getText(); + genericdeclarations = gcdeclaration.genericDeclarationList(); + constructordeclaration = gcdeclaration.constructorDeclaration(); + localgenerics.putAll(createGenerics(genericdeclarations, parentClass, name, reg, generics)); + gtvDeclarations = TypeGenerator.convert(genericdeclarations, parentClass, name, reg, localgenerics); + } else { + ConstructordeclContext constructordeclarationcontext = (ConstructordeclContext) constructorContext; + constructordeclaration = constructordeclarationcontext.constructorDeclaration(); + name = constructordeclaration.identifier().getText(); + gtvDeclarations = new GenericDeclarationList(new ArrayList<>(), constructordeclaration.getStart()); + } + RefTypeOrTPHOrWildcardOrGeneric retType = TypeGenerator.convertTypeName(name, constructordeclaration.getStart(), reg, localgenerics); + StatementGenerator stmtgen = new StatementGenerator(reg, localgenerics, fields, new HashMap<>()); + ParameterList paramlist = stmtgen.convert(constructordeclaration.formalParameters().formalParameterList()); + Block block = stmtgen.convert(constructordeclaration.constructorBody, true); + return new Constructor(modifiers, name, retType, paramlist, block, gtvDeclarations, constructordeclaration.getStart()); + } + + private List convert(Java17Parser.FieldDeclarationContext fieldDeclContext, int modifiers, GenericsRegistry generics) { List ret = new ArrayList<>(); - for(Java8Parser.ClassBodyDeclarationContext classMember : classBodyContext.classBodyDeclaration()){ - if(classMember.classMemberDeclaration() != null){ - Java8Parser.ClassMemberDeclarationContext classMemberDeclarationContext = classMember.classMemberDeclaration(); - if(classMemberDeclarationContext.fieldDeclaration() != null){ - ret.addAll(convert(classMember.classMemberDeclaration().fieldDeclaration(), generics)); - }else if(classMemberDeclarationContext.methodDeclaration()!= null){ - //Do nothing! - } - } - } - return ret; - } - - public static int convert(List methodModifierContexts) { - int ret = 0; - for(Java8Parser.MethodModifierContext mod : methodModifierContexts){ - if(mod.annotation() == null)convertModifier(mod.getText()); - } - return ret; - } - - public static int convertInterfaceModifier(List methodModifierContexts) { - int ret = 0; - for(Java8Parser.InterfaceMethodModifierContext mod : methodModifierContexts){ - if(mod.annotation() == null)convertModifier(mod.getText()); - } - return ret; - } - - private List convert(Java8Parser.FieldDeclarationContext fieldDeclarationContext, GenericsRegistry generics) { - List ret = new ArrayList<>(); - int modifiers = 0; - for(Java8Parser.FieldModifierContext fieldModifierContext : fieldDeclarationContext.fieldModifier()){ - modifiers+=(convert(fieldModifierContext)); - } RefTypeOrTPHOrWildcardOrGeneric fieldType; - if(fieldDeclarationContext.unannTypeOrAuto() != null - && fieldDeclarationContext.unannTypeOrAuto().unannType() != null){ - fieldType = TypeGenerator.convert(fieldDeclarationContext.unannTypeOrAuto().unannType(), reg, generics); - }else{ - fieldType = TypePlaceholder.fresh(fieldDeclarationContext.variableDeclaratorList().getStart()); //PL 2019-12-06: variableDeclaratorList() eingefuegt, um als Token nicht die Modifier zu bekommen + if (fieldDeclContext.typeType() != null) { + fieldType = TypeGenerator.convert(fieldDeclContext.typeType(), reg, generics); + } else { + // PL 2019-12-06: variableDeclaratorList() eingefuegt, um als Token nicht die + // Modifier zu bekommen + fieldType = TypePlaceholder.fresh(fieldDeclContext.variableDeclarators().getStart()); } - for(Java8Parser.VariableDeclaratorContext varCtx : fieldDeclarationContext.variableDeclaratorList().variableDeclarator()){ - String fieldName = convert(varCtx.variableDeclaratorId()); - fields.put(fieldName, fieldType); - if(varCtx.variableInitializer() != null){ - initializeField(varCtx, fieldType, generics); + for (Java17Parser.VariableDeclaratorContext varDecl : fieldDeclContext.variableDeclarators().variableDeclarator()) { + String fieldName = varDecl.variableDeclaratorId().getText(); + this.fields.put(fieldName, fieldType); + if (varDecl.variableInitializer() != null) { + initializeField(varDecl, fieldType, generics); } - ret.add(new Field(fieldName,fieldType,modifiers,varCtx.getStart())); + ret.add(new Field(fieldName, fieldType, modifiers, varDecl.getStart())); } return ret; } - public static String convert(Java8Parser.VariableDeclaratorIdContext variableDeclaratorIdContext) { + public static String convert(Java17Parser.VariableDeclaratorIdContext variableDeclaratorIdContext) { return variableDeclaratorIdContext.getText(); } // Initialize a field by creating implicit constructor. - private void initializeField(Java8Parser.VariableDeclaratorContext ctx, RefTypeOrTPHOrWildcardOrGeneric typeOfField, GenericsRegistry generics){ + private void initializeField(Java17Parser.VariableDeclaratorContext ctx, RefTypeOrTPHOrWildcardOrGeneric typeOfField, GenericsRegistry generics) { StatementGenerator statementGenerator = new StatementGenerator(reg, generics, fields, new HashMap<>()); fieldInitializations.add(statementGenerator.generateFieldAssignment(ctx, typeOfField)); } - public static int convertModifier(String modifier){ - HashMap modifiers = new HashMap<>(); - modifiers.put(Modifier.toString(Modifier.PUBLIC), Modifier.PUBLIC); - modifiers.put(Modifier.toString(Modifier.PRIVATE), Modifier.PRIVATE); - modifiers.put(Modifier.toString(Modifier.PROTECTED), Modifier.PROTECTED); - modifiers.put(Modifier.toString(Modifier.ABSTRACT), Modifier.ABSTRACT); - modifiers.put(Modifier.toString(Modifier.STATIC), Modifier.STATIC); - modifiers.put(Modifier.toString(Modifier.STRICT), Modifier.STRICT); - modifiers.put(Modifier.toString(Modifier.FINAL), Modifier.FINAL); - modifiers.put(Modifier.toString(Modifier.TRANSIENT), Modifier.TRANSIENT); - modifiers.put(Modifier.toString(Modifier.VOLATILE), Modifier.VOLATILE); - modifiers.put(Modifier.toString(Modifier.SYNCHRONIZED), Modifier.SYNCHRONIZED); - modifiers.put(Modifier.toString(Modifier.NATIVE), Modifier.NATIVE); - modifiers.put(Modifier.toString(Modifier.INTERFACE), Modifier.INTERFACE); - int ret = 0; - for(String m : modifiers.keySet()){ - if(modifier.contains(m))ret+=modifiers.get(m); - } - return ret; + public int convertModifier(String modifier) { + return allmodifiers.get(modifier); } - private int convert(Java8Parser.ClassModifierContext ctx){ - if(ctx.annotation() != null)return 0; - return convertModifier(ctx.getText()); - } - - private int convert(Java8Parser.FieldModifierContext ctx){ - if(ctx.annotation() != null)return 0; - return convertModifier(ctx.getText()); - } - - private int convert(Java8Parser.InterfaceModifierContext ctx) { - if(ctx.annotation() != null)return 0; - return convertModifier(ctx.getText()); - } - - private ClassOrInterface convertEnum(Java8Parser.EnumDeclarationContext ctx){ - return null; - } - - private ClassOrInterface convertInterface(Java8Parser.InterfaceDeclarationContext ctx){ - if(ctx.normalInterfaceDeclaration() != null){ - return convertNormal(ctx.normalInterfaceDeclaration()); - }else{ - throw new NotImplementedException(); - } - } - - private ClassOrInterface convertNormal(Java8Parser.NormalInterfaceDeclarationContext ctx) { - int modifiers = 0; - if(ctx.interfaceModifier() != null){ - for( Java8Parser.InterfaceModifierContext mod : ctx.interfaceModifier()){ - int newModifier = convert(mod); - modifiers += newModifier; - } - } - if(!Modifier.isInterface(modifiers))modifiers += Modifier.INTERFACE; - - JavaClassName name = reg.getName(ctx.Identifier().getText()); - - GenericsRegistry generics = createGenerics(ctx.typeParameters(), name, "", reg, new GenericsRegistry(globalGenerics)); - - GenericDeclarationList genericParams; - if(ctx.typeParameters() != null){ - genericParams = TypeGenerator.convert(ctx.typeParameters(), name, "",reg, generics); - }else{ - genericParams = createEmptyGenericDeclarationList(ctx.Identifier()); - } - RefType superClass = ASTFactory.createObjectType(); - - List fields = convertFields(ctx.interfaceBody()); - List methods = convertMethods(ctx.interfaceBody(), name, superClass, generics); - - List extendedInterfaces = convert(ctx.extendsInterfaces(), generics); - - return new ClassOrInterface(modifiers, name, fields, Optional.empty(), methods, new ArrayList<>(), - genericParams, superClass, true, extendedInterfaces, ctx.getStart()); - } - - private GenericDeclarationList createEmptyGenericDeclarationList(TerminalNode classNameIdentifier) { - CommonToken gtvOffset = new CommonToken(classNameIdentifier.getSymbol()); - gtvOffset.setCharPositionInLine(gtvOffset.getCharPositionInLine()+classNameIdentifier.getText().length()); - gtvOffset.setStartIndex(gtvOffset.getStopIndex()+1); - return new GenericDeclarationList(new ArrayList<>(), gtvOffset); - } - - private GenericsRegistry createGenerics(Java8Parser.TypeParametersContext ctx, JavaClassName parentClass, String parentMethod, JavaClassRegistry reg, GenericsRegistry generics) { + private GenericsRegistry createGenerics(Java17Parser.GenericDeclarationListContext ctx, JavaClassName parentClass, String parentMethod, JavaClassRegistry reg, GenericsRegistry generics) { GenericsRegistry ret = new GenericsRegistry(this.globalGenerics); ret.putAll(generics); - if(ctx == null || ctx.typeParameterList() == null)return ret; - for(Java8Parser.TypeParameterContext tp : ctx.typeParameterList().typeParameter()){ - ret.put(tp.Identifier().getText(), new GenericContext(parentClass, parentMethod)); - } - for(Java8Parser.TypeParameterContext tp : ctx.typeParameterList().typeParameter()){ + if (ctx == null) + return ret; + for (Java17Parser.GenericTypeVarContext tp : ctx.genericTypeVar()) { + ret.put(tp.identifier().getText(), new GenericContext(parentClass, parentMethod)); TypeGenerator.convert(tp, parentClass, parentMethod, reg, ret); } return ret; } - - private List convert(Java8Parser.ExtendsInterfacesContext extendsInterfacesContext, GenericsRegistry generics) { - if(extendsInterfacesContext == null)return new ArrayList<>(); - return convert(extendsInterfacesContext.interfaceTypeList(), generics); - } - - private List convertMethods(Java8Parser.InterfaceBodyContext interfaceBodyContext, - JavaClassName parentClass, RefType superClass, GenericsRegistry generics) { - List ret = new ArrayList<>(); - for(Java8Parser.InterfaceMemberDeclarationContext member : interfaceBodyContext.interfaceMemberDeclaration()){ - if(member.interfaceMethodDeclaration() != null){ - ret.add(this.convert(member.interfaceMethodDeclaration(), parentClass, superClass, generics)); - //new Method(name, type, modifier, params, null, genericDecls, member.interfaceMethodDeclaration().getStart()); - }else{ - throw new NotImplementedException(); - } - } - return ret; - } - - private List convertFields(Java8Parser.InterfaceBodyContext interfaceBodyContext) { - List ret = new ArrayList<>(); - for(Java8Parser.InterfaceMemberDeclarationContext member : interfaceBodyContext.interfaceMemberDeclaration()){ - if(member.constantDeclaration() != null){ - //TODO: Erstelle hier ein Feld! - throw new NotImplementedException(); - } - } - return ret; - } - - } diff --git a/src/main/java/de/dhbwstuttgart/parser/SyntaxTreeGenerator/TypeGenerator.java b/src/main/java/de/dhbwstuttgart/parser/SyntaxTreeGenerator/TypeGenerator.java index c30dad85..1e704d75 100644 --- a/src/main/java/de/dhbwstuttgart/parser/SyntaxTreeGenerator/TypeGenerator.java +++ b/src/main/java/de/dhbwstuttgart/parser/SyntaxTreeGenerator/TypeGenerator.java @@ -2,9 +2,11 @@ package de.dhbwstuttgart.parser.SyntaxTreeGenerator; import de.dhbwstuttgart.exceptions.NotImplementedException; import de.dhbwstuttgart.exceptions.TypeinferenceException; -import de.dhbwstuttgart.parser.NullToken; -import de.dhbwstuttgart.parser.antlr.Java8Parser; -import de.dhbwstuttgart.parser.antlr.Java8Parser.UnannClassType_lfno_unannClassOrInterfaceTypeContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser; +import de.dhbwstuttgart.parser.antlr.Java17Parser.IdentifierContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.TypeArgumentsContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.TypeTypeContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.WildcardTypeContext; import de.dhbwstuttgart.parser.scope.GenericsRegistry; import de.dhbwstuttgart.parser.scope.JavaClassName; import de.dhbwstuttgart.parser.scope.JavaClassRegistry; @@ -21,203 +23,182 @@ import org.antlr.v4.runtime.Token; import java.util.ArrayList; import java.util.List; +import java.util.Objects; import java.util.regex.Matcher; import java.util.regex.Pattern; public class TypeGenerator { - public static RefTypeOrTPHOrWildcardOrGeneric convert(Java8Parser.UnannClassOrInterfaceTypeContext unannClassOrInterfaceTypeContext, JavaClassRegistry reg, GenericsRegistry generics) { - Java8Parser.TypeArgumentsContext arguments=null; - /* PL 2019-03-19 auskommentiert ANFANG - if(unannClassOrInterfaceTypeContext.unannClassType_lfno_unannClassOrInterfaceType() != null){ - arguments = unannClassOrInterfaceTypeContext.unannClassType_lfno_unannClassOrInterfaceType().typeArguments(); - }else{// if(unannClassOrInterfaceTypeContext.unannInterfaceType_lfno_unannClassOrInterfaceType() != null){ - arguments = unannClassOrInterfaceTypeContext.unannInterfaceType_lfno_unannClassOrInterfaceType().unannClassType_lfno_unannClassOrInterfaceType().typeArguments(); - } - PL 2019-03-19 auskommentiert ENDE */ - /** - * Problem sind hier die verschachtelten Typen mit verschachtelten Typargumenten - * Beispiel: Typ.InnererTyp + public static RefTypeOrTPHOrWildcardOrGeneric convert(Java17Parser.ClassOrInterfaceTypeContext classOrInterfaceTypeContext, JavaClassRegistry reg, GenericsRegistry generics) { + Java17Parser.TypeArgumentsContext arguments = null; + /* + * PL 2019-03-19 auskommentiert ANFANG if(unannClassOrInterfaceTypeContext. unannClassType_lfno_unannClassOrInterfaceType() != null){ arguments = unannClassOrInterfaceTypeContext. unannClassType_lfno_unannClassOrInterfaceType().typeArguments(); }else{// if(unannClassOrInterfaceTypeContext. unannInterfaceType_lfno_unannClassOrInterfaceType() != null){ arguments = unannClassOrInterfaceTypeContext. unannInterfaceType_lfno_unannClassOrInterfaceType(). + * unannClassType_lfno_unannClassOrInterfaceType().typeArguments(); } PL 2019-03-19 auskommentiert ENDE */ - String name = unannClassOrInterfaceTypeContext.getText(); - if(name.contains("<")){ - name = name.split("<")[0]; //Der Typ ist alles vor den ersten Argumenten - /* Fuer Debug-Zwecke - unannClassOrInterfaceTypeContext.unannInterfaceType_lfno_unannClassOrInterfaceType(); - unannClassOrInterfaceTypeContext.unannClassType_lfno_unannClassOrInterfaceType().getText(); - //unannClassOrInterfaceTypeContext.unannInterfaceType_lfno_unannClassOrInterfaceType().unannClassType_lfno_unannClassOrInterfaceType().typeArguments(); - //UnannClassType_lfno_unannClassOrInterfaceTypeContext - unannClassOrInterfaceTypeContext.unannClassType_lf_unannClassOrInterfaceType(0); - unannClassOrInterfaceTypeContext.unannClassType_lf_unannClassOrInterfaceType(0).getText(); - unannClassOrInterfaceTypeContext.unannClassType_lf_unannClassOrInterfaceType(1); - unannClassOrInterfaceTypeContext.unannClassType_lf_unannClassOrInterfaceType(1).getText(); - unannClassOrInterfaceTypeContext.unannClassType_lfno_unannClassOrInterfaceType().getText(); - //unannClassOrInterfaceTypeContext.unannInterfaceType_lf_unannClassOrInterfaceType(); - //unannClassOrInterfaceTypeContext.unannInterfaceType_lf_unannClassOrInterfaceType(0).getText(); - //unannClassOrInterfaceTypeContext.unannInterfaceType_lf_unannClassOrInterfaceType(1).getText(); - //unannClassOrInterfaceTypeContext.unannInterfaceType_lfno_unannClassOrInterfaceType().getText(); - */ - int lastElement = new ArrayList<>(unannClassOrInterfaceTypeContext.unannClassType_lf_unannClassOrInterfaceType()).size()-1; - if (lastElement >=0) {//qualifizierter Name z.B.: java.util.Vector - arguments = unannClassOrInterfaceTypeContext.unannClassType_lf_unannClassOrInterfaceType(lastElement).typeArguments(); - } - else { //unqualifizierter Name z.B.: Vector - arguments = unannClassOrInterfaceTypeContext.unannClassType_lfno_unannClassOrInterfaceType().typeArguments(); - } + /** + * Problem sind hier die verschachtelten Typen mit verschachtelten Typargumenten Beispiel: Typ.InnererTyp + */ + if (classOrInterfaceTypeContext.typeArguments().size() > 1) + throw new NotImplementedException(); + + String name = ""; + for (IdentifierContext id : classOrInterfaceTypeContext.identifier()) { + name += id.getText() + '.'; } - return convertTypeName(name, arguments, unannClassOrInterfaceTypeContext.getStart(), reg, generics); + name += classOrInterfaceTypeContext.typeIdentifier().getText(); + if (classOrInterfaceTypeContext.getStop().getText().equals(">")) { + /* + * Fuer Debug-Zwecke unannClassOrInterfaceTypeContext. unannInterfaceType_lfno_unannClassOrInterfaceType(); unannClassOrInterfaceTypeContext. unannClassType_lfno_unannClassOrInterfaceType().getText(); //unannClassOrInterfaceTypeContext. unannInterfaceType_lfno_unannClassOrInterfaceType(). unannClassType_lfno_unannClassOrInterfaceType().typeArguments(); //UnannClassType_lfno_unannClassOrInterfaceTypeContext unannClassOrInterfaceTypeContext.unannClassType_lf_unannClassOrInterfaceType( 0); + * unannClassOrInterfaceTypeContext.unannClassType_lf_unannClassOrInterfaceType( 0).getText(); unannClassOrInterfaceTypeContext.unannClassType_lf_unannClassOrInterfaceType( 1); unannClassOrInterfaceTypeContext.unannClassType_lf_unannClassOrInterfaceType( 1).getText(); unannClassOrInterfaceTypeContext. unannClassType_lfno_unannClassOrInterfaceType().getText(); //unannClassOrInterfaceTypeContext. unannInterfaceType_lf_unannClassOrInterfaceType(); //unannClassOrInterfaceTypeContext. + * unannInterfaceType_lf_unannClassOrInterfaceType(0).getText(); //unannClassOrInterfaceTypeContext. unannInterfaceType_lf_unannClassOrInterfaceType(1).getText(); //unannClassOrInterfaceTypeContext. unannInterfaceType_lfno_unannClassOrInterfaceType().getText(); + */ + List typeargs = classOrInterfaceTypeContext.typeArguments(); + arguments = typeargs.size() != 0 ? classOrInterfaceTypeContext.typeArguments(0) : null; + } + return convertTypeName(name, arguments, classOrInterfaceTypeContext.getStart(), reg, generics); } - public static RefTypeOrTPHOrWildcardOrGeneric convert(Java8Parser.UnannTypeContext unannTypeContext, JavaClassRegistry reg, GenericsRegistry genericsRegistry) { - if(unannTypeContext.unannPrimitiveType()!=null){ - if(unannTypeContext.unannPrimitiveType().getText().equals("boolean")){ - return new RefType(ASTFactory.createClass(Boolean.class).getClassName(), unannTypeContext.getStart()); - }else{ - Java8Parser.NumericTypeContext numericType = unannTypeContext.unannPrimitiveType().numericType(); + public static RefTypeOrTPHOrWildcardOrGeneric convert(Java17Parser.TypeTypeContext typeContext, JavaClassRegistry reg, GenericsRegistry genericsRegistry) { + if (typeContext.primitiveType() != null) { + switch (typeContext.primitiveType().getText()) { + case "boolean": + return new RefType(ASTFactory.createClass(Boolean.class).getClassName(), typeContext.getStart()); + case "int": + return new RefType(ASTFactory.createClass(Integer.class).getClassName(), typeContext.getStart()); + default: throw new NotImplementedException(); } - }else - if(unannTypeContext.unannReferenceType().unannArrayType()!=null){ - //System.out.println(unannTypeContext.getText()); + } else if (!typeContext.LBRACK().isEmpty()) { // ArrayType über eckige Klammer prüfen + // System.out.println(unannTypeContext.getText()); throw new NotImplementedException(); - }else - if(unannTypeContext.unannReferenceType().unannTypeVariable()!=null){ - JavaClassName name = reg.getName(unannTypeContext.unannReferenceType().unannTypeVariable().Identifier().toString()); - return new RefType(name, unannTypeContext.getStart()); } - return TypeGenerator.convert(unannTypeContext.unannReferenceType().unannClassOrInterfaceType(), reg, genericsRegistry); + /* + * else if (typeContext.classOrInterfaceType() != null) { JavaClassName name = reg .getName(typeContext.classOrInterfaceType().typeIdentifier().getText()); return new RefType(name, typeContext.getStart()); } + */ + return TypeGenerator.convert(typeContext.classOrInterfaceType(), reg, genericsRegistry); } - public static GenericDeclarationList convert(Java8Parser.TypeParametersContext typeParametersContext, - JavaClassName parentClass, String parentMethod, JavaClassRegistry reg, GenericsRegistry generics) { + public static GenericDeclarationList convert(Java17Parser.GenericDeclarationListContext typeParametersContext, JavaClassName parentClass, String parentMethod, JavaClassRegistry reg, GenericsRegistry generics) { Token endOffset = typeParametersContext.getStop(); List typeVars = new ArrayList<>(); - for(Java8Parser.TypeParameterContext typeParameter : typeParametersContext.typeParameterList().typeParameter()){ + for (Java17Parser.GenericTypeVarContext typeParameter : typeParametersContext.genericTypeVar()) { typeVars.add(convert(typeParameter, parentClass, parentMethod, reg, generics)); endOffset = typeParameter.getStop(); } return new GenericDeclarationList(typeVars, endOffset); } - public static GenericTypeVar convert(Java8Parser.TypeParameterContext typeParameter, JavaClassName parentClass, String parentMethod, JavaClassRegistry reg, GenericsRegistry generics) { - String name = typeParameter.Identifier().getText(); - //TODO: Es müssen erst alle GenericTypeVars generiert werden, dann können die bounds dieser Generics ermittelt werden - //Problem ist erlaubt, würde aber bei den Bounds von A den Generic B nicht als solchen erkennen - List bounds = TypeGenerator.convert(typeParameter.typeBound(),reg, generics); + public static GenericTypeVar convert(Java17Parser.GenericTypeVarContext typeVar, JavaClassName parentClass, String parentMethod, JavaClassRegistry reg, GenericsRegistry generics) { + String name = typeVar.identifier().getText(); + // TODO: Es müssen erst alle GenericTypeVars generiert werden, dann können die + // bounds dieser Generics ermittelt werden + // Problem ist erlaubt, würde aber bei den Bounds von A den + // Generic B nicht als solchen erkennen + List bounds = TypeGenerator.convert(typeVar.typeBound(), reg, generics); - GenericTypeVar ret = new GenericTypeVar(name, bounds, typeParameter.getStart(), typeParameter.getStop()); + GenericTypeVar ret = new GenericTypeVar(name, bounds, typeVar.getStart(), typeVar.getStop()); return ret; } - public static List convert(Java8Parser.TypeBoundContext typeBoundContext, JavaClassRegistry reg, GenericsRegistry generics) { + public static List convert(Java17Parser.TypeBoundContext typeBoundContext, JavaClassRegistry reg, GenericsRegistry generics) { List ret = new ArrayList<>(); - if(typeBoundContext == null){ + if (Objects.isNull(typeBoundContext)) { ret.add(ASTFactory.createObjectType()); return ret; } - if(typeBoundContext.typeVariable() != null){ - ret.add(convertTypeName(typeBoundContext.typeVariable().Identifier().getText(), null, typeBoundContext.typeVariable().getStart(), reg, generics)); + if (typeBoundContext.typeType().size() > 0) { + for (TypeTypeContext tt : typeBoundContext.typeType()) { + ret.add(convert(tt, reg, generics)); + } return ret; } - if(typeBoundContext.classOrInterfaceType() != null){ - ret.add(convert(typeBoundContext.classOrInterfaceType(), reg, generics)); - if(typeBoundContext.additionalBound() != null) - for(Java8Parser.AdditionalBoundContext addCtx : typeBoundContext.additionalBound()){ - ret.add(convert(addCtx.interfaceType())); - } - return ret; - }else{ - throw new NotImplementedException(); - } - } - - private static RefTypeOrTPHOrWildcardOrGeneric convert(Java8Parser.ClassOrInterfaceTypeContext classOrInterfaceTypeContext, JavaClassRegistry reg, GenericsRegistry generics) { - Java8Parser.ClassType_lfno_classOrInterfaceTypeContext ctx = classOrInterfaceTypeContext.classType_lfno_classOrInterfaceType(); - if(ctx.typeArguments() != null && - classOrInterfaceTypeContext.classType_lf_classOrInterfaceType().size() > 0) - throw new NotImplementedException(); - String typeName = ctx.Identifier().toString(); - Java8Parser.ClassType_lf_classOrInterfaceTypeContext nextCtx = null; - for(Java8Parser.ClassType_lf_classOrInterfaceTypeContext forEachCtx : classOrInterfaceTypeContext.classType_lf_classOrInterfaceType()){ - nextCtx = forEachCtx; - typeName += "." + forEachCtx.Identifier().toString(); - } - Java8Parser.TypeArgumentsContext arguments = nextCtx!=null?nextCtx.typeArguments():ctx.typeArguments(); - return convertTypeName(typeName, arguments, classOrInterfaceTypeContext.getStart(), reg, generics); - } - - private static RefTypeOrTPHOrWildcardOrGeneric convert(Java8Parser.InterfaceTypeContext interfaceTypeContext) { throw new NotImplementedException(); } - public static RefTypeOrTPHOrWildcardOrGeneric convert(Java8Parser.ReferenceTypeContext referenceTypeContext, JavaClassRegistry reg, GenericsRegistry generics) { - if(referenceTypeContext.classOrInterfaceType() != null){ - if(referenceTypeContext.classOrInterfaceType().classType_lfno_classOrInterfaceType()!= null){ - return convert(referenceTypeContext.classOrInterfaceType(), reg, generics);//return convertTypeName(referenceTypeContext.getText(), ctx.typeArguments(),referenceTypeContext.getStart(), reg, generics); - }else{ - throw new NotImplementedException(); - } - }else{ - throw new NotImplementedException(); - } - } - - public static RefTypeOrTPHOrWildcardOrGeneric convert(Java8Parser.WildcardContext wildcardContext, JavaClassRegistry reg, GenericsRegistry generics) { - if(wildcardContext.wildcardBounds() != null){ - if(wildcardContext.wildcardBounds().getText().substring(0, 7).equals("extends")){ - return new ExtendsWildcardType(convert(wildcardContext.wildcardBounds().referenceType(), reg, generics), wildcardContext.getStart()); - }else{ - return new SuperWildcardType(convert(wildcardContext.wildcardBounds().referenceType(), reg, generics), wildcardContext.getStart()); - } - }else{ - return new ExtendsWildcardType(ASTFactory.createObjectType(), wildcardContext.getStart()); - } - } - - public static RefTypeOrTPHOrWildcardOrGeneric convertTypeName(String name, Token offset, JavaClassRegistry reg, GenericsRegistry generics){ - return convertTypeName(name, null, offset, reg, generics); - } - - public static RefTypeOrTPHOrWildcardOrGeneric convertTypeName( - String name, Java8Parser.TypeArgumentsContext typeArguments, Token offset, JavaClassRegistry reg, GenericsRegistry generics){ - if(!reg.contains(name)){ //Dann könnte es ein generischer Type oder ein FunN$$-Type sein - if(generics.contains(name)){ - return new GenericRefType(name, offset); - }else{ - Pattern p = Pattern.compile("Fun(\\d+)[$][$]"); - Matcher m = p.matcher(name); - if (m.matches()) {//es ist FunN$$-Type - return new RefType(new JavaClassName(name), convert(typeArguments, reg, generics), offset); + public static RefTypeOrTPHOrWildcardOrGeneric convert(Java17Parser.WildcardTypeContext wildcardContext, JavaClassRegistry reg, GenericsRegistry generics) { + if (wildcardContext.getChildCount() < 3) { + if (!Objects.isNull(wildcardContext.extendsWildcardType())) { + return new ExtendsWildcardType(convert(wildcardContext.extendsWildcardType().typeType(), reg, generics), wildcardContext.getStart()); } else { - throw new TypeinferenceException("Der Typ "+ name + " ist nicht vorhanden",offset); - }} + return new SuperWildcardType(convert(wildcardContext.superWildcardType().typeType(), reg, generics), wildcardContext.getStart()); + } + } else { + throw new NotImplementedException(); // Wildcard ohne Bound } - if(typeArguments == null){ + } + + public static RefTypeOrTPHOrWildcardOrGeneric convertTypeName(String name, Token offset, JavaClassRegistry reg, GenericsRegistry generics) { + return convertTypeName(name, (Java17Parser.TypeArgumentsContext) null, offset, reg, generics); + } + + public static RefTypeOrTPHOrWildcardOrGeneric convertTypeName(String name, Java17Parser.TypeArgumentsContext typeArguments, Token offset, JavaClassRegistry reg, GenericsRegistry generics) { + if (!reg.contains(name)) { // Dann könnte es ein generischer Type oder ein FunN$$-Type sein + if (generics.contains(name)) { + return new GenericRefType(name, offset); + } else { + Pattern p = Pattern.compile("Fun(\\d+)[$][$]"); + Matcher m = p.matcher(name); + if (m.matches()) {// es ist FunN$$-Type + return new RefType(new JavaClassName(name), convert(typeArguments, reg, generics), offset); + } else { + throw new TypeinferenceException("Der Typ " + name + " ist nicht vorhanden", offset); + } + } + } + if (typeArguments == null) { List params = new ArrayList<>(); - for(int i = 0; i convert(Java8Parser.TypeArgumentsContext typeArguments, - JavaClassRegistry reg, GenericsRegistry generics){ + public static RefTypeOrTPHOrWildcardOrGeneric convertTypeName(String name, Java17Parser.NonWildcardTypeArgumentsContext typeArguments, Token offset, JavaClassRegistry reg, GenericsRegistry generics) { + if (!reg.contains(name)) { // Dann könnte es ein generischer Type oder ein FunN$$-Type sein + if (generics.contains(name)) { + return new GenericRefType(name, offset); + } else { + Pattern p = Pattern.compile("Fun(\\d+)[$][$]"); + Matcher m = p.matcher(name); + if (m.matches()) {// es ist FunN$$-Type + return new RefType(new JavaClassName(name), convert(typeArguments, reg, generics), offset); + } else { + throw new TypeinferenceException("Der Typ " + name + " ist nicht vorhanden", offset); + } + } + } + if (typeArguments == null) { + List params = new ArrayList<>(); + for (int i = 0; i < reg.getNumberOfGenerics(name); i++) { + params.add(TypePlaceholder.fresh(offset)); + } + return new RefType(reg.getName(name), params, offset); + } else { + return new RefType(reg.getName(name), convert(typeArguments, reg, generics), offset); + } + } + + public static List convert(Java17Parser.TypeArgumentsContext typeArguments, JavaClassRegistry reg, GenericsRegistry generics) { List ret = new ArrayList<>(); - for(Java8Parser.TypeArgumentContext arg : typeArguments.typeArgumentList().typeArgument()){ - if(arg.wildcard() != null){ - ret.add(convert(arg.wildcard(), reg, generics)); - }else{ - ret.add(convert(arg.referenceType(), reg, generics)); + for (Java17Parser.TypeArgumentContext arg : typeArguments.typeArgument()) { + WildcardTypeContext wc = arg.wildcardType(); + if (!Objects.isNull(wc)) { + ret.add(convert(wc, reg, generics)); + } else { + ret.add(convert(arg.typeType(), reg, generics)); } } return ret; } - public static RefTypeOrTPHOrWildcardOrGeneric convert(Java8Parser.ClassTypeContext ctx, JavaClassRegistry reg, GenericsRegistry generics) { - if(ctx.classOrInterfaceType() != null)throw new NotImplementedException(); - return convertTypeName(ctx.Identifier().getText(), ctx.typeArguments(), ctx.getStart(), reg, generics); + public static List convert(Java17Parser.NonWildcardTypeArgumentsContext typeArguments, JavaClassRegistry reg, GenericsRegistry generics) { + List ret = new ArrayList<>(); + for (Java17Parser.TypeTypeContext arg : typeArguments.typeList().typeType()) { + ret.add(convert(arg, reg, generics)); + } + return ret; } } diff --git a/src/main/java/de/dhbwstuttgart/parser/scope/GatherNames.java b/src/main/java/de/dhbwstuttgart/parser/scope/GatherNames.java index aec9f8b4..c1d2aa53 100644 --- a/src/main/java/de/dhbwstuttgart/parser/scope/GatherNames.java +++ b/src/main/java/de/dhbwstuttgart/parser/scope/GatherNames.java @@ -1,102 +1,108 @@ package de.dhbwstuttgart.parser.scope; -import java.net.URL; -import java.net.URLClassLoader; import java.util.*; -import de.dhbwstuttgart.parser.antlr.Java8BaseListener; -import de.dhbwstuttgart.syntaxtree.AbstractASTWalker; -import org.antlr.v4.runtime.tree.AbstractParseTreeVisitor; -import org.antlr.v4.runtime.tree.ParseTreeWalker; -import org.antlr.v4.runtime.tree.TerminalNode; +import org.antlr.v4.runtime.ParserRuleContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.ClassDeclarationContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.ClassorinterfacedeclContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.NoclassorinterfaceContext; +import de.dhbwstuttgart.parser.antlr.Java17Parser.SrcfileContext; import de.dhbwstuttgart.environment.PackageCrawler; -import de.dhbwstuttgart.parser.antlr.Java8Parser; +import de.dhbwstuttgart.exceptions.NotImplementedException; +import de.dhbwstuttgart.parser.antlr.Java17Parser; public class GatherNames { - public static Map getNames(Java8Parser.CompilationUnitContext ctx, PackageCrawler packages, ClassLoader classLoader) throws ClassNotFoundException{ - Map ret = new HashMap<>(); - String pkgName = getPackageName(ctx); - String nameString = ""; - for (Java8Parser.TypeDeclarationContext typeDecl : ctx.typeDeclaration()){ - if(typeDecl.interfaceDeclaration() != null){ - if(typeDecl.interfaceDeclaration().normalInterfaceDeclaration() != null){ - if(pkgName != ""){ - nameString = pkgName + "." + typeDecl.interfaceDeclaration().normalInterfaceDeclaration().Identifier().toString(); - } - else{ - nameString = typeDecl.interfaceDeclaration().normalInterfaceDeclaration().Identifier().toString(); - } - int numGenerics = typeDecl.interfaceDeclaration().normalInterfaceDeclaration().typeParameters()!=null? - typeDecl.interfaceDeclaration().normalInterfaceDeclaration().typeParameters().typeParameterList().typeParameter().size():0; - //Die Generic TypeParameter Definitionen Nicht! an die JavaClassName-Registry anfügen: - /* //Diese gelängen dadurch in den globalen Scope, was sie schließlich nicht sind - if(typeDecl.classDeclaration().normalClassDeclaration().typeParameters() != null){ - for(Java8Parser.TypeParameterContext tp : typeDecl.classDeclaration().normalClassDeclaration().typeParameters().typeParameterList().typeParameter()){ - //this.reg.add(tp.Identifier().toString()); - } - } - */ - ret.put(nameString, numGenerics); - } - } - else{ - if(typeDecl.classDeclaration().normalClassDeclaration() != null){ - if(!pkgName.isEmpty()){ - nameString = pkgName + "." + typeDecl.classDeclaration().normalClassDeclaration().Identifier().toString(); - } - else{ - nameString = typeDecl.classDeclaration().normalClassDeclaration().Identifier().toString(); - } - //Die Generic TypeParameter Definitionen Nicht! an die JavaClassName-Registry anfügen: - /* //Diese gelängen dadurch in den globalen Scope, was sie schließlich nicht sind - if(typeDecl.classDeclaration().normalClassDeclaration().typeParameters() != null){ - for(Java8Parser.TypeParameterContext tp : typeDecl.classDeclaration().normalClassDeclaration().typeParameters().typeParameterList().typeParameter()){ - this.reg.add(tp.Identifier().toString()); - } - } - */ - int numGenerics = typeDecl.classDeclaration().normalClassDeclaration().typeParameters()!=null? - typeDecl.classDeclaration().normalClassDeclaration().typeParameters().typeParameterList().typeParameter().size():0; - - ret.put(nameString, numGenerics); - } - } - } - ret.putAll(getImports(ctx, packages, classLoader)); - return ret; - } - - public static Map getImports(Java8Parser.CompilationUnitContext ctx, PackageCrawler packages, ClassLoader classLoader) throws ClassNotFoundException { - Map ret = new HashMap<>(); - //ret.putAll(packages.getClassNames("java.lang")); - for(Java8Parser.ImportDeclarationContext importDeclCtx : ctx.importDeclaration()){ - if(importDeclCtx.singleTypeImportDeclaration() != null){ - Class cl = classLoader.loadClass(importDeclCtx.singleTypeImportDeclaration().typeName().getText()); - ret.put(cl.getName(), cl.getTypeParameters().length); - } - else if(importDeclCtx.typeImportOnDemandDeclaration() != null){ - ret.putAll(packages.getClassNames(importDeclCtx.typeImportOnDemandDeclaration().packageOrTypeName().getText())); - } - else if(importDeclCtx.singleStaticImportDeclaration() != null){ - Class cl = classLoader.loadClass(importDeclCtx.singleStaticImportDeclaration().typeName().getText()+"."+importDeclCtx.singleStaticImportDeclaration().Identifier().getText()); - ret.put(cl.getName(), cl.getTypeParameters().length); - } - else{ - ret.putAll(packages.getClassNames(importDeclCtx.staticImportOnDemandDeclaration().typeName().getText())); - } - } - return ret; - } - - private static String getPackageName(Java8Parser.CompilationUnitContext ctx){ - String pkgName = ""; - if(ctx.packageDeclaration() != null){ - for(TerminalNode t : ctx.packageDeclaration().Identifier()){ - pkgName = pkgName + "." + t.toString(); + public static Map getNames(SrcfileContext ctx, PackageCrawler packages, ClassLoader classLoader) throws ClassNotFoundException { + Map ret = new HashMap<>(); + String pkgName = getPackageName(ctx); + String nameString = ""; + for (Java17Parser.ClassOrInterfaceContext member : ctx.classOrInterface()) { + if (member instanceof NoclassorinterfaceContext) { + continue; } - pkgName = pkgName.substring(1); + ClassorinterfacedeclContext clsoif = (ClassorinterfacedeclContext) member; + String fullname = clsoif.getChild(clsoif.getChildCount() - 1).getClass().getName(); + String classname = fullname.substring(fullname.indexOf("$") + 1); + int numGenerics = 0; + /* + * Es werden alle Namen gesammelt, die syntaktisch von Java-TX (sprich der Grammatik) erkannt werden. Auch wenn z.B. Annotationen oder Enumerationen noch nicht im Compiler implementiert sind. Die "NotImplementedException" wird dann im "SyntaxTreeGenerator" geworfen. Das Statement soll als Vorbereitung dienen, für den Fall, dass weitere Sprachkonstrukte in den Compiler aufgenommen werden. + */ + switch (classname) { + case "ClassDeclarationContext": + if (!pkgName.isEmpty()) { + nameString = pkgName + "." + clsoif.classDeclaration().identifier().getText(); + } else { + nameString = clsoif.classDeclaration().identifier().getText(); + } + numGenerics = clsoif.classDeclaration().genericDeclarationList() != null ? clsoif.classDeclaration().genericDeclarationList().genericTypeVar().size() : 0; + ret.put(nameString, numGenerics); + break; + case "EnumDeclarationContext": + if (!pkgName.isEmpty()) { + nameString = pkgName + "." + clsoif.enumDeclaration().identifier().getText(); + } else { + nameString = clsoif.enumDeclaration().identifier().getText(); + } + numGenerics = 0; + ret.put(nameString, numGenerics); + break; + case "InterfaceDeclarationContext": + if (pkgName != "") { + nameString = pkgName + "." + clsoif.interfaceDeclaration().identifier().getText(); + } else { + nameString = clsoif.interfaceDeclaration().identifier().getText(); + } + numGenerics = clsoif.interfaceDeclaration().genericDeclarationList() != null ? clsoif.interfaceDeclaration().genericDeclarationList().genericTypeVar().size() : 0; + ret.put(nameString, numGenerics); + break; + case "AnnotationTypeDeclarationContext": + if (pkgName != "") { + nameString = pkgName + "." + clsoif.annotationTypeDeclaration().identifier().getText(); + } else { + nameString = clsoif.annotationTypeDeclaration().identifier().getText(); + } + numGenerics = 0; + ret.put(nameString, numGenerics); + break; + case "RecordDeclarationContext": + if (pkgName != "") { + nameString = pkgName + "." + clsoif.recordDeclaration().identifier().getText(); + } else { + nameString = clsoif.recordDeclaration().identifier().getText(); + } + numGenerics = clsoif.recordDeclaration().genericDeclarationList() != null ? clsoif.recordDeclaration().genericDeclarationList().genericTypeVar().size() : 0; + ret.put(nameString, numGenerics); + break; + default: + throw new NotImplementedException(); + } + } + ret.putAll(getImports(ctx, packages, classLoader)); + return ret; + } + + public static Map getImports(Java17Parser.SrcfileContext ctx, PackageCrawler packages, ClassLoader classLoader) throws ClassNotFoundException { + Map ret = new HashMap<>(); + // ret.putAll(packages.getClassNames("java.lang")); + for (Java17Parser.ImportDeclarationContext importDeclCtx : ctx.importDeclaration()) { + if (importDeclCtx.MUL() == null) { + Class cl = classLoader.loadClass(importDeclCtx.qualifiedName().getText()); + ret.put(cl.getName(), cl.getTypeParameters().length); + } else if (importDeclCtx.MUL() != null) { + ret.putAll(packages.getClassNames(importDeclCtx.qualifiedName().getText())); + } + // Die Unterscheidungen für 'static imports' wurden herausgenommen, da sie den + // auszuführenden Code nicht beeinflussen + } + return ret; + } + + private static String getPackageName(Java17Parser.SrcfileContext ctx) { + String pkgName = ""; + if (ctx.packageDeclaration() != null) { + pkgName = ctx.packageDeclaration().qualifiedName().getText(); } return pkgName; } diff --git a/src/main/java/de/dhbwstuttgart/parser/scope/JavaClassName.java b/src/main/java/de/dhbwstuttgart/parser/scope/JavaClassName.java index 534d0916..867973f9 100644 --- a/src/main/java/de/dhbwstuttgart/parser/scope/JavaClassName.java +++ b/src/main/java/de/dhbwstuttgart/parser/scope/JavaClassName.java @@ -1,12 +1,12 @@ package de.dhbwstuttgart.parser.scope; - import java.util.ArrayList; import java.util.List; /** - * Stellt den Namen einer Java Klasse dar. - * Dieser kann auch den Packagenamen mit beinhalten: de.dhbwstuttgart.typeinference.Menge + * Stellt den Namen einer Java Klasse dar. + * Dieser kann auch den Packagenamen mit beinhalten: + * de.dhbwstuttgart.typeinference.Menge * * @author Andreas Stadelmeier */ @@ -16,22 +16,23 @@ public class JavaClassName { private String name; private PackageName packageName; - public JavaClassName(String name){ - if(name == null)throw new NullPointerException(); - + public JavaClassName(String name) { + if (name == null) + throw new NullPointerException(); + String[] names = name.split("[.]"); boolean match = true; - if(names.length == 1){ - //packageName = new PackageName(); + if (names.length == 1) { + // packageName = new PackageName(); this.name = name; - }else { - name = names[names.length-1]; + } else { + name = names[names.length - 1]; List packageNames = new ArrayList(); - for(int i = 0; i names = new ArrayList<>(); - + public PackageName(List packageNames) { names = packageNames; } public PackageName() { - //Do nothing + // Do nothing } @Override @@ -132,12 +139,14 @@ class PackageName{ return false; return true; } - + @Override public String toString() { String ret = ""; - if(names == null)return ""; - for(String n : names)ret+=n+"."; + if (names == null) + return ""; + for (String n : names) + ret += n + "."; if (ret != null && ret.length() > 0 && ret.charAt(ret.length() - 1) == '.') { ret = ret.substring(0, ret.length() - 1); } diff --git a/src/main/java/de/dhbwstuttgart/parser/scope/JavaClassRegistry.java b/src/main/java/de/dhbwstuttgart/parser/scope/JavaClassRegistry.java index d9ab804c..b2d436c7 100644 --- a/src/main/java/de/dhbwstuttgart/parser/scope/JavaClassRegistry.java +++ b/src/main/java/de/dhbwstuttgart/parser/scope/JavaClassRegistry.java @@ -10,29 +10,31 @@ import java.util.*; public class JavaClassRegistry { final Map existingClasses = new HashMap<>(); - public JavaClassRegistry(Map initialNames){ - for(String name : initialNames.keySet()){ + public JavaClassRegistry(Map initialNames) { + for (String name : initialNames.keySet()) { existingClasses.put(new JavaClassName(name), initialNames.get(name)); } } public JavaClassName getName(String className) { - for(JavaClassName name : existingClasses.keySet()){ - if(name.equals(new JavaClassName(className)))return name; + for (JavaClassName name : existingClasses.keySet()) { + if (name.equals(new JavaClassName(className))) + return name; } throw new NotImplementedException(); } @Override - public String toString(){ + public String toString() { return existingClasses.toString(); } public List getAllFromPackage(String packageName) { List ret = new ArrayList<>(); - for(JavaClassName className : this.existingClasses.keySet()){ - JavaClassName toCompare = new JavaClassName(packageName + "." + JavaClassName.stripClassName(className.toString())); - if(toCompare.toString().equals(className.toString())){ + for (JavaClassName className : this.existingClasses.keySet()) { + JavaClassName toCompare = new JavaClassName( + packageName + "." + JavaClassName.stripClassName(className.toString())); + if (toCompare.toString().equals(className.toString())) { ret.add(className); } } diff --git a/src/main/java/de/dhbwstuttgart/syntaxtree/AbstractASTWalker.java b/src/main/java/de/dhbwstuttgart/syntaxtree/AbstractASTWalker.java index 0cbad897..0aa350c9 100644 --- a/src/main/java/de/dhbwstuttgart/syntaxtree/AbstractASTWalker.java +++ b/src/main/java/de/dhbwstuttgart/syntaxtree/AbstractASTWalker.java @@ -7,7 +7,7 @@ import de.dhbwstuttgart.syntaxtree.type.*; import java.util.Iterator; -public abstract class AbstractASTWalker implements ASTVisitor{ +public abstract class AbstractASTWalker implements ASTVisitor { @Override public void visit(Constructor cons) { visitMethod(cons); @@ -15,14 +15,14 @@ public abstract class AbstractASTWalker implements ASTVisitor{ @Override public void visit(SourceFile sourceFile) { - for(ClassOrInterface cl : sourceFile.getClasses()){ + for (ClassOrInterface cl : sourceFile.getClasses()) { cl.accept(this); } } @Override public void visit(ArgumentList argumentList) { - for(Expression expr : argumentList.getArguments()){ + for (Expression expr : argumentList.getArguments()) { expr.accept(this); } } @@ -40,8 +40,8 @@ public abstract class AbstractASTWalker implements ASTVisitor{ @Override public void visit(GenericDeclarationList genericTypeVars) { Iterator genericIterator = genericTypeVars.iterator(); - if(genericIterator.hasNext()){ - while(genericIterator.hasNext()){ + if (genericIterator.hasNext()) { + while (genericIterator.hasNext()) { genericIterator.next().accept(this); } } @@ -57,18 +57,18 @@ public abstract class AbstractASTWalker implements ASTVisitor{ visitMethod(method); } - private void visitMethod(Method method){ + private void visitMethod(Method method) { method.getReturnType().accept(this); method.getParameterList().accept(this); - if(method.block != null) + if (method.block != null) method.block.accept(this); } @Override public void visit(ParameterList formalParameters) { Iterator it = formalParameters.getFormalparalist().iterator(); - if(it.hasNext()){ - while(it.hasNext()){ + if (it.hasNext()) { + while (it.hasNext()) { it.next().accept(this); } } @@ -77,13 +77,13 @@ public abstract class AbstractASTWalker implements ASTVisitor{ @Override public void visit(ClassOrInterface classOrInterface) { classOrInterface.getGenerics().accept(this); - for(Field f : classOrInterface.getFieldDecl()){ + for (Field f : classOrInterface.getFieldDecl()) { f.accept(this); } - for(Constructor c : classOrInterface.getConstructors()){ + for (Constructor c : classOrInterface.getConstructors()) { c.accept(this); } - for(Method m : classOrInterface.getMethods()){ + for (Method m : classOrInterface.getMethods()) { m.accept(this); } } @@ -91,8 +91,8 @@ public abstract class AbstractASTWalker implements ASTVisitor{ @Override public void visit(RefType refType) { Iterator genericIterator = refType.getParaList().iterator(); - if(genericIterator.hasNext()){ - while(genericIterator.hasNext()){ + if (genericIterator.hasNext()) { + while (genericIterator.hasNext()) { genericIterator.next().accept(this); } } @@ -136,7 +136,7 @@ public abstract class AbstractASTWalker implements ASTVisitor{ @Override public void visit(Block block) { - for(Statement stmt : block.getStatements()){ + for (Statement stmt : block.getStatements()) { stmt.accept(this); } } @@ -177,7 +177,6 @@ public abstract class AbstractASTWalker implements ASTVisitor{ } - @Override public void visit(LocalVarDecl localVarDecl) { localVarDecl.getType().accept(this); @@ -190,7 +189,6 @@ public abstract class AbstractASTWalker implements ASTVisitor{ methodCall.getArgumentList().getArguments().forEach(a -> a.getType().accept((ASTVisitor) this)); } - @Override public void visit(NewClass methodCall) { visit((MethodCall) methodCall); @@ -222,6 +220,11 @@ public abstract class AbstractASTWalker implements ASTVisitor{ } + @Override + public void visit(Break aBreak) { + aBreak.accept(this); + } + @Override public void visit(StaticClassName staticClassName) { @@ -264,6 +267,6 @@ public abstract class AbstractASTWalker implements ASTVisitor{ @Override public void visit(SuperCall superCall) { - this.visit((MethodCall)superCall); + this.visit((MethodCall) superCall); } } diff --git a/src/main/java/de/dhbwstuttgart/syntaxtree/Constructor.java b/src/main/java/de/dhbwstuttgart/syntaxtree/Constructor.java index 24b3bb81..1c955c81 100644 --- a/src/main/java/de/dhbwstuttgart/syntaxtree/Constructor.java +++ b/src/main/java/de/dhbwstuttgart/syntaxtree/Constructor.java @@ -12,20 +12,16 @@ import java.util.List; public class Constructor extends Method { - - //TODO: Constructor braucht ein super-Statement - public Constructor(int modifier, String name, RefTypeOrTPHOrWildcardOrGeneric returnType, ParameterList parameterList, Block codeInsideConstructor, - GenericDeclarationList gtvDeclarations, Token offset /*, List fieldInitializations geloescht PL 2018-11-24 */) { - super(modifier, name, returnType, parameterList, /*codeInsideConstructor,*/ prepareBlock(codeInsideConstructor ) /*,fieldInitializations )geloescht PL 2018-11-24 )*/, gtvDeclarations, offset); + // TODO: Constructor braucht ein super-Statement + public Constructor(int modifier, String name, RefTypeOrTPHOrWildcardOrGeneric returnType, ParameterList parameterList, Block codeInsideConstructor, GenericDeclarationList gtvDeclarations, Token offset /* , List fieldInitializations geloescht PL 2018-11-24 */) { + super(modifier, name, returnType, parameterList, /* codeInsideConstructor, */ prepareBlock(codeInsideConstructor) /* ,fieldInitializations )geloescht PL 2018-11-24 ) */, gtvDeclarations, offset); } /** - * @param fieldInitializations - Das sind die Statements, - * welche die Felder der zugehörigen Klasse dieses - * Konstruktor initialisieren + * @param fieldInitializations - Das sind die Statements, welche die Felder der zugehörigen Klasse dieses Konstruktor initialisieren */ - protected static Block prepareBlock(Block constructorBlock /*, List fieldInitializations new ArrayList<>() geloescht PL 2018-11-24 */){ + protected static Block prepareBlock(Block constructorBlock /* , List fieldInitializations new ArrayList<>() geloescht PL 2018-11-24 */) { List statements = constructorBlock.getStatements(); statements.add(0, new SuperCall(null, null, constructorBlock.getOffset())); /* statements.addAll(fieldInitializations); geloescht PL 2018-11-24 */ diff --git a/src/main/java/de/dhbwstuttgart/syntaxtree/Field.java b/src/main/java/de/dhbwstuttgart/syntaxtree/Field.java index 8a4230e3..4afc3587 100644 --- a/src/main/java/de/dhbwstuttgart/syntaxtree/Field.java +++ b/src/main/java/de/dhbwstuttgart/syntaxtree/Field.java @@ -5,22 +5,22 @@ import org.antlr.v4.runtime.Token; import java.util.ArrayList; -public class Field extends SyntaxTreeNode implements TypeScope{ +public class Field extends SyntaxTreeNode implements TypeScope { public final int modifier; private String name; private RefTypeOrTPHOrWildcardOrGeneric type; - - public Field(String name, RefTypeOrTPHOrWildcardOrGeneric type, int modifier, Token offset){ + + public Field(String name, RefTypeOrTPHOrWildcardOrGeneric type, int modifier, Token offset) { super(offset); this.name = name; this.type = type; this.modifier = modifier; } - public String getName(){ - return this.name; - } + public String getName() { + return this.name; + } public RefTypeOrTPHOrWildcardOrGeneric getType() { return type; @@ -41,4 +41,3 @@ public class Field extends SyntaxTreeNode implements TypeScope{ return type; } } - diff --git a/src/main/java/de/dhbwstuttgart/syntaxtree/FormalParameter.java b/src/main/java/de/dhbwstuttgart/syntaxtree/FormalParameter.java index 8e7e7983..58291293 100644 --- a/src/main/java/de/dhbwstuttgart/syntaxtree/FormalParameter.java +++ b/src/main/java/de/dhbwstuttgart/syntaxtree/FormalParameter.java @@ -3,15 +3,14 @@ package de.dhbwstuttgart.syntaxtree; import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric; import org.antlr.v4.runtime.Token; -public class FormalParameter extends SyntaxTreeNode -{ +public class FormalParameter extends SyntaxTreeNode { private RefTypeOrTPHOrWildcardOrGeneric type; private String name; - - public FormalParameter(String name, RefTypeOrTPHOrWildcardOrGeneric type, Token offset){ + + public FormalParameter(String name, RefTypeOrTPHOrWildcardOrGeneric type, Token offset) { super(offset); this.name = name; - this.type = type; + this.type = type; } public RefTypeOrTPHOrWildcardOrGeneric getType() { diff --git a/src/main/java/de/dhbwstuttgart/syntaxtree/ParameterList.java b/src/main/java/de/dhbwstuttgart/syntaxtree/ParameterList.java index 2540f907..33a45c5d 100644 --- a/src/main/java/de/dhbwstuttgart/syntaxtree/ParameterList.java +++ b/src/main/java/de/dhbwstuttgart/syntaxtree/ParameterList.java @@ -1,39 +1,33 @@ package de.dhbwstuttgart.syntaxtree; - - import org.antlr.v4.runtime.Token; import java.util.Iterator; import java.util.List; - -public class ParameterList extends SyntaxTreeNode implements Iterable -{ +public class ParameterList extends SyntaxTreeNode implements Iterable { private List formalparameter; - - public ParameterList(List params, Token offset){ + + public ParameterList(List params, Token offset) { super(offset); this.formalparameter = params; } - public FormalParameter getParameterAt(int i) - { - if (i >= formalparameter.size() ) return null; - + public FormalParameter getParameterAt(int i) { + if (i >= formalparameter.size()) + return null; + return formalparameter.get(i); } - - - public List getFormalparalist() - { + + public List getFormalparalist() { return formalparameter; } - @Override - public Iterator iterator() { - return formalparameter.iterator(); - } + @Override + public Iterator iterator() { + return formalparameter.iterator(); + } @Override public void accept(ASTVisitor visitor) { diff --git a/src/main/java/de/dhbwstuttgart/syntaxtree/Record.java b/src/main/java/de/dhbwstuttgart/syntaxtree/Record.java new file mode 100644 index 00000000..46f89f19 --- /dev/null +++ b/src/main/java/de/dhbwstuttgart/syntaxtree/Record.java @@ -0,0 +1,16 @@ +package de.dhbwstuttgart.syntaxtree; + +import java.util.List; +import java.util.Optional; + +import org.antlr.v4.runtime.Token; + +import de.dhbwstuttgart.parser.scope.JavaClassName; +import de.dhbwstuttgart.syntaxtree.type.RefType; + +public class Record extends ClassOrInterface { + + public Record(int modifiers, JavaClassName name, List fielddecl, Optional fieldInitializations, List methods, List constructors, GenericDeclarationList genericClassParameters, RefType superClass, Boolean isInterface, List implementedInterfaces, Token offset) { + super(modifiers, name, fielddecl, fieldInitializations, methods, constructors, genericClassParameters, superClass, isInterface, implementedInterfaces, offset); + } +} diff --git a/src/main/java/de/dhbwstuttgart/syntaxtree/SourceFile.java b/src/main/java/de/dhbwstuttgart/syntaxtree/SourceFile.java index f9ec340b..252e7cc5 100644 --- a/src/main/java/de/dhbwstuttgart/syntaxtree/SourceFile.java +++ b/src/main/java/de/dhbwstuttgart/syntaxtree/SourceFile.java @@ -1,4 +1,5 @@ package de.dhbwstuttgart.syntaxtree; + import java.io.File; import java.util.*; @@ -8,48 +9,50 @@ import de.dhbwstuttgart.typeinference.constraints.ConstraintSet; import de.dhbwstuttgart.typeinference.assumptions.TypeInferenceInformation; //import sun.security.x509.X509CertInfo; - -public class SourceFile extends SyntaxTreeNode{ +public class SourceFile extends SyntaxTreeNode { private String pkgName; public final List KlassenVektor; public final Set imports; /** - * Die SourceFile repräsntiert eine zu einem Syntaxbaum eingelesene Java-Datei. - * SourceFile stellt dabei den Wurzelknoten des Syntaxbaumes dar. - */ - public SourceFile(String pkgName, List classDefinitions, Set imports){ + * Die SourceFile repräsntiert eine zu einem Syntaxbaum eingelesene Java-Datei. + * SourceFile stellt dabei den Wurzelknoten des Syntaxbaumes dar. + */ + public SourceFile(String pkgName, List classDefinitions, Set imports) { super(new NullToken()); - this.KlassenVektor = classDefinitions; + if (classDefinitions.size() > 0) { // Enthält die Liste Klassen? + this.KlassenVektor = classDefinitions; // Klassen werden übernommen + } else { + this.KlassenVektor = null; // es handelt sich um ein "Java Module" + } this.pkgName = pkgName; this.imports = imports; } - + public SourceFile(SourceFile sf) { - super(new NullToken()); - this.KlassenVektor = new ArrayList<>(sf.KlassenVektor); - this.imports = new HashSet<>(sf.imports); + super(new NullToken()); + this.KlassenVektor = new ArrayList<>(sf.KlassenVektor); + this.imports = new HashSet<>(sf.imports); } - - - public String getPkgName(){ + + public String getPkgName() { return this.pkgName; } // Get imports (to test implementation) - public Set getImports(){ + public Set getImports() { return this.imports; } public List getClasses() { return KlassenVektor; } - + public List getAllMethods() { - List ret = new ArrayList<>(); - getClasses().forEach(cl -> ret.addAll(cl.getMethods())); - return ret; + List ret = new ArrayList<>(); + getClasses().forEach(cl -> ret.addAll(cl.getMethods())); + return ret; } @Override diff --git a/src/main/java/de/dhbwstuttgart/syntaxtree/StatementVisitor.java b/src/main/java/de/dhbwstuttgart/syntaxtree/StatementVisitor.java index d6e0d1d5..59390f19 100644 --- a/src/main/java/de/dhbwstuttgart/syntaxtree/StatementVisitor.java +++ b/src/main/java/de/dhbwstuttgart/syntaxtree/StatementVisitor.java @@ -41,6 +41,8 @@ public interface StatementVisitor { void visit(ReturnVoid aReturn); + void visit(Break aBreak); + void visit(StaticClassName staticClassName); void visit(Super aSuper); diff --git a/src/main/java/de/dhbwstuttgart/syntaxtree/statement/Assign.java b/src/main/java/de/dhbwstuttgart/syntaxtree/statement/Assign.java index 3af2de6f..a827805e 100644 --- a/src/main/java/de/dhbwstuttgart/syntaxtree/statement/Assign.java +++ b/src/main/java/de/dhbwstuttgart/syntaxtree/statement/Assign.java @@ -11,16 +11,15 @@ import org.antlr.v4.runtime.Token; Aufbau: rightSide = leftSide */ -public class Assign extends Statement -{ +public class Assign extends Statement { public final Expression rightSide; public final AssignLeftSide lefSide; public Assign(AssignLeftSide leftHandSide, Expression value, Token offset) { - super(leftHandSide.getType(), offset); + super(leftHandSide.getType(), offset); this.rightSide = value; this.lefSide = leftHandSide; - } + } @Override public void accept(StatementVisitor visitor) { diff --git a/src/main/java/de/dhbwstuttgart/syntaxtree/statement/AssignToField.java b/src/main/java/de/dhbwstuttgart/syntaxtree/statement/AssignToField.java index 931443d1..8ed8b95c 100644 --- a/src/main/java/de/dhbwstuttgart/syntaxtree/statement/AssignToField.java +++ b/src/main/java/de/dhbwstuttgart/syntaxtree/statement/AssignToField.java @@ -2,8 +2,9 @@ package de.dhbwstuttgart.syntaxtree.statement; import de.dhbwstuttgart.syntaxtree.StatementVisitor; -public class AssignToField extends AssignLeftSide{ +public class AssignToField extends AssignLeftSide { public final FieldVar field; + public AssignToField(FieldVar fieldVar) { super(fieldVar.getType(), fieldVar.getOffset()); field = fieldVar; diff --git a/src/main/java/de/dhbwstuttgart/syntaxtree/statement/BinaryExpr.java b/src/main/java/de/dhbwstuttgart/syntaxtree/statement/BinaryExpr.java index 4fab15cc..cd93959c 100644 --- a/src/main/java/de/dhbwstuttgart/syntaxtree/statement/BinaryExpr.java +++ b/src/main/java/de/dhbwstuttgart/syntaxtree/statement/BinaryExpr.java @@ -1,24 +1,22 @@ package de.dhbwstuttgart.syntaxtree.statement; - import de.dhbwstuttgart.syntaxtree.StatementVisitor; import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric; import org.antlr.v4.runtime.Token; -public class BinaryExpr extends Expression -{ +public class BinaryExpr extends Expression { @Override public void accept(StatementVisitor visitor) { visitor.visit(this); } - public enum Operator{ + public enum Operator { ADD, // + SUB, // - MUL, // * MOD, // Modulo Operator % AND, // && - OR, // || + OR, // || DIV, // / LESSTHAN, // < BIGGERTHAN, // > @@ -32,9 +30,8 @@ public class BinaryExpr extends Expression public final Expression lexpr; public final Expression rexpr; - public BinaryExpr(Operator operation, RefTypeOrTPHOrWildcardOrGeneric type, Expression lexpr, Expression rexpr, Token offset) - { - super(type,offset); + public BinaryExpr(Operator operation, RefTypeOrTPHOrWildcardOrGeneric type, Expression lexpr, Expression rexpr, Token offset) { + super(type, offset); this.operation = operation; this.lexpr = lexpr; diff --git a/src/main/java/de/dhbwstuttgart/syntaxtree/statement/Break.java b/src/main/java/de/dhbwstuttgart/syntaxtree/statement/Break.java new file mode 100644 index 00000000..46db60e4 --- /dev/null +++ b/src/main/java/de/dhbwstuttgart/syntaxtree/statement/Break.java @@ -0,0 +1,19 @@ +package de.dhbwstuttgart.syntaxtree.statement; + +import org.antlr.v4.runtime.Token; + +import de.dhbwstuttgart.syntaxtree.StatementVisitor; +import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric; + +public class Break extends Statement { + + public Break(RefTypeOrTPHOrWildcardOrGeneric type, Token offset) { + super(type, offset); + } + + @Override + public void accept(StatementVisitor visitor) { + this.accept((StatementVisitor) visitor); + } + +} diff --git a/src/main/java/de/dhbwstuttgart/syntaxtree/statement/InstanceOf.java b/src/main/java/de/dhbwstuttgart/syntaxtree/statement/InstanceOf.java index 02fd667b..aea18dc3 100644 --- a/src/main/java/de/dhbwstuttgart/syntaxtree/statement/InstanceOf.java +++ b/src/main/java/de/dhbwstuttgart/syntaxtree/statement/InstanceOf.java @@ -4,14 +4,11 @@ import de.dhbwstuttgart.exceptions.NotImplementedException; import de.dhbwstuttgart.syntaxtree.StatementVisitor; import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric; - -public class InstanceOf extends BinaryExpr -{ +public class InstanceOf extends BinaryExpr { public Expression expr; private RefTypeOrTPHOrWildcardOrGeneric reftype; - - public InstanceOf(int offset,int variableLength) - { + + public InstanceOf(int offset, int variableLength) { super(null, null, null, null, null); throw new NotImplementedException(); // #JB# 20.04.2005 diff --git a/src/main/java/de/dhbwstuttgart/syntaxtree/statement/LocalVar.java b/src/main/java/de/dhbwstuttgart/syntaxtree/statement/LocalVar.java index 91094a7a..75ac436e 100644 --- a/src/main/java/de/dhbwstuttgart/syntaxtree/statement/LocalVar.java +++ b/src/main/java/de/dhbwstuttgart/syntaxtree/statement/LocalVar.java @@ -4,19 +4,17 @@ import de.dhbwstuttgart.syntaxtree.StatementVisitor; import de.dhbwstuttgart.syntaxtree.type.RefTypeOrTPHOrWildcardOrGeneric; import org.antlr.v4.runtime.Token; -public class LocalVar extends Statement{ +public class LocalVar extends Statement { public final String name; - public LocalVar(String n, RefTypeOrTPHOrWildcardOrGeneric type, Token offset) - { - super(type,offset); + public LocalVar(String n, RefTypeOrTPHOrWildcardOrGeneric type, Token offset) { + super(type, offset); this.name = n; } - public LocalVar(Expression e1, RefTypeOrTPHOrWildcardOrGeneric type, String access) - { - super(type,e1.getOffset()); + public LocalVar(Expression e1, RefTypeOrTPHOrWildcardOrGeneric type, String access) { + super(type, e1.getOffset()); this.name = access; } diff --git a/src/main/java/de/dhbwstuttgart/syntaxtree/statement/Return.java b/src/main/java/de/dhbwstuttgart/syntaxtree/statement/Return.java index 5a6a5312..33099a71 100644 --- a/src/main/java/de/dhbwstuttgart/syntaxtree/statement/Return.java +++ b/src/main/java/de/dhbwstuttgart/syntaxtree/statement/Return.java @@ -3,14 +3,11 @@ package de.dhbwstuttgart.syntaxtree.statement; import de.dhbwstuttgart.syntaxtree.StatementVisitor; import org.antlr.v4.runtime.Token; - -public class Return extends Statement -{ +public class Return extends Statement { public final Expression retexpr; - public Return(Expression retExpr, Token offset) - { - super(retExpr.getType(),offset); + public Return(Expression retExpr, Token offset) { + super(retExpr.getType(), offset); this.retexpr = retExpr; } diff --git a/src/main/java/de/dhbwstuttgart/syntaxtree/visual/OutputGenerator.java b/src/main/java/de/dhbwstuttgart/syntaxtree/visual/OutputGenerator.java index b25aa30b..151a70ce 100644 --- a/src/main/java/de/dhbwstuttgart/syntaxtree/visual/OutputGenerator.java +++ b/src/main/java/de/dhbwstuttgart/syntaxtree/visual/OutputGenerator.java @@ -9,12 +9,12 @@ import java.lang.reflect.Modifier; import java.util.Iterator; import java.util.Optional; -public class OutputGenerator implements ASTVisitor{ +public class OutputGenerator implements ASTVisitor { private static final String TAB = " "; String tabs = ""; protected final StringBuilder out; - public OutputGenerator(StringBuilder out){ + public OutputGenerator(StringBuilder out) { this.out = out; } @@ -23,12 +23,12 @@ public class OutputGenerator implements ASTVisitor{ } public void untab() { - tabs = tabs.substring(0,tabs.length()-TAB.length()); + tabs = tabs.substring(0, tabs.length() - TAB.length()); } @Override public void visit(SourceFile sourceFile) { - for(ClassOrInterface cl : sourceFile.getClasses()){ + for (ClassOrInterface cl : sourceFile.getClasses()) { cl.accept(this); } } @@ -37,9 +37,10 @@ public class OutputGenerator implements ASTVisitor{ public void visit(ArgumentList argumentList) { out.append("("); Iterator expressionIterator = argumentList.getArguments().iterator(); - while(expressionIterator.hasNext()){ + while (expressionIterator.hasNext()) { expressionIterator.next().accept(this); - if(expressionIterator.hasNext())out.append(", "); + if (expressionIterator.hasNext()) + out.append(", "); } out.append(")"); } @@ -59,11 +60,12 @@ public class OutputGenerator implements ASTVisitor{ @Override public void visit(GenericDeclarationList genericTypeVars) { Iterator genericIterator = genericTypeVars.iterator(); - if(genericIterator.hasNext()){ + if (genericIterator.hasNext()) { out.append("<"); - while(genericIterator.hasNext()){ + while (genericIterator.hasNext()) { genericIterator.next().accept(this); - if(genericIterator.hasNext())out.append(", "); + if (genericIterator.hasNext()) + out.append(", "); } out.append(">"); } @@ -82,7 +84,7 @@ public class OutputGenerator implements ASTVisitor{ method.getReturnType().accept(this); out.append(" " + method.getName()); method.getParameterList().accept(this); - if(method.block != null) + if (method.block != null) method.block.accept(this); out.append("\n"); } @@ -99,10 +101,11 @@ public class OutputGenerator implements ASTVisitor{ public void visit(ParameterList formalParameters) { out.append("("); Iterator genericIterator = formalParameters.getFormalparalist().iterator(); - if(genericIterator.hasNext()){ - while(genericIterator.hasNext()){ + if (genericIterator.hasNext()) { + while (genericIterator.hasNext()) { genericIterator.next().accept(this); - if(genericIterator.hasNext())out.append(", "); + if (genericIterator.hasNext()) + out.append(", "); } } out.append(")"); @@ -110,29 +113,29 @@ public class OutputGenerator implements ASTVisitor{ @Override public void visit(ClassOrInterface classOrInterface) { - if((Modifier.INTERFACE & classOrInterface.getModifiers()) == 1){ + if ((Modifier.INTERFACE & classOrInterface.getModifiers()) == 1) { out.append("interface "); - }else{ + } else { out.append("class "); } out.append(classOrInterface.getClassName().toString()); classOrInterface.getGenerics().accept(this); out.append(" {\n\n"); tab(); - for(Field f : classOrInterface.getFieldDecl()){ + for (Field f : classOrInterface.getFieldDecl()) { out.append(tabs); f.accept(this); out.append("\n"); } - if (classOrInterface.getfieldInitializations().isPresent()) {//PL 2019-11-28: Zum Ausdrucken der Fieldinitializer - classOrInterface.getfieldInitializations().get().accept(this); + if (classOrInterface.getfieldInitializations().isPresent()) {// PL 2019-11-28: Zum Ausdrucken der Fieldinitializer + classOrInterface.getfieldInitializations().get().accept(this); } - for(Method m : classOrInterface.getMethods()){ + for (Method m : classOrInterface.getMethods()) { out.append(tabs); m.accept(this); out.append("\n"); } - for(Constructor m : classOrInterface.getConstructors()){ + for (Constructor m : classOrInterface.getConstructors()) { out.append(tabs); m.accept(this); out.append("\n"); @@ -145,11 +148,12 @@ public class OutputGenerator implements ASTVisitor{ public void visit(RefType refType) { out.append(refType.getName().toString()); Iterator genericIterator = refType.getParaList().iterator(); - if(genericIterator.hasNext()){ + if (genericIterator.hasNext()) { out.append("<"); - while(genericIterator.hasNext()){ + while (genericIterator.hasNext()) { genericIterator.next().accept(this); - if(genericIterator.hasNext())out.append(", "); + if (genericIterator.hasNext()) + out.append(", "); } out.append(">"); } @@ -163,7 +167,7 @@ public class OutputGenerator implements ASTVisitor{ @Override public void visit(TypePlaceholder typePlaceholder) { - out.append("TPH "+ typePlaceholder.getName()); + out.append("TPH " + typePlaceholder.getName()); } @Override @@ -202,7 +206,7 @@ public class OutputGenerator implements ASTVisitor{ public void visit(Block block) { tab(); out.append("{\n"); - for(Statement stmt : block.getStatements()){ + for (Statement stmt : block.getStatements()) { out.append(tabs); stmt.accept(this); out.append(";\n"); @@ -242,7 +246,7 @@ public class OutputGenerator implements ASTVisitor{ out.append(tabs); ifStmt.then_block.accept(this); untab(); - if(ifStmt.else_block != null){ + if (ifStmt.else_block != null) { out.append("\n" + tabs + "else\n"); tab(); out.append(tabs); @@ -270,8 +274,8 @@ public class OutputGenerator implements ASTVisitor{ @Override public void visit(MethodCall methodCall) { methodCall.receiver.accept(this); - out.append("."+methodCall.name); - out.append(" Signature: "+methodCall.signature); + out.append("." + methodCall.name); + out.append(" Signature: " + methodCall.signature); methodCall.getArgumentList().accept(this); } @@ -298,6 +302,11 @@ public class OutputGenerator implements ASTVisitor{ out.append("return"); } + @Override + public void visit(Break aBreak) { + out.append("break"); + } + @Override public void visit(StaticClassName staticClassName) { @@ -354,23 +363,23 @@ public class OutputGenerator implements ASTVisitor{ @Override public void visit(UnaryExpr unaryExpr) { - if(unaryExpr.operation == UnaryExpr.Operation.MINUS){ + if (unaryExpr.operation == UnaryExpr.Operation.MINUS) { out.append("-"); } - if(unaryExpr.operation == UnaryExpr.Operation.PLUS){ + if (unaryExpr.operation == UnaryExpr.Operation.PLUS) { out.append("+"); } - if(unaryExpr.operation == UnaryExpr.Operation.PREDECREMENT){ + if (unaryExpr.operation == UnaryExpr.Operation.PREDECREMENT) { out.append("--"); } - if(unaryExpr.operation == UnaryExpr.Operation.PREINCREMENT){ + if (unaryExpr.operation == UnaryExpr.Operation.PREINCREMENT) { out.append("++"); } unaryExpr.expr.accept(this); - if(unaryExpr.operation == UnaryExpr.Operation.POSTDECREMENT){ + if (unaryExpr.operation == UnaryExpr.Operation.POSTDECREMENT) { out.append("--"); } - if(unaryExpr.operation == UnaryExpr.Operation.POSTINCREMENT){ + if (unaryExpr.operation == UnaryExpr.Operation.POSTINCREMENT) { out.append("++"); } } diff --git a/src/main/java/de/dhbwstuttgart/target/generate/ASTToTargetAST.java b/src/main/java/de/dhbwstuttgart/target/generate/ASTToTargetAST.java index 5db79459..36777e0f 100644 --- a/src/main/java/de/dhbwstuttgart/target/generate/ASTToTargetAST.java +++ b/src/main/java/de/dhbwstuttgart/target/generate/ASTToTargetAST.java @@ -33,11 +33,14 @@ public class ASTToTargetAST { public List txGenerics() { return all.stream().map(generics -> new GenericsResult(generics.txGenerics)).toList(); } + public List javaGenerics() { return all.stream().map(generics -> new GenericsResult(generics.javaGenerics)).toList(); } - record Generics(JavaGenerics javaGenerics, TxGenerics txGenerics) {} + record Generics(JavaGenerics javaGenerics, TxGenerics txGenerics) { + } + protected IByteArrayClassLoader classLoader; protected SourceFile sourceFile; @@ -58,9 +61,7 @@ public class ASTToTargetAST { } Optional findMethod(ClassOrInterface owner, String name, ArgumentList argumentList) { - return owner.getMethods().stream().filter( - m -> m.name.equals(name) && parameterEquals(m.getParameterList(), argumentList) - ).findFirst(); + return owner.getMethods().stream().filter(m -> m.name.equals(name) && parameterEquals(m.getParameterList(), argumentList)).findFirst(); } boolean parameterEquals(ParameterList parameterList, ArgumentList argumentList) { @@ -74,7 +75,8 @@ public class ASTToTargetAST { var type2 = convert(arguments.get(i).getType(), generics.javaGenerics); if (type2 instanceof TargetGenericType && type1 instanceof TargetGenericType) return true; - if (!type1.equals(type2)) return false; + if (!type1.equals(type2)) + return false; } return true; @@ -128,18 +130,11 @@ public class ASTToTargetAST { fieldInitializer = convert(input.getfieldInitializations().get().block); TargetBlock finalFieldInitializer = fieldInitializer; - return new TargetClass(input.getModifiers(), input.getClassName().toString(), convert(input.getSuperClass(), generics.javaGenerics), - javaGenerics, txGenerics, - input.getSuperInterfaces().stream().map(clazz -> convert(clazz, generics.javaGenerics)).toList(), - input.getConstructors().stream().map(constructor -> this.convert(constructor, finalFieldInitializer)).flatMap(List::stream).toList(), - input.getFieldDecl().stream().map(this::convert).toList(), - input.getMethods().stream().map(this::convert).flatMap(List::stream).toList() - ); + return new TargetClass(input.getModifiers(), input.getClassName().toString(), convert(input.getSuperClass(), generics.javaGenerics), javaGenerics, txGenerics, input.getSuperInterfaces().stream().map(clazz -> convert(clazz, generics.javaGenerics)).toList(), input.getConstructors().stream().map(constructor -> this.convert(constructor, finalFieldInitializer)).flatMap(List::stream).toList(), input.getFieldDecl().stream().map(this::convert).toList(), input.getMethods().stream().map(this::convert).flatMap(List::stream).toList()); } private List convert(ParameterList input, GenerateGenerics generics) { - return input.getFormalparalist().stream() - .map(param -> new MethodParameter(convert(param.getType(), generics), param.getName())).toList(); + return input.getFormalparalist().stream().map(param -> new MethodParameter(convert(param.getType(), generics), param.getName())).toList(); } private boolean hasGeneric(Set generics, GenericRefType type) { @@ -148,8 +143,7 @@ public class ASTToTargetAST { private Set collectMethodGenerics(GenerateGenerics generateGenerics, Set generics, Method input) { var convertedGenerics = new HashSet<>(convert(generics, generateGenerics)); - outer: - for (GenericTypeVar typeVar : input.getGenerics()) { + outer: for (GenericTypeVar typeVar : input.getGenerics()) { for (var classGeneric : currentClass.getGenerics()) { if (classGeneric.equals(typeVar)) { continue outer; @@ -157,16 +151,10 @@ public class ASTToTargetAST { } convertedGenerics.addAll(convert(typeVar, generateGenerics)); } - /*var returnType = sigma.getType(input.getReturnType(), equality); - if ((returnType instanceof GenericRefType refType) && !hasGeneric(convertedGenerics, refType)) { - convertedGenerics.add(new TargetGeneric(refType.getParsedName(), convert(OBJECT))); - } - for (var param : input.getParameterList()) { - var type = sigma.getType(param.getType(), equality); - if (type instanceof GenericRefType refType && !hasGeneric(convertedGenerics, refType)) { - convertedGenerics.add(new TargetGeneric(refType.getParsedName(), convert(OBJECT))); - } - }*/ + /* + * var returnType = sigma.getType(input.getReturnType(), equality); if ((returnType instanceof GenericRefType refType) && !hasGeneric(convertedGenerics, refType)) { convertedGenerics.add(new TargetGeneric(refType.getParsedName(), convert(OBJECT))); } for (var param : input.getParameterList()) { var type = sigma.getType(param.getType(), equality); if (type instanceof GenericRefType refType && !hasGeneric(convertedGenerics, refType)) { convertedGenerics.add(new + * TargetGeneric(refType.getParsedName(), convert(OBJECT))); } } + */ return convertedGenerics; } @@ -210,12 +198,7 @@ public class ASTToTargetAST { var javaMethodGenerics = collectMethodGenerics(generics.javaGenerics(), javaGenerics, input); var txMethodGenerics = collectMethodGenerics(generics.txGenerics(), txGenerics, input); - result.add(new TargetMethod( - input.modifier, - input.name, convert(input.block), - new TargetMethod.Signature(javaMethodGenerics, params, convert(input.getReturnType(), this.generics.javaGenerics)), - new TargetMethod.Signature(txMethodGenerics, txParams, convert(input.getReturnType(), this.generics.txGenerics)) - )); + result.add(new TargetMethod(input.modifier, input.name, convert(input.block), new TargetMethod.Signature(javaMethodGenerics, params, convert(input.getReturnType(), this.generics.javaGenerics)), new TargetMethod.Signature(txMethodGenerics, txParams, convert(input.getReturnType(), this.generics.txGenerics)))); parameterSet.add(params); } } @@ -233,11 +216,7 @@ public class ASTToTargetAST { } private TargetField convert(Field input) { - return new TargetField( - input.modifier, - convert(input.getType(), generics.javaGenerics), - input.getName() - ); + return new TargetField(input.modifier, convert(input.getType(), generics.javaGenerics), input.getName()); } private final Map usedFunN = new HashMap<>(); @@ -283,7 +262,8 @@ public class ASTToTargetAST { @Override public TargetType visit(RefType refType) { var name = refType.getName().toString(); - if (name.equals("void")) return null; + if (name.equals("void")) + return null; var params = refType.getParaList().stream().map(type -> convert(type, generics)).toList(); if (name.matches("Fun\\d+\\$\\$")) { // TODO This seems like a bad idea diff --git a/src/main/java/de/dhbwstuttgart/target/generate/StatementToTargetExpression.java b/src/main/java/de/dhbwstuttgart/target/generate/StatementToTargetExpression.java index b6a8f12f..62e68843 100644 --- a/src/main/java/de/dhbwstuttgart/target/generate/StatementToTargetExpression.java +++ b/src/main/java/de/dhbwstuttgart/target/generate/StatementToTargetExpression.java @@ -32,20 +32,20 @@ public class StatementToTargetExpression implements StatementVisitor { @Override public void visit(LambdaExpression lambdaExpression) { - var parameters = StreamSupport - .stream(lambdaExpression.params.spliterator(), false) - .map(p -> new MethodParameter(converter.convert(p.getType()), p.getName())) - .toList(); + var parameters = StreamSupport.stream(lambdaExpression.params.spliterator(), false).map(p -> new MethodParameter(converter.convert(p.getType()), p.getName())).toList(); List captures = new ArrayList<>(); lambdaExpression.methodBody.accept(new TracingStatementVisitor() { // TODO The same mechanism is implemented in Codegen, maybe use it from there? final Stack> localVariables = new Stack<>(); - { localVariables.push(new HashSet<>()); } + { + localVariables.push(new HashSet<>()); + } boolean hasLocalVar(String name) { for (var localVariables : this.localVariables) { - if (localVariables.contains(name)) return true; + if (localVariables.contains(name)) + return true; } return false; } @@ -72,13 +72,11 @@ public class StatementToTargetExpression implements StatementVisitor { } @Override - public void visit(LambdaExpression lambda) {} // Don't look at lambda expressions + public void visit(LambdaExpression lambda) { + } // Don't look at lambda expressions }); - result = new TargetLambdaExpression( - converter.convert(lambdaExpression.getType()), - captures, parameters, converter.convert(lambdaExpression.getReturnType()), converter.convert(lambdaExpression.methodBody) - ); + result = new TargetLambdaExpression(converter.convert(lambdaExpression.getType()), captures, parameters, converter.convert(lambdaExpression.getReturnType()), converter.convert(lambdaExpression.methodBody)); } @Override @@ -96,19 +94,19 @@ public class StatementToTargetExpression implements StatementVisitor { @Override public void visit(BinaryExpr binary) { result = switch (binary.operation) { - case ADD -> new TargetBinaryOp.Add(converter.convert(binary.getType()), converter.convert(binary.lexpr), converter.convert(binary.rexpr)); - case SUB -> new TargetBinaryOp.Sub(converter.convert(binary.getType()), converter.convert(binary.lexpr), converter.convert(binary.rexpr)); - case MUL -> new TargetBinaryOp.Mul(converter.convert(binary.getType()), converter.convert(binary.lexpr), converter.convert(binary.rexpr)); - case MOD -> new TargetBinaryOp.Rem(converter.convert(binary.getType()), converter.convert(binary.lexpr), converter.convert(binary.rexpr)); - case AND -> new TargetBinaryOp.And(converter.convert(binary.getType()), converter.convert(binary.lexpr), converter.convert(binary.rexpr)); - case OR -> new TargetBinaryOp.Or(converter.convert(binary.getType()), converter.convert(binary.lexpr), converter.convert(binary.rexpr)); - case DIV -> new TargetBinaryOp.Div(converter.convert(binary.getType()), converter.convert(binary.lexpr), converter.convert(binary.rexpr)); - case LESSTHAN -> new TargetBinaryOp.Less(converter.convert(binary.getType()), converter.convert(binary.lexpr), converter.convert(binary.rexpr)); - case BIGGERTHAN -> new TargetBinaryOp.Greater(converter.convert(binary.getType()), converter.convert(binary.lexpr), converter.convert(binary.rexpr)); - case LESSEQUAL -> new TargetBinaryOp.LessOrEqual(converter.convert(binary.getType()), converter.convert(binary.lexpr), converter.convert(binary.rexpr)); - case BIGGEREQUAL -> new TargetBinaryOp.GreaterOrEqual(converter.convert(binary.getType()), converter.convert(binary.lexpr), converter.convert(binary.rexpr)); - case EQUAL -> new TargetBinaryOp.Equal(converter.convert(binary.getType()), converter.convert(binary.lexpr), converter.convert(binary.rexpr)); - case NOTEQUAL -> new TargetBinaryOp.NotEqual(converter.convert(binary.getType()), converter.convert(binary.lexpr), converter.convert(binary.rexpr)); + case ADD -> new TargetBinaryOp.Add(converter.convert(binary.getType()), converter.convert(binary.lexpr), converter.convert(binary.rexpr)); + case SUB -> new TargetBinaryOp.Sub(converter.convert(binary.getType()), converter.convert(binary.lexpr), converter.convert(binary.rexpr)); + case MUL -> new TargetBinaryOp.Mul(converter.convert(binary.getType()), converter.convert(binary.lexpr), converter.convert(binary.rexpr)); + case MOD -> new TargetBinaryOp.Rem(converter.convert(binary.getType()), converter.convert(binary.lexpr), converter.convert(binary.rexpr)); + case AND -> new TargetBinaryOp.And(converter.convert(binary.getType()), converter.convert(binary.lexpr), converter.convert(binary.rexpr)); + case OR -> new TargetBinaryOp.Or(converter.convert(binary.getType()), converter.convert(binary.lexpr), converter.convert(binary.rexpr)); + case DIV -> new TargetBinaryOp.Div(converter.convert(binary.getType()), converter.convert(binary.lexpr), converter.convert(binary.rexpr)); + case LESSTHAN -> new TargetBinaryOp.Less(converter.convert(binary.getType()), converter.convert(binary.lexpr), converter.convert(binary.rexpr)); + case BIGGERTHAN -> new TargetBinaryOp.Greater(converter.convert(binary.getType()), converter.convert(binary.lexpr), converter.convert(binary.rexpr)); + case LESSEQUAL -> new TargetBinaryOp.LessOrEqual(converter.convert(binary.getType()), converter.convert(binary.lexpr), converter.convert(binary.rexpr)); + case BIGGEREQUAL -> new TargetBinaryOp.GreaterOrEqual(converter.convert(binary.getType()), converter.convert(binary.lexpr), converter.convert(binary.rexpr)); + case EQUAL -> new TargetBinaryOp.Equal(converter.convert(binary.getType()), converter.convert(binary.lexpr), converter.convert(binary.rexpr)); + case NOTEQUAL -> new TargetBinaryOp.NotEqual(converter.convert(binary.getType()), converter.convert(binary.lexpr), converter.convert(binary.rexpr)); }; } @@ -129,12 +127,7 @@ public class StatementToTargetExpression implements StatementVisitor { @Override public void visit(FieldVar fieldVar) { - result = new TargetFieldVar( - converter.convert(fieldVar.getType()), - converter.convert(fieldVar.receiver.getType()), - false, - converter.convert(fieldVar.receiver), - fieldVar.fieldVarName); + result = new TargetFieldVar(converter.convert(fieldVar.getType()), converter.convert(fieldVar.receiver.getType()), false, converter.convert(fieldVar.receiver), fieldVar.fieldVarName); } @Override @@ -145,11 +138,7 @@ public class StatementToTargetExpression implements StatementVisitor { @Override public void visit(IfStmt ifStmt) { - result = new TargetIf( - converter.convert(ifStmt.expr), - converter.convert(ifStmt.then_block), - converter.convert(ifStmt.else_block) - ); + result = new TargetIf(converter.convert(ifStmt.expr), converter.convert(ifStmt.then_block), converter.convert(ifStmt.else_block)); } @Override @@ -169,7 +158,8 @@ public class StatementToTargetExpression implements StatementVisitor { } static boolean convertsTo(TargetType from, TargetType to) { - if (to.equals(TargetType.Object)) return true; // TODO Consider type coercion and subtyping + if (to.equals(TargetType.Object)) + return true; // TODO Consider type coercion and subtyping return to.equals(from); } @@ -179,8 +169,10 @@ public class StatementToTargetExpression implements StatementVisitor { var clazz = converter.classLoader.loadClass(className.toString()); outer: for (var method : clazz.getMethods()) { - if (method.getParameterTypes().length != args.size()) continue; - if (!method.getName().equals(name)) continue; + if (method.getParameterTypes().length != args.size()) + continue; + if (!method.getName().equals(name)) + continue; for (var i = 0; i < method.getParameterTypes().length; i++) { var param = method.getParameterTypes()[i]; @@ -188,15 +180,16 @@ public class StatementToTargetExpression implements StatementVisitor { if (param.isPrimitive()) { arg = TargetType.toPrimitive(arg); } - if (!convertsTo(arg, Objects.requireNonNull(TargetType.toTargetType(param)))) continue outer; + if (!convertsTo(arg, Objects.requireNonNull(TargetType.toTargetType(param)))) + continue outer; } return method; } - } catch (ClassNotFoundException ignored) {} + } catch (ClassNotFoundException ignored) { + } } if (converter.sourceFile != null) { // TODO Multiple source files - var thisClass = converter.sourceFile.KlassenVektor.stream() - .filter(classOrInterface -> classOrInterface.getClassName().equals(className)).findFirst(); + var thisClass = converter.sourceFile.KlassenVektor.stream().filter(classOrInterface -> classOrInterface.getClassName().equals(className)).findFirst(); if (thisClass.isPresent()) { var superClass = thisClass.get().getSuperClass().getName(); @@ -213,7 +206,7 @@ public class StatementToTargetExpression implements StatementVisitor { var returnType = isFunNType ? TargetType.Object : converter.convert(methodCall.signature.get(methodCall.signature.size() - 1)); var receiverName = new JavaClassName(converter.convert(methodCall.receiver.getType()).name()); var argList = methodCall.signature.stream().map(converter::convert).toList(); - argList = argList.subList(0, argList.size() - 1); + // argList = argList.subList(0, argList.size() - 1); Method foundMethod = null; if (methodCall.receiver instanceof ExpressionReceiver expressionReceiver && expressionReceiver.expr instanceof This) { @@ -230,22 +223,12 @@ public class StatementToTargetExpression implements StatementVisitor { argList = Stream.of(foundMethod.getParameterTypes()).map(TargetType::toTargetType).toList(); } - result = new TargetMethodCall( - converter.convert(methodCall.getType()), - returnType, argList, - converter.convert(methodCall.receiver), - methodCall.getArgumentList().getArguments().stream().map(converter::convert).toList(), - receiverType, - methodCall.name, false, isFunNType - ); + result = new TargetMethodCall(converter.convert(methodCall.getType()), returnType, argList, converter.convert(methodCall.receiver), methodCall.getArgumentList().getArguments().stream().map(converter::convert).toList(), receiverType, methodCall.name, false, isFunNType); } @Override public void visit(NewClass newClass) { - result = new TargetNew( - new TargetRefType(newClass.name), - newClass.getArgumentList().getArguments().stream().map(converter::convert).toList() - ); + result = new TargetNew(new TargetRefType(newClass.name), newClass.getArgumentList().getArguments().stream().map(converter::convert).toList()); } @Override @@ -264,6 +247,11 @@ public class StatementToTargetExpression implements StatementVisitor { result = new TargetReturn(null); } + @Override + public void visit(Break aBreak) { + result = new TargetBreak(); + } + @Override public void visit(StaticClassName staticClassName) { result = new TargetClassName(converter.convert(staticClassName.getType())); @@ -306,14 +294,7 @@ public class StatementToTargetExpression implements StatementVisitor { var type = converter.convert(superCall.getType()); var parameters = superCall.arglist.getArguments().stream().map(par -> converter.convert(par.getType())).toList(); - result = new TargetMethodCall( - type, type, - parameters, - new TargetSuper(aSuper), - superCall.getArgumentList().getArguments().stream().map(converter::convert).toList(), - aSuper, - superCall.name, false, false - ); + result = new TargetMethodCall(type, type, parameters, new TargetSuper(aSuper), superCall.getArgumentList().getArguments().stream().map(converter::convert).toList(), aSuper, superCall.name, false, false); } @Override @@ -324,21 +305,19 @@ public class StatementToTargetExpression implements StatementVisitor { @Override public void visit(UnaryExpr unaryExpr) { result = switch (unaryExpr.operation) { - case NOT -> new TargetUnaryOp.Not(converter.convert(unaryExpr.getType()), converter.convert(unaryExpr.expr)); - case MINUS -> new TargetUnaryOp.Negate(converter.convert(unaryExpr.getType()), converter.convert(unaryExpr.expr)); - case PREINCREMENT -> new TargetUnaryOp.PreIncrement(converter.convert(unaryExpr.getType()), converter.convert(unaryExpr.expr)); - case PREDECREMENT -> new TargetUnaryOp.PreDecrement(converter.convert(unaryExpr.getType()), converter.convert(unaryExpr.expr)); - case POSTINCREMENT -> new TargetUnaryOp.PostIncrement(converter.convert(unaryExpr.getType()), converter.convert(unaryExpr.expr)); - case PLUS -> new TargetUnaryOp.Add(converter.convert(unaryExpr.getType()), converter.convert(unaryExpr.expr)); - case POSTDECREMENT -> new TargetUnaryOp.PostDecrement(converter.convert(unaryExpr.getType()), converter.convert(unaryExpr.expr)); + case NOT -> new TargetUnaryOp.Not(converter.convert(unaryExpr.getType()), converter.convert(unaryExpr.expr)); + case MINUS -> new TargetUnaryOp.Negate(converter.convert(unaryExpr.getType()), converter.convert(unaryExpr.expr)); + case PREINCREMENT -> new TargetUnaryOp.PreIncrement(converter.convert(unaryExpr.getType()), converter.convert(unaryExpr.expr)); + case PREDECREMENT -> new TargetUnaryOp.PreDecrement(converter.convert(unaryExpr.getType()), converter.convert(unaryExpr.expr)); + case POSTINCREMENT -> new TargetUnaryOp.PostIncrement(converter.convert(unaryExpr.getType()), converter.convert(unaryExpr.expr)); + case PLUS -> new TargetUnaryOp.Add(converter.convert(unaryExpr.getType()), converter.convert(unaryExpr.expr)); + case POSTDECREMENT -> new TargetUnaryOp.PostDecrement(converter.convert(unaryExpr.getType()), converter.convert(unaryExpr.expr)); }; } @Override public void visit(Literal literal) { - if (literal.value instanceof Integer - || literal.value instanceof Short - || literal.value instanceof Byte) { + if (literal.value instanceof Integer || literal.value instanceof Short || literal.value instanceof Byte) { result = new TargetLiteral.IntLiteral((int) literal.value); } else if (literal.value instanceof Float) { diff --git a/src/main/java/de/dhbwstuttgart/target/generate/TracingStatementVisitor.java b/src/main/java/de/dhbwstuttgart/target/generate/TracingStatementVisitor.java index 6fc9c248..685e9ad2 100644 --- a/src/main/java/de/dhbwstuttgart/target/generate/TracingStatementVisitor.java +++ b/src/main/java/de/dhbwstuttgart/target/generate/TracingStatementVisitor.java @@ -4,9 +4,8 @@ import de.dhbwstuttgart.parser.SyntaxTreeGenerator.AssignToLocal; import de.dhbwstuttgart.syntaxtree.StatementVisitor; import de.dhbwstuttgart.syntaxtree.statement.*; - // This visitor walks the entire tree, individual methods may be overridden -public abstract class TracingStatementVisitor implements StatementVisitor { +public abstract class TracingStatementVisitor implements StatementVisitor { @Override public void visit(MethodCall methodCall) { @@ -102,6 +101,11 @@ public abstract class TracingStatementVisitor implements StatementVisitor { } + @Override + public void visit(Break aBreak) { + + } + @Override public void visit(StaticClassName staticClassName) { diff --git a/src/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java b/src/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java index acdce189..151bc309 100644 --- a/src/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java +++ b/src/main/java/de/dhbwstuttgart/typeinference/typeAlgo/TYPEStmt.java @@ -27,12 +27,12 @@ import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; -public class TYPEStmt implements StatementVisitor{ +public class TYPEStmt implements StatementVisitor { private final TypeInferenceBlockInformation info; private final ConstraintSet constraintsSet = new ConstraintSet(); - public TYPEStmt(TypeInferenceBlockInformation info){ + public TYPEStmt(TypeInferenceBlockInformation info) { this.info = info; } @@ -41,13 +41,11 @@ public class TYPEStmt implements StatementVisitor{ } /** - * Erstellt einen neuen GenericResolver - * Die Idee dieser Datenstruktur ist es, GTVs einen eindeutigen TPH zuzuweisen. - * Bei Methodenaufrufen oder anderen Zugriffen, bei denen alle benutzten GTVs jeweils einen einheitlichen TPH bekommen müssen - * kann diese Klasse eingesetzt werden. Wichtig ist, dass hierfür jeweils eine frische Instanz benutzt wird. + * Erstellt einen neuen GenericResolver Die Idee dieser Datenstruktur ist es, GTVs einen eindeutigen TPH zuzuweisen. Bei Methodenaufrufen oder anderen Zugriffen, bei denen alle benutzten GTVs jeweils einen einheitlichen TPH bekommen müssen kann diese Klasse eingesetzt werden. Wichtig ist, dass hierfür jeweils eine frische Instanz benutzt wird. + * * @return */ - private static GenericsResolver getResolverInstance(){ + private static GenericsResolver getResolverInstance() { return new GenericsResolverSameName(); } @@ -57,8 +55,8 @@ public class TYPEStmt implements StatementVisitor{ @Override public void visit(ArgumentList arglist) { - for(int i = 0;i lambdaParams = lambdaExpression.params.getFormalparalist().stream().map((formalParameter -> formalParameter.getType())).collect(Collectors.toList()); lambdaParams.add(tphRetType); - //lambdaParams.add(0,tphRetType); - constraintsSet.addUndConstraint( - new Pair(lambdaExpression.getType(), - new RefType(new JavaClassName("Fun"+(lambdaParams.size()-1)+"$$"), lambdaParams, new NullToken()), - //new FunN(lambdaParams), - PairOperator.EQUALSDOT)); - constraintsSet.addUndConstraint( - new Pair(lambdaExpression.getReturnType(), - tphRetType,PairOperator.EQUALSDOT)); + // lambdaParams.add(0,tphRetType); + constraintsSet.addUndConstraint(new Pair(lambdaExpression.getType(), new RefType(new JavaClassName("Fun" + (lambdaParams.size() - 1) + "$$"), lambdaParams, new NullToken()), + // new FunN(lambdaParams), + PairOperator.EQUALSDOT)); + constraintsSet.addUndConstraint(new Pair(lambdaExpression.getReturnType(), tphRetType, PairOperator.EQUALSDOT)); - //Constraints des Bodys generieren: + // Constraints des Bodys generieren: TYPEStmt lambdaScope = new TYPEStmt(new TypeInferenceBlockInformation(info, lambdaExpression)); lambdaExpression.methodBody.accept(lambdaScope); constraintsSet.addAll(lambdaScope.getConstraints()); @@ -87,13 +81,12 @@ public class TYPEStmt implements StatementVisitor{ public void visit(Assign assign) { assign.lefSide.accept(this); assign.rightSide.accept(this); - constraintsSet.addUndConstraint(new Pair( - assign.rightSide.getType(), assign.lefSide.getType(), PairOperator.SMALLERDOT)); + constraintsSet.addUndConstraint(new Pair(assign.rightSide.getType(), assign.lefSide.getType(), PairOperator.SMALLERDOT)); } @Override public void visit(Block block) { - for(Statement stmt : block.getStatements()){ + for (Statement stmt : block.getStatements()) { stmt.accept(this); } } @@ -105,23 +98,22 @@ public class TYPEStmt implements StatementVisitor{ @Override public void visit(EmptyStmt emptyStmt) { - //Nothing :) + // Nothing :) } @Override public void visit(FieldVar fieldVar) { fieldVar.receiver.accept(this); Set oderConstraints = new HashSet<>(); - for(FieldAssumption fieldAssumption : info.getFields(fieldVar.fieldVarName)){ + for (FieldAssumption fieldAssumption : info.getFields(fieldVar.fieldVarName)) { Constraint constraint = new Constraint(); GenericsResolver resolver = getResolverInstance(); - constraint.add(new Pair(fieldVar.receiver.getType(), fieldAssumption.getReceiverType(resolver), PairOperator.SMALLERDOT)); //PL 2019-12-09: SMALLERDOT eingefuegt, EQUALSDOT entfernt, wenn ds Field privat ist muesste es EQUALSDOT lauten - constraint.add(new Pair( - fieldVar.getType(), fieldAssumption.getType(resolver), PairOperator.EQUALSDOT)); + constraint.add(new Pair(fieldVar.receiver.getType(), fieldAssumption.getReceiverType(resolver), PairOperator.SMALLERDOT)); // PL 2019-12-09: SMALLERDOT eingefuegt, EQUALSDOT entfernt, wenn ds Field privat ist muesste es EQUALSDOT lauten + constraint.add(new Pair(fieldVar.getType(), fieldAssumption.getType(resolver), PairOperator.EQUALSDOT)); oderConstraints.add(constraint); } - if(oderConstraints.size() == 0) - throw new TypeinferenceException("Kein Feld "+fieldVar.fieldVarName+ " gefunden", fieldVar.getOffset()); + if (oderConstraints.size() == 0) + throw new TypeinferenceException("Kein Feld " + fieldVar.fieldVarName + " gefunden", fieldVar.getOffset()); constraintsSet.addOderConstraint(oderConstraints); } @@ -133,15 +125,15 @@ public class TYPEStmt implements StatementVisitor{ @Override public void visit(IfStmt ifStmt) { RefType booleanType = new RefType(ASTFactory.createClass(java.lang.Boolean.class).getClassName(), new NullToken()); - //Expression inferieren: + // Expression inferieren: ifStmt.expr.accept(this); - //Expression muss boolean sein: + // Expression muss boolean sein: constraintsSet.addUndConstraint(new Pair(ifStmt.expr.getType(), booleanType, PairOperator.EQUALSDOT)); - //Blöcke inferieren: + // Blöcke inferieren: ifStmt.then_block.accept(this); - //Beide Blöcke müssen den gleichen Supertyp haben, welcher den Rückgabetyp des If-Stmts darstellt + // Beide Blöcke müssen den gleichen Supertyp haben, welcher den Rückgabetyp des If-Stmts darstellt constraintsSet.addUndConstraint(new Pair(ifStmt.else_block.getType(), ifStmt.getType(), PairOperator.SMALLERDOT)); - if(ifStmt.else_block != null){ + if (ifStmt.else_block != null) { ifStmt.else_block.accept(this); constraintsSet.addUndConstraint(new Pair(ifStmt.else_block.getType(), ifStmt.getType(), PairOperator.SMALLERDOT)); } @@ -160,50 +152,42 @@ public class TYPEStmt implements StatementVisitor{ @Override public void visit(LocalVarDecl localVarDecl) { - //Hier ist nichts zu tun. Allen lokalen Variablen bekommen beim parsen schon den korrekten Typ + // Hier ist nichts zu tun. Allen lokalen Variablen bekommen beim parsen schon den korrekten Typ } @Override - //Es wird in OderConstraints davon ausgegangen dass die Bedingungen für die Typen der Argumente links stehen - //und die Typen der Rückgabewerte immer rechts stehen (vgl. JavaTXCompiler) + // Es wird in OderConstraints davon ausgegangen dass die Bedingungen für die Typen der Argumente links stehen + // und die Typen der Rückgabewerte immer rechts stehen (vgl. JavaTXCompiler) public void visit(MethodCall methodCall) { - + methodCall.receiver.accept(this); - //Overloading: + // Overloading: Set> methodConstraints = new HashSet<>(); - for(MethodAssumption m : this.getMethods(methodCall.name, methodCall.arglist, info)){ + for (MethodAssumption m : this.getMethods(methodCall.name, methodCall.arglist, info)) { GenericsResolver resolver = getResolverInstance(); Set> oneMethodConstraints = generateConstraint(methodCall, m, info, resolver); methodConstraints.addAll(oneMethodConstraints); - - /* pl 2023-01-20: in generateConstraint bereits umgesetzt - Constraint extendsOneMethodConstraint = oneMethodConstraint.stream() - .map(x -> (x.TA1 instanceof TypePlaceholder && - x.GetOperator() == PairOperator.EQUALSDOT && - !(x.TA2 instanceof TypePlaceholder)) - ? new Pair(x.TA1, new ExtendsWildcardType(x.TA2, x.TA2.getOffset()), PairOperator.EQUALSDOT) - : x) - .collect(Collectors.toCollection(() -> new Constraint(oneMethodConstraint.isInherited()))); - oneMethodConstraint.setExtendConstraint(extendsOneMethodConstraint); - extendsOneMethodConstraint.setExtendConstraint(oneMethodConstraint); - methodConstraints.add(extendsOneMethodConstraint); - */ + + /* + * pl 2023-01-20: in generateConstraint bereits umgesetzt Constraint extendsOneMethodConstraint = oneMethodConstraint.stream() .map(x -> (x.TA1 instanceof TypePlaceholder && x.GetOperator() == PairOperator.EQUALSDOT && !(x.TA2 instanceof TypePlaceholder)) ? new Pair(x.TA1, new ExtendsWildcardType(x.TA2, x.TA2.getOffset()), PairOperator.EQUALSDOT) : x) .collect(Collectors.toCollection(() -> new Constraint(oneMethodConstraint.isInherited()))); + * oneMethodConstraint.setExtendConstraint(extendsOneMethodConstraint); extendsOneMethodConstraint.setExtendConstraint(oneMethodConstraint); methodConstraints.add(extendsOneMethodConstraint); + */ } - if(methodConstraints.size()<1){ - throw new TypeinferenceException("Methode "+methodCall.name+" ist nicht vorhanden!",methodCall.getOffset()); + if (methodConstraints.size() < 1) { + throw new TypeinferenceException("Methode " + methodCall.name + " ist nicht vorhanden!", methodCall.getOffset()); } constraintsSet.addOderConstraint(methodConstraints); } @Override public void visit(NewClass methodCall) { - //Overloading: + // Overloading: Set methodConstraints = new HashSet<>(); - for(MethodAssumption m : this.getConstructors(info, (RefType) methodCall.getType(), methodCall.getArgumentList())){ + for (MethodAssumption m : this.getConstructors(info, (RefType) methodCall.getType(), methodCall.getArgumentList())) { methodConstraints.add(generateConstructorConstraint(methodCall, m, info, getResolverInstance())); } - if(methodConstraints.size()<1){ - throw new TypeinferenceException("Konstruktor in Klasse "+methodCall.getType().toString()+" ist nicht vorhanden!",methodCall.getOffset()); + if (methodConstraints.size() < 1) { + throw new TypeinferenceException("Konstruktor in Klasse " + methodCall.getType().toString() + " ist nicht vorhanden!", methodCall.getOffset()); } constraintsSet.addOderConstraint(methodConstraints); } @@ -226,276 +210,230 @@ public class TYPEStmt implements StatementVisitor{ private final RefType floatt = new RefType(ASTFactory.createClass(Float.class).getClassName(), new NullToken()); private final RefType doublee = new RefType(ASTFactory.createClass(Double.class).getClassName(), new NullToken()); private final RefType string = new RefType(ASTFactory.createClass(String.class).getClassName(), new NullToken()); - private final RefType bool = new RefType(ASTFactory.createClass(Boolean.class).getClassName(), new NullToken()); + private final RefType bool = new RefType(ASTFactory.createClass(Boolean.class).getClassName(), new NullToken()); + @Override public void visit(UnaryExpr unaryExpr) { - if(unaryExpr.operation == UnaryExpr.Operation.POSTDECREMENT || - unaryExpr.operation == UnaryExpr.Operation.POSTINCREMENT || - unaryExpr.operation == UnaryExpr.Operation.PREDECREMENT || - 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 + if (unaryExpr.operation == UnaryExpr.Operation.POSTDECREMENT || unaryExpr.operation == UnaryExpr.Operation.POSTINCREMENT || unaryExpr.operation == UnaryExpr.Operation.PREDECREMENT || 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 constraintsSet.addUndConstraint(new Pair(unaryExpr.expr.getType(), number, PairOperator.SMALLERNEQDOT)); - //The type of the postfix increment expression is the type of the variable + // 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{ + } else { throw new NotImplementedException(); } } @Override - //Es wird in OderConstraints davon ausgegangen dass die Bedingungen für die Typen der Argumente links stehen - //und die Typen der Rückgabewerte immer rechts stehen (vgl. JavaTXCompiler) + // Es wird in OderConstraints davon ausgegangen dass die Bedingungen für die Typen der Argumente links stehen + // und die Typen der Rückgabewerte immer rechts stehen (vgl. JavaTXCompiler) public void visit(BinaryExpr binary) { - binary.lexpr.accept(this); - binary.rexpr.accept(this); - 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)|| - binary.operation.equals(BinaryExpr.Operator.SUB)) { + binary.lexpr.accept(this); + binary.rexpr.accept(this); + if (binary.operation.equals(BinaryExpr.Operator.DIV) || binary.operation.equals(BinaryExpr.Operator.MUL) || binary.operation.equals(BinaryExpr.Operator.MOD) || binary.operation.equals(BinaryExpr.Operator.ADD) || binary.operation.equals(BinaryExpr.Operator.SUB)) { Set> numericAdditionOrStringConcatenation = new HashSet<>(); -// TODO PL 2018-11-06 - - // Auf importierte Typen einschraenken - // pruefen, ob Typen richtig bestimmt werden. - + // TODO PL 2018-11-06 - - //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 + // Auf importierte Typen einschraenken + // pruefen, ob Typen richtig bestimmt werden. + + // 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 Constraint numeric; - //PL eingefuegt 2018-07-17 + // PL eingefuegt 2018-07-17 if (info.getAvailableClasses().stream().map(x -> x.getClassName()).collect(Collectors.toCollection(HashSet::new)).contains(bytee.getName())) { - numeric = new Constraint<>(); - numeric.add(new Pair(binary.lexpr.getType(), bytee, PairOperator.SMALLERDOT)); - numeric.add(new Pair(binary.rexpr.getType(), bytee, PairOperator.SMALLERDOT)); - numeric.add(new Pair(binary.getType(), integer, PairOperator.EQUALSDOT)); + numeric = new Constraint<>(); + numeric.add(new Pair(binary.lexpr.getType(), bytee, PairOperator.SMALLERDOT)); + numeric.add(new Pair(binary.rexpr.getType(), bytee, PairOperator.SMALLERDOT)); + numeric.add(new Pair(binary.getType(), integer, PairOperator.EQUALSDOT)); numericAdditionOrStringConcatenation.add(numeric); } - //PL eingefuegt 2018-07-17 + // PL eingefuegt 2018-07-17 if (info.getAvailableClasses().stream().map(x -> x.getClassName()).collect(Collectors.toCollection(HashSet::new)).contains(shortt.getName())) { - numeric = new Constraint<>(); - numeric.add(new Pair(binary.lexpr.getType(), shortt, PairOperator.SMALLERDOT)); - numeric.add(new Pair(binary.rexpr.getType(), shortt, PairOperator.SMALLERDOT)); - numeric.add(new Pair(binary.getType(), integer, PairOperator.EQUALSDOT)); - numericAdditionOrStringConcatenation.add(numeric); + numeric = new Constraint<>(); + numeric.add(new Pair(binary.lexpr.getType(), shortt, PairOperator.SMALLERDOT)); + numeric.add(new Pair(binary.rexpr.getType(), shortt, PairOperator.SMALLERDOT)); + numeric.add(new Pair(binary.getType(), integer, PairOperator.EQUALSDOT)); + numericAdditionOrStringConcatenation.add(numeric); } - //PL eingefuegt 2018-07-17 + // PL eingefuegt 2018-07-17 if (info.getAvailableClasses().stream().map(x -> x.getClassName()).collect(Collectors.toCollection(HashSet::new)).contains(integer.getName())) { - numeric = new Constraint<>(); - numeric.add(new Pair(binary.lexpr.getType(), integer, PairOperator.SMALLERDOT)); - numeric.add(new Pair(binary.rexpr.getType(), integer, PairOperator.SMALLERDOT)); - numeric.add(new Pair(integer, binary.getType(), PairOperator.EQUALSDOT)); - numericAdditionOrStringConcatenation.add(numeric); + numeric = new Constraint<>(); + numeric.add(new Pair(binary.lexpr.getType(), integer, PairOperator.SMALLERDOT)); + numeric.add(new Pair(binary.rexpr.getType(), integer, PairOperator.SMALLERDOT)); + numeric.add(new Pair(integer, binary.getType(), PairOperator.EQUALSDOT)); + numericAdditionOrStringConcatenation.add(numeric); } - //PL eingefuegt 2018-07-17 + // PL eingefuegt 2018-07-17 if (info.getAvailableClasses().stream().map(x -> x.getClassName()).collect(Collectors.toCollection(HashSet::new)).contains(longg.getName())) { - numeric = new Constraint<>(); - numeric.add(new Pair(binary.lexpr.getType(), longg, PairOperator.SMALLERDOT)); - numeric.add(new Pair(binary.rexpr.getType(), longg, PairOperator.SMALLERDOT)); - numeric.add(new Pair(longg, binary.getType(), PairOperator.EQUALSDOT)); - numericAdditionOrStringConcatenation.add(numeric); + numeric = new Constraint<>(); + numeric.add(new Pair(binary.lexpr.getType(), longg, PairOperator.SMALLERDOT)); + numeric.add(new Pair(binary.rexpr.getType(), longg, PairOperator.SMALLERDOT)); + numeric.add(new Pair(longg, binary.getType(), PairOperator.EQUALSDOT)); + numericAdditionOrStringConcatenation.add(numeric); } - //PL eingefuegt 2018-07-17 + // PL eingefuegt 2018-07-17 if (info.getAvailableClasses().stream().map(x -> x.getClassName()).collect(Collectors.toCollection(HashSet::new)).contains(floatt.getName())) { - numeric = new Constraint<>(); - numeric.add(new Pair(binary.lexpr.getType(), floatt, PairOperator.SMALLERDOT)); - numeric.add(new Pair(binary.rexpr.getType(), floatt, PairOperator.SMALLERDOT)); - numeric.add(new Pair(floatt, binary.getType(), PairOperator.EQUALSDOT)); - numericAdditionOrStringConcatenation.add(numeric); + numeric = new Constraint<>(); + numeric.add(new Pair(binary.lexpr.getType(), floatt, PairOperator.SMALLERDOT)); + numeric.add(new Pair(binary.rexpr.getType(), floatt, PairOperator.SMALLERDOT)); + numeric.add(new Pair(floatt, binary.getType(), PairOperator.EQUALSDOT)); + numericAdditionOrStringConcatenation.add(numeric); } - //PL eingefuegt 2018-07-17 + // PL eingefuegt 2018-07-17 if (info.getAvailableClasses().stream().map(x -> x.getClassName()).collect(Collectors.toCollection(HashSet::new)).contains(doublee.getName())) { - numeric = new Constraint<>(); - numeric.add(new Pair(binary.lexpr.getType(), doublee, PairOperator.SMALLERDOT)); - numeric.add(new Pair(binary.rexpr.getType(), doublee, PairOperator.SMALLERDOT)); - numeric.add(new Pair(doublee, binary.getType(), PairOperator.EQUALSDOT)); - numericAdditionOrStringConcatenation.add(numeric); + numeric = new Constraint<>(); + numeric.add(new Pair(binary.lexpr.getType(), doublee, PairOperator.SMALLERDOT)); + numeric.add(new Pair(binary.rexpr.getType(), doublee, PairOperator.SMALLERDOT)); + numeric.add(new Pair(doublee, binary.getType(), PairOperator.EQUALSDOT)); + numericAdditionOrStringConcatenation.add(numeric); } - /* PL auskommentiert Anfang 2018-07-17 /* - In Java passiert bei den binären Operatoren eine sogenannte Type Promotion: - https://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.6.2 - Das bedeutet, dass Java die Typen je nach belieben castet, so lange sie nur von Number erben - - numeric = new Constraint<>(); - numeric.add(new Pair(binary.getType(), number, PairOperator.SMALLERDOT)); - numericAdditionOrStringConcatenation.add(numeric); - * PL auskommentiert Ende 2018-07-17 */ - - if(binary.operation.equals(BinaryExpr.Operator.ADD)) { - //Dann kann der Ausdruck auch das aneinanderfügen zweier Strings sein: ("a" + "b") oder (1 + 2) - if (info.getAvailableClasses().stream().map(x -> x.getClassName()).collect(Collectors.toCollection(HashSet::new)).contains(string.getName())) { - 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(string, binary.getType(), PairOperator.EQUALSDOT)); - numericAdditionOrStringConcatenation.add(stringConcat); - } + * PL auskommentiert Anfang 2018-07-17 /* In Java passiert bei den binären Operatoren eine sogenannte Type Promotion: https://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.6.2 Das bedeutet, dass Java die Typen je nach belieben castet, so lange sie nur von Number erben + * + * numeric = new Constraint<>(); numeric.add(new Pair(binary.getType(), number, PairOperator.SMALLERDOT)); numericAdditionOrStringConcatenation.add(numeric); PL auskommentiert Ende 2018-07-17 + */ + + if (binary.operation.equals(BinaryExpr.Operator.ADD)) { + // Dann kann der Ausdruck auch das aneinanderfügen zweier Strings sein: ("a" + "b") oder (1 + 2) + if (info.getAvailableClasses().stream().map(x -> x.getClassName()).collect(Collectors.toCollection(HashSet::new)).contains(string.getName())) { + 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(string, binary.getType(), PairOperator.EQUALSDOT)); + numericAdditionOrStringConcatenation.add(stringConcat); + } } - if(numericAdditionOrStringConcatenation.size()<1){ + if (numericAdditionOrStringConcatenation.size() < 1) { throw new TypeinferenceException("Kein Typ für " + binary.operation.toString() + " vorhanden", binary.getOffset()); } constraintsSet.addOderConstraint(numericAdditionOrStringConcatenation); - }else if(binary.operation.equals(BinaryExpr.Operator.LESSEQUAL) || - binary.operation.equals(BinaryExpr.Operator.BIGGEREQUAL) || - binary.operation.equals(BinaryExpr.Operator.BIGGERTHAN) || - binary.operation.equals(BinaryExpr.Operator.LESSTHAN)) { - /* //eingefuegt PL 2018-05-24 - Set> numericRelationConcatenation = new HashSet<>(); - Constraint numeric = new Constraint<>(); - numeric.add(new Pair(binary.lexpr.getType(), bytee, PairOperator.SMALLERDOT)); - numeric.add(new Pair(binary.rexpr.getType(), bytee, PairOperator.SMALLERDOT)); - numeric.add(new Pair(binary.getType(), bool, PairOperator.SMALLERDOT)); - numericRelationConcatenation.add(numeric); - numeric = new Constraint<>(); - numeric.add(new Pair(binary.lexpr.getType(), shortt, PairOperator.SMALLERDOT)); - numeric.add(new Pair(binary.rexpr.getType(), shortt, PairOperator.SMALLERDOT)); - numeric.add(new Pair(binary.getType(), bool, PairOperator.SMALLERDOT)); - numericRelationConcatenation.add(numeric); - numeric = new Constraint<>(); - numeric.add(new Pair(binary.lexpr.getType(), integer, PairOperator.SMALLERDOT)); - numeric.add(new Pair(binary.rexpr.getType(), integer, PairOperator.SMALLERDOT)); - numeric.add(new Pair(binary.getType(), bool, PairOperator.SMALLERDOT)); - numericRelationConcatenation.add(numeric); - numeric = new Constraint<>(); - numeric.add(new Pair(binary.lexpr.getType(), longg, PairOperator.SMALLERDOT)); - numeric.add(new Pair(binary.rexpr.getType(), longg, PairOperator.SMALLERDOT)); - numeric.add(new Pair(binary.getType(), bool, PairOperator.SMALLERDOT)); - numericRelationConcatenation.add(numeric); - numeric = new Constraint<>(); - numeric.add(new Pair(binary.lexpr.getType(), floatt, PairOperator.SMALLERDOT)); - numeric.add(new Pair(binary.rexpr.getType(), floatt, PairOperator.SMALLERDOT)); - numeric.add(new Pair(binary.getType(), bool, PairOperator.SMALLERDOT)); - numericRelationConcatenation.add(numeric); - numeric = new Constraint<>(); - numeric.add(new Pair(binary.lexpr.getType(), doublee, PairOperator.SMALLERDOT)); - numeric.add(new Pair(binary.rexpr.getType(), doublee, PairOperator.SMALLERDOT)); - numeric.add(new Pair(binary.getType(), bool, PairOperator.SMALLERDOT)); - numericRelationConcatenation.add(numeric); - - //***ACHTUNG: Moeglicherweise oder und und-Contraint falsch - constraintsSet.addOderConstraint(numericRelationConcatenation); - //***ACHTUNG: Moeglicherweise oder und und-Contraint falsch - */ - //Testeise eingefuegt PL 2018-05-24 - //Hier sollte evtl. noch importe angefragt werden PL 2019-05-07 + } else if (binary.operation.equals(BinaryExpr.Operator.LESSEQUAL) || binary.operation.equals(BinaryExpr.Operator.BIGGEREQUAL) || binary.operation.equals(BinaryExpr.Operator.BIGGERTHAN) || binary.operation.equals(BinaryExpr.Operator.LESSTHAN)) { + /* + * //eingefuegt PL 2018-05-24 Set> numericRelationConcatenation = new HashSet<>(); Constraint numeric = new Constraint<>(); numeric.add(new Pair(binary.lexpr.getType(), bytee, PairOperator.SMALLERDOT)); numeric.add(new Pair(binary.rexpr.getType(), bytee, PairOperator.SMALLERDOT)); numeric.add(new Pair(binary.getType(), bool, PairOperator.SMALLERDOT)); numericRelationConcatenation.add(numeric); numeric = new Constraint<>(); numeric.add(new Pair(binary.lexpr.getType(), + * shortt, PairOperator.SMALLERDOT)); numeric.add(new Pair(binary.rexpr.getType(), shortt, PairOperator.SMALLERDOT)); numeric.add(new Pair(binary.getType(), bool, PairOperator.SMALLERDOT)); numericRelationConcatenation.add(numeric); numeric = new Constraint<>(); numeric.add(new Pair(binary.lexpr.getType(), integer, PairOperator.SMALLERDOT)); numeric.add(new Pair(binary.rexpr.getType(), integer, PairOperator.SMALLERDOT)); numeric.add(new Pair(binary.getType(), bool, PairOperator.SMALLERDOT)); + * numericRelationConcatenation.add(numeric); numeric = new Constraint<>(); numeric.add(new Pair(binary.lexpr.getType(), longg, PairOperator.SMALLERDOT)); numeric.add(new Pair(binary.rexpr.getType(), longg, PairOperator.SMALLERDOT)); numeric.add(new Pair(binary.getType(), bool, PairOperator.SMALLERDOT)); numericRelationConcatenation.add(numeric); numeric = new Constraint<>(); numeric.add(new Pair(binary.lexpr.getType(), floatt, PairOperator.SMALLERDOT)); numeric.add(new + * Pair(binary.rexpr.getType(), floatt, PairOperator.SMALLERDOT)); numeric.add(new Pair(binary.getType(), bool, PairOperator.SMALLERDOT)); numericRelationConcatenation.add(numeric); numeric = new Constraint<>(); numeric.add(new Pair(binary.lexpr.getType(), doublee, PairOperator.SMALLERDOT)); numeric.add(new Pair(binary.rexpr.getType(), doublee, PairOperator.SMALLERDOT)); numeric.add(new Pair(binary.getType(), bool, PairOperator.SMALLERDOT)); numericRelationConcatenation.add(numeric); + * + * //***ACHTUNG: Moeglicherweise oder und und-Contraint falsch constraintsSet.addOderConstraint(numericRelationConcatenation); //***ACHTUNG: Moeglicherweise oder und und-Contraint falsch + */ + // Testeise eingefuegt PL 2018-05-24 + // Hier sollte evtl. noch importe angefragt werden PL 2019-05-07 constraintsSet.addUndConstraint(new Pair(binary.lexpr.getType(), number, PairOperator.SMALLERNEQDOT)); constraintsSet.addUndConstraint(new Pair(binary.rexpr.getType(), number, PairOperator.SMALLERNEQDOT)); - //Rückgabetyp ist Boolean + // Rückgabetyp ist Boolean constraintsSet.addUndConstraint(new Pair(bool, binary.getType(), PairOperator.EQUALSDOT)); - //auskommentiert PL 2018-05-24 - //constraintsSet.addUndConstraint(new Pair(binary.lexpr.getType(), number, PairOperator.SMALLERDOT)); - //constraintsSet.addUndConstraint(new Pair(binary.rexpr.getType(), number, PairOperator.SMALLERDOT)); - //Rückgabetyp ist Boolean - //constraintsSet.addUndConstraint(new Pair(bool, binary.getType(), PairOperator.EQUALSDOT)); - }else if(binary.operation.equals(BinaryExpr.Operator.EQUAL) || binary.operation.equals(BinaryExpr.Operator.NOTEQUAL)){ - /*Auszug aus https://docs.oracle.com/javase/specs/jls/se9/html/jls-15.html#jls-15.21 - The equality operators may be used to compare two operands that are convertible (§5.1.8) to numeric type, or two operands of type boolean or Boolean, or two operands that are each of either reference type or the null type. All other cases result in a compile-time error. + // auskommentiert PL 2018-05-24 + // constraintsSet.addUndConstraint(new Pair(binary.lexpr.getType(), number, PairOperator.SMALLERDOT)); + // constraintsSet.addUndConstraint(new Pair(binary.rexpr.getType(), number, PairOperator.SMALLERDOT)); + // Rückgabetyp ist Boolean + // constraintsSet.addUndConstraint(new Pair(bool, binary.getType(), PairOperator.EQUALSDOT)); + } else if (binary.operation.equals(BinaryExpr.Operator.EQUAL) || binary.operation.equals(BinaryExpr.Operator.NOTEQUAL)) { + /* + * Auszug aus https://docs.oracle.com/javase/specs/jls/se9/html/jls-15.html#jls-15.21 The equality operators may be used to compare two operands that are convertible (§5.1.8) to numeric type, or two operands of type boolean or Boolean, or two operands that are each of either reference type or the null type. All other cases result in a compile-time error. */ - //Der Equals Operator geht mit fast allen Typen, daher werden hier keine Constraints gesetzt + // Der Equals Operator geht mit fast allen Typen, daher werden hier keine Constraints gesetzt constraintsSet.addUndConstraint(new Pair(bool, binary.getType(), PairOperator.EQUALSDOT)); - }else{ - throw new NotImplementedException(); + } else { + throw new NotImplementedException(); } } @Override public void visit(Literal literal) { - //Nothing to do here. Literale erzeugen keine Constraints - //PL 2018-06-23 Sie haben einen Typ. Der muesste hier eingefuegt werden - //wie hier fuer double gezeigt. Im Momment auskommentiert, weil zu wenige Literaltypen - //funktionieren - if (literal.value instanceof Short) { - constraintsSet.addUndConstraint(new Pair(literal.getType(), shortt, PairOperator.EQUALSDOT)); - return; - } - if (literal.value instanceof Byte) { - constraintsSet.addUndConstraint(new Pair(literal.getType(), bytee, PairOperator.EQUALSDOT)); - return; - } - if (literal.value instanceof Float) { - constraintsSet.addUndConstraint(new Pair(literal.getType(), floatt, PairOperator.EQUALSDOT)); - return; - } - if (literal.value instanceof Double) { - constraintsSet.addUndConstraint(new Pair(literal.getType(), doublee, PairOperator.EQUALSDOT)); - return; - } - if (literal.value instanceof Long) { - constraintsSet.addUndConstraint(new Pair(literal.getType(), longg, PairOperator.EQUALSDOT)); - return; - } - if (literal.value instanceof Integer) { - //constraintsSet.addUndConstraint(new Pair(literal.getType(),integer, PairOperator.EQUALSDOT)); - // /* - HashSet clNames = info.getAvailableClasses().stream().map(x -> x.getClassName()).collect(Collectors.toCollection(HashSet::new)); - Set oderConstraints = new HashSet<>(); - Constraint constraint = new Constraint(); - constraint.add(new Pair(literal.getType(), integer, PairOperator.EQUALSDOT)); - oderConstraints.add(constraint); - if (clNames.stream().filter(x -> x.toString().equals("java.lang.Double")).findAny().isPresent()) { - constraint = new Constraint(); - constraint.add(new Pair(literal.getType(), doublee, PairOperator.EQUALSDOT)); - oderConstraints.add(constraint); - } - if (clNames.stream().filter(x -> x.toString().equals("java.lang.Long")).findAny().isPresent()) { - constraint = new Constraint(); - constraint.add(new Pair(literal.getType(), longg, PairOperator.EQUALSDOT)); - oderConstraints.add(constraint); - } - if (clNames.stream().filter(x -> x.toString().equals("java.lang.Float")).findAny().isPresent()) { - constraint = new Constraint(); - constraint.add(new Pair(literal.getType(), floatt, PairOperator.EQUALSDOT)); - oderConstraints.add(constraint); - } - if (clNames.stream().filter(x -> x.toString().equals("java.lang.Short")).findAny().isPresent()) { - constraint = new Constraint(); - constraint.add(new Pair(literal.getType(), shortt, PairOperator.EQUALSDOT)); - oderConstraints.add(constraint); - } - if (clNames.stream().filter(x -> x.toString().equals("java.lang.Byte")).findAny().isPresent()) { - constraint = new Constraint(); - constraint.add(new Pair(literal.getType(), bytee, PairOperator.EQUALSDOT)); - oderConstraints.add(constraint); - } - constraintsSet.addOderConstraint(oderConstraints); - // */ - return; - } - if (literal.value instanceof Short) { - constraintsSet.addUndConstraint(new Pair(literal.getType(),shortt, PairOperator.EQUALSDOT)); - return; - } - if (literal.value instanceof Byte) { - constraintsSet.addUndConstraint(new Pair(literal.getType(),bytee, PairOperator.EQUALSDOT)); - return; - } - if (literal.value instanceof Float) { - constraintsSet.addUndConstraint(new Pair(literal.getType(),floatt, PairOperator.EQUALSDOT)); - return; - } - if (literal.value instanceof String) { - constraintsSet.addUndConstraint(new Pair(literal.getType(),string, PairOperator.EQUALSDOT)); - return; - } - if (literal.value instanceof Boolean) { - constraintsSet.addUndConstraint(new Pair(literal.getType(),bool, PairOperator.EQUALSDOT)); - return; - } - else { - throw new NotImplementedException(); - } + // Nothing to do here. Literale erzeugen keine Constraints + // PL 2018-06-23 Sie haben einen Typ. Der muesste hier eingefuegt werden + // wie hier fuer double gezeigt. Im Momment auskommentiert, weil zu wenige Literaltypen + // funktionieren + if (literal.value instanceof Short) { + constraintsSet.addUndConstraint(new Pair(literal.getType(), shortt, PairOperator.EQUALSDOT)); + return; + } + if (literal.value instanceof Byte) { + constraintsSet.addUndConstraint(new Pair(literal.getType(), bytee, PairOperator.EQUALSDOT)); + return; + } + if (literal.value instanceof Float) { + constraintsSet.addUndConstraint(new Pair(literal.getType(), floatt, PairOperator.EQUALSDOT)); + return; + } + if (literal.value instanceof Double) { + constraintsSet.addUndConstraint(new Pair(literal.getType(), doublee, PairOperator.EQUALSDOT)); + return; + } + if (literal.value instanceof Long) { + constraintsSet.addUndConstraint(new Pair(literal.getType(), longg, PairOperator.EQUALSDOT)); + return; + } + if (literal.value instanceof Integer) { + // constraintsSet.addUndConstraint(new Pair(literal.getType(),integer, PairOperator.EQUALSDOT)); + // /* + HashSet clNames = info.getAvailableClasses().stream().map(x -> x.getClassName()).collect(Collectors.toCollection(HashSet::new)); + Set oderConstraints = new HashSet<>(); + Constraint constraint = new Constraint(); + constraint.add(new Pair(literal.getType(), integer, PairOperator.EQUALSDOT)); + oderConstraints.add(constraint); + if (clNames.stream().filter(x -> x.toString().equals("java.lang.Double")).findAny().isPresent()) { + constraint = new Constraint(); + constraint.add(new Pair(literal.getType(), doublee, PairOperator.EQUALSDOT)); + oderConstraints.add(constraint); + } + if (clNames.stream().filter(x -> x.toString().equals("java.lang.Long")).findAny().isPresent()) { + constraint = new Constraint(); + constraint.add(new Pair(literal.getType(), longg, PairOperator.EQUALSDOT)); + oderConstraints.add(constraint); + } + if (clNames.stream().filter(x -> x.toString().equals("java.lang.Float")).findAny().isPresent()) { + constraint = new Constraint(); + constraint.add(new Pair(literal.getType(), floatt, PairOperator.EQUALSDOT)); + oderConstraints.add(constraint); + } + if (clNames.stream().filter(x -> x.toString().equals("java.lang.Short")).findAny().isPresent()) { + constraint = new Constraint(); + constraint.add(new Pair(literal.getType(), shortt, PairOperator.EQUALSDOT)); + oderConstraints.add(constraint); + } + if (clNames.stream().filter(x -> x.toString().equals("java.lang.Byte")).findAny().isPresent()) { + constraint = new Constraint(); + constraint.add(new Pair(literal.getType(), bytee, PairOperator.EQUALSDOT)); + oderConstraints.add(constraint); + } + constraintsSet.addOderConstraint(oderConstraints); + // */ + return; + } + if (literal.value instanceof Short) { + constraintsSet.addUndConstraint(new Pair(literal.getType(), shortt, PairOperator.EQUALSDOT)); + return; + } + if (literal.value instanceof Byte) { + constraintsSet.addUndConstraint(new Pair(literal.getType(), bytee, PairOperator.EQUALSDOT)); + return; + } + if (literal.value instanceof Float) { + constraintsSet.addUndConstraint(new Pair(literal.getType(), floatt, PairOperator.EQUALSDOT)); + return; + } + if (literal.value instanceof String) { + constraintsSet.addUndConstraint(new Pair(literal.getType(), string, PairOperator.EQUALSDOT)); + return; + } + if (literal.value instanceof Boolean) { + constraintsSet.addUndConstraint(new Pair(literal.getType(), bool, PairOperator.EQUALSDOT)); + return; + } else { + throw new NotImplementedException(); + } } @Override public void visit(Return returnExpr) { returnExpr.retexpr.accept(this); - constraintsSet.addUndConstraint(new Pair(returnExpr.getType(),info.getCurrentTypeScope().getReturnType(), PairOperator.SMALLERDOT)); + constraintsSet.addUndConstraint(new Pair(returnExpr.getType(), info.getCurrentTypeScope().getReturnType(), PairOperator.SMALLERDOT)); } @Override @@ -503,9 +441,14 @@ public class TYPEStmt implements StatementVisitor{ visit((Return) aReturn); } + @Override + public void visit(Break aBreak) { + + } + @Override public void visit(StaticClassName staticClassName) { - //Hier entstehen keine Constraints + // Hier entstehen keine Constraints } @Override @@ -515,15 +458,14 @@ public class TYPEStmt implements StatementVisitor{ @Override public void visit(This aThis) { - //Im Falle von this, müssen die Generics in der Klasse als RefTypes behandelt werden. + // Im Falle von this, müssen die Generics in der Klasse als RefTypes behandelt werden. ClassOrInterface currentClass = info.getCurrentClass(); List params = new ArrayList<>(); - for(GenericTypeVar gtv : currentClass.getGenerics()){ + for (GenericTypeVar gtv : currentClass.getGenerics()) { params.add(new GenericRefType(gtv.getName(), aThis.getOffset())); } RefType thisType = new RefType(currentClass.getClassName(), params, aThis.getOffset()); - constraintsSet.addUndConstraint(new Pair( - aThis.getType(), thisType, PairOperator.EQUALSDOT)); + constraintsSet.addUndConstraint(new Pair(aThis.getType(), thisType, PairOperator.EQUALSDOT)); } private static TypeScope createNullTypeScope() { @@ -543,11 +485,11 @@ public class TYPEStmt implements StatementVisitor{ @Override public void visit(WhileStmt whileStmt) { RefType booleanType = new RefType(ASTFactory.createClass(java.lang.Boolean.class).getClassName(), new NullToken()); - //Expression inferieren: + // Expression inferieren: whileStmt.expr.accept(this); - //Expression muss boolean sein: + // Expression muss boolean sein: constraintsSet.addUndConstraint(new Pair(whileStmt.expr.getType(), booleanType, PairOperator.EQUALSDOT)); - //LoopBlock inferieren: + // LoopBlock inferieren: whileStmt.loopBlock.accept(this); } @@ -558,153 +500,138 @@ public class TYPEStmt implements StatementVisitor{ @Override public void visit(AssignToField assignLeftSide) { - //Hier ist kein Code nötig. Es werden keine extra Constraints generiert - //HIER muss Code rein PL 2018-10-24 - assignLeftSide.field.accept(this); + // Hier ist kein Code nötig. Es werden keine extra Constraints generiert + // HIER muss Code rein PL 2018-10-24 + assignLeftSide.field.accept(this); } @Override public void visit(AssignToLocal assignLeftSide) { - //Hier ist kein Code nötig. Es werden keine extra Constraints generiert + // Hier ist kein Code nötig. Es werden keine extra Constraints generiert } @Override public void visit(SuperCall superCall) { - //TODO: Für einen super-Call werden keine Constraints erzeugt bisher + // TODO: Für einen super-Call werden keine Constraints erzeugt bisher } /* - METHOD CALL Section: + * METHOD CALL Section: */ - protected Set> generateConstraint(MethodCall forMethod, MethodAssumption assumption, - TypeInferenceBlockInformation info, GenericsResolver resolver){ + protected Set> generateConstraint(MethodCall forMethod, MethodAssumption assumption, TypeInferenceBlockInformation info, GenericsResolver resolver) { Constraint methodConstraint, extendsMethodConstraint; methodConstraint = new Constraint<>(assumption.isInherited()); extendsMethodConstraint = new Constraint<>(assumption.isInherited());// PL 2023-01-24: Ersetzt die Dopplung in visit(MethodCall) - + ClassOrInterface receiverCl = assumption.getReceiver(); /* - List params = new ArrayList<>(); - for(GenericTypeVar gtv : receiverCl.getGenerics()){ - //Die Generics werden alle zu TPHs umgewandelt. - params.add(resolver.resolve(gtv.getName())); - } + * List params = new ArrayList<>(); for(GenericTypeVar gtv : receiverCl.getGenerics()){ //Die Generics werden alle zu TPHs umgewandelt. params.add(resolver.resolve(gtv.getName())); } + * + * RefTypeOrTPHOrWildcardOrGeneric receiverType = new RefType(assumption.getReceiver().getClassName(), params, forMethod.getOffset()); + */ - RefTypeOrTPHOrWildcardOrGeneric receiverType = new RefType(assumption.getReceiver().getClassName(), params, forMethod.getOffset()); - */ - RefTypeOrTPHOrWildcardOrGeneric receiverType = assumption.getReceiverType(resolver); - methodConstraint.add(new Pair(forMethod.receiver.getType(), receiverType, PairOperator.EQUALSDOT));//PL 2020-03-17 SMALLERDOT in EQUALSDOT umgewandelt, weil alle geerbten Methoden in den jeweilen Klassen enthalten sind. - - //PL 2023-01-24: dafuer ? extends receiverType noch ergaenzt + methodConstraint.add(new Pair(forMethod.receiver.getType(), receiverType, PairOperator.EQUALSDOT));// PL 2020-03-17 SMALLERDOT in EQUALSDOT umgewandelt, weil alle geerbten Methoden in den jeweilen Klassen enthalten sind. + + // PL 2023-01-24: dafuer ? extends receiverType noch ergaenzt extendsMethodConstraint.add(new Pair(forMethod.receiver.getType(), new ExtendsWildcardType(receiverType, receiverType.getOffset()), PairOperator.EQUALSDOT)); - - //gegenseite Verschraenkung der beiden Mengen von Typannahmen + + // gegenseite Verschraenkung der beiden Mengen von Typannahmen methodConstraint.setExtendConstraint(extendsMethodConstraint); extendsMethodConstraint.setExtendConstraint(methodConstraint); - - //Fuer Bytecodegenerierung PL 2020-03-09 wird derzeit nicht benutzt ANFANG - //methodConstraint.add(new Pair(forMethod.receiverType, retType, - // PairOperator.EQUALSDOT)); - //Fuer Bytecodegenerierung PL 2020-03-09 wird derzeit nicht benutzt ENDE - - + + // Fuer Bytecodegenerierung PL 2020-03-09 wird derzeit nicht benutzt ANFANG + // methodConstraint.add(new Pair(forMethod.receiverType, retType, + // PairOperator.EQUALSDOT)); + // Fuer Bytecodegenerierung PL 2020-03-09 wird derzeit nicht benutzt ENDE + methodConstraint.add(new Pair(assumption.getReturnType(resolver), forMethod.getType(), PairOperator.SMALLERDOT)); extendsMethodConstraint.add(new Pair(assumption.getReturnType(resolver), forMethod.getType(), PairOperator.SMALLERDOT)); - - //methodConstraint.add(new Pair(assumption.getReturnType(resolver), forMethod.getType(), PairOperator.EQUALSDOT)); - //extendsMethodConstraint.add(new Pair(assumption.getReturnType(resolver), forMethod.getType(), PairOperator.EQUALSDOT)); - - ((TypePlaceholder)forMethod.getType()).setOrCons((byte)-1);//fuer Maximums-Bestimmung - + + // methodConstraint.add(new Pair(assumption.getReturnType(resolver), forMethod.getType(), PairOperator.EQUALSDOT)); + // extendsMethodConstraint.add(new Pair(assumption.getReturnType(resolver), forMethod.getType(), PairOperator.EQUALSDOT)); + + ((TypePlaceholder) forMethod.getType()).setOrCons((byte) -1);// fuer Maximums-Bestimmung + Set parameterContraints = generateParameterConstraints(forMethod, assumption, info, resolver); - + methodConstraint.addAll(parameterContraints); extendsMethodConstraint.addAll(parameterContraints); - + Set methodSignatureConstraint = generatemethodSignatureConstraint(forMethod, assumption, info, resolver); - + System.out.println("methodSignatureConstraint; " + methodSignatureConstraint); - + methodConstraint.setmethodSignatureConstraint(methodSignatureConstraint); extendsMethodConstraint.setmethodSignatureConstraint(methodSignatureConstraint); - + Set> ret = new HashSet<>(); ret.add(methodConstraint); ret.add(extendsMethodConstraint); return ret; } - protected Set generateParameterConstraints(MethodCall foMethod, MethodAssumption assumption, - TypeInferenceBlockInformation info, GenericsResolver resolver) { + protected Set generateParameterConstraints(MethodCall foMethod, MethodAssumption assumption, TypeInferenceBlockInformation info, GenericsResolver resolver) { Set ret = new HashSet<>(); - for(int i = 0;i generatemethodSignatureConstraint(MethodCall foMethod, MethodAssumption assumption, - TypeInferenceBlockInformation info, GenericsResolver resolver) { - Set ret = new HashSet<>(); - - for(int i = 0; i generatemethodSignatureConstraint(MethodCall foMethod, MethodAssumption assumption, TypeInferenceBlockInformation info, GenericsResolver resolver) { + Set ret = new HashSet<>(); + + for (int i = 0; i < foMethod.arglist.getArguments().size(); i++) { + + // Zuordnung von MethoCall.signature (Argumenttypen) zu der Argumenttypen der ausgewaehlten Methode (assumption.params) + ret.add(new Pair(foMethod.signature.get(i), assumption.getArgTypes().get(i), PairOperator.EQUALSDOT)); + + } + + // Zuordnung von MethodCall.signature(ReturnType) zu dem ReturnType der ausgewaehlten Methode (assumption.returnType) System.out.println(foMethod.name); - ret.add(new Pair(foMethod.signature.get(foMethod.signature.size()-1), assumption.getReturnType(), PairOperator.EQUALSDOT)); - return ret; + ret.add(new Pair(foMethod.signature.get(foMethod.signature.size() - 1), assumption.getReturnType(), PairOperator.EQUALSDOT)); + return ret; } public static List getMethods(String name, int numArgs, TypeInferenceBlockInformation info) { List ret = new ArrayList<>(); - //TODO: apply Methoden wieder anfügen. Diese könnten möglicherweise auch in den Assumptions auftauchen (überdenken) - if(name.equals("apply")){ + // TODO: apply Methoden wieder anfügen. Diese könnten möglicherweise auch in den Assumptions auftauchen (überdenken) + if (name.equals("apply")) { List funNParams = new ArrayList<>(); - for(int i = 0; i< numArgs + 1 ; i++){ - //funNParams.add(TypePlaceholder.fresh(new NullToken())); - funNParams.add(new GenericRefType(NameGenerator.makeNewName(), - new NullToken())); + for (int i = 0; i < numArgs + 1; i++) { + // funNParams.add(TypePlaceholder.fresh(new NullToken())); + funNParams.add(new GenericRefType(NameGenerator.makeNewName(), new NullToken())); } - funNParams.get(funNParams.size()-1); - ret.add(new MethodAssumption(new FunNClass(funNParams), funNParams.get(funNParams.size()-1), funNParams.subList(0, funNParams.size()-1), - new TypeScope() { - @Override - public Iterable getGenerics() { - throw new NotImplementedException(); - } + funNParams.get(funNParams.size() - 1); + ret.add(new MethodAssumption(new FunNClass(funNParams), funNParams.get(funNParams.size() - 1), funNParams.subList(0, funNParams.size() - 1), new TypeScope() { + @Override + public Iterable getGenerics() { + throw new NotImplementedException(); + } - @Override - public RefTypeOrTPHOrWildcardOrGeneric getReturnType() { - throw new NotImplementedException(); - } - }, false)); + @Override + public RefTypeOrTPHOrWildcardOrGeneric getReturnType() { + throw new NotImplementedException(); + } + }, false)); } - for(ClassOrInterface cl : info.getAvailableClasses()){ - for(Method m : cl.getMethods()){ - if(m.getName().equals(name) && - m.getParameterList().getFormalparalist().size() == numArgs){ - RefTypeOrTPHOrWildcardOrGeneric retType = m.getReturnType();//info.checkGTV(m.getReturnType()); + for (ClassOrInterface cl : info.getAvailableClasses()) { + for (Method m : cl.getMethods()) { + if (m.getName().equals(name) && m.getParameterList().getFormalparalist().size() == numArgs) { + RefTypeOrTPHOrWildcardOrGeneric retType = m.getReturnType();// info.checkGTV(m.getReturnType()); - ret.add(new MethodAssumption(cl, retType, convertParams(m.getParameterList(),info), - createTypeScope(cl, m), m.isInherited)); + ret.add(new MethodAssumption(cl, retType, convertParams(m.getParameterList(), info), createTypeScope(cl, m), m.isInherited)); } } } @@ -715,31 +642,27 @@ public class TYPEStmt implements StatementVisitor{ return getMethods(name, arglist.getArguments().size(), info); } - protected static List convertParams(ParameterList parameterList, TypeInferenceBlockInformation info){ - //TODO: Hier müssen die Parameter mit den TPHs in den GEnerics des Receivers verknüpft werden + protected static List convertParams(ParameterList parameterList, TypeInferenceBlockInformation info) { + // TODO: Hier müssen die Parameter mit den TPHs in den GEnerics des Receivers verknüpft werden /* - BEispiel: - auto test = new List(); - test.add("hallo"); - - Hier kriegt der Receiver ja den COnstraint TPH REceiver <. List - Dann mus bei dem Parameter der COnstraint entstehen: TPH A <. String + * BEispiel: auto test = new List(); test.add("hallo"); + * + * Hier kriegt der Receiver ja den COnstraint TPH REceiver <. List Dann mus bei dem Parameter der COnstraint entstehen: TPH A <. String */ List params = new ArrayList<>(); - for(FormalParameter fp : parameterList.getFormalparalist()){ - params.add(fp.getType()); //info.checkGTV(fp.getType())); //PL 2018-06-22 GTV sollen in Argumenten erhalten bleiben + for (FormalParameter fp : parameterList.getFormalparalist()) { + params.add(fp.getType()); // info.checkGTV(fp.getType())); //PL 2018-06-22 GTV sollen in Argumenten erhalten bleiben } return params; } - public List getConstructors(TypeInferenceBlockInformation info, RefType ofType, ArgumentList argList){ + public List getConstructors(TypeInferenceBlockInformation info, RefType ofType, ArgumentList argList) { List ret = new ArrayList<>(); - for(ClassOrInterface cl : info.getAvailableClasses()){ - if(cl.getClassName().equals(ofType.getName())){ - for(Method m : cl.getConstructors()){ - if(m.getParameterList().getFormalparalist().size() == argList.getArguments().size()){ - ret.add(new MethodAssumption(cl, cl.generateTypeOfThisClass(), convertParams(m.getParameterList(), - info), createTypeScope(cl, m), m.isInherited)); + for (ClassOrInterface cl : info.getAvailableClasses()) { + if (cl.getClassName().equals(ofType.getName())) { + for (Method m : cl.getConstructors()) { + if (m.getParameterList().getFormalparalist().size() == argList.getArguments().size()) { + ret.add(new MethodAssumption(cl, cl.generateTypeOfThisClass(), convertParams(m.getParameterList(), info), createTypeScope(cl, m), m.isInherited)); } } } @@ -747,14 +670,12 @@ public class TYPEStmt implements StatementVisitor{ return ret; } - protected Constraint generateConstructorConstraint(NewClass forConstructor, MethodAssumption assumption, - TypeInferenceBlockInformation info, GenericsResolver resolver){ + protected Constraint generateConstructorConstraint(NewClass forConstructor, MethodAssumption assumption, TypeInferenceBlockInformation info, GenericsResolver resolver) { Constraint methodConstraint = new Constraint(); - //WELCHEN SINN MACHT DIESER CONSTRAINT??? - //Ist er nicht immer classname <. classname und damit redundant? - methodConstraint.add(new Pair(assumption.getReturnType(resolver), forConstructor.getType(), - PairOperator.SMALLERDOT)); - //WELCHEN SINN MACHT DIESER CONSTRAINT??? + // WELCHEN SINN MACHT DIESER CONSTRAINT??? + // Ist er nicht immer classname <. classname und damit redundant? + methodConstraint.add(new Pair(assumption.getReturnType(resolver), forConstructor.getType(), PairOperator.SMALLERDOT)); + // WELCHEN SINN MACHT DIESER CONSTRAINT??? methodConstraint.addAll(generateParameterConstraints(forConstructor, assumption, info, resolver)); return methodConstraint; } diff --git a/src/test/java/AllgemeinTest.java b/src/test/java/AllgemeinTest.java deleted file mode 100644 index 60ef6659..00000000 --- a/src/test/java/AllgemeinTest.java +++ /dev/null @@ -1,80 +0,0 @@ - - -import static org.junit.Assert.*; - -import java.io.File; -import java.lang.reflect.Field; -import java.net.URL; -import java.net.URLClassLoader; -import java.util.Arrays; - -import org.junit.BeforeClass; -import org.junit.Test; - -import com.google.common.collect.Lists; - -import de.dhbwstuttgart.core.JavaTXCompiler; - -public class AllgemeinTest { - - private static String path; - private static File fileToTest; - private static JavaTXCompiler compiler; - private static ClassLoader loader; - private static Class classToTest; - private static String pathToClassFile; - private static Object instanceOfClass; - - - @Test - public void test() throws Exception { - //String className = "GenTest"; - //String className = "Overloading_Generics"; - //String className = "Generics"; - //String className = "OverloadingMain"; - //String className = "OverrideMain"; - //String className = "OverrideMainRet"; - //String className = "FCTest1"; - //String className = "FCTest2"; - //String className = "Pair"; - //String className = "FCTest3"; - //String className = "Var"; - //String className = "Put"; - //String className = "Twice"; - //String className = "TestSubTypless"; - //String className = "addList"; - //String className = "M"; - //String className = "Wildcard_Andi"; - //String className = "Box"; - //String className = "Box_Main"; - //String className = "wildcardPair"; - //String className = "VectorConstAdd"; - //String className = "VectorNotObject"; - //String className = "WildcardCaptureConversionTest"; - //String className = "CaptureConversion"; - //String className = "Pair"; - //String className = "UseWildcardPair"; - //String className = "Assign"; - //String className = "StreamTest"; - String className = "Iteration"; - //PL 2019-10-24: genutzt fuer unterschiedliche Tests - path = System.getProperty("user.dir")+"/resources/AllgemeinTest/" + className + ".jav"; - //path = System.getProperty("user.dir")+"/src/test/resources/AllgemeinTest/Overloading_Generics.jav"; - //path = System.getProperty("user.dir")+"/src/test/resources/bytecode/javFiles/mathStrucInteger.jav"; - //compiler = new JavaTXCompiler(Lists.newArrayList(new File(System.getProperty("user.dir")+"/src/test/resources/AllgemeinTest/Overloading_Generics.jav"))); - ///* - compiler = new JavaTXCompiler( - Lists.newArrayList(new File(path)), - Lists.newArrayList(new File(System.getProperty("user.dir")+"/resources/testBytecode/generatedBC/"))); - //*/ - compiler.generateBytecode(System.getProperty("user.dir")+"/resources/testBytecode/generatedBC/"); - pathToClassFile = System.getProperty("user.dir")+"/resources/testBytecode/generatedBC/"; - loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); - classToTest = loader.loadClass(className); - //classToTest = loader.loadClass("Overloading_Generics"); - //instanceOfClass = classToTest.getDeclaredConstructor().newInstance("A"); - //classToTest = loader.loadClass("Overloading_Generics1"); - //instanceOfClass = classToTest.getDeclaredConstructor(Object.class).newInstance("B"); - } - -} diff --git a/src/test/java/targetast/TestComplete.java b/src/test/java/TestComplete.java similarity index 92% rename from src/test/java/targetast/TestComplete.java rename to src/test/java/TestComplete.java index 46699df1..286e6ec6 100644 --- a/src/test/java/targetast/TestComplete.java +++ b/src/test/java/TestComplete.java @@ -1,4 +1,3 @@ -package targetast; import de.dhbwstuttgart.environment.ByteArrayClassLoader; import org.junit.Ignore; @@ -9,6 +8,8 @@ import java.lang.reflect.ParameterizedType; import java.util.Arrays; import java.util.Vector; +import targetast.TestCodegen; + import static org.junit.Assert.*; import static targetast.TestCodegen.generateClassFiles; @@ -50,7 +51,7 @@ public class TestComplete { var instance = fac.getDeclaredConstructor().newInstance(); var getFac = fac.getDeclaredMethod("getFac", Integer.class); - //assertEquals(6, getFac.invoke(instance, 3)); TODO This could be either an Integer or a Double so this simple test fails + // assertEquals(6, getFac.invoke(instance, 3)); TODO This could be either an Integer or a Double so this simple test fails } @Test @@ -205,7 +206,7 @@ public class TestComplete { vv1.addElement(v3); vv1.addElement(v4); - var instanceOfClass_m2 = matrixOP.getDeclaredConstructor(Vector.class).newInstance(vv1);//Matrix m2 = new Matrix(vv1); + var instanceOfClass_m2 = matrixOP.getDeclaredConstructor(Vector.class).newInstance(vv1);// Matrix m2 = new Matrix(vv1); var mul = matrixOP.getField("mul"); mul.setAccessible(true); @@ -237,10 +238,10 @@ public class TestComplete { var matrix = classFiles.get("Matrix"); Vector> vv = new Vector<>(); - Vector v1 = new Vector<> (); + Vector v1 = new Vector<>(); v1.addElement(2); v1.addElement(2); - Vector v2 = new Vector<> (); + Vector v2 = new Vector<>(); v2.addElement(3); v2.addElement(3); vv.addElement(v1); @@ -249,10 +250,10 @@ public class TestComplete { var instanceOfClass_m1 = matrix.getDeclaredConstructor(Vector.class).newInstance(vv); Vector> vv1 = new Vector<>(); - Vector v3 = new Vector<> (); + Vector v3 = new Vector<>(); v3.addElement(2); v3.addElement(2); - Vector v4 = new Vector<> (); + Vector v4 = new Vector<>(); v4.addElement(3); v4.addElement(3); vv1.addElement(v3); @@ -265,10 +266,10 @@ public class TestComplete { System.out.println(instanceOfClass_m1.toString() + " * " + instanceOfClass_m2.toString() + " = " + result.toString()); Vector> res = new Vector<>(); - Vector v5 = new Vector<> (); + Vector v5 = new Vector<>(); v5.addElement(10); v5.addElement(10); - Vector v6 = new Vector<> (); + Vector v6 = new Vector<>(); v6.addElement(15); v6.addElement(15); res.addElement(v5); @@ -284,13 +285,13 @@ public class TestComplete { var scalar = classFiles.get("Scalar"); Vector> vv = new Vector<>(); - Vector v1 = new Vector<> (); + Vector v1 = new Vector<>(); v1.addElement(2); v1.addElement(2); - + var instanceOfClass_s1 = scalar.getDeclaredConstructor(Vector.class).newInstance(v1); - Vector v2 = new Vector<> (); + Vector v2 = new Vector<>(); v2.addElement(2); v2.addElement(2); @@ -303,7 +304,6 @@ public class TestComplete { assertEquals(result, 8); } - @Test public void mergeTest() throws Exception { var classFiles = generateClassFiles(new ByteArrayClassLoader(), "Merge.jav"); @@ -349,7 +349,7 @@ public class TestComplete { var relOps = classFiles.get("RelOps"); var instance = relOps.getDeclaredConstructor().newInstance(); - var m = relOps.getDeclaredMethod("m", Integer.class,Integer.class); + var m = relOps.getDeclaredMethod("m", Integer.class, Integer.class); assertFalse((Boolean) m.invoke(instance, 7, 3)); } @@ -364,7 +364,7 @@ public class TestComplete { var classFiles = generateClassFiles(new ByteArrayClassLoader(), "SubMatrix.jav"); var instance = classFiles.get("SubMatrix").getDeclaredConstructor().newInstance(); } - + @Test public void tphTest() throws Exception { var classFiles = generateClassFiles(new ByteArrayClassLoader(), "Tph.jav"); @@ -512,7 +512,6 @@ public class TestComplete { assertEquals(W, m2.getGenericReturnType()); } - @Test public void Tph7Test() throws Exception { var classFiles = TestCodegen.generateClassFiles(new ByteArrayClassLoader(), "Tph7.jav"); @@ -522,55 +521,52 @@ public class TestComplete { // public N m(O var1, N var2) Method m = classToTest.getDeclaredMethod("m", Object.class, Object.class); - //System.out.println(m.toString()); + // System.out.println(m.toString()); - //Argumenttypes of the method m + // Argumenttypes of the method m var paraTypes = m.getGenericParameterTypes(); - //Typeparameters of the method m - var typeParaTypes = m.getTypeParameters(); + // Typeparameters of the method m + var typeParaTypes = m.getTypeParameters(); - //Typeparameters are extracted from the argumenttypes - //Conditions for the extracted typeparameters are set + // Typeparameters are extracted from the argumenttypes + // Conditions for the extracted typeparameters are set - //paraTypes[0] = O - var boundFstArg = Arrays.stream(typeParaTypes) - .filter(x -> x.equals(paraTypes[0])).findFirst().get().getBounds(); + // paraTypes[0] = O + var boundFstArg = Arrays.stream(typeParaTypes).filter(x -> x.equals(paraTypes[0])).findFirst().get().getBounds(); - //Bound of O has to be Object + // Bound of O has to be Object assertEquals(Object.class, Arrays.stream(boundFstArg).findFirst().get()); - //paraTypes[1] = N - var N = Arrays.stream(typeParaTypes) - .filter(x -> x.equals(paraTypes[1])).findFirst().get(); + // paraTypes[1] = N + var N = Arrays.stream(typeParaTypes).filter(x -> x.equals(paraTypes[1])).findFirst().get(); var boundSndArg = N.getBounds(); - //Bound of H has to be Object + // Bound of H has to be Object assertEquals(Object.class, Arrays.stream(boundSndArg).findFirst().get()); - //N has to be the return type of m + // N has to be the return type of m assertEquals(N, m.getGenericReturnType()); - //public DZU m2(DZU); + // public DZU m2(DZU); Method m2 = classToTest.getDeclaredMethod("m2", Object.class); - //Argumenttypes of the method m2 + // Argumenttypes of the method m2 var paraTypesm2 = m2.getGenericParameterTypes(); - //Typeparameters of the method m2 - var typeParaTypesm2 = m2.getTypeParameters(); + // Typeparameters of the method m2 + var typeParaTypesm2 = m2.getTypeParameters(); - //Typeparameters are extracted from the argumenttypes - //Conditions for the extracted typeparameters are set + // Typeparameters are extracted from the argumenttypes + // Conditions for the extracted typeparameters are set - //paraTypes[0] = DZU - var fstArgm2 = Arrays.stream(typeParaTypesm2) - .filter(x -> x.equals(paraTypesm2[0])).findFirst().get(); + // paraTypes[0] = DZU + var fstArgm2 = Arrays.stream(typeParaTypesm2).filter(x -> x.equals(paraTypesm2[0])).findFirst().get(); - //Bound of DZU has to be Object + // Bound of DZU has to be Object assertEquals(Object.class, Arrays.stream(fstArgm2.getBounds()).findFirst().get()); - //DZU has to be the return type of m + // DZU has to be the return type of m assertEquals(fstArgm2, m2.getGenericReturnType()); } diff --git a/src/test/java/general/TestCleanUp.java b/src/test/java/general/TestCleanUp.java deleted file mode 100644 index f1b82cc8..00000000 --- a/src/test/java/general/TestCleanUp.java +++ /dev/null @@ -1,14 +0,0 @@ -package general; - -import java.io.File; -import java.io.FileFilter; - -public class TestCleanUp { - - public static void cleanUpDirectory(File directory, FileFilter fileFilter){ - if(!directory.isDirectory()) throw new RuntimeException("Directory for bytecode generation is wrong!"); - for (File file: directory.listFiles(fileFilter)) { - file.delete(); - } - } -} diff --git a/src/test/java/packages/Bytecode.java b/src/test/java/packages/Bytecode.java deleted file mode 100644 index 48a21f9b..00000000 --- a/src/test/java/packages/Bytecode.java +++ /dev/null @@ -1,52 +0,0 @@ -package packages; - -import de.dhbwstuttgart.core.JavaTXCompiler; -import junit.framework.TestCase; -import org.junit.Test; - -import java.io.File; -import java.io.IOException; -import java.lang.reflect.InvocationTargetException; -import java.net.URL; -import java.net.URLClassLoader; - -public class Bytecode extends TestCase { - - public static final String rootDirectory = System.getProperty("user.dir")+"/resources/javFiles/packageTest/"; - @Test - public void testSetPackageNameInBytecode() throws Exception { - JavaTXCompiler compiler = new JavaTXCompiler(new File(rootDirectory+"de/test/TestClass.jav")); - compiler.typeInference(); - File f = new File(rootDirectory + "de/test/TestClass.class"); - if(f.exists() && !f.isDirectory()) { - f.delete(); - } - compiler.generateBytecode(); - f = new File(rootDirectory + "de/test/TestClass.class"); - assertTrue(f.exists()); - - - URLClassLoader loader = new URLClassLoader(new URL[]{new URL("file://" + rootDirectory)}); - Class classToTest = loader.loadClass("de.test.TestClass"); - Object instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); - } - - @Test - public void testSetPackageNameInBytecodeAndOutputFolder() throws Exception { - JavaTXCompiler compiler = new JavaTXCompiler(new File(rootDirectory+"de/test/TestClass.jav")); - compiler.typeInference(); - File f = new File(rootDirectory + "de/test/output/de/test/TestClass.class"); - if(f.exists() && !f.isDirectory()) { - f.delete(); - } - compiler.generateBytecode(rootDirectory + "de/test/output/"); - f = new File(rootDirectory + "de/test/output/de/test/TestClass.class"); - assertTrue(f.exists()); - - URLClassLoader loader = new URLClassLoader(new URL[]{new URL("file://" + rootDirectory + "de/test/output/")}); - Class classToTest = loader.loadClass("de.test.TestClass"); - Object instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); - } - - -} diff --git a/src/test/java/packages/CheckPackageFolder.java b/src/test/java/packages/CheckPackageFolder.java deleted file mode 100644 index cb9a6231..00000000 --- a/src/test/java/packages/CheckPackageFolder.java +++ /dev/null @@ -1,80 +0,0 @@ -package packages; - -import de.dhbwstuttgart.core.JavaTXCompiler; -import de.dhbwstuttgart.syntaxtree.SourceFile; -import junit.framework.TestCase; -import org.junit.Test; -import org.junit.rules.ExpectedException; - -import java.io.File; -import java.io.IOException; -import java.util.Arrays; - -public class CheckPackageFolder extends TestCase { - - public static final String rootDirectory = System.getProperty("user.dir")+"/resources/javFiles/packageTest/de/test/"; - - @Test - public void testCorrectFolder1FileWithWrongPackageName() throws IOException, ClassNotFoundException { - JavaTXCompiler compiler = new JavaTXCompiler(new File(rootDirectory+"packageNameTestWrongPackage.jav")); - compiler.typeInference(); - File f = new File(rootDirectory + "TestClass.class"); - if(f.exists() && !f.isDirectory()) { - f.delete(); - } - compiler.generateBytecode(); - f = new File(rootDirectory + "TestClass.class"); - assertTrue(f.exists()); //Es ist erlaubt falsche package Namen zu verwenden. Warnung wäre optional - } - - @Test - public void testCorrectFolder1File() throws IOException, ClassNotFoundException { - JavaTXCompiler compiler = new JavaTXCompiler(new File(rootDirectory+"TestClass.jav")); - compiler.typeInference(); - File f = new File(rootDirectory + "TestClass.class"); - if(f.exists() && !f.isDirectory()) { - f.delete(); - } - compiler.generateBytecode(); - f = new File(rootDirectory + "TestClass.class"); - assertTrue(f.exists()); //Es ist erlaubt falsche package Namen zu verwenden. Warnung wäre optional - } - - @Test - public void testCorrectFolder1FileAndOutputDirectory() throws IOException, ClassNotFoundException { - JavaTXCompiler compiler = new JavaTXCompiler(new File(rootDirectory+"TestClass.jav")); - compiler.typeInference(); - File f = new File(rootDirectory + "output/de/test/TestClass.class"); - if(f.exists() && !f.isDirectory()) { - f.delete(); - } - compiler.generateBytecode(rootDirectory+"output/"); - f = new File(rootDirectory + "output/de/test/TestClass.class"); - assertTrue(f.exists()); //Es ist erlaubt falsche package Namen zu verwenden. Warnung wäre optional - } - - /* - * Dieser Test wird übersprungen, da der Bytecode-Generator nicht mit zwei Eingabedateien gleichzeitig umgehen kann - @Test - public void testCorrectFolder2Files() throws IOException, ClassNotFoundException { - JavaTXCompiler compiler = new JavaTXCompiler(Arrays.asList( - new File(rootDirectory+"subpackage1/Test1.jav"), - new File(rootDirectory+"subpackage2/Test2.jav") - )); - compiler.typeInference(); - File f = new File(rootDirectory + "subpackage1/Test1.class"); - if(f.exists() && !f.isDirectory()) { - f.delete(); - } - File f2 = new File(rootDirectory + "subpackage2/Test2.class"); - if(f.exists() && !f.isDirectory()) { - f.delete(); - } - compiler.generateBytecode(); - f = new File(rootDirectory + "subpackage1/Test1.class"); - f2 = new File(rootDirectory + "subpackage2/Test2.class"); - assertTrue(f.exists()); - assertTrue(f2.exists()); - } - */ -} diff --git a/src/test/java/packages/ConsoleInterfaceTest.java b/src/test/java/packages/ConsoleInterfaceTest.java deleted file mode 100644 index 658455af..00000000 --- a/src/test/java/packages/ConsoleInterfaceTest.java +++ /dev/null @@ -1,133 +0,0 @@ -package packages; - -import de.dhbwstuttgart.core.ConsoleInterface; -import de.dhbwstuttgart.core.JavaTXCompiler; -import junit.framework.TestCase; -import org.junit.Test; - -import java.io.File; -import java.net.URL; -import java.net.URLClassLoader; - -public class ConsoleInterfaceTest extends TestCase { - - public static final String rootDirectory = System.getProperty("user.dir")+"/resources/javFiles/packageTest/"; - - @Test - public void testCompileSingleJavFile() throws Exception { - File f = new File(rootDirectory + "de/test/TestClass.class"); - if(f.exists() && !f.isDirectory()) { - f.delete(); - } - - ConsoleInterface.main(new String[]{rootDirectory + "de/test/TestClass.jav"}); - - f = new File(rootDirectory + "de/test/TestClass.class"); - assertTrue(f.exists()); - } - - @Test - public void testCompileSingleJavFileWithOutputDirectory() throws Exception { - File f = new File(rootDirectory + "de/test/output/de/test/TestClass.class"); - if(f.exists() && !f.isDirectory()) { - f.delete(); - } - - ConsoleInterface.main(new String[]{"-d", rootDirectory + "de/test/output/" ,rootDirectory + "de/test/TestClass.jav"}); - - f = new File(rootDirectory + "de/test/output/de/test/TestClass.class"); - assertTrue(f.exists()); - } - - @Test - public void testCpNotEndsWithSlash() throws Exception { - JavaTXCompiler compiler = new JavaTXCompiler(new File(rootDirectory+"/de/test/ToImport.jav")); - compiler.typeInference(); - compiler.generateBytecode(rootDirectory + "output/"); - File f = new File(rootDirectory + "output/de/test/ToImport.class"); - assertTrue(f.exists()); - - f = new File(rootDirectory + "de/test/ImportTest.class"); - if(f.exists() && !f.isDirectory()) { - f.delete(); - } - - ConsoleInterface.main(new String[]{"-cp", rootDirectory + "de/test/output" , rootDirectory + "de/test/ImportTest.jav"}); - - f = new File(rootDirectory + "de/test/ImportTest.class"); - assertTrue(f.exists()); - } - - @Test - public void testOutputDirNotEndsWithSlash() throws Exception { - File f = new File(rootDirectory + "de/test/output/de/test/TestClass.class"); - if(f.exists() && !f.isDirectory()) { - f.delete(); - } - - ConsoleInterface.main(new String[]{"-d", rootDirectory + "de/test/output" ,rootDirectory + "de/test/TestClass.jav"}); - - f = new File(rootDirectory + "de/test/output/de/test/TestClass.class"); - assertTrue(f.exists()); - } - - @Test - public void testCompileSingleJavFileWithClassPath() throws Exception { - JavaTXCompiler compiler = new JavaTXCompiler(new File(rootDirectory+"/de/test/ToImport.jav")); - compiler.typeInference(); - compiler.generateBytecode(rootDirectory + "output/"); - File f = new File(rootDirectory + "output/de/test/ToImport.class"); - assertTrue(f.exists()); - - f = new File(rootDirectory + "de/test/ImportTest.class"); - if(f.exists() && !f.isDirectory()) { - f.delete(); - } - - ConsoleInterface.main(new String[]{"-cp", rootDirectory + "de/test/output/" ,rootDirectory + "de/test/ImportTest.jav"}); - - f = new File(rootDirectory + "de/test/ImportTest.class"); - assertTrue(f.exists()); - } - - @Test - public void testCompileSingleJavFileWithMultipleClassPath() throws Exception { - JavaTXCompiler compiler = new JavaTXCompiler(new File(rootDirectory+"/de/test/ToImport.jav")); - compiler.typeInference(); - compiler.generateBytecode(rootDirectory + "output/"); - File f = new File(rootDirectory + "output/de/test/ToImport.class"); - assertTrue(f.exists()); - - f = new File(rootDirectory + "de/test/ImportTest.class"); - if(f.exists() && !f.isDirectory()) { - f.delete(); - } - - ConsoleInterface.main(new String[]{"-cp", rootDirectory + "de/test/output/:"+rootDirectory+"de", - rootDirectory + "de/test/ImportTest.jav"}); - - f = new File(rootDirectory + "de/test/ImportTest.class"); - assertTrue(f.exists()); - } - - @Test - public void testCompileSingleJavFileWithClassPathAndOutputDir() throws Exception { - JavaTXCompiler compiler = new JavaTXCompiler(new File(rootDirectory+"/de/test/ToImport.jav")); - compiler.typeInference(); - compiler.generateBytecode(rootDirectory + "output/"); - File f = new File(rootDirectory + "output/de/test/ToImport.class"); - assertTrue(f.exists()); - - f = new File(rootDirectory + "de/test/output/de/test/ImportTest.class"); - if(f.exists() && !f.isDirectory()) { - f.delete(); - } - - ConsoleInterface.main(new String[]{"-cp", rootDirectory + "de/test/output/", - "-d"+rootDirectory + "de/test/output/" ,rootDirectory + "de/test/ImportTest.jav"}); - - f = new File(rootDirectory + "de/test/output/de/test/ImportTest.class"); - assertTrue(f.exists()); - } - -} diff --git a/src/test/java/packages/ImportTest.java b/src/test/java/packages/ImportTest.java deleted file mode 100644 index c6fc6e2e..00000000 --- a/src/test/java/packages/ImportTest.java +++ /dev/null @@ -1,108 +0,0 @@ -package packages; - -import com.google.common.collect.Lists; -import de.dhbwstuttgart.core.JavaTXCompiler; -import junit.framework.TestCase; -import org.junit.Before; -import org.junit.Test; - -import java.io.File; -import java.io.IOException; -import java.net.URL; - -public class ImportTest extends TestCase { - - public static final String rootDirectory = System.getProperty("user.dir")+"/resources/javFiles/packageTest/de/test/"; - - - public ImportTest() throws ClassNotFoundException, IOException { - /* - Generate ToImport class in rootDirectory and in output-Directory - */ - JavaTXCompiler compiler = new JavaTXCompiler(new File(rootDirectory+"ToImport.jav")); - compiler.typeInference(); - compiler.generateBytecode(rootDirectory + "output/"); - File f = new File(rootDirectory + "output/de/test/ToImport.class"); - assertTrue(f.exists()); - - compiler = new JavaTXCompiler(new File(rootDirectory+"ToImport.jav")); - compiler.typeInference(); - compiler.generateBytecode(); - f = new File(rootDirectory + "ToImport.class"); - assertTrue(f.exists()); - - compiler = new JavaTXCompiler(new File(rootDirectory+"subpackage1/ToImport2.jav")); - compiler.typeInference(); - compiler.generateBytecode(rootDirectory + "output/"); - f = new File(rootDirectory + "output/de/test/subpackage1/ToImport2.class"); - assertTrue(f.exists()); - - compiler = new JavaTXCompiler(new File(rootDirectory+"subpackage2/ToImport3.jav")); - compiler.typeInference(); - compiler.generateBytecode(rootDirectory + "output/"); - f = new File(rootDirectory + "output/de/test/subpackage2/ToImport3.class"); - assertTrue(f.exists()); - } - - @Test - public void testSetPackageNameInBytecodeAndOutputFolder() throws IOException, ClassNotFoundException { - JavaTXCompiler compiler = new JavaTXCompiler( - Lists.newArrayList(new File(rootDirectory+"ImportTest.jav")), - Lists.newArrayList(new File(rootDirectory+"output/"))); - compiler.typeInference(); - File f = new File(rootDirectory + "output/de/test/ImportTest.class"); - if(f.exists() && !f.isDirectory()) { - f.delete(); - } - compiler.generateBytecode(rootDirectory + "output/"); - f = new File(rootDirectory + "output/de/test/ImportTest.class"); - assertTrue(f.exists()); - } - - @Test - public void testSetPackageNameInBytecodeAndStandardOutputFolder() throws IOException, ClassNotFoundException { - JavaTXCompiler compiler = new JavaTXCompiler( - Lists.newArrayList(new File(rootDirectory+"ImportTest.jav")), - Lists.newArrayList(new File(rootDirectory+"output/"))); - compiler.typeInference(); - File f = new File(rootDirectory + "ImportTest.class"); - if(f.exists() && !f.isDirectory()) { - f.delete(); - } - compiler.generateBytecode(); - f = new File(rootDirectory + "ImportTest.class"); - assertTrue(f.exists()); - } - - - @Test - public void testImportTwoClasses() throws IOException, ClassNotFoundException { - JavaTXCompiler compiler = new JavaTXCompiler( - Lists.newArrayList(new File(rootDirectory+"ImportTest2.jav")), - Lists.newArrayList(new File(rootDirectory+"output/"))); - compiler.typeInference(); - File f = new File(rootDirectory + "ImportTest2.class"); - if(f.exists() && !f.isDirectory()) { - f.delete(); - } - compiler.generateBytecode(); - f = new File(rootDirectory + "ImportTest2.class"); - assertTrue(f.exists()); - } - - @Test - public void testImportDefaultPackage() throws IOException, ClassNotFoundException { - JavaTXCompiler compiler = new JavaTXCompiler( - Lists.newArrayList(new File(rootDirectory+"ImportTestDefault.jav"))); - compiler.typeInference(); - File f = new File(rootDirectory + "ImportTestDefault.class"); - if(f.exists() && !f.isDirectory()) { - f.delete(); - } - compiler.generateBytecode(); - f = new File(rootDirectory + "ImportTestDefault.class"); - assertTrue(f.exists()); - } - - -} diff --git a/src/test/java/packages/LoadDefaultPackageClassesTest.java b/src/test/java/packages/LoadDefaultPackageClassesTest.java deleted file mode 100644 index 49f33385..00000000 --- a/src/test/java/packages/LoadDefaultPackageClassesTest.java +++ /dev/null @@ -1,55 +0,0 @@ -package packages; - -import com.google.common.collect.Lists; -import de.dhbwstuttgart.core.JavaTXCompiler; -import de.dhbwstuttgart.environment.CompilationEnvironment; -import junit.framework.TestCase; -import org.junit.Test; - -import java.io.File; -import java.io.IOException; -import java.net.URL; -import java.net.URLClassLoader; - -public class LoadDefaultPackageClassesTest extends TestCase { - - public static final String rootDirectory = System.getProperty("user.dir")+"/resources/javFiles/packageTest/"; - - - public LoadDefaultPackageClassesTest() throws ClassNotFoundException, IOException { - /* - Generate ToImport class in rootDirectory and in output-Directory - */ - JavaTXCompiler compiler = new JavaTXCompiler( - Lists.newArrayList(new File(rootDirectory+"Gen.jav")), - Lists.newArrayList(new File(rootDirectory+"/de/test/output/"))); - compiler.typeInference(); - compiler.generateBytecode(); - File f = new File(rootDirectory + "Gen.class"); - assertTrue(f.exists()); - } - - public void testLoadGenClass() throws IOException, ClassNotFoundException { - CompilationEnvironment.loadDefaultPackageClasses(new File( rootDirectory + "Test.jav"), ClassLoader.getSystemClassLoader()); - } - - public void testURLClassLoader() throws IOException, ClassNotFoundException { - URLClassLoader cl = new URLClassLoader(new URL[]{new URL("file://"+rootDirectory)}, ClassLoader.getSystemClassLoader()); - cl.loadClass("Gen"); - } -/* - public void testE2E() throws IOException, ClassNotFoundException { - JavaTXCompiler compiler = new JavaTXCompiler(new File(rootDirectory+"OL.jav")); - compiler.typeInference(); - compiler.generateBytecode(); - File f = new File(rootDirectory + "OL.class"); - assertTrue(f.exists()); - - compiler = new JavaTXCompiler(new File(rootDirectory+"OLMain.jav")); - compiler.typeInference(); - compiler.generateBytecode(); - f = new File(rootDirectory + "OLMain.class"); - assertTrue(f.exists()); - } - */ -} diff --git a/src/test/java/packages/OLOneFileTest.java b/src/test/java/packages/OLOneFileTest.java deleted file mode 100644 index ddae05b5..00000000 --- a/src/test/java/packages/OLOneFileTest.java +++ /dev/null @@ -1,132 +0,0 @@ -package packages; - -import static org.junit.Assert.*; - -import java.io.File; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.net.URL; -import java.net.URLClassLoader; -import java.util.List; - -import org.junit.BeforeClass; -import org.junit.Test; - -import com.google.common.collect.Lists; - -import de.dhbwstuttgart.core.JavaTXCompiler; -import de.dhbwstuttgart.typeinference.result.ResultSet; - -public class OLOneFileTest { - private static String path; - private static File fileToTest; - private static JavaTXCompiler compiler; - private static ClassLoader loader; - private static Class classToTest; - private static Class classToTest1; - private static Class classToTest2; - private static String pathToClassFile; - private static Object instanceOfClass; - private static Object instanceOfClass1; - private static Object instanceOfClass2; - - public static final String rootDirectory = System.getProperty("user.dir")+"/resources/javFiles/packageTest/"; - - @BeforeClass - public static void setUpBeforeClass() throws Exception { - path = rootDirectory +"OLOneFile.jav"; - fileToTest = new File(path); - compiler = new JavaTXCompiler( - Lists.newArrayList(fileToTest), - Lists.newArrayList(new File(rootDirectory+"de/test/output/"))); - pathToClassFile = System.getProperty("user.dir")+"/resources/javFiles/packageTest/"; - List typeinferenceResult = compiler.typeInference(); - //List simplifyResultsForAllSourceFiles = compiler.getGeneratedGenericResultsForAllSourceFiles(typeinferenceResult); - //compiler.generateBytecode(new File(pathToClassFile),typeinferenceResult,simplifyResultsForAllSourceFiles); - loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)}); - classToTest = loader.loadClass("OLOneFile"); - instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); - classToTest1 = loader.loadClass("OLextendsOneFile"); - instanceOfClass1 = classToTest1.getDeclaredConstructor().newInstance(); - classToTest2 = loader.loadClass("OLMainOneFile"); - instanceOfClass2 = classToTest2.getDeclaredConstructor().newInstance(); - } - - @Test - public void testOLClassName() { - assertEquals("OLOneFile", classToTest.getName()); - } - - @Test - public void testmInt() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method m = classToTest.getDeclaredMethod("m2", Integer.class); - Integer result = (Integer) m.invoke(instanceOfClass, 5); - assertEquals(new Integer(10), result); - } - - @Test - public void testmDouble() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method m = classToTest.getDeclaredMethod("m2", Double.class); - Double result = (Double) m.invoke(instanceOfClass, 5.0); - assertEquals(new Double(10.0), result); - } - - @Test - public void testmString() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method m = classToTest.getDeclaredMethod("m2", String.class); - String result = (String) m.invoke(instanceOfClass, "xxx"); - assertEquals("xxxxxx", result); - } - - @Test - public void testOLextendsClassName() { - assertEquals("OLextendsOneFile", classToTest1.getName()); - } - - @Test - public void testextendsInt() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method main = classToTest1.getMethod("m2", Integer.class); - Integer result = (Integer) main.invoke(instanceOfClass1, 5); - assertEquals(new Integer(10), result); - } - - @Test - public void testextendsDouble() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method main = classToTest1.getMethod("m2", Double.class); - Double result = (Double) main.invoke(instanceOfClass1, 5.0); - assertEquals(new Double(10.0), result); - } - - @Test - public void testextendsString() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method main = classToTest1.getMethod("m2", String.class); - String result = (String) main.invoke(instanceOfClass1, "xxx"); - assertEquals("xxxxxx", result); - } - - @Test - public void testOLMainClassName() { - assertEquals("OLMainOneFile", classToTest2.getName()); - } - - @Test - public void testmainInt() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method main = classToTest2.getDeclaredMethod("main", Integer.class); - Integer result = (Integer) main.invoke(instanceOfClass2, 5); - assertEquals(new Integer(10), result); - } - - @Test - public void testmainDouble() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method main = classToTest2.getDeclaredMethod("main", Double.class); - Double result = (Double) main.invoke(instanceOfClass2, 5.0); - assertEquals(new Double(10.0), result); - } - - @Test - public void testmainString() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method main = classToTest2.getDeclaredMethod("main", String.class); - String result = (String) main.invoke(instanceOfClass2, "xxx"); - assertEquals("xxxxxx", result); - } -} diff --git a/src/test/java/packages/OLTest.java b/src/test/java/packages/OLTest.java deleted file mode 100644 index 0518be96..00000000 --- a/src/test/java/packages/OLTest.java +++ /dev/null @@ -1,145 +0,0 @@ -package packages; - -import static org.junit.Assert.*; - -import java.io.File; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.net.URL; -import java.net.URLClassLoader; -import java.util.List; - -import org.junit.BeforeClass; -import org.junit.Test; - -import com.google.common.collect.Lists; - -import de.dhbwstuttgart.core.JavaTXCompiler; - -public class OLTest { - private static String path; - private static File fileToTest; - private static JavaTXCompiler compiler; - private static ClassLoader loader; - private static Class classToTest; - private static Class classToTest1; - private static Class classToTest2; - private static String pathToClassFile; - private static Object instanceOfClass; - private static Object instanceOfClass1; - private static Object instanceOfClass2; - - public static final String rootDirectory = System.getProperty("user.dir")+"/resources/javFiles/packageTest"; - - @BeforeClass - public static void setUpBeforeClass() throws Exception { - JavaTXCompiler compiler = new JavaTXCompiler(new File(rootDirectory+"/de/test/OL.jav")); - compiler.typeInference(); - compiler.generateBytecode(rootDirectory + "/de/test/output/"); - loader = new URLClassLoader(new URL[] {new URL("file://"+ rootDirectory + "/de/test/output/")}); - classToTest = loader.loadClass("de.test.OL"); - instanceOfClass = classToTest.getDeclaredConstructor().newInstance(); - - path = System.getProperty("user.dir")+"/resources/javFiles/packageTest/OLextends.jav"; - fileToTest = new File(path); - compiler = new JavaTXCompiler( - Lists.newArrayList(new File(rootDirectory+"/OLextends.jav")), - Lists.newArrayList(new File(rootDirectory+"/de/test/output/"))); - //compiler = new JavaTXCompiler(fileToTest); - pathToClassFile = System.getProperty("user.dir")+"/resources/javFiles/packageTest/"; - compiler.generateBytecode(pathToClassFile); - loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile), new URL("file://"+ rootDirectory + "/de/test/output/")}); - classToTest1 = loader.loadClass("OLextends"); - instanceOfClass1 = classToTest1.getDeclaredConstructor().newInstance(); - - path = System.getProperty("user.dir")+"/resources/javFiles/packageTest/OLMain.jav"; - fileToTest = new File(path); - compiler = new JavaTXCompiler( - Lists.newArrayList(new File(rootDirectory+"/OLMain.jav")), - Lists.newArrayList(new File(rootDirectory+"/de/test/output/"))); - //compiler = new JavaTXCompiler(fileToTest); - pathToClassFile = System.getProperty("user.dir")+"/resources/javFiles/packageTest/"; - compiler.generateBytecode(pathToClassFile); - loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile), new URL("file://"+ rootDirectory + "/de/test/output/")}); - classToTest2 = loader.loadClass("OLMain"); - instanceOfClass2 = classToTest2.getDeclaredConstructor().newInstance(); - } - - @Test - public void testOLClassName() { - assertEquals("de.test.OL", classToTest.getName()); - } - - @Test - public void testmInt() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method m = classToTest.getDeclaredMethod("m", Integer.class); - Integer result = (Integer) m.invoke(instanceOfClass, 5); - assertEquals(new Integer(10), result); - } - - @Test - public void testmDouble() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method m = classToTest.getDeclaredMethod("m", Double.class); - Double result = (Double) m.invoke(instanceOfClass, 5.0); - assertEquals(new Double(10.0), result); - } - - @Test - public void testmString() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method m = classToTest.getDeclaredMethod("m", String.class); - String result = (String) m.invoke(instanceOfClass, "xxx"); - assertEquals("xxxxxx", result); - } - - @Test - public void testOLextendsClassName() { - assertEquals("OLextends", classToTest1.getName()); - } - - @Test - public void testextendsInt() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method main = classToTest1.getMethod("m", Integer.class); - Integer result = (Integer) main.invoke(instanceOfClass1, 5); - assertEquals(new Integer(10), result); - } - - @Test - public void testextendsDouble() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method main = classToTest1.getMethod("m", Double.class); - Double result = (Double) main.invoke(instanceOfClass1, 5.0); - assertEquals(new Double(10.0), result); - } - - @Test - public void testextendsString() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method main = classToTest1.getMethod("m", String.class); - String result = (String) main.invoke(instanceOfClass1, "xxx"); - assertEquals("xxxxxx", result); - } - - @Test - public void testOLMainClassName() { - assertEquals("OLMain", classToTest2.getName()); - } - - @Test - public void testmainInt() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method main = classToTest2.getDeclaredMethod("main", Integer.class); - Integer result = (Integer) main.invoke(instanceOfClass2, 5); - assertEquals(new Integer(10), result); - } - - @Test - public void testmainDouble() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method main = classToTest2.getDeclaredMethod("main", Double.class); - Double result = (Double) main.invoke(instanceOfClass2, 5.0); - assertEquals(new Double(10.0), result); - } - - @Test - public void testmainString() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method main = classToTest2.getDeclaredMethod("main", String.class); - String result = (String) main.invoke(instanceOfClass2, "xxx"); - assertEquals("xxxxxx", result); - } -} diff --git a/src/test/java/packages/ParsePackageName.java b/src/test/java/packages/ParsePackageName.java deleted file mode 100644 index ba5abac7..00000000 --- a/src/test/java/packages/ParsePackageName.java +++ /dev/null @@ -1,21 +0,0 @@ -package packages; - -import de.dhbwstuttgart.core.JavaTXCompiler; -import de.dhbwstuttgart.syntaxtree.SourceFile; -import org.junit.Test; - -import java.io.File; -import java.io.IOException; - -public class ParsePackageName { - - public static final String rootDirectory = System.getProperty("user.dir")+"/resources/javFiles/packageTest/de/test/"; - @Test - public void parsePackage() throws IOException, ClassNotFoundException { - JavaTXCompiler compiler = new JavaTXCompiler(new File(rootDirectory+"TestClass.jav")); - for(File f : compiler.sourceFiles.keySet()){ - SourceFile sf = compiler.sourceFiles.get(f); - assert sf.getPkgName().equals("de.test"); - } - } -} diff --git a/src/test/java/packages/mathStrucMatrixOPTest.java.txt b/src/test/java/packages/mathStrucMatrixOPTest.java.txt deleted file mode 100644 index c9c24969..00000000 --- a/src/test/java/packages/mathStrucMatrixOPTest.java.txt +++ /dev/null @@ -1,51 +0,0 @@ -package packages; - -import com.google.common.collect.Lists; -import de.dhbwstuttgart.core.JavaTXCompiler; -import junit.framework.TestCase; -import org.junit.Before; -import org.junit.Test; - -import java.io.File; -import java.io.IOException; -import java.net.URL; - -public class mathStrucMatrixOPTest extends TestCase { - - public static final String rootDirectory = System.getProperty("user.dir")+"/resources/javFiles/packageTest/de/test/"; - - - public mathStrucMatrixOPTest() throws ClassNotFoundException, IOException { - /* - Generate ToImport class in rootDirectory and in output-Directory - */ - /* PL 2020-01-07 kann z.Zt. nicht erzeugt werden (siehe Bug 170, http://bugzilla.ba-horb.de/show_bug.cgi?id=170) - JavaTXCompiler compiler = new JavaTXCompiler(new File(rootDirectory+"mathStruc.jav")); - compiler.typeInference(); - compiler.generateBytecode(rootDirectory + "output/"); - File f = new File(rootDirectory + "output/de/test/mathStruc.class"); - assertTrue(f.exists()); -*/ - JavaTXCompiler compiler = new JavaTXCompiler(new File(rootDirectory+"MatrixOP.jav")); - compiler.typeInference(); - compiler.generateBytecode(rootDirectory + "output/"); - File f = new File(rootDirectory + "output/de/test/MatrixOP.class"); - assertTrue(f.exists()); - - } - - @Test - public void testSetPackageNameInBytecodeAndOutputFolder() throws IOException, ClassNotFoundException { - JavaTXCompiler compiler = new JavaTXCompiler( - Lists.newArrayList(new File(rootDirectory+"mathStrucMatrixOP.jav")), - Lists.newArrayList(new File(rootDirectory+"output/"))); - compiler.typeInference(); - File f = new File(rootDirectory + "output/de/test/mathStrucMatrixOP.class"); - if(f.exists() && !f.isDirectory()) { - f.delete(); - } - compiler.generateBytecode(rootDirectory + "output/"); - f = new File(rootDirectory + "output/de/test/mathStrucMatrixOP.class"); - assertTrue(f.exists()); - } -} diff --git a/src/test/java/packages/mathStrucVectorTest.java b/src/test/java/packages/mathStrucVectorTest.java deleted file mode 100644 index 0d299d7b..00000000 --- a/src/test/java/packages/mathStrucVectorTest.java +++ /dev/null @@ -1,54 +0,0 @@ -package packages; - -import com.google.common.collect.Lists; -import de.dhbwstuttgart.core.JavaTXCompiler; -import junit.framework.TestCase; -import org.junit.Before; -import org.junit.Test; - -import java.io.File; -import java.io.IOException; -import java.net.URL; - -public class mathStrucVectorTest extends TestCase { - - public static final String rootDirectory = System.getProperty("user.dir")+"/resources/javFiles/packageTest/de/test/"; - - - public mathStrucVectorTest() throws ClassNotFoundException, IOException { - /* - Generate ToImport class in rootDirectory and in output-Directory - */ - -/* PL 2020-01-07 kann z.Zt. nicht erzeugt werden (siehe Bug 170, http://bugzilla.ba-horb.de/show_bug.cgi?id=170) - JavaTXCompiler compiler = new JavaTXCompiler(new File(rootDirectory+"mathStruc.jav")); - compiler.typeInference(); - compiler.generateBytecode(rootDirectory + "output/"); - File f = new File(rootDirectory + "output/de/test/mathStruc.class"); - assertTrue(f.exists()); - */ - JavaTXCompiler compiler = new JavaTXCompiler(new File(rootDirectory+"vectorAdd.jav")); - compiler.typeInference(); - compiler.generateBytecode(rootDirectory + "output/"); - File f = new File(rootDirectory + "output/de/test/vectorAdd.class"); - assertTrue(f.exists()); - - } - - @Test - public void testSetPackageNameInBytecodeAndOutputFolder() throws IOException, ClassNotFoundException { - JavaTXCompiler compiler = new JavaTXCompiler( - Lists.newArrayList(new File(rootDirectory+"mathStrucVector.jav")), - Lists.newArrayList(new File(rootDirectory+"output/"))); - compiler.typeInference(); - File f = new File(rootDirectory + "output/de/test/mathStrucVector.class"); - if(f.exists() && !f.isDirectory()) { - f.delete(); - } - compiler.generateBytecode(rootDirectory + "output/"); - f = new File(rootDirectory + "output/de/test/mathStrucVector.class"); - assertTrue(f.exists()); - } - - -} diff --git a/src/test/java/parser/AntlrTest.jav b/src/test/java/parser/AntlrTest.jav deleted file mode 100644 index 31ab067d..00000000 --- a/src/test/java/parser/AntlrTest.jav +++ /dev/null @@ -1,6 +0,0 @@ -class Test{ -method(){ - if(true)i++; - if(true)i--; - else i++; -}} \ No newline at end of file diff --git a/src/test/java/parser/BoundedParameter.jav b/src/test/java/parser/BoundedParameter.jav deleted file mode 100644 index 6d7518a9..00000000 --- a/src/test/java/parser/BoundedParameter.jav +++ /dev/null @@ -1,3 +0,0 @@ -class Matrix{ - String op = "String"; -} diff --git a/src/test/java/parser/CastTest.jav b/src/test/java/parser/CastTest.jav deleted file mode 100644 index 86ca7519..00000000 --- a/src/test/java/parser/CastTest.jav +++ /dev/null @@ -1,8 +0,0 @@ - -class CastTest{ -void methode(){ - Object a; - String b; - a = (Object) b; -} -} \ No newline at end of file diff --git a/src/test/java/parser/ExtendsTest.jav b/src/test/java/parser/ExtendsTest.jav deleted file mode 100644 index 9103f463..00000000 --- a/src/test/java/parser/ExtendsTest.jav +++ /dev/null @@ -1,4 +0,0 @@ -class C1 extends Object -{ - m(para) { return para; } -} \ No newline at end of file diff --git a/src/test/java/parser/FeatherWeightJava.jav b/src/test/java/parser/FeatherWeightJava.jav deleted file mode 100644 index e607b12a..00000000 --- a/src/test/java/parser/FeatherWeightJava.jav +++ /dev/null @@ -1,11 +0,0 @@ - -class FeatherWeightJava { - mt4(a,b,c) { return a.add(b).sub(c) ; } - - mt1(a) {return a; } - - mt2(a) {return a.f; } - - mt3(a) {return a.add(); } -} - diff --git a/src/test/java/parser/FieldInitializationTest.jav b/src/test/java/parser/FieldInitializationTest.jav deleted file mode 100644 index f7818cc3..00000000 --- a/src/test/java/parser/FieldInitializationTest.jav +++ /dev/null @@ -1,3 +0,0 @@ -class FieldInitializationTest{ - var var = "hallo"; -} \ No newline at end of file diff --git a/src/test/java/parser/FieldVarTest.jav b/src/test/java/parser/FieldVarTest.jav deleted file mode 100644 index 6e897824..00000000 --- a/src/test/java/parser/FieldVarTest.jav +++ /dev/null @@ -1,5 +0,0 @@ -package test; - -class Test{ -Typ a; -} \ No newline at end of file diff --git a/src/test/java/parser/GeneralParserTest.java b/src/test/java/parser/GeneralParserTest.java deleted file mode 100644 index 4e7d9868..00000000 --- a/src/test/java/parser/GeneralParserTest.java +++ /dev/null @@ -1,55 +0,0 @@ -package parser; - -import static org.junit.Assert.*; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; -import java.util.stream.Collectors; - -import de.dhbwstuttgart.core.JavaTXCompiler; -import de.dhbwstuttgart.parser.JavaTXParser; - -import org.junit.Test; - - -/** - * Dieser Test pr�ft nur, ob .java-Dateien fehlerfrei geparst werden. - * Der dabei erstellte Syntaxbaum wird nicht kontrolliert. - * @author janulrich - * - */ -public class GeneralParserTest{ - private static final String rootDirectory = System.getProperty("user.dir")+"/test/parser/"; - - @Test - public void run(){ - - - List filenames = new ArrayList(); - /* - filenames.add("NewTest.jav"); - filenames.add("FieldInitializationTest.jav"); - filenames.add("ImportTest.jav"); - filenames.add("CastTest.jav"); - filenames.add("StatementsTest.jav"); - //filenames.add("Methods.jav"); - filenames.add("ImportTestGeneric.jav"); - filenames.add("CastTest.jav"); - //filenames.add("BoundedParameter.jav"); - //filenames.add("GenericFieldVarTest.jav"); - filenames.add("FieldVarTest.jav"); - filenames.add("StructuralTypes.jav"); - */ -// filenames.add("ExtendsTest.jav"); - filenames.add("PackageNameTest.jav"); - try{ - new JavaTXCompiler(filenames.stream().map(s -> new File(rootDirectory + s)).collect(Collectors.toList())); - }catch(Exception exc){ - exc.printStackTrace(); - fail(); - } - assertTrue("Tests durchlaufen",filenames.size()>0); - } - -} diff --git a/src/test/java/parser/GenericFieldVarTest.jav b/src/test/java/parser/GenericFieldVarTest.jav deleted file mode 100644 index a47b41eb..00000000 --- a/src/test/java/parser/GenericFieldVarTest.jav +++ /dev/null @@ -1,3 +0,0 @@ -class Test{ - A var; -} diff --git a/src/test/java/parser/ImportTest.jav b/src/test/java/parser/ImportTest.jav deleted file mode 100644 index 2de55cee..00000000 --- a/src/test/java/parser/ImportTest.jav +++ /dev/null @@ -1,4 +0,0 @@ -import java.util.*; - -class ImportTest{ -} \ No newline at end of file diff --git a/src/test/java/parser/ImportTest2.jav b/src/test/java/parser/ImportTest2.jav deleted file mode 100644 index 3492e31c..00000000 --- a/src/test/java/parser/ImportTest2.jav +++ /dev/null @@ -1,4 +0,0 @@ -import java.util.ArrayList; - -class ImportTest{ -} \ No newline at end of file diff --git a/src/test/java/parser/ImportTestGeneric.jav b/src/test/java/parser/ImportTestGeneric.jav deleted file mode 100644 index 094f4c5e..00000000 --- a/src/test/java/parser/ImportTestGeneric.jav +++ /dev/null @@ -1,5 +0,0 @@ -import java.util.List; - -class ImportTest{ - List test; -} \ No newline at end of file diff --git a/src/test/java/parser/NewTest.jav b/src/test/java/parser/NewTest.jav deleted file mode 100644 index 992a2e8d..00000000 --- a/src/test/java/parser/NewTest.jav +++ /dev/null @@ -1,5 +0,0 @@ - -class NewTest { -main() { return new NewTest<>().mt(new NewTest(1) , new NewTest(2) , new -NewTest(3)); } -} \ No newline at end of file diff --git a/src/test/java/parser/OpratorTest.jav b/src/test/java/parser/OpratorTest.jav deleted file mode 100644 index 2764adf4..00000000 --- a/src/test/java/parser/OpratorTest.jav +++ /dev/null @@ -1,12 +0,0 @@ -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 diff --git a/src/test/java/parser/PackageNameTest.jav b/src/test/java/parser/PackageNameTest.jav deleted file mode 100644 index 53c889b7..00000000 --- a/src/test/java/parser/PackageNameTest.jav +++ /dev/null @@ -1,9 +0,0 @@ -import java.lang.Integer; -import java.lang.Comparable; - -class PackageNameTest{ -java.lang.Integer test(a){return a;} - -Comparable test2(a){return a;} - -} \ No newline at end of file diff --git a/src/test/java/parser/StatementsTest.jav b/src/test/java/parser/StatementsTest.jav deleted file mode 100644 index 891dff12..00000000 --- a/src/test/java/parser/StatementsTest.jav +++ /dev/null @@ -1,8 +0,0 @@ -class Statements{ - -public void methodeTest(){ - methodeTest(); - return null; -} - -} diff --git a/src/test/java/parser/StructuralTypes.jav b/src/test/java/parser/StructuralTypes.jav deleted file mode 100644 index b3c210c8..00000000 --- a/src/test/java/parser/StructuralTypes.jav +++ /dev/null @@ -1,5 +0,0 @@ - -class A { - mt(x, y, z) { return x.sub(y).add(z); } -} - diff --git a/src/test/java/parser/WhileTest.jav b/src/test/java/parser/WhileTest.jav deleted file mode 100644 index 2ce192bd..00000000 --- a/src/test/java/parser/WhileTest.jav +++ /dev/null @@ -1,14 +0,0 @@ -class WhileTest{ - void methode(){ - Boolean test; - do{ - test=test; - }while(test); - - - while(test){ - test = test; - } - return; - } -} \ No newline at end of file diff --git a/src/test/java/syntaxtreegenerator/TestComplete.java b/src/test/java/syntaxtreegenerator/TestComplete.java new file mode 100644 index 00000000..e60f01d8 --- /dev/null +++ b/src/test/java/syntaxtreegenerator/TestComplete.java @@ -0,0 +1,866 @@ +package syntaxtreegenerator; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.io.File; +import java.io.FileFilter; +import java.io.FileInputStream; +import java.util.HashMap; + +import org.junit.BeforeClass; +import org.junit.Test; + +import de.dhbwstuttgart.core.JavaTXCompiler; +import de.dhbwstuttgart.exceptions.NotImplementedException; +import de.dhbwstuttgart.syntaxtree.visual.ASTPrinter; + +/** + * Unit-Tests für den 'SyntaxTreeGenerator' aus dem Package 'parser' nach Vorbild der Klasse 'TestComplete' aus dem Test-Package 'targetast' + */ +public class TestComplete { + private static HashMap javFiles = new HashMap<>(); + + @BeforeClass + public static void setUp() { + final String testFileDirectory = "resources/bytecode/javFiles/"; + final String expectedASTDirectory = "resources/syntaxtreegenerator/"; + File dir = new File(testFileDirectory); + for (File f : dir.listFiles(new JavFilter())) { + String basefilename = f.getName().replace(".jav", ""); + javFiles.put(basefilename, new File[] { f, new File(expectedASTDirectory + basefilename + ".ast") }); + } + } + + @Test + public void applyLambdaTest() { + try { + FileInputStream fileIn = new FileInputStream(javFiles.get("applyLambda")[1]); + String expectedAST = new String(fileIn.readAllBytes()); + fileIn.close(); + expectedAST = expectedAST.replaceAll("TPH [A-Z]+", "TPH"); + File srcfile = javFiles.get("applyLambda")[0]; + JavaTXCompiler compiler = new JavaTXCompiler(srcfile); + String resultingAST = new String(ASTPrinter.print(compiler.sourceFiles.get(srcfile))); + resultingAST = resultingAST.replaceAll("TPH [A-Z]+", "TPH"); + System.out.println("Expected:\n" + new String(expectedAST)); + System.out.println("Result:\n" + new String(resultingAST)); + assertEquals("Comparing expected and resulting AST for applyLambda.jav", expectedAST, resultingAST); + } catch (Exception exc) { + exc.printStackTrace(); + fail("An error occured while generating the AST for applyLambda.jav"); + } + } + + @Test + public void binaryInMethTest() { + try { + FileInputStream fileIn = new FileInputStream(javFiles.get("BinaryInMeth")[1]); + String expectedAST = new String(fileIn.readAllBytes()); + fileIn.close(); + expectedAST = expectedAST.replaceAll("TPH [A-Z]+", "TPH"); + File srcfile = javFiles.get("BinaryInMeth")[0]; + JavaTXCompiler compiler = new JavaTXCompiler(srcfile); + String resultingAST = new String(ASTPrinter.print(compiler.sourceFiles.get(srcfile))); + resultingAST = resultingAST.replaceAll("TPH [A-Z]+", "TPH"); + System.out.println("Expected:\n" + new String(expectedAST)); + System.out.println("Result:\n" + new String(resultingAST)); + assertEquals("Comparing expected and resulting AST for BinaryInMeth.jav", expectedAST, resultingAST); + } catch (Exception exc) { + exc.printStackTrace(); + fail("An error occured while generating the AST for BinaryInMeth.jav"); + } + } + + @Test + public void classGenLamTest() { + try { + FileInputStream fileIn = new FileInputStream(javFiles.get("ClassGenLam")[1]); + String expectedAST = new String(fileIn.readAllBytes()); + fileIn.close(); + expectedAST = expectedAST.replaceAll("TPH [A-Z]+", "TPH"); + File srcfile = javFiles.get("ClassGenLam")[0]; + JavaTXCompiler compiler = new JavaTXCompiler(srcfile); + String resultingAST = new String(ASTPrinter.print(compiler.sourceFiles.get(srcfile))); + resultingAST = resultingAST.replaceAll("TPH [A-Z]+", "TPH"); + System.out.println("Expected:\n" + new String(expectedAST)); + System.out.println("Result:\n" + new String(resultingAST)); + assertEquals("Comparing expected and resulting AST for ClassGenLam.jav", expectedAST, resultingAST); + } catch (Exception exc) { + exc.printStackTrace(); + fail("An error occured while generating the AST for ClassGenLam.jav"); + } + } + + @Test + public void facTest() { + try { + FileInputStream fileIn = new FileInputStream(javFiles.get("Fac")[1]); + String expectedAST = new String(fileIn.readAllBytes()); + fileIn.close(); + expectedAST = expectedAST.replaceAll("TPH [A-Z]+", "TPH"); + File srcfile = javFiles.get("Fac")[0]; + JavaTXCompiler compiler = new JavaTXCompiler(srcfile); + String resultingAST = new String(ASTPrinter.print(compiler.sourceFiles.get(srcfile))); + resultingAST = resultingAST.replaceAll("TPH [A-Z]+", "TPH"); + System.out.println("Expected:\n" + new String(expectedAST)); + System.out.println("Result:\n" + new String(resultingAST)); + assertEquals("Comparing expected and resulting AST for Fac.jav", expectedAST, resultingAST); + } catch (Exception exc) { + exc.printStackTrace(); + fail("An error occured while generating the AST for Fac.jav"); + } + } + + @Test + public void facultyTest() { + try { + FileInputStream fileIn = new FileInputStream(javFiles.get("Faculty")[1]); + String expectedAST = new String(fileIn.readAllBytes()); + fileIn.close(); + expectedAST = expectedAST.replaceAll("TPH [A-Z]+", "TPH"); + File srcfile = javFiles.get("Faculty")[0]; + JavaTXCompiler compiler = new JavaTXCompiler(srcfile); + String resultingAST = new String(ASTPrinter.print(compiler.sourceFiles.get(srcfile))); + resultingAST = resultingAST.replaceAll("TPH [A-Z]+", "TPH"); + System.out.println("Expected:\n" + new String(expectedAST)); + System.out.println("Result:\n" + new String(resultingAST)); + assertEquals("Comparing expected and resulting AST for Faculty.jav", expectedAST, resultingAST); + } catch (Exception exc) { + exc.printStackTrace(); + fail("An error occured while generating the AST for Faculty.jav"); + } + } + + @Test + public void fieldTest() { + try { + FileInputStream fileIn = new FileInputStream(javFiles.get("Field")[1]); + String expectedAST = new String(fileIn.readAllBytes()); + fileIn.close(); + expectedAST = expectedAST.replaceAll("TPH [A-Z]+", "TPH"); + File srcfile = javFiles.get("Field")[0]; + JavaTXCompiler compiler = new JavaTXCompiler(srcfile); + String resultingAST = new String(ASTPrinter.print(compiler.sourceFiles.get(srcfile))); + resultingAST = resultingAST.replaceAll("TPH [A-Z]+", "TPH"); + System.out.println("Expected:\n" + new String(expectedAST)); + System.out.println("Result:\n" + new String(resultingAST)); + assertEquals("Comparing expected and resulting AST for Field.jav", expectedAST, resultingAST); + } catch (Exception exc) { + exc.printStackTrace(); + fail("An error occured while generating the AST for Field.jav"); + } + } + + @Test + public void fieldTph2Test() { + try { + FileInputStream fileIn = new FileInputStream(javFiles.get("FieldTph2")[1]); + String expectedAST = new String(fileIn.readAllBytes()); + fileIn.close(); + expectedAST = expectedAST.replaceAll("TPH [A-Z]+", "TPH"); + File srcfile = javFiles.get("FieldTph2")[0]; + JavaTXCompiler compiler = new JavaTXCompiler(srcfile); + String resultingAST = new String(ASTPrinter.print(compiler.sourceFiles.get(srcfile))); + resultingAST = resultingAST.replaceAll("TPH [A-Z]+", "TPH"); + System.out.println("Expected:\n" + new String(expectedAST)); + System.out.println("Result:\n" + new String(resultingAST)); + assertEquals("Comparing expected and resulting AST for FieldTph2.jav", expectedAST, resultingAST); + } catch (Exception exc) { + exc.printStackTrace(); + fail("An error occured while generating the AST for FieldTph2.jav"); + } + } + + @Test + public void fieldTphConsMethTest() { + try { + FileInputStream fileIn = new FileInputStream(javFiles.get("FieldTphConsMeth")[1]); + String expectedAST = new String(fileIn.readAllBytes()); + fileIn.close(); + expectedAST = expectedAST.replaceAll("TPH [A-Z]+", "TPH"); + File srcfile = javFiles.get("FieldTphConsMeth")[0]; + JavaTXCompiler compiler = new JavaTXCompiler(srcfile); + String resultingAST = new String(ASTPrinter.print(compiler.sourceFiles.get(srcfile))); + resultingAST = resultingAST.replaceAll("TPH [A-Z]+", "TPH"); + System.out.println("Expected:\n" + new String(expectedAST)); + System.out.println("Result:\n" + new String(resultingAST)); + assertEquals("Comparing expected and resulting AST for FieldTphConsMeth.jav", expectedAST, resultingAST); + } catch (Exception exc) { + exc.printStackTrace(); + fail("An error occured while generating the AST for FieldTphConsMeth.jav"); + } + } + + @Test + public void fieldTphMMethTest() { + try { + FileInputStream fileIn = new FileInputStream(javFiles.get("FieldTphMMeth")[1]); + String expectedAST = new String(fileIn.readAllBytes()); + fileIn.close(); + expectedAST = expectedAST.replaceAll("TPH [A-Z]+", "TPH"); + File srcfile = javFiles.get("FieldTphMMeth")[0]; + JavaTXCompiler compiler = new JavaTXCompiler(srcfile); + String resultingAST = new String(ASTPrinter.print(compiler.sourceFiles.get(srcfile))); + resultingAST = resultingAST.replaceAll("TPH [A-Z]+", "TPH"); + System.out.println("Expected:\n" + new String(expectedAST)); + System.out.println("Result:\n" + new String(resultingAST)); + assertEquals("Comparing expected and resulting AST for FieldTphMMeth.jav", expectedAST, resultingAST); + } catch (Exception exc) { + exc.printStackTrace(); + fail("An error occured while generating the AST for FieldTphMMeth.jav"); + } + } + + @Test + public void genTest() { + try { + FileInputStream fileIn = new FileInputStream(javFiles.get("Gen")[1]); + String expectedAST = new String(fileIn.readAllBytes()); + fileIn.close(); + expectedAST = expectedAST.replaceAll("TPH [A-Z]+", "TPH"); + File srcfile = javFiles.get("Gen")[0]; + JavaTXCompiler compiler = new JavaTXCompiler(srcfile); + String resultingAST = new String(ASTPrinter.print(compiler.sourceFiles.get(srcfile))); + resultingAST = resultingAST.replaceAll("TPH [A-Z]+", "TPH"); + System.out.println("Expected:\n" + new String(expectedAST)); + System.out.println("Result:\n" + new String(resultingAST)); + assertEquals("Comparing expected and resulting AST for Gen.jav", expectedAST, resultingAST); + } catch (Exception exc) { + exc.printStackTrace(); + fail("An error occured while generating the AST for Gen.jav"); + } + } + + @Test + public void idTest() { + try { + FileInputStream fileIn = new FileInputStream(javFiles.get("Id")[1]); + String expectedAST = new String(fileIn.readAllBytes()); + fileIn.close(); + expectedAST = expectedAST.replaceAll("TPH [A-Z]+", "TPH"); + File srcfile = javFiles.get("Id")[0]; + JavaTXCompiler compiler = new JavaTXCompiler(srcfile); + String resultingAST = new String(ASTPrinter.print(compiler.sourceFiles.get(srcfile))); + resultingAST = resultingAST.replaceAll("TPH [A-Z]+", "TPH"); + System.out.println("Expected:\n" + new String(expectedAST)); + System.out.println("Result:\n" + new String(resultingAST)); + assertEquals("Comparing expected and resulting AST for Id.jav", expectedAST, resultingAST); + } catch (Exception exc) { + exc.printStackTrace(); + fail("An error occured while generating the AST for Id.jav"); + } + } + + @Test + public void infTest() { + try { + FileInputStream fileIn = new FileInputStream(javFiles.get("Inf")[1]); + String expectedAST = new String(fileIn.readAllBytes()); + fileIn.close(); + expectedAST = expectedAST.replaceAll("TPH [A-Z]+", "TPH"); + File srcfile = javFiles.get("Inf")[0]; + JavaTXCompiler compiler = new JavaTXCompiler(srcfile); + String resultingAST = new String(ASTPrinter.print(compiler.sourceFiles.get(srcfile))); + resultingAST = resultingAST.replaceAll("TPH [A-Z]+", "TPH"); + System.out.println("Expected:\n" + new String(expectedAST)); + System.out.println("Result:\n" + new String(resultingAST)); + assertEquals("Comparing expected and resulting AST for Inf.jav", expectedAST, resultingAST); + } catch (Exception exc) { + exc.printStackTrace(); + fail("An error occured while generating the AST for Inf.jav"); + } + } + + @Test + public void kompTphTest() { + try { + FileInputStream fileIn = new FileInputStream(javFiles.get("KompTph")[1]); + String expectedAST = new String(fileIn.readAllBytes()); + fileIn.close(); + expectedAST = expectedAST.replaceAll("TPH [A-Z]+", "TPH"); + File srcfile = javFiles.get("KompTph")[0]; + JavaTXCompiler compiler = new JavaTXCompiler(srcfile); + String resultingAST = new String(ASTPrinter.print(compiler.sourceFiles.get(srcfile))); + resultingAST = resultingAST.replaceAll("TPH [A-Z]+", "TPH"); + System.out.println("Expected:\n" + new String(expectedAST)); + System.out.println("Result:\n" + new String(resultingAST)); + assertEquals("Comparing expected and resulting AST for KompTph.jav", expectedAST, resultingAST); + } catch (Exception exc) { + exc.printStackTrace(); + fail("An error occured while generating the AST for KompTph.jav"); + } + } + + @Test + public void lambdaCaptureTest() { + try { + FileInputStream fileIn = new FileInputStream(javFiles.get("LambdaCapture")[1]); + String expectedAST = new String(fileIn.readAllBytes()); + fileIn.close(); + expectedAST = expectedAST.replaceAll("TPH [A-Z]+", "TPH"); + File srcfile = javFiles.get("LambdaCapture")[0]; + JavaTXCompiler compiler = new JavaTXCompiler(srcfile); + String resultingAST = new String(ASTPrinter.print(compiler.sourceFiles.get(srcfile))); + resultingAST = resultingAST.replaceAll("TPH [A-Z]+", "TPH"); + System.out.println("Expected:\n" + new String(expectedAST)); + System.out.println("Result:\n" + new String(resultingAST)); + assertEquals("Comparing expected and resulting AST for LambdaCapture.jav", expectedAST, resultingAST); + } catch (Exception exc) { + exc.printStackTrace(); + fail("An error occured while generating the AST for LambdaCapture.jav"); + } + } + + @Test + public void lambdaTest() { + try { + FileInputStream fileIn = new FileInputStream(javFiles.get("Lambda")[1]); + String expectedAST = new String(fileIn.readAllBytes()); + fileIn.close(); + expectedAST = expectedAST.replaceAll("TPH [A-Z]+", "TPH"); + File srcfile = javFiles.get("Lambda")[0]; + JavaTXCompiler compiler = new JavaTXCompiler(srcfile); + String resultingAST = new String(ASTPrinter.print(compiler.sourceFiles.get(srcfile))); + resultingAST = resultingAST.replaceAll("TPH [A-Z]+", "TPH"); + System.out.println("Expected:\n" + new String(expectedAST)); + System.out.println("Result:\n" + new String(resultingAST)); + assertEquals("Comparing expected and resulting AST for Lambda.jav", expectedAST, resultingAST); + } catch (Exception exc) { + exc.printStackTrace(); + fail("An error occured while generating the AST for Lambda.jav"); + } + } + + @Test + public void mathStrucIntegerTest() { + try { + FileInputStream fileIn = new FileInputStream(javFiles.get("mathStrucInteger")[1]); + String expectedAST = new String(fileIn.readAllBytes()); + fileIn.close(); + expectedAST = expectedAST.replaceAll("TPH [A-Z]+", "TPH"); + File srcfile = javFiles.get("mathStrucInteger")[0]; + JavaTXCompiler compiler = new JavaTXCompiler(srcfile); + String resultingAST = new String(ASTPrinter.print(compiler.sourceFiles.get(srcfile))); + resultingAST = resultingAST.replaceAll("TPH [A-Z]+", "TPH"); + System.out.println("Expected:\n" + new String(expectedAST)); + System.out.println("Result:\n" + new String(resultingAST)); + assertEquals("Comparing expected and resulting AST for mathStrucInteger.jav", expectedAST, resultingAST); + } catch (Exception exc) { + exc.printStackTrace(); + assertTrue("An error occured while generating the AST for mathStrucInteger.jav", exc instanceof NotImplementedException); + } + } + + @Test + public void mathStrucTest() { + try { + FileInputStream fileIn = new FileInputStream(javFiles.get("mathStruc")[1]); + String expectedAST = new String(fileIn.readAllBytes()); + fileIn.close(); + expectedAST = expectedAST.replaceAll("TPH [A-Z]+", "TPH"); + File srcfile = javFiles.get("mathStruc")[0]; + JavaTXCompiler compiler = new JavaTXCompiler(srcfile); + String resultingAST = new String(ASTPrinter.print(compiler.sourceFiles.get(srcfile))); + resultingAST = resultingAST.replaceAll("TPH [A-Z]+", "TPH"); + System.out.println("Expected:\n" + new String(expectedAST)); + System.out.println("Result:\n" + new String(resultingAST)); + assertEquals("Comparing expected and resulting AST for mathStruc.jav", expectedAST, resultingAST); + } catch (Exception exc) { + exc.printStackTrace(); + fail("An error occured while generating the AST for mathStruc.jav"); + } + } + + @Test + public void matrixOPTest() { + try { + FileInputStream fileIn = new FileInputStream(javFiles.get("MatrixOP")[1]); + String expectedAST = new String(fileIn.readAllBytes()); + fileIn.close(); + expectedAST = expectedAST.replaceAll("TPH [A-Z]+", "TPH"); + File srcfile = javFiles.get("MatrixOP")[0]; + JavaTXCompiler compiler = new JavaTXCompiler(srcfile); + String resultingAST = new String(ASTPrinter.print(compiler.sourceFiles.get(srcfile))); + resultingAST = resultingAST.replaceAll("TPH [A-Z]+", "TPH"); + System.out.println("Expected:\n" + new String(expectedAST)); + System.out.println("Result:\n" + new String(resultingAST)); + assertEquals("Comparing expected and resulting AST for MatrixOP.jav", expectedAST, resultingAST); + } catch (Exception exc) { + exc.printStackTrace(); + fail("An error occured while generating the AST for MatrixOP.jav"); + } + } + + @Test + public void matrixTest() { + try { + FileInputStream fileIn = new FileInputStream(javFiles.get("Matrix")[1]); + String expectedAST = new String(fileIn.readAllBytes()); + fileIn.close(); + expectedAST = expectedAST.replaceAll("TPH [A-Z]+", "TPH"); + File srcfile = javFiles.get("Matrix")[0]; + JavaTXCompiler compiler = new JavaTXCompiler(srcfile); + String resultingAST = new String(ASTPrinter.print(compiler.sourceFiles.get(srcfile))); + resultingAST = resultingAST.replaceAll("TPH [A-Z]+", "TPH"); + System.out.println("Expected:\n" + new String(expectedAST)); + System.out.println("Result:\n" + new String(resultingAST)); + assertEquals("Comparing expected and resulting AST for Matrix.jav", expectedAST, resultingAST); + } catch (Exception exc) { + exc.printStackTrace(); + fail("An error occured while generating the AST for Matrix.jav"); + } + } + + @Test + public void mergeTest() { + try { + FileInputStream fileIn = new FileInputStream(javFiles.get("Merge")[1]); + String expectedAST = new String(fileIn.readAllBytes()); + fileIn.close(); + expectedAST = expectedAST.replaceAll("TPH [A-Z]+", "TPH"); + File srcfile = javFiles.get("Merge")[0]; + JavaTXCompiler compiler = new JavaTXCompiler(srcfile); + String resultingAST = new String(ASTPrinter.print(compiler.sourceFiles.get(srcfile))); + resultingAST = resultingAST.replaceAll("TPH [A-Z]+", "TPH"); + System.out.println("Expected:\n" + new String(expectedAST)); + System.out.println("Result:\n" + new String(resultingAST)); + assertEquals("Comparing expected and resulting AST for Merge.jav", expectedAST, resultingAST); + } catch (Exception exc) { + exc.printStackTrace(); + fail("An error occured while generating the AST for Merge.jav"); + } + } + + @Test + public void overloadingSortingTest() { + try { + FileInputStream fileIn = new FileInputStream(javFiles.get("Sorting")[1]); + String expectedAST = new String(fileIn.readAllBytes()); + fileIn.close(); + expectedAST = expectedAST.replaceAll("TPH [A-Z]+", "TPH"); + File srcfile = javFiles.get("Sorting")[0]; + JavaTXCompiler compiler = new JavaTXCompiler(srcfile); + String resultingAST = new String(ASTPrinter.print(compiler.sourceFiles.get(srcfile))); + resultingAST = resultingAST.replaceAll("TPH [A-Z]+", "TPH"); + System.out.println("Expected:\n" + new String(expectedAST)); + System.out.println("Result:\n" + new String(resultingAST)); + assertEquals("Comparing expected and resulting AST for Sorting.jav", expectedAST, resultingAST); + } catch (Exception exc) { + exc.printStackTrace(); + fail("An error occured while generating the AST for Sorting.jav"); + } + } + + @Test + public void overloadingTest() { + try { + FileInputStream fileIn = new FileInputStream(javFiles.get("Overloading")[1]); + String expectedAST = new String(fileIn.readAllBytes()); + fileIn.close(); + expectedAST = expectedAST.replaceAll("TPH [A-Z]+", "TPH"); + File srcfile = javFiles.get("Overloading")[0]; + JavaTXCompiler compiler = new JavaTXCompiler(srcfile); + String resultingAST = new String(ASTPrinter.print(compiler.sourceFiles.get(srcfile))); + resultingAST = resultingAST.replaceAll("TPH [A-Z]+", "TPH"); + System.out.println("Expected:\n" + new String(expectedAST)); + System.out.println("Result:\n" + new String(resultingAST)); + assertEquals("Comparing expected and resulting AST for Overloading.jav", expectedAST, resultingAST); + } catch (Exception exc) { + exc.printStackTrace(); + fail("An error occured while generating the AST for Overloading.jav"); + } + } + + @Test + public void plusTest() { + try { + FileInputStream fileIn = new FileInputStream(javFiles.get("Plus")[1]); + String expectedAST = new String(fileIn.readAllBytes()); + fileIn.close(); + expectedAST = expectedAST.replaceAll("TPH [A-Z]+", "TPH"); + File srcfile = javFiles.get("Plus")[0]; + JavaTXCompiler compiler = new JavaTXCompiler(srcfile); + String resultingAST = new String(ASTPrinter.print(compiler.sourceFiles.get(srcfile))); + resultingAST = resultingAST.replaceAll("TPH [A-Z]+", "TPH"); + System.out.println("Expected:\n" + new String(expectedAST)); + System.out.println("Result:\n" + new String(resultingAST)); + assertEquals("Comparing expected and resulting AST for Plus.jav", expectedAST, resultingAST); + } catch (Exception exc) { + exc.printStackTrace(); + fail("An error occured while generating the AST for Plus.jav"); + } + } + + @Test + public void relOpsTest() { + try { + FileInputStream fileIn = new FileInputStream(javFiles.get("RelOps")[1]); + String expectedAST = new String(fileIn.readAllBytes()); + fileIn.close(); + expectedAST = expectedAST.replaceAll("TPH [A-Z]+", "TPH"); + File srcfile = javFiles.get("RelOps")[0]; + JavaTXCompiler compiler = new JavaTXCompiler(srcfile); + String resultingAST = new String(ASTPrinter.print(compiler.sourceFiles.get(srcfile))); + resultingAST = resultingAST.replaceAll("TPH [A-Z]+", "TPH"); + System.out.println("Expected:\n" + new String(expectedAST)); + System.out.println("Result:\n" + new String(resultingAST)); + assertEquals("Comparing expected and resulting AST for RelOps.jav", expectedAST, resultingAST); + } catch (Exception exc) { + exc.printStackTrace(); + fail("An error occured while generating the AST for RelOps.jav"); + } + } + + @Test + public void simpleCycleTest() { + try { + FileInputStream fileIn = new FileInputStream(javFiles.get("SimpleCycle")[1]); + String expectedAST = new String(fileIn.readAllBytes()); + fileIn.close(); + expectedAST = expectedAST.replaceAll("TPH [A-Z]+", "TPH"); + File srcfile = javFiles.get("SimpleCycle")[0]; + JavaTXCompiler compiler = new JavaTXCompiler(srcfile); + String resultingAST = new String(ASTPrinter.print(compiler.sourceFiles.get(srcfile))); + resultingAST = resultingAST.replaceAll("TPH [A-Z]+", "TPH"); + System.out.println("Expected:\n" + new String(expectedAST)); + System.out.println("Result:\n" + new String(resultingAST)); + assertEquals("Comparing expected and resulting AST for SimpleCycle.jav", expectedAST, resultingAST); + } catch (Exception exc) { + exc.printStackTrace(); + fail("An error occured while generating the AST for SimpleCycle.jav"); + } + } + + @Test + public void subMatTest() { + try { + FileInputStream fileIn = new FileInputStream(javFiles.get("SubMatrix")[1]); + String expectedAST = new String(fileIn.readAllBytes()); + fileIn.close(); + expectedAST = expectedAST.replaceAll("TPH [A-Z]+", "TPH"); + File srcfile = javFiles.get("SubMatrix")[0]; + JavaTXCompiler compiler = new JavaTXCompiler(srcfile); + String resultingAST = new String(ASTPrinter.print(compiler.sourceFiles.get(srcfile))); + resultingAST = resultingAST.replaceAll("TPH [A-Z]+", "TPH"); + System.out.println("Expected:\n" + new String(expectedAST)); + System.out.println("Result:\n" + new String(resultingAST)); + assertEquals("Comparing expected and resulting AST for SubMatrix.jav", expectedAST, resultingAST); + } catch (Exception exc) { + exc.printStackTrace(); + fail("An error occured while generating the AST for SubMatrix.jav"); + } + } + + @Test + public void tphTest() { + try { + FileInputStream fileIn = new FileInputStream(javFiles.get("Tph")[1]); + String expectedAST = new String(fileIn.readAllBytes()); + fileIn.close(); + expectedAST = expectedAST.replaceAll("TPH [A-Z]+", "TPH"); + File srcfile = javFiles.get("Tph")[0]; + JavaTXCompiler compiler = new JavaTXCompiler(srcfile); + String resultingAST = new String(ASTPrinter.print(compiler.sourceFiles.get(srcfile))); + resultingAST = resultingAST.replaceAll("TPH [A-Z]+", "TPH"); + System.out.println("Expected:\n" + new String(expectedAST)); + System.out.println("Result:\n" + new String(resultingAST)); + assertEquals("Comparing expected and resulting AST for Tph.jav", expectedAST, resultingAST); + } catch (Exception exc) { + exc.printStackTrace(); + fail("An error occured while generating the AST for Tph.jav"); + } + } + + @Test + public void tph2Test() { + try { + FileInputStream fileIn = new FileInputStream(javFiles.get("Tph2")[1]); + String expectedAST = new String(fileIn.readAllBytes()); + fileIn.close(); + expectedAST = expectedAST.replaceAll("TPH [A-Z]+", "TPH"); + File srcfile = javFiles.get("Tph2")[0]; + JavaTXCompiler compiler = new JavaTXCompiler(srcfile); + String resultingAST = new String(ASTPrinter.print(compiler.sourceFiles.get(srcfile))); + resultingAST = resultingAST.replaceAll("TPH [A-Z]+", "TPH"); + System.out.println("Expected:\n" + new String(expectedAST)); + System.out.println("Result:\n" + new String(resultingAST)); + assertEquals("Comparing expected and resulting AST for Tph2.jav", expectedAST, resultingAST); + } catch (Exception exc) { + exc.printStackTrace(); + fail("An error occured while generating the AST for Tph2.jav"); + } + } + + @Test + public void tph3Test() { + try { + FileInputStream fileIn = new FileInputStream(javFiles.get("Tph3")[1]); + String expectedAST = new String(fileIn.readAllBytes()); + fileIn.close(); + expectedAST = expectedAST.replaceAll("TPH [A-Z]+", "TPH"); + File srcfile = javFiles.get("Tph3")[0]; + JavaTXCompiler compiler = new JavaTXCompiler(srcfile); + String resultingAST = new String(ASTPrinter.print(compiler.sourceFiles.get(srcfile))); + resultingAST = resultingAST.replaceAll("TPH [A-Z]+", "TPH"); + System.out.println("Expected:\n" + new String(expectedAST)); + System.out.println("Result:\n" + new String(resultingAST)); + assertEquals("Comparing expected and resulting AST for Tph3.jav", expectedAST, resultingAST); + } catch (Exception exc) { + exc.printStackTrace(); + fail("An error occured while generating the AST for Tph3.jav"); + } + } + + @Test + public void tph4Test() { + try { + FileInputStream fileIn = new FileInputStream(javFiles.get("Tph4")[1]); + String expectedAST = new String(fileIn.readAllBytes()); + fileIn.close(); + expectedAST = expectedAST.replaceAll("TPH [A-Z]+", "TPH"); + File srcfile = javFiles.get("Tph4")[0]; + JavaTXCompiler compiler = new JavaTXCompiler(srcfile); + String resultingAST = new String(ASTPrinter.print(compiler.sourceFiles.get(srcfile))); + resultingAST = resultingAST.replaceAll("TPH [A-Z]+", "TPH"); + System.out.println("Expected:\n" + new String(expectedAST)); + System.out.println("Result:\n" + new String(resultingAST)); + assertEquals("Comparing expected and resulting AST for Tph4.jav", expectedAST, resultingAST); + } catch (Exception exc) { + exc.printStackTrace(); + fail("An error occured while generating the AST for Tph4.jav"); + } + } + + @Test + public void tph5Test() { + try { + FileInputStream fileIn = new FileInputStream(javFiles.get("Tph5")[1]); + String expectedAST = new String(fileIn.readAllBytes()); + fileIn.close(); + expectedAST = expectedAST.replaceAll("TPH [A-Z]+", "TPH"); + File srcfile = javFiles.get("Tph5")[0]; + JavaTXCompiler compiler = new JavaTXCompiler(srcfile); + String resultingAST = new String(ASTPrinter.print(compiler.sourceFiles.get(srcfile))); + resultingAST = resultingAST.replaceAll("TPH [A-Z]+", "TPH"); + System.out.println("Expected:\n" + new String(expectedAST)); + System.out.println("Result:\n" + new String(resultingAST)); + assertEquals("Comparing expected and resulting AST for Tph5.jav", expectedAST, resultingAST); + } catch (Exception exc) { + exc.printStackTrace(); + fail("An error occured while generating the AST for Tph5.jav"); + } + } + + @Test + public void tph6Test() { + try { + FileInputStream fileIn = new FileInputStream(javFiles.get("Tph6")[1]); + String expectedAST = new String(fileIn.readAllBytes()); + fileIn.close(); + expectedAST = expectedAST.replaceAll("TPH [A-Z]+", "TPH"); + File srcfile = javFiles.get("Tph6")[0]; + JavaTXCompiler compiler = new JavaTXCompiler(srcfile); + String resultingAST = new String(ASTPrinter.print(compiler.sourceFiles.get(srcfile))); + resultingAST = resultingAST.replaceAll("TPH [A-Z]+", "TPH"); + System.out.println("Expected:\n" + new String(expectedAST)); + System.out.println("Result:\n" + new String(resultingAST)); + assertEquals("Comparing expected and resulting AST for Tph6.jav", expectedAST, resultingAST); + } catch (Exception exc) { + exc.printStackTrace(); + fail("An error occured while generating the AST for Tph6.jav"); + } + } + + @Test + public void tph7Test() { + try { + FileInputStream fileIn = new FileInputStream(javFiles.get("Tph7")[1]); + String expectedAST = new String(fileIn.readAllBytes()); + fileIn.close(); + expectedAST = expectedAST.replaceAll("TPH [A-Z]+", "TPH"); + File srcfile = javFiles.get("Tph7")[0]; + JavaTXCompiler compiler = new JavaTXCompiler(srcfile); + String resultingAST = new String(ASTPrinter.print(compiler.sourceFiles.get(srcfile))); + resultingAST = resultingAST.replaceAll("TPH [A-Z]+", "TPH"); + System.out.println("Expected:\n" + new String(expectedAST)); + System.out.println("Result:\n" + new String(resultingAST)); + assertEquals("Comparing expected and resulting AST for Tph7.jav", expectedAST, resultingAST); + } catch (Exception exc) { + exc.printStackTrace(); + fail("An error occured while generating the AST for Tph7.jav"); + } + } + + @Test + public void typedIdTest() { + try { + FileInputStream fileIn = new FileInputStream(javFiles.get("TypedID")[1]); + String expectedAST = new String(fileIn.readAllBytes()); + fileIn.close(); + expectedAST = expectedAST.replaceAll("TPH [A-Z]+", "TPH"); + File srcfile = javFiles.get("TypedID")[0]; + JavaTXCompiler compiler = new JavaTXCompiler(srcfile); + String resultingAST = new String(ASTPrinter.print(compiler.sourceFiles.get(srcfile))); + resultingAST = resultingAST.replaceAll("TPH [A-Z]+", "TPH"); + System.out.println("Expected:\n" + new String(expectedAST)); + System.out.println("Result:\n" + new String(resultingAST)); + assertEquals("Comparing expected and resulting AST for TypedID.jav", expectedAST, resultingAST); + } catch (Exception exc) { + exc.printStackTrace(); + fail("An error occured while generating the AST for TypedID.jav"); + } + } + + @Test + public void vectorAddTest() { + try { + FileInputStream fileIn = new FileInputStream(javFiles.get("VectorAdd")[1]); + String expectedAST = new String(fileIn.readAllBytes()); + fileIn.close(); + expectedAST = expectedAST.replaceAll("TPH [A-Z]+", "TPH"); + File srcfile = javFiles.get("VectorAdd")[0]; + JavaTXCompiler compiler = new JavaTXCompiler(srcfile); + String resultingAST = new String(ASTPrinter.print(compiler.sourceFiles.get(srcfile))); + resultingAST = resultingAST.replaceAll("TPH [A-Z]+", "TPH"); + System.out.println("Expected:\n" + new String(expectedAST)); + System.out.println("Result:\n" + new String(resultingAST)); + assertEquals("Comparing expected and resulting AST for VectorAdd.jav", expectedAST, resultingAST); + } catch (Exception exc) { + exc.printStackTrace(); + fail("An error occured while generating the AST for VectorAdd.jav"); + } + } + + @Test + public void vectorSuperTest() { + try { + FileInputStream fileIn = new FileInputStream(javFiles.get("VectorSuper")[1]); + String expectedAST = new String(fileIn.readAllBytes()); + fileIn.close(); + expectedAST = expectedAST.replaceAll("TPH [A-Z]+", "TPH"); + File srcfile = javFiles.get("VectorSuper")[0]; + JavaTXCompiler compiler = new JavaTXCompiler(srcfile); + String resultingAST = new String(ASTPrinter.print(compiler.sourceFiles.get(srcfile))); + resultingAST = resultingAST.replaceAll("TPH [A-Z]+", "TPH"); + System.out.println("Expected:\n" + new String(expectedAST)); + System.out.println("Result:\n" + new String(resultingAST)); + assertEquals("Comparing expected and resulting AST for VectorSuper.jav", expectedAST, resultingAST); + } catch (Exception exc) { + exc.printStackTrace(); + fail("An error occured while generating the AST for VectorSuper.jav"); + } + } + + @Test + public void yTest() { + try { + FileInputStream fileIn = new FileInputStream(javFiles.get("Y")[1]); + String expectedAST = new String(fileIn.readAllBytes()); + fileIn.close(); + expectedAST = expectedAST.replaceAll("TPH [A-Z]+", "TPH"); + File srcfile = javFiles.get("Y")[0]; + JavaTXCompiler compiler = new JavaTXCompiler(srcfile); + String resultingAST = new String(ASTPrinter.print(compiler.sourceFiles.get(srcfile))); + resultingAST = resultingAST.replaceAll("TPH [A-Z]+", "TPH"); + System.out.println("Expected:\n" + new String(expectedAST)); + System.out.println("Result:\n" + new String(resultingAST)); + assertEquals("Comparing expected and resulting AST for Y.jav", expectedAST, resultingAST); + } catch (Exception exc) { + exc.printStackTrace(); + fail("An error occured while generating the AST for Y.jav"); + } + } + + @Test + public void boxTest() { + try { + FileInputStream fileIn = new FileInputStream(javFiles.get("Box")[1]); + String expectedAST = new String(fileIn.readAllBytes()); + fileIn.close(); + expectedAST = expectedAST.replaceAll("TPH [A-Z]+", "TPH"); + File srcfile = javFiles.get("Box")[0]; + JavaTXCompiler compiler = new JavaTXCompiler(srcfile); + String resultingAST = new String(ASTPrinter.print(compiler.sourceFiles.get(srcfile))); + resultingAST = resultingAST.replaceAll("TPH [A-Z]+", "TPH"); + System.out.println("Expected:\n" + new String(expectedAST)); + System.out.println("Result:\n" + new String(resultingAST)); + assertEquals("Comparing expected and resulting AST for Box.jav", expectedAST, resultingAST); + } catch (Exception exc) { + exc.printStackTrace(); + fail("An error occured while generating the AST for Box.jav"); + } + } + + @Test + public void cycleTest() { + try { + FileInputStream fileIn = new FileInputStream(javFiles.get("Cycle")[1]); + String expectedAST = new String(fileIn.readAllBytes()); + fileIn.close(); + expectedAST = expectedAST.replaceAll("TPH [A-Z]+", "TPH"); + File srcfile = javFiles.get("Cycle")[0]; + JavaTXCompiler compiler = new JavaTXCompiler(srcfile); + String resultingAST = new String(ASTPrinter.print(compiler.sourceFiles.get(srcfile))); + resultingAST = resultingAST.replaceAll("TPH [A-Z]+", "TPH"); + System.out.println("Expected:\n" + new String(expectedAST)); + System.out.println("Result:\n" + new String(resultingAST)); + assertEquals("Comparing expected and resulting AST for Cycle.jav", expectedAST, resultingAST); + } catch (Exception exc) { + exc.printStackTrace(); + fail("An error occured while generating the AST for Cycle.jav"); + } + } + + @Test + public void olFunTest() { + try { + FileInputStream fileIn = new FileInputStream(javFiles.get("OLFun")[1]); + String expectedAST = new String(fileIn.readAllBytes()); + fileIn.close(); + expectedAST = expectedAST.replaceAll("TPH [A-Z]+", "TPH"); + File srcfile = javFiles.get("OLFun")[0]; + JavaTXCompiler compiler = new JavaTXCompiler(srcfile); + String resultingAST = new String(ASTPrinter.print(compiler.sourceFiles.get(srcfile))); + resultingAST = resultingAST.replaceAll("TPH [A-Z]+", "TPH"); + System.out.println("Expected:\n" + new String(expectedAST)); + System.out.println("Result:\n" + new String(resultingAST)); + assertEquals("Comparing expected and resulting AST for OLFun.jav", expectedAST, resultingAST); + } catch (Exception exc) { + exc.printStackTrace(); + fail("An error occured while generating the AST for OLFun.jav"); + } + } + + @Test + public void olFun2Test() { + try { + FileInputStream fileIn = new FileInputStream(javFiles.get("OLFun2")[1]); + String expectedAST = new String(fileIn.readAllBytes()); + fileIn.close(); + expectedAST = expectedAST.replaceAll("TPH [A-Z]+", "TPH"); + File srcfile = javFiles.get("OLFun2")[0]; + JavaTXCompiler compiler = new JavaTXCompiler(srcfile); + String resultingAST = new String(ASTPrinter.print(compiler.sourceFiles.get(srcfile))); + resultingAST = resultingAST.replaceAll("TPH [A-Z]+", "TPH"); + System.out.println("Expected:\n" + new String(expectedAST)); + System.out.println("Result:\n" + new String(resultingAST)); + assertEquals("Comparing expected and resulting AST for OLFun2.jav", expectedAST, resultingAST); + } catch (Exception exc) { + exc.printStackTrace(); + fail("An error occured while generating the AST for OLFun2.jav"); + } + } +} + +class JavFilter implements FileFilter { + + @Override + public boolean accept(File pathname) { + if (pathname.getName().contains(".jav")) + return true; + return false; + } + +} diff --git a/src/test/java/syntaxtreegenerator/TestNewFeatures.java b/src/test/java/syntaxtreegenerator/TestNewFeatures.java new file mode 100644 index 00000000..f35b0f11 --- /dev/null +++ b/src/test/java/syntaxtreegenerator/TestNewFeatures.java @@ -0,0 +1,5 @@ +package syntaxtreegenerator; + +public class TestNewFeatures { + +} \ No newline at end of file diff --git a/src/test/java/targetast/ASTToTypedTargetAST.java b/src/test/java/targetast/ASTToTypedTargetAST.java index 6d5a08c0..ecc070e1 100644 --- a/src/test/java/targetast/ASTToTypedTargetAST.java +++ b/src/test/java/targetast/ASTToTypedTargetAST.java @@ -24,9 +24,8 @@ import static org.junit.Assert.*; public class ASTToTypedTargetAST { @Test - public void emptyClass(){ - ClassOrInterface emptyClass = new ClassOrInterface(0, new JavaClassName("EmptyClass"), new ArrayList<>(), java.util.Optional.empty(), new ArrayList<>(), new ArrayList<>(), new GenericDeclarationList(new ArrayList<>(), new NullToken()), - new RefType(new JavaClassName("Object"), new NullToken()), false, new ArrayList<>(), new NullToken()); + public void emptyClass() { + ClassOrInterface emptyClass = new ClassOrInterface(0, new JavaClassName("EmptyClass"), new ArrayList<>(), java.util.Optional.empty(), new ArrayList<>(), new ArrayList<>(), new GenericDeclarationList(new ArrayList<>(), new NullToken()), new RefType(new JavaClassName("Object"), new NullToken()), false, new ArrayList<>(), new NullToken()); ResultSet emptyResultSet = new ResultSet(new HashSet<>()); TargetClass emptyTargetClass = new ASTToTargetAST(List.of(emptyResultSet)).convert(emptyClass); assert emptyTargetClass.getName().equals("EmptyClass"); @@ -36,7 +35,7 @@ public class ASTToTypedTargetAST { @Test public void overloading() throws Exception { - var file = Path.of(System.getProperty("user.dir"), "/resources/bytecode/javFiles/Overloading.jav").toFile(); + var file = Path.of(System.getProperty("user.dir"), "/src/test/resources/javFiles/Overloading.jav").toFile(); var compiler = new JavaTXCompiler(file); var resultSet = compiler.typeInference(); var converter = new ASTToTargetAST(resultSet); @@ -58,7 +57,7 @@ public class ASTToTypedTargetAST { @Test public void tphsAndGenerics() throws Exception { - var file = Path.of(System.getProperty("user.dir"), "/resources/bytecode/javFiles/Tph2.jav").toFile(); + var file = Path.of(System.getProperty("user.dir"), "/src/test/resources/javFiles/Tph2.jav").toFile(); var compiler = new JavaTXCompiler(file); var resultSet = compiler.typeInference(); var converter = new ASTToTargetAST(resultSet); @@ -69,7 +68,7 @@ public class ASTToTypedTargetAST { @Test public void cycles() throws Exception { - var file = Path.of(System.getProperty("user.dir"), "/resources/bytecode/javFiles/Cycle.jav").toFile(); + var file = Path.of(System.getProperty("user.dir"), "/src/test/resources/javFiles/Cycle.jav").toFile(); var compiler = new JavaTXCompiler(file); var resultSet = compiler.typeInference(); var converter = new ASTToTargetAST(resultSet); @@ -80,7 +79,7 @@ public class ASTToTypedTargetAST { @Test public void infimum() throws Exception { - var file = Path.of(System.getProperty("user.dir"), "/resources/bytecode/javFiles/Infimum.jav").toFile(); + var file = Path.of(System.getProperty("user.dir"), "/src/test/resources/javFiles/Infimum.jav").toFile(); var compiler = new JavaTXCompiler(file); var resultSet = compiler.typeInference(); var converter = new ASTToTargetAST(resultSet); @@ -91,7 +90,7 @@ public class ASTToTypedTargetAST { @Test public void gen() throws Exception { - var file = Path.of(System.getProperty("user.dir"), "/resources/bytecode/javFiles/Gen.jav").toFile(); + var file = Path.of(System.getProperty("user.dir"), "/src/test/resources/javFiles/Gen.jav").toFile(); var compiler = new JavaTXCompiler(file); var resultSet = compiler.typeInference(); var converter = new ASTToTargetAST(resultSet); @@ -101,12 +100,13 @@ public class ASTToTypedTargetAST { var m = generics.getDeclaredMethod("m", Vector.class); var mReturnType = m.getGenericReturnType(); assertEquals(mReturnType, m.getParameters()[0].getParameterizedType()); - assertEquals(mReturnType, new TypeToken>(){}.getType()); + assertEquals(mReturnType, new TypeToken>() { + }.getType()); } @Test public void definedGenerics() throws Exception { - var file = Path.of(System.getProperty("user.dir"), "/resources/bytecode/javFiles/Generics.jav").toFile(); + var file = Path.of(System.getProperty("user.dir"), "/src/test/resources/javFiles/Generics.jav").toFile(); var compiler = new JavaTXCompiler(file); var resultSet = compiler.typeInference(); var converter = new ASTToTargetAST(resultSet); @@ -124,7 +124,7 @@ public class ASTToTypedTargetAST { @Test public void definedGenerics2() throws Exception { - var file = Path.of(System.getProperty("user.dir"), "/resources/bytecode/javFiles/Generics2.jav").toFile(); + var file = Path.of(System.getProperty("user.dir"), "/src/test/resources/javFiles/Generics2.jav").toFile(); var compiler = new JavaTXCompiler(file); var resultSet = compiler.typeInference(); var converter = new ASTToTargetAST(resultSet); @@ -140,7 +140,7 @@ public class ASTToTypedTargetAST { @Test @Ignore("Not implemented") public void definedGenerics3() throws Exception { - var file = Path.of(System.getProperty("user.dir"), "/resources/bytecode/javFiles/Generics3.jav").toFile(); + var file = Path.of(System.getProperty("user.dir"), "/src/test/resources/javFiles/Generics3.jav").toFile(); var compiler = new JavaTXCompiler(file); var resultSet = compiler.typeInference(); var converter = new ASTToTargetAST(resultSet); @@ -151,7 +151,7 @@ public class ASTToTypedTargetAST { @Test public void definedGenerics4() throws Exception { - var file = Path.of(System.getProperty("user.dir"), "/resources/bytecode/javFiles/Generics4.jav").toFile(); + var file = Path.of(System.getProperty("user.dir"), "/src/test/resources/javFiles/Generics4.jav").toFile(); var compiler = new JavaTXCompiler(file); var resultSet = compiler.typeInference(); var converter = new ASTToTargetAST(resultSet); @@ -159,8 +159,8 @@ public class ASTToTypedTargetAST { var generics4 = TestCodegen.generateClass(converter.convert(classes.get(0)), new ByteArrayClassLoader()); - //var instance = generics4.getDeclaredConstructor().newInstance(); - //var method = generics4.getDeclaredMethod("m2", Object.class); - //method.invoke(instance, new Object()); + // var instance = generics4.getDeclaredConstructor().newInstance(); + // var method = generics4.getDeclaredMethod("m2", Object.class); + // method.invoke(instance, new Object()); } } diff --git a/src/test/java/targetast/TestCodegen.java b/src/test/java/targetast/TestCodegen.java index 00cc85bc..b1389f6e 100644 --- a/src/test/java/targetast/TestCodegen.java +++ b/src/test/java/targetast/TestCodegen.java @@ -28,345 +28,186 @@ import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; - public class TestCodegen { - static final Path outputPath = Path.of(System.getProperty("user.dir"), "src/test/resources/target/"); + static final Path outputPath = Path.of(System.getProperty("user.dir"), "src/test/resources/target/"); - private static void writeClassFile(String name, byte[] code) throws IOException { - Files.createDirectories(outputPath); - Files.write(outputPath.resolve(name + ".class"), code); - } - - public static Class generateClass(TargetClass clazz, IByteArrayClassLoader classLoader) throws IOException { - var codegen = new Codegen(clazz); - var code = codegen.generate(); - writeClassFile(clazz.qualifiedName(), code); - return classLoader.loadClass(code); - } - - public static Map> generateClassFiles(IByteArrayClassLoader classLoader, String... files) throws IOException, ClassNotFoundException { - var path = Path.of(System.getProperty("user.dir"), "/resources/bytecode/javFiles/"); - var filenames = Arrays.stream(files).map(filename -> Path.of(path.toString(), filename).toFile()).toList(); - var compiler = new JavaTXCompiler(filenames, List.of(path.toFile(), outputPath.toFile())); - var resultSet = compiler.typeInference(); - - var result = new HashMap>(); - for (var file : filenames) { - var sourceFile = compiler.sourceFiles.get(file); - var converter = new ASTToTargetAST(resultSet, sourceFile, classLoader); - var classes = compiler.sourceFiles.get(file).getClasses(); - - result.putAll(classes.stream().map(cli -> { - try { - return generateClass(converter.convert(cli), classLoader); - } catch (IOException exception) { - throw new RuntimeException(exception); - } - }).collect(Collectors.toMap(Class::getName, Function.identity()))); - - for (var entry : converter.auxiliaries.entrySet()) { - writeClassFile(entry.getKey(), entry.getValue()); - } + private static void writeClassFile(String name, byte[] code) throws IOException { + Files.createDirectories(outputPath); + Files.write(outputPath.resolve(name + ".class"), code); } - return result; - } + public static Map> generateClassFiles(IByteArrayClassLoader classLoader, String... files) throws IOException, ClassNotFoundException { + var path = Path.of(System.getProperty("user.dir"), "/resources/bytecode/javFiles/"); + var filenames = Arrays.stream(files).map(filename -> Path.of(path.toString(), filename).toFile()).toList(); + var compiler = new JavaTXCompiler(filenames, List.of(path.toFile(), outputPath.toFile())); + var resultSet = compiler.typeInference(); - @Test - public void testEmptyClass() throws Exception { - var clazz = new TargetClass(Opcodes.ACC_PUBLIC, "Empty"); - clazz.addMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "main", List.of(), null, new TargetBlock(List.of())); - generateClass(clazz, new ByteArrayClassLoader()).getDeclaredMethod("main").invoke(null); - } + var result = new HashMap>(); + for (var file : filenames) { + var sourceFile = compiler.sourceFiles.get(file); + var converter = new ASTToTargetAST(resultSet, sourceFile, classLoader); + var classes = compiler.sourceFiles.get(file).getClasses(); - @Test - public void testArithmetic() throws Exception { - var targetClass = new TargetClass(Opcodes.ACC_PUBLIC, "Arithmetic"); + result.putAll(classes.stream().map(cli -> { + try { + return generateClass(converter.convert(cli), classLoader); + } catch (IOException exception) { + throw new RuntimeException(exception); + } + }).collect(Collectors.toMap(Class::getName, Function.identity()))); - targetClass.addMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "add", - List.of(new MethodParameter(TargetType.Integer, "a"), new MethodParameter(TargetType.Integer, "b")), - TargetType.Integer, - new TargetBlock(List.of(new TargetReturn( - new TargetBinaryOp.Add(TargetType.Integer, new TargetLocalVar(TargetType.Integer, "a"), new TargetLocalVar(TargetType.Integer, "b"))) - )) - ); - targetClass.addMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "sub", - List.of(new MethodParameter(TargetType.Integer, "a"), new MethodParameter(TargetType.Integer, "b")), - TargetType.Integer, - new TargetBlock(List.of(new TargetReturn( - new TargetBinaryOp.Sub(TargetType.Integer, new TargetLocalVar(TargetType.Integer, "a"), new TargetLocalVar(TargetType.Integer, "b"))) - )) - ); - targetClass.addMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "div", - List.of(new MethodParameter(TargetType.Integer, "a"), new MethodParameter(TargetType.Integer, "b")), - TargetType.Integer, - new TargetBlock(List.of(new TargetReturn( - new TargetBinaryOp.Div(TargetType.Integer, new TargetLocalVar(TargetType.Integer, "a"), new TargetLocalVar(TargetType.Integer, "b"))) - )) - ); - targetClass.addMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "mul", - List.of(new MethodParameter(TargetType.Integer, "a"), new MethodParameter(TargetType.Integer, "b")), - TargetType.Integer, - new TargetBlock(List.of(new TargetReturn( - new TargetBinaryOp.Mul(TargetType.Integer, new TargetLocalVar(TargetType.Integer, "a"), new TargetLocalVar(TargetType.Integer, "b"))) - )) - ); - targetClass.addMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "rem", - List.of(new MethodParameter(TargetType.Integer, "a"), new MethodParameter(TargetType.Integer, "b")), - TargetType.Integer, - new TargetBlock(List.of(new TargetReturn( - new TargetBinaryOp.Rem(TargetType.Integer, new TargetLocalVar(TargetType.Integer, "a"), new TargetLocalVar(TargetType.Integer, "b"))) - )) - ); + for (var entry : converter.auxiliaries.entrySet()) { + writeClassFile(entry.getKey(), entry.getValue()); + } + } + return result; + } - var clazz = generateClass(targetClass, new ByteArrayClassLoader()); - assertEquals(clazz.getDeclaredMethod("add", Integer.class, Integer.class).invoke(null, 10, 10), 20); - assertEquals(clazz.getDeclaredMethod("sub", Integer.class, Integer.class).invoke(null, 20, 10), 10); - assertEquals(clazz.getDeclaredMethod("div", Integer.class, Integer.class).invoke(null, 20, 10), 2); - assertEquals(clazz.getDeclaredMethod("mul", Integer.class, Integer.class).invoke(null, 20, 10), 200); - assertEquals(clazz.getDeclaredMethod("rem", Integer.class, Integer.class).invoke(null, 10, 3), 1); - } + public static Class generateClass(TargetClass clazz, IByteArrayClassLoader classLoader) throws IOException { + var codegen = new Codegen(clazz); + var code = codegen.generate(); + writeClassFile(clazz.qualifiedName(), code); + return classLoader.loadClass(code); + } - @Test - public void testUnary() throws Exception { - var targetClass = new TargetClass(Opcodes.ACC_PUBLIC, "Unary"); + public static Map> generateClassFiles(String filename, IByteArrayClassLoader classLoader) throws IOException, ClassNotFoundException { + var file = Path.of(System.getProperty("user.dir"), "/src/test/resources/javFiles/", filename).toFile(); + var compiler = new JavaTXCompiler(List.of(file), List.of(file.getParentFile())); + var resultSet = compiler.typeInference(); - targetClass.addMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "not", - List.of(new MethodParameter(TargetType.Integer, "a")), - TargetType.Integer, - new TargetBlock(List.of(new TargetReturn( - new TargetUnaryOp.Not(TargetType.Integer, new TargetLocalVar(TargetType.Integer, "a"))) - )) - ); - targetClass.addMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "neg", - List.of(new MethodParameter(TargetType.Integer, "a")), - TargetType.Integer, - new TargetBlock(List.of(new TargetReturn( - new TargetUnaryOp.Negate(TargetType.Integer, new TargetLocalVar(TargetType.Integer, "a"))) - )) - ); - targetClass.addMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "add", - List.of(new MethodParameter(TargetType.Integer, "a")), - TargetType.Integer, - new TargetBlock(List.of(new TargetReturn( - new TargetUnaryOp.Add(TargetType.Integer, new TargetLocalVar(TargetType.Integer, "a"))) - )) - ); + var sourceFile = compiler.sourceFiles.get(file); + var converter = new ASTToTargetAST(resultSet, sourceFile, classLoader); + var classes = compiler.sourceFiles.get(file).getClasses(); - var clazz = generateClass(targetClass, new ByteArrayClassLoader()); - assertEquals(clazz.getDeclaredMethod("not", Integer.class).invoke(null, 10), -11); - assertEquals(clazz.getDeclaredMethod("neg", Integer.class).invoke(null, 10), -10); - assertEquals(clazz.getDeclaredMethod("add", Integer.class).invoke(null, 10), 10); + var result = classes.stream().map(cli -> { + try { + return generateClass(converter.convert(cli), classLoader); + } catch (IOException exception) { + throw new RuntimeException(exception); + } + }).collect(Collectors.toMap(Class::getName, Function.identity())); - } + for (var entry : converter.auxiliaries.entrySet()) { + writeClassFile(entry.getKey(), entry.getValue()); + } - @Test - public void testConditional() throws Exception { - var targetClass = new TargetClass(Opcodes.ACC_PUBLIC, "Conditional"); + return result; + } - targetClass.addMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "and", - List.of(new MethodParameter(TargetType.Boolean, "a"), new MethodParameter(TargetType.Boolean, "b")), - TargetType.Boolean, - new TargetBlock(List.of(new TargetReturn( - new TargetBinaryOp.And(TargetType.Boolean, new TargetLocalVar(TargetType.Boolean, "a"), new TargetLocalVar(TargetType.Boolean, "b"))) - )) - ); - targetClass.addMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "or", - List.of(new MethodParameter(TargetType.Boolean, "a"), new MethodParameter(TargetType.Boolean, "b")), - TargetType.Boolean, - new TargetBlock(List.of(new TargetReturn( - new TargetBinaryOp.Or(TargetType.Boolean, new TargetLocalVar(TargetType.Boolean, "a"), new TargetLocalVar(TargetType.Boolean, "b"))) - )) - ); + @Test + public void testEmptyClass() throws Exception { + var clazz = new TargetClass(Opcodes.ACC_PUBLIC, "Empty"); + clazz.addMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "main", List.of(), null, new TargetBlock(List.of())); + generateClass(clazz, new ByteArrayClassLoader()).getDeclaredMethod("main").invoke(null); + } - var clazz = generateClass(targetClass, new ByteArrayClassLoader()); - var and = clazz.getDeclaredMethod("and", Boolean.class, Boolean.class); - var or = clazz.getDeclaredMethod("or", Boolean.class, Boolean.class); - assertEquals(and.invoke(null, true, false), false); - assertEquals(and.invoke(null, true, true), true); - assertEquals(or.invoke(null, false, false), false); - assertEquals(or.invoke(null, true, false), true); - } + @Test + public void testArithmetic() throws Exception { + var targetClass = new TargetClass(Opcodes.ACC_PUBLIC, "Arithmetic"); - // When adding two numbers and the return type is Long it needs to convert both values to Long - @Test - public void testArithmeticConvert() throws Exception { - var targetClass = new TargetClass(Opcodes.ACC_PUBLIC, "ArithmeticConvert"); - targetClass.addMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "add", List.of(), TargetType.Long, - new TargetBlock(List.of(new TargetReturn( - new TargetBinaryOp.Add(TargetType.Long, new TargetLiteral.CharLiteral((char)10), new TargetLiteral.LongLiteral((long)20)) - ))) - ); - var clazz = generateClass(targetClass, new ByteArrayClassLoader()); - assertEquals(clazz.getDeclaredMethod("add").invoke(null), (long)30); - } + targetClass.addMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "add", List.of(new MethodParameter(TargetType.Integer, "a"), new MethodParameter(TargetType.Integer, "b")), TargetType.Integer, new TargetBlock(List.of(new TargetReturn(new TargetBinaryOp.Add(TargetType.Integer, new TargetLocalVar(TargetType.Integer, "a"), new TargetLocalVar(TargetType.Integer, "b")))))); + targetClass.addMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "sub", List.of(new MethodParameter(TargetType.Integer, "a"), new MethodParameter(TargetType.Integer, "b")), TargetType.Integer, new TargetBlock(List.of(new TargetReturn(new TargetBinaryOp.Sub(TargetType.Integer, new TargetLocalVar(TargetType.Integer, "a"), new TargetLocalVar(TargetType.Integer, "b")))))); + targetClass.addMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "div", List.of(new MethodParameter(TargetType.Integer, "a"), new MethodParameter(TargetType.Integer, "b")), TargetType.Integer, new TargetBlock(List.of(new TargetReturn(new TargetBinaryOp.Div(TargetType.Integer, new TargetLocalVar(TargetType.Integer, "a"), new TargetLocalVar(TargetType.Integer, "b")))))); + targetClass.addMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "mul", List.of(new MethodParameter(TargetType.Integer, "a"), new MethodParameter(TargetType.Integer, "b")), TargetType.Integer, new TargetBlock(List.of(new TargetReturn(new TargetBinaryOp.Mul(TargetType.Integer, new TargetLocalVar(TargetType.Integer, "a"), new TargetLocalVar(TargetType.Integer, "b")))))); + targetClass.addMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "rem", List.of(new MethodParameter(TargetType.Integer, "a"), new MethodParameter(TargetType.Integer, "b")), TargetType.Integer, new TargetBlock(List.of(new TargetReturn(new TargetBinaryOp.Rem(TargetType.Integer, new TargetLocalVar(TargetType.Integer, "a"), new TargetLocalVar(TargetType.Integer, "b")))))); - @Test - public void testMethodCall() throws Exception { - var targetClass = new TargetClass(Opcodes.ACC_PUBLIC, "HelloWorld"); - targetClass.addMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "helloWorld", List.of(), null, - new TargetBlock(List.of(new TargetMethodCall(null, - new TargetFieldVar( - new TargetRefType("java.io.PrintStream"), - new TargetRefType("java.lang.System"), - true, - new TargetClassName(new TargetRefType("java.lang.System")), - "out" - ), - List.of(new TargetLiteral.StringLiteral("Hello World!")), - new TargetRefType("java.io.PrintStream"), - "println", - false, false - ))) - ); + var clazz = generateClass(targetClass, new ByteArrayClassLoader()); + assertEquals(clazz.getDeclaredMethod("add", Integer.class, Integer.class).invoke(null, 10, 10), 20); + assertEquals(clazz.getDeclaredMethod("sub", Integer.class, Integer.class).invoke(null, 20, 10), 10); + assertEquals(clazz.getDeclaredMethod("div", Integer.class, Integer.class).invoke(null, 20, 10), 2); + assertEquals(clazz.getDeclaredMethod("mul", Integer.class, Integer.class).invoke(null, 20, 10), 200); + assertEquals(clazz.getDeclaredMethod("rem", Integer.class, Integer.class).invoke(null, 10, 3), 1); + } - var clazz = generateClass(targetClass, new ByteArrayClassLoader()); - clazz.getDeclaredMethod("helloWorld").invoke(null); - } + @Test + public void testUnary() throws Exception { + var targetClass = new TargetClass(Opcodes.ACC_PUBLIC, "Unary"); - @Test - public void testIfStatement() throws Exception { - var targetClass = new TargetClass(Opcodes.ACC_PUBLIC, "IfStmt"); - targetClass.addMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "ifStmt", - List.of(new MethodParameter(TargetType.Integer, "val")), - TargetType.Integer, - new TargetBlock(List.of(new TargetIf( - new TargetBinaryOp.Equal(TargetType.Integer, new TargetLocalVar(TargetType.Integer, "val"), new TargetLiteral.IntLiteral(10)), - new TargetReturn(new TargetLiteral.IntLiteral(1)), - new TargetIf( - new TargetBinaryOp.Less(TargetType.Integer, new TargetLocalVar(TargetType.Integer, "val"), new TargetLiteral.IntLiteral(5)), - new TargetReturn(new TargetLiteral.IntLiteral(2)), - new TargetReturn(new TargetLiteral.IntLiteral(3)) - ) - ))) - ); - var clazz = generateClass(targetClass, new ByteArrayClassLoader()); - var ifStmt = clazz.getDeclaredMethod("ifStmt", Integer.class); - assertEquals(ifStmt.invoke(null, 10), 1); - assertEquals(ifStmt.invoke(null, 3), 2); - assertEquals(ifStmt.invoke(null, 20), 3); - } + targetClass.addMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "not", List.of(new MethodParameter(TargetType.Integer, "a")), TargetType.Integer, new TargetBlock(List.of(new TargetReturn(new TargetUnaryOp.Not(TargetType.Integer, new TargetLocalVar(TargetType.Integer, "a")))))); + targetClass.addMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "neg", List.of(new MethodParameter(TargetType.Integer, "a")), TargetType.Integer, new TargetBlock(List.of(new TargetReturn(new TargetUnaryOp.Negate(TargetType.Integer, new TargetLocalVar(TargetType.Integer, "a")))))); + targetClass.addMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "add", List.of(new MethodParameter(TargetType.Integer, "a")), TargetType.Integer, new TargetBlock(List.of(new TargetReturn(new TargetUnaryOp.Add(TargetType.Integer, new TargetLocalVar(TargetType.Integer, "a")))))); - @Test - public void testFor() throws Exception { - var targetClass = new TargetClass(Opcodes.ACC_PUBLIC, "For"); - targetClass.addMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "forLoop", List.of(), TargetType.Integer, - new TargetBlock(List.of( - new TargetVarDecl(TargetType.Integer, "sum", new TargetLiteral.IntLiteral(0)), - new TargetFor( - new TargetVarDecl(TargetType.Integer, "i", new TargetLiteral.IntLiteral(0)), - new TargetBinaryOp.Less(TargetType.Integer, new TargetLocalVar(TargetType.Integer, "i"), new TargetLiteral.IntLiteral(10)), - new TargetAssign(TargetType.Integer, - new TargetLocalVar(TargetType.Integer, "i"), - new TargetBinaryOp.Add(TargetType.Integer, new TargetLocalVar(TargetType.Integer, "i"), new TargetLiteral.IntLiteral(1))), - new TargetBlock(List.of( - new TargetAssign(TargetType.Integer, - new TargetLocalVar(TargetType.Integer, "sum"), - new TargetBinaryOp.Add(TargetType.Integer, new TargetLocalVar(TargetType.Integer, "sum"), new TargetLocalVar(TargetType.Integer, "i")) - ) - )) - ), - new TargetReturn(new TargetLocalVar(TargetType.Integer, "sum")) - )) - ); - var clazz = generateClass(targetClass, new ByteArrayClassLoader()); - assertEquals(clazz.getDeclaredMethod("forLoop").invoke(null), 45); - } + var clazz = generateClass(targetClass, new ByteArrayClassLoader()); + assertEquals(clazz.getDeclaredMethod("not", Integer.class).invoke(null, 10), -11); + assertEquals(clazz.getDeclaredMethod("neg", Integer.class).invoke(null, 10), -10); + assertEquals(clazz.getDeclaredMethod("add", Integer.class).invoke(null, 10), 10); - @Test - public void testWhile() throws Exception { - var targetClass = new TargetClass(Opcodes.ACC_PUBLIC, "While"); - targetClass.addMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "whileLoop", List.of(), TargetType.Integer, - new TargetBlock(List.of( - new TargetVarDecl(TargetType.Integer, "i", new TargetLiteral.IntLiteral(0)), - new TargetWhile( - new TargetBinaryOp.Less(TargetType.Integer, new TargetLocalVar(TargetType.Integer, "i"), new TargetLiteral.IntLiteral(10)), - new TargetBlock(List.of( - new TargetAssign(TargetType.Integer, - new TargetLocalVar(TargetType.Integer, "i"), - new TargetBinaryOp.Add(TargetType.Integer, new TargetLocalVar(TargetType.Integer, "i"), new TargetLiteral.IntLiteral(1)) - ) - )) - ), - new TargetReturn(new TargetLocalVar(TargetType.Integer, "i")) - )) - ); - var clazz = generateClass(targetClass, new ByteArrayClassLoader()); - assertEquals(clazz.getDeclaredMethod("whileLoop").invoke(null), 10); - } + } - @Test - public void testNew() throws Exception { - var pointType = new TargetRefType("Point"); - var pointTarget = new TargetClass(Opcodes.ACC_PUBLIC, "Point"); - pointTarget.addField(Opcodes.ACC_PUBLIC, TargetType.Integer, "x"); - pointTarget.addField(Opcodes.ACC_PUBLIC, TargetType.Integer, "y"); - pointTarget.addConstructor(Opcodes.ACC_PUBLIC, - List.of(new MethodParameter(TargetType.Integer, "x"), new MethodParameter(TargetType.Integer, "y")), - new TargetBlock(List.of( - new TargetMethodCall(null, new TargetSuper(TargetType.Object), List.of(), TargetType.Object, "", false, false), - new TargetAssign(TargetType.Integer, - new TargetFieldVar(TargetType.Integer, pointType, false, new TargetThis(pointType), "x"), - new TargetLocalVar(TargetType.Integer, "x") - ), - new TargetAssign(TargetType.Integer, - new TargetFieldVar(TargetType.Integer, pointType, false, new TargetThis(pointType), "y"), - new TargetLocalVar(TargetType.Integer, "y") - ) - )) - ); + @Test + public void testConditional() throws Exception { + var targetClass = new TargetClass(Opcodes.ACC_PUBLIC, "Conditional"); - var mainTarget = new TargetClass(Opcodes.ACC_PUBLIC, "New"); - mainTarget.addMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "makePoint", - List.of(new MethodParameter(TargetType.Integer, "x"), new MethodParameter(TargetType.Integer, "y")), pointType, - new TargetBlock(List.of( - new TargetReturn(new TargetNew(pointType, List.of( - new TargetLocalVar(TargetType.Integer, "x"), - new TargetLocalVar(TargetType.Integer, "y") - ))) - )) - ); + targetClass.addMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "and", List.of(new MethodParameter(TargetType.Boolean, "a"), new MethodParameter(TargetType.Boolean, "b")), TargetType.Boolean, new TargetBlock(List.of(new TargetReturn(new TargetBinaryOp.And(TargetType.Boolean, new TargetLocalVar(TargetType.Boolean, "a"), new TargetLocalVar(TargetType.Boolean, "b")))))); + targetClass.addMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "or", List.of(new MethodParameter(TargetType.Boolean, "a"), new MethodParameter(TargetType.Boolean, "b")), TargetType.Boolean, new TargetBlock(List.of(new TargetReturn(new TargetBinaryOp.Or(TargetType.Boolean, new TargetLocalVar(TargetType.Boolean, "a"), new TargetLocalVar(TargetType.Boolean, "b")))))); - var classLoader = new ByteArrayClassLoader(); - var pointClass = generateClass(pointTarget, classLoader); - var mainClass = generateClass(mainTarget, classLoader); + var clazz = generateClass(targetClass, new ByteArrayClassLoader()); + var and = clazz.getDeclaredMethod("and", Boolean.class, Boolean.class); + var or = clazz.getDeclaredMethod("or", Boolean.class, Boolean.class); + assertEquals(and.invoke(null, true, false), false); + assertEquals(and.invoke(null, true, true), true); + assertEquals(or.invoke(null, false, false), false); + assertEquals(or.invoke(null, true, false), true); + } - var point = mainClass.getDeclaredMethod("makePoint", Integer.class, Integer.class).invoke(null, 10, 20); - assertEquals(point.getClass().getDeclaredField("x").get(point), 10); - assertEquals(point.getClass().getDeclaredField("y").get(point), 20); - } + // When adding two numbers and the return type is Long it needs to convert both values to Long + @Test + public void testArithmeticConvert() throws Exception { + var targetClass = new TargetClass(Opcodes.ACC_PUBLIC, "ArithmeticConvert"); + targetClass.addMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "add", List.of(), TargetType.Long, new TargetBlock(List.of(new TargetReturn(new TargetBinaryOp.Add(TargetType.Long, new TargetLiteral.CharLiteral((char) 10), new TargetLiteral.LongLiteral((long) 20)))))); + var clazz = generateClass(targetClass, new ByteArrayClassLoader()); + assertEquals(clazz.getDeclaredMethod("add").invoke(null), (long) 30); + } - @Test - @Ignore("The lambda class is not generated because we don't call ASTToTargetAST") - public void testLambda() throws Exception { - var classLoader = new ByteArrayClassLoader(); - //var fun = classLoader.loadClass(Path.of(System.getProperty("user.dir"), "src/test/java/targetast/Fun1$$.class")); - var interfaceType = TargetFunNType.fromParams(List.of(TargetType.Integer)); + @Test + public void testMethodCall() throws Exception { + var targetClass = new TargetClass(Opcodes.ACC_PUBLIC, "HelloWorld"); + targetClass.addMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "helloWorld", List.of(), null, new TargetBlock(List.of(new TargetMethodCall(null, new TargetFieldVar(new TargetRefType("java.io.PrintStream"), new TargetRefType("java.lang.System"), true, new TargetClassName(new TargetRefType("java.lang.System")), "out"), List.of(new TargetLiteral.StringLiteral("Hello World!")), new TargetRefType("java.io.PrintStream"), "println", false, false)))); - var targetClass = new TargetClass(Opcodes.ACC_PUBLIC, "CGLambda"); - targetClass.addConstructor(Opcodes.ACC_PUBLIC, List.of(), new TargetBlock(List.of( - new TargetMethodCall(null, new TargetSuper(TargetType.Object), List.of(), TargetType.Object, "", false, false) - ))); - targetClass.addMethod(Opcodes.ACC_PUBLIC, "lambda", List.of(), TargetType.Integer, - new TargetBlock(List.of( - new TargetVarDecl(interfaceType, "by2", - new TargetLambdaExpression(interfaceType, List.of(), List.of(new MethodParameter(TargetType.Integer, "num")), TargetType.Integer, - new TargetBlock(List.of( - new TargetReturn(new TargetBinaryOp.Mul(TargetType.Integer, - new TargetLocalVar(TargetType.Integer, "num"), - new TargetLiteral.IntLiteral(2) - )) - ) - )) - ), - new TargetReturn(new TargetCast(TargetType.Integer, new TargetMethodCall(TargetType.Object, TargetType.Object, List.of(TargetType.Object), new TargetLocalVar(interfaceType, "by2"), List.of( - new TargetLiteral.IntLiteral(10) - ), interfaceType, "apply", false, true))) - )) - ); - var clazz = generateClass(targetClass, classLoader); - var instance = clazz.getConstructor().newInstance(); - assertEquals(clazz.getDeclaredMethod("lambda").invoke(instance), 20); - } + var clazz = generateClass(targetClass, new ByteArrayClassLoader()); + clazz.getDeclaredMethod("helloWorld").invoke(null); + } + + @Test + public void testIfStatement() throws Exception { + var targetClass = new TargetClass(Opcodes.ACC_PUBLIC, "IfStmt"); + targetClass.addMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "ifStmt", List.of(new MethodParameter(TargetType.Integer, "val")), TargetType.Integer, new TargetBlock(List.of(new TargetIf(new TargetBinaryOp.Equal(TargetType.Integer, new TargetLocalVar(TargetType.Integer, "val"), new TargetLiteral.IntLiteral(10)), new TargetReturn(new TargetLiteral.IntLiteral(1)), new TargetIf(new TargetBinaryOp.Less(TargetType.Integer, new TargetLocalVar(TargetType.Integer, "val"), new TargetLiteral.IntLiteral(5)), new TargetReturn(new TargetLiteral.IntLiteral(2)), new TargetReturn(new TargetLiteral.IntLiteral(3))))))); + var clazz = generateClass(targetClass, new ByteArrayClassLoader()); + var ifStmt = clazz.getDeclaredMethod("ifStmt", Integer.class); + assertEquals(ifStmt.invoke(null, 10), 1); + assertEquals(ifStmt.invoke(null, 3), 2); + assertEquals(ifStmt.invoke(null, 20), 3); + } + + @Test + public void testFor() throws Exception { + var targetClass = new TargetClass(Opcodes.ACC_PUBLIC, "For"); + targetClass.addMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "forLoop", List.of(), TargetType.Integer, new TargetBlock(List.of(new TargetVarDecl(TargetType.Integer, "sum", new TargetLiteral.IntLiteral(0)), new TargetFor(new TargetVarDecl(TargetType.Integer, "i", new TargetLiteral.IntLiteral(0)), new TargetBinaryOp.Less(TargetType.Integer, new TargetLocalVar(TargetType.Integer, "i"), new TargetLiteral.IntLiteral(10)), new TargetAssign(TargetType.Integer, new TargetLocalVar(TargetType.Integer, "i"), new TargetBinaryOp.Add(TargetType.Integer, new TargetLocalVar(TargetType.Integer, "i"), new TargetLiteral.IntLiteral(1))), new TargetBlock(List.of(new TargetAssign(TargetType.Integer, new TargetLocalVar(TargetType.Integer, "sum"), new TargetBinaryOp.Add(TargetType.Integer, new TargetLocalVar(TargetType.Integer, "sum"), new TargetLocalVar(TargetType.Integer, "i")))))), new TargetReturn(new TargetLocalVar(TargetType.Integer, "sum"))))); + var clazz = generateClass(targetClass, new ByteArrayClassLoader()); + assertEquals(clazz.getDeclaredMethod("forLoop").invoke(null), 45); + } + + @Test + public void testWhile() throws Exception { + var targetClass = new TargetClass(Opcodes.ACC_PUBLIC, "While"); + targetClass.addMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "whileLoop", List.of(), TargetType.Integer, new TargetBlock(List.of(new TargetVarDecl(TargetType.Integer, "i", new TargetLiteral.IntLiteral(0)), new TargetWhile(new TargetBinaryOp.Less(TargetType.Integer, new TargetLocalVar(TargetType.Integer, "i"), new TargetLiteral.IntLiteral(10)), new TargetBlock(List.of(new TargetAssign(TargetType.Integer, new TargetLocalVar(TargetType.Integer, "i"), new TargetBinaryOp.Add(TargetType.Integer, new TargetLocalVar(TargetType.Integer, "i"), new TargetLiteral.IntLiteral(1)))))), new TargetReturn(new TargetLocalVar(TargetType.Integer, "i"))))); + var clazz = generateClass(targetClass, new ByteArrayClassLoader()); + assertEquals(clazz.getDeclaredMethod("whileLoop").invoke(null), 10); + } + + @Test + @Ignore("The lambda class is not generated because we don't call ASTToTargetAST") + public void testLambda() throws Exception { + var classLoader = new ByteArrayClassLoader(); + // var fun = classLoader.loadClass(Path.of(System.getProperty("user.dir"), "src/test/java/targetast/Fun1$$.class")); + var interfaceType = TargetFunNType.fromParams(List.of(TargetType.Integer)); + + var targetClass = new TargetClass(Opcodes.ACC_PUBLIC, "CGLambda"); + targetClass.addConstructor(Opcodes.ACC_PUBLIC, List.of(), new TargetBlock(List.of(new TargetMethodCall(null, new TargetSuper(TargetType.Object), List.of(), TargetType.Object, "", false, false)))); + targetClass.addMethod(Opcodes.ACC_PUBLIC, "lambda", List.of(), TargetType.Integer, new TargetBlock(List.of(new TargetVarDecl(interfaceType, "by2", new TargetLambdaExpression(interfaceType, List.of(), List.of(new MethodParameter(TargetType.Integer, "num")), TargetType.Integer, new TargetBlock(List.of(new TargetReturn(new TargetBinaryOp.Mul(TargetType.Integer, new TargetLocalVar(TargetType.Integer, "num"), new TargetLiteral.IntLiteral(2))))))), new TargetReturn(new TargetCast(TargetType.Integer, new TargetMethodCall(TargetType.Object, TargetType.Object, List.of(TargetType.Object), new TargetLocalVar(interfaceType, "by2"), List.of(new TargetLiteral.IntLiteral(10)), interfaceType, "apply", false, true)))))); + var clazz = generateClass(targetClass, classLoader); + var instance = clazz.getConstructor().newInstance(); + assertEquals(clazz.getDeclaredMethod("lambda").invoke(instance), 20); + } } diff --git a/src/test/java/targetast/TestGenerics.java b/src/test/java/targetast/TestGenerics.java index 5f74ae3a..6d2ab724 100644 --- a/src/test/java/targetast/TestGenerics.java +++ b/src/test/java/targetast/TestGenerics.java @@ -21,9 +21,7 @@ import java.nio.file.Path; import java.util.ArrayList; import java.util.List; - public class TestGenerics { - private static final String rootDirectory = System.getProperty("user.dir") + "/resources/insertGenerics/javFiles/"; private static final String bytecodeDirectory = System.getProperty("user.dir") + "/src/test/resources/testBytecode/generatedBC/"; diff --git a/src/test/java/typeinference/JavaTXCompilerTest.java b/src/test/java/typeinference/JavaTXCompilerTest.java index 60a27221..069f9e40 100644 --- a/src/test/java/typeinference/JavaTXCompilerTest.java +++ b/src/test/java/typeinference/JavaTXCompilerTest.java @@ -7,6 +7,8 @@ import de.dhbwstuttgart.syntaxtree.visual.ASTTypePrinter; import de.dhbwstuttgart.typedeployment.TypeInsert; import de.dhbwstuttgart.typedeployment.TypeInsertFactory; import de.dhbwstuttgart.typeinference.result.ResultSet; + +import org.junit.Ignore; import org.junit.Test; import java.io.File; @@ -20,157 +22,178 @@ import java.util.HashSet; import java.util.List; import java.util.Set; +@Ignore("To be renewed") public class JavaTXCompilerTest { - public static final String rootDirectory = System.getProperty("user.dir")+"/resources/javFiles/"; + public static final String rootDirectory = System.getProperty("user.dir") + "/src/test/resources/javFiles/"; + @Test public void finiteClosure() throws IOException, ClassNotFoundException { - execute(new File(rootDirectory+"fc.jav")); - } - @Test - public void importTest() throws IOException, ClassNotFoundException { - execute(new File(rootDirectory+"Import.jav")); - } - @Test - public void fieldTest() throws IOException, ClassNotFoundException { - execute(new File(rootDirectory+"FieldAccess.jav")); - } - @Test - 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 lambdaField() throws IOException, ClassNotFoundException { - execute(new File(rootDirectory+"LambdaField.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 genericsMethodCall() throws IOException, ClassNotFoundException { - TestResultSet result = execute(new File(rootDirectory+"MethodCallGenerics.jav")); - //TODO: Hier sollte der Rückgabetyp der Methode String sein - } - @Test - public void faculty() throws IOException, ClassNotFoundException { - execute(new File(rootDirectory+"Faculty.jav")); - } - @Test - public void facultyIf() throws IOException, ClassNotFoundException { - execute(new File(rootDirectory+"FacultyIf.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")); - } - @Test - public void packageTests() throws IOException, ClassNotFoundException { - execute(new File(rootDirectory+"Package.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")); - } - @Test - public void addLong() throws IOException, ClassNotFoundException { - execute(new File(rootDirectory+"AddLong.jav")); - } - @Test - public void fields() throws IOException, ClassNotFoundException { - execute(new File(rootDirectory+"Fields.jav")); - } - @Test - public void ifStatement() throws IOException, ClassNotFoundException { - execute(new File(rootDirectory+"IfTest.jav")); - } - @Test - public void multipleSolutions() throws IOException, ClassNotFoundException { - execute(new File(rootDirectory+"Sorting.jav")); - } - @Test - public void listenerTest() throws IOException, ClassNotFoundException { - execute(new File(rootDirectory+"ListenerOverload.jav")); + execute(new File(rootDirectory + "fc.jav")); } - private static class TestResultSet{ + @Test + public void importTest() throws IOException, ClassNotFoundException { + execute(new File(rootDirectory + "Import.jav")); + } + + @Test + public void fieldTest() throws IOException, ClassNotFoundException { + execute(new File(rootDirectory + "FieldAccess.jav")); + } + + @Test + 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 lambdaField() throws IOException, ClassNotFoundException { + execute(new File(rootDirectory + "LambdaField.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 genericsMethodCall() throws IOException, ClassNotFoundException { + TestResultSet result = execute(new File(rootDirectory + "MethodCallGenerics.jav")); + // TODO: Hier sollte der Rückgabetyp der Methode String sein + } + + @Test + public void faculty() throws IOException, ClassNotFoundException { + execute(new File(rootDirectory + "Faculty.jav")); + } + + @Test + public void facultyIf() throws IOException, ClassNotFoundException { + execute(new File(rootDirectory + "FacultyIf.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")); + } + + @Test + public void packageTests() throws IOException, ClassNotFoundException { + execute(new File(rootDirectory + "Package.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")); + } + + @Test + public void addLong() throws IOException, ClassNotFoundException { + execute(new File(rootDirectory + "AddLong.jav")); + } + + @Test + public void fields() throws IOException, ClassNotFoundException { + execute(new File(rootDirectory + "Fields.jav")); + } + + @Test + public void ifStatement() throws IOException, ClassNotFoundException { + execute(new File(rootDirectory + "IfTest.jav")); + } + + @Test + public void multipleSolutions() throws IOException, ClassNotFoundException { + execute(new File(rootDirectory + "Sorting.jav")); + } + + @Test + public void listenerTest() throws IOException, ClassNotFoundException { + execute(new File(rootDirectory + "ListenerOverload.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")); - //filesToTest.add(new File(rootDirectory+"Lambda3.jav")); - //filesToTest.add(new File(rootDirectory+"Vector.jav")); - //filesToTest.add(new File(rootDirectory+"Generics.jav")); - //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")); + // filesToTest.add(new File(rootDirectory+"fc.jav")); + // filesToTest.add(new File(rootDirectory+"Lambda.jav")); + // filesToTest.add(new File(rootDirectory+"Lambda2.jav")); + // filesToTest.add(new File(rootDirectory+"Lambda3.jav")); + // filesToTest.add(new File(rootDirectory+"Vector.jav")); + // filesToTest.add(new File(rootDirectory+"Generics.jav")); + // 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); - for(File f : compiler.sourceFiles.keySet()){ + for (File f : compiler.sourceFiles.keySet()) { SourceFile sf = compiler.sourceFiles.get(f); System.out.println(ASTTypePrinter.print(sf)); System.out.println(ASTPrinter.print(sf)); } List results = compiler.typeInference(); - //compiler.generateBytecode(rootDirectory+"xxx.class", results, simplifyResultsForAllSourceFiles); - for(File f : compiler.sourceFiles.keySet()){ + // compiler.generateBytecode(rootDirectory+"xxx.class", results, simplifyResultsForAllSourceFiles); + for (File f : compiler.sourceFiles.keySet()) { SourceFile sf = compiler.sourceFiles.get(f); System.out.println(ASTTypePrinter.print(sf)); System.out.println(ASTPrinter.print(sf)); - //List results = compiler.typeInference(); PL 2017-10-03 vor die For-Schleife gezogen - assert results.size()>0; + // List results = compiler.typeInference(); PL 2017-10-03 vor die For-Schleife gezogen + assert results.size() > 0; Set insertedTypes = new HashSet<>(); - for(var i = 0; i < results.size(); i++) { + for (var i = 0; i < results.size(); i++) { var resultSet = results.get(i); Set result = TypeInsertFactory.createTypeInsertPoints(sf, resultSet, compiler.getGeneratedGenerics().get(sf).get(i)); - assert result.size()>0; + assert result.size() > 0; String content = readFile(f.getPath(), StandardCharsets.UTF_8); - for(TypeInsert tip : result){ + for (TypeInsert tip : result) { insertedTypes.add(tip.insert(content)); } } - for(String s : insertedTypes){ + for (String s : insertedTypes) { System.out.println(s); } } return new TestResultSet(); } - static String readFile(String path, Charset encoding) - throws IOException - { + static String readFile(String path, Charset encoding) throws IOException { byte[] encoded = Files.readAllBytes(Paths.get(path)); return new String(encoded, encoding); } } - diff --git a/src/test/java/typeinference/Meth_GenTest.java b/src/test/java/typeinference/Meth_GenTest.java deleted file mode 100644 index 22f7fd51..00000000 --- a/src/test/java/typeinference/Meth_GenTest.java +++ /dev/null @@ -1,140 +0,0 @@ -package typeinference; - -import de.dhbwstuttgart.core.JavaTXCompiler; -import de.dhbwstuttgart.syntaxtree.SourceFile; -import de.dhbwstuttgart.syntaxtree.visual.ASTPrinter; -import de.dhbwstuttgart.syntaxtree.visual.ASTTypePrinter; -import de.dhbwstuttgart.typedeployment.TypeInsert; -import de.dhbwstuttgart.typedeployment.TypeInsertFactory; -import de.dhbwstuttgart.typeinference.result.ResultSet; -import org.junit.Test; - -import java.io.File; -import java.io.IOException; -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -public class Meth_GenTest { - - public static final String rootDirectory = System.getProperty("user.dir")+"/resources/javFiles/"; -/* - @Test - public void finiteClosure() throws IOException, ClassNotFoundException { - execute(new File(rootDirectory+"fc.jav")); - } - @Test - 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 facultyTyped() throws IOException, ClassNotFoundException { - execute(new File(rootDirectory+"FacultyTyped.jav")); - } -*/ - @Test - public void matrix() throws IOException, ClassNotFoundException { - execute(new File(rootDirectory+"Meth_Gen.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")); - } - @Test - public void matrixFC() throws IOException, ClassNotFoundException { - execute(new File(rootDirectory+"FC_Matrix.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")); - //filesToTest.add(new File(rootDirectory+"Lambda3.jav")); - //filesToTest.add(new File(rootDirectory+"Vector.jav")); - //filesToTest.add(new File(rootDirectory+"Generics.jav")); - //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); - for(File f : compiler.sourceFiles.keySet()){ - SourceFile sf = compiler.sourceFiles.get(f); - System.out.println(ASTTypePrinter.print(sf)); - System.out.println(ASTPrinter.print(sf)); - } - List results = compiler.typeInference(); - - for(File f : compiler.sourceFiles.keySet()){ - SourceFile sf = compiler.sourceFiles.get(f); - System.out.println(ASTTypePrinter.print(sf)); - System.out.println(ASTPrinter.print(sf)); - //List results = compiler.typeInference(); PL 2017-10-03 vor die For-Schleife gezogen - assert results.size()>0; - Set insertedTypes = new HashSet<>(); - for(var i = 0; i < results.size(); i++){ - var resultSet = results.get(i); - Set result = TypeInsertFactory.createTypeInsertPoints(sf, resultSet, compiler.getGeneratedGenerics().get(sf).get(i)); - assert result.size()>0; - String content = readFile(f.getPath(), StandardCharsets.UTF_8); - for(TypeInsert tip : result){ - insertedTypes.add(tip.insert(content)); - } - } - for(String s : insertedTypes){ - System.out.println(s); - } - } - return new TestResultSet(); - } - - static String readFile(String path, Charset encoding) - throws IOException - { - byte[] encoded = Files.readAllBytes(Paths.get(path)); - return new String(encoded, encoding); - } - -} - diff --git a/src/test/java/typeinference/UnifyTest.java b/src/test/java/typeinference/UnifyTest.java deleted file mode 100644 index 4881de34..00000000 --- a/src/test/java/typeinference/UnifyTest.java +++ /dev/null @@ -1,166 +0,0 @@ -package typeinference; - -import de.dhbwstuttgart.core.JavaTXCompiler; -import de.dhbwstuttgart.syntaxtree.SourceFile; -import de.dhbwstuttgart.syntaxtree.visual.ASTPrinter; -import de.dhbwstuttgart.syntaxtree.visual.ASTTypePrinter; -import de.dhbwstuttgart.typedeployment.TypeInsert; -import de.dhbwstuttgart.typedeployment.TypeInsertFactory; -import de.dhbwstuttgart.typeinference.result.ResultSet; -import org.junit.Test; - -import java.io.File; -import java.io.IOException; -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -public class UnifyTest { - - public static final String rootDirectory = System.getProperty("user.dir")+"/resources/javFiles/"; -/* - @Test - public void finiteClosure() throws IOException, ClassNotFoundException { - execute(new File(rootDirectory+"fc.jav")); - } - - @Test - public void lambda() throws IOException, ClassNotFoundException { - execute(new File(rootDirectory+"Lambda.jav")); - } - - */ - /* - @Test - public void vector() throws IOException, ClassNotFoundException { - execute(new File(rootDirectory+"Vector.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 lambdafield() throws IOException, ClassNotFoundException { - execute(new File(rootDirectory+"LambdaField.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 facultyTyped() throws IOException, ClassNotFoundException { - execute(new File(rootDirectory+"FacultyTyped.jav")); - } - */ - - @Test - public void matrix() throws IOException, ClassNotFoundException { - execute(new File(rootDirectory+"Matrix.jav")); - //JavaTXCompiler compiler = new JavaTXCompiler(new File(rootDirectory+"Matrix.jav")); - //compiler.generateBytecode(); - } - - -/* - @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")); - } - @Test - public void matrixFC() throws IOException, ClassNotFoundException { - execute(new File(rootDirectory+"FC_Matrix.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")); - //filesToTest.add(new File(rootDirectory+"Lambda3.jav")); - //filesToTest.add(new File(rootDirectory+"Vector.jav")); - //filesToTest.add(new File(rootDirectory+"Generics.jav")); - //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); - for(File f : compiler.sourceFiles.keySet()){ - SourceFile sf = compiler.sourceFiles.get(f); - System.out.println(ASTTypePrinter.print(sf)); - System.out.println(ASTPrinter.print(sf)); - } - List results = compiler.typeInference(); - - for(File f : compiler.sourceFiles.keySet()){ - SourceFile sf = compiler.sourceFiles.get(f); - System.out.println(ASTTypePrinter.print(sf)); - System.out.println(ASTPrinter.print(sf)); - //List results = compiler.typeInference(); PL 2017-10-03 vor die For-Schleife gezogen - assert results.size()>0; - Set insertedTypes = new HashSet<>(); - for(var i = 0; i < results.size(); i++) { - var resultSet = results.get(i); - Set result = TypeInsertFactory.createTypeInsertPoints(sf, resultSet, compiler.getGeneratedGenerics().get(sf).get(i)); - assert result.size()>0; - String content = readFile(f.getPath(), StandardCharsets.UTF_8); - for(TypeInsert tip : result){ - insertedTypes.add(tip.insert(content)); - } - } - for(String s : insertedTypes){ - System.out.println(s); - } - } - return new TestResultSet(); - } - - static String readFile(String path, Charset encoding) - throws IOException - { - byte[] encoded = Files.readAllBytes(Paths.get(path)); - return new String(encoded, encoding); - } - -} - diff --git a/src/test/java/visualisation/ToString.java b/src/test/java/visualisation/ToString.java deleted file mode 100644 index 00b8ddea..00000000 --- a/src/test/java/visualisation/ToString.java +++ /dev/null @@ -1,5 +0,0 @@ -package visualisation; - -public class ToString { - -} diff --git a/resources/log4jTesting.xml b/src/test/resources/log4jTesting.xml similarity index 100% rename from resources/log4jTesting.xml rename to src/test/resources/log4jTesting.xml