]> matita.cs.unibo.it Git - helm.git/blob - helm/software/components/grafite_engine/grafiteEngine.ml
new tactic constructor: @[n]
[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) -> NTactics.constructor_tac ?num
657   | GrafiteAst.NDot _ -> NTactics.dot_tac 
658   | GrafiteAst.NElim (_loc, what, where) ->
659       NTactics.elim_tac 
660         ~what:(text,prefix_len,what)
661         ~where:(text,prefix_len,where)
662   | GrafiteAst.NFocus (_,l) -> NTactics.focus_tac l
663   | GrafiteAst.NGeneralize (_loc, where) -> 
664       NTactics.generalize_tac ~where:(text,prefix_len,where)
665   | GrafiteAst.NId _ -> (fun x -> x)
666   | GrafiteAst.NIntro (_loc,n) -> NTactics.intro_tac n
667   | GrafiteAst.NLetIn (_loc,where,what,name) ->
668       NTactics.letin_tac ~where:(text,prefix_len,where) 
669         ~what:(text,prefix_len,what) name
670   | GrafiteAst.NMerge _ -> NTactics.merge_tac 
671   | GrafiteAst.NPos (_,l) -> NTactics.pos_tac l
672   | GrafiteAst.NReduce (_loc, reduction, where) ->
673       NTactics.reduce_tac ~reduction ~where:(text,prefix_len,where)
674   | GrafiteAst.NRewrite (_loc,dir,what,where) ->
675      NTactics.rewrite_tac ~dir ~what:(text,prefix_len,what)
676       ~where:(text,prefix_len,where)
677   | GrafiteAst.NSemicolon _ -> fun x -> x
678   | GrafiteAst.NShift _ -> NTactics.shift_tac 
679   | GrafiteAst.NSkip _ -> NTactics.skip_tac
680   | GrafiteAst.NUnfocus _ -> NTactics.unfocus_tac
681   | GrafiteAst.NWildcard _ -> NTactics.wildcard_tac 
682   | GrafiteAst.NTry (_,tac) -> NTactics.try_tac
683       (aux f (text, prefix_len, tac))
684   | GrafiteAst.NAssumption _ -> NTactics.assumption_tac
685   | GrafiteAst.NBlock (_,l) -> 
686       NTactics.block_tac (List.map (fun x -> aux f (text,prefix_len,x)) l)
687   |GrafiteAst.NRepeat (_,tac) ->
688       NTactics.repeat_tac (f f (text, prefix_len, tac))
689  in
690   aux aux tac (* trick for non uniform recursion call *)
691 ;;
692       
693 let subst_metasenv_and_fix_names status =
694   let u,h,metasenv, subst,o = status#obj in
695   let o = 
696     NCicUntrusted.map_obj_kind ~skip_body:true 
697      (NCicUntrusted.apply_subst subst []) o
698   in
699    status#set_obj(u,h,NCicUntrusted.apply_subst_metasenv subst metasenv,subst,o)
700 ;;
701
702 let rec eval_ncommand opts status (text,prefix_len,cmd) =
703   match cmd with
704   | GrafiteAst.UnificationHint (loc, t, n) -> eval_unification_hint status t n
705   | GrafiteAst.NCoercion (loc, name, t, ty, source, target) ->
706       NCicCoercDeclaration.eval_ncoercion status name t ty source target
707   | GrafiteAst.NQed loc ->
708      if status#ng_mode <> `ProofMode then
709       raise (GrafiteTypes.Command_error "Not in proof mode")
710      else
711       let uri,height,menv,subst,obj_kind = status#obj in
712        if menv <> [] then
713         raise
714          (GrafiteTypes.Command_error"You can't Qed an incomplete theorem")
715        else
716         let obj_kind =
717          NCicUntrusted.map_obj_kind 
718           (NCicUntrusted.apply_subst subst []) obj_kind in
719         let height = NCicTypeChecker.height_of_obj_kind uri [] obj_kind in
720         (* fix the height inside the object *)
721         let rec fix () = function 
722           | NCic.Const (NReference.Ref (u,spec)) when NUri.eq u uri -> 
723              NCic.Const (NReference.reference_of_spec u
724               (match spec with
725               | NReference.Def _ -> NReference.Def height
726               | NReference.Fix (i,j,_) -> NReference.Fix(i,j,height)
727               | NReference.CoFix _ -> NReference.CoFix height
728               | NReference.Ind _ | NReference.Con _
729               | NReference.Decl as s -> s))
730           | t -> NCicUtils.map (fun _ () -> ()) () fix t
731         in
732         let obj_kind = 
733           match obj_kind with
734           | NCic.Fixpoint _ -> 
735               NCicUntrusted.map_obj_kind (fix ()) obj_kind 
736           | _ -> obj_kind
737         in
738         let obj = uri,height,[],[],obj_kind in
739         let old_status = status in
740         let status = NCicLibrary.add_obj status obj in
741         HLog.message ("New object: " ^ NUri.string_of_uri uri);
742          (try
743        (*prerr_endline (NCicPp.ppobj obj);*)
744            let boxml = NCicElim.mk_elims obj in
745            let boxml = boxml @ NCicElim.mk_projections obj in
746 (*
747            let objs = [] in
748            let timestamp,uris_rev =
749              List.fold_left
750               (fun (status,uris_rev) (uri,_,_,_,_) as obj ->
751                 let status = NCicLibrary.add_obj status obj in
752                  status,uri::uris_rev
753               ) (status,[]) objs in
754            let uris = uri::List.rev uris_rev in
755 *)
756            let status = status#set_ng_mode `CommandMode in
757            let status = LexiconSync.add_aliases_for_objs status (`New [uri]) in
758            let status,uris =
759             List.fold_left
760              (fun (status,uris) boxml ->
761                try
762                 let status,nuris =
763                  eval_ncommand opts status
764                   ("",0,GrafiteAst.NObj (HExtlib.dummy_floc,boxml))
765                 in
766                  match uris,nuris with
767                     `New uris, `New nuris -> status,`New (nuris@uris)
768                   | _ -> assert false
769                with
770                 NCicTypeChecker.TypeCheckerFailure msg
771                  when Lazy.force msg =
772                  "Sort elimination not allowed" ->
773                   status,uris
774              ) (status,`New [] (* uris *)) boxml in
775            let coercions =
776             match obj with
777               _,_,_,_,NCic.Inductive
778                (true,leftno,[_,_,_,[_,_,_]],(_,`Record fields))
779                ->
780                 HExtlib.filter_map
781                  (fun (name,is_coercion,arity) ->
782                    if is_coercion then Some(name,leftno,arity) else None) fields
783             | _ -> [] in
784            let status =
785             List.fold_left
786              (fun status (name,cpos,arity) ->
787                let metasenv,subst,status,t =
788                 GrafiteDisambiguate.disambiguate_nterm None status [] [] []
789                  ("",0,CicNotationPt.Ident (name,None)) in
790                assert (metasenv = [] && subst = []);
791                NCicCoercDeclaration.basic_eval_and_inject_ncoercion_from_t_cpos_arity 
792                  status (name,t,cpos,arity)
793              ) status coercions
794            in
795             status,uris
796           with
797            exn ->
798             NCicLibrary.time_travel old_status;
799             raise exn)
800   | GrafiteAst.NCopy (log,tgt,src_uri, map) ->
801      if status#ng_mode <> `CommandMode then
802       raise (GrafiteTypes.Command_error "Not in command mode")
803      else
804        let tgt_uri_ext, old_ok = 
805          match NCicEnvironment.get_checked_obj src_uri with
806          | _,_,[],[], (NCic.Inductive _ as ok) -> ".ind", ok
807          | _,_,[],[], (NCic.Fixpoint _ as ok) -> ".con", ok
808          | _,_,[],[], (NCic.Constant _ as ok) -> ".con", ok
809          | _ -> assert false
810        in
811        let tgt_uri = NUri.uri_of_string (status#baseuri^"/"^tgt^tgt_uri_ext) in
812        let map = (src_uri, tgt_uri) :: map in
813        let ok = 
814          let rec subst () = function
815            | NCic.Meta _ -> assert false
816            | NCic.Const (NReference.Ref (u,spec)) as t ->
817                (try NCic.Const 
818                  (NReference.reference_of_spec (List.assoc u map)spec)
819                with Not_found -> t)
820            | t -> NCicUtils.map (fun _ _ -> ()) () subst t
821          in
822          NCicUntrusted.map_obj_kind ~skip_body:false (subst ()) old_ok
823        in
824        let ninitial_stack = Continuationals.Stack.of_nmetasenv [] in
825        let status = status#set_obj (tgt_uri,0,[],[],ok) in
826        (*prerr_endline (NCicPp.ppobj (tgt_uri,0,[],[],ok));*)
827        let status = status#set_stack ninitial_stack in
828        let status = subst_metasenv_and_fix_names status in
829        let status = status#set_ng_mode `ProofMode in
830        eval_ncommand opts status ("",0,GrafiteAst.NQed Stdpp.dummy_loc)
831   | GrafiteAst.NObj (loc,obj) ->
832      if status#ng_mode <> `CommandMode then
833       raise (GrafiteTypes.Command_error "Not in command mode")
834      else
835       let status,obj =
836        GrafiteDisambiguate.disambiguate_nobj status
837         ~baseuri:status#baseuri (text,prefix_len,obj) in
838       let uri,height,nmenv,nsubst,nobj = obj in
839       let ninitial_stack = Continuationals.Stack.of_nmetasenv nmenv in
840       let status = status#set_obj obj in
841       let status = status#set_stack ninitial_stack in
842       let status = subst_metasenv_and_fix_names status in
843       let status = status#set_ng_mode `ProofMode in
844       (match nmenv with
845           [] ->
846            eval_ncommand opts status ("",0,GrafiteAst.NQed Stdpp.dummy_loc)
847         | _ -> status,`New [])
848   | GrafiteAst.NUnivConstraint (loc,strict,u1,u2) ->
849       eval_add_constraint status strict [false,u1] [false,u2]
850 ;;
851
852 let rec eval_command = {ec_go = fun ~disambiguate_command opts status
853 (text,prefix_len,cmd) ->
854  let status,cmd = disambiguate_command status (text,prefix_len,cmd) in
855  let status,uris =
856   match cmd with
857   | GrafiteAst.Index (loc,None,uri) -> 
858         assert false (* TODO: for user input *)
859   | GrafiteAst.Index (loc,Some key,uri) -> 
860       let universe = 
861         status#automation_cache.AutomationCache.univ
862       in
863       let universe = Universe.index universe key (CicUtil.term_of_uri uri) in
864       let cache = { 
865         status#automation_cache with AutomationCache.univ = universe } 
866       in
867       let status = status#set_automation_cache cache in
868 (* debug
869       let msg =
870        let candidates = Universe.get_candidates status.GrafiteTypes.universe key in
871        ("candidates for " ^ (CicPp.ppterm key) ^ " = " ^ 
872           (String.concat "\n" (List.map CicPp.ppterm candidates))) 
873      in
874      prerr_endline msg;
875 *)
876       let status = GrafiteTypes.add_moo_content [cmd] status in
877       status,`Old [] 
878   | GrafiteAst.Select (_,uri) as cmd ->
879       if List.mem cmd status#moo_content_rev then status, `Old []
880       else 
881        let cache = 
882          AutomationCache.add_term_to_active status#automation_cache
883            [] [] [] (CicUtil.term_of_uri uri) None
884        in
885        let status = status#set_automation_cache cache in
886        let status = GrafiteTypes.add_moo_content [cmd] status in
887        status, `Old []
888   | GrafiteAst.Pump (_,steps) ->
889       let cache = 
890         AutomationCache.pump status#automation_cache steps
891       in
892       let status = status#set_automation_cache cache in
893       status, `Old []
894   | GrafiteAst.PreferCoercion (loc, coercion) ->
895      eval_prefer_coercion status coercion
896   | GrafiteAst.Coercion (loc, uri, add_composites, arity, saturations) ->
897      let res,uris =
898       eval_coercion status ~add_composites uri arity saturations
899      in
900       res,`Old uris
901   | GrafiteAst.Inverter (loc, name, indty, params) ->
902      let buri = status#baseuri in 
903      let uri = UriManager.uri_of_string (buri ^ "/" ^ name ^ ".con") in
904      let indty_uri = 
905        try CicUtil.uri_of_term indty
906        with Invalid_argument _ ->
907          raise (Invalid_argument "not an inductive type to invert") in
908      let res,uris =
909       Inversion_principle.build_inverter ~add_obj status uri indty_uri params
910      in
911       res,`Old uris
912   | GrafiteAst.Default (loc, what, uris) as cmd ->
913      LibraryObjects.set_default what uris;
914      GrafiteTypes.add_moo_content [cmd] status,`Old []
915   | GrafiteAst.Drop loc -> raise Drop
916   | GrafiteAst.Include (loc, mode, new_or_old, baseuri) ->
917      (* Old Include command is not recursive; new one is *)
918      let status =
919       if new_or_old = `OldAndNew then
920        let moopath_rw, moopath_r = 
921         LibraryMisc.obj_file_of_baseuri 
922           ~must_exist:false ~baseuri ~writable:true,
923         LibraryMisc.obj_file_of_baseuri 
924           ~must_exist:false ~baseuri ~writable:false in
925        let moopath = 
926         if Sys.file_exists moopath_r then moopath_r else
927           if Sys.file_exists moopath_rw then moopath_rw else
928             raise (IncludedFileNotCompiled (moopath_rw,baseuri))
929        in
930         eval_from_moo.efm_go status moopath
931       else
932        status
933      in
934       let status =
935        NRstatus.Serializer.require ~baseuri:(NUri.uri_of_string baseuri)
936         status in
937       let status =
938        GrafiteTypes.add_moo_content
939         [GrafiteAst.Include (loc,mode,`New,baseuri)] status
940       in
941        status,`Old []
942   | GrafiteAst.Print (_,"proofterm") ->
943       let _,_,_,p,_, _ = GrafiteTypes.get_current_proof status in
944       prerr_endline (Auto.pp_proofterm (Lazy.force p));
945       status,`Old []
946   | GrafiteAst.Print (_,_) -> status,`Old []
947   | GrafiteAst.Qed loc ->
948       let uri, metasenv, _subst, bo, ty, attrs =
949         match status#proof_status with
950         | GrafiteTypes.Proof (Some uri, metasenv, subst, body, ty, attrs) ->
951             uri, metasenv, subst, body, ty, attrs
952         | GrafiteTypes.Proof (None, metasenv, subst, body, ty, attrs) -> 
953             raise (GrafiteTypes.Command_error 
954               ("Someone allows to start a theorem without giving the "^
955                "name/uri. This should be fixed!"))
956         | _->
957           raise
958            (GrafiteTypes.Command_error "You can't Qed an incomplete theorem")
959       in
960       if metasenv <> [] then 
961         raise
962          (GrafiteTypes.Command_error
963            "Proof not completed! metasenv is not empty!");
964       let name = UriManager.name_of_uri uri in
965       let obj = Cic.Constant (name,Some (Lazy.force bo),ty,[],attrs) in
966       let status, lemmas = add_obj uri obj status in
967        status#set_proof_status GrafiteTypes.No_proof,
968         (*CSC: I throw away the arities *)
969         `Old (uri::lemmas)
970   | GrafiteAst.Relation (loc, id, a, aeq, refl, sym, trans) -> 
971      Setoids.add_relation id a aeq refl sym trans;
972      status, `Old [] (*CSC: TO BE FIXED *)
973   | GrafiteAst.Set (loc, name, value) -> status, `Old []
974 (*       GrafiteTypes.set_option status name value,[] *)
975   | GrafiteAst.Obj (loc,obj) ->
976      let ext,name =
977       match obj with
978          Cic.Constant (name,_,_,_,_)
979        | Cic.CurrentProof (name,_,_,_,_,_) -> ".con",name
980        | Cic.InductiveDefinition (types,_,_,_) ->
981           ".ind",
982           (match types with (name,_,_,_)::_ -> name | _ -> assert false)
983        | _ -> assert false in
984      let buri = status#baseuri in 
985      let uri = UriManager.uri_of_string (buri ^ "/" ^ name ^ ext) in
986      let obj = CicRefine.pack_coercion_obj obj in
987      let metasenv = GrafiteTypes.get_proof_metasenv status in
988      match obj with
989      | Cic.CurrentProof (_,metasenv',bo,ty,_, attrs) ->
990          let name = UriManager.name_of_uri uri in
991          if not(CicPp.check name ty) then
992            HLog.warn ("Bad name: " ^ name);
993          if opts.do_heavy_checks then
994            begin
995              let dbd = LibraryDb.instance () in
996              let similar = Whelp.match_term ~dbd ty in
997              let similar_len = List.length similar in
998              if similar_len> 30 then
999                (HLog.message
1000                  ("Duplicate check will compare your theorem with " ^ 
1001                    string_of_int similar_len ^ 
1002                    " theorems, this may take a while."));
1003              let convertible =
1004                List.filter (
1005                  fun u ->
1006                    let t = CicUtil.term_of_uri u in
1007                    let ty',g = 
1008                      CicTypeChecker.type_of_aux' 
1009                        metasenv' [] t CicUniv.oblivion_ugraph
1010                    in
1011                    fst(CicReduction.are_convertible [] ty' ty g)) 
1012                similar 
1013              in
1014              (match convertible with
1015              | [] -> ()
1016              | x::_ -> 
1017                  HLog.warn  
1018                  ("Theorem already proved: " ^ UriManager.string_of_uri x ^ 
1019                   "\nPlease use a variant."));
1020            end;
1021          let _subst = [] in
1022          let initial_proof = (Some uri, metasenv', _subst, lazy bo, ty, attrs) in
1023          let initial_stack = Continuationals.Stack.of_metasenv metasenv' in
1024           status#set_proof_status
1025            (GrafiteTypes.Incomplete_proof
1026             { GrafiteTypes.proof = initial_proof; stack = initial_stack }),
1027           `Old []
1028      | _ ->
1029          if metasenv <> [] then
1030           raise (GrafiteTypes.Command_error (
1031             "metasenv not empty while giving a definition with body: " ^
1032             CicMetaSubst.ppmetasenv [] metasenv));
1033          let status, lemmas = add_obj uri obj status in 
1034          let status,new_lemmas = add_coercions_of_lemmas lemmas status in
1035           status#set_proof_status GrafiteTypes.No_proof,
1036            `Old (uri::new_lemmas@lemmas)
1037  in
1038   match status#proof_status with
1039      GrafiteTypes.Intermediate _ ->
1040       status#set_proof_status GrafiteTypes.No_proof,uris
1041    | _ -> status,uris
1042
1043 } and eval_executable = {ee_go = fun ~disambiguate_tactic ~disambiguate_command
1044 ~disambiguate_macro opts status (text,prefix_len,ex) ->
1045   match ex with
1046   | GrafiteAst.Tactic (_(*loc*), Some tac, punct) ->
1047      let tac = apply_tactic ~disambiguate_tactic (text,prefix_len,tac) in
1048      let status = eval_tactical status (tactic_of_ast' tac) in
1049      (* CALL auto on every goal, easy way of testing it  
1050      let auto = 
1051        GrafiteAst.AutoBatch 
1052          (loc, ([],["depth","2";"timeout","1";"type","1"])) in
1053      (try
1054        let auto = apply_tactic ~disambiguate_tactic ("",0,auto) in
1055        let _ = eval_tactical status (tactic_of_ast' auto) in 
1056        print_endline "GOOD"; () 
1057      with ProofEngineTypes.Fail _ -> print_endline "BAD" | _ -> ());*)
1058       eval_tactical status
1059        (punctuation_tactical_of_ast (text,prefix_len,punct)),`Old []
1060   | GrafiteAst.Tactic (_, None, punct) ->
1061       eval_tactical status
1062        (punctuation_tactical_of_ast (text,prefix_len,punct)),`Old []
1063   | GrafiteAst.NTactic (_(*loc*), tacl) ->
1064       if status#ng_mode <> `ProofMode then
1065        raise (GrafiteTypes.Command_error "Not in proof mode")
1066       else
1067        let status =
1068         List.fold_left 
1069           (fun status tac ->
1070             let status = eval_ng_tac (text,prefix_len,tac) status in
1071             subst_metasenv_and_fix_names status)
1072           status tacl
1073        in
1074         status,`New []
1075   | GrafiteAst.NonPunctuationTactical (_, tac, punct) ->
1076      let status = 
1077       eval_tactical status
1078        (non_punctuation_tactical_of_ast (text,prefix_len,tac))
1079      in
1080       eval_tactical status
1081        (punctuation_tactical_of_ast (text,prefix_len,punct)),`Old []
1082   | GrafiteAst.Command (_, cmd) ->
1083       eval_command.ec_go ~disambiguate_command opts status (text,prefix_len,cmd)
1084   | GrafiteAst.NCommand (_, cmd) ->
1085       eval_ncommand opts status (text,prefix_len,cmd)
1086   | GrafiteAst.Macro (loc, macro) ->
1087      raise (Macro (loc,disambiguate_macro status (text,prefix_len,macro)))
1088   | GrafiteAst.NMacro (loc, macro) ->
1089      raise (NMacro (loc,macro))
1090
1091 } and eval_from_moo = {efm_go = fun status fname ->
1092   let ast_of_cmd cmd =
1093     ("",0,GrafiteAst.Executable (HExtlib.dummy_floc,
1094       GrafiteAst.Command (HExtlib.dummy_floc,
1095         cmd)))
1096   in
1097   let moo = GrafiteMarshal.load_moo fname in
1098   List.fold_left 
1099     (fun status ast -> 
1100       let ast = ast_of_cmd ast in
1101       let status,lemmas =
1102        eval_ast.ea_go
1103          ~disambiguate_tactic:(fun status _ (_,_,tactic) -> status,tactic)
1104          ~disambiguate_command:(fun status (_,_,cmd) -> status,cmd)
1105          ~disambiguate_macro:(fun _ _ -> assert false)
1106          status ast
1107       in
1108        assert (lemmas=`Old []);
1109        status)
1110     status moo
1111 } and eval_ast = {ea_go = fun ~disambiguate_tactic ~disambiguate_command
1112 ~disambiguate_macro ?(do_heavy_checks=false) status
1113 (text,prefix_len,st)
1114 ->
1115   let opts = { do_heavy_checks = do_heavy_checks ; } in
1116   match st with
1117   | GrafiteAst.Executable (_,ex) ->
1118      eval_executable.ee_go ~disambiguate_tactic ~disambiguate_command
1119       ~disambiguate_macro opts status (text,prefix_len,ex)
1120   | GrafiteAst.Comment (_,c) -> 
1121       eval_comment.ecm_go ~disambiguate_command opts status (text,prefix_len,c) 
1122 } and eval_comment = { ecm_go = fun ~disambiguate_command opts status (text,prefix_len,c) -> 
1123     status, `Old []
1124 }
1125 ;;
1126
1127
1128 let eval_ast = eval_ast.ea_go