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