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