From 10f5dc692dab996ebbd8262f210030893b8d9a55 Mon Sep 17 00:00:00 2001 From: Julian Murek Date: Tue, 2 Jul 2024 13:04:43 +0200 Subject: [PATCH] Codegen now generates "output.jar" --- src/main/java/abstractSyntaxTree/Program.java | 40 +++++++++++++++++-- 1 file changed, 37 insertions(+), 3 deletions(-) diff --git a/src/main/java/abstractSyntaxTree/Program.java b/src/main/java/abstractSyntaxTree/Program.java index 3826a24..6b25a0a 100644 --- a/src/main/java/abstractSyntaxTree/Program.java +++ b/src/main/java/abstractSyntaxTree/Program.java @@ -10,6 +10,8 @@ import abstractSyntaxTree.Parameter.ParameterList; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.Opcodes; +import java.io.File; +import java.io.FileInputStream; import java.util.*; import java.io.FileOutputStream; import java.io.IOException; @@ -71,28 +73,60 @@ public class Program implements Node { return result; } - public void codeGen() throws Exception{ + public void codeGen() throws Exception { + // Store the names of the generated class files + List classFileNames = new ArrayList<>(); + try { for (RefType oneClass : classes) { ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES); cw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, oneClass.name, null, "java/lang/Object", null); - oneClass.codeGen(cw, methodContext, typeContext); + oneClass.codeGen(cw, methodContext, typeContext); cw.visitEnd(); byte[] bytecode = cw.toByteArray(); - try (FileOutputStream fos = new FileOutputStream(oneClass.name + ".class")) { + String classFileName = oneClass.name + ".class"; + classFileNames.add(classFileName); + + try (FileOutputStream fos = new FileOutputStream(classFileName)) { fos.write(bytecode); } catch (IOException e) { e.printStackTrace(); } } + + // Now create the JAR file + try (FileOutputStream fos = new FileOutputStream("output.jar"); + JarOutputStream jos = new JarOutputStream(fos)) { + + for (String classFileName : classFileNames) { + addFileToJar(jos, classFileName); + } + } catch (IOException e) { + e.printStackTrace(); + } } catch (Exception e) { throw new RuntimeException(e); } } + private void addFileToJar(JarOutputStream jos, String fileName) throws IOException { + File file = new File(fileName); + try (FileInputStream fis = new FileInputStream(file)) { + JarEntry entry = new JarEntry(fileName); + jos.putNextEntry(entry); + + byte[] buffer = new byte[1024]; + int bytesRead; + while ((bytesRead = fis.read(buffer)) != -1) { + jos.write(buffer, 0, bytesRead); + } + jos.closeEntry(); + } + } + @Override public boolean equals(Object o) { if (this == o) return true;