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