166b8ab22586debccb1f787d4d52b7f042d4ddeb8John Bauman(*===----------------------------------------------------------------------===
266b8ab22586debccb1f787d4d52b7f042d4ddeb8John Bauman * Top-Level parsing and JIT Driver
366b8ab22586debccb1f787d4d52b7f042d4ddeb8John Bauman *===----------------------------------------------------------------------===*)
466b8ab22586debccb1f787d4d52b7f042d4ddeb8John Bauman
566b8ab22586debccb1f787d4d52b7f042d4ddeb8John Bauman(* top ::= definition | external | expression | ';' *)
666b8ab22586debccb1f787d4d52b7f042d4ddeb8John Baumanlet rec main_loop stream =
766b8ab22586debccb1f787d4d52b7f042d4ddeb8John Bauman  match Stream.peek stream with
866b8ab22586debccb1f787d4d52b7f042d4ddeb8John Bauman  | None -> ()
966b8ab22586debccb1f787d4d52b7f042d4ddeb8John Bauman
1066b8ab22586debccb1f787d4d52b7f042d4ddeb8John Bauman  (* ignore top-level semicolons. *)
1166b8ab22586debccb1f787d4d52b7f042d4ddeb8John Bauman  | Some (Token.Kwd ';') ->
1266b8ab22586debccb1f787d4d52b7f042d4ddeb8John Bauman      Stream.junk stream;
1366b8ab22586debccb1f787d4d52b7f042d4ddeb8John Bauman      main_loop stream
1466b8ab22586debccb1f787d4d52b7f042d4ddeb8John Bauman
1566b8ab22586debccb1f787d4d52b7f042d4ddeb8John Bauman  | Some token ->
1666b8ab22586debccb1f787d4d52b7f042d4ddeb8John Bauman      begin
1766b8ab22586debccb1f787d4d52b7f042d4ddeb8John Bauman        try match token with
1866b8ab22586debccb1f787d4d52b7f042d4ddeb8John Bauman        | Token.Def ->
1966b8ab22586debccb1f787d4d52b7f042d4ddeb8John Bauman            ignore(Parser.parse_definition stream);
2066b8ab22586debccb1f787d4d52b7f042d4ddeb8John Bauman            print_endline "parsed a function definition.";
2166b8ab22586debccb1f787d4d52b7f042d4ddeb8John Bauman        | Token.Extern ->
2266b8ab22586debccb1f787d4d52b7f042d4ddeb8John Bauman            ignore(Parser.parse_extern stream);
2366b8ab22586debccb1f787d4d52b7f042d4ddeb8John Bauman            print_endline "parsed an extern.";
2466b8ab22586debccb1f787d4d52b7f042d4ddeb8John Bauman        | _ ->
2566b8ab22586debccb1f787d4d52b7f042d4ddeb8John Bauman            (* Evaluate a top-level expression into an anonymous function. *)
2666b8ab22586debccb1f787d4d52b7f042d4ddeb8John Bauman            ignore(Parser.parse_toplevel stream);
2766b8ab22586debccb1f787d4d52b7f042d4ddeb8John Bauman            print_endline "parsed a top-level expr";
2866b8ab22586debccb1f787d4d52b7f042d4ddeb8John Bauman        with Stream.Error s ->
2966b8ab22586debccb1f787d4d52b7f042d4ddeb8John Bauman          (* Skip token for error recovery. *)
3066b8ab22586debccb1f787d4d52b7f042d4ddeb8John Bauman          Stream.junk stream;
3166b8ab22586debccb1f787d4d52b7f042d4ddeb8John Bauman          print_endline s;
3266b8ab22586debccb1f787d4d52b7f042d4ddeb8John Bauman      end;
3366b8ab22586debccb1f787d4d52b7f042d4ddeb8John Bauman      print_string "ready> "; flush stdout;
3466b8ab22586debccb1f787d4d52b7f042d4ddeb8John Bauman      main_loop stream
35