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