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