Xpeg (xpeg v0.9.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")

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

Functions

Link to this function

match(module, 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 grammar
  • result: either :ok or :error, depending on a successful match of the subject
  • time: Time taken to match the subject (seconds)
  • match_len: The total number of UTF-8 characters matched
  • userdata: Returned userdata
Link to this macro

patt(v)

(macro)

Define a grammar with one anonymous rule.

Link to this macro

peg(start, rules)

(macro)

Define a PEG grammar which uses start as the initial rule

Link to this macro

peg(start, options, list)

(macro)

Define a PEG grammar which uses start as the initial rule, allowing for additional options:

  • :trace - if true, a trace is dumped during parser execution
  • :dump_ir - if true, the IR (intermediate representation) of the generated parser is dumped at compile time
  • :dump_code - if true, the generated Elixir code for the parser is dumped at compile time
  • :dump_graph - if true, generate a graphical 'railroad' diagram of the grammar at compile time
  • :userdata - if true, 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 the userdata field in the return value of the `match()1 function