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