cduce.ml 12.6 KB
Newer Older
1
open Location
2
open Ident
3

4
exception Escape of exn
5
6
7
exception InvalidInputFilename of string
exception InvalidObjectFilename of string

8
9
let extra_specs = ref []

10
11
(* if set to false toplevel exception aren't cought. 
 * Useful for debugging with OCAMLRUNPARAM="b" *)
12
13
let catch_exceptions = true

14
15
16
17
18
19
20
21
(* retuns a filename without the suffix suff if any *) 
let prefix filename suff =
  if Filename.check_suffix filename suff then
    try
      Filename.chop_extension filename
    with Invalid_argument filename -> failwith "Not a point in the suffix?"
  else filename

22
let toplevel = ref false
23
let verbose = ref false
24
let silent = ref false
25

26
let typing_env = State.ref "Cduce.typing_env" Builtin.env
27
let compile_env = State.ref "Cduce.compile_env" Compile.empty_toplevel
28

29
let get_global_value cenv v =
30
  Eval.var (Compile.find v !compile_env)
31
32
33

let get_global_type v =
  Typer.find_value v !typing_env
34

35
36
37
38
39
let rec is_abstraction = function
  | Ast.Abstraction _ -> true
  | Ast.LocatedExpr (_,e) -> is_abstraction e
  | _ -> false

40
let print_norm ppf d = 
41
  Types.Print.print ppf ((*Types.normalize*) d)
42

43
let print_sample ppf s =
44
  Sample.print ppf s
45

46
let print_protect ppf s =
47
  Format.fprintf ppf "%s" s
48

49
let print_value ppf v =
50
  Value.print ppf v
51

52
53
let dump_value ppf x t v =
  Format.fprintf ppf "@[val %a : @[%a = %a@]@]@."
54
    Ident.print x print_norm t print_value v
55

56
57
58
let dump_env ppf tenv cenv =
  Format.fprintf ppf "Types:%a@." Typer.dump_types tenv;
  Format.fprintf ppf "Namespace prefixes:@\n%a" Typer.dump_ns tenv;
59
  Format.fprintf ppf "Namespace prefixes used for pretty-printing:@.%t"
60
    Ns.InternalPrinter.dump;
61
  Format.fprintf ppf "Schemas: %s@."
62
    (String.concat " " (List.map U.get_str (Typer.get_schema_names tenv)));
63
  Format.fprintf ppf "Values:@.";
64
65
  Typer.iter_values tenv
    (fun x t -> dump_value ppf x t (get_global_value cenv x))
66

67
68
69
let directive_help ppf =
  Format.fprintf ppf
"Toplevel directives:
70
71
72
73
  #quit;;                 quit the interpreter
  #env;;                  dump current environment
  #reinit_ns;;            reinitialize namespace processing
  #help;;                 shows this help message
74
  #print_type <type>;;
75
76
  #silent;;               turn off outputs from the toplevel
  #verbose;;              turn on outputs from the toplevel
77
  #builtins;;             shows embedded OCaml values
78
79
"

80
let rec print_exn ppf = function
81
82
  | Location (loc, w, exn) ->
      Format.fprintf ppf "Error %a:@." Location.print_loc (loc,w);
83
      Location.html_hilight (loc,w); 
84
      print_exn ppf exn
85
  | Value.CDuceExn v ->
86
      Format.fprintf ppf "Uncaught CDuce exception: @[%a@]@."
87
        print_value v
88
  | Typer.WrongLabel (t,l) ->
89
      Format.fprintf ppf "Wrong record selection; field %a " 
90
        Label.print (LabelPool.value l);
91
      Format.fprintf ppf "not present in an expression of type:@.%a@."
92
        print_norm t
93
  | Typer.ShouldHave (t,msg) ->
94
      Format.fprintf ppf "This expression should have type:@.%a@.%a@." 
95
        print_norm t
96
        print_protect msg
97
  | Typer.ShouldHave2 (t1,msg,t2) ->
98
      Format.fprintf ppf "This expression should have type:@.%a@.%a %a@." 
99
        print_norm t1
100
        print_protect msg
101
        print_norm t2
102
  | Typer.Error s ->
103
      Format.fprintf ppf "%a@." print_protect s
104
  | Typer.Constraint (s,t) ->
105
      Format.fprintf ppf "This expression should have type:@.%a@." 
