]> matita.cs.unibo.it Git - helm.git/blob - matita/components/grafite_engine/grafiteEngine.ml
Partially restore the assume tactic
[helm.git] / matita / components / grafite_engine / grafiteEngine.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 (* $Id$ *)
27
28 (* mo file name, ma file name *)
29 exception NMacro of GrafiteAst.loc * GrafiteAst.nmacro
30
31 type 'a disambiguator_input = string * int * 'a
32
33 type options = { 
34   do_heavy_checks: bool ; 
35 }
36
37 let basic_eval_unification_hint (t,n) status =
38  NCicUnifHint.add_user_provided_hint status t n
39 ;;
40
41 let inject_unification_hint =
42  let basic_eval_unification_hint (t,n) 
43    ~refresh_uri_in_universe ~refresh_uri_in_term ~refresh_uri_in_reference
44    ~alias_only status
45  =
46   if not alias_only then
47    let t = refresh_uri_in_term (status :> NCic.status) t in
48     basic_eval_unification_hint (t,n) status
49   else
50    status
51  in
52   GrafiteTypes.Serializer.register#run "unification_hints"
53    basic_eval_unification_hint
54 ;;
55
56 let eval_unification_hint status t n = 
57  let metasenv,subst,status,t =
58   GrafiteDisambiguate.disambiguate_nterm status `XTSort [] [] [] ("",0,t) in
59  assert (metasenv=[]);
60  let t = NCicUntrusted.apply_subst status subst [] t in
61  let status = basic_eval_unification_hint (t,n) status in
62   NCicLibrary.dump_obj status (inject_unification_hint (t,n))
63 ;;
64
65 let basic_index_obj l (status:#NCic.status) =
66   status#set_auto_cache 
67     (List.fold_left
68       (fun t (ks,v) -> 
69          List.fold_left (fun t k ->
70            NDiscriminationTree.DiscriminationTree.index t k v)
71           t ks) 
72     status#auto_cache l) 
73 ;;     
74
75 let basic_eval_interpretation ~alias_only (dsc, (symbol, args), cic_appl_pattern) status =
76  let status =
77   if not alias_only then
78    Interpretations.add_interpretation status dsc (symbol, args) cic_appl_pattern
79   else
80    status
81  in
82  let mode = GrafiteAst.WithPreferences (*assert false*) in (* MATITA 1.0 VEDI SOTTO *)
83  let diff =
84   [DisambiguateTypes.Symbol (symbol, 0), GrafiteAst.Symbol_alias (symbol,0,dsc)]
85  in
86   GrafiteDisambiguate.set_proof_aliases status ~implicit_aliases:false mode diff
87 ;;
88
89 let inject_interpretation =
90  let basic_eval_interpretation (dsc, (symbol, args), cic_appl_pattern)
91    ~refresh_uri_in_universe ~refresh_uri_in_term ~refresh_uri_in_reference
92    ~alias_only
93  =
94   let rec refresh =
95    function
96       NotationPt.NRefPattern (NReference.Ref (uri,spec)) ->
97        NotationPt.NRefPattern
98         (NReference.reference_of_spec (NCicLibrary.refresh_uri uri) spec)
99     | NotationPt.VarPattern _
100     | NotationPt.ImplicitPattern as x -> x
101     | NotationPt.ApplPattern l -> NotationPt.ApplPattern (List.map refresh l)
102   in
103   let cic_appl_pattern = refresh cic_appl_pattern in
104    basic_eval_interpretation ~alias_only (dsc, (symbol, args), cic_appl_pattern)
105  in
106   GrafiteTypes.Serializer.register#run "interpretation"
107    basic_eval_interpretation
108 ;;
109
110 let eval_interpretation status data= 
111  let status = basic_eval_interpretation ~alias_only:false data status in
112   NCicLibrary.dump_obj status (inject_interpretation data)
113 ;;
114
115 let basic_eval_alias (mode,diff) status =
116   GrafiteDisambiguate.set_proof_aliases status ~implicit_aliases:false mode diff
117 ;;
118
119 let inject_alias =
120  let basic_eval_alias (mode,diff) ~refresh_uri_in_universe ~refresh_uri_in_term
121    ~refresh_uri_in_reference ~alias_only =
122    basic_eval_alias (mode,diff)
123  in
124   GrafiteTypes.Serializer.register#run "alias" basic_eval_alias
125 ;;
126
127 let eval_alias status data= 
128  let status = basic_eval_alias data status in
129   NCicLibrary.dump_obj status (inject_alias data)
130 ;;
131
132 let basic_eval_input_notation (l1,l2) status =
133   GrafiteParser.extend status l1 
134    (fun env loc ->
135      NotationPt.AttributedTerm
136       (`Loc loc,TermContentPres.instantiate_level2 status env l2)) 
137 ;;
138
139 let inject_input_notation =
140  let basic_eval_input_notation (l1,l2)
141   ~refresh_uri_in_universe ~refresh_uri_in_term ~refresh_uri_in_reference
142   ~alias_only status
143  =
144    if not alias_only then
145     let l1 =
146      CicNotationParser.refresh_uri_in_checked_l1_pattern
147       ~refresh_uri_in_term:(refresh_uri_in_term (status:>NCic.status))
148       ~refresh_uri_in_reference l1 in
149     let l2 = NotationUtil.refresh_uri_in_term
150       ~refresh_uri_in_term:(refresh_uri_in_term (status:>NCic.status))
151       ~refresh_uri_in_reference l2
152     in
153      basic_eval_input_notation (l1,l2) status
154    else
155     status
156  in
157   GrafiteTypes.Serializer.register#run "input_notation"
158    basic_eval_input_notation
159 ;;
160
161 let eval_input_notation status data= 
162  let status = basic_eval_input_notation data status in
163   NCicLibrary.dump_obj status (inject_input_notation data)
164 ;;
165
166 let basic_eval_output_notation (l1,l2) status =
167  TermContentPres.add_pretty_printer status l2 l1
168 ;;
169
170 let inject_output_notation =
171  let basic_eval_output_notation (l1,l2)
172   ~refresh_uri_in_universe ~refresh_uri_in_term ~refresh_uri_in_reference
173   ~alias_only status
174  =
175   if not alias_only then
176    let l1 =
177     CicNotationParser.refresh_uri_in_checked_l1_pattern
178      ~refresh_uri_in_term:(refresh_uri_in_term (status:>NCic.status))
179       ~refresh_uri_in_reference l1 in
180    let l2 = NotationUtil.refresh_uri_in_term
181      ~refresh_uri_in_term:(refresh_uri_in_term (status:>NCic.status))
182       ~refresh_uri_in_reference l2
183    in
184     basic_eval_output_notation (l1,l2) status
185   else
186    status
187  in
188   GrafiteTypes.Serializer.register#run "output_notation"
189    basic_eval_output_notation
190 ;;
191
192 let eval_output_notation status data= 
193  let status = basic_eval_output_notation data status in
194   NCicLibrary.dump_obj status (inject_output_notation data)
195 ;;
196
197 let record_index_obj = 
198  let aux l ~refresh_uri_in_universe 
199    ~refresh_uri_in_term ~refresh_uri_in_reference ~alias_only status
200  =
201   let refresh_uri_in_term = refresh_uri_in_term (status:>NCic.status) in
202   if not alias_only then
203     basic_index_obj
204       (List.map 
205         (fun ks,v -> List.map refresh_uri_in_term ks, refresh_uri_in_term v) 
206       l) status
207   else
208    status
209  in
210   GrafiteTypes.Serializer.register#run "index_obj" aux
211 ;;
212
213 let compute_keys status uri height kind = 
214  let mk_item ty spec =
215    let orig_ty = NTacStatus.mk_cic_term [] ty in
216    let status,keys = NnAuto.keys_of_type status orig_ty in
217    let keys =  
218      List.map 
219        (fun t -> 
220           snd (NTacStatus.term_of_cic_term status t (NTacStatus.ctx_of t)))
221        keys
222    in
223    keys,NCic.Const(NReference.reference_of_spec uri spec)
224  in
225  let data = 
226   match kind with
227   | NCic.Fixpoint (ind,ifl,_) -> 
228      HExtlib.list_mapi 
229        (fun (_,_,rno,ty,_) i -> 
230           if ind then mk_item ty (NReference.Fix (i,rno,height)) 
231           else mk_item ty (NReference.CoFix height)) ifl
232   | NCic.Inductive (b,lno,itl,_) -> 
233      HExtlib.list_mapi 
234        (fun (_,_,ty,_) i -> mk_item ty (NReference.Ind (b,i,lno))) itl 
235      @
236      List.map (fun ((_,_,ty),i,j) -> mk_item ty (NReference.Con (i,j+1,lno)))
237        (List.flatten (HExtlib.list_mapi 
238          (fun (_,_,_,cl) i -> HExtlib.list_mapi (fun x j-> x,i,j) cl)
239          itl))
240   | NCic.Constant (_,_,Some _, ty, _) -> 
241      [ mk_item ty (NReference.Def height) ]
242   | NCic.Constant (_,_,None, ty, _) ->
243      [ mk_item ty NReference.Decl ]
244  in
245   HExtlib.filter_map
246    (fun (keys, t) ->
247      let keys = List.filter
248        (function 
249          | (NCic.Meta _) 
250          | (NCic.Appl (NCic.Meta _::_)) -> false 
251          | _ -> true) 
252        keys
253      in
254      if keys <> [] then 
255       begin
256         HLog.debug ("Indexing:" ^ 
257           status#ppterm ~metasenv:[] ~subst:[] ~context:[] t);
258         HLog.debug ("With keys:" ^ String.concat "\n" (List.map (fun t ->
259           status#ppterm ~metasenv:[] ~subst:[] ~context:[] t) keys));
260         Some (keys,t) 
261       end
262      else 
263       begin
264         HLog.debug ("Not indexing:" ^ 
265           status#ppterm ~metasenv:[] ~subst:[] ~context:[] t);
266         None
267       end)
268     data
269 ;;
270
271 let index_obj_for_auto status (uri, height, _, _, kind) = 
272  (*prerr_endline (string_of_int height);*)
273   let data = compute_keys status uri height kind in
274   let status = basic_index_obj data status in
275    NCicLibrary.dump_obj status (record_index_obj data)
276 ;; 
277
278 let basic_extract_obj obj status =
279  try
280   ignore (Helm_registry.get "extract_haskell");
281   let status,(msg,infos) = NCicExtraction.haskell_of_obj status obj in
282    prerr_endline msg;
283    status,infos
284  with
285     Helm_registry.Key_not_found _ -> status,NCicExtraction.empty_info
286   | exn -> prerr_endline ("EXTRACTION FAILURE: " ^ Printexc.to_string exn); assert false
287 ;;
288
289 let basic_extract_ocaml_obj obj status =
290  try
291   let status  = OcamlExtraction.print_ocaml_of_obj status obj in
292   let infos,status = status#get_info in
293    status,infos
294  with
295   exn -> prerr_endline ("EXTRACTION FAILURE: " ^ Printexc.to_string exn); assert false
296 ;;
297
298 let inject_extract_obj =
299  let basic_extract_obj info
300    ~refresh_uri_in_universe ~refresh_uri_in_term ~refresh_uri_in_reference
301    ~alias_only status
302  =
303   let info= NCicExtraction.refresh_uri_in_info ~refresh_uri_in_reference info in
304    status#set_extraction_db
305     (NCicExtraction.register_infos status#extraction_db info)
306  in
307   GrafiteTypes.Serializer.register#run "extraction" basic_extract_obj
308 ;;
309
310 let inject_extract_ocaml_obj =
311  let basic_extract_ocaml_obj info
312    ~refresh_uri_in_universe ~refresh_uri_in_term ~refresh_uri_in_reference
313    ~alias_only status
314  =
315   let info= OcamlExtractionTable.refresh_uri_in_info ~refresh_uri_in_reference ~refresh_uri:NCicLibrary.refresh_uri info in
316    status#set_ocaml_extraction_db
317     (OcamlExtractionTable.register_infos status#ocaml_extraction_db info)
318  in
319   GrafiteTypes.Serializer.register#run "ocaml_extraction" basic_extract_ocaml_obj
320 ;;
321
322 let eval_extract_obj status obj = 
323  let status,infos = basic_extract_obj obj status in
324   NCicLibrary.dump_obj status (inject_extract_obj infos)
325 ;;
326
327 let eval_extract_ocaml_obj status obj = 
328  let status,infos = basic_extract_ocaml_obj obj status in
329   NCicLibrary.dump_obj status (inject_extract_ocaml_obj infos)
330 ;;
331
332 (*
333 module EmptyC = 
334   struct
335     let metasenv = []
336     let subst = []
337     let context = []
338   end
339 *)
340
341 let index_eq print uri (status:#NCic.status) =
342   let eq_status = status#eq_cache in
343   let eq_status,clause = NCicParamod.index_obj status eq_status uri in
344   if print then
345    ((*let module NCicBlob =
346     struct
347      include NCicBlob.NCicBlob(EmptyC)
348      let pp t = status#ppterm ~metasenv:[] ~subst:[] ~context:[] t
349     end in
350    let module Pp = Pp.Pp(NCicBlob) in*)
351    (match clause with
352      | Some (*clause*) (_,Terms.Equation (_,_,_,o),_,_) ->
353         HLog.debug ("Indexed with orientation: " ^ Pp.string_of_comparison o);
354         (*HLog.debug ("Indexed as:" ^ Pp.pp_unit_clause clause)*)
355      | _ -> HLog.debug "Not indexed (i.e. pruned)")) ;
356   status#set_eq_cache eq_status
357 ;;
358
359 let record_index_eq =
360  let basic_index_eq uri
361    ~refresh_uri_in_universe ~refresh_uri_in_term ~refresh_uri_in_reference 
362    ~alias_only status
363    = if not alias_only then index_eq false (NCicLibrary.refresh_uri uri) status 
364      else
365       status
366  in
367   GrafiteTypes.Serializer.register#run "index_eq" basic_index_eq
368 ;;
369
370 let index_eq_for_auto status uri =
371  if NnAuto.is_a_fact_obj status uri then
372    let newstatus = index_eq true uri status in
373      if newstatus#eq_cache == status#eq_cache then status 
374      else
375        ((*prerr_endline ("recording " ^ (NUri.string_of_uri uri));*)
376         NCicLibrary.dump_obj newstatus (record_index_eq uri))
377  else 
378    ((*prerr_endline "Not a fact";*)
379    status)
380 ;; 
381
382 let inject_constraint =
383  let basic_eval_add_constraint (acyclic,u1,u2) 
384      ~refresh_uri_in_universe ~refresh_uri_in_term ~refresh_uri_in_reference
385      ~alias_only status
386  =
387   if not alias_only then
388    let u1 = refresh_uri_in_universe u1 in 
389    let u2 = refresh_uri_in_universe u2 in 
390     (* NCicLibrary.add_constraint adds the constraint to the NCicEnvironment
391      * and also to the storage (for undo/redo). During inclusion of compiled
392      * files the storage must not be touched. *)
393     NCicEnvironment.add_lt_constraint acyclic u1 u2;
394     status
395   else
396    status
397  in
398   GrafiteTypes.Serializer.register#run "constraints" basic_eval_add_constraint 
399 ;;
400
401 let eval_add_constraint status acyclic u1 u2 = 
402  let status = NCicLibrary.add_constraint status acyclic u1 u2 in
403   NCicLibrary.dump_obj status (inject_constraint (acyclic,u1,u2))
404 ;;
405
406 let eval_ng_tac tac =
407  let rec aux f (text, prefix_len, tac) =
408   match tac with
409   | GrafiteAst.NApply (_loc, t) -> NTactics.apply_tac (text,prefix_len,t) 
410   | GrafiteAst.NSmartApply (_loc, t) -> 
411       NnAuto.smart_apply_tac (text,prefix_len,t) 
412   | GrafiteAst.NAssert (_loc, seqs) ->
413      NTactics.assert_tac
414       ((List.map
415         (function (hyps,concl) ->
416           List.map
417            (function
418               (id,`Decl t) -> id,`Decl (text,prefix_len,t)
419              |(id,`Def (b,t))->id,`Def((text,prefix_len,b),(text,prefix_len,t))
420            ) hyps,
421           (text,prefix_len,concl))
422        ) seqs)
423   | GrafiteAst.NAuto (_loc, (None,a)) -> 
424       NnAuto.auto_tac ~params:(None,a) ?trace_ref:None
425   | GrafiteAst.NAuto (_loc, (Some l,a)) ->
426       NnAuto.auto_tac
427         ~params:(Some List.map (fun x -> "",0,x) l,a) ?trace_ref:None
428   | GrafiteAst.NBranch _ -> NTactics.branch_tac ~force:false
429   | GrafiteAst.NCases (_loc, what, where) ->
430       NTactics.cases_tac 
431         ~what:(text,prefix_len,what)
432         ~where:(text,prefix_len,where)
433   | GrafiteAst.NCase1 (_loc,n) -> NTactics.case1_tac n
434   | GrafiteAst.NChange (_loc, pat, ww) -> 
435       NTactics.change_tac 
436        ~where:(text,prefix_len,pat) ~with_what:(text,prefix_len,ww) 
437   | GrafiteAst.NConstructor (_loc,num,args) -> 
438      NTactics.constructor_tac 
439        ?num ~args:(List.map (fun x -> text,prefix_len,x) args)
440   | GrafiteAst.NCut (_loc, t) -> NTactics.cut_tac (text,prefix_len,t) 
441 (*| GrafiteAst.NDiscriminate (_,what) -> NDestructTac.discriminate_tac ~what:(text,prefix_len,what)
442   | GrafiteAst.NSubst (_,what) -> NDestructTac.subst_tac ~what:(text,prefix_len,what)*)
443   | GrafiteAst.NClear (_loc, l) -> NTactics.clear_tac l
444   | GrafiteAst.NDestruct (_,dom,skip) -> NDestructTac.destruct_tac dom skip
445   | GrafiteAst.NDot _ -> NTactics.dot_tac 
446   | GrafiteAst.NElim (_loc, what, where) ->
447       NTactics.elim_tac 
448         ~what:(text,prefix_len,what)
449         ~where:(text,prefix_len,where)
450   | GrafiteAst.NFocus (_,l) -> NTactics.focus_tac l
451   | GrafiteAst.NGeneralize (_loc, where) -> 
452       NTactics.generalize_tac ~where:(text,prefix_len,where)
453   | GrafiteAst.NId _ -> (fun x -> x)
454   | GrafiteAst.NIntro (_loc,n) -> NTactics.intro_tac n
455   | GrafiteAst.NIntros (_loc,ns) -> NTactics.intros_tac ns
456   | GrafiteAst.NInversion (_loc, what, where) ->
457       NTactics.inversion_tac 
458         ~what:(text,prefix_len,what)
459         ~where:(text,prefix_len,where)
460   | GrafiteAst.NLApply (_loc, t) -> NTactics.lapply_tac (text,prefix_len,t) 
461   | GrafiteAst.NLetIn (_loc,where,what,name) ->
462       NTactics.letin_tac ~where:(text,prefix_len,where) 
463         ~what:(text,prefix_len,what) name
464   | GrafiteAst.NMerge _ -> NTactics.merge_tac 
465   | GrafiteAst.NPos (_,l) -> NTactics.pos_tac l
466   | GrafiteAst.NPosbyname (_,s) -> NTactics.case_tac s
467   | GrafiteAst.NReduce (_loc, reduction, where) ->
468       NTactics.reduce_tac ~reduction ~where:(text,prefix_len,where)
469   | GrafiteAst.NRewrite (_loc,dir,what,where) ->
470      NTactics.rewrite_tac ~dir ~what:(text,prefix_len,what)
471       ~where:(text,prefix_len,where)
472   | GrafiteAst.NSemicolon _ -> fun x -> x
473   | GrafiteAst.NShift _ -> NTactics.shift_tac 
474   | GrafiteAst.NSkip _ -> NTactics.skip_tac
475   | GrafiteAst.NUnfocus _ -> NTactics.unfocus_tac
476   | GrafiteAst.NWildcard _ -> NTactics.wildcard_tac 
477   | GrafiteAst.NTry (_,tac) -> NTactics.try_tac
478       (f f (text, prefix_len, tac))
479   | GrafiteAst.NAssumption _ -> NTactics.assumption_tac
480   | GrafiteAst.NBlock (_,l) -> 
481       NTactics.block_tac (List.map (fun x -> aux f (text,prefix_len,x)) l)
482   |GrafiteAst.NRepeat (_,tac) ->
483       NTactics.repeat_tac (f f (text, prefix_len, tac))
484   |GrafiteAst.Assume (_,id,t) -> Declarative.assume id t
485  in
486   aux aux tac (* trick for non uniform recursion call *)
487 ;;
488       
489 let subst_metasenv_and_fix_names status =
490   let u,h,metasenv, subst,o = status#obj in
491   let o = 
492     NCicUntrusted.map_obj_kind ~skip_body:true 
493      (NCicUntrusted.apply_subst status subst []) o
494   in
495    status#set_obj(u,h,NCicUntrusted.apply_subst_metasenv status subst metasenv,subst,o)
496 ;;
497
498 let is_proof_irrelevant status context ty =
499   match
500     NCicReduction.whd status ~subst:[] context
501      (NCicTypeChecker.typeof status ~subst:[] ~metasenv:[] context ty)
502   with
503      NCic.Sort NCic.Prop -> true
504    | NCic.Sort _ -> false
505    | _ -> assert false
506 ;;
507
508 let rec relevance_of status ?(context=[]) ty =
509  match NCicReduction.whd status ~subst:[] context ty with
510     NCic.Prod (n,s,t) ->
511      not (is_proof_irrelevant status context s) ::
512       relevance_of status ~context:((n,NCic.Decl s)::context) t
513   | _ -> []
514 ;;
515
516 let compute_relevance status uri =
517  function
518     NCic.Constant (_,name,bo,ty,attrs) ->
519      let relevance = relevance_of status ty in
520       NCic.Constant (relevance,name,bo,ty,attrs)
521   | NCic.Fixpoint (ind,funs,attrs) ->
522      let funs =
523        List.map
524        (fun (_,name,recno,ty,bo) ->
525          let relevance = relevance_of status ty in
526           relevance,name,recno,ty,bo
527         ) funs
528      in
529       NCic.Fixpoint (ind,funs,attrs)
530   | NCic.Inductive (ind,leftno,tys,attrs) ->
531      let context =
532       List.rev_map (fun (_,name,arity,_) -> name,NCic.Decl arity) tys in
533      let tysno = List.length tys in
534      let tys =
535        List.map
536         (fun (_,name,arity,cons) ->
537          let relevance = relevance_of status arity in
538          let cons =
539           List.map
540            (fun (_,name,ty) ->
541              let dety =
542                NCicTypeChecker.debruijn status uri tysno ~subst:[] [] ty in
543              let relevance = relevance_of status ~context dety in
544               relevance,name,ty
545            ) cons
546          in
547           (relevance,name,arity,cons)
548         ) tys
549      in
550       NCic.Inductive (ind,leftno,tys,attrs)
551 ;;
552
553 let extract_uris status uris =
554  List.fold_left
555   (fun status uri ->
556     let obj = NCicEnvironment.get_checked_obj status uri in
557      let status = eval_extract_obj status obj in
558       eval_extract_ocaml_obj status obj
559   ) status uris
560 ;;
561
562 let rec eval_ncommand ~include_paths opts status (text,prefix_len,cmd) =
563   match cmd with
564   | GrafiteAst.Include (loc, mode, fname) ->
565      let _root, baseuri, fullpath, _rrelpath = 
566        Librarian.baseuri_of_script ~include_paths fname in
567      let baseuri = NUri.uri_of_string baseuri in
568      (* MATITA 1.0: keep WithoutPreferences? *)
569      let alias_only = (mode = GrafiteAst.OnlyPreferences) in
570      let status =
571       GrafiteTypes.Serializer.require
572        ~alias_only ~baseuri ~fname:fullpath status in
573      OcamlExtraction.print_open status
574       (NCicLibrary.get_transitively_included status)
575   | GrafiteAst.UnificationHint (loc, t, n) -> eval_unification_hint status t n
576   | GrafiteAst.NCoercion (loc, name, compose, None) ->
577      let status, t, ty, source, target =
578        let o_t = NotationPt.Ident (name,None) in
579        let metasenv,subst, status,t =
580          GrafiteDisambiguate.disambiguate_nterm 
581            status `XTNone [] [] [] ("",0,o_t) in
582        assert( metasenv = [] && subst = []);
583        let ty = NCicTypeChecker.typeof status [] [] [] t in
584        let source, target =
585          let clean = function
586            | NCic.Appl (NCic.Const _ as r :: l) -> 
587                NotationPt.Appl (NotationPt.NCic r ::
588                  List.map (fun _ -> NotationPt.Implicit `JustOne)l)
589            | NCic.Const _ as r -> NotationPt.NCic r
590            | NCic.Sort _ as r -> NotationPt.NCic r (* FG: missing case *)
591            | _ -> assert false
592          in
593          let rec aux = function
594            | NCic.Prod (_,_, (NCic.Prod _ as rest)) -> aux rest
595            | NCic.Prod (name, src, tgt) -> (name, clean src), clean tgt
596            | _ -> assert false
597          in
598          aux ty
599        in
600        status, o_t, NotationPt.NCic ty, source, target
601      in
602       let cmd = 
603        GrafiteAst.NCoercion (loc, name, compose, Some (t, ty, source, target))
604       in
605       eval_ncommand ~include_paths opts status (text,prefix_len,cmd)
606   | GrafiteAst.NCoercion (loc, name, compose, Some (t, ty, source, target)) ->
607      let status, composites =
608       NCicCoercDeclaration.eval_ncoercion status name compose t ty source
609        target in
610      let status = extract_uris status composites in
611      let mode = GrafiteAst.WithPreferences in (* MATITA 1.0: fixme *)
612      let aliases = GrafiteDisambiguate.aliases_for_objs status composites in
613       eval_alias status (mode,aliases)
614   | GrafiteAst.NQed (loc,index) ->
615      if status#ng_mode <> `ProofMode then
616       raise (GrafiteTypes.Command_error "Not in proof mode")
617      else
618       let uri,height,menv,subst,obj_kind = status#obj in
619        if menv <> [] then
620         raise
621          (GrafiteTypes.Command_error"You can't Qed an incomplete theorem")
622        else
623         let obj_kind =
624          NCicUntrusted.map_obj_kind 
625           (NCicUntrusted.apply_subst status subst []) obj_kind in
626         let height = NCicTypeChecker.height_of_obj_kind status uri [] obj_kind in
627         (* fix the height inside the object *)
628         let rec fix () = function 
629           | NCic.Const (NReference.Ref (u,spec)) when NUri.eq u uri -> 
630              NCic.Const (NReference.reference_of_spec u
631               (match spec with
632               | NReference.Def _ -> NReference.Def height
633               | NReference.Fix (i,j,_) -> NReference.Fix(i,j,height)
634               | NReference.CoFix i -> NReference.CoFix i
635               | NReference.Ind _ | NReference.Con _
636               | NReference.Decl as s -> s))
637           | t -> NCicUtils.map status (fun _ () -> ()) () fix t
638         in
639         let obj_kind = 
640           match obj_kind with
641           | NCic.Fixpoint _ -> 
642               NCicUntrusted.map_obj_kind (fix ()) obj_kind 
643           | _ -> obj_kind
644         in
645         let obj_kind = compute_relevance status uri obj_kind in
646         let obj = uri,height,[],[],obj_kind in
647         let old_status = status in
648         let status = NCicLibrary.add_obj status obj in
649         let status = eval_extract_obj status obj in
650         let status = eval_extract_ocaml_obj status obj in
651        (try
652         let index_obj = index &&
653          match obj_kind with
654             NCic.Constant (_,_,_,_,(_,`Example,_))
655           | NCic.Fixpoint (_,_,(_,`Example,_)) -> false
656           | _ -> true
657         in
658         let status =
659          if index_obj then
660           let status = index_obj_for_auto status obj in
661            (try index_eq_for_auto status uri
662            with
663               Sys.Break as exn -> raise exn
664             | _ -> status)
665          else
666           status in
667         (* purge tinycals stack *)
668         let ninitial_stack = Continuationals.Stack.of_nmetasenv [] in
669         let status = status#set_stack ninitial_stack in
670 (*
671           try 
672             index_eq uri status
673           with _ -> prerr_endline "got an exception"; status
674         in *)
675 (*         prerr_endline (status#ppobj obj); *)
676         HLog.message ("New object: " ^ NUri.string_of_uri uri);
677        (*prerr_endline (status#ppobj obj);*)
678            let boxml = NCicElim.mk_elims status obj in
679            let boxml = boxml @ NCicElim.mk_projections status obj in
680            let status = status#set_ng_mode `CommandMode in
681            let xxaliases = GrafiteDisambiguate.aliases_for_objs status [uri] in
682            let mode = GrafiteAst.WithPreferences in (* MATITA 1.0: fixme *)
683            let status = eval_alias status (mode,xxaliases) in
684            let status =
685             List.fold_left
686              (fun status boxml ->
687                try
688                 let nstatus =
689                  eval_ncommand ~include_paths opts status
690                   ("",0,GrafiteAst.NObj (HExtlib.dummy_floc,boxml,true))
691                 in
692                 if nstatus#ng_mode <> `CommandMode then
693                   begin
694                     (*HLog.warn "error in generating projection/eliminator";*)
695                     assert(status#ng_mode = `CommandMode);
696                     status
697                   end
698                 else
699                   nstatus
700                with
701                | MultiPassDisambiguator.DisambiguationError _ ->
702                   HLog.warn "error in disambiguating projection/eliminator";
703                   status
704                | NCicTypeChecker.TypeCheckerFailure _ ->
705                   HLog.warn "error in typechecking projection/eliminator";
706                   status
707              ) status boxml in             
708            let _,_,_,_,nobj = obj in
709            (* attempting to generate an inversion principle on the maximum
710             * universe can take a long time to fail: this code removes maximal
711             * sorts from the universe list *)
712            let universes = NCicEnvironment.get_universes () in
713            let max_univ = List.fold_left max [] universes in
714            let universes = 
715              List.filter (fun x -> NCicEnvironment.universe_lt x max_univ)
716                universes
717            in
718            let status = match nobj with
719                NCic.Inductive (is_ind,leftno,itl,_) ->
720                  List.fold_left (fun status it ->      
721                  (let _,ind_name,ty,cl = it in
722                   List.fold_left 
723                    (fun status outsort ->
724                       let status = status#set_ng_mode `ProofMode in
725                       try
726                        (let status,invobj =
727                          NInversion.mk_inverter 
728                           (ind_name ^ "_inv_" ^
729                             (snd (NCicElim.ast_of_sort outsort)))
730                           is_ind it leftno outsort status status#baseuri in
731                        let _,_,menv,_,_ = invobj in
732                         (match menv with
733                              [] -> eval_ncommand ~include_paths opts status
734                                     ("",0,GrafiteAst.NQed (Stdpp.dummy_loc,false))
735                            | _ -> status))
736                        (* XXX *)
737                       with
738                          Sys.Break as exn -> raise exn
739                        | _ -> (*HLog.warn "error in generating inversion principle"; *)
740                                 let status = status#set_ng_mode `CommandMode in status)
741                   status
742                   (NCic.Prop::
743                     List.map (fun s -> NCic.Type s) universes))) status itl
744               | _ -> status
745            in
746            let status = match nobj with
747                NCic.Inductive (is_ind,leftno,itl,_) ->
748                  (* first leibniz *)
749                  let status' = List.fold_left
750                    (fun status it ->
751                       let _,ind_name,ty,cl = it in
752                       let status = status#set_ng_mode `ProofMode in
753                       try
754                        (let status,invobj =
755                          NDestructTac.mk_discriminator ~use_jmeq:false
756                           (ind_name ^ "_discr")
757                           it leftno status status#baseuri in
758                        let _,_,menv,_,_ = invobj in
759                         (match menv with
760                              [] -> eval_ncommand ~include_paths opts status
761                                     ("",0,GrafiteAst.NQed(Stdpp.dummy_loc,false))
762                            | _ -> status))
763                        (* XXX *)
764                       with 
765                       | NDestructTac.ConstructorTooBig k -> 
766                           HLog.warn (Printf.sprintf 
767                            "unable to generate leibniz discrimination principle (constructor %s too big)"
768                            k);
769                            let status = status#set_ng_mode `CommandMode in status
770                       | _ -> (*HLog.warn "error in generating discrimination principle"; *)
771                                 let status = status#set_ng_mode `CommandMode in
772                                 status)
773                   status itl
774                 in
775                 (* then JMeq *)
776                 List.fold_left
777                    (fun status it ->
778                       let _,ind_name,ty,cl = it in
779                       let status = status#set_ng_mode `ProofMode in
780                       try
781                        (let status,invobj =
782                          NDestructTac.mk_discriminator ~use_jmeq:true
783                           (ind_name ^ "_jmdiscr")
784                           it leftno status status#baseuri in
785                        let _,_,menv,_,_ = invobj in
786                         (match menv with
787                              [] -> eval_ncommand ~include_paths opts status
788                                     ("",0,GrafiteAst.NQed(Stdpp.dummy_loc,false))
789                            | _ -> status))
790                        (* XXX *)
791                       with
792                          Sys.Break as exn -> raise exn
793                        | _ -> (*HLog.warn "error in generating discrimination principle"; *)
794                                 let status = status#set_ng_mode `CommandMode in
795                                 status)
796                   status' itl
797               | _ -> status
798            in
799            let coercions =
800             match obj with
801               _,_,_,_,NCic.Inductive
802                (true,leftno,[_,_,_,[_,_,_]],(_,`Record fields))
803                ->
804                 HExtlib.filter_map
805                  (fun (name,is_coercion,arity) ->
806                    if is_coercion then Some(name,leftno,arity) else None) fields
807             | _ -> [] in
808            let status =
809             List.fold_left
810              (fun status (name,cpos,arity) ->
811                try
812                  let metasenv,subst,status,t =
813                   GrafiteDisambiguate.disambiguate_nterm status `XTNone [] [] []
814                    ("",0,NotationPt.Ident (name,None)) in
815                  assert (metasenv = [] && subst = []);
816                  let status, nuris = 
817                    NCicCoercDeclaration.
818                      basic_eval_and_record_ncoercion_from_t_cpos_arity 
819                       status (name,true,t,cpos,arity) in
820                  let aliases = GrafiteDisambiguate.aliases_for_objs status nuris in
821                  let status = extract_uris status nuris in
822                   eval_alias status (mode,aliases)
823                with MultiPassDisambiguator.DisambiguationError _-> 
824                  HLog.warn ("error in generating coercion: "^name);
825                  status) 
826              status coercions
827            in
828             status
829           with
830            exn ->
831             NCicLibrary.time_travel old_status;
832             raise exn)
833   | GrafiteAst.NCopy (log,tgt,src_uri, map) ->
834      if status#ng_mode <> `CommandMode then
835       raise (GrafiteTypes.Command_error "Not in command mode")
836      else
837        let tgt_uri_ext, old_ok = 
838          match NCicEnvironment.get_checked_obj status src_uri with
839          | _,_,[],[], (NCic.Inductive _ as ok) -> ".ind", ok
840          | _,_,[],[], (NCic.Fixpoint _ as ok) -> ".con", ok
841          | _,_,[],[], (NCic.Constant _ as ok) -> ".con", ok
842          | _ -> assert false
843        in
844        let tgt_uri = NUri.uri_of_string (status#baseuri^"/"^tgt^tgt_uri_ext) in
845        let map = (src_uri, tgt_uri) :: map in
846        let ok = 
847          let rec subst () = function
848            | NCic.Meta _ -> assert false
849            | NCic.Const (NReference.Ref (u,spec)) as t ->
850                (try NCic.Const 
851                  (NReference.reference_of_spec (List.assoc u map)spec)
852                with Not_found -> t)
853            | t -> NCicUtils.map status (fun _ _ -> ()) () subst t
854          in
855          NCicUntrusted.map_obj_kind ~skip_body:false (subst ()) old_ok
856        in
857        let ninitial_stack = Continuationals.Stack.of_nmetasenv [] in
858        let status = status#set_obj (tgt_uri,0,[],[],ok) in
859        (*prerr_endline (status#ppobj (tgt_uri,0,[],[],ok));*)
860        let status = status#set_stack ninitial_stack in
861        let status = subst_metasenv_and_fix_names status in
862        let status = status#set_ng_mode `ProofMode in
863        eval_ncommand ~include_paths opts status ("",0,GrafiteAst.NQed(Stdpp.dummy_loc,false))
864   | GrafiteAst.NObj (loc,obj,index) ->
865      if status#ng_mode <> `CommandMode then
866       raise (GrafiteTypes.Command_error "Not in command mode")
867      else
868       let status,obj =
869        GrafiteDisambiguate.disambiguate_nobj status
870         ~baseuri:status#baseuri (text,prefix_len,obj) in
871       let uri,height,nmenv,nsubst,nobj = obj in
872       let ninitial_stack = Continuationals.Stack.of_nmetasenv nmenv in
873       let status = status#set_obj obj in
874       let status = status#set_stack ninitial_stack in
875       let status = subst_metasenv_and_fix_names status in
876       let status = status#set_ng_mode `ProofMode in
877       (match nmenv with
878           [] ->
879            eval_ncommand ~include_paths opts status
880              ("",0,GrafiteAst.NQed(Stdpp.dummy_loc,index))
881         | _ -> status)
882   | GrafiteAst.NDiscriminator (loc, indty) ->
883       if status#ng_mode <> `CommandMode then
884         raise (GrafiteTypes.Command_error "Not in command mode")
885       else
886         let status = status#set_ng_mode `ProofMode in
887         let metasenv,subst,status,indty =
888           GrafiteDisambiguate.disambiguate_nterm status `XTNone [] [] [] (text,prefix_len,indty) in
889         let indtyno, (_,_,tys,_,_),leftno = match indty with
890             NCic.Const ((NReference.Ref (_,NReference.Ind (_,indtyno,leftno))) as r) ->
891               indtyno, NCicEnvironment.get_checked_indtys status r, leftno
892           | _ -> prerr_endline ("engine: indty expected... (fix this error message)"); assert false in
893         let (_,ind_name,_,_ as it) = List.nth tys indtyno in
894         let status,obj =  
895           NDestructTac.mk_discriminator ~use_jmeq:true ~force:true (ind_name ^ "_jmdiscr")
896            it leftno status status#baseuri in
897         let _,_,menv,_,_ = obj in
898           (match menv with
899                [] -> eval_ncommand ~include_paths opts status ("",0,GrafiteAst.NQed(Stdpp.dummy_loc,false))
900              | _ -> prerr_endline ("Discriminator: non empty metasenv");
901                     status)
902   | GrafiteAst.NInverter (loc, name, indty, selection, sort) ->
903      if status#ng_mode <> `CommandMode then
904       raise (GrafiteTypes.Command_error "Not in command mode")
905      else
906       let metasenv,subst,status,sort = match sort with
907         | None -> [],[],status,NCic.Sort NCic.Prop
908         | Some s ->
909            GrafiteDisambiguate.disambiguate_nterm status `XTSort [] [] []
910             (text,prefix_len,s) 
911       in
912       assert (metasenv = []);
913       let sort = NCicReduction.whd status ~subst [] sort in
914       let sort =
915        match sort with 
916           NCic.Sort s -> s
917         | _ ->
918            raise (Invalid_argument (Printf.sprintf
919             "ninverter: found target %s, which is not a sort"
920              (status#ppterm ~metasenv ~subst ~context:[] sort))) in
921       let status = status#set_ng_mode `ProofMode in
922       let metasenv,subst,status,indty =
923        GrafiteDisambiguate.disambiguate_nterm status `XTNone [] [] subst
924         (text,prefix_len,indty) in
925       let indtyno,(_,leftno,tys,_,_) =
926        match indty with
927           NCic.Const ((NReference.Ref (_,NReference.Ind (_,indtyno,_))) as r) ->
928            indtyno, NCicEnvironment.get_checked_indtys status r
929         | _ ->
930           prerr_endline ("engine: indty ="  ^ status#ppterm ~metasenv:[]
931            ~subst:[] ~context:[] indty);
932           assert false in
933       let it = List.nth tys indtyno in
934       let status,obj =
935        NInversion.mk_inverter name true it leftno ?selection sort 
936         status status#baseuri in
937       let _,_,menv,_,_ = obj in
938        (match menv with
939           [] ->
940             eval_ncommand ~include_paths opts status
941              ("",0,GrafiteAst.NQed(Stdpp.dummy_loc,false))
942         | _ -> assert false)
943   | GrafiteAst.NUnivConstraint (loc,acyclic,u1,u2) ->
944       eval_add_constraint status acyclic [`Type,u1] [`Type,u2]
945   (* ex lexicon commands *)
946   | GrafiteAst.Interpretation (loc, dsc, (symbol, args), cic_appl_pattern) ->
947      let cic_appl_pattern =
948       GrafiteDisambiguate.disambiguate_cic_appl_pattern status args
949        cic_appl_pattern
950      in
951       eval_interpretation status (dsc,(symbol, args),cic_appl_pattern)
952   | GrafiteAst.Notation (loc, dir, l1, associativity, precedence, l2) ->
953       let l1 = 
954         CicNotationParser.check_l1_pattern
955          l1 (dir = Some `RightToLeft) precedence associativity
956       in
957       let status =
958         if dir <> Some `RightToLeft then eval_input_notation status (l1,l2)
959         else status
960       in
961        if dir <> Some `LeftToRight then eval_output_notation status (l1,l2)
962        else status
963   | GrafiteAst.Alias (loc, spec) -> 
964      let diff =
965       (*CSC: Warning: this code should be factorized with the corresponding
966              code in DisambiguatePp *)
967       match spec with
968       | GrafiteAst.Ident_alias (id,uri) -> 
969          [DisambiguateTypes.Id id,spec]
970       | GrafiteAst.Symbol_alias (symb, instance, desc) ->
971          [DisambiguateTypes.Symbol (symb,instance),spec]
972       | GrafiteAst.Number_alias (instance,desc) ->
973          [DisambiguateTypes.Num instance,spec]
974      in
975       let mode = GrafiteAst.WithPreferences in(*assert false in (* VEDI SOPRA *) MATITA 1.0*)
976        eval_alias status (mode,diff)
977 ;;
978
979 let eval_comment opts status (text,prefix_len,c) = status
980
981 let rec eval_executable ~include_paths opts status (text,prefix_len,ex) =
982   match ex with
983   | GrafiteAst.NTactic (_(*loc*), tacl) ->
984       if status#ng_mode <> `ProofMode then
985        raise (GrafiteTypes.Command_error "Not in proof mode")
986       else
987        let status =
988         List.fold_left 
989           (fun status tac ->
990             let time0 = Unix.gettimeofday () in
991             let status = eval_ng_tac (text,prefix_len,tac) status in
992             let time3 = Unix.gettimeofday () in
993             HLog.debug ("... eval_ng_tac done in " ^ string_of_float (time3 -. time0) ^ "s");
994             let status = subst_metasenv_and_fix_names status in
995             let time3 = Unix.gettimeofday () in
996             HLog.debug ("... subst_metasenv_and_fix_names done in " ^ string_of_float (time3 -. time0) ^ "s"); status)
997           status tacl
998        in
999         status
1000   | GrafiteAst.NCommand (_, cmd) ->
1001       eval_ncommand ~include_paths opts status (text,prefix_len,cmd)
1002   | GrafiteAst.NMacro (loc, macro) ->
1003      raise (NMacro (loc,macro))
1004
1005 and eval_ast ~include_paths ?(do_heavy_checks=false) status (text,prefix_len,st)
1006 =
1007   let opts = { do_heavy_checks = do_heavy_checks ; } in
1008   match st with
1009   | GrafiteAst.Executable (_,ex) ->
1010      eval_executable ~include_paths opts status (text,prefix_len,ex)
1011   | GrafiteAst.Comment (_,c) -> 
1012       eval_comment opts status (text,prefix_len,c) 
1013 ;;