【问题标题】:Example of grammar (lex/yacc) for tree description树描述的语法示例 (lex/yacc)
【发布时间】:2013-07-27 14:25:40
【问题描述】:

我想从一个文件中解析一棵树,该文件将描述这棵树(实际上是一种分类法)。

我正在寻找提供树描述的语法示例(最好是 lex/yacc 文件)。如果所描述的树不是二叉搜索树,而是每个节点(可能)有几个孩子的树(它称为家谱树吗?平面树?),那就更好了。

理想情况下,如果这个 lex/yacc 实际包含在 OCaml 库中,那就太完美了。但是任何好的树描述语法都会让我满意。

我尝试通过 Google 或 Stackoverflow 查找示例,但研究结果被解析树相关的问题所淹没。 我可以自己制作一个语法,但我想先看一个例子,以便有一个好的起点。

【问题讨论】:

  • 您应该使用与 OCaml 集成的 ocamllex 和 menhir,而不是 lex 和 yacc。不知道你的树文件的语法,我帮不了你很多。
  • 别担心,我确实打算使用 ocamllex/ocamlyacc(或者可能是 Menhir)。我只是在寻找已经完成的关于树描述语法的事情(也许使用 lex/yacc,在这种情况下,我会将代码翻译成 ocamllex/ocamlyacc)。
  • 我使用 ocamllex 和 ocamlyacc 来解析 POY 中的树;检查code.google.com/p/poy/source/browse/src/nexus/grammar.mly#849。我不得不承认,我们考虑了一些额外的格式化情况,但这是另一种口味。

标签: tree ocaml grammar ocamllex menhir


【解决方案1】:

这是我尝试创建解析树的最小示例:

我假设树表示为name_of_the_node(child(...), other_child(...), ...)。例如,这是一棵具有根和 3 个叶子的简单树:root(first_leaf(), second_leaf(), third_leaf())

lexer.mll

{
  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) }

parser.mly

%{
  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) }

tree.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()))";;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多