]> matita.cs.unibo.it Git - helm.git/blob - matita/components/grafite_engine/grafiteEngine.ml
f2876d2a9b6fb977cd0a42e5103ed85dbd657545
[helm.git] / matita / components / grafite_engine / grafiteEngine.ml
1 (* Copyright (C) 2005, HELM Team.
2  * 
3  * This file is part of HELM, an Hypertextual, Electronic
4  * Library of Mathematics, developed at the Computer Science
5  * Department, University of Bologna, Italy.
6  * 
7  * HELM is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License
9  * as published by the Free Software Foundation; either version 2
10  * of the License, or (at your option) any later version.
11  * 
12  * HELM is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with HELM; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place - Suite 330, Boston,
20  * MA  02111-1307, USA.
21  * 
22  * For details, see the HELM World-Wide-Web page,
23  * http://helm.cs.unibo.it/
24  *)
25
26 (* $Id$ *)
27
28 (* mo file name, ma file name *)
29 exception NMacro of GrafiteAst.loc * GrafiteAst.nmacro
30
31 type 'a disambiguator_input = string * int * 'a
32
33 type options = { 
34   do_heavy_checks: bool ; 
35 }
36
37 let basic_eval_unification_hint (t,n) status =
38  NCicUnifHint.add_user_provided_hint status t n
39 ;;
40
41 let inject_unification_hint =
42  let basic_eval_unification_hint (t,n) 
43    ~refresh_uri_in_universe ~refresh_uri_in_term ~refresh_uri_in_reference
44    ~alias_only status
45  =
46   if not alias_only then
47    let t = refresh_uri_in_term (status :> NCic.status) t in
48     basic_eval_unification_hint (t,n) status
49   else
50    status
51  in
52   GrafiteTypes.Serializer.register#run "unification_hints"
53    basic_eval_unification_hint
54 ;;
55
56 let eval_unification_hint status t n = 
57  let metasenv,subst,status,t =
58   GrafiteDisambiguate.disambiguate_nterm status `XTSort [] [] [] ("",0,t) in
59  assert (metasenv=[]);
60  let t = NCicUntrusted.apply_subst status subst [] t in
61  let status = basic_eval_unification_hint (t,n) status in
62   NCicLibrary.dump_obj status (inject_unification_hint (t,n))
63 ;;
64
65 let basic_index_obj l (status:#NCic.status) =
66   status#set_auto_cache 
67     (List.fold_left
68       (fun t (ks,v) -> 
69          List.fold_left (fun t k ->
70            NDiscriminationTree.DiscriminationTree.index t k v)
71           t ks) 
72     status#auto_cache l) 
73 ;;     
74
75 let basic_eval_interpretation ~alias_only (dsc, (symbol, args), cic_appl_pattern) status =
76  let status =
77   if not alias_only then
78    Interpretations.add_interpretation status dsc (symbol, args) cic_appl_pattern
79   else
80    status
81  in
82  let mode = GrafiteAst.WithPreferences (*assert false*) in (* MATITA 1.0 VEDI SOTTO *)
83  let diff =
84   [DisambiguateTypes.Symbol (symbol, 0), GrafiteAst.Symbol_alias (symbol,0,dsc)]
85  in
86   GrafiteDisambiguate.set_proof_aliases status ~implicit_aliases:false mode diff
87 ;;
88
89 let inject_interpretation =
90  let basic_eval_interpretation (dsc, (symbol, args), cic_appl_pattern)
91    ~refresh_uri_in_universe ~refresh_uri_in_term ~refresh_uri_in_reference
92    ~alias_only
93  =
94   let rec refresh =
95    function
96       NotationPt.NRefPattern (NReference.Ref (uri,spec)) ->
97        NotationPt.NRefPattern
98         (NReference.reference_of_spec (NCicLibrary.refresh_uri uri) spec)
99     | NotationPt.VarPattern _
100     | NotationPt.ImplicitPattern as x -> x
101     | NotationPt.ApplPattern l -> NotationPt.ApplPattern (List.map refresh l)
102   in
103   let cic_appl_pattern = refresh cic_appl_pattern in
104    basic_eval_interpretation ~alias_only (dsc, (symbol, args), cic_appl_pattern)
105  in
106   GrafiteTypes.Serializer.register#run "interpretation"
107    basic_eval_interpretation
108 ;;
109
110 let eval_interpretation status data= 
111  let status = basic_eval_interpretation ~alias_only:false data status in
112   NCicLibrary.dump_obj status (inject_interpretation data)
113 ;;
114
115 let basic_eval_alias (mode,diff) status =
116   GrafiteDisambiguate.set_proof_aliases status ~implicit_aliases:false mode diff
117 ;;
118
119 let inject_alias =
120  let basic_eval_alias (mode,diff) ~refresh_uri_in_universe ~refresh_uri_in_term
121    ~refresh_uri_in_reference ~alias_only =
122    basic_eval_alias (mode,diff)
123  in
124   GrafiteTypes.Serializer.register#run "alias" basic_eval_alias
125 ;;
126
127 let eval_alias status data= 
128  let status = basic_eval_alias data status in
129   NCicLibrary.dump_obj status (inject_alias data)
130 ;;
131
132 let basic_eval_input_notation (l1,l2) status =
133   GrafiteParser.extend status l1 
134    (fun env loc ->
135      NotationPt.AttributedTerm
136       (`Loc loc,TermContentPres.instantiate_level2 status env l2)) 
137 ;;
138
139 let inject_input_notation =
140  let basic_eval_input_notation (l1,l2)
141   ~refresh_uri_in_universe ~refresh_uri_in_term ~refresh_uri_in_reference
142   ~alias_only status
143  =
144    if not alias_only then
145     let l1 =
146      CicNotationParser.refresh_uri_in_checked_l1_pattern
147       ~refresh_uri_in_term:(refresh_uri_in_term (status:>NCic.status))
148       ~refresh_uri_in_reference l1 in
149     let l2 = NotationUtil.refresh_uri_in_term
150       ~refresh_uri_in_term:(refresh_uri_in_term (status:>NCic.status))
151       ~refresh_uri_in_reference l2
152     in
153      basic_eval_input_notation (l1,l2) status
154    else
155     status
156  in
157   GrafiteTypes.Serializer.register#run "input_notation"
158    basic_eval_input_notation
159 ;;
160
161 let eval_input_notation status data= 
162  let status = basic_eval_input_notation data status in
163   NCicLibrary.dump_obj status (inject_input_notation data)
164 ;;
165
166 let basic_eval_output_notation (l1,l2) status =
167  TermContentPres.add_pretty_printer status l2 l1
168 ;;
169
170 let inject_output_notation =
171  let basic_eval_output_notation (l1,l2)
172   ~refresh_uri_in_universe ~refresh_uri_in_term ~refresh_uri_in_reference
173   ~alias_only status
174  =
175   if not alias_only then
176    let l1 =
177     CicNotationParser.refresh_uri_in_checked_l1_pattern
178      ~refresh_uri_in_term:(refresh_uri_in_term (status:>NCic.status))
179       ~refresh_uri_in_reference l1 in
180    let l2 = NotationUtil.refresh_uri_in_term
181      ~refresh_uri_in_term:(refresh_uri_in_term (status:>NCic.status))
182       ~refresh_uri_in_reference l2
183    in
184     basic_eval_output_notation (l1,l2) status
185   else
186    status
187  in
188   GrafiteTypes.Serializer.register#run "output_notation"
189    basic_eval_output_notation
190 ;;
191
192 let eval_output_notation status data= 
193  let status = basic_eval_output_notation data status in
194   NCicLibrary.dump_obj status (inject_output_notation data)
195 ;;
196
197 let record_index_obj = 
198  let aux l ~refresh_uri_in_universe 
199    ~refresh_uri_in_term ~refresh_uri_in_reference ~alias_only status
200  =
201   let refresh_uri_in_term = refresh_uri_in_term (status:>NCic.status) in
202   if not alias_only then
203     basic_index_obj
204       (List.map 
205         (fun ks,v -> List.map refresh_uri_in_term ks, refresh_uri_in_term v) 
206       l) status
207   else
208    status
209  in
210   GrafiteTypes.Serializer.register#run "index_obj" aux
211 ;;
212
213 let compute_keys status uri height kind = 
214  let mk_item ty spec =
215    let orig_ty = NTacStatus.mk_cic_term [] ty in
216    let status,keys = NnAuto.keys_of_type status orig_ty in
217    let keys =  
218      List.map 
219        (fun t -> 
220           snd (NTacStatus.term_of_cic_term status t (NTacStatus.ctx_of t)))
221        keys
222    in
223    keys,NCic.Const(NReference.reference_of_spec uri spec)
224  in
225  let data = 
226   match kind with
227   | NCic.Fixpoint (ind,ifl,_) -> 
228      HExtlib.list_mapi 
229        (fun (_,_,rno,ty,_) i -> 
230           if ind then mk_item ty (NReference.Fix (i,rno,height)) 
231           else mk_item ty (NReference.CoFix height)) ifl
232   | NCic.Inductive (b,lno,itl,_) -> 
233      HExtlib.list_mapi 
234        (fun (_,_,ty,_) i -> mk_item ty (NReference.Ind (b,i,lno))) itl 
235      @
236      List.map (fun ((_,_,ty),i,j) -> mk_item ty (NReference.Con (i,j+1,lno)))
237        (List.flatten (HExtlib.list_mapi 
238          (fun (_,_,_,cl) i -> HExtlib.list_mapi (fun x j-> x,i,j) cl)
239          itl))
240   | NCic.Constant (_,_,Some _, ty, _) -> 
241      [ mk_item ty (NReference.Def height) ]
242   | NCic.Constant (_,_,None, ty, _) ->
243      [ mk_item ty NReference.Decl ]
244  in
245   HExtlib.filter_map
246    (fun (keys, t) ->
247      let keys = List.filter
248        (function 
249          | (NCic.Meta _) 
250          | (NCic.Appl (NCic.Meta _::_)) -> false 
251          | _ -> true) 
252        keys
253      in
254      if keys <> [] then 
255       begin
256         HLog.debug ("Indexing:" ^ 
257           status#ppterm ~metasenv:[] ~subst:[] ~context:[] t);
258         HLog.debug ("With keys:" ^ String.concat "\n" (List.map (fun t ->
259           status#ppterm ~metasenv:[] ~subst:[] ~context:[] t) keys));
260         Some (keys,t) 
261       end
262      else 
263       begin
264         HLog.debug ("Not indexing:" ^ 
265           status#ppterm ~metasenv:[] ~subst:[] ~context:[] t);
266         None
267       end)
268     data
269 ;;
270
271 let index_obj_for_auto status (uri, height, _, _, kind) = 
272  (*prerr_endline (string_of_int height);*)
273   let data = compute_keys status uri height kind in
274   let status = basic_index_obj data status in
275    NCicLibrary.dump_obj status (record_index_obj data)
276 ;; 
277
278 let basic_extract_obj obj status =
279  try
280   ignore (Helm_registry.get "extract_haskell");
281   let status,(msg,infos) = NCicExtraction.haskell_of_obj status obj in
282    prerr_endline msg;
283    status,infos
284  with
285     Helm_registry.Key_not_found _ -> status,NCicExtraction.empty_info
286   | exn -> prerr_endline ("EXTRACTION FAILURE: " ^ Printexc.to_string exn); assert false
287 ;;
288
289 let basic_extract_ocaml_obj obj status =
290  try
291   let status  = OcamlExtraction.print_ocaml_of_obj status obj in
292   let infos,status = status#get_info in
293    status,infos
294  with
295   exn -> prerr_endline ("EXTRACTION FAILURE: " ^ Printexc.to_string exn); assert false
296 ;;
297
298 let inject_extract_obj =
299  let basic_extract_obj info
300    ~refresh_uri_in_universe ~refresh_uri_in_term ~refresh_uri_in_reference
301    ~alias_only status
302  =
303   let info= NCicExtraction.refresh_uri_in_info ~refresh_uri_in_reference info in
304    status#set_extraction_db
305     (NCicExtraction.register_infos status#extraction_db info)
306  in
307   GrafiteTypes.Serializer.register#run "extraction" basic_extract_obj
308 ;;
309
310 let inject_extract_ocaml_obj =
311  let basic_extract_ocaml_obj info
312    ~refresh_uri_in_universe ~refresh_uri_in_term ~refresh_uri_in_reference
313    ~alias_only status
314  =
315   let info= OcamlExtractionTable.refresh_uri_in_info ~refresh_uri_in_reference ~refresh_uri:NCicLibrary.refresh_uri info in
316    status#set_ocaml_extraction_db
317     (OcamlExtractionTable.register_infos status#ocaml_extraction_db info)
318  in
319   GrafiteTypes.Serializer.register#run "ocaml_extraction" basic_extract_ocaml_obj
320 ;;
321
322 let eval_extract_obj status obj = 
323  let status,infos = basic_extract_obj obj status in
324   NCicLibrary.dump_obj status (inject_extract_obj infos)
325 ;;
326
327 let eval_extract_ocaml_obj status obj = 
328  let status,infos = basic_extract_ocaml_obj obj status in
329   NCicLibrary.dump_obj status (inject_extract_ocaml_obj infos)
330 ;;
331
332 (*
333 module EmptyC = 
334   struct
335     let metasenv = []
336     let subst = []
337     let context = []
338   end
339 *)
340
341 let index_eq print uri (status:#NCic.status) =
342   let eq_status = status#eq_cache in
343   let eq_status,clause = NCicParamod.index_obj status eq_status uri in
344   if print then
345    ((*let module NCicBlob =
346     struct
347      include NCicBlob.NCicBlob(EmptyC)
348      let pp t = status#ppterm ~metasenv:[] ~subst:[] ~context:[] t
349     end in
350    let module Pp = Pp.Pp(NCicBlob) in*)
351    (match clause with
352      | Some (*clause*) (_,Terms.Equation (_,_,_,o),_,_) ->
353         HLog.debug ("Indexed with orientation: " ^ Pp.string_of_comparison o);
354         (*HLog.debug ("Indexed as:" ^ Pp.pp_unit_clause clause)*)
355      | _ -> HLog.debug "Not indexed (i.e. pruned)")) ;
356   status#set_eq_cache eq_status
357 ;;
358
359 let record_index_eq =
360  let basic_index_eq uri
361    ~refresh_uri_in_universe ~refresh_uri_in_term ~refresh_uri_in_reference 
362    ~alias_only status
363    = if not alias_only then index_eq false (NCicLibrary.refresh_uri uri) status 
364      else
365       status
366  in
367   GrafiteTypes.Serializer.register#run "index_eq" basic_index_eq
368 ;;
369
370 let index_eq_for_auto status uri =
371  if NnAuto.is_a_fact_obj status uri then
372    let newstatus = index_eq true uri status in
373      if newstatus#eq_cache == status#eq_cache then status 
374      else
375        ((*prerr_endline ("recording " ^ (NUri.string_of_uri uri));*)
376         NCicLibrary.dump_obj newstatus (record_index_eq uri))
377  else 
378    ((*prerr_endline "Not a fact";*)
379    status)
380 ;; 
381
382 let inject_constraint =
383  let basic_eval_add_constraint (acyclic,u1,u2) 
384      ~refresh_uri_in_universe ~refresh_uri_in_term ~refresh_uri_in_reference
385      ~alias_only status
386  =
387   if not alias_only then
388    let u1 = refresh_uri_in_universe u1 in 
389    let u2 = refresh_uri_in_universe u2 in 
390     (* NCicLibrary.add_constraint adds the constraint to the NCicEnvironment
391      * and also to the storage (for undo/redo). During inclusion of compiled
392      * files the storage must not be touched. *)
393     NCicEnvironment.add_lt_constraint acyclic u1 u2;
394     status
395   else
396    status
397  in
398   GrafiteTypes.Serializer.register#run "constraints" basic_eval_add_constraint 
399 ;;
400
401 let eval_add_constraint status acyclic u1 u2 = 
402  let status = NCicLibrary.add_constraint status acyclic u1 u2 in
403   NCicLibrary.dump_obj status (inject_constraint (acyclic,u1,u2))
404 ;;
405
406 let eval_ng_tac tac =
407  let just_to_tacstatus_just just text prefix_len =
408     match just with
409     | `Term t -> `Term (text,prefix_len,t)
410     | `Auto (l,params) -> 
411     (
412         match l with
413         | None -> `Auto (None,params)
414         | Some l -> `Auto (Some (List.map (fun t -> (text,prefix_len,t)) l),params)
415     )
416     | _ -> assert false
417  in
418  let rec aux f (text, prefix_len, tac) =
419   match tac with
420   | GrafiteAst.NApply (_loc, t) -> NTactics.apply_tac (text,prefix_len,t) 
421   | GrafiteAst.NSmartApply (_loc, t) -> 
422       NnAuto.smart_apply_tac (text,prefix_len,t) 
423   | GrafiteAst.NAssert (_loc, seqs) ->
424      NTactics.assert_tac
425       ((List.map
426         (function (hyps,concl) ->
427           List.map
428            (function
429               (id,`Decl t) -> id,`Decl (text,prefix_len,t)
430              |(id,`Def (b,t))->id,`Def((text,prefix_len,b),(text,prefix_len,t))
431            ) hyps,
432           (text,prefix_len,concl))
433        ) seqs)
434   | GrafiteAst.NAuto (_loc, (None,a)) -> 
435       NnAuto.auto_tac ~params:(None,a) ?trace_ref:None
436   | GrafiteAst.NAuto (_loc, (Some l,a)) ->
437       NnAuto.auto_tac
438         ~params:(Some List.map (fun x -> "",0,x) l,a) ?trace_ref:None
439   | GrafiteAst.NBranch _ -> NTactics.branch_tac ~force:false
440   | GrafiteAst.NCases (_loc, what, where) ->
441       NTactics.cases_tac 
442         ~what:(text,prefix_len,what)
443         ~where:(text,prefix_len,where)
444   | GrafiteAst.NCase1 (_loc,n) -> NTactics.case1_tac n
445   | GrafiteAst.NChange (_loc, pat, ww) -> 
446       NTactics.change_tac 
447        ~where:(text,prefix_len,pat) ~with_what:(text,prefix_len,ww) 
448   | GrafiteAst.NConstructor (_loc,num,args) -> 
449      NTactics.constructor_tac 
450        ?num ~args:(List.map (fun x -> text,prefix_len,x) args)
451   | GrafiteAst.NCut (_loc, t) -> NTactics.cut_tac (text,prefix_len,t) 
452 (*| GrafiteAst.NDiscriminate (_,what) -> NDestructTac.discriminate_tac ~what:(text,prefix_len,what)
453   | GrafiteAst.NSubst (_,what) -> NDestructTac.subst_tac ~what:(text,prefix_len,what)*)
454   | GrafiteAst.NClear (_loc, l) -> NTactics.clear_tac l
455   | GrafiteAst.NDestruct (_,dom,skip) -> NDestructTac.destruct_tac dom skip
456   | GrafiteAst.NDot _ -> NTactics.dot_tac 
457   | GrafiteAst.NElim (_loc, what, where) ->
458       NTactics.elim_tac 
459         ~what:(text,prefix_len,what)
460         ~where:(text,prefix_len,where)
461   | GrafiteAst.NFocus (_,l) -> NTactics.focus_tac l
462   | GrafiteAst.NGeneralize (_loc, where) -> 
463       NTactics.generalize_tac ~where:(text,prefix_len,where)
464   | GrafiteAst.NId _ -> (fun x -> x)
465   | GrafiteAst.NIntro (_loc,n) -> NTactics.intro_tac n
466   | GrafiteAst.NIntros (_loc,ns) -> NTactics.intros_tac ns
467   | GrafiteAst.NInversion (_loc, what, where) ->
468       NTactics.inversion_tac 
469         ~what:(text,prefix_len,what)
470         ~where:(text,prefix_len,where)
471   | GrafiteAst.NLApply (_loc, t) -> NTactics.lapply_tac (text,prefix_len,t) 
472   | GrafiteAst.NLetIn (_loc,where,what,name) ->
473       NTactics.letin_tac ~where:(text,prefix_len,where) 
474         ~what:(text,prefix_len,what) name
475   | GrafiteAst.NMerge _ -> NTactics.merge_tac 
476   | GrafiteAst.NPos (_,l) -> NTactics.pos_tac l
477   | GrafiteAst.NPosbyname (_,s) -> NTactics.case_tac s
478   | GrafiteAst.NReduce (_loc, reduction, where) ->
479       NTactics.reduce_tac ~reduction ~where:(text,prefix_len,where)
480   | GrafiteAst.NRewrite (_loc,dir,what,where) ->
481      NTactics.rewrite_tac ~dir ~what:(text,prefix_len,what)
482       ~where:(text,prefix_len,where)
483   | GrafiteAst.NSemicolon _ -> fun x -> x
484   | GrafiteAst.NShift _ -> NTactics.shift_tac 
485   | GrafiteAst.NSkip _ -> NTactics.skip_tac
486   | GrafiteAst.NUnfocus _ -> NTactics.unfocus_tac
487   | GrafiteAst.NWildcard _ -> NTactics.wildcard_tac 
488   | GrafiteAst.NTry (_,tac) -> NTactics.try_tac
489       (f f (text, prefix_len, tac))
490   | GrafiteAst.NAssumption _ -> NTactics.assumption_tac
491   | GrafiteAst.NBlock (_,l) -> 
492       NTactics.block_tac (List.map (fun x -> aux f (text,prefix_len,x)) l)
493   |GrafiteAst.NRepeat (_,tac) ->
494       NTactics.repeat_tac (f f (text, prefix_len, tac))
495   |GrafiteAst.Assume (_,id,t,t1) -> Declarative.assume id (text,prefix_len,t) (match t1 with None ->
496   None | Some t1 -> (Some (text,prefix_len,t1)))
497   |GrafiteAst.Suppose (_,t,id,t1) -> Declarative.suppose (text,prefix_len,t) id (match t1 with None
498   -> None | Some t1 -> (Some (text,prefix_len,t1)))
499   |GrafiteAst.By_just_we_proved (_,j,t1,s,t2) -> Declarative.by_just_we_proved
500   (just_to_tacstatus_just j text prefix_len) (text,prefix_len,t1) s (match t2 with None -> None |
501   Some t2 -> (Some (text,prefix_len,t2)))
502   |GrafiteAst.We_need_to_prove (_, t, id, t2) -> Declarative.we_need_to_prove (text,prefix_len,t) id
503   (match t2 with None -> None | Some t2 -> Some (text,prefix_len,t2))
504   | GrafiteAst.Bydone (_, j) -> Declarative.bydone (just_to_tacstatus_just j text prefix_len)
505   | GrafiteAst.ExistsElim (_, just, id1, t1, t2, id2) ->
506      Declarative.existselim (just_to_tacstatus_just just text prefix_len) id1 (text,prefix_len,t1)
507      (text,prefix_len,t2) id2
508   | GrafiteAst.AndElim(_,just,t1,id1,t2,id2) -> Declarative.andelim (just_to_tacstatus_just just
509     text prefix_len) (text,prefix_len,t1) id1 (text,prefix_len,t2) id2
510   | GrafiteAst.Thesisbecomes (_, t1, t2) -> Declarative.thesisbecomes (text,prefix_len,t1)
511   (match t2 with None -> None | Some t2 -> (Some (text,prefix_len,t2)))
512   | GrafiteAst.RewritingStep (_,rhs,just,cont) ->
513      Declarative.rewritingstep (text,prefix_len,rhs)
514                                 (match just with 
515                                 `Term t -> just_to_tacstatus_just just text prefix_len
516                                 | `Auto params -> just_to_tacstatus_just just text prefix_len
517                                 |`Proof -> `Proof
518                                 |`SolveWith t -> `SolveWith (text,prefix_len,t)
519                                 )
520                                 cont
521   | GrafiteAst.Obtain (_,id,t1) ->
522      Declarative.obtain id (text,prefix_len,t1)
523   | GrafiteAst.Conclude (_,t1) ->
524      Declarative.conclude (text,prefix_len,t1)
525   | GrafiteAst.We_proceed_by_cases_on (_, t, t1) ->
526      Declarative.we_proceed_by_cases_on (text,prefix_len,t) (text,prefix_len,t1)
527   | GrafiteAst.We_proceed_by_induction_on (_, t, t1) ->
528      Declarative.we_proceed_by_induction_on (text,prefix_len,t) (text,prefix_len,t1)
529   | GrafiteAst.Byinduction (_, t, id) -> Declarative.byinduction (text,prefix_len,t) id
530   | GrafiteAst.Case (_,id,params) -> Declarative.case id params
531   | GrafiteAst.PrintStack (_) -> Declarative.print_stack
532  in
533   aux aux tac (* trick for non uniform recursion call *)
534 ;;
535       
536 let subst_metasenv_and_fix_names status =
537   let u,h,metasenv, subst,o = status#obj in
538   let o = 
539     NCicUntrusted.map_obj_kind ~skip_body:true 
540      (NCicUntrusted.apply_subst status subst []) o
541   in
542    status#set_obj(u,h,NCicUntrusted.apply_subst_metasenv status subst metasenv,subst,o)
543 ;;
544
545 let is_proof_irrelevant status context ty =
546   match
547     NCicReduction.whd status ~subst:[] context
548      (NCicTypeChecker.typeof status ~subst:[] ~metasenv:[] context ty)
549   with
550      NCic.Sort NCic.Prop -> true
551    | NCic.Sort _ -> false
552    | _ -> assert false
553 ;;
554
555 let rec relevance_of status ?(context=[]) ty =
556  match NCicReduction.whd status ~subst:[] context ty with
557     NCic.Prod (n,s,t) ->
558      not (is_proof_irrelevant status context s) ::
559       relevance_of status ~context:((n,NCic.Decl s)::context) t
560   | _ -> []
561 ;;
562
563 let compute_relevance status uri =
564  function
565     NCic.Constant (_,name,bo,ty,attrs) ->
566      let relevance = relevance_of status ty in
567       NCic.Constant (relevance,name,bo,ty,attrs)
568   | NCic.Fixpoint (ind,funs,attrs) ->
569      let funs =
570        List.map
571        (fun (_,name,recno,ty,bo) ->
572          let relevance = relevance_of status ty in
573           relevance,name,recno,ty,bo
574         ) funs
575      in
576       NCic.Fixpoint (ind,funs,attrs)
577   | NCic.Inductive (ind,leftno,tys,attrs) ->
578      let context =
579       List.rev_map (fun (_,name,arity,_) -> name,NCic.Decl arity) tys in
580      let tysno = List.length tys in
581      let tys =
582        List.map
583         (fun (_,name,arity,cons) ->
584          let relevance = relevance_of status arity in
585          let cons =
586           List.map
587            (fun (_,name,ty) ->
588              let dety =
589                NCicTypeChecker.debruijn status uri tysno ~subst:[] [] ty in
590              let relevance = relevance_of status ~context dety in
591               relevance,name,ty
592            ) cons
593          in
594           (relevance,name,arity,cons)
595         ) tys
596      in
597       NCic.Inductive (ind,leftno,tys,attrs)
598 ;;
599
600 let extract_uris status uris =
601  List.fold_left
602   (fun status uri ->
603     let obj = NCicEnvironment.get_checked_obj status uri in
604      let status = eval_extract_obj status obj in
605       eval_extract_ocaml_obj status obj
606   ) status uris
607 ;;
608
609 let rec eval_ncommand ~include_paths opts status (text,prefix_len,cmd) =
610   match cmd with
611   | GrafiteAst.Include (loc, mode, fname) ->
612      let _root, baseuri, fullpath, _rrelpath = 
613        Librarian.baseuri_of_script ~include_paths fname in
614      let baseuri = NUri.uri_of_string baseuri in
615      (* MATITA 1.0: keep WithoutPreferences? *)
616      let alias_only = (mode = GrafiteAst.OnlyPreferences) in
617      let status =
618       GrafiteTypes.Serializer.require
619        ~alias_only ~baseuri ~fname:fullpath status in
620      OcamlExtraction.print_open status
621       (NCicLibrary.get_transitively_included status)
622   | GrafiteAst.UnificationHint (loc, t, n) -> eval_unification_hint status t n
623   | GrafiteAst.NCoercion (loc, name, compose, None) ->
624      let status, t, ty, source, target =
625        let o_t = NotationPt.Ident (name,None) in
626        let metasenv,subst, status,t =
627          GrafiteDisambiguate.disambiguate_nterm 
628            status `XTNone [] [] [] ("",0,o_t) in
629        assert( metasenv = [] && subst = []);
630        let ty = NCicTypeChecker.typeof status [] [] [] t in
631        let source, target =
632          let clean = function
633            | NCic.Appl (NCic.Const _ as r :: l) -> 
634                NotationPt.Appl (NotationPt.NCic r ::
635                  List.map (fun _ -> NotationPt.Implicit `JustOne)l)
636            | NCic.Const _ as r -> NotationPt.NCic r
637            | NCic.Sort _ as r -> NotationPt.NCic r (* FG: missing case *)
638            | _ -> assert false
639          in
640          let rec aux = function
641            | NCic.Prod (_,_, (NCic.Prod _ as rest)) -> aux rest
642            | NCic.Prod (name, src, tgt) -> (name, clean src), clean tgt
643            | _ -> assert false
644          in
645          aux ty
646        in
647        status, o_t, NotationPt.NCic ty, source, target
648      in
649       let cmd = 
650        GrafiteAst.NCoercion (loc, name, compose, Some (t, ty, source, target))
651       in
652       eval_ncommand ~include_paths opts status (text,prefix_len,cmd)
653   | GrafiteAst.NCoercion (loc, name, compose, Some (t, ty, source, target)) ->
654      let status, composites =
655       NCicCoercDeclaration.eval_ncoercion status name compose t ty source
656        target in
657      let status = extract_uris status composites in
658      let mode = GrafiteAst.WithPreferences in (* MATITA 1.0: fixme *)
659      let aliases = GrafiteDisambiguate.aliases_for_objs status composites in
660       eval_alias status (mode,aliases)
661   | GrafiteAst.NQed (loc,index) ->
662      if status#ng_mode <> `ProofMode then
663       raise (GrafiteTypes.Command_error "Not in proof mode")
664      else
665       let uri,height,menv,subst,obj_kind = status#obj in
666        if menv <> [] then
667         raise
668          (GrafiteTypes.Command_error"You can't Qed an incomplete theorem")
669        else
670         let obj_kind =
671          NCicUntrusted.map_obj_kind 
672           (NCicUntrusted.apply_subst status subst []) obj_kind in
673         let height = NCicTypeChecker.height_of_obj_kind status uri [] obj_kind in
674         (* fix the height inside the object *)
675         let rec fix () = function 
676           | NCic.Const (NReference.Ref (u,spec)) when NUri.eq u uri -> 
677              NCic.Const (NReference.reference_of_spec u
678               (match spec with
679               | NReference.Def _ -> NReference.Def height
680               | NReference.Fix (i,j,_) -> NReference.Fix(i,j,height)
681               | NReference.CoFix i -> NReference.CoFix i
682               | NReference.Ind _ | NReference.Con _
683               | NReference.Decl as s -> s))
684           | t -> NCicUtils.map status (fun _ () -> ()) () fix t
685         in
686         let obj_kind = 
687           match obj_kind with
688           | NCic.Fixpoint _ -> 
689               NCicUntrusted.map_obj_kind (fix ()) obj_kind 
690           | _ -> obj_kind
691         in
692         let obj_kind = compute_relevance status uri obj_kind in
693         let obj = uri,height,[],[],obj_kind in
694         let old_status = status in
695         let status = NCicLibrary.add_obj status obj in
696         let status = eval_extract_obj status obj in
697         let status = eval_extract_ocaml_obj status obj in
698        (try
699         let index_obj = index &&
700          match obj_kind with
701             NCic.Constant (_,_,_,_,(_,`Example,_))
702           | NCic.Fixpoint (_,_,(_,`Example,_)) -> false
703           | _ -> true
704         in
705         let status =
706          if index_obj then
707           let status = index_obj_for_auto status obj in
708            (try index_eq_for_auto status uri
709            with
710               Sys.Break as exn -> raise exn
711             | _ -> status)
712          else
713           status in
714         (* purge tinycals stack *)
715         let ninitial_stack = Continuationals.Stack.of_nmetasenv [] in
716         let status = status#set_stack ninitial_stack in
717 (*
718           try 
719             index_eq uri status
720           with _ -> prerr_endline "got an exception"; status
721         in *)
722 (*         prerr_endline (status#ppobj obj); *)
723         HLog.message ("New object: " ^ NUri.string_of_uri uri);
724        (*prerr_endline (status#ppobj obj);*)
725            let boxml = NCicElim.mk_elims status obj in
726            let boxml = boxml @ NCicElim.mk_projections status obj in
727            let status = status#set_ng_mode `CommandMode in
728            let xxaliases = GrafiteDisambiguate.aliases_for_objs status [uri] in
729            let mode = GrafiteAst.WithPreferences in (* MATITA 1.0: fixme *)
730            let status = eval_alias status (mode,xxaliases) in
731            let status =
732             List.fold_left
733              (fun status boxml ->
734                try
735                 let nstatus =
736                  eval_ncommand ~include_paths opts status
737                   ("",0,GrafiteAst.NObj (HExtlib.dummy_floc,boxml,true))
738                 in
739                 if nstatus#ng_mode <> `CommandMode then
740                   begin
741                     (*HLog.warn "error in generating projection/eliminator";*)
742                     assert(status#ng_mode = `CommandMode);
743                     status
744                   end
745                 else
746                   nstatus
747                with
748                | MultiPassDisambiguator.DisambiguationError _ ->
749                   HLog.warn "error in disambiguating projection/eliminator";
750                   status
751                | NCicTypeChecker.TypeCheckerFailure _ ->
752                   HLog.warn "error in typechecking projection/eliminator";
753                   status
754              ) status boxml in             
755            let _,_,_,_,nobj = obj in
756            (* attempting to generate an inversion principle on the maximum
757             * universe can take a long time to fail: this code removes maximal
758             * sorts from the universe list *)
759            let universes = NCicEnvironment.get_universes () in
760            let max_univ = List.fold_left max [] universes in
761            let universes = 
762              List.filter (fun x -> NCicEnvironment.universe_lt x max_univ)
763                universes
764            in
765            let status = match nobj with
766                NCic.Inductive (is_ind,leftno,itl,_) ->
767                  List.fold_left (fun status it ->      
768                  (let _,ind_name,ty,cl = it in
769                   List.fold_left 
770                    (fun status outsort ->
771                       let status = status#set_ng_mode `ProofMode in
772                       try
773                        (let status,invobj =
774                          NInversion.mk_inverter 
775                           (ind_name ^ "_inv_" ^
776                             (snd (NCicElim.ast_of_sort outsort)))
777                           is_ind it leftno outsort status status#baseuri in
778                        let _,_,menv,_,_ = invobj in
779                         (match menv with
780                              [] -> eval_ncommand ~include_paths opts status
781                                     ("",0,GrafiteAst.NQed (Stdpp.dummy_loc,false))
782                            | _ -> status))
783                        (* XXX *)
784                       with
785                          Sys.Break as exn -> raise exn
786                        | _ -> (*HLog.warn "error in generating inversion principle"; *)
787                                 let status = status#set_ng_mode `CommandMode in status)
788                   status
789                   (NCic.Prop::
790                     List.map (fun s -> NCic.Type s) universes))) status itl
791               | _ -> status
792            in
793            let status = match nobj with
794                NCic.Inductive (is_ind,leftno,itl,_) ->
795                  (* first leibniz *)
796                  let status' = List.fold_left
797                    (fun status it ->
798                       let _,ind_name,ty,cl = it in
799                       let status = status#set_ng_mode `ProofMode in
800                       try
801                        (let status,invobj =
802                          NDestructTac.mk_discriminator ~use_jmeq:false
803                           (ind_name ^ "_discr")
804                           it leftno status status#baseuri in
805                        let _,_,menv,_,_ = invobj in
806                         (match menv with
807                              [] -> eval_ncommand ~include_paths opts status
808                                     ("",0,GrafiteAst.NQed(Stdpp.dummy_loc,false))
809                            | _ -> status))
810                        (* XXX *)
811                       with 
812                       | NDestructTac.ConstructorTooBig k -> 
813                           HLog.warn (Printf.sprintf 
814                            "unable to generate leibniz discrimination principle (constructor %s too big)"
815                            k);
816                            let status = status#set_ng_mode `CommandMode in status
817                       | _ -> (*HLog.warn "error in generating discrimination principle"; *)
818                                 let status = status#set_ng_mode `CommandMode in
819                                 status)
820                   status itl
821                 in
822                 (* then JMeq *)
823                 List.fold_left
824                    (fun status it ->
825                       let _,ind_name,ty,cl = it in
826                       let status = status#set_ng_mode `ProofMode in
827                       try
828                        (let status,invobj =
829                          NDestructTac.mk_discriminator ~use_jmeq:true
830                           (ind_name ^ "_jmdiscr")
831                           it leftno status status#baseuri in
832                        let _,_,menv,_,_ = invobj in
833                         (match menv with
834                              [] -> eval_ncommand ~include_paths opts status
835                                     ("",0,GrafiteAst.NQed(Stdpp.dummy_loc,false))
836                            | _ -> status))
837                        (* XXX *)
838                       with
839                          Sys.Break as exn -> raise exn
840                        | _ -> (*HLog.warn "error in generating discrimination principle"; *)
841                                 let status = status#set_ng_mode `CommandMode in
842                                 status)
843                   status' itl
844               | _ -> status
845            in
846            let coercions =
847             match obj with
848               _,_,_,_,NCic.Inductive
849                (true,leftno,[_,_,_,[_,_,_]],(_,`Record fields))
850                ->
851                 HExtlib.filter_map
852                  (fun (name,is_coercion,arity) ->
853                    if is_coercion then Some(name,leftno,arity) else None) fields
854             | _ -> [] in
855            let status =
856             List.fold_left
857              (fun status (name,cpos,arity) ->
858                try
859                  let metasenv,subst,status,t =
860                   GrafiteDisambiguate.disambiguate_nterm status `XTNone [] [] []
861                    ("",0,NotationPt.Ident (name,None)) in
862                  assert (metasenv = [] && subst = []);
863                  let status, nuris = 
864                    NCicCoercDeclaration.
865                      basic_eval_and_record_ncoercion_from_t_cpos_arity 
866                       status (name,true,t,cpos,arity) in
867                  let aliases = GrafiteDisambiguate.aliases_for_objs status nuris in
868                  let status = extract_uris status nuris in
869                   eval_alias status (mode,aliases)
870                with MultiPassDisambiguator.DisambiguationError _-> 
871                  HLog.warn ("error in generating coercion: "^name);
872                  status) 
873              status coercions
874            in
875             status
876           with
877            exn ->
878             NCicLibrary.time_travel old_status;
879             raise exn)
880   | GrafiteAst.NCopy (log,tgt,src_uri, map) ->
881      if status#ng_mode <> `CommandMode then
882       raise (GrafiteTypes.Command_error "Not in command mode")
883      else
884        let tgt_uri_ext, old_ok = 
885          match NCicEnvironment.get_checked_obj status src_uri with
886          | _,_,[],[], (NCic.Inductive _ as ok) -> ".ind", ok
887          | _,_,[],[], (NCic.Fixpoint _ as ok) -> ".con", ok
888          | _,_,[],[], (NCic.Constant _ as ok) -> ".con", ok
889          | _ -> assert false
890        in
891        let tgt_uri = NUri.uri_of_string (status#baseuri^"/"^tgt^tgt_uri_ext) in
892        let map = (src_uri, tgt_uri) :: map in
893        let ok = 
894          let rec subst () = function
895            | NCic.Meta _ -> assert false
896            | NCic.Const (NReference.Ref (u,spec)) as t ->
897                (try NCic.Const 
898                  (NReference.reference_of_spec (List.assoc u map)spec)
899                with Not_found -> t)
900            | t -> NCicUtils.map status (fun _ _ -> ()) () subst t
901          in
902          NCicUntrusted.map_obj_kind ~skip_body:false (subst ()) old_ok
903        in
904        let ninitial_stack = Continuationals.Stack.of_nmetasenv [] in
905        let status = status#set_obj (tgt_uri,0,[],[],ok) in
906        (*prerr_endline (status#ppobj (tgt_uri,0,[],[],ok));*)
907        let status = status#set_stack ninitial_stack in
908        let status = subst_metasenv_and_fix_names status in
909        let status = status#set_ng_mode `ProofMode in
910        eval_ncommand ~include_paths opts status ("",0,GrafiteAst.NQed(Stdpp.dummy_loc,false))
911   | GrafiteAst.NObj (loc,obj,index) ->
912      if status#ng_mode <> `CommandMode then
913       raise (GrafiteTypes.Command_error "Not in command mode")
914      else
915       let status,obj =
916        GrafiteDisambiguate.disambiguate_nobj status
917         ~baseuri:status#baseuri (text,prefix_len,obj) in
918       let uri,height,nmenv,nsubst,nobj = obj in
919       let ninitial_stack = Continuationals.Stack.of_nmetasenv nmenv in
920       let status = status#set_obj obj in
921       let status = status#set_stack ninitial_stack in
922       let status = subst_metasenv_and_fix_names status in
923       let status = status#set_ng_mode `ProofMode in
924       (match nmenv with
925           [] ->
926            eval_ncommand ~include_paths opts status
927              ("",0,GrafiteAst.NQed(Stdpp.dummy_loc,index))
928         | _ -> status)
929   | GrafiteAst.NDiscriminator (loc, indty) ->
930       if status#ng_mode <> `CommandMode then
931         raise (GrafiteTypes.Command_error "Not in command mode")
932       else
933         let status = status#set_ng_mode `ProofMode in
934         let metasenv,subst,status,indty =
935           GrafiteDisambiguate.disambiguate_nterm status `XTNone [] [] [] (text,prefix_len,indty) in
936         let indtyno, (_,_,tys,_,_),leftno = match indty with
937             NCic.Const ((NReference.Ref (_,NReference.Ind (_,indtyno,leftno))) as r) ->
938               indtyno, NCicEnvironment.get_checked_indtys status r, leftno
939           | _ -> prerr_endline ("engine: indty expected... (fix this error message)"); assert false in
940         let (_,ind_name,_,_ as it) = List.nth tys indtyno in
941         let status,obj =  
942           NDestructTac.mk_discriminator ~use_jmeq:true ~force:true (ind_name ^ "_jmdiscr")
943            it leftno status status#baseuri in
944         let _,_,menv,_,_ = obj in
945           (match menv with
946                [] -> eval_ncommand ~include_paths opts status ("",0,GrafiteAst.NQed(Stdpp.dummy_loc,false))
947              | _ -> prerr_endline ("Discriminator: non empty metasenv");
948                     status)
949   | GrafiteAst.NInverter (loc, name, indty, selection, sort) ->
950      if status#ng_mode <> `CommandMode then
951       raise (GrafiteTypes.Command_error "Not in command mode")
952      else
953       let metasenv,subst,status,sort = match sort with
954         | None -> [],[],status,NCic.Sort NCic.Prop
955         | Some s ->
956            GrafiteDisambiguate.disambiguate_nterm status `XTSort [] [] []
957             (text,prefix_len,s) 
958       in
959       assert (metasenv = []);
960       let sort = NCicReduction.whd status ~subst [] sort in
961       let sort =
962        match sort with 
963           NCic.Sort s -> s
964         | _ ->
965            raise (Invalid_argument (Printf.sprintf
966             "ninverter: found target %s, which is not a sort"
967              (status#ppterm ~metasenv ~subst ~context:[] sort))) in
968       let status = status#set_ng_mode `ProofMode in
969       let metasenv,subst,status,indty =
970        GrafiteDisambiguate.disambiguate_nterm status `XTNone [] [] subst
971         (text,prefix_len,indty) in
972       let indtyno,(_,leftno,tys,_,_) =
973        match indty with
974           NCic.Const ((NReference.Ref (_,NReference.Ind (_,indtyno,_))) as r) ->
975            indtyno, NCicEnvironment.get_checked_indtys status r
976         | _ ->
977           prerr_endline ("engine: indty ="  ^ status#ppterm ~metasenv:[]
978            ~subst:[] ~context:[] indty);
979           assert false in
980       let it = List.nth tys indtyno in
981       let status,obj =
982        NInversion.mk_inverter name true it leftno ?selection sort 
983         status status#baseuri in
984       let _,_,menv,_,_ = obj in
985        (match menv with
986           [] ->
987             eval_ncommand ~include_paths opts status
988              ("",0,GrafiteAst.NQed(Stdpp.dummy_loc,false))
989         | _ -> assert false)
990   | GrafiteAst.NUnivConstraint (loc,acyclic,u1,u2) ->
991       eval_add_constraint status acyclic [`Type,u1] [`Type,u2]
992   (* ex lexicon commands *)
993   | GrafiteAst.Interpretation (loc, dsc, (symbol, args), cic_appl_pattern) ->
994      let cic_appl_pattern =
995       GrafiteDisambiguate.disambiguate_cic_appl_pattern status args
996        cic_appl_pattern
997      in
998       eval_interpretation status (dsc,(symbol, args),cic_appl_pattern)
999   | GrafiteAst.Notation (loc, dir, l1, associativity, precedence, l2) ->
1000       let l1 = 
1001         CicNotationParser.check_l1_pattern
1002          l1 (dir = Some `RightToLeft) precedence associativity
1003       in
1004       let status =
1005         if dir <> Some `RightToLeft then eval_input_notation status (l1,l2)
1006         else status
1007       in
1008        if dir <> Some `LeftToRight then eval_output_notation status (l1,l2)
1009        else status
1010   | GrafiteAst.Alias (loc, spec) -> 
1011      let diff =
1012       (*CSC: Warning: this code should be factorized with the corresponding
1013              code in DisambiguatePp *)
1014       match spec with
1015       | GrafiteAst.Ident_alias (id,uri) -> 
1016          [DisambiguateTypes.Id id,spec]
1017       | GrafiteAst.Symbol_alias (symb, instance, desc) ->
1018          [DisambiguateTypes.Symbol (symb,instance),spec]
1019       | GrafiteAst.Number_alias (instance,desc) ->
1020          [DisambiguateTypes.Num instance,spec]
1021      in
1022       let mode = GrafiteAst.WithPreferences in(*assert false in (* VEDI SOPRA *) MATITA 1.0*)
1023        eval_alias status (mode,diff)
1024 ;;
1025
1026 let eval_comment opts status (text,prefix_len,c) = status
1027
1028 let rec eval_executable ~include_paths opts status (text,prefix_len,ex) =
1029   match ex with
1030   | GrafiteAst.NTactic (_(*loc*), tacl) ->
1031       if status#ng_mode <> `ProofMode then
1032        raise (GrafiteTypes.Command_error "Not in proof mode")
1033       else
1034        let status =
1035         List.fold_left 
1036           (fun status tac ->
1037             let time0 = Unix.gettimeofday () in
1038             let status = eval_ng_tac (text,prefix_len,tac) status in
1039             let time3 = Unix.gettimeofday () in
1040             HLog.debug ("... eval_ng_tac done in " ^ string_of_float (time3 -. time0) ^ "s");
1041             let status = subst_metasenv_and_fix_names status in
1042             let time3 = Unix.gettimeofday () in
1043             HLog.debug ("... subst_metasenv_and_fix_names done in " ^ string_of_float (time3 -. time0) ^ "s"); status)
1044           status tacl
1045        in
1046         status
1047   | GrafiteAst.NCommand (_, cmd) ->
1048       eval_ncommand ~include_paths opts status (text,prefix_len,cmd)
1049   | GrafiteAst.NMacro (loc, macro) ->
1050      raise (NMacro (loc,macro))
1051
1052 and eval_ast ~include_paths ?(do_heavy_checks=false) status (text,prefix_len,st)
1053 =
1054   let opts = { do_heavy_checks = do_heavy_checks ; } in
1055   match st with
1056   | GrafiteAst.Executable (_,ex) ->
1057      eval_executable ~include_paths opts status (text,prefix_len,ex)
1058   | GrafiteAst.Comment (_,c) -> 
1059       eval_comment opts status (text,prefix_len,c) 
1060 ;;