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