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