]> matita.cs.unibo.it Git - helm.git/blob - components/cic_exportation/cicExportation.ml
Type application and abstractions are now exported correctly.
[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_name ?(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 buri = UriManager.buri_of_uri uri in
96  let index = String.rindex buri '/' in
97  let filename = String.sub buri (index + 1) (String.length buri - index - 1) in
98   if current_module_name = filename then
99    name
100   else
101    String.capitalize filename ^ "." ^ name
102 ;;
103
104 (* pp t l                                                                  *)
105 (* pretty-prints a term t of cic in an environment l where l is a list of  *)
106 (* identifier names used to resolve DeBrujin indexes. The head of l is the *)
107 (* name associated to the greatest DeBrujin index in t                     *)
108 let pp current_module_name ?metasenv =
109 let rec pp t context =
110  let module C = Cic in
111    match t with
112       C.Rel n ->
113        begin
114         try
115          (match get_nth context n with
116              Some (C.Name s,_) -> ppid s
117            | Some (C.Anonymous,_) -> "__" ^ string_of_int n
118            | None -> "_hidden_" ^ string_of_int n
119          )
120         with
121          NotEnoughElements -> string_of_int (List.length context - n)
122        end
123     | C.Var (uri,exp_named_subst) ->
124         qualified_name_of_uri current_module_name uri ^
125          pp_exp_named_subst exp_named_subst context
126     | C.Meta (n,l1) ->
127        (match metasenv with
128            None ->
129             "?" ^ (string_of_int n) ^ "[" ^ 
130              String.concat " ; "
131               (List.rev_map (function None -> "_" | Some t -> pp t context) l1) ^
132              "]"
133          | Some metasenv ->
134             try
135              let _,context,_ = CicUtil.lookup_meta n metasenv in
136               "?" ^ (string_of_int n) ^ "[" ^ 
137                String.concat " ; "
138                 (List.rev
139                   (List.map2
140                     (fun x y ->
141                       match x,y with
142                          _, None
143                        | None, _ -> "_"
144                        | Some _, Some t -> pp t context
145                     ) context l1)) ^
146                "]"
147             with
148               CicUtil.Meta_not_found _ 
149             | Invalid_argument _ ->
150               "???" ^ (string_of_int n) ^ "[" ^ 
151                String.concat " ; "
152                 (List.rev_map (function None -> "_" | Some t -> pp t context) l1) ^
153                "]"
154        )
155     | C.Sort s ->
156        (match s with
157            C.Prop  -> "Prop"
158          | C.Set   -> "Set"
159          | C.Type _ -> "Type"
160          (*| C.Type u -> ("Type" ^ CicUniv.string_of_universe u)*)
161          | C.CProp -> "CProp" 
162        )
163     | C.Implicit (Some `Hole) -> "%"
164     | C.Implicit _ -> "?"
165     | C.Prod (b,s,t) ->
166        (match b with
167           C.Name n ->
168            let n = "'" ^ String.uncapitalize n in
169             "(" ^ pp s context ^ " -> " ^ pp t ((Some (Cic.Name n,Cic.Decl s))::context) ^ ")"
170         | C.Anonymous -> "(" ^ pp s context ^ " -> " ^ pp t ((Some (b,Cic.Decl s))::context) ^ ")"
171        )
172     | C.Cast (v,t) -> pp v context
173     | C.Lambda (b,s,t) ->
174        (match analyze_type context s with
175            `Sort _
176          | `Statement -> pp t ((Some (b,Cic.Decl s))::context)
177          | `Type -> "(function " ^ ppname b ^ " -> " ^ pp t ((Some (b,Cic.Decl s))::context) ^ ")")
178     | C.LetIn (b,s,t) ->
179        let ty,_ = CicTypeChecker.type_of_aux' [] context t CicUniv.oblivion_ugraph in
180        "(let " ^ ppname b ^ " = " ^ pp s context ^ " in " ^ pp t ((Some (b,Cic.Def (s,Some ty)))::context) ^ ")"
181     | C.Appl (C.MutInd _ as he::tl) ->
182        let hes = pp he context in
183        let stl = String.concat "," (clean_args_for_ty context tl) in
184         (if stl = "" then "" else "(" ^ stl ^ ") ") ^ hes
185     | C.Appl (C.MutConstruct _ as he::tl) ->
186        let hes = pp he context in
187        let stl = String.concat "," (clean_args context tl) in
188         "(" ^ hes ^ (if stl = "" then "" else "(" ^ stl ^ ")") ^ ")"
189     | C.Appl li ->
190        "(" ^ String.concat " " (clean_args context li) ^ ")"
191     | C.Const (uri,exp_named_subst) ->
192        qualified_name_of_uri current_module_name uri ^
193         pp_exp_named_subst exp_named_subst context
194     | C.MutInd (uri,n,exp_named_subst) ->
195        (try
196          match fst(CicEnvironment.get_obj CicUniv.empty_ugraph uri) with
197             C.InductiveDefinition (dl,_,_,_) ->
198              let (name,_,_,_) = get_nth dl (n+1) in
199               qualified_name_of_uri current_module_name
200                (UriManager.uri_of_string
201                  (UriManager.buri_of_uri uri ^ "/" ^ name ^ ".con")) ^
202               pp_exp_named_subst exp_named_subst context
203           | _ -> raise CicExportationInternalError
204         with
205            Sys.Break as exn -> raise exn
206          | _ -> UriManager.string_of_uri uri ^ "#1/" ^ string_of_int (n + 1)
207        )
208     | C.MutConstruct (uri,n1,n2,exp_named_subst) ->
209        (try
210          match fst(CicEnvironment.get_obj CicUniv.empty_ugraph uri) with
211             C.InductiveDefinition (dl,_,_,_) ->
212              let _,_,_,cons = get_nth dl (n1+1) in
213               let id,_ = get_nth cons n2 in
214                qualified_name_of_uri current_module_name ~capitalize:true
215                 (UriManager.uri_of_string
216                   (UriManager.buri_of_uri uri ^ "/" ^ id ^ ".con")) ^
217                pp_exp_named_subst exp_named_subst context
218           | _ -> raise CicExportationInternalError
219         with
220            Sys.Break as exn -> raise exn
221          | _ ->
222           UriManager.string_of_uri uri ^ "#1/" ^ string_of_int (n1 + 1) ^ "/" ^
223            string_of_int n2
224        )
225     | C.MutCase (uri,n1,ty,te,patterns) ->
226        (match analyze_term context te with
227            `Type -> assert false
228          | `Proof ->
229              (match patterns with
230                  [] -> "assert false"   (* empty type elimination *)
231                | [he] -> pp he context  (* singleton elimination *)
232                | _ -> assert false)
233          | `Term ->
234             if patterns = [] then "assert false"
235             else
236              (let connames_and_argsno =
237                (match fst(CicEnvironment.get_obj CicUniv.empty_ugraph uri) with
238                    C.InductiveDefinition (dl,_,paramsno,_) ->
239                     let (_,_,_,cons) = get_nth dl (n1+1) in
240                      List.map
241                       (fun (id,ty) ->
242                         (* this is just an approximation since we do not have
243                            reduction yet! *)
244                         let rec count_prods toskip =
245                          function
246                             C.Prod (_,_,bo) when toskip > 0 ->
247                              count_prods (toskip - 1) bo
248                           | C.Prod (_,_,bo) -> 1 + count_prods 0 bo
249                           | _ -> 0
250                         in
251                          qualified_name_of_uri current_module_name
252                           ~capitalize:true
253                           (UriManager.uri_of_string
254                             (UriManager.buri_of_uri uri ^ "/" ^ id ^ ".con")),
255                          count_prods paramsno ty
256                       ) cons
257                  | _ -> raise CicExportationInternalError
258                )
259               in
260                let connames_and_argsno_and_patterns =
261                 let rec combine =
262                    function
263                       [],[] -> []
264                     | [],l -> List.map (fun x -> "???",0,Some x) l
265                     | l,[] -> List.map (fun (x,no) -> x,no,None) l
266                     | (x,no)::tlx,y::tly -> (x,no,Some y)::(combine (tlx,tly))
267                 in
268                  combine (connames_and_argsno,patterns)
269                in
270                 "\n(match " ^ pp te context ^ " with \n" ^
271                  (String.concat "\n | "
272                   (List.map
273                    (fun (x,argsno,y) ->
274                      let rec aux argsno context =
275                       function
276                          Cic.Lambda (name,ty,bo) when argsno > 0 ->
277                           let args,res =
278                            aux (argsno - 1) (Some (name,Cic.Decl ty)::context)
279                             bo
280                           in
281                            (match name with C.Anonymous -> "_" | C.Name s -> s)
282                            ::args,
283                            res
284                        | t when argsno = 0 -> [],pp t context
285                        | t ->
286                           ["{" ^ string_of_int argsno ^ " args missing}"],
287                            pp t context
288                      in
289                       let pattern,body =
290                        match y with
291                           None -> x,""
292                         | Some y when argsno = 0 -> x,pp y context
293                         | Some y ->
294                            let args,body = aux argsno context y in
295                            let sargs = String.concat "," args in
296                             x ^ (if sargs = "" then "" else "(" ^ sargs^ ")"),
297                              body
298                       in
299                        pattern ^ " -> " ^ body
300                    ) connames_and_argsno_and_patterns)) ^
301                  ")\n"))
302     | C.Fix (no, funs) ->
303        let names =
304         List.rev
305          (List.map
306            (function (name,_,ty,_) ->
307              Some (C.Name name,Cic.Decl ty)) funs)
308        in
309          "\nlet rec " ^
310          List.fold_right
311           (fun (name,ind,ty,bo) i -> name ^ " = \n" ^
312             pp bo (names@context) ^ i)
313           funs "" ^
314          " in " ^
315          (match get_nth names (no + 1) with
316              Some (Cic.Name n,_) -> n
317            | _ -> assert false) ^ "\n"
318     | C.CoFix (no,funs) ->
319        let names =
320         List.rev
321          (List.map
322            (function (name,ty,_) ->
323              Some (C.Name name,Cic.Decl ty)) funs)
324        in
325          "\nCoFix " ^ " {" ^
326          List.fold_right
327           (fun (name,ty,bo) i -> "\n" ^ name ^ 
328             " : " ^ pp ty context ^ " := \n" ^
329             pp bo (names@context) ^ i)
330           funs "" ^
331          "}\n"
332 and pp_exp_named_subst exp_named_subst context =
333  if exp_named_subst = [] then "" else
334   "\\subst[" ^
335    String.concat " ; " (
336     List.map
337      (function (uri,t) -> UriManager.name_of_uri uri ^ " \\Assign " ^ pp t context)
338      exp_named_subst
339    ) ^ "]"
340 and clean_args context =
341  HExtlib.filter_map
342   (function t ->
343     match analyze_term context t with
344        `Type -> None
345      | `Proof -> None
346      | `Term -> Some pp t context)
347 and clean_args_for_ty context =
348  HExtlib.filter_map
349   (function t ->
350     match analyze_term context t with
351        `Type -> Some pp t context
352      | `Proof -> None
353      | `Term -> None)
354 in
355  pp
356 ;;
357
358 let ppty current_module_name =
359  let rec args context =
360   function
361      Cic.Prod (n,s,t) ->
362       let n =
363        match n with
364           Cic.Anonymous -> Cic.Anonymous
365         | Cic.Name n -> Cic.Name (String.uncapitalize n)
366       in
367        (match analyze_type context s with
368            `Sort Cic.Prop -> args ((Some (n,Cic.Decl s))::context) t
369          | `Statement
370          | `Sort _ ->
371              let n =
372               match n with
373                  Cic.Anonymous -> Cic.Anonymous
374                | Cic.Name name -> Cic.Name ("'" ^ name) in
375              let abstr,args = args ((Some (n,Cic.Decl s))::context) t in
376               (match n with
377                   Cic.Anonymous -> abstr
378                 | Cic.Name name -> name::abstr),
379               args
380          | `Type ->
381              let abstr,args = args ((Some (n,Cic.Decl s))::context) t in
382               abstr,pp current_module_name s context::args)
383    | _ -> [],[]
384  in
385   args
386 ;;
387
388 (* ppinductiveType (typename, inductive, arity, cons)                       *)
389 (* pretty-prints a single inductive definition                              *)
390 (* (typename, inductive, arity, cons)                                       *)
391 let ppinductiveType current_module_name nparams (typename, inductive, arity, cons)
392 =
393  match analyze_type [] arity with
394     `Sort Cic.Prop -> ""
395   | `Statement
396   | `Type -> assert false
397   | `Sort _ ->
398     if cons = [] then
399      "type " ^ String.uncapitalize typename ^ " = unit (* empty type *)\n"
400     else (
401      let abstr,scons =
402       List.fold_right
403        (fun (id,ty) (_abstr,i) -> (* we should verify _abstr = abstr' *)
404           let abstr',sargs = ppty current_module_name [] ty in
405           let sargs = String.concat " * " sargs in
406            abstr',
407            String.capitalize id ^
408             (if sargs = "" then "" else " of " ^ sargs) ^
409             (if i = "" then "" else "\n | ") ^ i)
410        cons ([],"")
411       in
412        let abstr =
413         let s = String.concat "," abstr in
414         if s = "" then "" else "(" ^ s ^ ") "
415        in
416        "type " ^ abstr ^ String.uncapitalize typename ^ " =\n" ^ scons ^ "\n")
417 ;;
418
419 let ppobj current_module_name obj =
420  let module C = Cic in
421  let module U = UriManager in
422   let pp = pp current_module_name in
423   match obj with
424     C.Constant (name, Some t1, t2, params, _) ->
425       (match analyze_type [] t2 with
426           `Sort Cic.Prop
427         | `Statement -> ""
428         | `Type -> "let " ^ ppid name ^ " =\n" ^ pp t1 [] ^ "\n"
429         | `Sort _ ->
430             match analyze_type [] t1 with
431                `Sort Cic.Prop -> ""
432              | _ ->
433                let abstr,args = ppty current_module_name [] t1 in
434                let abstr =
435                 let s = String.concat "," abstr in
436                 if s = "" then "" else "(" ^ s ^ ") "
437                in
438                 "type " ^ abstr ^ ppid name ^ " = " ^ String.concat "->" args ^
439                 "\n")
440    | C.Constant (name, None, ty, params, _) ->
441       (match analyze_type [] ty with
442           `Sort Cic.Prop
443         | `Statement -> ""
444         | `Sort _ -> "type " ^ ppid name ^ "\n"
445         | `Type -> "let " ^ ppid name ^ " = assert false\n")
446    | C.Variable (name, bo, ty, params, _) ->
447       "Variable " ^ name ^
448        "(" ^ String.concat ";" (List.map UriManager.string_of_uri params) ^
449        ")" ^ ":\n" ^
450        pp ty [] ^ "\n" ^
451        (match bo with None -> "" | Some bo -> ":= " ^ pp bo [])
452    | C.CurrentProof (name, conjectures, value, ty, params, _) ->
453       "Current Proof of " ^ name ^
454        "(" ^ String.concat ";" (List.map UriManager.string_of_uri params) ^
455        ")" ^ ":\n" ^
456       let separate s = if s = "" then "" else s ^ " ; " in
457        List.fold_right
458         (fun (n, context, t) i -> 
459           let conjectures',name_context =
460                  List.fold_right 
461                   (fun context_entry (i,name_context) ->
462                     (match context_entry with
463                         Some (n,C.Decl at) ->
464                          (separate i) ^
465                            ppname n ^ ":" ^
466                             pp ~metasenv:conjectures at name_context ^ " ",
467                             context_entry::name_context
468                       | Some (n,C.Def (at,None)) ->
469                          (separate i) ^
470                            ppname n ^ ":= " ^ pp ~metasenv:conjectures
471                             at name_context ^ " ",
472                             context_entry::name_context
473                       | None ->
474                          (separate i) ^ "_ :? _ ", context_entry::name_context
475                       | _ -> assert false)
476             ) context ("",[])
477           in
478            conjectures' ^ " |- " ^ "?" ^ (string_of_int n) ^ ": " ^
479             pp ~metasenv:conjectures t name_context ^ "\n" ^ i
480         ) conjectures "" ^
481         "\n" ^ pp ~metasenv:conjectures value [] ^ " : " ^
482           pp ~metasenv:conjectures ty [] 
483    | C.InductiveDefinition (l, params, nparams, _) ->
484       List.fold_right
485        (fun x i -> ppinductiveType current_module_name nparams x ^ i) l ""
486 ;;
487
488 let ppobj current_module_name obj =
489  let res = ppobj current_module_name obj in
490   if res = "" then "" else res ^ ";;\n\n"
491 ;;