Make an exact parser using NimbleParsec

I am using the following code

defmodule Jotamenos.Parser.Types do
  import NimbleParsec
  # Type ::= "int" "[" "]" | "boolean" | "int" | Identifier
  array_int = string("int []") |> label("int[]")
  int = string("int")  |> label("int")
  bool = string("boolean") |> label("boolean")

  defparsec(:types, choice([array_int, int, bool]))
end

When a test using Jotamenos.Parser.Types.types("int") it says ok but if I use Jotamenos.Parser.Types.types("intd") also says ok, but I want to catch the exact word int and reject any variation like intd, intuiw, intc...

You can use the eos() combinator for that:

defmodule Jotamenos.Parser.Types do
  import NimbleParsec
  # Type ::= "int" "[" "]" | "boolean" | "int" | Identifier
  array_int = string("int []") |> label("int[]")
  int = string("int")  |> label("int")
  bool = string("boolean") |> label("boolean")

  # eos() requires that there be no more input to consume
  defparsec(:types, choice([array_int, int, bool]) |> eos())
end
3 Likes