106
        print_norm t;
107
      Format.fprintf ppf "but its inferred type is:@.%a@." 
108
        print_norm s;
109
      Format.fprintf ppf "which is not a subtype, as shown by the sample:@.%a@." 
110
	print_sample (Sample.get (Types.diff s t))
111
  | Typer.NonExhaustive t ->
112
113
      Format.fprintf ppf "This pattern matching is not exhaustive@.";
      Format.fprintf ppf "Residual type:@.%a@."
114
	print_norm t;
115
      Format.fprintf ppf "Sample:@.%a@." print_sample (Sample.get t)
116
  | Typer.UnboundId (x,tn) ->
117
      Format.fprintf ppf "Unbound identifier %a%s@." Ident.print x
118
        (if tn then " (it is a type name)" else "")
119
120
121
  | Typer.UnboundExtId (cu,x) ->
      Format.fprintf ppf "Unbound external identifier %a:%a@." 
	U.print (Types.CompUnit.value cu)
122
	Ident.print x
123
124
125
  | Ulexer.Error (i,j,s) ->
      let loc = Location.loc_of_pos (i,j), `Full in
      Format.fprintf ppf "Error %a:@." Location.print_loc loc;
126
127
      Location.html_hilight loc;
      Format.fprintf ppf "%s" s
128
  | Parser.Error s | Stream.Error s -> 
129
      Format.fprintf ppf "Parsing error: %a@." print_protect s
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
  | Librarian.InconsistentCrc id ->
      Format.fprintf ppf "Link error:@.";
      let name = Encodings.Utf8.to_string (Types.CompUnit.value id) in
      Format.fprintf ppf "Inconsistent checksum (compilation unit: %s)@."
	name
  | Librarian.NoImplementation id ->
      Format.fprintf ppf "Link error:@.";
      let name = Encodings.Utf8.to_string (Types.CompUnit.value id) in
      Format.fprintf ppf "No implementation found for compilation unit: %s@."
	name
  | Librarian.Loop id ->
      Format.fprintf ppf "Compilation error:@.";
      let name = Encodings.Utf8.to_string (Types.CompUnit.value id) in
      Format.fprintf ppf "Loop between compilation unit (compilation unit: %s)@."
	name
  | InvalidInputFilename f ->
      Format.fprintf ppf "Compilation error:@.";
      Format.fprintf ppf "Source filename must have extension .cd@.";
  | InvalidObjectFilename f ->
      Format.fprintf ppf "Compilation error:@.";
150
      Format.fprintf ppf "Object filename must have extension .cdo and no path@.";
151
152
153
154
  | Librarian.InvalidObject f ->
      Format.fprintf ppf "Invalid object file %s@." f
  | Librarian.CannotOpen f ->
      Format.fprintf ppf "Cannot open file %s@." f
155
  | Location.Generic s ->
156
      Format.fprintf ppf "%a@." print_protect s
157
  | exn ->
158
(*      raise exn *)
159
      Format.fprintf ppf "%a@." print_protect (Printexc.to_string exn)
160

161

162
163
let eval_quiet tenv cenv e = 
  let (e,_) = Typer.type_expr tenv e in
164
  let e = Compile.compile_expr cenv e in 
165
166
  Eval.expr e

167
let debug ppf tenv cenv = function
168
  | `Subtype (t1,t2) ->
169
      Format.fprintf ppf "[DEBUG:subtype]@.";
170
171
      let t1 = Types.descr (Typer.typ tenv t1)
      and t2 = Types.descr (Typer.typ tenv t2) in
172
173
      let s = Types.subtype t1 t2 in
      Format.fprintf ppf "%a %a %a : %b@." print_norm t1 print_protect "<=" print_norm t2 s
174
  | `Sample t ->
175
176
      Format.fprintf ppf "[DEBUG:sample]@.";
      (try
177
	 let t = Types.descr (Typer.typ tenv t) in
178
179
180
	 Format.fprintf ppf "%a@." print_sample (Sample.get t)
       with Not_found ->
	 Format.fprintf ppf "Empty type : no sample !@.")
181
  | `Filter (t,p) -> 
182
183
      let t = Typer.typ tenv t
      and p = Typer.pat tenv p in
184
185
186
      Format.fprintf ppf "[DEBUG:filter t=%a p=%a]@."
	Types.Print.print (Types.descr t)
	Patterns.Print.print (Patterns.descr p);
