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

4
5
let () = Stats.gettimeofday := Unix.gettimeofday

6
exception Escape of exn
7
8
9
exception InvalidInputFilename of string
exception InvalidObjectFilename of string

10
11
let extra_specs = ref []

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

16
17
18
19
20
21
22
23
(* 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

24
let toplevel = ref false
25
let verbose = ref false
26
let silent = ref false
27

28
29
let typing_env = ref Builtin.env
let compile_env = ref Compile.empty_toplevel
30

31
let get_global_value cenv v =
32
  Eval.eval_var (Compile.find v !compile_env)
33
34
35

let get_global_type v =
  Typer.find_value v !typing_env
36

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

42
let print_norm ppf d = 
43
  Types.Print.print ppf ((*Types.normalize*) d)
44

45
let print_sample ppf s =
46
  Sample.print ppf s
47

48
let print_protect ppf s =
49
  Format.fprintf ppf "%s" s
50

51
let print_value ppf v =
52
  Value.print ppf v
53

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

58
59
60
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;
61
  Format.fprintf ppf "Namespace prefixes used for pretty-printing:@.%t"
62
    Ns.InternalPrinter.dump;
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
  | Location (loc, w, exn) ->
82
      Location.print_loc ppf (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_attr 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
  | Typer.UnboundExtId (cu,x) ->
      Format.fprintf ppf "Unbound external identifier %a:%a@." 
121
	U.print (Librarian.name cu)
122
	Ident.print x
123
124
  | Ulexer.Error (i,j,s) ->
      let loc = Location.loc_of_pos (i,j), `Full in
125
      Location.print_loc ppf 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
  | Librarian.InconsistentCrc name ->
131
      Format.fprintf ppf "Link error:@.";
132
133
134
      Format.fprintf ppf "Inconsistent checksum (compilation unit: %a)@."
	U.print name
  | Librarian.NoImplementation name ->
135
      Format.fprintf ppf "Link error:@.";
136
137
      Format.fprintf ppf "No implementation found for compilation unit: %a@."
	U.print name
138
139
140
141
142
  | InvalidInputFilename f ->
      Format.fprintf ppf "Compilation error:@.";
      Format.fprintf ppf "Source filename must have extension .cd@.";
  | InvalidObjectFilename f ->
      Format.fprintf ppf "Compilation error:@.";
143
      Format.fprintf ppf "Object filename must have extension .cdo and no path@.";
144
145
146
147
  | Librarian.InvalidObject f ->
      Format.fprintf ppf "Invalid object file %s@." f
  | Librarian.CannotOpen f ->
      Format.fprintf ppf "Cannot open file %s@." f
148
  | Location.Generic s ->
149
      Format.fprintf ppf "%a@." print_protect s
150
151
152
153
154
155
156
157
158
159
  | Ns.Label.Not_unique ((ns1,s1),(ns2,s2)) ->
      Format.fprintf ppf "Collision on label hash: {%a}:%a, {%a}:%a" 
	U.print (Ns.Uri.value ns1) 
	U.print s1 
	U.print (Ns.Uri.value ns2) 
	U.print s2
  | Ns.Uri.Not_unique (ns1,ns2) ->
      Format.fprintf ppf "Collision on namespaces hash: %a, %a" 
	U.print ns1 
	U.print ns2
160
161
162
163
164
165
166
167
168
169
170
171
172
173
  | Sequence.Error (Sequence.CopyTag (t,expect)) ->
      Format.fprintf ppf "Tags in %a will be copied, but only %a are allowed.@.Counter-example:%a@."
	Types.Print.print t
	Types.Print.print expect
	Sample.print (Sample.get (Types.diff t expect))
  | Sequence.Error (Sequence.CopyAttr (t,expect)) ->
      Format.fprintf ppf "Attributes in %a will be copied, but only %a are allowed.@.Counter-example:%a@."
	Types.Print.print t
	Types.Print.print expect
	Sample.print (Sample.get (Types.diff t expect))
  | Sequence.Error (Sequence.UnderTag (t,exn)) ->
      Format.fprintf ppf "Under tag %a:@." Types.Print.print t;
      print_exn ppf exn
      
174
  | exn ->
175
(*      raise exn *)
176
      Format.fprintf ppf "%a@." print_protect (Printexc.to_string exn)
177

178

179
180
let eval_quiet tenv cenv e = 
  let (e,_) = Typer.type_expr tenv e in
181
  Compile.compile_eval_expr cenv e
182

183
let debug ppf tenv cenv = function
184
  | `Subtype (t1,t2) ->
185
      Format.fprintf ppf "[DEBUG:subtype]@.";
186
187
      let t1 = Types.descr (Typer.typ tenv t1)
      and t2 = Types.descr (Typer.typ tenv t2) in
188
189
      let s = Types.subtype t1 t2 in
      Format.fprintf ppf "%a %a %a : %b@." print_norm t1 print_protect "<=" print_norm t2 s
190
  | `Sample t ->
191
192
      Format.fprintf ppf "[DEBUG:sample]@.";
      (try
193
	 let t = Types.descr (Typer.typ tenv t) in
194
	 Format.fprintf ppf "%a@." print_sample (Sample.get t);
195
	 Format.fprintf ppf "witness: %a@." Types.Witness.print_witness (Types.witness t);
196
197
       with Not_found ->
	 Format.fprintf ppf "Empty type : no sample !@.")
198
  | `Filter (t,p) -> 
199
200
      let t = Typer.typ tenv t
      and p = Typer.pat tenv p in
201
202
203
      Format.fprintf ppf "[DEBUG:filter t=%a p=%a]@."
	Types.Print.print (Types.descr t)
	Patterns.Print.print (Patterns.descr p);
204
      let f = Patterns.filter (Types.descr t) p in
205
      IdMap.iteri (fun x t ->
206
207
		   Format.fprintf ppf " %a:%a@." 
		     Ident.print x
208
209
		     print_norm (Types.descr t)) f
  | `Accept p ->
210
      Format.fprintf ppf "[DEBUG:accept]@.";
211
      let p = Typer.pat tenv p in
212
      let t = Patterns.accept p in
213
      Format.fprintf ppf " %a@." Types.Print.print (Types.descr t)
214
  | `Compile (t,pl) ->
215
      Format.fprintf ppf "[DEBUG:compile]@.";
216
217
218
219
220
221
222
223
224
225
226
227
      let no = ref (-1) in
      let t = Types.descr (Typer.typ tenv t) 
      and pl = List.map (fun p -> incr no; (Typer.pat tenv p, !no)) pl in

      let (state,rhs) = Patterns.Compile.make_branches t pl in
      Array.iteri (fun i r ->
		     Format.fprintf ppf "Return code %i:" i;
		     match r with
		     | Auto_pat.Fail -> Format.fprintf ppf "Fail@."
		     | Auto_pat.Match (_,n) -> Format.fprintf ppf "Pat(%i)@." n
		  ) rhs;
      Format.fprintf ppf "@.Dispatcher:@.%a@." Print_auto.print_state state
228
229
230
231
232
233
234
235
236
  | `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@.")
237

238

239
240
241
242
243
244
245
246
247
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
248
249
250
  | `Print_type t ->
      let t = Typer.typ tenv t in
      Format.fprintf ppf "%a@." Types.Print.print_noname (Types.descr t)
251
252
253
254
255
256
257
  | `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
258
259
260
261
  | `Silent ->
      silent := true
  | `Verbose ->
      silent := false
262
263
264
265
266
  | `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 "@."
267
268
269

let print_id_opt ppf = function
  | None -> Format.fprintf ppf "-"
270
  | Some id -> Format.fprintf ppf "val %a" Ident.print id
271
272
273
274
275
276

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

let show ppf id t v =
277
278
  if !silent then ()
  else Format.fprintf ppf "@[%a : @[%a%a@]@]@."
279
280
281
282
    print_id_opt id 
    print_norm t 
    print_value_opt v

283
284
285
let ev_top ~run ~show ?directive phs =
  let (tenv,cenv,_) =  
    Compile.comp_unit ~run ~show ?directive
286
287
288
      !typing_env !compile_env phs in
  typing_env := tenv;
  compile_env := cenv
289
290
291
292
  

let phrases ppf phs =
  ev_top ~run:true ~show:(show ppf)  ~directive:(directive ppf) phs
293

294
295
296
let catch_exn ppf_err exn =
  if not catch_exceptions then raise exn;
  match exn with
297
298
299
300
301
302
303
304
  | (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 =
305
306
  try Parser.localize_exn (fun () -> rule input)
  with e -> Parser.sync (); raise e
307

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

312
let topinput = run Parser.top_phrases
313
let script = run Parser.prog
314

315

316
let compile src out_dir =
317
  try
318
319
320
321
322
323
324
325
    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
326
327
    let name = U.mk_latin1 cu in
    Librarian.compile_save !verbose name src out;
328
    exit 0
329
330
  with exn -> catch_exn Format.err_formatter exn; exit 1
  
331
let compile_run src =
332
  try
333
    let name = 
334
335
336
337
338
      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
339
340
    let name = U.mk_latin1 name in
    Librarian.compile_run !verbose name src;
341
  with exn -> catch_exn Format.err_formatter exn; exit 1
342

343
let run obj =  
344
  try
345
    if not (Filename.check_suffix obj ".cdo") || (Filename.basename obj <> obj)
346
    then raise (InvalidObjectFilename obj);
347
348
349
    let name = Filename.chop_suffix (Filename.basename obj) ".cdo" in
    let name = U.mk_latin1 name in
    Librarian.load_run name
350
  with exn -> catch_exn Format.err_formatter exn; exit 1
351

352
353

let dump_env ppf = dump_env ppf !typing_env !compile_env
354
355
356
357
358
359
360
361

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 -> 
362
	  vals := (Some (Atoms.V.mk id),v) :: !vals
363
364
365
366
      | None, Some v ->
	  vals := (None,v) :: !vals
      | _ -> assert false
  in
367
  ev_top ~run:true ~show phs;
368
369
370
371
372
373
374
375
376
  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 "@.";
377
    Value.failwith' (Buffer.contents b)
378
	   
379

380
let () =        
381
  Operators.register_fun "eval_expr" Builtin_defs.string_latin1 Types.any
382
383
384
385
386
  (fun v ->
     match eval (Value.cduce2ocaml_string v) with
       | [ (None,v) ] -> v
       | _ -> Value.failwith' "eval: the string must evaluate to a single value"
  )
387