]> matita.cs.unibo.it Git - helm.git/blob - matitaB/components/ng_cic_content/interpretations.ml
First commit with new (incomplete) disambiguation engine.
[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 idref register_ref =
89  let id = ref 0 in
90   fun ?reference t ->
91    incr id;
92    let id = "i" ^ string_of_int !id in
93     (match reference with None -> () | Some r -> register_ref id r);
94     Ast.AttributedTerm (`IdRef id, t)
95 ;;
96
97 let level_of_uri u = 
98   let name = NUri.name_of_uri u in
99   assert(String.length name > String.length "Type");
100   String.sub name 4 (String.length name - 4)
101 ;;
102
103 let find_level2_patterns32 status pid =
104  IntMap.find pid status#interp_db.level2_patterns32
105
106 let add_idrefs =
107   List.fold_right (fun idref t -> Ast.AttributedTerm (`IdRef idref, t))
108
109 let instantiate32 idrefs env symbol args =
110   let rec instantiate_arg = function
111     | Ast.IdentArg (n, name) ->
112         let t = 
113           try List.assoc name env 
114           with Not_found -> prerr_endline ("name not found in env: "^name);
115                             assert false
116         in
117         let rec count_lambda = function
118           | Ast.AttributedTerm (_, t) -> count_lambda t
119           | Ast.Binder (`Lambda, _, body) -> 1 + count_lambda body
120           | _ -> 0
121         in
122         let rec add_lambda t n =
123           if n > 0 then
124             let name = NotationUtil.fresh_name () in
125             Ast.Binder (`Lambda, (Ast.Ident (name, `Ambiguous), None),
126               Ast.Appl [add_lambda t (n - 1); Ast.Ident (name, `Ambiguous)])
127           else
128             t
129         in
130         add_lambda t (n - count_lambda t)
131   in
132   let head =
133     let symbol = Ast.Symbol (symbol, None) in
134     add_idrefs idrefs symbol
135   in
136   if args = [] then head
137   else Ast.Appl (head :: List.map instantiate_arg args)
138
139 let fresh_id status =
140   let counter = status#interp_db.counter+1 in
141    status#set_interp_db ({ status#interp_db with counter = counter  }), counter
142
143 let load_patterns32 status t =
144  let t =
145   HExtlib.filter_map (function (true, ap, id) -> Some (ap, id) | _ -> None) t
146  in
147   status#set_interp_db
148    {status#interp_db with
149      compiled32 = lazy (Ncic2astMatcher.Matcher32.compiler status t) }
150 ;;
151
152 let add_interpretation status dsc (symbol, args) appl_pattern =
153   let status,id = fresh_id status in
154   let ids =
155    try
156     id::StringMap.find symbol status#interp_db.interpretations
157    with Not_found -> [id] in
158   let status =
159    status#set_interp_db { status#interp_db with
160     level2_patterns32 =
161       IntMap.add id (dsc, symbol, args, appl_pattern)
162        status#interp_db.level2_patterns32;
163     pattern32_matrix = (true,appl_pattern,id)::status#interp_db.pattern32_matrix;
164     interpretations = StringMap.add symbol ids status#interp_db.interpretations
165    }
166   in
167    load_patterns32 status status#interp_db.pattern32_matrix
168
169 let toggle_active_interpretations status b =
170   status#set_interp_db { status#interp_db with
171    pattern32_matrix =
172      List.map (fun (_,ap,id) -> b,ap,id) status#interp_db.pattern32_matrix }
173
174 exception Interpretation_not_found
175
176 let lookup_interpretations status ?(sorted=true) symbol =
177   try
178     let raw = 
179       List.map (
180         fun id ->
181           let (dsc, _, args, appl_pattern) =
182             try IntMap.find id status#interp_db.level2_patterns32
183             with Not_found -> assert false 
184           in
185           dsc, args, appl_pattern
186       ) (StringMap.find symbol status#interp_db.interpretations)
187     in
188     if sorted then HExtlib.list_uniq (List.sort Pervasives.compare raw)
189               else raw
190   with Not_found -> raise Interpretation_not_found
191
192 let instantiate_appl_pattern 
193   ~mk_appl ~mk_implicit ~term_of_nref env appl_pattern 
194 =
195   let lookup name =
196     try List.assoc name env
197     with Not_found ->
198       prerr_endline (sprintf "Name %s not found" name);
199       assert false
200   in
201   let rec aux = function
202     | Ast.NRefPattern nref -> term_of_nref nref
203     | Ast.ImplicitPattern -> mk_implicit false
204     | Ast.VarPattern name -> lookup name
205     | Ast.ApplPattern terms -> mk_appl (List.map aux terms)
206   in
207   aux appl_pattern
208
209 let destroy_nat =
210   let is_nat_URI = NUri.eq (NUri.uri_of_string
211   "cic:/matita/arithmetics/nat/nat.ind") in
212   let is_zero = function
213     | NCic.Const (NReference.Ref (uri, NReference.Con (0, 1, 0))) when
214        is_nat_URI uri -> true
215     | _ -> false
216   in
217   let is_succ = function
218     | NCic.Const (NReference.Ref (uri, NReference.Con (0, 2, 0))) when
219        is_nat_URI uri -> true
220     | _ -> false
221   in
222   let rec aux acc = function
223     | NCic.Appl [he ; tl] when is_succ he -> aux (acc + 1) tl
224     | t when is_zero t -> Some acc
225     | _ -> None
226   in
227    aux 0
228
229 (* CODICE c&p da NCicPp *)
230 let nast_of_cic0 status
231  ~(idref:
232     ?reference:NReference.reference -> NotationPt.term -> NotationPt.term)
233  ~output_type ~metasenv ~subst k ~context =
234   function
235     | NCic.Rel n ->
236        (try 
237          let name,_ = List.nth context (n-1) in
238          let name = if name = "_" then "__"^string_of_int n else name in
239           idref (Ast.Ident (name,`Ambiguous))
240         with Failure "nth" | Invalid_argument "List.nth" -> 
241          idref (Ast.Ident ("-" ^ string_of_int (n - List.length
242          context),`Ambiguous)))
243     | NCic.Const r -> idref ~reference:r (Ast.Ident (NCicPp.r2s status true r, `Ambiguous))
244     | NCic.Meta (n,lc) when List.mem_assoc n subst -> 
245         let _,_,t,_ = List.assoc n subst in
246          k ~context (NCicSubstitution.subst_meta status lc t)
247     | NCic.Meta (n,(s,l)) ->
248        (* CSC: qua non dovremmo espandere *)
249        let l = NCicUtils.expand_local_context l in
250         idref (Ast.Meta
251          (n, List.map (fun x -> Some (k ~context (NCicSubstitution.lift status s x))) l))
252     | NCic.Sort NCic.Prop -> idref (Ast.Sort `Prop)
253     | NCic.Sort NCic.Type [] -> idref (Ast.Sort `Set)
254     | NCic.Sort NCic.Type ((`Type,u)::_) -> 
255               idref(Ast.Sort (`NType (level_of_uri u)))
256     | NCic.Sort NCic.Type ((`CProp,u)::_) -> 
257               idref(Ast.Sort (`NCProp (level_of_uri u)))
258     | NCic.Sort NCic.Type ((`Succ,u)::_) -> 
259               idref(Ast.Sort (`NType (level_of_uri u ^ "+1")))
260     | NCic.Implicit `Hole -> idref (Ast.UserInput)
261     | NCic.Implicit `Vector -> idref (Ast.Implicit `Vector)
262     | NCic.Implicit _ -> idref (Ast.Implicit `JustOne)
263     | NCic.Prod (n,s,t) ->
264         let n = if n.[0] = '_' then "_" else n in
265         let binder_kind = `Forall in
266          idref (Ast.Binder (binder_kind, (Ast.Ident (n,`Ambiguous), Some (k ~context s)),
267           k ~context:((n,NCic.Decl s)::context) t))
268     | NCic.Lambda (n,s,t) ->
269         idref (Ast.Binder (`Lambda,(Ast.Ident (n,`Ambiguous), Some (k ~context s)),
270          k ~context:((n,NCic.Decl s)::context) t))
271     | NCic.LetIn (n,s,ty,NCic.Rel 1) ->
272         idref (Ast.Cast (k ~context ty, k ~context s))
273     | NCic.LetIn (n,s,ty,t) ->
274         idref (Ast.LetIn ((Ast.Ident (n,`Ambiguous), Some (k ~context s)), k ~context
275           ty, k ~context:((n,NCic.Decl s)::context) t))
276     | NCic.Appl (NCic.Meta (n,lc) :: args) when List.mem_assoc n subst -> 
277        let _,_,t,_ = List.assoc n subst in
278        let hd = NCicSubstitution.subst_meta status lc t in
279         k ~context
280          (NCicReduction.head_beta_reduce status ~upto:(List.length args)
281            (match hd with
282            | NCic.Appl l -> NCic.Appl (l@args)
283            | _ -> NCic.Appl (hd :: args)))
284     | NCic.Appl args as t ->
285        (match destroy_nat t with
286          | Some n -> idref (Ast.Num (string_of_int n, None))
287          | None ->
288             let args =
289              if not !hide_coercions then args
290              else
291               match
292                NCicCoercion.match_coercion status ~metasenv ~context ~subst t
293               with
294                | None -> args
295                | Some (_,sats,cpos) -> 
296 (* CSC: sats e' il numero di pi, ma non so cosa farmene! voglio il numero di
297    argomenti da saltare, come prima! *)
298                   if cpos < List.length args - 1 then
299                    List.nth args (cpos + 1) ::
300                     try snd (HExtlib.split_nth (cpos+sats+2) args)
301                     with Failure _->[]
302                   else
303                    args
304             in
305              (match args with
306                  [arg] -> idref (k ~context arg)
307                | _ -> idref (Ast.Appl (List.map (k ~context) args))))
308     | NCic.Match (NReference.Ref (uri,_) as r,outty,te,patterns) ->
309         let name = NUri.name_of_uri uri in
310 (* CSC
311         let uri_str = UriManager.string_of_uri uri in
312         let puri_str = sprintf "%s#xpointer(1/%d)" uri_str (typeno+1) in
313         let ctor_puri j =
314           UriManager.uri_of_string
315             (sprintf "%s#xpointer(1/%d/%d)" uri_str (typeno+1) j)
316         in
317 *)
318         let case_indty =
319          name, None(*CSC Some (UriManager.uri_of_string puri_str)*) in
320         let constructors, leftno =
321          let _,leftno,tys,_,n = NCicEnvironment.get_checked_indtys status r in
322          let _,_,_,cl  = List.nth tys n in
323           cl,leftno
324         in
325         let rec eat_branch n ctx ty pat =
326           match (ty, pat) with
327           | NCic.Prod (name, s, t), _ when n > 0 ->
328              eat_branch (pred n) ctx t pat 
329           | NCic.Prod (_, _, t), NCic.Lambda (name, s, t') ->
330               let cv, rhs = eat_branch 0 ((name,NCic.Decl s)::ctx) t t' in
331               (Ast.Ident (name,`Ambiguous), Some (k ~context:ctx s)) :: cv, rhs
332           | _, _ -> [], k ~context:ctx pat
333         in
334         let j = ref 0 in
335         let patterns =
336           try
337             List.map2
338               (fun (_, name, ty) pat ->
339                 incr j;
340                 let name,(capture_variables,rhs) =
341                  match output_type with
342                     `Term -> name, eat_branch leftno context ty pat
343                   | `Pattern -> "_", ([], k ~context pat)
344                 in
345                  Ast.Pattern (name, None(*CSC Some (ctor_puri !j)*), capture_variables), rhs
346               ) constructors patterns
347           with Invalid_argument _ -> assert false
348         in
349         let indty =
350          match output_type with
351             `Pattern -> None
352           | `Term -> Some case_indty
353         in
354          idref (Ast.Case (k ~context te, indty, Some (k ~context outty), patterns))
355 ;;
356
357 let rec nast_of_cic1 status ~idref ~output_type ~metasenv ~subst ~context term =
358   match Lazy.force status#interp_db.compiled32 term with
359   | None ->
360      nast_of_cic0 status ~idref ~output_type ~metasenv ~subst
361       (nast_of_cic1 status ~idref ~output_type ~metasenv ~subst) ~context term 
362   | Some (env, ctors, pid) -> 
363       let idrefs =
364        List.map
365         (fun term ->
366           let attrterm =
367            idref
368             ~reference:
369               (match term with NCic.Const nref -> nref | _ -> assert false)
370            (NotationPt.Ident ("dummy",`Ambiguous))
371           in
372            match attrterm with
373               Ast.AttributedTerm (`IdRef id, _) -> id
374             | _ -> assert false
375         ) ctors
376       in
377       let env =
378        List.map
379         (fun (name, term) ->
380           name,
381            nast_of_cic1 status ~idref ~output_type ~subst ~metasenv ~context
382             term
383         ) env
384       in
385       let _, symbol, args, _ =
386         try
387          find_level2_patterns32 status pid
388         with Not_found -> assert false
389       in
390       let ast = instantiate32 idrefs env symbol args in
391       idref ast (*Ast.AttributedTerm (`IdRef (idref term), ast)*)
392 ;;
393
394 let nmap_context0 status ~idref ~metasenv ~subst context =
395  let module K = Content in
396  let nast_of_cic =
397   nast_of_cic1 status ~idref ~output_type:`Term ~metasenv ~subst
398  in
399  fst (
400   List.fold_right
401    (fun item (res,context) ->
402      match item with
403       | name,NCic.Decl t ->
404          Some
405           (* We should call build_decl_item, but we have not computed *)
406           (* the inner-types ==> we always produce a declaration      *)
407           (`Declaration
408             { K.dec_name = (Some name);
409               K.dec_id = "-1"; 
410               K.dec_inductive = false;
411               K.dec_aref = "-1";
412               K.dec_type = nast_of_cic ~context t
413             })::res,item::context
414       | name,NCic.Def (t,ty) ->
415          Some
416           (* We should call build_def_item, but we have not computed *)
417           (* the inner-types ==> we always produce a declaration     *)
418           (`Definition
419              { K.def_name = (Some name);
420                K.def_id = "-1"; 
421                K.def_aref = "-1";
422                K.def_term = nast_of_cic ~context t;
423                K.def_type = nast_of_cic ~context ty
424              })::res,item::context
425    ) context ([],[]))
426 ;;
427
428 let nmap_sequent0 status ~idref ~metasenv ~subst (i,(n,context,ty)) =
429  let module K = Content in
430  let nast_of_cic =
431   nast_of_cic1 status ~idref ~output_type:`Term ~metasenv ~subst in
432  let context' = nmap_context0 status ~idref ~metasenv ~subst context in
433   ("-1",i,context',nast_of_cic ~context ty)
434 ;;
435
436 let object_prefix = "obj:";;
437 let declaration_prefix = "decl:";;
438 let definition_prefix = "def:";;
439 let inductive_prefix = "ind:";;
440 let joint_prefix = "joint:";;
441
442 let get_id =
443  function
444     Ast.AttributedTerm (`IdRef id, _) -> id
445   | _ -> assert false
446 ;;
447
448 let gen_id prefix seed =
449  let res = prefix ^ string_of_int !seed in
450   incr seed ;
451   res
452 ;;
453
454 let build_def_item seed context metasenv id n t ty =
455  let module K = Content in
456 (*
457   try
458    let sort = Hashtbl.find ids_to_inner_sorts id in
459    if sort = `Prop then
460        (let p = 
461         (acic2content seed context metasenv ?name:(name_of n) ~ids_to_inner_sorts  ~ids_to_inner_types t)
462        in 
463         `Proof p;)
464    else 
465 *)
466       `Definition
467         { K.def_name = Some n;
468           K.def_id = gen_id definition_prefix seed; 
469           K.def_aref = id;
470           K.def_term = t;
471           K.def_type = ty
472         }
473 (*
474   with
475    Not_found -> assert false
476 *)
477
478 let build_decl_item seed id n s =
479  let module K = Content in
480 (*
481  let sort =
482    try
483     Some (Hashtbl.find ids_to_inner_sorts (Cic2acic.source_id_of_id id))
484    with Not_found -> None
485  in
486  match sort with
487  | Some `Prop ->
488     `Hypothesis
489       { K.dec_name = name_of n;
490         K.dec_id = gen_id declaration_prefix seed; 
491         K.dec_inductive = false;
492         K.dec_aref = id;
493         K.dec_type = s
494       }
495  | _ ->
496 *)
497     `Declaration
498       { K.dec_name = Some n;
499         K.dec_id = gen_id declaration_prefix seed; 
500         K.dec_inductive = false;
501         K.dec_aref = id;
502         K.dec_type = s
503       }
504 ;;
505
506 let nmap_obj0 status ~idref (uri,_,metasenv,subst,kind) =
507   let module K = Content in
508   let nast_of_cic =
509    nast_of_cic1 status ~idref ~output_type:`Term ~metasenv ~subst in
510   let seed = ref 0 in
511   let conjectures =
512    match metasenv with
513       [] -> None
514     | _ -> (*Some (List.map (map_conjectures seed) metasenv)*)
515       (*CSC: used to be the previous line, that uses seed *)
516       Some (List.map (nmap_sequent0 status ~idref ~metasenv ~subst) metasenv)
517   in
518 let  build_constructors seed l =
519       List.map 
520        (fun (_,n,ty) ->
521            let ty = nast_of_cic ~context:[] ty in
522            { K.dec_name = Some n;
523              K.dec_id = gen_id declaration_prefix seed;
524              K.dec_inductive = false;
525              K.dec_aref = "";
526              K.dec_type = ty
527            }) l
528 in
529 let build_inductive b seed = 
530       fun (_,n,ty,cl) ->
531         let ty = nast_of_cic ~context:[] ty in
532         `Inductive
533           { K.inductive_id = gen_id inductive_prefix seed;
534             K.inductive_name = n;
535             K.inductive_kind = b;
536             K.inductive_type = ty;
537             K.inductive_constructors = build_constructors seed cl
538            }
539 in
540 let build_fixpoint b seed = 
541       fun (_,n,_,ty,t) ->
542         let t = nast_of_cic ~context:[] t in
543         let ty = nast_of_cic ~context:[] ty in
544         `Definition
545           { K.def_id = gen_id inductive_prefix seed;
546             K.def_name = Some n;
547             K.def_aref = "";
548             K.def_type = ty;
549             K.def_term = t;
550            }
551 in
552  match kind with
553   | NCic.Fixpoint (is_rec, ifl, _) -> 
554        (gen_id object_prefix seed, conjectures,
555           `Joint
556             { K.joint_id = gen_id joint_prefix seed;
557               K.joint_kind = 
558                  if is_rec then 
559                       `Recursive (List.map (fun (_,_,i,_,_) -> i) ifl)
560                  else `CoRecursive;
561               K.joint_defs = List.map (build_fixpoint is_rec seed) ifl
562             }) 
563   | NCic.Inductive (is_ind, lno, itl, _) ->
564        (gen_id object_prefix seed, conjectures,
565           `Joint
566             { K.joint_id = gen_id joint_prefix seed;
567               K.joint_kind = 
568                  if is_ind then `Inductive lno else `CoInductive lno;
569               K.joint_defs = List.map (build_inductive is_ind seed) itl
570             }) 
571   | NCic.Constant (_,_,Some bo,ty,_) ->
572      let ty = nast_of_cic ~context:[] ty in
573      let bo = nast_of_cic ~context:[] bo in
574       (gen_id object_prefix seed, conjectures,
575         `Def (K.Const,ty,
576           build_def_item seed [] [] (get_id bo) (NUri.name_of_uri uri) bo ty))
577   | NCic.Constant (_,_,None,ty,_) ->
578      let ty = nast_of_cic ~context:[] ty in
579        (gen_id object_prefix seed, conjectures,
580          `Decl (K.Const,
581            (*CSC: ??? get_id ty here used to be the id of the axiom! *)
582            build_decl_item seed (get_id ty) (NUri.name_of_uri uri) ty))
583 ;;
584
585 let with_idrefs foo status obj =
586  let ids_to_refs = Hashtbl.create 211 in
587  let register_ref = Hashtbl.add ids_to_refs in
588   foo status ~idref:(idref register_ref) obj, ids_to_refs
589 ;;
590
591 let nmap_obj status = with_idrefs nmap_obj0 status
592
593 let nmap_sequent status ~metasenv ~subst =
594  with_idrefs (nmap_sequent0 ~metasenv ~subst) status
595
596 let nmap_term status ~metasenv ~subst ~context =
597  with_idrefs (nast_of_cic1 ~output_type:`Term ~metasenv ~subst ~context) status
598
599 let nmap_context status ~metasenv ~subst =
600  with_idrefs (nmap_context0 ~metasenv ~subst) status