mltypes.ml 8.94 KB
Newer Older
1
exception Error of string
2

3
module Loc = Location
4
open Caml_cduce
5
6
7
8
9
open Asttypes
open Types

(* Unfolding of OCaml types *)

10
11
exception PolyAbstract of string

12
13
14
15
16
let ocaml_env = ref Env.initial

type t = { uid : int; mutable recurs : int; mutable def : def }
and def =
  | Link of t
17
  | Arrow of string * t * t
18
19
  | Tuple of t list
  | PVariant of (string * t option) list  (* Polymorphic variant *)
20
21
  | Variant of string * (string * t list) list * bool
  | Record of string * (string * t) list * bool
22
23
  | Builtin of string * t list
  | Abstract of string
24
  | Var of int
25
26
27

module IntMap = 
  Map.Make(struct type t = int let compare : t -> t -> int = compare end)
28
29
30
31
module IntSet = 
  Set.Make(struct type t = int let compare : t -> t -> int = compare end)
module StringSet =   Set.Make(struct type t = string let compare : t -> t -> int = compare end)

32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54

let rec print_sep f sep ppf = function
  | [] -> ()
  | [x] -> f ppf x
  | x::tl -> Format.fprintf ppf "%a%s" f x sep; print_sep f sep ppf tl

let printed = ref IntMap.empty

let rec print_slot ppf slot =
  if slot.recurs > 0 then
    (
      if IntMap.mem slot.uid !printed then
	Format.fprintf ppf "X%i" slot.uid
      else (
	printed := IntMap.add slot.uid () !printed;
	Format.fprintf ppf "X%i:=%a" slot.uid print_def slot.def
      )
    )
  else 
    print_def ppf slot.def

and print_def ppf = function
  | Link t -> print_slot ppf t
55
  | Arrow (l,t,s) -> Format.fprintf ppf "%s:%a -> %a" l print_slot t print_slot s
56
57
  | Tuple tl -> Format.fprintf ppf "(%a)" (print_sep print_slot ",") tl
  | PVariant l -> Format.fprintf ppf "[%a]" (print_sep print_palt " | ") l
58
59
  | Variant (p,l,_) -> Format.fprintf ppf "[%s:%a]" p (print_sep print_alt " | ") l
  | Record (p,l,_) -> Format.fprintf ppf "{%s:%a}" p (print_sep print_field " ; ") l
60
61
  | Builtin (p,tl) -> Format.fprintf ppf "%s(%a)" p (print_sep print_slot ",") tl
  | Abstract s -> Format.fprintf ppf "%s" s
62
  | Var i -> Format.fprintf ppf "'a%i" i
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86


and print_palt ppf = function
  | lab, None -> Format.fprintf ppf "`%s" lab
  | lab, Some t -> Format.fprintf ppf "`%s of %a" lab print_slot t
   
and print_alt ppf = function
  | (lab,[]) ->
      Format.fprintf ppf "%s" lab
  | (lab,l) ->
      Format.fprintf ppf "%s of [%a]" lab (print_sep print_slot ",") l

and print_field ppf (lab,t) =
  Format.fprintf ppf "%s:%a" lab print_slot t


let print = print_slot

let counter = ref 0
let new_slot () =
  incr counter;
  { uid = !counter; recurs = 0; def = Abstract "DUMMY" }

let builtins =
87
  List.fold_left (fun m x -> StringSet.add x m) StringSet.empty
88
89
90
    [
      "list"; "Pervasives.ref"; 
      "unit"; "array";
91
      "Big_int.big_int";
92
      "option";
93
94
95
      "Cduce_lib.Value.t"; 
      "Cduce_lib.Encodings.Utf8.t";
      "Cduce_lib.Atoms.V.t";
96
    ]
97

98
99
let vars = ref []

100
let get_var id = 
101
  try List.assq id !vars
102
  with Not_found -> 
103
    let i = List.length !vars in
104
    vars := (id,i) :: !vars; 
105
106
    i

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
let constr_table = Hashtbl.create 1024

