open Regexp
open Scanf

let rec print_regexp = function
  | Char c -> print_char c
  | Alt (e1, e2) -> print_regexp e1; print_char '|'; print_regexp e2
  | Seq (e1, e2) -> print_par1 e1; print_par1 e2
  | Star e -> print_par2 e; print_char '*'
  | _ -> ()
and print_pars e = print_char '('; print_regexp e; print_char ')'
and print_par1 = function
  | Alt (e1, e2) as e -> print_pars e
  | e -> print_regexp e
and print_par2 = function
  | Seq (e1, e2) as e -> print_pars e
  | e -> print_par1 e

let read_regexp() =
  let rec read_rex() = read_alt(read_seq()) 
  and read_alt e1 =
    try scanf "%_[ ]|" (); read_alt (Alt (e1, read_seq()))
    with End_of_file | Scan_failure _ -> e1
  and read_seq() = read_rest(read_term())
  and read_rest e1 = try read_rest (Seq (e1, read_term())) with Exit -> e1
  and read_term() = read_stars(read_atom())
  and read_stars e1 = 
    try scanf "%_[ ]*" (); read_stars (Star e1)
    with End_of_file | Scan_failure _ -> e1
  and read_atom() =
    try (scanf "%_[ ](" ();
         let r = try read_rex() with Exit -> Eps in
         try scanf "%_[ ])" (); r
         with End_of_file | Scan_failure _ -> failwith "missing )")
    with Scan_failure _ -> scanf "%1[^\n)|]"
      (fun s -> if s = "" then raise Exit else Char s.[0])
  in let r = try read_rex() with Exit -> failwith "empty regexp" in
     try scanf "%0c" (fun c ->
       if c = '\n' then (scanf "%_c" (); r)
       else failwith ("illegal character " ^ (Char.escaped c)))
     with End_of_file -> r


This document was generated using caml2html