Bytecode IO

medium · compilers, bytecode, serialization

Bytecode IO

Implement a simple text encoder/decoder for the BC1 bytecode format.

Function signatures

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

BC1 format

BC1
FUNC add a b
LOAD a
LOAD b
ADD
RETURN
END
MAIN
PUSH_NUM 1
PUSH_NUM 2
CALL add 2
END

Rules:

  • The first non-empty line must be BC1.
  • FUNC <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 name 2
  • 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 BC1 document.
  • Decode must parse the document into an equivalent Bytecode.
  • On malformed input, Decode returns a non-nil error.

Notes

  • Assume identifiers match /[A-Za-z_][A-Za-z0-9_]*/.
  • 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