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