Implementing struct / enums in an interpreter

  1. Sorry for the confusion. I guess this Rust post has been people helping me debug my thought process.

  2. I do want to be able to define structs at RUNTIME. It's an interpreter / REPL. The user enters some commands, we read/parse/compile-to-byte-instr it, then evaluate it.

  3. I am disallowing adding/deleting fields from EXISTING structs/enums -- that would wreck all types of havoc. But I absolutely want the user to be able to define structs/enums fro the REPL.

  4. I do think it is possible to define "C-style", i.e. everything in-line in one contiguous block of memory, type structs / enums, at "runtime", i.e. at a REPL on the interpreter.

Perhaps better way to describe this is:

  1. imagine we start with a Scheme (or lua or elisp) repl.

  2. We then want the ability to define "C-style" structs/enums (i.e. contiguous block of memory) at the REPL.

I think the above described methods work for this.

What I am not sure about is how much unsafe this will incur.

> define enum Gender { Male, Female };

defined.

> define struct Human_Base {
  first: String,
  last: String,
  age: i32,
  gender: Gender
}

defined.

> define struct Programmer {
  base: Human_Base,
  favorite_language: String,
  experience: i32
}

defined.

> let bob = Programmer {
  base: Human_Base {
    first: "Bob", last: "Doe", age: 70, gender: Male
  },
  favoreite_language: "Rust",
  experience: 2,
  }

bob.

> bob.base.age = 71; // just had a birthday

ok.

> print_layout(bob)

bob at addr 0x.....
base: {
  first: 8 bytes, ptr to heap allocated string,
  last: 8 bytes, ptr to heap allocated string,
  age: 4 bytes, i32, = 71
  gender: 1 byte, = Gender::Male
}
favorite_language: 8 bytes, ptr to heap allocated string,
experience: 4 bytes, i32 = 2


(Fictional REPL session).

The trifecta here is:

  • interactivity of a REPL / interpreter

  • safety of having structs / enums / types

  • performance of C style layout of above structs / enums

You are missing the intermediate step: ā€œdumb JITā€. Something like Java 1.2 (or Lua-JIT): no tracing, no hot spotting, but simple fixed sequence of instructions for each bytecode instruction.

This may already give 5-10x speedup compared to bytecode interpreter (and bytecode interpreter is 5-10x faster that Bill-Gates BASIC interpreter). ā€œEnterprise-grade JITā€ is even faster, but much more complicated.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.