Simplify Constructor -> Ctor.
[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) =
72   Cmdline.debug "%a: running goal %s %a"
73     Ast.string_loc loc name Ast.string_expr (Ast.EList (Ast.noloc, args));
74
75   (* This is the point where we evaluate the goal arguments.  We must
76    * do this before creating the new environment, because variables
77    * appearing in goal arguments don't refer to goal parameters.
78    *)
79   let args = List.map (Eval.evaluate_goal_arg env) args in
80
81   (* Create a new environment which maps the parameter names to
82    * the args.
83    *)
84   let env =
85     let params =
86       try List.combine params args
87       with Invalid_argument _ ->
88         failwithf "%a: calling goal ‘%s’ with wrong number of arguments"
89           Ast.string_loc loc name in
90     List.fold_left (fun env (k, v) -> Ast.Env.add k v env) env params in
91
92   (* Check all dependencies have been updated. *)
93   run_targets env deps;
94
95   (* Check if any target (ie. pattern) needs to be rebuilt.
96    * As with make, a goal with no targets is always run.
97    *)
98   let rebuild =
99     patterns = [] || List.exists (needs_rebuild env loc deps) patterns in
100
101   if rebuild then (
102     (* Run the code (if any). *)
103     (match code with
104      | None -> () (* No { CODE } section. *)
105
106      | Some code ->
107         (* Add some standard variables to the environment. *)
108         let expr_of_substs s = Ast.ESubsts (Ast.noloc, s) in
109         let expr_of_pattern = function
110           | Ast.PTactic (loc, tactic, targs) ->
111              Ast.ETacticCtor (loc, tactic, List.map expr_of_substs targs)
112         in
113         let pexprs = List.map expr_of_pattern patterns in
114         let env = Ast.Env.add "@" (Ast.EList (Ast.noloc, pexprs)) env in
115         let env = Ast.Env.add "<" (Ast.EList (Ast.noloc, deps)) env in
116         let env =
117           match deps with
118           | [] -> env
119           | d :: _ -> Ast.Env.add "^" d env in
120         let code = Eval.to_shell_script env loc code in
121         let code = "set -e\nset -x\n\n" ^ code in
122         let r = Sys.command code in
123         if r <> 0 then (
124           eprintf "*** goal ‘%s’ failed with exit code %d\n" name r;
125           exit 1
126         );
127
128         (* Check all targets were updated after the code was
129          * run (else it's an error).
130          *)
131         let pattern_still_needs_rebuild =
132           try Some (List.find (needs_rebuild env loc deps) patterns)
133           with Not_found -> None in
134         match pattern_still_needs_rebuild with
135         | None -> ()
136         | Some pattern ->
137            failwithf "%a: goal ‘%s’ ran successfully but it did not rebuild %a"
138              Ast.string_loc loc
139              name
140              Ast.string_pattern pattern
141     )
142   )
143
144 (* Return whether the target (pattern) needs to be rebuilt. *)
145 and needs_rebuild env loc deps pattern =
146   Cmdline.debug "%a: testing if %a needs rebuild"
147     Ast.string_loc loc Ast.string_pattern pattern;
148
149   match pattern with
150   | Ast.PTactic (loc, tactic, targs) ->
151      (* Look up the tactic. *)
152      let params, code = Ast.gettactic env loc tactic in
153
154      (* Resolve the targs down to constants.  Since needs_rebuild
155       * should be called with env containing the goal params, this
156       * should substitute any parameters in the tactic arguments.
157       *)
158      let targs = List.map (Ast.substitute env loc) targs in
159      let targs =
160        List.map (fun targ ->
161            Ast.EConstant (Ast.noloc, Ast.CString targ)) targs in
162
163      (* Create a new environment binding parameter names
164       * to tactic args.
165       *)
166      let env =
167        let params =
168          try List.combine params targs
169          with Invalid_argument _ ->
170            failwithf "%a: calling tactic ‘%s’ with wrong number of arguments"
171              Ast.string_loc loc tactic in
172        List.fold_left (fun env (k, v) -> Ast.Env.add k v env) env params in
173
174      (* Add some standard variables to the environment. *)
175      let env = Ast.Env.add "<" (Ast.EList (Ast.noloc, deps)) env in
176      let env =
177        match deps with
178        | [] -> env
179        | d :: _ -> Ast.Env.add "^" d env in
180      let code = Eval.to_shell_script env loc code in
181      let code = "set -e\nset -x\n\n" ^ code in
182      let r = Sys.command code in
183      if r = 99 (* means "needs rebuild" *) then true
184      else if r = 0 (* means "doesn't need rebuild" *) then false
185      else (
186        eprintf "*** tactic ‘%s’ failed with exit code %d\n" tactic r;
187        exit 1
188      )
189
190 (* Find the goal which matches the given tactic and run it.
191  * cargs is a list of parameters (all constants).
192  *)
193 and run_tactic env loc tactic cargs =
194   Cmdline.debug "%a: running tactic %s" Ast.string_loc loc tactic;
195
196   (* Find all goals in the environment.  Returns a list of (name, goal). *)
197   let goals =
198     let env = Ast.Env.bindings env in
199     filter_map
200       (function
201        | name, Ast.EGoalDefn (loc, goal) -> Some (name, goal)
202        | _ -> None) env in
203
204   (* Find all patterns.  Returns a list of (pattern, name, goal). *)
205   let patterns : (Ast.pattern * Ast.id * Ast.goal) list =
206     List.flatten
207       (List.map (fun (name, ((_, patterns, _, _) as goal)) ->
208            List.map (fun pattern -> (pattern, name, goal)) patterns) goals) in
209
210   (* Find any patterns (ie. tactics) which match the one we
211    * are searching for.  This returns a binding for the goal args,
212    * so we end up with a list of (pattern, name, goal, args).
213    *)
214   let patterns : (Ast.pattern * Ast.id * Ast.goal * Ast.expr list) list =
215     filter_map (
216       fun (pattern, name, ((params, _, _, _) as goal)) ->
217         match matching_pattern env loc tactic cargs pattern params with
218         | None -> None
219         | Some args -> Some (pattern, name, goal, args)
220     ) patterns in
221
222   match patterns with
223   | [] ->
224      (* There's no matching goal, but we don't need one if
225       * the tactic doesn't need to be rebuilt.
226       *)
227      let targs = List.map (function Ast.CString s -> [Ast.SString s]) cargs in
228      let p = Ast.PTactic (loc, tactic, targs) in
229      if needs_rebuild env loc [] p then (
230        let t = Ast.ETacticCtor (loc, tactic,
231                                 List.map (fun c -> Ast.EConstant (loc, c))
232                                   cargs) in
233        failwithf "%a: don't know how to build %a"
234          Ast.string_loc loc Ast.string_expr t
235      )
236
237   | goals ->
238      (* One or more goals match.  We run them all (although if
239       * one of them succeeds in rebuilding, it will cut short the rest).
240       *)
241      List.iter (
242        fun (_, name, goal, args) ->
243          run_goal env loc name args goal
244      ) goals
245
246 (* Test if pattern matches *tactic(cargs).  If it does
247  * then we return Some args where args is the arguments that must
248  * be passed to the matching goal.  The params parameter is
249  * the names of the parameters of that goal.
250  *)
251 and matching_pattern env loc tactic cargs pattern params =
252   match pattern with
253   | Ast.PTactic (loc, ttactic, targs)
254        when tactic <> ttactic ||
255             List.length cargs <> List.length targs ->
256      None (* Can't possibly match if tactic name or #args is different. *)
257   | Ast.PTactic (loc, ttactic, targs) ->
258      (* Do the args match with a possible params binding? *)
259      try Some (matching_params env loc params targs cargs)
260      with Not_found -> None
261
262 (* Return a possible binding.  For example the goal is:
263  *   goal compile (name) = "%name.o": "%name.c" {}
264  * which means that params = ["name"] and targs = ["%name.o"].
265  *
266  * If we are called with cargs = ["file1.o"], we would
267  * return ["file1"].
268  *
269  * On non-matching this raises Not_found.
270  *)
271 and matching_params env loc params targs cargs =
272   (* This is going to record the resulting binding. *)
273   let res = ref Ast.Env.empty in
274   List.iter2 (matching_param env loc params res) targs cargs;
275
276   (* Rearrange the result into goal parameter order.  Also this
277    * checks that every parameter got a binding.
278    *)
279   let res = !res in
280   List.map (
281     (* Allow the Not_found exception to escape if no binding for this param. *)
282     fun param -> Ast.Env.find param res
283   ) params
284
285 (* If targ = "%name.o" and carg = "file.o" then this would set
286  * name => "file" in !res.  If they don't match, raises Not_found.
287  *)
288 and matching_param env loc params res targ carg =
289   match carg with
290   | Ast.CString carg ->
291      (* Substitute any non parameters in targ from the environment. *)
292      let targ =
293        List.map (
294          function
295          | Ast.SString _ as s -> s
296          | Ast.SVar name ->
297             if not (List.mem name params) then (
298               try
299                 let expr = Ast.getvar env loc name in
300                 match Eval.to_constant env expr with
301                 | Ast.CString s -> Ast.SString s
302               with Failure _ -> raise Not_found
303             )
304             else
305               Ast.SVar name
306        ) targ in
307
308      (* Do the actual pattern matching.  Any remaining SVar elements
309       * must refer to goal parameters.
310       *)
311      let carg = ref carg in
312      let rec loop = function
313        | [] ->
314           (* End of targ, we must have matched all of carg. *)
315           if !carg <> "" then raise Not_found
316        | Ast.SString s :: rest ->
317           (* Does this match the first part of !carg? *)
318           let clen = String.length !carg in
319           let slen = String.length s in
320           if slen > clen || s <> String.sub !carg 0 slen then
321             raise Not_found;
322           (* Yes, so continue after the matching prefix. *)
323           carg := String.sub !carg slen (clen-slen);
324           loop rest
325        | Ast.SVar name :: Ast.SString s :: rest ->
326           (* This is a goal parameter.  Find s later in !carg. *)
327           let i = string_find !carg s in
328           if i = -1 then raise Not_found;
329           (* Set the binding in !res. *)
330           let r = Ast.EConstant (Ast.noloc,
331                                  Ast.CString (String.sub !carg 0 i)) in
332           res := Ast.Env.add name r !res;
333           (* Continue after the match. *)
334           let skip = i + String.length s in
335           carg := String.sub !carg skip (String.length !carg - skip);
336           loop rest
337        | Ast.SVar name :: [] ->
338           (* Matches the whole remainder of the string. *)
339           let r = Ast.EConstant (Ast.noloc, Ast.CString !carg) in
340           res := Ast.Env.add name r !res
341        | Ast.SVar x :: Ast.SVar y :: _ ->
342           (* TODO! We cannot match a target like "%x%y". *)
343           assert false
344      in
345      loop targ