Neotomex v0.1.7 Neotomex.ExGrammar View Source

Neotomex.ExGrammar

ExGrammar provides an interface for defining a PEG from within an Elixir module.

For example:

defmodule Number do
  use Neotomex.ExGrammar

  @root true
  define :digits, "[0-9]+" do
    digits when is_list(digits) -> digits |> Enum.join |> String.to_integer
  end
end

Number.parse!("42") = 42

Check the examples/ folder for slightly more useful examples of grammar specifications via ExGrammar.

By default, the grammar is validated on compile. To disable validation, add @validate true to the module.

Definitions

A grammar consists of a set of definitions with optional transformation functions, and a pointer to the root definition. Using the ExGrammar interface, a definition is specified using the define macro.

Here are some example usages of define:

# No transformation
define name, expression

# With transformation
define name, expression do
  match -> match
end

# With a more complex transformation
# (yup, you could just reduce the list, but that doesn't make the point :)
define name, expression do
  [x] ->
    String.to_integer(x)
  [x, y] when is_binary(x) and is_binary(y) ->
    String.to_integer(x) + String.to_integer(y)
end

The root rule must be labeled via @root true.

Link to this section Summary

Functions

Create a new definition for the module’s grammar

Link to this section Functions

Link to this macro define(identifier, expr, body \\ nil) View Source (macro)

Create a new definition for the module’s grammar.