munificent / craftinginterpreters

Repository for the book "Crafting Interpreters"
http://www.craftinginterpreters.com/
Other
8.87k stars 1.04k forks source link

How to deal with callables that are async in nature? #1105

Open thumbert opened 1 year ago

thumbert commented 1 year ago

Hi,

I don't see a clear way to implement callables that are async. In my case I'm using a Dart implementation and I'm even willing to restrict the async functions to the globals (so all are predefined), say to get some data from a database. However, the visitCallExpr will return a Future that I can't await properly to preserve the sequential nature of a Lox script.

For example, a global async function:

    globals.define(
      'get42',
      JuiceCallable(0, (interpreter, arguments) {
        return Future.delayed(Duration(seconds: 5), () => 42);
      }),
    );

called from the Lox script

var x = get42();
print x;

will print Instance of Future<int>, etc.

If you can share any tips for a possible implementation it would be much appreciated.

Thank you!

ratchetfreak commented 1 year ago

if you want the async nature of the call to be hidden from lox then you will need to implement some coroutine functionality

So you will need to be able to yield from the interpreter where the stack gets preserved and restored on the next resume.

Or you can use the built in async/await you need to detect whether the return of a function is a Future and instead of returning it you need to await it (and make the entire interpreter callstack stack up to that point async)