+
+(* Functions are only called from goal args or when substituting
+ * into a shell script or constant expression (this may change if we
+ * implement ‘:=’ assignment for variables). This evaluates a
+ * function by running the associated shell script and substituting
+ * the output into an EList.
+ *
+ * XXX In future allow functions to be annotated with a return type.
+ *)
+and call_function env loc name args (params, code) =
+ (* This is used to print the function in debug and error messages only. *)
+ let debug_func =
+ sprintf "%s (%s)" name
+ (String.concat ", " (List.map (Ast.string_expr ()) args)) in
+ Cmdline.debug "%a: running function %s" Ast.string_loc loc debug_func;
+
+ (* Evaluate function args. Must be done before updating the environment. *)
+ let args = List.map (evaluate_goal_arg env) args in
+
+ (* Create a new environment which maps the parameter names to
+ * the args.
+ *)
+ let env =
+ let params =
+ try List.combine params args
+ with Invalid_argument _ ->
+ failwithf "%a: calling function %s with wrong number of arguments, expecting %d args but got %d args"
+ Ast.string_loc loc debug_func
+ (List.length params) (List.length args) in
+ List.fold_left (fun env (k, v) -> Ast.Env.add k v env) env params in
+
+ (* Run the code. *)
+ let code = to_shell_script env loc code in
+ let code = "set -e\n" (*^ "set -x\n"*) ^ "\n" ^ code in
+
+ let chan = Unix.open_process_in code in
+ let lines = ref [] in
+ (try while true do lines := input_line chan :: !lines done
+ with End_of_file -> ());
+ let lines = List.rev !lines in
+ let st = Unix.close_process_in chan in
+ (match st with
+ | Unix.WEXITED 0 -> ()
+ | Unix.WEXITED i ->
+ eprintf "*** function ‘%s’ failed with exit code %d\n" name i
+ | Unix.WSIGNALED i ->
+ eprintf "*** function ‘%s’ killed by signal %d\n" name i
+ | Unix.WSTOPPED i ->
+ eprintf "*** function ‘%s’ stopped by signal %d\n" name i
+ );
+
+ Ast.EList (Ast.noloc,
+ (List.map (fun line ->
+ Ast.EConstant (Ast.noloc, Ast.CString line))
+ lines))