src/Pure/ML/ml_compiler.ML
author Walther Neuper <walther.neuper@jku.at>
Thu, 17 Dec 2020 09:10:30 +0100
changeset 60134 85ce6e27e130
parent 60133 83003c700845
child 60139 c3cb65678c47
permissions -rw-r--r--
step 4.2: writeln at calling Output.report uncover some of proof handling
     1 (*  Title:      Pure/ML/ml_compiler.ML
     2     Author:     Makarius
     3 
     4 Runtime compilation and evaluation.
     5 *)
     6 
     7 signature ML_COMPILER =
     8 sig
     9   type flags =
    10     {environment: string, redirect: bool, verbose: bool,
    11       debug: bool option, writeln: string -> unit, warning: string -> unit}
    12   val debug_flags: bool option -> flags
    13   val flags: flags
    14   val verbose: bool -> flags -> flags
    15   val eval: flags -> Position.T -> ML_Lex.token list -> unit
    16 end;
    17 
    18 structure ML_Compiler: ML_COMPILER =
    19 struct
    20 
    21 (* flags *)
    22 
    23 type flags =
    24   {environment: string, redirect: bool, verbose: bool,
    25     debug: bool option, writeln: string -> unit, warning: string -> unit};
    26 
    27 fun debug_flags opt_debug : flags =
    28   {environment = "", redirect = false, verbose = false,
    29     debug = opt_debug, writeln = writeln, warning = warning};
    30 
    31 val flags = debug_flags NONE;
    32 
    33 fun verbose b (flags: flags) =
    34   {environment = #environment flags, redirect = #redirect flags, verbose = b,
    35     debug = #debug flags, writeln = #writeln flags, warning = #warning flags};
    36 
    37 
    38 (* parse trees *)
    39 
    40 fun breakpoint_position loc =
    41   let val pos = Position.no_range_position (Exn_Properties.position_of_polyml_location loc) in
    42     (case Position.offset_of pos of
    43       NONE => pos
    44     | SOME 1 => pos
    45     | SOME j =>
    46         Position.properties_of pos
    47         |> Properties.put (Markup.offsetN, Value.print_int (j - 1))
    48         |> Position.of_properties)
    49   end;
    50 
    51 fun report_parse_tree redirect depth name_space parse_tree =
    52   let
    53     val is_visible =
    54       (case Context.get_generic_context () of
    55         SOME context => Context_Position.is_visible_generic context
    56       | NONE => true);
    57     fun is_reported pos = is_visible andalso Position.is_reported pos;
    58 
    59 
    60     (* syntax reports *)
    61 
    62     fun reported_types loc types =
    63       let val pos = Exn_Properties.position_of_polyml_location loc in
    64         is_reported pos ?
    65           let
    66             val xml =
    67               PolyML.NameSpace.Values.printType (types, depth, SOME name_space)
    68               |> Pretty.from_polyml |> Pretty.string_of
    69               |> Output.output |> YXML.parse_body;
    70           in cons (pos, fn () => Markup.ML_typing, fn () => YXML.string_of_body xml) end
    71       end;
    72 
    73     fun reported_entity kind loc decl =
    74       let
    75         val pos = Exn_Properties.position_of_polyml_location loc;
    76         val def_pos = Exn_Properties.position_of_polyml_location decl;
    77       in
    78         (is_reported pos andalso pos <> def_pos) ?
    79           let
    80             fun markup () =
    81               (Markup.entityN, (Markup.kindN, kind) :: Position.def_properties_of def_pos);
    82           in cons (pos, markup, fn () => "") end
    83       end;
    84 
    85     fun reported_entity_id def id loc =
    86       let
    87         val pos = Exn_Properties.position_of_polyml_location loc;
    88       in
    89         (is_reported pos andalso id <> 0) ?
    90           let
    91             fun markup () =
    92               (Markup.entityN, [(if def then Markup.defN else Markup.refN, Value.print_int id)]);
    93           in cons (pos, markup, fn () => "") end
    94       end;
    95 
    96     fun reported_completions loc names =
    97       let val pos = Exn_Properties.position_of_polyml_location loc in
    98         if is_reported pos andalso not (null names) then
    99           let
   100             val completion = Completion.names pos (map (fn a => (a, ("ML", a))) names);
   101             val xml = Completion.encode completion;
   102           in cons (pos, fn () => Markup.completion, fn () => YXML.string_of_body xml) end
   103         else I
   104       end;
   105 
   106     fun reported _ (PolyML.PTnextSibling tree) = reported_tree (tree ())
   107       | reported _ (PolyML.PTfirstChild tree) = reported_tree (tree ())
   108       | reported loc (PolyML.PTdefId id) = reported_entity_id true (FixedInt.toLarge id) loc
   109       | reported loc (PolyML.PTrefId id) = reported_entity_id false (FixedInt.toLarge id) loc
   110       | reported loc (PolyML.PTtype types) = reported_types loc types
   111       | reported loc (PolyML.PTdeclaredAt decl) = reported_entity Markup.ML_defN loc decl
   112       | reported loc (PolyML.PTcompletions names) = reported_completions loc names
   113       | reported _ _ = I
   114     and reported_tree (loc, props) = fold (reported loc) props;
   115 
   116     val persistent_reports = reported_tree parse_tree [];
   117 
   118     fun output () =
   119       persistent_reports
   120       |> map (fn (pos, markup, text) => Position.reported_text pos (markup ()) (text ()))
   121       |> 
   122         ((** )@{print} {a = "### ML_Compiler.output"};( *..NOT yet available 2 *)
   123          (**)writeln "### ML_Compiler.output";(**)
   124           Output.report);
   125     val _ =
   126       if not (null persistent_reports) andalso redirect andalso Future.enabled ()
   127       then
   128         Execution.print
   129           {name = "ML_Compiler.report", pos = Position.thread_data (), pri = Task_Queue.urgent_pri}
   130           output
   131       else output ();
   132 
   133 
   134     (* breakpoints *)
   135 
   136     fun breakpoints _ (PolyML.PTnextSibling tree) = breakpoints_tree (tree ())
   137       | breakpoints _ (PolyML.PTfirstChild tree) = breakpoints_tree (tree ())
   138       | breakpoints loc (PolyML.PTbreakPoint b) =
   139           let val pos = breakpoint_position loc in
   140             if is_reported pos then
   141               let val id = serial ();
   142               in cons ((pos, Markup.ML_breakpoint id), (id, (b, pos))) end
   143             else I
   144           end
   145       | breakpoints _ _ = I
   146     and breakpoints_tree (loc, props) = fold (breakpoints loc) props;
   147 
   148     val all_breakpoints = rev (breakpoints_tree parse_tree []);
   149     val _ = Position.reports (map #1 all_breakpoints);
   150  in map (fn (_, (id, (b, pos))) => (id, (b, Position.dest pos))) all_breakpoints end;
   151 
   152 
   153 (* eval ML source tokens *)
   154 
   155 fun eval (flags: flags) pos toks =
   156   let
   157     val opt_context = Context.get_generic_context ();
   158 
   159     val env as {debug, name_space, add_breakpoints} =
   160       (case (ML_Recursive.get (), #environment flags <> "") of
   161         (SOME env, false) => env
   162       | _ =>
   163          {debug =
   164             (case #debug flags of
   165               SOME debug => debug
   166             | NONE => ML_Options.debugger_enabled opt_context),
   167           name_space = ML_Env.make_name_space (#environment flags),
   168           add_breakpoints = ML_Env.add_breakpoints});
   169 
   170 
   171     (* input *)
   172 
   173     val location_props = op ^ (YXML.output_markup (":", #props (Position.dest pos)));
   174 
   175     val {explode_token, ...} = ML_Env.operations opt_context (#environment flags);
   176     fun token_content tok = if ML_Lex.is_comment tok then NONE else SOME (`explode_token tok);
   177 
   178     val input_buffer =
   179       Unsynchronized.ref (map_filter token_content toks);
   180 
   181     fun get () =
   182       (case ! input_buffer of
   183         (c :: cs, tok) :: rest => (input_buffer := (cs, tok) :: rest; SOME c)
   184       | ([], _) :: rest => (input_buffer := rest; SOME #" ")
   185       | [] => NONE);
   186 
   187     fun get_pos () =
   188       (case ! input_buffer of
   189         (_ :: _, tok) :: _ => ML_Lex.pos_of tok
   190       | ([], tok) :: _ => ML_Lex.end_pos_of tok
   191       | [] => Position.none);
   192 
   193 
   194     (* output *)
   195 
   196     val writeln_buffer = Unsynchronized.ref Buffer.empty;
   197     fun write s = Unsynchronized.change writeln_buffer (Buffer.add s);
   198     fun output_writeln () = #writeln flags (trim_line (Buffer.content (! writeln_buffer)));
   199 
   200     val warnings = Unsynchronized.ref ([]: string list);
   201     fun warn msg = Unsynchronized.change warnings (cons msg);
   202     fun output_warnings () = List.app (#warning flags) (rev (! warnings));
   203 
   204     val error_buffer = Unsynchronized.ref Buffer.empty;
   205     fun err msg = Unsynchronized.change error_buffer (Buffer.add msg #> Buffer.add "\n");
   206     fun flush_error () = #writeln flags (trim_line (Buffer.content (! error_buffer)));
   207     fun raise_error msg = error (trim_line (Buffer.content (Buffer.add msg (! error_buffer))));
   208 
   209     fun message {message = msg, hard, location = loc, context = _} =
   210       let
   211         val pos = Exn_Properties.position_of_polyml_location loc;
   212         val txt =
   213           (if hard then "ML error" else "ML warning") ^ Position.here pos ^ ":\n" ^
   214           Pretty.string_of (Pretty.from_polyml msg);
   215       in if hard then err txt else warn txt end;
   216 
   217 
   218     (* results *)
   219 
   220     val depth = FixedInt.fromInt (ML_Print_Depth.get_print_depth ());
   221 
   222     fun apply_result {fixes, types, signatures, structures, functors, values} =
   223       let
   224         fun display disp x =
   225           if depth > 0 then
   226             (write (disp x |> Pretty.from_polyml |> Pretty.string_of); write "\n")
   227           else ();
   228 
   229         fun apply_fix (a, b) =
   230           (#enterFix name_space (a, b);
   231             display PolyML.NameSpace.Infixes.print b);
   232         fun apply_type (a, b) =
   233           (#enterType name_space (a, b);
   234             display PolyML.NameSpace.TypeConstrs.print (b, depth, SOME name_space));
   235         fun apply_sig (a, b) =
   236           (#enterSig name_space (a, b);
   237             display PolyML.NameSpace.Signatures.print (b, depth, SOME name_space));
   238         fun apply_struct (a, b) =
   239           (#enterStruct name_space (a, b);
   240             display PolyML.NameSpace.Structures.print (b, depth, SOME name_space));
   241         fun apply_funct (a, b) =
   242           (#enterFunct name_space (a, b);
   243             display PolyML.NameSpace.Functors.print (b, depth, SOME name_space));
   244         fun apply_val (a, b) =
   245           (#enterVal name_space (a, b);
   246             display PolyML.NameSpace.Values.printWithType (b, depth, SOME name_space));
   247       in
   248         List.app apply_fix fixes;
   249         List.app apply_type types;
   250         List.app apply_sig signatures;
   251         List.app apply_struct structures;
   252         List.app apply_funct functors;
   253         List.app apply_val values
   254       end;
   255 
   256     exception STATIC_ERRORS of unit;
   257 
   258     fun result_fun (phase1, phase2) () =
   259      ((case phase1 of
   260         NONE => ()
   261       | SOME parse_tree =>
   262           add_breakpoints (report_parse_tree (#redirect flags) depth name_space parse_tree));
   263       (case phase2 of
   264         NONE => raise STATIC_ERRORS ()
   265       | SOME code =>
   266           apply_result
   267             ((code
   268               |> Runtime.debugging opt_context
   269               |> Runtime.toplevel_error (err o Runtime.exn_message)) ())));
   270 
   271 
   272     (* compiler invocation *)
   273 
   274     val parameters =
   275      [PolyML.Compiler.CPOutStream write,
   276       PolyML.Compiler.CPNameSpace name_space,
   277       PolyML.Compiler.CPErrorMessageProc message,
   278       PolyML.Compiler.CPLineNo (the_default 0 o Position.line_of o get_pos),
   279       PolyML.Compiler.CPLineOffset (the_default 0 o Position.offset_of o get_pos),
   280       PolyML.Compiler.CPFileName location_props,
   281       PolyML.Compiler.CPPrintDepth ML_Print_Depth.get_print_depth,
   282       PolyML.Compiler.CPCompilerResultFun result_fun,
   283       PolyML.Compiler.CPPrintInAlphabeticalOrder false,
   284       PolyML.Compiler.CPDebug debug,
   285       PolyML.Compiler.CPBindingSeq serial];
   286 
   287     val _ =
   288       (while not (List.null (! input_buffer)) do
   289         ML_Recursive.recursive env (fn () => PolyML.compiler (get, parameters) ()))
   290       handle exn =>
   291         if Exn.is_interrupt exn then Exn.reraise exn
   292         else
   293           let
   294             val exn_msg =
   295               (case exn of
   296                 STATIC_ERRORS () => ""
   297               | Runtime.TOPLEVEL_ERROR => ""
   298               | _ => "Exception- " ^ Pretty.string_of (Runtime.pretty_exn exn) ^ " raised");
   299             val _ = output_warnings ();
   300             val _ = output_writeln ();
   301           in raise_error exn_msg end;
   302   in
   303     if #verbose flags then (output_warnings (); flush_error (); output_writeln ())
   304     else ()
   305   end;
   306 
   307 end;