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