aboutsummaryrefslogtreecommitdiffhomepage
path: root/pretyping/detyping.ml
blob: 3ed28a91e44b05eaa5ba098f12442690315ee1a5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384

(* $Id$ *)

open Pp
open Util
open Univ
open Names
open Term
open Inductive
open Sign
open Declare
open Impargs
open Rawterm

(* Nouvelle version de renommage des variables (DEC 98) *)
(* This is the algorithm to display distinct bound variables 

    - Règle 1 : un nom non anonyme, même non affiché, contribue à la liste
      des noms à éviter 
    - Règle 2 : c'est la dépendance qui décide si on affiche ou pas

    Exemple : 
    si bool_ind = (P:bool->Prop)(f:(P true))(f:(P false))(b:bool)(P b), alors
    il est affiché (P:bool->Prop)(P true)->(P false)->(b:bool)(P b)
    mais f et f0 contribue à la liste des variables à éviter (en supposant 
    que les noms f et f0 ne sont pas déjà pris)
    Intérêt : noms homogènes dans un but avant et après Intro
*)

type used_idents = identifier list

exception Occur

let occur_rel p env id = 
  try lookup_name_of_rel p env = Name id
  with Not_found -> false (* Unbound indice : may happen in debug *)

let occur_id env id0 c =
  let rec occur n c = match kind_of_term c with
    | IsVar id when  id=id0 -> raise Occur
    | IsConst (sp, _) when basename sp = id0 -> raise Occur
    | IsMutInd (ind_sp, _)
	when basename (path_of_inductive_path ind_sp) = id0 -> raise Occur
    | IsMutConstruct (cstr_sp, _) 
	when basename (path_of_constructor_path cstr_sp) = id0 -> raise Occur
    | IsRel p when p>n & occur_rel (p-n) env id0 -> raise Occur
    | _ -> iter_constr_with_binders succ occur n c
  in 
  try occur 1 c; false
  with Occur -> true

let next_name_not_occuring name l env_names t =
  let rec next id =
    if List.mem id l or occur_id env_names id t then next (lift_ident id)
    else id
  in 
  match name with
    | Name id   -> next id
    | Anonymous -> id_of_string "_"

