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