mlstub.ml 9.99 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
#load "q_MLast.cmo";;

(* TODO:
   - optimizations: generate labels and atoms only once.
   - implement functions OCaml -> CDuce 
*)


open Mltypes
open Ident

module IntMap = 
  Map.Make(struct type t = int let compare : t -> t -> int = compare end)

module IntHash =
  Hashtbl.Make(struct type t = int let hash i = i let equal i j = i == j end)

(* Compute CDuce type *)

let memo_typ = IntHash.create 13

let atom lab = Types.atom (Atoms.atom (Atoms.V.mk_ascii lab))
let label lab = LabelPool.mk (Ns.empty, U.mk lab)
let bigcup f l = List.fold_left (fun accu x -> Types.cup accu (f x)) Types.empty l

let rec typ t =
  try IntHash.find memo_typ t.uid
  with Not_found ->
    let node = Types.make () in
    IntHash.add memo_typ t.uid node;
    Types.define node (typ_descr t.def);
    node

and typ_descr = function
  | Link t -> typ_descr t.def
  | Arrow (t,s) -> Types.arrow (typ t) (typ s)
  | Tuple tl -> Types.tuple (List.map typ tl)
  | PVariant l -> bigcup pvariant l
  | Variant (l,_) -> bigcup variant l
  | Record (l,_) ->
      let l = List.map (fun (lab,t) -> label lab, typ t) l in
      Types.record' (false,(LabelMap.from_list_disj l))
  | Abstract "int" -> Builtin_defs.caml_int
  | Abstract "char" -> Builtin_defs.char_latin1
  | Abstract "string" -> Builtin_defs.string_latin1
  | Builtin ("list", [t]) -> Types.descr (Sequence.star_node (typ t))
  | _ -> assert false
	   
and pvariant = function
  | (lab, None) -> atom lab
  | (lab, Some t) -> Types.times (Types.cons (atom lab)) (typ t)

and variant = function
  | (lab, []) -> atom lab
  | (lab, c) -> Types.tuple (Types.cons (atom lab) :: List.map typ c)


(* Syntactic tools *)


let mk_vars l = 
  let i = ref 0 in
  List.map (fun t -> incr i; Printf.sprintf "x%i" !i) l

let loc = (-1,-1)

let let_in p e body =
  <:expr< let $list:[ p, e ]$ in $body$ >>

let atom_ascii lab =
  <:expr< Value.atom_ascii $str: String.escaped lab$ >>

let label_ascii lab =
  <:expr< Value.label_ascii $str: String.escaped lab$ >>

let pair e1 e2 = <:expr< Value.Pair ($e1$,$e2$) >>

let pmatch e l = 
  let l = List.map (fun (p,e) -> p,None,e) l in
  <:expr< match $e$ with [ $list:l$ ] >>

let rec matches ine oute = function
  | [v1;v2] ->
      let_in <:patt<($lid:v1$,$lid:v2$)>> <:expr< Value.get_pair $ine$ >> oute
  | v::vl ->
      let oute = matches <:expr< r >> oute vl in
      let_in <:patt<($lid:v$,r)>> <:expr< Value.get_pair $ine$ >> oute
  | [] -> assert false

let list_lit el =
  List.fold_right (fun a e -> <:expr< [$a$ :: $e$] >>) el <:expr< [] >>

(* OCaml -> CDuce conversions *)

let to_cd_gen = ref []

let to_cd_fun_name t = 
  Printf.sprintf "to_cd_%i" t.uid

let to_cd_fun t =
  to_cd_gen := t :: !to_cd_gen;
  to_cd_fun_name t

let rec tuple = function
  | [v] -> v
  | v::l -> <:expr< Value.Pair ($v$, $tuple l$) >> 
  | [] -> assert false

let pat_tuple vars = 
  let pl = List.map (fun id -> <:patt< $lid:id$ >>) vars in
  <:patt< ($list:pl$) >>


let rec to_cd e t =
(*  Format.fprintf Format.std_formatter "to_cd %a [uid=%i; recurs=%i]@."
    Mltypes.print t t.uid t.recurs; *)
  if t.recurs > 0 then <:expr< $lid:to_cd_fun t$ $e$ >>
  else to_cd_descr e t.def

