From 8e8bb4b9b980b3b9bc660a46f262f522334c9f84 Mon Sep 17 00:00:00 2001 From: Bob Nystrom Date: Sun, 12 Jan 2014 19:37:11 -0800 Subject: [PATCH] Allow returns without an explicit value. --- src/wren_compiler.c | 13 +++++++++---- src/wren_core.c | 2 +- test/return/in_function.wren | 7 ++++++- test/return/return_null_if_brace.wren | 6 ++++++ test/return/return_null_if_newline.wren | 6 ++++++ 5 files changed, 28 insertions(+), 6 deletions(-) create mode 100644 test/return/return_null_if_brace.wren create mode 100644 test/return/return_null_if_newline.wren diff --git a/src/wren_compiler.c b/src/wren_compiler.c index a5f70448..2a67cff8 100644 --- a/src/wren_compiler.c +++ b/src/wren_compiler.c @@ -1828,7 +1828,6 @@ void namedSignature(Compiler* compiler, char* name, int* length) if (match(compiler, TOKEN_EQ)) { // It's a setter. - // TODO: Allow setters with parameters? Like: foo.bar(1, 2) = "blah" name[(*length)++] = '='; name[(*length)++] = ' '; @@ -2326,9 +2325,15 @@ void statement(Compiler* compiler) if (match(compiler, TOKEN_RETURN)) { // Compile the return value. - // TODO: Implicitly return null if there is a newline or } after the - // "return". - expression(compiler); + if (peek(compiler) == TOKEN_LINE || peek(compiler) == TOKEN_RIGHT_BRACE) + { + // Implicitly return null if there is no value. + emit(compiler, CODE_NULL); + } + else + { + expression(compiler); + } emit(compiler, CODE_RETURN); return; diff --git a/src/wren_core.c b/src/wren_core.c index c7515ed8..0b9aba1d 100644 --- a/src/wren_core.c +++ b/src/wren_core.c @@ -185,7 +185,7 @@ DEF_NATIVE(fiber_create) ObjFiber* newFiber = wrenNewFiber(vm, AS_OBJ(args[1])); - // The compiler expect the first slot of a function to hold the receiver. + // The compiler expects the first slot of a function to hold the receiver. // Since a fiber's stack is invoked directly, it doesn't have one, so put it // in here. // TODO: Is there a cleaner solution? diff --git a/test/return/in_function.wren b/test/return/in_function.wren index 0b1a26af..916d7390 100644 --- a/test/return/in_function.wren +++ b/test/return/in_function.wren @@ -1 +1,6 @@ -var a = "ok"; IO.print(a) // expect: ok +var f = fn { + return "ok" + IO.print("bad") +} + +IO.print(f.call) // expect: ok diff --git a/test/return/return_null_if_brace.wren b/test/return/return_null_if_brace.wren new file mode 100644 index 00000000..31010935 --- /dev/null +++ b/test/return/return_null_if_brace.wren @@ -0,0 +1,6 @@ +var f = fn { + if (true) { return } + IO.print("bad") +} + +IO.print(f.call) // expect: null diff --git a/test/return/return_null_if_newline.wren b/test/return/return_null_if_newline.wren new file mode 100644 index 00000000..ab5ad28d --- /dev/null +++ b/test/return/return_null_if_newline.wren @@ -0,0 +1,6 @@ +var f = fn { + return + IO.print("bad") +} + +IO.print(f.call) // expect: null