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