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