Parsing grammars using OCaml

前端 未结 3 1320
余生分开走
余生分开走 2020-12-28 10:33

I have a task to write a (toy) parser for a (toy) grammar using OCaml and not sure how to start (and proceed with) this problem.

Here\'s a sample Awk grammar:

<
3条回答
  •  鱼传尺愫
    2020-12-28 11:06

    I'm not sure if you specifically require the derivation tree, or if this is a just a first step in parsing. I'm assuming the latter.

    You could start by defining the structure of the resulting abstract syntax tree by defining types. It could be something like this:

    type expr =
        | Operation of term * binop * term
        | Term of term
    and term =
        | Num of num
        | Lvalue of expr
        | Incrop of incrop * expression
    and incrop = Incr | Decr
    and binop = Plus | Minus
    and num = int
    

    Then I'd implement a recursive descent parser. Of course it would be much nicer if you could use streams combined with the preprocessor camlp4of...

    By the way, there's a small example about arithmetic expressions in the OCaml documentation here.

提交回复
热议问题