1
{ }
rule translate = parse
| "current_directory" { print_string (Sys.getcwd ()) }
| _ as c { print_char c }
| eof { exit 0 }
{
let main () =
let lexbuf = Lexing.from_channel stdin in
while true do
translate lexbuf
done
let _ = Printexc.print main ()
}

Can someone please explain me how the main function works? I have understood the regexp part, and am able to get a sense of the main function, but not the exact meaning.

darque
  • 1,566
  • 1
  • 14
  • 22
alpha42
  • 55
  • 6

1 Answers1

1

The main function looks like this:

let main () =
  let lexbuf = Lexing.from_channel stdin in
  while true do
    translate lexbuf
  done

It creates a lexbuf using stdin as its source, then calls translate repeatedly using this lexbuf. The type of translate is Lexing.lexbuf -> unit. It expects a lexbuf, looks for one token, and executes the associated rule. You define a rule for eof that causes the program to exit, which terminates the while.

The next line actually runs the main function:

let _ = Printexc.print main ()

What this does is call main, passing it (). If an exception is raised during execution, Printexc.print will print out a description of it. Since no exception is raised in the test, eventually you reach the end of file and the eof rule causes the program to exit.

Jeffrey Scofield
  • 65,646
  • 2
  • 72
  • 108