]> matita.cs.unibo.it Git - helm.git/blob - helm/matita/matitaEngine.ml
Original semantics of a now almost random piece of code restored.
[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 make_absolute paths path =
505   let rec aux = function
506   | [] -> ignore (Unix.stat path); path
507   | p :: tl ->
508      let path = p ^ "/" ^ path in
509       try
510         ignore (Unix.stat path); path
511       with Unix.Unix_error _ -> aux tl
512   in
513   try
514     aux paths
515   with Unix.Unix_error _ as exc ->
516     command_error ("File " ^ path ^ " not found")
517 ;;
518        
519 let eval_command opts status cmd =
520   let status,cmd = disambiguate_command status cmd in
521   let cmd,notation_ids' = CicNotation.process_notation cmd in
522   let status =
523     { status with notation_ids = notation_ids' @ status.notation_ids }
524   in
525   match cmd with
526   | GrafiteAst.Default (loc, what, uris) as cmd ->
527      LibraryObjects.set_default what uris;
528      {status with moo_content_rev =
529         (GrafiteAstPp.pp_command cmd ^ "\n") :: status.moo_content_rev}
530   | GrafiteAst.Include (loc, path) ->
531      let absolute_path = make_absolute opts.include_paths path in
532      let moopath = MatitaMisc.obj_file_of_script absolute_path in
533      let ic =
534       try open_in moopath with Sys_error _ -> raise (UnableToInclude moopath) in
535      let stream = Stream.of_channel ic in
536      let status = ref status in
537       !eval_from_stream_ref status stream (fun _ _ -> ());
538       close_in ic;
539       !status
540   | GrafiteAst.Set (loc, name, value) -> 
541       let value = 
542         if name = "baseuri" then
543           let v = MatitaMisc.strip_trailing_slash value in
544           try
545             ignore (String.index v ' ');
546             command_error "baseuri can't contain spaces"
547           with Not_found -> v
548         else
549           value
550       in
551       if not (MatitaMisc.is_empty value) then
552         begin
553           MatitaLog.warn ("baseuri " ^ value ^ " is not empty");
554           if opts.clean_baseuri then
555             begin 
556               MatitaLog.message ("cleaning baseuri " ^ value);
557               MatitacleanLib.clean_baseuris [value]
558             end
559         end;
560       set_option status name value
561   | GrafiteAst.Drop loc -> raise Drop
562   | GrafiteAst.Qed loc ->
563       let uri, metasenv, bo, ty = 
564         match status.proof_status with
565         | Proof (Some uri, metasenv, body, ty) ->
566             uri, metasenv, body, ty
567         | Proof (None, metasenv, body, ty) -> 
568             command_error 
569               ("Someone allows to start a thm without giving the "^
570                "name/uri. This should be fixed!")
571         | _-> command_error "You can't qed an uncomplete theorem"
572       in
573       let suri = UriManager.string_of_uri uri in
574       if metasenv <> [] then 
575         command_error "Proof not completed! metasenv is not empty!";
576       let name = UriManager.name_of_uri uri in
577       let obj = Cic.Constant (name,Some bo,ty,[],[]) in
578       MatitaSync.add_obj uri obj status
579   | GrafiteAst.Coercion (loc, coercion) -> 
580       eval_coercion status coercion
581   | GrafiteAst.Alias (loc, spec) -> 
582      let aliases =
583       match spec with
584       | GrafiteAst.Ident_alias (id,uri) -> 
585          DisambiguateTypes.Environment.add 
586           (DisambiguateTypes.Id id) 
587           (uri,(fun _ _ _-> CicUtil.term_of_uri (UriManager.uri_of_string uri)))
588           status.aliases 
589       | GrafiteAst.Symbol_alias (symb, instance, desc) ->
590          DisambiguateTypes.Environment.add
591           (DisambiguateTypes.Symbol (symb,instance))
592           (DisambiguateChoices.lookup_symbol_by_dsc symb desc)
593           status.aliases
594       | GrafiteAst.Number_alias (instance,desc) ->
595          DisambiguateTypes.Environment.add
596           (DisambiguateTypes.Num instance)
597           (DisambiguateChoices.lookup_num_by_dsc desc) status.aliases
598      in
599       MatitaSync.set_proof_aliases status aliases
600   | GrafiteAst.Render _ -> assert false (* ZACK: to be removed *)
601   | GrafiteAst.Dump _ -> assert false   (* ZACK: to be removed *)
602   | GrafiteAst.Interpretation _
603   | GrafiteAst.Notation _ as stm ->
604       { status with moo_content_rev =
605         (GrafiteAstPp.pp_command stm ^ "\n") :: status.moo_content_rev }
606   | GrafiteAst.Obj (loc,obj) ->
607      let ext,name =
608       match obj with
609          Cic.Constant (name,_,_,_,_)
610        | Cic.CurrentProof (name,_,_,_,_,_) -> ".con",name
611        | Cic.InductiveDefinition (types,_,_,_) ->
612           ".ind",
613           (match types with (name,_,_,_)::_ -> name | _ -> assert false)
614        | _ -> assert false in
615      let uri = 
616        UriManager.uri_of_string (MatitaMisc.qualify status name ^ ext) 
617      in
618      let metasenv = MatitaMisc.get_proof_metasenv status in
619      match obj with
620      | Cic.CurrentProof (_,metasenv',bo,ty,_,_) ->
621          let name = UriManager.name_of_uri uri in
622          if not(CicPp.check name ty) then
623            MatitaLog.error ("Bad name: " ^ name);
624          if opts.do_heavy_checks then
625            begin
626              let dbd = MatitaDb.instance () in
627              let similar = MetadataQuery.match_term ~dbd ty in
628              let similar_len = List.length similar in
629              if similar_len> 30 then
630                (MatitaLog.message
631                  ("Duplicate check will compare your theorem with " ^ 
632                    string_of_int similar_len ^ 
633                    " theorems, this may take a while."));
634              let convertible =
635                List.filter (
636                  fun u ->
637                    let t = CicUtil.term_of_uri u in
638                    let ty',g = 
639                      CicTypeChecker.type_of_aux' 
640                        metasenv' [] t CicUniv.empty_ugraph
641                    in
642                    fst(CicReduction.are_convertible [] ty' ty g)) 
643                similar 
644              in
645              (match convertible with
646              | [] -> ()
647              | x::_ -> 
648                  MatitaLog.warn  
649                  ("Theorem already proved: " ^ UriManager.string_of_uri x ^ 
650                   "\nPlease use a variant."));
651            end;
652          assert (metasenv = metasenv');
653          let goalno =
654            match metasenv' with (goalno,_,_)::_ -> goalno | _ -> assert false 
655          in
656          let initial_proof = (Some uri, metasenv, bo, ty) in
657          { status with proof_status = Incomplete_proof (initial_proof,goalno)}
658      | _ ->
659          if metasenv <> [] then
660           command_error (
661             "metasenv not empty while giving a definition with body: " ^
662             CicMetaSubst.ppmetasenv metasenv []);
663          let status = MatitaSync.add_obj uri obj status in
664           match obj with
665              Cic.Constant _ -> status
666            | Cic.InductiveDefinition (_,_,_,attrs) ->
667               let status = generate_elimination_principles uri status in
668               let rec get_record_attrs =
669                function
670                   [] -> None
671                 | (`Class (`Record fields))::_ -> Some fields
672                 | _::tl -> get_record_attrs tl
673               in
674                (match get_record_attrs attrs with
675                    None -> status (* not a record *)
676                  | Some fields -> generate_projections uri fields status)
677            | Cic.CurrentProof _
678            | Cic.Variable _ -> assert false
679
680 let eval_executable opts status ex =
681   match ex with
682   | GrafiteAst.Tactical (_, tac) -> eval_tactical status tac
683   | GrafiteAst.Command (_, cmd) -> eval_command opts status cmd
684   | GrafiteAst.Macro (_, mac) -> 
685       command_error (sprintf "The macro %s can't be in a script" 
686         (GrafiteAstPp.pp_macro_ast mac))
687
688 let eval_comment status c = status
689             
690
691 let eval_ast 
692   ?(do_heavy_checks=false) ?(include_paths=[]) ?(clean_baseuri=true) status st 
693 =
694   let opts = {
695     do_heavy_checks = do_heavy_checks ; 
696     include_paths = include_paths;
697     clean_baseuri = clean_baseuri }
698   in
699   match st with
700   | GrafiteAst.Executable (_,ex) -> eval_executable opts status ex
701   | GrafiteAst.Comment (_,c) -> eval_comment status c
702
703 let eval_from_stream 
704   ?do_heavy_checks ?include_paths ?clean_baseuri status str cb 
705 =
706   try
707     while true do
708       let ast = GrafiteParser.parse_statement str in
709       cb !status ast;
710       status := eval_ast ?do_heavy_checks ?include_paths ?clean_baseuri !status ast
711     done
712   with End_of_file -> ()
713
714 (* to avoid a long list of recursive functions *)
715 let _ = eval_from_stream_ref := eval_from_stream
716   
717 let eval_from_stream_greedy 
718   ?do_heavy_checks ?include_paths ?clean_baseuri status str cb 
719 =
720   while true do
721     print_string "matita> ";
722     flush stdout;
723     let ast = GrafiteParser.parse_statement str in
724     cb !status ast;
725     status := eval_ast ?do_heavy_checks ?include_paths ?clean_baseuri !status ast 
726   done
727 ;;
728
729 let eval_string ?do_heavy_checks ?include_paths ?clean_baseuri status str =
730   eval_from_stream 
731     ?do_heavy_checks ?include_paths ?clean_baseuri status (Stream.of_string str) (fun _ _ ->())
732
733 let default_options () =
734 (*
735   let options =
736     StringMap.add "baseuri"
737       (String
738         (Helm_registry.get "matita.baseuri" ^ Helm_registry.get "matita.owner"))
739       no_options
740   in
741 *)
742   let options =
743     StringMap.add "basedir"
744       (String (Helm_registry.get "matita.basedir"))
745       no_options
746   in
747   options
748
749 let initial_status =
750   lazy {
751     aliases = DisambiguateTypes.empty_environment;
752     moo_content_rev = [];
753     proof_status = No_proof;
754     options = default_options ();
755     objects = [];
756     notation_ids = [];
757   }
758