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