]> matita.cs.unibo.it Git - helm.git/blob - helm/software/components/cic_exportation/cicExportation.ml
Very experimental commit: the type of the source is now required in LetIns
[helm.git] / helm / software / 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,ty,t) ->
186        (match analyze_term context s with
187            `Type
188          | `Proof -> pp ~in_type t ((Some (b,Cic.Def (s,ty)))::context)
189          | `Term ->
190             "(let " ^ ppname b ^ " : " ^ pp ~in_type:true ty context ^
191             " = " ^ pp ~in_type:false s context ^ " in " ^
192              pp ~in_type t ((Some (b,Cic.Def (s,ty)))::context) ^ ")")
193     | C.Appl (he::tl) when in_type ->
194        let hes = pp ~in_type he context in
195        let stl = String.concat "," (clean_args_for_ty context tl) in
196         (if stl = "" then "" else "(" ^ stl ^ ") ") ^ hes
197     | C.Appl (C.MutInd _ as he::tl) ->
198        let hes = pp ~in_type he context in
199        let stl = String.concat "," (clean_args_for_ty context tl) in
200         (if stl = "" then "" else "(" ^ stl ^ ") ") ^ hes
201     | C.Appl (C.MutConstruct (uri,n,_,_) as he::tl) ->
202        let nparams =
203         match fst(CicEnvironment.get_obj CicUniv.empty_ugraph uri) with
204            C.InductiveDefinition (_,_,nparams,_) -> nparams
205          | _ -> assert false in
206        let hes = pp ~in_type he context in
207        let stl = String.concat "," (clean_args nparams context tl) in
208         "(" ^ hes ^ (if stl = "" then "" else "(" ^ stl ^ ")") ^ ")"
209     | C.Appl li ->
210        "(" ^ String.concat " " (clean_args 0 context li) ^ ")"
211     | C.Const (uri,exp_named_subst) ->
212        qualified_name_of_uri current_module_uri uri ^
213         pp_exp_named_subst exp_named_subst context
214     | C.MutInd (uri,n,exp_named_subst) ->
215        (try
216          match fst(CicEnvironment.get_obj CicUniv.empty_ugraph uri) with
217             C.InductiveDefinition (dl,_,_,_) ->
218              let (name,_,_,_) = get_nth dl (n+1) in
219               qualified_name_of_uri current_module_uri
220                (UriManager.uri_of_string
221                  (UriManager.buri_of_uri uri ^ "/" ^ name ^ ".con")) ^
222               pp_exp_named_subst exp_named_subst context
223           | _ -> raise CicExportationInternalError
224         with
225            Sys.Break as exn -> raise exn
226          | _ -> UriManager.string_of_uri uri ^ "#1/" ^ string_of_int (n + 1)
227        )
228     | C.MutConstruct (uri,n1,n2,exp_named_subst) ->
229        (try
230          match fst(CicEnvironment.get_obj CicUniv.empty_ugraph uri) with
231             C.InductiveDefinition (dl,_,_,_) ->
232              let _,_,_,cons = get_nth dl (n1+1) in
233               let id,_ = get_nth cons n2 in
234                qualified_name_of_uri current_module_uri ~capitalize:true
235                 (UriManager.uri_of_string
236                   (UriManager.buri_of_uri uri ^ "/" ^ id ^ ".con")) ^
237                pp_exp_named_subst exp_named_subst context
238           | _ -> raise CicExportationInternalError
239         with
240            Sys.Break as exn -> raise exn
241          | _ ->
242           UriManager.string_of_uri uri ^ "#1/" ^ string_of_int (n1 + 1) ^ "/" ^
243            string_of_int n2
244        )
245     | C.MutCase (uri,n1,ty,te,patterns) ->
246        if in_type then
247         "unit (* TOO POLYMORPHIC TYPE *)"
248        else (
249        let needs_obj_magic =
250         (* BUG HERE: we should consider also the right parameters *)
251         match CicReduction.whd context ty with
252            Cic.Lambda (_,_,t) -> not (DoubleTypeInference.does_not_occur 1 t)
253          | _ -> false (* it can be a Rel, e.g. in *_rec *)
254        in
255        (match analyze_term context te with
256            `Type -> assert false
257          | `Proof ->
258              (match patterns with
259                  [] -> "assert false"   (* empty type elimination *)
260                | [he] ->
261                   pp ~in_type:false he context  (* singleton elimination *)
262                | _ -> assert false)
263          | `Term ->
264             if patterns = [] then "assert false"
265             else
266              (let connames_and_argsno =
267                (match fst(CicEnvironment.get_obj CicUniv.empty_ugraph uri) with
268                    C.InductiveDefinition (dl,_,paramsno,_) ->
269                     let (_,_,_,cons) = get_nth dl (n1+1) in
270                      List.map
271                       (fun (id,ty) ->
272                         (* this is just an approximation since we do not have
273                            reduction yet! *)
274                         let rec count_prods toskip =
275                          function
276                             C.Prod (_,_,bo) when toskip > 0 ->
277                              count_prods (toskip - 1) bo
278                           | C.Prod (_,_,bo) -> 1 + count_prods 0 bo
279                           | _ -> 0
280                         in
281                          qualified_name_of_uri current_module_uri
282                           ~capitalize:true
283                           (UriManager.uri_of_string
284                             (UriManager.buri_of_uri uri ^ "/" ^ id ^ ".con")),
285                          count_prods paramsno ty
286                       ) cons
287                  | _ -> raise CicExportationInternalError
288                )
289               in
290                let connames_and_argsno_and_patterns =
291                 let rec combine =
292                    function
293                       [],[] -> []
294                     | (x,no)::tlx,y::tly -> (x,no,y)::(combine (tlx,tly))
295                     | _,_ -> assert false
296                 in
297                  combine (connames_and_argsno,patterns)
298                in
299                 "\n(match " ^ pp ~in_type:false te context ^ " with \n   " ^
300                  (String.concat "\n | "
301                   (List.map
302                    (fun (x,argsno,y) ->
303                      let rec aux argsno context =
304                       function
305                          Cic.Lambda (name,ty,bo) when argsno > 0 ->
306                           let name =
307                            match name with
308                               Cic.Anonymous -> Cic.Anonymous
309                             | Cic.Name n -> Cic.Name (ppid n) in
310                           let args,res =
311                            aux (argsno - 1) (Some (name,Cic.Decl ty)::context)
312                             bo
313                           in
314                            (match analyze_type context ty with
315                                `Statement
316                              | `Sort _ -> args,res
317                              | `Type ->
318                                  (match name with
319                                      C.Anonymous -> "_"
320                                    | C.Name s -> s)::args,res)
321                        | t when argsno = 0 -> [],pp ~in_type:false t context
322                        | t ->
323                           ["{" ^ string_of_int argsno ^ " args missing}"],
324                            pp ~in_type:false t context
325                      in
326                       let pattern,body =
327                        if argsno = 0 then x,pp ~in_type:false y context
328                        else
329                         let args,body = aux argsno context y in
330                         let sargs = String.concat "," args in
331                          x ^ (if sargs = "" then "" else "(" ^ sargs^ ")"),
332                           body
333                       in
334                        pattern ^ " -> " ^
335                         if needs_obj_magic then
336                          "Obj.magic (" ^ body ^ ")"
337                         else
338                          body
339                    ) connames_and_argsno_and_patterns)) ^
340                  ")\n")))
341     | C.Fix (no, funs) ->
342        let names,_ =
343         List.fold_left
344          (fun (types,len) (n,_,ty,_) ->
345             (Some (C.Name n,(C.Decl (CicSubstitution.lift len ty)))::types,
346              len+1)
347          ) ([],0) funs
348        in
349          "let rec " ^
350          List.fold_right
351           (fun (name,ind,ty,bo) i -> name ^ " = \n" ^
352             pp ~in_type:false bo (names@context) ^ i)
353           funs "" ^
354          " in " ^
355          (match get_nth names (no + 1) with
356              Some (Cic.Name n,_) -> n
357            | _ -> assert false)
358     | C.CoFix (no,funs) ->
359        let names,_ =
360         List.fold_left
361          (fun (types,len) (n,ty,_) ->
362             (Some (C.Name n,(C.Decl (CicSubstitution.lift len ty)))::types,
363              len+1)
364          ) ([],0) funs
365        in
366          "\nCoFix " ^ " {" ^
367          List.fold_right
368           (fun (name,ty,bo) i -> "\n" ^ name ^ 
369             " : " ^ pp ~in_type:true ty context ^ " := \n" ^
370             pp ~in_type:false bo (names@context) ^ i)
371           funs "" ^
372          "}\n"
373 and pp_exp_named_subst exp_named_subst context =
374  if exp_named_subst = [] then "" else
375   "\\subst[" ^
376    String.concat " ; " (
377     List.map
378      (function (uri,t) -> UriManager.name_of_uri uri ^ " \\Assign " ^ pp ~in_type:false t context)
379      exp_named_subst
380    ) ^ "]"
381 and clean_args nparams context =
382  let nparams = ref nparams in
383  HExtlib.filter_map
384   (function t ->
385     decr nparams;
386     match analyze_term context t with
387        `Term when !nparams < 0 -> Some (pp ~in_type:false t context)
388      | `Term
389      | `Type
390      | `Proof -> None)
391 and clean_args_for_ty context =
392  HExtlib.filter_map
393   (function t ->
394     match analyze_term context t with
395        `Type -> Some (pp ~in_type:true t context)
396      | `Proof -> None
397      | `Term -> None)
398 in
399  pp ~in_type
400 ;;
401
402 let ppty current_module_uri =
403  (* nparams is the number of left arguments
404     left arguments should either become parameters or be skipped altogether *)
405  let rec args nparams context =
406   function
407      Cic.Prod (n,s,t) ->
408       let n =
409        match n with
410           Cic.Anonymous -> Cic.Anonymous
411         | Cic.Name n -> Cic.Name (String.uncapitalize n)
412       in
413        (match analyze_type context s with
414            `Statement
415          | `Sort Cic.Prop ->
416              args (nparams - 1) ((Some (n,Cic.Decl s))::context) t
417          | `Type when nparams > 0 ->
418              args (nparams - 1) ((Some (n,Cic.Decl s))::context) t
419          | `Type ->
420              let abstr,args =
421               args (nparams - 1) ((Some (n,Cic.Decl s))::context) t in
422                abstr,pp ~in_type:true current_module_uri s context::args
423          | `Sort _ when nparams <= 0 ->
424              let n = Cic.Name "unit (* EXISTENTIAL TYPE *)" in
425               args (nparams - 1) ((Some (n,Cic.Decl s))::context) t
426          | `Sort _ ->
427              let n =
428               match n with
429                  Cic.Anonymous -> Cic.Anonymous
430                | Cic.Name name -> Cic.Name ("'" ^ name) in
431              let abstr,args =
432               args (nparams - 1) ((Some (n,Cic.Decl s))::context) t
433              in
434               (match n with
435                   Cic.Anonymous -> abstr
436                 | Cic.Name name -> name::abstr),
437               args)
438    | _ -> [],[]
439  in
440   args
441 ;;
442
443 exception DoNotExtract;;
444
445 let pp_abstracted_ty current_module_uri =
446  let rec args context =
447   function
448      Cic.Lambda (n,s,t) ->
449       let n =
450        match n with
451           Cic.Anonymous -> Cic.Anonymous
452         | Cic.Name n -> Cic.Name (String.uncapitalize n)
453       in
454        (match analyze_type context s with
455            `Statement
456          | `Type
457          | `Sort Cic.Prop ->
458              args ((Some (n,Cic.Decl s))::context) t
459          | `Sort _ ->
460              let n =
461               match n with
462                  Cic.Anonymous -> Cic.Anonymous
463                | Cic.Name name -> Cic.Name ("'" ^ name) in
464              let abstr,res =
465               args ((Some (n,Cic.Decl s))::context) t
466              in
467               (match n with
468                   Cic.Anonymous -> abstr
469                 | Cic.Name name -> name::abstr),
470               res)
471    | ty ->
472      match analyze_type context ty with
473       `  Sort _
474       | `Statement -> raise DoNotExtract
475       | `Type ->
476           (* BUG HERE: this can be a real System F type *)
477           let head = pp ~in_type:true current_module_uri ty context in
478           [],head
479  in
480   args
481 ;;
482
483
484 (* ppinductiveType (typename, inductive, arity, cons)                       *)
485 (* pretty-prints a single inductive definition                              *)
486 (* (typename, inductive, arity, cons)                                       *)
487 let ppinductiveType current_module_uri nparams (typename, inductive, arity, cons)
488 =
489  match analyze_type [] arity with
490     `Sort Cic.Prop -> ""
491   | `Statement
492   | `Type -> assert false
493   | `Sort _ ->
494     if cons = [] then
495      "type " ^ String.uncapitalize typename ^ " = unit (* empty type *)\n"
496     else (
497      let abstr,scons =
498       List.fold_right
499        (fun (id,ty) (_abstr,i) -> (* we should verify _abstr = abstr' *)
500           let abstr',sargs = ppty current_module_uri nparams [] ty in
501           let sargs = String.concat " * " sargs in
502            abstr',
503            String.capitalize id ^
504             (if sargs = "" then "" else " of " ^ sargs) ^
505             (if i = "" then "" else "\n | ") ^ i)
506        cons ([],"")
507       in
508        let abstr =
509         let s = String.concat "," abstr in
510         if s = "" then "" else "(" ^ s ^ ") "
511        in
512        "type " ^ abstr ^ String.uncapitalize typename ^ " =\n" ^ scons ^ "\n")
513 ;;
514
515 let ppobj current_module_uri obj =
516  let module C = Cic in
517  let module U = UriManager in
518   let pp ~in_type = pp ~in_type current_module_uri in
519   match obj with
520     C.Constant (name, Some t1, t2, params, _) ->
521       (match analyze_type [] t2 with
522           `Sort Cic.Prop
523         | `Statement -> ""
524         | `Type -> "let " ^ ppid name ^ " =\n" ^ pp ~in_type:false t1 [] ^ "\n"
525         | `Sort _ ->
526             match analyze_type [] t1 with
527                `Sort Cic.Prop -> ""
528              | _ ->
529                (try
530                  let abstr,res = pp_abstracted_ty current_module_uri [] t1 in
531                  let abstr =
532                   let s = String.concat "," abstr in
533                   if s = "" then "" else "(" ^ s ^ ") "
534                  in
535                   "type " ^ abstr ^ ppid name ^ " = " ^ res ^ "\n"
536                 with
537                  DoNotExtract -> ""))
538    | C.Constant (name, None, ty, params, _) ->
539       (match analyze_type [] ty with
540           `Sort Cic.Prop
541         | `Statement -> ""
542         | `Sort _ -> "type " ^ ppid name ^ "\n"
543         | `Type -> "let " ^ ppid name ^ " = assert false\n")
544    | C.Variable (name, bo, ty, params, _) ->
545       "Variable " ^ name ^
546        "(" ^ String.concat ";" (List.map UriManager.string_of_uri params) ^
547        ")" ^ ":\n" ^
548        pp ~in_type:true ty [] ^ "\n" ^
549        (match bo with None -> "" | Some bo -> ":= " ^ pp ~in_type:false bo [])
550    | C.CurrentProof (name, conjectures, value, ty, params, _) ->
551       "Current Proof of " ^ name ^
552        "(" ^ String.concat ";" (List.map UriManager.string_of_uri params) ^
553        ")" ^ ":\n" ^
554       let separate s = if s = "" then "" else s ^ " ; " in
555        List.fold_right
556         (fun (n, context, t) i -> 
557           let conjectures',name_context =
558                  List.fold_right 
559                   (fun context_entry (i,name_context) ->
560                     (match context_entry with
561                         Some (n,C.Decl at) ->
562                          (separate i) ^
563                            ppname n ^ ":" ^
564                             pp ~in_type:true ~metasenv:conjectures
565                             at name_context ^ " ",
566                             context_entry::name_context
567                       | Some (n,C.Def (at,aty)) ->
568                          (separate i) ^
569                            ppname n ^ ":" ^
570                             pp ~in_type:true ~metasenv:conjectures
571                             aty name_context ^
572                            ":= " ^ pp ~in_type:false
573                             ~metasenv:conjectures at name_context ^ " ",
574                             context_entry::name_context
575                       | None ->
576                          (separate i) ^ "_ :? _ ", context_entry::name_context)
577             ) context ("",[])
578           in
579            conjectures' ^ " |- " ^ "?" ^ (string_of_int n) ^ ": " ^
580             pp ~in_type:true ~metasenv:conjectures t name_context ^ "\n" ^ i
581         ) conjectures "" ^
582         "\n" ^ pp ~in_type:false ~metasenv:conjectures value [] ^ " : " ^
583           pp ~in_type:true ~metasenv:conjectures ty [] 
584    | C.InductiveDefinition (l, params, nparams, _) ->
585       List.fold_right
586        (fun x i -> ppinductiveType current_module_uri nparams x ^ i) l ""
587 ;;
588
589 let ppobj current_module_uri obj =
590  let res = ppobj current_module_uri obj in
591   if res = "" then "" else res ^ ";;\n\n"
592 ;;