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