mpe85 / grampa

A PEG parser library for Kotlin/JVM
https://mpe85.github.io/grampa/
MIT License
13 stars 1 forks source link

typical use pattern? #52

Open jottinger opened 1 month ago

jottinger commented 1 month ago

Back to documentation: is it presumed that you create a new parser object for every corpus you need to parse? Does a parser retain state prior to run()? I ask mostly because in my code, I have data from a prior parsing run that is showing up "later" - getting a new parser addresses that, but it was surprising, because the first thing my grammar does is push an empty state only to the stack, and this implies that parsers are not threadsafe - which is fine, but something that should be pointed out explicitly and clearly somewhere.

mpe85 commented 1 month ago

The grammar instance created by createGrammar() is thread-safe as long as all the code blocks passed to the rule functions, like command { ... }, action { ... }, push { ... }, conditional ( { ... }, ...) etc., are all thread-safe for themselves. The dayOfWeek example in https://github.com/mpe85/grampa/issues/48 will not really be thread-safe because the condition code block uses the day property inside the grammar (which could cause unwanted behavior when it's manipulated by a different thread).

The parser object you create from the grammar is never thread-safe since it uses a single stack internally. So you have to create one Parser instance per thread, yes. Inside a single thread, you can of course run the Parser multiple times successively, the stack and the parser context will be reset automatically at the beginning of each run.

When I revisit the docs, I will also add a section about thread safety. Great feedback, thanks.