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