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