peggyjs / peggy

Peggy: Parser generator for JavaScript
https://peggyjs.org/
MIT License
943 stars 65 forks source link

allow await #504

Closed yukulele closed 1 month ago

yukulele commented 8 months ago
Expression = first:[0-9]+ [+] last[0-9]+ { 
  return await asyncAdd(first, last)
}

get this error :

await is only valid in async functions and the top level bodies of modules

await could be allowed inside expression body function.

hildjj commented 8 months ago

I thought I needed this once or twice, but have gotten around it by pre-processing the async class, post-processing a generated AST, or parsing once, processing, and parsing again. The most interesting cases are those where the text the grammar would accept is modified by the results of an async call that uses information parsed from the input.

There will have to be an option that affects code generation.

Discussion:

This is going to be a good amount of work to get correct. A compelling use case would help increase its priority.

vipcxj commented 2 months ago

@hildjj I think we can add a async mode. In async mode, all parser methods are async, even without 'await' keyword. And 'await' only allowed in this mode.

ashokgowtham commented 1 month ago

async as a 'mode' is a bad idea imo. It might seem like easy win, but it will cost the development in the longer run. It introduces another parallel code path. All of a sudden, it will require new features getting added to be thought through twice, once with async and another with sync. Also it doesn't scale well. Every type of 'mode' would double the number of code paths.

yukulele commented 1 month ago

it will require new features getting added to be thought through twice, once with async and another with sync.

Not really, because what works in async also works in sync.

reverofevil commented 1 month ago

Not really, because what works in async also works in sync.

Unfortunately, no, because even sync code in async function will produce a Promise that resolves in next microtask. If you need truly sync code (for example, in *.config.js file for some library), you're out of luck.

reverofevil commented 1 month ago

I don't think this should be done on peggy side. return async function() { return ...; } or return (some promise) is totally doable with the way it works right now.

Grammar is not a programming language, actions are best described in a separate file (and even better if it's in a typed language), and only valid reasons to use actions in peggy is to clean up AST and, maybe, write some prototype in its online playground. Asynchronous code is certainly something that should be done well outside the grammar.

hildjj commented 1 month ago

@reverofevil makes a compelling point. I'm going to mark this as "not planned" for the moment. Good arguments could persuade me otherwise, but this seems like a LOT of work and breakage for not enough benefit at the moment.