Search code examples
ocamlyacclexocamllexocamlyacc

How to create a program combining both Parser and Lexer


I want to build a compiler using Ocamllex/Ocamlyacc and I want to create a main program to combine both of my OcamlParser and OcamlLexer. The thing is that I know how to do it using an input in the command line like the following code:

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

But how can I do if I want to use a file as an input; I tried something like this:

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

But it's not really working.


Solution

  • The following code works for me. In your version, you have some syntax errors.

    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
    

    Putting 1+2 in "add.txt" gives me 3.