61153219fa0e4806c13fb3ae875d0ec216adeb77
[goals.git] / src / eval.ml
1 (* Goalfile Abstract Syntax Tree
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 pure_cache = Hashtbl.create 13
25
26 let rec to_constant env = function
27   | Ast.EConstant (loc, c) -> c
28
29   | EVar (loc, name) ->
30      let expr = Ast.getvar env loc name in
31      to_constant env expr
32
33   | ESubsts (loc, str) ->
34      CString (substitute env loc str)
35
36   | EList (loc, _) ->
37      failwithf "%a: list found where constant expression expected"
38        Ast.string_loc loc
39
40   | ECall (loc, name, args) ->
41      let expr = Ast.getvar env loc name in
42      (match expr with
43       | EGoalDefn _ ->
44          (* Goals don't return anything so they cannot be used in
45           * constant expressions.  Use a function instead.
46           *)
47          failwithf "%a: cannot use goal call ‘%s’ in shell expansion"
48            Ast.string_loc loc name
49
50       | EFuncDefn (loc, func) ->
51          to_constant env (call_function env loc name args func)
52
53       | _ ->
54          failwithf "%a: cannot use ‘%s’ in constant expression"
55            Ast.string_loc loc name
56      )
57
58   | ETacticCtor (loc, name, _) ->
59      failwithf "%a: cannot use tactic ‘%s’ in constant expression"
60        Ast.string_loc loc name
61
62   | EGoalDefn (loc, _) ->
63      failwithf "%a: cannot use goal in constant expression"
64        Ast.string_loc loc
65
66   | EFuncDefn (loc, _) ->
67      failwithf "%a: cannot use function in constant expression"
68        Ast.string_loc loc
69
70   | ETacticDefn (loc, _) ->
71      failwithf "%a: cannot use tactic in constant expression"
72        Ast.string_loc loc
73
74 and substitute env loc substs =
75   let b = Buffer.create 13 in
76   List.iter (
77     function
78     | Ast.SString s -> Buffer.add_string b s
79     | SVar name ->
80        let expr = Ast.getvar env loc name in
81        match to_constant env expr with
82        | Ast.CString s -> Buffer.add_string b s
83   ) substs;
84   Buffer.contents b
85
86 and to_shell_script env loc substs =
87   let b = Buffer.create 13 in
88   List.iter (
89     function
90     | Ast.SString s -> Buffer.add_string b s
91     | SVar name ->
92        let expr = Ast.getvar env loc name in
93        let s = expr_to_shell_string env expr in
94        Buffer.add_string b s
95   ) substs;
96   Buffer.contents b
97
98 and expr_to_shell_string env = function
99   | Ast.EConstant (loc, CString s) -> Filename.quote s
100
101   | EVar (loc, name) ->
102      let expr = Ast.getvar env loc name in
103      expr_to_shell_string env expr
104
105   | ESubsts (loc, str) ->
106      Filename.quote (substitute env loc str)
107
108   | EList (loc, exprs) ->
109      let strs = List.map (expr_to_shell_string env) exprs in
110      (* These are shell quoted so we can just concat them with space. *)
111      String.concat " " strs
112
113   | ECall (loc, name, args) ->
114      let expr = Ast.getvar env loc name in
115      (match expr with
116       | EGoalDefn _ ->
117          (* Goals don't return anything so they cannot be used in
118           * shell script expansions.  Use a function instead.
119           *)
120          failwithf "%a: cannot use goal call ‘%s’ in shell expansion"
121            Ast.string_loc loc name
122
123       | EFuncDefn (loc, func) ->
124          expr_to_shell_string env (call_function env loc name args func)
125
126       | _ ->
127          failwithf "%a: cannot call ‘%s’ which is not a function"
128            Ast.string_loc loc name
129      )
130
131   (* Tactics expand to the first parameter. *)
132   | ETacticCtor (loc, _, []) -> Filename.quote ""
133   | ETacticCtor (loc, _, (arg :: _)) -> expr_to_shell_string env arg
134
135   | EGoalDefn (loc, _) ->
136      failwithf "%a: cannot use goal in shell expansion"
137        Ast.string_loc loc
138
139   | EFuncDefn (loc, _) ->
140      failwithf "%a: cannot use function in shell expansion"
141        Ast.string_loc loc
142
143   | ETacticDefn (loc, _) ->
144      failwithf "%a: cannot use tactic in shell expansion"
145        Ast.string_loc loc
146
147 and run_code env loc (code, quiet) =
148   let code = to_shell_script env loc code in
149   let code =
150     "source " ^ Filename.quote Cmdline.prelude_sh_file ^ "\n" ^
151     "set -e\n" ^
152     (if not quiet then "set -x\n" else "") ^
153     "\n" ^
154     code in
155
156   let chan = Unix.open_process_in code in
157   let b = Buffer.create 1024 in
158   (try
159      while true do
160        Buffer.add_string b (input_line chan);
161        Buffer.add_char b '\n'
162      done
163    with End_of_file -> ());
164   let st = Unix.close_process_in chan in
165   let i =
166     match st with
167     | Unix.WEXITED i -> i
168     | Unix.WSIGNALED i ->
169        failwithf "%a: killed by signal %d" Ast.string_loc loc i
170     | Unix.WSTOPPED i ->
171        failwithf "%a: stopped by signal %d" Ast.string_loc loc i in
172   i, Buffer.contents b
173
174 and evaluate_goal_arg env = function
175   | Ast.EVar (loc, name) ->
176      let expr = Ast.getvar env loc name in
177      evaluate_goal_arg env expr
178
179   | ESubsts (loc, str) ->
180      let str = substitute env loc str in
181      Ast.EConstant (loc, Ast.CString str)
182
183   | EList (loc, exprs) ->
184      Ast.EList (loc, List.map (evaluate_goal_arg env) exprs)
185
186   | ETacticCtor (loc, name, exprs) ->
187      Ast.ETacticCtor (loc, name, List.map (evaluate_goal_arg env) exprs)
188
189   | ECall (loc, name, args) ->
190      let expr = Ast.getvar env loc name in
191      (match expr with
192       | EGoalDefn _ ->
193          (* Goals don't return anything so they cannot be used in
194           * goal args.  Use a function instead.
195           *)
196          failwithf "%a: cannot use goal call ‘%s’ in goal argument"
197            Ast.string_loc loc name
198
199       | EFuncDefn (loc, func) ->
200          call_function env loc name args func
201
202       | _ ->
203          failwithf "%a: cannot call ‘%s’ which is not a function"
204            Ast.string_loc loc name
205      )
206
207   | EConstant _
208   | EGoalDefn _
209   | EFuncDefn _
210   | ETacticDefn _ as e -> e
211
212 (* Functions are only called from goal args or when substituting
213  * into a shell script or constant expression (this may change if we
214  * implement ‘:=’ assignment for variables).  This evaluates a
215  * function by running the associated shell script and parsing
216  * the output as an expression, string or list of strings.
217  *)
218 and call_function env loc name args (params, returning, pure, code) =
219   (* This is used to print the function in debug and error messages only. *)
220   let debug_func =
221     sprintf "%s (%s) returning %s" name
222       (String.concat ", " (List.map (Ast.string_expr ()) args))
223       (match returning with RetExpr -> "expression"
224                           | RetString -> "string"
225                           | RetStrings -> "strings") in
226   Cmdline.debug "%a: running function %s" Ast.string_loc loc debug_func;
227
228   (* Evaluate function args.  Must be done before updating the environment. *)
229   let args = List.map (evaluate_goal_arg env) args in
230
231   (* Create a new environment which maps the parameter names to
232    * the args.
233    *)
234   let env =
235     let params =
236       try List.combine params args
237       with Invalid_argument _ ->
238         failwithf "%a: calling function %s with wrong number of arguments, expecting %d args but got %d args"
239           Ast.string_loc loc debug_func
240           (List.length params) (List.length args) in
241     List.fold_left (fun env (k, v) -> Ast.Env.add k v env) env params in
242
243   if pure then call_function_pure env loc name returning code
244   else call_function_really env loc name returning code
245
246 and call_function_really env loc name returning code =
247   let r, b = run_code env loc code in
248   if r <> 0 then (
249     eprintf "*** function ‘%s’ failed with exit code %d\n" name r;
250     exit 1
251   );
252
253   match returning with
254   | RetExpr -> Parse.parse_expr (sprintf "function:%s" name) b
255   | RetString -> Ast.EConstant (loc, Ast.CString b)
256   | RetStrings ->
257      (* run_code always adds \n after the final line, so when we
258       * read it back we will get a final empty string which we
259       * have to drop.  XXX Probably better to preserve the lines
260       * read from the external command.
261       *)
262      let strs = nsplit "\n" b in
263      let strs = List.rev strs in
264      let strs = match strs with "" :: xs -> xs | xs -> xs in
265      let strs = List.rev strs in
266      let strs = List.map (fun s -> Ast.EConstant (loc, Ast.CString s)) strs in
267      EList (loc, strs)
268
269 (* For pure functions, check if the function can be matched to
270  * a previously memoized result, but don't fail if this goes wrong.
271  *)
272 and call_function_pure env loc name returning code =
273   let code_key =
274     try Some (to_shell_script env loc (fst code))
275     with Failure _ -> None in
276   match code_key with
277   | None -> call_function_really env loc name returning code
278   | Some code_key ->
279      let r =
280        try Some (Hashtbl.find pure_cache code_key)
281        with Not_found -> None in
282      match r with
283      | Some expr -> expr
284      | None ->
285         let expr = call_function_really env loc name returning code in
286         Hashtbl.add pure_cache code_key expr;
287         expr