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