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