From da68aacaa08db4154fecc1c85379b3eb59c9f9a2 Mon Sep 17 00:00:00 2001 From: i22007 Date: Tue, 7 May 2024 19:13:40 +0200 Subject: [PATCH] Generate byteode for empty class without typecheck --- pom.xml | 12 +++++++ src/main/java/bytecode/ByteCodeGenerator.java | 33 +++++++++++++++++++ src/main/java/parser/Main.java | 3 ++ 3 files changed, 48 insertions(+) create mode 100644 src/main/java/bytecode/ByteCodeGenerator.java diff --git a/pom.xml b/pom.xml index f1dc834..9ee63e3 100644 --- a/pom.xml +++ b/pom.xml @@ -22,6 +22,18 @@ 5.9.3 test + + org.antlr + antlr4-runtime + 4.13.1 + + + + org.ow2.asm + asm + 9.7 + + diff --git a/src/main/java/bytecode/ByteCodeGenerator.java b/src/main/java/bytecode/ByteCodeGenerator.java new file mode 100644 index 0000000..8b07bbb --- /dev/null +++ b/src/main/java/bytecode/ByteCodeGenerator.java @@ -0,0 +1,33 @@ +package bytecode; + +import java.io.FileOutputStream; +import java.io.IOException; +import org.objectweb.asm.ClassWriter; +import org.objectweb.asm.Opcodes; +import parser.ClassDeclarationNode; +import parser.ProgramNode; + +public class ByteCodeGenerator { + + public void generateByteCode(ProgramNode ast) { + for (ClassDeclarationNode classDeclarationNode : ast.classes) { + ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS); + cw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, classDeclarationNode.identifier, null, + "java/lang/Object", null); + cw.visitEnd(); + printIntoClassFile(cw.toByteArray(), classDeclarationNode.identifier); + } + } + + private void printIntoClassFile(byte[] byteCode, String name) { + String filePath = name + ".class"; + + try { + FileOutputStream fileOutputStream = new FileOutputStream(filePath); + fileOutputStream.write(byteCode); + fileOutputStream.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } +} diff --git a/src/main/java/parser/Main.java b/src/main/java/parser/Main.java index ca8554f..64a1c8b 100644 --- a/src/main/java/parser/Main.java +++ b/src/main/java/parser/Main.java @@ -23,5 +23,8 @@ public class Main { // Optionally print or process the AST System.out.println("Parsed " + ast.classes.size() + " classes."); System.out.println(ast.classes.get(0).identifier); + + //ByteCodeGenerator byteCodeGenerator = new ByteCodeGenerator(); + //byteCodeGenerator.generateByteCode(ast); } } \ No newline at end of file