Merge remote-tracking branch 'origin/master'

This commit is contained in:
Krauß, Josefine 2024-05-09 14:22:59 +02:00
commit 5de106876a
39 changed files with 386 additions and 3380 deletions

View File

@ -8,7 +8,7 @@ import java.util.List;
public class Compiler {
public static void Main(String[] args) throws Exception{
public static void main(String[] args) throws Exception{
// get file
@ -20,6 +20,5 @@ public class Compiler {
abstractSyntaxTree.typeCheck();
abstractSyntaxTree.codeGen();
}
}

View File

@ -35,7 +35,7 @@ public class FieldDecl extends AbstractType implements IClass{
}
@Override
public TypeCheckResult typeCheck() throws Exception {
public TypeCheckResult typeCheck(HashMap<String, HashMap<String, HashMap<String, List<String>>>> methodContext, HashMap<String, HashMap<String, String>> typeContext, List<MethodDecl> fieldsOrMethods) throws Exception {
return null;
}

View File

@ -4,12 +4,13 @@ import TypeCheck.TypeCheckResult;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.TypeReference;
import java.util.HashMap;
import java.util.List;
public interface IClass {
// visit method for code generation
TypeCheckResult typeCheck() throws Exception;
TypeCheckResult typeCheck(HashMap<String, HashMap<String, HashMap<String, List<String>>>> methodContext, HashMap<String, HashMap<String, String>> typeContext, List<MethodDecl> fieldsOrMethods) throws Exception;
void codeGen(ClassWriter cw) throws Exception;
}

View File

@ -18,7 +18,7 @@ public class MethodDecl implements IClass {
//TODO: Move this into the typeCheck
private HashMap<String, String> localVars; // (type, identifier) // add content here
public TypeCheckResult typeCheck(HashMap<String, HashMap<String, HashMap<String, String>>> methodContext, HashMap<String, HashMap<String, String>> typeContext, List<MethodDecl> fieldsOrMethods) throws Exception {
public TypeCheckResult typeCheck(HashMap<String, HashMap<String, HashMap<String, List<String>>>> methodContext, HashMap<String, HashMap<String, String>> typeContext, List<MethodDecl> fieldsOrMethods) throws Exception {
// write localvars

View File

@ -20,14 +20,13 @@ public class RefType extends AbstractType implements IClass {
public List<FieldDecl> fieldDecls;
public List<MethodDecl> methodDecls;
private HashMap<String, HashMap<String, String>> typeContext; // (class, (type, identifier))
private HashMap<String, HashMap<String, HashMap<String, String>>> methodContext; // (class, (returntype, (identifier, parameter)
public HashMap<String, HashMap<String, HashMap<String, List<String>>>> methodContext; // (class, (returntype, (identifier, parameter)))
private boolean hasMain;
public RefType(List<FieldDecl> fieldDecls,
List<MethodDecl> methodDecls,
HashMap<String, HashMap<String, String>> typeContext,
HashMap<String, HashMap<String, HashMap<String, String>>> methodContext){
HashMap<String, HashMap<String, HashMap<String, List<String>>>> methodContext){
this.fieldDecls = fieldDecls;
this.methodDecls = methodDecls;
this.typeContext = typeContext;
@ -37,7 +36,7 @@ public class RefType extends AbstractType implements IClass {
@Override
public TypeCheckResult typeCheck() throws Exception {
public TypeCheckResult typeCheck(HashMap<String, HashMap<String, HashMap<String, List<String>>>> methodContext, HashMap<String, HashMap<String, String>> typeContext, List<MethodDecl> fieldsOrMethods) throws Exception {
TypeCheckResult result = new TypeCheckResult();
for (FieldDecl fieldDecl : fieldDecls) {

View File

@ -39,7 +39,7 @@ public class Program {
methodContext.put(oneClass.name, returnTypeAndMethod);
oneClass.typeCheck();
oneClass.typeCheck(methodContext, typeContext, oneClass.methodDecls);
}
return null;
}

View File

@ -33,9 +33,9 @@ public class AssignStatementExpression extends AbstractType implements IExpressi
}
@Override
public void CodeGen(MethodVisitor mv) throws Exception {
left.CodeGen(mv);
right.CodeGen(mv);
public void codeGen(MethodVisitor mv) throws Exception {
left.codeGen(mv);
right.codeGen(mv);
if (left instanceof VarRefExpression varRef) {
//TODO: Implement the handling of a variable reference --> I need a list of local variables

View File

@ -6,6 +6,7 @@ import abstractSyntaxTree.Class.MethodDecl;
import abstractSyntaxTree.Class.RefType;
import abstractSyntaxTree.Expression.IExpression;
import abstractSyntaxTree.Statement.IStatement;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
@ -42,17 +43,12 @@ public class MethodCallStatementExpression extends AbstractType implements IExpr
return result;
}
@Override
public void codeGen(MethodVisitor mv) throws Exception {
}
//Errors occur due to the change in parameter in the RefType class
@Override
public void CodeGen(MethodVisitor mv) throws Exception {
public void codeGen(MethodVisitor mv) throws Exception {
//Generate Bytecode for the receiver
if(classThatHasTheMethodIfNotThis != null){
classThatHasTheMethodIfNotThis.codeGen();
classThatHasTheMethodIfNotThis.codeGen(new ClassWriter(ClassWriter.COMPUTE_FRAMES));
} else {
mv.visitVarInsn(Opcodes.ALOAD, 0);
}

View File

@ -13,7 +13,7 @@ public class NewStatementExpression extends AbstractType implements IExpression,
}
@Override
public void CodeGen(MethodVisitor mv) throws Exception {
public void codeGen(MethodVisitor mv) throws Exception {
throw new Exception("CodeGen not implemented for NewStatementExpression");
}
}

View File

@ -1,273 +0,0 @@
package AST;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.InputStream;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import Helper.MockGenerator;
import Helper.Resources;
import common.AccessModifier;
import common.BaseType;
import common.Compiler;
import common.Primitives;
import common.PrintableVector;
import syntaxtree.structure.ClassDecl;
import syntaxtree.structure.ConstructorDecl;
import syntaxtree.structure.FieldDecl;
import syntaxtree.structure.Program;
@DisplayName("Abstract Syntax Tree Generation")
public class TestRunner {
@Test
@DisplayName("Control Test")
void controlTest() {
var first = MockGenerator.getConstructorParameterAst();
var second = MockGenerator.getConstructorParameterAst();
assertEquals(first, second);
}
@Test
@DisplayName("Empty Class")
void emptyClass() {
InputStream file = Resources.getFileAsStream("SimpleTests/EmptyClass.java");
Program ast = Compiler.getFactory().getAstAdapter().getAst(file);
PrintableVector<ConstructorDecl> constructors = new PrintableVector<>();
constructors.add(new ConstructorDecl());
ClassDecl classDecl = new ClassDecl("EmptyClass", new PrintableVector<>(), constructors,
new PrintableVector<>());
PrintableVector<ClassDecl> classDecls = new PrintableVector<>();
classDecls.add(classDecl);
var generatedAst = new Program(classDecls);
assertEquals(generatedAst, ast);
}
@Test
@DisplayName("EmptyClassWithConstructor")
void emptyClassWithConstructor() {
InputStream file = Resources.getFileAsStream("SimpleTests/EmptyClassWithConstructor.java");
Program generatedAst = Compiler.getFactory().getAstAdapter().getAst(file);
PrintableVector<ConstructorDecl> constructors = new PrintableVector<>();
constructors.add(new ConstructorDecl());
ClassDecl classDecl = new ClassDecl("EmptyClassWithConstructor", new PrintableVector<>(), constructors,
new PrintableVector<>());
PrintableVector<ClassDecl> classDecls = new PrintableVector<>();
classDecls.add(classDecl);
var ast = new Program(classDecls);
assertEquals(ast, generatedAst);
}
@Test
@DisplayName("ClassFields")
void classFields() {
Program generatedAst = Resources.getProgram("SimpleTests/ClassFields.java");
Program expectedAst = MockGenerator.getClassFieldsAst();
assertEquals(expectedAst, generatedAst);
}
@Test
@DisplayName("ClassField without AccessModifier")
void classFieldWithoutAccessModifier() {
Program generatedAst = Resources.getProgram("SimpleTests/AutoAccessModifierField.java");
Program expectedAst = MockGenerator.getAutoClassFieldAst();
assertEquals(expectedAst, generatedAst);
}
@Test
@DisplayName("Comments")
void commentTest() {
InputStream file = Resources.getFileAsStream("SimpleTests/Comments.java");
Program generatedAst = Compiler.getFactory().getAstAdapter().getAst(file);
PrintableVector<ConstructorDecl> constructors = new PrintableVector<>();
constructors.add(new ConstructorDecl());
PrintableVector<FieldDecl> fields = new PrintableVector<>();
FieldDecl lorem = new FieldDecl("lorem", AccessModifier.PRIVATE);
lorem.setType(new BaseType(Primitives.INT));
fields.add(lorem);
FieldDecl ipsum = new FieldDecl("ipsum", AccessModifier.PRIVATE);
ipsum.setType(new BaseType(Primitives.BOOL));
fields.add(ipsum);
ClassDecl classDecl = new ClassDecl("Comments", fields, constructors, new PrintableVector<>());
PrintableVector<ClassDecl> classDecls = new PrintableVector<>();
classDecls.add(classDecl);
var expectedAst = new Program(classDecls);
assertEquals(expectedAst, generatedAst);
}
@Test
@DisplayName("Constructor With Parameters")
void constructorWithParameters() {
Program generatedAst = Resources.getProgram("SimpleTests/ConstructorParams.java");
Program expectedAst = MockGenerator.getConstructorParameterAst();
assertEquals(expectedAst, generatedAst);
}
@Test
@DisplayName("Constructor With this. assign body")
void constructorWithThisAssignBody() {
Program generatedAst = Resources.getProgram("SimpleTests/ConstructorThisDot.java");
Program expectedAst = MockGenerator.getConstructorThisDotAst();
assertEquals(expectedAst, generatedAst);
}
@Test
@DisplayName("VoidMethod")
void voidMethod() {
Program generatedAst = Resources.getProgram("SimpleTests/VoidMethod.java");
Program expectedAst = MockGenerator.getVoidMethodAst();
assertEquals(expectedAst, generatedAst);
}
@Test
@DisplayName("RealConstructor")
void realConstructor() {
Program generatedAst = Resources.getProgram("SimpleTests/RealConstructor.java");
Program expectedAst = MockGenerator.getRealConstructorAst();
assertEquals(expectedAst, generatedAst);
}
@Test
@DisplayName("MethodCall")
void methodCall() {
Program generatedAst = Resources.getProgram("SimpleTests/MethodCall.java");
Program expectedAst = MockGenerator.getMethodCallAst();
assertEquals(expectedAst, generatedAst);
}
@Test
@DisplayName("ThisDotMethodCall")
void thisDotMethodCall() {
Program generatedAst = Resources.getProgram("SimpleTests/ThisDotMethodCall.java");
Program expectedAst = MockGenerator.getThisDotMethodCallAst();
assertEquals(expectedAst, generatedAst);
}
@Test
@DisplayName("MethodCallWithParameters")
void methodCallWithParameters() {
Program generatedAst = Resources.getProgram("SimpleTests/MethodCallParams.java");
Program expectedAst = MockGenerator.getMethodCallWithParameterAst();
assertEquals(expectedAst, generatedAst);
}
@Test
@DisplayName("GetterFunction")
void getterFunction() {
Program generatedAst = Resources.getProgram("SimpleTests/GetterFunction.java");
Program expectedAst = MockGenerator.getGetterFunctionAst();
System.out.println(generatedAst);
assertEquals(expectedAst, generatedAst);
}
@Test
@DisplayName("CharArgument")
void charArgument() {
Program generatedAst = Resources.getProgram("SimpleTests/CharArgument.java");
Program expectedAst = MockGenerator.getCharArgumentAst();
assertEquals(expectedAst, generatedAst);
}
@Test
@DisplayName("ExplicitNullAssign")
void explicitNullAssign() {
Program generatedAst = Resources.getProgram("SimpleTests/ExplicitNullAssign.java");
Program expectedAst = MockGenerator.getExplicitNullAssignAst();
assertEquals(expectedAst, generatedAst);
}
@Test
@DisplayName("SelfReference")
void selfReference() {
Program generatedAst = Resources.getProgram("SimpleTests/SelfReference.java");
Program expectedAst = MockGenerator.getSelfReferenceAst();
assertEquals(expectedAst, generatedAst);
}
@Test
@DisplayName("ValueAdapterTests")
void valueAdapterTest() {
Program generatedAst = Resources.getProgram("SimpleTests/ValueAdapterTests.java");
Program expectedAst = MockGenerator.getValueAdapterTestAst();
assertEquals(expectedAst, generatedAst);
}
@Test
@DisplayName("System.out.println Test")
void systemOutPrintlnTest() {
Program generatedAst = Resources.getProgram("SimpleTests/SystemOutPrintln.java");
Program expectedAst = MockGenerator.getSystemOutPrintlnAst();
assertEquals(expectedAst, generatedAst);
}
@Test
@DisplayName("System.out.print-String Test")
void systemOutPrintStringTest() {
Program generatedAst = Resources.getProgram("SimpleTests/SystemOutPrintlnString.java");
Program expectedAst = MockGenerator.getSystemOutPrintStringAst();
assertEquals(expectedAst, generatedAst);
}
@Test
@DisplayName("MainMethodTest")
void mainMethodTest() {
Program generatedAst = Resources.getProgram("SimpleTests/MainMethodTest.java");
Program expectedAst = MockGenerator.getMainMethodTestAst();
assertEquals(expectedAst, generatedAst);
}
@Test
@DisplayName("ForTest")
void forTest() {
Program generatedAst = Resources.getProgram("SimpleTests/ForTest.java");
Program expectedAst = MockGenerator.getForTestAst();
assertEquals(expectedAst, generatedAst);
}
@Test
@DisplayName("IncTest")
void incTest() {
Program generatedAst = Resources.getProgram("SimpleTests/IncTest.java");
Program expectedAst = MockGenerator.getIncTestAst();
assertEquals(expectedAst, generatedAst);
}
@Test
@DisplayName("DecTest")
void decTest() {
Program generatedAst = Resources.getProgram("SimpleTests/DecTest.java");
Program expectedAst = MockGenerator.getDecTestAst();
assertEquals(expectedAst, generatedAst);
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,16 @@
package ByteCode;
import java.security.SecureClassLoader;
public class ByteCodeLoader extends SecureClassLoader {
private final byte[] bytecode;
public ByteCodeLoader(byte[] bytecode) {
this.bytecode = bytecode;
}
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
return defineClass(name, bytecode, 0, bytecode.length);
}
}

View File

@ -1,356 +0,0 @@
package CodeGen;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import Helper.MockGenerator;
import Helper.ReflectLoader;
import Helper.Resources;
import common.Compiler;
import common.PrintableVector;
import syntaxtree.structure.ClassDecl;
import syntaxtree.structure.ConstructorDecl;
import syntaxtree.structure.Program;
@DisplayName("Bytecode Generation")
public class TestRunner {
private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
private final ByteArrayOutputStream errContent = new ByteArrayOutputStream();
private final PrintStream originalOut = System.out;
private final PrintStream originalErr = System.err;
@Test
@DisplayName("Empty Class")
void main() {
ClassDecl emptyClass = new ClassDecl("EmptyClass", new PrintableVector<>(), new PrintableVector<>(),
new PrintableVector<>());
PrintableVector<ClassDecl> classDecls = new PrintableVector<>();
classDecls.add(emptyClass);
var tast = new Program(classDecls);
var bc = Compiler.getFactory().getProgramGenerator().generateBytecode(tast);
ReflectLoader loader = new ReflectLoader(bc);
Class<?> c = loader.findClass("EmptyClass");
Object o;
try {
o = c.getDeclaredConstructor().newInstance();
assertEquals(o.getClass().getName(), "EmptyClass");
} catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException
| NoSuchMethodException | SecurityException e) {
fail(e.getLocalizedMessage());
}
}
@Test
@DisplayName("EmptyClassWithConstructor")
void emptyClassWithConstructor() {
PrintableVector<ConstructorDecl> constructors = new PrintableVector<>();
constructors.add(new ConstructorDecl());
ClassDecl classDecl = new ClassDecl("EmptyClassWithConstructor", new PrintableVector<>(), constructors,
new PrintableVector<>());
PrintableVector<ClassDecl> classDecls = new PrintableVector<>();
classDecls.add(classDecl);
var tast = new Program(classDecls);
var bc = Compiler.getFactory().getProgramGenerator().generateBytecode(tast);
ReflectLoader loader = new ReflectLoader(bc);
Class<?> c = loader.findClass("EmptyClassWithConstructor");
Object o;
try {
o = c.getDeclaredConstructor().newInstance();
assertEquals(o.getClass().getName(), "EmptyClassWithConstructor");
} catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException
| NoSuchMethodException | SecurityException e) {
fail(e.getLocalizedMessage());
}
}
@Test
@DisplayName("Constructor With Parameters")
void constructorWithParameters() {
Program tast = MockGenerator.getConstructorParameterTast();
var bc = Compiler.getFactory().getProgramGenerator().generateBytecode(tast);
ReflectLoader loader = new ReflectLoader(bc);
Class<?> c = loader.findClass("ConstructorParams");
Object o = null;
try {
o = c.getDeclaredConstructor(int.class).newInstance(1);
assertEquals(o.getClass().getName(), "ConstructorParams");
} catch (Exception e) {
fail(e.getLocalizedMessage());
}
}
@Test
@DisplayName("Constructor With this. assign body")
void constructorWithThisAssignBody() {
Program tast = MockGenerator.getConstructorThisDotTast();
var bc = Compiler.getFactory().getProgramGenerator().generateBytecode(tast);
ReflectLoader loader = new ReflectLoader(bc);
Class<?> c = loader.findClass("ConstructorThisDot");
Object o = null;
try {
o = c.getDeclaredConstructor().newInstance();
var i = loader.getField("ConstructorThisDot", "i");
var ivalue = i.get(o);
assertEquals(5, ivalue);
} catch (Exception e) {
fail(e.getLocalizedMessage());
}
}
@Test
@DisplayName("ClassFields - autoAccess")
void classFieldsAuto() {
Program tast = MockGenerator.getAutoClassFieldAst();
var bc = Compiler.getFactory().getProgramGenerator().generateBytecode(tast);
ReflectLoader loader = new ReflectLoader(bc);
try {
var autoAccess = loader.getField("AutoAccessModifierField", "autoAccess");
System.out.println(autoAccess.getModifiers());
assertEquals(0, autoAccess.getModifiers());
} catch (Exception e) {
fail(e.getLocalizedMessage());
}
}
@Test
@DisplayName("ClassFields - privateAccess")
void classFieldsPrivate() {
Program tast = MockGenerator.getClassFieldsTast();
var bc = Compiler.getFactory().getProgramGenerator().generateBytecode(tast);
ReflectLoader loader = new ReflectLoader(bc);
try {
var autoAccess = loader.getField("ClassFields", "privateAccess");
assertEquals(Modifier.PRIVATE, autoAccess.getModifiers());
} catch (Exception e) {
fail(e.getLocalizedMessage());
}
}
@Test
@DisplayName("ClassFields - publicAccess")
void classFieldsPublic() {
Program tast = MockGenerator.getClassFieldsTast();
var bc = Compiler.getFactory().getProgramGenerator().generateBytecode(tast);
ReflectLoader loader = new ReflectLoader(bc);
try {
var autoAccess = loader.getField("ClassFields", "publicAccess");
assertEquals(Modifier.PUBLIC, autoAccess.getModifiers());
} catch (Exception e) {
fail(e.getLocalizedMessage());
}
}
@Test
@DisplayName("ClassFields - protectedAccess")
void classFieldsProtected() {
Program tast = MockGenerator.getClassFieldsTast();
var bc = Compiler.getFactory().getProgramGenerator().generateBytecode(tast);
ReflectLoader loader = new ReflectLoader(bc);
try {
var autoAccess = loader.getField("ClassFields", "protectedAccess");
assertEquals(Modifier.PROTECTED, autoAccess.getModifiers());
} catch (Exception e) {
fail(e.getLocalizedMessage());
}
}
@Test
@DisplayName("VoidMethod")
void voidMethod() {
Program tast = MockGenerator.getVoidMethodTast();
var bc = Compiler.getFactory().getProgramGenerator().generateBytecode(tast);
ReflectLoader loader = new ReflectLoader(bc);
Class<?> c = loader.findClass("VoidMethod");
Object o = null;
try {
o = c.getDeclaredConstructor().newInstance();
var m = loader.getMethod("VoidMethod", "foo");
m.invoke(o);
assertEquals("foo", m.getName());
} catch (Exception e) {
fail(e.getLocalizedMessage());
}
}
@Test
@DisplayName("RealConstructor")
void realConstructor() {
Program tast = MockGenerator.getRealConstructorTast();
var bc = Compiler.getFactory().getProgramGenerator().generateBytecode(tast);
ReflectLoader loader = new ReflectLoader(bc);
Class<?> c = loader.findClass("RealConstructor");
try {
int randomI = 2;
var constructor = c.getDeclaredConstructor(int.class);
Object o = constructor.newInstance(randomI);
var i = loader.getField("RealConstructor", "i");
int ivalue = (int) i.get(o);
assertEquals(randomI, ivalue);
} catch (NoSuchFieldException e) {
fail("No such field");
} catch (Exception e) {
fail(e.getCause());
}
}
@Test
@DisplayName("MethodCall")
void methodCall() {
Program tast = MockGenerator.getMethodCallTast();
var bc = Compiler.getFactory().getProgramGenerator().generateBytecode(tast);
ReflectLoader loader = new ReflectLoader(bc);
Class<?> c = loader.findClass("MethodCall");
Object o = null;
int value = 1;
try {
o = c.getDeclaredConstructor().newInstance();
var i = loader.getField("MethodCall", "i");
int ivalue = (int) i.get(o);
assertEquals(value, ivalue);
} catch (Exception e) {
fail(e.getMessage());
}
}
@Test
@DisplayName("MiniLinkedList")
void miniLinkedList() {
Program program = Resources.getProgram("SimpleTests/MiniLinkedList.java");
System.out.println(program);
Program tast = Compiler.getFactory().getTastAdapter().getTast(program);
Compiler.getFactory().getProgramGenerator().generateBytecode(tast);
}
@Test
@DisplayName("SystemOutPrintln Test")
void systemOutPrintlnTest() {
Program tast = MockGenerator.getSystemOutPrintlnTast();
var bc = Compiler.getFactory().getProgramGenerator().generateBytecode(tast);
ReflectLoader loader = new ReflectLoader(bc);
Class<?> c = loader.findClass("SystemOutPrintln");
Object o = null;
try {
o = c.getDeclaredConstructor().newInstance();
var m = loader.getMethod("SystemOutPrintln", "foo");
m.invoke(o);
} catch (Exception e) {
fail(e.getMessage());
}
}
@Test
@DisplayName("SystemOutPrintlnString Test")
void systemOutPrintlnStringTest() {
Program tast = MockGenerator.getSystemOutPrintStringTast();
var bc = Compiler.getFactory().getProgramGenerator().generateBytecode(tast);
ReflectLoader loader = new ReflectLoader(bc);
Class<?> c = loader.findClass("SystemOutPrintlnString");
Object o = null;
try {
o = c.getDeclaredConstructor().newInstance();
var m = loader.getMethod("SystemOutPrintlnString", "foo");
m.invoke(o);
} catch (Exception e) {
fail(e.getMessage());
}
}
@Test
@DisplayName("MainMethodTest")
void mainMethodTest() {
Program tast = MockGenerator.getMainMethodTestTast();
var bc = Compiler.getFactory().getProgramGenerator().generateBytecode(tast);
ReflectLoader loader = new ReflectLoader(bc);
Class<?> c = loader.findClass("MainMethodTest");
try {
var m = c.getMethod("main", String[].class);
m.invoke(null, new Object[] { new String[] {} });
} catch (Exception e) {
fail(e.getMessage());
}
}
@Test
@DisplayName("IncTest")
void incTest() {
Program tast = MockGenerator.getIncTestTast();
var bc = Compiler.getFactory().getProgramGenerator().generateBytecode(tast);
ReflectLoader loader = new ReflectLoader(bc);
Class<?> c = loader.findClass("IncTest");
Object o = null;
try {
o = c.getDeclaredConstructor().newInstance();
var foo = loader.getMethod("IncTest", "foo");
var bar = loader.getMethod("IncTest", "bar");
foo.invoke(o);
bar.invoke(o);
System.setOut(new PrintStream(outContent));
foo.invoke(o);
var expected = new String("0123456789").replaceAll("\\p{C}", "");
var actual = new String(outContent.toByteArray()).replaceAll("\\p{C}", "");
outContent.reset();
assertEquals(expected, actual);
bar.invoke(o);
actual = new String(outContent.toByteArray()).replaceAll("\\p{C}", "");
assertEquals(expected, actual);
System.setOut(originalOut);
} catch (Exception e) {
fail(e.getMessage());
}
}
@Test
@DisplayName("DecTest")
void decTest() {
Program tast = MockGenerator.getDecTestTast();
var bc = Compiler.getFactory().getProgramGenerator().generateBytecode(tast);
ReflectLoader loader = new ReflectLoader(bc);
Class<?> c = loader.findClass("DecTest");
Object o = null;
try {
o = c.getDeclaredConstructor().newInstance();
var foo = loader.getMethod("DecTest", "foo");
var bar = loader.getMethod("DecTest", "bar");
foo.invoke(o);
bar.invoke(o);
System.setOut(new PrintStream(outContent));
foo.invoke(o);
var expected = new String("10987654321").replaceAll("\\p{C}", "");
var actual = new String(outContent.toByteArray()).replaceAll("\\p{C}", "");
outContent.reset();
assertEquals(expected, actual);
bar.invoke(o);
actual = new String(outContent.toByteArray()).replaceAll("\\p{C}", "");
assertEquals(expected, actual);
System.setOut(originalOut);
} catch (Exception e) {
fail(e.getMessage());
}
}
}

View File

@ -1,965 +0,0 @@
package Helper;
import common.AccessModifier;
import common.BaseType;
import common.Operator;
import common.Primitives;
import common.PrintableVector;
import common.ReferenceType;
import syntaxtree.expressions.Binary;
import syntaxtree.expressions.BoolExpr;
import syntaxtree.expressions.CharExpr;
import syntaxtree.expressions.IExpression;
import syntaxtree.expressions.InstVar;
import syntaxtree.expressions.IntegerExpr;
import syntaxtree.expressions.LocalOrFieldVar;
import syntaxtree.expressions.Null;
import syntaxtree.expressions.StringExpr;
import syntaxtree.expressions.This;
import syntaxtree.statementexpression.Assign;
import syntaxtree.statementexpression.CrementStmtExpr;
import syntaxtree.statementexpression.MethodCall;
import syntaxtree.statementexpression.NewDecl;
import syntaxtree.statements.Block;
import syntaxtree.statements.ForStmt;
import syntaxtree.statements.IStatement;
import syntaxtree.statements.LocalVarDecl;
import syntaxtree.statements.ReturnStmt;
import syntaxtree.structure.ClassDecl;
import syntaxtree.structure.ConstructorDecl;
import syntaxtree.structure.FieldDecl;
import syntaxtree.structure.MainMethodDecl;
import syntaxtree.structure.MethodDecl;
import syntaxtree.structure.MethodParameter;
import syntaxtree.structure.Program;
public abstract class MockGenerator {
/**
* @param className
* @return Program
*/
public static Program getEmptyProgram(String className) {
PrintableVector<ClassDecl> classes = new PrintableVector<>();
classes.add(getEmptyClass(className));
return new Program(classes);
}
/**
* @param id
* @return ClassDecl
*/
public static ClassDecl getEmptyClass(String id) {
return new ClassDecl(id, new PrintableVector<>(), new PrintableVector<>(), new PrintableVector<>());
}
/**
* @param expressions
* @return Block
*/
public static Block getBlock(IStatement... expressions) {
PrintableVector<IStatement> expressionsVector = new PrintableVector<>();
for (IStatement expression : expressions) {
expressionsVector.add(expression);
}
return new Block(expressionsVector);
}
/**
* @return Block
*/
public static Block getEmptyBlock() {
return new Block();
}
/**
* @param expressions
* @return PrintableVector<IExpression>
*/
public static PrintableVector<IExpression> getArguments(IExpression... expressions) {
PrintableVector<IExpression> arguments = new PrintableVector<>();
for (IExpression expression : expressions) {
arguments.add(expression);
}
return arguments;
}
/**
* @param constructors
* @return PrintableVector<ConstructorDecl>
*/
public static PrintableVector<ConstructorDecl> getConstructors(ConstructorDecl... constructors) {
PrintableVector<ConstructorDecl> cons = new PrintableVector<>();
if (constructors.length == 0)
cons.add(new ConstructorDecl());
for (ConstructorDecl constructor : constructors) {
cons.add(constructor);
}
return cons;
}
/**
* @return PrintableVector<MethodParameter>
*/
public static PrintableVector<MethodParameter> getEmptyParameters() {
return new PrintableVector<>();
}
/**
* @param parameters
* @return PrintableVector<MethodParameter>
*/
public static PrintableVector<MethodParameter> getParameters(MethodParameter... parameters) {
PrintableVector<MethodParameter> parametersVector = new PrintableVector<>();
for (MethodParameter parameter : parameters) {
parametersVector.add(parameter);
}
return parametersVector;
}
/**
* @return Program
*/
public static Program getClassFieldsTast() {
return getClassFieldsAst();
}
/**
* @return Program
*/
public static Program getClassFieldsAst() {
Program expectedAst = getEmptyProgram("ClassFields");
expectedAst.getClasses().firstElement().getConstructorDeclarations().add(new ConstructorDecl());
FieldDecl privateField = new FieldDecl("privateAccess", AccessModifier.PRIVATE);
privateField.setType(new BaseType(Primitives.INT));
FieldDecl publicField = new FieldDecl("publicAccess", AccessModifier.PUBLIC);
publicField.setType(new BaseType(Primitives.INT));
FieldDecl protectedField = new FieldDecl("protectedAccess", AccessModifier.PROTECTED);
protectedField.setType(new BaseType(Primitives.INT));
PrintableVector<FieldDecl> fields = expectedAst.getClasses().firstElement().getFieldDelcarations();
fields.add(privateField);
fields.add(publicField);
fields.add(protectedField);
return expectedAst;
}
/**
* @return Program
*/
public static Program getAutoClassFieldAst() {
Program expectedAst = getEmptyProgram("AutoAccessModifierField");
FieldDecl autoField = new FieldDecl(new BaseType(Primitives.INT), "autoAccess");
expectedAst.getClasses().firstElement().getConstructorDeclarations().add(new ConstructorDecl());
PrintableVector<FieldDecl> fields = expectedAst.getClasses().firstElement().getFieldDelcarations();
fields.add(autoField);
return expectedAst;
}
/**
* @return Program
*/
public static Program getAutoClassFieldTast() {
return getAutoClassFieldAst();
}
/**
* @return Program
*/
public static Program getConstructorParameterTast() {
return getConstructorParameterAst();
}
/**
* @return Program
*/
public static Program getConstructorParameterAst() {
Program expectedAst = getEmptyProgram("ConstructorParams");
ClassDecl classDecl = expectedAst.getClasses().firstElement();
MethodParameter parameter = new MethodParameter(Primitives.INT, "i");
PrintableVector<MethodParameter> parameters = new PrintableVector<>();
parameters.add(parameter);
classDecl.getConstructorDeclarations()
.add(new ConstructorDecl(AccessModifier.PUBLIC, parameters, getEmptyBlock()));
return expectedAst;
}
/**
* @return Program
*/
public static Program getConstructorThisDotAst() {
Program expectedAst = getEmptyProgram("ConstructorThisDot");
FieldDecl i = new FieldDecl("i", AccessModifier.PUBLIC);
i.setType(new BaseType(Primitives.INT));
PrintableVector<FieldDecl> fields = expectedAst.getClasses().firstElement().getFieldDelcarations();
fields.add(i);
ClassDecl classDecl = expectedAst.getClasses().firstElement();
Block block = getEmptyBlock();
Assign assign = new Assign(new InstVar("i", new This()), new IntegerExpr(5));
block.getStatements().add(assign);
classDecl.getConstructorDeclarations()
.add(new ConstructorDecl(AccessModifier.PUBLIC, getParameters(), block));
System.out.println(classDecl);
return expectedAst;
}
/**
* @return Program
*/
public static Program getConstructorThisDotTast() {
Program expectedTast = getEmptyProgram("ConstructorThisDot");
FieldDecl i = new FieldDecl("i", AccessModifier.PUBLIC);
i.setType(new BaseType(Primitives.INT));
PrintableVector<FieldDecl> fields = expectedTast.getClasses().firstElement().getFieldDelcarations();
fields.add(i);
ClassDecl classDecl = expectedTast.getClasses().firstElement();
Block block = getEmptyBlock();
var thisi = new InstVar("i", new This("ConstructorThisDot"));
thisi.setType(Primitives.INT);
Assign assign = new Assign(thisi, new IntegerExpr(5));
assign.setType(Primitives.INT);
block.getStatements().add(assign);
classDecl.getConstructorDeclarations()
.add(new ConstructorDecl(AccessModifier.PUBLIC, getEmptyParameters(), block));
return expectedTast;
}
/**
* @return Program
*/
public static Program getVoidMethodAst() {
Program expectedAst = getEmptyProgram("VoidMethod");
ClassDecl classDecl = expectedAst.getClasses().firstElement();
expectedAst.getClasses().firstElement().getConstructorDeclarations().add(new ConstructorDecl());
PrintableVector<MethodDecl> methods = classDecl.getMethodDeclarations();
MethodDecl foo = new MethodDecl(new BaseType(Primitives.VOID), "foo", getEmptyParameters(),
getEmptyBlock());
methods.add(foo);
return expectedAst;
}
/**
* @return Program
*/
public static Program getVoidMethodTast() {
return getVoidMethodAst();
}
/**
* @return Program
*/
public static Program getRealMethodAst() {
Program expectedAst = getEmptyProgram("RealMethod");
ClassDecl classDecl = expectedAst.getClasses().firstElement();
Block block = getEmptyBlock();
ReturnStmt returnStmt = new ReturnStmt(new LocalOrFieldVar("i"));
block.getStatements().add(returnStmt);
var parameters = getEmptyParameters();
parameters.add(new MethodParameter(Primitives.INT, "i"));
PrintableVector<MethodDecl> methods = classDecl.getMethodDeclarations();
MethodDecl foo = new MethodDecl(new BaseType(Primitives.INT), "foo", parameters, block);
methods.add(foo);
return expectedAst;
}
/**
* @return Program
*/
public static Program getRealConstructorAst() {
Program expectedAst = getEmptyProgram("RealConstructor");
ClassDecl classDecl = expectedAst.getClasses().firstElement();
FieldDecl i = new FieldDecl(AccessModifier.PRIVATE, new BaseType(Primitives.INT), "i");
classDecl.getFieldDelcarations().add(i);
Assign assignStmt = new Assign(new InstVar(new This(), "i"), new LocalOrFieldVar("i"));
Block block = getBlock(assignStmt);
var parameters = getParameters(new MethodParameter(Primitives.INT, "i"));
PrintableVector<ConstructorDecl> constructors = classDecl.getConstructorDeclarations();
ConstructorDecl constructor = new ConstructorDecl(AccessModifier.PUBLIC, parameters, block);
constructors.add(constructor);
return expectedAst;
}
/**
* @return Program
*/
public static Program getRealConstructorTast() {
String className = "RealConstructor";
Program expectedTast = getEmptyProgram(className);
ClassDecl classDecl = expectedTast.getClasses().firstElement();
FieldDecl i = new FieldDecl(AccessModifier.PRIVATE, new BaseType(Primitives.INT), "i");
classDecl.getFieldDelcarations().add(i);
Assign assignStmt = new Assign(new InstVar(new BaseType(Primitives.INT), new This(
className), "i"), new LocalOrFieldVar(new BaseType(Primitives.INT), "i"));
assignStmt.setType(new BaseType(Primitives.INT));
Block block = getBlock(assignStmt);
var parameters = getParameters(new MethodParameter(Primitives.INT, "i"));
PrintableVector<ConstructorDecl> constructors = classDecl.getConstructorDeclarations();
ConstructorDecl constructor = new ConstructorDecl(AccessModifier.PUBLIC, parameters, block);
constructors.add(constructor);
return expectedTast;
}
/**
* @return Program
*/
public static Program getMethodCallAst() {
Program expectedAst = getEmptyProgram("MethodCall");
ClassDecl classDecl = expectedAst.getClasses().firstElement();
var fields = classDecl.getFieldDelcarations();
fields.add(new FieldDecl(new BaseType(Primitives.INT), "i"));
PrintableVector<ConstructorDecl> constructors = classDecl.getConstructorDeclarations();
Block block = getBlock(
new Assign(new InstVar(new This(), "i"),
new MethodCall(new This(), "foo", getArguments())));
constructors.add(new ConstructorDecl(AccessModifier.PUBLIC, getParameters(), block));
Block fooBlock = getBlock(new ReturnStmt(new IntegerExpr(1)));
PrintableVector<MethodDecl> methods = classDecl.getMethodDeclarations();
methods.add(new MethodDecl(new BaseType(Primitives.INT), "foo", getEmptyParameters(), fooBlock));
return expectedAst;
}
/**
* @return Program
*/
public static Program getMethodCallTast() {
Program expectedTast = getEmptyProgram("MethodCall");
ClassDecl classDecl = expectedTast.getClasses().firstElement();
var fields = classDecl.getFieldDelcarations();
fields.add(new FieldDecl(new BaseType(Primitives.INT), "i"));
PrintableVector<ConstructorDecl> constructors = classDecl.getConstructorDeclarations();
Block block = getBlock(
new Assign(new BaseType(
Primitives.INT),
new InstVar(new BaseType(Primitives.INT), new This("MethodCall"), "i"),
new MethodCall(new BaseType(Primitives.INT), new This("MethodCall"),
"foo", getArguments())));
constructors.add(new ConstructorDecl(AccessModifier.PUBLIC, getParameters(), block));
Block fooBlock = getBlock(new ReturnStmt(new BaseType(Primitives.INT), new IntegerExpr(1)));
fooBlock.setType(Primitives.INT);
PrintableVector<MethodDecl> methods = classDecl.getMethodDeclarations();
methods.add(new MethodDecl(new BaseType(Primitives.INT), "foo", getEmptyParameters(), fooBlock));
return expectedTast;
}
/**
* @return Program
*/
public static Program getMethodCallWithParameterAst() {
Program expectedAst = getEmptyProgram("MethodCallParams");
ClassDecl classDecl = expectedAst.getClasses().firstElement();
var fields = classDecl.getFieldDelcarations();
fields.add(new FieldDecl(new BaseType(Primitives.INT), "i"));
PrintableVector<ConstructorDecl> constructors = classDecl.getConstructorDeclarations();
Block block = getBlock(
new Assign(new InstVar(new This(), "i"),
new MethodCall(new This(), "foo",
getArguments(new LocalOrFieldVar("i")))));
constructors.add(new ConstructorDecl(AccessModifier.PUBLIC,
getParameters(new MethodParameter(Primitives.INT, "i")), block));
Block fooBlock = getBlock(new ReturnStmt(new LocalOrFieldVar("i")));
PrintableVector<MethodDecl> methods = classDecl.getMethodDeclarations();
methods.add(new MethodDecl(new BaseType(Primitives.INT), "foo",
getParameters(new MethodParameter(Primitives.INT, "i")), fooBlock));
return expectedAst;
}
/**
* @return Program
*/
public static Program getCharArgumentAst() {
Program expectedAst = getEmptyProgram("CharArgument");
ClassDecl classDecl = expectedAst.getClasses().firstElement();
var fields = classDecl.getFieldDelcarations();
fields.add(new FieldDecl(new BaseType(Primitives.CHAR), "c"));
PrintableVector<ConstructorDecl> constructors = classDecl.getConstructorDeclarations();
Block block = getBlock(
new Assign(new InstVar(new This(), "c"),
new MethodCall(new This(), "foo", getArguments(new CharExpr('a')))));
constructors.add(new ConstructorDecl(AccessModifier.PUBLIC,
getParameters(), block));
Block fooBlock = getBlock(new ReturnStmt(new LocalOrFieldVar("c")));
PrintableVector<MethodDecl> methods = classDecl.getMethodDeclarations();
methods.add(new MethodDecl(new BaseType(Primitives.CHAR), "foo",
getParameters(new MethodParameter(Primitives.CHAR, "c")), fooBlock));
return expectedAst;
}
/**
* @return Program
*/
public static Program getGetterFunctionAst() {
Program expectedAst = getEmptyProgram("GetterFunction");
ClassDecl classDecl = expectedAst.getClasses().firstElement();
FieldDecl i = new FieldDecl(AccessModifier.PRIVATE, new BaseType(Primitives.INT), "i");
classDecl.getFieldDelcarations().add(i);
Assign assignStmt = new Assign(new InstVar(new This(), "i"), new LocalOrFieldVar("i"));
Block block = getBlock(assignStmt);
var parameters = getParameters(new MethodParameter(Primitives.INT, "i"));
PrintableVector<ConstructorDecl> constructors = classDecl.getConstructorDeclarations();
ConstructorDecl constructor = new ConstructorDecl(AccessModifier.PUBLIC, parameters, block);
constructors.add(constructor);
var getI = new MethodDecl(AccessModifier.PUBLIC, new BaseType(Primitives.INT), "getI", getParameters(),
getBlock(new ReturnStmt(new InstVar(new This(), "i"))));
classDecl.getMethodDeclarations().add(getI);
return expectedAst;
}
public static Program getExplicitNullAssignAst() {
Program expectedAst = getEmptyProgram("ExplicitNullAssign");
ClassDecl classDecl = expectedAst.getClasses().firstElement();
FieldDecl i = new FieldDecl(AccessModifier.PACKAGE_PRIVATE, new ReferenceType("ExplicitNullAssign"),
"e");
classDecl.getFieldDelcarations().add(i);
var test = new MethodDecl(AccessModifier.PACKAGE_PRIVATE, new BaseType(Primitives.VOID), "test",
getParameters(),
getBlock(new Assign(new LocalOrFieldVar("e"), new Null())));
classDecl.getMethodDeclarations().add(test);
classDecl.getConstructorDeclarations().add(new ConstructorDecl());
return expectedAst;
}
public static Program getSelfReferenceAst() {
Program expectedAst = getEmptyProgram("SelfReference");
ClassDecl classDecl = expectedAst.getClasses().firstElement();
FieldDecl i = new FieldDecl(AccessModifier.PACKAGE_PRIVATE, new ReferenceType("SelfReference"),
"selfRef");
classDecl.getFieldDelcarations().add(i);
var foo = new MethodDecl(AccessModifier.PACKAGE_PRIVATE, new BaseType(Primitives.INT), "foo",
getParameters(),
getBlock(new ReturnStmt(new MethodCall(new This(), "baz", getArguments()))));
var baz = new MethodDecl(AccessModifier.PACKAGE_PRIVATE, new BaseType(Primitives.INT), "baz",
getParameters(),
getBlock(new ReturnStmt(new IntegerExpr(10))));
var bar = new MethodDecl(AccessModifier.PACKAGE_PRIVATE, new BaseType(Primitives.INT), "bar",
getParameters(),
getBlock(
new LocalVarDecl(new ReferenceType("SelfReference"), "self",
new NewDecl("SelfReference", getArguments())),
new ReturnStmt(new MethodCall(
new InstVar(new LocalOrFieldVar("self"), "selfRef"),
"foo",
getArguments()))));
classDecl.getMethodDeclarations().add(foo);
classDecl.getMethodDeclarations().add(baz);
classDecl.getMethodDeclarations().add(bar);
classDecl.getConstructorDeclarations().add(new ConstructorDecl());
return expectedAst;
}
public static Program getSelfReferenceTast() {
Program expectedAst = getEmptyProgram("SelfReference");
ClassDecl classDecl = expectedAst.getClasses().firstElement();
FieldDecl i = new FieldDecl(AccessModifier.PACKAGE_PRIVATE, new ReferenceType("SelfReference"),
"selfRef");
classDecl.getFieldDelcarations().add(i);
Block fooBlock = getBlock(new ReturnStmt(new BaseType(Primitives.INT),
new MethodCall(new BaseType(Primitives.INT), new This("SelfReference"), "baz",
getArguments())));
fooBlock.setType(new BaseType(Primitives.INT));
Block bazBlock = getBlock(new ReturnStmt(new BaseType(Primitives.INT), new IntegerExpr(10)));
bazBlock.setType(new BaseType(Primitives.INT));
Block barBlock = getBlock(
new LocalVarDecl(new ReferenceType("SelfReference"), "self",
new NewDecl("SelfReference", getArguments())),
new ReturnStmt(new BaseType(Primitives.INT),
new MethodCall(new BaseType(Primitives.INT),
new InstVar(new ReferenceType("SelfReference"),
new LocalOrFieldVar(new ReferenceType(
"SelfReference"),
"self"),
"selfRef"),
"foo",
getArguments())));
barBlock.setType(new BaseType(Primitives.INT));
var foo = new MethodDecl(AccessModifier.PACKAGE_PRIVATE, new BaseType(Primitives.INT), "foo",
getParameters(), fooBlock);
var baz = new MethodDecl(AccessModifier.PACKAGE_PRIVATE, new BaseType(Primitives.INT), "baz",
getParameters(), bazBlock);
var bar = new MethodDecl(AccessModifier.PACKAGE_PRIVATE, new BaseType(Primitives.INT), "bar",
getParameters(),
barBlock);
classDecl.getMethodDeclarations().add(foo);
classDecl.getMethodDeclarations().add(baz);
classDecl.getMethodDeclarations().add(bar);
classDecl.getConstructorDeclarations().add(new ConstructorDecl());
return expectedAst;
}
public static Program getThisDotMethodCallAst() {
Program expectedAst = getEmptyProgram("ThisDotMethodCall");
ClassDecl classDecl = expectedAst.getClasses().firstElement();
var fields = classDecl.getFieldDelcarations();
fields.add(new FieldDecl(new BaseType(Primitives.INT), "i"));
PrintableVector<ConstructorDecl> constructors = classDecl.getConstructorDeclarations();
Block block = getBlock(
new Assign(new InstVar(new This(), "i"),
new MethodCall(new This(), "foo", getArguments())));
constructors.add(new ConstructorDecl(AccessModifier.PUBLIC, getParameters(), block));
Block fooBlock = getBlock(new ReturnStmt(new IntegerExpr(1)));
PrintableVector<MethodDecl> methods = classDecl.getMethodDeclarations();
methods.add(new MethodDecl(new BaseType(Primitives.INT), "foo", getEmptyParameters(), fooBlock));
return expectedAst;
}
public static Program getValueAdapterTestAst() {
Program expectedAst = getEmptyProgram("ValueAdapterTests");
Block readsTrueBlock = getBlock(new ReturnStmt(new BoolExpr(true)));
Block readsFalseBlock = getBlock(new ReturnStmt(new BoolExpr(false)));
Block readsTrueAndFalseBlock = getBlock(new ReturnStmt(new Binary(new BoolExpr(true),
Operator.AND, new BoolExpr(false))));
Block readsIntBlock = getBlock(new ReturnStmt(new IntegerExpr(1)));
Block readsIntAndIntBlock = getBlock(new ReturnStmt(new Binary(new IntegerExpr(1),
Operator.PLUS, new IntegerExpr(1))));
Block readsCharBlock = getBlock(new ReturnStmt(new CharExpr('a')));
MethodDecl readsTrue = new MethodDecl(new BaseType(Primitives.BOOL), "readsTrue", getEmptyParameters(),
readsTrueBlock);
MethodDecl readsFalse = new MethodDecl(new BaseType(Primitives.BOOL), "readsFalse",
getEmptyParameters(),
readsFalseBlock);
MethodDecl readsTrueAndFalse = new MethodDecl(new BaseType(Primitives.BOOL), "readsTrueAndFalse",
getEmptyParameters(), readsTrueAndFalseBlock);
MethodDecl readsInt = new MethodDecl(new BaseType(Primitives.INT), "readsInt", getEmptyParameters(),
readsIntBlock);
MethodDecl readsIntAndInt = new MethodDecl(new BaseType(Primitives.INT), "readsIntAndInt",
getEmptyParameters(),
readsIntAndIntBlock);
MethodDecl readsChar = new MethodDecl(new BaseType(Primitives.CHAR), "readsChar", getEmptyParameters(),
readsCharBlock);
var methods = expectedAst.getClasses().firstElement().getMethodDeclarations();
methods.add(readsTrue);
methods.add(readsFalse);
methods.add(readsTrueAndFalse);
methods.add(readsInt);
methods.add(readsIntAndInt);
methods.add(readsChar);
expectedAst.getClasses().firstElement().getConstructorDeclarations().add(new ConstructorDecl());
return expectedAst;
}
public static Program getSystemOutPrintlnTast() {
Program expectedAst = getEmptyProgram("SystemOutPrintln");
var iv = new InstVar(new ReferenceType("java/io/PrintStream"),
new LocalOrFieldVar(new ReferenceType("java/lang/System"), "System"), "out");
iv.setAccessModifier(AccessModifier.PUBLIC_STATIC);
Block block = getBlock(
new MethodCall(new BaseType(Primitives.VOID),
iv,
"println",
getArguments(new IntegerExpr(1))));
var method = new MethodDecl(new BaseType(Primitives.VOID), "foo", getEmptyParameters(), block);
expectedAst.getClasses().firstElement().getMethodDeclarations().add(method);
expectedAst.getClasses().firstElement().getConstructorDeclarations().add(new ConstructorDecl());
return expectedAst;
}
public static Program getSystemOutPrintlnAst() {
Program expectedAst = getEmptyProgram("SystemOutPrintln");
Block block = getBlock(
new MethodCall(new InstVar(new LocalOrFieldVar("System"), "out"), "println",
getArguments(new IntegerExpr(1))));
var method = new MethodDecl(new BaseType(Primitives.VOID), "foo", getEmptyParameters(), block);
expectedAst.getClasses().firstElement().getMethodDeclarations().add(method);
expectedAst.getClasses().firstElement().getConstructorDeclarations().add(new ConstructorDecl());
return expectedAst;
}
public static Program getSystemOutPrintStringAst() {
Program expectedAst = getEmptyProgram("SystemOutPrintlnString");
Block block = getBlock(
new MethodCall(new InstVar(new LocalOrFieldVar("System"), "out"), "println",
getArguments(new StringExpr("Das ist ein String"))));
var method = new MethodDecl(new BaseType(Primitives.VOID), "foo", getEmptyParameters(), block);
expectedAst.getClasses().firstElement().getMethodDeclarations().add(method);
expectedAst.getClasses().firstElement().getConstructorDeclarations().add(new ConstructorDecl());
return expectedAst;
}
public static Program getSystemOutPrintStringTast() {
Program expectedAst = getEmptyProgram("SystemOutPrintlnString");
var iv = new InstVar(new ReferenceType("java/io/PrintStream"),
new LocalOrFieldVar(new ReferenceType("java/lang/System"), "System"), "out");
iv.setAccessModifier(AccessModifier.PUBLIC_STATIC);
Block block = getBlock(
new MethodCall(new BaseType(Primitives.VOID),
iv,
"println",
getArguments(new StringExpr("Das ist ein String"))));
var method = new MethodDecl(new BaseType(Primitives.VOID), "foo", getEmptyParameters(), block);
expectedAst.getClasses().firstElement().getMethodDeclarations().add(method);
expectedAst.getClasses().firstElement().getConstructorDeclarations().add(new ConstructorDecl());
return expectedAst;
}
public static Program getMainMethodTestAst() {
Program expectedAst = getEmptyProgram("MainMethodTest");
Block block = getBlock(
new MethodCall(new InstVar(new LocalOrFieldVar("System"), "out"), "println",
getArguments(new StringExpr("maintest"))));
var method = new MainMethodDecl(block);
expectedAst.getClasses().firstElement().getMethodDeclarations().add(method);
expectedAst.getClasses().firstElement().getConstructorDeclarations().add(new ConstructorDecl());
return expectedAst;
}
public static Program getMainMethodTestTast() {
Program expectedAst = getEmptyProgram("MainMethodTest");
var iv = new InstVar(new ReferenceType("java/io/PrintStream"),
new LocalOrFieldVar(new ReferenceType("java/lang/System"), "System"), "out");
iv.setAccessModifier(AccessModifier.PUBLIC_STATIC);
Block block = getBlock(
new MethodCall(new BaseType(Primitives.VOID),
iv,
"println",
getArguments(new StringExpr("maintest"))));
var method = new MainMethodDecl(block);
expectedAst.getClasses().firstElement().getMethodDeclarations().add(method);
expectedAst.getClasses().firstElement().getConstructorDeclarations().add(new ConstructorDecl());
return expectedAst;
}
public static Program getForTestAst() {
Program expectedAst = getEmptyProgram("ForTest");
Block forBlock = getBlock(new MethodCall(new InstVar(new LocalOrFieldVar("System"), "out"), "println",
getArguments(new LocalOrFieldVar("i"))));
Block block = getBlock(
new ForStmt(new LocalVarDecl(new BaseType(Primitives.INT), "i", new IntegerExpr(0)),
new Binary(new LocalOrFieldVar("i"), new IntegerExpr(10),
Operator.LESS),
new Assign(new LocalOrFieldVar("i"),
new Binary(new LocalOrFieldVar("i"), new IntegerExpr(1),
Operator.PLUS)),
forBlock));
var method = new MethodDecl(new BaseType(Primitives.VOID), "foo", getEmptyParameters(), block);
expectedAst.getClasses().firstElement().getMethodDeclarations().add(method);
expectedAst.getClasses().firstElement().getConstructorDeclarations().add(new ConstructorDecl());
return expectedAst;
}
public static Program getForTestTast() {
Program expectedAst = getEmptyProgram("ForTest");
var iv = new InstVar(new ReferenceType("java/io/PrintStream"),
new LocalOrFieldVar(new ReferenceType("java/lang/System"), "System"), "out");
iv.setAccessModifier(AccessModifier.PUBLIC_STATIC);
Block forBlock = getBlock(new MethodCall(new BaseType(Primitives.VOID),
iv,
"println",
getArguments(new LocalOrFieldVar(new BaseType(Primitives.INT), "i"))));
Block block = getBlock(
new ForStmt(new LocalVarDecl(new BaseType(Primitives.INT), "i", new IntegerExpr(0)),
new Binary(new BaseType(Primitives.BOOL),
new LocalOrFieldVar(new BaseType(Primitives.INT), "i"),
new IntegerExpr(10),
Operator.LESS),
new Assign(new BaseType(Primitives.INT),
new LocalOrFieldVar(new BaseType(Primitives.INT), "i"),
new Binary(new BaseType(Primitives.INT),
new LocalOrFieldVar(new BaseType(
Primitives.INT), "i"),
new IntegerExpr(1),
Operator.PLUS)),
forBlock));
var method = new MethodDecl(new BaseType(Primitives.VOID), "foo", getEmptyParameters(), block);
expectedAst.getClasses().firstElement().getMethodDeclarations().add(method);
expectedAst.getClasses().firstElement().getConstructorDeclarations().add(new ConstructorDecl());
return expectedAst;
}
public static Program getIncTestAst() {
Program expectedAst = getEmptyProgram("IncTest");
Block forBlock = getBlock(new MethodCall(new InstVar(new LocalOrFieldVar("System"), "out"), "println",
getArguments(new LocalOrFieldVar("i"))));
Block blockfoo = getBlock(
new ForStmt(new LocalVarDecl(new BaseType(Primitives.INT), "i", new IntegerExpr(0)),
new Binary(new LocalOrFieldVar("i"), new IntegerExpr(10),
Operator.LESS),
new CrementStmtExpr(new LocalOrFieldVar("i"), Operator.INCSUF),
forBlock));
Block blockbar = getBlock(
new ForStmt(new LocalVarDecl(new BaseType(Primitives.INT), "i", new IntegerExpr(0)),
new Binary(new LocalOrFieldVar("i"), new IntegerExpr(10),
Operator.LESS),
new CrementStmtExpr(new LocalOrFieldVar("i"), Operator.INCPRE),
forBlock));
var foo = new MethodDecl(new BaseType(Primitives.VOID), "foo", getEmptyParameters(), blockfoo);
var bar = new MethodDecl(new BaseType(Primitives.VOID), "bar", getEmptyParameters(), blockbar);
expectedAst.getClasses().firstElement().getMethodDeclarations().add(foo);
expectedAst.getClasses().firstElement().getMethodDeclarations().add(bar);
expectedAst.getClasses().firstElement().getConstructorDeclarations().add(new ConstructorDecl());
return expectedAst;
}
public static Program getIncTestTast() {
Program expectedAst = getEmptyProgram("IncTest");
var iv = new InstVar(new ReferenceType("java/io/PrintStream"),
new LocalOrFieldVar(new ReferenceType("java/lang/System"), "System"), "out");
iv.setAccessModifier(AccessModifier.PUBLIC_STATIC);
Block forBlock = getBlock(new MethodCall(new BaseType(Primitives.VOID),
iv,
"println",
getArguments(new LocalOrFieldVar(new BaseType(Primitives.INT), "i"))));
Block fooblock = getBlock(
new ForStmt(new LocalVarDecl(new BaseType(Primitives.INT), "i", new IntegerExpr(0)),
new Binary(new BaseType(Primitives.BOOL),
new LocalOrFieldVar(new BaseType(Primitives.INT), "i"),
new IntegerExpr(10),
Operator.LESS),
new CrementStmtExpr(new BaseType(Primitives.INT),
new LocalOrFieldVar(new BaseType(Primitives.INT), "i"),
Operator.INCSUF),
forBlock));
Block barblock = getBlock(
new ForStmt(new LocalVarDecl(new BaseType(Primitives.INT), "i", new IntegerExpr(0)),
new Binary(new BaseType(Primitives.BOOL),
new LocalOrFieldVar(new BaseType(Primitives.INT), "i"),
new IntegerExpr(10),
Operator.LESS),
new CrementStmtExpr(new BaseType(Primitives.INT),
new LocalOrFieldVar(new BaseType(Primitives.INT), "i"),
Operator.INCPRE),
forBlock));
var foo = new MethodDecl(new BaseType(Primitives.VOID), "foo", getEmptyParameters(), fooblock);
var bar = new MethodDecl(new BaseType(Primitives.VOID), "bar", getEmptyParameters(), barblock);
expectedAst.getClasses().firstElement().getMethodDeclarations().add(foo);
expectedAst.getClasses().firstElement().getMethodDeclarations().add(bar);
expectedAst.getClasses().firstElement().getConstructorDeclarations().add(new ConstructorDecl());
return expectedAst;
}
public static Program getDecTestAst() {
Program expectedAst = getEmptyProgram("DecTest");
Block forBlock = getBlock(new MethodCall(new InstVar(new LocalOrFieldVar("System"), "out"), "println",
getArguments(new LocalOrFieldVar("i"))));
Block blockfoo = getBlock(
new ForStmt(new LocalVarDecl(new BaseType(Primitives.INT), "i", new IntegerExpr(10)),
new Binary(new LocalOrFieldVar("i"), new IntegerExpr(0),
Operator.GREATER),
new CrementStmtExpr(new LocalOrFieldVar("i"), Operator.DECSUF),
forBlock));
Block blockbar = getBlock(
new ForStmt(new LocalVarDecl(new BaseType(Primitives.INT), "i", new IntegerExpr(10)),
new Binary(new LocalOrFieldVar("i"), new IntegerExpr(0),
Operator.GREATER),
new CrementStmtExpr(new LocalOrFieldVar("i"), Operator.DECPRE),
forBlock));
var foo = new MethodDecl(new BaseType(Primitives.VOID), "foo", getEmptyParameters(), blockfoo);
var bar = new MethodDecl(new BaseType(Primitives.VOID), "bar", getEmptyParameters(), blockbar);
expectedAst.getClasses().firstElement().getMethodDeclarations().add(foo);
expectedAst.getClasses().firstElement().getMethodDeclarations().add(bar);
expectedAst.getClasses().firstElement().getConstructorDeclarations().add(new ConstructorDecl());
return expectedAst;
}
public static Program getDecTestTast() {
Program expectedAst = getEmptyProgram("DecTest");
var iv = new InstVar(new ReferenceType("java/io/PrintStream"),
new LocalOrFieldVar(new ReferenceType("java/lang/System"), "System"), "out");
iv.setAccessModifier(AccessModifier.PUBLIC_STATIC);
Block forBlock = getBlock(new MethodCall(new BaseType(Primitives.VOID),
iv,
"println",
getArguments(new LocalOrFieldVar(new BaseType(Primitives.INT), "i"))));
Block fooblock = getBlock(
new ForStmt(new LocalVarDecl(new BaseType(Primitives.INT), "i", new IntegerExpr(10)),
new Binary(new BaseType(Primitives.BOOL),
new LocalOrFieldVar(new BaseType(Primitives.INT), "i"),
new IntegerExpr(0),
Operator.GREATER),
new CrementStmtExpr(new BaseType(Primitives.INT),
new LocalOrFieldVar(new BaseType(Primitives.INT), "i"),
Operator.DECSUF),
forBlock));
Block barblock = getBlock(
new ForStmt(new LocalVarDecl(new BaseType(Primitives.INT), "i", new IntegerExpr(10)),
new Binary(new BaseType(Primitives.BOOL),
new LocalOrFieldVar(new BaseType(Primitives.INT), "i"),
new IntegerExpr(0),
Operator.GREATER),
new CrementStmtExpr(new BaseType(Primitives.INT),
new LocalOrFieldVar(new BaseType(Primitives.INT), "i"),
Operator.DECPRE),
forBlock));
var foo = new MethodDecl(new BaseType(Primitives.VOID), "foo", getEmptyParameters(), fooblock);
var bar = new MethodDecl(new BaseType(Primitives.VOID), "bar", getEmptyParameters(), barblock);
expectedAst.getClasses().firstElement().getMethodDeclarations().add(foo);
expectedAst.getClasses().firstElement().getMethodDeclarations().add(bar);
expectedAst.getClasses().firstElement().getConstructorDeclarations().add(new ConstructorDecl());
return expectedAst;
}
}

View File

@ -1,104 +0,0 @@
package Helper;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import common.Compiler;
import syntaxtree.structure.Program;
public class ReflectLoader extends ClassLoader {
private byte[] byteCode;
private Map<String, byte[]> byteCodes;
private Map<String, Class<?>> classes = new HashMap<>();
public ReflectLoader(byte[] byteCode) {
byteCodes = new HashMap<>();
this.byteCode = byteCode;
}
public ReflectLoader(String fileName) {
Program program = Resources.getProgram(fileName);
Program tast = Compiler.getFactory().getTastAdapter().getTast(program);
var bc = Compiler.getFactory().getProgramGenerator().generateBytecode(tast);
this.byteCodes = bc;
}
/**
* @param fileName
* @param className
* @return Class<?>
* @throws Exception
*/
public static Class<?> getClass(String fileName, String className) throws Exception {
ReflectLoader loader = new ReflectLoader(fileName);
return loader.findClass(className);
}
public ReflectLoader(Map<String, byte[]> byteCodes) {
this.byteCodes = byteCodes;
}
/**
* @param name
* @return Class<?>
*/
@Override
public Class<?> findClass(String name) {
if (!byteCodes.containsKey(name)) {
if (byteCode != null) {
byteCodes.put(name, byteCode);
byteCode = null;
} else {
return null;
}
}
if (classes.containsKey(name)) {
return classes.get(name);
} else {
Class<?> clazz = defineClass(name, byteCodes.get(name), 0, byteCodes.get(name).length);
classes.put(name, clazz);
return clazz;
}
}
/**
* @param className
* @param method
* @param parameterTypes
* @return Method
* @throws NoSuchMethodException
*/
public Method getMethod(String className, String method, Class<?>... parameterTypes) throws NoSuchMethodException {
Method method1 = findClass(className).getDeclaredMethod(method, parameterTypes);
method1.setAccessible(true);
return method1;
}
/**
* @param className
* @param field
* @return Field
* @throws NoSuchFieldException
*/
public Field getField(String className, String field) throws NoSuchFieldException {
Field field1 = findClass(className).getDeclaredField(field);
field1.setAccessible(true);
return field1;
}
/**
* @param classname
* @param parameterTyped
* @return Constructor<?>
* @throws NoSuchMethodException
*/
public Constructor<?> getConstructor(String classname, Class<?>... parameterTyped) throws NoSuchMethodException {
Constructor<?> constructor = findClass(classname).getDeclaredConstructor(parameterTyped);
constructor.setAccessible(true);
return constructor;
}
}

View File

@ -1,42 +0,0 @@
package Helper;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.fail;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import common.Compiler;
import syntaxtree.structure.Program;
public class Resources {
/**
* @param fileName
* @return Program
*/
public static Program getProgram(String fileName) {
return Compiler.getFactory().getAstAdapter().getAst(getFileAsStream(fileName));
}
/**
* @param fileName
* @return InputStream
*/
public static InputStream getFileAsStream(String fileName) {
ClassLoader classLoader = Resources.class.getClassLoader();
File file = new File(classLoader.getResource(fileName).getFile());
assertNotNull(file);
try {
return new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
fail();
}
throw new IllegalStateException();
}
}

View File

@ -1,324 +0,0 @@
package TAST;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.io.FileNotFoundException;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import Helper.MockGenerator;
import Helper.Resources;
import common.AccessModifier;
import common.BaseType;
import common.Compiler;
import common.Primitives;
import common.PrintableVector;
import semantic.exceptions.SemanticError;
import syntaxtree.structure.ClassDecl;
import syntaxtree.structure.ConstructorDecl;
import syntaxtree.structure.FieldDecl;
import syntaxtree.structure.Program;
@DisplayName("Typed Abstract Syntax Generation")
public class TestRunner {
/**
* @throws FileNotFoundException
*/
@Test
@DisplayName("EmptyClass")
void emptyClass() throws FileNotFoundException {
ClassDecl emptyClass = new ClassDecl("EmptyClass", new PrintableVector<>(), new PrintableVector<>(),
new PrintableVector<>());
PrintableVector<ClassDecl> classDecls = new PrintableVector<>();
classDecls.add(emptyClass);
var ast = new Program(classDecls);
var tast = ast;
var generatedTast = Compiler.getFactory().getTastAdapter().getTast(ast);
assertEquals(tast, generatedTast);
}
@Test
@DisplayName("ClassFields")
void classFields() {
Program expectedAst = MockGenerator.getEmptyProgram("ClassFields");
FieldDecl autoAccess = new FieldDecl(AccessModifier.PACKAGE_PRIVATE, new BaseType(Primitives.INT),
"autoAccess");
FieldDecl privateField = new FieldDecl(AccessModifier.PRIVATE, new BaseType(Primitives.INT), "private");
FieldDecl publicField = new FieldDecl(AccessModifier.PUBLIC, new BaseType(Primitives.INT), "public");
FieldDecl protectedField = new FieldDecl(AccessModifier.PROTECTED, new BaseType(Primitives.INT), "protected");
PrintableVector<FieldDecl> fields = expectedAst.getClasses().firstElement().getFieldDelcarations();
fields.add(autoAccess);
fields.add(privateField);
fields.add(publicField);
fields.add(protectedField);
var generatedAst = Compiler.getFactory().getTastAdapter().getTast(expectedAst);
assertEquals(expectedAst, generatedAst);
}
@Test
@DisplayName("ClassField without AccessModifier")
void classFieldWithoutAccessModifier() {
Program expectedTast = MockGenerator.getAutoClassFieldTast();
Program generatedTast = Compiler.getFactory().getTastAdapter().getTast(expectedTast);
assertEquals(expectedTast, generatedTast);
}
@Test
@DisplayName("EmptyClassWithConstructor")
void emptyClassWithConstructor() {
PrintableVector<ConstructorDecl> constructors = new PrintableVector<>();
constructors.add(new ConstructorDecl());
ClassDecl classDecl = new ClassDecl("EmptyClassWithConstructor", new PrintableVector<>(), constructors,
new PrintableVector<>());
PrintableVector<ClassDecl> classDecls = new PrintableVector<>();
classDecls.add(classDecl);
var ast = new Program(classDecls);
var generatedTast = Compiler.getFactory().getTastAdapter().getTast(ast);
var tast = ast;
assertEquals(tast, generatedTast);
}
@Test
@DisplayName("Constructor With Parameters")
void constructorWithParameters() {
Program generatedTast = Compiler.getFactory().getTastAdapter()
.getTast(MockGenerator.getConstructorParameterAst());
Program expectedTast = MockGenerator.getConstructorParameterTast();
assertEquals(expectedTast, generatedTast);
}
@Test
@DisplayName("Constructor With this. assign body")
void constructorWithThisAssignBody() {
Program generatedTast = Compiler.getFactory().getTastAdapter()
.getTast(MockGenerator.getConstructorThisDotAst());
Program expectedTast = MockGenerator.getConstructorThisDotTast();
assertEquals(expectedTast, generatedTast);
}
@Test
@DisplayName("VoidMethod")
void voidMethod() {
Program generatedTast = Compiler.getFactory().getTastAdapter().getTast(MockGenerator.getVoidMethodAst());
Program expectedTast = MockGenerator.getVoidMethodTast();
assertEquals(expectedTast, generatedTast);
}
@Test
@DisplayName("RealConstructor")
void realConstructor() {
Program generatedTast = Compiler.getFactory().getTastAdapter().getTast(MockGenerator.getRealConstructorAst());
Program expectedTast = MockGenerator.getRealConstructorTast();
assertEquals(expectedTast, generatedTast);
}
@Test
@DisplayName("MethodCall")
void methodCall() {
Program generatedTast = Compiler.getFactory().getTastAdapter().getTast(MockGenerator.getMethodCallAst());
Program expectedTast = MockGenerator.getMethodCallTast();
assertEquals(expectedTast, generatedTast);
}
@Test
@DisplayName("MultipleFields")
@Tag("expectfail")
void multipleFields() {
Program program = Resources.getProgram("FailTests/MultiFieldDecl.java");
System.err.print(assertThrows(
SemanticError.class,
() -> Compiler.getFactory().getTastAdapter().getTast(program),
"Expected SemanticError to be thrown").getMessage());
}
@Test
@DisplayName("MismatchingReturnType")
@Tag("expectfail")
void mismatchingReturnType() {
Program program = Resources.getProgram("FailTests/MismatchingReturnType.java");
System.err.print(assertThrows(
SemanticError.class,
() -> Compiler.getFactory().getTastAdapter().getTast(program),
"Expected SemanticError to be thrown").getMessage());
}
@Test
@DisplayName("WhileTest")
void whileTest() {
Program program = Resources.getProgram("SimpleTests/WhileTest.java");
Compiler.getFactory().getTastAdapter().getTast(program);
}
@Test
@DisplayName("WhileFailTest")
void whileFailTest() {
Program program = Resources.getProgram("FailTests/WhileBool.java");
System.err.print(assertThrows(
SemanticError.class,
() -> Compiler.getFactory().getTastAdapter().getTast(program),
"Expected SemanticError to be thrown").getMessage());
}
@Test
@DisplayName("ScopeFailTest")
void scopeFailTest() {
Program program = Resources.getProgram("FailTests/ScopeTest.java");
System.err.print(assertThrows(
SemanticError.class,
() -> Compiler.getFactory().getTastAdapter().getTast(program),
"Expected SemanticError to be thrown").getMessage());
}
@Test
@DisplayName("AssignFailTest")
void assignFailTest() {
Program program = Resources.getProgram("FailTests/AssignWrongType.java");
System.err.print(assertThrows(
SemanticError.class,
() -> Compiler.getFactory().getTastAdapter().getTast(program),
"Expected SemanticError to be thrown").getMessage());
}
@Test
@DisplayName("LocalVarDeclaration with wrong init-Type")
void localVarDeclInitFail() {
Program program = Resources.getProgram("FailTests/LocalVarWrongInit.java");
System.err.print(assertThrows(
SemanticError.class,
() -> Compiler.getFactory().getTastAdapter().getTast(program),
"Expected SemanticError to be thrown").getMessage());
}
@Test
@DisplayName("ExplicitNullAssign")
void explicitNullAssign() {
Program program = Resources.getProgram("SimpleTests/ExplicitNullAssign.java");
Compiler.getFactory().getTastAdapter().getTast(program);
}
@Test
@DisplayName("SelfReference")
void selfReference() {
Program generatedTast = Compiler.getFactory().getTastAdapter().getTast(MockGenerator.getSelfReferenceAst());
Program expectedTast = MockGenerator.getSelfReferenceTast();
assertEquals(expectedTast, generatedTast);
}
@Test
@DisplayName("SystemOutPrintln-Test")
void systemOutPrintlnTest() {
Program generatedTast = Compiler.getFactory().getTastAdapter().getTast(MockGenerator.getSystemOutPrintlnAst());
Program expectedTast = MockGenerator.getSystemOutPrintlnTast();
assertEquals(expectedTast, generatedTast);
}
@Test
@DisplayName("FieldAccessTests")
void fieldAccessTests() {
Program program = Resources.getProgram("FailTests/FieldAccessTests.java");
System.err.print(assertThrows(
SemanticError.class,
() -> Compiler.getFactory().getTastAdapter().getTast(program),
"Expected SemanticError to be thrown").getMessage());
}
@Test
@DisplayName("MethodAccessTests")
void methodAccessTests() {
Program program = Resources.getProgram("FailTests/MethodAccessTests.java");
System.err.print(assertThrows(
SemanticError.class,
() -> Compiler.getFactory().getTastAdapter().getTast(program),
"Expected SemanticError to be thrown").getMessage());
}
@Test
@DisplayName("DuplicateMethod")
void duplicateMethod() {
Program program = Resources.getProgram("FailTests/DuplicateMethod.java");
System.err.print(assertThrows(
SemanticError.class,
() -> Compiler.getFactory().getTastAdapter().getTast(program),
"Expected SemanticError to be thrown").getMessage());
}
@Test
@DisplayName("SystemOutPrintln-String-Test")
void systemOutPrintlnStringTest() {
Program generatedTast = Compiler.getFactory().getTastAdapter()
.getTast(MockGenerator.getSystemOutPrintStringAst());
Program expectedTast = MockGenerator.getSystemOutPrintStringTast();
assertEquals(expectedTast, generatedTast);
}
@Test
@DisplayName("MainMethodTest")
void mainMethodTest() {
Program generatedTast = Compiler.getFactory().getTastAdapter().getTast(MockGenerator.getMainMethodTestAst());
Program expectedTast = MockGenerator.getMainMethodTestTast();
assertEquals(expectedTast, generatedTast);
}
@Test
@DisplayName("ForLoopTest")
void forLoopTest() {
Program generatedTast = Compiler.getFactory().getTastAdapter().getTast(MockGenerator.getForTestAst());
Program expectedTast = MockGenerator.getForTestTast();
assertEquals(expectedTast, generatedTast);
}
@Test
@DisplayName("IncTest")
void incTest() {
Program generatedTast = Compiler.getFactory().getTastAdapter().getTast(MockGenerator.getIncTestAst());
Program expectedTast = MockGenerator.getIncTestTast();
assertEquals(expectedTast, generatedTast);
}
@Test
@DisplayName("DecTest")
void decTest() {
Program generatedTast = Compiler.getFactory().getTastAdapter().getTast(MockGenerator.getDecTestAst());
Program expectedTast = MockGenerator.getDecTestTast();
assertEquals(expectedTast, generatedTast);
}
}

View File

@ -0,0 +1,42 @@
package Tokens;
import org.antlr.v4.runtime.*;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertEquals;
public class JavaLexerTest {
public void testFileTokens(String sourcePath, String tokensPath) throws IOException {
String content = new String(Files.readAllBytes(Paths.get(sourcePath)));
JavaLexer lexer = new JavaLexer(CharStreams.fromString(content));
CommonTokenStream tokens = new CommonTokenStream(lexer);
tokens.fill(); // Load all tokens
List<Integer> expectedTokenTypes = loadExpectedTokens(tokensPath);
List<Integer> actualTokenTypes = tokens.getTokens().stream()
.map(Token::getType)
.collect(Collectors.toList());
assertEquals(expectedTokenTypes, actualTokenTypes.subList(0, actualTokenTypes.size()));
}
private List<Integer> loadExpectedTokens(String tokenFilePath) throws IOException {
List<Integer> tokenTypes = new ArrayList<>();
List<String> lines = Files.readAllLines(Paths.get(tokenFilePath));
for (String line : lines) {
int tokenType;
try {
tokenType = JavaLexer.class.getField(line).getInt(null);
} catch (NoSuchFieldException | IllegalAccessException e) {
throw new RuntimeException("Invalid token type in tokens file: " + line, e);
}
tokenTypes.add(tokenType);
}
return tokenTypes;
}
}

View File

@ -1,12 +0,0 @@
package initialTest;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class initialTest {
@Test
public void testSomething() {
//MyClass myClass = new MyClass();
assertEquals(1, 1);
}
}

View File

@ -1,5 +1,3 @@
package FailTests;
class AssignWrongType {
int test() {

View File

@ -0,0 +1,22 @@
Class
Identifier
OpenCurlyBracket
Int
Identifier
OpenRoundBracket
ClosedRoundBracket
OpenCurlyBracket
Int
Identifier
Assign
IntValue
Semicolon
Identifier
Assign
Identifier
Semicolon
Return
Identifier
Semicolon
ClosedCurlyBracket
ClosedCurlyBracket

View File

@ -1,9 +1,7 @@
package FailTests;
class BoolAssignedInt {
void foo() {
boolean bool = 10;
bool myBool = 10;
}
}

View File

@ -0,0 +1,15 @@
Class
Identifier
OpenCurlyBracket
Void
Identifier
OpenRoundBracket
ClosedRoundBracket
OpenCurlyBracket
Boolean
Identifier
Assign
Int
Semicolon
ClosedCurlyBracket
ClosedCurlyBracket

View File

@ -1,5 +1,3 @@
package FailTests;
class DivideByZero {
public static void main(String[] args) {

View File

@ -0,0 +1,14 @@
Class
Identifier
OpenCurlyBracket
MainMethodDecl
OpenCurlyBracket
Int
Identifier
Assign
IntValue
DotOperator
IntValue
Semicolon
ClosedCurlyBracket
ClosedCurlyBracket

View File

@ -1,5 +1,3 @@
package FailTests;
class DuplicateFieldDeclaration {
char i;
int i;

View File

@ -0,0 +1,10 @@
Class
Identifier
OpenCurlyBracket
Char
Identifier
Semicolon
Int
Identifier
Semicolon
ClosedCurlyBracket

View File

@ -1,6 +1,4 @@
package FailTests;
class DuplicateMethod {
Class DuplicateMethod {
public void test() { }

View File

@ -0,0 +1,18 @@
Class
Identifier
OpenCurlyBrackets
AccessModifier
Void
Identifier
OpenRoundBrackets
ClosedRoundBrackets
OpenCurlyBrackets
ClosedCurlyBrackets
AccessModifier
Void
Identifier
OpenRoundBrackets
ClosedRoundBrackets
OpenCurlyBrackets
ClosedCurlyBrackets
ClosedCurlyBrackets

View File

@ -1,11 +0,0 @@
package FailTests;
class FaultyForLoop {
int foo() {
int x;
for (x == true; ;) {
return 4324;
}
}
}

View File

@ -1,5 +1,3 @@
package SimpleTests;
class EmptyClassWithConstructor{
public EmptyClassWithConstructor(){

View File

@ -0,0 +1,10 @@
Class
Identifier
OpenCurlyBracket
AccessModifier
Identifier
OpenRoundBracket
ClosedRoundBracket
OpenCurlyBracket
ClosedCurlyBracket
EOF

View File

@ -1,5 +1,3 @@
package SimpleTests;
class FourClasses {
public int main(int i) {
@ -11,7 +9,7 @@ class FourClasses {
}
class Test {
private int x;
public int x;
public int y;
public Test3 test3;
@ -42,7 +40,7 @@ class Test2 {
class Test3 {
public int x;
private int y;
public int y;
public Test3(int i) {
this.x = i;

View File

@ -0,0 +1,207 @@
Class
Identifier
OpenCurlyBracket
AccessModifier
Int
Identifier
OpenRoundBracket
Int
Identifier
ClosedRoundBracket
OpenCurlyBracket
Identifier
Identifier
Assign
New
Identifier
OpenRoundBracket
Identifier
ClosedRoundBracket
Semicolon
Identifier
Identifier
Assign
New
Identifier
OpenRoundBracket
Identifier
Dot
Identifier
ClosedRoundBracket
Semicolon
Return
Identifier
Dot
Identifier
Dot
Identifier
Dot
Identifier
OpenRoundBracket
ClosedRoundBracket
Semicolon
ClosedCurlyBracket
Class
Identifier
OpenCurlyBracket
AccessModifier
Int
Identifier
Semicolon
AccessModifier
Int
Identifier
Semicolon
AccessModifier
Int
Identifier
Semicolon
AccessModifier
Identifier
OpenRoundBracket
Int
Identifier
ClosedRoundBracket
OpenCurlyBracket
This
Dot
Identifier
Assign
Identifier
Semicolon
This
Dot
Identifier
Assign
IntValue
Semicolon
This
Dot
Identifier
Assign
New
Identifier
OpenRoundBracket
Identifier
DotOperator
IntValue
ClosedRoundBracket
Semicolon
ClosedCurlyBracket
AccessModifier
Identifier
Identifier
OpenRoundBracket
ClosedRoundBracket
OpenCurlyBracket
Return
This
Dot
Identifier
Semicolon
ClosedCurlyBracket
AccessModifier
Int
Identifier
OpenRoundBracket
ClosedRoundBracket
OpenCurlyBracket
Return
This
Dot
Identifier
Semicolon
ClosedCurlyBracket
ClosedCurlyBracket
Class
Identifier
OpenCurlyBracket
AccessModifier
Identifier
Identifier
Semicolon
AccessModifier
Identifier
OpenRoundBracket
Int
Identifier
ClosedRoundBracket
OpenCurlyBracket
This
Dot
Identifier
Assign
New
Identifier
OpenRoundBrackets
Identifier
ClosedRoundBrackets
Semicolon
ClosedCurlyBracket
ClosedCurlyBracket
Class
Identifier
OpenCurlyBracket
AccessModifier
Int
Identifier
Semicolon
AccessModifier
Int
Identifier
Semicolon
AccessModifier
Identifier
OpenRoundBrackets
Int
Identifier
ClosedRoundBrackets
OpenCurlyBrackets
This
Dot
Identifier
Assign
Identifier
Semicolon
ClosedCurlyBracket
AccessModifier
Int
Identifier
OpenRoundBrackets
ClosedRoundBrackets
OpenCurlyBracket
Return
This
Dot
Identifier
Semicolon
ClosedCurlyBracket
AccessModifier
Int
Identifier
OpenRoundBracket
ClosedRoundBracket
OpenCurlyBracket
Return
This
Dot
Identifier
Semicolon
ClosedCurlyBracket
AccessModifier
Void
Identifier
OpenRoundBracket
Int
Identifier
ClosedRoundBracket
OpenCurlyBracket
This
Dot
Identifier
Assign
Identifier
Semicolon
ClosedCurlyBracket
ClosedCurlyBracket
EOF

View File

@ -0,0 +1,5 @@
Class
Identifier
OpenCurlyBracket
ClosedCurlyBracket
EOF

View File

@ -0,0 +1 @@
public class emptyClass {}

View File

@ -0,0 +1,6 @@
AccessModifier
Class
Identifier
OpenCurlyBracket
ClosedCurlyBracket
EOF