]> matita.cs.unibo.it Git - helm.git/blob - helm/matita/matitaEngine.ml
new tacticals
[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 -> MatitaMisc.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:(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 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 Disambiguate.NoWellTypedInterpretation)
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 (MatitaMisc.get_stack status)); *)
459  let starting_metasenv = MatitaMisc.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 =  MatitaMisc.get_proof_metasenv !status_ref in
464  let proof = MatitaMisc.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, _) = MatitaMisc.get_stack status
519
520   let set_stack stack (status, opened, closed) = 
521     MatitaMisc.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,_) -> MatitaSync.add_obj uri o status)
618     status new_coercions in
619   let statement_of name =
620     GrafiteAst.Coercion (DisambiguateTypes.dummy_floc, 
621       (CicNotationPt.Ident (name, None)))
622   in
623   let moo_content = 
624     statement_of (UriManager.name_of_uri coer_uri) ::
625     (List.map 
626       (fun (uri, _, _) -> 
627         statement_of (UriManager.name_of_uri uri))
628     new_coercions)
629   in
630   let status = add_moo_content moo_content status in
631   { status with proof_status = No_proof }
632
633 let generate_elimination_principles uri status =
634   let status' = ref status in
635   let elim sort =
636     try
637       let uri,obj = CicElim.elim_of ~sort uri 0 in
638       status' := MatitaSync.add_obj uri obj !status'
639     with CicElim.Can_t_eliminate -> ()
640   in
641   try
642     List.iter elim [ Cic.Prop; Cic.Set; (Cic.Type (CicUniv.fresh ())) ];
643     !status'
644   with exn ->
645     MatitaSync.time_travel ~present:!status' ~past:status;
646     raise exn
647
648 let generate_projections uri fields status =
649  let projections = CicRecord.projections_of uri fields in
650   List.fold_left
651    (fun status (uri, name, bo) -> 
652      try 
653       let ty, ugraph = 
654         CicTypeChecker.type_of_aux' [] [] bo CicUniv.empty_ugraph in
655       let attrs = [`Class `Projection; `Generated] in
656       let obj = Cic.Constant (name,Some bo,ty,[],attrs) in
657        MatitaSync.add_obj uri obj status
658      with
659         CicTypeChecker.TypeCheckerFailure s ->
660          MatitaLog.message 
661           ("Unable to create projection " ^ name ^ " cause: " ^ (Lazy.force s));
662          status
663       | CicEnvironment.Object_not_found uri ->
664          let depend = UriManager.name_of_uri uri in
665           MatitaLog.message 
666            ("Unable to create projection " ^ name ^ " because it requires " ^ depend);
667          status
668   ) status projections
669
670 (* to avoid a long list of recursive functions *)
671 let eval_from_moo_ref = ref (fun _ _ _ -> assert false);;
672  
673 let disambiguate_obj status obj =
674   let uri =
675    match obj with
676       GrafiteAst.Inductive (_,(name,_,_,_)::_)
677     | GrafiteAst.Record (_,name,_,_) ->
678        Some (UriManager.uri_of_string (MatitaMisc.qualify status name ^ ".ind"))
679     | GrafiteAst.Inductive _ -> assert false
680     | GrafiteAst.Theorem _ -> None in
681   let (diff, metasenv, cic, _) =
682     singleton
683       (MatitaDisambiguator.disambiguate_obj ~dbd:(MatitaDb.instance ())
684         ~aliases:status.aliases ~universe:(Some status.multi_aliases) ~uri obj)
685   in
686   let proof_status =
687     match status.proof_status with
688     | No_proof -> Intermediate metasenv
689     | Incomplete_proof _
690     | Proof _ -> command_error "imbricated proofs not allowed"
691     | Intermediate _ -> assert false
692   in
693   let status = { status with proof_status = proof_status } in
694   let status = MatitaSync.set_proof_aliases status diff in
695   status, cic
696   
697 let disambiguate_command status =
698   function
699   | GrafiteAst.Alias _
700   | GrafiteAst.Default _
701   | GrafiteAst.Drop _
702   | GrafiteAst.Dump _
703   | GrafiteAst.Include _
704   | GrafiteAst.Interpretation _
705   | GrafiteAst.Metadata _
706   | GrafiteAst.Notation _
707   | GrafiteAst.Qed _
708   | GrafiteAst.Render _
709   | GrafiteAst.Set _ as cmd ->
710       status,cmd
711   | GrafiteAst.Coercion (loc, term) ->
712       let status_ref = ref status in
713       let term = disambiguate_term ~context:[] status_ref ~-1 term in
714       !status_ref, GrafiteAst.Coercion (loc,term)
715   | GrafiteAst.Obj (loc,obj) ->
716       let status,obj = disambiguate_obj status obj in
717       status, GrafiteAst.Obj (loc,obj)
718
719 let make_absolute paths path =
720   if path = "coq.ma" then path
721   else
722    let rec aux = function
723    | [] -> ignore (Unix.stat path); path
724    | p :: tl ->
725       let path = p ^ "/" ^ path in
726        try
727          ignore (Unix.stat path); path
728        with Unix.Unix_error _ -> aux tl
729    in
730    try
731      aux paths
732    with Unix.Unix_error _ as exc -> raise (UnableToInclude path)
733 ;;
734        
735 let eval_command opts status cmd =
736   let status,cmd = disambiguate_command status cmd in
737   let cmd,notation_ids' = CicNotation.process_notation cmd in
738   let status =
739     { status with notation_ids = notation_ids' @ status.notation_ids }
740   in
741   match cmd with
742   | GrafiteAst.Default (loc, what, uris) as cmd ->
743      LibraryObjects.set_default what uris;
744      add_moo_content [cmd] status
745   | GrafiteAst.Include (loc, path) ->
746      let absolute_path = make_absolute opts.include_paths path in
747      let moopath = MatitaMisc.obj_file_of_script absolute_path in
748      let status = ref status in
749      if not (Sys.file_exists moopath) then
750        raise (IncludedFileNotCompiled moopath);
751      !eval_from_moo_ref status moopath (fun _ _ -> ());
752      !status
753   | GrafiteAst.Metadata (loc, m) ->
754       (match m with
755       | GrafiteAst.Dependency uri -> MatitaTypes.add_moo_metadata [m] status
756       | GrafiteAst.Baseuri _ -> status)
757   | GrafiteAst.Set (loc, name, value) -> 
758       let status = 
759         if name = "baseuri" then begin
760           let value = 
761             let v = MatitaMisc.strip_trailing_slash value in
762             try
763               ignore (String.index v ' ');
764               command_error "baseuri can't contain spaces"
765             with Not_found -> v
766           in
767           if not (MatitaMisc.is_empty value) && opts.clean_baseuri then begin
768             MatitaLog.warn ("baseuri " ^ value ^ " is not empty");
769             MatitaLog.message ("cleaning baseuri " ^ value);
770             MatitacleanLib.clean_baseuris [value]
771           end;
772           add_moo_metadata [GrafiteAst.Baseuri value] status
773         end else
774           status
775       in
776       set_option status name value
777   | GrafiteAst.Drop loc -> raise Drop
778   | GrafiteAst.Qed loc ->
779       let uri, metasenv, bo, ty =
780         match status.proof_status with
781         | Proof (Some uri, metasenv, body, ty) ->
782             uri, metasenv, body, ty
783         | Proof (None, metasenv, body, ty) -> 
784             command_error 
785               ("Someone allows to start a thm without giving the "^
786                "name/uri. This should be fixed!")
787         | _-> command_error "You can't Qed an incomplete theorem"
788       in
789       let suri = UriManager.string_of_uri uri in
790       if metasenv <> [] then 
791         command_error "Proof not completed! metasenv is not empty!";
792       let name = UriManager.name_of_uri uri in
793       let obj = Cic.Constant (name,Some bo,ty,[],[]) in
794       MatitaSync.add_obj uri obj status
795   | GrafiteAst.Coercion (loc, coercion) -> eval_coercion status coercion
796   | GrafiteAst.Alias (loc, spec) -> 
797      let diff =
798       (*CSC: Warning: this code should be factorized with the corresponding
799              code in DisambiguatePp *)
800       match spec with
801       | GrafiteAst.Ident_alias (id,uri) -> 
802          [DisambiguateTypes.Id id,
803           (uri,(fun _ _ _-> CicUtil.term_of_uri(UriManager.uri_of_string uri)))]
804       | GrafiteAst.Symbol_alias (symb, instance, desc) ->
805          [DisambiguateTypes.Symbol (symb,instance),
806           DisambiguateChoices.lookup_symbol_by_dsc symb desc]
807       | GrafiteAst.Number_alias (instance,desc) ->
808          [DisambiguateTypes.Num instance,
809           DisambiguateChoices.lookup_num_by_dsc desc]
810      in
811       MatitaSync.set_proof_aliases status diff
812   | GrafiteAst.Render _ -> assert false (* ZACK: to be removed *)
813   | GrafiteAst.Dump _ -> assert false   (* ZACK: to be removed *)
814   | GrafiteAst.Interpretation (_, dsc, (symbol, _), cic_appl_pattern) as stm ->
815       let status = add_moo_content [stm] status in
816       let uris =
817         List.map
818           (fun uri -> GrafiteAst.Dependency (UriManager.buri_of_uri uri))
819           (CicNotationUtil.find_appl_pattern_uris cic_appl_pattern)
820       in
821       let diff =
822        [DisambiguateTypes.Symbol (symbol, 0),
823          DisambiguateChoices.lookup_symbol_by_dsc symbol dsc]
824       in
825       let status = MatitaSync.set_proof_aliases status diff in
826       let status = MatitaTypes.add_moo_metadata uris status in
827       status
828   | GrafiteAst.Notation _ as stm -> add_moo_content [stm] status
829   | GrafiteAst.Obj (loc,obj) ->
830      let ext,name =
831       match obj with
832          Cic.Constant (name,_,_,_,_)
833        | Cic.CurrentProof (name,_,_,_,_,_) -> ".con",name
834        | Cic.InductiveDefinition (types,_,_,_) ->
835           ".ind",
836           (match types with (name,_,_,_)::_ -> name | _ -> assert false)
837        | _ -> assert false in
838      let uri = 
839        UriManager.uri_of_string (MatitaMisc.qualify status name ^ ext) 
840      in
841      let metasenv = MatitaMisc.get_proof_metasenv status in
842      match obj with
843      | Cic.CurrentProof (_,metasenv',bo,ty,_,_) ->
844          let name = UriManager.name_of_uri uri in
845          if not(CicPp.check name ty) then
846            MatitaLog.error ("Bad name: " ^ name);
847          if opts.do_heavy_checks then
848            begin
849              let dbd = MatitaDb.instance () in
850              let similar = MetadataQuery.match_term ~dbd ty in
851              let similar_len = List.length similar in
852              if similar_len> 30 then
853                (MatitaLog.message
854                  ("Duplicate check will compare your theorem with " ^ 
855                    string_of_int similar_len ^ 
856                    " theorems, this may take a while."));
857              let convertible =
858                List.filter (
859                  fun u ->
860                    let t = CicUtil.term_of_uri u in
861                    let ty',g = 
862                      CicTypeChecker.type_of_aux' 
863                        metasenv' [] t CicUniv.empty_ugraph
864                    in
865                    fst(CicReduction.are_convertible [] ty' ty g)) 
866                similar 
867              in
868              (match convertible with
869              | [] -> ()
870              | x::_ -> 
871                  MatitaLog.warn  
872                  ("Theorem already proved: " ^ UriManager.string_of_uri x ^ 
873                   "\nPlease use a variant."));
874            end;
875          assert (metasenv = metasenv');
876          let goalno =
877            match metasenv' with (goalno,_,_)::_ -> goalno | _ -> assert false 
878          in
879          let initial_proof = (Some uri, metasenv, bo, ty) in
880          let initial_stack = Continuationals.Stack.of_metasenv metasenv in
881          { status with proof_status =
882             Incomplete_proof { proof = initial_proof; stack = initial_stack } }
883      | _ ->
884          if metasenv <> [] then
885           command_error (
886             "metasenv not empty while giving a definition with body: " ^
887             CicMetaSubst.ppmetasenv [] metasenv);
888          let status' = ref status in
889          (try
890            status' := MatitaSync.add_obj uri obj !status';
891            (match obj with
892            | Cic.Constant _ -> ()
893            | Cic.InductiveDefinition (_,_,_,attrs) ->
894                status' := generate_elimination_principles uri !status';
895                let rec get_record_attrs =
896                  function
897                  | [] -> None
898                  | (`Class (`Record fields))::_ -> Some fields
899                  | _::tl -> get_record_attrs tl
900                in
901                (match get_record_attrs attrs with
902                | None -> () (* not a record *)
903                | Some fields ->
904                    status' := generate_projections uri fields !status')
905            | Cic.CurrentProof _
906            | Cic.Variable _ -> assert false);
907            !status'
908          with exn ->
909            MatitaSync.time_travel ~present:!status' ~past:status;
910            raise exn)
911
912 let eval_executable opts status ex =
913   match ex with
914   | GrafiteAst.Tactical (_, tac, None) -> eval_tactical status tac
915   | GrafiteAst.Tactical (_, tac, Some punct) ->
916       let status = eval_tactical status tac in
917       eval_tactical status punct
918   | GrafiteAst.Command (_, cmd) -> eval_command opts status cmd
919   | GrafiteAst.Macro (_, mac) -> 
920       command_error (sprintf "The macro %s can't be in a script" 
921         (GrafiteAstPp.pp_macro_ast mac))
922
923 let eval_comment status c = status
924             
925 let eval_ast 
926   ?(do_heavy_checks=false) ?(include_paths=[]) ?(clean_baseuri=true) status st 
927 =
928   let opts = {
929     do_heavy_checks = do_heavy_checks ; 
930     include_paths = include_paths;
931     clean_baseuri = clean_baseuri }
932   in
933   match st with
934   | GrafiteAst.Executable (_,ex) -> eval_executable opts status ex
935   | GrafiteAst.Comment (_,c) -> eval_comment status c
936
937 let eval_from_moo ?do_heavy_checks ?include_paths ?clean_baseuri status fname cb
938 =
939   let ast_of_cmd cmd =
940     GrafiteAst.Executable (DisambiguateTypes.dummy_floc,
941       GrafiteAst.Command (DisambiguateTypes.dummy_floc,
942         (GrafiteAst.reash_cmd_uris cmd)))
943   in
944   let moo, metadata = MatitaMoo.load_moo fname in
945   List.iter 
946     (fun ast -> 
947       let ast = ast_of_cmd ast in
948       cb !status ast;
949       status :=
950         eval_ast ?do_heavy_checks ?include_paths ?clean_baseuri !status ast)
951     moo;
952   List.iter
953     (fun m ->
954       let ast =
955         ast_of_cmd (GrafiteAst.Metadata (DisambiguateTypes.dummy_floc, m))
956       in
957       cb !status ast;
958       status :=
959         eval_ast ?do_heavy_checks ?include_paths ?clean_baseuri !status ast)
960     metadata
961
962 let eval_from_stream 
963   ?do_heavy_checks ?include_paths ?clean_baseuri status str cb 
964 =
965   try
966     while true do
967       let ast = GrafiteParser.parse_statement str in
968       cb !status ast;
969       status :=
970         eval_ast ?do_heavy_checks ?include_paths ?clean_baseuri !status ast
971     done
972   with End_of_file -> ()
973
974 (* to avoid a long list of recursive functions *)
975 let _ = eval_from_moo_ref := eval_from_moo
976   
977 let eval_from_stream_greedy 
978   ?do_heavy_checks ?include_paths ?clean_baseuri status str cb 
979 =
980   while true do
981     print_string "matita> ";
982     flush stdout;
983     let ast = GrafiteParser.parse_statement str in
984     cb !status ast;
985     status := eval_ast ?do_heavy_checks ?include_paths ?clean_baseuri !status ast 
986   done
987 ;;
988
989 let eval_string ?do_heavy_checks ?include_paths ?clean_baseuri status str =
990   eval_from_stream 
991     ?do_heavy_checks ?include_paths ?clean_baseuri status
992       (Ulexing.from_utf8_string str) (fun _ _ -> ())
993
994 let default_options () =
995 (*
996   let options =
997     StringMap.add "baseuri"
998       (String
999         (Helm_registry.get "matita.baseuri" ^ Helm_registry.get "matita.owner"))
1000       no_options
1001   in
1002 *)
1003   let options =
1004     StringMap.add "basedir"
1005       (String (Helm_registry.get "matita.basedir"))
1006       no_options
1007   in
1008   options
1009
1010 let initial_status =
1011   lazy {
1012     aliases = DisambiguateTypes.Environment.empty;
1013     multi_aliases = DisambiguateTypes.Environment.empty;
1014     moo_content_rev = [], [];
1015     proof_status = No_proof;
1016     options = default_options ();
1017     objects = [];
1018     notation_ids = [];
1019   }
1020