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