]> matita.cs.unibo.it Git - helm.git/blob - helm/ocaml/grafite2/grafiteEngine.ml
1. matitaEngine splitted into disambiguation (now in grafite_parser) and
[helm.git] / helm / ocaml / grafite2 / grafiteEngine.ml
1 (* Copyright (C) 2005, HELM Team.
2  * 
3  * This file is part of HELM, an Hypertextual, Electronic
4  * Library of Mathematics, developed at the Computer Science
5  * Department, University of Bologna, Italy.
6  * 
7  * HELM is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License
9  * as published by the Free Software Foundation; either version 2
10  * of the License, or (at your option) any later version.
11  * 
12  * HELM is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with HELM; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place - Suite 330, Boston,
20  * MA  02111-1307, USA.
21  * 
22  * For details, see the HELM World-Wide-Web page,
23  * http://helm.cs.unibo.it/
24  *)
25
26 exception Drop
27 exception UnableToInclude of string
28 exception IncludedFileNotCompiled of string
29
30 type options = { 
31   do_heavy_checks: bool ; 
32   include_paths: string list ;
33   clean_baseuri: bool
34 }
35
36 (** create a ProofEngineTypes.mk_fresh_name_type function which uses given
37   * names as long as they are available, then it fallbacks to name generation
38   * using FreshNamesGenerator module *)
39 let namer_of names =
40   let len = List.length names in
41   let count = ref 0 in
42   fun metasenv context name ~typ ->
43     if !count < len then begin
44       let name = Cic.Name (List.nth names !count) in
45       incr count;
46       name
47     end else
48       FreshNamesGenerator.mk_fresh_name ~subst:[] metasenv context name ~typ
49
50 let tactic_of_ast ast =
51   let module PET = ProofEngineTypes in
52   match ast with
53   | GrafiteAst.Absurd (_, term) -> Tactics.absurd term
54   | GrafiteAst.Apply (_, term) -> Tactics.apply term
55   | GrafiteAst.Assumption _ -> Tactics.assumption
56   | GrafiteAst.Auto (_,depth,width,paramodulation,full) ->
57       AutoTactic.auto_tac ?depth ?width ?paramodulation ?full
58         ~dbd:(LibraryDb.instance ()) ()
59   | GrafiteAst.Change (_, pattern, with_what) ->
60      Tactics.change ~pattern with_what
61   | GrafiteAst.Clear (_,id) -> Tactics.clear id
62   | GrafiteAst.ClearBody (_,id) -> Tactics.clearbody id
63   | GrafiteAst.Contradiction _ -> Tactics.contradiction
64   | GrafiteAst.Compare (_, term) -> Tactics.compare term
65   | GrafiteAst.Constructor (_, n) -> Tactics.constructor n
66   | GrafiteAst.Cut (_, ident, term) ->
67      let names = match ident with None -> [] | Some id -> [id] in
68      Tactics.cut ~mk_fresh_name_callback:(namer_of names) term
69   | GrafiteAst.DecideEquality _ -> Tactics.decide_equality
70   | GrafiteAst.Decompose (_, types, what, names) -> 
71       let to_type = function
72          | GrafiteAst.Type (uri, typeno) -> uri, typeno
73          | GrafiteAst.Ident _            -> assert false
74       in
75       let user_types = List.rev_map to_type types in
76       let dbd = LibraryDb.instance () in
77       let mk_fresh_name_callback = namer_of names in
78       Tactics.decompose ~mk_fresh_name_callback ~dbd ~user_types what
79   | GrafiteAst.Discriminate (_,term) -> Tactics.discriminate term
80   | GrafiteAst.Elim (_, what, using, depth, names) ->
81       Tactics.elim_intros ?using ?depth ~mk_fresh_name_callback:(namer_of names)
82         what
83   | GrafiteAst.ElimType (_, what, using, depth, names) ->
84       Tactics.elim_type ?using ?depth ~mk_fresh_name_callback:(namer_of names)
85         what
86   | GrafiteAst.Exact (_, term) -> Tactics.exact term
87   | GrafiteAst.Exists _ -> Tactics.exists
88   | GrafiteAst.Fail _ -> Tactics.fail
89   | GrafiteAst.Fold (_, reduction_kind, term, pattern) ->
90       let reduction =
91         match reduction_kind with
92         | `Normalize ->
93             PET.const_lazy_reduction
94               (CicReduction.normalize ~delta:false ~subst:[])
95         | `Reduce -> PET.const_lazy_reduction ProofEngineReduction.reduce
96         | `Simpl -> PET.const_lazy_reduction ProofEngineReduction.simpl
97         | `Unfold None ->
98             PET.const_lazy_reduction (ProofEngineReduction.unfold ?what:None)
99         | `Unfold (Some lazy_term) ->
100            (fun context metasenv ugraph ->
101              let what, metasenv, ugraph = lazy_term context metasenv ugraph in
102              ProofEngineReduction.unfold ~what, metasenv, ugraph)
103         | `Whd ->
104             PET.const_lazy_reduction (CicReduction.whd ~delta:false ~subst:[])
105       in
106       Tactics.fold ~reduction ~term ~pattern
107   | GrafiteAst.Fourier _ -> Tactics.fourier
108   | GrafiteAst.FwdSimpl (_, hyp, names) -> 
109      Tactics.fwd_simpl ~mk_fresh_name_callback:(namer_of names)
110       ~dbd:(LibraryDb.instance ()) hyp
111   | GrafiteAst.Generalize (_,pattern,ident) ->
112      let names = match ident with None -> [] | Some id -> [id] in
113      Tactics.generalize ~mk_fresh_name_callback:(namer_of names) pattern 
114   | GrafiteAst.Goal (_, n) -> Tactics.set_goal n
115   | GrafiteAst.IdTac _ -> Tactics.id
116   | GrafiteAst.Injection (_,term) -> Tactics.injection term
117   | GrafiteAst.Intros (_, None, names) ->
118       PrimitiveTactics.intros_tac ~mk_fresh_name_callback:(namer_of names) ()
119   | GrafiteAst.Intros (_, Some num, names) ->
120       PrimitiveTactics.intros_tac ~howmany:num
121         ~mk_fresh_name_callback:(namer_of names) ()
122   | GrafiteAst.LApply (_, how_many, to_what, what, ident) ->
123       let names = match ident with None -> [] | Some id -> [id] in
124       Tactics.lapply ~mk_fresh_name_callback:(namer_of names) ?how_many
125         ~to_what what
126   | GrafiteAst.Left _ -> Tactics.left
127   | GrafiteAst.LetIn (loc,term,name) ->
128       Tactics.letin term ~mk_fresh_name_callback:(namer_of [name])
129   | GrafiteAst.Reduce (_, reduction_kind, pattern) ->
130       (match reduction_kind with
131       | `Normalize -> Tactics.normalize ~pattern
132       | `Reduce -> Tactics.reduce ~pattern  
133       | `Simpl -> Tactics.simpl ~pattern 
134       | `Unfold what -> Tactics.unfold ~pattern what
135       | `Whd -> Tactics.whd ~pattern)
136   | GrafiteAst.Reflexivity _ -> Tactics.reflexivity
137   | GrafiteAst.Replace (_, pattern, with_what) ->
138      Tactics.replace ~pattern ~with_what
139   | GrafiteAst.Rewrite (_, direction, t, pattern) ->
140      EqualityTactics.rewrite_tac ~direction ~pattern t
141   | GrafiteAst.Right _ -> Tactics.right
142   | GrafiteAst.Ring _ -> Tactics.ring
143   | GrafiteAst.Split _ -> Tactics.split
144   | GrafiteAst.Symmetry _ -> Tactics.symmetry
145   | GrafiteAst.Transitivity (_, term) -> Tactics.transitivity term
146
147 (* maybe we only need special cases for apply and goal *)
148 let classify_tactic tactic = 
149   match tactic with
150   (* tactics that can't close the goal (return a goal we want to "select") *)
151   | GrafiteAst.Rewrite _ 
152   | GrafiteAst.Split _ 
153   | GrafiteAst.Replace _ 
154   | GrafiteAst.Reduce _
155   | GrafiteAst.Injection _ 
156   | GrafiteAst.IdTac _ 
157   | GrafiteAst.Generalize _ 
158   | GrafiteAst.Elim _ 
159   | GrafiteAst.Cut _
160   | GrafiteAst.Decompose _ -> true, true
161   (* tactics we don't want to reorder goals. I think only Goal needs this. *)
162   | GrafiteAst.Goal _ -> false, true
163   (* tactics like apply *)
164   | _ -> true, false
165   
166 let reorder_metasenv start refine tactic goals current_goal always_opens_a_goal=
167   let module PEH = ProofEngineHelpers in
168 (*   let print_m name metasenv =
169     prerr_endline (">>>>> " ^ name);
170     prerr_endline (CicMetaSubst.ppmetasenv [] metasenv)
171   in *)
172   (* phase one calculates:
173    *   new_goals_from_refine:  goals added by refine
174    *   head_goal:              the first goal opened by ythe tactic 
175    *   other_goals:            other goals opened by the tactic
176    *)
177   let new_goals_from_refine = PEH.compare_metasenvs start refine in
178   let new_goals_from_tactic = PEH.compare_metasenvs refine tactic in
179   let head_goal, other_goals, goals = 
180     match goals with
181     | [] -> None,[],goals
182     | hd::tl -> 
183         (* assert (List.mem hd new_goals_from_tactic);
184          * invalidato dalla goal_tac
185          * *)
186         Some hd, List.filter ((<>) hd) new_goals_from_tactic, List.filter ((<>)
187         hd) goals
188   in
189   let produced_goals = 
190     match head_goal with
191     | None -> new_goals_from_refine @ other_goals
192     | Some x -> x :: new_goals_from_refine @ other_goals
193   in
194   (* extract the metas generated by refine and tactic *)
195   let metas_for_tactic_head = 
196     match head_goal with
197     | None -> []
198     | Some head_goal -> List.filter (fun (n,_,_) -> n = head_goal) tactic in
199   let metas_for_tactic_goals = 
200     List.map 
201       (fun x -> List.find (fun (metano,_,_) -> metano = x) tactic)
202     goals 
203   in
204   let metas_for_refine_goals = 
205     List.filter (fun (n,_,_) -> List.mem n new_goals_from_refine) tactic in
206   let produced_metas, goals = 
207     let produced_metas =
208       if always_opens_a_goal then
209         metas_for_tactic_head @ metas_for_refine_goals @ 
210           metas_for_tactic_goals
211       else begin
212 (*         print_m "metas_for_refine_goals" metas_for_refine_goals;
213         print_m "metas_for_tactic_head" metas_for_tactic_head;
214         print_m "metas_for_tactic_goals" metas_for_tactic_goals; *)
215         metas_for_refine_goals @ metas_for_tactic_head @ 
216           metas_for_tactic_goals
217       end
218     in
219     let goals = List.map (fun (metano, _, _) -> metano)  produced_metas in
220     produced_metas, goals
221   in
222   (* residual metas, preserving the original order *)
223   let before, after = 
224     let rec split e =
225       function 
226       | [] -> [],[]
227       | (metano, _, _) :: tl when metano = e -> 
228           [], List.map (fun (x,_,_) -> x) tl
229       | (metano, _, _) :: tl -> let b, a = split e tl in metano :: b, a
230     in
231     let find n metasenv =
232       try
233         Some (List.find (fun (metano, _, _) -> metano = n) metasenv)
234       with Not_found -> None
235     in
236     let extract l =
237       List.fold_right 
238         (fun n acc -> 
239           match find n tactic with
240           | Some x -> x::acc
241           | None -> acc
242         ) l [] in
243     let before_l, after_l = split current_goal start in
244     let before_l = 
245       List.filter (fun x -> not (List.mem x produced_goals)) before_l in
246     let after_l = 
247       List.filter (fun x -> not (List.mem x produced_goals)) after_l in
248     let before = extract before_l in
249     let after = extract after_l in
250       before, after
251   in
252 (* |+   DEBUG CODE  +|
253   print_m "BEGIN" start;
254   prerr_endline ("goal was: " ^ string_of_int current_goal);
255   prerr_endline ("and metas from refine are:");
256   List.iter 
257     (fun t -> prerr_string (" " ^ string_of_int t)) 
258   new_goals_from_refine;
259   prerr_endline "";
260   print_m "before" before;
261   print_m "metas_for_tactic_head" metas_for_tactic_head;
262   print_m "metas_for_refine_goals" metas_for_refine_goals;
263   print_m "metas_for_tactic_goals" metas_for_tactic_goals;
264   print_m "produced_metas" produced_metas;
265   print_m "after" after; 
266 |+   FINE DEBUG CODE +| *)
267   before @ produced_metas @ after, goals 
268   
269 let apply_tactic ~disambiguate_tactic tactic (status, goal) =
270 (* prerr_endline "apply_tactic"; *)
271 (* prerr_endline (Continuationals.Stack.pp (GrafiteTypes.get_stack status)); *)
272  let starting_metasenv = GrafiteTypes.get_proof_metasenv status in
273  let before = List.map (fun g, _, _ -> g) starting_metasenv in
274 (* prerr_endline "disambiguate"; *)
275  let status_ref, tactic = disambiguate_tactic status goal tactic in
276  let metasenv_after_refinement =  GrafiteTypes.get_proof_metasenv !status_ref in
277  let proof = GrafiteTypes.get_current_proof !status_ref in
278  let proof_status = proof, goal in
279  let needs_reordering, always_opens_a_goal = classify_tactic tactic in
280  let tactic = tactic_of_ast tactic in
281  (* apply tactic will change the status pointed by status_ref ... *)
282 (* prerr_endline "apply_tactic bassa"; *)
283  let (proof, opened) = ProofEngineTypes.apply_tactic tactic proof_status in
284  let after = ProofEngineTypes.goals_of_proof proof in
285  let opened_goals, closed_goals = Tacticals.goals_diff ~before ~after ~opened in
286 (* prerr_endline("before: " ^ String.concat ", " (List.map string_of_int before));
287 prerr_endline("after: " ^ String.concat ", " (List.map string_of_int after));
288 prerr_endline("opened: " ^ String.concat ", " (List.map string_of_int opened)); *)
289 (* prerr_endline("opened_goals: " ^ String.concat ", " (List.map string_of_int opened_goals));
290 prerr_endline("closed_goals: " ^ String.concat ", " (List.map string_of_int closed_goals)); *)
291  let proof, opened_goals = 
292    if needs_reordering then begin
293      let uri, metasenv_after_tactic, t, ty = proof in
294 (* prerr_endline ("goal prima del riordino: " ^ String.concat " " (List.map string_of_int (ProofEngineTypes.goals_of_proof proof))); *)
295      let reordered_metasenv, opened_goals = 
296        reorder_metasenv
297         starting_metasenv
298         metasenv_after_refinement metasenv_after_tactic
299         opened goal always_opens_a_goal
300      in
301      let proof' = uri, reordered_metasenv, t, ty in
302 (* prerr_endline ("goal dopo il riordino: " ^ String.concat " " (List.map string_of_int (ProofEngineTypes.goals_of_proof proof'))); *)
303      proof', opened_goals
304    end
305       else
306         proof, opened_goals
307  in
308  let incomplete_proof =
309    match !status_ref.GrafiteTypes.proof_status with
310    | GrafiteTypes.Incomplete_proof p -> p
311    | _ -> assert false
312  in
313  { !status_ref with GrafiteTypes.proof_status =
314     GrafiteTypes.Incomplete_proof
315      { incomplete_proof with GrafiteTypes.proof = proof } },
316  opened_goals, closed_goals
317
318 type eval_ast =
319  {ea_go:
320   'term 'lazy_term 'reduction 'obj 'ident.
321   disambiguate_tactic:
322    (GrafiteTypes.status ->
323     ProofEngineTypes.goal ->
324     ('term, 'lazy_term, 'reduction, 'ident) GrafiteAst.tactic ->
325    GrafiteTypes.status ref *
326     (Cic.term, ProofEngineTypes.lazy_term, ProofEngineTypes.lazy_term GrafiteAst.reduction, string) GrafiteAst.tactic) ->
327
328   disambiguate_command:
329    (GrafiteTypes.status ->
330     ('term, 'obj) GrafiteAst.command ->
331     GrafiteTypes.status * (Cic.term, Cic.obj) GrafiteAst.command) ->
332
333   ?do_heavy_checks:bool ->
334   ?include_paths:string list ->
335   ?clean_baseuri:bool ->
336   GrafiteTypes.status ->
337   ('term, 'lazy_term, 'reduction, 'obj, 'ident) GrafiteAst.statement ->
338   GrafiteTypes.status
339  }
340
341 type 'a eval_command =
342  {ec_go: 'term 'obj.
343   disambiguate_command:
344    (GrafiteTypes.status ->
345     ('term,'obj) GrafiteAst.command ->
346     GrafiteTypes.status * (Cic.term, Cic.obj) GrafiteAst.command) ->
347   options -> GrafiteTypes.status -> ('term,'obj) GrafiteAst.command ->
348    GrafiteTypes.status
349  }
350
351 type 'a eval_executable =
352  {ee_go: 'term 'lazy_term 'reduction 'obj 'ident.
353   disambiguate_tactic:
354    (GrafiteTypes.status ->
355     ProofEngineTypes.goal ->
356     ('term, 'lazy_term, 'reduction, 'ident) GrafiteAst.tactic ->
357    GrafiteTypes.status ref *
358     (Cic.term, ProofEngineTypes.lazy_term, ProofEngineTypes.lazy_term GrafiteAst.reduction, string) GrafiteAst.tactic) ->
359
360   disambiguate_command:
361    (GrafiteTypes.status ->
362     ('term, 'obj) GrafiteAst.command ->
363     GrafiteTypes.status * (Cic.term, Cic.obj) GrafiteAst.command) ->
364
365   options ->
366   GrafiteTypes.status ->
367   ('term, 'lazy_term, 'reduction, 'obj, 'ident) GrafiteAst.code -> GrafiteTypes.status
368  }
369
370 type 'a eval_from_moo = { efm_go: GrafiteTypes.status ref -> string -> unit }
371
372 let eval_coercion status ~add_composites coercion =
373  let uri = CicUtil.uri_of_term coercion in
374  let status = MatitaSync.add_coercion status ~add_composites uri in
375   {status with GrafiteTypes.proof_status = GrafiteTypes.No_proof}
376
377 let eval_tactical ~disambiguate_tactic status tac =
378  let apply_tactic = apply_tactic ~disambiguate_tactic in
379  let module MatitaStatus =
380   struct
381    type input_status = GrafiteTypes.status * ProofEngineTypes.goal
382  
383    type output_status =
384      GrafiteTypes.status * ProofEngineTypes.goal list * ProofEngineTypes.goal list
385  
386    type tactic = input_status -> output_status
387  
388    let id_tactic = apply_tactic (GrafiteAst.IdTac DisambiguateTypes.dummy_floc)
389    let mk_tactic tac = tac
390    let apply_tactic tac = tac
391    let goals (_, opened, closed) = opened, closed
392    let set_goals (opened, closed) (status, _, _) = (status, opened, closed)
393    let get_stack (status, _) = GrafiteTypes.get_stack status
394  
395    let set_stack stack (status, opened, closed) = 
396      GrafiteTypes.set_stack stack status, opened, closed
397  
398    let inject (status, _) = (status, [], [])
399    let focus goal (status, _, _) = (status, goal)
400   end
401  in
402  let module MatitaTacticals = Tacticals.Make (MatitaStatus) in
403   let rec tactical_of_ast l tac =
404     match tac with
405     | GrafiteAst.Tactic (loc, tactic) ->
406         MatitaTacticals.tactic (MatitaStatus.mk_tactic (apply_tactic tactic))
407     | GrafiteAst.Seq (loc, tacticals) ->  (* tac1; tac2; ... *)
408        assert (l > 0);
409        MatitaTacticals.seq ~tactics:(List.map (tactical_of_ast (l+1)) tacticals)
410     | GrafiteAst.Do (loc, n, tactical) ->
411         MatitaTacticals.do_tactic ~n ~tactic:(tactical_of_ast (l+1) tactical)
412     | GrafiteAst.Repeat (loc, tactical) ->
413         MatitaTacticals.repeat_tactic ~tactic:(tactical_of_ast (l+1) tactical)
414     | GrafiteAst.Then (loc, tactical, tacticals) ->  (* tac; [ tac1 | ... ] *)
415         assert (l > 0);
416         MatitaTacticals.thens ~start:(tactical_of_ast (l+1) tactical)
417           ~continuations:(List.map (tactical_of_ast (l+1)) tacticals)
418     | GrafiteAst.First (loc, tacticals) ->
419         MatitaTacticals.first
420           ~tactics:(List.map (fun t -> "", tactical_of_ast (l+1) t) tacticals)
421     | GrafiteAst.Try (loc, tactical) ->
422         MatitaTacticals.try_tactic ~tactic:(tactical_of_ast (l+1) tactical)
423     | GrafiteAst.Solve (loc, tacticals) ->
424         MatitaTacticals.solve_tactics
425          ~tactics:(List.map (fun t -> "", tactical_of_ast (l+1) t) tacticals)
426
427     | GrafiteAst.Skip loc -> MatitaTacticals.skip
428     | GrafiteAst.Dot loc -> MatitaTacticals.dot
429     | GrafiteAst.Semicolon loc -> MatitaTacticals.semicolon
430     | GrafiteAst.Branch loc -> MatitaTacticals.branch
431     | GrafiteAst.Shift loc -> MatitaTacticals.shift
432     | GrafiteAst.Pos (loc, i) -> MatitaTacticals.pos i
433     | GrafiteAst.Merge loc -> MatitaTacticals.merge
434     | GrafiteAst.Focus (loc, goals) -> MatitaTacticals.focus goals
435     | GrafiteAst.Unfocus loc -> MatitaTacticals.unfocus
436   in
437   let status, _, _ = tactical_of_ast 0 tac (status, ~-1) in
438   let status =  (* is proof completed? *)
439     match status.GrafiteTypes.proof_status with
440     | GrafiteTypes.Incomplete_proof
441        { GrafiteTypes.stack = stack; proof = proof }
442       when Continuationals.Stack.is_empty stack ->
443         { status with GrafiteTypes.proof_status = GrafiteTypes.Proof proof }
444     | _ -> status
445   in
446   status
447
448 let make_absolute paths path =
449    let rec aux = function
450    | [] -> ignore (Unix.stat path); path
451    | p :: tl ->
452       let path = p ^ "/" ^ path in
453        try
454          ignore (Unix.stat path); path
455        with Unix.Unix_error _ -> aux tl
456    in
457    try
458      aux paths
459    with Unix.Unix_error _ -> raise (UnableToInclude path)
460 ;;
461        
462 let eval_comment status c = status
463
464 let rec eval_command = {ec_go = fun ~disambiguate_command opts status cmd ->
465   let status,cmd = disambiguate_command status cmd in
466   let cmd,notation_ids' = CicNotation.process_notation cmd in
467   let status =
468     { status with
469        GrafiteTypes.notation_ids =
470         notation_ids' @ status.GrafiteTypes.notation_ids } in
471   let basedir = Helm_registry.get "matita.basedir" in
472   match cmd with
473   | GrafiteAst.Default (loc, what, uris) as cmd ->
474      LibraryObjects.set_default what uris;
475      GrafiteTypes.add_moo_content [cmd] status
476   | GrafiteAst.Include (loc, path) ->
477      let absolute_path = make_absolute opts.include_paths path in
478      let moopath = GrafiteMisc.obj_file_of_script ~basedir absolute_path in
479      let status = ref status in
480      if not (Sys.file_exists moopath) then
481        raise (IncludedFileNotCompiled moopath);
482      eval_from_moo.efm_go status moopath;
483      !status
484   | GrafiteAst.Metadata (loc, m) ->
485       (match m with
486       | GrafiteAst.Dependency uri -> GrafiteTypes.add_moo_metadata [m] status
487       | GrafiteAst.Baseuri _ -> status)
488   | GrafiteAst.Set (loc, name, value) -> 
489       let status = 
490         if name = "baseuri" then begin
491           let value = 
492             let v = Http_getter_misc.strip_trailing_slash value in
493             try
494               ignore (String.index v ' ');
495               raise (GrafiteTypes.Command_error "baseuri can't contain spaces")
496             with Not_found -> v
497           in
498           if not (GrafiteMisc.is_empty value) && opts.clean_baseuri then begin
499             HLog.warn ("baseuri " ^ value ^ " is not empty");
500             HLog.message ("cleaning baseuri " ^ value);
501             LibraryClean.clean_baseuris ~basedir [value]
502           end;
503           GrafiteTypes.add_moo_metadata [GrafiteAst.Baseuri value] status
504         end else
505           status
506       in
507       GrafiteTypes.set_option status name value
508   | GrafiteAst.Drop loc -> raise Drop
509   | GrafiteAst.Qed loc ->
510       let uri, metasenv, bo, ty =
511         match status.GrafiteTypes.proof_status with
512         | GrafiteTypes.Proof (Some uri, metasenv, body, ty) ->
513             uri, metasenv, body, ty
514         | GrafiteTypes.Proof (None, metasenv, body, ty) -> 
515             raise (GrafiteTypes.Command_error 
516               ("Someone allows to start a theorem without giving the "^
517                "name/uri. This should be fixed!"))
518         | _->
519           raise
520            (GrafiteTypes.Command_error "You can't Qed an incomplete theorem")
521       in
522       if metasenv <> [] then 
523         raise
524          (GrafiteTypes.Command_error
525            "Proof not completed! metasenv is not empty!");
526       let name = UriManager.name_of_uri uri in
527       let obj = Cic.Constant (name,Some bo,ty,[],[]) in
528       MatitaSync.add_obj uri obj
529        {status with GrafiteTypes.proof_status = GrafiteTypes.No_proof}
530   | GrafiteAst.Coercion (loc, coercion, add_composites) ->
531      eval_coercion status ~add_composites coercion
532   | GrafiteAst.Alias (loc, spec) -> 
533      let diff =
534       (*CSC: Warning: this code should be factorized with the corresponding
535              code in DisambiguatePp *)
536       match spec with
537       | GrafiteAst.Ident_alias (id,uri) -> 
538          [DisambiguateTypes.Id id,
539           (uri,(fun _ _ _-> CicUtil.term_of_uri(UriManager.uri_of_string uri)))]
540       | GrafiteAst.Symbol_alias (symb, instance, desc) ->
541          [DisambiguateTypes.Symbol (symb,instance),
542           DisambiguateChoices.lookup_symbol_by_dsc symb desc]
543       | GrafiteAst.Number_alias (instance,desc) ->
544          [DisambiguateTypes.Num instance,
545           DisambiguateChoices.lookup_num_by_dsc desc]
546      in
547       MatitaSync.set_proof_aliases status diff
548   | GrafiteAst.Render _ -> assert false (* ZACK: to be removed *)
549   | GrafiteAst.Dump _ -> assert false   (* ZACK: to be removed *)
550   | GrafiteAst.Interpretation (_, dsc, (symbol, _), cic_appl_pattern) as stm ->
551       let status = GrafiteTypes.add_moo_content [stm] status in
552       let uris =
553         List.map
554           (fun uri -> GrafiteAst.Dependency (UriManager.buri_of_uri uri))
555           (CicNotationUtil.find_appl_pattern_uris cic_appl_pattern)
556       in
557       let diff =
558        [DisambiguateTypes.Symbol (symbol, 0),
559          DisambiguateChoices.lookup_symbol_by_dsc symbol dsc]
560       in
561       let status = MatitaSync.set_proof_aliases status diff in
562       let status = GrafiteTypes.add_moo_metadata uris status in
563       status
564   | GrafiteAst.Notation _ as stm -> GrafiteTypes.add_moo_content [stm] status
565   | GrafiteAst.Obj (loc,obj) ->
566      let ext,name =
567       match obj with
568          Cic.Constant (name,_,_,_,_)
569        | Cic.CurrentProof (name,_,_,_,_,_) -> ".con",name
570        | Cic.InductiveDefinition (types,_,_,_) ->
571           ".ind",
572           (match types with (name,_,_,_)::_ -> name | _ -> assert false)
573        | _ -> assert false in
574      let uri = 
575        UriManager.uri_of_string (GrafiteTypes.qualify status name ^ ext) 
576      in
577      let metasenv = GrafiteTypes.get_proof_metasenv status in
578      match obj with
579      | Cic.CurrentProof (_,metasenv',bo,ty,_,_) ->
580          let name = UriManager.name_of_uri uri in
581          if not(CicPp.check name ty) then
582            HLog.error ("Bad name: " ^ name);
583          if opts.do_heavy_checks then
584            begin
585              let dbd = LibraryDb.instance () in
586              let similar = Whelp.match_term ~dbd ty in
587              let similar_len = List.length similar in
588              if similar_len> 30 then
589                (HLog.message
590                  ("Duplicate check will compare your theorem with " ^ 
591                    string_of_int similar_len ^ 
592                    " theorems, this may take a while."));
593              let convertible =
594                List.filter (
595                  fun u ->
596                    let t = CicUtil.term_of_uri u in
597                    let ty',g = 
598                      CicTypeChecker.type_of_aux' 
599                        metasenv' [] t CicUniv.empty_ugraph
600                    in
601                    fst(CicReduction.are_convertible [] ty' ty g)) 
602                similar 
603              in
604              (match convertible with
605              | [] -> ()
606              | x::_ -> 
607                  HLog.warn  
608                  ("Theorem already proved: " ^ UriManager.string_of_uri x ^ 
609                   "\nPlease use a variant."));
610            end;
611          assert (metasenv = metasenv');
612          let goalno =
613            match metasenv' with (goalno,_,_)::_ -> goalno | _ -> assert false 
614          in
615          let initial_proof = (Some uri, metasenv, bo, ty) in
616          let initial_stack = Continuationals.Stack.of_metasenv metasenv in
617          { status with GrafiteTypes.proof_status =
618             GrafiteTypes.Incomplete_proof
619              { GrafiteTypes.proof = initial_proof; stack = initial_stack } }
620      | _ ->
621          if metasenv <> [] then
622           raise (GrafiteTypes.Command_error (
623             "metasenv not empty while giving a definition with body: " ^
624             CicMetaSubst.ppmetasenv [] metasenv));
625          MatitaSync.add_obj uri obj
626           {status with GrafiteTypes.proof_status = GrafiteTypes.No_proof}
627
628 } and eval_executable = {ee_go = fun ~disambiguate_tactic ~disambiguate_command opts status ex ->
629   match ex with
630   | GrafiteAst.Tactical (_, tac, None) ->
631      eval_tactical ~disambiguate_tactic status tac
632   | GrafiteAst.Tactical (_, tac, Some punct) ->
633      let status = eval_tactical ~disambiguate_tactic status tac in
634       eval_tactical ~disambiguate_tactic status punct
635   | GrafiteAst.Command (_, cmd) ->
636       eval_command.ec_go ~disambiguate_command opts status cmd
637   | GrafiteAst.Macro (_, mac) -> 
638 (*CSC: DA RIPRISTINARE CON UN TIPO DIVERSO
639       raise (Command_error
640        (Printf.sprintf "The macro %s can't be in a script" 
641         (GrafiteAstPp.pp_macro_ast mac)))
642 *) assert false
643
644 } and eval_from_moo = {efm_go = fun status fname ->
645   let ast_of_cmd cmd =
646     GrafiteAst.Executable (DisambiguateTypes.dummy_floc,
647       GrafiteAst.Command (DisambiguateTypes.dummy_floc,
648         (GrafiteAst.reash_cmd_uris cmd)))
649   in
650   let moo, metadata = GrafiteMarshal.load_moo fname in
651   List.iter 
652     (fun ast -> 
653       let ast = ast_of_cmd ast in
654       status :=
655         eval_ast.ea_go
656          ~disambiguate_tactic:(fun status _ tactic -> ref status,tactic)
657          ~disambiguate_command:(fun status cmd -> status,cmd)
658          !status ast)
659     moo;
660   List.iter
661     (fun m ->
662       let ast =
663         ast_of_cmd (GrafiteAst.Metadata (DisambiguateTypes.dummy_floc, m))
664       in
665       status :=
666         eval_ast.ea_go
667          ~disambiguate_tactic:(fun status _ tactic -> ref status,tactic)
668          ~disambiguate_command:(fun status cmd -> status,cmd)
669          !status ast)
670     metadata
671
672 } and eval_ast = {ea_go = fun ~disambiguate_tactic ~disambiguate_command
673   ?(do_heavy_checks=false) ?(include_paths=[]) ?(clean_baseuri=true) status st 
674 ->
675   let opts = {
676     do_heavy_checks = do_heavy_checks ; 
677     include_paths = include_paths;
678     clean_baseuri = clean_baseuri }
679   in
680   match st with
681   | GrafiteAst.Executable (_,ex) ->
682      eval_executable.ee_go ~disambiguate_tactic ~disambiguate_command opts status ex
683   | GrafiteAst.Comment (_,c) -> eval_comment status c
684 }
685
686 let eval_ast = eval_ast.ea_go