feat: add if/else expression parsing with jump bytecodes and null object support
Implement initial support for `if` expressions in the compiler, including new `TOKEN_IF` and `TOKEN_ELSE` tokens, `CODE_JUMP` and `CODE_JUMP_IF` bytecodes for conditional branching, and a `makeNull()` function in the VM to represent the value returned when an if-condition is false without an else clause. The `emit()` function now returns the index of the emitted bytecode to enable patching jump offsets. Also add a `nullClass` to the VM and a `OBJ_NULL` object type, along with a `dumpCode()` debugging helper and new test files for block syntax and if-expression behavior.
This commit is contained in:
@@ -0,0 +1,31 @@
|
||||
// Single line.
|
||||
{ io.write("ok") }.call // expect: ok
|
||||
|
||||
// No trailing newline.
|
||||
{
|
||||
io.write("ok") }.call // expect: ok
|
||||
|
||||
// Trailing newline.
|
||||
{
|
||||
io.write("ok") // expect: ok
|
||||
}.call
|
||||
|
||||
// Multiple expressions.
|
||||
{
|
||||
io.write("1") // expect: 1
|
||||
io.write("2") // expect: 2
|
||||
}.call
|
||||
|
||||
// Extra newlines.
|
||||
{
|
||||
|
||||
|
||||
io.write("1") // expect: 1
|
||||
|
||||
|
||||
io.write("2") // expect: 2
|
||||
|
||||
|
||||
}.call
|
||||
|
||||
// TODO(bob): Arguments.
|
||||
@@ -0,0 +1,16 @@
|
||||
// Evaluate the 'then' expression if the condition is true.
|
||||
if (true) io.write("good") // expect: good
|
||||
if (false) io.write("bad")
|
||||
|
||||
// Evaluate the 'else' expression if the condition is false.
|
||||
if (true) io.write("good") else io.write("bad") // expect: good
|
||||
if (false) io.write("bad") else io.write("good") // expect: good
|
||||
|
||||
// Return the 'then' expression if the condition is true.
|
||||
io.write(if (true) "good") // expect: good
|
||||
|
||||
// Return null if the condition is false and there is no else.
|
||||
io.write(if (false) "bad") // expect: null
|
||||
|
||||
// Return the 'else' expression if the condition is false.
|
||||
io.write(if (false) "bad" else "good") // expect: good
|
||||
Reference in New Issue
Block a user