munificent / craftinginterpreters

Repository for the book "Crafting Interpreters"
http://www.craftinginterpreters.com/
Other
8.5k stars 1.01k forks source link

Cannot create an object of a class inside its own constructor #1047

Closed tusharsadhwani closed 2 years ago

tusharsadhwani commented 2 years ago

So this is the code snippet that I tried out:

class C { init() { var x = C(); } }
var c = C();

And it causes a stack overflow in both jlox and clox:

❯ ./jlox 
> class C { init() { var x = C(); }}
> C;
> print C;
C
> var c = C();
Exception in thread "main" java.lang.StackOverflowError
    at com.craftinginterpreters.lox.Expr$Call.accept(Expr.java:67)
    at com.craftinginterpreters.lox.Interpreter.evaluate(Interpreter.java:78)
    at com.craftinginterpreters.lox.Interpreter.visitVarStmt(Interpreter.java:228)
    at com.craftinginterpreters.lox.Interpreter.visitVarStmt(Interpreter.java:21)
    at com.craftinginterpreters.lox.Stmt$Var.accept(Stmt.java:143)
    at com.craftinginterpreters.lox.Interpreter.execute(Interpreter.java:83)
    at com.craftinginterpreters.lox.Interpreter.executeBlock(Interpreter.java:99)
    at com.craftinginterpreters.lox.LoxFunction.call(LoxFunction.java:75)
    at com.craftinginterpreters.lox.LoxClass.call(LoxClass.java:66)
    at com.craftinginterpreters.lox.Interpreter.visitCallExpr(Interpreter.java:362)
    ...
    at com.craftinginterpreters.lox.Stmt$Var.accept(Stmt.java:143)
    at com.craftinginterpreters.lox.Interpreter.execute(Interpreter.java:83)
    at com.craftinginterpreters.lox.Interpreter.executeBlock(Interpreter.java:99)
    at com.craftinginterpreters.lox.LoxFunction.call(LoxFunction.java:75)
    at com.craftinginterpreters.lox.LoxClass.call(LoxClass.java:66)
    at com.craftinginterpreters.lox.Interpreter.visitCallExpr(Interpreter.java:362)
    at com.craftinginterpreters.lox.Expr$Call.accept(Expr.java:67)
    at com.craftinginterpreters.lox.Interpreter.evaluate(Interpreter.java:78)
    at com.craftinginterpreters.lox.Interpreter.visitVarStmt(Interpreter.java:228)
    at com.craftinginterpreters.lox.Interpreter.visitVarStmt(Interpreter.java:21)

$ ./clox
> class C { init() { var x = C(); } }   
> var c = C();
Stack overflow.
[line 1] in init()
[line 1] in init()
...
[line 1] in init()
[line 1] in script
> 

Is there any way to mitigate this?

tusharsadhwani commented 2 years ago

Nevermind. This is intended behaviour :')