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