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