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