Use Cases

This sections describes how the handle common use cases with drom.

Using menhir

Whereas ocamlyacc is the legacy parser generator for OCaml, menhir is much more powerful and probably more prevalent nowadays.

For trivial usage where there is a simple parser.mly file in your package, setting:

generators = ["menhir"]

into the corresponding package.toml will likely work. However, if you have multiple .mly files, or need to specify custom menhir flags, you’ll probably need to use the [menhir] table in the corresponding package.toml. For example:

[menhir]
version = "2.1"
parser = {
  modules = ["tokens", "parser"],
  merge-into = "parser",
  tokens = "Tokens",
  flags = [ "--table" ],
  infer = true
}
tokens = {
  modules = ["tokens"],
  #flags = []
}

This will generate the following rules in you dune file:

(menhir
  (modules tokens)
  (flags --only-tokens))
(menhir
  (modules tokens parser)
  (merge_into parser)
  (flags --table --external-tokens Tokens)
  (infer true))

and will add:

(using menhir 2.1)

to the dune-project file.

You can also can tune the dune generation. A good way to properly do that is to disable the default dune generation for and add your own dune stanzas for parsing generators. First, add (using menhir X.Y) in the drom.toml’s ‘dune-project-header field. For example:

[fields]
dune-project-header = "(using menhir 2.1)"

Then split your parsing code into at least two files tokens.mly and parser.mly. The first one will contain the tokens definitions and the second one the parsing rules. Doing this allows to parametrize the parser in a modular fashion by using the %parameter <> directive, if needed. Then replace the generators = ["menhir"] line by the following:

generators = []

in package.toml to disable the default dune stanzas generation. Finally, add the following dune stanzas to your dune-trailer field:

[fields]
dune-trailer = """
(menhir
  (modules tokens)
  (flags --only-tokens)
)

(menhir
  (modules tokens parser)
  (merge_into parser)
  (flags --external-tokens Tokens)
)
"""

Of course, this is just a basic tuning and you can modify the flags or targets as needed. The overall result will likely fit in most of menhir usages in drom projects waiting for a better menhir support.