187
      let f = Patterns.filter (Types.descr t) p in
188
      IdMap.iteri (fun x t ->
189
190
		   Format.fprintf ppf " %a:%a@." 
		     Ident.print x
191
192
		     print_norm (Types.descr t)) f
  | `Accept p ->
193
      Format.fprintf ppf "[DEBUG:accept]@.";
194
      let p = Typer.pat tenv p in
195
      let t = Patterns.accept p in
196
      Format.fprintf ppf " %a@." Types.Print.print (Types.descr t)
197
  | `Compile (t,pl) ->
198
      Format.fprintf ppf "[DEBUG:compile]@.";
199
      let t = Typer.typ tenv t
200
      and pl = List.map (Typer.pat tenv) pl in  
201
202
203
      Patterns.Compile.debug_compile ppf t pl;
      Format.fprintf ppf "@.";

204
(*
205
       Patterns.demo_compile ppf (Types.descr t) (List.map Patterns.descr pl)  
206
*)
207
  | `Explain (t0,t,e) ->
208
      Format.fprintf ppf "[DEBUG:explain]@.";
209
210
211
      let t = Types.descr (Typer.typ tenv t) in
      let t0 = Types.descr (Typer.typ tenv t0) in
      (match Explain.explain t0 t (eval_quiet tenv cenv e) with
212
	 | Some p ->
213
	     Format.fprintf ppf "%a@."
214
	       Explain.print p
215
	 | None ->
216
	     Format.fprintf ppf "Value has given type@.")
217
218
219
220
221
222
223
224
225
226
227
228
229
  | `Single t ->
      Format.fprintf ppf "[DEBUG:single]@.";
      let t = Typer.typ tenv t in
      (try 
	 let c = Sample.single (Types.descr t) in
	 Format.fprintf ppf "Constant:%a@." Types.Print.print_const c
       with
	 | Exit -> Format.fprintf ppf "Non constant@." 
	 | Not_found ->  Format.fprintf ppf "Empty@.")
  | `Approx (p,t) ->
      Format.fprintf ppf "[DEBUG:approx]@.";
      let t = Typer.typ tenv t in
      let p = Typer.pat tenv p in
230
      Patterns.demo ppf (Patterns.descr p) (Types.descr t); 
231
(*
232
233
234
      let (x,c) = Patterns.approx (Patterns.descr p) (Types.descr t) in
      List.iter (fun x -> Format.fprintf ppf "%a=* " U.print (Id.value x)) x;
      List.iter
235
	(fun (x,c) ->
236
237
238
	   Format.fprintf ppf "%a=%a "
	     U.print (Id.value x) 
	     Types.Print.print_const c
239
	) c;  *)
240
      Format.fprintf ppf "@."
241

242

243
244
245
246
247
248
249
250
251
let flush_ppf ppf = Format.fprintf ppf "@."

let directive ppf tenv cenv = function
  | `Debug d ->
      debug ppf tenv cenv d
  | `Quit ->
      (if !toplevel then raise End_of_file)
  | `Env ->
      dump_env ppf tenv cenv
252
253
254
  | `Print_type t ->
      let t = Typer.typ tenv t in
      Format.fprintf ppf "%a@." Types.Print.print_noname (Types.descr t)
255
256
257
258
259
260
261
  | `Reinit_ns ->
      Typer.set_ns_table_for_printer tenv
  | `Help ->
      directive_help ppf
  | `Dump pexpr ->
      Value.dump_xml ppf (eval_quiet tenv cenv pexpr);
      flush_ppf ppf
262
263
264
265
  | `Silent ->
      silent := true
  | `Verbose ->
      silent := false
