jobs: Introduce stop_all function to stop job submission on error.
[goals.git] / src / run.ml
1 (* Goalfile run
2  * Copyright (C) 2019 Richard W.M. Jones
3  * Copyright (C) 2019 Red Hat Inc.
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License along
16  * with this program; if not, write to the Free Software Foundation, Inc.,
17  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18  *)
19
20 open Printf
21
22 open Utils
23
24 (* Goals uses the goal (name + parameters) as the key to
25  * ensure you cannot have two jobs running at the same time
26  * which would interfere with each other by trying to build
27  * the same target.
28  *)
29 module Jobs = Jobs.Make (
30   struct
31     type t = string * Ast.expr list
32     let compare = compare
33     let to_string (name, args) =
34       sprintf "%s (%s)" name
35         (String.concat ", " (List.map (Ast.string_expr ()) args))
36   end
37 )
38
39 let stop_all = Jobs.stop_all
40
41 (* Starts the target expressions running and waits for them to complete. *)
42 let rec run_targets_to_completion env exprs =
43   let group = Jobs.new_group () in
44   run_targets group env exprs;
45   Jobs.wait group
46
47 (* This starts the targets, adding them to the jobs group, but does not
48  * wait for them to complete.
49  *)
50 and run_targets group env exprs =
51   List.iter (run_target group env) exprs
52
53 (* This starts a single target, adding the (usually single but can
54  * be multiple) jobs to the jobs group.  It does not wait for the
55  * jobs to complete.
56  *)
57 and run_target group env = function
58   | Ast.EGoalDefn _ | Ast.EFuncDefn _ | Ast.ETacticDefn _ -> assert false
59
60   (* Call a goal or function. *)
61   | Ast.ECall (loc, name, args) ->
62      let expr = Ast.getvar env loc name in
63      (match expr with
64       | Ast.EGoalDefn (_, goal) ->
65          let key = name, args in
66          Jobs.start group key (
67            fun () -> run_goal env loc name args goal []
68          )
69       | Ast.EFuncDefn (_, func) ->
70          let expr = Eval.call_function env loc name args func in
71          run_target group env expr
72       | _ ->
73          failwithf "%a: tried to call ‘%s’ which is not a goal or a function"
74            Ast.string_loc loc name
75      )
76
77   (* Call a tactic. *)
78   | Ast.ETacticCtor (loc, name, args) ->
79      (* All parameters of tactics must be simple constant expressions
80       * (strings, in future booleans, numbers, etc).
81       *)
82      let args = List.map (Eval.to_constant env) args in
83      run_tactic group env loc name args
84
85   (* If this is a goal then it's the same as calling goal().  If not
86    * then look up the variable and substitute it.
87    *)
88   | Ast.EVar (loc, name) ->
89      let expr = Ast.getvar env loc name in
90      (match expr with
91       | Ast.EGoalDefn (loc, ([], _, _, _)) ->
92          run_target group env (Ast.ECall (loc, name, []))
93       | EGoalDefn _ ->
94          failwithf "%a: cannot call %s() since this goal has parameters"
95            Ast.string_loc loc name
96       | _ ->
97          run_target group env expr
98      )
99
100   (* Lists are inlined when found as a target. *)
101   | Ast.EList (loc, exprs) ->
102      run_targets group env exprs
103
104   (* A string (with or without substitutions) implies *file(filename). *)
105   | Ast.ESubsts (loc, str) ->
106      let str = Eval.substitute env loc str in
107      run_tactic group env loc "*file" [Ast.CString str]
108
109   | Ast.EConstant (loc, c) ->
110      run_tactic group env loc "*file" [c]
111
112 (* Run a goal by name. *)
113 and run_goal env loc name args (params, patterns, deps, code) extra_deps =
114   (* This is used to print the goal in debug and error messages only. *)
115   let debug_goal =
116     sprintf "%s (%s)" name
117       (String.concat ", " (List.map (Ast.string_expr ()) args)) in
118   Cmdline.debug "%a: running goal %s" Ast.string_loc loc debug_goal;
119
120   (* This is the point where we evaluate the goal arguments.  We must
121    * do this before creating the new environment, because variables
122    * appearing in goal arguments don't refer to goal parameters.
123    *)
124   let args = List.map (Eval.evaluate_goal_arg env) args in
125
126   (* Create a new environment which maps the parameter names to
127    * the args.
128    *)
129   let env =
130     let params =
131       try List.combine params args
132       with Invalid_argument _ ->
133         failwithf "%a: calling goal %s with wrong number of arguments, expecting %d args but got %d args"
134           Ast.string_loc loc debug_goal
135           (List.length params) (List.length args) in
136     List.fold_left (fun env (k, v) -> Ast.Env.add k v env) env params in
137
138   (* Check all dependencies have been updated.  We must wait
139    * for these to complete before we can continue.
140    *)
141   run_targets_to_completion env (deps @ extra_deps);
142
143   (* Check if any target (ie. pattern) needs to be rebuilt.
144    * As with make, a goal with no targets is always run.
145    *)
146   let rebuild =
147     patterns = [] ||
148     List.exists (needs_rebuild env loc deps extra_deps) patterns in
149
150   if rebuild then (
151     (* Run the code (if any). *)
152     (match code with
153      | None -> () (* No { CODE } section. *)
154
155      | Some code ->
156         (* Add some standard variables to the environment. *)
157         let expr_of_substs s = Ast.ESubsts (Ast.noloc, s) in
158         let expr_of_pattern = function
159           | Ast.PTactic (loc, tactic, targs) ->
160              Ast.ETacticCtor (loc, tactic, List.map expr_of_substs targs)
161         in
162         let pexprs = List.map expr_of_pattern patterns in
163         let env = Ast.Env.add "@" (Ast.EList (Ast.noloc, pexprs)) env in
164         let env = Ast.Env.add "<" (Ast.EList (Ast.noloc, deps)) env in
165         let env =
166           (* NB: extra_deps are not added to %^ *)
167           match deps with
168           | [] -> env
169           | d :: _ -> Ast.Env.add "^" d env in
170         let r = Eval.run_code env loc code in
171         if r <> 0 then (
172           eprintf "*** goal ‘%s’ failed with exit code %d\n" name r;
173           exit 1
174         );
175
176         (* Check all targets were updated after the code was
177          * run (else it's an error).
178          *)
179         let pattern_still_needs_rebuild =
180           try
181             Some (List.find (needs_rebuild env loc deps extra_deps) patterns)
182           with
183             Not_found -> None in
184         match pattern_still_needs_rebuild with
185         | None -> ()
186         | Some pattern ->
187            failwithf "%a: goal %s ran successfully but it did not rebuild %a"
188              Ast.string_loc loc debug_goal Ast.string_pattern pattern
189     )
190   )
191
192 (* Return whether the target (pattern) needs to be rebuilt. *)
193 and needs_rebuild env loc deps extra_deps pattern =
194   Cmdline.debug "%a: testing if %a needs rebuild"
195     Ast.string_loc loc Ast.string_pattern pattern;
196
197   match pattern with
198   | Ast.PTactic (loc, tactic, targs) ->
199      (* Look up the tactic. *)
200      let params, code = Ast.gettactic env loc tactic in
201
202      (* Resolve the targs down to constants.  Since needs_rebuild
203       * should be called with env containing the goal params, this
204       * should substitute any parameters in the tactic arguments.
205       *)
206      let targs = List.map (Eval.substitute env loc) targs in
207      let targs =
208        List.map (fun targ ->
209            Ast.EConstant (Ast.noloc, Ast.CString targ)) targs in
210
211      (* Create a new environment binding parameter names
212       * to tactic args.
213       *)
214      let env =
215        let params =
216          try List.combine params targs
217          with Invalid_argument _ ->
218            failwithf "%a: calling tactic ‘%s’ with wrong number of arguments"
219              Ast.string_loc loc tactic in
220        List.fold_left (fun env (k, v) -> Ast.Env.add k v env) env params in
221
222      (* Add some standard variables to the environment. *)
223      let env = Ast.Env.add "<" (Ast.EList (Ast.noloc, deps)) env in
224      let env =
225        (* NB: extra_deps are not added to %^ *)
226        match deps with
227        | [] -> env
228        | d :: _ -> Ast.Env.add "^" d env in
229      let r = Eval.run_code env loc code in
230      if r = 99 (* means "needs rebuild" *) then true
231      else if r = 0 (* means "doesn't need rebuild" *) then false
232      else (
233        eprintf "*** tactic ‘%s’ failed with exit code %d\n" tactic r;
234        exit 1
235      )
236
237 (* Find the goal which matches the given tactic and start it.
238  * cargs is a list of parameters (all constants).
239  *)
240 and run_tactic group env loc tactic cargs =
241   (* This is used to print the tactic in debug and error messages only. *)
242   let debug_tactic =
243     Ast.string_expr ()
244       (Ast.ETacticCtor (loc, tactic,
245                         List.map (fun c -> Ast.EConstant (loc, c)) cargs)) in
246   Cmdline.debug "%a: running tactic %s" Ast.string_loc loc debug_tactic;
247
248   (* Find all goals in the environment.  Returns a list of (name, goal). *)
249   let goals =
250     let env = Ast.Env.bindings env in
251     filter_map
252       (function
253        | name, Ast.EGoalDefn (loc, goal) -> Some (name, goal)
254        | _ -> None) env in
255
256   (* Find all patterns.  Returns a list of (pattern, name, goal). *)
257   let patterns : (Ast.pattern * Ast.id * Ast.goal) list =
258     List.flatten
259       (List.map (fun (name, ((_, patterns, _, _) as goal)) ->
260            List.map (fun pattern -> (pattern, name, goal)) patterns) goals) in
261
262   (* Find any patterns (ie. tactics) which match the one we
263    * are searching for.  This returns a binding for the goal args,
264    * so we end up with a list of (pattern, name, goal, args).
265    *)
266   let patterns : (Ast.pattern * Ast.id * Ast.goal * Ast.expr list) list =
267     filter_map (
268       fun (pattern, name, ((params, _, _, _) as goal)) ->
269         match matching_pattern env loc tactic cargs pattern params with
270         | None -> None
271         | Some args -> Some (pattern, name, goal, args)
272     ) patterns in
273
274   match patterns with
275   | [] ->
276      (* There's no matching goal, but we don't need one if
277       * the tactic doesn't need to be rebuilt.
278       *)
279      let targs = List.map (function Ast.CString s -> [Ast.SString s]) cargs in
280      let p = Ast.PTactic (loc, tactic, targs) in
281      if needs_rebuild env loc [] [] p then
282        failwithf "%a: don't know how to build %s"
283          Ast.string_loc loc debug_tactic
284
285   | [_, name, goal, args] ->
286      (* Single goal matches, run it. *)
287      let key = name, args in
288      Jobs.start group key (
289        fun () -> run_goal env loc name args goal []
290      )
291
292   | goals ->
293      (* Two or more goals match.  Only one must have a CODE section,
294       * and we combine the dependencies into a "supergoal".
295       *)
296      let with_code, without_code =
297        List.partition (
298          fun (_, _, (_, _, _, code), _) -> code <> None
299        ) goals in
300
301      let (_, name, goal, args), extra_deps =
302        match with_code with
303        | [g] ->
304           let extra_deps =
305             List.flatten (
306               List.map (fun (_, _, (_, _, deps, _), _) -> deps) without_code
307             ) in
308           (g, extra_deps)
309
310        | [] ->
311           (* This is OK, it means we'll rebuild all dependencies
312            * but there is no code to run.  Pick the first goal
313            * without code and the dependencies from the other goals.
314            *)
315           let g = List.hd without_code in
316           let extra_deps =
317             List.flatten (
318               List.map (fun (_, _, (_, _, deps, _), _) -> deps)
319                 (List.tl without_code)
320             ) in
321           (g, extra_deps)
322
323        | _ :: _ ->
324           failwithf "%a: multiple goals found which match tactic %s, but more than one of these goals have {code} sections which is not allowed"
325             Ast.string_loc loc debug_tactic in
326
327      let key = name, args in
328      Jobs.start group key (fun () ->
329        run_goal env loc name args goal extra_deps
330      )
331
332 (* Test if pattern matches *tactic(cargs).  If it does
333  * then we return Some args where args is the arguments that must
334  * be passed to the matching goal.  The params parameter is
335  * the names of the parameters of that goal.
336  *)
337 and matching_pattern env loc tactic cargs pattern params =
338   match pattern with
339   | Ast.PTactic (loc, ttactic, targs)
340        when tactic <> ttactic ||
341             List.length cargs <> List.length targs ->
342      None (* Can't possibly match if tactic name or #args is different. *)
343   | Ast.PTactic (loc, ttactic, targs) ->
344      (* Do the args match with a possible params binding? *)
345      try Some (matching_params env loc params targs cargs)
346      with Not_found -> None
347
348 (* Return a possible binding.  For example the goal is:
349  *   goal compile (name) = "%name.o": "%name.c" {}
350  * which means that params = ["name"] and targs = ["%name.o"].
351  *
352  * If we are called with cargs = ["file1.o"], we would
353  * return ["file1"].
354  *
355  * On non-matching this raises Not_found.
356  *)
357 and matching_params env loc params targs cargs =
358   (* This is going to record the resulting binding. *)
359   let res = ref Ast.Env.empty in
360   List.iter2 (matching_param env loc params res) targs cargs;
361
362   (* Rearrange the result into goal parameter order.  Also this
363    * checks that every parameter got a binding.
364    *)
365   let res = !res in
366   List.map (
367     (* Allow the Not_found exception to escape if no binding for this param. *)
368     fun param -> Ast.Env.find param res
369   ) params
370
371 (* If targ = "%name.o" and carg = "file.o" then this would set
372  * name => "file" in !res.  If they don't match, raises Not_found.
373  *)
374 and matching_param env loc params res targ carg =
375   match carg with
376   | Ast.CString carg ->
377      (* Substitute any non parameters in targ from the environment. *)
378      let targ =
379        List.map (
380          function
381          | Ast.SString _ as s -> s
382          | Ast.SVar name ->
383             if not (List.mem name params) then (
384               try
385                 let expr = Ast.getvar env loc name in
386                 match Eval.to_constant env expr with
387                 | Ast.CString s -> Ast.SString s
388               with Failure _ -> raise Not_found
389             )
390             else
391               Ast.SVar name
392        ) targ in
393
394      (* Do the actual pattern matching.  Any remaining SVar elements
395       * must refer to goal parameters.
396       *)
397      let carg = ref carg in
398      let rec loop = function
399        | [] ->
400           (* End of targ, we must have matched all of carg. *)
401           if !carg <> "" then raise Not_found
402        | Ast.SString s :: rest ->
403           (* Does this match the first part of !carg? *)
404           let clen = String.length !carg in
405           let slen = String.length s in
406           if slen > clen || s <> String.sub !carg 0 slen then
407             raise Not_found;
408           (* Yes, so continue after the matching prefix. *)
409           carg := String.sub !carg slen (clen-slen);
410           loop rest
411        | Ast.SVar name :: Ast.SString s :: rest ->
412           (* This is a goal parameter.  Find s later in !carg. *)
413           let i = string_find !carg s in
414           if i = -1 then raise Not_found;
415           (* Set the binding in !res. *)
416           let r = Ast.EConstant (Ast.noloc,
417                                  Ast.CString (String.sub !carg 0 i)) in
418           res := Ast.Env.add name r !res;
419           (* Continue after the match. *)
420           let skip = i + String.length s in
421           carg := String.sub !carg skip (String.length !carg - skip);
422           loop rest
423        | Ast.SVar name :: [] ->
424           (* Matches the whole remainder of the string. *)
425           let r = Ast.EConstant (Ast.noloc, Ast.CString !carg) in
426           res := Ast.Env.add name r !res
427        | Ast.SVar x :: Ast.SVar y :: _ ->
428           (* TODO! We cannot match a target like "%x%y". *)
429           assert false
430      in
431      loop targ