]> matita.cs.unibo.it Git - helm.git/blob - components/cic_exportation/cicExportation.ml
4b10fe7316514680e465d5d9d994c01bb1f01ba7
[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             let connames_and_argsno =
228              (match fst(CicEnvironment.get_obj CicUniv.empty_ugraph uri) with
229                  C.InductiveDefinition (dl,_,paramsno,_) ->
230                   let (_,_,_,cons) = get_nth dl (n1+1) in
231                    List.map
232                     (fun (id,ty) ->
233                       (* this is just an approximation since we do not have
234                          reduction yet! *)
235                       let rec count_prods toskip =
236                        function
237                           C.Prod (_,_,bo) when toskip > 0 ->
238                            count_prods (toskip - 1) bo
239                         | C.Prod (_,_,bo) -> 1 + count_prods 0 bo
240                         | _ -> 0
241                       in
242                        qualified_name_of_uri current_module_name ~capitalize:true
243                         (UriManager.uri_of_string
244                           (UriManager.buri_of_uri uri ^ "/" ^ id ^ ".con")),
245                        count_prods paramsno ty
246                     ) cons
247                | _ -> raise CicExportationInternalError
248              )
249             in
250              let connames_and_argsno_and_patterns =
251               let rec combine =
252                  function
253                     [],[] -> []
254                   | [],l -> List.map (fun x -> "???",0,Some x) l
255                   | l,[] -> List.map (fun (x,no) -> x,no,None) l
256                   | (x,no)::tlx,y::tly -> (x,no,Some y)::(combine (tlx,tly))
257               in
258                combine (connames_and_argsno,patterns)
259              in
260               "\n(match " ^ pp te context ^ " with \n" ^
261                (String.concat "\n | "
262                 (List.map
263                  (fun (x,argsno,y) ->
264                    let rec aux argsno context =
265                     function
266                        Cic.Lambda (name,ty,bo) when argsno > 0 ->
267                         let args,res = aux (argsno - 1) (Some (name,Cic.Decl ty)::context) bo in
268                          (match name with C.Anonymous -> "_" | C.Name s -> s)::args,
269                          res
270                      | t when argsno = 0 -> [],pp t context
271                      | t -> ["{" ^ string_of_int argsno ^ " args missing}"],pp t context
272                    in
273                     let pattern,body =
274                      match y with
275                         None -> x,""
276                       | Some y when argsno = 0 -> x,pp y context
277                       | Some y ->
278                          let args,body = aux argsno context y in
279                          let sargs = String.concat "," args in
280                           x ^ (if sargs = "" then "" else "(" ^ sargs^ ")"),body
281                     in
282                      pattern ^ " -> " ^ body
283                  ) connames_and_argsno_and_patterns)) ^
284                ")\n")
285     | C.Fix (no, funs) ->
286        let names =
287         List.rev
288          (List.map
289            (function (name,_,ty,_) ->
290              Some (C.Name name,Cic.Decl ty)) funs)
291        in
292          "\nlet rec " ^
293          List.fold_right
294           (fun (name,ind,ty,bo) i -> name ^ " = \n" ^
295             pp bo (names@context) ^ i)
296           funs "" ^
297          " in " ^
298          (match get_nth names (no + 1) with
299              Some (Cic.Name n,_) -> n
300            | _ -> assert false) ^ "\n"
301     | C.CoFix (no,funs) ->
302        let names =
303         List.rev
304          (List.map
305            (function (name,ty,_) ->
306              Some (C.Name name,Cic.Decl ty)) funs)
307        in
308          "\nCoFix " ^ " {" ^
309          List.fold_right
310           (fun (name,ty,bo) i -> "\n" ^ name ^ 
311             " : " ^ pp ty context ^ " := \n" ^
312             pp bo (names@context) ^ i)
313           funs "" ^
314          "}\n"
315 and pp_exp_named_subst exp_named_subst context =
316  if exp_named_subst = [] then "" else
317   "\\subst[" ^
318    String.concat " ; " (
319     List.map
320      (function (uri,t) -> UriManager.name_of_uri uri ^ " \\Assign " ^ pp t context)
321      exp_named_subst
322    ) ^ "]"
323 and clean_args context =
324  HExtlib.filter_map
325   (function t ->
326     match analyze_term context t with
327        `Type -> None
328      | `Proof -> None
329      | `Term -> Some pp t context)
330 in
331  pp
332 ;;
333
334 let ppty current_module_name =
335  let rec args context =
336   function
337      Cic.Prod (n,s,t) ->
338        (match analyze_type context s with
339            `Sort Cic.Prop -> args ((Some (n,Cic.Decl s))::context) t
340          | `Statement
341          | `Sort _ ->
342              let n =
343               match n with
344                  Cic.Anonymous -> Cic.Anonymous
345                | Cic.Name name -> Cic.Name ("'" ^ name) in
346              let abstr,args = args ((Some (n,Cic.Decl s))::context) t in
347               (match n with
348                   Cic.Anonymous -> abstr
349                 | Cic.Name name -> name::abstr),
350               args
351          | `Type ->
352              let abstr,args = args ((Some (n,Cic.Decl s))::context) t in
353               abstr,pp current_module_name s context::args)
354    | _ -> [],[]
355  in
356   args
357 ;;
358
359 (* ppinductiveType (typename, inductive, arity, cons)                       *)
360 (* pretty-prints a single inductive definition                              *)
361 (* (typename, inductive, arity, cons)                                       *)
362 let ppinductiveType current_module_name (typename, inductive, arity, cons) =
363  match analyze_type [] arity with
364     `Sort Cic.Prop -> ""
365   | `Statement
366   | `Type -> assert false
367   | `Sort _ ->
368     let abstr,scons =
369      List.fold_right
370       (fun (id,ty) (abstr,i) ->
371          let abstr',sargs = ppty current_module_name [] ty in
372          let sargs = String.concat " * " sargs in
373           abstr'@abstr,
374           String.capitalize id ^
375            (if sargs = "" then "" else " of " ^ sargs) ^
376            (if i = "" then "\n" else "\n | ") ^ i)
377       cons ([],"")
378      in
379       let abstr =
380        let s = String.concat "," abstr in
381        if s = "" then "" else "(" ^ s ^ ") "
382       in
383       "type " ^ abstr ^ String.uncapitalize typename ^ " =\n" ^ scons ^ "\n"
384 ;;
385
386 let ppobj current_module_name obj =
387  let module C = Cic in
388  let module U = UriManager in
389   let pp = pp current_module_name in
390   match obj with
391     C.Constant (name, Some t1, t2, params, _) ->
392       (match analyze_type [] t2 with
393           `Sort Cic.Prop
394         | `Statement -> ""
395         | `Type -> "let " ^ ppid name ^ " =\n" ^ pp t1 [] ^ "\n"
396         | `Sort _ ->
397             match analyze_type [] t1 with
398                `Sort Cic.Prop -> ""
399              | _ ->
400                let abstr,args = ppty current_module_name [] t1 in
401                let abstr =
402                 let s = String.concat "," abstr in
403                 if s = "" then "" else "(" ^ s ^ ") "
404                in
405                 "type " ^ abstr ^ ppid name ^ " = " ^ String.concat "->" args ^
406                 "\n")
407    | C.Constant (name, None, ty, params, _) ->
408       (match analyze_type [] ty with
409           `Sort Cic.Prop
410         | `Statement -> ""
411         | `Sort _ -> "type " ^ ppid name ^ "\n"
412         | `Type -> "let " ^ ppid name ^ " = assert false\n")
413    | C.Variable (name, bo, ty, params, _) ->
414       "Variable " ^ name ^
415        "(" ^ String.concat ";" (List.map UriManager.string_of_uri params) ^
416        ")" ^ ":\n" ^
417        pp ty [] ^ "\n" ^
418        (match bo with None -> "" | Some bo -> ":= " ^ pp bo [])
419    | C.CurrentProof (name, conjectures, value, ty, params, _) ->
420       "Current Proof of " ^ name ^
421        "(" ^ String.concat ";" (List.map UriManager.string_of_uri params) ^
422        ")" ^ ":\n" ^
423       let separate s = if s = "" then "" else s ^ " ; " in
424        List.fold_right
425         (fun (n, context, t) i -> 
426           let conjectures',name_context =
427                  List.fold_right 
428                   (fun context_entry (i,name_context) ->
429                     (match context_entry with
430                         Some (n,C.Decl at) ->
431                          (separate i) ^
432                            ppname n ^ ":" ^
433                             pp ~metasenv:conjectures at name_context ^ " ",
434                             context_entry::name_context
435                       | Some (n,C.Def (at,None)) ->
436                          (separate i) ^
437                            ppname n ^ ":= " ^ pp ~metasenv:conjectures
438                             at name_context ^ " ",
439                             context_entry::name_context
440                       | None ->
441                          (separate i) ^ "_ :? _ ", context_entry::name_context
442                       | _ -> assert false)
443             ) context ("",[])
444           in
445            conjectures' ^ " |- " ^ "?" ^ (string_of_int n) ^ ": " ^
446             pp ~metasenv:conjectures t name_context ^ "\n" ^ i
447         ) conjectures "" ^
448         "\n" ^ pp ~metasenv:conjectures value [] ^ " : " ^
449           pp ~metasenv:conjectures ty [] 
450    | C.InductiveDefinition (l, params, nparams, _) ->
451       List.fold_right
452        (fun x i -> ppinductiveType current_module_name x ^ i) l ""
453 ;;
454
455 let ppobj current_module_name obj =
456  let res = ppobj current_module_name obj in
457   if res = "" then "" else res ^ ";;\n"
458 ;;