Closed zxul767 closed 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.
In the book, incorrect usage of the
return
statement (i.e., outside of function definitions) is detected using theResolver
class (i.e., after parsing). However, this strikes me as inappropriate given thatreturn
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 fordeclaration
, and adding a rule forfunctionBody
that includes the union ofdeclaration
andreturnStmt
)