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