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