ocaml - 将 ocamlyacc 与 sedlex 结合使用

标签 ocaml ocamllex ocamlyacc

我正在尝试弄清楚如何将 ocamlyacc 与 sedlex 一起使用。

lexer.ml(使用 sedlex):

let rec lex (lexbuf: Sedlexing.lexbuf) =
    match%sedlex lexbuf with
    | white_space -> lex lexbuf
    (* ... other lexing rules ... *)
    | _ -> failwith "Unrecognized."

我还有一个名为 parser.mly 的 ocamlyacc 文件,其中包含 parse 作为语法规则之一。

为了解析字符串,我使用了这个:

let lexbuf = Sedlexing.Utf8.from_string s in
let parsed = (Parser.parse Lexer.lex) lexbuf in
(* ... do things ... *)

但是在编译过程中,出现了这个错误(由上面的Lexer.lex引起):

Error: This expression has type Sedlexing.lexbuf -> Parser.token but an expression was expected of type Lexing.lexbuf -> Parser.token Type Sedlexing.lexbuf is not compatible with type Lexing.lexbuf

根据我的理解,出现此错误是因为 ocamlyacc 期望词法分析器由 ocamllex 生成,而不是由 sedlex 生成。所以问题是:如何将 ocamlyacc 与 sedlex 一起使用?

最佳答案

如果您没有非常具体的原因使用 ocamlyacc 而不是 Menhir,那么使用 Menhir 并将解析函数转换为修订后的 API 可能要简单得多,只需一个 类型的 token 生成器函数单位 -> 代币 * 位置 * 位置:

 let provider lexbuf () =
    let tok = generated_lexer lexbuf in
    let start, stop =  Sedlexing.lexing_positions lexbuf in
    tok, start, stop

 let parser_result = MenhirLib.Convert.Simplified.traditional2revised
     generated_parser_entry_point
     (provider lexbuf)

否则,您需要从 Sedlexing.lexbuf -> token 创建函数 Leshing.lexbuf -> token,该函数采用虚拟 lexbuf 作为输入,应用真实的词法分析sedlex 缓冲区上的函数,将位置信息复制到虚拟 Lexing.lexbuf,然后返回 token 。

关于ocaml - 将 ocamlyacc 与 sedlex 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52474076/

相关文章:

ocaml - 从 OCaml 检查感应类型的元素

OCaml 解析器代码

OCamlLex 不区分大小写

metaprogramming - 在 OCaml 顶层嵌入领域特定语言——是否嵌入 Camlp4?

ocamlyacc 解析错误 : what token?

ocaml - 从 LLVM 字符串常量中获取字符串

data-structures - 纯函数式数据结构有什么好处?

parsing - 使包含标记的表对 .mly 和 .mll 均可见(作者:menhir)

ocaml - 扩展 ocamllex 以获取更大的词典