shuhei / cymbal

Yet another Rust implementation of the Monkey language from "Writing an Interpreter in Go" and "Writing a Compiler in Go"
MIT License
81 stars 12 forks source link

Serialize/deserialize bytecode #2

Open shuhei opened 5 years ago

shuhei commented 5 years ago
shuhei commented 5 years ago

An example: Java bytecode format https://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html

shuhei commented 5 years ago
pub struct Bytecode {
  insturctions: Vec<u8>,
  constants: Vec<Constant>,
}
pub enum Constant {
    Integer(i64),
    Float(f64),
    String(String),
    CompiledFunction(CompiledFunction),
}
pub struct CompiledFunction {
    pub instructions: Instructions,
    pub num_locals: u8,
    pub num_parameters: u8,
}
shuhei commented 5 years ago

Bytecode:

8 bytes version
8 bytes instructions_size (in bytes)
${instructions_size} instructions
8 bytes constants_count (in bytes)
constant * constants_count

Constant:

1 byte tag (integer, float, string, compiled function)

and...

8byte data (integer or float)

or

8byte string_size
${string_size} string data

or

1byte num_locals
1byte num_parameters
8 bytes instructions_size (in bytes)
${instructions_size} instructions

Use Big Endian.