这是我尝试创建解析树的最小示例:
我假设树表示为name_of_the_node(child(...), other_child(...), ...)
。例如,这是一棵有根和 3 片叶子的简单树:root(first_leaf(), second_leaf(), third_leaf())
.
词法分析器
{
open Parser
open Lexing
exception Bad_char of char
}
rule main = parse
| ' ' | '\t' | '\n' { main lexbuf }
| ',' { COMMA }
| '(' { LP }
| ')' { RP }
| ['a'-'z' '_']+ as s { IDENT s }
| _ as c { raise (Bad_char c) }
解析器
%{
open Tree
%}
%token <string> IDENT
%token COMMA LP RP
%start <Tree.t> tree
%%
tree:
label = IDENT LP children = separated_list(COMMA, tree) RP { T(label, children) }
树.ml
type t = T of string * t list
编译:
ocamllex lexer.mll
ocamlc -c tree.ml
menhir --infer -v parser.mly
ocamlc -c parser.mli
ocamlc -c parser.ml
ocamlc -c lexer.ml
测试到顶层:
ocaml tree.cmo parser.cmo lexer.cmo
接着:
let tree_of_string s = Parser.tree Lexer.main (Lexing.from_string s);;
tree_of_string "toto (titi(), tata(tutu()))";;