zxul767 / lox

An interpreter for the Lox language
1 stars 0 forks source link

Report incorrect return usage #1

Closed zxul767 closed 1 year ago

zxul767 commented 1 year ago

In the book, incorrect usage of the return statement (i.e., outside of function definitions) is detected using the Resolver class (i.e., after parsing). However, this strikes me as inappropriate given that return statements are meant to be used strictly inside function definition blocks. In my opinion, it'd be better to modify the grammar to detect the error as a parsing error (e.g., Python 3.8+ does this).

The modifications necessary for this are likely to be minimal (e.g., removing returnStmt from the top-level production for declaration, and adding a rule for functionBody that includes the union of declaration and returnStmt)

zxul767 commented 1 year ago

After a bit more thinking I realized that it is actually not possible to detect incorrect return usage without modifying the grammar to no longer be context-free.

This is essentially due to the fact that return statements can appear in the bodies of for, if and other statements which are valid both in top-level and function-level scopes.

Therefore, the solution proposed in the book is correct.