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