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