/parser-indent

An elm package for parsing indented blocks with elm/parser

Primary LanguageElmBSD 3-Clause "New" or "Revised" LicenseBSD-3-Clause

A parser for parsing indented lists.

This was inspired by the YAML library by Tereza Sokol. I recommend watching her Elm-Conf talk on parsers.

Example - parsing a list:

The following document contains a list with indented items:

List:
  Item 1
  Item 2
  Item 3
  Item 4
  Item 5

It should be parsed into the following type:

-- Type
type Item
    = Item Int

With the following parsers:

-- Parsers
item =
    succeed Item
        |. keyword "Item"
        |. spaces
        |= int

list =
    succeed identity
        |. keyword "List"
        |. spaces
        |. symbol ":"
        |. spaces
        |. eol
        |= Indent.list item

spaces =
  chompWhile (\c -> c == ' ')

eol =
    chompUntilEndOr "\n"

Example - parsing a tree with recursive lists:

Read this document:

Node
  Node
    Leaf 1
    Leaf 2
    Leaf 3
  Leaf 4

Into a tree type:

-- Type
type Tree
    = Node (List Tree)
    | Leaf Int

With the following parsers:

-- Parsers
tree =
    oneOf
        [ node
        , leaf
        ]

leaf =
    succeed Leaf
        |. keyword "Leaf"
        |. spaces
        |= int

node =
    succeed Node
        |. keyword "Node"
        |. spaces
        |. eol
        |= Indent.list (lazy (\_ -> tree))

spaces =
  chompWhile (\c -> c == ' ')

eol =
    chompUntilEndOr "\n"