Debian Codegraph @

interp/impargs.ml

raw symbols SCIP
1 (************************************************************************)
2 (* * The Rocq Prover / The Rocq Development Team *)
3 (* v * Copyright INRIA, CNRS and contributors *)
4 (* <O___,, * (see version control and CREDITS file for authors & dates) *)
5 (* \VV/ **************************************************************)
6 (* // * This file is distributed under the terms of the *)
7 (* * GNU Lesser General Public License Version 2.1 *)
8 (* * (see LICENSE file for the text of the license) *)
9 (************************************************************************)
10
11 open CErrors
12 open Pp
13 open Util
14 open Names
15 open Constr
16 open Globnames
17 open Glob_term
18 open Declarations
19 open Libobject
20 open EConstr
21 open Reductionops
22 open Constrexpr
23
24 let whd_prod env sigma typ =
25 let open CClosure in
26 let infos = Evarutil.create_clos_infos env sigma RedFlags.all in
27 let tab = create_tab () in
28 let typ = inject (EConstr.Unsafe.to_constr typ) in
29 let typ, stk = whd_stack infos tab typ [] in
30 match fterm_of typ with
31 | FProd (na, c1, c2, e) ->
32 let c1 = EConstr.of_constr @@ term_of_fconstr c1 in
33 let c2 = EConstr.of_constr @@ term_of_fconstr (mk_clos (CClosure.usubs_lift e) c2) in
34 Some (EConstr.of_binder_annot na, c1, c2)
35 | _ -> None
36
37 module NamedDecl = Context.Named.Declaration
38
39 (*s Flags governing the computation of implicit arguments *)
40
41 type implicits_flags = {
42 auto : bool; (* automatic or manual only *)
43 strict : bool; (* true = strict *)
44 strongly_strict : bool; (* true = strongly strict *)
45 reversible_pattern : bool;
46 contextual : bool; (* true = contextual *)
47 maximal : bool
48 }
49
50 let implicit_args = ref {
51 auto = false;
52 strict = true;
53 strongly_strict = false;
54 reversible_pattern = false;
55 contextual = false;
56 maximal = false;
57 }
58
59 let make_implicit_args flag =
60 implicit_args := { !implicit_args with auto = flag }
61
62 let make_strict_implicit_args flag =
63 implicit_args := { !implicit_args with strict = flag }
64
65 let make_strongly_strict_implicit_args flag =
66 implicit_args := { !implicit_args with strongly_strict = flag }
67
68 let make_reversible_pattern_implicit_args flag =
69 implicit_args := { !implicit_args with reversible_pattern = flag }
70
71 let make_contextual_implicit_args flag =
72 implicit_args := { !implicit_args with contextual = flag }
73
74 let make_maximal_implicit_args flag =
75 implicit_args := { !implicit_args with maximal = flag }
76
77 let is_implicit_args () = !implicit_args.auto
78 let is_strict_implicit_args () = !implicit_args.strict
79 let is_strongly_strict_implicit_args () = !implicit_args.strongly_strict
80 let is_reversible_pattern_implicit_args () = !implicit_args.reversible_pattern
81 let is_contextual_implicit_args () = !implicit_args.contextual
82 let is_maximal_implicit_args () = !implicit_args.maximal
83
84 let with_implicit_protection f x =
85 let open Memprof_coq.Resource_bind in
86 let& () = Util.protect_ref implicit_args in
87 f x
88
89 type on_trailing_implicit = Error | Info | Silent
90
91 let msg_trailing_implicit (fail : on_trailing_implicit) na i =
92 let pos = match na with
93 | Anonymous -> "number " ^ string_of_int i
94 | Name id -> Names.Id.to_string id in
95 let str1 = "Argument " ^ pos ^ " is a trailing implicit, " in
96 match fail with
97 | Error ->
98 user_err (strbrk (str1 ^ "so it can't be declared non maximal. Please use { } instead of [ ]."))
99 | Info ->
100 Flags.if_verbose Feedback.msg_info (strbrk (str1 ^ "so it has been declared maximally inserted."))
101 | Silent -> ()
102
103 let set_maximality fail na i imps b =
104 (* Force maximal insertion on ending implicits (compatibility) *)
105 b || (
106 let is_set x = match x with None -> false | _ -> true in
107 let b' = List.for_all is_set imps in
108 if b' then msg_trailing_implicit fail na i;
109 b')
110
111 (*s Computation of implicit arguments *)
112
113 (* We remember various information about why an argument is
114 inferable as implicit
115
116 - [DepRigid] means that the implicit argument can be found by
117 unification along a rigid path (we do not print the arguments of
118 this kind if there is enough arguments to infer them)
119
120 - [DepFlex] means that the implicit argument can be found by unification
121 along a collapsible path only (e.g. as x in (P x) where P is another
122 argument) (we do (defensively) print the arguments of this kind)
123
124 - [DepFlexAndRigid] means that the least argument from which the
125 implicit argument can be inferred is following a collapsible path
126 but there is a greater argument from where the implicit argument is
127 inferable following a rigid path (useful to know how to print a
128 partial application)
129
130 - [Manual] means the argument has been explicitly set as implicit.
131
132 We also consider arguments inferable from the conclusion but it is
133 operational only if [conclusion_matters] is true.
134 *)
135
136 type argument_position =
137 | Conclusion
138 | Hyp of int
139
140 let argument_position_eq p1 p2 = match p1, p2 with
141 | Conclusion, Conclusion -> true
142 | Hyp h1, Hyp h2 -> Int.equal h1 h2
143 | _ -> false
144
145 type implicit_explanation =
146 | DepRigid of argument_position
147 | DepFlex of argument_position
148 | DepFlexAndRigid of (*flex*) argument_position * (*rig*) argument_position
149 | Manual
150
151 let argument_less = function
152 | Hyp n, Hyp n' -> n<n'
153 | Hyp _, Conclusion -> true
154 | Conclusion, _ -> false
155
156 let update pos rig st =
157 let e =
158 if rig then
159 match st with
160 | None -> DepRigid pos
161 | Some (DepRigid n as x) ->
162 if argument_less (pos,n) then DepRigid pos else x
163 | Some (DepFlexAndRigid (fpos,rpos) as x) ->
164 if argument_less (pos,fpos) || argument_position_eq pos fpos then DepRigid pos else
165 if argument_less (pos,rpos) then DepFlexAndRigid (fpos,pos) else x
166 | Some (DepFlex fpos) ->
167 if argument_less (pos,fpos) || argument_position_eq pos fpos then DepRigid pos
168 else DepFlexAndRigid (fpos,pos)
169 | Some Manual -> assert false
170 else
171 match st with
172 | None -> DepFlex pos
173 | Some (DepRigid rpos as x) ->
174 if argument_less (pos,rpos) then DepFlexAndRigid (pos,rpos) else x
175 | Some (DepFlexAndRigid (fpos,rpos) as x) ->
176 if argument_less (pos,fpos) then DepFlexAndRigid (pos,rpos) else x
177 | Some (DepFlex fpos as x) ->
178 if argument_less (pos,fpos) then DepFlex pos else x
179 | Some Manual -> assert false
180 in Some e
181
182 (* modified is_rigid_reference with a truncated env *)
183 let is_flexible_reference env sigma bound depth f =
184 match kind sigma f with
185 | Rel n when n >= bound+depth -> (* inductive type *) false
186 | Rel n when n >= depth -> (* previous argument *) true
187 | Rel n -> (* since local definitions have been expanded *) false
188 | Const (kn,_) ->
189 let cb = Environ.lookup_constant kn env in
190 (match cb.const_body with Def _ -> true | _ -> false)
191 | Var id ->
192 env |> Environ.lookup_named id |> NamedDecl.is_local_def
193 | Ind _ | Construct _ -> false
194 | _ -> true
195
196 let push_lift d (e,n) = (push_rel d e,n+1)
197
198 let is_reversible_pattern sigma bound depth f l =
199 isRel sigma f && let n = destRel sigma f in (n < bound+depth) && (n >= depth) &&
200 Array.for_all (fun c -> isRel sigma c && destRel sigma c < depth) l &&
201 Array.distinct l
202
203 (* Precondition: rels in env are for inductive types only *)
204 let add_free_rels_until strict strongly_strict revpat bound env sigma m pos acc =
205 let rec frec rig (env,depth as ed) c =
206 let hd = if strict then Reductionops.clos_whd_flags RedFlags.all env sigma c else c in
207 let c = if strongly_strict then hd else c in
208 match kind sigma hd with
209 | Rel n when (n < bound+depth) && (n >= depth) ->
210 let i = bound + depth - n - 1 in
211 acc.(i) <- update pos rig acc.(i)
212 | App (f,l) when revpat && is_reversible_pattern sigma bound depth f l ->
213 let i = bound + depth - EConstr.destRel sigma f - 1 in
214 acc.(i) <- update pos rig acc.(i)
215 | App (f,_) when rig && is_flexible_reference env sigma bound depth f ->
216 if strict then () else
217 iter_with_full_binders env sigma push_lift (frec false) ed c
218 | Proj (p, _, _) when rig ->
219 if strict then () else
220 iter_with_full_binders env sigma push_lift (frec false) ed c
221 | Case _ when rig ->
222 if strict then () else
223 iter_with_full_binders env sigma push_lift (frec false) ed c
224 | Evar _ -> ()
225 | _ ->
226 iter_with_full_binders env sigma push_lift (frec rig) ed c
227 in
228 let () = if not (Vars.noccur_between sigma 1 bound m) then frec true (env,1) m in
229 acc
230
231 (* compute the list of implicit arguments *)
232
233 let rec is_rigid_head sigma t = match kind sigma t with
234 | Rel _ | Evar _ -> false
235 | Ind _ | Const _ | Var _ | Sort _ -> true
236 | Case (_,_,_,_,_,f,_) -> is_rigid_head sigma f
237 | Proj _ -> true
238 | App (f,args) ->
239 (match kind sigma f with
240 | Fix ((fi,i),_) -> is_rigid_head sigma (args.(fi.(i)))
241 | _ -> is_rigid_head sigma f)
242 | Lambda _ | LetIn _ | Construct _ | CoFix _ | Fix _
243 | Prod _ | Meta _ | Cast _ | Int _ | Float _ | String _ | Array _ -> assert false
244
245 let is_rigid env sigma t =
246 let open Context.Rel.Declaration in
247 match whd_prod env sigma t with
248 | Some (na,a,b) ->
249 let (_,t) = whd_decompose_prod (push_rel (LocalAssum (na,a)) env) sigma b in
250 is_rigid_head sigma t
251 | _ -> true
252
253 let compute_implicits_names env sigma t =
254 let open Context.Rel.Declaration in
255 let rec aux env names t = match whd_prod env sigma t with
256 | Some (na, a, b) ->
257 let rels,ids = Termops.free_rels_and_unqualified_refs sigma a in
258 aux (push_rel (LocalAssum (na,a)) env) ((na.Context.binder_name,rels,ids)::names) b
259 | None ->
260 let rels,ids = Termops.free_rels_and_unqualified_refs sigma t in
261 let rec set_names (allrels,ids) = function
262 | [] -> (1,1,[])
263 | (na,rels',ids')::names ->
264 let (absolute_pos,nnondep,names) = set_names (rels'::allrels,Id.Set.union ids ids') names in
265 let isdep = List.exists_i (fun i rels -> Int.Set.mem i rels) 1 allrels in
266 let nnondep',dep_pos = if isdep then nnondep, None else nnondep + 1, Some nnondep in
267 (absolute_pos+1,nnondep',(na,absolute_pos,dep_pos)::names) in
268 let _,_,names = set_names ([rels],ids) names in
269 List.rev names
270 in
271 NewProfile.profile "compute_implicits_names" (fun () -> aux env [] t) ()
272
273 let compute_implicits_explanation_gen strict strongly_strict revpat contextual env sigma t =
274 let open Context.Rel.Declaration in
275 let rec aux env n t = match whd_prod env sigma t with
276 | Some (na, a, b) ->
277 add_free_rels_until strict strongly_strict revpat n env sigma a (Hyp (n+1))
278 (aux (push_rel (LocalAssum (na,a)) env) (n+1) b)
279 | _ ->
280 let v = Array.make n None in
281 if contextual then
282 add_free_rels_until strict strongly_strict revpat n env sigma t Conclusion v
283 else v
284 in
285 NewProfile.profile "compute_implicits_explanation_gen" (fun () ->
286 match whd_prod env sigma t with
287 | Some (na, a, b) ->
288 let v = aux (push_rel (LocalAssum (na,a)) env) 1 b in
289 Array.to_list v
290 | _ -> [])
291 ()
292
293 let compute_implicits_explanation_flags env sigma f t =
294 compute_implicits_explanation_gen
295 (f.strict || f.strongly_strict) f.strongly_strict
296 f.reversible_pattern f.contextual env sigma t
297
298 let compute_implicits_flags env sigma f t =
299 List.combine
300 (compute_implicits_names env sigma t)
301 (compute_implicits_explanation_flags env sigma f t)
302
303 let compute_auto_implicits env sigma flags enriching t =
304 List.combine
305 (compute_implicits_names env sigma t)
306 (if enriching then compute_implicits_explanation_flags env sigma flags t
307 else compute_implicits_explanation_gen false false false true env sigma t)
308
309 (* Extra information about implicit arguments *)
310
311 type maximal_insertion = bool (* true = maximal contextual insertion *)
312 type force_inference = bool (* true = always infer, never turn into evar/subgoal *)
313
314 type implicit_position = Name.t * int * int option
315
316 type implicit_status_info = {
317 impl_pos : implicit_position;
318 impl_expl : implicit_explanation;
319 impl_max : maximal_insertion;
320 impl_force : force_inference;
321 }
322
323 type implicit_status = implicit_status_info option
324
325 type implicit_side_condition = DefaultImpArgs | LessArgsThan of int
326
327 type implicits_list = implicit_side_condition * implicit_status list
328
329 let is_status_implicit = function
330 | None -> false
331 | _ -> true
332
333 let name_of_pos k = Id.of_string ("arg_" ^ string_of_int k)
334
335 let binding_kind_of_status = function
336 | Some { impl_max = false } -> NonMaxImplicit
337 | Some { impl_max = true } -> MaxImplicit
338 | None -> Explicit
339
340 let name_of_implicit = function
341 | None -> anomaly (Pp.str "Not an implicit argument.")
342 | Some { impl_pos = (Name id, _, _) } -> id
343 | Some { impl_pos = (Anonymous, k, _) } -> name_of_pos k
344
345 let match_implicit imp pos = match imp, pos with
346 | None, _ -> anomaly (Pp.str "Not an implicit argument.")
347 | Some { impl_pos = (Name id, _, _) }, ExplByName id' -> Id.equal id id'
348 | Some { impl_pos = (_, _, Some n) }, ExplByPos n' -> Int.equal n n'
349 | Some { impl_pos = (_, n, _) }, ExplByName id -> Id.equal id (name_of_pos n)
350 | _ -> false
351
352 let maximal_insertion_of = function
353 | Some imp -> imp.impl_max
354 | None -> anomaly (Pp.str "Not an implicit argument.")
355
356 let force_inference_of = function
357 | Some imp -> imp.impl_force
358 | None -> anomaly (Pp.str "Not an implicit argument.")
359
360 let is_nondep_implicit p imps =
361 List.exists (function Some { impl_pos = (_,_,Some p') } -> Int.equal p p' | _ -> false) imps
362
363 (* [in_ctx] means we know the expected type, [n] is the index of the argument *)
364 let is_inferable_implicit in_ctx n = function
365 | None -> false
366 | Some { impl_expl = DepRigid (Hyp p) } -> in_ctx || n >= p
367 | Some { impl_expl = DepFlex (Hyp p) } -> false
368 | Some { impl_expl = DepFlexAndRigid (_,Hyp q) } -> in_ctx || n >= q
369 | Some { impl_expl = DepRigid Conclusion } -> in_ctx
370 | Some { impl_expl = DepFlex Conclusion } -> false
371 | Some { impl_expl = DepFlexAndRigid (_,Conclusion) } -> in_ctx
372 | Some { impl_expl = Manual } -> true
373
374 let explicitation = function
375 | None -> anomaly (Pp.str "not implicit")
376 | Some imp ->
377 let (na, _, p) = imp.impl_pos in
378 match na, p with
379 | Name id, _ -> ExplByName id
380 | _, Some p -> ExplByPos p
381 | _ -> anomaly (Pp.str "Implicit without a position")
382
383 let positions_of_implicits (_,impls) =
384 let rec aux n = function
385 [] -> []
386 | Some _ :: l -> n :: aux (n+1) l
387 | None :: l -> aux (n+1) l
388 in aux 1 impls
389
390 (* Manage user-given implicit arguments *)
391
392 let rec prepare_implicits i f = function
393 | [] -> []
394 | ((na,_,_ as pos), Some imp)::imps ->
395 let imps' = prepare_implicits (i+1) f imps in
396 let data = {
397 impl_pos = pos;
398 impl_expl = imp;
399 impl_max = set_maximality Silent na i imps' f.maximal;
400 impl_force = true
401 } in
402 Some data :: imps'
403 | _::imps -> None :: prepare_implicits (i+1) f imps
404
405 let set_manual_implicits silent flags enriching autoimps l =
406 (* Compare with automatic implicits to recover printing data and names *)
407 let rec merge k autoimps explimps = match autoimps, explimps with
408 | autoimp::autoimps, explimp::explimps ->
409 let imps' = merge (k+1) autoimps explimps in
410 begin match autoimp, explimp.CAst.v with
411 | ((Name _ as na,_,_ as pos),_), Some (_,max) ->
412 Some {
413 impl_pos = pos;
414 impl_expl = Manual;
415 impl_max = set_maximality (if silent then Silent else Error) na k imps' max;
416 impl_force = true;
417 }
418 | ((Anonymous,n1,n2),_), Some (na,max) ->
419 Some {
420 impl_pos = (na,n1,n2);
421 impl_expl = Manual;
422 impl_max = max;
423 impl_force = true;
424 }
425 | ((na,_,_ as pos),Some exp), None when enriching ->
426 Some {
427 impl_pos = pos;
428 impl_expl = exp;
429 impl_max = set_maximality (if silent then Silent else Info) na k imps' flags.maximal;
430 impl_force = true;
431 }
432 | (pos,_), None -> None
433 end :: imps'
434 | [], [] -> []
435 | [], _ -> assert false
436 (* possibly more automatic than manual implicit arguments
437 when the conclusion is an unfoldable constant *)
438 | autoimps, [] -> merge k autoimps [CAst.make None]
439 in merge 1 autoimps l
440
441 let compute_semi_auto_implicits env sigma f t =
442 if not f.auto then [DefaultImpArgs, []]
443 else let l = compute_implicits_flags env sigma f t in
444 [DefaultImpArgs, prepare_implicits 1 f l]
445
446 (*s Constants. *)
447
448 let compute_constant_implicits flags cst =
449 let env = Global.env () in
450 let sigma = Evd.from_env env in
451 let cb = Environ.lookup_constant cst env in
452 let ty = of_constr cb.const_type in
453 let impls = compute_semi_auto_implicits env sigma flags ty in
454 impls
455
456 (*s Inductives and constructors. Their implicit arguments are stored
457 in an array, indexed by the inductive number, of pairs $(i,v)$ where
458 $i$ are the implicit arguments of the inductive and $v$ the array of
459 implicit arguments of the constructors. *)
460
461 let compute_mib_implicits flags kn =
462 let env = Global.env () in
463 let sigma = Evd.from_env env in
464 let mib = Environ.lookup_mind kn env in
465 let ar =
466 Array.to_list
467 (Array.mapi (* No need to lift, arities contain no de Bruijn *)
468 (fun i mip ->
469 (* No need to care about constraints here *)
470 let ty, _ = Typeops.type_of_global_in_context env (GlobRef.IndRef (kn,i)) in
471 let r = (snd @@ Inductive.lookup_mind_specif env (kn,i)).mind_relevance in
472 Context.Rel.Declaration.LocalAssum (Context.make_annot (Name mip.mind_typename) r, ty))
473 mib.mind_packets) in
474 let env_ar = Environ.push_rel_context ar env in
475 let imps_one_inductive i mip =
476 let ind = (kn,i) in
477 let ar, _ = Typeops.type_of_global_in_context env (GlobRef.IndRef ind) in
478 ((GlobRef.IndRef ind,compute_semi_auto_implicits env sigma flags (of_constr ar)),
479 Array.mapi (fun j (ctx, cty) ->
480 let c = of_constr (Term.it_mkProd_or_LetIn cty ctx) in
481 (GlobRef.ConstructRef (ind,j+1),compute_semi_auto_implicits env_ar sigma flags c))
482 mip.mind_nf_lc)
483 in
484 Array.mapi imps_one_inductive mib.mind_packets
485
486 let compute_all_mib_implicits flags kn =
487 let imps = compute_mib_implicits flags kn in
488 List.flatten
489 (Array.map_to_list (fun (ind,cstrs) -> ind::Array.to_list cstrs) imps)
490
491 (*s Variables. *)
492
493 let compute_var_implicits flags id =
494 let env = Global.env () in
495 let sigma = Evd.from_env env in
496 compute_semi_auto_implicits env sigma flags (NamedDecl.get_type (lookup_named id env))
497
498 (* Implicits of a global reference. *)
499
500 let compute_global_implicits flags = let open GlobRef in function
501 | VarRef id -> compute_var_implicits flags id
502 | ConstRef kn -> compute_constant_implicits flags kn
503 | IndRef (kn,i) ->
504 let ((_,imps),_) = (compute_mib_implicits flags kn).(i) in imps
505 | ConstructRef ((kn,i),j) ->
506 let (_,cimps) = (compute_mib_implicits flags kn).(i) in snd cimps.(j-1)
507
508 (* Merge a manual implicit position with an implicit_status list *)
509
510 let merge_impls (cond,oldimpls) (_,newimpls) =
511 let oldimpls,usersuffiximpls = List.chop (List.length newimpls) oldimpls in
512 cond, (List.map2 (fun orig ni ->
513 match orig with
514 | Some { impl_expl = Manual } -> orig
515 | _ -> ni) oldimpls newimpls)@usersuffiximpls
516
517 (* Caching implicits *)
518
519 type implicit_interactive_request =
520 | ImplAuto
521 | ImplManual of int
522
523 type implicit_discharge_request =
524 | ImplLocal
525 | ImplConstant of implicits_flags
526 | ImplMutualInductive of MutInd.t * implicits_flags
527 | ImplInteractive of implicits_flags *
528 implicit_interactive_request
529
530 module GlobRefMap = Environ.QGlobRef.Map
531
532 let implicits_table = Summary.ref GlobRefMap.empty ~name:"implicits"
533
534 let implicits_of_global ref =
535 try
536 let env = Global.env () in
537 let l = GlobRefMap.find env ref !implicits_table in
538 try
539 let rename_l = Arguments_renaming.arguments_names env ref in
540 let rec rename implicits names = match implicits, names with
541 | [], _ -> []
542 | _, [] -> implicits
543 | Some ({ impl_pos = (_, n1, n2) } as impl) :: implicits, Name id :: names ->
544 Some { impl with impl_pos = (Name id, n1, n2) } :: rename implicits names
545 | imp :: implicits, _ :: names -> imp :: rename implicits names
546 in
547 List.map (fun (t, il) -> t, rename il rename_l) l
548 with Not_found -> l
549 with Not_found -> [DefaultImpArgs,[]]
550
551 let cache_implicits_decl (ref, imps) =
552 implicits_table := GlobRefMap.add (Global.env ()) ref imps !implicits_table
553
554 let load_implicits _ (_,l) = List.iter cache_implicits_decl l
555
556 let cache_implicits o =
557 load_implicits 1 o
558
559 let subst_implicits_decl subst (r,imps as o) =
560 let r' = fst (subst_global subst r) in if r==r' then o else (r',imps)
561
562 let subst_implicits (subst,(req,l)) =
563 (ImplLocal,List.Smart.map (subst_implicits_decl subst) l)
564
565 (* This was moved out of lib.ml, however it is not stored with regular
566 implicit data *)
567 let sec_implicits =
568 Summary.ref Id.Map.empty ~name:"section-implicits"
569
570 let impls_of_context vars =
571 let map n id =
572 let impl_pos = (Name id, n, None) in
573 match Id.Map.get id !sec_implicits with
574 | NonMaxImplicit ->
575 Some { impl_pos; impl_expl = Manual; impl_max = false; impl_force = true }
576 | MaxImplicit ->
577 Some { impl_pos; impl_expl = Manual; impl_max = true; impl_force = true }
578 | Explicit -> None
579 in
580 List.map_i map 1 vars
581
582 let adjust_side_condition p = function
583 | LessArgsThan n -> LessArgsThan (n+p)
584 | DefaultImpArgs -> DefaultImpArgs
585
586 let lift_argument_position p = function
587 | Conclusion -> Conclusion
588 | Hyp q -> Hyp (p+q)
589
590 let lift_explanation p = function
591 | DepRigid e -> DepRigid (lift_argument_position p e)
592 | DepFlex e -> DepFlex (lift_argument_position p e)
593 | DepFlexAndRigid (e1,e2) -> DepFlexAndRigid (lift_argument_position p e1,lift_argument_position p e2)
594 | Manual -> Manual
595
596 let lift_implicits p imp =
597 let (na, n1, o) = imp.impl_pos in
598 { imp with impl_pos = (na, n1 + p, o); impl_expl = lift_explanation p imp.impl_expl }
599
600 let add_section_impls vars extra_impls (cond,impls) =
601 let p = List.length vars - List.length extra_impls in
602 adjust_side_condition p cond, extra_impls @ List.map (Option.map (lift_implicits p)) impls
603
604 let discharge_implicits (req,l) =
605 match req with
606 | ImplLocal -> None
607 | ImplMutualInductive _ | ImplInteractive _ | ImplConstant _ ->
608 let l' =
609 try
610 List.map (fun (gr, l) ->
611 let vars = Array.map_to_list Constr.destVar (Global.section_instance gr) in
612 let extra_impls = impls_of_context vars in
613 let newimpls = List.map (add_section_impls vars extra_impls) l in
614 (gr, newimpls)) l
615 with Not_found -> l in
616 Some (req,l')
617
618 let rebuild_implicits (req,l) =
619 match req with
620 | ImplLocal -> assert false
621 | ImplConstant flags ->
622 let ref,oldimpls = List.hd l in
623 let newimpls = compute_global_implicits flags ref in
624 req, [ref, List.map2 merge_impls oldimpls newimpls]
625 | ImplMutualInductive (kn,flags) ->
626 let newimpls = compute_all_mib_implicits flags kn in
627 let rec aux olds news =
628 match olds, news with
629 | (_, oldimpls) :: old, (gr, newimpls) :: tl ->
630 (gr, List.map2 merge_impls oldimpls newimpls) :: aux old tl
631 | [], [] -> []
632 | _, _ -> assert false
633 in req, aux l newimpls
634
635 | ImplInteractive (flags,o) ->
636 let ref,oldimpls = List.hd l in
637 (if isVarRef ref && Global.is_in_section ref then ImplLocal else req),
638 match o with
639 | ImplAuto ->
640 let newimpls = compute_global_implicits flags ref in
641 [ref,List.map2 merge_impls oldimpls newimpls]
642 | ImplManual userimplsize ->
643 if flags.auto then
644 let newimpls = List.hd (compute_global_implicits flags ref) in
645 let p = List.length (snd newimpls) - userimplsize in
646 let newimpls = on_snd (List.firstn p) newimpls in
647 [ref,List.map (fun o -> merge_impls o newimpls) oldimpls]
648 else
649 [ref,oldimpls]
650
651 let classify_implicits (req,_) = match req with
652 | ImplLocal -> Dispose
653 | _ -> Substitute
654
655 type implicits_obj =
656 implicit_discharge_request *
657 (GlobRef.t * implicits_list list) list
658
659 let inImplicits : implicits_obj -> obj =
660 declare_object {(default_object "IMPLICITS") with
661 cache_function = cache_implicits;
662 load_function = load_implicits;
663 subst_function = subst_implicits;
664 classify_function = classify_implicits;
665 discharge_function = discharge_implicits;
666 rebuild_function = rebuild_implicits }
667
668 let is_local local ref = local || isVarRef ref && Global.is_in_section ref
669
670 let declare_implicits_gen req flags ref =
671 let imps = compute_global_implicits flags ref in
672 Lib.add_leaf (inImplicits (req,[ref,imps]))
673
674 let declare_implicits local ref =
675 let flags = { !implicit_args with auto = true } in
676 let req =
677 if is_local local ref then ImplLocal else ImplInteractive(flags,ImplAuto) in
678 declare_implicits_gen req flags ref
679
680 let declare_var_implicits id ~impl =
681 let flags = !implicit_args in
682 sec_implicits := Id.Map.add id impl !sec_implicits;
683 declare_implicits_gen ImplLocal flags (GlobRef.VarRef id)
684
685 let declare_constant_implicits con =
686 let flags = !implicit_args in
687 declare_implicits_gen (ImplConstant flags) flags (GlobRef.ConstRef con)
688
689 let declare_mib_implicits kn =
690 let flags = !implicit_args in
691 let imps = Array.map_to_list
692 (fun (ind,cstrs) -> ind::(Array.to_list cstrs))
693 (compute_mib_implicits flags kn) in
694 Lib.add_leaf
695 (inImplicits (ImplMutualInductive (kn,flags),List.flatten imps))
696
697 (* Declare manual implicits *)
698 type manual_implicits = (Name.t * bool) option CAst.t list
699
700 let compute_implicits_with_manual env sigma ?(silent=true) typ enriching l =
701 let autoimpls = compute_auto_implicits env sigma !implicit_args enriching typ in
702 set_manual_implicits silent !implicit_args enriching autoimpls l
703
704 let check_inclusion l =
705 (* Check strict inclusion *)
706 let rec aux = function
707 | n1::(n2::_ as nl) ->
708 if n1 <= n2 then
709 user_err Pp.(str "Sequences of implicit arguments must be of different lengths.");
710 aux nl
711 | _ -> () in
712 aux (List.map snd l)
713
714 let check_rigidity isrigid =
715 if not isrigid then
716 user_err (strbrk "Multiple sequences of implicit arguments available only for references that cannot be applied to an arbitrarily large number of arguments.")
717
718 let projection_implicits env p impls =
719 let npars = Projection.npars p in
720 CList.skipn_at_best npars impls
721
722 let declare_manual_implicits local ref ?enriching l =
723 let flags = !implicit_args in
724 let env = Global.env () in
725 let sigma = Evd.from_env env in
726 let t, _ = Typeops.type_of_global_in_context env ref in
727 let t = of_constr t in
728 let enriching = Option.default flags.auto enriching in
729 let autoimpls = compute_auto_implicits env sigma flags enriching t in
730 let l = [DefaultImpArgs, set_manual_implicits false flags enriching autoimpls l] in
731 let req =
732 if is_local local ref then ImplLocal
733 else ImplInteractive(flags,ImplManual (List.length autoimpls))
734 in
735 Lib.add_leaf (inImplicits (req,[ref,l]))
736
737 let maybe_declare_manual_implicits local ref ?enriching l =
738 if List.exists (fun x -> x.CAst.v <> None) l then
739 declare_manual_implicits local ref ?enriching l
740
741 let set_name (na',x,y as pos) = function
742 | Name _ as na -> (na,x,y)
743 | Anonymous -> pos
744
745 let compute_implicit_statuses autoimps l =
746 let rec aux i = function
747 | _ :: autoimps, (_, Explicit) :: manualimps -> None :: aux (i+1) (autoimps, manualimps)
748 | pos :: autoimps, (na, MaxImplicit) :: manualimps ->
749 let imp = {
750 impl_pos = set_name pos na;
751 impl_expl = Manual;
752 impl_max = true;
753 impl_force = true;
754 } in
755 Some imp :: aux (i+1) (autoimps, manualimps)
756 | pos :: autoimps, (na, NonMaxImplicit) :: manualimps ->
757 let imps' = aux (i+1) (autoimps, manualimps) in
758 let max = set_maximality Error na i imps' false in
759 let imp = {
760 impl_pos = set_name pos na;
761 impl_expl = Manual;
762 impl_max = max;
763 impl_force = true;
764 } in
765 Some imp :: imps'
766 | autoimps, [] -> List.map (fun _ -> None) autoimps
767 | [], _::_ -> assert false
768 in aux 1 (autoimps, l)
769
770 let set_implicits local ref l =
771 let flags = !implicit_args in
772 let env = Global.env () in
773 let sigma = Evd.from_env env in
774 let t, _ = Typeops.type_of_global_in_context env ref in
775 let t = of_constr t in
776 let autoimpls = compute_implicits_names env sigma t in
777 let l' = match l with
778 | [] -> assert false
779 | [l] ->
780 [DefaultImpArgs, compute_implicit_statuses autoimpls l]
781 | _ ->
782 check_rigidity (is_rigid env sigma t);
783 (* Sort by number of implicits, decreasing *)
784 let is_implicit = function
785 | _, Explicit -> false
786 | _ -> true in
787 let l = List.map (fun imps -> (imps,List.count is_implicit imps)) l in
788 let l = List.sort (fun (_,n1) (_,n2) -> n2 - n1) l in
789 check_inclusion l;
790 let nargs = List.length autoimpls in
791 List.map (fun (imps,n) ->
792 (LessArgsThan (nargs-n),
793 compute_implicit_statuses autoimpls imps)) l in
794 let req =
795 if is_local local ref then ImplLocal
796 else ImplInteractive(flags,ImplManual (List.length autoimpls))
797 in
798 Lib.add_leaf (inImplicits (req,[ref,l']))
799
800 let extract_impargs_data impls =
801 let rec aux p = function
802 | (DefaultImpArgs, imps)::_ -> [None,imps]
803 | (LessArgsThan n, imps)::l -> (Some (p,n),imps) :: aux (n+1) l
804 | [] -> [] in
805 aux 0 impls
806
807 let make_implicits_list l = [DefaultImpArgs, l]
808
809 let rec drop_first_implicits p l =
810 if Int.equal p 0 then l else match l with
811 | _,[] as x -> x
812 | DefaultImpArgs,imp::impls ->
813 drop_first_implicits (p-1) (DefaultImpArgs,impls)
814 | LessArgsThan n,imp::impls ->
815 let n = if is_status_implicit imp then n else n-1 in
816 drop_first_implicits (p-1) (LessArgsThan n,impls)
817
818 let rec chop_and_adjust n l1 l2 =
819 if n = 0 then (List.rev l1, l2) else
820 match l2 with
821 | [] -> chop_and_adjust (n-1) (None :: l1) []
822 | a::l2 -> chop_and_adjust (n-1) (a :: l1) l2
823
824 let rec select_impargs_size n = function
825 | [] -> [] (* Tolerance for (DefaultImpArgs,[]) *)
826 | [_, impls] | (DefaultImpArgs, impls)::_ -> impls
827 | (LessArgsThan p, impls)::l ->
828 if n <= p then impls else select_impargs_size n l
829
830 let select_stronger_impargs = function
831 | [] -> [] (* Tolerance for (DefaultImpArgs,[]) *)
832 | (_,impls)::_ -> impls
833
834 let select_impargs_size_for_proj ~nexpectedparams ~ngivenparams ~nextraargs impls =
835 let split_implicit_params imps =
836 if List.is_empty imps then (nexpectedparams, [], []) else
837 let imps1, imps2 = chop_and_adjust nexpectedparams [] imps in
838 let imp, imps2 = match imps2 with imp :: imps2 -> [imp],imps2 | _ -> [], [] in
839 let nimps1 = nexpectedparams - List.count is_status_implicit imps1 in
840 (* Force the main argument to be explicit *)
841 (nimps1, imps1 @ [None], imps2)
842 in
843 let nallgivenargs = ngivenparams + nextraargs + 1 in
844 let little_enough_all_implicit = function
845 | (DefaultImpArgs, impls) -> Some (split_implicit_params impls)
846 | (LessArgsThan r, impls) when nallgivenargs <= r -> Some (split_implicit_params impls)
847 | _ -> None in
848 (* Compute the implicit signatures with little enough implicit to
849 match the number of arguments *)
850 let impls = List.map_filter little_enough_all_implicit impls in
851 (* Compute those which matches the number of parameters given *)
852 let impls' = List.filter (fun (nimps1,_,_) -> Int.equal nimps1 ngivenparams) impls in
853 match impls' with
854 | (_, imps1, imps2) :: _ -> Inl (imps1, imps2)
855 | [] ->
856 if Int.equal ngivenparams nexpectedparams then Inl ([], [])
857 else Inr (lazy (List.sort_uniq Int.compare (List.rev_map pi1 impls)))
858
859 let impargs_for_proj ~nexpectedparams ~nextraargs imps =
860 let imps1, imps2 = try List.chop nexpectedparams imps with Failure _ -> imps, [] in
861 let imp, imps2 = match imps2 with imp :: imps2 -> imp, imps2 | _ -> None, [] in
862 let imps2 = try List.firstn nextraargs imps2 with Failure _ -> [] in
863 imps1@[None], imps2