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