]> matita.cs.unibo.it Git - helm.git/blob - components/cic_exportation/cicExportation.ml
Bug in detection of too polymorphic types partially fixed (see comment).
[helm.git] / components / cic_exportation / cicExportation.ml
1 (* Copyright (C) 2000, 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://cs.unibo.it/helm/.
24  *)
25
26 (* $Id: cicPp.ml 7413 2007-05-29 15:30:53Z tassi $ *)
27
28 exception CicExportationInternalError;;
29 exception NotEnoughElements;;
30
31 (* Utility functions *)
32
33 let analyze_term context t =
34  match fst(CicTypeChecker.type_of_aux' [] context t CicUniv.oblivion_ugraph)with
35     Cic.Sort _ -> `Type
36   | ty -> 
37      match
38       fst (CicTypeChecker.type_of_aux' [] context ty CicUniv.oblivion_ugraph)
39      with
40         Cic.Sort Cic.Prop -> `Proof
41      | _ -> `Term
42 ;;
43
44 let analyze_type context t =
45  let rec aux =
46   function
47      Cic.Sort s -> `Sort s
48    | Cic.Prod (_,_,t)
49    | Cic.Lambda (_,_,t) -> aux t
50    | _ -> `SomethingElse
51  in
52  match aux t with
53     `Sort _ as res -> res
54   | `SomethingElse ->
55       match
56        fst(CicTypeChecker.type_of_aux' [] context t CicUniv.oblivion_ugraph)
57       with
58           Cic.Sort Cic.Prop -> `Statement
59        | _ -> `Type
60 ;;
61
62 let ppid =
63  let reserved =
64   [ "to";
65     "mod";
66     "val"
67   ]
68  in
69   function n ->
70    let n = String.uncapitalize n in
71     if List.mem n reserved then n ^ "_" else n
72 ;;
73
74 let ppname =
75  function
76     Cic.Name s     -> ppid s
77   | Cic.Anonymous  -> "_"
78 ;;
79
80 (* get_nth l n   returns the nth element of the list l if it exists or *)
81 (* raises NotEnoughElements if l has less than n elements             *)
82 let rec get_nth l n =
83  match (n,l) with
84     (1, he::_) -> he
85   | (n, he::tail) when n > 1 -> get_nth tail (n-1)
86   | (_,_) -> raise NotEnoughElements
87 ;;
88
89 let qualified_name_of_uri current_module_uri ?(capitalize=false) uri =
90  let name =
91   if capitalize then
92    String.capitalize (UriManager.name_of_uri uri)
93   else
94    ppid (UriManager.name_of_uri uri) in
95   let filename =
96    let suri = UriManager.buri_of_uri uri in
97    let s = String.sub suri 5 (String.length suri - 5) in
98    let s = Pcre.replace ~pat:"/" ~templ:"_" s in
99     String.uncapitalize s in
100   if current_module_uri = UriManager.buri_of_uri uri then
101    name
102   else
103    String.capitalize filename ^ "." ^ name
104 ;;
105
106 let pp current_module_uri ?metasenv ~in_type =
107 let rec pp ~in_type t context =
108  let module C = Cic in
109    match t with
110       C.Rel n ->
111        begin
112         try
113          (match get_nth context n with
114              Some (C.Name s,_) -> ppid s
115            | Some (C.Anonymous,_) -> "__" ^ string_of_int n
116            | None -> "_hidden_" ^ string_of_int n
117          )
118         with
119          NotEnoughElements -> string_of_int (List.length context - n)
120        end
121     | C.Var (uri,exp_named_subst) ->
122         qualified_name_of_uri current_module_uri uri ^
123          pp_exp_named_subst exp_named_subst context
124     | C.Meta (n,l1) ->
125        (match metasenv with
126            None ->
127             "?" ^ (string_of_int n) ^ "[" ^ 
128              String.concat " ; "
129               (List.rev_map
130                 (function
131                     None -> "_"
132                   | Some t -> pp ~in_type:false t context) l1) ^
133              "]"
134          | Some metasenv ->
135             try
136              let _,context,_ = CicUtil.lookup_meta n metasenv in
137               "?" ^ (string_of_int n) ^ "[" ^ 
138                String.concat " ; "
139                 (List.rev
140                   (List.map2
141                     (fun x y ->
142                       match x,y with
143                          _, None
144                        | None, _ -> "_"
145                        | Some _, Some t -> pp ~in_type:false t context
146                     ) context l1)) ^
147                "]"
148             with
149               CicUtil.Meta_not_found _ 
150             | Invalid_argument _ ->
151               "???" ^ (string_of_int n) ^ "[" ^ 
152                String.concat " ; "
153                 (List.rev_map (function None -> "_" | Some t ->
154                   pp ~in_type:false t context) l1) ^
155                "]"
156        )
157     | C.Sort s ->
158        (match s with
159            C.Prop  -> "Prop"
160          | C.Set   -> "Set"
161          | C.Type _ -> "Type"
162          (*| C.Type u -> ("Type" ^ CicUniv.string_of_universe u)*)
163          | C.CProp -> "CProp" 
164        )
165     | C.Implicit (Some `Hole) -> "%"
166     | C.Implicit _ -> "?"
167     | C.Prod (b,s,t) ->
168        (match b with
169           C.Name n ->
170            let n = "'" ^ String.uncapitalize n in
171             "(" ^ pp ~in_type:true s context ^ " -> " ^
172             pp ~in_type:true t ((Some (Cic.Name n,Cic.Decl s))::context) ^ ")"
173         | C.Anonymous ->
174            "(" ^ pp ~in_type:true s context ^ " -> " ^
175            pp ~in_type:true t ((Some (b,Cic.Decl s))::context) ^ ")")
176     | C.Cast (v,t) -> pp ~in_type v context
177     | C.Lambda (b,s,t) ->
178        (match analyze_type context s with
179            `Sort _
180          | `Statement -> pp ~in_type t ((Some (b,Cic.Decl s))::context)
181          | `Type ->
182             "(function " ^ ppname b ^ " -> " ^
183              pp ~in_type t ((Some (b,Cic.Decl s))::context) ^ ")")
184     | C.LetIn (b,s,t) ->
185        let ty,_ = CicTypeChecker.type_of_aux' [] context t CicUniv.oblivion_ugraph in
186        "(let " ^ ppname b ^ " = " ^ pp ~in_type:false s context ^ " in " ^
187         pp ~in_type t ((Some (b,Cic.Def (s,Some ty)))::context) ^ ")"
188     | C.Appl (C.MutInd _ as he::tl) ->
189        let hes = pp ~in_type he context in
190        let stl = String.concat "," (clean_args_for_ty context tl) in
191         (if stl = "" then "" else "(" ^ stl ^ ") ") ^ hes
192     | C.Appl (C.MutConstruct (uri,n,_,_) as he::tl) ->
193        let nparams =
194         match fst(CicEnvironment.get_obj CicUniv.empty_ugraph uri) with
195            C.InductiveDefinition (_,_,nparams,_) -> nparams
196          | _ -> assert false in
197        let hes = pp ~in_type he context in
198        let stl = String.concat "," (clean_args nparams context tl) in
199         "(" ^ hes ^ (if stl = "" then "" else "(" ^ stl ^ ")") ^ ")"
200     | C.Appl li ->
201        "(" ^ String.concat " " (clean_args 0 context li) ^ ")"
202     | C.Const (uri,exp_named_subst) ->
203        qualified_name_of_uri current_module_uri uri ^
204         pp_exp_named_subst exp_named_subst context
205     | C.MutInd (uri,n,exp_named_subst) ->
206        (try
207          match fst(CicEnvironment.get_obj CicUniv.empty_ugraph uri) with
208             C.InductiveDefinition (dl,_,_,_) ->
209              let (name,_,_,_) = get_nth dl (n+1) in
210               qualified_name_of_uri current_module_uri
211                (UriManager.uri_of_string
212                  (UriManager.buri_of_uri uri ^ "/" ^ name ^ ".con")) ^
213               pp_exp_named_subst exp_named_subst context
214           | _ -> raise CicExportationInternalError
215         with
216            Sys.Break as exn -> raise exn
217          | _ -> UriManager.string_of_uri uri ^ "#1/" ^ string_of_int (n + 1)
218        )
219     | C.MutConstruct (uri,n1,n2,exp_named_subst) ->
220        (try
221          match fst(CicEnvironment.get_obj CicUniv.empty_ugraph uri) with
222             C.InductiveDefinition (dl,_,_,_) ->
223              let _,_,_,cons = get_nth dl (n1+1) in
224               let id,_ = get_nth cons n2 in
225                qualified_name_of_uri current_module_uri ~capitalize:true
226                 (UriManager.uri_of_string
227                   (UriManager.buri_of_uri uri ^ "/" ^ id ^ ".con")) ^
228                pp_exp_named_subst exp_named_subst context
229           | _ -> raise CicExportationInternalError
230         with
231            Sys.Break as exn -> raise exn
232          | _ ->
233           UriManager.string_of_uri uri ^ "#1/" ^ string_of_int (n1 + 1) ^ "/" ^
234            string_of_int n2
235        )
236     | C.MutCase (uri,n1,ty,te,patterns) ->
237        if in_type then
238         "unit (* TOO POLYMORPHIC TYPE *)"
239        else (
240        let needs_obj_magic =
241         (* BUG HERE: we should consider also the right parameters *)
242         match CicReduction.whd context ty with
243            Cic.Lambda (_,_,t) -> not (DoubleTypeInference.does_not_occur 1 t)
244          | _ -> false (* it can be a Rel, e.g. in *_rec *)
245        in
246        (match analyze_term context te with
247            `Type -> assert false
248          | `Proof ->
249              (match patterns with
250                  [] -> "assert false"   (* empty type elimination *)
251                | [he] ->
252                   pp ~in_type:false he context  (* singleton elimination *)
253                | _ -> assert false)
254          | `Term ->
255             if patterns = [] then "assert false"
256             else
257              (let connames_and_argsno =
258                (match fst(CicEnvironment.get_obj CicUniv.empty_ugraph uri) with
259                    C.InductiveDefinition (dl,_,paramsno,_) ->
260                     let (_,_,_,cons) = get_nth dl (n1+1) in
261                      List.map
262                       (fun (id,ty) ->
263                         (* this is just an approximation since we do not have
264                            reduction yet! *)
265                         let rec count_prods toskip =
266                          function
267                             C.Prod (_,_,bo) when toskip > 0 ->
268                              count_prods (toskip - 1) bo
269                           | C.Prod (_,_,bo) -> 1 + count_prods 0 bo
270                           | _ -> 0
271                         in
272                          qualified_name_of_uri current_module_uri
273                           ~capitalize:true
274                           (UriManager.uri_of_string
275                             (UriManager.buri_of_uri uri ^ "/" ^ id ^ ".con")),
276                          count_prods paramsno ty
277                       ) cons
278                  | _ -> raise CicExportationInternalError
279                )
280               in
281                let connames_and_argsno_and_patterns =
282                 let rec combine =
283                    function
284                       [],[] -> []
285                     | (x,no)::tlx,y::tly -> (x,no,y)::(combine (tlx,tly))
286                     | _,_ -> assert false
287                 in
288                  combine (connames_and_argsno,patterns)
289                in
290                 "\n(match " ^ pp ~in_type:false te context ^ " with \n   " ^
291                  (String.concat "\n | "
292                   (List.map
293                    (fun (x,argsno,y) ->
294                      let rec aux argsno context =
295                       function
296                          Cic.Lambda (name,ty,bo) when argsno > 0 ->
297                           let args,res =
298                            aux (argsno - 1) (Some (name,Cic.Decl ty)::context)
299                             bo
300                           in
301                            (match analyze_type context ty with
302                                `Statement
303                              | `Sort _ -> args,res
304                              | `Type ->
305                                  (match name with
306                                      C.Anonymous -> "_"
307                                    | C.Name s -> s)::args,res)
308                        | t when argsno = 0 -> [],pp ~in_type:false t context
309                        | t ->
310                           ["{" ^ string_of_int argsno ^ " args missing}"],
311                            pp ~in_type:false t context
312                      in
313                       let pattern,body =
314                        if argsno = 0 then x,pp ~in_type:false y context
315                        else
316                         let args,body = aux argsno context y in
317                         let sargs = String.concat "," args in
318                          x ^ (if sargs = "" then "" else "(" ^ sargs^ ")"),
319                           body
320                       in
321                        pattern ^ " -> " ^
322                         if needs_obj_magic then
323                          "Obj.magic (" ^ body ^ ")"
324                         else
325                          body
326                    ) connames_and_argsno_and_patterns)) ^
327                  ")\n")))
328     | C.Fix (no, funs) ->
329        let names =
330         List.rev
331          (List.map
332            (function (name,_,ty,_) ->
333              Some (C.Name name,Cic.Decl ty)) funs)
334        in
335          "let rec " ^
336          List.fold_right
337           (fun (name,ind,ty,bo) i -> name ^ " = \n" ^
338             pp ~in_type:false bo (names@context) ^ i)
339           funs "" ^
340          " in " ^
341          (match get_nth names (no + 1) with
342              Some (Cic.Name n,_) -> n
343            | _ -> assert false)
344     | C.CoFix (no,funs) ->
345        let names =
346         List.rev
347          (List.map
348            (function (name,ty,_) ->
349              Some (C.Name name,Cic.Decl ty)) funs)
350        in
351          "\nCoFix " ^ " {" ^
352          List.fold_right
353           (fun (name,ty,bo) i -> "\n" ^ name ^ 
354             " : " ^ pp ~in_type:true ty context ^ " := \n" ^
355             pp ~in_type:false bo (names@context) ^ i)
356           funs "" ^
357          "}\n"
358 and pp_exp_named_subst exp_named_subst context =
359  if exp_named_subst = [] then "" else
360   "\\subst[" ^
361    String.concat " ; " (
362     List.map
363      (function (uri,t) -> UriManager.name_of_uri uri ^ " \\Assign " ^ pp ~in_type:false t context)
364      exp_named_subst
365    ) ^ "]"
366 and clean_args nparams context =
367  let nparams = ref nparams in
368  HExtlib.filter_map
369   (function t ->
370     decr nparams;
371     match analyze_term context t with
372        `Term when !nparams < 0 -> Some (pp ~in_type:false t context)
373      | `Term
374      | `Type
375      | `Proof -> None)
376 and clean_args_for_ty context =
377  HExtlib.filter_map
378   (function t ->
379     match analyze_term context t with
380        `Type -> Some (pp ~in_type:true t context)
381      | `Proof -> None
382      | `Term -> None)
383 in
384  pp ~in_type
385 ;;
386
387 let ppty current_module_uri =
388  (* nparams is the number of left arguments
389     left arguments should either become parameters or be skipped altogether *)
390  let rec args nparams context =
391   function
392      Cic.Prod (n,s,t) ->
393       let n =
394        match n with
395           Cic.Anonymous -> Cic.Anonymous
396         | Cic.Name n -> Cic.Name (String.uncapitalize n)
397       in
398        (match analyze_type context s with
399            `Statement
400          | `Sort Cic.Prop ->
401              args (nparams - 1) ((Some (n,Cic.Decl s))::context) t
402          | `Type when nparams > 0 ->
403              args (nparams - 1) ((Some (n,Cic.Decl s))::context) t
404          | `Type ->
405              let abstr,args =
406               args (nparams - 1) ((Some (n,Cic.Decl s))::context) t in
407                abstr,pp ~in_type:true current_module_uri s context::args
408          | `Sort _ ->
409              let n =
410               match n with
411                  Cic.Anonymous -> Cic.Anonymous
412                | Cic.Name name -> Cic.Name ("'" ^ name) in
413              let abstr,args =
414               args (nparams - 1) ((Some (n,Cic.Decl s))::context) t
415              in
416               (match n with
417                   Cic.Anonymous -> abstr
418                 | Cic.Name name -> name::abstr),
419               args)
420    | _ -> [],[]
421  in
422   args
423 ;;
424
425 (* ppinductiveType (typename, inductive, arity, cons)                       *)
426 (* pretty-prints a single inductive definition                              *)
427 (* (typename, inductive, arity, cons)                                       *)
428 let ppinductiveType current_module_uri nparams (typename, inductive, arity, cons)
429 =
430  match analyze_type [] arity with
431     `Sort Cic.Prop -> ""
432   | `Statement
433   | `Type -> assert false
434   | `Sort _ ->
435     if cons = [] then
436      "type " ^ String.uncapitalize typename ^ " = unit (* empty type *)\n"
437     else (
438      let abstr,scons =
439       List.fold_right
440        (fun (id,ty) (_abstr,i) -> (* we should verify _abstr = abstr' *)
441           let abstr',sargs = ppty current_module_uri nparams [] ty in
442           let sargs = String.concat " * " sargs in
443            abstr',
444            String.capitalize id ^
445             (if sargs = "" then "" else " of " ^ sargs) ^
446             (if i = "" then "" else "\n | ") ^ i)
447        cons ([],"")
448       in
449        let abstr =
450         let s = String.concat "," abstr in
451         if s = "" then "" else "(" ^ s ^ ") "
452        in
453        "type " ^ abstr ^ String.uncapitalize typename ^ " =\n" ^ scons ^ "\n")
454 ;;
455
456 let ppobj current_module_uri obj =
457  let module C = Cic in
458  let module U = UriManager in
459   let pp ~in_type = pp ~in_type current_module_uri in
460   match obj with
461     C.Constant (name, Some t1, t2, params, _) ->
462       (match analyze_type [] t2 with
463           `Sort Cic.Prop
464         | `Statement -> ""
465         | `Type -> "let " ^ ppid name ^ " =\n" ^ pp ~in_type:false t1 [] ^ "\n"
466         | `Sort _ ->
467             match analyze_type [] t1 with
468                `Sort Cic.Prop -> ""
469              | _ ->
470                let abstr,args = ppty current_module_uri 0 [] t1 in
471                let abstr =
472                 let s = String.concat "," abstr in
473                 if s = "" then "" else "(" ^ s ^ ") "
474                in
475                 "type " ^ abstr ^ ppid name ^ " = " ^ String.concat "->" args ^
476                 "\n")
477    | C.Constant (name, None, ty, params, _) ->
478       (match analyze_type [] ty with
479           `Sort Cic.Prop
480         | `Statement -> ""
481         | `Sort _ -> "type " ^ ppid name ^ "\n"
482         | `Type -> "let " ^ ppid name ^ " = assert false\n")
483    | C.Variable (name, bo, ty, params, _) ->
484       "Variable " ^ name ^
485        "(" ^ String.concat ";" (List.map UriManager.string_of_uri params) ^
486        ")" ^ ":\n" ^
487        pp ~in_type:true ty [] ^ "\n" ^
488        (match bo with None -> "" | Some bo -> ":= " ^ pp ~in_type:false bo [])
489    | C.CurrentProof (name, conjectures, value, ty, params, _) ->
490       "Current Proof of " ^ name ^
491        "(" ^ String.concat ";" (List.map UriManager.string_of_uri params) ^
492        ")" ^ ":\n" ^
493       let separate s = if s = "" then "" else s ^ " ; " in
494        List.fold_right
495         (fun (n, context, t) i -> 
496           let conjectures',name_context =
497                  List.fold_right 
498                   (fun context_entry (i,name_context) ->
499                     (match context_entry with
500                         Some (n,C.Decl at) ->
501                          (separate i) ^
502                            ppname n ^ ":" ^
503                             pp ~in_type:true ~metasenv:conjectures
504                             at name_context ^ " ",
505                             context_entry::name_context
506                       | Some (n,C.Def (at,None)) ->
507                          (separate i) ^
508                            ppname n ^ ":= " ^ pp ~in_type:false
509                             ~metasenv:conjectures at name_context ^ " ",
510                             context_entry::name_context
511                       | None ->
512                          (separate i) ^ "_ :? _ ", context_entry::name_context
513                       | _ -> assert false)
514             ) context ("",[])
515           in
516            conjectures' ^ " |- " ^ "?" ^ (string_of_int n) ^ ": " ^
517             pp ~in_type:true ~metasenv:conjectures t name_context ^ "\n" ^ i
518         ) conjectures "" ^
519         "\n" ^ pp ~in_type:false ~metasenv:conjectures value [] ^ " : " ^
520           pp ~in_type:true ~metasenv:conjectures ty [] 
521    | C.InductiveDefinition (l, params, nparams, _) ->
522       List.fold_right
523        (fun x i -> ppinductiveType current_module_uri nparams x ^ i) l ""
524 ;;
525
526 let ppobj current_module_uri obj =
527  let res = ppobj current_module_uri obj in
528   if res = "" then "" else res ^ ";;\n\n"
529 ;;