OCaml:操作从文件读取的字符串时出现问题

den*_*ieg 3 string parsing ocaml file

我正在尝试在 OCaml 中逐行读取文件。文件中的每一行代表一个我想要解析的字符串,采用解析工具所需的正确格式。我将每一行保存在列表结构中。

我发现解析列表每个元素中包含的字符串时出现问题。我使用 OCamllex 和 Menhir 作为解析工具。

  • 如果我尝试print_string在每个元素上打印列表的内容,我会得到正确的文件内容。

  • 如果我尝试将string程序中定义的 a 传递给函数,那么我会得到所需的输出。

  • 但是,如果我尝试解析刚刚从文件中读取的字符串,则会收到错误:Fatal error: exception Failure ("lexing empty token")

注意:所有这些都已针对同一字符串进行了测试。

这是代码片段:

let parse_mon m = Parser.monitor Lexer.token (from_string m)

let parse_and_print (mon: string)=
  print_endline (print_monitor (parse_mon mon) 0)

let get_file_contents file =
  let m_list = ref [] in
    let read_contents = open_in file in
      try
        while true; do
          m_list := input_line read_contents :: !m_list
        done; !m_list
      with End_of_file -> close_in read_contents; List.rev !m_list

let rec print_file_contents cont_list = match cont_list with
  | [] -> ()
  | m::ms -> parse_and_print m

let pt = print_file_contents (get_file_contents filename)
Run Code Online (Sandbox Code Playgroud)

Pie*_*Pah 5

Failure "lexing: empty token"当流中的文本与任何扫描仪模式都不匹配时,Ocamllex 会引发异常。因此,您需要匹配“包罗万象”的模式,例如._eof

{ }
rule scan = parse
  | "hello" as w { print_string w; scan lexbuf }
  (* need these two for catch-all *)
  | _ as c       { print_char c; scan lexbuf }
  | eof          { exit 0 }
Run Code Online (Sandbox Code Playgroud)