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