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

add generators to Lox #17

Open
zxul767 opened this issue Nov 12, 2022 · 0 comments
Open

add generators to Lox #17

zxul767 opened this issue Nov 12, 2022 · 0 comments
Labels
enhancement New feature or request p2

Comments

@zxul767
Copy link
Owner

zxul767 commented Nov 12, 2022

it would be interesting to add generators to Lox, with syntax similar to other languages (i.e., adding the yield keyword and using the resulting objects with an iterator protocol)

fun fib(limit) {
   var a = 0
   var b = 1
   while (a <= limit) {
      yield a
      var previous_a = a
      a = b
      b = previous_a + b
   }
}

var iter = fib(/* limit: */10)
while (!iter.at_end()) {
   println(iter.value)
   it.more()
}

for clox, the feature is not likely to require large runtime restructuring, as it is a matter of adding a new opcode and being able to save/restore a function's local environment (along with the program counter for properly resuming a function after the last yield)

for jlox, the feature unfortunately requires more extensive changes since the way code is currently executed (a recursive traversal of the AST) doesn't allow for easy resuming of a function's execution. one way to implement it would be by creating a family of "resumable" statement classes which store the current state of a statement's execution (e.g., this gist has a proof of concept of such an implementation).

@zxul767 zxul767 added the enhancement New feature or request label Nov 12, 2022
@zxul767 zxul767 added the p2 label Dec 7, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request p2
Projects
None yet
Development

No branches or pull requests

1 participant