type env = { constrs: StringSet.t; seen: IntSet.t; vars: t IntMap.t }

let rec unfold_constr env p args =
  let args = List.map (unfold env) args in
  let pn = Path.name p in
  if StringSet.mem pn builtins 
  then ( let slot = new_slot () in slot.def <- Builtin (pn,args); slot )
  else
    let args_id = List.map (fun t -> t.uid) args in
    let k = (pn,args_id) in
    try Hashtbl.find constr_table k
    with Not_found ->
      if StringSet.mem pn env.constrs then
	failwith "Polymorphic recursion forbidden";
      let slot = new_slot () in
      slot.recurs <- 1;
      Hashtbl.add constr_table k slot;

      let decl = 
	try Env.find_type p !ocaml_env
	with Not_found -> failwith ("Cannot resolve path " ^ pn) in

      let env = 
	{ env with 
	    constrs = StringSet.add pn env.constrs;
	    vars = 
	    List.fold_left2 
	      (fun vars a t -> IntMap.add a.id t vars) 
	      env.vars decl.type_params args } in

      let prefix = match p with
	| Path.Pident _ -> ""
	| Path.Pdot (p,_,_) -> Path.name p ^ "."
	| _ -> assert false in

      slot.def <- 
	(match decl.type_kind, decl.type_manifest with
	   | Type_variant (cstrs,pub), _ ->
	       let cstrs =
		 List.map 
		   (fun (cst,f) -> (cst,List.map (unfold env) f)) cstrs in
	       Variant (prefix, cstrs, pub = Public)
	   | Type_record (f,_,pub), _ ->
	       let f = List.map (fun (l,_,t) -> (l,unfold env t)) f in
	       Record (prefix, f, pub = Public)
	   | Type_abstract, Some t ->
	       Link (unfold env t)
	   | Type_abstract, None ->
	       (match args with
		  | [] -> Abstract pn
		  | l ->raise (PolyAbstract pn)));
      slot
	
and unfold env ty =
  if IntSet.mem ty.id env.seen then failwith "Unguarded recursion";
  let env = { env with seen = IntSet.add ty.id env.seen } in 
  let slot = new_slot () in
  slot.def <-
167
    (match ty.desc with
168
169
170
171
172
       | Tarrow (l,t1,t2,_) -> 
	   let t1 = unfold env t1 in
	   let t2 = unfold env t2 in 
	   Arrow (l, t1,t2)
       | Ttuple tyl -> Tuple (List.map (unfold env) tyl)
173
174
       | Tvariant rd ->
	   let fields = 
175
176
	     List.fold_left
	       (fun accu (lab,f) -> 
177
		  match f with
178
		    | Rpresent (Some t) 
179
180
		    | Reither(true, [t], _, _) -> 
			(lab, Some (unfold env t)) :: accu
181
182
183
184
185
		    | Rpresent None 
		    | Reither(true, [], _, _) -> (lab, None) :: accu
		    | Rabsent -> Printf.eprintf "Warning: Rabsent not supported"; accu
		    | Reither _ -> Printf.eprintf "Warning: Reither not supported"; accu
	       ) []
186
187
	       rd.row_fields in
	   PVariant fields
188
189
190
       | Tvar -> 
	   (try Link (IntMap.find ty.id env.vars)
	    with Not_found -> Var (get_var ty.id))
191
       | Tconstr (p,args,_) ->
192
	   Link (unfold_constr env p args)
193
194
       | _ -> failwith "Unsupported feature"
    );
195
  slot
196

197
198
let unfold ty = 
  vars := [];
199
200
201
  Hashtbl.clear constr_table; (* Get rid of that (careful with exceptions) *)
  let t = unfold { seen = IntSet.empty; constrs = StringSet.empty;
		   vars = IntMap.empty } ty in
202
203
204
  let n = List.length !vars in
  vars := [];
  (t,n)
205
206
207

(* Reading .cmi *)

208
let unsupported s =
209
  raise (Error (Printf.sprintf "Unsupported feature (%s) found in .cmi" s))
