Codegen now generates "output.jar"

This commit is contained in:
Julian Murek 2024-07-02 13:04:43 +02:00
parent e46cede8d5
commit 10f5dc692d

View File

@ -10,6 +10,8 @@ import abstractSyntaxTree.Parameter.ParameterList;
import org.objectweb.asm.ClassWriter; import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Opcodes; import org.objectweb.asm.Opcodes;
import java.io.File;
import java.io.FileInputStream;
import java.util.*; import java.util.*;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
@ -72,6 +74,9 @@ public class Program implements Node {
} }
public void codeGen() throws Exception { public void codeGen() throws Exception {
// Store the names of the generated class files
List<String> classFileNames = new ArrayList<>();
try { try {
for (RefType oneClass : classes) { for (RefType oneClass : classes) {
ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES); ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
@ -82,17 +87,46 @@ public class Program implements Node {
cw.visitEnd(); cw.visitEnd();
byte[] bytecode = cw.toByteArray(); 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); fos.write(bytecode);
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); 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) { } catch (Exception e) {
throw new RuntimeException(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 @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) return true; if (this == o) return true;