]> matita.cs.unibo.it Git - helm.git/blob - matitaB/components/ng_cic_content/interpretations.ml
WIP on cpce ...
[helm.git] / matitaB / components / ng_cic_content / interpretations.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 open Printf
29
30 module Ast = NotationPt
31
32
33 let debug = false
34 let debug_print s = if debug then prerr_endline (Lazy.force s) else ()
35
36 type id = string
37 let hide_coercions = ref true;;
38
39 type cic_id = string
40
41 module IntMap = Map.Make(struct type t = int let compare = compare end);;
42 module StringMap = Map.Make(String);;
43
44 type db = {
45   counter: int;
46   pattern32_matrix: (bool * NotationPt.cic_appl_pattern * int) list;
47   level2_patterns32:
48    (string * string * NotationPt.argument_pattern list *
49      NotationPt.cic_appl_pattern) IntMap.t;
50   interpretations: int list StringMap.t; (* symb -> id list *)
51   compiled32:
52    (NCic.term -> ((string * NCic.term) list * NCic.term list * int) option)
53     Lazy.t
54 }
55
56 let initial_db status = {
57    counter = -1; 
58    pattern32_matrix = [];
59    level2_patterns32 = IntMap.empty;
60    interpretations = StringMap.empty;
61    compiled32 = lazy (Ncic2astMatcher.Matcher32.compiler status [])
62 }
63
64 class type g_status =
65   object
66     inherit NCicCoercion.g_status
67     method interp_db: db
68   end
69  
70 class virtual status uid =
71  object(self)
72    inherit NCicCoercion.status uid
73    val mutable interp_db = None (* mutable only to initialize it :-( *)
74    method interp_db = match interp_db with None -> assert false | Some x -> x
75    method set_interp_db v = {< interp_db = Some v >}
76    method set_interp_status
77     : 'status. #g_status as 'status -> 'self
78     = fun o -> {< interp_db = Some o#interp_db >}#set_coercion_status o
79    initializer
80     interp_db <- Some (initial_db self)
81  end
82
83 let level_of_uri u = 
84   let name = NUri.name_of_uri u in
85   assert(String.length name > String.length "Type");
86   String.sub name 4 (String.length name - 4)
87 ;;
88
89 let find_level2_patterns32 status pid =
90  IntMap.find pid status#interp_db.level2_patterns32
91
92 let instantiate32 env symbol dsc args =
93   let rec instantiate_arg = function
94     | Ast.IdentArg (n, name) ->
95         let t = 
96           try List.assoc name env 
97           with Not_found -> prerr_endline ("name not found in env: "^name);
98                             assert false
99         in
100         let rec count_lambda = function
101           | Ast.AttributedTerm (_, t) -> count_lambda t
102           | Ast.Binder (`Lambda, _, body) -> 1 + count_lambda body
103           | _ -> 0
104         in
105         let rec add_lambda t n =
106           if n > 0 then
107             let name = NotationUtil.fresh_name () in
108             Ast.Binder (`Lambda, (Ast.Ident (name, `Ambiguous), None),
109               Ast.Appl [add_lambda t (n - 1); Ast.Ident (name, `Ambiguous)])
110           else
111             t
112         in
113         add_lambda t (n - count_lambda t)
114   in
115   let head = Ast.Symbol (symbol, Some (None, dsc)) in
116   if args = [] then head
117   else Ast.Appl (head :: List.map instantiate_arg args)
118
119 let fresh_id status =
120   let counter = status#interp_db.counter + 1 in
121     status#set_interp_db {status#interp_db with counter = counter},counter
122
123 let load_patterns32 status t =
124  let t =
125   HExtlib.filter_map (function (true, ap, id) -> Some (ap, id) | _ -> None) t
126  in
127   status#set_interp_db
128    {status#interp_db with
129      compiled32 = lazy (Ncic2astMatcher.Matcher32.compiler status t) }
130 ;;
131
132 let add_interpretation status dsc (symbol, args) appl_pattern =
133   let status,id = fresh_id status in
134   let ids =
135    try
136     id::StringMap.find symbol status#interp_db.interpretations
137    with Not_found -> [id] in
138   let status =
139    status#set_interp_db { status#interp_db with
140     level2_patterns32 =
141       IntMap.add id (dsc, symbol, args, appl_pattern)
142        status#interp_db.level2_patterns32;
143     pattern32_matrix = (true,appl_pattern,id)::status#interp_db.pattern32_matrix;
144     interpretations = StringMap.add symbol ids status#interp_db.interpretations
145    }
146   in
147    load_patterns32 status status#interp_db.pattern32_matrix
148
149 let toggle_active_interpretations status b =
150   status#set_interp_db { status#interp_db with
151    pattern32_matrix =
152      List.map (fun (_,ap,id) -> b,ap,id) status#interp_db.pattern32_matrix }
153
154 exception Interpretation_not_found
155
156 let lookup_interpretations status ?(sorted=true) symbol =
157   try
158     let raw = 
159       List.map (
160         fun id ->
161           let (dsc, _, args, appl_pattern) =
162             try IntMap.find id status#interp_db.level2_patterns32
163             with Not_found -> assert false 
164           in
165           dsc, args, appl_pattern
166       ) (StringMap.find symbol status#interp_db.interpretations)
167     in
168     if sorted then HExtlib.list_uniq (List.sort Pervasives.compare raw)
169               else raw
170   with Not_found -> raise Interpretation_not_found
171
172 let instantiate_appl_pattern 
173   ~mk_appl ~mk_implicit ~term_of_nref env appl_pattern 
174 =
175   let lookup name =
176     try List.assoc name env
177     with Not_found ->
178       prerr_endline (sprintf "Name %s not found" name);
179       assert false
180   in
181   let rec aux = function
182     | Ast.NRefPattern nref -> term_of_nref nref
183     | Ast.ImplicitPattern -> mk_implicit false
184     | Ast.VarPattern name -> lookup name
185     | Ast.ApplPattern terms -> mk_appl (List.map aux terms)
186   in
187   aux appl_pattern
188
189 let destroy_nat =
190   let is_nat_URI = NUri.eq (NUri.uri_of_string
191   "cic:/matita/arithmetics/nat/nat.ind") in
192   let is_zero = function
193     | NCic.Const (NReference.Ref (uri, NReference.Con (0, 1, 0))) when
194        is_nat_URI uri -> true
195     | _ -> false
196   in
197   let is_succ = function
198     | NCic.Const (NReference.Ref (uri, NReference.Con (0, 2, 0))) when
199        is_nat_URI uri -> true
200     | _ -> false
201   in
202   let rec aux acc = function
203     | NCic.Appl [he ; tl] when is_succ he -> aux (acc + 1) tl
204     | t when is_zero t -> Some acc
205     | _ -> None
206   in
207    aux 0
208
209 let nast_of_cic0 status
210  ~output_type ~metasenv ~subst k ~context =
211   function
212     | NCic.Rel n ->
213        (try 
214          let name,_ = List.nth context (n-1) in
215          let name = if name = "_" then "__"^string_of_int n else name in
216           Ast.Ident (name,`Ambiguous)
217         with Failure "nth" | Invalid_argument "List.nth" -> 
218          Ast.Ident ("-" ^ string_of_int (n - List.length context),`Ambiguous))
219     | NCic.Const r -> 
220         let uri = `Uri (NReference.string_of_reference r) in
221         Ast.Ident (NCicPp.r2s status true r, uri)
222     | NCic.Meta (n,lc) when List.mem_assoc n subst -> 
223         let _,_,t,_ = List.assoc n subst in
224          k ~context (NCicSubstitution.subst_meta status lc t)
225     | NCic.Meta (n,(s,l)) ->
226        (* CSC: qua non dovremmo espandere *)
227        let l = NCicUtils.expand_local_context l in
228        Ast.Meta
229          (n, List.map (fun x -> Some (k ~context (NCicSubstitution.lift status s x))) l)
230     | NCic.Sort NCic.Prop -> Ast.Sort `Prop
231     | NCic.Sort NCic.Type [] -> Ast.Sort `Set
232     | NCic.Sort NCic.Type ((`Type,u)::_) -> 
233               Ast.Sort (`NType (level_of_uri u))
234     | NCic.Sort NCic.Type ((`CProp,u)::_) -> 
235               Ast.Sort (`NCProp (level_of_uri u))
236     | NCic.Sort NCic.Type ((`Succ,u)::_) -> 
237               Ast.Sort (`NType (level_of_uri u ^ "+1"))
238     | NCic.Implicit `Hole -> Ast.UserInput
239     | NCic.Implicit `Vector -> Ast.Implicit `Vector
240     | NCic.Implicit _ -> Ast.Implicit `JustOne
241     | NCic.Prod (n,s,t) ->
242         let n = if n.[0] = '_' then "_" else n in
243         let binder_kind = `Forall in
244           Ast.Binder (binder_kind, (Ast.Ident (n,`Ambiguous), Some (k ~context s)),
245           k ~context:((n,NCic.Decl s)::context) t)
246     | NCic.Lambda (n,s,t) ->
247         Ast.Binder (`Lambda,(Ast.Ident (n,`Ambiguous), Some (k ~context s)),
248                     k ~context:((n,NCic.Decl s)::context) t)
249     | NCic.LetIn (n,s,ty,NCic.Rel 1) ->
250         Ast.Cast (k ~context ty, k ~context s)
251     | NCic.LetIn (n,s,ty,t) ->
252         Ast.LetIn ((Ast.Ident (n,`Ambiguous), Some (k ~context s)), k ~context
253           ty, k ~context:((n,NCic.Decl s)::context) t)
254     | NCic.Appl (NCic.Meta (n,lc) :: args) when List.mem_assoc n subst -> 
255        let _,_,t,_ = List.assoc n subst in
256        let hd = NCicSubstitution.subst_meta status lc t in
257         k ~context
258          (NCicReduction.head_beta_reduce status ~upto:(List.length args)
259            (match hd with
260            | NCic.Appl l -> NCic.Appl (l@args)
261            | _ -> NCic.Appl (hd :: args)))
262     | NCic.Appl args as t ->
263        (match destroy_nat t with
264          | Some n -> Ast.Num (string_of_int n, None)
265          | None ->
266             let args =
267              if not !hide_coercions then args
268              else
269               match
270                NCicCoercion.match_coercion status ~metasenv ~context ~subst t
271               with
272                | None -> args
273                | Some (_,sats,cpos) -> 
274 (* CSC: sats e' il numero di pi, ma non so cosa farmene! voglio il numero di
275    argomenti da saltare, come prima! *)
276                   if cpos < List.length args - 1 then
277                    List.nth args (cpos + 1) ::
278                     try snd (HExtlib.split_nth (cpos+sats+2) args)
279                     with Failure _->[]
280                   else
281                    args
282             in
283              (match args with
284                  [arg] -> k ~context arg
285                | _ -> Ast.Appl (List.map (k ~context) args)))
286     | NCic.Match (NReference.Ref (uri,_) as r,outty,te,patterns) ->
287         let name = NUri.name_of_uri uri in
288         let case_indty =
289          name, Some r in
290         let constructors, leftno =
291          let _,leftno,tys,_,n = NCicEnvironment.get_checked_indtys status r in
292          let _,_,_,cl  = List.nth tys n in
293           cl,leftno
294         in
295         let rec eat_branch n ctx ty pat =
296           match (ty, pat) with
297           | NCic.Prod (name, s, t), _ when n > 0 ->
298              eat_branch (pred n) ctx t pat 
299           | NCic.Prod (_, _, t), NCic.Lambda (name, s, t') ->
300               let cv, rhs = eat_branch 0 ((name,NCic.Decl s)::ctx) t t' in
301               (Ast.Ident (name,`Ambiguous), Some (k ~context:ctx s)) :: cv, rhs
302           | _, _ -> [], k ~context:ctx pat
303         in
304         let j = ref 0 in
305         let patterns =
306           try
307             List.map2
308               (fun (_, name, ty) pat ->
309                 incr j;
310                 let name,(capture_variables,rhs) =
311                  match output_type with
312                     `Term -> name, eat_branch leftno context ty pat
313                   | `Pattern -> "_", ([], k ~context pat)
314                 in
315                  Ast.Pattern (name, None(*CSC Some (ctor_puri !j)*), capture_variables), rhs
316               ) constructors patterns
317           with Invalid_argument _ -> assert false
318         in
319         let indty =
320          match output_type with
321             `Pattern -> None
322           | `Term -> Some case_indty
323         in
324          Ast.Case (k ~context te, indty, Some (k ~context outty), patterns)
325 ;;
326
327 let rec nast_of_cic1 status ~output_type ~metasenv ~subst ~context term =
328   match Lazy.force status#interp_db.compiled32 term with
329   | None ->
330      nast_of_cic0 status ~output_type ~metasenv ~subst
331       (nast_of_cic1 status ~output_type ~metasenv ~subst) ~context term 
332   | Some (env, ctors, pid) -> 
333       let env =
334        List.map
335         (fun (name, term) ->
336           name,
337            nast_of_cic1 status ~output_type ~subst ~metasenv ~context
338             term
339         ) env
340       in
341       let dsc, symbol, args, _ =
342         try
343          find_level2_patterns32 status pid
344         with Not_found -> assert false
345       in
346       instantiate32 env symbol dsc args 
347 ;;
348
349 let nmap_context0 status ~metasenv ~subst context =
350  let nast_of_cic =
351   nast_of_cic1 status ~output_type:`Term ~metasenv ~subst
352  in
353  fst (
354   List.fold_right
355    (fun item (res,context) ->
356      match item with
357       | name,NCic.Decl t ->
358           (name, Ast.Decl (nast_of_cic ~context t))::res,
359           item::context
360       | name,NCic.Def (t,ty) ->
361           (name, Ast.Def (nast_of_cic ~context t, 
362                            nast_of_cic ~context ty))::res,
363            item::context
364    ) context ([],[]))
365 ;;
366
367 let nmap_sequent0 status ~metasenv ~subst (i,(n,context,ty)) =
368  let nast_of_cic =
369   nast_of_cic1 status ~output_type:`Term ~metasenv ~subst in
370  let context' = nmap_context0 status ~metasenv ~subst context in
371   (i,context',nast_of_cic ~context ty)
372 ;;
373
374 let object_prefix = "obj:";;
375 let declaration_prefix = "decl:";;
376 let definition_prefix = "def:";;
377 let inductive_prefix = "ind:";;
378 let joint_prefix = "joint:";;
379
380 (*
381 let get_id =
382  function
383     Ast.AttributedTerm (`IdRef id, _) -> id
384   | _ -> assert false
385 ;;
386
387 let gen_id prefix seed =
388  let res = prefix ^ string_of_int !seed in
389   incr seed ;
390   res
391 ;;
392
393 let nmap_obj0 status ~idref (uri,_,metasenv,subst,kind) =
394   let module K = Content in
395   let nast_of_cic =
396    nast_of_cic1 status ~idref ~output_type:`Term ~metasenv ~subst in
397   let seed = ref 0 in
398   let conjectures =
399    match metasenv with
400       [] -> None
401     | _ -> (*Some (List.map (map_conjectures seed) metasenv)*)
402       (*CSC: used to be the previous line, that uses seed *)
403       Some (List.map (nmap_sequent0 status ~idref ~metasenv ~subst) metasenv)
404   in
405 let  build_constructors seed l =
406       List.map 
407        (fun (_,n,ty) ->
408            let ty = nast_of_cic ~context:[] ty in
409            { K.dec_name = Some n;
410              K.dec_id = gen_id declaration_prefix seed;
411              K.dec_inductive = false;
412              K.dec_aref = "";
413              K.dec_type = ty
414            }) l
415 in
416 let build_inductive b seed = 
417       fun (_,n,ty,cl) ->
418         let ty = nast_of_cic ~context:[] ty in
419         `Inductive
420           { K.inductive_id = gen_id inductive_prefix seed;
421             K.inductive_name = n;
422             K.inductive_kind = b;
423             K.inductive_type = ty;
424             K.inductive_constructors = build_constructors seed cl
425            }
426 in
427 let build_fixpoint b seed = 
428       fun (_,n,_,ty,t) ->
429         let t = nast_of_cic ~context:[] t in
430         let ty = nast_of_cic ~context:[] ty in
431         `Definition
432           { K.def_id = gen_id inductive_prefix seed;
433             K.def_name = Some n;
434             K.def_aref = "";
435             K.def_type = ty;
436             K.def_term = t;
437            }
438 in
439  match kind with
440   | NCic.Fixpoint (is_rec, ifl, _) -> 
441        (gen_id object_prefix seed, conjectures,
442           `Joint
443             { K.joint_id = gen_id joint_prefix seed;
444               K.joint_kind = 
445                  if is_rec then 
446                       `Recursive (List.map (fun (_,_,i,_,_) -> i) ifl)
447                  else `CoRecursive;
448               K.joint_defs = List.map (build_fixpoint is_rec seed) ifl
449             }) 
450   | NCic.Inductive (is_ind, lno, itl, _) ->
451        (gen_id object_prefix seed, conjectures,
452           `Joint
453             { K.joint_id = gen_id joint_prefix seed;
454               K.joint_kind = 
455                  if is_ind then `Inductive lno else `CoInductive lno;
456               K.joint_defs = List.map (build_inductive is_ind seed) itl
457             }) 
458   | NCic.Constant (_,_,Some bo,ty,_) ->
459      let ty = nast_of_cic ~context:[] ty in
460      let bo = nast_of_cic ~context:[] bo in
461       (gen_id object_prefix seed, conjectures,
462         `Def (K.Const,ty,
463           build_def_item seed [] [] (get_id bo) (NUri.name_of_uri uri) bo ty))
464   | NCic.Constant (_,_,None,ty,_) ->
465      let ty = nast_of_cic ~context:[] ty in
466        (gen_id object_prefix seed, conjectures,
467          `Decl (K.Const,
468            (*CSC: ??? get_id ty here used to be the id of the axiom! *)
469            build_decl_item seed (get_id ty) (NUri.name_of_uri uri) ty))
470 ;;
471
472 let with_idrefs foo status obj =
473  let ids_to_refs = Hashtbl.create 211 in
474  let register_ref = Hashtbl.add ids_to_refs in
475   foo status ~idref:(idref register_ref) obj, ids_to_refs
476 ;;
477
478 let nmap_obj status = with_idrefs nmap_obj0 status
479 *)
480
481 let nmap_obj _ = assert false
482
483 let nmap_sequent = nmap_sequent0 
484
485 let nmap_term = nast_of_cic1 ~output_type:`Term 
486
487 let nmap_context = nmap_context0