Commit cda10357 authored by fpottier's avatar fpottier

Updated calc and its lexer for better style.

git-svn-id: svn+ssh://scm.gforge.inria.fr/svnroot/menhir@349 0f8b5475-4b4e-0410-85a8-ee3154a6bfe7
parent ea0c1793
let () =
let stdinbuf = Lexing.from_channel stdin in
while true do
(* Read line by line. *)
let linebuf = Lexing.from_string (Lexer.line stdinbuf) in
let process (line : string) =
let linebuf = Lexing.from_string line in
try
(* Run the parser on a single line of input. *)
(* Run the parser on this line of input. *)
Printf.printf "%d\n%!" (Parser.main Lexer.token linebuf)
with
| Lexer.Error msg ->
Printf.fprintf stderr "%s%!" msg
| Parser.Error ->
Printf.fprintf stderr "At offset %d: syntax error.\n%!" (Lexing.lexeme_start linebuf)
done
let process (optional_line : string option) =
match optional_line with
| None ->
()
| Some line ->
process line
let rec repeat channel =
(* Attempt to read one line. *)
let optional_line, continue = Lexer.line channel in
process optional_line;
if continue then
repeat channel
let () =
repeat (Lexing.from_channel stdin)
......@@ -5,11 +5,24 @@
}
(* This rule looks for a single line, terminated with '\n' or eof.
It returns a pair of an optional string (the line that was found)
and a Boolean flag (false if eof was reached). *)
rule line = parse
| ([^'\n']* '\n') as line
{ line }
(* Normal case: one line, no eof. *)
{ Some line, true }
| eof
{ exit 0 }
(* Normal case: no data, eof. *)
{ None, false }
| ([^'\n']+ as line) eof
(* Special case: some data but missing '\n', then eof.
Consider this as the last line, and add the missing '\n'. *)
{ Some (line ^ "\n"), false }
(* This rule analyzes a single line and turns it into a stream of
tokens. *)
and token = parse
| [' ' '\t']
......@@ -30,8 +43,6 @@ and token = parse
{ LPAREN }
| ')'
{ RPAREN }
| eof
{ exit 0 }
| _
{ raise (Error (Printf.sprintf "At offset %d: unexpected character.\n" (Lexing.lexeme_start lexbuf))) }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment