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