Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Still able to return nil from init #234

Closed
mattwildig opened this issue May 21, 2018 · 1 comment
Closed

Still able to return nil from init #234

mattwildig opened this issue May 21, 2018 · 1 comment

Comments

@mattwildig
Copy link

At the end of Chapter 12 dealing with classes in jlox we make the init method always return this, and then in the next section we prevent the use of returning any other value from init. However the check preventing return statements only applies to statements with a value, and doesn’t prevent “plain” return statements.

This means it is possible to return nil from init, which I don”t think is the intention.

class Foo {
    init() {
        return;
    }
}

var f = Foo();
print f.init();  // -> nil

Removing the return, the above code prints Foo instance.

One fix is to add a check when catching the return value in LoxFunction#call, only returning the value if the function isn’t an initializer and letting it fall through if it is:

try {
    interpreter.executeBlock(declaration.body, environment);
} catch (Return returnValue) {
    if (!isInitializer) {    // <- add this check here
        return returnValue.value;
    }
}
if (isInitializer) {
    return closure.getAt(0, "this");
}

Another possibility could be to prevent all return statements in initializers, but I don’t think that’s the right choice.

@munificent
Copy link
Owner

Great catch!

zzl0 pushed a commit to zzl0/craftinginterpreters that referenced this issue Nov 19, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants