mna / pigeon

Command pigeon generates parsers in Go from a PEG grammar.
BSD 3-Clause "New" or "Revised" License
835 stars 66 forks source link

How to pass in data into parser #61

Closed felipellrocha closed 6 years ago

felipellrocha commented 6 years ago

In peg.js I'm able to pass data into the parser via an options variable. Is there an example of how I could do the same here?

breml commented 6 years ago

@felipellrocha Thanks for your question. Have a look at the GlobalStore function, which can be used to pass arbitrary data to the global store of the parser. See also the respective section in godoc or this test as an example how to use it.

felipellrocha commented 6 years ago

This example confuses me a little bit... How do I pass multiple options? Also... Option is a function that returns other Options?

breml commented 6 years ago

@felipellrocha The function Parse (and its variants ParseFile and ParseReader) accept a variadic list of options as aguments. This means, that you can parse the above mentioned GlobalStore function multiple times to set multiple values in the global store. The type Option is a function, which returns the previous setting as an option, which means, that the returned option function could be used to reset the previous state. this being said, this is not used here, because these option functions are not returned in setOptions).

In the end, what matters for you is, that you can use the GlobalStore function to initialize the global store with multiple values upon creation of the parser like this:

got, err := Parse("", []byte(test.input), GlobalStore("key1", value1), GlobalStore("key2", value2))