]> matita.cs.unibo.it Git - helm.git/blob - helm/software/components/cic_proof_checking/cicPp.ml
1. Some warnings about unused warning fixed (hopefully well)
[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,_,_,_) ->
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 =
149                   function
150                      C.Prod (_,_,bo) -> 1 + count_prods bo
151                    | _ -> 0
152                  in
153                   id, count_prods ty
154                ) cons
155           | _ -> raise CicPpInternalError
156         )
157        in
158         let connames_and_argsno_and_patterns =
159          let rec combine =
160             function
161                [],[] -> []
162              | [],l -> List.map (fun x -> "???",0,Some x) l
163              | l,[] -> List.map (fun (x,no) -> x,no,None) l
164              | (x,no)::tlx,y::tly -> (x,no,Some y)::(combine (tlx,tly))
165          in
166           combine (connames_and_argsno,patterns)
167         in
168          "\nmatch " ^ pp te l ^ " return " ^ pp ty l ^ " with \n [ " ^
169           (String.concat "\n | "
170            (List.map
171             (fun (x,argsno,y) ->
172               let rec aux argsno l =
173                function
174                   Cic.Lambda (name,ty,bo) when argsno > 0 ->
175                    let args,res = aux (argsno - 1) (Some name::l) bo in
176                     ("(" ^ (match name with C.Anonymous -> "_" | C.Name s -> s)^
177                      ":" ^ pp ty l ^ ")")::args, res
178                 | t when argsno = 0 -> [],pp t l
179                 | t -> ["{" ^ string_of_int argsno ^ " args missing}"],pp t l
180               in
181                let pattern,body =
182                 match y with
183                    None -> x,""
184                  | Some y when argsno = 0 -> x,pp y l
185                  | Some y ->
186                     let args,body = aux argsno l y in
187                      "(" ^ x ^ " " ^ String.concat " " args ^ ")",body
188                in
189                 pattern ^ " => " ^ body
190             ) connames_and_argsno_and_patterns)) ^
191           "\n]"
192     | C.Fix (no, funs) ->
193        let snames = List.map (fun (name,_,_,_) -> name) funs in
194         let names =
195          List.rev (List.map (function name -> Some (C.Name name)) snames)
196         in
197          "\nFix " ^ get_nth snames (no + 1) ^ " {" ^
198          List.fold_right
199           (fun (name,ind,ty,bo) i -> "\n" ^ name ^ " / " ^ string_of_int ind ^
200             " : " ^ pp ty l ^ " := \n" ^
201             pp bo (names@l) ^ i)
202           funs "" ^
203          "}\n"
204     | C.CoFix (no,funs) ->
205        let snames = List.map (fun (name,_,_) -> name) funs in
206         let names =
207          List.rev (List.map (function name -> Some (C.Name name)) snames)
208         in
209          "\nCoFix " ^ get_nth snames (no + 1) ^ " {" ^
210          List.fold_right
211           (fun (name,ty,bo) i -> "\n" ^ name ^ 
212             " : " ^ pp ty l ^ " := \n" ^
213             pp bo (names@l) ^ i)
214           funs "" ^
215          "}\n"
216 and pp_exp_named_subst exp_named_subst l =
217  if exp_named_subst = [] then "" else
218   "\\subst[" ^
219    String.concat " ; " (
220     List.map
221      (function (uri,t) -> UriManager.name_of_uri uri ^ " \\Assign " ^ pp t l)
222      exp_named_subst
223    ) ^ "]"
224 ;;
225
226 let ppterm t =
227  pp t []
228 ;;
229
230 (* ppinductiveType (typename, inductive, arity, cons)                       *)
231 (* pretty-prints a single inductive definition                              *)
232 (* (typename, inductive, arity, cons)                                       *)
233 let ppinductiveType (typename, inductive, arity, cons) =
234   (if inductive then "\nInductive " else "\nCoInductive ") ^ typename ^ ": " ^
235   pp arity [] ^ " =\n   " ^
236   List.fold_right
237    (fun (id,ty) i -> id ^ " : " ^ pp ty [] ^ 
238     (if i = "" then "\n" else "\n | ") ^ i)
239    cons ""
240 ;;
241
242 let ppcontext ?(sep = "\n") context =
243  let separate s = if s = "" then "" else s ^ sep in
244  fst (List.fold_right 
245    (fun context_entry (i,name_context) ->
246      match context_entry with
247         Some (n,Cic.Decl t) ->
248          Printf.sprintf "%s%s : %s" (separate i) (ppname n)
249           (pp t name_context), (Some n)::name_context
250       | Some (n,Cic.Def (bo,ty)) ->
251          Printf.sprintf "%s%s : %s := %s" (separate i) (ppname n)
252           (match ty with
253               None -> "_"
254             | Some ty -> pp ty name_context)
255           (pp bo name_context), (Some n)::name_context
256        | None ->
257           Printf.sprintf "%s_ :? _" (separate i), None::name_context
258     ) context ("",[]))
259
260 (* ppobj obj  returns a string with describing the cic object obj in a syntax *)
261 (* similar to the one used by Coq                                             *)
262 let ppobj obj =
263  let module C = Cic in
264  let module U = UriManager in
265   match obj with
266     C.Constant (name, Some t1, t2, params, _) ->
267       "Definition of " ^ name ^
268        "(" ^ String.concat ";" (List.map UriManager.string_of_uri params) ^
269        ")" ^ ":\n" ^ pp t1 [] ^ " : " ^ pp t2 []
270    | C.Constant (name, None, ty, params, _) ->
271       "Axiom " ^ name ^
272        "(" ^ String.concat ";" (List.map UriManager.string_of_uri params) ^
273        "):\n" ^ pp ty []
274    | C.Variable (name, bo, ty, params, _) ->
275       "Variable " ^ name ^
276        "(" ^ String.concat ";" (List.map UriManager.string_of_uri params) ^
277        ")" ^ ":\n" ^
278        pp ty [] ^ "\n" ^
279        (match bo with None -> "" | Some bo -> ":= " ^ pp bo [])
280    | C.CurrentProof (name, conjectures, value, ty, params, _) ->
281       "Current Proof of " ^ name ^
282        "(" ^ String.concat ";" (List.map UriManager.string_of_uri params) ^
283        ")" ^ ":\n" ^
284       let separate s = if s = "" then "" else s ^ " ; " in
285        List.fold_right
286         (fun (n, context, t) i -> 
287           let conjectures',name_context =
288                  List.fold_right 
289                   (fun context_entry (i,name_context) ->
290                     (match context_entry with
291                         Some (n,C.Decl at) ->
292                    (separate i) ^
293                      ppname n ^ ":" ^ pp at name_context ^ " ",
294                       (Some n)::name_context
295                       | Some (n,C.Def (at,None)) ->
296                    (separate i) ^
297                      ppname n ^ ":= " ^ pp at name_context ^ " ",
298                       (Some n)::name_context
299                 | None ->
300                    (separate i) ^ "_ :? _ ", None::name_context
301                 | _ -> assert false)
302             ) context ("",[])
303           in
304            conjectures' ^ " |- " ^ "?" ^ (string_of_int n) ^ ": " ^
305             pp t name_context ^ "\n" ^ i
306         ) conjectures "" ^
307         "\n" ^ pp value [] ^ " : " ^ pp ty [] 
308    | C.InductiveDefinition (l, params, nparams, _) ->
309       "Parameters = " ^
310        String.concat ";" (List.map UriManager.string_of_uri params) ^ "\n" ^
311        "NParams = " ^ string_of_int nparams ^ "\n" ^
312         List.fold_right (fun x i -> ppinductiveType x ^ i) l ""
313 ;;
314
315 let ppsort = function
316   | Cic.Prop -> "Prop"
317   | Cic.Set -> "Set"
318   | Cic.Type _ -> "Type"
319   | Cic.CProp -> "CProp"
320
321
322 (* MATITA NAMING CONVENTION *)
323
324 let is_prefix prefix string =
325   let len = String.length prefix in
326   let len1 = String.length string in
327   if len <= len1 then
328     begin
329       let head = String.sub string 0 len in
330       if 
331       (String.compare (String.lowercase head) (String.lowercase prefix)=0) then 
332         begin
333           let diff = len1-len in
334           let tail = String.sub string len diff in
335           if ((diff > 0) && (String.rcontains_from tail 0 '_')) then
336             Some (String.sub tail 1 (diff-1))
337             else Some tail
338           end
339         else None
340     end
341   else None
342
343 let remove_prefix prefix (last,string) =
344   if string = "" then (last,string)
345   else 
346     match is_prefix prefix string with
347       None ->
348         if last <> "" then 
349           match is_prefix last prefix with
350             None -> (last,string)
351           | Some _ ->
352               (match is_prefix prefix (last^string) with
353                 None -> (last,string)
354               | Some tail -> (prefix,tail))
355         else (last,string)
356     | Some tail -> (prefix, tail)
357         
358 let legal_suffix string = 
359   if string = "" then true else
360   begin
361     let legal_s = Str.regexp "_?\\([0-9]+\\|r\\|l\\|'\\|\"\\)" in
362     (Str.string_match legal_s string 0) && (Str.matched_string string = string)
363   end
364
365 (** check if a prefix of string_name is legal for term and returns the tail.
366     chec_rec cannot fail: at worst it return string_name.
367     The algorithm is greedy, but last contains the last name matched, providing
368     a one slot buffer. 
369     string_name is here a pair (last,string_name).*)
370
371 let rec check_rec ctx string_name =
372   function
373     | Cic.Rel m -> 
374         (match List.nth ctx (m-1) with
375           Cic.Name name ->
376             remove_prefix name string_name
377         | Cic.Anonymous -> string_name)
378     | Cic.Meta _ -> string_name
379     | Cic.Sort sort -> remove_prefix (ppsort sort) string_name  
380     | Cic.Implicit _ -> string_name
381     | Cic.Cast (te,ty) -> check_rec ctx string_name te
382     | Cic.Prod (name,so,dest) -> 
383         let l_string_name = check_rec ctx string_name so in
384         check_rec (name::ctx) string_name dest
385     | Cic.Lambda (name,so,dest) -> 
386         let string_name =
387           match name with
388             Cic.Anonymous -> string_name
389           | Cic.Name name -> remove_prefix name string_name in
390         let l_string_name = check_rec ctx string_name so in
391         check_rec (name::ctx) l_string_name dest
392     | Cic.LetIn (name,so,dest) -> 
393         let string_name = check_rec ctx string_name so in
394         check_rec (name::ctx) string_name dest
395     | Cic.Appl l ->
396         List.fold_left (check_rec ctx) string_name l
397     | Cic.Var (uri,exp_named_subst) ->
398         let name = UriManager.name_of_uri uri in
399         remove_prefix name string_name
400     | Cic.Const (uri,exp_named_subst) ->
401         let name = UriManager.name_of_uri uri in
402         remove_prefix name string_name
403     | Cic.MutInd (uri,_,exp_named_subst) -> 
404         let name = UriManager.name_of_uri uri in
405         remove_prefix name string_name  
406     | Cic.MutConstruct (uri,n,m,exp_named_subst) ->
407         let name =
408           (match fst(CicEnvironment.get_obj CicUniv.empty_ugraph uri) with
409             Cic.InductiveDefinition (dl,_,_,_) ->
410               let (_,_,_,cons) = get_nth dl (n+1) in
411               let (id,_) = get_nth cons m in
412               id 
413           | _ -> assert false) in
414         remove_prefix name string_name  
415     | Cic.MutCase (_,_,_,te,pl) ->
416         let string_name = remove_prefix "match" string_name in
417         let string_name = check_rec ctx string_name te in
418         List.fold_right (fun t s -> check_rec ctx s t) pl string_name
419     | Cic.Fix (_,fl) ->
420         let string_name = remove_prefix "fix" string_name in
421         let names = List.map (fun (name,_,_,_) -> name) fl in
422         let onames =
423           List.rev (List.map (function name -> Cic.Name name) names)
424         in
425         List.fold_right 
426           (fun (_,_,_,bo) s -> check_rec (onames@ctx) s bo) fl string_name
427     | Cic.CoFix (_,fl) ->
428         let string_name = remove_prefix "cofix" string_name in
429         let names = List.map (fun (name,_,_) -> name) fl in
430         let onames =
431           List.rev (List.map (function name -> Cic.Name name) names)
432         in
433         List.fold_right 
434           (fun (_,_,bo) s -> check_rec (onames@ctx) s bo) fl string_name
435
436 let check_name ?(allow_suffix=false) ctx name term =
437   let (_,tail) = check_rec ctx ("",name) term in
438   if (not allow_suffix) then (String.length tail = 0) 
439   else legal_suffix tail
440
441 let check_elim ctx conclusion_name =
442   let elim = Str.regexp "_elim\\|_case" in
443   if (Str.string_match elim conclusion_name 0) then
444     let len = String.length conclusion_name in
445     let tail = String.sub conclusion_name 5 (len-5) in
446     legal_suffix tail
447   else false
448
449 let rec check_names ctx hyp_names conclusion_name t =
450   match t with
451     | Cic.Prod (name,s,t) -> 
452         (match hyp_names with
453              [] -> check_names (name::ctx) hyp_names conclusion_name t
454            | hd::tl ->
455                if check_name ctx hd s then 
456                  check_names (name::ctx) tl conclusion_name t
457                else 
458                  check_names (name::ctx) hyp_names conclusion_name t)
459     | Cic.Appl ((Cic.Rel n)::args) -> 
460         (match hyp_names with
461           | [] ->
462               (check_name ~allow_suffix:true ctx conclusion_name t) ||
463               (check_elim ctx conclusion_name)
464           | [what_to_elim] ->   
465               (* what to elim could be an argument 
466                  of the predicate: e.g. leb_elim *)
467               let (last,tail) = 
468                 List.fold_left (check_rec ctx) ("",what_to_elim) args in
469               (tail = "" && check_elim ctx conclusion_name)
470           | _ -> false)
471     | Cic.MutCase  (_,_,Cic.Lambda(name,so,ty),te,_) ->
472         (match hyp_names with
473           | [] ->
474                (match is_prefix "match" conclusion_name with
475                    None -> check_name ~allow_suffix:true ctx conclusion_name t
476                | Some tail -> check_name ~allow_suffix:true ctx tail t)
477           | [what_to_match] ->   
478               (* what to match could be the term te or its type so; in this case the
479                  conclusion name should match ty *)
480               check_name ~allow_suffix:true (name::ctx) conclusion_name ty &&
481               (check_name ctx what_to_match te || check_name ctx what_to_match so)
482           | _ -> false)
483     | _ -> 
484         hyp_names=[] && check_name ~allow_suffix:true ctx conclusion_name t
485
486 let check name term =
487   let names = Str.split (Str.regexp_string "_to_") name in
488   let hyp_names,conclusion_name =
489     match List.rev names with
490         [] -> assert false
491       | hd::tl -> 
492           let elim = Str.regexp "_elim\\|_case" in
493           let len = String.length hd in
494           try 
495             let pos = Str.search_backward elim hd len in
496             let hyp = String.sub hd 0 pos in
497             let concl = String.sub hd pos (len-pos) in
498             List.rev (hyp::tl),concl
499           with Not_found -> (List.rev tl),hd in
500   check_names [] hyp_names conclusion_name term
501 ;;
502
503