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