and to_cd_descr e = function
  | Link t -> to_cd e t
  | Arrow (t,s) -> failwith "to_cd: Arrow. TODO"
  | Tuple tl -> 
      (* let (x1,...,xn) = ... in Value.Pair (t1(x1), Value.Pair(...,tn(xn))) *)
      let vars = mk_vars tl in
      let_in (pat_tuple vars) e (tuple (tuple_to_cd tl vars))
  | PVariant l ->
      (* match <...> with 
	 | `A -> Value.atom_ascii "A" 
	 | `B x -> Value.Pair (Value.atom_ascii "B",t(x))
      *)
      let cases = 
	List.map
	  (function 
	     | (lab,None) -> <:patt< `$lid:lab$ >>, atom_ascii lab
	     | (lab,Some t) -> 
		 <:patt< `$lid:lab$ x >>, 
		 pair (atom_ascii lab) (to_cd <:expr< x >> t)
	  ) l in
      pmatch e cases
  | Variant (l,_) ->
      (* match <...> with 
	 | A -> Value.atom_ascii "A" 
	 | B (x1,x2,..) -> Value.Pair (Value.atom_ascii "B",...,Value.Pair(tn(x)))
      *)
      let cases = 
	List.map
	  (function 
	     | (lab,[]) -> <:patt< $uid:lab$ >>, atom_ascii lab
	     | (lab,tl) -> 
		 let vars = mk_vars tl in
		 <:patt< $uid:lab$ $pat_tuple vars$ >>,
		 tuple (atom_ascii lab :: tuple_to_cd tl vars)
	  ) l in
      pmatch e cases
  | Record (l,_) ->
      (* let x = <...> in Value.record [ l1,t1(x.l1); ...; ln,x.ln ] *)
      let l = 
	List.map
	  (fun (lab,t) ->
	     let e = to_cd <:expr<x.$lid:lab$>> t in
	     <:expr< ($label_ascii lab$, $e$) >>)
	  l
      in
      let_in <:patt< x >> e <:expr< Value.record $list_lit l$ >>
      
  | Abstract "int" -> <:expr< ocaml2cduce_int $e$ >>
  | Abstract "char" -> <:expr< ocaml2cduce_char $e$ >>
  | Abstract "string" -> <:expr< ocaml2cduce_string $e$ >>
  | Builtin ("list",[t]) ->
      (* Value.sequence_rev (List.rev_map fun_t <...>) *)
      <:expr< Value.sequence_rev (List.rev_map $lid:to_cd_fun t$ $e$) >>
  | _ -> assert false

and tuple_to_cd tl vars = List.map2 (fun t id -> to_cd <:expr< $lid:id$ >> t) tl vars

(* CDuce -> OCaml conversions *)

let to_ml_gen = ref []

let to_ml_fun_name t =
  Printf.sprintf "to_ml_%i" t.uid

let to_ml_fun t =
  to_ml_gen := t :: !to_ml_gen;
  to_ml_fun_name t

let rec to_ml e t =
(*  Format.fprintf Format.std_formatter "to_ml %a@."
    Mltypes.print t; *)
  if t.recurs > 0 then <:expr< $lid:to_ml_fun t$ $e$ >>
  else to_ml_descr e t.def

