]> matita.cs.unibo.it Git - helm.git/blob - matita/components/grafite_engine/grafiteEngine.ml
Implementation of proof irrelevance finished.
[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  =
45   let t = refresh_uri_in_term t in basic_eval_unification_hint (t,n)
46  in
47   GrafiteTypes.Serializer.register#run "unification_hints"
48    basic_eval_unification_hint
49 ;;
50
51 let eval_unification_hint status t n = 
52  let metasenv,subst,status,t =
53   GrafiteDisambiguate.disambiguate_nterm status None [] [] [] ("",0,t) in
54  assert (metasenv=[]);
55  let t = NCicUntrusted.apply_subst subst [] t in
56  let status = basic_eval_unification_hint (t,n) status in
57  let dump = inject_unification_hint (t,n)::status#dump in
58  let status = status#set_dump dump in
59   status
60 ;;
61
62 let basic_index_obj l status =
63   status#set_auto_cache 
64     (List.fold_left
65       (fun t (ks,v) -> 
66          List.fold_left (fun t k ->
67            NDiscriminationTree.DiscriminationTree.index t k v)
68           t ks) 
69     status#auto_cache l) 
70 ;;     
71
72 let basic_eval_interpretation (dsc, (symbol, args), cic_appl_pattern) status =
73  let status =
74   Interpretations.add_interpretation status dsc (symbol, args) cic_appl_pattern
75  in
76  let mode = GrafiteAst.WithPreferences (*assert false*) in (* MATITA 1.0 VEDI SOTTO *)
77  let diff =
78   [DisambiguateTypes.Symbol (symbol, 0), GrafiteAst.Symbol_alias (symbol,0,dsc)]
79  in
80   GrafiteDisambiguate.set_proof_aliases status ~implicit_aliases:false mode diff
81 ;;
82
83 let inject_interpretation =
84  let basic_eval_interpretation (dsc, (symbol, args), cic_appl_pattern)
85    ~refresh_uri_in_universe ~refresh_uri_in_term ~refresh_uri_in_reference
86  =
87   let rec refresh =
88    function
89       NotationPt.NRefPattern (NReference.Ref (uri,spec)) ->
90        NotationPt.NRefPattern
91         (NReference.reference_of_spec (NCicLibrary.refresh_uri uri) spec)
92     | NotationPt.VarPattern _
93     | NotationPt.ImplicitPattern as x -> x
94     | NotationPt.ApplPattern l -> NotationPt.ApplPattern (List.map refresh l)
95   in
96   let cic_appl_pattern = refresh cic_appl_pattern in
97    basic_eval_interpretation (dsc, (symbol, args), cic_appl_pattern)
98  in
99   GrafiteTypes.Serializer.register#run "interpretation"
100    basic_eval_interpretation
101 ;;
102
103 let eval_interpretation status data= 
104  let status = basic_eval_interpretation data status in
105  let dump = inject_interpretation data::status#dump in
106   status#set_dump dump
107 ;;
108
109 let basic_eval_alias (mode,diff) status =
110   GrafiteDisambiguate.set_proof_aliases status ~implicit_aliases:false mode diff
111 ;;
112
113 let inject_alias =
114  let basic_eval_alias (mode,diff) ~refresh_uri_in_universe ~refresh_uri_in_term
115    ~refresh_uri_in_reference =
116    basic_eval_alias (mode,diff)
117  in
118   GrafiteTypes.Serializer.register#run "alias" basic_eval_alias
119 ;;
120
121 let eval_alias status data= 
122  let status = basic_eval_alias data status in
123  let dump = inject_alias data::status#dump in
124   status#set_dump dump
125 ;;
126
127 let basic_eval_input_notation (l1,l2) status =
128   GrafiteParser.extend status l1 
129    (fun env loc ->
130      NotationPt.AttributedTerm
131       (`Loc loc,TermContentPres.instantiate_level2 env l2)) 
132 ;;
133
134 let inject_input_notation =
135  let basic_eval_input_notation (l1,l2)
136   ~refresh_uri_in_universe ~refresh_uri_in_term ~refresh_uri_in_reference
137  =
138    let l1 =
139     CicNotationParser.refresh_uri_in_checked_l1_pattern
140      ~refresh_uri_in_term ~refresh_uri_in_reference l1 in
141    let l2 = NotationUtil.refresh_uri_in_term
142      ~refresh_uri_in_term ~refresh_uri_in_reference l2
143    in
144     basic_eval_input_notation (l1,l2)
145  in
146   GrafiteTypes.Serializer.register#run "input_notation"
147    basic_eval_input_notation
148 ;;
149
150 let eval_input_notation status data= 
151  let status = basic_eval_input_notation data status in
152  let dump = inject_input_notation data::status#dump in
153   status#set_dump dump
154 ;;
155
156 let basic_eval_output_notation (l1,l2) status =
157  TermContentPres.add_pretty_printer status l2 l1
158 ;;
159
160 let inject_output_notation =
161  let basic_eval_output_notation (l1,l2)
162   ~refresh_uri_in_universe ~refresh_uri_in_term ~refresh_uri_in_reference
163  =
164   let l1 =
165    CicNotationParser.refresh_uri_in_checked_l1_pattern
166     ~refresh_uri_in_term ~refresh_uri_in_reference l1 in
167   let l2 = NotationUtil.refresh_uri_in_term
168     ~refresh_uri_in_term ~refresh_uri_in_reference l2
169   in
170    basic_eval_output_notation (l1,l2)
171  in
172   GrafiteTypes.Serializer.register#run "output_notation"
173    basic_eval_output_notation
174 ;;
175
176 let eval_output_notation status data= 
177  let status = basic_eval_output_notation data status in
178  let dump = inject_output_notation data::status#dump in
179   status#set_dump dump
180 ;;
181
182 let record_index_obj = 
183  let aux l ~refresh_uri_in_universe 
184    ~refresh_uri_in_term ~refresh_uri_in_reference
185  =
186     basic_index_obj
187       (List.map 
188         (fun ks,v -> List.map refresh_uri_in_term ks, refresh_uri_in_term v) 
189       l)
190  in
191   GrafiteTypes.Serializer.register#run "index_obj" aux
192 ;;
193
194 let compute_keys status uri height kind = 
195  let mk_item ty spec =
196    let orig_ty = NTacStatus.mk_cic_term [] ty in
197    let status,keys = NnAuto.keys_of_type status orig_ty in
198    let keys =  
199      List.map 
200        (fun t -> 
201           snd (NTacStatus.term_of_cic_term status t (NTacStatus.ctx_of t)))
202        keys
203    in
204    keys,NCic.Const(NReference.reference_of_spec uri spec)
205  in
206  let data = 
207   match kind with
208   | NCic.Fixpoint (ind,ifl,_) -> 
209      HExtlib.list_mapi 
210        (fun (_,_,rno,ty,_) i -> 
211           if ind then mk_item ty (NReference.Fix (i,rno,height)) 
212           else mk_item ty (NReference.CoFix height)) ifl
213   | NCic.Inductive (b,lno,itl,_) -> 
214      HExtlib.list_mapi 
215        (fun (_,_,ty,_) i -> mk_item ty (NReference.Ind (b,i,lno))) itl 
216      @
217      List.map (fun ((_,_,ty),i,j) -> mk_item ty (NReference.Con (i,j+1,lno)))
218        (List.flatten (HExtlib.list_mapi 
219          (fun (_,_,_,cl) i -> HExtlib.list_mapi (fun x j-> x,i,j) cl)
220          itl))
221   | NCic.Constant (_,_,Some _, ty, _) -> 
222      [ mk_item ty (NReference.Def height) ]
223   | NCic.Constant (_,_,None, ty, _) ->
224      [ mk_item ty NReference.Decl ]
225  in
226   HExtlib.filter_map
227    (fun (keys, t) ->
228      let keys = List.filter
229        (function 
230          | (NCic.Meta _) 
231          | (NCic.Appl (NCic.Meta _::_)) -> false 
232          | _ -> true) 
233        keys
234      in
235      if keys <> [] then 
236       begin
237         HLog.debug ("Indexing:" ^ 
238           NCicPp.ppterm ~metasenv:[] ~subst:[] ~context:[] t);
239         HLog.debug ("With keys:" ^ String.concat "\n" (List.map (fun t ->
240           NCicPp.ppterm ~metasenv:[] ~subst:[] ~context:[] t) keys));
241         Some (keys,t) 
242       end
243      else 
244       begin
245         HLog.debug ("Not indexing:" ^ 
246           NCicPp.ppterm ~metasenv:[] ~subst:[] ~context:[] t);
247         None
248       end)
249     data
250 ;;
251
252 let index_obj_for_auto status (uri, height, _, _, kind) = 
253  (*prerr_endline (string_of_int height);*)
254   let data = compute_keys status uri height kind in
255   let status = basic_index_obj data status in
256   let dump = record_index_obj data :: status#dump in   
257   status#set_dump dump
258 ;; 
259
260 let index_eq uri status =
261   let eq_status = status#eq_cache in
262   let eq_status1 = NCicParamod.index_obj eq_status uri in
263     status#set_eq_cache eq_status1
264 ;;
265
266 let record_index_eq =
267  let basic_index_eq uri
268    ~refresh_uri_in_universe ~refresh_uri_in_term ~refresh_uri_in_reference 
269    = index_eq (NCicLibrary.refresh_uri uri) 
270  in
271   GrafiteTypes.Serializer.register#run "index_eq" basic_index_eq
272 ;;
273
274 let index_eq_for_auto status uri =
275  if NnAuto.is_a_fact_obj status uri then
276    let newstatus = index_eq uri status in
277      if newstatus#eq_cache == status#eq_cache then status 
278      else
279        ((*prerr_endline ("recording " ^ (NUri.string_of_uri uri));*)
280         let dump = record_index_eq uri :: newstatus#dump 
281         in newstatus#set_dump dump)
282  else 
283    ((*prerr_endline "Not a fact";*)
284    status)
285 ;; 
286
287 let basic_eval_add_constraint (u1,u2) status =
288  NCicLibrary.add_constraint status u1 u2
289 ;;
290
291 let inject_constraint =
292  let basic_eval_add_constraint (u1,u2) 
293        ~refresh_uri_in_universe ~refresh_uri_in_term ~refresh_uri_in_reference
294  =
295   let u1 = refresh_uri_in_universe u1 in 
296   let u2 = refresh_uri_in_universe u2 in 
297   basic_eval_add_constraint (u1,u2)
298  in
299   GrafiteTypes.Serializer.register#run "constraints" basic_eval_add_constraint 
300 ;;
301
302 let eval_add_constraint status u1 u2 = 
303  let status = basic_eval_add_constraint (u1,u2) status in
304  let dump = inject_constraint (u1,u2)::status#dump in
305  let status = status#set_dump dump in
306   status
307 ;;
308
309 let eval_ng_tac tac =
310  let rec aux f (text, prefix_len, tac) =
311   match tac with
312   | GrafiteAst.NApply (_loc, t) -> NTactics.apply_tac (text,prefix_len,t) 
313   | GrafiteAst.NSmartApply (_loc, t) -> 
314       NnAuto.smart_apply_tac (text,prefix_len,t) 
315   | GrafiteAst.NAssert (_loc, seqs) ->
316      NTactics.assert_tac
317       ((List.map
318         (function (hyps,concl) ->
319           List.map
320            (function
321               (id,`Decl t) -> id,`Decl (text,prefix_len,t)
322              |(id,`Def (b,t))->id,`Def((text,prefix_len,b),(text,prefix_len,t))
323            ) hyps,
324           (text,prefix_len,concl))
325        ) seqs)
326   | GrafiteAst.NAuto (_loc, (None,a)) -> 
327       NnAuto.auto_tac ~params:(None,a) ?trace_ref:None
328   | GrafiteAst.NAuto (_loc, (Some l,a)) ->
329       NnAuto.auto_tac
330         ~params:(Some List.map (fun x -> "",0,x) l,a) ?trace_ref:None
331   | GrafiteAst.NBranch _ -> NTactics.branch_tac ~force:false
332   | GrafiteAst.NCases (_loc, what, where) ->
333       NTactics.cases_tac 
334         ~what:(text,prefix_len,what)
335         ~where:(text,prefix_len,where)
336   | GrafiteAst.NCase1 (_loc,n) -> NTactics.case1_tac n
337   | GrafiteAst.NChange (_loc, pat, ww) -> 
338       NTactics.change_tac 
339        ~where:(text,prefix_len,pat) ~with_what:(text,prefix_len,ww) 
340   | GrafiteAst.NConstructor (_loc,num,args) -> 
341      NTactics.constructor_tac 
342        ?num ~args:(List.map (fun x -> text,prefix_len,x) args)
343   | GrafiteAst.NCut (_loc, t) -> NTactics.cut_tac (text,prefix_len,t) 
344 (*| GrafiteAst.NDiscriminate (_,what) -> NDestructTac.discriminate_tac ~what:(text,prefix_len,what)
345   | GrafiteAst.NSubst (_,what) -> NDestructTac.subst_tac ~what:(text,prefix_len,what)*)
346   | GrafiteAst.NDestruct (_,dom,skip) -> NDestructTac.destruct_tac dom skip
347   | GrafiteAst.NDot _ -> NTactics.dot_tac 
348   | GrafiteAst.NElim (_loc, what, where) ->
349       NTactics.elim_tac 
350         ~what:(text,prefix_len,what)
351         ~where:(text,prefix_len,where)
352   | GrafiteAst.NFocus (_,l) -> NTactics.focus_tac l
353   | GrafiteAst.NGeneralize (_loc, where) -> 
354       NTactics.generalize_tac ~where:(text,prefix_len,where)
355   | GrafiteAst.NId _ -> (fun x -> x)
356   | GrafiteAst.NIntro (_loc,n) -> NTactics.intro_tac n
357   | GrafiteAst.NIntros (_loc,ns) -> NTactics.intros_tac ns
358   | GrafiteAst.NInversion (_loc, what, where) ->
359       NTactics.inversion_tac 
360         ~what:(text,prefix_len,what)
361         ~where:(text,prefix_len,where)
362   | GrafiteAst.NLApply (_loc, t) -> NTactics.lapply_tac (text,prefix_len,t) 
363   | GrafiteAst.NLetIn (_loc,where,what,name) ->
364       NTactics.letin_tac ~where:(text,prefix_len,where) 
365         ~what:(text,prefix_len,what) name
366   | GrafiteAst.NMerge _ -> NTactics.merge_tac 
367   | GrafiteAst.NPos (_,l) -> NTactics.pos_tac l
368   | GrafiteAst.NPosbyname (_,s) -> NTactics.case_tac s
369   | GrafiteAst.NReduce (_loc, reduction, where) ->
370       NTactics.reduce_tac ~reduction ~where:(text,prefix_len,where)
371   | GrafiteAst.NRewrite (_loc,dir,what,where) ->
372      NTactics.rewrite_tac ~dir ~what:(text,prefix_len,what)
373       ~where:(text,prefix_len,where)
374   | GrafiteAst.NSemicolon _ -> fun x -> x
375   | GrafiteAst.NShift _ -> NTactics.shift_tac 
376   | GrafiteAst.NSkip _ -> NTactics.skip_tac
377   | GrafiteAst.NUnfocus _ -> NTactics.unfocus_tac
378   | GrafiteAst.NWildcard _ -> NTactics.wildcard_tac 
379   | GrafiteAst.NTry (_,tac) -> NTactics.try_tac
380       (aux f (text, prefix_len, tac))
381   | GrafiteAst.NAssumption _ -> NTactics.assumption_tac
382   | GrafiteAst.NBlock (_,l) -> 
383       NTactics.block_tac (List.map (fun x -> aux f (text,prefix_len,x)) l)
384   |GrafiteAst.NRepeat (_,tac) ->
385       NTactics.repeat_tac (f f (text, prefix_len, tac))
386  in
387   aux aux tac (* trick for non uniform recursion call *)
388 ;;
389       
390 let subst_metasenv_and_fix_names status =
391   let u,h,metasenv, subst,o = status#obj in
392   let o = 
393     NCicUntrusted.map_obj_kind ~skip_body:true 
394      (NCicUntrusted.apply_subst subst []) o
395   in
396    status#set_obj(u,h,NCicUntrusted.apply_subst_metasenv subst metasenv,subst,o)
397 ;;
398
399 let is_proof_irrelevant context ty =
400   match
401     NCicReduction.whd ~subst:[] context
402      (NCicTypeChecker.typeof ~subst:[] ~metasenv:[] context ty)
403   with
404      NCic.Sort NCic.Prop -> true
405    | NCic.Sort _ -> false
406    | _ -> assert false
407 ;;
408
409 let rec relevance_of ?(context=[]) ty =
410  match NCicReduction.whd ~subst:[] context ty with
411     NCic.Prod (n,s,t) ->
412      not (is_proof_irrelevant context s) ::
413       relevance_of ~context:((n,NCic.Decl s)::context) t
414   | _ -> []
415 ;;
416
417 let compute_relevance uri =
418  function
419     NCic.Constant (_,name,bo,ty,attrs) ->
420      let relevance = relevance_of ty in
421       NCic.Constant (relevance,name,bo,ty,attrs)
422   | NCic.Fixpoint (ind,funs,attrs) ->
423      let funs =
424        List.map
425        (fun (_,name,recno,ty,bo) ->
426          let relevance = relevance_of ty in
427           relevance,name,recno,ty,bo
428         ) funs
429      in
430       NCic.Fixpoint (ind,funs,attrs)
431   | NCic.Inductive (ind,leftno,tys,attrs) ->
432      let context =
433       List.rev_map (fun (_,name,arity,_) -> name,NCic.Decl arity) tys in
434      let tysno = List.length tys in
435      let tys =
436        List.map
437         (fun (_,name,arity,cons) ->
438          let relevance = relevance_of arity in
439          let cons =
440           List.map
441            (fun (_,name,ty) ->
442              let dety =
443                NCicTypeChecker.debruijn uri tysno ~subst:[] [] ty in
444              let relevance = relevance_of ~context dety in
445               relevance,name,ty
446            ) cons
447          in
448           (relevance,name,arity,cons)
449         ) tys
450      in
451       NCic.Inductive (ind,leftno,tys,attrs)
452 ;;
453
454
455 let rec eval_ncommand ~include_paths opts status (text,prefix_len,cmd) =
456   match cmd with
457   | GrafiteAst.Include (loc, mode, fname) ->
458            let _root, baseuri, _fullpath, _rrelpath = 
459        Librarian.baseuri_of_script ~include_paths fname in
460      let status,obj =
461        GrafiteTypes.Serializer.require ~baseuri:(NUri.uri_of_string baseuri)
462         status in
463      let status = status#set_dump (obj::status#dump) in
464      let status = status#set_dependencies (fname::status#dependencies) in
465      (*assert false;*) (*  MATITA 1.0mode must be passed to GrafiteTypes.Serializer.require
466      somehow *)
467        status
468   | GrafiteAst.UnificationHint (loc, t, n) -> eval_unification_hint status t n
469   | GrafiteAst.NCoercion (loc, name, t, ty, source, target) ->
470      let status, composites =
471       NCicCoercDeclaration.eval_ncoercion status name t ty source target in
472      let mode = GrafiteAst.WithPreferences in (* MATITA 1.0: fixme *)
473      let aliases = GrafiteDisambiguate.aliases_for_objs composites in
474       eval_alias status (mode,aliases)
475   | GrafiteAst.NQed loc ->
476      if status#ng_mode <> `ProofMode then
477       raise (GrafiteTypes.Command_error "Not in proof mode")
478      else
479       let uri,height,menv,subst,obj_kind = status#obj in
480        if menv <> [] then
481         raise
482          (GrafiteTypes.Command_error"You can't Qed an incomplete theorem")
483        else
484         let obj_kind =
485          NCicUntrusted.map_obj_kind 
486           (NCicUntrusted.apply_subst subst []) obj_kind in
487         let height = NCicTypeChecker.height_of_obj_kind uri [] obj_kind in
488         (* fix the height inside the object *)
489         let rec fix () = function 
490           | NCic.Const (NReference.Ref (u,spec)) when NUri.eq u uri -> 
491              NCic.Const (NReference.reference_of_spec u
492               (match spec with
493               | NReference.Def _ -> NReference.Def height
494               | NReference.Fix (i,j,_) -> NReference.Fix(i,j,height)
495               | NReference.CoFix _ -> NReference.CoFix height
496               | NReference.Ind _ | NReference.Con _
497               | NReference.Decl as s -> s))
498           | t -> NCicUtils.map (fun _ () -> ()) () fix t
499         in
500         let obj_kind = 
501           match obj_kind with
502           | NCic.Fixpoint _ -> 
503               NCicUntrusted.map_obj_kind (fix ()) obj_kind 
504           | _ -> obj_kind
505         in
506         let obj_kind = compute_relevance uri obj_kind in
507         let obj = uri,height,[],[],obj_kind in
508         let old_status = status in
509         let status = NCicLibrary.add_obj status obj in
510         let index_obj =
511          match obj_kind with
512             NCic.Constant (_,_,_,_,(_,`Example,_))
513           | NCic.Fixpoint (_,_,(_,`Example,_)) -> false
514           | _ -> true
515         in
516         let status =
517          if index_obj then
518           let status = index_obj_for_auto status obj in
519            (try index_eq_for_auto status uri
520            with _ -> status)
521          else
522           status in
523 (*
524           try 
525             index_eq uri status
526           with _ -> prerr_endline "got an exception"; status
527         in *)
528 (*         prerr_endline (NCicPp.ppobj obj); *)
529         HLog.message ("New object: " ^ NUri.string_of_uri uri);
530          (try
531        (*prerr_endline (NCicPp.ppobj obj);*)
532            let boxml = NCicElim.mk_elims obj in
533            let boxml = boxml @ NCicElim.mk_projections obj in
534 (*
535            let objs = [] in
536            let timestamp,uris_rev =
537              List.fold_left
538               (fun (status,uris_rev) (uri,_,_,_,_) as obj ->
539                 let status = NCicLibrary.add_obj status obj in
540                  status,uri::uris_rev
541               ) (status,[]) objs in
542            let uris = uri::List.rev uris_rev in
543 *)
544            let status = status#set_ng_mode `CommandMode in
545            let xxaliases = GrafiteDisambiguate.aliases_for_objs [uri] in
546            let mode = GrafiteAst.WithPreferences in (* MATITA 1.0: fixme *)
547            let status = eval_alias status (mode,xxaliases) in
548            let status =
549             List.fold_left
550              (fun status boxml ->
551                try
552                 let nstatus =
553                  eval_ncommand ~include_paths opts status
554                   ("",0,GrafiteAst.NObj (HExtlib.dummy_floc,boxml))
555                 in
556                 if nstatus#ng_mode <> `CommandMode then
557                   begin
558                     (*HLog.warn "error in generating projection/eliminator";*)
559                     assert(status#ng_mode = `CommandMode);
560                     status
561                   end
562                 else
563                   nstatus
564                with
565                | MultiPassDisambiguator.DisambiguationError _
566                | NCicTypeChecker.TypeCheckerFailure _ ->
567                   (*HLog.warn "error in generating projection/eliminator";*)
568                   status
569              ) status boxml in             
570            let _,_,_,_,nobj = obj in 
571            let status = match nobj with
572                NCic.Inductive (is_ind,leftno,[it],_) ->
573                  let _,ind_name,ty,cl = it in
574                  List.fold_left 
575                    (fun status outsort ->
576                       let status = status#set_ng_mode `ProofMode in
577                       try
578                        (let status,invobj =
579                          NInversion.mk_inverter 
580                           (ind_name ^ "_inv_" ^
581                             (snd (NCicElim.ast_of_sort outsort)))
582                           is_ind it leftno outsort status status#baseuri in
583                        let _,_,menv,_,_ = invobj in
584                         (match menv with
585                              [] -> eval_ncommand ~include_paths opts status
586                                     ("",0,GrafiteAst.NQed Stdpp.dummy_loc)
587                            | _ -> status))
588                        (* XXX *)
589                       with _ -> (*HLog.warn "error in generating inversion principle"; *)
590                                 let status = status#set_ng_mode `CommandMode in status)
591                   status
592                   (NCic.Prop::
593                     List.map (fun s -> NCic.Type s) (NCicEnvironment.get_universes ()))
594               | _ -> status
595            in
596            let coercions =
597             match obj with
598               _,_,_,_,NCic.Inductive
599                (true,leftno,[_,_,_,[_,_,_]],(_,`Record fields))
600                ->
601                 HExtlib.filter_map
602                  (fun (name,is_coercion,arity) ->
603                    if is_coercion then Some(name,leftno,arity) else None) fields
604             | _ -> [] in
605            let status =
606             List.fold_left
607              (fun status (name,cpos,arity) ->
608                try
609                  let metasenv,subst,status,t =
610                   GrafiteDisambiguate.disambiguate_nterm status None [] [] []
611                    ("",0,NotationPt.Ident (name,None)) in
612                  assert (metasenv = [] && subst = []);
613                  let status, nuris = 
614                    NCicCoercDeclaration.
615                      basic_eval_and_record_ncoercion_from_t_cpos_arity 
616                       status (name,t,cpos,arity) in
617                  let aliases = GrafiteDisambiguate.aliases_for_objs nuris in
618                   eval_alias status (mode,aliases)
619                with MultiPassDisambiguator.DisambiguationError _-> 
620                  HLog.warn ("error in generating coercion: "^name);
621                  status) 
622              status coercions
623            in
624             status
625           with
626            exn ->
627             NCicLibrary.time_travel old_status;
628             raise exn)
629   | GrafiteAst.NCopy (log,tgt,src_uri, map) ->
630      if status#ng_mode <> `CommandMode then
631       raise (GrafiteTypes.Command_error "Not in command mode")
632      else
633        let tgt_uri_ext, old_ok = 
634          match NCicEnvironment.get_checked_obj src_uri with
635          | _,_,[],[], (NCic.Inductive _ as ok) -> ".ind", ok
636          | _,_,[],[], (NCic.Fixpoint _ as ok) -> ".con", ok
637          | _,_,[],[], (NCic.Constant _ as ok) -> ".con", ok
638          | _ -> assert false
639        in
640        let tgt_uri = NUri.uri_of_string (status#baseuri^"/"^tgt^tgt_uri_ext) in
641        let map = (src_uri, tgt_uri) :: map in
642        let ok = 
643          let rec subst () = function
644            | NCic.Meta _ -> assert false
645            | NCic.Const (NReference.Ref (u,spec)) as t ->
646                (try NCic.Const 
647                  (NReference.reference_of_spec (List.assoc u map)spec)
648                with Not_found -> t)
649            | t -> NCicUtils.map (fun _ _ -> ()) () subst t
650          in
651          NCicUntrusted.map_obj_kind ~skip_body:false (subst ()) old_ok
652        in
653        let ninitial_stack = Continuationals.Stack.of_nmetasenv [] in
654        let status = status#set_obj (tgt_uri,0,[],[],ok) in
655        (*prerr_endline (NCicPp.ppobj (tgt_uri,0,[],[],ok));*)
656        let status = status#set_stack ninitial_stack in
657        let status = subst_metasenv_and_fix_names status in
658        let status = status#set_ng_mode `ProofMode in
659        eval_ncommand ~include_paths opts status ("",0,GrafiteAst.NQed Stdpp.dummy_loc)
660   | GrafiteAst.NObj (loc,obj) ->
661      if status#ng_mode <> `CommandMode then
662       raise (GrafiteTypes.Command_error "Not in command mode")
663      else
664       let status,obj =
665        GrafiteDisambiguate.disambiguate_nobj status
666         ~baseuri:status#baseuri (text,prefix_len,obj) in
667       let uri,height,nmenv,nsubst,nobj = obj in
668       let ninitial_stack = Continuationals.Stack.of_nmetasenv nmenv in
669       let status = status#set_obj obj in
670       let status = status#set_stack ninitial_stack in
671       let status = subst_metasenv_and_fix_names status in
672       let status = status#set_ng_mode `ProofMode in
673       (match nmenv with
674           [] ->
675            eval_ncommand ~include_paths opts status ("",0,GrafiteAst.NQed Stdpp.dummy_loc)
676         | _ -> status)
677   | GrafiteAst.NDiscriminator (_,_) -> assert false (*(loc, indty) ->
678       if status#ng_mode <> `CommandMode then
679         raise (GrafiteTypes.Command_error "Not in command mode")
680       else
681         let status = status#set_ng_mode `ProofMode in
682         let metasenv,subst,status,indty =
683           GrafiteDisambiguate.disambiguate_nterm None status [] [] [] (text,prefix_len,indty) in
684         let indtyno, (_,_,tys,_,_) = match indty with
685             NCic.Const ((NReference.Ref (_,NReference.Ind (_,indtyno,_))) as r) ->
686               indtyno, NCicEnvironment.get_checked_indtys r
687           | _ -> prerr_endline ("engine: indty expected... (fix this error message)"); assert false in
688         let it = List.nth tys indtyno in
689         let status,obj =  NDestructTac.mk_discriminator it status in
690         let _,_,menv,_,_ = obj in
691           (match menv with
692                [] -> eval_ncommand ~include_paths opts status ("",0,GrafiteAst.NQed Stdpp.dummy_loc)
693              | _ -> prerr_endline ("Discriminator: non empty metasenv");
694                     status, []) *)
695   | GrafiteAst.NInverter (loc, name, indty, selection, sort) ->
696      if status#ng_mode <> `CommandMode then
697       raise (GrafiteTypes.Command_error "Not in command mode")
698      else
699       let metasenv,subst,status,sort = match sort with
700         | None -> [],[],status,NCic.Sort NCic.Prop
701         | Some s ->
702            GrafiteDisambiguate.disambiguate_nterm status None [] [] []
703             (text,prefix_len,s) 
704       in
705       assert (metasenv = []);
706       let sort = NCicReduction.whd ~subst [] sort in
707       let sort =
708        match sort with 
709           NCic.Sort s -> s
710         | _ ->
711            raise (Invalid_argument (Printf.sprintf
712             "ninverter: found target %s, which is not a sort"
713              (NCicPp.ppterm ~metasenv ~subst ~context:[] sort))) in
714       let status = status#set_ng_mode `ProofMode in
715       let metasenv,subst,status,indty =
716        GrafiteDisambiguate.disambiguate_nterm status None [] [] subst
717         (text,prefix_len,indty) in
718       let indtyno,(_,leftno,tys,_,_) =
719        match indty with
720           NCic.Const ((NReference.Ref (_,NReference.Ind (_,indtyno,_))) as r) ->
721            indtyno, NCicEnvironment.get_checked_indtys r
722         | _ ->
723           prerr_endline ("engine: indty ="  ^ NCicPp.ppterm ~metasenv:[]
724            ~subst:[] ~context:[] indty);
725           assert false in
726       let it = List.nth tys indtyno in
727       let status,obj =
728        NInversion.mk_inverter name true it leftno ?selection sort 
729         status status#baseuri in
730       let _,_,menv,_,_ = obj in
731        (match menv with
732           [] ->
733             eval_ncommand ~include_paths opts status
734              ("",0,GrafiteAst.NQed Stdpp.dummy_loc)
735         | _ -> assert false)
736   | GrafiteAst.NUnivConstraint (loc,u1,u2) ->
737       eval_add_constraint status [`Type,u1] [`Type,u2]
738   (* ex lexicon commands *)
739   | GrafiteAst.Interpretation (loc, dsc, (symbol, args), cic_appl_pattern) ->
740      let cic_appl_pattern =
741       GrafiteDisambiguate.disambiguate_cic_appl_pattern status args
742        cic_appl_pattern
743      in
744       eval_interpretation status (dsc,(symbol, args),cic_appl_pattern)
745   | GrafiteAst.Notation (loc, dir, l1, associativity, precedence, l2) ->
746       let l1 = 
747         CicNotationParser.check_l1_pattern
748          l1 (dir = Some `RightToLeft) precedence associativity
749       in
750       let status =
751         if dir <> Some `RightToLeft then eval_input_notation status (l1,l2)
752         else status
753       in
754        if dir <> Some `LeftToRight then eval_output_notation status (l1,l2)
755        else status
756   | GrafiteAst.Alias (loc, spec) -> 
757      let diff =
758       (*CSC: Warning: this code should be factorized with the corresponding
759              code in DisambiguatePp *)
760       match spec with
761       | GrafiteAst.Ident_alias (id,uri) -> 
762          [DisambiguateTypes.Id id,spec]
763       | GrafiteAst.Symbol_alias (symb, instance, desc) ->
764          [DisambiguateTypes.Symbol (symb,instance),spec]
765       | GrafiteAst.Number_alias (instance,desc) ->
766          [DisambiguateTypes.Num instance,spec]
767      in
768       let mode = GrafiteAst.WithPreferences in(*assert false in (* VEDI SOPRA *) MATITA 1.0*)
769        eval_alias status (mode,diff)
770 ;;
771
772 let eval_comment opts status (text,prefix_len,c) = status
773
774 let rec eval_executable ~include_paths opts status (text,prefix_len,ex) =
775   match ex with
776   | GrafiteAst.NTactic (_(*loc*), tacl) ->
777       if status#ng_mode <> `ProofMode then
778        raise (GrafiteTypes.Command_error "Not in proof mode")
779       else
780        let status =
781         List.fold_left 
782           (fun status tac ->
783             let status = eval_ng_tac (text,prefix_len,tac) status in
784             subst_metasenv_and_fix_names status)
785           status tacl
786        in
787         status
788   | GrafiteAst.NCommand (_, cmd) ->
789       eval_ncommand ~include_paths opts status (text,prefix_len,cmd)
790   | GrafiteAst.NMacro (loc, macro) ->
791      raise (NMacro (loc,macro))
792
793 and eval_ast ~include_paths ?(do_heavy_checks=false) status (text,prefix_len,st)
794 =
795   let opts = { do_heavy_checks = do_heavy_checks ; } in
796   match st with
797   | GrafiteAst.Executable (_,ex) ->
798      eval_executable ~include_paths opts status (text,prefix_len,ex)
799   | GrafiteAst.Comment (_,c) -> 
800       eval_comment opts status (text,prefix_len,c) 
801 ;;