xref: /aosp_15_r20/external/llvm/examples/OCaml-Kaleidoscope/Chapter2/toplevel.ml (revision 9880d6810fe72a1726cb53787c6711e909410d58)
1*9880d681SAndroid Build Coastguard Worker(*===----------------------------------------------------------------------===
2*9880d681SAndroid Build Coastguard Worker * Top-Level parsing and JIT Driver
3*9880d681SAndroid Build Coastguard Worker *===----------------------------------------------------------------------===*)
4*9880d681SAndroid Build Coastguard Worker
5*9880d681SAndroid Build Coastguard Worker(* top ::= definition | external | expression | ';' *)
6*9880d681SAndroid Build Coastguard Workerlet rec main_loop stream =
7*9880d681SAndroid Build Coastguard Worker  match Stream.peek stream with
8*9880d681SAndroid Build Coastguard Worker  | None -> ()
9*9880d681SAndroid Build Coastguard Worker
10*9880d681SAndroid Build Coastguard Worker  (* ignore top-level semicolons. *)
11*9880d681SAndroid Build Coastguard Worker  | Some (Token.Kwd ';') ->
12*9880d681SAndroid Build Coastguard Worker      Stream.junk stream;
13*9880d681SAndroid Build Coastguard Worker      main_loop stream
14*9880d681SAndroid Build Coastguard Worker
15*9880d681SAndroid Build Coastguard Worker  | Some token ->
16*9880d681SAndroid Build Coastguard Worker      begin
17*9880d681SAndroid Build Coastguard Worker        try match token with
18*9880d681SAndroid Build Coastguard Worker        | Token.Def ->
19*9880d681SAndroid Build Coastguard Worker            ignore(Parser.parse_definition stream);
20*9880d681SAndroid Build Coastguard Worker            print_endline "parsed a function definition.";
21*9880d681SAndroid Build Coastguard Worker        | Token.Extern ->
22*9880d681SAndroid Build Coastguard Worker            ignore(Parser.parse_extern stream);
23*9880d681SAndroid Build Coastguard Worker            print_endline "parsed an extern.";
24*9880d681SAndroid Build Coastguard Worker        | _ ->
25*9880d681SAndroid Build Coastguard Worker            (* Evaluate a top-level expression into an anonymous function. *)
26*9880d681SAndroid Build Coastguard Worker            ignore(Parser.parse_toplevel stream);
27*9880d681SAndroid Build Coastguard Worker            print_endline "parsed a top-level expr";
28*9880d681SAndroid Build Coastguard Worker        with Stream.Error s ->
29*9880d681SAndroid Build Coastguard Worker          (* Skip token for error recovery. *)
30*9880d681SAndroid Build Coastguard Worker          Stream.junk stream;
31*9880d681SAndroid Build Coastguard Worker          print_endline s;
32*9880d681SAndroid Build Coastguard Worker      end;
33*9880d681SAndroid Build Coastguard Worker      print_string "ready> "; flush stdout;
34*9880d681SAndroid Build Coastguard Worker      main_loop stream
35