]> matita.cs.unibo.it Git - helm.git/blob - helm/matita/matitaEngine.ml
CicUtil.profile ==> HExtlib.profile
[helm.git] / helm / matita / matitaEngine.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 open Printf
27
28 open MatitaTypes
29
30 exception Drop;;
31 exception UnableToInclude of string
32 exception IncludedFileNotCompiled of string
33
34 let debug = false ;;
35 let debug_print = if debug then prerr_endline else ignore ;;
36
37 type options = { 
38   do_heavy_checks: bool ; 
39   include_paths: string list ;
40   clean_baseuri: bool
41 }
42
43 type statement =
44   (CicNotationPt.term, CicNotationPt.term, GrafiteAst.reduction, GrafiteAst.obj,
45    string)
46   GrafiteAst.statement
47
48 (** create a ProofEngineTypes.mk_fresh_name_type function which uses given
49   * names as long as they are available, then it fallbacks to name generation
50   * using FreshNamesGenerator module *)
51 let namer_of names =
52   let len = List.length names in
53   let count = ref 0 in
54   fun metasenv context name ~typ ->
55     if !count < len then begin
56       let name = Cic.Name (List.nth names !count) in
57       incr count;
58       name
59     end else
60       FreshNamesGenerator.mk_fresh_name ~subst:[] metasenv context name ~typ
61
62 let tactic_of_ast ast =
63   let module PET = ProofEngineTypes in
64   match ast with
65   | GrafiteAst.Absurd (_, term) -> Tactics.absurd term
66   | GrafiteAst.Apply (_, term) -> Tactics.apply term
67   | GrafiteAst.Assumption _ -> Tactics.assumption
68   | GrafiteAst.Auto (_,depth,width,paramodulation) ->
69       AutoTactic.auto_tac ?depth ?width ?paramodulation
70         ~dbd:(MatitaDb.instance ()) ()
71   | GrafiteAst.Change (_, pattern, with_what) ->
72      Tactics.change ~pattern with_what
73   | GrafiteAst.Clear (_,id) -> Tactics.clear id
74   | GrafiteAst.ClearBody (_,id) -> Tactics.clearbody id
75   | GrafiteAst.Contradiction _ -> Tactics.contradiction
76   | GrafiteAst.Compare (_, term) -> Tactics.compare term
77   | GrafiteAst.Constructor (_, n) -> Tactics.constructor n
78   | GrafiteAst.Cut (_, ident, term) ->
79      let names = match ident with None -> [] | Some id -> [id] in
80      Tactics.cut ~mk_fresh_name_callback:(namer_of names) term
81   | GrafiteAst.DecideEquality _ -> Tactics.decide_equality
82   | GrafiteAst.Decompose (_, types, what, names) -> 
83       let to_type = function
84          | GrafiteAst.Type (uri, typeno) -> uri, typeno
85          | GrafiteAst.Ident _            -> assert false
86       in
87       let user_types = List.rev_map to_type types in
88       let dbd = MatitaDb.instance () in
89       let mk_fresh_name_callback = namer_of names in
90       Tactics.decompose ~mk_fresh_name_callback ~dbd ~user_types what
91   | GrafiteAst.Discriminate (_,term) -> Tactics.discriminate term
92   | GrafiteAst.Elim (_, what, using, depth, names) ->
93       Tactics.elim_intros ?using ?depth ~mk_fresh_name_callback:(namer_of names)
94         what
95   | GrafiteAst.ElimType (_, what, using, depth, names) ->
96       Tactics.elim_type ?using ?depth ~mk_fresh_name_callback:(namer_of names)
97         what
98   | GrafiteAst.Exact (_, term) -> Tactics.exact term
99   | GrafiteAst.Exists _ -> Tactics.exists
100   | GrafiteAst.Fail _ -> Tactics.fail
101   | GrafiteAst.Fold (_, reduction_kind, term, pattern) ->
102       let reduction =
103         match reduction_kind with
104         | `Normalize ->
105             PET.const_lazy_reduction
106               (CicReduction.normalize ~delta:false ~subst:[])
107         | `Reduce -> PET.const_lazy_reduction ProofEngineReduction.reduce
108         | `Simpl -> PET.const_lazy_reduction ProofEngineReduction.simpl
109         | `Unfold None ->
110             PET.const_lazy_reduction (ProofEngineReduction.unfold ?what:None)
111         | `Unfold (Some lazy_term) ->
112            (fun context metasenv ugraph ->
113              let what, metasenv, ugraph = lazy_term context metasenv ugraph in
114              ProofEngineReduction.unfold ~what, metasenv, ugraph)
115         | `Whd ->
116             PET.const_lazy_reduction (CicReduction.whd ~delta:false ~subst:[])
117       in
118       Tactics.fold ~reduction ~term ~pattern
119   | GrafiteAst.Fourier _ -> Tactics.fourier
120   | GrafiteAst.FwdSimpl (_, hyp, names) -> 
121      Tactics.fwd_simpl ~mk_fresh_name_callback:(namer_of names)
122       ~dbd:(MatitaDb.instance ()) hyp
123   | GrafiteAst.Generalize (_,pattern,ident) ->
124      let names = match ident with None -> [] | Some id -> [id] in
125      Tactics.generalize ~mk_fresh_name_callback:(namer_of names) pattern 
126   | GrafiteAst.Goal (_, n) -> Tactics.set_goal n
127   | GrafiteAst.IdTac _ -> Tactics.id
128   | GrafiteAst.Injection (_,term) -> Tactics.injection term
129   | GrafiteAst.Intros (_, None, names) ->
130       PrimitiveTactics.intros_tac ~mk_fresh_name_callback:(namer_of names) ()
131   | GrafiteAst.Intros (_, Some num, names) ->
132       PrimitiveTactics.intros_tac ~howmany:num
133         ~mk_fresh_name_callback:(namer_of names) ()
134   | GrafiteAst.LApply (_, how_many, to_what, what, ident) ->
135       let names = match ident with None -> [] | Some id -> [id] in
136       Tactics.lapply ~mk_fresh_name_callback:(namer_of names) ?how_many
137         ~to_what what
138   | GrafiteAst.Left _ -> Tactics.left
139   | GrafiteAst.LetIn (loc,term,name) ->
140       Tactics.letin term ~mk_fresh_name_callback:(namer_of [name])
141   | GrafiteAst.Reduce (_, reduction_kind, pattern) ->
142       (match reduction_kind with
143       | `Normalize -> Tactics.normalize ~pattern
144       | `Reduce -> Tactics.reduce ~pattern  
145       | `Simpl -> Tactics.simpl ~pattern 
146       | `Unfold what -> Tactics.unfold ~pattern what
147       | `Whd -> Tactics.whd ~pattern)
148   | GrafiteAst.Reflexivity _ -> Tactics.reflexivity
149   | GrafiteAst.Replace (_, pattern, with_what) ->
150      Tactics.replace ~pattern ~with_what
151   | GrafiteAst.Rewrite (_, direction, t, pattern) ->
152      EqualityTactics.rewrite_tac ~direction ~pattern t
153   | GrafiteAst.Right _ -> Tactics.right
154   | GrafiteAst.Ring _ -> Tactics.ring
155   | GrafiteAst.Split _ -> Tactics.split
156   | GrafiteAst.Symmetry _ -> Tactics.symmetry
157   | GrafiteAst.Transitivity (_, term) -> Tactics.transitivity term
158
159 let singleton = function
160   | [x], _ -> x
161   | _ -> assert false
162
163 let disambiguate_term status_ref term =
164   let status = !status_ref in
165   let (diff, metasenv, cic, _) =
166     singleton
167       (MatitaDisambiguator.disambiguate_term ~dbd:(MatitaDb.instance ())
168         ~aliases:status.aliases ~universe:(Some status.multi_aliases)
169         ~context:(MatitaMisc.get_proof_context status)
170         ~metasenv:(MatitaMisc.get_proof_metasenv status) term)
171   in
172   let status = MatitaTypes.set_metasenv metasenv status in
173   let status = MatitaSync.set_proof_aliases status diff in
174   status_ref := status;
175   cic
176   
177   (** disambiguate_lazy_term (circa): term -> (unit -> status) * lazy_term
178    * rationale: lazy_term will be invoked in different context to obtain a term,
179    * each invocation will disambiguate the term and can add aliases. Once all
180    * disambiguations have been performed, the first returned function can be
181    * used to obtain the resulting aliases *)
182 let disambiguate_lazy_term status_ref term =
183   (fun context metasenv ugraph ->
184     let status = !status_ref in
185     let (diff, metasenv, cic, ugraph) =
186       singleton
187         (MatitaDisambiguator.disambiguate_term ~dbd:(MatitaDb.instance ())
188           ~initial_ugraph:ugraph ~aliases:status.aliases
189           ~universe:(Some status.multi_aliases) ~context ~metasenv term)
190     in
191     let status = MatitaTypes.set_metasenv metasenv status in
192     let status = MatitaSync.set_proof_aliases status diff in
193     status_ref := status;
194     cic, metasenv, ugraph)
195
196 let disambiguate_pattern status_ref (wanted, hyp_paths, goal_path) =
197   let interp path = Disambiguate.interpretate_path [] path in
198   let goal_path = interp goal_path in
199   let hyp_paths = List.map (fun (name, path) -> name, interp path) hyp_paths in
200   let wanted =
201    match wanted with
202       None -> None
203     | Some wanted ->
204        let wanted = disambiguate_lazy_term status_ref wanted in
205        Some wanted
206   in
207   (wanted, hyp_paths ,goal_path)
208
209 let disambiguate_reduction_kind aliases_ref = function
210   | `Unfold (Some t) ->
211       let t = disambiguate_lazy_term aliases_ref t in
212       `Unfold (Some t)
213   | `Normalize
214   | `Reduce
215   | `Simpl
216   | `Unfold None
217   | `Whd as kind -> kind
218   
219 let disambiguate_tactic status tactic =
220   let status_ref = ref status in
221   let tactic =
222     match tactic with
223     | GrafiteAst.Absurd (loc, term) -> 
224         let cic = disambiguate_term status_ref term in
225         GrafiteAst.Absurd (loc, cic)
226     | GrafiteAst.Apply (loc, term) ->
227         let cic = disambiguate_term status_ref term in
228         GrafiteAst.Apply (loc, cic)
229     | GrafiteAst.Assumption loc -> GrafiteAst.Assumption loc
230     | GrafiteAst.Auto (loc,depth,width,paramodulation) ->
231         GrafiteAst.Auto (loc,depth,width,paramodulation)
232     | GrafiteAst.Change (loc, pattern, with_what) -> 
233         let with_what = disambiguate_lazy_term status_ref with_what in
234         let pattern = disambiguate_pattern status_ref pattern in
235         GrafiteAst.Change (loc, pattern, with_what)
236     | GrafiteAst.Clear (loc,id) -> GrafiteAst.Clear (loc,id)
237     | GrafiteAst.ClearBody (loc,id) -> GrafiteAst.ClearBody (loc,id)
238     | GrafiteAst.Compare (loc,term) ->
239         let term = disambiguate_term status_ref term in
240         GrafiteAst.Compare (loc,term)
241     | GrafiteAst.Constructor (loc,n) -> GrafiteAst.Constructor (loc,n)
242     | GrafiteAst.Contradiction loc -> GrafiteAst.Contradiction loc
243     | GrafiteAst.Cut (loc, ident, term) -> 
244         let cic = disambiguate_term status_ref term in
245         GrafiteAst.Cut (loc, ident, cic)
246     | GrafiteAst.DecideEquality loc -> GrafiteAst.DecideEquality loc
247     | GrafiteAst.Decompose (loc, types, what, names) ->
248         let disambiguate types = function
249            | GrafiteAst.Type _   -> assert false
250            | GrafiteAst.Ident id ->
251               (match disambiguate_term status_ref (CicNotationPt.Ident (id, None)) with
252               | Cic.MutInd (uri, tyno, _) ->
253                   (GrafiteAst.Type (uri, tyno) :: types)
254               | _ -> raise Disambiguate.NoWellTypedInterpretation)
255         in
256         let types = List.fold_left disambiguate [] types in
257         GrafiteAst.Decompose (loc, types, what, names)
258     | GrafiteAst.Discriminate (loc,term) ->
259         let term = disambiguate_term status_ref term in
260         GrafiteAst.Discriminate(loc,term)
261     | GrafiteAst.Exact (loc, term) -> 
262         let cic = disambiguate_term status_ref term in
263         GrafiteAst.Exact (loc, cic)
264     | GrafiteAst.Elim (loc, what, Some using, depth, idents) ->
265         let what = disambiguate_term status_ref what in
266         let using = disambiguate_term status_ref using in
267         GrafiteAst.Elim (loc, what, Some using, depth, idents)
268     | GrafiteAst.Elim (loc, what, None, depth, idents) ->
269         let what = disambiguate_term status_ref what in
270         GrafiteAst.Elim (loc, what, None, depth, idents)
271     | GrafiteAst.ElimType (loc, what, Some using, depth, idents) ->
272         let what = disambiguate_term status_ref what in
273         let using = disambiguate_term status_ref using in
274         GrafiteAst.ElimType (loc, what, Some using, depth, idents)
275     | GrafiteAst.ElimType (loc, what, None, depth, idents) ->
276         let what = disambiguate_term status_ref what in
277         GrafiteAst.ElimType (loc, what, None, depth, idents)
278     | GrafiteAst.Exists loc -> GrafiteAst.Exists loc 
279     | GrafiteAst.Fail loc -> GrafiteAst.Fail loc
280     | GrafiteAst.Fold (loc,red_kind, term, pattern) ->
281         let pattern = disambiguate_pattern status_ref pattern in
282         let term = disambiguate_lazy_term status_ref term in
283         let red_kind = disambiguate_reduction_kind status_ref red_kind in
284         GrafiteAst.Fold (loc, red_kind, term, pattern)
285     | GrafiteAst.FwdSimpl (loc, hyp, names) ->
286        GrafiteAst.FwdSimpl (loc, hyp, names)  
287     | GrafiteAst.Fourier loc -> GrafiteAst.Fourier loc
288     | GrafiteAst.Generalize (loc,pattern,ident) ->
289         let pattern = disambiguate_pattern status_ref pattern in
290         GrafiteAst.Generalize (loc,pattern,ident)
291     | GrafiteAst.Goal (loc, g) -> GrafiteAst.Goal (loc, g)
292     | GrafiteAst.IdTac loc -> GrafiteAst.IdTac loc
293     | GrafiteAst.Injection (loc, term) ->
294         let term = disambiguate_term status_ref term in
295         GrafiteAst.Injection (loc,term)
296     | GrafiteAst.Intros (loc, num, names) -> GrafiteAst.Intros (loc, num, names)
297     | GrafiteAst.LApply (loc, depth, to_what, what, ident) ->
298        let f term to_what =
299           let term = disambiguate_term status_ref term in
300           term :: to_what
301        in
302        let to_what = List.fold_right f to_what [] in 
303        let what = disambiguate_term status_ref what in
304        GrafiteAst.LApply (loc, depth, to_what, what, ident)
305     | GrafiteAst.Left loc -> GrafiteAst.Left loc
306     | GrafiteAst.LetIn (loc, term, name) ->
307         let term = disambiguate_term status_ref term in
308         GrafiteAst.LetIn (loc,term,name)
309     | GrafiteAst.Reduce (loc, red_kind, pattern) ->
310         let pattern = disambiguate_pattern status_ref pattern in
311         let red_kind = disambiguate_reduction_kind status_ref red_kind in
312         GrafiteAst.Reduce(loc, red_kind, pattern)
313     | GrafiteAst.Reflexivity loc -> GrafiteAst.Reflexivity loc
314     | GrafiteAst.Replace (loc, pattern, with_what) -> 
315         let pattern = disambiguate_pattern status_ref pattern in
316         let with_what = disambiguate_lazy_term status_ref with_what in
317         GrafiteAst.Replace (loc, pattern, with_what)
318     | GrafiteAst.Rewrite (loc, dir, t, pattern) ->
319         let term = disambiguate_term status_ref t in
320         let pattern = disambiguate_pattern status_ref pattern in
321         GrafiteAst.Rewrite (loc, dir, term, pattern)
322     | GrafiteAst.Right loc -> GrafiteAst.Right loc
323     | GrafiteAst.Ring loc -> GrafiteAst.Ring loc
324     | GrafiteAst.Split loc -> GrafiteAst.Split loc
325     | GrafiteAst.Symmetry loc -> GrafiteAst.Symmetry loc
326     | GrafiteAst.Transitivity (loc, term) -> 
327         let cic = disambiguate_term status_ref term in
328         GrafiteAst.Transitivity (loc, cic)
329   in
330   status_ref, tactic
331
332 let reorder_metasenv start refine tactic goals current_goal always_opens_a_goal=
333   let module PEH = ProofEngineHelpers in
334   (* phase one calculates:
335    *   new_goals_from_refine:  goals added by refine
336    *   head_goal:              the first goal opened by ythe tactic 
337    *   other_goals:            other goals opened by the tactic
338    *)
339   let new_goals_from_refine = PEH.compare_metasenvs start refine in
340   let new_goals_from_tactic = PEH.compare_metasenvs refine tactic in
341   let head_goal, other_goals, goals = 
342     match goals with
343     | [] -> None,[],goals
344     | hd::tl -> 
345         (* assert (List.mem hd new_goals_from_tactic);
346          * invalidato dalla goal_tac
347          * *)
348         Some hd, List.filter ((<>) hd) new_goals_from_tactic, List.filter ((<>)
349         hd) goals
350   in
351   let produced_goals = 
352     match head_goal with
353     | None -> new_goals_from_refine @ other_goals
354     | Some x -> x :: new_goals_from_refine @ other_goals
355   in
356   (* extract the metas generated by refine and tactic *)
357   let metas_for_tactic_head = 
358     match head_goal with
359     | None -> []
360     | Some head_goal -> List.filter (fun (n,_,_) -> n = head_goal) tactic in
361   let metas_for_tactic_goals = 
362     List.map 
363       (fun x -> List.find (fun (metano,_,_) -> metano = x) tactic)
364     goals 
365   in
366   let metas_for_refine_goals = 
367     List.filter (fun (n,_,_) -> List.mem n new_goals_from_refine) tactic in
368   let produced_metas, goals = 
369     let produced_metas =
370       if always_opens_a_goal then
371         metas_for_tactic_head @ metas_for_refine_goals @ 
372           metas_for_tactic_goals
373       else  
374         metas_for_refine_goals @ metas_for_tactic_head @ 
375           metas_for_tactic_goals
376     in
377     let goals = List.map (fun (metano, _, _) -> metano)  produced_metas in
378     produced_metas, goals
379   in
380   (* residual metas, preserving the original order *)
381   let before, after = 
382     let rec split e =
383       function 
384       | [] -> [],[]
385       | (metano, _, _) :: tl when metano = e -> 
386           [], List.map (fun (x,_,_) -> x) tl
387       | (metano, _, _) :: tl -> let b, a = split e tl in metano :: b, a
388     in
389     let find n metasenv =
390       try
391         Some (List.find (fun (metano, _, _) -> metano = n) metasenv)
392       with Not_found -> None
393     in
394     let extract l =
395       List.fold_right 
396         (fun n acc -> 
397           match find n tactic with
398           | Some x -> x::acc
399           | None -> acc
400         ) l [] in
401     let before_l, after_l = split current_goal start in
402     let before_l = 
403       List.filter (fun x -> not (List.mem x produced_goals)) before_l in
404     let after_l = 
405       List.filter (fun x -> not (List.mem x produced_goals)) after_l in
406     let before = extract before_l in
407     let after = extract after_l in
408       before, after
409   in
410   (* DEBUG CODE 
411   let print_m name metasenv =
412     prerr_endline (">>>>> " ^ name);
413     prerr_endline (CicMetaSubst.ppmetasenv metasenv [])
414   in
415   print_m "BEGIN" start;
416   prerr_endline ("goal was: " ^ string_of_int current_goal);
417   prerr_endline ("and metas from refine are:");
418   List.iter 
419     (fun t -> prerr_string (" " ^ string_of_int t)) 
420   new_goals_from_refine;
421   prerr_endline "";
422   print_m "before" before;
423   print_m "metas_for_tactic_head" metas_for_tactic_head;
424   print_m "metas_for_refine_goals" metas_for_refine_goals;
425   print_m "metas_for_tactic_goals" metas_for_tactic_goals;
426   print_m "after" after; 
427    FINE DEBUG CODE *)
428   before @ produced_metas @ after, goals 
429   
430 (* maybe we only need special cases for apply and goal *)
431 let classify_tactic tactic = 
432   match tactic with
433   (* tactics that can't close the goal (return a goal we want to "select") *)
434   | GrafiteAst.Rewrite _ 
435   | GrafiteAst.Split _ 
436   | GrafiteAst.Replace _ 
437   | GrafiteAst.Reduce _
438   | GrafiteAst.Injection _ 
439   | GrafiteAst.IdTac _ 
440   | GrafiteAst.Generalize _ 
441   | GrafiteAst.Elim _ 
442   | GrafiteAst.Decompose _ -> true, true
443   (* tactics we don't want to reorder goals. I think only Goal needs this. *)
444   | GrafiteAst.Goal _ -> false, true
445   (* tactics like apply *)
446   | _ -> true, false
447   
448 let apply_tactic tactic status =
449  let starting_metasenv = MatitaMisc.get_proof_metasenv status in
450  let status_ref, tactic = disambiguate_tactic status tactic in
451  let metasenv_after_refinement =  MatitaMisc.get_proof_metasenv !status_ref in
452  let proof_status = MatitaMisc.get_proof_status !status_ref in
453  let needs_reordering, always_opens_a_goal = classify_tactic tactic in
454  let tactic = tactic_of_ast tactic in
455  (* apply tactic will change the status pointed by status_ref ... *)
456  let current_goal = let _, g = proof_status in g in
457  let (proof, goals) = ProofEngineTypes.apply_tactic tactic proof_status in
458  let proof, goals = 
459    if needs_reordering then
460      let uri, metasenv_after_tactic, t, ty = proof in
461      let reordered_metasenv, goals = 
462        reorder_metasenv starting_metasenv metasenv_after_refinement 
463        metasenv_after_tactic goals current_goal always_opens_a_goal in
464      (uri, reordered_metasenv, t, ty), goals
465    else
466      proof, goals
467  in
468  let dummy = -1 in
469  { !status_ref with
470     proof_status = MatitaTypes.Incomplete_proof (proof,dummy) },
471  goals
472
473 module MatitaStatus =
474  struct
475   type input_status = MatitaTypes.status
476   type output_status = MatitaTypes.status * ProofEngineTypes.goal list
477   type tactic = input_status -> output_status
478
479   let focus (status,_) goal =
480    let proof,_ = MatitaMisc.get_proof_status status in
481     {status with proof_status = MatitaTypes.Incomplete_proof (proof,goal)}
482
483   let goals (_,goals) = goals
484
485   let set_goals (status,_) goals = status,goals
486
487   let id_tac status =
488     apply_tactic (GrafiteAst.IdTac DisambiguateTypes.dummy_floc) status
489
490   let mk_tactic tac = tac
491
492   let apply_tactic tac = tac
493
494  end
495
496 module MatitaTacticals = Tacticals.Make(MatitaStatus)
497
498 let eval_tactical status tac =
499  let rec tactical_of_ast tac =
500   match tac with
501     | GrafiteAst.Tactic (loc, tactic) -> apply_tactic tactic
502     | GrafiteAst.Seq (loc, tacticals) ->  (* tac1; tac2; ... *)
503        MatitaTacticals.seq ~tactics:(List.map tactical_of_ast tacticals)
504     | GrafiteAst.Do (loc, num, tactical) ->
505         MatitaTacticals.do_tactic ~n:num ~tactic:(tactical_of_ast tactical)
506     | GrafiteAst.Repeat (loc, tactical) ->
507         MatitaTacticals.repeat_tactic ~tactic:(tactical_of_ast tactical)
508     | GrafiteAst.Then (loc, tactical, tacticals) ->  (* tac; [ tac1 | ... ] *)
509         MatitaTacticals.thens ~start:(tactical_of_ast tactical)
510           ~continuations:(List.map tactical_of_ast tacticals)
511     | GrafiteAst.First (loc, tacticals) ->
512         MatitaTacticals.first
513           ~tactics:(List.map (fun t -> "", tactical_of_ast t) tacticals)
514     | GrafiteAst.Try (loc, tactical) ->
515         MatitaTacticals.try_tactic ~tactic:(tactical_of_ast tactical)
516     | GrafiteAst.Solve (loc, tacticals) ->
517         MatitaTacticals.solve_tactics
518          ~tactics:(List.map (fun t -> "",tactical_of_ast t) tacticals)
519  in
520   let status,goals = tactical_of_ast tac status in
521   let proof,_ = MatitaMisc.get_proof_status status in
522   let new_status =
523    match goals with
524    | [] -> 
525        let (_,metasenv,_,_) = proof in
526        (match metasenv with
527        | [] -> Proof proof
528        | (ng,_,_)::_ -> Incomplete_proof (proof,ng))
529    | ng::_ -> Incomplete_proof (proof, ng)
530   in
531    { status with proof_status = new_status }
532
533 let eval_coercion status coercion = 
534   let coer_uri,coer_ty =
535     match coercion with 
536     | Cic.Const (uri,_)
537     | Cic.Var (uri,_) ->
538         let o,_ = CicEnvironment.get_obj CicUniv.empty_ugraph uri in
539         (match o with
540         | Cic.Constant (_,_,ty,_,_)
541         | Cic.Variable (_,_,ty,_,_) ->
542             uri,ty
543         | _ -> assert false)
544     | Cic.MutConstruct (uri,t,c,_) ->
545         let o,_ = CicEnvironment.get_obj CicUniv.empty_ugraph uri in
546         (match o with
547         | Cic.InductiveDefinition (l,_,_,_) ->
548             let (_,_,_,cl) = List.nth l t in
549             let (_,cty) = List.nth cl c in
550               uri,cty
551         | _ -> assert false)
552     | _ -> assert false 
553   in
554   (* we have to get the source and the tgt type uri 
555    * in Coq syntax we have already their names, but 
556    * since we don't support Funclass and similar I think
557    * all the coercion should be of the form
558    * (A:?)(B:?)T1->T2
559    * So we should be able to extract them from the coercion type
560    *)
561   let extract_last_two_p ty =
562     let rec aux = function
563       | Cic.Prod( _, src, Cic.Prod (n,t1,t2)) -> aux (Cic.Prod(n,t1,t2))   
564       | Cic.Prod( _, src, tgt) -> src, tgt
565       | _ -> assert false
566     in  
567     aux ty
568   in
569   let ty_src,ty_tgt = extract_last_two_p coer_ty in
570   let context = [] in 
571   let src_uri = 
572     let ty_src = CicReduction.whd context ty_src in
573      CicUtil.uri_of_term ty_src
574   in
575   let tgt_uri = 
576     let ty_tgt = CicReduction.whd context ty_tgt in
577      CicUtil.uri_of_term ty_tgt
578   in
579   let new_coercions =
580     (* also adds them to the Db *)
581     CoercGraph.close_coercion_graph src_uri tgt_uri coer_uri in
582   let status =
583    List.fold_left (fun s (uri,o,_) -> MatitaSync.add_obj uri o status)
584     status new_coercions in
585   let statement_of name =
586     GrafiteAst.Coercion (DisambiguateTypes.dummy_floc, 
587       (CicNotationPt.Ident (name, None)))
588   in
589   let moo_content = 
590     statement_of (UriManager.name_of_uri coer_uri) ::
591     (List.map 
592       (fun (uri, _, _) -> 
593         statement_of (UriManager.name_of_uri uri))
594     new_coercions)
595   in
596   let status = add_moo_content moo_content status in
597   { status with proof_status = No_proof }
598
599 let generate_elimination_principles uri status =
600   let status' = ref status in
601   let elim sort =
602     try
603       let uri,obj = CicElim.elim_of ~sort uri 0 in
604       status' := MatitaSync.add_obj uri obj !status'
605     with CicElim.Can_t_eliminate -> ()
606   in
607   try
608     List.iter elim [ Cic.Prop; Cic.Set; (Cic.Type (CicUniv.fresh ())) ];
609     !status'
610   with exn ->
611     MatitaSync.time_travel ~present:!status' ~past:status;
612     raise exn
613
614 let generate_projections uri fields status =
615  let projections = CicRecord.projections_of uri fields in
616   List.fold_left
617    (fun status (uri, name, bo) -> 
618      try 
619       let ty, ugraph = 
620         CicTypeChecker.type_of_aux' [] [] bo CicUniv.empty_ugraph in
621       let attrs = [`Class `Projection; `Generated] in
622       let obj = Cic.Constant (name,Some bo,ty,[],attrs) in
623        MatitaSync.add_obj uri obj status
624      with
625         CicTypeChecker.TypeCheckerFailure s ->
626          MatitaLog.message 
627           ("Unable to create projection " ^ name ^ " cause: " ^ s);
628          status
629       | CicEnvironment.Object_not_found uri ->
630          let depend = UriManager.name_of_uri uri in
631           MatitaLog.message 
632            ("Unable to create projection " ^ name ^ " because it requires " ^ depend);
633          status
634   ) status projections
635
636 (* to avoid a long list of recursive functions *)
637 let eval_from_stream_ref = ref (fun _ _ _ -> assert false);;
638  
639 let disambiguate_obj status obj =
640   let uri =
641    match obj with
642       GrafiteAst.Inductive (_,(name,_,_,_)::_)
643     | GrafiteAst.Record (_,name,_,_) ->
644        Some (UriManager.uri_of_string (MatitaMisc.qualify status name ^ ".ind"))
645     | GrafiteAst.Inductive _ -> assert false
646     | GrafiteAst.Theorem _ -> None in
647   let (diff, metasenv, cic, _) =
648     singleton
649       (MatitaDisambiguator.disambiguate_obj ~dbd:(MatitaDb.instance ())
650         ~aliases:status.aliases ~universe:(Some status.multi_aliases) ~uri obj)
651   in
652   let proof_status =
653     match status.proof_status with
654     | No_proof -> Intermediate metasenv
655     | Incomplete_proof _
656     | Proof _ -> command_error "imbricated proofs not allowed"
657     | Intermediate _ -> assert false
658   in
659   let status = { status with proof_status = proof_status } in
660   let status = MatitaSync.set_proof_aliases status diff in
661   status, cic
662   
663 let disambiguate_command status = function
664   | GrafiteAst.Alias _
665   | GrafiteAst.Default _
666   | GrafiteAst.Drop _
667   | GrafiteAst.Dump _
668   | GrafiteAst.Include _
669   | GrafiteAst.Interpretation _
670   | GrafiteAst.Notation _
671   | GrafiteAst.Qed _
672   | GrafiteAst.Render _
673   | GrafiteAst.Set _ as cmd ->
674       status,cmd
675   | GrafiteAst.Coercion (loc, term) ->
676       let status_ref = ref status in
677       let term = disambiguate_term status_ref term in
678       !status_ref, GrafiteAst.Coercion (loc,term)
679   | GrafiteAst.Obj (loc,obj) ->
680       let status,obj = disambiguate_obj status obj in
681       status, GrafiteAst.Obj (loc,obj)
682
683 let make_absolute paths path =
684   if path = "coq.ma" then path
685   else
686    let rec aux = function
687    | [] -> ignore (Unix.stat path); path
688    | p :: tl ->
689       let path = p ^ "/" ^ path in
690        try
691          ignore (Unix.stat path); path
692        with Unix.Unix_error _ -> aux tl
693    in
694    try
695      aux paths
696    with Unix.Unix_error _ as exc -> raise (UnableToInclude path)
697 ;;
698        
699 let profiler_include = HExtlib.profile "include"
700
701 let eval_command opts status cmd =
702   let status,cmd = disambiguate_command status cmd in
703   let cmd,notation_ids' = CicNotation.process_notation cmd in
704   let status =
705     { status with notation_ids = notation_ids' @ status.notation_ids }
706   in
707   match cmd with
708   | GrafiteAst.Default (loc, what, uris) as cmd ->
709      LibraryObjects.set_default what uris;
710      add_moo_content [cmd] status
711   | GrafiteAst.Include (loc, path) ->
712      let absolute_path = make_absolute opts.include_paths path in
713      let moopath = MatitaMisc.obj_file_of_script absolute_path in
714      let ic =
715       try open_in moopath with Sys_error _ -> 
716         raise (IncludedFileNotCompiled moopath) in
717      let stream = Ulexing.from_utf8_channel ic in
718      let status = ref status in
719       profiler_include.HExtlib.profile
720        (!eval_from_stream_ref status stream) (fun _ _ -> ());
721       close_in ic;
722       !status
723   | GrafiteAst.Set (loc, name, value) -> 
724       let value = 
725         if name = "baseuri" then
726           let v = MatitaMisc.strip_trailing_slash value in
727           try
728             ignore (String.index v ' ');
729             command_error "baseuri can't contain spaces"
730           with Not_found -> v
731         else
732           value
733       in
734       if not (MatitaMisc.is_empty value) then
735         begin
736           MatitaLog.warn ("baseuri " ^ value ^ " is not empty");
737           if opts.clean_baseuri then
738             begin 
739               MatitaLog.message ("cleaning baseuri " ^ value);
740               MatitacleanLib.clean_baseuris [value]
741             end
742         end;
743       set_option status name value
744   | GrafiteAst.Drop loc -> raise Drop
745   | GrafiteAst.Qed loc ->
746       let uri, metasenv, bo, ty =
747         match status.proof_status with
748         | Proof (Some uri, metasenv, body, ty) ->
749             uri, metasenv, body, ty
750         | Proof (None, metasenv, body, ty) -> 
751             command_error 
752               ("Someone allows to start a thm without giving the "^
753                "name/uri. This should be fixed!")
754         | _-> command_error "You can't qed an uncomplete theorem"
755       in
756       let suri = UriManager.string_of_uri uri in
757       if metasenv <> [] then 
758         command_error "Proof not completed! metasenv is not empty!";
759       let name = UriManager.name_of_uri uri in
760       let obj = Cic.Constant (name,Some bo,ty,[],[]) in
761       MatitaSync.add_obj uri obj status
762   | GrafiteAst.Coercion (loc, coercion) -> 
763       eval_coercion status coercion
764   | GrafiteAst.Alias (loc, spec) -> 
765      let diff =
766       (*CSC: Warning: this code should be factorized with the corresponding
767              code in DisambiguatePp *)
768       match spec with
769       | GrafiteAst.Ident_alias (id,uri) -> 
770          [DisambiguateTypes.Id id,
771           (uri,(fun _ _ _-> CicUtil.term_of_uri(UriManager.uri_of_string uri)))]
772       | GrafiteAst.Symbol_alias (symb, instance, desc) ->
773          [DisambiguateTypes.Symbol (symb,instance),
774           DisambiguateChoices.lookup_symbol_by_dsc symb desc]
775       | GrafiteAst.Number_alias (instance,desc) ->
776          [DisambiguateTypes.Num instance,
777           DisambiguateChoices.lookup_num_by_dsc desc]
778      in
779       MatitaSync.set_proof_aliases status diff
780   | GrafiteAst.Render _ -> assert false (* ZACK: to be removed *)
781   | GrafiteAst.Dump _ -> assert false   (* ZACK: to be removed *)
782   | GrafiteAst.Interpretation (_, dsc, (symbol, _), _) as stm ->
783       let status' = add_moo_content [stm] status in
784       let diff =
785        [DisambiguateTypes.Symbol (symbol, 0),
786          DisambiguateChoices.lookup_symbol_by_dsc symbol dsc]
787       in
788       MatitaSync.set_proof_aliases status' diff
789   | GrafiteAst.Notation _ as stm -> add_moo_content [stm] status
790   | GrafiteAst.Obj (loc,obj) ->
791      let ext,name =
792       match obj with
793          Cic.Constant (name,_,_,_,_)
794        | Cic.CurrentProof (name,_,_,_,_,_) -> ".con",name
795        | Cic.InductiveDefinition (types,_,_,_) ->
796           ".ind",
797           (match types with (name,_,_,_)::_ -> name | _ -> assert false)
798        | _ -> assert false in
799      let uri = 
800        UriManager.uri_of_string (MatitaMisc.qualify status name ^ ext) 
801      in
802      let metasenv = MatitaMisc.get_proof_metasenv status in
803      match obj with
804      | Cic.CurrentProof (_,metasenv',bo,ty,_,_) ->
805          let name = UriManager.name_of_uri uri in
806          if not(CicPp.check name ty) then
807            MatitaLog.error ("Bad name: " ^ name);
808          if opts.do_heavy_checks then
809            begin
810              let dbd = MatitaDb.instance () in
811              let similar = MetadataQuery.match_term ~dbd ty in
812              let similar_len = List.length similar in
813              if similar_len> 30 then
814                (MatitaLog.message
815                  ("Duplicate check will compare your theorem with " ^ 
816                    string_of_int similar_len ^ 
817                    " theorems, this may take a while."));
818              let convertible =
819                List.filter (
820                  fun u ->
821                    let t = CicUtil.term_of_uri u in
822                    let ty',g = 
823                      CicTypeChecker.type_of_aux' 
824                        metasenv' [] t CicUniv.empty_ugraph
825                    in
826                    fst(CicReduction.are_convertible [] ty' ty g)) 
827                similar 
828              in
829              (match convertible with
830              | [] -> ()
831              | x::_ -> 
832                  MatitaLog.warn  
833                  ("Theorem already proved: " ^ UriManager.string_of_uri x ^ 
834                   "\nPlease use a variant."));
835            end;
836          assert (metasenv = metasenv');
837          let goalno =
838            match metasenv' with (goalno,_,_)::_ -> goalno | _ -> assert false 
839          in
840          let initial_proof = (Some uri, metasenv, bo, ty) in
841          { status with proof_status = Incomplete_proof (initial_proof,goalno)}
842      | _ ->
843          if metasenv <> [] then
844           command_error (
845             "metasenv not empty while giving a definition with body: " ^
846             CicMetaSubst.ppmetasenv [] metasenv);
847          let status' = ref status in
848          (try
849            status' := MatitaSync.add_obj uri obj !status';
850            (match obj with
851            | Cic.Constant _ -> ()
852            | Cic.InductiveDefinition (_,_,_,attrs) ->
853                status' := generate_elimination_principles uri !status';
854                let rec get_record_attrs =
855                  function
856                  | [] -> None
857                  | (`Class (`Record fields))::_ -> Some fields
858                  | _::tl -> get_record_attrs tl
859                in
860                (match get_record_attrs attrs with
861                | None -> () (* not a record *)
862                | Some fields ->
863                    status' := generate_projections uri fields !status')
864            | Cic.CurrentProof _
865            | Cic.Variable _ -> assert false);
866            !status'
867          with exn ->
868            MatitaSync.time_travel ~present:!status' ~past:status;
869            raise exn)
870
871 let eval_executable opts status ex =
872   match ex with
873   | GrafiteAst.Tactical (_, tac) -> eval_tactical status tac
874   | GrafiteAst.Command (_, cmd) -> eval_command opts status cmd
875   | GrafiteAst.Macro (_, mac) -> 
876       command_error (sprintf "The macro %s can't be in a script" 
877         (GrafiteAstPp.pp_macro_ast mac))
878
879 let eval_comment status c = status
880             
881
882 let eval_ast 
883   ?(do_heavy_checks=false) ?(include_paths=[]) ?(clean_baseuri=true) status st 
884 =
885   let opts = {
886     do_heavy_checks = do_heavy_checks ; 
887     include_paths = include_paths;
888     clean_baseuri = clean_baseuri }
889   in
890   match st with
891   | GrafiteAst.Executable (_,ex) -> eval_executable opts status ex
892   | GrafiteAst.Comment (_,c) -> eval_comment status c
893
894 let eval_from_stream 
895   ?do_heavy_checks ?include_paths ?clean_baseuri status str cb 
896 =
897   try
898     while true do
899       let ast = GrafiteParser.parse_statement str in
900       cb !status ast;
901       status := eval_ast ?do_heavy_checks ?include_paths ?clean_baseuri !status ast
902     done
903   with End_of_file -> ()
904
905 (* to avoid a long list of recursive functions *)
906 let _ = eval_from_stream_ref := eval_from_stream
907   
908 let eval_from_stream_greedy 
909   ?do_heavy_checks ?include_paths ?clean_baseuri status str cb 
910 =
911   while true do
912     print_string "matita> ";
913     flush stdout;
914     let ast = GrafiteParser.parse_statement str in
915     cb !status ast;
916     status := eval_ast ?do_heavy_checks ?include_paths ?clean_baseuri !status ast 
917   done
918 ;;
919
920 let eval_string ?do_heavy_checks ?include_paths ?clean_baseuri status str =
921   eval_from_stream 
922     ?do_heavy_checks ?include_paths ?clean_baseuri status
923       (Ulexing.from_utf8_string str) (fun _ _ ->())
924
925 let default_options () =
926 (*
927   let options =
928     StringMap.add "baseuri"
929       (String
930         (Helm_registry.get "matita.baseuri" ^ Helm_registry.get "matita.owner"))
931       no_options
932   in
933 *)
934   let options =
935     StringMap.add "basedir"
936       (String (Helm_registry.get "matita.basedir"))
937       no_options
938   in
939   options
940
941 let initial_status =
942   lazy {
943     aliases = DisambiguateTypes.Environment.empty;
944     multi_aliases = DisambiguateTypes.Environment.empty;
945     moo_content_rev = [];
946     proof_status = No_proof;
947     options = default_options ();
948     objects = [];
949     notation_ids = [];
950   }
951