zxul767 / lox

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

add generators to Lox #17

Open zxul767 opened 1 year ago

zxul767 commented 1 year ago

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).