]> matita.cs.unibo.it Git - helm.git/blob - components/grafite_engine/grafiteEngine.ml
- semantics of tactic subst allmost fixed
[helm.git] / components / 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 (* $Id$ *)
27
28 module GT = GrafiteTypes
29
30 open Printf
31
32 exception Drop
33 (* mo file name, ma file name *)
34 exception IncludedFileNotCompiled of string * string 
35 exception Macro of
36  GrafiteAst.loc *
37   (Cic.context -> GT.status * Cic.term GrafiteAst.macro)
38 exception ReadOnlyUri of string
39
40 type 'a disambiguator_input = string * int * 'a
41
42 type options = { 
43   do_heavy_checks: bool ; 
44   clean_baseuri: bool
45 }
46
47 (** create a ProofEngineTypes.mk_fresh_name_type function which uses given
48   * names as long as they are available, then it fallbacks to name generation
49   * using FreshNamesGenerator module *)
50 let namer_of names =
51   let len = List.length names in
52   let count = ref 0 in
53   fun metasenv context name ~typ ->
54     if !count < len then begin
55       let name = Cic.Name (List.nth names !count) in
56       incr count;
57       name
58     end else
59       FreshNamesGenerator.mk_fresh_name ~subst:[] metasenv context name ~typ
60
61 let tactic_of_ast ast =
62   let module PET = ProofEngineTypes in
63   match ast with
64   | GrafiteAst.Absurd (_, term) -> Tactics.absurd term
65   | GrafiteAst.Apply (_, term) -> Tactics.apply term
66   | GrafiteAst.ApplyS (_, term) ->
67      Tactics.applyS ~term ~dbd:(LibraryDb.instance ())
68   | GrafiteAst.Assumption _ -> Tactics.assumption
69   | GrafiteAst.Auto (_,params) ->
70       AutoTactic.auto_tac ~params ~dbd:(LibraryDb.instance ()) 
71   | GrafiteAst.Change (_, pattern, with_what) ->
72      Tactics.change ~pattern with_what
73   | GrafiteAst.Clear (_,id) -> Tactics.clear id
74   | GrafiteAst.ClearBody (_,id) -> Tactics.clearbody id
75   | GrafiteAst.Contradiction _ -> Tactics.contradiction
76   | GrafiteAst.Constructor (_, n) -> Tactics.constructor n
77   | GrafiteAst.Cut (_, ident, term) ->
78      let names = match ident with None -> [] | Some id -> [id] in
79      Tactics.cut ~mk_fresh_name_callback:(namer_of names) term
80   | GrafiteAst.Decompose (_, types, what, names) -> 
81       let to_type = function
82          | GrafiteAst.Type (uri, typeno) -> uri, typeno
83          | GrafiteAst.Ident _            -> assert false
84       in
85       let user_types = List.rev_map to_type types in
86       let dbd = LibraryDb.instance () in
87       let mk_fresh_name_callback = namer_of names in
88       Tactics.decompose ~mk_fresh_name_callback ~dbd ~user_types ?what
89   | GrafiteAst.Demodulate _ -> Tactics.demodulate ~dbd:(LibraryDb.instance ())
90   | GrafiteAst.Discriminate (_,term) -> Tactics.discriminate term
91   | GrafiteAst.Elim (_, what, using, depth, names) ->
92       Tactics.elim_intros ?using ?depth ~mk_fresh_name_callback:(namer_of names)
93         what
94   | GrafiteAst.ElimType (_, what, using, depth, names) ->
95       Tactics.elim_type ?using ?depth ~mk_fresh_name_callback:(namer_of names)
96         what
97   | GrafiteAst.Exact (_, term) -> Tactics.exact term
98   | GrafiteAst.Exists _ -> Tactics.exists
99   | GrafiteAst.Fail _ -> Tactics.fail
100   | GrafiteAst.Fold (_, reduction_kind, term, pattern) ->
101       let reduction =
102         match reduction_kind with
103         | `Normalize ->
104             PET.const_lazy_reduction
105               (CicReduction.normalize ~delta:false ~subst:[])
106         | `Reduce -> PET.const_lazy_reduction ProofEngineReduction.reduce
107         | `Simpl -> PET.const_lazy_reduction ProofEngineReduction.simpl
108         | `Unfold None ->
109             PET.const_lazy_reduction (ProofEngineReduction.unfold ?what:None)
110         | `Unfold (Some lazy_term) ->
111            (fun context metasenv ugraph ->
112              let what, metasenv, ugraph = lazy_term context metasenv ugraph in
113              ProofEngineReduction.unfold ~what, metasenv, ugraph)
114         | `Whd ->
115             PET.const_lazy_reduction (CicReduction.whd ~delta:false ~subst:[])
116       in
117       Tactics.fold ~reduction ~term ~pattern
118   | GrafiteAst.Fourier _ -> Tactics.fourier
119   | GrafiteAst.FwdSimpl (_, hyp, names) -> 
120      Tactics.fwd_simpl ~mk_fresh_name_callback:(namer_of names)
121       ~dbd:(LibraryDb.instance ()) hyp
122   | GrafiteAst.Generalize (_,pattern,ident) ->
123      let names = match ident with None -> [] | Some id -> [id] in
124      Tactics.generalize ~mk_fresh_name_callback:(namer_of names) pattern 
125   | GrafiteAst.Goal (_, n) -> Tactics.set_goal n
126   | GrafiteAst.IdTac _ -> Tactics.id
127   | GrafiteAst.Injection (_,term) -> Tactics.injection term
128   | GrafiteAst.Intros (_, None, names) ->
129       PrimitiveTactics.intros_tac ~mk_fresh_name_callback:(namer_of names) ()
130   | GrafiteAst.Intros (_, Some num, names) ->
131       PrimitiveTactics.intros_tac ~howmany:num
132         ~mk_fresh_name_callback:(namer_of names) ()
133   | GrafiteAst.Inversion (_, term) ->
134       Tactics.inversion term
135   | GrafiteAst.LApply (_, linear, how_many, to_what, what, ident) ->
136       let names = match ident with None -> [] | Some id -> [id] in
137       Tactics.lapply ~mk_fresh_name_callback:(namer_of names) 
138         ~linear ?how_many ~to_what what
139   | GrafiteAst.Left _ -> Tactics.left
140   | GrafiteAst.LetIn (loc,term,name) ->
141       Tactics.letin term ~mk_fresh_name_callback:(namer_of [name])
142   | GrafiteAst.Reduce (_, reduction_kind, pattern) ->
143       (match reduction_kind with
144          | `Normalize -> Tactics.normalize ~pattern
145          | `Reduce -> Tactics.reduce ~pattern  
146          | `Simpl -> Tactics.simpl ~pattern 
147          | `Unfold what -> Tactics.unfold ~pattern what
148          | `Whd -> Tactics.whd ~pattern)
149   | GrafiteAst.Reflexivity _ -> Tactics.reflexivity
150   | GrafiteAst.Replace (_, pattern, with_what) ->
151      Tactics.replace ~pattern ~with_what
152   | GrafiteAst.Rewrite (_, direction, t, pattern) ->
153      EqualityTactics.rewrite_tac ~direction ~pattern t
154   | GrafiteAst.Right _ -> Tactics.right
155   | GrafiteAst.Ring _ -> Tactics.ring
156   | GrafiteAst.Split _ -> Tactics.split
157   | GrafiteAst.Subst _ -> Tactics.subst
158   | GrafiteAst.Symmetry _ -> Tactics.symmetry
159   | GrafiteAst.Transitivity (_, term) -> Tactics.transitivity term
160   (* Implementazioni Aggiunte *)
161   | GrafiteAst.Assume (_, id, t) -> Declarative.assume id t
162   | GrafiteAst.Suppose (_, t, id, t1) -> Declarative.suppose t id t1
163   | GrafiteAst.By_term_we_proved (_, t, ty, id, t1) ->
164      Declarative.by_term_we_proved ~dbd:(LibraryDb.instance()) t ty id t1
165   | GrafiteAst.We_need_to_prove (_, t, id, t2) ->
166      Declarative.we_need_to_prove t id t2
167   | GrafiteAst.Bydone (_, t) -> Declarative.bydone ~dbd:(LibraryDb.instance()) t
168   | GrafiteAst.We_proceed_by_induction_on (_, t, t1) ->
169      Declarative.we_proceed_by_induction_on t t1
170   | GrafiteAst.Byinduction (_, t, id) -> Declarative.byinduction t id
171   | GrafiteAst.Thesisbecomes (_, t) -> Declarative.thesisbecomes t
172   | GrafiteAst.ExistsElim (_, t, id1, t1, id2, t2) ->
173      Declarative.existselim t id1 t1 id2 t2
174   | GrafiteAst.Case (_,id,params) -> Declarative.case id params
175   | GrafiteAst.AndElim(_,t,id1,t1,id2,t2) -> Declarative.andelim t id1 t1 id2 t2
176   | GrafiteAst.RewritingStep (_,termine,t1,t2,cont) ->
177      Declarative.rewritingstep ~dbd:(LibraryDb.instance ()) termine t1 t2 cont
178
179 let classify_tactic tactic = 
180   match tactic with
181   (* tactics that can't close the goal (return a goal we want to "select") *)
182   | GrafiteAst.Rewrite _ 
183   | GrafiteAst.Split _ 
184   | GrafiteAst.Replace _ 
185   | GrafiteAst.Reduce _
186   | GrafiteAst.Injection _ 
187   | GrafiteAst.IdTac _ 
188   | GrafiteAst.Generalize _ 
189   | GrafiteAst.Elim _ 
190   | GrafiteAst.Cut _
191   | GrafiteAst.Decompose _ -> true, true
192   (* tactics we don't want to reorder goals. I think only Goal needs this. *)
193   | GrafiteAst.Goal _ -> false, true
194   (* tactics like apply *)
195   | _ -> true, false
196   
197 let reorder_metasenv start refine tactic goals current_goal always_opens_a_goal=
198   let module PEH = ProofEngineHelpers in
199 (*   let print_m name metasenv =
200     prerr_endline (">>>>> " ^ name);
201     prerr_endline (CicMetaSubst.ppmetasenv [] metasenv)
202   in *)
203   (* phase one calculates:
204    *   new_goals_from_refine:  goals added by refine
205    *   head_goal:              the first goal opened by ythe tactic 
206    *   other_goals:            other goals opened by the tactic
207    *)
208   let new_goals_from_refine = PEH.compare_metasenvs start refine in
209   let new_goals_from_tactic = PEH.compare_metasenvs refine tactic in
210   let head_goal, other_goals, goals = 
211     match goals with
212     | [] -> None,[],goals
213     | hd::tl -> 
214         (* assert (List.mem hd new_goals_from_tactic);
215          * invalidato dalla goal_tac
216          * *)
217         Some hd, List.filter ((<>) hd) new_goals_from_tactic, List.filter ((<>)
218         hd) goals
219   in
220   let produced_goals = 
221     match head_goal with
222     | None -> new_goals_from_refine @ other_goals
223     | Some x -> x :: new_goals_from_refine @ other_goals
224   in
225   (* extract the metas generated by refine and tactic *)
226   let metas_for_tactic_head = 
227     match head_goal with
228     | None -> []
229     | Some head_goal -> List.filter (fun (n,_,_) -> n = head_goal) tactic in
230   let metas_for_tactic_goals = 
231     List.map 
232       (fun x -> List.find (fun (metano,_,_) -> metano = x) tactic)
233     goals 
234   in
235   let metas_for_refine_goals = 
236     List.filter (fun (n,_,_) -> List.mem n new_goals_from_refine) tactic in
237   let produced_metas, goals = 
238     let produced_metas =
239       if always_opens_a_goal then
240         metas_for_tactic_head @ metas_for_refine_goals @ 
241           metas_for_tactic_goals
242       else begin
243 (*         print_m "metas_for_refine_goals" metas_for_refine_goals;
244         print_m "metas_for_tactic_head" metas_for_tactic_head;
245         print_m "metas_for_tactic_goals" metas_for_tactic_goals; *)
246         metas_for_refine_goals @ metas_for_tactic_head @ 
247           metas_for_tactic_goals
248       end
249     in
250     let goals = List.map (fun (metano, _, _) -> metano)  produced_metas in
251     produced_metas, goals
252   in
253   (* residual metas, preserving the original order *)
254   let before, after = 
255     let rec split e =
256       function 
257       | [] -> [],[]
258       | (metano, _, _) :: tl when metano = e -> 
259           [], List.map (fun (x,_,_) -> x) tl
260       | (metano, _, _) :: tl -> let b, a = split e tl in metano :: b, a
261     in
262     let find n metasenv =
263       try
264         Some (List.find (fun (metano, _, _) -> metano = n) metasenv)
265       with Not_found -> None
266     in
267     let extract l =
268       List.fold_right 
269         (fun n acc -> 
270           match find n tactic with
271           | Some x -> x::acc
272           | None -> acc
273         ) l [] in
274     let before_l, after_l = split current_goal start in
275     let before_l = 
276       List.filter (fun x -> not (List.mem x produced_goals)) before_l in
277     let after_l = 
278       List.filter (fun x -> not (List.mem x produced_goals)) after_l in
279     let before = extract before_l in
280     let after = extract after_l in
281       before, after
282   in
283 (* |+   DEBUG CODE  +|
284   print_m "BEGIN" start;
285   prerr_endline ("goal was: " ^ string_of_int current_goal);
286   prerr_endline ("and metas from refine are:");
287   List.iter 
288     (fun t -> prerr_string (" " ^ string_of_int t)) 
289   new_goals_from_refine;
290   prerr_endline "";
291   print_m "before" before;
292   print_m "metas_for_tactic_head" metas_for_tactic_head;
293   print_m "metas_for_refine_goals" metas_for_refine_goals;
294   print_m "metas_for_tactic_goals" metas_for_tactic_goals;
295   print_m "produced_metas" produced_metas;
296   print_m "after" after; 
297 |+   FINE DEBUG CODE +| *)
298   before @ produced_metas @ after, goals 
299   
300 let apply_tactic ~disambiguate_tactic (text,prefix_len,tactic) (status, goal) =
301 (* prerr_endline "apply_tactic"; *)
302 (* prerr_endline (Continuationals.Stack.pp (GT.get_stack status)); *)
303  let starting_metasenv = GT.get_proof_metasenv status in
304  let before = List.map (fun g, _, _ -> g) starting_metasenv in
305 (* prerr_endline "disambiguate"; *)
306  let status, tactic = disambiguate_tactic status goal (text,prefix_len,tactic) in
307  let metasenv_after_refinement =  GT.get_proof_metasenv status in
308  let proof = GT.get_current_proof status in
309  let proof_status = proof, goal in
310  let needs_reordering, always_opens_a_goal = classify_tactic tactic in
311  let tactic = tactic_of_ast tactic in
312  (* apply tactic will change the lexicon_status ... *)
313 (* prerr_endline "apply_tactic bassa"; *)
314  let (proof, opened) = ProofEngineTypes.apply_tactic tactic proof_status in
315  let after = ProofEngineTypes.goals_of_proof proof in
316  let opened_goals, closed_goals = Tacticals.goals_diff ~before ~after ~opened in
317 (* prerr_endline("before: " ^ String.concat ", " (List.map string_of_int before));
318 prerr_endline("after: " ^ String.concat ", " (List.map string_of_int after));
319 prerr_endline("opened: " ^ String.concat ", " (List.map string_of_int opened)); *)
320 (* prerr_endline("opened_goals: " ^ String.concat ", " (List.map string_of_int opened_goals));
321 prerr_endline("closed_goals: " ^ String.concat ", " (List.map string_of_int closed_goals)); *)
322  let proof, opened_goals = 
323    if needs_reordering then begin
324      let uri, metasenv_after_tactic, t, ty = proof in
325 (* prerr_endline ("goal prima del riordino: " ^ String.concat " " (List.map string_of_int (ProofEngineTypes.goals_of_proof proof))); *)
326      let reordered_metasenv, opened_goals = 
327        reorder_metasenv
328         starting_metasenv
329         metasenv_after_refinement metasenv_after_tactic
330         opened goal always_opens_a_goal
331      in
332      let proof' = uri, reordered_metasenv, t, ty in
333 (* prerr_endline ("goal dopo il riordino: " ^ String.concat " " (List.map string_of_int (ProofEngineTypes.goals_of_proof proof'))); *)
334      proof', opened_goals
335    end
336       else
337         proof, opened_goals
338  in
339  let incomplete_proof =
340    match status.GT.proof_status with
341    | GT.Incomplete_proof p -> p
342    | _ -> assert false
343  in
344  { status with GT.proof_status =
345     GT.Incomplete_proof
346      { incomplete_proof with GT.proof = proof } },
347  opened_goals, closed_goals
348
349 type eval_ast =
350  {ea_go:
351   'term 'lazy_term 'reduction 'obj 'ident.
352   disambiguate_tactic:
353    (GT.status ->
354     ProofEngineTypes.goal ->
355     (('term, 'lazy_term, 'reduction, 'ident) GrafiteAst.tactic)
356     disambiguator_input ->
357     GT.status *
358    (Cic.term, Cic.lazy_term, Cic.lazy_term GrafiteAst.reduction, string) GrafiteAst.tactic) ->
359
360   disambiguate_command:
361    (GT.status ->
362     ('obj GrafiteAst.command) disambiguator_input ->
363     GT.status * Cic.obj GrafiteAst.command) ->
364
365   disambiguate_macro:
366    (GT.status ->
367     ('term GrafiteAst.macro) disambiguator_input ->
368     Cic.context -> GT.status * Cic.term GrafiteAst.macro) ->
369
370   ?do_heavy_checks:bool ->
371   ?clean_baseuri:bool ->
372   GT.status ->
373   (('term, 'lazy_term, 'reduction, 'obj, 'ident) GrafiteAst.statement)
374   disambiguator_input ->
375   GT.status * UriManager.uri list
376  }
377
378 type 'a eval_command =
379  {ec_go: 'term 'obj.
380   disambiguate_command:
381    (GT.status -> ('obj GrafiteAst.command) disambiguator_input ->
382     GT.status * Cic.obj GrafiteAst.command) -> 
383   options -> GT.status -> 
384     ('obj GrafiteAst.command) disambiguator_input ->
385    GT.status * UriManager.uri list
386  }
387
388 type 'a eval_executable =
389  {ee_go: 'term 'lazy_term 'reduction 'obj 'ident.
390   disambiguate_tactic:
391    (GT.status ->
392     ProofEngineTypes.goal ->
393     (('term, 'lazy_term, 'reduction, 'ident) GrafiteAst.tactic)
394     disambiguator_input ->
395     GT.status *
396    (Cic.term, Cic.lazy_term, Cic.lazy_term GrafiteAst.reduction, string) GrafiteAst.tactic) ->
397
398   disambiguate_command:
399    (GT.status ->
400     ('obj GrafiteAst.command) disambiguator_input ->
401     GT.status * Cic.obj GrafiteAst.command) ->
402
403   disambiguate_macro:
404    (GT.status ->
405     ('term GrafiteAst.macro) disambiguator_input ->
406     Cic.context -> GT.status * Cic.term GrafiteAst.macro) ->
407
408   options ->
409   GT.status ->
410   (('term, 'lazy_term, 'reduction, 'obj, 'ident) GrafiteAst.code) disambiguator_input ->
411   GT.status * UriManager.uri list
412  }
413
414 type 'a eval_from_moo =
415  { efm_go: GT.status -> string -> GT.status }
416       
417 let coercion_moo_statement_of uri =
418   GrafiteAst.Coercion (HExtlib.dummy_floc, uri, false)
419
420 let refinement_toolkit = {
421   RefinementTool.type_of_aux' = 
422     (fun ?localization_tbl e c t u ->
423       let saved = !CicRefine.insert_coercions in 
424       CicRefine.insert_coercions:= false;
425       let rc = 
426         try 
427           let t, ty, metasenv, ugraph = 
428             CicRefine.type_of_aux' ?localization_tbl e c t u in
429           RefinementTool.Success (t, ty, metasenv, ugraph)
430         with
431         | CicRefine.RefineFailure s
432         | CicRefine.Uncertain s 
433         | CicRefine.AssertFailure s -> RefinementTool.Exception s
434       in
435       CicRefine.insert_coercions := saved;
436       rc);
437   RefinementTool.ppsubst = CicMetaSubst.ppsubst;
438   RefinementTool.apply_subst = CicMetaSubst.apply_subst; 
439   RefinementTool.ppmetasenv = CicMetaSubst.ppmetasenv; 
440   RefinementTool.pack_coercion_obj = CicRefine.pack_coercion_obj;
441  }
442   
443 let eval_coercion status ~add_composites uri =
444  let status,compounds =
445   GrafiteSync.add_coercion ~add_composites refinement_toolkit status uri in
446  let moo_content = 
447    List.map coercion_moo_statement_of (uri::compounds)
448  in
449  let status = GT.add_moo_content moo_content status in
450   {status with GT.proof_status = GT.No_proof},
451    compounds
452
453 let eval_tactical ~disambiguate_tactic status tac =
454  let apply_tactic = apply_tactic ~disambiguate_tactic in
455  let module MatitaStatus =
456   struct
457    type input_status = GT.status * ProofEngineTypes.goal
458  
459    type output_status =
460      GT.status * ProofEngineTypes.goal list * ProofEngineTypes.goal list
461  
462    type tactic = input_status -> output_status
463  
464    let id_tactic = apply_tactic ("",0,(GrafiteAst.IdTac HExtlib.dummy_floc))
465    let mk_tactic tac = tac
466    let apply_tactic tac = tac
467    let goals (_, opened, closed) = opened, closed
468    let set_goals (opened, closed) (status, _, _) = (status, opened, closed)
469    let get_stack (status, _) = GT.get_stack status
470    
471    let get_status (status, goal) =
472       match status.GT.proof_status with
473          | GT.Incomplete_proof incomplete -> incomplete.GT.proof, goal
474          | _                              -> assert false
475       
476    let get_proof (status, _, _) =
477       match status.GT.proof_status with
478          | GT.Incomplete_proof incomplete -> incomplete.GT.proof
479          | _                              -> assert false
480  
481    let set_stack stack (status, opened, closed) = 
482      GT.set_stack stack status, opened, closed
483  
484    let inject (status, _) = (status, [], [])
485    let focus goal (status, _, _) = (status, goal)
486   end
487  in
488  let module MatitaTacticals = Tacticals.Make (MatitaStatus) in
489   let rec tactical_of_ast l (text,prefix_len,tac) =
490     let apply_tactic t = apply_tactic (text, prefix_len, t) in
491     let tactical_of_ast l t = tactical_of_ast l (text,prefix_len,t) in
492     match tac with
493     | GrafiteAst.Tactic (loc, tactic) ->
494         MatitaTacticals.tactic (MatitaStatus.mk_tactic (apply_tactic tactic))
495     | GrafiteAst.Seq (loc, tacticals) ->  (* tac1; tac2; ... *)
496        assert (l > 0);
497        MatitaTacticals.seq ~tactics:(List.map (tactical_of_ast (l+1)) tacticals)
498     | GrafiteAst.Do (loc, n, tactical) ->
499         MatitaTacticals.do_tactic ~n ~tactic:(tactical_of_ast (l+1) tactical)
500     | GrafiteAst.Repeat (loc, tactical) ->
501         MatitaTacticals.repeat_tactic ~tactic:(tactical_of_ast (l+1) tactical)
502     | GrafiteAst.Then (loc, tactical, tacticals) ->  (* tac; [ tac1 | ... ] *)
503         assert (l > 0);
504         MatitaTacticals.thens ~start:(tactical_of_ast (l+1) tactical)
505           ~continuations:(List.map (tactical_of_ast (l+1)) tacticals)
506     | GrafiteAst.First (loc, tacticals) ->
507         MatitaTacticals.first
508           ~tactics:(List.map (fun t -> "", tactical_of_ast (l+1) t) tacticals)
509     | GrafiteAst.Try (loc, tactical) ->
510         MatitaTacticals.try_tactic ~tactic:(tactical_of_ast (l+1) tactical)
511     | GrafiteAst.Solve (loc, tacticals) ->
512         MatitaTacticals.solve_tactics
513          ~tactics:(List.map (fun t -> "", tactical_of_ast (l+1) t) tacticals)
514     | GrafiteAst.Progress (loc, tactical) ->
515         MatitaTacticals.progress_tactic ~tactic:(tactical_of_ast (l+1) tactical)
516
517     | GrafiteAst.Skip _loc -> MatitaTacticals.skip
518     | GrafiteAst.Dot _loc -> MatitaTacticals.dot
519     | GrafiteAst.Semicolon _loc -> MatitaTacticals.semicolon
520     | GrafiteAst.Branch _loc -> MatitaTacticals.branch
521     | GrafiteAst.Shift _loc -> MatitaTacticals.shift
522     | GrafiteAst.Pos (_loc, i) -> MatitaTacticals.pos i
523     | GrafiteAst.Merge _loc -> MatitaTacticals.merge
524     | GrafiteAst.Focus (_loc, goals) -> MatitaTacticals.focus goals
525     | GrafiteAst.Unfocus _loc -> MatitaTacticals.unfocus
526     | GrafiteAst.Wildcard _loc -> MatitaTacticals.wildcard
527   in
528   let status, _, _ = tactical_of_ast 0 tac (status, ~-1) in
529   let status =  (* is proof completed? *)
530     match status.GT.proof_status with
531     | GT.Incomplete_proof
532        { GT.stack = stack; proof = proof }
533       when Continuationals.Stack.is_empty stack ->
534         { status with GT.proof_status = GT.Proof proof }
535     | _ -> status
536   in
537   status
538
539 let eval_comment status c = status
540
541 (* since the record syntax allows to declare coercions, we have to put this
542  * information inside the moo *)
543 let add_coercions_of_record_to_moo obj lemmas status =
544   let attributes = CicUtil.attributes_of_obj obj in
545   let is_record = function `Class (`Record att) -> Some att | _-> None in
546   match HExtlib.list_findopt is_record attributes with
547   | None -> status,[]
548   | Some fields -> 
549       let is_a_coercion uri =
550         try
551           let obj,_ = 
552             CicEnvironment.get_cooked_obj  CicUniv.empty_ugraph uri in
553           let attrs = CicUtil.attributes_of_obj obj in
554           List.mem (`Class `Coercion) attrs
555         with Not_found -> assert false
556       in
557       (* looking at the fields we can know the 'wanted' coercions, but not the 
558        * actually generated ones. So, only the intersection between the wanted
559        * and the actual should be in the moo as coercion, while everithing in
560        * lemmas should go as aliases *)
561       let wanted_coercions = 
562         HExtlib.filter_map 
563           (function 
564             | (name,true) -> 
565                Some 
566                  (UriManager.uri_of_string 
567                    (GT.qualify status name ^ ".con"))
568             | _ -> None) 
569           fields
570       in
571       (*prerr_endline "wanted coercions:";
572       List.iter 
573         (fun u -> prerr_endline (UriManager.string_of_uri u)) 
574         wanted_coercions; *)
575       let coercions, moo_content = 
576         List.split
577           (HExtlib.filter_map 
578             (fun uri ->
579               let is_a_wanted_coercion = 
580                 List.exists (UriManager.eq uri) wanted_coercions 
581               in
582               if is_a_coercion uri || is_a_wanted_coercion then
583                 Some (uri, coercion_moo_statement_of uri)
584               else
585                 None) 
586             lemmas)
587       in
588       (*prerr_endline "actual coercions:";
589       List.iter 
590         (fun u -> prerr_endline (UriManager.string_of_uri u)) 
591         coercions; 
592       prerr_endline "lemmas was:";
593       List.iter 
594         (fun u -> prerr_endline (UriManager.string_of_uri u)) 
595         lemmas; *)
596       let status = GT.add_moo_content moo_content status in 
597       {status with 
598         GT.coercions = coercions @ status.GT.coercions}, 
599       lemmas
600
601 let add_obj uri obj status =
602  let status,lemmas = GrafiteSync.add_obj refinement_toolkit uri obj status in
603  status, lemmas 
604       
605 let rec eval_command = {ec_go = fun ~disambiguate_command opts status
606 (text,prefix_len,cmd) ->
607  let status,cmd = disambiguate_command status (text,prefix_len,cmd) in
608  let status,uris =
609   match cmd with
610   | GrafiteAst.Print (_,"proofterm") ->
611       let _,_,p,_ = GT.get_current_proof status in
612       print_endline (AutoTactic.pp_proofterm p);
613       status,[]
614   | GrafiteAst.Print (_,_) -> status,[]
615   | GrafiteAst.Default (loc, what, uris) as cmd ->
616      LibraryObjects.set_default what uris;
617      GT.add_moo_content [cmd] status,[]
618   | GrafiteAst.Include (loc, baseuri) ->
619      let moopath_rw, moopath_r = 
620        LibraryMisc.obj_file_of_baseuri 
621          ~must_exist:false ~baseuri ~writable:true,
622        LibraryMisc.obj_file_of_baseuri 
623          ~must_exist:false ~baseuri ~writable:false
624      in
625      let moopath = 
626        if Sys.file_exists moopath_r then moopath_r else
627          if Sys.file_exists moopath_rw then moopath_rw else
628            raise (IncludedFileNotCompiled (moopath_rw,baseuri))
629      in
630      let status = eval_from_moo.efm_go status moopath in
631      status,[]
632   | GrafiteAst.Set (loc, name, value) -> 
633       if name = "baseuri" then begin
634         let value = 
635           let v = Http_getter_misc.strip_trailing_slash value in
636           try
637             ignore (String.index v ' ');
638             GT.command_error "baseuri can't contain spaces"
639           with Not_found -> v
640         in
641         if Http_getter_storage.is_read_only value then begin
642           HLog.error (sprintf "uri %s belongs to a read-only repository" value);
643           raise (ReadOnlyUri value)
644         end;
645         if not (Http_getter_storage.is_empty value) && 
646            opts.clean_baseuri 
647           then begin
648           HLog.message ("baseuri " ^ value ^ " is not empty");
649           HLog.message ("cleaning baseuri " ^ value);
650           LibraryClean.clean_baseuris [value];
651           assert (Http_getter_storage.is_empty value);
652         end;
653         if not (Helm_registry.get_opt_default Helm_registry.bool "matita.nodisk"
654                   ~default:false) 
655         then
656           HExtlib.mkdir 
657             (Filename.dirname (Http_getter.filename ~writable:true (value ^
658               "/foo.con")));
659       end;
660       GT.set_option status name value,[]
661   | GrafiteAst.Drop loc -> raise Drop
662   | GrafiteAst.Qed loc ->
663       let uri, metasenv, bo, ty =
664         match status.GT.proof_status with
665         | GT.Proof (Some uri, metasenv, body, ty) ->
666             uri, metasenv, body, ty
667         | GT.Proof (None, metasenv, body, ty) -> 
668             raise (GT.Command_error 
669               ("Someone allows to start a theorem without giving the "^
670                "name/uri. This should be fixed!"))
671         | _->
672           raise
673            (GT.Command_error "You can't Qed an incomplete theorem")
674       in
675       if metasenv <> [] then 
676         raise
677          (GT.Command_error
678            "Proof not completed! metasenv is not empty!");
679       let name = UriManager.name_of_uri uri in
680       let obj = Cic.Constant (name,Some bo,ty,[],[]) in
681       let status, lemmas = add_obj uri obj status in
682        {status with GT.proof_status = GT.No_proof},
683         uri::lemmas
684   | GrafiteAst.Coercion (loc, uri, add_composites) ->
685      eval_coercion status ~add_composites uri
686   | GrafiteAst.Obj (loc,obj) ->
687      let ext,name =
688       match obj with
689          Cic.Constant (name,_,_,_,_)
690        | Cic.CurrentProof (name,_,_,_,_,_) -> ".con",name
691        | Cic.InductiveDefinition (types,_,_,_) ->
692           ".ind",
693           (match types with (name,_,_,_)::_ -> name | _ -> assert false)
694        | _ -> assert false in
695      let uri = 
696        UriManager.uri_of_string (GT.qualify status name ^ ext) in
697      let obj = CicRefine.pack_coercion_obj obj in
698      let metasenv = GT.get_proof_metasenv status in
699      match obj with
700      | Cic.CurrentProof (_,metasenv',bo,ty,_,_) ->
701          let name = UriManager.name_of_uri uri in
702          if not(CicPp.check name ty) then
703            HLog.error ("Bad name: " ^ name);
704          if opts.do_heavy_checks then
705            begin
706              let dbd = LibraryDb.instance () in
707              let similar = Whelp.match_term ~dbd ty in
708              let similar_len = List.length similar in
709              if similar_len> 30 then
710                (HLog.message
711                  ("Duplicate check will compare your theorem with " ^ 
712                    string_of_int similar_len ^ 
713                    " theorems, this may take a while."));
714              let convertible =
715                List.filter (
716                  fun u ->
717                    let t = CicUtil.term_of_uri u in
718                    let ty',g = 
719                      CicTypeChecker.type_of_aux' 
720                        metasenv' [] t CicUniv.empty_ugraph
721                    in
722                    fst(CicReduction.are_convertible [] ty' ty g)) 
723                similar 
724              in
725              (match convertible with
726              | [] -> ()
727              | x::_ -> 
728                  HLog.warn  
729                  ("Theorem already proved: " ^ UriManager.string_of_uri x ^ 
730                   "\nPlease use a variant."));
731            end;
732          let initial_proof = (Some uri, metasenv', bo, ty) in
733          let initial_stack = Continuationals.Stack.of_metasenv metasenv' in
734          { status with GT.proof_status =
735             GT.Incomplete_proof
736              { GT.proof = initial_proof; stack = initial_stack } },
737           []
738      | _ ->
739          if metasenv <> [] then
740           raise (GT.Command_error (
741             "metasenv not empty while giving a definition with body: " ^
742             CicMetaSubst.ppmetasenv [] metasenv));
743          let status, lemmas = add_obj uri obj status in 
744          let status,new_lemmas =
745           add_coercions_of_record_to_moo obj lemmas status
746          in
747           {status with GT.proof_status = GT.No_proof},
748            uri::new_lemmas@lemmas
749  in
750   match status.GT.proof_status with
751      GT.Intermediate _ ->
752       {status with GT.proof_status = GT.No_proof},uris
753    | _ -> status,uris
754
755 } and eval_executable = {ee_go = fun ~disambiguate_tactic ~disambiguate_command
756 ~disambiguate_macro opts status (text,prefix_len,ex) ->
757   match ex with
758   | GrafiteAst.Tactical (_, tac, None) ->
759      eval_tactical ~disambiguate_tactic status (text,prefix_len,tac),[]
760   | GrafiteAst.Tactical (_, tac, Some punct) ->
761      let status = 
762        eval_tactical ~disambiguate_tactic status (text,prefix_len,tac) in
763       eval_tactical ~disambiguate_tactic status (text,prefix_len,punct),[]
764   | GrafiteAst.Command (_, cmd) ->
765       eval_command.ec_go ~disambiguate_command opts status (text,prefix_len,cmd)
766   | GrafiteAst.Macro (loc, macro) ->
767      raise (Macro (loc,disambiguate_macro status (text,prefix_len,macro)))
768
769 } and eval_from_moo = {efm_go = fun status fname ->
770   let ast_of_cmd cmd =
771     ("",0,GrafiteAst.Executable (HExtlib.dummy_floc,
772       GrafiteAst.Command (HExtlib.dummy_floc,
773         cmd)))
774   in
775   let moo = GrafiteMarshal.load_moo fname in
776   List.fold_left 
777     (fun status ast -> 
778       let ast = ast_of_cmd ast in
779       let status,lemmas =
780        eval_ast.ea_go
781          ~disambiguate_tactic:(fun status _ (_,_,tactic) -> status,tactic)
782          ~disambiguate_command:(fun status (_,_,cmd) -> status,cmd)
783          ~disambiguate_macro:(fun _ _ -> assert false)
784          status ast
785       in
786        assert (lemmas=[]);
787        status)
788     status moo
789 } and eval_ast = {ea_go = fun ~disambiguate_tactic ~disambiguate_command
790 ~disambiguate_macro ?(do_heavy_checks=false) ?(clean_baseuri=true) status
791 (text,prefix_len,st)
792 ->
793   let opts = {
794     do_heavy_checks = do_heavy_checks ; 
795     clean_baseuri = clean_baseuri }
796   in
797   match st with
798   | GrafiteAst.Executable (_,ex) ->
799      eval_executable.ee_go ~disambiguate_tactic ~disambiguate_command
800       ~disambiguate_macro opts status (text,prefix_len,ex)
801   | GrafiteAst.Comment (_,c) -> eval_comment status (text,prefix_len,c),[]
802 }
803
804 let eval_ast = eval_ast.ea_go