]> matita.cs.unibo.it Git - helm.git/blob - matita/components/grafite_engine/grafiteEngine.ml
Sys.Break no longer catched
[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 None [] [] [] ("",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 (*
279 module EmptyC = 
280   struct
281     let metasenv = []
282     let subst = []
283     let context = []
284   end
285 *)
286
287 let index_eq print uri (status:#NCic.status) =
288   let eq_status = status#eq_cache in
289   let eq_status,clause = NCicParamod.index_obj status eq_status uri in
290   if print then
291    ((*let module NCicBlob =
292     struct
293      include NCicBlob.NCicBlob(EmptyC)
294      let pp t = status#ppterm ~metasenv:[] ~subst:[] ~context:[] t
295     end in
296    let module Pp = Pp.Pp(NCicBlob) in*)
297    (match clause with
298      | Some (*clause*) (_,Terms.Equation (_,_,_,o),_,_) ->
299         HLog.debug ("Indexed with orientation: " ^ Pp.string_of_comparison o);
300         (*HLog.debug ("Indexed as:" ^ Pp.pp_unit_clause clause)*)
301      | _ -> HLog.debug "Not indexed (i.e. pruned)")) ;
302   status#set_eq_cache eq_status
303 ;;
304
305 let record_index_eq =
306  let basic_index_eq uri
307    ~refresh_uri_in_universe ~refresh_uri_in_term ~refresh_uri_in_reference 
308    ~alias_only status
309    = if not alias_only then index_eq false (NCicLibrary.refresh_uri uri) status 
310      else
311       status
312  in
313   GrafiteTypes.Serializer.register#run "index_eq" basic_index_eq
314 ;;
315
316 let index_eq_for_auto status uri =
317  if NnAuto.is_a_fact_obj status uri then
318    let newstatus = index_eq true uri status in
319      if newstatus#eq_cache == status#eq_cache then status 
320      else
321        ((*prerr_endline ("recording " ^ (NUri.string_of_uri uri));*)
322         NCicLibrary.dump_obj newstatus (record_index_eq uri))
323  else 
324    ((*prerr_endline "Not a fact";*)
325    status)
326 ;; 
327
328 let inject_constraint =
329  let basic_eval_add_constraint (u1,u2) 
330      ~refresh_uri_in_universe ~refresh_uri_in_term ~refresh_uri_in_reference
331      ~alias_only status
332  =
333   if not alias_only then
334    let u1 = refresh_uri_in_universe u1 in 
335    let u2 = refresh_uri_in_universe u2 in 
336     (* NCicLibrary.add_constraint adds the constraint to the NCicEnvironment
337      * and also to the storage (for undo/redo). During inclusion of compiled
338      * files the storage must not be touched. *)
339     NCicEnvironment.add_lt_constraint u1 u2;
340     status
341   else
342    status
343  in
344   GrafiteTypes.Serializer.register#run "constraints" basic_eval_add_constraint 
345 ;;
346
347 let eval_add_constraint status u1 u2 = 
348  let status = NCicLibrary.add_constraint status u1 u2 in
349   NCicLibrary.dump_obj status (inject_constraint (u1,u2))
350 ;;
351
352 let eval_ng_tac tac =
353  let rec aux f (text, prefix_len, tac) =
354   match tac with
355   | GrafiteAst.NApply (_loc, t) -> NTactics.apply_tac (text,prefix_len,t) 
356   | GrafiteAst.NSmartApply (_loc, t) -> 
357       NnAuto.smart_apply_tac (text,prefix_len,t) 
358   | GrafiteAst.NAssert (_loc, seqs) ->
359      NTactics.assert_tac
360       ((List.map
361         (function (hyps,concl) ->
362           List.map
363            (function
364               (id,`Decl t) -> id,`Decl (text,prefix_len,t)
365              |(id,`Def (b,t))->id,`Def((text,prefix_len,b),(text,prefix_len,t))
366            ) hyps,
367           (text,prefix_len,concl))
368        ) seqs)
369   | GrafiteAst.NAuto (_loc, (None,a)) -> 
370       NnAuto.auto_tac ~params:(None,a) ?trace_ref:None
371   | GrafiteAst.NAuto (_loc, (Some l,a)) ->
372       NnAuto.auto_tac
373         ~params:(Some List.map (fun x -> "",0,x) l,a) ?trace_ref:None
374   | GrafiteAst.NBranch _ -> NTactics.branch_tac ~force:false
375   | GrafiteAst.NCases (_loc, what, where) ->
376       NTactics.cases_tac 
377         ~what:(text,prefix_len,what)
378         ~where:(text,prefix_len,where)
379   | GrafiteAst.NCase1 (_loc,n) -> NTactics.case1_tac n
380   | GrafiteAst.NChange (_loc, pat, ww) -> 
381       NTactics.change_tac 
382        ~where:(text,prefix_len,pat) ~with_what:(text,prefix_len,ww) 
383   | GrafiteAst.NConstructor (_loc,num,args) -> 
384      NTactics.constructor_tac 
385        ?num ~args:(List.map (fun x -> text,prefix_len,x) args)
386   | GrafiteAst.NCut (_loc, t) -> NTactics.cut_tac (text,prefix_len,t) 
387 (*| GrafiteAst.NDiscriminate (_,what) -> NDestructTac.discriminate_tac ~what:(text,prefix_len,what)
388   | GrafiteAst.NSubst (_,what) -> NDestructTac.subst_tac ~what:(text,prefix_len,what)*)
389   | GrafiteAst.NClear (_loc, l) -> NTactics.clear_tac l
390   | GrafiteAst.NDestruct (_,dom,skip) -> NDestructTac.destruct_tac dom skip
391   | GrafiteAst.NDot _ -> NTactics.dot_tac 
392   | GrafiteAst.NElim (_loc, what, where) ->
393       NTactics.elim_tac 
394         ~what:(text,prefix_len,what)
395         ~where:(text,prefix_len,where)
396   | GrafiteAst.NFocus (_,l) -> NTactics.focus_tac l
397   | GrafiteAst.NGeneralize (_loc, where) -> 
398       NTactics.generalize_tac ~where:(text,prefix_len,where)
399   | GrafiteAst.NId _ -> (fun x -> x)
400   | GrafiteAst.NIntro (_loc,n) -> NTactics.intro_tac n
401   | GrafiteAst.NIntros (_loc,ns) -> NTactics.intros_tac ns
402   | GrafiteAst.NInversion (_loc, what, where) ->
403       NTactics.inversion_tac 
404         ~what:(text,prefix_len,what)
405         ~where:(text,prefix_len,where)
406   | GrafiteAst.NLApply (_loc, t) -> NTactics.lapply_tac (text,prefix_len,t) 
407   | GrafiteAst.NLetIn (_loc,where,what,name) ->
408       NTactics.letin_tac ~where:(text,prefix_len,where) 
409         ~what:(text,prefix_len,what) name
410   | GrafiteAst.NMerge _ -> NTactics.merge_tac 
411   | GrafiteAst.NPos (_,l) -> NTactics.pos_tac l
412   | GrafiteAst.NPosbyname (_,s) -> NTactics.case_tac s
413   | GrafiteAst.NReduce (_loc, reduction, where) ->
414       NTactics.reduce_tac ~reduction ~where:(text,prefix_len,where)
415   | GrafiteAst.NRewrite (_loc,dir,what,where) ->
416      NTactics.rewrite_tac ~dir ~what:(text,prefix_len,what)
417       ~where:(text,prefix_len,where)
418   | GrafiteAst.NSemicolon _ -> fun x -> x
419   | GrafiteAst.NShift _ -> NTactics.shift_tac 
420   | GrafiteAst.NSkip _ -> NTactics.skip_tac
421   | GrafiteAst.NUnfocus _ -> NTactics.unfocus_tac
422   | GrafiteAst.NWildcard _ -> NTactics.wildcard_tac 
423   | GrafiteAst.NTry (_,tac) -> NTactics.try_tac
424       (f f (text, prefix_len, tac))
425   | GrafiteAst.NAssumption _ -> NTactics.assumption_tac
426   | GrafiteAst.NBlock (_,l) -> 
427       NTactics.block_tac (List.map (fun x -> aux f (text,prefix_len,x)) l)
428   |GrafiteAst.NRepeat (_,tac) ->
429       NTactics.repeat_tac (f f (text, prefix_len, tac))
430  in
431   aux aux tac (* trick for non uniform recursion call *)
432 ;;
433       
434 let subst_metasenv_and_fix_names status =
435   let u,h,metasenv, subst,o = status#obj in
436   let o = 
437     NCicUntrusted.map_obj_kind ~skip_body:true 
438      (NCicUntrusted.apply_subst status subst []) o
439   in
440    status#set_obj(u,h,NCicUntrusted.apply_subst_metasenv status subst metasenv,subst,o)
441 ;;
442
443 let is_proof_irrelevant status context ty =
444   match
445     NCicReduction.whd status ~subst:[] context
446      (NCicTypeChecker.typeof status ~subst:[] ~metasenv:[] context ty)
447   with
448      NCic.Sort NCic.Prop -> true
449    | NCic.Sort _ -> false
450    | _ -> assert false
451 ;;
452
453 let rec relevance_of status ?(context=[]) ty =
454  match NCicReduction.whd status ~subst:[] context ty with
455     NCic.Prod (n,s,t) ->
456      not (is_proof_irrelevant status context s) ::
457       relevance_of status ~context:((n,NCic.Decl s)::context) t
458   | _ -> []
459 ;;
460
461 let compute_relevance status uri =
462  function
463     NCic.Constant (_,name,bo,ty,attrs) ->
464      let relevance = relevance_of status ty in
465       NCic.Constant (relevance,name,bo,ty,attrs)
466   | NCic.Fixpoint (ind,funs,attrs) ->
467      let funs =
468        List.map
469        (fun (_,name,recno,ty,bo) ->
470          let relevance = relevance_of status ty in
471           relevance,name,recno,ty,bo
472         ) funs
473      in
474       NCic.Fixpoint (ind,funs,attrs)
475   | NCic.Inductive (ind,leftno,tys,attrs) ->
476      let context =
477       List.rev_map (fun (_,name,arity,_) -> name,NCic.Decl arity) tys in
478      let tysno = List.length tys in
479      let tys =
480        List.map
481         (fun (_,name,arity,cons) ->
482          let relevance = relevance_of status arity in
483          let cons =
484           List.map
485            (fun (_,name,ty) ->
486              let dety =
487                NCicTypeChecker.debruijn status uri tysno ~subst:[] [] ty in
488              let relevance = relevance_of status ~context dety in
489               relevance,name,ty
490            ) cons
491          in
492           (relevance,name,arity,cons)
493         ) tys
494      in
495       NCic.Inductive (ind,leftno,tys,attrs)
496 ;;
497
498
499 let rec eval_ncommand ~include_paths opts status (text,prefix_len,cmd) =
500   match cmd with
501   | GrafiteAst.Include (loc, mode, fname) ->
502      let _root, baseuri, fullpath, _rrelpath = 
503        Librarian.baseuri_of_script ~include_paths fname in
504      let baseuri = NUri.uri_of_string baseuri in
505      (* MATITA 1.0: keep WithoutPreferences? *)
506      let alias_only = (mode = GrafiteAst.OnlyPreferences) in
507       GrafiteTypes.Serializer.require
508        ~alias_only ~baseuri ~fname:fullpath status
509   | GrafiteAst.UnificationHint (loc, t, n) -> eval_unification_hint status t n
510   | GrafiteAst.NCoercion (loc, name, compose, None) ->
511      let status, t, ty, source, target =
512        let o_t = NotationPt.Ident (name,None) in
513        let metasenv,subst, status,t =
514          GrafiteDisambiguate.disambiguate_nterm 
515            status None [] [] [] ("",0,o_t) in
516        assert( metasenv = [] && subst = []);
517        let ty = NCicTypeChecker.typeof status [] [] [] t in
518        let source, target =
519          let clean = function
520            | NCic.Appl (NCic.Const _ as r :: l) -> 
521                NotationPt.Appl (NotationPt.NCic r ::
522                  List.map (fun _ -> NotationPt.Implicit `JustOne)l)
523            | NCic.Const _ as r -> NotationPt.NCic r
524            | NCic.Sort _ as r -> NotationPt.NCic r (* FG: missing case *)
525            | _ -> assert false
526          in
527          let rec aux = function
528            | NCic.Prod (_,_, (NCic.Prod _ as rest)) -> aux rest
529            | NCic.Prod (name, src, tgt) -> (name, clean src), clean tgt
530            | _ -> assert false
531          in
532          aux ty
533        in
534        status, o_t, NotationPt.NCic ty, source, target
535      in
536      let status, composites =
537       NCicCoercDeclaration.eval_ncoercion status name compose t ty source
538        target
539      in
540      let mode = GrafiteAst.WithPreferences in (* MATITA 1.0: fixme *)
541      let aliases = GrafiteDisambiguate.aliases_for_objs status composites in
542       eval_alias status (mode,aliases)
543   | GrafiteAst.NCoercion (loc, name, compose, Some (t, ty, source, target)) ->
544      let status, composites =
545       NCicCoercDeclaration.eval_ncoercion status name compose t ty source
546        target in
547      let mode = GrafiteAst.WithPreferences in (* MATITA 1.0: fixme *)
548      let aliases = GrafiteDisambiguate.aliases_for_objs status composites in
549       eval_alias status (mode,aliases)
550   | GrafiteAst.NQed (loc,index) ->
551      if status#ng_mode <> `ProofMode then
552       raise (GrafiteTypes.Command_error "Not in proof mode")
553      else
554       let uri,height,menv,subst,obj_kind = status#obj in
555        if menv <> [] then
556         raise
557          (GrafiteTypes.Command_error"You can't Qed an incomplete theorem")
558        else
559         let obj_kind =
560          NCicUntrusted.map_obj_kind 
561           (NCicUntrusted.apply_subst status subst []) obj_kind in
562         let height = NCicTypeChecker.height_of_obj_kind status uri [] obj_kind in
563         (* fix the height inside the object *)
564         let rec fix () = function 
565           | NCic.Const (NReference.Ref (u,spec)) when NUri.eq u uri -> 
566              NCic.Const (NReference.reference_of_spec u
567               (match spec with
568               | NReference.Def _ -> NReference.Def height
569               | NReference.Fix (i,j,_) -> NReference.Fix(i,j,height)
570               | NReference.CoFix i -> NReference.CoFix i
571               | NReference.Ind _ | NReference.Con _
572               | NReference.Decl as s -> s))
573           | t -> NCicUtils.map status (fun _ () -> ()) () fix t
574         in
575         let obj_kind = 
576           match obj_kind with
577           | NCic.Fixpoint _ -> 
578               NCicUntrusted.map_obj_kind (fix ()) obj_kind 
579           | _ -> obj_kind
580         in
581         let obj_kind = compute_relevance status uri obj_kind in
582         let obj = uri,height,[],[],obj_kind in
583         let old_status = status in
584         let status = NCicLibrary.add_obj status obj in
585        (try
586         let index_obj = index &&
587          match obj_kind with
588             NCic.Constant (_,_,_,_,(_,`Example,_))
589           | NCic.Fixpoint (_,_,(_,`Example,_)) -> false
590           | _ -> true
591         in
592         let status =
593          if index_obj then
594           let status = index_obj_for_auto status obj in
595            (try index_eq_for_auto status uri
596            with
597               Sys.Break as exn -> raise exn
598             | _ -> status)
599          else
600           status in
601 (*
602           try 
603             index_eq uri status
604           with _ -> prerr_endline "got an exception"; status
605         in *)
606 (*         prerr_endline (status#ppobj obj); *)
607         HLog.message ("New object: " ^ NUri.string_of_uri uri);
608        (*prerr_endline (status#ppobj obj);*)
609            let boxml = NCicElim.mk_elims status obj in
610            let boxml = boxml @ NCicElim.mk_projections status obj in
611            let status = status#set_ng_mode `CommandMode in
612            let xxaliases = GrafiteDisambiguate.aliases_for_objs status [uri] in
613            let mode = GrafiteAst.WithPreferences in (* MATITA 1.0: fixme *)
614            let status = eval_alias status (mode,xxaliases) in
615            let status =
616             List.fold_left
617              (fun status boxml ->
618                try
619                 let nstatus =
620                  eval_ncommand ~include_paths opts status
621                   ("",0,GrafiteAst.NObj (HExtlib.dummy_floc,boxml,true))
622                 in
623                 if nstatus#ng_mode <> `CommandMode then
624                   begin
625                     (*HLog.warn "error in generating projection/eliminator";*)
626                     assert(status#ng_mode = `CommandMode);
627                     status
628                   end
629                 else
630                   nstatus
631                with
632                | MultiPassDisambiguator.DisambiguationError _
633                | NCicTypeChecker.TypeCheckerFailure _ ->
634                   (*HLog.warn "error in generating projection/eliminator";*)
635                   status
636              ) status boxml in             
637            let _,_,_,_,nobj = obj in 
638            let status = match nobj with
639                NCic.Inductive (is_ind,leftno,itl,_) ->
640                  List.fold_left (fun status it ->      
641                  (let _,ind_name,ty,cl = it in
642                   List.fold_left 
643                    (fun status outsort ->
644                       let status = status#set_ng_mode `ProofMode in
645                       try
646                        (let status,invobj =
647                          NInversion.mk_inverter 
648                           (ind_name ^ "_inv_" ^
649                             (snd (NCicElim.ast_of_sort outsort)))
650                           is_ind it leftno outsort status status#baseuri in
651                        let _,_,menv,_,_ = invobj in
652                         (match menv with
653                              [] -> eval_ncommand ~include_paths opts status
654                                     ("",0,GrafiteAst.NQed (Stdpp.dummy_loc,false))
655                            | _ -> status))
656                        (* XXX *)
657                       with
658                          Sys.Break as exn -> raise exn
659                        | _ -> (*HLog.warn "error in generating inversion principle"; *)
660                                 let status = status#set_ng_mode `CommandMode in status)
661                   status
662                   (NCic.Prop::
663                     List.map (fun s -> NCic.Type s)
664                     (NCicEnvironment.get_universes ())))) status itl
665               | _ -> status
666            in
667            let status = match nobj with
668                NCic.Inductive (is_ind,leftno,itl,_) ->
669                  (* first leibniz *)
670                  let status' = List.fold_left
671                    (fun status it ->
672                       let _,ind_name,ty,cl = it in
673                       let status = status#set_ng_mode `ProofMode in
674                       try
675                        (let status,invobj =
676                          NDestructTac.mk_discriminator ~use_jmeq:false
677                           (ind_name ^ "_discr")
678                           it leftno status status#baseuri in
679                        let _,_,menv,_,_ = invobj in
680                         (match menv with
681                              [] -> eval_ncommand ~include_paths opts status
682                                     ("",0,GrafiteAst.NQed(Stdpp.dummy_loc,false))
683                            | _ -> status))
684                        (* XXX *)
685                       with 
686                       | NDestructTac.ConstructorTooBig k -> 
687                           HLog.warn (Printf.sprintf 
688                            "unable to generate leibniz discrimination principle (constructor %s too big)"
689                            k);
690                            let status = status#set_ng_mode `CommandMode in status
691                       | _ -> (*HLog.warn "error in generating discrimination principle"; *)
692                                 let status = status#set_ng_mode `CommandMode in
693                                 status)
694                   status itl
695                 in
696                 (* then JMeq *)
697                 List.fold_left
698                    (fun status it ->
699                       let _,ind_name,ty,cl = it in
700                       let status = status#set_ng_mode `ProofMode in
701                       try
702                        (let status,invobj =
703                          NDestructTac.mk_discriminator ~use_jmeq:true
704                           (ind_name ^ "_jmdiscr")
705                           it leftno status status#baseuri in
706                        let _,_,menv,_,_ = invobj in
707                         (match menv with
708                              [] -> eval_ncommand ~include_paths opts status
709                                     ("",0,GrafiteAst.NQed(Stdpp.dummy_loc,false))
710                            | _ -> status))
711                        (* XXX *)
712                       with
713                          Sys.Break as exn -> raise exn
714                        | _ -> (*HLog.warn "error in generating discrimination principle"; *)
715                                 let status = status#set_ng_mode `CommandMode in
716                                 status)
717                   status' itl
718               | _ -> status
719            in
720            let coercions =
721             match obj with
722               _,_,_,_,NCic.Inductive
723                (true,leftno,[_,_,_,[_,_,_]],(_,`Record fields))
724                ->
725                 HExtlib.filter_map
726                  (fun (name,is_coercion,arity) ->
727                    if is_coercion then Some(name,leftno,arity) else None) fields
728             | _ -> [] in
729            let status =
730             List.fold_left
731              (fun status (name,cpos,arity) ->
732                try
733                  let metasenv,subst,status,t =
734                   GrafiteDisambiguate.disambiguate_nterm status None [] [] []
735                    ("",0,NotationPt.Ident (name,None)) in
736                  assert (metasenv = [] && subst = []);
737                  let status, nuris = 
738                    NCicCoercDeclaration.
739                      basic_eval_and_record_ncoercion_from_t_cpos_arity 
740                       status (name,true,t,cpos,arity) in
741                  let aliases = GrafiteDisambiguate.aliases_for_objs status nuris in
742                   eval_alias status (mode,aliases)
743                with MultiPassDisambiguator.DisambiguationError _-> 
744                  HLog.warn ("error in generating coercion: "^name);
745                  status) 
746              status coercions
747            in
748             status
749           with
750            exn ->
751             NCicLibrary.time_travel old_status;
752             raise exn)
753   | GrafiteAst.NCopy (log,tgt,src_uri, map) ->
754      if status#ng_mode <> `CommandMode then
755       raise (GrafiteTypes.Command_error "Not in command mode")
756      else
757        let tgt_uri_ext, old_ok = 
758          match NCicEnvironment.get_checked_obj status src_uri with
759          | _,_,[],[], (NCic.Inductive _ as ok) -> ".ind", ok
760          | _,_,[],[], (NCic.Fixpoint _ as ok) -> ".con", ok
761          | _,_,[],[], (NCic.Constant _ as ok) -> ".con", ok
762          | _ -> assert false
763        in
764        let tgt_uri = NUri.uri_of_string (status#baseuri^"/"^tgt^tgt_uri_ext) in
765        let map = (src_uri, tgt_uri) :: map in
766        let ok = 
767          let rec subst () = function
768            | NCic.Meta _ -> assert false
769            | NCic.Const (NReference.Ref (u,spec)) as t ->
770                (try NCic.Const 
771                  (NReference.reference_of_spec (List.assoc u map)spec)
772                with Not_found -> t)
773            | t -> NCicUtils.map status (fun _ _ -> ()) () subst t
774          in
775          NCicUntrusted.map_obj_kind ~skip_body:false (subst ()) old_ok
776        in
777        let ninitial_stack = Continuationals.Stack.of_nmetasenv [] in
778        let status = status#set_obj (tgt_uri,0,[],[],ok) in
779        (*prerr_endline (status#ppobj (tgt_uri,0,[],[],ok));*)
780        let status = status#set_stack ninitial_stack in
781        let status = subst_metasenv_and_fix_names status in
782        let status = status#set_ng_mode `ProofMode in
783        eval_ncommand ~include_paths opts status ("",0,GrafiteAst.NQed(Stdpp.dummy_loc,false))
784   | GrafiteAst.NObj (loc,obj,index) ->
785      if status#ng_mode <> `CommandMode then
786       raise (GrafiteTypes.Command_error "Not in command mode")
787      else
788       let status,obj =
789        GrafiteDisambiguate.disambiguate_nobj status
790         ~baseuri:status#baseuri (text,prefix_len,obj) in
791       let uri,height,nmenv,nsubst,nobj = obj in
792       let ninitial_stack = Continuationals.Stack.of_nmetasenv nmenv in
793       let status = status#set_obj obj in
794       let status = status#set_stack ninitial_stack in
795       let status = subst_metasenv_and_fix_names status in
796       let status = status#set_ng_mode `ProofMode in
797       (match nmenv with
798           [] ->
799            eval_ncommand ~include_paths opts status
800              ("",0,GrafiteAst.NQed(Stdpp.dummy_loc,index))
801         | _ -> status)
802   | GrafiteAst.NDiscriminator (loc, indty) ->
803       if status#ng_mode <> `CommandMode then
804         raise (GrafiteTypes.Command_error "Not in command mode")
805       else
806         let status = status#set_ng_mode `ProofMode in
807         let metasenv,subst,status,indty =
808           GrafiteDisambiguate.disambiguate_nterm status None [] [] [] (text,prefix_len,indty) in
809         let indtyno, (_,_,tys,_,_),leftno = match indty with
810             NCic.Const ((NReference.Ref (_,NReference.Ind (_,indtyno,leftno))) as r) ->
811               indtyno, NCicEnvironment.get_checked_indtys status r, leftno
812           | _ -> prerr_endline ("engine: indty expected... (fix this error message)"); assert false in
813         let (_,ind_name,_,_ as it) = List.nth tys indtyno in
814         let status,obj =  
815           NDestructTac.mk_discriminator ~use_jmeq:true (ind_name ^ "_jmdiscr")
816            it leftno status status#baseuri in
817         let _,_,menv,_,_ = obj in
818           (match menv with
819                [] -> eval_ncommand ~include_paths opts status ("",0,GrafiteAst.NQed(Stdpp.dummy_loc,false))
820              | _ -> prerr_endline ("Discriminator: non empty metasenv");
821                     status)
822   | GrafiteAst.NInverter (loc, name, indty, selection, sort) ->
823      if status#ng_mode <> `CommandMode then
824       raise (GrafiteTypes.Command_error "Not in command mode")
825      else
826       let metasenv,subst,status,sort = match sort with
827         | None -> [],[],status,NCic.Sort NCic.Prop
828         | Some s ->
829            GrafiteDisambiguate.disambiguate_nterm status None [] [] []
830             (text,prefix_len,s) 
831       in
832       assert (metasenv = []);
833       let sort = NCicReduction.whd status ~subst [] sort in
834       let sort =
835        match sort with 
836           NCic.Sort s -> s
837         | _ ->
838            raise (Invalid_argument (Printf.sprintf
839             "ninverter: found target %s, which is not a sort"
840              (status#ppterm ~metasenv ~subst ~context:[] sort))) in
841       let status = status#set_ng_mode `ProofMode in
842       let metasenv,subst,status,indty =
843        GrafiteDisambiguate.disambiguate_nterm status None [] [] subst
844         (text,prefix_len,indty) in
845       let indtyno,(_,leftno,tys,_,_) =
846        match indty with
847           NCic.Const ((NReference.Ref (_,NReference.Ind (_,indtyno,_))) as r) ->
848            indtyno, NCicEnvironment.get_checked_indtys status r
849         | _ ->
850           prerr_endline ("engine: indty ="  ^ status#ppterm ~metasenv:[]
851            ~subst:[] ~context:[] indty);
852           assert false in
853       let it = List.nth tys indtyno in
854       let status,obj =
855        NInversion.mk_inverter name true it leftno ?selection sort 
856         status status#baseuri in
857       let _,_,menv,_,_ = obj in
858        (match menv with
859           [] ->
860             eval_ncommand ~include_paths opts status
861              ("",0,GrafiteAst.NQed(Stdpp.dummy_loc,false))
862         | _ -> assert false)
863   | GrafiteAst.NUnivConstraint (loc,u1,u2) ->
864       eval_add_constraint status [`Type,u1] [`Type,u2]
865   (* ex lexicon commands *)
866   | GrafiteAst.Interpretation (loc, dsc, (symbol, args), cic_appl_pattern) ->
867      let cic_appl_pattern =
868       GrafiteDisambiguate.disambiguate_cic_appl_pattern status args
869        cic_appl_pattern
870      in
871       eval_interpretation status (dsc,(symbol, args),cic_appl_pattern)
872   | GrafiteAst.Notation (loc, dir, l1, associativity, precedence, l2) ->
873       let l1 = 
874         CicNotationParser.check_l1_pattern
875          l1 (dir = Some `RightToLeft) precedence associativity
876       in
877       let status =
878         if dir <> Some `RightToLeft then eval_input_notation status (l1,l2)
879         else status
880       in
881        if dir <> Some `LeftToRight then eval_output_notation status (l1,l2)
882        else status
883   | GrafiteAst.Alias (loc, spec) -> 
884      let diff =
885       (*CSC: Warning: this code should be factorized with the corresponding
886              code in DisambiguatePp *)
887       match spec with
888       | GrafiteAst.Ident_alias (id,uri) -> 
889          [DisambiguateTypes.Id id,spec]
890       | GrafiteAst.Symbol_alias (symb, instance, desc) ->
891          [DisambiguateTypes.Symbol (symb,instance),spec]
892       | GrafiteAst.Number_alias (instance,desc) ->
893          [DisambiguateTypes.Num instance,spec]
894      in
895       let mode = GrafiteAst.WithPreferences in(*assert false in (* VEDI SOPRA *) MATITA 1.0*)
896        eval_alias status (mode,diff)
897 ;;
898
899 let eval_comment opts status (text,prefix_len,c) = status
900
901 let rec eval_executable ~include_paths opts status (text,prefix_len,ex) =
902   match ex with
903   | GrafiteAst.NTactic (_(*loc*), tacl) ->
904       if status#ng_mode <> `ProofMode then
905        raise (GrafiteTypes.Command_error "Not in proof mode")
906       else
907        let status =
908         List.fold_left 
909           (fun status tac ->
910             let status = eval_ng_tac (text,prefix_len,tac) status in
911             subst_metasenv_and_fix_names status)
912           status tacl
913        in
914         status
915   | GrafiteAst.NCommand (_, cmd) ->
916       eval_ncommand ~include_paths opts status (text,prefix_len,cmd)
917   | GrafiteAst.NMacro (loc, macro) ->
918      raise (NMacro (loc,macro))
919
920 and eval_ast ~include_paths ?(do_heavy_checks=false) status (text,prefix_len,st)
921 =
922   let opts = { do_heavy_checks = do_heavy_checks ; } in
923   match st with
924   | GrafiteAst.Executable (_,ex) ->
925      eval_executable ~include_paths opts status (text,prefix_len,ex)
926   | GrafiteAst.Comment (_,c) -> 
927       eval_comment opts status (text,prefix_len,c) 
928 ;;