0

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.

Thomas Dickey
  • 51,086
  • 7
  • 70
  • 105

1 Answers1

1

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.

alifirat
  • 2,899
  • 1
  • 17
  • 33
  • Thanks a lot for your answer.. Actually i'm trying to build a compiler so i can say if an input is matching a grammar or not... Do you know if it's possible to know where the syntax error is ? – Anas El Kesri Aug 06 '15 at 12:20
  • When you say the syntax error, it's about the input that you give ? – alifirat Aug 06 '15 at 12:25
  • Watch the following answer, it's exactly what you want : http://stackoverflow.com/questions/14046392/verbose-error-with-ocamlyacc – alifirat Aug 06 '15 at 12:45