如何创建结合了 Parser 和 Lexer 的程序

How to create a program combining both Parser and Lexer

我想使用 Ocamllex/Ocamlyacc 构建一个编译器,我想创建一个主程序来组合我的 OcamlParser 和 OcamlLexer。问题是我知道如何使用命令行中的输入来完成它,如下面的代码:

let _ =
  try
    let lexbuf = Lexing.from_channel stdin in
    while true do
      let result = Parser.main Lexer.token lexbuf in
      print_int result; print_newline(); flush stdout
    done
  with Lexer.Eof ->
    exit 0

但是我想用一个文件作为输入怎么办;我试过这样的事情:

let file ="add.txt"
    let _ =
     let ic = open_in file in 
      try
        let lexbuf = Lexing.from_channel file in
        while true do
          let result = Parser.main Lexer.token lexbuf in
          print_int result; print_newline(); flush stdout
        done
      with Lexer.Eof ->
        exit 0

但这并没有真正起作用。

以下代码适用于我。在你的版本中,你有一些语法错误。

let _ =
      let file ="add.txt" in
      let i = open_in file in 
      try
        let lexbuf = Lexing.from_channel i in
        while true do
          let result = Parser.main Lexer.token lexbuf in
          print_int result; print_newline(); flush stdout
        done
      with Lexer.Eof ->
        exit 0

1+2 放入 "add.txt" 得到 3