add mainmethod to typedAst; there are Problems with TypeCheck though

This commit is contained in:
404Simon 2024-05-30 19:49:45 +02:00
parent fd35b4583e
commit a59ac5ef23
4 changed files with 31 additions and 3 deletions

View File

@ -28,7 +28,7 @@ public class ASTGenerator {
constructors.add(new Constructor(ctx.id().IDENTIFIER().getText(), List.of(), new Block(List.of())));
}
Block mainmeth = null;
if (ctx.mainmeth() != null) {
if (!ctx.mainmeth().isEmpty()) {
if (ctx.mainmeth().size() > 1) {
throw new RuntimeException("Only one main method allowed!");
}

View File

@ -1,7 +1,10 @@
package de.maishai.typedast;
import de.maishai.typedast.typedclass.TypedBlock;
import de.maishai.typedast.typedclass.TypedParameter;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import java.io.FileOutputStream;
import java.util.List;
@ -30,4 +33,13 @@ public class CodeGenUtils {
System.out.println("Error writing classfile: " + e);
}
}
public static void generateMainMethod(ClassContext ctx, TypedBlock mainMethodBlock) {
System.out.println("Generating main method");
MethodVisitor mv = ctx.getCw().visitMethod(Opcodes.ACC_PUBLIC + Opcodes.ACC_STATIC, "main", "([Ljava/lang/String;)V", null, null);
MethodContext context = new MethodContext(ctx, mv);
context.registerVariable("args", Type.REFERENCE("[Ljava/lang/String;"));
mainMethodBlock.codeGen(context);
context.wrapUp();
}
}

View File

@ -23,6 +23,7 @@ public class TypedClass implements TypedNode {
private String className;
private List<TypedDeclaration> typedDeclarations = new ArrayList<>();
private List<TypedMethod> typedMethods = new ArrayList<>();
private TypedBlock mainMethodBlock;
private List<TypedConstructor> typedConstructors = new ArrayList<>();
private TypedMethod currentMethod;
private TypedConstructor currentConstructor;
@ -74,6 +75,10 @@ public class TypedClass implements TypedNode {
for (Method method : c.methods()) {
enterCurrentMethod(typedMethods.get(j));
typedMethods.get(j).convertToTypedBlock(typedProgram, method);
// Hier wird der Block des main-Methode ausgeführt
if (c.mainmeth() != null) {
mainMethodBlock = new TypedBlock(typedProgram, c.mainmeth());
}
exitCurrentMethod();
j++;
}
@ -203,6 +208,10 @@ public class TypedClass implements TypedNode {
m.codeGen(ctx);
}
if (mainMethodBlock != null) {
CodeGenUtils.generateMainMethod(ctx, mainMethodBlock);
}
return cw.toByteArray();
}
}

View File

@ -1,12 +1,19 @@
public class ClassCanBeBytecoded {
public ClassCanBeBytecoded c;
public int x;
public ClassCanBeBytecoded() {
}
public int test(int var1) {
print(var1);
print(5+5);
int i = 8;
var1 = i + 5;
return var1;
}
public static void main(String[] args) {
ClassCanBeBytecoded c = new ClassCanBeBytecoded();
c.test(5);
}
}