]> matita.cs.unibo.it Git - helm.git/blob - helm/software/components/grafite_engine/grafiteEngine.ml
Added initial support for inversion principles in Matita NG.
[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,Cic.lazy_term) GrafiteAst.macro)
36 exception NMacro of GrafiteAst.loc * GrafiteAst.nmacro
37
38 type 'a disambiguator_input = string * int * 'a
39
40 type options = { 
41   do_heavy_checks: bool ; 
42 }
43
44 let concat_nuris uris nuris =
45    match uris,nuris with
46    | `New uris, `New nuris -> `New (nuris@uris)
47    | _ -> assert false
48 ;;
49 (** create a ProofEngineTypes.mk_fresh_name_type function which uses given
50   * names as long as they are available, then it fallbacks to name generation
51   * using FreshNamesGenerator module *)
52 let namer_of names =
53   let len = List.length names in
54   let count = ref 0 in
55   fun metasenv context name ~typ ->
56     if !count < len then begin
57       let name = match List.nth names !count with
58          | Some s -> Cic.Name s
59          | None   -> Cic.Anonymous
60       in
61       incr count;
62       name
63     end else
64       FreshNamesGenerator.mk_fresh_name ~subst:[] metasenv context name ~typ
65
66 let rec tactic_of_ast status ast =
67   let module PET = ProofEngineTypes in
68   match ast with
69   (* Higher order tactics *)
70   | GrafiteAst.Do (loc, n, tactic) ->
71      Tacticals.do_tactic n (tactic_of_ast status tactic)
72   | GrafiteAst.Seq (loc, tactics) ->  (* tac1; tac2; ... *)
73      Tacticals.seq (List.map (tactic_of_ast status) tactics)
74   | GrafiteAst.Repeat (loc, tactic) ->
75      Tacticals.repeat_tactic (tactic_of_ast status tactic)
76   | GrafiteAst.Then (loc, tactic, tactics) ->  (* tac; [ tac1 | ... ] *)
77      Tacticals.thens
78       (tactic_of_ast status tactic)
79       (List.map (tactic_of_ast status) tactics)
80   | GrafiteAst.First (loc, tactics) ->
81      Tacticals.first (List.map (tactic_of_ast status) tactics)
82   | GrafiteAst.Try (loc, tactic) ->
83      Tacticals.try_tactic (tactic_of_ast status tactic)
84   | GrafiteAst.Solve (loc, tactics) ->
85      Tacticals.solve_tactics (List.map (tactic_of_ast status) tactics)
86   | GrafiteAst.Progress (loc, tactic) ->
87      Tacticals.progress_tactic (tactic_of_ast status tactic)
88   (* First order tactics *)
89   | GrafiteAst.Absurd (_, term) -> Tactics.absurd term
90   | GrafiteAst.Apply (_, term) -> Tactics.apply term
91   | GrafiteAst.ApplyRule (_, term) -> Tactics.apply term
92   | GrafiteAst.ApplyP (_, term) -> Tactics.applyP term
93   | GrafiteAst.ApplyS (_, term, params) ->
94      Tactics.applyS ~term ~params ~dbd:(LibraryDb.instance ())
95        ~automation_cache:status#automation_cache
96   | GrafiteAst.Assumption _ -> Tactics.assumption
97   | GrafiteAst.AutoBatch (_,params) ->
98       Tactics.auto ~params ~dbd:(LibraryDb.instance ()) 
99         ~automation_cache:status#automation_cache
100   | GrafiteAst.Cases (_, what, pattern, (howmany, names)) ->
101       Tactics.cases_intros ?howmany ~mk_fresh_name_callback:(namer_of names)
102         ~pattern what
103   | GrafiteAst.Change (_, pattern, with_what) ->
104      Tactics.change ~pattern with_what
105   | GrafiteAst.Clear (_,id) -> Tactics.clear id
106   | GrafiteAst.ClearBody (_,id) -> Tactics.clearbody id
107   | GrafiteAst.Compose (_,t1,t2,times,(howmany, names)) -> 
108       Tactics.compose times t1 t2 ?howmany
109         ~mk_fresh_name_callback:(namer_of names)
110   | GrafiteAst.Contradiction _ -> Tactics.contradiction
111   | GrafiteAst.Constructor (_, n) -> Tactics.constructor n
112   | GrafiteAst.Cut (_, ident, term) ->
113      let names = match ident with None -> [] | Some id -> [Some id] in
114      Tactics.cut ~mk_fresh_name_callback:(namer_of names) term
115   | GrafiteAst.Decompose (_, names) ->
116       let mk_fresh_name_callback = namer_of names in
117       Tactics.decompose ~mk_fresh_name_callback ()
118   | GrafiteAst.Demodulate (_, params) -> 
119       Tactics.demodulate 
120         ~dbd:(LibraryDb.instance ()) ~params 
121           ~automation_cache:status#automation_cache
122   | GrafiteAst.Destruct (_,xterms) -> Tactics.destruct xterms
123   | GrafiteAst.Elim (_, what, using, pattern, (depth, names)) ->
124       Tactics.elim_intros ?using ?depth ~mk_fresh_name_callback:(namer_of names)
125         ~pattern what
126   | GrafiteAst.ElimType (_, what, using, (depth, names)) ->
127       Tactics.elim_type ?using ?depth ~mk_fresh_name_callback:(namer_of names)
128         what
129   | GrafiteAst.Exact (_, term) -> Tactics.exact term
130   | GrafiteAst.Exists _ -> Tactics.exists
131   | GrafiteAst.Fail _ -> Tactics.fail
132   | GrafiteAst.Fold (_, reduction_kind, term, pattern) ->
133       let reduction =
134         match reduction_kind with
135         | `Normalize ->
136             PET.const_lazy_reduction
137               (CicReduction.normalize ~delta:false ~subst:[])
138         | `Simpl -> PET.const_lazy_reduction ProofEngineReduction.simpl
139         | `Unfold None ->
140             PET.const_lazy_reduction (ProofEngineReduction.unfold ?what:None)
141         | `Unfold (Some lazy_term) ->
142            (fun context metasenv ugraph ->
143              let what, metasenv, ugraph = lazy_term context metasenv ugraph in
144              ProofEngineReduction.unfold ~what, metasenv, ugraph)
145         | `Whd ->
146             PET.const_lazy_reduction (CicReduction.whd ~delta:false ~subst:[])
147       in
148       Tactics.fold ~reduction ~term ~pattern
149   | GrafiteAst.Fourier _ -> Tactics.fourier
150   | GrafiteAst.FwdSimpl (_, hyp, names) -> 
151      Tactics.fwd_simpl ~mk_fresh_name_callback:(namer_of names)
152       ~dbd:(LibraryDb.instance ()) hyp
153   | GrafiteAst.Generalize (_,pattern,ident) ->
154      let names = match ident with None -> [] | Some id -> [Some id] in
155      Tactics.generalize ~mk_fresh_name_callback:(namer_of names) pattern 
156   | GrafiteAst.IdTac _ -> Tactics.id
157   | GrafiteAst.Intros (_, (howmany, names)) ->
158       PrimitiveTactics.intros_tac ?howmany
159         ~mk_fresh_name_callback:(namer_of names) ()
160   | GrafiteAst.Inversion (_, term) ->
161       Tactics.inversion term
162   | GrafiteAst.LApply (_, linear, how_many, to_what, what, ident) ->
163       let names = match ident with None -> [] | Some id -> [Some id] in
164       Tactics.lapply ~mk_fresh_name_callback:(namer_of names) 
165         ~linear ?how_many ~to_what what
166   | GrafiteAst.Left _ -> Tactics.left
167   | GrafiteAst.LetIn (loc,term,name) ->
168       Tactics.letin term ~mk_fresh_name_callback:(namer_of [Some name])
169   | GrafiteAst.Reduce (_, reduction_kind, pattern) ->
170       (match reduction_kind with
171          | `Normalize -> Tactics.normalize ~pattern
172          | `Simpl -> Tactics.simpl ~pattern 
173          | `Unfold what -> Tactics.unfold ~pattern what
174          | `Whd -> Tactics.whd ~pattern)
175   | GrafiteAst.Reflexivity _ -> Tactics.reflexivity
176   | GrafiteAst.Replace (_, pattern, with_what) ->
177      Tactics.replace ~pattern ~with_what
178   | GrafiteAst.Rewrite (_, direction, t, pattern, names) ->
179      EqualityTactics.rewrite_tac ~direction ~pattern t 
180 (* to be replaced with ~mk_fresh_name_callback:(namer_of names) *)
181      (List.map (function Some s -> s | None -> assert false) names)
182   | GrafiteAst.Right _ -> Tactics.right
183   | GrafiteAst.Ring _ -> Tactics.ring
184   | GrafiteAst.Split _ -> Tactics.split
185   | GrafiteAst.Symmetry _ -> Tactics.symmetry
186   | GrafiteAst.Transitivity (_, term) -> Tactics.transitivity term
187   (* Implementazioni Aggiunte *)
188   | GrafiteAst.Assume (_, id, t) -> Declarative.assume id t
189   | GrafiteAst.Suppose (_, t, id, t1) -> Declarative.suppose t id t1
190   | GrafiteAst.By_just_we_proved (_, just, ty, id, t1) ->
191      Declarative.by_just_we_proved ~dbd:(LibraryDb.instance())
192       ~automation_cache:status#automation_cache just ty id t1
193   | GrafiteAst.We_need_to_prove (_, t, id, t2) ->
194      Declarative.we_need_to_prove t id t2
195   | GrafiteAst.Bydone (_, t) ->
196      Declarative.bydone ~dbd:(LibraryDb.instance())
197       ~automation_cache:status#automation_cache t
198   | GrafiteAst.We_proceed_by_cases_on (_, t, t1) ->
199      Declarative.we_proceed_by_cases_on t t1
200   | GrafiteAst.We_proceed_by_induction_on (_, t, t1) ->
201      Declarative.we_proceed_by_induction_on t t1
202   | GrafiteAst.Byinduction (_, t, id) -> Declarative.byinduction t id
203   | GrafiteAst.Thesisbecomes (_, t) -> Declarative.thesisbecomes t
204   | GrafiteAst.ExistsElim (_, just, id1, t1, id2, t2) ->
205      Declarative.existselim ~dbd:(LibraryDb.instance())
206       ~automation_cache:status#automation_cache just id1 t1 id2 t2
207   | GrafiteAst.Case (_,id,params) -> Declarative.case id params
208   | GrafiteAst.AndElim(_,just,id1,t1,id2,t2) ->
209      Declarative.andelim ~dbd:(LibraryDb.instance ())
210       ~automation_cache:status#automation_cache just id1 t1 id2 t2
211   | GrafiteAst.RewritingStep (_,termine,t1,t2,cont) ->
212      Declarative.rewritingstep ~dbd:(LibraryDb.instance ())
213       ~automation_cache:status#automation_cache termine t1 t2 cont
214
215 let classify_tactic tactic = 
216   match tactic with
217   (* tactics that can't close the goal (return a goal we want to "select") *)
218   | GrafiteAst.Rewrite _ 
219   | GrafiteAst.Split _ 
220   | GrafiteAst.Replace _ 
221   | GrafiteAst.Reduce _
222   | GrafiteAst.IdTac _ 
223   | GrafiteAst.Generalize _ 
224   | GrafiteAst.Elim _ 
225   | GrafiteAst.Cut _
226   | GrafiteAst.Decompose _ -> true
227   (* tactics like apply *)
228   | _ -> false
229   
230 let reorder_metasenv start refine tactic goals current_goal always_opens_a_goal=
231 (*   let print_m name metasenv =
232     prerr_endline (">>>>> " ^ name);
233     prerr_endline (CicMetaSubst.ppmetasenv [] metasenv)
234   in *)
235   (* phase one calculates:
236    *   new_goals_from_refine:  goals added by refine
237    *   head_goal:              the first goal opened by ythe tactic 
238    *   other_goals:            other goals opened by the tactic
239    *)
240   let new_goals_from_refine = PEH.compare_metasenvs start refine in
241   let new_goals_from_tactic = PEH.compare_metasenvs refine tactic in
242   let head_goal, other_goals, goals = 
243     match goals with
244     | [] -> None,[],goals
245     | hd::tl -> 
246         (* assert (List.mem hd new_goals_from_tactic);
247          * invalidato dalla goal_tac
248          * *)
249         Some hd, List.filter ((<>) hd) new_goals_from_tactic, List.filter ((<>)
250         hd) goals
251   in
252   let produced_goals = 
253     match head_goal with
254     | None -> new_goals_from_refine @ other_goals
255     | Some x -> x :: new_goals_from_refine @ other_goals
256   in
257   (* extract the metas generated by refine and tactic *)
258   let metas_for_tactic_head = 
259     match head_goal with
260     | None -> []
261     | Some head_goal -> List.filter (fun (n,_,_) -> n = head_goal) tactic in
262   let metas_for_tactic_goals = 
263     List.map 
264       (fun x -> List.find (fun (metano,_,_) -> metano = x) tactic)
265     goals 
266   in
267   let metas_for_refine_goals = 
268     List.filter (fun (n,_,_) -> List.mem n new_goals_from_refine) tactic in
269   let produced_metas, goals = 
270     let produced_metas =
271       if always_opens_a_goal then
272         metas_for_tactic_head @ metas_for_refine_goals @ 
273           metas_for_tactic_goals
274       else begin
275 (*         print_m "metas_for_refine_goals" metas_for_refine_goals;
276         print_m "metas_for_tactic_head" metas_for_tactic_head;
277         print_m "metas_for_tactic_goals" metas_for_tactic_goals; *)
278         metas_for_refine_goals @ metas_for_tactic_head @ 
279           metas_for_tactic_goals
280       end
281     in
282     let goals = List.map (fun (metano, _, _) -> metano)  produced_metas in
283     produced_metas, goals
284   in
285   (* residual metas, preserving the original order *)
286   let before, after = 
287     let rec split e =
288       function 
289       | [] -> [],[]
290       | (metano, _, _) :: tl when metano = e -> 
291           [], List.map (fun (x,_,_) -> x) tl
292       | (metano, _, _) :: tl -> let b, a = split e tl in metano :: b, a
293     in
294     let find n metasenv =
295       try
296         Some (List.find (fun (metano, _, _) -> metano = n) metasenv)
297       with Not_found -> None
298     in
299     let extract l =
300       List.fold_right 
301         (fun n acc -> 
302           match find n tactic with
303           | Some x -> x::acc
304           | None -> acc
305         ) l [] in
306     let before_l, after_l = split current_goal start in
307     let before_l = 
308       List.filter (fun x -> not (List.mem x produced_goals)) before_l in
309     let after_l = 
310       List.filter (fun x -> not (List.mem x produced_goals)) after_l in
311     let before = extract before_l in
312     let after = extract after_l in
313       before, after
314   in
315 (* |+   DEBUG CODE  +|
316   print_m "BEGIN" start;
317   prerr_endline ("goal was: " ^ string_of_int current_goal);
318   prerr_endline ("and metas from refine are:");
319   List.iter 
320     (fun t -> prerr_string (" " ^ string_of_int t)) 
321   new_goals_from_refine;
322   prerr_endline "";
323   print_m "before" before;
324   print_m "metas_for_tactic_head" metas_for_tactic_head;
325   print_m "metas_for_refine_goals" metas_for_refine_goals;
326   print_m "metas_for_tactic_goals" metas_for_tactic_goals;
327   print_m "produced_metas" produced_metas;
328   print_m "after" after; 
329 |+   FINE DEBUG CODE +| *)
330   before @ produced_metas @ after, goals 
331   
332 let apply_tactic ~disambiguate_tactic (text,prefix_len,tactic) (status, goal) =
333  let starting_metasenv = GrafiteTypes.get_proof_metasenv status in
334  let before = List.map (fun g, _, _ -> g) starting_metasenv in
335  let status, tactic = disambiguate_tactic status goal (text,prefix_len,tactic) in
336  let metasenv_after_refinement =  GrafiteTypes.get_proof_metasenv status in
337  let proof = GrafiteTypes.get_current_proof status in
338  let proof_status = proof, goal in
339  let always_opens_a_goal = classify_tactic tactic in
340  let tactic = tactic_of_ast status tactic in
341  let (proof, opened) = ProofEngineTypes.apply_tactic tactic proof_status in
342  let after = ProofEngineTypes.goals_of_proof proof in
343  let opened_goals, closed_goals = Tacticals.goals_diff ~before ~after ~opened in
344  let proof, opened_goals = 
345   let uri, metasenv_after_tactic, subst, t, ty, attrs = proof in
346   let reordered_metasenv, opened_goals = 
347     reorder_metasenv
348      starting_metasenv
349      metasenv_after_refinement metasenv_after_tactic
350      opened goal always_opens_a_goal
351   in
352   let proof' = uri, reordered_metasenv, [], t, ty, attrs in
353   proof', opened_goals
354  in
355  let incomplete_proof =
356    match status#proof_status with
357    | GrafiteTypes.Incomplete_proof p -> p
358    | _ -> assert false
359  in
360   status#set_proof_status
361    (GrafiteTypes.Incomplete_proof
362      { incomplete_proof with GrafiteTypes.proof = proof }),
363  opened_goals, closed_goals
364
365 let apply_atomic_tactical ~disambiguate_tactic ~patch (text,prefix_len,tactic) (status, goal) =
366  let starting_metasenv = GrafiteTypes.get_proof_metasenv status in
367  let before = List.map (fun g, _, _ -> g) starting_metasenv in
368  let status, tactic = disambiguate_tactic status goal (text,prefix_len,tactic) in
369  let metasenv_after_refinement =  GrafiteTypes.get_proof_metasenv status in
370  let proof = GrafiteTypes.get_current_proof status in
371  let proof_status = proof, goal in
372  let always_opens_a_goal = classify_tactic tactic in
373  let tactic = tactic_of_ast status tactic in
374  let tactic = patch tactic in
375  let (proof, opened) = ProofEngineTypes.apply_tactic tactic proof_status in
376  let after = ProofEngineTypes.goals_of_proof proof in
377  let opened_goals, closed_goals = Tacticals.goals_diff ~before ~after ~opened in
378  let proof, opened_goals = 
379   let uri, metasenv_after_tactic, _subst, t, ty, attrs = proof in
380   let reordered_metasenv, opened_goals = 
381     reorder_metasenv
382      starting_metasenv
383      metasenv_after_refinement metasenv_after_tactic
384      opened goal always_opens_a_goal
385   in
386   let proof' = uri, reordered_metasenv, _subst, t, ty, attrs in
387   proof', opened_goals
388  in
389  let incomplete_proof =
390    match status#proof_status with
391    | GrafiteTypes.Incomplete_proof p -> p
392    | _ -> assert false
393  in
394   status#set_proof_status
395    (GrafiteTypes.Incomplete_proof
396      { incomplete_proof with GrafiteTypes.proof = proof }),
397  opened_goals, closed_goals
398 type eval_ast =
399  {ea_go:
400   'term 'lazy_term 'reduction 'obj 'ident.
401   disambiguate_tactic:
402    (GrafiteTypes.status ->
403     ProofEngineTypes.goal ->
404     (('term, 'lazy_term, 'reduction, 'ident) GrafiteAst.tactic)
405     disambiguator_input ->
406     GrafiteTypes.status *
407    (Cic.term, Cic.lazy_term, Cic.lazy_term GrafiteAst.reduction, string) GrafiteAst.tactic) ->
408
409   disambiguate_command:
410    (GrafiteTypes.status ->
411     (('term,'obj) GrafiteAst.command) disambiguator_input ->
412     GrafiteTypes.status * (Cic.term,Cic.obj) GrafiteAst.command) ->
413
414   disambiguate_macro:
415    (GrafiteTypes.status ->
416     (('term,'lazy_term) GrafiteAst.macro) disambiguator_input ->
417     Cic.context -> GrafiteTypes.status * (Cic.term,Cic.lazy_term) GrafiteAst.macro) ->
418
419   ?do_heavy_checks:bool ->
420   GrafiteTypes.status ->
421   (('term, 'lazy_term, 'reduction, 'obj, 'ident) GrafiteAst.statement)
422   disambiguator_input ->
423   GrafiteTypes.status * [`Old of UriManager.uri list | `New of NUri.uri list]
424  }
425
426 type 'a eval_command =
427  {ec_go: 'term 'obj.
428   disambiguate_command:
429    (GrafiteTypes.status -> (('term,'obj) GrafiteAst.command) disambiguator_input ->
430     GrafiteTypes.status * (Cic.term,Cic.obj) GrafiteAst.command) -> 
431   options -> GrafiteTypes.status -> 
432     (('term,'obj) GrafiteAst.command) disambiguator_input ->
433    GrafiteTypes.status * [`Old of UriManager.uri list | `New of NUri.uri list]
434  }
435
436 type 'a eval_comment =
437  {ecm_go: 'term 'lazy_term 'reduction_kind 'obj 'ident.
438   disambiguate_command:
439    (GrafiteTypes.status -> (('term,'obj) GrafiteAst.command) disambiguator_input ->
440     GrafiteTypes.status * (Cic.term,Cic.obj) GrafiteAst.command) -> 
441   options -> GrafiteTypes.status -> 
442     (('term,'lazy_term,'reduction_kind,'obj,'ident) GrafiteAst.comment) disambiguator_input ->
443    GrafiteTypes.status * [`Old of UriManager.uri list | `New of NUri.uri list]
444  }
445
446 type 'a eval_executable =
447  {ee_go: 'term 'lazy_term 'reduction 'obj 'ident.
448   disambiguate_tactic:
449    (GrafiteTypes.status ->
450     ProofEngineTypes.goal ->
451     (('term, 'lazy_term, 'reduction, 'ident) GrafiteAst.tactic)
452     disambiguator_input ->
453     GrafiteTypes.status *
454    (Cic.term, Cic.lazy_term, Cic.lazy_term GrafiteAst.reduction, string) GrafiteAst.tactic) ->
455
456   disambiguate_command:
457    (GrafiteTypes.status ->
458     (('term,'obj) GrafiteAst.command) disambiguator_input ->
459     GrafiteTypes.status * (Cic.term,Cic.obj) GrafiteAst.command) ->
460
461   disambiguate_macro:
462    (GrafiteTypes.status ->
463     (('term,'lazy_term) GrafiteAst.macro) disambiguator_input ->
464     Cic.context -> GrafiteTypes.status * (Cic.term,Cic.lazy_term) GrafiteAst.macro) ->
465
466   options ->
467   GrafiteTypes.status ->
468   (('term, 'lazy_term, 'reduction, 'obj, 'ident) GrafiteAst.code) disambiguator_input ->
469   GrafiteTypes.status * [`Old of UriManager.uri list | `New of NUri.uri list]
470  }
471
472 type 'a eval_from_moo =
473  { efm_go: GrafiteTypes.status -> string -> GrafiteTypes.status }
474       
475 let coercion_moo_statement_of (uri,arity, saturations,_) =
476   GrafiteAst.Coercion
477    (HExtlib.dummy_floc, CicUtil.term_of_uri uri, false, arity, saturations)
478
479 let basic_eval_unification_hint (t,n) status =
480  NCicUnifHint.add_user_provided_hint status t n
481 ;;
482
483 let inject_unification_hint =
484  let basic_eval_unification_hint (t,n) 
485    ~refresh_uri_in_universe 
486    ~refresh_uri_in_term
487  =
488   let t = refresh_uri_in_term t in basic_eval_unification_hint (t,n)
489  in
490   NRstatus.Serializer.register "unification_hints" basic_eval_unification_hint
491 ;;
492
493 let eval_unification_hint status t n = 
494  let metasenv,subst,status,t =
495   GrafiteDisambiguate.disambiguate_nterm None status [] [] [] ("",0,t) in
496  assert (metasenv=[]);
497  let t = NCicUntrusted.apply_subst subst [] t in
498  let status = basic_eval_unification_hint (t,n) status in
499  let dump = inject_unification_hint (t,n)::status#dump in
500  let status = status#set_dump dump in
501   status,`New []
502 ;;
503
504 let basic_eval_add_constraint (u1,u2) status =
505  NCicLibrary.add_constraint status u1 u2
506 ;;
507
508 let inject_constraint =
509  let basic_eval_add_constraint (u1,u2) 
510        ~refresh_uri_in_universe 
511        ~refresh_uri_in_term
512  =
513   let u1 = refresh_uri_in_universe u1 in 
514   let u2 = refresh_uri_in_universe u2 in 
515   basic_eval_add_constraint (u1,u2)
516  in
517   NRstatus.Serializer.register "constraints" basic_eval_add_constraint
518 ;;
519
520 let eval_add_constraint status u1 u2 = 
521  let status = basic_eval_add_constraint (u1,u2) status in
522  let dump = inject_constraint (u1,u2)::status#dump in
523  let status = status#set_dump dump in
524   status,`Old []
525 ;;
526
527 let add_coercions_of_lemmas lemmas status =
528   let moo_content = 
529     HExtlib.filter_map 
530       (fun uri ->
531         match CoercDb.is_a_coercion (Cic.Const (uri,[])) with
532         | None -> None
533         | Some (_,tgt,_,sat,_) ->
534             let arity = match tgt with CoercDb.Fun n -> n | _ -> 0 in
535             Some (coercion_moo_statement_of (uri,arity,sat,0)))
536       lemmas
537   in
538   let status = GrafiteTypes.add_moo_content moo_content status in 
539    status#set_coercions (CoercDb.dump ()), 
540   lemmas
541
542 let eval_coercion status ~add_composites uri arity saturations =
543  let uri = 
544    try CicUtil.uri_of_term uri 
545    with Invalid_argument _ -> 
546      raise (Invalid_argument "coercion can only be constants/constructors")
547  in
548  let status, lemmas =
549   GrafiteSync.add_coercion ~add_composites 
550     ~pack_coercion_obj:CicRefine.pack_coercion_obj
551    status uri arity saturations status#baseuri in
552  let moo_content = coercion_moo_statement_of (uri,arity,saturations,0) in
553  let status = GrafiteTypes.add_moo_content [moo_content] status in 
554   add_coercions_of_lemmas lemmas status
555
556 let eval_prefer_coercion status c =
557  let uri = 
558    try CicUtil.uri_of_term c 
559    with Invalid_argument _ -> 
560      raise (Invalid_argument "coercion can only be constants/constructors")
561  in
562  let status = GrafiteSync.prefer_coercion status uri in
563  let moo_content = GrafiteAst.PreferCoercion (HExtlib.dummy_floc,c) in
564  let status = GrafiteTypes.add_moo_content [moo_content] status in 
565  status, `Old []
566
567 module MatitaStatus =
568  struct
569   type input_status = GrafiteTypes.status * ProofEngineTypes.goal
570
571   type output_status =
572     GrafiteTypes.status * ProofEngineTypes.goal list * ProofEngineTypes.goal list
573
574   type tactic = input_status -> output_status
575
576   let mk_tactic tac = tac
577   let apply_tactic tac = tac
578   let goals (_, opened, closed) = opened, closed
579   let get_stack (status, _) = GrafiteTypes.get_stack status
580   
581   let set_stack stack (status, opened, closed) = 
582     GrafiteTypes.set_stack stack status, opened, closed
583
584   let inject (status, _) = (status, [], [])
585   let focus goal (status, _, _) = (status, goal)
586  end
587
588 module MatitaTacticals = Continuationals.Make(MatitaStatus)
589
590 let tactic_of_ast' tac =
591  MatitaTacticals.Tactical (MatitaTacticals.Tactic (MatitaStatus.mk_tactic tac))
592
593 let punctuation_tactical_of_ast (text,prefix_len,punct) =
594  match punct with
595   | GrafiteAst.Dot _loc -> MatitaTacticals.Dot
596   | GrafiteAst.Semicolon _loc -> MatitaTacticals.Semicolon
597   | GrafiteAst.Branch _loc -> MatitaTacticals.Branch
598   | GrafiteAst.Shift _loc -> MatitaTacticals.Shift
599   | GrafiteAst.Pos (_loc, i) -> MatitaTacticals.Pos i
600   | GrafiteAst.Merge _loc -> MatitaTacticals.Merge
601   | GrafiteAst.Wildcard _loc -> MatitaTacticals.Wildcard
602
603 let non_punctuation_tactical_of_ast (text,prefix_len,punct) =
604  match punct with
605   | GrafiteAst.Focus (_loc,goals) -> MatitaTacticals.Focus goals
606   | GrafiteAst.Unfocus _loc -> MatitaTacticals.Unfocus
607   | GrafiteAst.Skip _loc -> MatitaTacticals.Tactical MatitaTacticals.Skip
608
609 let eval_tactical status tac =
610   let status, _, _ = MatitaTacticals.eval tac (status, ~-1) in
611   let status =  (* is proof completed? *)
612     match status#proof_status with
613     | GrafiteTypes.Incomplete_proof
614        { GrafiteTypes.stack = stack; proof = proof }
615       when Continuationals.Stack.is_empty stack ->
616        status#set_proof_status (GrafiteTypes.Proof proof)
617     | _ -> status
618   in
619   status
620
621 let add_obj = GrafiteSync.add_obj ~pack_coercion_obj:CicRefine.pack_coercion_obj
622
623 let eval_ng_punct (_text, _prefix_len, punct) =
624   match punct with
625   | GrafiteAst.Dot _ -> NTactics.dot_tac 
626   | GrafiteAst.Semicolon _ -> fun x -> x
627   | GrafiteAst.Branch _ -> NTactics.branch_tac 
628   | GrafiteAst.Shift _ -> NTactics.shift_tac 
629   | GrafiteAst.Pos (_,l) -> NTactics.pos_tac l
630   | GrafiteAst.Wildcard _ -> NTactics.wildcard_tac 
631   | GrafiteAst.Merge _ -> NTactics.merge_tac 
632 ;;
633
634 let eval_ng_tac tac =
635  let rec aux f (text, prefix_len, tac) =
636   match tac with
637   | GrafiteAst.NApply (_loc, t) -> NTactics.apply_tac (text,prefix_len,t) 
638   | GrafiteAst.NAssert (_loc, seqs) ->
639      NTactics.assert_tac
640       ((List.map
641         (function (hyps,concl) ->
642           List.map
643            (function
644               (id,`Decl t) -> id,`Decl (text,prefix_len,t)
645              |(id,`Def (b,t))->id,`Def((text,prefix_len,b),(text,prefix_len,t))
646            ) hyps,
647           (text,prefix_len,concl))
648        ) seqs)
649   | GrafiteAst.NAuto (_loc, (l,a)) ->
650       NTactics.auto_tac
651         ~params:(List.map (fun x -> "",0,x) l,a)
652   | GrafiteAst.NBranch _ -> NTactics.branch_tac 
653   | GrafiteAst.NCases (_loc, what, where) ->
654       NTactics.cases_tac 
655         ~what:(text,prefix_len,what)
656         ~where:(text,prefix_len,where)
657   | GrafiteAst.NCase1 (_loc,n) -> NTactics.case1_tac n
658   | GrafiteAst.NChange (_loc, pat, ww) -> 
659       NTactics.change_tac 
660        ~where:(text,prefix_len,pat) ~with_what:(text,prefix_len,ww) 
661   | GrafiteAst.NConstructor (_loc,num,args) -> 
662      NTactics.constructor_tac 
663        ?num ~args:(List.map (fun x -> text,prefix_len,x) args)
664   | GrafiteAst.NCut (_loc, t) -> NTactics.cut_tac (text,prefix_len,t) 
665   | GrafiteAst.NDot _ -> NTactics.dot_tac 
666   | GrafiteAst.NElim (_loc, what, where) ->
667       NTactics.elim_tac 
668         ~what:(text,prefix_len,what)
669         ~where:(text,prefix_len,where)
670   | GrafiteAst.NFocus (_,l) -> NTactics.focus_tac l
671   | GrafiteAst.NGeneralize (_loc, where) -> 
672       NTactics.generalize_tac ~where:(text,prefix_len,where)
673   | GrafiteAst.NId _ -> (fun x -> x)
674   | GrafiteAst.NIntro (_loc,n) -> NTactics.intro_tac n
675   | GrafiteAst.NLApply (_loc, t) -> NTactics.lapply_tac (text,prefix_len,t) 
676   | GrafiteAst.NLetIn (_loc,where,what,name) ->
677       NTactics.letin_tac ~where:(text,prefix_len,where) 
678         ~what:(text,prefix_len,what) name
679   | GrafiteAst.NMerge _ -> NTactics.merge_tac 
680   | GrafiteAst.NPos (_,l) -> NTactics.pos_tac l
681   | GrafiteAst.NReduce (_loc, reduction, where) ->
682       NTactics.reduce_tac ~reduction ~where:(text,prefix_len,where)
683   | GrafiteAst.NRewrite (_loc,dir,what,where) ->
684      NTactics.rewrite_tac ~dir ~what:(text,prefix_len,what)
685       ~where:(text,prefix_len,where)
686   | GrafiteAst.NSemicolon _ -> fun x -> x
687   | GrafiteAst.NShift _ -> NTactics.shift_tac 
688   | GrafiteAst.NSkip _ -> NTactics.skip_tac
689   | GrafiteAst.NUnfocus _ -> NTactics.unfocus_tac
690   | GrafiteAst.NWildcard _ -> NTactics.wildcard_tac 
691   | GrafiteAst.NTry (_,tac) -> NTactics.try_tac
692       (aux f (text, prefix_len, tac))
693   | GrafiteAst.NAssumption _ -> NTactics.assumption_tac
694   | GrafiteAst.NBlock (_,l) -> 
695       NTactics.block_tac (List.map (fun x -> aux f (text,prefix_len,x)) l)
696   |GrafiteAst.NRepeat (_,tac) ->
697       NTactics.repeat_tac (f f (text, prefix_len, tac))
698  in
699   aux aux tac (* trick for non uniform recursion call *)
700 ;;
701       
702 let subst_metasenv_and_fix_names status =
703   let u,h,metasenv, subst,o = status#obj in
704   let o = 
705     NCicUntrusted.map_obj_kind ~skip_body:true 
706      (NCicUntrusted.apply_subst subst []) o
707   in
708    status#set_obj(u,h,NCicUntrusted.apply_subst_metasenv subst metasenv,subst,o)
709 ;;
710
711 let rec eval_ncommand opts status (text,prefix_len,cmd) =
712   match cmd with
713   | GrafiteAst.UnificationHint (loc, t, n) -> eval_unification_hint status t n
714   | GrafiteAst.NCoercion (loc, name, t, ty, source, target) ->
715       NCicCoercDeclaration.eval_ncoercion status name t ty source target
716   | GrafiteAst.NQed loc ->
717      if status#ng_mode <> `ProofMode then
718       raise (GrafiteTypes.Command_error "Not in proof mode")
719      else
720       let uri,height,menv,subst,obj_kind = status#obj in
721        if menv <> [] then
722         raise
723          (GrafiteTypes.Command_error"You can't Qed an incomplete theorem")
724        else
725         let obj_kind =
726          NCicUntrusted.map_obj_kind 
727           (NCicUntrusted.apply_subst subst []) obj_kind in
728         let height = NCicTypeChecker.height_of_obj_kind uri [] obj_kind in
729         (* fix the height inside the object *)
730         let rec fix () = function 
731           | NCic.Const (NReference.Ref (u,spec)) when NUri.eq u uri -> 
732              NCic.Const (NReference.reference_of_spec u
733               (match spec with
734               | NReference.Def _ -> NReference.Def height
735               | NReference.Fix (i,j,_) -> NReference.Fix(i,j,height)
736               | NReference.CoFix _ -> NReference.CoFix height
737               | NReference.Ind _ | NReference.Con _
738               | NReference.Decl as s -> s))
739           | t -> NCicUtils.map (fun _ () -> ()) () fix t
740         in
741         let obj_kind = 
742           match obj_kind with
743           | NCic.Fixpoint _ -> 
744               NCicUntrusted.map_obj_kind (fix ()) obj_kind 
745           | _ -> obj_kind
746         in
747         let obj = uri,height,[],[],obj_kind in
748         let old_status = status in
749         let status = NCicLibrary.add_obj status obj in
750         HLog.message ("New object: " ^ NUri.string_of_uri uri);
751          (try
752        (*prerr_endline (NCicPp.ppobj obj);*)
753            let boxml = NCicElim.mk_elims obj in
754            let boxml = boxml @ NCicElim.mk_projections obj in
755 (*
756            let objs = [] in
757            let timestamp,uris_rev =
758              List.fold_left
759               (fun (status,uris_rev) (uri,_,_,_,_) as obj ->
760                 let status = NCicLibrary.add_obj status obj in
761                  status,uri::uris_rev
762               ) (status,[]) objs in
763            let uris = uri::List.rev uris_rev in
764 *)
765            let status = status#set_ng_mode `CommandMode in
766            let status = LexiconSync.add_aliases_for_objs status (`New [uri]) in
767            let status,uris =
768             List.fold_left
769              (fun (status,uris) boxml ->
770                try
771                 let status,nuris =
772                  eval_ncommand opts status
773                   ("",0,GrafiteAst.NObj (HExtlib.dummy_floc,boxml))
774                 in
775                 status, concat_nuris uris nuris
776                with
777                | MultiPassDisambiguator.DisambiguationError _ 
778                | NCicTypeChecker.TypeCheckerFailure _ ->
779                   HLog.warn "error in generating projection/eliminator";
780                   status,uris
781              ) (status,`New [] (* uris *)) boxml in
782            let coercions =
783             match obj with
784               _,_,_,_,NCic.Inductive
785                (true,leftno,[_,_,_,[_,_,_]],(_,`Record fields))
786                ->
787                 HExtlib.filter_map
788                  (fun (name,is_coercion,arity) ->
789                    if is_coercion then Some(name,leftno,arity) else None) fields
790             | _ -> [] in
791            let status,uris =
792             List.fold_left
793              (fun (status,uris) (name,cpos,arity) ->
794                try
795                  let metasenv,subst,status,t =
796                   GrafiteDisambiguate.disambiguate_nterm None status [] [] []
797                    ("",0,CicNotationPt.Ident (name,None)) in
798                  assert (metasenv = [] && subst = []);
799                  let status, nuris = 
800                    NCicCoercDeclaration.
801                      basic_eval_and_record_ncoercion_from_t_cpos_arity 
802                       status (name,t,cpos,arity)
803                  in
804                  let uris = concat_nuris nuris uris in
805                  status, uris
806                with MultiPassDisambiguator.DisambiguationError _-> 
807                  HLog.warn ("error in generating coercion: "^name);
808                  status, uris) 
809              (status,uris) coercions
810            in
811             status,uris
812           with
813            exn ->
814             NCicLibrary.time_travel old_status;
815             raise exn)
816   | GrafiteAst.NCopy (log,tgt,src_uri, map) ->
817      if status#ng_mode <> `CommandMode then
818       raise (GrafiteTypes.Command_error "Not in command mode")
819      else
820        let tgt_uri_ext, old_ok = 
821          match NCicEnvironment.get_checked_obj src_uri with
822          | _,_,[],[], (NCic.Inductive _ as ok) -> ".ind", ok
823          | _,_,[],[], (NCic.Fixpoint _ as ok) -> ".con", ok
824          | _,_,[],[], (NCic.Constant _ as ok) -> ".con", ok
825          | _ -> assert false
826        in
827        let tgt_uri = NUri.uri_of_string (status#baseuri^"/"^tgt^tgt_uri_ext) in
828        let map = (src_uri, tgt_uri) :: map in
829        let ok = 
830          let rec subst () = function
831            | NCic.Meta _ -> assert false
832            | NCic.Const (NReference.Ref (u,spec)) as t ->
833                (try NCic.Const 
834                  (NReference.reference_of_spec (List.assoc u map)spec)
835                with Not_found -> t)
836            | t -> NCicUtils.map (fun _ _ -> ()) () subst t
837          in
838          NCicUntrusted.map_obj_kind ~skip_body:false (subst ()) old_ok
839        in
840        let ninitial_stack = Continuationals.Stack.of_nmetasenv [] in
841        let status = status#set_obj (tgt_uri,0,[],[],ok) in
842        (*prerr_endline (NCicPp.ppobj (tgt_uri,0,[],[],ok));*)
843        let status = status#set_stack ninitial_stack in
844        let status = subst_metasenv_and_fix_names status in
845        let status = status#set_ng_mode `ProofMode in
846        eval_ncommand opts status ("",0,GrafiteAst.NQed Stdpp.dummy_loc)
847   | GrafiteAst.NObj (loc,obj) ->
848      if status#ng_mode <> `CommandMode then
849       raise (GrafiteTypes.Command_error "Not in command mode")
850      else
851       let status,obj =
852        GrafiteDisambiguate.disambiguate_nobj status
853         ~baseuri:status#baseuri (text,prefix_len,obj) in
854       let uri,height,nmenv,nsubst,nobj = obj in
855       let ninitial_stack = Continuationals.Stack.of_nmetasenv nmenv in
856       let status = status#set_obj obj in
857       let status = status#set_stack ninitial_stack in
858       let status = subst_metasenv_and_fix_names status in
859       let status = status#set_ng_mode `ProofMode in
860       (match nmenv with
861           [] ->
862            eval_ncommand opts status ("",0,GrafiteAst.NQed Stdpp.dummy_loc)
863         | _ -> status,`New [])
864   | GrafiteAst.NInverter (loc, name, indty) ->
865      if status#ng_mode <> `CommandMode then
866       raise (GrafiteTypes.Command_error "Not in command mode")
867      else
868       let status = status#set_ng_mode `ProofMode in
869       let metasenv,subst,status,indty =
870        GrafiteDisambiguate.disambiguate_nterm None status [] [] [] (text,prefix_len,indty) in
871       let _,leftno,tys,_,_ = match indty with
872           NCic.Const r -> NCicEnvironment.get_checked_indtys r
873         | _ -> assert false in
874       let it = match tys with
875           hd::tl -> hd
876         | _ -> assert false
877       in
878      let status,obj =
879       NInversion.mk_inverter name it leftno status status#baseuri in
880      let _,_,menv,_,_ = obj in
881      (match menv with
882         [] ->
883           eval_ncommand opts status ("",0,GrafiteAst.NQed Stdpp.dummy_loc)
884       | _ -> assert false)
885   | GrafiteAst.NUnivConstraint (loc,u1,u2) ->
886       eval_add_constraint status [`Type,u1] [`Type,u2]
887 ;;
888
889 let rec eval_command = {ec_go = fun ~disambiguate_command opts status
890 (text,prefix_len,cmd) ->
891  let status,cmd = disambiguate_command status (text,prefix_len,cmd) in
892  let status,uris =
893   match cmd with
894   | GrafiteAst.Index (loc,None,uri) -> 
895         assert false (* TODO: for user input *)
896   | GrafiteAst.Index (loc,Some key,uri) -> 
897       let universe = 
898         status#automation_cache.AutomationCache.univ
899       in
900       let universe = Universe.index universe key (CicUtil.term_of_uri uri) in
901       let cache = { 
902         status#automation_cache with AutomationCache.univ = universe } 
903       in
904       let status = status#set_automation_cache cache in
905 (* debug
906       let msg =
907        let candidates = Universe.get_candidates status.GrafiteTypes.universe key in
908        ("candidates for " ^ (CicPp.ppterm key) ^ " = " ^ 
909           (String.concat "\n" (List.map CicPp.ppterm candidates))) 
910      in
911      prerr_endline msg;
912 *)
913       let status = GrafiteTypes.add_moo_content [cmd] status in
914       status,`Old [] 
915   | GrafiteAst.Select (_,uri) as cmd ->
916       if List.mem cmd status#moo_content_rev then status, `Old []
917       else 
918        let cache = 
919          AutomationCache.add_term_to_active status#automation_cache
920            [] [] [] (CicUtil.term_of_uri uri) None
921        in
922        let status = status#set_automation_cache cache in
923        let status = GrafiteTypes.add_moo_content [cmd] status in
924        status, `Old []
925   | GrafiteAst.Pump (_,steps) ->
926       let cache = 
927         AutomationCache.pump status#automation_cache steps
928       in
929       let status = status#set_automation_cache cache in
930       status, `Old []
931   | GrafiteAst.PreferCoercion (loc, coercion) ->
932      eval_prefer_coercion status coercion
933   | GrafiteAst.Coercion (loc, uri, add_composites, arity, saturations) ->
934      let res,uris =
935       eval_coercion status ~add_composites uri arity saturations
936      in
937       res,`Old uris
938   | GrafiteAst.Inverter (loc, name, indty, params) ->
939      let buri = status#baseuri in 
940      let uri = UriManager.uri_of_string (buri ^ "/" ^ name ^ ".con") in
941      let indty_uri = 
942        try CicUtil.uri_of_term indty
943        with Invalid_argument _ ->
944          raise (Invalid_argument "not an inductive type to invert") in
945      let res,uris =
946       Inversion_principle.build_inverter ~add_obj status uri indty_uri params
947      in
948       res,`Old uris
949   | GrafiteAst.Default (loc, what, uris) as cmd ->
950      LibraryObjects.set_default what uris;
951      GrafiteTypes.add_moo_content [cmd] status,`Old []
952   | GrafiteAst.Drop loc -> raise Drop
953   | GrafiteAst.Include (loc, mode, new_or_old, baseuri) ->
954      (* Old Include command is not recursive; new one is *)
955      let status =
956       if new_or_old = `OldAndNew then
957        let moopath_rw, moopath_r = 
958         LibraryMisc.obj_file_of_baseuri 
959           ~must_exist:false ~baseuri ~writable:true,
960         LibraryMisc.obj_file_of_baseuri 
961           ~must_exist:false ~baseuri ~writable:false in
962        let moopath = 
963         if Sys.file_exists moopath_r then moopath_r else
964           if Sys.file_exists moopath_rw then moopath_rw else
965             raise (IncludedFileNotCompiled (moopath_rw,baseuri))
966        in
967         eval_from_moo.efm_go status moopath
968       else
969        status
970      in
971       let status =
972        NRstatus.Serializer.require ~baseuri:(NUri.uri_of_string baseuri)
973         status in
974       let status =
975        GrafiteTypes.add_moo_content
976         [GrafiteAst.Include (loc,mode,`New,baseuri)] status
977       in
978        status,`Old []
979   | GrafiteAst.Print (_,"proofterm") ->
980       let _,_,_,p,_, _ = GrafiteTypes.get_current_proof status in
981       prerr_endline (Auto.pp_proofterm (Lazy.force p));
982       status,`Old []
983   | GrafiteAst.Print (_,_) -> status,`Old []
984   | GrafiteAst.Qed loc ->
985       let uri, metasenv, _subst, bo, ty, attrs =
986         match status#proof_status with
987         | GrafiteTypes.Proof (Some uri, metasenv, subst, body, ty, attrs) ->
988             uri, metasenv, subst, body, ty, attrs
989         | GrafiteTypes.Proof (None, metasenv, subst, body, ty, attrs) -> 
990             raise (GrafiteTypes.Command_error 
991               ("Someone allows to start a theorem without giving the "^
992                "name/uri. This should be fixed!"))
993         | _->
994           raise
995            (GrafiteTypes.Command_error "You can't Qed an incomplete theorem")
996       in
997       if metasenv <> [] then 
998         raise
999          (GrafiteTypes.Command_error
1000            "Proof not completed! metasenv is not empty!");
1001       let name = UriManager.name_of_uri uri in
1002       let obj = Cic.Constant (name,Some (Lazy.force bo),ty,[],attrs) in
1003       let status, lemmas = add_obj uri obj status in
1004        status#set_proof_status GrafiteTypes.No_proof,
1005         (*CSC: I throw away the arities *)
1006         `Old (uri::lemmas)
1007   | GrafiteAst.Relation (loc, id, a, aeq, refl, sym, trans) -> 
1008      Setoids.add_relation id a aeq refl sym trans;
1009      status, `Old [] (*CSC: TO BE FIXED *)
1010   | GrafiteAst.Set (loc, name, value) -> status, `Old []
1011 (*       GrafiteTypes.set_option status name value,[] *)
1012   | GrafiteAst.Obj (loc,obj) ->
1013      let ext,name =
1014       match obj with
1015          Cic.Constant (name,_,_,_,_)
1016        | Cic.CurrentProof (name,_,_,_,_,_) -> ".con",name
1017        | Cic.InductiveDefinition (types,_,_,_) ->
1018           ".ind",
1019           (match types with (name,_,_,_)::_ -> name | _ -> assert false)
1020        | _ -> assert false in
1021      let buri = status#baseuri in 
1022      let uri = UriManager.uri_of_string (buri ^ "/" ^ name ^ ext) in
1023      let obj = CicRefine.pack_coercion_obj obj in
1024      let metasenv = GrafiteTypes.get_proof_metasenv status in
1025      match obj with
1026      | Cic.CurrentProof (_,metasenv',bo,ty,_, attrs) ->
1027          let name = UriManager.name_of_uri uri in
1028          if not(CicPp.check name ty) then
1029            HLog.warn ("Bad name: " ^ name);
1030          if opts.do_heavy_checks then
1031            begin
1032              let dbd = LibraryDb.instance () in
1033              let similar = Whelp.match_term ~dbd ty in
1034              let similar_len = List.length similar in
1035              if similar_len> 30 then
1036                (HLog.message
1037                  ("Duplicate check will compare your theorem with " ^ 
1038                    string_of_int similar_len ^ 
1039                    " theorems, this may take a while."));
1040              let convertible =
1041                List.filter (
1042                  fun u ->
1043                    let t = CicUtil.term_of_uri u in
1044                    let ty',g = 
1045                      CicTypeChecker.type_of_aux' 
1046                        metasenv' [] t CicUniv.oblivion_ugraph
1047                    in
1048                    fst(CicReduction.are_convertible [] ty' ty g)) 
1049                similar 
1050              in
1051              (match convertible with
1052              | [] -> ()
1053              | x::_ -> 
1054                  HLog.warn  
1055                  ("Theorem already proved: " ^ UriManager.string_of_uri x ^ 
1056                   "\nPlease use a variant."));
1057            end;
1058          let _subst = [] in
1059          let initial_proof = (Some uri, metasenv', _subst, lazy bo, ty, attrs) in
1060          let initial_stack = Continuationals.Stack.of_metasenv metasenv' in
1061           status#set_proof_status
1062            (GrafiteTypes.Incomplete_proof
1063             { GrafiteTypes.proof = initial_proof; stack = initial_stack }),
1064           `Old []
1065      | _ ->
1066          if metasenv <> [] then
1067           raise (GrafiteTypes.Command_error (
1068             "metasenv not empty while giving a definition with body: " ^
1069             CicMetaSubst.ppmetasenv [] metasenv));
1070          let status, lemmas = add_obj uri obj status in 
1071          let status,new_lemmas = add_coercions_of_lemmas lemmas status in
1072           status#set_proof_status GrafiteTypes.No_proof,
1073            `Old (uri::new_lemmas@lemmas)
1074  in
1075   match status#proof_status with
1076      GrafiteTypes.Intermediate _ ->
1077       status#set_proof_status GrafiteTypes.No_proof,uris
1078    | _ -> status,uris
1079
1080 } and eval_executable = {ee_go = fun ~disambiguate_tactic ~disambiguate_command
1081 ~disambiguate_macro opts status (text,prefix_len,ex) ->
1082   match ex with
1083   | GrafiteAst.Tactic (_(*loc*), Some tac, punct) ->
1084      let tac = apply_tactic ~disambiguate_tactic (text,prefix_len,tac) in
1085      let status = eval_tactical status (tactic_of_ast' tac) in
1086      (* CALL auto on every goal, easy way of testing it  
1087      let auto = 
1088        GrafiteAst.AutoBatch 
1089          (loc, ([],["depth","2";"timeout","1";"type","1"])) in
1090      (try
1091        let auto = apply_tactic ~disambiguate_tactic ("",0,auto) in
1092        let _ = eval_tactical status (tactic_of_ast' auto) in 
1093        print_endline "GOOD"; () 
1094      with ProofEngineTypes.Fail _ -> print_endline "BAD" | _ -> ());*)
1095       eval_tactical status
1096        (punctuation_tactical_of_ast (text,prefix_len,punct)),`Old []
1097   | GrafiteAst.Tactic (_, None, punct) ->
1098       eval_tactical status
1099        (punctuation_tactical_of_ast (text,prefix_len,punct)),`Old []
1100   | GrafiteAst.NTactic (_(*loc*), tacl) ->
1101       if status#ng_mode <> `ProofMode then
1102        raise (GrafiteTypes.Command_error "Not in proof mode")
1103       else
1104        let status =
1105         List.fold_left 
1106           (fun status tac ->
1107             let status = eval_ng_tac (text,prefix_len,tac) status in
1108             subst_metasenv_and_fix_names status)
1109           status tacl
1110        in
1111         status,`New []
1112   | GrafiteAst.NonPunctuationTactical (_, tac, punct) ->
1113      let status = 
1114       eval_tactical status
1115        (non_punctuation_tactical_of_ast (text,prefix_len,tac))
1116      in
1117       eval_tactical status
1118        (punctuation_tactical_of_ast (text,prefix_len,punct)),`Old []
1119   | GrafiteAst.Command (_, cmd) ->
1120       eval_command.ec_go ~disambiguate_command opts status (text,prefix_len,cmd)
1121   | GrafiteAst.NCommand (_, cmd) ->
1122       eval_ncommand opts status (text,prefix_len,cmd)
1123   | GrafiteAst.Macro (loc, macro) ->
1124      raise (Macro (loc,disambiguate_macro status (text,prefix_len,macro)))
1125   | GrafiteAst.NMacro (loc, macro) ->
1126      raise (NMacro (loc,macro))
1127
1128 } and eval_from_moo = {efm_go = fun status fname ->
1129   let ast_of_cmd cmd =
1130     ("",0,GrafiteAst.Executable (HExtlib.dummy_floc,
1131       GrafiteAst.Command (HExtlib.dummy_floc,
1132         cmd)))
1133   in
1134   let moo = GrafiteMarshal.load_moo fname in
1135   List.fold_left 
1136     (fun status ast -> 
1137       let ast = ast_of_cmd ast in
1138       let status,lemmas =
1139        eval_ast.ea_go
1140          ~disambiguate_tactic:(fun status _ (_,_,tactic) -> status,tactic)
1141          ~disambiguate_command:(fun status (_,_,cmd) -> status,cmd)
1142          ~disambiguate_macro:(fun _ _ -> assert false)
1143          status ast
1144       in
1145        assert (lemmas=`Old []);
1146        status)
1147     status moo
1148 } and eval_ast = {ea_go = fun ~disambiguate_tactic ~disambiguate_command
1149 ~disambiguate_macro ?(do_heavy_checks=false) status
1150 (text,prefix_len,st)
1151 ->
1152   let opts = { do_heavy_checks = do_heavy_checks ; } in
1153   match st with
1154   | GrafiteAst.Executable (_,ex) ->
1155      eval_executable.ee_go ~disambiguate_tactic ~disambiguate_command
1156       ~disambiguate_macro opts status (text,prefix_len,ex)
1157   | GrafiteAst.Comment (_,c) -> 
1158       eval_comment.ecm_go ~disambiguate_command opts status (text,prefix_len,c) 
1159 } and eval_comment = { ecm_go = fun ~disambiguate_command opts status (text,prefix_len,c) -> 
1160     status, `Old []
1161 }
1162 ;;
1163
1164
1165 let eval_ast = eval_ast.ea_go