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