and to_ml_descr e = function
  | Link t -> to_ml e t
  | Arrow (t,s) -> 
      (* fun x -> s(Eval.eval_apply <...> (t(x))) *)
      let arg = to_cd <:expr< x >> t in
      let res = to_ml <:expr< Eval.eval_apply $e$ $arg$ >> s in
      <:expr< fun x -> $res$ >>

  | Tuple tl -> 
      (* let (x1,r) = Value.get_pair <...> in
         let (x2,r) = Value.get_pair r in
         ...
         let (xn-1,xn) = Value.get_pair r in
	 (t1(x1),...,tn(xn)) *)

      let vars = mk_vars tl in
      let el = tuple_to_ml tl vars in
      matches e <:expr< ($list:el$) >> vars
  | PVariant l ->
      (* match Value.get_variant <...> with 
	 | "A",None -> `A 
	 | "B",Some x -> `B (t(x))
      *)
      let cases = 
	List.map 
	  (function 
	     | (lab,None) -> 
		 <:patt< ($str: String.escaped lab$, None) >>,
		 <:expr< `$lid:lab$ >>
	     | (lab,Some t) ->
		 <:patt< ($str: String.escaped lab$, Some x) >>,
		 <:expr< `$lid:lab$ $to_ml <:expr< x >> t$ >>
	  ) l in
      pmatch <:expr< Value.get_variant $e$ >> cases
  | Variant (l,false) ->
      failwith "Private Sum type"
  | Variant (l,true) ->
      (* match Value.get_variant <...> with 
	 | "A",None -> A 
	 | "B",Some x -> let (x1,r) = x in ... 
      *)
      let cases = 
	List.map 
	  (function 
	     | (lab,[]) -> 
		 <:patt< ($str: String.escaped lab$, None) >>,
		 (match lab with (* Stupid Camlp4 *)
		    | "true" -> <:expr< True >>
		    | "false" -> <:expr< False >>
		    | lab -> <:expr< $lid:lab$ >>)
	     | (lab,[t]) ->
		 <:patt< ($str: String.escaped lab$, Some x) >>,
		 <:expr< $lid:lab$ $to_ml <:expr< x >> t$ >>
	     | (lab,tl) ->
		 let vars = mk_vars tl in
		 let el = tuple_to_ml tl vars in
		 <:patt< ($str: String.escaped lab$, Some x) >>,
		 matches <:expr< x >> <:expr< $lid:lab$ ($list:el$) >> vars
	  ) l in
      pmatch <:expr< Value.get_variant $e$ >> cases
  | Record (l,false) ->
      failwith "Private Record type"
  | Record (l,true) ->
      (* let x = <...> in
	 { l1 = t1(Value.get_field x "l1"); ... } *)
      let l = 
	List.map
	  (fun (lab,t) ->
	     (<:patt< $uid:lab$>>,
	      to_ml <:expr< Value.get_field x $label_ascii lab$ >> t)) l in
      let_in <:patt< x >> e <:expr< {$list:l$} >>

  | Abstract "int" -> <:expr< cduce2ocaml_int $e$ >>
  | Abstract "char" -> <:expr< cduce2ocaml_char $e$ >>
  | Abstract "string" -> <:expr< cduce2ocaml_string $e$ >>
  | Builtin ("list",[t]) ->
      (* List.rev_map fun_t (Value.get_sequence_rev <...> *)
      <:expr< List.rev_map $lid:to_ml_fun t$ (Value.get_sequence_rev $e$) >>
  | _ -> assert false

and tuple_to_ml tl vars = List.map2 (fun t id -> to_ml <:expr< $lid:id$ >> t) tl vars


let to_ml_done = IntHash.create 13
let to_cd_done = IntHash.create 13

let global_transl () = 
  let defs = ref [] in
  let rec aux hd tl gen don fun_name to_descr =
    gen := tl;
    if not (IntHash.mem don hd.uid) then (
      IntHash.add don hd.uid ();
      let p = <:patt< $lid:fun_name hd$ >> in
      let e = <:expr< fun x -> $to_descr <:expr< x >> hd.def$ >> in
      defs := (p,e) :: !defs
    );
    loop ()
  and loop () = match !to_cd_gen,!to_ml_gen with
    | hd::tl,_ -> aux hd tl to_cd_gen to_cd_done to_cd_fun_name to_cd_descr
    | _,hd::tl -> aux hd tl to_ml_gen to_ml_done to_ml_fun_name to_ml_descr
    | [],[] -> ()
  in
  loop ();
  !defs

(* Check type constraints and generate stub code *)

let check_value ty_env c_env (s,t) =
  (* Find the type for the value in the CDuce module *)
  let id = Id.mk (U.mk s) in
  let vt = 
    try Typer.find_value id ty_env
    with Not_found ->
      Printf.eprintf 
      "The interface exports a value %s which is not available in the module\n" s;
      exit 1
  in

  (* Compute expected CDuce type *)
  let et = Types.descr (typ t) in

  (* Check subtyping *)
  if not (Types.subtype vt et) then
    (
      Format.fprintf
       Format.err_formatter
       "The type for the value %s is invalid@\nExpected type:@[%a@]@\nInferred type:@[%a@]@."
       s
       Types.Print.print et
       Types.Print.print vt;
      exit 1
    );
   
  (* Generate stub code *)
  (* let x = t(Eval.get_slot cu slot) *)
  let slot = Compile.find_slot id c_env in
  let e = to_ml <:expr< Eval.get_slot cu $int:string_of_int slot$ >> t in
  <:patt< $uid:s$ >>, e

let stub name cu values =
  let ty_env = !Typer.from_comp_unit cu in
  let c_env = !Compile.from_comp_unit cu in
  let items = List.map (check_value ty_env c_env) values in
  let g = global_transl () in

  (* open Cdml
     open CDuce_all
     let cu = Cdml.initialize <modname>
     let rec <global translation functions>
     let <stubs for values>
  *)

  [ <:str_item< open Cdml >>;
    <:str_item< open CDuce_all >>;
    <:str_item< value cu = Cdml.initialize $str: String.escaped name$ >> ] @
  (if g = [] then [] else [ <:str_item< value rec $list:g$ >> ]) @
  [ <:str_item< value $list:items$ >> ]