266
267
268
269
270
  | `Builtins ->
      let b = Librarian.get_builtins () in
      Format.fprintf ppf "Embedded OCaml value: ";
      List.iter (fun s -> Format.fprintf ppf "%s " s) b;
      Format.fprintf ppf "@."
271
272
273

let print_id_opt ppf = function
  | None -> Format.fprintf ppf "-"
274
  | Some id -> Format.fprintf ppf "val %a" Ident.print id
275
276
277
278
279
280

let print_value_opt ppf = function
  | None -> ()
  | Some v -> Format.fprintf ppf " = %a" print_value v

let show ppf id t v =
281
282
  if !silent then ()
  else Format.fprintf ppf "@[%a : @[%a%a@]@]@."
283
284
285
286
287
288
289
290
    print_id_opt id 
    print_norm t 
    print_value_opt v

let phrases ppf phs =
  let (tenv,cenv,_) = 
    Compile.comp_unit 
      ~run:true ~show:(show ppf) 
291
      ~loading:Librarian.import_and_run
292
293
294
295
      ~directive:(directive ppf)
      !typing_env !compile_env phs in
  typing_env := tenv;
  compile_env := cenv
296

297
298
299
let catch_exn ppf_err exn =
  if not catch_exceptions then raise exn;
  match exn with
300
301
302
303
304
305
306
307
  | (End_of_file | Failure _ | Not_found | Invalid_argument _ | Sys.Break) 
      as e -> 
      raise e
  | exn -> 
      print_exn ppf_err exn;
      Format.fprintf ppf_err "@."

let parse rule input =
308
309
  try Parser.localize_exn (fun () -> rule input)
  with e -> Parser.sync (); raise e
310

311
let run rule ppf ppf_err input =
312
  try phrases ppf (parse rule input); true
313
  with Escape exn -> raise exn | exn -> catch_exn ppf_err exn; false
314

315
let topinput = run Parser.top_phrases
316
let script = run Parser.prog
317

318

319
let compile src out_dir =
320
  try
321
322
323
324
325
326
327
328
329
    if not (Filename.check_suffix src ".cd")
    then raise (InvalidInputFilename src);
    let cu = Filename.chop_suffix (Filename.basename src) ".cd" in
    let out_dir = 
      match out_dir with
	| None -> Filename.dirname src
	| Some x -> x in
    let out = Filename.concat out_dir (cu ^ ".cdo") in
    let id = Types.CompUnit.mk (U.mk_latin1 cu) in
330
    Librarian.compile !verbose cu id src;
331
    Librarian.save cu id out;
332
    exit 0
333
334
  with exn -> catch_exn Format.err_formatter exn; exit 1
  
335
let compile_run src =
336
  try
337
338
339
340
341
342
    let cu = 
      if src = "" then "<stdin>"
      else
	if not (Filename.check_suffix src ".cd")
	then raise (InvalidInputFilename src)
	else Filename.chop_suffix (Filename.basename src) ".cd" in
343
    let id = Types.CompUnit.mk (U.mk_latin1 cu) in
344
    Librarian.compile !verbose cu id src;
345
    Librarian.run id
346
  with exn -> catch_exn Format.err_formatter exn; exit 1
347

348
let run obj =  
349
  try
350
    if not (Filename.check_suffix obj ".cdo") || (Filename.basename obj <> obj)
351
352
353
    then raise (InvalidObjectFilename obj);
    let cu = Filename.chop_suffix (Filename.basename obj) ".cdo" in
    let id = Types.CompUnit.mk (U.mk_latin1 cu) in
354
    Librarian.import_and_run id
355
  with exn -> catch_exn Format.err_formatter exn; exit 1
356

357
358

let dump_env ppf = dump_env ppf !typing_env !compile_env
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385

let eval s =
  let st = Stream.of_string s in
  let phs = parse Parser.prog st in
  let vals = ref [] in
  let show id t v =
    match id,v with
      | Some id, Some v -> 
	  let id = Id.value id in
	  vals := (Some id,v) :: !vals
      | None, Some v ->
	  vals := (None,v) :: !vals
      | _ -> assert false
  in
  let r () = 
    ignore (Compile.comp_unit 
	      ~run:true ~show Builtin.env Compile.empty_toplevel phs) in
  Eval.new_stack r ();
  List.rev !vals
  
let eval s =
  try eval s
  with exn -> 
    let b = Buffer.create 1024 in
    let ppf = Format.formatter_of_buffer b in
    print_exn ppf exn;
    Format.fprintf ppf "@.";
386
    Value.failwith' (Buffer.contents b)
387
	   
388

389
let () =        
390
  Operators.register_fun "eval_expr" Builtin_defs.string_latin1 Types.any
391
392
393
394
395
  (fun v ->
     match eval (Value.cduce2ocaml_string v) with
       | [ (None,v) ] -> v
       | _ -> Value.failwith' "eval: the string must evaluate to a single value"
  )
396