koto-lang / koto

A simple, expressive, embeddable programming language, made with Rust
https://koto.dev
MIT License
524 stars 27 forks source link

Optimize tail calls #115

Open irh opened 2 years ago

irh commented 2 years ago

Currently no effort is made in Koto to optimize tail calls, making it easy to run into stack overflows when implementing recursive functions.

e.g. The following script takes a huge amount of memory to execute:

f = |x|
  if x == 0
    return
  f x - 1
f 123456789

The idea would be that if a terminating expression (i.e. throw or return (implicit returns for the last expression in a function included)) in a function is a call, then instead of creating a new frame, the current function's execution frame can be reused.

irh commented 2 years ago

I looked at this a bit today with @alisomay and here are some notes from our discussion:

irh commented 8 months ago

Some groundwork for this was done in #290. I didn't go any further because I'd like to understand more about how debugging might one day work before making any guarantees regarding tail calls.