I want to create a programming language that compiles to its own bytecode format and a VM that interprets it. But I want the bytecode to be compatible with JVM. I've searched for any way to insert comments to JVM bytecode so then I can parse them with my own VM but I couldn't find any. Also I tried to insert some bytes in the start of the byte array and in the end, but it produced ClassFormatException. Is there any workaround?
-
Maybe your question is answered here https://stackoverflow.com/questions/688098/compile-to-java-bytecode-without-using-java ? – Henryk Gerlach Jul 25 '19 at 20:48
2 Answers
"compiles to its own bytecode format" and "compatible with JVM" are mutually exclusive requirements.
If you want the JVM to be able to parse your classfiles, the classfiles must strictly comply with the Java Virtual Machine Specification Chapter 4. The class File Format.
The standard way of exteding the class file format is Attributes. You may invent your own attributes and include them to one or more of the following structures:

- 92,924
- 10
- 193
- 247
Scala does this, so you should check that out. As mentioned by apanging, the standard way to insert "comments" in a classfile are with attributes. The classfile format defines certain standard attributes that are used by the JVM. However, you can also include arbitrary user defined attributes which can contain arbitrary data. This is what Scala uses to include the metadata required by the Scala runtime.

- 37,781
- 10
- 100
- 107