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