]> matita.cs.unibo.it Git - helm.git/blob - helm/software/components/cic_proof_checking/cicPp.ml
Bug fixed in pretty printing in new syntax of MutCases on inductive types
[helm.git] / helm / software / components / cic_proof_checking / cicPp.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 (*****************************************************************************)
27 (*                                                                           *)
28 (*                               PROJECT HELM                                *)
29 (*                                                                           *)
30 (* This module implements a very simple Coq-like pretty printer that, given  *)
31 (* an object of cic (internal representation) returns a string describing    *)
32 (* the object in a syntax similar to that of coq                             *)
33 (*                                                                           *)
34 (* It also contains the utility functions to check a name w.r.t the Matita   *)
35 (* naming policy                                                             *)
36 (*                                                                           *)
37 (*****************************************************************************)
38
39 (* $Id$ *)
40
41 exception CicPpInternalError;;
42 exception NotEnoughElements;;
43
44 (* Utility functions *)
45
46 let ppname =
47  function
48     Cic.Name s     -> s
49   | Cic.Anonymous  -> "_"
50 ;;
51
52 (* get_nth l n   returns the nth element of the list l if it exists or *)
53 (* raises NotEnoughElements if l has less than n elements             *)
54 let rec get_nth l n =
55  match (n,l) with
56     (1, he::_) -> he
57   | (n, he::tail) when n > 1 -> get_nth tail (n-1)
58   | (_,_) -> raise NotEnoughElements
59 ;;
60
61 (* pp t l                                                                  *)
62 (* pretty-prints a term t of cic in an environment l where l is a list of  *)
63 (* identifier names used to resolve DeBrujin indexes. The head of l is the *)
64 (* name associated to the greatest DeBrujin index in t                     *)
65 let rec pp t l =
66  let module C = Cic in
67    match t with
68       C.Rel n ->
69        begin
70         try
71          (match get_nth l n with
72              Some (C.Name s) -> s
73            | Some C.Anonymous -> "__" ^ string_of_int n
74            | None -> "_hidden_" ^ string_of_int n
75          )
76         with
77          NotEnoughElements -> string_of_int (List.length l - n)
78        end
79     | C.Var (uri,exp_named_subst) ->
80        UriManager.string_of_uri (*UriManager.name_of_uri*) uri ^ pp_exp_named_subst exp_named_subst l
81     | C.Meta (n,l1) ->
82        "?" ^ (string_of_int n) ^ "[" ^ 
83         String.concat " ; "
84          (List.rev_map (function None -> "_" | Some t -> pp t l) l1) ^
85         "]"
86     | C.Sort s ->
87        (match s with
88            C.Prop  -> "Prop"
89          | C.Set   -> "Set"
90          | C.Type _ -> "Type"
91          (*| C.Type u -> ("Type" ^ CicUniv.string_of_universe u)*)
92          | C.CProp -> "CProp" 
93        )
94     | C.Implicit (Some `Hole) -> "%"
95     | C.Implicit _ -> "?"
96     | C.Prod (b,s,t) ->
97        (match b with
98           C.Name n -> "(\\forall " ^ n ^ ":" ^ pp s l ^ "." ^ pp t ((Some b)::l) ^ ")"
99         | C.Anonymous -> "(" ^ pp s l ^ "\\to " ^ pp t ((Some b)::l) ^ ")"
100        )
101     | C.Cast (v,t) -> "(" ^ pp v l ^ ":" ^ pp t l ^ ")"
102     | C.Lambda (b,s,t) ->
103        "(\\lambda " ^ ppname b ^ ":" ^ pp s l ^ "." ^ pp t ((Some b)::l) ^ ")"
104     | C.LetIn (b,s,t) ->
105        " let " ^ ppname b ^ " \\def " ^ pp s l ^ " in " ^ pp t ((Some b)::l)
106     | C.Appl li ->
107        "(" ^
108        (List.fold_right
109         (fun x i -> pp x l ^ (match i with "" -> "" | _ -> " ") ^ i)
110         li ""
111        ) ^ ")"
112     | C.Const (uri,exp_named_subst) ->
113        UriManager.name_of_uri uri ^ pp_exp_named_subst exp_named_subst l
114     | C.MutInd (uri,n,exp_named_subst) ->
115        (try
116          match fst(CicEnvironment.get_obj CicUniv.empty_ugraph uri) with
117             C.InductiveDefinition (dl,_,_,_) ->
118              let (name,_,_,_) = get_nth dl (n+1) in
119               name ^ pp_exp_named_subst exp_named_subst l
120           | _ -> raise CicPpInternalError
121         with
122            Sys.Break as exn -> raise exn
123          | _ -> UriManager.string_of_uri uri ^ "#1/" ^ string_of_int (n + 1)
124        )
125     | C.MutConstruct (uri,n1,n2,exp_named_subst) ->
126        (try
127          match fst(CicEnvironment.get_obj CicUniv.empty_ugraph uri) with
128             C.InductiveDefinition (dl,_,_,_) ->
129              let (_,_,_,cons) = get_nth dl (n1+1) in
130               let (id,_) = get_nth cons n2 in
131                id ^ pp_exp_named_subst exp_named_subst l
132           | _ -> raise CicPpInternalError
133         with
134            Sys.Break as exn -> raise exn
135          | _ ->
136           UriManager.string_of_uri uri ^ "#1/" ^ string_of_int (n1 + 1) ^ "/" ^
137            string_of_int n2
138        )
139     | C.MutCase (uri,n1,ty,te,patterns) ->
140        let connames_and_argsno =
141         (match fst(CicEnvironment.get_obj CicUniv.empty_ugraph uri) with
142             C.InductiveDefinition (dl,_,paramsno,_) ->
143              let (_,_,_,cons) = get_nth dl (n1+1) in
144               List.map
145                (fun id,ty ->
146                  (* this is just an approximation since we do not have
147                     reduction yet! *)
148                  let rec count_prods toskip =
149                   function
150                      C.Prod (_,_,bo) when toskip > 0 ->
151                       count_prods (toskip - 1) bo
152                    | C.Prod (_,_,bo) -> 1 + count_prods 0 bo
153                    | _ -> 0
154                  in
155                   id, count_prods paramsno ty
156                ) cons
157           | _ -> raise CicPpInternalError
158         )
159        in
160         let connames_and_argsno_and_patterns =
161          let rec combine =
162             function
163                [],[] -> []
164              | [],l -> List.map (fun x -> "???",0,Some x) l
165              | l,[] -> List.map (fun (x,no) -> x,no,None) l
166              | (x,no)::tlx,y::tly -> (x,no,Some y)::(combine (tlx,tly))
167          in
168           combine (connames_and_argsno,patterns)
169         in
170          "\nmatch " ^ pp te l ^ " return " ^ pp ty l ^ " with \n [ " ^
171           (String.concat "\n | "
172            (List.map
173             (fun (x,argsno,y) ->
174               let rec aux argsno l =
175                function
176                   Cic.Lambda (name,ty,bo) when argsno > 0 ->
177                    let args,res = aux (argsno - 1) (Some name::l) bo in
178                     ("(" ^ (match name with C.Anonymous -> "_" | C.Name s -> s)^
179                      ":" ^ pp ty l ^ ")")::args, res
180                 | t when argsno = 0 -> [],pp t l
181                 | t -> ["{" ^ string_of_int argsno ^ " args missing}"],pp t l
182               in
183                let pattern,body =
184                 match y with
185                    None -> x,""
186                  | Some y when argsno = 0 -> x,pp y l
187                  | Some y ->
188                     let args,body = aux argsno l y in
189                      "(" ^ x ^ " " ^ String.concat " " args ^ ")",body
190                in
191                 pattern ^ " => " ^ body
192             ) connames_and_argsno_and_patterns)) ^
193           "\n]"
194     | C.Fix (no, funs) ->
195        let snames = List.map (fun (name,_,_,_) -> name) funs in
196         let names =
197          List.rev (List.map (function name -> Some (C.Name name)) snames)
198         in
199          "\nFix " ^ get_nth snames (no + 1) ^ " {" ^
200          List.fold_right
201           (fun (name,ind,ty,bo) i -> "\n" ^ name ^ " / " ^ string_of_int ind ^
202             " : " ^ pp ty l ^ " := \n" ^
203             pp bo (names@l) ^ i)
204           funs "" ^
205          "}\n"
206     | C.CoFix (no,funs) ->
207        let snames = List.map (fun (name,_,_) -> name) funs in
208         let names =
209          List.rev (List.map (function name -> Some (C.Name name)) snames)
210         in
211          "\nCoFix " ^ get_nth snames (no + 1) ^ " {" ^
212          List.fold_right
213           (fun (name,ty,bo) i -> "\n" ^ name ^ 
214             " : " ^ pp ty l ^ " := \n" ^
215             pp bo (names@l) ^ i)
216           funs "" ^
217          "}\n"
218 and pp_exp_named_subst exp_named_subst l =
219  if exp_named_subst = [] then "" else
220   "\\subst[" ^
221    String.concat " ; " (
222     List.map
223      (function (uri,t) -> UriManager.name_of_uri uri ^ " \\Assign " ^ pp t l)
224      exp_named_subst
225    ) ^ "]"
226 ;;
227
228 let ppterm t =
229  pp t []
230 ;;
231
232 (* ppinductiveType (typename, inductive, arity, cons)                       *)
233 (* pretty-prints a single inductive definition                              *)
234 (* (typename, inductive, arity, cons)                                       *)
235 let ppinductiveType (typename, inductive, arity, cons) =
236   (if inductive then "\nInductive " else "\nCoInductive ") ^ typename ^ ": " ^
237   pp arity [] ^ " =\n   " ^
238   List.fold_right
239    (fun (id,ty) i -> id ^ " : " ^ pp ty [] ^ 
240     (if i = "" then "\n" else "\n | ") ^ i)
241    cons ""
242 ;;
243
244 let ppcontext ?(sep = "\n") context =
245  let separate s = if s = "" then "" else s ^ sep in
246  fst (List.fold_right 
247    (fun context_entry (i,name_context) ->
248      match context_entry with
249         Some (n,Cic.Decl t) ->
250          Printf.sprintf "%s%s : %s" (separate i) (ppname n)
251           (pp t name_context), (Some n)::name_context
252       | Some (n,Cic.Def (bo,ty)) ->
253          Printf.sprintf "%s%s : %s := %s" (separate i) (ppname n)
254           (match ty with
255               None -> "_"
256             | Some ty -> pp ty name_context)
257           (pp bo name_context), (Some n)::name_context
258        | None ->
259           Printf.sprintf "%s_ :? _" (separate i), None::name_context
260     ) context ("",[]))
261
262 (* ppobj obj  returns a string with describing the cic object obj in a syntax *)
263 (* similar to the one used by Coq                                             *)
264 let ppobj obj =
265  let module C = Cic in
266  let module U = UriManager in
267   match obj with
268     C.Constant (name, Some t1, t2, params, _) ->
269       "Definition of " ^ name ^
270        "(" ^ String.concat ";" (List.map UriManager.string_of_uri params) ^
271        ")" ^ ":\n" ^ pp t1 [] ^ " : " ^ pp t2 []
272    | C.Constant (name, None, ty, params, _) ->
273       "Axiom " ^ name ^
274        "(" ^ String.concat ";" (List.map UriManager.string_of_uri params) ^
275        "):\n" ^ pp ty []
276    | C.Variable (name, bo, ty, params, _) ->
277       "Variable " ^ name ^
278        "(" ^ String.concat ";" (List.map UriManager.string_of_uri params) ^
279        ")" ^ ":\n" ^
280        pp ty [] ^ "\n" ^
281        (match bo with None -> "" | Some bo -> ":= " ^ pp bo [])
282    | C.CurrentProof (name, conjectures, value, ty, params, _) ->
283       "Current Proof of " ^ name ^
284        "(" ^ String.concat ";" (List.map UriManager.string_of_uri params) ^
285        ")" ^ ":\n" ^
286       let separate s = if s = "" then "" else s ^ " ; " in
287        List.fold_right
288         (fun (n, context, t) i -> 
289           let conjectures',name_context =
290                  List.fold_right 
291                   (fun context_entry (i,name_context) ->
292                     (match context_entry with
293                         Some (n,C.Decl at) ->
294                    (separate i) ^
295                      ppname n ^ ":" ^ pp at name_context ^ " ",
296                       (Some n)::name_context
297                       | Some (n,C.Def (at,None)) ->
298                    (separate i) ^
299                      ppname n ^ ":= " ^ pp at name_context ^ " ",
300                       (Some n)::name_context
301                 | None ->
302                    (separate i) ^ "_ :? _ ", None::name_context
303                 | _ -> assert false)
304             ) context ("",[])
305           in
306            conjectures' ^ " |- " ^ "?" ^ (string_of_int n) ^ ": " ^
307             pp t name_context ^ "\n" ^ i
308         ) conjectures "" ^
309         "\n" ^ pp value [] ^ " : " ^ pp ty [] 
310    | C.InductiveDefinition (l, params, nparams, _) ->
311       "Parameters = " ^
312        String.concat ";" (List.map UriManager.string_of_uri params) ^ "\n" ^
313        "NParams = " ^ string_of_int nparams ^ "\n" ^
314         List.fold_right (fun x i -> ppinductiveType x ^ i) l ""
315 ;;
316
317 let ppsort = function
318   | Cic.Prop -> "Prop"
319   | Cic.Set -> "Set"
320   | Cic.Type _ -> "Type"
321   | Cic.CProp -> "CProp"
322
323
324 (* MATITA NAMING CONVENTION *)
325
326 let is_prefix prefix string =
327   let len = String.length prefix in
328   let len1 = String.length string in
329   if len <= len1 then
330     begin
331       let head = String.sub string 0 len in
332       if 
333       (String.compare (String.lowercase head) (String.lowercase prefix)=0) then 
334         begin
335           let diff = len1-len in
336           let tail = String.sub string len diff in
337           if ((diff > 0) && (String.rcontains_from tail 0 '_')) then
338             Some (String.sub tail 1 (diff-1))
339             else Some tail
340           end
341         else None
342     end
343   else None
344
345 let remove_prefix prefix (last,string) =
346   if string = "" then (last,string)
347   else 
348     match is_prefix prefix string with
349       None ->
350         if last <> "" then 
351           match is_prefix last prefix with
352             None -> (last,string)
353           | Some _ ->
354               (match is_prefix prefix (last^string) with
355                 None -> (last,string)
356               | Some tail -> (prefix,tail))
357         else (last,string)
358     | Some tail -> (prefix, tail)
359         
360 let legal_suffix string = 
361   if string = "" then true else
362   begin
363     let legal_s = Str.regexp "_?\\([0-9]+\\|r\\|l\\|'\\|\"\\)" in
364     (Str.string_match legal_s string 0) && (Str.matched_string string = string)
365   end
366
367 (** check if a prefix of string_name is legal for term and returns the tail.
368     chec_rec cannot fail: at worst it return string_name.
369     The algorithm is greedy, but last contains the last name matched, providing
370     a one slot buffer. 
371     string_name is here a pair (last,string_name).*)
372
373 let rec check_rec ctx string_name =
374   function
375     | Cic.Rel m -> 
376         (match List.nth ctx (m-1) with
377           Cic.Name name ->
378             remove_prefix name string_name
379         | Cic.Anonymous -> string_name)
380     | Cic.Meta _ -> string_name
381     | Cic.Sort sort -> remove_prefix (ppsort sort) string_name  
382     | Cic.Implicit _ -> string_name
383     | Cic.Cast (te,ty) -> check_rec ctx string_name te
384     | Cic.Prod (name,so,dest) -> 
385         let l_string_name = check_rec ctx string_name so in
386         check_rec (name::ctx) string_name dest
387     | Cic.Lambda (name,so,dest) -> 
388         let string_name =
389           match name with
390             Cic.Anonymous -> string_name
391           | Cic.Name name -> remove_prefix name string_name in
392         let l_string_name = check_rec ctx string_name so in
393         check_rec (name::ctx) l_string_name dest
394     | Cic.LetIn (name,so,dest) -> 
395         let string_name = check_rec ctx string_name so in
396         check_rec (name::ctx) string_name dest
397     | Cic.Appl l ->
398         List.fold_left (check_rec ctx) string_name l
399     | Cic.Var (uri,exp_named_subst) ->
400         let name = UriManager.name_of_uri uri in
401         remove_prefix name string_name
402     | Cic.Const (uri,exp_named_subst) ->
403         let name = UriManager.name_of_uri uri in
404         remove_prefix name string_name
405     | Cic.MutInd (uri,_,exp_named_subst) -> 
406         let name = UriManager.name_of_uri uri in
407         remove_prefix name string_name  
408     | Cic.MutConstruct (uri,n,m,exp_named_subst) ->
409         let name =
410           (match fst(CicEnvironment.get_obj CicUniv.empty_ugraph uri) with
411             Cic.InductiveDefinition (dl,_,_,_) ->
412               let (_,_,_,cons) = get_nth dl (n+1) in
413               let (id,_) = get_nth cons m in
414               id 
415           | _ -> assert false) in
416         remove_prefix name string_name  
417     | Cic.MutCase (_,_,_,te,pl) ->
418         let string_name = remove_prefix "match" string_name in
419         let string_name = check_rec ctx string_name te in
420         List.fold_right (fun t s -> check_rec ctx s t) pl string_name
421     | Cic.Fix (_,fl) ->
422         let string_name = remove_prefix "fix" string_name in
423         let names = List.map (fun (name,_,_,_) -> name) fl in
424         let onames =
425           List.rev (List.map (function name -> Cic.Name name) names)
426         in
427         List.fold_right 
428           (fun (_,_,_,bo) s -> check_rec (onames@ctx) s bo) fl string_name
429     | Cic.CoFix (_,fl) ->
430         let string_name = remove_prefix "cofix" string_name in
431         let names = List.map (fun (name,_,_) -> name) fl in
432         let onames =
433           List.rev (List.map (function name -> Cic.Name name) names)
434         in
435         List.fold_right 
436           (fun (_,_,bo) s -> check_rec (onames@ctx) s bo) fl string_name
437
438 let check_name ?(allow_suffix=false) ctx name term =
439   let (_,tail) = check_rec ctx ("",name) term in
440   if (not allow_suffix) then (String.length tail = 0) 
441   else legal_suffix tail
442
443 let check_elim ctx conclusion_name =
444   let elim = Str.regexp "_elim\\|_case" in
445   if (Str.string_match elim conclusion_name 0) then
446     let len = String.length conclusion_name in
447     let tail = String.sub conclusion_name 5 (len-5) in
448     legal_suffix tail
449   else false
450
451 let rec check_names ctx hyp_names conclusion_name t =
452   match t with
453     | Cic.Prod (name,s,t) -> 
454         (match hyp_names with
455              [] -> check_names (name::ctx) hyp_names conclusion_name t
456            | hd::tl ->
457                if check_name ctx hd s then 
458                  check_names (name::ctx) tl conclusion_name t
459                else 
460                  check_names (name::ctx) hyp_names conclusion_name t)
461     | Cic.Appl ((Cic.Rel n)::args) -> 
462         (match hyp_names with
463           | [] ->
464               (check_name ~allow_suffix:true ctx conclusion_name t) ||
465               (check_elim ctx conclusion_name)
466           | [what_to_elim] ->   
467               (* what to elim could be an argument 
468                  of the predicate: e.g. leb_elim *)
469               let (last,tail) = 
470                 List.fold_left (check_rec ctx) ("",what_to_elim) args in
471               (tail = "" && check_elim ctx conclusion_name)
472           | _ -> false)
473     | Cic.MutCase  (_,_,Cic.Lambda(name,so,ty),te,_) ->
474         (match hyp_names with
475           | [] ->
476                (match is_prefix "match" conclusion_name with
477                    None -> check_name ~allow_suffix:true ctx conclusion_name t
478                | Some tail -> check_name ~allow_suffix:true ctx tail t)
479           | [what_to_match] ->   
480               (* what to match could be the term te or its type so; in this case the
481                  conclusion name should match ty *)
482               check_name ~allow_suffix:true (name::ctx) conclusion_name ty &&
483               (check_name ctx what_to_match te || check_name ctx what_to_match so)
484           | _ -> false)
485     | _ -> 
486         hyp_names=[] && check_name ~allow_suffix:true ctx conclusion_name t
487
488 let check name term =
489   let names = Str.split (Str.regexp_string "_to_") name in
490   let hyp_names,conclusion_name =
491     match List.rev names with
492         [] -> assert false
493       | hd::tl -> 
494           let elim = Str.regexp "_elim\\|_case" in
495           let len = String.length hd in
496           try 
497             let pos = Str.search_backward elim hd len in
498             let hyp = String.sub hd 0 pos in
499             let concl = String.sub hd pos (len-pos) in
500             List.rev (hyp::tl),concl
501           with Not_found -> (List.rev tl),hd in
502   check_names [] hyp_names conclusion_name term
503 ;;
504
505