Debian Codegraph @

plugins/extraction/haskell.ml

raw symbols SCIP
1 (************************************************************************)
2 (* * The Rocq Prover / The Rocq Development Team *)
3 (* v * Copyright INRIA, CNRS and contributors *)
4 (* <O___,, * (see version control and CREDITS file for authors & dates) *)
5 (* \VV/ **************************************************************)
6 (* // * This file is distributed under the terms of the *)
7 (* * GNU Lesser General Public License Version 2.1 *)
8 (* * (see LICENSE file for the text of the license) *)
9 (************************************************************************)
10
11 (*s Production of Haskell syntax. *)
12
13 open Pp
14 open CErrors
15 open Util
16 open Names
17 open Table
18 open Miniml
19 open Mlutil
20 open Common
21
22 (*s Haskell renaming issues. *)
23 let pr_lower_id id = str (String.uncapitalize_ascii (Id.to_string id))
24 let pr_upper_id id = str (String.capitalize_ascii (Id.to_string id))
25
26 let keywords =
27 List.fold_right (fun s -> Id.Set.add (Id.of_string s))
28 [ "Any"; "case"; "class"; "data"; "default"; "deriving"; "do"; "else";
29 "family"; "forall"; "foreign"; "if"; "import"; "in"; "infix"; "infixl"; "infixr"; "instance";
30 "let"; "mdo"; "module"; "newtype"; "of"; "proc"; "rec"; "then"; "type"; "where"; "_"; "__";
31 "as"; "qualified"; "hiding" ; "unit" ; "unsafeCoerce" ]
32 Id.Set.empty
33
34 let pp_comment s = str "-- " ++ s ++ fnl ()
35 let pp_bracket_comment s = str"{- " ++ hov 0 s ++ str" -}"
36
37 (* Note: do not shorten [str "foo" ++ fnl ()] into [str "foo\n"],
38 the '\n' character interacts badly with the Format boxing mechanism *)
39
40 let preamble table mod_name comment used_modules usf =
41 let pp_import dp = str ("import qualified "^ string_of_modfile (State.get_table table) dp) ++ fnl ()
42 in
43 (if not (usf.magic || usf.tunknown) then mt ()
44 else
45 str "{-# OPTIONS_GHC -cpp -XMagicHash #-}" ++ fnl () ++
46 str "{- For Hugs, use the option -F\"cpp -P -traditional\" -}" ++ fnl2 ())
47 ++
48 (match comment with
49 | None -> mt ()
50 | Some com -> pp_bracket_comment com ++ fnl2 ())
51 ++
52 str "module " ++ pr_upper_id mod_name ++ str " where" ++ fnl2 () ++
53 str "import qualified Prelude" ++ fnl () ++
54 prlist pp_import (DirPath.Set.elements used_modules) ++ fnl ()
55 ++
56 (if not (usf.magic || usf.tunknown) then mt ()
57 else
58 str "#ifdef __GLASGOW_HASKELL__" ++ fnl () ++
59 str "import qualified GHC.Base" ++ fnl () ++
60 str "#if __GLASGOW_HASKELL__ >= 900" ++ fnl () ++
61 str "import qualified GHC.Exts" ++ fnl () ++
62 str "#endif" ++ fnl () ++
63 str "#else" ++ fnl () ++
64 str "-- HUGS" ++ fnl () ++
65 str "import qualified IOExts" ++ fnl () ++
66 str "#endif" ++ fnl2 ())
67 ++
68 (if not usf.magic then mt ()
69 else
70 str "#ifdef __GLASGOW_HASKELL__" ++ fnl () ++
71 str "unsafeCoerce :: a -> b" ++ fnl () ++
72 str "#if __GLASGOW_HASKELL__ >= 900" ++ fnl () ++
73 str "unsafeCoerce = GHC.Exts.unsafeCoerce#" ++ fnl () ++
74 str "#else" ++ fnl () ++
75 str "unsafeCoerce = GHC.Base.unsafeCoerce#" ++ fnl () ++
76 str "#endif" ++ fnl () ++
77 str "#else" ++ fnl () ++
78 str "-- HUGS" ++ fnl () ++
79 str "unsafeCoerce :: a -> b" ++ fnl () ++
80 str "unsafeCoerce = IOExts.unsafeCoerce" ++ fnl () ++
81 str "#endif" ++ fnl2 ())
82 ++
83 (if not usf.tunknown then mt ()
84 else
85 str "#ifdef __GLASGOW_HASKELL__" ++ fnl () ++
86 str "type Any = GHC.Base.Any" ++ fnl () ++
87 str "#else" ++ fnl () ++
88 str "-- HUGS" ++ fnl () ++
89 str "type Any = ()" ++ fnl () ++
90 str "#endif" ++ fnl2 ())
91 ++
92 (if not usf.mldummy then mt ()
93 else
94 str "__ :: any" ++ fnl () ++
95 str "__ = Prelude.error \"Logical or arity value used\"" ++ fnl2 ())
96
97 let pp_abst = function
98 | [] -> (mt ())
99 | l -> (str "\\" ++
100 prlist_with_sep (fun () -> (str " ")) Id.print l ++
101 str " ->" ++ spc ())
102
103 (*s The pretty-printer for haskell syntax *)
104
105 let pp_global table k r =
106 if is_inline_custom r then str (find_custom r)
107 else str (Common.pp_global table k r)
108
109 (*s Pretty-printing of types. [par] is a boolean indicating whether parentheses
110 are needed or not. *)
111
112 let rec pp_type table par vl t =
113 let rec pp_rec par = function
114 | Tmeta _ | Tvar' _ -> assert false
115 | Tvar i ->
116 (try Id.print (List.nth vl (pred i))
117 with Failure _ -> (str "a" ++ int i))
118 | Tglob (r,[]) -> pp_global table Type r
119 | Tglob (gr,l)
120 when not (keep_singleton ()) && Rocqlib.check_ref sig_type_name gr.glob ->
121 pp_type table true vl (List.hd l)
122 | Tglob (r,l) ->
123 pp_par par
124 (pp_global table Type r ++ spc () ++
125 prlist_with_sep spc (pp_type table true vl) l)
126 | Tarr (t1,t2) ->
127 pp_par par
128 (pp_rec true t1 ++ spc () ++ str "->" ++ spc () ++ pp_rec false t2)
129 | Tdummy _ -> str "()"
130 | Tunknown -> str "Any"
131 | Taxiom -> str "() -- AXIOM TO BE REALIZED" ++ fnl ()
132 in
133 hov 0 (pp_rec par t)
134
135 (*s Pretty-printing of expressions. [par] indicates whether
136 parentheses are needed or not. [env] is the list of names for the
137 de Bruijn variables. [args] is the list of collected arguments
138 (already pretty-printed). *)
139
140 let expr_needs_par = function
141 | MLlam _ -> true
142 | MLcase _ -> false (* now that we use the case ... of { ... } syntax *)
143 | _ -> false
144
145
146 let rec pp_expr table par env args =
147 let apply st = pp_apply st par args
148 and apply2 st = pp_apply2 st par args in
149 function
150 | MLrel n ->
151 let id = get_db_name n env in
152 (* Try to survive to the occurrence of a Dummy rel.
153 TODO: we should get rid of this hack (cf. BZ#592) *)
154 let id = if Id.equal id dummy_name then Id.of_string "__" else id in
155 apply (Id.print id)
156 | MLapp (f,args') ->
157 let stl = List.map (pp_expr table true env []) args' in
158 pp_expr table par env (stl @ args) f
159 | MLlam _ as a ->
160 let fl,a' = collect_lams a in
161 let fl,env' = push_vars (List.map id_of_mlid fl) env in
162 let st = (pp_abst (List.rev fl) ++ pp_expr table false env' [] a') in
163 apply2 st
164 | MLletin (id,a1,a2) ->
165 let i,env' = push_vars [id_of_mlid id] env in
166 let pp_id = Id.print (List.hd i)
167 and pp_a1 = pp_expr table false env [] a1
168 and pp_a2 = pp_expr table (not par && expr_needs_par a2) env' [] a2 in
169 let pp_def =
170 str "let {" ++ cut () ++
171 hov 1 (pp_id ++ str " = " ++ pp_a1 ++ str "}")
172 in
173 apply2 (hv 0 (hv 0 (hv 1 pp_def ++ spc () ++ str "in") ++
174 spc () ++ hov 0 pp_a2))
175 | MLglob r ->
176 apply (pp_global table Term r)
177 | MLcons (_,r,a) as c ->
178 assert (List.is_empty args);
179 begin match a with
180 | _ when is_native_char c -> pp_native_char c
181 | _ when is_native_string c -> pp_native_string c
182 | [] -> pp_global table Cons r
183 | [a] ->
184 pp_par par (pp_global table Cons r ++ spc () ++ pp_expr table true env [] a)
185 | _ ->
186 pp_par par (pp_global table Cons r ++ spc () ++
187 prlist_with_sep spc (pp_expr table true env []) a)
188 end
189 | MLtuple l ->
190 assert (List.is_empty args);
191 pp_boxed_tuple (pp_expr table true env []) l
192 | MLcase (_,t, pv) when is_custom_match pv ->
193 if not (is_regular_match pv) then
194 user_err Pp.(str "Cannot mix yet user-given match and general patterns.");
195 let mkfun (ids,_,e) =
196 if not (List.is_empty ids) then named_lams (List.rev ids) e
197 else dummy_lams (ast_lift 1 e) 1
198 in
199 let pp_branch tr = pp_expr table true env [] (mkfun tr) ++ fnl () in
200 let inner =
201 str (find_custom_match pv) ++ fnl () ++
202 prvect pp_branch pv ++
203 pp_expr table true env [] t
204 in
205 apply2 (hov 2 inner)
206 | MLcase (typ,t,pv) ->
207 apply2
208 (v 0 (str "case " ++ pp_expr table false env [] t ++ str " of {" ++
209 fnl () ++ pp_pat table env pv))
210 | MLfix (i,ids,defs) ->
211 let ids',env' = push_vars (List.rev (Array.to_list ids)) env in
212 pp_fix table par env' i (Array.of_list (List.rev ids'),defs) args
213 | MLexn s ->
214 (* An [MLexn] may be applied, but I don't really care. *)
215 pp_par par (str "Prelude.error" ++ spc () ++ qs s)
216 | MLdummy k ->
217 (* An [MLdummy] may be applied, but I don't really care. *)
218 (match msg_of_implicit k with
219 | "" -> str "__"
220 | s -> str "__" ++ spc () ++ pp_bracket_comment (str s))
221 | MLmagic a ->
222 pp_apply (str "unsafeCoerce") par (pp_expr table true env [] a :: args)
223 | MLaxiom s -> pp_par par (str "Prelude.error \"AXIOM TO BE REALIZED (" ++ str s ++ str ")\"")
224 | MLuint _ ->
225 pp_par par (str "Prelude.error \"EXTRACTION OF UINT NOT IMPLEMENTED\"")
226 | MLfloat _ ->
227 pp_par par (str "Prelude.error \"EXTRACTION OF FLOAT NOT IMPLEMENTED\"")
228 | MLstring _ ->
229 pp_par par (str "Prelude.error \"EXTRACTION OF STRING NOT IMPLEMENTED\"")
230 | MLparray _ ->
231 pp_par par (str "Prelude.error \"EXTRACTION OF ARRAY NOT IMPLEMENTED\"")
232
233 and pp_cons_pat table par r ppl =
234 pp_par par
235 (pp_global table Cons r ++ space_if (not (List.is_empty ppl)) ++ prlist_with_sep spc identity ppl)
236
237 and pp_gen_pat table par ids env = function
238 | Pcons (r,l) -> pp_cons_pat table par r (List.map (pp_gen_pat table true ids env) l)
239 | Pusual r -> pp_cons_pat table par r (List.map Id.print ids)
240 | Ptuple l -> pp_boxed_tuple (pp_gen_pat table false ids env) l
241 | Pwild -> str "_"
242 | Prel n -> Id.print (get_db_name n env)
243
244 and pp_one_pat table env (ids,p,t) =
245 let ids',env' = push_vars (List.rev_map id_of_mlid ids) env in
246 hov 2 (str " " ++
247 pp_gen_pat table false (List.rev ids') env' p ++
248 str " ->" ++ spc () ++
249 pp_expr table (expr_needs_par t) env' [] t)
250
251 and pp_pat table env pv =
252 prvecti
253 (fun i x ->
254 pp_one_pat table env pv.(i) ++
255 if Int.equal i (Array.length pv - 1) then str "}" else
256 (str ";" ++ fnl ()))
257 pv
258
259 (*s names of the functions ([ids]) are already pushed in [env],
260 and passed here just for convenience. *)
261
262 and pp_fix table par env i (ids,bl) args =
263 pp_par par
264 (v 0
265 (v 1 (str "let {" ++ fnl () ++
266 prvect_with_sep (fun () -> str ";" ++ fnl ())
267 (fun (fi,ti) -> pp_function table env (Id.print fi) ti)
268 (Array.map2 (fun a b -> a,b) ids bl) ++
269 str "}") ++
270 fnl () ++ str "in " ++ pp_apply (Id.print ids.(i)) false args))
271
272 and pp_function table env f t =
273 let bl,t' = collect_lams t in
274 let bl,env' = push_vars (List.map id_of_mlid bl) env in
275 (f ++ pr_binding (List.rev bl) ++
276 str " =" ++ fnl () ++ str " " ++
277 hov 2 (pp_expr table false env' [] t'))
278
279 (*s Pretty-printing of inductive types declaration. *)
280
281 let pp_logical_ind packet =
282 pp_bracket_comment
283 (Id.print packet.ip_typename ++ str " : logical inductive" ++ fnl () ++
284 str "with constructors : " ++ prvect_with_sep spc Id.print packet.ip_consnames)
285
286 let pp_singleton table packet =
287 let name = pp_global table Type packet.ip_typename_ref in
288 let l = rename_tvars keywords packet.ip_vars in
289 hov 2 (str "type " ++ name ++ spc () ++
290 prlist_with_sep spc Id.print l ++
291 (if not (List.is_empty l) then str " " else mt ()) ++ str "=" ++ spc () ++
292 pp_type table false l (List.hd packet.ip_types.(0)) ++ fnl () ++
293 pp_comment (str "singleton inductive, whose constructor was " ++
294 Id.print packet.ip_consnames.(0)))
295
296 let pp_one_ind table p pl cv =
297 let pl = rename_tvars keywords pl in
298 let pp_constructor (r,l) =
299 (pp_global table Cons r ++
300 match l with
301 | [] -> (mt ())
302 | _ -> (str " " ++
303 prlist_with_sep
304 (fun () -> (str " ")) (pp_type table true pl) l))
305 in
306 str (if Array.is_empty cv then "type " else "data ") ++
307 pp_global table Type p.ip_typename_ref ++
308 prlist_strict (fun id -> str " " ++ pr_lower_id id) pl ++ str " =" ++
309 if Array.is_empty cv then str " () -- empty inductive"
310 else
311 (fnl () ++ str " " ++
312 v 0 (str " " ++
313 prvect_with_sep (fun () -> fnl () ++ str "| ") pp_constructor
314 (Array.mapi (fun i c -> p.ip_consnames_ref.(i), c) cv)))
315
316 let rec pp_ind table first i ind =
317 if i >= Array.length ind.ind_packets then
318 if first then mt () else fnl ()
319 else
320 let p = ind.ind_packets.(i) in
321 let ip = p.ip_typename_ref in
322 if is_custom ip then pp_ind table first (i+1) ind
323 else
324 if p.ip_logical then
325 pp_logical_ind p ++ pp_ind table first (i+1) ind
326 else
327 pp_one_ind table p p.ip_vars p.ip_types ++ fnl () ++
328 pp_ind table false (i+1) ind
329
330
331 (*s Pretty-printing of a declaration. *)
332
333 let pp_decl table = function
334 | Dind i when i.ind_kind == Singleton ->
335 pp_singleton table i.ind_packets.(0) ++ fnl ()
336 | Dind i -> hov 0 (pp_ind table true 0 i)
337 | Dtype (r, l, t) ->
338 if is_inline_custom r then mt ()
339 else
340 let l = rename_tvars keywords l in
341 let st =
342 try
343 let ids,s = find_type_custom r in
344 prlist (fun id -> str (id^" ")) ids ++ str "=" ++ spc () ++ str s
345 with Not_found ->
346 prlist (fun id -> Id.print id ++ str " ") l ++
347 if t == Taxiom then str "= () -- AXIOM TO BE REALIZED" ++ fnl ()
348 else str "=" ++ spc () ++ pp_type table false l t
349 in
350 hov 2 (str "type " ++ pp_global table Type r ++ spc () ++ st) ++ fnl2 ()
351 | Dfix (rv, defs, typs) ->
352 let names = Array.map
353 (fun r -> if is_inline_custom r then mt () else pp_global table Term r) rv
354 in
355 prvecti
356 (fun i r ->
357 let void = is_inline_custom r ||
358 (not (is_custom r) &&
359 match defs.(i) with MLexn "UNUSED" -> true | _ -> false)
360 in
361 if void then mt ()
362 else
363 hov 2 (names.(i) ++ str " :: " ++ pp_type table false [] typs.(i)) ++ fnl () ++
364 (if is_custom r then
365 (names.(i) ++ str " = " ++ str (find_custom r))
366 else
367 (pp_function table (empty_env table ()) names.(i) defs.(i)))
368 ++ fnl2 ())
369 rv
370 | Dterm (r, a, t) ->
371 if is_inline_custom r then mt ()
372 else
373 let e = pp_global table Term r in
374 hov 2 (e ++ str " :: " ++ pp_type table false [] t) ++ fnl () ++
375 if is_custom r then
376 hov 0 (e ++ str " = " ++ str (find_custom r) ++ fnl2 ())
377 else
378 hov 0 (pp_function table (empty_env table ()) e a ++ fnl2 ())
379
380 let rec pp_structure_elem table = function
381 | (l,SEdecl d) -> pp_decl table d
382 | (l,SEmodule m) -> pp_module_expr table m.ml_mod_expr
383 | (l,SEmodtype m) -> mt ()
384 (* for the moment we simply discard module type *)
385
386 and pp_module_expr table = function
387 | MEstruct (mp,sel) -> prlist_strict (fun e -> pp_structure_elem table e) sel
388 | MEfunctor _ -> mt ()
389 (* for the moment we simply discard unapplied functors *)
390 | MEident _ | MEapply _ -> assert false
391 (* should be expanded in extract_env *)
392
393 let pp_struct table =
394 let pp_sel (mp,sel) = State.with_visibility table mp [] begin fun table ->
395 prlist_strict (fun e -> pp_structure_elem table e) sel
396 end in
397 prlist_strict pp_sel
398
399 let file_naming state mp = file_of_modfile (State.get_table state) mp
400
401 let haskell_descr = {
402 keywords = keywords;
403 file_suffix = ".hs";
404 file_naming = file_naming;
405 preamble = preamble;
406 pp_struct = pp_struct;
407 sig_suffix = None;
408 sig_preamble = (fun _ _ _ _ _ -> mt ());
409 pp_sig = (fun _ _ -> mt ());
410 pp_decl = pp_decl;
411 }