How to implement the eof (when pressing ctrl^d) on the following code in Ocaml and print the results when the user press ctr^d?

I am trying to implement a parser that read regular expression. It ask the user to enter a valid input of string/integers/float. If is valid and the user press ctrl^d, then print the number. Otherwise shows an error. But the problem in the following code does not stop when I press ctrl^D. How to implement eof token and print the input ?

{ type result = Int of int | Float of float | String of string }
let digit = ['0'-'9']
let digits = digit +
let lower_case = ['a'-'z']
let upper_case = ['A'-'Z']
let letter = upper_case | lower_case
let letters = letter +

rule main = parse
   (digits)'.'digits as f  { Float (float_of_string f) }
 | digits as n              { Int (int_of_string n) }
 | letters as s             { String s}
 | _ { main lexbuf }


 { let newlexbuf = (Lexing.from_channel stdin) in
 let result = main newlexbuf in
 print_endline result }

Your lexer is caught in an infinite loop because it does not handle the
special eof pattern which signifies end of input. It is instead matched
by your wildcard _ match which just loops.

See OCaml - Lexer and parser generators (ocamllex, ocamlyacc)

1 Like