]> matita.cs.unibo.it Git - helm.git/blob - helm/software/components/ng_cic_content/nTermCicContent.ml
Huge commit with several changes:
[helm.git] / helm / software / components / ng_cic_content / nTermCicContent.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: termAcicContent.ml 9304 2008-12-05 23:12:39Z sacerdot $ *)
27
28 open Printf
29
30 module Ast = CicNotationPt
31
32 let debug = false
33 let debug_print s = if debug then prerr_endline (Lazy.force s) else ()
34
35 type id = string
36
37 (*
38 type interpretation_id = int
39
40 type term_info =
41   { sort: (Cic.id, Ast.sort_kind) Hashtbl.t;
42     uri: (Cic.id, UriManager.uri) Hashtbl.t;
43   }
44
45 let get_types uri =
46   let o,_ = CicEnvironment.get_obj CicUniv.oblivion_ugraph uri in
47     match o with
48       | Cic.InductiveDefinition (l,_,leftno,_) -> l, leftno 
49       | _ -> assert false
50 *)
51
52 let idref register_ref =
53  let id = ref 0 in
54   fun ?reference t ->
55    incr id;
56    let id = "i" ^ string_of_int !id in
57     (match reference with None -> () | Some r -> register_ref id r);
58     Ast.AttributedTerm (`IdRef id, t)
59 ;;
60
61 (* CODICE c&p da NCicPp *)
62 let nast_of_cic0
63  ~(idref:
64     ?reference:NReference.reference -> CicNotationPt.term -> CicNotationPt.term)
65  ~output_type ~subst k ~context =
66   function
67     | NCic.Rel n ->
68        (try 
69          let name,_ = List.nth context (n-1) in
70          let name = if name = "_" then "__"^string_of_int n else name in
71           idref (Ast.Ident (name,None))
72         with Failure "nth" | Invalid_argument "List.nth" -> 
73          idref (Ast.Ident ("-" ^ string_of_int (n - List.length context),None)))
74     | NCic.Const r -> idref ~reference:r (Ast.Ident (NCicPp.r2s true r, None))
75     | NCic.Meta (n,lc) when List.mem_assoc n subst -> 
76         let _,_,t,_ = List.assoc n subst in
77          k ~context (NCicSubstitution.subst_meta lc t)
78     | NCic.Meta (n,(s,l)) ->
79        (* CSC: qua non dovremmo espandere *)
80        let l = NCicUtils.expand_local_context l in
81         idref (Ast.Meta
82          (n, List.map (fun x -> Some (k ~context (NCicSubstitution.lift s x))) l))
83     | NCic.Sort NCic.Prop -> idref (Ast.Sort `Prop)
84     | NCic.Sort NCic.Type _ -> idref (Ast.Sort `Set)
85     (* CSC: | C.Sort (C.Type []) -> F.fprintf f "Type0"
86     | C.Sort (C.Type [false, u]) -> F.fprintf f "%s" (NUri.name_of_uri u)
87     | C.Sort (C.Type [true, u]) -> F.fprintf f "S(%s)" (NUri.name_of_uri u)
88     | C.Sort (C.Type l) -> 
89        F.fprintf f "Max(";
90        aux ctx (C.Sort (C.Type [List.hd l]));
91        List.iter (fun x -> F.fprintf f ",";aux ctx (C.Sort (C.Type [x])))
92         (List.tl l);
93        F.fprintf f ")"*)
94     (* CSC: qua siamo grezzi *)
95     | NCic.Implicit `Hole -> idref (Ast.UserInput)
96     | NCic.Implicit _ -> idref (Ast.Implicit)
97     | NCic.Prod (n,s,t) ->
98         let n = if n.[0] = '_' then "_" else n in
99         let binder_kind = `Forall in
100          idref (Ast.Binder (binder_kind, (Ast.Ident (n,None), Some (k ~context s)),
101           k ~context:((n,NCic.Decl s)::context) t))
102     | NCic.Lambda (n,s,t) ->
103         idref (Ast.Binder (`Lambda,(Ast.Ident (n,None), Some (k ~context s)),
104          k ~context:((n,NCic.Decl s)::context) t))
105     | NCic.LetIn (n,s,ty,t) ->
106         idref (Ast.LetIn ((Ast.Ident (n,None), Some (k ~context ty)), k ~context s,
107          k ~context:((n,NCic.Decl s)::context) t))
108     | NCic.Appl (NCic.Meta (n,lc) :: args) when List.mem_assoc n subst -> 
109        let _,_,t,_ = List.assoc n subst in
110        let hd = NCicSubstitution.subst_meta lc t in
111         k ~context
112          (NCicReduction.head_beta_reduce ~upto:(List.length args)
113            (match hd with
114            | NCic.Appl l -> NCic.Appl (l@args)
115            | _ -> NCic.Appl (hd :: args)))
116     | NCic.Appl args -> idref (Ast.Appl (List.map (k ~context) args))
117     | NCic.Match (NReference.Ref (uri,_) as r,outty,te,patterns) ->
118         let name = NUri.name_of_uri uri in
119 (* CSC
120         let uri_str = UriManager.string_of_uri uri in
121         let puri_str = sprintf "%s#xpointer(1/%d)" uri_str (typeno+1) in
122         let ctor_puri j =
123           UriManager.uri_of_string
124             (sprintf "%s#xpointer(1/%d/%d)" uri_str (typeno+1) j)
125         in
126 *)
127         let case_indty =
128          name, None(*CSC Some (UriManager.uri_of_string puri_str)*) in
129         let constructors, leftno =
130          let _,leftno,tys,_,n = NCicEnvironment.get_checked_indtys r in
131          let _,_,_,cl  = List.nth tys n in
132           cl,leftno
133         in
134         let rec eat_branch n ctx ty pat =
135           match (ty, pat) with
136           | NCic.Prod (name, s, t), _ when n > 0 ->
137              eat_branch (pred n) ((name,NCic.Decl s)::ctx) t pat 
138           | NCic.Prod (_, _, t), NCic.Lambda (name, s, t') ->
139               let cv, rhs = eat_branch 0 ((name,NCic.Decl s)::ctx) t t' in
140               (Ast.Ident (name,None), Some (k ~context s)) :: cv, rhs
141           | _, _ -> [], k ~context pat
142         in
143         let j = ref 0 in
144         let patterns =
145           try
146             List.map2
147               (fun (_, name, ty) pat ->
148                 incr j;
149                 let name,(capture_variables,rhs) =
150                  match output_type with
151                     `Term -> name, eat_branch leftno context ty pat
152                   | `Pattern -> "_", ([], k ~context pat)
153                 in
154                  Ast.Pattern (name, None(*CSC Some (ctor_puri !j)*), capture_variables), rhs
155               ) constructors patterns
156           with Invalid_argument _ -> assert false
157         in
158         let indty =
159          match output_type with
160             `Pattern -> None
161           | `Term -> Some case_indty
162         in
163          idref (Ast.Case (k ~context te, indty, Some (k ~context outty), patterns))
164 ;;
165
166   (* persistent state *)
167
168 (*
169 let initial_level2_patterns32 () = Hashtbl.create 211
170 let initial_interpretations () = Hashtbl.create 211
171
172 let level2_patterns32 = ref (initial_level2_patterns32 ())
173 (* symb -> id list ref *)
174 let interpretations = ref (initial_interpretations ())
175 *)
176 let compiled32 = ref None
177 (*
178 let pattern32_matrix = ref []
179 let counter = ref ~-1 
180
181 let stack = ref []
182
183 let push () =
184  stack := (!counter,!level2_patterns32,!interpretations,!compiled32,!pattern32_matrix)::!stack;
185  counter := ~-1;
186  level2_patterns32 := initial_level2_patterns32 ();
187  interpretations := initial_interpretations ();
188  compiled32 := None;
189  pattern32_matrix := []
190 ;;
191
192 let pop () =
193  match !stack with
194     [] -> assert false
195   | (ocounter,olevel2_patterns32,ointerpretations,ocompiled32,opattern32_matrix)::old ->
196    stack := old;
197    counter := ocounter;
198    level2_patterns32 := olevel2_patterns32;
199    interpretations := ointerpretations;
200    compiled32 := ocompiled32;
201    pattern32_matrix := opattern32_matrix
202 ;;
203 *)
204
205 let get_compiled32 () =
206   match !compiled32 with
207   | None -> assert false
208   | Some f -> Lazy.force f
209
210 let set_compiled32 f = compiled32 := Some f
211
212 let add_idrefs =
213   List.fold_right (fun idref t -> Ast.AttributedTerm (`IdRef idref, t))
214
215 let instantiate32 idrefs env symbol args =
216   let rec instantiate_arg = function
217     | Ast.IdentArg (n, name) ->
218         let t = 
219           try List.assoc name env 
220           with Not_found -> prerr_endline ("name not found in env: "^name);
221                             assert false
222         in
223         let rec count_lambda = function
224           | Ast.AttributedTerm (_, t) -> count_lambda t
225           | Ast.Binder (`Lambda, _, body) -> 1 + count_lambda body
226           | _ -> 0
227         in
228         let rec add_lambda t n =
229           if n > 0 then
230             let name = CicNotationUtil.fresh_name () in
231             Ast.Binder (`Lambda, (Ast.Ident (name, None), None),
232               Ast.Appl [add_lambda t (n - 1); Ast.Ident (name, None)])
233           else
234             t
235         in
236         add_lambda t (n - count_lambda t)
237   in
238   let head =
239     let symbol = Ast.Symbol (symbol, 0) in
240     add_idrefs idrefs symbol
241   in
242   if args = [] then head
243   else Ast.Appl (head :: List.map instantiate_arg args)
244
245 let rec nast_of_cic1 ~idref ~output_type ~subst ~context term = 
246   match (get_compiled32 ()) term with
247   | None ->
248      nast_of_cic0 ~idref ~output_type ~subst
249       (nast_of_cic1 ~idref ~output_type ~subst) ~context term 
250   | Some (env, ctors, pid) -> 
251       let idrefs =
252        List.map
253         (fun term ->
254           let attrterm =
255            idref
256             ~reference:
257               (match term with NCic.Const nref -> nref | _ -> assert false)
258            (CicNotationPt.Ident ("dummy",None))
259           in
260            match attrterm with
261               Ast.AttributedTerm (`IdRef id, _) -> id
262             | _ -> assert false
263         ) ctors
264       in
265       let env =
266        List.map
267         (fun (name, term) ->
268           name,
269            nast_of_cic1 ~idref ~output_type ~subst ~context term
270         ) env
271       in
272       let _, symbol, args, _ =
273         try
274           TermAcicContent.find_level2_patterns32 pid
275         with Not_found -> assert false
276       in
277       let ast = instantiate32 idrefs env symbol args in
278       idref ast (*Ast.AttributedTerm (`IdRef (idref term), ast)*)
279 ;;
280
281 let load_patterns32 t =
282  let t =
283   HExtlib.filter_map (function (true, ap, id) -> Some (ap, id) | _ -> None) t
284  in
285   set_compiled32 (lazy (Ncic2astMatcher.Matcher32.compiler t))
286 in
287  TermAcicContent.add_load_patterns32 load_patterns32;
288  TermAcicContent.init ()
289 ;;
290
291 (*
292 let ast_of_acic ~output_type id_to_sort annterm =
293   debug_print (lazy ("ast_of_acic <- "
294     ^ CicPp.ppterm (Deannotate.deannotate_term annterm)));
295   let term_info = { sort = id_to_sort; uri = Hashtbl.create 211 } in
296   let ast = ast_of_acic1 ~output_type term_info annterm in
297   debug_print (lazy ("ast_of_acic -> " ^ CicNotationPp.pp_term ast));
298   ast, term_info.uri
299
300 let fresh_id =
301   fun () ->
302     incr counter;
303     !counter
304
305 let add_interpretation dsc (symbol, args) appl_pattern =
306   let id = fresh_id () in
307   Hashtbl.add !level2_patterns32 id (dsc, symbol, args, appl_pattern);
308   pattern32_matrix := (true, appl_pattern, id) :: !pattern32_matrix;
309   load_patterns32 !pattern32_matrix;
310   (try
311     let ids = Hashtbl.find !interpretations symbol in
312     ids := id :: !ids
313   with Not_found -> Hashtbl.add !interpretations symbol (ref [id]));
314   id
315
316 let get_all_interpretations () =
317   List.map
318     (function (_, _, id) ->
319       let (dsc, _, _, _) =
320         try
321           Hashtbl.find !level2_patterns32 id
322         with Not_found -> assert false
323       in
324       (id, dsc))
325     !pattern32_matrix
326
327 let get_active_interpretations () =
328   HExtlib.filter_map (function (true, _, id) -> Some id | _ -> None)
329     !pattern32_matrix
330
331 let set_active_interpretations ids =
332   let pattern32_matrix' =
333     List.map
334       (function 
335         | (_, ap, id) when List.mem id ids -> (true, ap, id)
336         | (_, ap, id) -> (false, ap, id))
337       !pattern32_matrix
338   in
339   pattern32_matrix := pattern32_matrix';
340   load_patterns32 !pattern32_matrix
341
342 exception Interpretation_not_found
343
344 let lookup_interpretations symbol =
345   try
346    HExtlib.list_uniq
347     (List.sort Pervasives.compare
348      (List.map
349       (fun id ->
350         let (dsc, _, args, appl_pattern) =
351           try
352             Hashtbl.find !level2_patterns32 id
353           with Not_found -> assert false 
354         in
355         dsc, args, appl_pattern)
356       !(Hashtbl.find !interpretations symbol)))
357   with Not_found -> raise Interpretation_not_found
358
359 let remove_interpretation id =
360   (try
361     let dsc, symbol, _, _ = Hashtbl.find !level2_patterns32 id in
362     let ids = Hashtbl.find !interpretations symbol in
363     ids := List.filter ((<>) id) !ids;
364     Hashtbl.remove !level2_patterns32 id;
365   with Not_found -> raise Interpretation_not_found);
366   pattern32_matrix :=
367     List.filter (fun (_, _, id') -> id <> id') !pattern32_matrix;
368   load_patterns32 !pattern32_matrix
369
370 let _ = load_patterns32 []
371
372 let instantiate_appl_pattern 
373   ~mk_appl ~mk_implicit ~term_of_uri env appl_pattern 
374 =
375   let lookup name =
376     try List.assoc name env
377     with Not_found ->
378       prerr_endline (sprintf "Name %s not found" name);
379       assert false
380   in
381   let rec aux = function
382     | Ast.UriPattern uri -> term_of_uri uri
383     | Ast.ImplicitPattern -> mk_implicit false
384     | Ast.VarPattern name -> lookup name
385     | Ast.ApplPattern terms -> mk_appl (List.map aux terms)
386   in
387   aux appl_pattern
388 *)
389
390 let nmap_sequent ~subst (i,(n,context,ty):int * NCic.conjecture) =
391  let module K = Content in
392  let ids_to_refs = Hashtbl.create 211 in
393  let register_ref = Hashtbl.add ids_to_refs in
394  let nast_of_cic =
395   nast_of_cic1 ~idref:(idref register_ref) ~output_type:`Term
396    ~subst in
397  let context',_ =
398   List.fold_right
399    (fun item (res,context) ->
400      match item with
401       | name,NCic.Decl t ->
402          Some
403           (* We should call build_decl_item, but we have not computed *)
404           (* the inner-types ==> we always produce a declaration      *)
405           (`Declaration
406             { K.dec_name = (Some name);
407               K.dec_id = "-1"; 
408               K.dec_inductive = false;
409               K.dec_aref = "-1";
410               K.dec_type = nast_of_cic ~context t
411             })::res,item::context
412       | name,NCic.Def (t,ty) ->
413          Some
414           (* We should call build_def_item, but we have not computed *)
415           (* the inner-types ==> we always produce a declaration     *)
416           (`Definition
417              { K.def_name = (Some name);
418                K.def_id = "-1"; 
419                K.def_aref = "-1";
420                K.def_term = nast_of_cic ~context t;
421                K.def_type = nast_of_cic ~context ty
422              })::res,item::context
423    ) context ([],[])
424  in
425   ("-1",i,context',nast_of_cic ~context ty), ids_to_refs
426 ;;
427