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