(* Remark: Anonymous var may be dependent in Evar's contexts *)
let concrete_name l env_names n c =
  if n = Anonymous & not (dependent (mkRel 1) c) then
    (None,l)
  else
    let fresh_id = next_name_not_occuring n l env_names c in
    let idopt = if dependent (mkRel 1) c then (Some fresh_id) else None in
    (idopt, fresh_id::l)

let concrete_let_name l env_names n c =
  let fresh_id = next_name_not_occuring n l env_names c in
  (Name fresh_id, fresh_id::l)

    (* Returns the list of global variables and constants in a term *)
let global_vars_and_consts t =
  let rec collect acc c =
    let op, cl = splay_constr c in
    let acc' = Array.fold_left collect acc cl in
    match op with
    | OpVar id -> id::acc'
    | OpConst sp -> (basename sp)::acc'
    | OpMutInd ind_sp -> (basename (path_of_inductive_path ind_sp))::acc'
    | OpMutConstruct csp -> (basename (path_of_constructor_path csp))::acc'
    | _ -> acc'
  in
  list_uniquize (collect [] t)
    
let used_of = global_vars_and_consts

(****************************************************************************)
(* Tools for printing of Cases                                              *)

let encode_inductive id =
  let (indsp,_ as ind) =
    try 
      match kind_of_term (global_reference CCI id) with
	| IsMutInd (indsp,args) -> (indsp,args)
	| _ -> errorlabstrm "indsp_of_id" 
	    [< 'sTR ((string_of_id id)^" is not an inductive type") >]
    with Not_found -> 
      error ("Cannot find reference "^(string_of_id id))
  in
  let mis = Global.lookup_mind_specif ind in
  let constr_lengths = Array.map List.length (mis_recarg mis) in
  (indsp,constr_lengths)

let sp_of_spi (refsp,tyi) =
  let mip = Declarations.mind_nth_type_packet (Global.lookup_mind refsp) tyi in
  let (pa,_,k) = repr_path refsp in 
  make_path pa mip.Declarations.mind_typename k

(*
  let (_,mip) = mind_specif_of_mind_light spi in
  let (pa,_,k) = repr_path sp in 
  make_path pa (mip.mind_typename) k
*)
(* Parameterization of the translation from constr to ast      *)

(* Tables for Cases printing under a "if" form, a "let" form,  *)

let isomorphic_to_bool lc =
  Array.length lc = 2 & lc.(0) = 0 & lc.(1) = 0

(*
let isomorphic_to_bool lc =
  let lcparams = Array.map get_params lc in
  Array.length lcparams = 2 & lcparams.(0) = [] & lcparams.(1) = []
*)

let isomorphic_to_tuple lc = (Array.length lc = 1)
(*
let isomorphic_to_tuple lc = (Array.length lc = 1)
*)
module PrintingCasesMake =
  functor (Test : sig 
     val test : int array -> bool
(*     val test : constr array -> bool*)
     val error_message : string
     val member_message : identifier -> bool -> string
     val field : string
     val title : string
  end) ->
  struct
    type t = inductive_path * int array
    let encode = encode_inductive
    let check (_,lc) =
      if not (Test.test lc) then 
	errorlabstrm "check_encode" [< 'sTR Test.error_message >]
    let printer (spi,_) = [< 'sTR(string_of_path (sp_of_spi spi)) >]
    let key = Goptions.SecondaryTable ("Printing",Test.field)
    let title = Test.title
    let member_message = Test.member_message
    let synchronous = true
  end

module PrintingCasesIf =
  PrintingCasesMake (struct 
    let test = isomorphic_to_bool
    let error_message = "This type cannot be seen as a boolean type"
    let field = "If"
    let title = "Types leading to pretty-printing of Cases using a `if' form: "
    let member_message id = function
      | true  -> 
          "Cases on elements of " ^ (string_of_id id)
          ^ " are printed using a `if' form"
      | false -> 
          "Cases on elements of " ^ (string_of_id id)
          ^ " are not printed using `if' form"
  end)

module PrintingCasesLet =
  PrintingCasesMake (struct 
    let test = isomorphic_to_tuple
    let error_message = "This type cannot be seen as a tuple type"
    let field = "Let"
    let title = 
      "Types leading to a pretty-printing of Cases using a `let' form:"
    let member_message id = function
      | true  -> 
          "Cases on elements of " ^ (string_of_id id)
          ^ " are printed using a `let' form"
      | false -> 
          "Cases on elements of " ^ (string_of_id id)
          ^ " are not printed using a `let' form"
  end)

module PrintingIf  = Goptions.MakeIdentTable(PrintingCasesIf)
module PrintingLet = Goptions.MakeIdentTable(PrintingCasesLet)

let force_let (lc,(indsp,_,_,_,_)) = PrintingLet.active (indsp,lc)
let force_if (lc,(indsp,_,_,_,_)) = PrintingIf.active (indsp,lc)

(* Options for printing or not wildcard and synthetisable types *)

open Goptions

let wildcard_value = ref true
let force_wildcard () = !wildcard_value

let _ =                           
  declare_async_bool_option 
    { optasyncname  = "the forced wildcard option";
      optasynckey   = SecondaryTable ("Printing","Wildcard");
      optasyncread  = force_wildcard;
      optasyncwrite = (fun v -> wildcard_value := v) }

let synth_type_value = ref true
let synthetize_type () = !synth_type_value

let _ = 
  declare_async_bool_option 
    { optasyncname = "the synthesisablity";
      optasynckey   = SecondaryTable ("Printing","Synth");
      optasyncread = synthetize_type;
      optasyncwrite = (fun v -> synth_type_value := v) }

(* Auxiliary function for MutCase printing *)
(* [computable] tries to tell if the predicate typing the result is inferable*)

let computable p k =
    (* We first remove as many lambda as the arity, then we look
       if it remains a lambda for a dependent elimination. This function
       works for normal eta-expanded term. For non eta-expanded or
       non-normal terms, it may affirm the pred is synthetisable
       because of an undetected ultimate dependent variable in the second
       clause, or else, it may affirms the pred non synthetisable
       because of a non normal term in the fourth clause.
       A solution could be to store, in the MutCase, the eta-expanded
       normal form of pred to decide if it depends on its variables

       Lorsque le prédicat est dépendant de manière certaine, on
       ne déclare pas le prédicat synthétisable (même si la
       variable dépendante ne l'est pas effectivement) parce que
       sinon on perd la réciprocité de la synthèse (qui, lui,
       engendrera un prédicat non dépendant) *)

  let rec striprec (n,c) = match n, kind_of_term c with
    | (0,IsLambda (_,_,d)) -> false
    | (0,_)                -> noccur_between 1 k c
    | (n,IsLambda (_,_,d)) -> striprec (n-1,d)
    |  _                           -> false
  in 
  striprec (k,p)

let lookup_name_as_renamed ctxt t s =
  let rec lookup avoid env_names n c = match kind_of_term c with
    | IsProd (name,t,c') ->
	(match concrete_name avoid env_names name c' with
             (Some id,avoid') -> 
	       if id=s then (Some n) 
	       else lookup avoid' (add_name (Name id) env_names) (n+1) c'
	   | (None,avoid')    -> lookup avoid' env_names (n+1) (pop c'))
    | IsCast (c,_) -> lookup avoid env_names n c
    | _ -> None
  in lookup (ids_of_named_context ctxt) empty_names_context 1 t

let lookup_index_as_renamed t n =
  let rec lookup n d c = match kind_of_term c with
    | IsProd (name,_,c') ->
	  (match concrete_name [] empty_names_context name c' with
          (Some _,_) -> lookup n (d+1) c'
        | (None  ,_) -> if n=1 then Some d else lookup (n-1) (d+1) c')
    | IsCast (c,_) -> lookup n d c
    | _ -> None
  in lookup n 1 t

let rec detype avoid env t =
  match kind_of_term (collapse_appl t) with
    | IsRel n ->
      (try match lookup_name_of_rel n env with
	 | Name id   -> RRef (dummy_loc, RVar id)
	 | Anonymous -> anomaly "detype: index to an anonymous variable"
       with Not_found ->
	 let s = "[REL "^(string_of_int n)^"]"
	 in RRef (dummy_loc, RVar (id_of_string s)))
    | IsMeta n -> RMeta (dummy_loc, n)
    | IsVar id -> RRef (dummy_loc,RVar id)
    | IsXtra s -> warning "bdize: Xtra should no longer occur in constr";
	RRef(dummy_loc,RVar (id_of_string ("XTRA"^s)))
        (* ope("XTRA",((str s):: pl@(List.map detype cl)))*) 
    | IsSort (Prop c) -> RSort (dummy_loc,RProp c)
    | IsSort (Type _) -> RSort (dummy_loc,RType)
    | IsCast (c1,c2) ->
	RCast(dummy_loc,detype avoid env c1,detype avoid env c2)
    | IsProd (na,ty,c) -> detype_binder BProd avoid env na ty c
    | IsLambda (na,ty,c) -> detype_binder BLambda avoid env na ty c
    | IsLetIn (na,b,_,c) -> detype_binder BLetIn avoid env na b c
    | IsApp (f,args) ->
	RApp (dummy_loc,detype avoid env f,array_map_to_list (detype avoid env) args)
    | IsConst (sp,cl) ->
	RRef(dummy_loc,RConst(sp,Array.map (detype avoid env) cl))
    | IsEvar (ev,cl) ->
	RRef(dummy_loc,REVar(ev,Array.map (detype avoid env) cl))
    | IsMutInd (ind_sp,cl) ->
	RRef (dummy_loc,RInd (ind_sp,Array.map (detype avoid env) cl))
    | IsMutConstruct (cstr_sp,cl) ->
	RRef (dummy_loc,RConstruct (cstr_sp,Array.map (detype avoid env) cl))
    | IsMutCase (annot,p,c,bl) ->
	let synth_type = synthetize_type () in
	let tomatch = detype avoid env c in
	begin 
	  match annot with
(*	  | None -> (* Pas d'annotation --> affichage avec vieux Case *)
	      warning "Printing in old Case syntax";
	      ROldCase (dummy_loc,false,Some (detype avoid env p),
			tomatch,Array.map (detype avoid env) bl)
	  | Some *) (consnargsl,(indsp,considl,k,style,tags)) ->
	    let pred = 
	      if synth_type & computable p k & considl <> [||] then
		None
	      else 
		Some (detype avoid env p) 
	    in
	    let constructs = 
	      Array.init (Array.length considl)
		(fun i -> ((indsp,i+1),[] (* on triche *))) in
	    let eqnv =
	      array_map3 (detype_eqn avoid env) constructs consnargsl bl in
	    let eqnl = Array.to_list eqnv in
	    let tag =
	      if PrintingLet.active (indsp,consnargsl) then 
		PrintLet 
	      else if PrintingIf.active (indsp,consnargsl) then 
		PrintIf 
	      else 
		PrintCases
	    in 
	    RCases (dummy_loc,tag,pred,[tomatch],eqnl)
	end
	
    | IsFix (nvn,(cl,lfn,vt)) -> detype_fix (RFix nvn) avoid env cl lfn vt
    | IsCoFix (n,(cl,lfn,vt))  -> detype_fix (RCoFix n) avoid env cl lfn vt

and detype_fix fk avoid env cl lfn vt =
  let lfi = List.map (fun id -> next_name_away id avoid) lfn in
  let def_avoid = lfi@avoid in
  let def_env =
    List.fold_left (fun env id -> add_name (Name id) env) env lfi in
  RRec(dummy_loc,fk,Array.of_list lfi,Array.map (detype avoid env) cl,
       Array.map (detype def_avoid def_env) vt)


and detype_eqn avoid env constr_id construct_nargs branch =
  let make_pat x avoid env b ids =
    if not (force_wildcard ()) or (dependent (mkRel 1) b) then
      let id = next_name_away_with_default "x" x avoid in
      PatVar (dummy_loc,Name id),id::avoid,(add_name (Name id) env),id::ids
    else 
      PatVar (dummy_loc,Anonymous),avoid,(add_name Anonymous env),ids
  in
  let rec buildrec ids patlist avoid env n b =
    if n=0 then
      (ids, [PatCstr(dummy_loc, constr_id, List.rev patlist,Anonymous)],
       detype avoid env b)
    else
      match kind_of_term b with
	| IsLambda (x,_,b) -> 
	    let pat,new_avoid,new_env,new_ids = make_pat x avoid env b ids in
            buildrec new_ids (pat::patlist) new_avoid new_env (n-1) b

	| IsCast (c,_) ->    (* Oui, il y a parfois des cast *)
	    buildrec ids patlist avoid env n c

	| _ -> (* eta-expansion : n'arrivera plus lorsque tous les
                  termes seront construits à partir de la syntaxe Cases *)
            (* nommage de la nouvelle variable *)
	    let new_b = applist (lift 1 b, [mkRel 1]) in
            let pat,new_avoid,new_env,new_ids =
	      make_pat Anonymous avoid env new_b ids in
	    buildrec new_ids (pat::patlist) new_avoid new_env (n-1) new_b
	  
  in 
  buildrec [] [] avoid env construct_nargs branch

and detype_binder bk avoid env na ty c =
  let na',avoid' =
    if bk = BLetIn then concrete_let_name avoid env na c
    else
      match concrete_name avoid env na c with
	| (Some id,l') -> (Name id), l'
	| (None,l')    -> Anonymous, l' in
  RBinder (dummy_loc,bk,
	   na',detype [] env ty,
	   detype avoid' (add_name na' env) c)