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