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