Bytecode IO v3

medium · compilers, bytecode, serialization

Bytecode IO v3

Implement a text encoder/decoder for the BC2 bytecode format (closures + function IDs).

Function signatures

func Encode(bc Bytecode) string
func Decode(src string) (Bytecode, error)

BC2 format

BC2
FUNC 0 add a b
LOAD a
LOAD b
ADD
RETURN
END
MAIN
MAKE_CLOSURE 0
PUSH_NUM 1
PUSH_NUM 2
CALL 2
END

Rules:

  • The first non-empty line must be BC2.
  • FUNC <id> <name> <param...> starts a function section.
  • MAIN starts the main section.
  • END ends the current section.
  • Empty lines and lines starting with # are ignored.

Instruction encoding

One instruction per line. Examples:

  • PUSH_NUM 42
  • PUSH_STR "hello"
  • PUSH_BOOL 0
  • PUSH_NIL
  • LOAD name
  • STORE name
  • DEFINE_VAR name
  • DEFINE_CONST name
  • CALL 2
  • MAKE_CLOSURE 7
  • MAKE_ARRAY 3
  • MAKE_MAP 2
  • GET_INDEX
  • SET_INDEX
  • JUMP 10
  • JUMP_IF_FALSE 20
  • RETURN
  • ENTER_SCOPE
  • EXIT_SCOPE
  • POP

Strings use double quotes with escapes: \", \\, \n, \t.

Requirements

  • Encode must produce a valid BC2 document.
  • Decode must parse the document into an equivalent Bytecode.
  • On malformed input, Decode returns a non-nil error.

Notes

  • Function parameter names are listed on the FUNC line.
  • Keep the encoder/decoder readable.

Before implementation

Use the module’s worked reconstruction and independent debugging lab to predict an intermediate artifact first. Preserve one failing counterexample while implementing the stated API. The lesson’s transfer task uses a fresh case after the guided trace.

Run tests to see results
No issues detected
    Join Discord