Bytecode IO
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.MAINstarts the main section.ENDends the current section.- Empty lines and lines starting with
#are ignored.
Instruction encoding
One instruction per line. Examples:
PUSH_NUM 42PUSH_STR "hello"PUSH_BOOL 0PUSH_NILLOAD nameSTORE nameDEFINE_VAR nameDEFINE_CONST nameCALL name 2JUMP 10JUMP_IF_FALSE 20RETURNENTER_SCOPEEXIT_SCOPEPOP
Strings use double quotes with escapes: \", \\, \n, \t.
Requirements
Encodemust produce a valid BC1 document.Decodemust parse the document into an equivalentBytecode.- On malformed input,
Decodereturns a non-nil error.
Notes
- Assume identifiers match
/[A-Za-z_][A-Za-z0-9_]*/. - Function parameter names are listed on the
FUNCline. - Keep the encoder/decoder readable.
Run tests to see results
No issues detected