]> matita.cs.unibo.it Git - helm.git/blob - helm/matita/matitaEngine.ml
- changed moo representation in MatitaTypes.status, no longer a string list, but...
[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 (aliases, metasenv, cic, _) =
166     singleton
167       (MatitaDisambiguator.disambiguate_term ~dbd:(MatitaDb.instance ())
168         ~aliases:(status.aliases) ~context:(MatitaMisc.get_proof_context status)
169         ~metasenv:(MatitaMisc.get_proof_metasenv status) term)
170   in
171   let status = MatitaTypes.set_metasenv metasenv status in
172   let status = MatitaSync.set_proof_aliases status aliases in
173   status_ref := status;
174   cic
175   
176   (** disambiguate_lazy_term (circa): term -> (unit -> status) * lazy_term
177    * rationale: lazy_term will be invoked in different context to obtain a term,
178    * each invocation will disambiguate the term and can add aliases. Once all
179    * disambiguations have been performed, the first returned function can be
180    * used to obtain the resulting aliases *)
181 let disambiguate_lazy_term status_ref term =
182   (fun context metasenv ugraph ->
183     let status = !status_ref in
184     let (aliases, metasenv, cic, ugraph) =
185       singleton
186         (MatitaDisambiguator.disambiguate_term ~dbd:(MatitaDb.instance ())
187           ~initial_ugraph:ugraph ~aliases:status.aliases ~context ~metasenv
188             term)
189     in
190     let status = MatitaTypes.set_metasenv metasenv status in
191     let status = MatitaSync.set_proof_aliases status aliases in
192     status_ref := status;
193     cic, metasenv, ugraph)
194
195 let disambiguate_pattern status_ref (wanted, hyp_paths, goal_path) =
196   let interp path = Disambiguate.interpretate_path [] path in
197   let goal_path = interp goal_path in
198   let hyp_paths = List.map (fun (name, path) -> name, interp path) hyp_paths in
199   let wanted =
200    match wanted with
201       None -> None
202     | Some wanted ->
203        let wanted = disambiguate_lazy_term status_ref wanted in
204        Some wanted
205   in
206   (wanted, hyp_paths ,goal_path)
207
208 let disambiguate_reduction_kind aliases_ref = function
209   | `Unfold (Some t) ->
210       let t = disambiguate_lazy_term aliases_ref t in
211       `Unfold (Some t)
212   | `Normalize
213   | `Reduce
214   | `Simpl
215   | `Unfold None
216   | `Whd as kind -> kind
217   
218 let disambiguate_tactic status tactic =
219   let status_ref = ref status in
220   let tactic =
221     match tactic with
222     | GrafiteAst.Absurd (loc, term) -> 
223         let cic = disambiguate_term status_ref term in
224         GrafiteAst.Absurd (loc, cic)
225     | GrafiteAst.Apply (loc, term) ->
226         let cic = disambiguate_term status_ref term in
227         GrafiteAst.Apply (loc, cic)
228     | GrafiteAst.Assumption loc -> GrafiteAst.Assumption loc
229     | GrafiteAst.Auto (loc,depth,width,paramodulation) ->
230         GrafiteAst.Auto (loc,depth,width,paramodulation)
231     | GrafiteAst.Change (loc, pattern, with_what) -> 
232         let with_what = disambiguate_lazy_term status_ref with_what in
233         let pattern = disambiguate_pattern status_ref pattern in
234         GrafiteAst.Change (loc, pattern, with_what)
235     | GrafiteAst.Clear (loc,id) -> GrafiteAst.Clear (loc,id)
236     | GrafiteAst.ClearBody (loc,id) -> GrafiteAst.ClearBody (loc,id)
237     | GrafiteAst.Compare (loc,term) ->
238         let term = disambiguate_term status_ref term in
239         GrafiteAst.Compare (loc,term)
240     | GrafiteAst.Constructor (loc,n) -> GrafiteAst.Constructor (loc,n)
241     | GrafiteAst.Contradiction loc -> GrafiteAst.Contradiction loc
242     | GrafiteAst.Cut (loc, ident, term) -> 
243         let cic = disambiguate_term status_ref term in
244         GrafiteAst.Cut (loc, ident, cic)
245     | GrafiteAst.DecideEquality loc -> GrafiteAst.DecideEquality loc
246     | GrafiteAst.Decompose (loc, types, what, names) ->
247         let disambiguate types = function
248            | GrafiteAst.Type _   -> assert false
249            | GrafiteAst.Ident id ->
250               (match disambiguate_term status_ref (CicNotationPt.Ident (id, None)) with
251               | Cic.MutInd (uri, tyno, _) ->
252                   (GrafiteAst.Type (uri, tyno) :: types)
253               | _ -> raise Disambiguate.NoWellTypedInterpretation)
254         in
255         let types = List.fold_left disambiguate [] types in
256         GrafiteAst.Decompose (loc, types, what, names)
257     | GrafiteAst.Discriminate (loc,term) ->
258         let term = disambiguate_term status_ref term in
259         GrafiteAst.Discriminate(loc,term)
260     | GrafiteAst.Exact (loc, term) -> 
261         let cic = disambiguate_term status_ref term in
262         GrafiteAst.Exact (loc, cic)
263     | GrafiteAst.Elim (loc, what, Some using, depth, idents) ->
264         let what = disambiguate_term status_ref what in
265         let using = disambiguate_term status_ref using in
266         GrafiteAst.Elim (loc, what, Some using, depth, idents)
267     | GrafiteAst.Elim (loc, what, None, depth, idents) ->
268         let what = disambiguate_term status_ref what in
269         GrafiteAst.Elim (loc, what, None, depth, idents)
270     | GrafiteAst.ElimType (loc, what, Some using, depth, idents) ->
271         let what = disambiguate_term status_ref what in
272         let using = disambiguate_term status_ref using in
273         GrafiteAst.ElimType (loc, what, Some using, depth, idents)
274     | GrafiteAst.ElimType (loc, what, None, depth, idents) ->
275         let what = disambiguate_term status_ref what in
276         GrafiteAst.ElimType (loc, what, None, depth, idents)
277     | GrafiteAst.Exists loc -> GrafiteAst.Exists loc 
278     | GrafiteAst.Fail loc -> GrafiteAst.Fail loc
279     | GrafiteAst.Fold (loc,red_kind, term, pattern) ->
280         let pattern = disambiguate_pattern status_ref pattern in
281         let term = disambiguate_lazy_term status_ref term in
282         let red_kind = disambiguate_reduction_kind status_ref red_kind in
283         GrafiteAst.Fold (loc, red_kind, term, pattern)
284     | GrafiteAst.FwdSimpl (loc, hyp, names) ->
285        GrafiteAst.FwdSimpl (loc, hyp, names)  
286     | GrafiteAst.Fourier loc -> GrafiteAst.Fourier loc
287     | GrafiteAst.Generalize (loc,pattern,ident) ->
288         let pattern = disambiguate_pattern status_ref pattern in
289         GrafiteAst.Generalize (loc,pattern,ident)
290     | GrafiteAst.Goal (loc, g) -> GrafiteAst.Goal (loc, g)
291     | GrafiteAst.IdTac loc -> GrafiteAst.IdTac loc
292     | GrafiteAst.Injection (loc, term) ->
293         let term = disambiguate_term status_ref term in
294         GrafiteAst.Injection (loc,term)
295     | GrafiteAst.Intros (loc, num, names) -> GrafiteAst.Intros (loc, num, names)
296     | GrafiteAst.LApply (loc, depth, to_what, what, ident) ->
297        let f term to_what =
298           let term = disambiguate_term status_ref term in
299           term :: to_what
300        in
301        let to_what = List.fold_right f to_what [] in 
302        let what = disambiguate_term status_ref what in
303        GrafiteAst.LApply (loc, depth, to_what, what, ident)
304     | GrafiteAst.Left loc -> GrafiteAst.Left loc
305     | GrafiteAst.LetIn (loc, term, name) ->
306         let term = disambiguate_term status_ref term in
307         GrafiteAst.LetIn (loc,term,name)
308     | GrafiteAst.Reduce (loc, red_kind, pattern) ->
309         let pattern = disambiguate_pattern status_ref pattern in
310         let red_kind = disambiguate_reduction_kind status_ref red_kind in
311         GrafiteAst.Reduce(loc, red_kind, pattern)
312     | GrafiteAst.Reflexivity loc -> GrafiteAst.Reflexivity loc
313     | GrafiteAst.Replace (loc, pattern, with_what) -> 
314         let pattern = disambiguate_pattern status_ref pattern in
315         let with_what = disambiguate_lazy_term status_ref with_what in
316         GrafiteAst.Replace (loc, pattern, with_what)
317     | GrafiteAst.Rewrite (loc, dir, t, pattern) ->
318         let term = disambiguate_term status_ref t in
319         let pattern = disambiguate_pattern status_ref pattern in
320         GrafiteAst.Rewrite (loc, dir, term, pattern)
321     | GrafiteAst.Right loc -> GrafiteAst.Right loc
322     | GrafiteAst.Ring loc -> GrafiteAst.Ring loc
323     | GrafiteAst.Split loc -> GrafiteAst.Split loc
324     | GrafiteAst.Symmetry loc -> GrafiteAst.Symmetry loc
325     | GrafiteAst.Transitivity (loc, term) -> 
326         let cic = disambiguate_term status_ref term in
327         GrafiteAst.Transitivity (loc, cic)
328   in
329   status_ref, tactic
330
331 let apply_tactic tactic status =
332  let status_ref, tactic = disambiguate_tactic status tactic in
333  let proof_status = MatitaMisc.get_proof_status !status_ref in
334  let tactic = tactic_of_ast tactic in
335  (* apply tactic will change the status pointed by status_ref ... *)
336  let (proof, goals) = ProofEngineTypes.apply_tactic tactic proof_status in
337  let dummy = -1 in
338  { !status_ref with
339     proof_status = MatitaTypes.Incomplete_proof (proof,dummy) },
340  goals
341
342 module MatitaStatus =
343  struct
344   type input_status = MatitaTypes.status
345   type output_status = MatitaTypes.status * ProofEngineTypes.goal list
346   type tactic = input_status -> output_status
347
348   let focus (status,_) goal =
349    let proof,_ = MatitaMisc.get_proof_status status in
350     {status with proof_status = MatitaTypes.Incomplete_proof (proof,goal)}
351
352   let goals (_,goals) = goals
353
354   let set_goals (status,_) goals = status,goals
355
356   let id_tac status =
357     apply_tactic (GrafiteAst.IdTac DisambiguateTypes.dummy_floc) status
358
359   let mk_tactic tac = tac
360
361   let apply_tactic tac = tac
362
363  end
364
365 module MatitaTacticals = Tacticals.Make(MatitaStatus)
366
367 let eval_tactical status tac =
368  let rec tactical_of_ast tac =
369   match tac with
370     | GrafiteAst.Tactic (loc, tactic) -> apply_tactic tactic
371     | GrafiteAst.Seq (loc, tacticals) ->  (* tac1; tac2; ... *)
372        MatitaTacticals.seq ~tactics:(List.map tactical_of_ast tacticals)
373     | GrafiteAst.Do (loc, num, tactical) ->
374         MatitaTacticals.do_tactic ~n:num ~tactic:(tactical_of_ast tactical)
375     | GrafiteAst.Repeat (loc, tactical) ->
376         MatitaTacticals.repeat_tactic ~tactic:(tactical_of_ast tactical)
377     | GrafiteAst.Then (loc, tactical, tacticals) ->  (* tac; [ tac1 | ... ] *)
378         MatitaTacticals.thens ~start:(tactical_of_ast tactical)
379           ~continuations:(List.map tactical_of_ast tacticals)
380     | GrafiteAst.First (loc, tacticals) ->
381         MatitaTacticals.first
382           ~tactics:(List.map (fun t -> "", tactical_of_ast t) tacticals)
383     | GrafiteAst.Try (loc, tactical) ->
384         MatitaTacticals.try_tactic ~tactic:(tactical_of_ast tactical)
385     | GrafiteAst.Solve (loc, tacticals) ->
386         MatitaTacticals.solve_tactics
387          ~tactics:(List.map (fun t -> "",tactical_of_ast t) tacticals)
388  in
389   let status,goals = tactical_of_ast tac status in
390   let proof,_ = MatitaMisc.get_proof_status status in
391   let new_status =
392    match goals with
393    | [] -> 
394        let (_,metasenv,_,_) = proof in
395        (match metasenv with
396        | [] -> Proof proof
397        | (ng,_,_)::_ -> Incomplete_proof (proof,ng))
398    | ng::_ -> Incomplete_proof (proof, ng)
399   in
400    { status with proof_status = new_status }
401
402 let eval_coercion status coercion = 
403   let coer_uri,coer_ty =
404     match coercion with 
405     | Cic.Const (uri,_)
406     | Cic.Var (uri,_) ->
407         let o,_ = CicEnvironment.get_obj CicUniv.empty_ugraph uri in
408         (match o with
409         | Cic.Constant (_,_,ty,_,_)
410         | Cic.Variable (_,_,ty,_,_) ->
411             uri,ty
412         | _ -> assert false)
413     | Cic.MutConstruct (uri,t,c,_) ->
414         let o,_ = CicEnvironment.get_obj CicUniv.empty_ugraph uri in
415         (match o with
416         | Cic.InductiveDefinition (l,_,_,_) ->
417             let (_,_,_,cl) = List.nth l t in
418             let (_,cty) = List.nth cl c in
419               uri,cty
420         | _ -> assert false)
421     | _ -> assert false 
422   in
423   (* we have to get the source and the tgt type uri 
424    * in Coq syntax we have already their names, but 
425    * since we don't support Funclass and similar I think
426    * all the coercion should be of the form
427    * (A:?)(B:?)T1->T2
428    * So we should be able to extract them from the coercion type
429    *)
430   let extract_last_two_p ty =
431     let rec aux = function
432       | Cic.Prod( _, src, Cic.Prod (n,t1,t2)) -> aux (Cic.Prod(n,t1,t2))   
433       | Cic.Prod( _, src, tgt) -> src, tgt
434       | _ -> assert false
435     in  
436     aux ty
437   in
438   let ty_src,ty_tgt = extract_last_two_p coer_ty in
439   let context = [] in 
440   let src_uri = 
441     let ty_src = CicReduction.whd context ty_src in
442      CicUtil.uri_of_term ty_src
443   in
444   let tgt_uri = 
445     let ty_tgt = CicReduction.whd context ty_tgt in
446      CicUtil.uri_of_term ty_tgt
447   in
448   let new_coercions =
449     (* also adds them to the Db *)
450     CoercGraph.close_coercion_graph src_uri tgt_uri coer_uri in
451   let status =
452    List.fold_left (fun s (uri,o,ugraph) -> MatitaSync.add_obj uri o status)
453     status new_coercions in
454   let statement_of name =
455     GrafiteAst.Coercion (DisambiguateTypes.dummy_floc, 
456       (CicNotationPt.Ident (name, None)))
457   in
458   let moo_content = 
459     statement_of (UriManager.name_of_uri coer_uri) ::
460     (List.map 
461       (fun (uri, _, _) -> 
462         statement_of (UriManager.name_of_uri uri))
463     new_coercions)
464   in
465   let status = add_moo_content moo_content status in
466   { status with proof_status = No_proof }
467
468 let generate_elimination_principles uri status =
469  let elim sort status =
470    try
471     let uri,obj = CicElim.elim_of ~sort uri 0 in
472      MatitaSync.add_obj uri obj status
473    with CicElim.Can_t_eliminate -> status
474  in
475  List.fold_left (fun status sort -> elim sort status) status
476   [ Cic.Prop; Cic.Set; (Cic.Type (CicUniv.fresh ())) ]
477
478 let generate_projections uri fields status =
479  let projections = CicRecord.projections_of uri fields in
480   List.fold_left
481    (fun status (uri, name, bo) -> 
482      try 
483       let ty, ugraph = 
484         CicTypeChecker.type_of_aux' [] [] bo CicUniv.empty_ugraph in
485       let attrs = [`Class `Projection; `Generated] in
486       let obj = Cic.Constant (name,Some bo,ty,[],attrs) in
487        MatitaSync.add_obj uri obj status
488      with
489         CicTypeChecker.TypeCheckerFailure s ->
490          MatitaLog.message 
491           ("Unable to create projection " ^ name ^ " cause: " ^ s);
492          status
493       | CicEnvironment.Object_not_found uri ->
494          let depend = UriManager.name_of_uri uri in
495           MatitaLog.message 
496            ("Unable to create projection " ^ name ^ " because it requires " ^ depend);
497          status
498   ) status projections
499
500 (* to avoid a long list of recursive functions *)
501 let eval_from_stream_ref = ref (fun _ _ _ -> assert false);;
502  
503 let disambiguate_obj status obj =
504   let uri =
505    match obj with
506       GrafiteAst.Inductive (_,(name,_,_,_)::_)
507     | GrafiteAst.Record (_,name,_,_) ->
508        Some (UriManager.uri_of_string (MatitaMisc.qualify status name ^ ".ind"))
509     | GrafiteAst.Inductive _ -> assert false
510     | GrafiteAst.Theorem _ -> None in
511   let (aliases, metasenv, cic, _) =
512     singleton
513       (MatitaDisambiguator.disambiguate_obj ~dbd:(MatitaDb.instance ())
514         ~aliases:(status.aliases) ~uri obj)
515   in
516   let proof_status =
517     match status.proof_status with
518     | No_proof -> Intermediate metasenv
519     | Incomplete_proof _
520     | Proof _ -> command_error "imbricated proofs not allowed"
521     | Intermediate _ -> assert false
522   in
523   let status = { status with proof_status = proof_status } in
524   let status = MatitaSync.set_proof_aliases status aliases in
525   status, cic
526   
527 let disambiguate_command status = function
528   | GrafiteAst.Alias _
529   | GrafiteAst.Default _
530   | GrafiteAst.Drop _
531   | GrafiteAst.Dump _
532   | GrafiteAst.Include _
533   | GrafiteAst.Interpretation _
534   | GrafiteAst.Notation _
535   | GrafiteAst.Qed _
536   | GrafiteAst.Render _
537   | GrafiteAst.Set _ as cmd ->
538       status,cmd
539   | GrafiteAst.Coercion (loc, term) ->
540       let status_ref = ref status in
541       let term = disambiguate_term status_ref term in
542       !status_ref, GrafiteAst.Coercion (loc,term)
543   | GrafiteAst.Obj (loc,obj) ->
544       let status,obj = disambiguate_obj status obj in
545       status, GrafiteAst.Obj (loc,obj)
546
547 let make_absolute paths path =
548   if path = "coq.ma" then path
549   else
550    let rec aux = function
551    | [] -> ignore (Unix.stat path); path
552    | p :: tl ->
553       let path = p ^ "/" ^ path in
554        try
555          ignore (Unix.stat path); path
556        with Unix.Unix_error _ -> aux tl
557    in
558    try
559      aux paths
560    with Unix.Unix_error _ as exc -> raise (UnableToInclude path)
561 ;;
562        
563 let eval_command opts status cmd =
564   let status,cmd = disambiguate_command status cmd in
565   let cmd,notation_ids' = CicNotation.process_notation cmd in
566   let status =
567     { status with notation_ids = notation_ids' @ status.notation_ids }
568   in
569   match cmd with
570   | GrafiteAst.Default (loc, what, uris) as cmd ->
571      LibraryObjects.set_default what uris;
572      add_moo_content [cmd] status
573   | GrafiteAst.Include (loc, path) ->
574      let absolute_path = make_absolute opts.include_paths path in
575      let moopath = MatitaMisc.obj_file_of_script absolute_path in
576      let ic =
577       try open_in moopath with Sys_error _ -> 
578         raise (IncludedFileNotCompiled moopath) in
579      let stream = Stream.of_channel ic in
580      let status = ref status in
581       !eval_from_stream_ref status stream (fun _ _ -> ());
582       close_in ic;
583       !status
584   | GrafiteAst.Set (loc, name, value) -> 
585       let value = 
586         if name = "baseuri" then
587           let v = MatitaMisc.strip_trailing_slash value in
588           try
589             ignore (String.index v ' ');
590             command_error "baseuri can't contain spaces"
591           with Not_found -> v
592         else
593           value
594       in
595       if not (MatitaMisc.is_empty value) then
596         begin
597           MatitaLog.warn ("baseuri " ^ value ^ " is not empty");
598           if opts.clean_baseuri then
599             begin 
600               MatitaLog.message ("cleaning baseuri " ^ value);
601               MatitacleanLib.clean_baseuris [value]
602             end
603         end;
604       set_option status name value
605   | GrafiteAst.Drop loc -> raise Drop
606   | GrafiteAst.Qed loc ->
607       let uri, metasenv, bo, ty =
608         match status.proof_status with
609         | Proof (Some uri, metasenv, body, ty) ->
610             uri, metasenv, body, ty
611         | Proof (None, metasenv, body, ty) -> 
612             command_error 
613               ("Someone allows to start a thm without giving the "^
614                "name/uri. This should be fixed!")
615         | _-> command_error "You can't qed an uncomplete theorem"
616       in
617       let suri = UriManager.string_of_uri uri in
618       if metasenv <> [] then 
619         command_error "Proof not completed! metasenv is not empty!";
620       let name = UriManager.name_of_uri uri in
621       let obj = Cic.Constant (name,Some bo,ty,[],[]) in
622       MatitaSync.add_obj uri obj status
623   | GrafiteAst.Coercion (loc, coercion) -> 
624       eval_coercion status coercion
625   | GrafiteAst.Alias (loc, spec) -> 
626      let aliases =
627       (*CSC: Warning: this code should be factorized with the corresponding
628              code in DisambiguatePp *)
629       match spec with
630       | GrafiteAst.Ident_alias (id,uri) -> 
631          DisambiguateTypes.Environment.cons
632           (DisambiguateTypes.Id id) 
633           (uri,(fun _ _ _-> CicUtil.term_of_uri (UriManager.uri_of_string uri)))
634           status.aliases 
635       | GrafiteAst.Symbol_alias (symb, instance, desc) ->
636          DisambiguateTypes.Environment.cons
637           (DisambiguateTypes.Symbol (symb,instance))
638           (DisambiguateChoices.lookup_symbol_by_dsc symb desc)
639           status.aliases
640       | GrafiteAst.Number_alias (instance,desc) ->
641          DisambiguateTypes.Environment.cons
642           (DisambiguateTypes.Num instance)
643           (DisambiguateChoices.lookup_num_by_dsc desc) status.aliases
644      in
645       MatitaSync.set_proof_aliases status aliases
646   | GrafiteAst.Render _ -> assert false (* ZACK: to be removed *)
647   | GrafiteAst.Dump _ -> assert false   (* ZACK: to be removed *)
648   | GrafiteAst.Interpretation (_, dsc, (symbol, _), _) as stm ->
649       let status' = add_moo_content [stm] status in
650       let aliases' =
651         DisambiguateTypes.Environment.cons
652           (DisambiguateTypes.Symbol (symbol, 0))
653           (DisambiguateChoices.lookup_symbol_by_dsc symbol dsc)
654           status.aliases
655       in
656       MatitaSync.set_proof_aliases status' aliases'
657   | GrafiteAst.Notation _ as stm -> add_moo_content [stm] status
658   | GrafiteAst.Obj (loc,obj) ->
659      let ext,name =
660       match obj with
661          Cic.Constant (name,_,_,_,_)
662        | Cic.CurrentProof (name,_,_,_,_,_) -> ".con",name
663        | Cic.InductiveDefinition (types,_,_,_) ->
664           ".ind",
665           (match types with (name,_,_,_)::_ -> name | _ -> assert false)
666        | _ -> assert false in
667      let uri = 
668        UriManager.uri_of_string (MatitaMisc.qualify status name ^ ext) 
669      in
670      let metasenv = MatitaMisc.get_proof_metasenv status in
671      match obj with
672      | Cic.CurrentProof (_,metasenv',bo,ty,_,_) ->
673          let name = UriManager.name_of_uri uri in
674          if not(CicPp.check name ty) then
675            MatitaLog.error ("Bad name: " ^ name);
676          if opts.do_heavy_checks then
677            begin
678              let dbd = MatitaDb.instance () in
679              let similar = MetadataQuery.match_term ~dbd ty in
680              let similar_len = List.length similar in
681              if similar_len> 30 then
682                (MatitaLog.message
683                  ("Duplicate check will compare your theorem with " ^ 
684                    string_of_int similar_len ^ 
685                    " theorems, this may take a while."));
686              let convertible =
687                List.filter (
688                  fun u ->
689                    let t = CicUtil.term_of_uri u in
690                    let ty',g = 
691                      CicTypeChecker.type_of_aux' 
692                        metasenv' [] t CicUniv.empty_ugraph
693                    in
694                    fst(CicReduction.are_convertible [] ty' ty g)) 
695                similar 
696              in
697              (match convertible with
698              | [] -> ()
699              | x::_ -> 
700                  MatitaLog.warn  
701                  ("Theorem already proved: " ^ UriManager.string_of_uri x ^ 
702                   "\nPlease use a variant."));
703            end;
704          assert (metasenv = metasenv');
705          let goalno =
706            match metasenv' with (goalno,_,_)::_ -> goalno | _ -> assert false 
707          in
708          let initial_proof = (Some uri, metasenv, bo, ty) in
709          { status with proof_status = Incomplete_proof (initial_proof,goalno)}
710      | _ ->
711          if metasenv <> [] then
712           command_error (
713             "metasenv not empty while giving a definition with body: " ^
714             CicMetaSubst.ppmetasenv metasenv []);
715          let status = MatitaSync.add_obj uri obj status in
716           match obj with
717              Cic.Constant _ -> status
718            | Cic.InductiveDefinition (_,_,_,attrs) ->
719               let status = generate_elimination_principles uri status in
720               let rec get_record_attrs =
721                function
722                   [] -> None
723                 | (`Class (`Record fields))::_ -> Some fields
724                 | _::tl -> get_record_attrs tl
725               in
726                (match get_record_attrs attrs with
727                    None -> status (* not a record *)
728                  | Some fields -> generate_projections uri fields status)
729            | Cic.CurrentProof _
730            | Cic.Variable _ -> assert false
731
732 let eval_executable opts status ex =
733   match ex with
734   | GrafiteAst.Tactical (_, tac) -> eval_tactical status tac
735   | GrafiteAst.Command (_, cmd) -> eval_command opts status cmd
736   | GrafiteAst.Macro (_, mac) -> 
737       command_error (sprintf "The macro %s can't be in a script" 
738         (GrafiteAstPp.pp_macro_ast mac))
739
740 let eval_comment status c = status
741             
742
743 let eval_ast 
744   ?(do_heavy_checks=false) ?(include_paths=[]) ?(clean_baseuri=true) status st 
745 =
746   let opts = {
747     do_heavy_checks = do_heavy_checks ; 
748     include_paths = include_paths;
749     clean_baseuri = clean_baseuri }
750   in
751   match st with
752   | GrafiteAst.Executable (_,ex) -> eval_executable opts status ex
753   | GrafiteAst.Comment (_,c) -> eval_comment status c
754
755 let eval_from_stream 
756   ?do_heavy_checks ?include_paths ?clean_baseuri status str cb 
757 =
758   try
759     while true do
760       let ast = GrafiteParser.parse_statement str in
761       cb !status ast;
762       status := eval_ast ?do_heavy_checks ?include_paths ?clean_baseuri !status ast
763     done
764   with End_of_file -> ()
765
766 (* to avoid a long list of recursive functions *)
767 let _ = eval_from_stream_ref := eval_from_stream
768   
769 let eval_from_stream_greedy 
770   ?do_heavy_checks ?include_paths ?clean_baseuri status str cb 
771 =
772   while true do
773     print_string "matita> ";
774     flush stdout;
775     let ast = GrafiteParser.parse_statement str in
776     cb !status ast;
777     status := eval_ast ?do_heavy_checks ?include_paths ?clean_baseuri !status ast 
778   done
779 ;;
780
781 let eval_string ?do_heavy_checks ?include_paths ?clean_baseuri status str =
782   eval_from_stream 
783     ?do_heavy_checks ?include_paths ?clean_baseuri status (Stream.of_string str) (fun _ _ ->())
784
785 let default_options () =
786 (*
787   let options =
788     StringMap.add "baseuri"
789       (String
790         (Helm_registry.get "matita.baseuri" ^ Helm_registry.get "matita.owner"))
791       no_options
792   in
793 *)
794   let options =
795     StringMap.add "basedir"
796       (String (Helm_registry.get "matita.basedir"))
797       no_options
798   in
799   options
800
801 let initial_status =
802   lazy {
803     aliases = DisambiguateTypes.empty_environment;
804     moo_content_rev = [];
805     proof_status = No_proof;
806     options = default_options ();
807     objects = [];
808     notation_ids = [];
809   }
810