]> matita.cs.unibo.it Git - helm.git/blob - helm/software/components/grafite_engine/grafiteEngine.ml
aa056f3e2c35585c8d4c599bdbf055913918f1a9
[helm.git] / helm / software / 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
37 type 'a disambiguator_input = string * int * 'a
38
39 type options = { 
40   do_heavy_checks: bool ; 
41 }
42
43 (** create a ProofEngineTypes.mk_fresh_name_type function which uses given
44   * names as long as they are available, then it fallbacks to name generation
45   * using FreshNamesGenerator module *)
46 let namer_of names =
47   let len = List.length names in
48   let count = ref 0 in
49   fun metasenv context name ~typ ->
50     if !count < len then begin
51       let name = match List.nth names !count with
52          | Some s -> Cic.Name s
53          | None   -> Cic.Anonymous
54       in
55       incr count;
56       name
57     end else
58       FreshNamesGenerator.mk_fresh_name ~subst:[] metasenv context name ~typ
59
60 let rec tactic_of_ast status ast =
61   let module PET = ProofEngineTypes in
62   match ast with
63   (* Higher order tactics *)
64   | GrafiteAst.Do (loc, n, tactic) ->
65      Tacticals.do_tactic n (tactic_of_ast status tactic)
66   | GrafiteAst.Seq (loc, tactics) ->  (* tac1; tac2; ... *)
67      Tacticals.seq (List.map (tactic_of_ast status) tactics)
68   | GrafiteAst.Repeat (loc, tactic) ->
69      Tacticals.repeat_tactic (tactic_of_ast status tactic)
70   | GrafiteAst.Then (loc, tactic, tactics) ->  (* tac; [ tac1 | ... ] *)
71      Tacticals.thens
72       (tactic_of_ast status tactic)
73       (List.map (tactic_of_ast status) tactics)
74   | GrafiteAst.First (loc, tactics) ->
75      Tacticals.first (List.map (tactic_of_ast status) tactics)
76   | GrafiteAst.Try (loc, tactic) ->
77      Tacticals.try_tactic (tactic_of_ast status tactic)
78   | GrafiteAst.Solve (loc, tactics) ->
79      Tacticals.solve_tactics (List.map (tactic_of_ast status) tactics)
80   | GrafiteAst.Progress (loc, tactic) ->
81      Tacticals.progress_tactic (tactic_of_ast status tactic)
82   (* First order tactics *)
83   | GrafiteAst.Absurd (_, term) -> Tactics.absurd term
84   | GrafiteAst.Apply (_, term) -> Tactics.apply term
85   | GrafiteAst.ApplyS (_, term, params) ->
86      Tactics.applyS ~term ~params ~dbd:(LibraryDb.instance ())
87        ~universe:status.GrafiteTypes.universe
88   | GrafiteAst.Assumption _ -> Tactics.assumption
89   | GrafiteAst.AutoBatch (_,params) ->
90       Tactics.auto ~params ~dbd:(LibraryDb.instance ()) 
91         ~universe:status.GrafiteTypes.universe
92   | GrafiteAst.Cases (_, what, (howmany, names)) ->
93       Tactics.cases_intros ?howmany ~mk_fresh_name_callback:(namer_of names)
94         what
95   | GrafiteAst.Change (_, pattern, with_what) ->
96      Tactics.change ~pattern with_what
97   | GrafiteAst.Clear (_,id) -> Tactics.clear id
98   | GrafiteAst.ClearBody (_,id) -> Tactics.clearbody id
99   | GrafiteAst.Compose (_,t1,t2,times,(howmany, names)) -> 
100       Tactics.compose times t1 t2 ?howmany
101         ~mk_fresh_name_callback:(namer_of names)
102   | GrafiteAst.Contradiction _ -> Tactics.contradiction
103   | GrafiteAst.Constructor (_, n) -> Tactics.constructor n
104   | GrafiteAst.Cut (_, ident, term) ->
105      let names = match ident with None -> [] | Some id -> [Some id] in
106      Tactics.cut ~mk_fresh_name_callback:(namer_of names) term
107   | GrafiteAst.Decompose (_, names) ->
108       let mk_fresh_name_callback = namer_of names in
109       Tactics.decompose ~mk_fresh_name_callback ()
110   | GrafiteAst.Demodulate _ -> 
111       Tactics.demodulate 
112         ~dbd:(LibraryDb.instance ()) ~universe:status.GrafiteTypes.universe
113   | GrafiteAst.Destruct (_,xterms) -> Tactics.destruct xterms
114   | GrafiteAst.Elim (_, what, using, pattern, (depth, names)) ->
115       Tactics.elim_intros ?using ?depth ~mk_fresh_name_callback:(namer_of names)
116         ~pattern what
117   | GrafiteAst.ElimType (_, what, using, (depth, names)) ->
118       Tactics.elim_type ?using ?depth ~mk_fresh_name_callback:(namer_of names)
119         what
120   | GrafiteAst.Exact (_, term) -> Tactics.exact term
121   | GrafiteAst.Exists _ -> Tactics.exists
122   | GrafiteAst.Fail _ -> Tactics.fail
123   | GrafiteAst.Fold (_, reduction_kind, term, pattern) ->
124       let reduction =
125         match reduction_kind with
126         | `Normalize ->
127             PET.const_lazy_reduction
128               (CicReduction.normalize ~delta:false ~subst:[])
129         | `Simpl -> PET.const_lazy_reduction ProofEngineReduction.simpl
130         | `Unfold None ->
131             PET.const_lazy_reduction (ProofEngineReduction.unfold ?what:None)
132         | `Unfold (Some lazy_term) ->
133            (fun context metasenv ugraph ->
134              let what, metasenv, ugraph = lazy_term context metasenv ugraph in
135              ProofEngineReduction.unfold ~what, metasenv, ugraph)
136         | `Whd ->
137             PET.const_lazy_reduction (CicReduction.whd ~delta:false ~subst:[])
138       in
139       Tactics.fold ~reduction ~term ~pattern
140   | GrafiteAst.Fourier _ -> Tactics.fourier
141   | GrafiteAst.FwdSimpl (_, hyp, names) -> 
142      Tactics.fwd_simpl ~mk_fresh_name_callback:(namer_of names)
143       ~dbd:(LibraryDb.instance ()) hyp
144   | GrafiteAst.Generalize (_,pattern,ident) ->
145      let names = match ident with None -> [] | Some id -> [Some id] in
146      Tactics.generalize ~mk_fresh_name_callback:(namer_of names) pattern 
147   | GrafiteAst.IdTac _ -> Tactics.id
148   | GrafiteAst.Intros (_, (howmany, names)) ->
149       PrimitiveTactics.intros_tac ?howmany
150         ~mk_fresh_name_callback:(namer_of names) ()
151   | GrafiteAst.Inversion (_, term) ->
152       Tactics.inversion term
153   | GrafiteAst.LApply (_, linear, how_many, to_what, what, ident) ->
154       let names = match ident with None -> [] | Some id -> [Some id] in
155       Tactics.lapply ~mk_fresh_name_callback:(namer_of names) 
156         ~linear ?how_many ~to_what what
157   | GrafiteAst.Left _ -> Tactics.left
158   | GrafiteAst.LetIn (loc,term,name) ->
159       Tactics.letin term ~mk_fresh_name_callback:(namer_of [Some name])
160   | GrafiteAst.Reduce (_, reduction_kind, pattern) ->
161       (match reduction_kind with
162          | `Normalize -> Tactics.normalize ~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 
171 (* to be replaced with ~mk_fresh_name_callback:(namer_of names) *)
172      (List.map (function Some s -> s | None -> assert false) names)
173   | GrafiteAst.Right _ -> Tactics.right
174   | GrafiteAst.Ring _ -> Tactics.ring
175   | GrafiteAst.Split _ -> Tactics.split
176   | GrafiteAst.Symmetry _ -> Tactics.symmetry
177   | GrafiteAst.Transitivity (_, term) -> Tactics.transitivity term
178   (* Implementazioni Aggiunte *)
179   | GrafiteAst.Assume (_, id, t) -> Declarative.assume id t
180   | GrafiteAst.Suppose (_, t, id, t1) -> Declarative.suppose t id t1
181   | GrafiteAst.By_term_we_proved (_, t, ty, id, t1) ->
182      Declarative.by_term_we_proved ~dbd:(LibraryDb.instance())
183       ~universe:status.GrafiteTypes.universe t ty id t1
184   | GrafiteAst.We_need_to_prove (_, t, id, t2) ->
185      Declarative.we_need_to_prove t id t2
186   | GrafiteAst.Bydone (_, t) ->
187      Declarative.bydone ~dbd:(LibraryDb.instance())
188       ~universe:status.GrafiteTypes.universe t
189   | GrafiteAst.We_proceed_by_cases_on (_, t, t1) ->
190      Declarative.we_proceed_by_cases_on t t1
191   | GrafiteAst.We_proceed_by_induction_on (_, t, t1) ->
192      Declarative.we_proceed_by_induction_on t t1
193   | GrafiteAst.Byinduction (_, t, id) -> Declarative.byinduction t id
194   | GrafiteAst.Thesisbecomes (_, t) -> Declarative.thesisbecomes t
195   | GrafiteAst.ExistsElim (_, t, id1, t1, id2, t2) ->
196      Declarative.existselim ~dbd:(LibraryDb.instance())
197       ~universe:status.GrafiteTypes.universe t id1 t1 id2 t2
198   | GrafiteAst.Case (_,id,params) -> Declarative.case id params
199   | GrafiteAst.AndElim(_,t,id1,t1,id2,t2) -> Declarative.andelim t id1 t1 id2 t2
200   | GrafiteAst.RewritingStep (_,termine,t1,t2,cont) ->
201      Declarative.rewritingstep ~dbd:(LibraryDb.instance ())
202       ~universe:status.GrafiteTypes.universe termine t1 t2 cont
203
204 let classify_tactic tactic = 
205   match tactic with
206   (* tactics that can't close the goal (return a goal we want to "select") *)
207   | GrafiteAst.Rewrite _ 
208   | GrafiteAst.Split _ 
209   | GrafiteAst.Replace _ 
210   | GrafiteAst.Reduce _
211   | GrafiteAst.IdTac _ 
212   | GrafiteAst.Generalize _ 
213   | GrafiteAst.Elim _ 
214   | GrafiteAst.Cut _
215   | GrafiteAst.Decompose _ -> true
216   (* tactics like apply *)
217   | _ -> false
218   
219 let reorder_metasenv start refine tactic goals current_goal always_opens_a_goal=
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, _subst, 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, _subst, 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, _subst, 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, _subst, 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   GrafiteTypes.status ->
410   (('term, 'lazy_term, 'reduction, 'obj, 'ident) GrafiteAst.statement)
411   disambiguator_input ->
412   GrafiteTypes.status * UriManager.uri list
413  }
414
415 type 'a eval_command =
416  {ec_go: 'term 'obj.
417   disambiguate_command:
418    (GrafiteTypes.status -> (('term,'obj) GrafiteAst.command) disambiguator_input ->
419     GrafiteTypes.status * (Cic.term,Cic.obj) GrafiteAst.command) -> 
420   options -> GrafiteTypes.status -> 
421     (('term,'obj) GrafiteAst.command) disambiguator_input ->
422    GrafiteTypes.status * UriManager.uri list
423  }
424
425 type 'a eval_executable =
426  {ee_go: 'term 'lazy_term 'reduction 'obj 'ident.
427   disambiguate_tactic:
428    (GrafiteTypes.status ->
429     ProofEngineTypes.goal ->
430     (('term, 'lazy_term, 'reduction, 'ident) GrafiteAst.tactic)
431     disambiguator_input ->
432     GrafiteTypes.status *
433    (Cic.term, Cic.lazy_term, Cic.lazy_term GrafiteAst.reduction, string) GrafiteAst.tactic) ->
434
435   disambiguate_command:
436    (GrafiteTypes.status ->
437     (('term,'obj) GrafiteAst.command) disambiguator_input ->
438     GrafiteTypes.status * (Cic.term,Cic.obj) GrafiteAst.command) ->
439
440   disambiguate_macro:
441    (GrafiteTypes.status ->
442     ('term GrafiteAst.macro) disambiguator_input ->
443     Cic.context -> GrafiteTypes.status * Cic.term GrafiteAst.macro) ->
444
445   options ->
446   GrafiteTypes.status ->
447   (('term, 'lazy_term, 'reduction, 'obj, 'ident) GrafiteAst.code) disambiguator_input ->
448   GrafiteTypes.status * UriManager.uri list
449  }
450
451 type 'a eval_from_moo =
452  { efm_go: GrafiteTypes.status -> string -> GrafiteTypes.status }
453       
454 let coercion_moo_statement_of (uri,arity, saturations) =
455   GrafiteAst.Coercion (HExtlib.dummy_floc, uri, false, arity, saturations)
456
457 let refinement_toolkit = {
458   RefinementTool.type_of_aux' = 
459     (fun ?localization_tbl e c t u ->
460       let saved = !CicRefine.insert_coercions in 
461       CicRefine.insert_coercions:= false;
462       let rc = 
463         try 
464           let t, ty, metasenv, ugraph = 
465             CicRefine.type_of_aux' ?localization_tbl e c t u in
466           RefinementTool.Success (t, ty, metasenv, ugraph)
467         with
468         | CicRefine.RefineFailure s
469         | CicRefine.Uncertain s 
470         | CicRefine.AssertFailure s -> RefinementTool.Exception s
471       in
472       CicRefine.insert_coercions := saved;
473       rc);
474   RefinementTool.ppsubst = CicMetaSubst.ppsubst;
475   RefinementTool.apply_subst = CicMetaSubst.apply_subst; 
476   RefinementTool.ppmetasenv = CicMetaSubst.ppmetasenv; 
477   RefinementTool.pack_coercion_obj = CicRefine.pack_coercion_obj;
478  }
479   
480 let eval_coercion status ~add_composites uri arity saturations =
481  let status,compounds =
482   GrafiteSync.add_coercion ~add_composites refinement_toolkit status uri arity
483    saturations (GrafiteTypes.get_baseuri status)
484  in
485  let moo_content = 
486    List.map coercion_moo_statement_of ((uri,arity,saturations)::compounds)
487  in
488  let status = GrafiteTypes.add_moo_content moo_content status in
489   {status with GrafiteTypes.proof_status = GrafiteTypes.No_proof},
490    List.map (fun u,_,_ -> u) compounds
491
492 module MatitaStatus =
493  struct
494   type input_status = GrafiteTypes.status * ProofEngineTypes.goal
495
496   type output_status =
497     GrafiteTypes.status * ProofEngineTypes.goal list * ProofEngineTypes.goal list
498
499   type tactic = input_status -> output_status
500
501   let mk_tactic tac = tac
502   let apply_tactic tac = tac
503   let goals (_, opened, closed) = opened, closed
504   let get_stack (status, _) = GrafiteTypes.get_stack status
505   
506   let set_stack stack (status, opened, closed) = 
507     GrafiteTypes.set_stack stack status, opened, closed
508
509   let inject (status, _) = (status, [], [])
510   let focus goal (status, _, _) = (status, goal)
511  end
512
513 module MatitaTacticals = Continuationals.Make(MatitaStatus)
514
515 let tactic_of_ast' tac =
516  MatitaTacticals.Tactical (MatitaTacticals.Tactic (MatitaStatus.mk_tactic tac))
517
518 let punctuation_tactical_of_ast (text,prefix_len,punct) =
519  match punct with
520   | GrafiteAst.Dot _loc -> MatitaTacticals.Dot
521   | GrafiteAst.Semicolon _loc -> MatitaTacticals.Semicolon
522   | GrafiteAst.Branch _loc -> MatitaTacticals.Branch
523   | GrafiteAst.Shift _loc -> MatitaTacticals.Shift
524   | GrafiteAst.Pos (_loc, i) -> MatitaTacticals.Pos i
525   | GrafiteAst.Merge _loc -> MatitaTacticals.Merge
526   | GrafiteAst.Wildcard _loc -> MatitaTacticals.Wildcard
527
528 let non_punctuation_tactical_of_ast (text,prefix_len,punct) =
529  match punct with
530   | GrafiteAst.Focus (_loc,goals) -> MatitaTacticals.Focus goals
531   | GrafiteAst.Unfocus _loc -> MatitaTacticals.Unfocus
532   | GrafiteAst.Skip _loc -> MatitaTacticals.Tactical MatitaTacticals.Skip
533
534 let eval_tactical status tac =
535   let status, _, _ = MatitaTacticals.eval tac (status, ~-1) in
536   let status =  (* is proof completed? *)
537     match status.GrafiteTypes.proof_status with
538     | GrafiteTypes.Incomplete_proof
539        { GrafiteTypes.stack = stack; proof = proof }
540       when Continuationals.Stack.is_empty stack ->
541         { status with GrafiteTypes.proof_status = GrafiteTypes.Proof proof }
542     | _ -> status
543   in
544   status
545
546 let eval_comment status c = status
547
548 (* since the record syntax allows to declare coercions, we have to put this
549  * information inside the moo *)
550 let add_coercions_of_record_to_moo obj lemmas status =
551   let attributes = CicUtil.attributes_of_obj obj in
552   let is_record = function `Class (`Record att) -> Some att | _-> None in
553   match HExtlib.list_findopt is_record attributes with
554   | None -> status,[]
555   | Some fields -> 
556       let is_a_coercion uri =
557         try
558           let obj,_ = 
559             CicEnvironment.get_cooked_obj  CicUniv.empty_ugraph uri in
560           let attrs = CicUtil.attributes_of_obj obj in
561           try 
562             match List.find 
563              (function `Class (`Coercion _) -> true | _-> false) attrs
564             with `Class (`Coercion n) -> true,n | _ -> assert false
565           with Not_found -> false,0            
566         with Not_found -> assert false
567       in
568       let buri = GrafiteTypes.get_baseuri status 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 (buri ^ "/" ^ name ^ ".con" ))
579             | _ -> None) 
580           fields
581       in
582       (*prerr_endline "wanted coercions:";
583       List.iter 
584         (fun u -> prerr_endline (UriManager.string_of_uri u)) 
585         wanted_coercions; *)
586       let coercions, moo_content = 
587         List.split
588           (HExtlib.filter_map 
589             (fun uri ->
590               let is_a_wanted_coercion,arity_wanted = 
591                 try
592                   let arity,_ = 
593                     List.find (fun (n,u) -> UriManager.eq u uri) 
594                       wanted_coercions
595                   in
596                   true, arity
597                 with Not_found -> false, 0
598               in
599               let is_a_coercion, arity_coercion = is_a_coercion uri in
600               if is_a_coercion then
601                 Some (uri, coercion_moo_statement_of (uri,arity_coercion,0))
602               else if is_a_wanted_coercion then
603                 Some (uri, coercion_moo_statement_of (uri,arity_wanted,0))
604               else
605                 None)
606             lemmas)
607       in
608       (*prerr_endline "actual coercions:";
609       List.iter 
610         (fun u -> prerr_endline (UriManager.string_of_uri u)) 
611         coercions; 
612       prerr_endline "lemmas was:";
613       List.iter 
614         (fun u -> prerr_endline (UriManager.string_of_uri u)) 
615         lemmas; *)
616       let status = GrafiteTypes.add_moo_content moo_content status in 
617       {status with 
618         GrafiteTypes.coercions = coercions @ status.GrafiteTypes.coercions}, 
619       lemmas
620
621 let add_obj uri obj status =
622  let status,lemmas = GrafiteSync.add_obj refinement_toolkit uri obj status in
623  status, lemmas 
624       
625 let rec eval_command = {ec_go = fun ~disambiguate_command opts status
626 (text,prefix_len,cmd) ->
627  let status,cmd = disambiguate_command status (text,prefix_len,cmd) in
628  let status,uris =
629   match cmd with
630   | GrafiteAst.Index (loc,None,uri) -> 
631         assert false (* TODO: for user input *)
632   | GrafiteAst.Index (loc,Some key,uri) -> 
633       let universe = Universe.index 
634         status.GrafiteTypes.universe key (CicUtil.term_of_uri uri) in
635       let status = {status with GrafiteTypes.universe = universe} in
636 (* debug
637       let msg =
638        let candidates = Universe.get_candidates status.GrafiteTypes.universe key in
639        ("candidates for " ^ (CicPp.ppterm key) ^ " = " ^ 
640           (String.concat "\n" (List.map CicPp.ppterm candidates))) 
641      in
642      prerr_endline msg;
643 *)
644       let status = GrafiteTypes.add_moo_content [cmd] status in
645       status,[] 
646   | GrafiteAst.Coercion (loc, uri, add_composites, arity, saturations) ->
647      eval_coercion status ~add_composites uri arity saturations 
648   | GrafiteAst.Default (loc, what, uris) as cmd ->
649      LibraryObjects.set_default what uris;
650      GrafiteTypes.add_moo_content [cmd] status,[]
651   | GrafiteAst.Drop loc -> raise Drop
652   | GrafiteAst.Include (loc, baseuri) ->
653      let moopath_rw, moopath_r = 
654        LibraryMisc.obj_file_of_baseuri 
655          ~must_exist:false ~baseuri ~writable:true,
656        LibraryMisc.obj_file_of_baseuri 
657          ~must_exist:false ~baseuri ~writable:false
658      in
659      let moopath = 
660        if Sys.file_exists moopath_r then moopath_r else
661          if Sys.file_exists moopath_rw then moopath_rw else
662            raise (IncludedFileNotCompiled (moopath_rw,baseuri))
663      in
664      let status = eval_from_moo.efm_go status moopath in
665 (* debug
666      let lt_uri = UriManager.uri_of_string "cic:/matita/nat/orders/lt.con" in
667      let nat_uri = UriManager.uri_of_string "cic:/matita/nat/nat/nat.ind" in
668      let nat = Cic.MutInd(nat_uri,0,[]) in
669      let zero = Cic.MutConstruct(nat_uri,0,1,[]) in
670      let succ = Cic.MutConstruct(nat_uri,0,2,[]) in
671      let fake= Cic.Meta(-1,[]) in
672      let term= Cic.Appl [Cic.Const (lt_uri,[]);zero;Cic.Appl[succ;zero]] in     let msg =
673        let candidates = Universe.get_candidates status.GrafiteTypes.universe term in
674        ("candidates for " ^ (CicPp.ppterm term) ^ " = " ^ 
675           (String.concat "\n" (List.map CicPp.ppterm candidates))) 
676      in
677      prerr_endline msg;
678 *)
679      status,[]
680   | GrafiteAst.Print (_,"proofterm") ->
681       let _,_,_,p,_, _ = GrafiteTypes.get_current_proof status in
682       prerr_endline (Auto.pp_proofterm p);
683       status,[]
684   | GrafiteAst.Print (_,_) -> status,[]
685   | GrafiteAst.Qed loc ->
686       let uri, metasenv, _subst, bo, ty, attrs =
687         match status.GrafiteTypes.proof_status with
688         | GrafiteTypes.Proof (Some uri, metasenv, subst, body, ty, attrs) ->
689             uri, metasenv, subst, body, ty, attrs
690         | GrafiteTypes.Proof (None, metasenv, subst, body, ty, attrs) -> 
691             raise (GrafiteTypes.Command_error 
692               ("Someone allows to start a theorem without giving the "^
693                "name/uri. This should be fixed!"))
694         | _->
695           raise
696            (GrafiteTypes.Command_error "You can't Qed an incomplete theorem")
697       in
698       if metasenv <> [] then 
699         raise
700          (GrafiteTypes.Command_error
701            "Proof not completed! metasenv is not empty!");
702       let name = UriManager.name_of_uri uri in
703       let obj = Cic.Constant (name,Some bo,ty,[],attrs) in
704       let status, lemmas = add_obj uri obj status in
705        {status with 
706           GrafiteTypes.proof_status = GrafiteTypes.No_proof},
707         (*CSC: I throw away the arities *)
708         uri::lemmas
709   | GrafiteAst.Relation (loc, id, a, aeq, refl, sym, trans) -> 
710      Setoids.add_relation id a aeq refl sym trans;
711      status, [] (*CSC: TO BE FIXED *)
712   | GrafiteAst.Set (loc, name, value) -> status, []
713 (*       GrafiteTypes.set_option status name value,[] *)
714   | GrafiteAst.Obj (loc,obj) ->
715      let ext,name =
716       match obj with
717          Cic.Constant (name,_,_,_,_)
718        | Cic.CurrentProof (name,_,_,_,_,_) -> ".con",name
719        | Cic.InductiveDefinition (types,_,_,_) ->
720           ".ind",
721           (match types with (name,_,_,_)::_ -> name | _ -> assert false)
722        | _ -> assert false in
723      let buri = GrafiteTypes.get_baseuri status in 
724      let uri = UriManager.uri_of_string (buri ^ "/" ^ name ^ ext) in
725      let obj = CicRefine.pack_coercion_obj obj in
726      let metasenv = GrafiteTypes.get_proof_metasenv status in
727      match obj with
728      | Cic.CurrentProof (_,metasenv',bo,ty,_, attrs) ->
729          let name = UriManager.name_of_uri uri in
730          if not(CicPp.check name ty) then
731            HLog.warn ("Bad name: " ^ name);
732          if opts.do_heavy_checks then
733            begin
734              let dbd = LibraryDb.instance () in
735              let similar = Whelp.match_term ~dbd ty in
736              let similar_len = List.length similar in
737              if similar_len> 30 then
738                (HLog.message
739                  ("Duplicate check will compare your theorem with " ^ 
740                    string_of_int similar_len ^ 
741                    " theorems, this may take a while."));
742              let convertible =
743                List.filter (
744                  fun u ->
745                    let t = CicUtil.term_of_uri u in
746                    let ty',g = 
747                      CicTypeChecker.type_of_aux' 
748                        metasenv' [] t CicUniv.empty_ugraph
749                    in
750                    fst(CicReduction.are_convertible [] ty' ty g)) 
751                similar 
752              in
753              (match convertible with
754              | [] -> ()
755              | x::_ -> 
756                  HLog.warn  
757                  ("Theorem already proved: " ^ UriManager.string_of_uri x ^ 
758                   "\nPlease use a variant."));
759            end;
760          let _subst = [] in
761          let initial_proof = (Some uri, metasenv', _subst, bo, ty, attrs) in
762          let initial_stack = Continuationals.Stack.of_metasenv metasenv' in
763          { status with GrafiteTypes.proof_status =
764             GrafiteTypes.Incomplete_proof
765              { GrafiteTypes.proof = initial_proof; stack = initial_stack } },
766           []
767      | _ ->
768          if metasenv <> [] then
769           raise (GrafiteTypes.Command_error (
770             "metasenv not empty while giving a definition with body: " ^
771             CicMetaSubst.ppmetasenv [] metasenv));
772          let status, lemmas = add_obj uri obj status in 
773          let status,new_lemmas =
774           add_coercions_of_record_to_moo obj lemmas status
775          in
776           {status with GrafiteTypes.proof_status = GrafiteTypes.No_proof},
777            uri::new_lemmas@lemmas
778  in
779   match status.GrafiteTypes.proof_status with
780      GrafiteTypes.Intermediate _ ->
781       {status with GrafiteTypes.proof_status = GrafiteTypes.No_proof},uris
782    | _ -> status,uris
783
784 } and eval_executable = {ee_go = fun ~disambiguate_tactic ~disambiguate_command
785 ~disambiguate_macro opts status (text,prefix_len,ex) ->
786   match ex with
787   | GrafiteAst.Tactic (_, Some tac, punct) ->
788      let tac = apply_tactic ~disambiguate_tactic (text,prefix_len,tac) in
789      let status = eval_tactical status (tactic_of_ast' tac) in
790       eval_tactical status
791        (punctuation_tactical_of_ast (text,prefix_len,punct)),[]
792   | GrafiteAst.Tactic (_, None, punct) ->
793       eval_tactical status
794        (punctuation_tactical_of_ast (text,prefix_len,punct)),[]
795   | GrafiteAst.NonPunctuationTactical (_, tac, punct) ->
796      let status = 
797       eval_tactical status
798        (non_punctuation_tactical_of_ast (text,prefix_len,tac))
799      in
800       eval_tactical status
801        (punctuation_tactical_of_ast (text,prefix_len,punct)),[]
802   | GrafiteAst.Command (_, cmd) ->
803       eval_command.ec_go ~disambiguate_command opts status (text,prefix_len,cmd)
804   | GrafiteAst.Macro (loc, macro) ->
805      raise (Macro (loc,disambiguate_macro status (text,prefix_len,macro)))
806
807 } and eval_from_moo = {efm_go = fun status fname ->
808   let ast_of_cmd cmd =
809     ("",0,GrafiteAst.Executable (HExtlib.dummy_floc,
810       GrafiteAst.Command (HExtlib.dummy_floc,
811         cmd)))
812   in
813   let moo = GrafiteMarshal.load_moo fname in
814   List.fold_left 
815     (fun status ast -> 
816       let ast = ast_of_cmd ast in
817       let status,lemmas =
818        eval_ast.ea_go
819          ~disambiguate_tactic:(fun status _ (_,_,tactic) -> status,tactic)
820          ~disambiguate_command:(fun status (_,_,cmd) -> status,cmd)
821          ~disambiguate_macro:(fun _ _ -> assert false)
822          status ast
823       in
824        assert (lemmas=[]);
825        status)
826     status moo
827 } and eval_ast = {ea_go = fun ~disambiguate_tactic ~disambiguate_command
828 ~disambiguate_macro ?(do_heavy_checks=false) status
829 (text,prefix_len,st)
830 ->
831   let opts = { do_heavy_checks = do_heavy_checks ; } in
832   match st with
833   | GrafiteAst.Executable (_,ex) ->
834      eval_executable.ee_go ~disambiguate_tactic ~disambiguate_command
835       ~disambiguate_macro opts status (text,prefix_len,ex)
836   | GrafiteAst.Comment (_,c) -> eval_comment status (text,prefix_len,c),[]
837 }
838
839 let eval_ast = eval_ast.ea_go