]> matita.cs.unibo.it Git - helm.git/blob - components/cic_exportation/cicExportation.ml
Trivial bug fixed in type inference of LetIn source types.
[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 s 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 name =
298                            match name with
299                               Cic.Anonymous -> Cic.Anonymous
300                             | Cic.Name n -> Cic.Name (ppid n) in
301                           let args,res =
302                            aux (argsno - 1) (Some (name,Cic.Decl ty)::context)
303                             bo
304                           in
305                            (match analyze_type context ty with
306                                `Statement
307                              | `Sort _ -> args,res
308                              | `Type ->
309                                  (match name with
310                                      C.Anonymous -> "_"
311                                    | C.Name s -> s)::args,res)
312                        | t when argsno = 0 -> [],pp ~in_type:false t context
313                        | t ->
314                           ["{" ^ string_of_int argsno ^ " args missing}"],
315                            pp ~in_type:false t context
316                      in
317                       let pattern,body =
318                        if argsno = 0 then x,pp ~in_type:false y context
319                        else
320                         let args,body = aux argsno context y in
321                         let sargs = String.concat "," args in
322                          x ^ (if sargs = "" then "" else "(" ^ sargs^ ")"),
323                           body
324                       in
325                        pattern ^ " -> " ^
326                         if needs_obj_magic then
327                          "Obj.magic (" ^ body ^ ")"
328                         else
329                          body
330                    ) connames_and_argsno_and_patterns)) ^
331                  ")\n")))
332     | C.Fix (no, funs) ->
333        let names =
334         List.rev
335          (List.map
336            (function (name,_,ty,_) ->
337              Some (C.Name name,Cic.Decl ty)) funs)
338        in
339          "let rec " ^
340          List.fold_right
341           (fun (name,ind,ty,bo) i -> name ^ " = \n" ^
342             pp ~in_type:false bo (names@context) ^ i)
343           funs "" ^
344          " in " ^
345          (match get_nth names (no + 1) with
346              Some (Cic.Name n,_) -> n
347            | _ -> assert false)
348     | C.CoFix (no,funs) ->
349        let names =
350         List.rev
351          (List.map
352            (function (name,ty,_) ->
353              Some (C.Name name,Cic.Decl ty)) funs)
354        in
355          "\nCoFix " ^ " {" ^
356          List.fold_right
357           (fun (name,ty,bo) i -> "\n" ^ name ^ 
358             " : " ^ pp ~in_type:true ty context ^ " := \n" ^
359             pp ~in_type:false bo (names@context) ^ i)
360           funs "" ^
361          "}\n"
362 and pp_exp_named_subst exp_named_subst context =
363  if exp_named_subst = [] then "" else
364   "\\subst[" ^
365    String.concat " ; " (
366     List.map
367      (function (uri,t) -> UriManager.name_of_uri uri ^ " \\Assign " ^ pp ~in_type:false t context)
368      exp_named_subst
369    ) ^ "]"
370 and clean_args nparams context =
371  let nparams = ref nparams in
372  HExtlib.filter_map
373   (function t ->
374     decr nparams;
375     match analyze_term context t with
376        `Term when !nparams < 0 -> Some (pp ~in_type:false t context)
377      | `Term
378      | `Type
379      | `Proof -> None)
380 and clean_args_for_ty context =
381  HExtlib.filter_map
382   (function t ->
383     match analyze_term context t with
384        `Type -> Some (pp ~in_type:true t context)
385      | `Proof -> None
386      | `Term -> None)
387 in
388  pp ~in_type
389 ;;
390
391 let ppty current_module_uri =
392  (* nparams is the number of left arguments
393     left arguments should either become parameters or be skipped altogether *)
394  let rec args nparams context =
395   function
396      Cic.Prod (n,s,t) ->
397       let n =
398        match n with
399           Cic.Anonymous -> Cic.Anonymous
400         | Cic.Name n -> Cic.Name (String.uncapitalize n)
401       in
402        (match analyze_type context s with
403            `Statement
404          | `Sort Cic.Prop ->
405              args (nparams - 1) ((Some (n,Cic.Decl s))::context) t
406          | `Type when nparams > 0 ->
407              args (nparams - 1) ((Some (n,Cic.Decl s))::context) t
408          | `Type ->
409              let abstr,args =
410               args (nparams - 1) ((Some (n,Cic.Decl s))::context) t in
411                abstr,pp ~in_type:true current_module_uri s context::args
412          | `Sort _ ->
413              let n =
414               match n with
415                  Cic.Anonymous -> Cic.Anonymous
416                | Cic.Name name -> Cic.Name ("'" ^ name) in
417              let abstr,args =
418               args (nparams - 1) ((Some (n,Cic.Decl s))::context) t
419              in
420               (match n with
421                   Cic.Anonymous -> abstr
422                 | Cic.Name name -> name::abstr),
423               args)
424    | _ -> [],[]
425  in
426   args
427 ;;
428
429 (* ppinductiveType (typename, inductive, arity, cons)                       *)
430 (* pretty-prints a single inductive definition                              *)
431 (* (typename, inductive, arity, cons)                                       *)
432 let ppinductiveType current_module_uri nparams (typename, inductive, arity, cons)
433 =
434  match analyze_type [] arity with
435     `Sort Cic.Prop -> ""
436   | `Statement
437   | `Type -> assert false
438   | `Sort _ ->
439     if cons = [] then
440      "type " ^ String.uncapitalize typename ^ " = unit (* empty type *)\n"
441     else (
442      let abstr,scons =
443       List.fold_right
444        (fun (id,ty) (_abstr,i) -> (* we should verify _abstr = abstr' *)
445           let abstr',sargs = ppty current_module_uri nparams [] ty in
446           let sargs = String.concat " * " sargs in
447            abstr',
448            String.capitalize id ^
449             (if sargs = "" then "" else " of " ^ sargs) ^
450             (if i = "" then "" else "\n | ") ^ i)
451        cons ([],"")
452       in
453        let abstr =
454         let s = String.concat "," abstr in
455         if s = "" then "" else "(" ^ s ^ ") "
456        in
457        "type " ^ abstr ^ String.uncapitalize typename ^ " =\n" ^ scons ^ "\n")
458 ;;
459
460 let ppobj current_module_uri obj =
461  let module C = Cic in
462  let module U = UriManager in
463   let pp ~in_type = pp ~in_type current_module_uri in
464   match obj with
465     C.Constant (name, Some t1, t2, params, _) ->
466       (match analyze_type [] t2 with
467           `Sort Cic.Prop
468         | `Statement -> ""
469         | `Type -> "let " ^ ppid name ^ " =\n" ^ pp ~in_type:false t1 [] ^ "\n"
470         | `Sort _ ->
471             match analyze_type [] t1 with
472                `Sort Cic.Prop -> ""
473              | _ ->
474                let abstr,args = ppty current_module_uri 0 [] t1 in
475                let abstr =
476                 let s = String.concat "," abstr in
477                 if s = "" then "" else "(" ^ s ^ ") "
478                in
479                 "type " ^ abstr ^ ppid name ^ " = " ^ String.concat "->" args ^
480                 "\n")
481    | C.Constant (name, None, ty, params, _) ->
482       (match analyze_type [] ty with
483           `Sort Cic.Prop
484         | `Statement -> ""
485         | `Sort _ -> "type " ^ ppid name ^ "\n"
486         | `Type -> "let " ^ ppid name ^ " = assert false\n")
487    | C.Variable (name, bo, ty, params, _) ->
488       "Variable " ^ name ^
489        "(" ^ String.concat ";" (List.map UriManager.string_of_uri params) ^
490        ")" ^ ":\n" ^
491        pp ~in_type:true ty [] ^ "\n" ^
492        (match bo with None -> "" | Some bo -> ":= " ^ pp ~in_type:false bo [])
493    | C.CurrentProof (name, conjectures, value, ty, params, _) ->
494       "Current Proof of " ^ name ^
495        "(" ^ String.concat ";" (List.map UriManager.string_of_uri params) ^
496        ")" ^ ":\n" ^
497       let separate s = if s = "" then "" else s ^ " ; " in
498        List.fold_right
499         (fun (n, context, t) i -> 
500           let conjectures',name_context =
501                  List.fold_right 
502                   (fun context_entry (i,name_context) ->
503                     (match context_entry with
504                         Some (n,C.Decl at) ->
505                          (separate i) ^
506                            ppname n ^ ":" ^
507                             pp ~in_type:true ~metasenv:conjectures
508                             at name_context ^ " ",
509                             context_entry::name_context
510                       | Some (n,C.Def (at,None)) ->
511                          (separate i) ^
512                            ppname n ^ ":= " ^ pp ~in_type:false
513                             ~metasenv:conjectures at name_context ^ " ",
514                             context_entry::name_context
515                       | None ->
516                          (separate i) ^ "_ :? _ ", context_entry::name_context
517                       | _ -> assert false)
518             ) context ("",[])
519           in
520            conjectures' ^ " |- " ^ "?" ^ (string_of_int n) ^ ": " ^
521             pp ~in_type:true ~metasenv:conjectures t name_context ^ "\n" ^ i
522         ) conjectures "" ^
523         "\n" ^ pp ~in_type:false ~metasenv:conjectures value [] ^ " : " ^
524           pp ~in_type:true ~metasenv:conjectures ty [] 
525    | C.InductiveDefinition (l, params, nparams, _) ->
526       List.fold_right
527        (fun x i -> ppinductiveType current_module_uri nparams x ^ i) l ""
528 ;;
529
530 let ppobj current_module_uri obj =
531  let res = ppobj current_module_uri obj in
532   if res = "" then "" else res ^ ";;\n\n"
533 ;;