]> matita.cs.unibo.it Git - helm.git/blob - components/cic_exportation/cicExportation.ml
New OCaml keyword "val".
[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 -> "(\\forall " ^ n ^ ":" ^ pp s context ^ "." ^ pp t ((Some (b,Cic.Decl s))::context) ^ ")"
168         | C.Anonymous -> "(" ^ pp s context ^ "\\to " ^ pp t ((Some (b,Cic.Decl s))::context) ^ ")"
169        )
170     | C.Cast (v,t) -> pp v context
171     | C.Lambda (b,s,t) ->
172        (match analyze_type context s with
173            `Sort _
174          | `Statement -> pp t ((Some (b,Cic.Decl s))::context)
175          | `Type -> "(function " ^ ppname b ^ " -> " ^ pp t ((Some (b,Cic.Decl s))::context) ^ ")")
176     | C.LetIn (b,s,t) ->
177        let ty,_ = CicTypeChecker.type_of_aux' [] context t CicUniv.oblivion_ugraph in
178        "(let " ^ ppname b ^ " = " ^ pp s context ^ " in " ^ pp t ((Some (b,Cic.Def (s,Some ty)))::context) ^ ")"
179     | C.Appl (C.MutConstruct _ as he::tl) ->
180        let hes = pp he context in
181        let stl = String.concat "," (clean_args context tl) in
182         "(" ^ hes ^ (if stl = "" then "" else "(" ^ stl ^ ")") ^ ")"
183     | C.Appl li ->
184        "(" ^ String.concat " " (clean_args context li) ^ ")"
185     | C.Const (uri,exp_named_subst) ->
186        qualified_name_of_uri current_module_name uri ^
187         pp_exp_named_subst exp_named_subst context
188     | C.MutInd (uri,n,exp_named_subst) ->
189        (try
190          match fst(CicEnvironment.get_obj CicUniv.empty_ugraph uri) with
191             C.InductiveDefinition (dl,_,_,_) ->
192              let (name,_,_,_) = get_nth dl (n+1) in
193               qualified_name_of_uri current_module_name
194                (UriManager.uri_of_string
195                  (UriManager.buri_of_uri uri ^ "/" ^ name ^ ".con")) ^
196               pp_exp_named_subst exp_named_subst context
197           | _ -> raise CicExportationInternalError
198         with
199            Sys.Break as exn -> raise exn
200          | _ -> UriManager.string_of_uri uri ^ "#1/" ^ string_of_int (n + 1)
201        )
202     | C.MutConstruct (uri,n1,n2,exp_named_subst) ->
203        (try
204          match fst(CicEnvironment.get_obj CicUniv.empty_ugraph uri) with
205             C.InductiveDefinition (dl,_,_,_) ->
206              let _,_,_,cons = get_nth dl (n1+1) in
207               let id,_ = get_nth cons n2 in
208                qualified_name_of_uri current_module_name ~capitalize:true
209                 (UriManager.uri_of_string
210                   (UriManager.buri_of_uri uri ^ "/" ^ id ^ ".con")) ^
211                pp_exp_named_subst exp_named_subst context
212           | _ -> raise CicExportationInternalError
213         with
214            Sys.Break as exn -> raise exn
215          | _ ->
216           UriManager.string_of_uri uri ^ "#1/" ^ string_of_int (n1 + 1) ^ "/" ^
217            string_of_int n2
218        )
219     | C.MutCase (uri,n1,ty,te,patterns) ->
220        (match analyze_term context te with
221            `Type -> assert false
222          | `Proof ->
223              (match patterns with
224                  [] -> "assert false"   (* empty type elimination *)
225                | [he] -> pp he context  (* singleton elimination *)
226                | _ -> assert false)
227          | `Term ->
228             if patterns = [] then "assert false"
229             else
230              (let connames_and_argsno =
231                (match fst(CicEnvironment.get_obj CicUniv.empty_ugraph uri) with
232                    C.InductiveDefinition (dl,_,paramsno,_) ->
233                     let (_,_,_,cons) = get_nth dl (n1+1) in
234                      List.map
235                       (fun (id,ty) ->
236                         (* this is just an approximation since we do not have
237                            reduction yet! *)
238                         let rec count_prods toskip =
239                          function
240                             C.Prod (_,_,bo) when toskip > 0 ->
241                              count_prods (toskip - 1) bo
242                           | C.Prod (_,_,bo) -> 1 + count_prods 0 bo
243                           | _ -> 0
244                         in
245                          qualified_name_of_uri current_module_name
246                           ~capitalize:true
247                           (UriManager.uri_of_string
248                             (UriManager.buri_of_uri uri ^ "/" ^ id ^ ".con")),
249                          count_prods paramsno ty
250                       ) cons
251                  | _ -> raise CicExportationInternalError
252                )
253               in
254                let connames_and_argsno_and_patterns =
255                 let rec combine =
256                    function
257                       [],[] -> []
258                     | [],l -> List.map (fun x -> "???",0,Some x) l
259                     | l,[] -> List.map (fun (x,no) -> x,no,None) l
260                     | (x,no)::tlx,y::tly -> (x,no,Some y)::(combine (tlx,tly))
261                 in
262                  combine (connames_and_argsno,patterns)
263                in
264                 "\n(match " ^ pp te context ^ " with \n" ^
265                  (String.concat "\n | "
266                   (List.map
267                    (fun (x,argsno,y) ->
268                      let rec aux argsno context =
269                       function
270                          Cic.Lambda (name,ty,bo) when argsno > 0 ->
271                           let args,res =
272                            aux (argsno - 1) (Some (name,Cic.Decl ty)::context)
273                             bo
274                           in
275                            (match name with C.Anonymous -> "_" | C.Name s -> s)
276                            ::args,
277                            res
278                        | t when argsno = 0 -> [],pp t context
279                        | t ->
280                           ["{" ^ string_of_int argsno ^ " args missing}"],
281                            pp t context
282                      in
283                       let pattern,body =
284                        match y with
285                           None -> x,""
286                         | Some y when argsno = 0 -> x,pp y context
287                         | Some y ->
288                            let args,body = aux argsno context y in
289                            let sargs = String.concat "," args in
290                             x ^ (if sargs = "" then "" else "(" ^ sargs^ ")"),
291                              body
292                       in
293                        pattern ^ " -> " ^ body
294                    ) connames_and_argsno_and_patterns)) ^
295                  ")\n"))
296     | C.Fix (no, funs) ->
297        let names =
298         List.rev
299          (List.map
300            (function (name,_,ty,_) ->
301              Some (C.Name name,Cic.Decl ty)) funs)
302        in
303          "\nlet rec " ^
304          List.fold_right
305           (fun (name,ind,ty,bo) i -> name ^ " = \n" ^
306             pp bo (names@context) ^ i)
307           funs "" ^
308          " in " ^
309          (match get_nth names (no + 1) with
310              Some (Cic.Name n,_) -> n
311            | _ -> assert false) ^ "\n"
312     | C.CoFix (no,funs) ->
313        let names =
314         List.rev
315          (List.map
316            (function (name,ty,_) ->
317              Some (C.Name name,Cic.Decl ty)) funs)
318        in
319          "\nCoFix " ^ " {" ^
320          List.fold_right
321           (fun (name,ty,bo) i -> "\n" ^ name ^ 
322             " : " ^ pp ty context ^ " := \n" ^
323             pp bo (names@context) ^ i)
324           funs "" ^
325          "}\n"
326 and pp_exp_named_subst exp_named_subst context =
327  if exp_named_subst = [] then "" else
328   "\\subst[" ^
329    String.concat " ; " (
330     List.map
331      (function (uri,t) -> UriManager.name_of_uri uri ^ " \\Assign " ^ pp t context)
332      exp_named_subst
333    ) ^ "]"
334 and clean_args context =
335  HExtlib.filter_map
336   (function t ->
337     match analyze_term context t with
338        `Type -> None
339      | `Proof -> None
340      | `Term -> Some pp t context)
341 in
342  pp
343 ;;
344
345 let ppty current_module_name =
346  let rec args context =
347   function
348      Cic.Prod (n,s,t) ->
349       let n =
350        match n with
351           Cic.Anonymous -> Cic.Anonymous
352         | Cic.Name n -> Cic.Name (String.uncapitalize n)
353       in
354        (match analyze_type context s with
355            `Sort Cic.Prop -> args ((Some (n,Cic.Decl s))::context) t
356          | `Statement
357          | `Sort _ ->
358              let n =
359               match n with
360                  Cic.Anonymous -> Cic.Anonymous
361                | Cic.Name name -> Cic.Name ("'" ^ name) in
362              let abstr,args = args ((Some (n,Cic.Decl s))::context) t in
363               (match n with
364                   Cic.Anonymous -> abstr
365                 | Cic.Name name -> name::abstr),
366               args
367          | `Type ->
368              let abstr,args = args ((Some (n,Cic.Decl s))::context) t in
369               abstr,pp current_module_name s context::args)
370    | _ -> [],[]
371  in
372   args
373 ;;
374
375 (* ppinductiveType (typename, inductive, arity, cons)                       *)
376 (* pretty-prints a single inductive definition                              *)
377 (* (typename, inductive, arity, cons)                                       *)
378 let ppinductiveType current_module_name nparams (typename, inductive, arity, cons)
379 =
380  match analyze_type [] arity with
381     `Sort Cic.Prop -> ""
382   | `Statement
383   | `Type -> assert false
384   | `Sort _ ->
385     if cons = [] then
386      "type " ^ String.uncapitalize typename ^ " = unit (* empty type *)\n"
387     else (
388      let abstr,scons =
389       List.fold_right
390        (fun (id,ty) (_abstr,i) -> (* we should verify _abstr = abstr' *)
391           let abstr',sargs = ppty current_module_name [] ty in
392           let sargs = String.concat " * " sargs in
393            abstr',
394            String.capitalize id ^
395             (if sargs = "" then "" else " of " ^ sargs) ^
396             (if i = "" then "" else "\n | ") ^ i)
397        cons ([],"")
398       in
399        let abstr =
400         let s = String.concat "," abstr in
401         if s = "" then "" else "(" ^ s ^ ") "
402        in
403        "type " ^ abstr ^ String.uncapitalize typename ^ " =\n" ^ scons ^ "\n")
404 ;;
405
406 let ppobj current_module_name obj =
407  let module C = Cic in
408  let module U = UriManager in
409   let pp = pp current_module_name in
410   match obj with
411     C.Constant (name, Some t1, t2, params, _) ->
412       (match analyze_type [] t2 with
413           `Sort Cic.Prop
414         | `Statement -> ""
415         | `Type -> "let " ^ ppid name ^ " =\n" ^ pp t1 [] ^ "\n"
416         | `Sort _ ->
417             match analyze_type [] t1 with
418                `Sort Cic.Prop -> ""
419              | _ ->
420                let abstr,args = ppty current_module_name [] t1 in
421                let abstr =
422                 let s = String.concat "," abstr in
423                 if s = "" then "" else "(" ^ s ^ ") "
424                in
425                 "type " ^ abstr ^ ppid name ^ " = " ^ String.concat "->" args ^
426                 "\n")
427    | C.Constant (name, None, ty, params, _) ->
428       (match analyze_type [] ty with
429           `Sort Cic.Prop
430         | `Statement -> ""
431         | `Sort _ -> "type " ^ ppid name ^ "\n"
432         | `Type -> "let " ^ ppid name ^ " = assert false\n")
433    | C.Variable (name, bo, ty, params, _) ->
434       "Variable " ^ name ^
435        "(" ^ String.concat ";" (List.map UriManager.string_of_uri params) ^
436        ")" ^ ":\n" ^
437        pp ty [] ^ "\n" ^
438        (match bo with None -> "" | Some bo -> ":= " ^ pp bo [])
439    | C.CurrentProof (name, conjectures, value, ty, params, _) ->
440       "Current Proof of " ^ name ^
441        "(" ^ String.concat ";" (List.map UriManager.string_of_uri params) ^
442        ")" ^ ":\n" ^
443       let separate s = if s = "" then "" else s ^ " ; " in
444        List.fold_right
445         (fun (n, context, t) i -> 
446           let conjectures',name_context =
447                  List.fold_right 
448                   (fun context_entry (i,name_context) ->
449                     (match context_entry with
450                         Some (n,C.Decl at) ->
451                          (separate i) ^
452                            ppname n ^ ":" ^
453                             pp ~metasenv:conjectures at name_context ^ " ",
454                             context_entry::name_context
455                       | Some (n,C.Def (at,None)) ->
456                          (separate i) ^
457                            ppname n ^ ":= " ^ pp ~metasenv:conjectures
458                             at name_context ^ " ",
459                             context_entry::name_context
460                       | None ->
461                          (separate i) ^ "_ :? _ ", context_entry::name_context
462                       | _ -> assert false)
463             ) context ("",[])
464           in
465            conjectures' ^ " |- " ^ "?" ^ (string_of_int n) ^ ": " ^
466             pp ~metasenv:conjectures t name_context ^ "\n" ^ i
467         ) conjectures "" ^
468         "\n" ^ pp ~metasenv:conjectures value [] ^ " : " ^
469           pp ~metasenv:conjectures ty [] 
470    | C.InductiveDefinition (l, params, nparams, _) ->
471       List.fold_right
472        (fun x i -> ppinductiveType current_module_name nparams x ^ i) l ""
473 ;;
474
475 let ppobj current_module_name obj =
476  let res = ppobj current_module_name obj in
477   if res = "" then "" else res ^ ";;\n\n"
478 ;;