]> matita.cs.unibo.it Git - helm.git/blob - helm/ocaml/grafite_engine/grafiteEngine.ml
c820986b39f47e2a6fce588ada47db8d35d2bd02
[helm.git] / helm / ocaml / grafite_engine / 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 IncludedFileNotCompiled of string (* file name *)
28
29 type options = { 
30   do_heavy_checks: bool ; 
31   clean_baseuri: bool
32 }
33
34 (** create a ProofEngineTypes.mk_fresh_name_type function which uses given
35   * names as long as they are available, then it fallbacks to name generation
36   * using FreshNamesGenerator module *)
37 let namer_of names =
38   let len = List.length names in
39   let count = ref 0 in
40   fun metasenv context name ~typ ->
41     if !count < len then begin
42       let name = Cic.Name (List.nth names !count) in
43       incr count;
44       name
45     end else
46       FreshNamesGenerator.mk_fresh_name ~subst:[] metasenv context name ~typ
47
48 let tactic_of_ast ast =
49   let module PET = ProofEngineTypes in
50   match ast with
51   | GrafiteAst.Absurd (_, term) -> Tactics.absurd term
52   | GrafiteAst.Apply (_, term) -> Tactics.apply term
53   | GrafiteAst.Assumption _ -> Tactics.assumption
54   | GrafiteAst.Auto (_,depth,width,paramodulation,full) ->
55       AutoTactic.auto_tac ?depth ?width ?paramodulation ?full
56         ~dbd:(LibraryDb.instance ()) ()
57   | GrafiteAst.Change (_, pattern, with_what) ->
58      Tactics.change ~pattern with_what
59   | GrafiteAst.Clear (_,id) -> Tactics.clear id
60   | GrafiteAst.ClearBody (_,id) -> Tactics.clearbody id
61   | GrafiteAst.Contradiction _ -> Tactics.contradiction
62   | GrafiteAst.Compare (_, term) -> Tactics.compare term
63   | GrafiteAst.Constructor (_, n) -> Tactics.constructor n
64   | GrafiteAst.Cut (_, ident, term) ->
65      let names = match ident with None -> [] | Some id -> [id] in
66      Tactics.cut ~mk_fresh_name_callback:(namer_of names) term
67   | GrafiteAst.DecideEquality _ -> Tactics.decide_equality
68   | GrafiteAst.Decompose (_, types, what, names) -> 
69       let to_type = function
70          | GrafiteAst.Type (uri, typeno) -> uri, typeno
71          | GrafiteAst.Ident _            -> assert false
72       in
73       let user_types = List.rev_map to_type types in
74       let dbd = LibraryDb.instance () in
75       let mk_fresh_name_callback = namer_of names in
76       Tactics.decompose ~mk_fresh_name_callback ~dbd ~user_types what
77   | GrafiteAst.Discriminate (_,term) -> Tactics.discriminate term
78   | GrafiteAst.Elim (_, what, using, depth, names) ->
79       Tactics.elim_intros ?using ?depth ~mk_fresh_name_callback:(namer_of names)
80         what
81   | GrafiteAst.ElimType (_, what, using, depth, names) ->
82       Tactics.elim_type ?using ?depth ~mk_fresh_name_callback:(namer_of names)
83         what
84   | GrafiteAst.Exact (_, term) -> Tactics.exact term
85   | GrafiteAst.Exists _ -> Tactics.exists
86   | GrafiteAst.Fail _ -> Tactics.fail
87   | GrafiteAst.Fold (_, reduction_kind, term, pattern) ->
88       let reduction =
89         match reduction_kind with
90         | `Normalize ->
91             PET.const_lazy_reduction
92               (CicReduction.normalize ~delta:false ~subst:[])
93         | `Reduce -> PET.const_lazy_reduction ProofEngineReduction.reduce
94         | `Simpl -> PET.const_lazy_reduction ProofEngineReduction.simpl
95         | `Unfold None ->
96             PET.const_lazy_reduction (ProofEngineReduction.unfold ?what:None)
97         | `Unfold (Some lazy_term) ->
98            (fun context metasenv ugraph ->
99              let what, metasenv, ugraph = lazy_term context metasenv ugraph in
100              ProofEngineReduction.unfold ~what, metasenv, ugraph)
101         | `Whd ->
102             PET.const_lazy_reduction (CicReduction.whd ~delta:false ~subst:[])
103       in
104       Tactics.fold ~reduction ~term ~pattern
105   | GrafiteAst.Fourier _ -> Tactics.fourier
106   | GrafiteAst.FwdSimpl (_, hyp, names) -> 
107      Tactics.fwd_simpl ~mk_fresh_name_callback:(namer_of names)
108       ~dbd:(LibraryDb.instance ()) hyp
109   | GrafiteAst.Generalize (_,pattern,ident) ->
110      let names = match ident with None -> [] | Some id -> [id] in
111      Tactics.generalize ~mk_fresh_name_callback:(namer_of names) pattern 
112   | GrafiteAst.Goal (_, n) -> Tactics.set_goal n
113   | GrafiteAst.IdTac _ -> Tactics.id
114   | GrafiteAst.Injection (_,term) -> Tactics.injection term
115   | GrafiteAst.Intros (_, None, names) ->
116       PrimitiveTactics.intros_tac ~mk_fresh_name_callback:(namer_of names) ()
117   | GrafiteAst.Intros (_, Some num, names) ->
118       PrimitiveTactics.intros_tac ~howmany:num
119         ~mk_fresh_name_callback:(namer_of names) ()
120   | GrafiteAst.Inversion (_, term) ->
121       Tactics.inversion term
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, tactic = disambiguate_tactic status goal tactic in
276  let metasenv_after_refinement =  GrafiteTypes.get_proof_metasenv status in
277  let proof = GrafiteTypes.get_current_proof status 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 lexicon_status ... *)
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.GrafiteTypes.proof_status with
310    | GrafiteTypes.Incomplete_proof p -> p
311    | _ -> assert false
312  in
313  { status 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 *
326    (Cic.term, Cic.lazy_term, Cic.lazy_term GrafiteAst.reduction, string) GrafiteAst.tactic) ->
327
328   disambiguate_command:
329    (GrafiteTypes.status ->
330     'obj GrafiteAst.command ->
331     GrafiteTypes.status * Cic.obj GrafiteAst.command) ->
332
333   ?do_heavy_checks:bool ->
334   ?clean_baseuri:bool ->
335   GrafiteTypes.status ->
336   ('term, 'lazy_term, 'reduction, 'obj, 'ident) GrafiteAst.statement ->
337   GrafiteTypes.status * UriManager.uri list
338  }
339
340 type 'a eval_command =
341  {ec_go: 'term 'obj.
342   disambiguate_command:
343    (GrafiteTypes.status ->
344     'obj GrafiteAst.command ->
345     GrafiteTypes.status * Cic.obj GrafiteAst.command) ->
346   options -> GrafiteTypes.status -> 'obj GrafiteAst.command ->
347    GrafiteTypes.status * UriManager.uri list
348  }
349
350 type 'a eval_executable =
351  {ee_go: 'term 'lazy_term 'reduction 'obj 'ident.
352   disambiguate_tactic:
353    (GrafiteTypes.status ->
354     ProofEngineTypes.goal ->
355     ('term, 'lazy_term, 'reduction, 'ident) GrafiteAst.tactic ->
356     GrafiteTypes.status *
357    (Cic.term, Cic.lazy_term, Cic.lazy_term GrafiteAst.reduction, string) GrafiteAst.tactic) ->
358
359   disambiguate_command:
360    (GrafiteTypes.status ->
361     'obj GrafiteAst.command ->
362     GrafiteTypes.status * Cic.obj GrafiteAst.command) ->
363
364   options ->
365   GrafiteTypes.status ->
366   ('term, 'lazy_term, 'reduction, 'obj, 'ident) GrafiteAst.code ->
367   GrafiteTypes.status * UriManager.uri list
368  }
369
370 type 'a eval_from_moo =
371  { efm_go: GrafiteTypes.status -> string -> GrafiteTypes.status }
372       
373 let coercion_moo_statement_of uri =
374   GrafiteAst.Coercion (HExtlib.dummy_floc, uri, false)
375
376 let eval_coercion status ~add_composites uri =
377  let basedir = Helm_registry.get "matita.basedir" in
378  let status,compounds =
379   GrafiteSync.add_coercion ~basedir ~add_composites status uri in
380  let moo_content = coercion_moo_statement_of uri in
381  let status = GrafiteTypes.add_moo_content [moo_content] status in
382   {status with GrafiteTypes.proof_status = GrafiteTypes.No_proof},
383    compounds
384
385 let eval_tactical ~disambiguate_tactic status tac =
386  let apply_tactic = apply_tactic ~disambiguate_tactic in
387  let module MatitaStatus =
388   struct
389    type input_status = GrafiteTypes.status * ProofEngineTypes.goal
390  
391    type output_status =
392      GrafiteTypes.status * ProofEngineTypes.goal list * ProofEngineTypes.goal list
393  
394    type tactic = input_status -> output_status
395  
396    let id_tactic = apply_tactic (GrafiteAst.IdTac HExtlib.dummy_floc)
397    let mk_tactic tac = tac
398    let apply_tactic tac = tac
399    let goals (_, opened, closed) = opened, closed
400    let set_goals (opened, closed) (status, _, _) = (status, opened, closed)
401    let get_stack (status, _) = GrafiteTypes.get_stack status
402  
403    let set_stack stack (status, opened, closed) = 
404      GrafiteTypes.set_stack stack status, opened, closed
405  
406    let inject (status, _) = (status, [], [])
407    let focus goal (status, _, _) = (status, goal)
408   end
409  in
410  let module MatitaTacticals = Tacticals.Make (MatitaStatus) in
411   let rec tactical_of_ast l tac =
412     match tac with
413     | GrafiteAst.Tactic (loc, tactic) ->
414         MatitaTacticals.tactic (MatitaStatus.mk_tactic (apply_tactic tactic))
415     | GrafiteAst.Seq (loc, tacticals) ->  (* tac1; tac2; ... *)
416        assert (l > 0);
417        MatitaTacticals.seq ~tactics:(List.map (tactical_of_ast (l+1)) tacticals)
418     | GrafiteAst.Do (loc, n, tactical) ->
419         MatitaTacticals.do_tactic ~n ~tactic:(tactical_of_ast (l+1) tactical)
420     | GrafiteAst.Repeat (loc, tactical) ->
421         MatitaTacticals.repeat_tactic ~tactic:(tactical_of_ast (l+1) tactical)
422     | GrafiteAst.Then (loc, tactical, tacticals) ->  (* tac; [ tac1 | ... ] *)
423         assert (l > 0);
424         MatitaTacticals.thens ~start:(tactical_of_ast (l+1) tactical)
425           ~continuations:(List.map (tactical_of_ast (l+1)) tacticals)
426     | GrafiteAst.First (loc, tacticals) ->
427         MatitaTacticals.first
428           ~tactics:(List.map (fun t -> "", tactical_of_ast (l+1) t) tacticals)
429     | GrafiteAst.Try (loc, tactical) ->
430         MatitaTacticals.try_tactic ~tactic:(tactical_of_ast (l+1) tactical)
431     | GrafiteAst.Solve (loc, tacticals) ->
432         MatitaTacticals.solve_tactics
433          ~tactics:(List.map (fun t -> "", tactical_of_ast (l+1) t) tacticals)
434
435     | GrafiteAst.Skip loc -> MatitaTacticals.skip
436     | GrafiteAst.Dot loc -> MatitaTacticals.dot
437     | GrafiteAst.Semicolon loc -> MatitaTacticals.semicolon
438     | GrafiteAst.Branch loc -> MatitaTacticals.branch
439     | GrafiteAst.Shift loc -> MatitaTacticals.shift
440     | GrafiteAst.Pos (loc, i) -> MatitaTacticals.pos i
441     | GrafiteAst.Merge loc -> MatitaTacticals.merge
442     | GrafiteAst.Focus (loc, goals) -> MatitaTacticals.focus goals
443     | GrafiteAst.Unfocus loc -> MatitaTacticals.unfocus
444   in
445   let status, _, _ = tactical_of_ast 0 tac (status, ~-1) in
446   let status =  (* is proof completed? *)
447     match status.GrafiteTypes.proof_status with
448     | GrafiteTypes.Incomplete_proof
449        { GrafiteTypes.stack = stack; proof = proof }
450       when Continuationals.Stack.is_empty stack ->
451         { status with GrafiteTypes.proof_status = GrafiteTypes.Proof proof }
452     | _ -> status
453   in
454   status
455
456 let eval_comment status c = status
457
458 (* since the record syntax allows to declare coercions, we have to put this
459  * information inside the moo *)
460 let add_coercions_of_record_to_moo obj lemmas status =
461   let attributes = CicUtil.attributes_of_obj obj in
462   let is_record = function `Class (`Record att) -> Some att | _-> None in
463   match HExtlib.list_findopt is_record attributes with
464   | None -> status,[]
465   | Some fields -> 
466       let is_a_coercion uri =
467         try
468           let obj,_ = 
469             CicEnvironment.get_cooked_obj  CicUniv.empty_ugraph uri in
470           let attrs = CicUtil.attributes_of_obj obj in
471           List.mem (`Class `Projection) attrs
472         with Not_found -> assert false
473       in
474       (* looking at the fields we can know the 'wanted' coercions, but not the 
475        * actually generated ones. So, only the intersection between the wanted
476        * and the actual should be in the moo as coercion, while everithing in
477        * lemmas should go as aliases *)
478       let wanted_coercions = 
479         HExtlib.filter_map 
480           (function 
481             | (name,true) -> 
482                Some 
483                  (UriManager.uri_of_string 
484                    (GrafiteTypes.qualify status name ^ ".con"))
485             | _ -> None) 
486           fields
487       in
488       prerr_endline "wanted coercions:";
489       List.iter 
490         (fun u -> prerr_endline (UriManager.string_of_uri u)) 
491         wanted_coercions;
492       let coercions, moo_content = 
493         List.split
494           (HExtlib.filter_map 
495             (fun uri ->
496               let is_a_wanted_coercion = 
497                 List.exists (UriManager.eq uri) wanted_coercions in
498               if is_a_coercion uri && is_a_wanted_coercion then
499                 Some (uri, coercion_moo_statement_of uri)
500               else
501                 None) 
502             lemmas)
503       in
504       List.iter 
505         (fun u -> prerr_endline (UriManager.string_of_uri u)) 
506         coercions;
507       let status = GrafiteTypes.add_moo_content moo_content status in
508       let basedir = Helm_registry.get "matita.basedir" in
509       List.fold_left 
510         (fun (status,lemmas) uri ->
511           let status,new_lemmas =
512            GrafiteSync.add_coercion ~basedir ~add_composites:true status uri
513           in
514            status,new_lemmas@lemmas
515         ) (status,[]) coercions
516
517 let add_obj uri obj status =
518  let basedir = Helm_registry.get "matita.basedir" in
519  let status,lemmas = GrafiteSync.add_obj ~basedir uri obj status in
520  status, lemmas 
521       
522 let rec eval_command = {ec_go = fun ~disambiguate_command opts status cmd ->
523  let status,cmd = disambiguate_command status cmd in
524  let basedir = Helm_registry.get "matita.basedir" in
525  let status,uris =
526   match cmd with
527   | GrafiteAst.Default (loc, what, uris) as cmd ->
528      LibraryObjects.set_default what uris;
529      GrafiteTypes.add_moo_content [cmd] status,[]
530   | GrafiteAst.Include (loc, baseuri) ->
531      let moopath = LibraryMisc.obj_file_of_baseuri ~basedir ~baseuri in
532      let metadatapath= LibraryMisc.metadata_file_of_baseuri ~basedir ~baseuri in
533      if not (Sys.file_exists moopath) then
534        raise (IncludedFileNotCompiled moopath);
535      let status = eval_from_moo.efm_go status moopath in
536      status,[]
537   | GrafiteAst.Set (loc, name, value) -> 
538       if name = "baseuri" then begin
539         let value = 
540           let v = Http_getter_misc.strip_trailing_slash value in
541           try
542             ignore (String.index v ' ');
543             raise (GrafiteTypes.Command_error "baseuri can't contain spaces")
544           with Not_found -> v
545         in
546         if not (GrafiteMisc.is_empty value) && opts.clean_baseuri then begin
547           HLog.warn ("baseuri " ^ value ^ " is not empty");
548           HLog.message ("cleaning baseuri " ^ value);
549           LibraryClean.clean_baseuris ~basedir [value];
550         end;
551       end;
552       GrafiteTypes.set_option status name value,[]
553   | GrafiteAst.Drop loc -> raise Drop
554   | GrafiteAst.Qed loc ->
555       let uri, metasenv, bo, ty =
556         match status.GrafiteTypes.proof_status with
557         | GrafiteTypes.Proof (Some uri, metasenv, body, ty) ->
558             uri, metasenv, body, ty
559         | GrafiteTypes.Proof (None, metasenv, body, ty) -> 
560             raise (GrafiteTypes.Command_error 
561               ("Someone allows to start a theorem without giving the "^
562                "name/uri. This should be fixed!"))
563         | _->
564           raise
565            (GrafiteTypes.Command_error "You can't Qed an incomplete theorem")
566       in
567       if metasenv <> [] then 
568         raise
569          (GrafiteTypes.Command_error
570            "Proof not completed! metasenv is not empty!");
571       let name = UriManager.name_of_uri uri in
572       let obj = Cic.Constant (name,Some bo,ty,[],[]) in
573       let status, lemmas = add_obj uri obj status in
574        {status with GrafiteTypes.proof_status = GrafiteTypes.No_proof},
575         uri::lemmas
576   | GrafiteAst.Coercion (loc, uri, add_composites) ->
577      eval_coercion status ~add_composites uri
578   | GrafiteAst.Obj (loc,obj) ->
579      let ext,name =
580       match obj with
581          Cic.Constant (name,_,_,_,_)
582        | Cic.CurrentProof (name,_,_,_,_,_) -> ".con",name
583        | Cic.InductiveDefinition (types,_,_,_) ->
584           ".ind",
585           (match types with (name,_,_,_)::_ -> name | _ -> assert false)
586        | _ -> assert false in
587      let uri = 
588        UriManager.uri_of_string (GrafiteTypes.qualify status name ^ ext) 
589      in
590      let metasenv = GrafiteTypes.get_proof_metasenv status in
591      match obj with
592      | Cic.CurrentProof (_,metasenv',bo,ty,_,_) ->
593          let name = UriManager.name_of_uri uri in
594          if not(CicPp.check name ty) then
595            HLog.error ("Bad name: " ^ name);
596          if opts.do_heavy_checks then
597            begin
598              let dbd = LibraryDb.instance () in
599              let similar = Whelp.match_term ~dbd ty in
600              let similar_len = List.length similar in
601              if similar_len> 30 then
602                (HLog.message
603                  ("Duplicate check will compare your theorem with " ^ 
604                    string_of_int similar_len ^ 
605                    " theorems, this may take a while."));
606              let convertible =
607                List.filter (
608                  fun u ->
609                    let t = CicUtil.term_of_uri u in
610                    let ty',g = 
611                      CicTypeChecker.type_of_aux' 
612                        metasenv' [] t CicUniv.empty_ugraph
613                    in
614                    fst(CicReduction.are_convertible [] ty' ty g)) 
615                similar 
616              in
617              (match convertible with
618              | [] -> ()
619              | x::_ -> 
620                  HLog.warn  
621                  ("Theorem already proved: " ^ UriManager.string_of_uri x ^ 
622                   "\nPlease use a variant."));
623            end;
624          assert (metasenv = metasenv');
625          let goalno =
626            match metasenv' with (goalno,_,_)::_ -> goalno | _ -> assert false 
627          in
628          let initial_proof = (Some uri, metasenv, bo, ty) in
629          let initial_stack = Continuationals.Stack.of_metasenv metasenv in
630          { status with GrafiteTypes.proof_status =
631             GrafiteTypes.Incomplete_proof
632              { GrafiteTypes.proof = initial_proof; stack = initial_stack } },
633           []
634      | _ ->
635          if metasenv <> [] then
636           raise (GrafiteTypes.Command_error (
637             "metasenv not empty while giving a definition with body: " ^
638             CicMetaSubst.ppmetasenv [] metasenv));
639          let status, lemmas = add_obj uri obj status in 
640          let status,new_lemmas =
641           add_coercions_of_record_to_moo obj lemmas status
642          in
643           {status with GrafiteTypes.proof_status = GrafiteTypes.No_proof},
644            uri::new_lemmas@lemmas
645  in
646   match status.GrafiteTypes.proof_status with
647      GrafiteTypes.Intermediate _ ->
648       {status with GrafiteTypes.proof_status = GrafiteTypes.No_proof},uris
649    | _ -> status,uris
650
651 } and eval_executable = {ee_go = fun ~disambiguate_tactic ~disambiguate_command opts status ex ->
652   match ex with
653   | GrafiteAst.Tactical (_, tac, None) ->
654      eval_tactical ~disambiguate_tactic status tac,[]
655   | GrafiteAst.Tactical (_, tac, Some punct) ->
656      let status = eval_tactical ~disambiguate_tactic status tac in
657       eval_tactical ~disambiguate_tactic status punct,[]
658   | GrafiteAst.Command (_, cmd) ->
659       eval_command.ec_go ~disambiguate_command opts status cmd
660   | GrafiteAst.Macro (_, mac) -> 
661 (*CSC: DA RIPRISTINARE CON UN TIPO DIVERSO
662       raise (Command_error
663        (Printf.sprintf "The macro %s can't be in a script" 
664         (GrafiteAstPp.pp_macro_ast mac)))
665 *) assert false
666
667 } and eval_from_moo = {efm_go = fun status fname ->
668   let ast_of_cmd cmd =
669     GrafiteAst.Executable (HExtlib.dummy_floc,
670       GrafiteAst.Command (HExtlib.dummy_floc,
671         cmd))
672   in
673   let moo = GrafiteMarshal.load_moo fname in
674   List.fold_left 
675     (fun status ast -> 
676       let ast = ast_of_cmd ast in
677       let status,lemmas =
678        eval_ast.ea_go
679          ~disambiguate_tactic:(fun status _ tactic -> status,tactic)
680          ~disambiguate_command:(fun status cmd -> status,cmd)
681          status ast
682       in
683        assert (lemmas=[]);
684        status)
685     status moo
686 } and eval_ast = {ea_go = fun ~disambiguate_tactic ~disambiguate_command ?(do_heavy_checks=false) ?(clean_baseuri=true) status
687  st 
688 ->
689   let opts = {
690     do_heavy_checks = do_heavy_checks ; 
691     clean_baseuri = clean_baseuri }
692   in
693   match st with
694   | GrafiteAst.Executable (_,ex) ->
695      eval_executable.ee_go ~disambiguate_tactic
696       ~disambiguate_command opts status ex
697   | GrafiteAst.Comment (_,c) -> eval_comment status c,[]
698 }
699
700 let eval_ast = eval_ast.ea_go