Xpeg (xpeg v0.4.1)
XPeg is a pure Elixir pattern matching library. It provides macros to compile patterns and grammars (PEGs) to Elixir function which will parse a string and collect selected parts of the input. PEGs are not unlike regular expressions, but offer more power and flexibility, and have less ambiguities. (More about PEGs on Wikipedia)
Some use cases where XPeg is useful are configuration or data file parsers, robust protocol implementations, input validation, lexing of programming languages or domain specific languages.
Examples
p = Xpeg.peg :dict do
:dict <- :pair * star("," * :pair) * !1
:pair <- :word * "=" * :number * fn [a,b|cs] -> [{b,a}|cs] end
:word <- cap(+{'a'..'z'})
:number <- cap(+{'0'..'9'}) * fn [v|cs] -> [String.to_integer(v) | cs] end
end
Xpeg.match(p, "grass=4,horse=1,star=2")
Link to this section Summary
Functions
Execute a grammar against a subject string. The result is a map with the following fields
Define a grammar with one anonymous rule.
Define a PEG grammar which uses start
as the initial rule
Define a PEG grammar which uses start
as the initial rule, allowing
for additional options
Link to this section Functions
match(func, s, userdata \\ nil)
Execute a grammar against a subject string. The result is a map with the following fields:
captures
: The captures made by the grammarresult
: either:ok
or:error
, depending on a successful match of the subjecttime
: Time taken to match the subject (seconds)match_len
: The total number of UTF-8 characters matcheduserdata
: Returned userdata
Define a grammar with one anonymous rule.
Define a PEG grammar which uses start
as the initial rule
Define a PEG grammar which uses start
as the initial rule, allowing
for additional options:
:trace
- iftrue
, a trace is dumped during parser execution:dump_ir
- iftrue
, the IR (intermediate representation) of the generated parser is dumped at compile time:dump_code
- iftrue
, the generated Elixir code for the parser is dumped at compile time:userdata
- iftrue
, elixir functions that are embedded in the grammar take an additional accumulator argument and should return a tuple{captures | acc}
- the resulting accumulator value is available as theuserdata
field in the return value of the `match()1 function