210

211
212
213
214
215
let has_cmi name =
  Config.load_path := Config.standard_library :: !Librarian.obj_path;
  try ignore (Misc.find_in_path_uncap !Config.load_path (name ^ ".cmi")); true
  with Not_found -> false

216
217
218
219
let find_value v =
  Config.load_path := Config.standard_library :: !Librarian.obj_path;
  let li = Longident.parse v in
  ocaml_env := Env.initial;
220
  let (_,vd) = Env.lookup_value li Env.initial in
221
222
  unfold vd.val_type

223
let values_of_sig name sg =
224
225
226
  List.fold_left
    (fun accu v -> match v with
       | Tsig_value (id,_) -> 
227
228
229
230
231
232
233
	   let id = Ident.name id in
	   (match id.[0] with
	     | 'a'..'z' | '_' ->
		 let n = name ^ "." ^ id in
		 (try (n, (fst (find_value n))) :: accu
		  with PolyAbstract _ -> accu)
	     | _ -> accu (* operator *))
234
235
       | _ -> accu
    ) [] sg
236

237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255

let load_module name = 
  Config.load_path := Config.standard_library :: !Librarian.obj_path;
  let li = Longident.parse name in
  ocaml_env := Env.initial;
  let (_,mty) = Env.lookup_module li Env.initial in
  match mty with
    | Tmty_signature sg -> values_of_sig name sg
    | _ -> raise (Loc.Generic 
		    (Printf.sprintf "Module %s is not a structure" name))

(*
  let filename = Misc.find_in_path_uncap !Config.load_path (name ^ ".cmi") in
  let sg = Env.read_signature name filename in
  values_of_sig sg
*)

let load_module name =
  try load_module name
256
257
258
259
260
  with Env.Error e ->
    Env.report_error Format.str_formatter e;
    let s = Format.flush_str_formatter () in
    let s = Printf.sprintf "Error while reading OCaml interface %s: %s"
	      name s in
261
    raise (Loc.Generic s)
262

263
let read_cmi name =
264
  Config.load_path := Config.standard_library :: !Librarian.obj_path;
265
266
267
268
269
270
271
272
273
  let filename = Misc.find_in_path_uncap !Config.load_path (name ^ ".cmi") in
  let sg = Env.read_signature name filename in
  ocaml_env := Env.add_signature sg Env.initial;
  let buf = Buffer.create 1024 in
  let ppf = Format.formatter_of_buffer buf in
  let values = ref [] in
  List.iter
    (function
       | Tsig_value (id, {val_type=t;val_kind=Val_reg}) -> 
274
275
276
	   let (unf,n) = unfold t in
	   if n !=0 then unsupported "polymorphic value";
	   values := (Ident.name id, t, unf) :: !values
277
278
279
       | Tsig_type (id,t,rs) -> 
	   Format.fprintf ppf "%a@."
	     !Oprint.out_sig_item (Printtyp.tree_of_type_declaration id t rs);
280
281
282
283
284
285
       | Tsig_value _ -> unsupported "external value"
       | Tsig_exception _ -> unsupported "exception"
       | Tsig_module _ -> unsupported "module"
       | Tsig_modtype _ -> unsupported "module type"
       | Tsig_class _ -> unsupported "class"
       | Tsig_cltype _ -> unsupported "class type"
286
287
288
    ) sg;
  (Buffer.contents buf, !values)

289
290
291
292
293
294
295
let read_cmi name =
  try read_cmi name
  with Env.Error e ->
    Env.report_error Format.str_formatter e;
    let s = Format.flush_str_formatter () in
    let s = Printf.sprintf "Error while reading OCaml interface %s: %s"
	      name s in
296
    raise (Loc.Generic s)
297
298


299
let print_ocaml = Printtyp.type_expr
300
301
302
303
304
305
306


let rec dump_li = function
  | Longident.Lident s -> print_endline s
  | Longident.Ldot (li,s) -> dump_li li; print_endline s
  | _ -> assert false