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