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