Debian Codegraph @

interp/constrintern.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 Pp
12 open CErrors
13 open Util
14 open CAst
15 open Names
16 open Nameops
17 open Namegen
18 open Constr
19 open Context
20 open Libnames
21 open Globnames
22 open Impargs
23 open Glob_term
24 open Glob_ops
25 open Patternops
26 open Pretyping
27 open Structures
28 open Cases
29 open Constrexpr
30 open Constrexpr_ops
31 open Notation_term
32 open Notation_ops
33 open Notation
34 open Inductiveops
35 open Context.Rel.Declaration
36 open NumTok
37
38
39 (** constr_expr -> glob_constr translation:
40 - it adds holes for implicit arguments
41 - it replaces notations by their value (scopes stuff are here)
42 - it recognizes global vars from local ones
43 - it prepares pattern matching problems (a pattern becomes a tree
44 where nodes are constructor/variable pairs and leafs are variables)
45
46 All that at once, fasten your seatbelt!
47 *)
48
49 (* To interpret implicits and arg scopes of variables in inductive
50 types and recursive definitions and of projection names in records *)
51
52 type var_internalization_type =
53 | Inductive
54 | Recursive
55 | Method
56 | Variable
57
58 type var_unique_id = string
59
60 let var_uid =
61 let count = ref 0 in
62 fun id -> incr count; Id.to_string id ^ ":" ^ string_of_int !count
63
64 type var_internalization_data = {
65 (* type of the "free" variable, for coqdoc, e.g. while typing the
66 constructor of JMeq, "JMeq" behaves as a variable of type Inductive *)
67 var_intern_typ : var_internalization_type;
68 (* signature of impargs of the variable *)
69 var_impls : Impargs.implicit_status list;
70 (* subscopes of the args of the variable *)
71 var_scopes : scope_name list list;
72 (* unique ID for coqdoc links *)
73 var_uid : var_unique_id;
74 }
75
76 let make_var_data var_intern_typ var_impls var_scopes var_uid =
77 {var_intern_typ; var_impls; var_scopes; var_uid}
78
79 type internalization_env = var_internalization_data Id.Map.t
80
81 type ltac_sign = {
82 ltac_vars : Id.Set.t;
83 ltac_bound : Id.Set.t;
84 ltac_extra : Genintern.Store.t;
85 }
86
87 (**********************************************************************)
88 (* Internalization errors *)
89
90 type internalization_error =
91 | VariableCapture of Id.t * Id.t
92 | IllegalMetavariable
93 | NotAConstructor of qualid
94 | UnboundFixName of bool * Id.t
95 | NonLinearPattern of Id.t
96 | BadPatternsNumber of int * int
97 | NotAProjection of qualid
98 | ProjectionsOfDifferentRecords of Structure.t * Structure.t
99
100 exception InternalizationError of internalization_error
101
102 let explain_variable_capture id id' =
103 Id.print id ++ str " is dependent in the type of " ++ Id.print id' ++
104 strbrk ": cannot interpret both of them with the same type"
105
106 let explain_illegal_metavariable =
107 str "Metavariables allowed only in patterns"
108
109 let explain_not_a_constructor qid =
110 str "Unknown constructor: " ++ pr_qualid qid
111
112 let explain_unbound_fix_name is_cofix id =
113 str "The name" ++ spc () ++ Id.print id ++
114 spc () ++ str "is not bound in the corresponding" ++ spc () ++
115 str (if is_cofix then "co" else "") ++ str "fixpoint definition"
116
117 let explain_non_linear_pattern id =
118 str "The variable " ++ Id.print id ++ str " is bound several times in pattern"
119
120 let explain_bad_patterns_number n1 n2 =
121 str "Expecting " ++ int n1 ++ str (String.plural n1 " pattern") ++
122 str " but found " ++ int n2
123
124 let inductive_of_record s =
125 let inductive = GlobRef.IndRef (s.Structure.name) in
126 Nametab.shortest_qualid_of_global Id.Set.empty inductive
127
128 let explain_field_not_a_projection field_id =
129 pr_qualid field_id ++ str ": Not a projection"
130
131 let explain_projections_of_diff_records record1 record2 =
132 let inductive1_id = inductive_of_record record1 in
133 let inductive2_id = inductive_of_record record2 in
134 str "This record contains fields of both " ++ pr_qualid inductive1_id ++
135 str " and " ++ pr_qualid inductive2_id
136
137 let explain_internalization_error e =
138 let pp = match e with
139 | VariableCapture (id,id') -> explain_variable_capture id id'
140 | IllegalMetavariable -> explain_illegal_metavariable
141 | NotAConstructor ref -> explain_not_a_constructor ref
142 | UnboundFixName (iscofix,id) -> explain_unbound_fix_name iscofix id
143 | NonLinearPattern id -> explain_non_linear_pattern id
144 | BadPatternsNumber (n1,n2) -> explain_bad_patterns_number n1 n2
145 | NotAProjection field_id -> explain_field_not_a_projection field_id
146 | ProjectionsOfDifferentRecords (inductive1_id, inductive2_id) ->
147 explain_projections_of_diff_records inductive1_id inductive2_id
148 in pp ++ str "."
149
150 let _ = CErrors.register_handler (function
151 | InternalizationError e ->
152 Some (explain_internalization_error e)
153 | _ -> None)
154
155 let error_bad_inductive_type ?loc ?info () =
156 user_err ?loc ?info (str
157 "This should be an inductive type applied to patterns.")
158
159 let error_parameter_not_implicit ?loc =
160 user_err ?loc (str
161 "The parameters do not bind in patterns;" ++ spc () ++ str
162 "they must be replaced by '_'.")
163
164 let error_ldots_var ?loc =
165 user_err ?loc (str "Special token " ++ Id.print ldots_var ++
166 str " is for use in the Notation command.")
167
168 (**********************************************************************)
169 (* Pre-computing the implicit arguments and arguments scopes needed *)
170 (* for interpretation *)
171
172 let parsing_explicit = ref false
173
174 let empty_internalization_env = Id.Map.empty
175
176 let compute_internalization_data env sigma ?silent id ty typ impl =
177 let impl = compute_implicits_with_manual env sigma ?silent typ (is_implicit_args()) impl in
178 make_var_data ty impl (compute_arguments_scope env sigma typ) (var_uid id)
179
180 let compute_internalization_env env sigma ?(impls=empty_internalization_env) ?force ty names =
181 let force = match force with None -> List.map (fun _ -> Id.Set.empty) names | Some l -> l in
182 let f force_ids = function {impl_pos=(na,_,_)} as impl ->
183 match na with
184 | Name id when Id.Set.mem id force_ids -> {impl with impl_force = false}
185 | _ -> impl in
186 List.fold_left4
187 (fun map id force_ids typ impl ->
188 let var_info = compute_internalization_data env sigma id ty typ impl in
189 let impls = List.map (Option.map (f force_ids)) var_info.var_impls in
190 Id.Map.add id {var_info with var_impls = impls} map)
191 impls names force
192
193 let implicits_of_decl_in_internalization_env id (int_env:internalization_env) =
194 let {var_impls=impls} = Id.Map.find id int_env in impls
195
196 (**********************************************************************)
197 (* Contracting "{ _ }" in notations *)
198
199 let rec wildcards ntn n =
200 if Int.equal n (String.length ntn) then []
201 else let l = spaces ntn (n+1) in if ntn.[n] == '_' then n::l else l
202 and spaces ntn n =
203 if Int.equal n (String.length ntn) then []
204 else if ntn.[n] == ' ' then wildcards ntn (n+1) else spaces ntn (n+1)
205
206 let expand_notation_string ntn n =
207 let pos = List.nth (wildcards ntn 0) n in
208 let hd = if Int.equal pos 0 then "" else String.sub ntn 0 pos in
209 let tl =
210 if Int.equal pos (String.length ntn) then ""
211 else String.sub ntn (pos+1) (String.length ntn - pos -1) in
212 hd ^ "{ _ }" ^ tl
213
214 (* This contracts the special case of "{ _ }" for sumbool, sumor notations *)
215 (* Remark: expansion of squash at definition is done in metasyntax.ml *)
216 let contract_curly_brackets ntn (l,ll,bl,bll) =
217 match ntn with
218 | InCustomEntry _,_ -> ntn,(l,ll,bl,bll)
219 | InConstrEntry, ntn ->
220 let ntn' = ref ntn in
221 let rec contract_squash n = function
222 | [] -> []
223 | { CAst.v = CNotation (None,(InConstrEntry,"{ _ }"),([a],[],[],[])) } :: l ->
224 ntn' := expand_notation_string !ntn' n;
225 contract_squash n (a::l)
226 | a :: l ->
227 a::contract_squash (n+1) l in
228 let l = contract_squash 0 l in
229 (* side effect; don't inline *)
230 (InConstrEntry,!ntn'),(l,ll,bl,bll)
231
232 let contract_curly_brackets_pat ntn (l,ll,bl) =
233 match ntn with
234 | InCustomEntry _,_ -> ntn,(l,ll,bl)
235 | InConstrEntry, ntn ->
236 let ntn' = ref ntn in
237 let rec contract_squash n = function
238 | [] -> []
239 | { CAst.v = CPatNotation (None,(InConstrEntry,"{ _ }"),([a],[],[]),[]) } :: l ->
240 ntn' := expand_notation_string !ntn' n;
241 contract_squash n (a::l)
242 | a :: l ->
243 a::contract_squash (n+1) l in
244 let l = contract_squash 0 l in
245 (* side effect; don't inline *)
246 (InConstrEntry,!ntn'),(l,ll,bl)
247
248 type local_univs = { bound : UnivNames.universe_binders; unb_univs : bool }
249
250 let empty_local_univs = { bound = UnivNames.empty_binders; unb_univs = false }
251
252 type abstraction_kind = AbsLambda | AbsPi
253
254 type intern_env = {
255 ids: Id.Set.t;
256 pattern_mode : bool;
257 strict_check: bool option;
258 (* None = not passed via ltac yet: works as "true" unless when interpreting
259 ltac:() in which case we assume the default Ltac value, that is "false" *)
260 local_univs: local_univs;
261 tmp_scope: Notation_term.tmp_scope_name list;
262 scopes: Notation_term.scope_name list;
263 impls: internalization_env;
264 binder_block_names: abstraction_kind option (* None = unknown *) option;
265 ntn_binding_ids: Id.Set.t; (* subset of ids that are notation variables *)
266 }
267
268 type pattern_intern_env = {
269 pat_scopes: Notation_term.subscopes;
270 (* ids = Some means accept local variables; this is useful for
271 terms as patterns parsed as patterns in notations *)
272 pat_ids: Id.Set.t option;
273 }
274
275 (**********************************************************************)
276 (* Remembering the parsing scope of variables in notations *)
277
278 let make_current_scope tmp scopes = match tmp, scopes with
279 | [], scopes -> scopes
280 | [tmp_scope], (sc :: _) when String.equal sc tmp_scope -> scopes
281 | tmp_scope, scopes -> tmp_scope @ scopes
282
283 let pr_scope_stack begin_of_sentence l =
284 let bstr x =
285 if begin_of_sentence then str (CString.capitalize_ascii x) else str x in
286 match l with
287 | [] -> bstr "the empty scope stack"
288 | [a] -> bstr "scope " ++ str a
289 | l -> bstr "scope stack " ++
290 str "[" ++ prlist_with_sep pr_comma str l ++ str "]"
291
292 let warn_inconsistent_scope =
293 CWarnings.create ~name:"inconsistent-scopes" ~category:CWarnings.CoreCategories.syntax
294 (fun (id,scopes1,scopes2) ->
295 (str "Argument " ++ Id.print id ++
296 strbrk " was previously inferred to be in " ++
297 pr_scope_stack false scopes1 ++
298 strbrk " but is here used in " ++
299 pr_scope_stack false scopes2 ++
300 strbrk ". " ++
301 pr_scope_stack true scopes1 ++
302 strbrk " will be used at parsing time unless you override it by" ++
303 strbrk " annotating the argument with an explicit scope of choice."))
304
305 let error_expect_binder_notation_type ?loc id =
306 user_err ?loc
307 (Id.print id ++
308 str " is expected to occur in binding position in the right-hand side.")
309
310 let set_notation_var_scope ?loc id (tmp_scope,subscopes as scopes) ntnbinders ntnvars =
311 try
312 let {Genintern.ntnvar_typ=typ} as status = Id.Map.find id ntnvars in
313 match typ with
314 | Notation_term.NtnInternTypeOnlyBinder -> error_expect_binder_notation_type ?loc id
315 | Notation_term.NtnInternTypeAny principal ->
316 let () = match status.ntnvar_scopes with
317 | None -> status.ntnvar_scopes <- Some scopes
318 | Some (tmp_scope', subscopes') ->
319 let s' = make_current_scope tmp_scope' subscopes' in
320 let s = make_current_scope tmp_scope subscopes in
321 if Option.is_empty principal && not (List.equal String.equal s' s) then
322 warn_inconsistent_scope ?loc (id,s',s)
323 in
324 let () = match status.ntnvar_binding_ids with
325 | None -> status.ntnvar_binding_ids <- Some ntnbinders
326 | Some ntnbinders' -> status.ntnvar_binding_ids <- Some (Id.Set.inter ntnbinders ntnbinders')
327 in
328 let () = match status.ntnvar_used with
329 | [] -> () (* not recording if notation var is used *)
330 | true :: _ -> () (* already marked used *)
331 | false :: rest -> status.ntnvar_used <- true :: rest
332 in
333 ()
334 with Not_found ->
335 (* Not in a notation *)
336 ()
337
338 let set_var_is_binder ?loc id ntnvars =
339 try
340 let status = Id.Map.find id ntnvars in
341 status.Genintern.ntnvar_used_as_binder <- true
342 with Not_found ->
343 (* Not in a notation *)
344 ()
345
346 let set_type_scope env = {env with tmp_scope = Notation.current_type_scope_names ()}
347
348 let reset_tmp_scope env = {env with tmp_scope = []}
349
350 let set_env_scopes env (scopt,subscopes) =
351 {env with tmp_scope = scopt; scopes = subscopes @ env.scopes}
352
353 let env_for_pattern env =
354 {pat_scopes = (env.tmp_scope, env.scopes); pat_ids = Some env.ids}
355
356 let mkGProd ?loc (na,bk,t) body = DAst.make ?loc @@ GProd (na, None, bk, t, body)
357 let mkGLambda ?loc (na,bk,t) body = DAst.make ?loc @@ GLambda (na, None, bk, t, body)
358
359 (**********************************************************************)
360 (* Utilities for binders *)
361
362 let warn_shadowed_implicit_name =
363 CWarnings.create ~name:"shadowed-implicit-name" ~category:CWarnings.CoreCategories.syntax
364 Pp.(fun na -> str "Making shadowed name of implicit argument accessible by position.")
365
366 let exists_name na l =
367 match na with
368 | Name id -> List.exists (function Some { impl_pos = (Name id', _, _) } -> Id.equal id id' | _ -> false) l
369 | _ -> false
370
371 let build_impls ?loc n bk na acc =
372 let impl_status max =
373 let na =
374 if exists_name na acc then begin warn_shadowed_implicit_name ?loc na; Anonymous end
375 else na in
376 Some {
377 impl_pos = (na, n, (*TODO, enhancement: compute dependency*) None);
378 impl_expl = Manual;
379 impl_max = max;
380 impl_force = true
381 }
382 in
383 match bk with
384 | NonMaxImplicit -> impl_status false :: acc
385 | MaxImplicit -> impl_status true :: acc
386 | Explicit -> None :: acc
387
388 let impls_binder_list =
389 let rec aux acc n = function
390 | (na,_,bk,None,_) :: binders -> aux (build_impls n bk na acc) (n+1) binders
391 | (na,_,bk,Some _,_) :: binders -> aux acc n binders
392 | [] -> (n,acc)
393 in aux []
394
395 let impls_type_list n ?(args = []) =
396 let rec aux acc n c = match DAst.get c with
397 | GProd (na,_,bk,_,c) -> aux (build_impls n bk na acc) (n+1) c
398 | _ -> List.rev acc
399 in aux args n
400
401 let impls_term_list n ?(args = []) =
402 let rec aux acc n c = match DAst.get c with
403 | GLambda (na,_,bk,_,c) -> aux (build_impls n bk na acc) (n+1) c
404 | GRec (fix_kind, nas, args, tys, bds) ->
405 let nb = match fix_kind with |GFix (_, n) -> n | GCoFix n -> n in
406 let n,acc' = List.fold_left (fun (n,acc) (na, _, bk, _, _) -> (n+1,build_impls n bk na acc)) (n,acc) args.(nb) in
407 aux acc' n bds.(nb)
408 |_ -> List.rev acc
409 in aux args n
410
411 (* Check if in binder "(x1 x2 .. xn : t)", none of x1 .. xn-1 occurs in t *)
412 let rec check_capture ty = let open CAst in function
413 | { loc; v = Name id } :: { v = Name id' } :: _ when occur_glob_constr id ty ->
414 Loc.raise ?loc (InternalizationError (VariableCapture (id,id')))
415 | _::nal ->
416 check_capture ty nal
417 | [] ->
418 ()
419
420 (** Status of the internalizer wrt "Arguments" of names *)
421
422 let restart_no_binders env =
423 { env with binder_block_names = None}
424 (* Not in relation with the "Arguments" of a name *)
425
426 let restart_prod_binders env =
427 { env with binder_block_names = Some (Some AbsPi) }
428 (* In a position binding a type to a name *)
429
430 let restart_lambda_binders env =
431 { env with binder_block_names = Some (Some AbsLambda) }
432 (* In a position binding a body to a name *)
433
434 let switch_prod_binders env =
435 match env.binder_block_names with
436 | Some o when o <> Some AbsLambda -> restart_prod_binders env
437 | _ -> restart_no_binders env
438 (* In a position switching to a type *)
439
440 let switch_lambda_binders env =
441 match env.binder_block_names with
442 | Some o when o <> Some AbsPi -> restart_lambda_binders env
443 | _ -> restart_no_binders env
444 (* In a position switching to a term *)
445
446 let slide_binders env =
447 match env.binder_block_names with
448 | Some o when o <> Some AbsPi -> restart_prod_binders env
449 | _ -> restart_no_binders env
450 (* In a position of cast *)
451
452 let binder_status_fun = {
453 no = (fun x -> x);
454 restart_prod = on_snd restart_prod_binders;
455 restart_lambda = on_snd restart_lambda_binders;
456 switch_prod = on_snd switch_prod_binders;
457 switch_lambda = on_snd switch_lambda_binders;
458 slide = on_snd slide_binders;
459 }
460
461 (* [test_kind_strict] rules out pattern which refers to global other
462 than constructors or variables; It is used in instances of notations *)
463
464 let test_kind_pattern_in_notation ?loc = function
465 | GlobRef.ConstructRef _ -> ()
466 (* We do not accept non constructors to be used as variables in
467 patterns *)
468 | GlobRef.ConstRef _ ->
469 user_err ?loc (str "Found a constant while a pattern was expected.")
470 | GlobRef.IndRef _ ->
471 user_err ?loc (str "Found an inductive type while a pattern was expected.")
472 | GlobRef.VarRef _ ->
473 (* we accept a section variable name to be used as pattern variable *)
474 raise Not_found
475
476 let test_kind_ident_in_notation ?loc = function
477 | GlobRef.ConstructRef _ ->
478 user_err ?loc (str "Found a constructor while a variable name was expected.")
479 | GlobRef.ConstRef _ ->
480 user_err ?loc (str "Found a constant while a variable name was expected.")
481 | GlobRef.IndRef _ ->
482 user_err ?loc (str "Found an inductive type while a variable name was expected.")
483 | GlobRef.VarRef _ ->
484 (* we accept a section variable name to be used as pattern variable *)
485 raise Not_found
486
487 (* [test_kind_tolerant] allow global reference names to be used as pattern variables *)
488
489 let test_kind_tolerant ?loc = function
490 | GlobRef.ConstructRef _ -> ()
491 | GlobRef.ConstRef _ | GlobRef.IndRef _ | GlobRef.VarRef _ ->
492 (* A non-constructor global reference in a pattern is seen as a variable *)
493 raise Not_found
494
495 (**)
496
497 let locate_if_hole ?loc na c = match DAst.get c with
498 | GHole (GNamedHole _) -> c
499 | GHole _ ->
500 (try match na with
501 | Name id -> glob_constr_of_notation_constr ?loc
502 (Reserve.find_reserved_type id)
503 | Anonymous -> raise Not_found
504 with Not_found -> DAst.make ?loc @@ GHole (GBinderType na))
505 | _ -> c
506
507 let pure_push_name_env (id,implargs,is_ntn_id) env =
508 {env with
509 ids = Id.Set.add id env.ids;
510 impls = Id.Map.add id implargs env.impls;
511 ntn_binding_ids = if is_ntn_id then Id.Set.add id env.ntn_binding_ids else env.ntn_binding_ids;
512 }
513
514 let push_name_env ~dump ntnvars implargs env =
515 let open CAst in
516 function
517 | { loc; v = Anonymous } ->
518 env
519 | { loc; v = Name id } ->
520 if Id.Map.is_empty ntnvars && Id.equal id ldots_var
521 then error_ldots_var ?loc;
522 set_var_is_binder ?loc id ntnvars;
523 let uid = var_uid id in
524 if dump then Dumpglob.dump_binding ?loc uid;
525 pure_push_name_env (id,(make_var_data Variable implargs [] uid),Id.Map.mem id ntnvars) env
526
527 let remember_binders_impargs env bl =
528 List.map_filter (fun (na,_,_,_,_) ->
529 match na with
530 | Anonymous -> None
531 | Name id -> Some (id,Id.Map.find id env.impls,Id.Set.mem id env.ntn_binding_ids)) bl
532
533 let restore_binders_impargs env l =
534 List.fold_right pure_push_name_env l env
535
536 let warn_ignoring_unexpected_implicit_binder_declaration =
537 CWarnings.create ~name:"unexpected-implicit-declaration" ~category:CWarnings.CoreCategories.syntax
538 Pp.(fun () -> str "Ignoring implicit binder declaration in unexpected position.")
539
540 let check_implicit_meaningful ?loc k env =
541 if k <> Explicit && env.binder_block_names = None then
542 (warn_ignoring_unexpected_implicit_binder_declaration ?loc (); Explicit)
543 else
544 k
545
546 let intern_generalized_binder ~dump intern_type ntnvars
547 env {loc;v=na} b' t ty =
548 let ids = (match na with Anonymous -> fun x -> x | Name na -> Id.Set.add na) env.ids in
549 let ty, ids' =
550 if t then ty, ids
551 else Implicit_quantifiers.implicit_application ids ty
552 in
553 let ty' = intern_type {env with ids = ids; strict_check = Some false} ty in
554 let fvs = Implicit_quantifiers.generalizable_vars_of_glob_constr ~bound:ids ~allowed:ids' ty' in
555 let env' = List.fold_left
556 (fun env {loc;v=x} -> push_name_env ~dump ntnvars [](*?*) env (make ?loc @@ Name x))
557 env fvs in
558 let b' = check_implicit_meaningful ?loc b' env in
559 let bl = List.map
560 CAst.(map (fun id ->
561 (Name id, MaxImplicit, DAst.make ?loc @@ GHole (GBinderType (Name id)))))
562 fvs
563 in
564 let na = match na with
565 | Anonymous ->
566 let id =
567 match ty with
568 | { v = CApp ({ v = CRef (qid,_) }, _) } when qualid_is_ident qid ->
569 qualid_basename qid
570 | _ -> default_non_dependent_ident
571 in
572 let ids' = List.fold_left (fun ids' lid -> Id.Set.add lid.CAst.v ids') ids' fvs in
573 let id =
574 Implicit_quantifiers.make_fresh ids' (Global.env ()) id
575 in
576 Name id
577 | _ -> na
578 in
579 let impls = impls_type_list 1 ty' in
580 (push_name_env ~dump ntnvars impls env' (make ?loc na),
581 (make ?loc (na,b',ty')) :: List.rev bl)
582
583 let intern_assumption ~dump intern ntnvars env nal bk ty =
584 let intern_type env = intern (restart_prod_binders (set_type_scope env)) in
585 match bk with
586 | Default k ->
587 let ty = intern_type env ty in
588 check_capture ty nal;
589 let impls = impls_type_list 1 ty in
590 List.fold_left
591 (fun (env, bl) ({loc;v=na} as locna) ->
592 let k = check_implicit_meaningful ?loc k env in
593 (push_name_env ~dump ntnvars impls env locna,
594 (make ?loc (na,k,locate_if_hole ?loc na ty))::bl))
595 (env, []) nal
596 | Generalized (b',t) ->
597 let env, b = intern_generalized_binder ~dump intern_type ntnvars env (List.hd nal) b' t ty in
598 env, b
599
600 let glob_local_binder_of_extended = DAst.with_loc_val (fun ?loc -> function
601 | GLocalAssum (na,r,bk,t) -> (na,None,bk,None,t)
602 | GLocalDef (na,r,c,Some t) -> (na,None,Explicit,Some c,t)
603 | GLocalDef (na,r,c,None) ->
604 let t = DAst.make ?loc @@ GHole (GBinderType na) in
605 (na,None,Explicit,Some c,t)
606 | GLocalPattern (_,_,_,_) ->
607 Loc.raise ?loc (Gramlib.Grammar.ParseError "Pattern with quote not allowed here")
608 )
609
610 let intern_cases_pattern_fwd = ref (fun _ -> failwith "intern_cases_pattern_fwd")
611
612 let intern_letin_binder ~dump intern ntnvars env (({loc;v=na} as locna),def,ty) =
613 let term = intern (reset_tmp_scope (restart_lambda_binders env)) def in
614 let ty = Option.map (intern (set_type_scope (restart_prod_binders env))) ty in
615 let impls = impls_term_list 1 term in
616 (push_name_env ~dump ntnvars impls env locna,
617 (na,term,ty))
618
619 let intern_cases_pattern_as_binder ~dump intern test_kind ntnvars env bk (CAst.{v=p;loc} as pv) =
620 let p,t,tmp_scope = match p with
621 | CPatCast (p, t) -> (p, Some t, (* Redone later, not nice: *) Notation.compute_glob_type_scope (intern (set_type_scope env) t))
622 | _ -> (pv, None, []) in
623 let il,disjpat =
624 let (il, subst_disjpat) = !intern_cases_pattern_fwd test_kind ntnvars (env_for_pattern {env with tmp_scope}) p in
625 let substl,disjpat = List.split subst_disjpat in
626 if not (List.for_all (fun subst -> Id.Map.equal Id.equal subst Id.Map.empty) substl) then
627 user_err ?loc (str "Unsupported nested \"as\" clause.");
628 il,disjpat
629 in
630 let na = alias_of_pat (List.hd disjpat) in
631 let env = List.fold_right (fun {loc;v=id} env -> push_name_env ~dump ntnvars [] env (make ?loc @@ Name id)) il env in
632 let ienv = Name.fold_right Id.Set.remove na env.ids in
633 let id = Namegen.next_name_away_with_default "pat" na ienv in
634 let na = make ?loc @@ Name id in
635 let t = match t with
636 | Some t -> t
637 | None -> CAst.make ?loc @@ CHole (Some (GBinderType na.v)) in
638 let _, bl' = intern_assumption ~dump intern ntnvars env [na] (Default bk) t in
639 let {v=(_,bk,t)} = List.hd bl' in
640 let il = List.map (fun id -> id.v) il in
641 env,((disjpat,il),id),bk,t
642
643 let intern_local_binder_aux ~dump intern ntnvars (env,bl) = function
644 | CLocalAssum(nal,_,bk,ty) ->
645 let env, bl' = intern_assumption ~dump intern ntnvars env nal bk ty in
646 let bl' = List.map (fun {loc;v=(na,c,t)} -> DAst.make ?loc @@ GLocalAssum (na,None,c,t)) bl' in
647 env, bl' @ bl
648 | CLocalDef( {loc; v=na} as locna,_,def,ty) ->
649 let env,(na,def,ty) = intern_letin_binder ~dump intern ntnvars env (locna,def,ty) in
650 env, (DAst.make ?loc @@ GLocalDef (na,None,def,ty)) :: bl
651 | CLocalPattern p ->
652 let env, ((disjpat,il),id),bk,t = intern_cases_pattern_as_binder ~dump intern test_kind_tolerant ntnvars env Explicit p in
653 (env, (DAst.make ?loc:p.CAst.loc @@ GLocalPattern((disjpat,il),id,bk,t)) :: bl)
654
655 let intern_generalization intern env ntnvars loc bk c =
656 let c = intern {env with strict_check = Some false} c in
657 let fvs = Implicit_quantifiers.generalizable_vars_of_glob_constr ~bound:env.ids c in
658 let env', c' =
659 let abs =
660 let pi =
661 match Notation.current_type_scope_names () with
662 | [] -> false
663 | type_scopes ->
664 let is_type_scope = match env.tmp_scope with
665 | [] -> false
666 | scl -> List.equal String.equal scl type_scopes
667 in
668 is_type_scope ||
669 List.exists (fun sc -> String.List.mem sc env.scopes) type_scopes
670 in
671 if pi then
672 (fun {loc=loc';v=id} acc ->
673 DAst.make ?loc:(Loc.merge_opt loc' loc) @@
674 GProd (Name id, None, bk, DAst.make ?loc:loc' @@ GHole (GBinderType (Name id)), acc))
675 else
676 (fun {loc=loc';v=id} acc ->
677 DAst.make ?loc:(Loc.merge_opt loc' loc) @@
678 GLambda (Name id, None, bk, DAst.make ?loc:loc' @@ GHole (GBinderType (Name id)), acc))
679 in
680 List.fold_right (fun ({loc;v=id} as lid) (env, acc) ->
681 let env' = push_name_env ~dump:true ntnvars [] env CAst.(make @@ Name id) in
682 (env', abs lid acc)) fvs (env,c)
683 in c'
684
685 let rec expand_binders ?loc mk bl c =
686 match bl with
687 | [] -> c
688 | b :: bl ->
689 match DAst.get b with
690 | GLocalDef (n, r, b, oty) ->
691 expand_binders ?loc mk bl (DAst.make ?loc @@ GLetIn (n, r, b, oty, c))
692 | GLocalAssum (n, _, bk, t) ->
693 expand_binders ?loc mk bl (mk ?loc (n,bk,t) c)
694 | GLocalPattern ((disjpat,ids), id, bk, ty) ->
695 let tm = DAst.make ?loc (GVar id) in
696 (* Distribute the disjunctive patterns over the shared right-hand side *)
697 let eqnl = List.map (fun pat -> CAst.make ?loc (ids,[pat],c)) disjpat in
698 let c = DAst.make ?loc @@ GCases (LetPatternStyle, None, [tm,(Anonymous,None)], eqnl) in
699 expand_binders ?loc mk bl (mk ?loc (Name id,Explicit,ty) c)
700
701 (**********************************************************************)
702 (* Syntax extensions *)
703
704 let check_not_notation_variable f ntnvars =
705 (* Check bug #4690 *)
706 match DAst.get f with
707 | GVar id when Id.Map.mem id ntnvars ->
708 user_err (str "Prefix @ is not applicable to notation variables.")
709 | _ ->
710 ()
711
712 let option_mem_assoc id = function
713 | Some (id',c) -> Id.equal id id'
714 | None -> false
715
716 let find_fresh_name renaming (terms,termlists,binders,binderlists) avoid id =
717 let fold1 _ (c, _) accu = Id.Set.union (free_vars_of_constr_expr c) accu in
718 let fold2 _ (l, _) accu =
719 let fold accu c = Id.Set.union (free_vars_of_constr_expr c) accu in
720 List.fold_left fold accu l
721 in
722 let fold3 _ x accu = Id.Set.add x accu in
723 let fvs1 = Id.Map.fold fold1 terms avoid in
724 let fvs2 = Id.Map.fold fold2 termlists fvs1 in
725 let fvs3 = Id.Map.fold fold3 renaming fvs2 in
726 (* TODO binders *)
727 next_ident_away_from id (fun id -> Id.Set.mem id fvs3)
728
729 let is_patvar c =
730 match DAst.get c with
731 | PatVar _ -> true
732 | _ -> false
733
734 let is_patvar_store store pat =
735 match DAst.get pat with
736 | PatVar na -> ignore(store (CAst.make ?loc:pat.loc na)); true
737 | _ -> false
738
739 let out_patvar = CAst.map_with_loc (fun ?loc -> function
740 | CPatAtom (Some qid) when qualid_is_ident qid ->
741 Name (qualid_basename qid)
742 | CPatAtom None -> Anonymous
743 | _ -> assert false)
744
745 let canonize_type = function
746 | None -> None
747 | Some t as t' ->
748 match DAst.get t with
749 | GHole (GBinderType _) -> None
750 | _ -> t'
751
752 let set_type ty1 ty2 =
753 match canonize_type ty1, canonize_type ty2 with
754 (* Not a meta-binding binder, we use the type given in the notation *)
755 | _, None -> ty1
756 (* A meta-binding binder meta-bound to a possibly-typed pattern *)
757 (* the binder is supposed to come w/o an explicit type in the notation *)
758 | None, Some _ -> ty2
759 | Some ty1, Some t2 ->
760 (* An explicitly typed meta-binding binder, not supposed to be a pattern; checked in interp_notation *)
761 user_err ?loc:t2.CAst.loc Pp.(str "Unexpected type constraint in notation already providing a type constraint.")
762
763 let cook_pattern ((disjpat, ids), id) =
764 let store,get = set_temporary_memory () in
765 let pat, na = match disjpat with
766 | [pat] when is_patvar_store store pat -> let na = get () in None, na.v
767 | _ -> Some ((ids,disjpat),id), Name id in
768 pat, na
769
770 let extract_pattern_from_binder b =
771 match DAst.get b with
772 | GLocalDef _ -> user_err ?loc:b.CAst.loc (str "Local definitions not supported here.")
773 | GLocalAssum (na, _, bk, t) -> None, na, bk, t
774 | GLocalPattern (patl, id, bk, ty) ->
775 let pat, na = cook_pattern (patl, id) in
776 pat, na, bk, ty
777
778 let traverse_binder intern_pat ntnvars (terms,_,binders,_ as subst) binderopt avoid (renaming,env) na ty =
779 match na with
780 | Anonymous -> (renaming,env), None, Anonymous, Explicit, set_type ty None
781 | Name id ->
782 let test_kind = test_kind_tolerant in
783 try
784 (* We instantiate binder name with patterns which may be parsed as terms *)
785 let pat = coerce_to_cases_pattern_expr (fst (Id.Map.find id terms)) in
786 let env,pat,bk,t = intern_pat test_kind ntnvars env Explicit pat in
787 let pat, na = cook_pattern pat in
788 (renaming,env), pat, na, bk, set_type ty (Some t)
789 with Not_found ->
790 try
791 (* Trying to associate a pattern *)
792 let (pat,bk),(onlyident,scopes) = Id.Map.find id binders in
793 let env = set_env_scopes env scopes in
794 if onlyident then
795 (* Do not try to interpret a variable as a constructor *)
796 let na = out_patvar pat in
797 let env = push_name_env ~dump:true ntnvars [] env na in
798 let ty' = DAst.make @@ GHole (GBinderType na.CAst.v) in
799 (renaming,env), None, na.v, bk, set_type ty (Some ty')
800 else
801 (* Interpret as a pattern *)
802 let env,pat,bk,t = intern_pat test_kind ntnvars env bk pat in
803 let pat, na = cook_pattern pat in
804 (renaming,env), pat, na, bk, set_type ty (Some t)
805 with Not_found ->
806 if option_mem_assoc id binderopt then
807 let binder = snd (Option.get binderopt) in
808 let pat, na, bk, t = extract_pattern_from_binder binder in
809 (renaming,env), pat, na, bk, set_type ty (Some t)
810 else
811 (* Binders not bound in the notation do not capture variables *)
812 (* outside the notation (i.e. in the substitution) *)
813 let id' = find_fresh_name renaming subst avoid id in
814 let renaming = Id.Map.add id id' renaming in
815 (renaming,env), None, Name id', Explicit, set_type ty None
816
817 type binder_action =
818 | AddLetIn of lname * constr_expr * constr_expr option
819 | AddTermIter of (constr_expr * subscopes) Names.Id.Map.t
820 | AddPreBinderIter of Id.t * local_binder_expr (* A binder to be internalized *)
821 | AddBinderIter of Id.t * extended_glob_local_binder (* A binder already internalized - used for generalized binders *)
822 | AddNList (* Insert a ".. term .." block *)
823
824 let dmap_with_loc f n =
825 CAst.map_with_loc (fun ?loc c -> f ?loc (DAst.get_thunk c)) n
826
827 let error_cannot_coerce_wildcard_term ?loc () =
828 user_err ?loc Pp.(str "Cannot turn \"_\" into a term.")
829
830 let error_cannot_coerce_disjunctive_pattern_term ?loc () =
831 user_err ?loc Pp.(str "Cannot turn a disjunctive pattern into a term.")
832
833 let terms_of_binders bl =
834 let rec term_of_pat pt = dmap_with_loc (fun ?loc -> function
835 | PatVar (Name id) -> CRef (qualid_of_ident id, None)
836 | PatVar (Anonymous) -> error_cannot_coerce_wildcard_term ?loc ()
837 | PatCstr (c,l,_) ->
838 let qid = qualid_of_path ?loc (Nametab.path_of_global (GlobRef.ConstructRef c)) in
839 let hole = CAst.make ?loc @@ CHole (None) in
840 let params = List.make (Inductiveops.inductive_nparams (Global.env()) (fst c)) hole in
841 CAppExpl ((qid,None),params @ List.map term_of_pat l)) pt in
842 let rec extract_variables l = match l with
843 | bnd :: l ->
844 let loc = bnd.loc in
845 begin match DAst.get bnd with
846 | GLocalAssum (Name id,_,_,_) -> (CAst.make ?loc @@ CRef (qualid_of_ident ?loc id, None)) :: extract_variables l
847 | GLocalDef (Name id,_,_,_) -> extract_variables l
848 | GLocalDef (Anonymous,_,_,_)
849 | GLocalAssum (Anonymous,_,_,_) -> user_err Pp.(str "Cannot turn \"_\" into a term.")
850 | GLocalPattern (([u],_),_,_,_) -> term_of_pat u :: extract_variables l
851 | GLocalPattern ((_,_),_,_,_) -> error_cannot_coerce_disjunctive_pattern_term ?loc ()
852 end
853 | [] -> [] in
854 extract_variables bl
855
856 let flatten_generalized_binders_if_any y l =
857 match List.rev l with
858 | [] -> assert false
859 | l ->
860 (* if l has more than one element, this means we had a generalized binder *)
861 let select_iter a =
862 match DAst.get a with
863 | GLocalAssum (Name id,_,_,_) when Id.equal id ldots_var -> AddNList
864 | _ -> AddBinderIter (y,a) in
865 List.map select_iter l
866
867 let flatten_binders bl =
868 let dispatch = function
869 | CLocalAssum (nal,r,bk,t) -> List.map (fun na -> CLocalAssum ([na],r,bk,t)) nal
870 | a -> [a] in
871 List.flatten (List.map dispatch bl)
872
873 let rec adjust_env env = function
874 (* We need to adjust scopes, binder blocks ... to the env expected
875 at the recursive occurrence; We do an underapproximation... *)
876 | NProd (_,_,c) -> adjust_env (switch_prod_binders env) c
877 | NLambda (_,_,c) -> adjust_env (switch_lambda_binders env) c
878 | NLetIn (_,_,_,c) -> adjust_env env c
879 | NVar id when Id.equal id ldots_var -> env
880 | NCast (c,_,_) -> adjust_env env c
881 | NApp _ -> restart_no_binders env
882 | NVar _ | NRef _ | NHole _ | NGenarg _ | NCases _ | NLetTuple _ | NIf _
883 | NRec _ | NSort _ | NProj _ | NInt _ | NFloat _ | NString _ | NArray _
884 | NList _ | NBinderList _ -> env (* to be safe, but restart should be ok *)
885
886 let subst_var loc intern_pat intern ntnvars binders (terms, binderopt, _terminopt) (renaming, env) id =
887 (* subst remembers the delimiters stack in the interpretation *)
888 (* of the notations *)
889 try
890 let (a,scopes) = Id.Map.find id terms in
891 intern (set_env_scopes env scopes) a
892 with Not_found ->
893 try
894 let (pat,bk),(onlyident,scopes) = Id.Map.find id binders in
895 let env = set_env_scopes env scopes in
896 let test_kind =
897 if onlyident then test_kind_ident_in_notation
898 else test_kind_pattern_in_notation in
899 let env,((disjpat,ids),id),bk,_ty = intern_pat test_kind ntnvars env bk pat in
900 (* TODO: use cast? *)
901 match disjpat with
902 | [pat] -> glob_constr_of_cases_pattern (Global.env()) pat
903 | _ -> user_err Pp.(str "Cannot turn a disjunctive pattern into a term.")
904 with Not_found ->
905 try
906 match binderopt with
907 | Some (x,binder) when Id.equal x id ->
908 let terms = terms_of_binders [binder] in
909 assert (List.length terms = 1);
910 intern env (List.hd terms)
911 | _ -> raise Not_found
912 with Not_found ->
913 DAst.make ?loc (
914 try
915 GVar (Id.Map.find id renaming)
916 with Not_found ->
917 (* Happens for local notation joint with inductive/fixpoint defs *)
918 GVar id)
919
920 let instantiate_notation_constr loc intern intern_pat ntnvars subst infos c =
921 let (terms,termlists,binders,binderlists) = subst in
922 (* when called while defining a notation, avoid capturing the private binders
923 of the expression by variables bound by the notation (see #3892) *)
924 let avoid = Id.Map.domain ntnvars in
925 let rec aux (terms,binderopt,iteropt as subst') (renaming,env) c =
926 let subinfos = renaming,{env with tmp_scope = []} in
927 match c with
928 | NVar id when Id.equal id ldots_var ->
929 (* apply the pending sequence of letin, term iterator instances,
930 binder iterator instances, and eventually terminator *)
931 let rec aux_letin env = function
932 | [],terminator,_ -> aux (terms,None,None) (renaming,env) terminator
933 | AddPreBinderIter (y,binder)::rest,terminator,iter ->
934 let env,binders = intern_local_binder_aux ~dump:true intern ntnvars (adjust_env env iter,[]) binder in
935 let binders = flatten_generalized_binders_if_any y binders in
936 aux_letin env (binders@rest,terminator,iter)
937 | AddBinderIter (y,binder)::rest,terminator,iter ->
938 (* [y] is the placeholder for the [binder] in [iter] *)
939 aux (terms,Some (y,binder),Some (rest,terminator,iter)) (renaming,env) iter
940 | AddTermIter nterms::rest,terminator,iter ->
941 (* This time, the variable [y] is the placeholder for the [binder] in [iter] *)
942 aux (nterms,None,Some (rest,terminator,iter)) (renaming,env) iter
943 | AddLetIn (na,c,t)::rest,terminator,iter ->
944 let env,(na,c,t) = intern_letin_binder ~dump:true intern ntnvars (adjust_env env iter) (na,c,t) in
945 DAst.make ?loc (GLetIn (na,None,c,t,aux_letin env (rest,terminator,iter)))
946 | AddNList::rest,terminator,iter ->
947 DAst.make ?loc (GApp (DAst.make ?loc (GVar ldots_var), [aux_letin env (rest,terminator,iter)]))
948 in
949 aux_letin env (Option.get iteropt)
950 | NVar id -> subst_var loc intern_pat intern ntnvars binders subst' (renaming, env) id
951 | NList (x,y,iter,terminator,revert) ->
952 let l,(scopt,subscopes) =
953 (* All elements of the list are in scopes (scopt,subscopes) *)
954 try
955 let l,scopes = Id.Map.find x termlists in
956 (if revert then List.rev l else l),scopes
957 with Not_found ->
958 try
959 let (bl,(scopt,subscopes)) = Id.Map.find x binderlists in
960 let env,bl' = List.fold_left (intern_local_binder_aux ~dump:true intern ntnvars) (env,[]) bl in
961 terms_of_binders (if revert then bl' else List.rev bl'),([],[])
962 with Not_found ->
963 anomaly (Pp.str "Inconsistent substitution of recursive notation.") in
964 let select_iter a =
965 match a.CAst.v with
966 | CRef (qid,None) when qualid_is_ident qid && Id.equal (qualid_basename qid) ldots_var -> AddNList
967 | _ -> AddTermIter (Id.Map.add y (a,(scopt,subscopes)) terms) in
968 let l = List.map select_iter l in
969 aux (terms,None,Some (l,terminator,iter)) subinfos (NVar ldots_var)
970 | NHole (knd) ->
971 let knd = match knd with
972 | GBinderType (Name id as na) ->
973 let na =
974 try (coerce_to_name (fst (Id.Map.find id terms))).v
975 with Not_found ->
976 try Name (Id.Map.find id renaming)
977 with Not_found -> na
978 in
979 GBinderType na
980 | _ -> knd
981 in
982 DAst.make ?loc @@ GHole (knd)
983 | NGenarg arg ->
984 let glob_of_term (c, scopes) =
985 let nenv = set_env_scopes env scopes in
986 let gc = intern nenv c in
987 gc
988 in
989 let glob_of_binder ((c,_bk), (onlyident,(tmp_scope,subscopes))) =
990 let nenv = {env with tmp_scope; scopes = subscopes @ env.scopes} in
991 let test_kind =
992 if onlyident then test_kind_ident_in_notation
993 else test_kind_pattern_in_notation in
994 let _,((disjpat,_),_),_,_ty = intern_pat test_kind ntnvars nenv Explicit c in
995 (* TODO: use cast? *)
996 match disjpat with
997 | [pat] -> (glob_constr_of_cases_pattern (Global.env()) pat)
998 | _ -> error_cannot_coerce_disjunctive_pattern_term ?loc:c.loc ()
999 in
1000 let get_glob id =
1001 match Id.Map.find_opt id terms with
1002 | Some term -> Some (glob_of_term term)
1003 | None -> match Id.Map.find_opt id binders with
1004 | Some binder -> Some (glob_of_binder binder)
1005 | None -> None
1006 in
1007 let arg = Genintern.generic_substitute_notation ntnvars get_glob arg in
1008 DAst.make ?loc @@ GGenarg arg
1009 | NBinderList (x,y,iter,terminator,revert) ->
1010 (try
1011 (* All elements of the list are in scopes (scopt,subscopes) *)
1012 let (bl,(scopt,subscopes)) = Id.Map.find x binderlists in
1013 (* We flatten binders so that we can interpret them at substitution time *)
1014 let bl = flatten_binders bl in
1015 let bl = if revert then List.rev bl else bl in
1016 (* We isolate let-ins which do not contribute to the repeated pattern *)
1017 let l = List.map (function | CLocalDef (na,_,c,t) -> AddLetIn (na,c,t)
1018 | binder -> AddPreBinderIter (y,binder)) bl in
1019 (* We stack the binders to iterate or let-ins to insert *)
1020 aux (terms,None,Some (l,terminator,iter)) subinfos (NVar ldots_var)
1021 with Not_found ->
1022 anomaly (Pp.str "Inconsistent substitution of recursive notation."))
1023 | NProd (Name id, None, c') when option_mem_assoc id binderopt ->
1024 let binder = snd (Option.get binderopt) in
1025 expand_binders ?loc mkGProd [binder] (aux subst' (renaming,env) c')
1026 | NLambda (Name id, None, c') when option_mem_assoc id binderopt ->
1027 let binder = snd (Option.get binderopt) in
1028 expand_binders ?loc mkGLambda [binder] (aux subst' (renaming,env) c')
1029 | t ->
1030 glob_constr_of_notation_constr_with_binders ?loc
1031 (traverse_binder intern_pat ntnvars subst binderopt avoid) (aux subst') ~h:binder_status_fun subinfos t
1032 in aux (terms,None,None) infos c
1033
1034 (* Turning substitution coming from parsing and based on production
1035 into a substitution for interpretation and based on binding/constr
1036 distinction *)
1037
1038 let cases_pattern_of_id {loc;v=id} =
1039 CAst.make ?loc (CPatAtom (Some (qualid_of_ident ?loc id)))
1040
1041 let cases_pattern_of_name {loc;v=na} =
1042 let atom = match na with Name id -> Some (qualid_of_ident ?loc id) | Anonymous -> None in
1043 CAst.make ?loc (CPatAtom atom)
1044
1045 let cases_pattern_of_binder_as_constr a = function
1046 | AsAnyPattern | AsStrictPattern -> coerce_to_cases_pattern_expr a
1047 | AsIdent -> cases_pattern_of_id (coerce_to_id a)
1048 | AsName -> cases_pattern_of_name (coerce_to_name a)
1049
1050 let is_onlyident = function
1051 | AsIdent | AsName -> true
1052 | AsAnyPattern | AsStrictPattern -> false
1053
1054 let split_by_type ids (subst : constr_notation_substitution) =
1055 let bind id scl l s =
1056 match l with
1057 | [] -> assert false
1058 | a::l -> l, Id.Map.add id (a,scl) s in
1059 let (terms,termlists,binders,binderlists),subst =
1060 List.fold_left (fun ((terms,termlists,binders,binderlists),(terms',termlists',binders',binderlists')) (id,((_,scl),_,typ)) ->
1061 match typ with
1062 | NtnTypeConstr ->
1063 let terms,terms' = bind id scl terms terms' in
1064 (terms,termlists,binders,binderlists),(terms',termlists',binders',binderlists')
1065 | NtnTypeBinder ntn_binder_kind ->
1066 let onlyident,a,terms,binders =
1067 match ntn_binder_kind with
1068 | NtnBinderParsedAsConstr k ->
1069 let a,terms = List.sep_first terms in
1070 is_onlyident k, (cases_pattern_of_binder_as_constr a k, Explicit), terms, binders
1071 | NtnBinderParsedAsBinder ->
1072 let a,binders = List.sep_first binders in
1073 false, a, terms, binders
1074 | NtnBinderParsedAsSomeBinderKind k ->
1075 let a,binders = List.sep_first binders in
1076 is_onlyident k, a, terms, binders
1077 in
1078 let binders' = Id.Map.add id (a,(onlyident,scl)) binders' in
1079 (terms,termlists,binders,binderlists),(terms',termlists',binders',binderlists')
1080 | NtnTypeConstrList ->
1081 let termlists,termlists' = bind id scl termlists termlists' in
1082 (terms,termlists,binders,binderlists),(terms',termlists',binders',binderlists')
1083 | NtnTypeBinderList ntn_binder_kind ->
1084 let l,termlists,binderlists =
1085 match ntn_binder_kind with
1086 | NtnBinderParsedAsConstr k ->
1087 let l,termlists = List.sep_first termlists in
1088 List.map (fun a -> CLocalPattern (cases_pattern_of_binder_as_constr a k)) l, termlists, binderlists
1089 | NtnBinderParsedAsBinder | NtnBinderParsedAsSomeBinderKind _ ->
1090 let l,binderlists = List.sep_first binderlists in
1091 l, termlists, binderlists
1092 in
1093 let binderlists' = Id.Map.add id (l,scl) binderlists' in
1094 (terms,termlists,binders,binderlists),(terms',termlists',binders',binderlists'))
1095 (subst,(Id.Map.empty,Id.Map.empty,Id.Map.empty,Id.Map.empty)) ids in
1096 assert (terms = [] && termlists = [] && binders = [] && binderlists = []);
1097 subst
1098
1099 let split_by_type_pat ?loc ids subst =
1100 let bind id (_,scopes) l s =
1101 match l with
1102 | [] -> assert false
1103 | a::l -> l, Id.Map.add id (a,scopes) s in
1104 let bind_binders id (_,scopes) l s =
1105 match l with
1106 | [] -> assert false
1107 | (a,Explicit)::l -> l, Id.Map.add id (a,scopes) s
1108 | (a,(MaxImplicit|NonMaxImplicit))::l -> user_err (str "Implicit arguments not supported.") (* shouldn't arrive *)
1109 in
1110 let (terms,termlists,binders),subst =
1111 List.fold_left (fun ((terms,termlists,binders),(terms',termlists')) (id,(scl,_,typ)) ->
1112 match typ with
1113 | NtnTypeConstr | NtnTypeBinder (NtnBinderParsedAsConstr _) ->
1114 let terms,terms' = bind id scl terms terms' in
1115 (terms,termlists,binders),(terms',termlists')
1116 | NtnTypeConstrList ->
1117 let termlists,termlists' = bind id scl termlists termlists' in
1118 (terms,termlists,binders),(terms',termlists')
1119 | NtnTypeBinder (NtnBinderParsedAsBinder | NtnBinderParsedAsSomeBinderKind _) ->
1120 let binders,terms' = bind_binders id scl binders terms' in
1121 (terms,termlists,binders),(terms',termlists')
1122 | NtnTypeBinderList _ -> error_invalid_pattern_notation ?loc ())
1123 (subst,(Id.Map.empty,Id.Map.empty)) ids in
1124 assert (terms = [] && termlists = [] && binders = []);
1125 subst
1126
1127 let intern_notation intern env ntnvars loc ntn fullargs =
1128 (* Adjust to parsing of { } *)
1129 let ntn,fullargs = contract_curly_brackets ntn fullargs in
1130 (* Recover interpretation { } *)
1131 let ((ids,c),df) = interp_notation ?loc ntn (env.tmp_scope,env.scopes) in
1132 Dumpglob.dump_notation_location (ntn_loc ?loc fullargs ntn) ntn df;
1133 (* Dispatch parsing substitution to an interpretation substitution *)
1134 let subst = split_by_type ids fullargs in
1135 (* Instantiate the notation *)
1136 instantiate_notation_constr loc intern (intern_cases_pattern_as_binder ~dump:true intern) ntnvars subst (Id.Map.empty, env) c
1137
1138 (**********************************************************************)
1139 (* Discriminating between bound variables and global references *)
1140
1141 let string_of_ty = function
1142 | Inductive -> "ind"
1143 | Recursive -> "def"
1144 | Method -> "meth"
1145 | Variable -> "var"
1146
1147 let gvar (loc, id) us = match us with
1148 | None | Some ([],[]) -> DAst.make ?loc @@ GVar id
1149 | Some _ ->
1150 user_err ?loc (str "Variable " ++ Id.print id ++
1151 str " cannot have a universe instance")
1152
1153 let intern_var env (ltacvars,ntnvars) namedctx loc id us =
1154 (* Is [id] a notation variable *)
1155 if Id.Map.mem id ntnvars then
1156 begin
1157 if not (Id.Map.mem id env.impls) then set_notation_var_scope ?loc id (env.tmp_scope,env.scopes) env.ntn_binding_ids ntnvars;
1158 gvar (loc,id) us
1159 end
1160 else
1161 (* Is [id] registered with implicit arguments *)
1162 try
1163 let {var_intern_typ=ty; var_uid=uid} = Id.Map.find id env.impls in
1164 let tys = string_of_ty ty in
1165 Dumpglob.dump_reference ?loc "<>" uid tys;
1166 gvar (loc,id) us
1167 with Not_found ->
1168 (* Is [id] bound in current term or is an ltac var bound to constr *)
1169 if Id.Set.mem id env.ids || Id.Set.mem id ltacvars.ltac_vars
1170 then
1171 gvar (loc,id) us
1172 else if Id.equal id ldots_var
1173 (* Is [id] the special variable for recursive notations? *)
1174 then if Id.Map.is_empty ntnvars
1175 then error_ldots_var ?loc
1176 else gvar (loc,id) us
1177 else if Id.Set.mem id ltacvars.ltac_bound then
1178 (* Is [id] bound to a free name in ltac (this is an ltac error message) *)
1179 user_err ?loc
1180 (str "variable " ++ Id.print id ++ str " should be bound to a term.")
1181 else
1182 (* Is [id] a goal or section variable *)
1183 let _ = Environ.lookup_named_ctxt id namedctx in
1184 try
1185 (* [id] a section variable *)
1186 (* Redundant: could be done in intern_qualid *)
1187 let ref = GlobRef.VarRef id in
1188 Dumpglob.dump_secvar ?loc id; (* this raises Not_found when not a section variable *)
1189 (* Someday we should stop relying on Dumglob raising exceptions *)
1190 DAst.make ?loc @@ GRef (ref, us)
1191 with e when CErrors.noncritical e ->
1192 (* [id] a goal variable *)
1193 gvar (loc,id) us
1194
1195 (**********************************************************************)
1196 (* Locating reference, possibly via an abbreviation *)
1197
1198 let locate_reference qid =
1199 Smartlocate.global_of_extended_global (Nametab.locate_extended qid)
1200
1201 let is_global id =
1202 try
1203 let _ = locate_reference (qualid_of_ident id) in true
1204 with Not_found ->
1205 false
1206
1207 let dump_extended_global loc = function
1208 | TrueGlobal ref -> (*feedback_global loc ref;*) Dumpglob.add_glob ?loc ref
1209 | Abbrev sp -> Dumpglob.add_glob_kn ?loc sp
1210
1211 let intern_extended_global_of_qualid qid =
1212 let r = Nametab.locate_extended qid in dump_extended_global qid.CAst.loc r; r
1213
1214 let intern_reference qid =
1215 let r =
1216 try intern_extended_global_of_qualid qid
1217 with Not_found as exn ->
1218 let _, info = Exninfo.capture exn in
1219 Nametab.error_global_not_found ~info qid
1220 in
1221 Smartlocate.global_of_extended_global r
1222
1223 let intern_sort_name ~local_univs = function
1224 | CSProp -> GSProp
1225 | CProp -> GProp
1226 | CSet -> GSet
1227 | CRawType u -> GRawUniv u
1228 | CType qid ->
1229 let is_id = qualid_is_ident qid in
1230 let local = if not is_id then None
1231 else Id.Map.find_opt (qualid_basename qid) (snd local_univs.bound)
1232 in
1233 match local with
1234 | Some u -> GUniv u
1235 | None ->
1236 try GUniv (Univ.Level.make (Nametab.locate_universe qid))
1237 with Not_found ->
1238 if is_id && local_univs.unb_univs
1239 then GLocalUniv (CAst.make ?loc:qid.loc (qualid_basename qid))
1240 else
1241 CErrors.user_err ?loc:qid.loc Pp.(str "Undeclared universe " ++ pr_qualid qid ++ str".")
1242
1243 let intern_qvar ~local_univs = function
1244 | CQAnon loc -> GLocalQVar (CAst.make ?loc Anonymous)
1245 | CRawQVar q -> GRawQVar q
1246 | CQVar qid ->
1247 let is_id = qualid_is_ident qid in
1248 let local = if not is_id then None
1249 else Id.Map.find_opt (qualid_basename qid) (fst local_univs.bound)
1250 in
1251 match local with
1252 | Some u -> GQVar u
1253 | None ->
1254 try GQVar (Sorts.QVar.make_global (Nametab.Quality.locate qid))
1255 with Not_found ->
1256 if is_id && local_univs.unb_univs
1257 then GLocalQVar (CAst.make ?loc:qid.loc (Name (qualid_basename qid)))
1258 else
1259 CErrors.user_err ?loc:qid.loc Pp.(str "Undeclared quality " ++ pr_qualid qid ++ str".")
1260
1261 let intern_quality ~local_univs q =
1262 match q with
1263 | CQConstant q -> GQConstant q
1264 | CQualVar q -> GQualVar (intern_qvar ~local_univs q)
1265
1266 let intern_sort ~local_univs (q,l) =
1267 Option.map (intern_qvar ~local_univs) q,
1268 map_glob_sort_gen (List.map (on_fst (intern_sort_name ~local_univs))) l
1269
1270 let intern_instance ~local_univs = function
1271 | None -> None
1272 | Some (qs, us) ->
1273 let qs = List.map (intern_quality ~local_univs) qs in
1274 let us = List.map (map_glob_sort_gen (intern_sort_name ~local_univs)) us in
1275 Some (qs, us)
1276
1277 let intern_name_alias = function
1278 | { CAst.v = CRef(qid,u) } ->
1279 let r =
1280 try Some (intern_extended_global_of_qualid qid)
1281 with Not_found -> None
1282 in
1283 Option.bind r Smartlocate.global_of_extended_global |>
1284 Option.map (fun r -> r, intern_instance ~local_univs:empty_local_univs u)
1285 | _ -> None
1286
1287 let intern_field_ref qid =
1288 match
1289 Smartlocate.global_of_extended_global (intern_extended_global_of_qualid qid) |>
1290 Option.map (function
1291 | GlobRef.ConstRef c as x -> x, Structure.find_from_projection (Global.env ()) c
1292 | _ -> raise Not_found)
1293 with
1294 | exception Not_found ->
1295 Loc.raise ?loc:qid.loc (InternalizationError (NotAProjection qid))
1296 | None ->
1297 Loc.raise ?loc:qid.loc (InternalizationError (NotAProjection qid))
1298 | Some x -> x
1299
1300 (**********************************************************************)
1301 (* Interpreting references *)
1302
1303 let find_appl_head_data genv env (_,ntnvars) c =
1304 let loc = c.CAst.loc in
1305 match DAst.get c with
1306 | GVar id when not (Id.Map.mem id ntnvars) ->
1307 (try
1308 let {var_impls=impls; var_scopes=argsc} = Id.Map.find id env.impls in
1309 Some (CAst.make ?loc (GlobRef.VarRef id)), make_implicits_list impls, argsc
1310 with Not_found -> None, [], [])
1311 | GRef (ref,_) ->
1312 let impls = implicits_of_global ref in
1313 let scopes = find_arguments_scope genv ref in
1314 Some (CAst.make ?loc ref), impls, scopes
1315 | GApp (r, l) ->
1316 begin match DAst.get r with
1317 | GRef (ref,_) ->
1318 let n = List.length l in
1319 let impls = implicits_of_global ref in
1320 let scopes = find_arguments_scope genv ref in
1321 Some (CAst.make ?loc ref),
1322 (if n = 0 then [] else List.map (drop_first_implicits n) impls),
1323 List.skipn_at_best n scopes
1324 | _ -> None, [], []
1325 end
1326 | GProj ((cst,_), l, c) ->
1327 let ref = GlobRef.ConstRef cst in
1328 let n = List.length l + 1 in
1329 let impls = implicits_of_global ref in
1330 let scopes = find_arguments_scope genv ref in
1331 Some (CAst.make ?loc (GlobRef.ConstRef cst)),
1332 List.map (drop_first_implicits n) impls,
1333 List.skipn_at_best n scopes
1334 | _ -> None, [], []
1335
1336 let error_not_enough_arguments ?loc =
1337 user_err ?loc (str "Abbreviation is not applied enough.")
1338
1339 let check_no_explicitation l =
1340 let is_unset (a, b) = match b with None -> false | Some _ -> true in
1341 let l = List.filter is_unset l in
1342 match l with
1343 | [] -> ()
1344 | (_, None) :: _ -> assert false
1345 | (_, Some {loc}) :: _ ->
1346 user_err ?loc (str"Unexpected explicitation of the argument of an abbreviation.")
1347
1348 let find_projection_data c =
1349 match DAst.get c with
1350 | GApp (r, l) ->
1351 begin match DAst.get r with
1352 | GRef (GlobRef.ConstRef cst,us) -> Some (cst, us, l, Structure.projection_nparams (Global.env ()) cst)
1353 | _ -> None
1354 end
1355 | GRef (GlobRef.ConstRef cst,us) -> Some (cst, us, [], Structure.projection_nparams (Global.env ()) cst)
1356 | _ -> None
1357
1358 let glob_sort_of_level (level: glob_level) : glob_sort =
1359 match level with
1360 | UAnonymous _ as l -> None, l
1361 | UNamed id -> None, UNamed [id, 0]
1362
1363 (* Is it a global reference or a syntactic definition? *)
1364 let intern_qualid ?(no_secvar=false) qid intern env ntnvars us args =
1365 let loc = qid.loc in
1366 match intern_extended_global_of_qualid qid with
1367 | TrueGlobal (GlobRef.VarRef _) when no_secvar ->
1368 (* Rule out section vars since these should have been found by intern_var *)
1369 raise Not_found
1370 | TrueGlobal ref -> (DAst.make ?loc @@ GRef (ref, us)), Some ref, args
1371 | Abbrev sp ->
1372 let (ids,c) = Abbreviation.find_interp sp in
1373 let nids = List.length ids in
1374 if List.length args < nids then error_not_enough_arguments ?loc;
1375 let args1,args2 = List.chop nids args in
1376 check_no_explicitation args1;
1377 let subst = split_by_type ids (List.map fst args1,[],[],[]) in
1378 let infos = (Id.Map.empty, env) in
1379 let c = instantiate_notation_constr loc intern (intern_cases_pattern_as_binder ~dump:true intern) ntnvars subst infos c in
1380 let loc = c.loc in
1381 let err () =
1382 user_err ?loc (str "Notation " ++ pr_qualid qid
1383 ++ str " cannot have a universe instance,"
1384 ++ str " its expanded head does not start with a reference")
1385 in
1386 let c = match us, DAst.get c with
1387 | None, _ -> c
1388 | Some _, GRef (ref, None) -> DAst.make ?loc @@ GRef (ref, us)
1389 | Some _, GApp (r, arg) ->
1390 let loc' = r.CAst.loc in
1391 begin match DAst.get r with
1392 | GRef (ref, None) ->
1393 DAst.make ?loc @@ GApp (DAst.make ?loc:loc' @@ GRef (ref, us), arg)
1394 | _ -> err ()
1395 end
1396 | Some ([],[s]), GSort gs when Glob_ops.(glob_sort_eq glob_Type_sort gs) ->
1397 DAst.make ?loc @@ GSort (glob_sort_of_level s)
1398 | Some ([],[_old_level]), GSort _new_sort ->
1399 (* TODO: add old_level and new_sort to the error message *)
1400 user_err ?loc (str "Cannot change universe level of notation " ++ pr_qualid qid)
1401 | Some _, _ -> err ()
1402 in
1403 c, None, args2
1404
1405 let intern_qualid_for_pattern test_global intern_not qid pats =
1406 match Nametab.locate_extended_nowarn qid with
1407 | TrueGlobal g as xref ->
1408 test_global g;
1409 Nametab.is_warned_xref xref |> Option.iter (fun warn -> Nametab.warn_user_warn_xref ?loc:qid.loc warn (TrueGlobal g));
1410 dump_extended_global qid.loc (TrueGlobal g);
1411 (g, false, Some [], pats)
1412 | Abbrev kn as xref ->
1413 let filter (vars,a) =
1414 match a with
1415 | NRef (g,_) ->
1416 (* Convention: do not deactivate implicit arguments and scopes for further arguments *)
1417 test_global g;
1418 let () = assert (List.is_empty vars) in
1419 Some (g, Some [], pats)
1420 | NApp (NRef (g,_),[]) -> (* special case: abbreviation for @Cstr deactivates implicit arguments *)
1421 test_global g;
1422 let () = assert (List.is_empty vars) in
1423 Some (g, None, pats)
1424 | NApp (NRef (g,_),args) ->
1425 (* Convention: do not deactivate implicit arguments and scopes for further arguments *)
1426 test_global g;
1427 let nvars = List.length vars in
1428 if List.length pats < nvars then error_not_enough_arguments ?loc:qid.loc;
1429 let pats1,pats2 = List.chop nvars pats in
1430 let subst = split_by_type_pat vars (pats1,[],[]) in
1431 let args = List.map (intern_not subst) args in
1432 Some (g, Some args, pats2)
1433 | _ -> None in
1434 match Abbreviation.find_opt kn with
1435 | None -> raise Not_found
1436 | Some abbrev ->
1437 match filter (Abbreviation.interp abbrev) with
1438 | Some (g, pats1, pats2) ->
1439 Nametab.is_warned_xref xref
1440 |> Option.iter (fun warn -> Nametab.warn_user_warn_xref ?loc:qid.loc warn (Abbrev kn));
1441 dump_extended_global qid.loc (Abbrev kn);
1442 (g, true, pats1, pats2)
1443 | None -> raise Not_found
1444
1445 let warn_nonprimitive_projection =
1446 CWarnings.create ~name:"nonprimitive-projection-syntax" ~category:CWarnings.CoreCategories.syntax ~default:CWarnings.Disabled
1447 Pp.(fun f -> pr_qualid f ++ str " used as a primitive projection but is not one.")
1448
1449 let error_nonprojection_syntax ?loc qid =
1450 CErrors.user_err ?loc Pp.(pr_qualid qid ++ str" is not a projection.")
1451
1452 let check_applied_projection isproj realref qid =
1453 if isproj then
1454 let open GlobRef in
1455 let is_prim = match realref with
1456 | None | Some (IndRef _ | ConstructRef _ | VarRef _) -> false
1457 | Some (ConstRef c) ->
1458 if PrimitiveProjections.mem c then true
1459 else if Structure.is_projection c then false
1460 else error_nonprojection_syntax ?loc:qid.loc qid
1461 (* TODO check projargs, note we will need implicit argument info *)
1462 in
1463 if not is_prim then warn_nonprimitive_projection ?loc:qid.loc qid
1464
1465 let intern_applied_reference ~isproj intern env namedctx (_, ntnvars as lvar) us args qid =
1466 let loc = qid.CAst.loc in
1467 let us = intern_instance ~local_univs:env.local_univs us in
1468 if qualid_is_ident qid then
1469 try
1470 let res = intern_var env lvar namedctx loc (qualid_basename qid) us in
1471 check_applied_projection isproj None qid;
1472 res, args
1473 with Not_found ->
1474 try
1475 let res, realref, args2 = intern_qualid ~no_secvar:true qid intern env ntnvars us args in
1476 check_applied_projection isproj realref qid;
1477 res, args2
1478 with Not_found as exn ->
1479 (* Extra allowance for non globalizing functions *)
1480 if Option.default true env.strict_check || List.exists (fun (_,e) -> Option.has_some e) args
1481 then
1482 let _, info = Exninfo.capture exn in
1483 Nametab.error_global_not_found ~info qid
1484 else
1485 (* check_applied_projection ?? *)
1486 gvar (loc,qualid_basename qid) us, args
1487 else
1488 try
1489 let res, realref, args2 = intern_qualid qid intern env ntnvars us args in
1490 check_applied_projection isproj realref qid;
1491 res, args2
1492 with Not_found as exn ->
1493 let _, info = Exninfo.capture exn in
1494 Nametab.error_global_not_found ~info qid
1495
1496 let interp_reference vars r =
1497 let r,_ =
1498 intern_applied_reference ~isproj:false (fun _ -> error_not_enough_arguments ?loc:None)
1499 {ids = Id.Set.empty; strict_check = Some true; pattern_mode = false;
1500 local_univs = empty_local_univs;(* <- doesn't matter here *)
1501 tmp_scope = []; scopes = []; impls = empty_internalization_env;
1502 binder_block_names = None; ntn_binding_ids = Id.Set.empty}
1503 Environ.empty_named_context_val
1504 (vars, Id.Map.empty) None [] r
1505 in r
1506
1507 (**********************************************************************)
1508 (** {5 Cases } *)
1509
1510 (** Intermediate type common to the patterns of the "in" and of the
1511 "with" clause of "match" *)
1512
1513 type 'a raw_cases_pattern_expr_r =
1514 | RCPatAlias of 'a raw_cases_pattern_expr * lname
1515 | RCPatCstr of GlobRef.t * 'a raw_cases_pattern_expr list
1516 | RCPatAtom of (lident * (Notation_term.tmp_scope_name list * Notation_term.scope_name list)) option
1517 | RCPatOr of 'a raw_cases_pattern_expr list
1518 and 'a raw_cases_pattern_expr = ('a raw_cases_pattern_expr_r, 'a) DAst.t
1519
1520 (** {6 Elementary bricks } *)
1521
1522 let apply_scope_env env = function
1523 | [] -> {env with tmp_scope = []}, []
1524 | sc::scl -> {env with tmp_scope = sc}, scl
1525
1526 let rec simple_adjust_scopes n scopes =
1527 (* Note: there can be less scopes than arguments but also more scopes *)
1528 (* than arguments because extra scopes are used in the presence of *)
1529 (* coercions to funclass *)
1530 if Int.equal n 0 then [] else match scopes with
1531 | [] -> [] :: simple_adjust_scopes (n-1) []
1532 | sc::scopes -> sc :: simple_adjust_scopes (n-1) scopes
1533
1534 let rec adjust_to_up l l' default =
1535 match l, l' with
1536 | l, [] -> []
1537 | [], l -> l
1538 | true::l, l' -> default :: adjust_to_up l l' default
1539 | false::l, y::l' -> y :: adjust_to_up l l' default
1540
1541 let rec adjust_to_down l l' default =
1542 match l, l' with
1543 | [], l -> []
1544 | true::l, l' -> adjust_to_down l l' default
1545 | false::l, [] -> default :: adjust_to_down l [] default
1546 | false::l, y::l' -> y :: adjust_to_down l l' default
1547
1548 let loc_of_multiple_pattern pl =
1549 Loc.merge_opt (cases_pattern_expr_loc (List.hd pl)) (cases_pattern_expr_loc (List.last pl))
1550
1551 let check_linearity loc ids =
1552 match List.duplicates (fun id1 id2 -> Id.equal id1.v id2.v) ids with
1553 | id::_ ->
1554 Loc.raise ?loc (InternalizationError (NonLinearPattern id.v))
1555 | [] ->
1556 ()
1557
1558 (* Match the number of pattern against the number of matched args *)
1559 let check_number_of_pattern loc n l =
1560 let p = List.length l in
1561 if not (Int.equal n p) then
1562 Loc.raise ?loc (InternalizationError (BadPatternsNumber (n,p)))
1563
1564 let check_or_pat_variables loc ids idsl =
1565 let eq_id {v=id} {v=id'} = Id.equal id id' in
1566 (* Collect remaining patterns which do not have the same variables as the first pattern *)
1567 let idsl = List.filter (fun ids' -> not (List.eq_set eq_id ids ids')) idsl in
1568 match idsl with
1569 | ids'::_ ->
1570 (* Look for an [id] which is either in [ids] and not in [ids'] or in [ids'] and not in [ids] *)
1571 let ids'' = List.subtract eq_id ids ids' in
1572 let ids'' = if ids'' = [] then List.subtract eq_id ids' ids else ids'' in
1573 user_err ?loc
1574 (strbrk "The components of this disjunctive pattern must bind the same variables (" ++
1575 Id.print (List.hd ids'').v ++ strbrk " is not bound in all patterns).")
1576 | [] -> ()
1577
1578 let error_wrong_numarg ?loc g ~expanded ~nargs ~expected_nassums ~expected_ndecls =
1579 let env = Global.env() in
1580 match g with
1581 | GlobRef.ConstructRef cstr -> error_wrong_numarg_constructor ?loc env ~cstr ~expanded ~nargs ~expected_nassums ~expected_ndecls
1582 | GlobRef.IndRef ind -> error_wrong_numarg_inductive ?loc env ~ind ~expanded ~nargs ~expected_nassums ~expected_ndecls
1583 | _ -> assert false
1584
1585 let error_wrong_numarg_with_notation_patterns ?loc g nargs tags =
1586 error_wrong_numarg ?loc g ~expanded:true ~nargs
1587 ~expected_nassums:(List.count (fun x -> not x) tags)
1588 ~expected_ndecls:(List.length tags)
1589
1590 let check_has_letin ?loc g expanded nargs nimps tags =
1591 let expected_ndecls = List.length tags - nimps in
1592 let expected_nassums = List.count (fun x -> not x) tags - nimps in
1593 if nargs = expected_nassums then false
1594 else if nargs = expected_ndecls then true else
1595 error_wrong_numarg ?loc g ~expanded ~nargs ~expected_nassums ~expected_ndecls
1596
1597 (** Do not raise NotEnoughArguments thanks to preconditions*)
1598 let chop_params_pattern loc ind args with_letin =
1599 let nparams = if with_letin
1600 then Inductiveops.inductive_nparamdecls (Global.env()) ind
1601 else Inductiveops.inductive_nparams (Global.env()) ind in
1602 assert (nparams <= List.length args);
1603 let params,args = List.chop nparams args in
1604 List.iter (fun c -> match DAst.get c with
1605 | PatVar Anonymous -> ()
1606 | PatVar _ | PatCstr(_,_,_) -> error_parameter_not_implicit ?loc:c.CAst.loc) params;
1607 args
1608
1609 let find_constructor_head ?loc ref =
1610 let open GlobRef in
1611 match ref with
1612 | ConstructRef cstr -> cstr
1613 | IndRef _ ->
1614 let error = str "There is an inductive name deep in a \"in\" clause." in
1615 user_err ?loc error
1616 | ConstRef _ | VarRef _ ->
1617 let error = str "This reference is not a constructor." in
1618 user_err ?loc error
1619
1620 let find_inductive_head ?loc ref =
1621 let open GlobRef in
1622 match ref with
1623 | IndRef ind -> ind
1624 | _ -> error_bad_inductive_type ?loc ()
1625
1626 let find_pattern_variable qid =
1627 if qualid_is_ident qid then qualid_basename qid
1628 else Loc.raise ?loc:qid.CAst.loc (InternalizationError(NotAConstructor qid))
1629
1630 let check_duplicate ?loc fields =
1631 let eq (ref1, _) (ref2, _) = qualid_eq ref1 ref2 in
1632 let dups = List.duplicates eq fields in
1633 match dups with
1634 | [] -> ()
1635 | (r, _) :: _ ->
1636 user_err ?loc (str "This record defines several times the field " ++
1637 pr_qualid r ++ str ".")
1638
1639 (** [sort_fields ~complete loc fields completer] expects a list
1640 [fields] of field assignments [f = e1; g = e2; ...], where [f, g]
1641 are fields of a record and [e1] are "values" (either terms, when
1642 interning a record construction, or patterns, when intering record
1643 pattern-matching). It will sort the fields according to the record
1644 declaration order (which is important when type-checking them in
1645 presence of dependencies between fields). If the parameter
1646 [complete] is true, we require the assignment to be complete: all
1647 the fields of the record must be present in the
1648 assignment. Otherwise the record assignment may be partial
1649 (in a pattern, we may match on some fields only), and we call the
1650 function [completer] to fill the missing fields; the returned
1651 field assignment list is always complete. *)
1652 let sort_fields genv ~complete loc fields completer =
1653 match fields with
1654 | [] -> None
1655 | (first_field_ref, _):: _ ->
1656 let (first_field_glob_ref, record) = intern_field_ref first_field_ref in
1657 (* the number of parameters *)
1658 let nparams = record.Structure.nparams in
1659 (* the reference constructor of the record *)
1660 let base_constructor = GlobRef.ConstructRef (record.Structure.name,1) in
1661 let () = check_duplicate ?loc fields in
1662 let build_proj idx proj =
1663 if proj.Structure.proj_body = None && complete then
1664 (* we don't want anonymous fields *)
1665 user_err ?loc (str "This record contains anonymous fields.")
1666 else
1667 (idx, proj.Structure.proj_body, proj.Structure.proj_true) in
1668 let proj_list =
1669 List.map_i build_proj 1 record.Structure.projections in
1670 (* now we want to have all fields assignments indexed by their place in
1671 the constructor *)
1672 let rec index_fields fields remaining_projs acc =
1673 match fields with
1674 | (field_ref, field_value) :: fields ->
1675 let field_glob_ref,this_field_record = intern_field_ref field_ref in
1676 let remaining_projs, (field_index, _, regular) =
1677 let the_proj = function
1678 | (idx, Some glob_id, _) -> Environ.QGlobRef.equal genv field_glob_ref (GlobRef.ConstRef glob_id)
1679 | (idx, None, _) -> false in
1680 try CList.extract_first the_proj remaining_projs
1681 with Not_found ->
1682 Loc.raise ?loc (InternalizationError(ProjectionsOfDifferentRecords (record, this_field_record)))
1683 in
1684 if not regular && complete then
1685 (* "regular" is false when the field is defined
1686 by a let-in in the record declaration
1687 (its value is fixed from other fields). *)
1688 user_err ?loc (str "No local fields allowed in a record construction.");
1689 Dumpglob.add_glob ?loc:field_ref.CAst.loc field_glob_ref;
1690 index_fields fields remaining_projs ((field_index, field_value) :: acc)
1691 | [] ->
1692 let remaining_fields =
1693 let complete_field (idx, field_ref, regular) =
1694 if not regular && complete then
1695 (* For terms, we keep only regular fields *)
1696 None
1697 else
1698 Some (idx, completer idx field_ref (record.Structure.name,1)) in
1699 List.map_filter complete_field remaining_projs in
1700 List.rev_append remaining_fields acc
1701 in
1702 let unsorted_indexed_fields = index_fields fields proj_list [] in
1703 let sorted_indexed_fields =
1704 let cmp_by_index (i, _) (j, _) = Int.compare i j in
1705 List.sort cmp_by_index unsorted_indexed_fields in
1706 let sorted_fields = List.map snd sorted_indexed_fields in
1707 Some (nparams, base_constructor, sorted_fields)
1708
1709 (** {6 Manage multiple aliases} *)
1710
1711 type alias = {
1712 alias_ids : lident list;
1713 alias_map : Id.t Id.Map.t;
1714 }
1715
1716 let empty_alias = {
1717 alias_ids = [];
1718 alias_map = Id.Map.empty;
1719 }
1720
1721 (* [merge_aliases] returns the sets of all aliases encountered at this
1722 point and a substitution mapping extra aliases to the first one *)
1723 let merge_aliases aliases {loc;v=na} =
1724 match na with
1725 | Anonymous -> aliases
1726 | Name id ->
1727 let alias_ids = List.add_set (fun id1 id2 -> Id.equal id1.v id2.v) (make ?loc id) aliases.alias_ids in
1728 (* Note: assumes that add_set adds in front, see alias_of *)
1729 let alias_map = match aliases.alias_ids with
1730 | [] -> aliases.alias_map
1731 | {v=id'} :: _ -> Id.Map.add id id' aliases.alias_map
1732 in
1733 { alias_ids; alias_map; }
1734
1735 let alias_of als = match als.alias_ids with
1736 | [] -> Anonymous
1737 | l -> Name (List.last l).v
1738
1739 (** {6 Expanding notations }
1740
1741 @returns a raw_case_pattern_expr :
1742 - no notations and syntactic definition
1743 - global reference and identifier instead of reference
1744
1745 *)
1746
1747 let merge_subst s1 s2 = Id.Map.fold Id.Map.add s1 s2
1748
1749 let product_of_cases_patterns aliases idspl =
1750 (* each [pl] is a disjunction of patterns over common identifiers [ids] *)
1751 (* We stepwise build a disjunction of patterns [ptaill] over common [ids'] *)
1752 List.fold_right (fun (ids,pl) (ids',ptaill) ->
1753 (ids @ ids',
1754 (* Cartesian prod of the or-pats for the nth arg and the tail args *)
1755 List.flatten (
1756 List.map (fun (subst,p) ->
1757 List.map (fun (subst',ptail) -> (merge_subst subst subst',p::ptail)) ptaill) pl)))
1758 idspl (aliases.alias_ids,[aliases.alias_map,[]])
1759
1760 let rec subst_pat_iterator y t = DAst.(map (function
1761 | RCPatAtom id as p ->
1762 begin match id with Some ({v=x},_) when Id.equal x y -> DAst.get t | _ -> p end
1763 | RCPatCstr (id,l) ->
1764 RCPatCstr (id,List.map (subst_pat_iterator y t) l)
1765 | RCPatAlias (p,a) -> RCPatAlias (subst_pat_iterator y t p,a)
1766 | RCPatOr pl -> RCPatOr (List.map (subst_pat_iterator y t) pl)))
1767
1768 let is_non_zero c = match c with
1769 | { CAst.v = CPrim (Number p) } -> not (NumTok.Signed.is_zero p)
1770 | _ -> false
1771
1772 let is_non_zero_pat c = match c with
1773 | { CAst.v = CPatPrim (Number p) } -> not (NumTok.Signed.is_zero p)
1774 | _ -> false
1775
1776 let { Goptions.get = get_asymmetric_patterns } =
1777 Goptions.declare_bool_option_and_ref
1778 ~key:["Asymmetric";"Patterns"]
1779 ~value:false
1780 ()
1781
1782 type global_reference_test = {
1783 for_ind : bool;
1784 test_kind : ?loc:Loc.t -> GlobRef.t -> unit
1785 }
1786
1787 let drop_notations_pattern (test_kind_top,test_kind_inner) genv env pat =
1788 (* At toplevel, Constructors and Inductives are accepted, in recursive calls
1789 only constructor are allowed *)
1790 let ensure_kind {test_kind} ?loc g =
1791 try test_kind ?loc g
1792 with Not_found ->
1793 error_invalid_pattern_notation ?loc ()
1794 in
1795 (* [rcp_of_glob] : from [glob_constr] to [raw_cases_pattern_expr] *)
1796 let make_pars ?loc g =
1797 let env = Global.env () in
1798 let n = match g with
1799 | GlobRef.ConstructRef (ind,_) -> Inductiveops.inductive_nparams env ind
1800 | _ -> 0 in
1801 List.make n (DAst.make ?loc @@ RCPatAtom None)
1802 in
1803 (* Check Ind/Construct structure of patterns for primitive notation *)
1804 let rec check_allowed_ref_in_pat test_kind = DAst.(with_loc_val (fun ?loc -> function
1805 | GVar _ | GHole _ -> ()
1806 | GRef (g,_) -> test_kind.test_kind ?loc g
1807 | GApp (f, l) ->
1808 begin match DAst.get f with
1809 | GRef (g, _) ->
1810 test_kind.test_kind ?loc g;
1811 let nparams = match g with
1812 | IndRef ind | ConstructRef (ind,_) -> Inductiveops.inductive_nparams (Global.env ()) ind
1813 | _ -> assert false in
1814 let l = try List.skipn nparams l with Failure _ -> raise Not_found in
1815 List.iter (check_allowed_ref_in_pat test_kind_inner) l
1816 | _ -> raise Not_found
1817 end
1818 | _ -> raise Not_found)) in
1819 (* Interpret a primitive notation (part of Glob_ops.cases_pattern_of_glob_constr) *)
1820 let rec rcp_of_glob scopes x = DAst.(map_with_loc (fun ?loc -> function
1821 | GVar id -> RCPatAtom (Some (CAst.make ?loc id,scopes))
1822 | GHole _ -> RCPatAtom None
1823 | GRef (g,_) -> RCPatCstr (g, in_patargs ?loc scopes g ~expanded:true ~no_impl:false [] [])
1824 | GApp (r, l) ->
1825 begin match DAst.get r with
1826 | GRef (g,_) ->
1827 let allscs = find_arguments_scope genv g in
1828 let allscs = simple_adjust_scopes (List.length l) allscs in
1829 let params = make_pars ?loc g in (* Rem: no letins *)
1830 let nparams = List.length params in
1831 let allscs = List.skipn nparams allscs in
1832 let l = List.skipn nparams l in
1833 let pl = List.map2 (fun sc a -> rcp_of_glob (sc,snd scopes) a) allscs l in
1834 RCPatCstr (g, in_patargs ?loc scopes g ~expanded:true ~no_impl:false (params@pl) [])
1835 | _ ->
1836 CErrors.anomaly Pp.(str "Invalid return pattern from Notation.interp_prim_token_cases_pattern_expr.")
1837 end
1838 | _ -> CErrors.anomaly Pp.(str "Invalid return pattern from Notation.interp_prim_token_cases_pattern_expr."))) x
1839 and drop_abbrev {test_kind} ?loc scopes qid add_par_if_no_ntn_with_par no_impl pats =
1840 try
1841 if qualid_is_ident qid && Option.cata (Id.Set.mem (qualid_basename qid)) false env.pat_ids && List.is_empty pats then
1842 raise Not_found;
1843 let intern_not subst pat = in_not test_kind_inner qid.loc scopes subst [] pat in
1844 let g, expanded, ntnpats, pats = intern_qualid_for_pattern (test_kind ?loc) intern_not qid pats in
1845 match ntnpats with
1846 | None ->
1847 (* deactivate implicit *)
1848 let ntnpats = if add_par_if_no_ntn_with_par then make_pars ?loc g else [] in
1849 Some (g, in_patargs ?loc scopes g ~expanded ~no_impl:true ntnpats pats)
1850 | Some ntnpats ->
1851 let ntnpats = if add_par_if_no_ntn_with_par && ntnpats = [] then make_pars ?loc g else ntnpats in
1852 Some (g, in_patargs ?loc scopes g ~expanded ~no_impl ntnpats pats)
1853 with Not_found -> None
1854 and in_pat ({for_ind} as test_kind) scopes pt =
1855 let open CAst in
1856 let loc = pt.loc in
1857 (* The two policies implied by asymmetric pattern mode *)
1858 let add_par_if_no_ntn_with_par = get_asymmetric_patterns () && not for_ind in
1859 let no_impl = get_asymmetric_patterns () && not for_ind in
1860 match pt.v with
1861 | CPatAlias (p, id) -> DAst.make ?loc @@ RCPatAlias (in_pat test_kind scopes p, id)
1862 | CPatRecord l ->
1863 let sorted_fields =
1864 sort_fields genv ~complete:false loc l (fun _idx fieldname constructor -> CAst.make ?loc @@ CPatAtom None) in
1865 begin match sorted_fields with
1866 | None -> DAst.make ?loc @@ RCPatAtom None
1867 | Some (n, head, pl) ->
1868 let pars = make_pars ?loc head in
1869 let pats = in_patargs ?loc scopes head ~expanded:true ~no_impl:true pars pl in
1870 DAst.make ?loc @@ RCPatCstr(head, pats)
1871 end
1872 | CPatCstr (head, None, pl) ->
1873 begin
1874 match drop_abbrev test_kind ?loc scopes head add_par_if_no_ntn_with_par no_impl pl with
1875 | Some (g,pl) -> DAst.make ?loc @@ RCPatCstr(g, pl)
1876 | None -> Loc.raise ?loc (InternalizationError (NotAConstructor head))
1877 end
1878 | CPatCstr (qid, Some expl_pl, pl) ->
1879 begin
1880 match drop_abbrev test_kind ?loc scopes qid false true (expl_pl@pl) with
1881 | Some (g,pl) -> DAst.make ?loc @@ RCPatCstr (g, pl)
1882 | None -> Loc.raise ?loc (InternalizationError (NotAConstructor qid))
1883 end
1884 | CPatNotation (_,(InConstrEntry,"- _"),([a],[],[]),[]) when is_non_zero_pat a ->
1885 let p = match a.CAst.v with CPatPrim (Number (_, p)) -> p | _ -> assert false in
1886 let pat, _df = Notation.interp_prim_token_cases_pattern_expr ?loc
1887 (check_allowed_ref_in_pat test_kind) (Number (SMinus,p)) scopes in
1888 rcp_of_glob scopes pat
1889 | CPatNotation (_,(InConstrEntry,"( _ )"),([a],[],[]),[]) ->
1890 in_pat test_kind scopes a
1891 | CPatNotation (_,ntn,fullargs,extrargs) ->
1892 let ntn,(terms,termlists,binders) = contract_curly_brackets_pat ntn fullargs in
1893 let ((ids',c),df) = Notation.interp_notation ?loc ntn scopes in
1894 let subst = split_by_type_pat ?loc ids' (terms,termlists,binders) in
1895 Dumpglob.dump_notation_location (patntn_loc ?loc fullargs ntn) ntn df;
1896 in_not test_kind loc scopes subst extrargs c
1897 | CPatDelimiters (depth, key, e) ->
1898 let sc = find_delimiters_scope ?loc key in
1899 let scopes = match depth with
1900 | DelimOnlyTmpScope -> [sc], snd scopes
1901 | DelimUnboundedScope -> [], sc::snd scopes in
1902 in_pat test_kind scopes e
1903 | CPatPrim p ->
1904 let pat, _df = Notation.interp_prim_token_cases_pattern_expr ?loc
1905 (check_allowed_ref_in_pat test_kind) p scopes in
1906 rcp_of_glob scopes pat
1907 | CPatAtom (Some id) ->
1908 begin
1909 match drop_abbrev test_kind ?loc scopes id add_par_if_no_ntn_with_par no_impl [] with
1910 | Some (g, pl) -> DAst.make ?loc @@ RCPatCstr (g, pl)
1911 | None -> DAst.make ?loc @@ RCPatAtom (Some ((make ?loc @@ find_pattern_variable id),scopes))
1912 end
1913 | CPatAtom None -> DAst.make ?loc @@ RCPatAtom None
1914 | CPatOr pl -> DAst.make ?loc @@ RCPatOr (List.map (in_pat test_kind scopes) pl)
1915 | CPatCast (_,_) ->
1916 (* We raise an error if the pattern contains a cast, due to
1917 current restrictions on casts in patterns. Cast in patterns
1918 are supported only in local binders and only at for_ind level.
1919 The only reason they are in the [cases_pattern_expr] type
1920 is that the parser needs to factor the "c : t" notation
1921 with user defined notations. In the long term, we will try to
1922 support such casts everywhere, and perhaps use them to print
1923 the domains of lambdas in the encoding of match in constr.
1924 This check is here and not in the parser because it would require
1925 duplicating the levels of the [pattern] rule. *)
1926 CErrors.user_err ?loc (Pp.strbrk "Casts are not supported in this pattern.")
1927 and in_pat_sc scopes x = in_pat test_kind_inner (x,snd scopes)
1928 and in_patargs ?loc scopes
1929 gr (* head of the pattern *)
1930 ~expanded (* tell if comes from a notation (for error reporting) *)
1931 ~no_impl (* tell if implicit are not expected (for asymmetric patterns, or @, or {| |} *)
1932 ntnpats (* prefix of patterns obtained by expansion of notations or parameter insertion *)
1933 pats (* user given patterns *)
1934 =
1935 let default = DAst.make ?loc @@ RCPatAtom None in
1936 let npats = List.length pats in
1937 let n = List.length ntnpats in
1938 let ntnpats_with_letin, tags =
1939 let tags = match gr with
1940 | GlobRef.ConstructRef cstr -> constructor_alltags (Global.env()) cstr
1941 | GlobRef.IndRef ind -> inductive_alltags (Global.env()) ind
1942 | _ -> assert false in
1943 let ntnpats_with_letin = adjust_to_up tags ntnpats default in
1944 let tags =
1945 try List.skipn (List.length ntnpats_with_letin) tags with Failure _ ->
1946 error_wrong_numarg_with_notation_patterns ?loc gr (n+npats) tags in
1947 ntnpats_with_letin, tags in
1948 let imps =
1949 let imps =
1950 if no_impl then [] else
1951 let impls_st = implicits_of_global gr in
1952 if Int.equal n 0 then select_impargs_size npats impls_st
1953 else List.skipn_at_best n (select_stronger_impargs impls_st) in
1954 adjust_to_down tags imps None in
1955 let subscopes = adjust_to_down tags (List.skipn_at_best n (find_arguments_scope genv gr)) [] in
1956 let has_letin = check_has_letin ?loc gr expanded npats (List.count is_status_implicit imps) tags in
1957 let rec aux imps subscopes tags pats =
1958 match imps, subscopes, tags, pats with
1959 | _, _, true::tags, p::pats when has_letin ->
1960 in_pat_sc scopes [] p :: aux imps subscopes tags pats
1961 | _, _, true::tags, _ ->
1962 default :: aux imps subscopes tags pats
1963 | imp::imps, sc::subscopes, false::tags, _ when is_status_implicit imp ->
1964 default :: aux imps subscopes tags pats
1965 | imp::imps, sc::subscopes, false::tags, p::pats ->
1966 in_pat_sc scopes sc p :: aux imps subscopes tags pats
1967 | _, _, [], [] -> []
1968 | _ -> assert false in
1969 ntnpats_with_letin @ aux imps subscopes tags pats
1970 and in_not test_kind loc scopes (terms,termlists as fullsubst) args = function
1971 | NVar id ->
1972 begin
1973 (* subst remembers the delimiters stack in the interpretation *)
1974 (* of the notations *)
1975 try
1976 let (a,(scopt,subscopes)) = Id.Map.find id terms in
1977 in_pat test_kind (scopt,subscopes@snd scopes) (mkAppPattern ?loc a args)
1978 with Not_found ->
1979 if Id.equal id ldots_var then
1980 if List.is_empty args then
1981 DAst.make ?loc @@ RCPatAtom (Some ((make ?loc id),scopes))
1982 else
1983 user_err (str "Recursive notations with arguments not supported in patterns.")
1984 else
1985 anomaly (str "Unbound pattern notation variable: " ++ Id.print id ++ str ".")
1986 end
1987 | NApp (NVar id,ntnpl) ->
1988 user_err ?loc (str "Notations with an applied head variable not supported in patterns.")
1989 | NRef (g,_) ->
1990 ensure_kind test_kind ?loc g;
1991 DAst.make ?loc @@ RCPatCstr (g, in_patargs ?loc scopes g ~expanded:true ~no_impl:false [] args)
1992 | NApp (NRef (g,_),ntnpl) ->
1993 ensure_kind test_kind ?loc g;
1994 let ntnpl = List.map (in_not test_kind_inner loc scopes fullsubst []) ntnpl in
1995 let no_impl =
1996 (* Convention: if notation is @f, encoded as NApp(Nref g,[]), then
1997 implicit arguments are not inherited *)
1998 ntnpl = [] in
1999 DAst.make ?loc @@ RCPatCstr (g, in_patargs ?loc scopes g ~expanded:true ~no_impl ntnpl args)
2000 | NList (x,y,iter,terminator,revert) ->
2001 if not (List.is_empty args) then user_err ?loc
2002 (strbrk "Application of arguments to a recursive notation not supported in patterns.");
2003 (try
2004 (* All elements of the list are in scopes (scopt,subscopes) *)
2005 let (l,(scopt,subscopes)) = Id.Map.find x termlists in
2006 let termin = in_not test_kind_inner loc scopes fullsubst [] terminator in
2007 List.fold_right (fun a t ->
2008 let nterms = Id.Map.add y (a, (scopt, subscopes)) terms in
2009 let u = in_not test_kind_inner loc scopes (nterms, termlists) [] iter in
2010 subst_pat_iterator ldots_var t u)
2011 (if revert then List.rev l else l) termin
2012 with Not_found ->
2013 anomaly (Pp.str "Inconsistent substitution of recursive notation."))
2014 | NHole _ ->
2015 if not (List.is_empty args) then user_err ?loc (str "Such pattern cannot have arguments.");
2016 DAst.make ?loc @@ RCPatAtom None
2017 | NGenarg _ ->
2018 user_err ?loc (str "Quotations not supported in patterns.")
2019 | t -> error_invalid_pattern_notation ?loc ()
2020 in in_pat test_kind_top env.pat_scopes pat
2021
2022 let rec intern_pat genv ntnvars aliases pat =
2023 let loc = pat.loc in
2024 match DAst.get pat with
2025 | RCPatAlias (p, id) ->
2026 let aliases' = merge_aliases aliases id in
2027 intern_pat genv ntnvars aliases' p
2028 | RCPatCstr (head, pl) ->
2029 let c = find_constructor_head ?loc head in
2030 let idslpl = List.map (intern_pat genv ntnvars empty_alias) pl in
2031 let (ids',pll) = product_of_cases_patterns aliases idslpl in
2032 let pl' = List.map (fun (asubst,pl) ->
2033 (asubst, DAst.make ?loc @@ PatCstr (c,chop_params_pattern loc (fst c) pl true,alias_of aliases))) pll in
2034 ids',pl'
2035 | RCPatAtom (Some ({loc;v=id},scopes)) ->
2036 let aliases = merge_aliases aliases (make ?loc @@ Name id) in
2037 set_var_is_binder ?loc id ntnvars;
2038 (aliases.alias_ids,[aliases.alias_map, DAst.make ?loc @@ PatVar (alias_of aliases)]) (* TO CHECK: aura-t-on id? *)
2039 | RCPatAtom None ->
2040 let { alias_ids = ids; alias_map = asubst; } = aliases in
2041 (ids, [asubst, DAst.make ?loc @@ PatVar (alias_of aliases)])
2042 | RCPatOr pl ->
2043 assert (not (List.is_empty pl));
2044 let pl' = List.map (intern_pat genv ntnvars aliases) pl in
2045 let (idsl,pl') = List.split pl' in
2046 let ids = List.hd idsl in
2047 List.iter2 check_linearity (List.map (fun x -> x.CAst.loc) pl) idsl;
2048 check_or_pat_variables loc ids (List.tl idsl);
2049 (ids,List.flatten pl')
2050
2051 let intern_cases_pattern test_kind genv ntnvars env aliases pat =
2052 let test = {for_ind=false;test_kind} in
2053 intern_pat genv ntnvars aliases
2054 (drop_notations_pattern (test,test) genv env pat)
2055
2056 let _ =
2057 intern_cases_pattern_fwd :=
2058 fun test_kind ntnvars env p ->
2059 intern_cases_pattern test_kind (Global.env ()) ntnvars env empty_alias p
2060
2061 let intern_ind_pattern genv ntnvars env pat =
2062 let test_kind_top ?loc = function
2063 | GlobRef.IndRef _ -> ()
2064 | GlobRef.ConstructRef _ | GlobRef.ConstRef _ | GlobRef.VarRef _ ->
2065 (* A non-inductive global reference at top is an error *)
2066 error_invalid_pattern_notation ?loc () in
2067 let test_kind_inner ?loc = function
2068 | GlobRef.ConstructRef _ -> ()
2069 | GlobRef.IndRef _ | GlobRef.ConstRef _ | GlobRef.VarRef _ ->
2070 (* A non-constructor global reference deep in a pattern is seen as a variable *)
2071 raise Not_found in
2072 let no_not =
2073 try
2074 let test_top = {for_ind=true;test_kind=test_kind_top} in
2075 let test_inner = {for_ind=false;test_kind=test_kind_inner} in
2076 drop_notations_pattern (test_top,test_inner) genv env pat
2077 with InternalizationError (NotAConstructor _) as exn ->
2078 let _, info = Exninfo.capture exn in
2079 error_bad_inductive_type ~info ()
2080 in
2081 let loc = no_not.CAst.loc in
2082 match DAst.get no_not with
2083 | RCPatCstr (head, pl) ->
2084 let ind = find_inductive_head ?loc head in
2085 let idslpl = List.map (intern_pat genv ntnvars empty_alias) pl in
2086 (match product_of_cases_patterns empty_alias idslpl with
2087 | ids,[asubst,pl] -> (ind,ids,asubst,chop_params_pattern loc ind pl true)
2088 | _ -> error_bad_inductive_type ?loc ())
2089 | x -> error_bad_inductive_type ?loc ()
2090
2091 (**********************************************************************)
2092 (* Utilities for application *)
2093
2094 let get_implicit_name n imps = Impargs.name_of_implicit (List.nth imps (n-1))
2095
2096 let set_hole_implicit i na imp r =
2097 let loc, r = match r with
2098 | Some CAst.{loc;v} -> loc, v
2099 | None -> anomaly (Pp.str "Only refs have implicits.") in
2100 DAst.make ?loc (GHole (GImplicitArg (r,(i,na),force_inference_of imp)))
2101
2102 let exists_implicit_name id =
2103 List.exists (fun imp -> is_status_implicit imp && Id.equal id (name_of_implicit imp))
2104
2105 let print_allowed_named_implicit imps =
2106 let l = List.map_filter (function Some { impl_pos = (Name id, _, _) } -> Some id | _ -> None) imps in
2107 match l with
2108 | [] -> mt ()
2109 | l ->
2110 let n = List.length l in
2111 str " (possible " ++ str (String.plural n "name") ++ str ":" ++ spc () ++
2112 pr_sequence Id.print l ++ str ")"
2113
2114 let print_allowed_nondep_implicit imps =
2115 let l = List.map_filter (function Some { impl_pos = (_, _, Some n) } -> Some n | _ -> None) imps in
2116 match l with
2117 | [] -> mt ()
2118 | l ->
2119 let n = List.length l in
2120 str " (possible " ++ str (String.plural n "position") ++ str ":" ++ spc () ++
2121 pr_sequence Pp.int l ++ str ")"
2122
2123 let extract_explicit_arg imps args =
2124 let rec aux = function
2125 | [] -> [], []
2126 | (a,e)::l ->
2127 let (eargs,rargs) = aux l in
2128 match e with
2129 | None -> (eargs,a::rargs)
2130 | Some {loc;v=pos} ->
2131 let () = match pos with
2132 | ExplByName id ->
2133 if not (exists_implicit_name id imps) then
2134 user_err ?loc
2135 (str "Wrong argument name " ++ Id.print id ++
2136 print_allowed_named_implicit imps ++ str ".");
2137 if List.mem_assoc pos eargs then
2138 user_err ?loc (str "Argument name " ++ Id.print id
2139 ++ str " occurs more than once.")
2140 | ExplByPos p ->
2141 if not (is_nondep_implicit p imps) then
2142 user_err ?loc
2143 (str"Wrong argument position " ++ int p ++
2144 print_allowed_nondep_implicit imps ++ str ".");
2145 if List.mem_assoc pos eargs then
2146 user_err ?loc (str"Argument at position " ++ int p ++
2147 str " is mentioned more than once.") in
2148 ((pos,(loc,a))::eargs, rargs)
2149 in aux args
2150
2151 let extract_regular_arguments args =
2152 List.map_filter (function
2153 | (a,Some pos) -> user_err ?loc:pos.loc (str "Unexpected explicit argument.")
2154 | (a,None) -> Some a) args
2155
2156 (**********************************************************************)
2157 (* Main loop *)
2158
2159 module Interner = struct
2160
2161 type 'a fn = Environ.env -> intern_env -> (ltac_sign * Genintern.ntnvar_status Id.Map.t) -> ?loc:Loc.t -> 'a -> glob_constr
2162
2163 type t = {
2164 ref : t -> (qualid * instance_expr option) fn
2165 ; fix : t -> (lident * fix_expr list) fn
2166 ; cofix : t -> (lident * cofix_expr list) fn
2167 ; prodn : t -> (local_binder_expr list * constr_expr) fn
2168 ; lambdan : t -> (local_binder_expr list * constr_expr) fn
2169 ; letin : t -> (lname * constr_expr * constr_expr option * constr_expr) fn
2170 ; appexpl : t -> ((qualid * instance_expr option) * constr_expr list) fn
2171 ; app : t -> (constr_expr * (constr_expr * explicitation CAst.t option) list) fn
2172 ; proj : t -> (explicit_flag * (qualid * instance_expr option)
2173 * (constr_expr * explicitation CAst.t option) list * constr_expr) fn
2174 ; record : t -> ((qualid * constr_expr) list) fn
2175 ; cases : t -> (Constr.case_style * constr_expr option * case_expr list * branch_expr list) fn
2176 ; lettuple : t -> (lname list * (lname option * constr_expr option) * constr_expr * constr_expr) fn
2177 ; if_ : t -> (constr_expr * (lname option * constr_expr option) * constr_expr * constr_expr) fn
2178 ; hole : t -> Evar_kinds.glob_evar_kind option fn
2179 ; genarg : t -> Genarg.raw_generic_argument fn
2180 ; genargglob : t -> Genarg.glob_generic_argument fn
2181 ; patvar : t -> (Pattern.patvar) fn
2182 ; evar : t -> (Glob_term.existential_name CAst.t * (lident * constr_expr) list) fn
2183 ; sort : t -> sort_expr fn
2184 ; cast : t -> (constr_expr * Constr.cast_kind option * constr_expr) fn
2185 ; notation : t -> (notation_with_optional_scope option * notation * constr_notation_substitution) fn
2186 ; generalization : t -> (Glob_term.binding_kind * constr_expr) fn
2187 ; prim : t -> prim_token fn
2188 ; delimiters : t -> (delimiter_depth * string * constr_expr) fn
2189 ; array : t -> (instance_expr option * constr_expr array * constr_expr * constr_expr) fn
2190 }
2191
2192 let eval (self : t) genv env lvar ?loc = function
2193 | CRef (ref_, us) ->
2194 self.ref self genv env lvar ?loc (ref_, us)
2195 | CFix (lid, dl) ->
2196 self.fix self genv env lvar ?loc (lid, dl)
2197 | CCoFix (lid, dl) ->
2198 self.cofix self genv env lvar ?loc (lid, dl)
2199 | CProdN (bl,c2) ->
2200 self.prodn self genv env lvar ?loc (bl, c2)
2201 | CLambdaN (bl, c2) ->
2202 self.lambdan self genv env lvar ?loc (bl, c2)
2203 | CLetIn (na,c1,t,c2) ->
2204 self.letin self genv env lvar ?loc (na,c1,t,c2)
2205 | CAppExpl ((ref,us), args) ->
2206 self.appexpl self genv env lvar ?loc ((ref,us), args)
2207 | CApp (f, args) ->
2208 self.app self genv env lvar ?loc (f, args)
2209 | CProj (expl, f, args, c) ->
2210 self.proj self genv env lvar ?loc (expl, f, args, c)
2211 | CRecord fs ->
2212 self.record self genv env lvar ?loc fs
2213 | CCases (sty, rtnpo, tms, eqns) ->
2214 self.cases self genv env lvar ?loc (sty, rtnpo, tms, eqns)
2215 | CLetTuple (nal, (na,po), b, c) ->
2216 self.lettuple self genv env lvar ?loc (nal, (na,po), b, c)
2217 | CIf (c, (na,po), b1, b2) ->
2218 self.if_ self genv env lvar ?loc (c, (na,po), b1, b2)
2219 | CHole k ->
2220 self.hole self genv env lvar ?loc k
2221 | CGenarg gen ->
2222 self.genarg self genv env lvar ?loc gen
2223 | CGenargGlob gen ->
2224 self.genargglob self genv env lvar ?loc gen
2225 | CPatVar n ->
2226 self.patvar self genv env lvar ?loc n
2227 | CEvar (n, l) ->
2228 self.evar self genv env lvar ?loc (n, l)
2229 | CSort s ->
2230 self.sort self genv env lvar ?loc s
2231 | CCast (c1, k, c2) ->
2232 self.cast self genv env lvar ?loc (c1, k, c2)
2233 | CNotation (key, ntn, args) ->
2234 self.notation self genv env lvar ?loc (key, ntn, args)
2235 | CGeneralization (b, c) ->
2236 self.generalization self genv env lvar ?loc (b, c)
2237 | CPrim p ->
2238 self.prim self genv env lvar ?loc p
2239 | CDelimiters (depth, key, e) ->
2240 self.delimiters self genv env lvar ?loc (depth, key, e)
2241 | CArray (u,t,def,ty) ->
2242 self.array self genv env lvar ?loc (u,t,def,ty)
2243
2244 end
2245
2246 let smart_gapp f loc = function
2247 | [] -> f
2248 | l ->
2249 let loc' = f.CAst.loc in
2250 match DAst.get f with
2251 | GApp (g, args) -> DAst.make ?loc:(Loc.merge_opt loc' loc) @@ GApp (g, args@l)
2252 | _ -> DAst.make ?loc:(Loc.merge_opt (loc_of_glob_constr f) loc) @@ GApp (f, l)
2253
2254 let intern self genv lvar c = CAst.with_loc_val (fun ?loc ->
2255 Interner.eval self genv lvar ?loc c)
2256
2257 let intern_type self genv env = intern self genv (set_type_scope env)
2258
2259 let intern_type_no_implicit self genv env = intern self genv (restart_no_binders (set_type_scope env))
2260
2261 let intern_no_implicit self genv env = intern self genv (restart_no_binders env)
2262
2263 let intern_restart_binders self genv env = intern self genv (restart_lambda_binders env)
2264
2265 let intern_type_restart_binders self genv env = intern self genv (restart_prod_binders (set_type_scope env))
2266
2267 let rec intern_args self genv env lvar subscopes = function
2268 | [] -> []
2269 | a::args ->
2270 let (enva,subscopes) = apply_scope_env env subscopes in
2271 let a = intern_no_implicit self genv enva lvar a in
2272 a :: intern_args self genv env lvar subscopes args
2273
2274 let apply_args self genv env lvar loc hd args =
2275 let _, _, subscopes = find_appl_head_data genv env lvar hd in
2276 smart_gapp hd loc (intern_args self genv env lvar subscopes args)
2277
2278 let intern_impargs self genv env lvar head allimps subscopes args =
2279 let eargs, rargs = extract_explicit_arg allimps args in
2280 if !parsing_explicit then
2281 if List.is_empty eargs then intern_args self genv env lvar subscopes rargs
2282 else user_err Pp.(str "Arguments given by name or position not supported in explicit mode.")
2283 else
2284 let rec aux n imps subscopes eargs rargs =
2285 let (enva,subscopes') = apply_scope_env env subscopes in
2286 match (imps,rargs) with
2287 | (imp::imps', rargs) when is_status_implicit imp ->
2288 begin try
2289 let eargs',(_,(_,a)) = List.extract_first (fun (pos,a) -> match_implicit imp pos) eargs in
2290 intern_no_implicit self genv enva lvar a :: aux (n+1) imps' subscopes' eargs' rargs
2291 with Not_found ->
2292 if List.is_empty rargs && List.is_empty eargs && not (maximal_insertion_of imp) then
2293 (* Less regular arguments than expected: complete *)
2294 (* with implicit arguments if maximal insertion is set *)
2295 []
2296 else
2297 set_hole_implicit n (get_implicit_name n allimps) imp head :: aux (n+1) imps' subscopes' eargs rargs
2298 end
2299 | (imp::impl', a::rargs') ->
2300 intern_no_implicit self genv enva lvar a :: aux (n+1) impl' subscopes' eargs rargs'
2301 | (imp::impl', []) ->
2302 if not (List.is_empty eargs) then
2303 (let pr_position = function ExplByName id -> Id.print id | ExplByPos n -> str "position " ++ int n in
2304 let (pos,(loc,_)) = List.hd eargs in
2305 user_err ?loc (str "Not enough non implicit \
2306 arguments to accept the argument bound to " ++
2307 pr_position pos ++ str"."));
2308 []
2309 | ([], rargs) ->
2310 assert (List.is_empty eargs);
2311 intern_args self genv env lvar subscopes rargs
2312 in aux 1 allimps subscopes eargs rargs
2313
2314 let apply_impargs self genv env lvar loc c args =
2315 let head, impls, subscopes = find_appl_head_data genv env lvar c in
2316 let imps = select_impargs_size (List.length (List.filter (fun (_,x) -> x == None) args)) impls in
2317 let args = intern_impargs self genv env lvar head imps subscopes args in
2318 smart_gapp c loc args
2319
2320 let intern_local_binder self genv env lvar bind : intern_env * Glob_term.extended_glob_local_binder list =
2321 let intern env = intern self genv env lvar in
2322 intern_local_binder_aux ~dump:true intern (snd lvar) env bind
2323
2324 (* Expands a multiple pattern into a disjunction of multiple patterns *)
2325 let intern_multiple_pattern genv env ntnvars n pl =
2326 let env = { pat_ids = None; pat_scopes = ([],env.scopes) } in
2327 let idsl_pll = List.map (intern_cases_pattern test_kind_tolerant genv ntnvars env empty_alias) pl in
2328 let loc = loc_of_multiple_pattern pl in
2329 check_number_of_pattern loc n pl;
2330 product_of_cases_patterns empty_alias idsl_pll
2331
2332 (* Expands a disjunction of multiple pattern *)
2333 let intern_disjunctive_multiple_pattern genv env ntnvars loc n mpl =
2334 assert (not (List.is_empty mpl));
2335 let mpl' = List.map (intern_multiple_pattern genv env ntnvars n) mpl in
2336 let (idsl,mpl') = List.split mpl' in
2337 let ids = List.hd idsl in
2338 List.iter2 check_linearity (List.map loc_of_multiple_pattern mpl) idsl;
2339 check_or_pat_variables loc ids (List.tl idsl);
2340 (ids,List.flatten mpl')
2341
2342 (* Expands a pattern-matching clause [lhs => rhs] *)
2343 let intern_eqn self genv env (_, ntnvars as lvars) n {loc;v=(lhs,rhs)} =
2344 let eqn_ids,pll = intern_disjunctive_multiple_pattern genv env ntnvars loc n lhs in
2345 (* Linearity implies the order in ids is irrelevant *)
2346 let eqn_ids = List.map (fun x -> x.v) eqn_ids in
2347 let env_ids = List.fold_right Id.Set.add eqn_ids env.ids in
2348 List.map (fun (asubst,pl) ->
2349 let rhs = replace_vars_constr_expr asubst rhs in
2350 let rhs' = intern_no_implicit self genv {env with ids = env_ids} lvars rhs in
2351 CAst.make ?loc (eqn_ids,pl,rhs')) pll
2352
2353 let intern_case_item self genv env lvar forbidden_names_for_gen (tm,na,t) =
2354 (* the "match" part *)
2355 let tm' = intern_no_implicit self genv env lvar tm in
2356 (* the "as" part *)
2357 let extra_id,na =
2358 let loc = tm'.CAst.loc in
2359 match DAst.get tm', na with
2360 | GVar id, None when not (Id.Map.mem id (snd lvar)) -> Some id, CAst.make ?loc @@ Name id
2361 | GRef (GlobRef.VarRef id, _), None -> Some id, CAst.make ?loc @@ Name id
2362 | _, None -> None, CAst.make Anonymous
2363 | _, Some ({ CAst.loc; v = na } as lna) -> None, lna in
2364 (* the "in" part *)
2365 let match_td,typ = match t with
2366 | Some t ->
2367 let (ind,ind_ids,alias_subst,l) =
2368 intern_ind_pattern genv (snd lvar) (env_for_pattern (set_type_scope env)) t in
2369 let (mib,mip) = Inductive.lookup_mind_specif genv ind in
2370 let nparams = (List.length (mib.Declarations.mind_params_ctxt)) in
2371 (* for "in Vect n", we answer (["n","n"],[(loc,"n")])
2372
2373 for "in Vect (S n)", we answer ((match over "m", relevant branch is "S
2374 n"), abstract over "m") = ([("m","S n")],[(loc,"m")]) where "m" is
2375 generated from the canonical name of the inductive and outside of
2376 {forbidden_names_for_gen} *)
2377 let (match_to_do,nal) =
2378 let rec canonize_args case_rel_ctxt arg_pats forbidden_names match_acc var_acc =
2379 let add_name l = function
2380 | { CAst.v = Anonymous } -> l
2381 | { CAst.loc; v = (Name y as x) } -> (y, DAst.make ?loc @@ PatVar x) :: l in
2382 match case_rel_ctxt,arg_pats with
2383 | [],[] ->
2384 (add_name match_acc na, var_acc)
2385 | (LocalAssum (cano_name,ty) | LocalDef (cano_name,_,ty)) :: t, c::tt ->
2386 begin match DAst.get c with
2387 | PatVar x ->
2388 let loc = c.CAst.loc in
2389 canonize_args t tt forbidden_names
2390 (add_name match_acc CAst.(make ?loc x)) (CAst.make ?loc x::var_acc)
2391 | _ ->
2392 let fresh =
2393 Namegen.next_name_away_with_default_using_types genv (Evd.from_env genv)
2394 "iV" cano_name.binder_name forbidden_names (EConstr.of_constr ty) in
2395 canonize_args t tt (Id.Set.add fresh forbidden_names)
2396 ((fresh,c)::match_acc) ((CAst.make ?loc:(cases_pattern_loc c) @@ Name fresh)::var_acc)
2397 end
2398 | _ -> assert false in
2399 let _,args_rel =
2400 List.chop nparams (List.rev mip.Declarations.mind_arity_ctxt) in
2401 canonize_args args_rel l forbidden_names_for_gen [] [] in
2402 (Id.Set.of_list (List.map (fun id -> id.CAst.v) ind_ids),alias_subst,match_to_do),
2403 Some (CAst.make ?loc:(cases_pattern_expr_loc t) (ind,List.rev_map (fun x -> x.v) nal))
2404 | None ->
2405 (Id.Set.empty,Id.Map.empty,[]), None in
2406 (tm',(na.CAst.v, typ)), extra_id, match_td
2407
2408 let intern_proj self genv env lvar ?loc expl (qid,us) args1 c args2 =
2409 let intern env = intern self genv env lvar in
2410 let f,args1 =
2411 intern_applied_reference ~isproj:true intern env
2412 (Environ.named_context_val genv) lvar us args1 qid
2413 in
2414 match find_projection_data f with
2415 | Some (p, us, args0, nexpectedparams) ->
2416 (* A reference registered as projection *)
2417 check_not_notation_variable f (snd lvar);
2418 let head, impls, subscopes = find_appl_head_data genv env lvar f in
2419 let imps1, imps2 =
2420 if expl then
2421 [], []
2422 else
2423 let ngivenparams = List.length args0 + List.count (fun (_,x) -> Option.is_empty x) args1 in
2424 let nextraargs = List.length args2 in
2425 match select_impargs_size_for_proj ~nexpectedparams ~ngivenparams ~nextraargs impls with
2426 | Inl (imps1,imps2) -> (imps1,imps2)
2427 | Inr l ->
2428 let l = Lazy.force l in
2429 let n = match l with [n] -> n | _ -> 2 in (* singular only when l = [1] *)
2430 user_err ?loc:qid.CAst.loc (str "Projection " ++ pr_qualid qid ++ str " expected " ++ pr_choice int l ++
2431 str (String.plural n " explicit parameter") ++ str ".")
2432 in
2433 let subscopes1, subscopes2 = try List.chop (nexpectedparams + 1) subscopes with Failure _ -> subscopes, [] in
2434 let c,args1 = List.sep_last (intern_impargs self genv env lvar head imps1 subscopes1 (args1@[c,None])) in
2435 let p = DAst.make ?loc (GProj ((p,us),args0@args1,c)) in
2436 let args2 = intern_impargs self genv env lvar head imps2 subscopes2 args2 in
2437 smart_gapp p loc args2
2438 | None ->
2439 (* Tolerate a use of t.(f) notation for an ordinary application until a decision is taken about it *)
2440 if expl then intern env (CAst.make ?loc (CAppExpl ((qid,us), List.map fst args1@c::List.map fst args2)))
2441 else intern env (CAst.make ?loc (CApp ((CAst.make ?loc:qid.CAst.loc (CRef (qid,us))), args1@(c,None)::args2)))
2442
2443 let ref self genv env lvar ?loc (ref, us) =
2444 let intern env = intern self genv env lvar in
2445 let c,_ =
2446 intern_applied_reference ~isproj:false intern env (Environ.named_context_val genv)
2447 lvar us [] ref
2448 in
2449 apply_impargs self genv env lvar loc c []
2450
2451 let fix self genv env (_, ntnvars as lvar) ?loc ({ CAst.loc = locid; v = iddef}, dl) =
2452 let intern env = intern self genv env lvar in
2453 let intern_type env = intern_type self genv env lvar in
2454 let lf = List.map (fun ({CAst.v = id},_,_,_,_,_) -> id) dl in
2455 let dl = Array.of_list dl in
2456 let n =
2457 try List.index0 Id.equal iddef lf
2458 with Not_found as exn ->
2459 let _, info = Exninfo.capture exn in
2460 let info = Option.cata (Loc.add_loc info) info locid in
2461 Exninfo.iraise (InternalizationError (UnboundFixName (false,iddef)),info)
2462 in
2463 let env = restart_lambda_binders env in
2464 let idl_temp = Array.map
2465 (fun (id,_,recarg,bl,ty,_) ->
2466 let recarg = Option.map (function { CAst.v = v; loc } -> match v with
2467 | CStructRec i -> i
2468 | _ -> user_err ?loc Pp.(str "Well-founded induction requires Program Fixpoint or Function.")) recarg
2469 in
2470 let intern_local_binder env = intern_local_binder self genv env lvar in
2471 let (env',bl) = List.fold_left intern_local_binder (env,[]) bl in
2472 let bl = List.rev_map glob_local_binder_of_extended bl in
2473 let n = Option.map (fun recarg ->
2474 let exception Found of int in
2475 try
2476 List.fold_left (fun n (id,_,_,body,_) ->
2477 match body, Name.equal id (Name recarg.v) with
2478 | None, true -> raise (Found n)
2479 | Some _, true ->
2480 CErrors.user_err ?loc
2481 (Name.print id ++ str" must be a proper parameter and not a local definition.")
2482 | None, false -> n + 1
2483 | Some _, false -> n (* let-ins don't count *))
2484 0 bl |> ignore;
2485 CErrors.user_err ?loc:recarg.loc
2486 (str "No parameter named " ++ Id.print recarg.v ++ str".");
2487 with
2488 Found k -> k)
2489 recarg
2490 in
2491 let bl_impls = remember_binders_impargs env' bl in
2492 (n, bl, intern_type env' ty, bl_impls)) dl in
2493 (* We add the recursive functions to the environment *)
2494 let env_rec = List.fold_left_i (fun i en name ->
2495 let (_,bli,tyi,_) = idl_temp.(i) in
2496 let binder_index,fix_args = impls_binder_list 1 bli in
2497 let impls = impls_type_list ~args:fix_args binder_index tyi in
2498 push_name_env ~dump:true ntnvars impls en (CAst.make @@ Name name)) 0 env lf in
2499 let idl = Array.map2 (fun (_,_,_,_,_,bd) (n,bl,ty,before_impls) ->
2500 (* We add the binders common to body and type to the environment *)
2501 let env_body = restore_binders_impargs env_rec before_impls in
2502 (n,bl,ty,intern {env_body with tmp_scope = []} bd)) dl idl_temp in
2503 DAst.make ?loc @@
2504 GRec (GFix
2505 (Array.map (fun (ro,_,_,_) -> ro) idl,n),
2506 Array.of_list lf,
2507 Array.map (fun (_,bl,_,_) -> bl) idl,
2508 Array.map (fun (_,_,ty,_) -> ty) idl,
2509 Array.map (fun (_,_,_,bd) -> bd) idl)
2510
2511 let cofix self genv env (_, ntnvars as lvar) ?loc ({ CAst.loc = locid; v = iddef }, dl) =
2512 let intern env = intern self genv env lvar in
2513 let intern_type env = intern_type self genv env lvar in
2514 let lf = List.map (fun ({CAst.v = id},_,_,_,_) -> id) dl in
2515 let dl = Array.of_list dl in
2516 let n =
2517 try List.index0 Id.equal iddef lf
2518 with Not_found as exn ->
2519 let _, info = Exninfo.capture exn in
2520 let info = Option.cata (Loc.add_loc info) info locid in
2521 Exninfo.iraise (InternalizationError (UnboundFixName (true,iddef)), info)
2522 in
2523 let env = restart_lambda_binders env in
2524 let idl_tmp = Array.map
2525 (fun ({ CAst.loc; v = id },_,bl,ty,_) ->
2526 let intern_local_binder env = intern_local_binder self genv env lvar in
2527 let (env',rbl) = List.fold_left intern_local_binder (env,[]) bl in
2528 let bl = List.rev (List.map glob_local_binder_of_extended rbl) in
2529 let bl_impls = remember_binders_impargs env' bl in
2530 (bl,intern_type env' ty,bl_impls)) dl in
2531 let env_rec = List.fold_left_i (fun i en name ->
2532 let (bli,tyi,_) = idl_tmp.(i) in
2533 let binder_index,cofix_args = impls_binder_list 1 bli in
2534 push_name_env ~dump:true ntnvars (impls_type_list ~args:cofix_args binder_index tyi)
2535 en (CAst.make @@ Name name)) 0 env lf in
2536 let idl = Array.map2 (fun (_,_,_,_,bd) (b,c,bl_impls) ->
2537 (* We add the binders common to body and type to the environment *)
2538 let env_body = restore_binders_impargs env_rec bl_impls in
2539 (b,c,intern {env_body with tmp_scope = []} bd)) dl idl_tmp in
2540 DAst.make ?loc @@
2541 GRec (GCoFix n,
2542 Array.of_list lf,
2543 Array.map (fun (bl,_,_) -> bl) idl,
2544 Array.map (fun (_,ty,_) -> ty) idl,
2545 Array.map (fun (_,_,bd) -> bd) idl)
2546
2547 let prodn self genv env lvar ?loc (bl,c2) =
2548 let intern_type env = intern_type self genv env lvar in
2549 let intern_local_binder env = intern_local_binder self genv env lvar in
2550 match bl with
2551 | [] ->
2552 anomaly (Pp.str "The AST is malformed, found prod without binders.")
2553 | bl ->
2554 let (env',bl) = List.fold_left intern_local_binder (switch_prod_binders env,[]) bl in
2555 expand_binders ?loc mkGProd bl (intern_type env' c2)
2556
2557 let lambdan self genv env lvar ?loc (bl, c2) =
2558 let intern env = intern self genv env lvar in
2559 let intern_local_binder env = intern_local_binder self genv env lvar in
2560 match bl with
2561 | [] ->
2562 anomaly (Pp.str "The AST is malformed, found lambda without binders.")
2563 | bl ->
2564 let (env',bl) = List.fold_left intern_local_binder (reset_tmp_scope (switch_lambda_binders env),[]) bl in
2565 expand_binders ?loc mkGLambda bl (intern env' c2)
2566
2567 let letin self genv env lvar ?loc (na,c1,t,c2) =
2568 let inc1 = intern_restart_binders self genv (reset_tmp_scope env) lvar c1 in
2569 let int = Option.map (intern_type_restart_binders self genv env lvar) t in
2570 DAst.make ?loc @@
2571 GLetIn (na.CAst.v, None, inc1, int,
2572 intern_restart_binders self genv (push_name_env ~dump:true (snd lvar) (impls_term_list 1 inc1) env na) lvar c2)
2573
2574 let appexpl self genv env lvar ?loc ((ref,us), args) =
2575 let intern env = intern self genv env lvar in
2576 let f,args =
2577 let args = List.map (fun a -> (a,None)) args in
2578 intern_applied_reference ~isproj:false intern env (Environ.named_context_val genv)
2579 lvar us args ref
2580 in
2581 check_not_notation_variable f (snd lvar);
2582 (* Rem: GApp(_,f,[]) stands for @f *)
2583 if args = [] then DAst.make ?loc @@ GApp (f,[])
2584 else apply_args self genv env lvar loc f (List.map fst args)
2585
2586 let app self genv env lvar ?loc (f, args) =
2587 let intern env = intern self genv env lvar in
2588 let apply_impargs env = apply_impargs self genv env lvar in
2589 let apply_args env = apply_args self genv env lvar in
2590 begin match f.CAst.v with
2591 (* t.(f args') args *)
2592 | CProj (expl, (ref,us), args', c) ->
2593 intern_proj self genv env lvar ?loc:f.CAst.loc expl (ref,us) args' c args
2594 | CRef (ref,us) ->
2595 let f, args = intern_applied_reference ~isproj:false intern env
2596 (Environ.named_context_val genv) lvar us args ref in
2597 apply_impargs env loc f args
2598 | CNotation (_,ntn,ntnargs) ->
2599 let c = intern_notation intern env (snd lvar) loc ntn ntnargs in
2600 apply_impargs env loc c args
2601 | _ ->
2602 let f = intern_no_implicit self genv env lvar f in
2603 let args = extract_regular_arguments args in
2604 apply_args env loc f args
2605 end
2606
2607 let proj self genv env lvar ?loc (expl, f, args, c) =
2608 intern_proj self genv env lvar ?loc expl f args c []
2609
2610 let record self genv env lvar ?loc fs =
2611 let st = Evar_kinds.Define (not (Program.get_proofs_transparency ())) in
2612 let fields =
2613 sort_fields genv ~complete:true loc fs
2614 (fun _idx fieldname constructorname ->
2615 let open Evar_kinds in
2616 let fieldinfo : Evar_kinds.record_field =
2617 {fieldname=Option.get fieldname; recordname=inductive_of_constructor constructorname}
2618 in
2619 CAst.make ?loc @@ CHole (Some
2620 (GQuestionMark { Evar_kinds.default_question_mark with
2621 Evar_kinds.qm_obligation=st;
2622 Evar_kinds.qm_record_field=Some fieldinfo
2623 })))
2624 in
2625 begin
2626 match fields with
2627 | None -> user_err ?loc (str"No constructor inference.")
2628 | Some (n, constrname, args) ->
2629 let hd = DAst.make @@ GRef (constrname,None) in
2630 let pars = List.make n (CAst.make ?loc @@ CHole (None)) in
2631 apply_args self genv env lvar loc hd (List.rev_append pars args)
2632 end
2633
2634 let cases self genv env lvar ?loc (sty, rtnpo, tms, eqns) =
2635 let intern_type env = intern_type self genv env lvar in
2636 let as_in_vars = List.fold_left (fun acc (_,na,inb) ->
2637 (Option.fold_left (fun acc { CAst.v = y } -> Name.fold_right Id.Set.add y acc) acc na))
2638 Id.Set.empty tms in
2639 (* as, in & return vars *)
2640 let forbidden_vars = Option.cata free_vars_of_constr_expr as_in_vars rtnpo in
2641 let tms,ex_ids,aliases,match_from_in = List.fold_right
2642 (fun citm (inds,ex_ids,asubst,matchs) ->
2643 let ((tm,ind),extra_id,(ind_ids,alias_subst,match_td)) =
2644 intern_case_item self genv env lvar forbidden_vars citm in
2645 (tm,ind)::inds,
2646 Id.Set.union ind_ids (Option.fold_right Id.Set.add extra_id ex_ids),
2647 merge_subst alias_subst asubst,
2648 List.rev_append match_td matchs)
2649 tms ([],Id.Set.empty,Id.Map.empty,[]) in
2650 let env' = Id.Set.fold
2651 (fun var bli -> push_name_env ~dump:true (snd lvar) [] bli (CAst.make @@ Name var))
2652 (Id.Set.union ex_ids as_in_vars)
2653 (restart_lambda_binders env)
2654 in
2655 (* PatVars before a real pattern do not need to be matched *)
2656 let stripped_match_from_in =
2657 let rec aux = function
2658 | [] -> []
2659 | (_, c) :: q when is_patvar c -> aux q
2660 | l -> l
2661 in aux match_from_in in
2662 let rtnpo = Option.map (replace_vars_constr_expr aliases) rtnpo in
2663 let rtnpo = match stripped_match_from_in with
2664 | [] -> Option.map (intern_type (slide_binders env')) rtnpo (* Only PatVar in "in" clauses *)
2665 | l ->
2666 (* Build a return predicate by expansion of the patterns of the "in" clause *)
2667 let thevars, thepats = List.split l in
2668 let sub_rtn = (* Some (GSort (Loc.ghost,GType None)) *) None in
2669 let sub_tms = List.map (fun id -> (DAst.make @@ GVar id),(Name id,None)) thevars (* "match v1,..,vn" *) in
2670 let main_sub_eqn = CAst.make @@
2671 ([],thepats, (* "|p1,..,pn" *)
2672 Option.cata (intern_type_no_implicit self genv env' lvar)
2673 (DAst.make ?loc @@ GHole (GCasesType))
2674 rtnpo) (* "=> P" if there were a return predicate P, and "=> _" otherwise *) in
2675 let catch_all_sub_eqn =
2676 if List.for_all (irrefutable genv) thepats then [] else
2677 [CAst.make @@ ([],List.make (List.length thepats) (DAst.make @@ PatVar Anonymous), (* "|_,..,_" *)
2678 DAst.make @@ GHole(GImpossibleCase))] (* "=> _" *) in
2679 Some (DAst.make @@ GCases(RegularStyle,sub_rtn,sub_tms,main_sub_eqn::catch_all_sub_eqn))
2680 in
2681 let eqns' = List.map (intern_eqn self genv env lvar (List.length tms)) eqns in
2682 DAst.make ?loc @@
2683 GCases (sty, rtnpo, tms, List.flatten eqns')
2684
2685 let lettuple self genv env lvar ?loc (nal, (na,po), b, c) =
2686 let intern env = intern self genv env lvar in
2687 let intern_type env = intern_type self genv env lvar in
2688 let env' = reset_tmp_scope env in
2689 (* "in" is None so no match to add *)
2690 let ((b',(na',_)),_,_) = intern_case_item self genv env' lvar Id.Set.empty (b,na,None) in
2691 let p' = Option.map (fun u ->
2692 let env'' = push_name_env ~dump:true (snd lvar) [] env'
2693 (CAst.make na') in
2694 intern_type (slide_binders env'') u) po in
2695 DAst.make ?loc @@
2696 GLetTuple (List.map (fun { CAst.v } -> v) nal, (na', p'), b',
2697 intern (List.fold_left (push_name_env ~dump:true (snd lvar) []) env nal) c)
2698
2699 let if_ self genv env lvar ?loc (c, (na,po), b1, b2) =
2700 let intern env = intern self genv env lvar in
2701 let intern_type env = intern_type self genv env lvar in
2702 let env' = reset_tmp_scope env in
2703 let ((c',(na',_)),_,_) = intern_case_item self genv env' lvar Id.Set.empty (c,na,None) in (* no "in" no match to ad too *)
2704 let p' = Option.map (fun p ->
2705 let env'' = push_name_env ~dump:true (snd lvar) [] env
2706 (CAst.make na') in
2707 intern_type (slide_binders env'') p) po in
2708 DAst.make ?loc @@
2709 GIf (c', (na', p'), intern env b1, intern env b2)
2710
2711 let hole self genv env lvar ?loc k =
2712 let k = match k with
2713 | None ->
2714 let st = Evar_kinds.Define (not (Program.get_proofs_transparency ())) in
2715 GQuestionMark { Evar_kinds.default_question_mark with Evar_kinds.qm_obligation=st; }
2716 | Some k -> k
2717 in
2718 DAst.make ?loc @@
2719 GHole k
2720
2721 let genarg self genv env lvar ?loc gen =
2722 let (ltacvars, ntnvars) = lvar in
2723 (* Preventively declare notation variables in ltac as non-bindings *)
2724 Id.Map.iter (fun x status -> status.Genintern.ntnvar_used_as_binder <- false) ntnvars;
2725 let extra = ltacvars.ltac_extra in
2726 (* We inform ltac that the interning vars and the notation vars are bound *)
2727 (* but we could instead rely on the "intern_sign" *)
2728 let lvars = Id.Set.union ltacvars.ltac_bound ltacvars.ltac_vars in
2729 let lvars = Id.Set.union lvars (Id.Map.domain ntnvars) in
2730 let ltacvars = Id.Set.union lvars env.ids in
2731 (* Propagating enough information for mutual interning with tac-in-term *)
2732 let intern_sign = {
2733 Genintern.intern_ids = env.ids;
2734 Genintern.notation_variable_status = ntnvars
2735 } in
2736 let ist = {
2737 Genintern.genv;
2738 ltacvars;
2739 extra;
2740 intern_sign;
2741 strict_check = match env.strict_check with None -> false | Some b -> b;
2742 } in
2743 let intern = if env.pattern_mode
2744 then Genintern.generic_intern_pat ?loc
2745 else Genintern.generic_intern
2746 in
2747 let (_, glb) = intern ist gen in
2748 DAst.make ?loc @@
2749 GGenarg glb
2750
2751 let genargglob self genv env lvar ?loc gen =
2752 DAst.make ?loc @@ GGenarg gen
2753
2754 (* Parsing pattern variables *)
2755 let patvar self genv env lvar ?loc n =
2756 if env.pattern_mode then
2757 DAst.make ?loc @@
2758 GPatVar (Evar_kinds.SecondOrderPatVar n)
2759 else
2760 Loc.raise ?loc (InternalizationError IllegalMetavariable)
2761
2762 let evar self genv env lvar ?loc (n, l) =
2763 match l with
2764 | [] when env.pattern_mode ->
2765 DAst.make ?loc @@
2766 GPatVar (Evar_kinds.FirstOrderPatVar n.CAst.v)
2767 | l ->
2768 DAst.make ?loc @@
2769 GEvar (n, List.map (on_snd (intern_no_implicit self genv env lvar)) l)
2770
2771 let sort self genv env lvar ?loc s =
2772 DAst.make ?loc @@
2773 GSort (intern_sort ~local_univs:env.local_univs s)
2774
2775 let cast self genv env lvar ?loc (c1, k, c2) =
2776 let intern env = intern self genv env lvar in
2777 let intern_type env = intern_type self genv env lvar in
2778 let c2 = intern_type (slide_binders env) c2 in
2779 let sc = Notation.compute_glob_type_scope c2 in
2780 let env' = {env with tmp_scope = sc @ env.tmp_scope} in
2781 let c1 = intern env' c1 in
2782 DAst.make ?loc @@
2783 GCast (c1, k, c2)
2784
2785 let notation self genv env lvar ?loc (_, ntn, args) =
2786 let intern env = intern self genv env lvar in
2787 match ntn, args with
2788 | (InConstrEntry,"- _"), ([a],[],[],[]) when is_non_zero a ->
2789 let p = match a.CAst.v with CPrim (Number (_, p)) -> p | _ -> assert false in
2790 intern env (CAst.make ?loc @@ CPrim (Number (SMinus,p)))
2791 | (InConstrEntry,"( _ )"), ([a],[],[],[]) ->
2792 intern env a
2793 | ntn, args ->
2794 let c = intern_notation intern env (snd lvar) loc ntn args in
2795 apply_impargs self genv env lvar loc c []
2796
2797 let generalization self genv env lvar ?loc (b, c) =
2798 let intern env = intern self genv env lvar in
2799 intern_generalization intern env (snd lvar) loc b c
2800
2801 let prim self genv env lvar ?loc p =
2802 let c = fst (Notation.interp_prim_token ?loc p (env.tmp_scope,env.scopes)) in
2803 apply_impargs self genv env lvar loc c []
2804
2805 let delimiters self genv env lvar ?loc (depth, key, e) =
2806 let intern env = intern self genv env lvar in
2807 let sc = find_delimiters_scope ?loc key in
2808 let env = match depth with
2809 | DelimOnlyTmpScope -> {env with tmp_scope = [sc]}
2810 | DelimUnboundedScope -> {env with tmp_scope = []; scopes = sc :: env.scopes} in
2811 intern env e
2812
2813 let array self genv env lvar ?loc (u,t,def,ty) =
2814 let intern env = intern self genv env lvar in
2815 DAst.make ?loc @@ GArray(intern_instance ~local_univs:env.local_univs u, Array.map (intern env) t, intern env def, intern env ty)
2816
2817 let default : Interner.t =
2818 { ref
2819 ; fix
2820 ; cofix
2821 ; prodn
2822 ; lambdan
2823 ; letin
2824 ; appexpl
2825 ; app
2826 ; proj
2827 ; record
2828 ; cases
2829 ; lettuple
2830 ; if_
2831 ; hole
2832 ; genarg
2833 ; genargglob
2834 ; patvar
2835 ; evar
2836 ; sort
2837 ; cast
2838 ; notation
2839 ; generalization
2840 ; prim
2841 ; delimiters
2842 ; array
2843 }
2844
2845 let internalize genv env lvar c =
2846 NewProfile.profile "intern" (fun () -> intern default genv env lvar c) ()
2847
2848 (**************************************************************************)
2849 (* Functions to translate constr_expr into glob_constr *)
2850 (**************************************************************************)
2851
2852 let extract_ids env =
2853 List.fold_right Id.Set.add
2854 (Termops.ids_of_rel_context (Environ.rel_context env))
2855 Id.Set.empty
2856
2857 let bound_univs sigma = Evd.universe_binders sigma
2858
2859 let scope_of_type_kind env sigma = function
2860 | IsType -> Notation.current_type_scope_names ()
2861 | OfType typ -> compute_type_scope env sigma typ
2862 | WithoutTypeConstraint -> []
2863
2864 let allowed_binder_kind_of_type_kind = function
2865 | IsType -> AbsPi
2866 | OfType _ | WithoutTypeConstraint -> AbsLambda
2867
2868 let empty_ltac_sign = {
2869 ltac_vars = Id.Set.empty;
2870 ltac_bound = Id.Set.empty;
2871 ltac_extra = Genintern.Store.empty;
2872 }
2873
2874 let intern_gen kind env sigma
2875 ?(impls=empty_internalization_env) ?strict_check ?(pattern_mode=false) ?(ltacvars=empty_ltac_sign)
2876 c =
2877 let tmp_scope = Option.cata (scope_of_type_kind env sigma) [] kind in
2878 let k = Option.map allowed_binder_kind_of_type_kind kind in
2879 internalize env {ids = extract_ids env; strict_check; pattern_mode;
2880 local_univs = { bound = bound_univs sigma; unb_univs = true };
2881 tmp_scope = tmp_scope; scopes = [];
2882 impls; binder_block_names = Some k; ntn_binding_ids = Id.Set.empty}
2883 (ltacvars, Id.Map.empty) c
2884
2885 let intern_unknown_if_term_or_type env sigma c =
2886 intern_gen None env sigma c
2887
2888 let intern_gen kind env sigma ?impls ?strict_check ?pattern_mode ?ltacvars c =
2889 intern_gen (Some kind) env sigma ?impls ?strict_check ?pattern_mode ?ltacvars c
2890
2891 let intern_constr env sigma c = intern_gen WithoutTypeConstraint env sigma c
2892 let intern_type env sigma c = intern_gen IsType env sigma c
2893 let intern_pattern globalenv patt =
2894 let env = {pat_ids = None; pat_scopes = ([], [])} in
2895 intern_cases_pattern test_kind_tolerant globalenv Id.Map.empty env empty_alias patt
2896
2897 (*********************************************************************)
2898 (* Functions to parse and interpret constructions *)
2899
2900 (* All evars resolved *)
2901
2902 let interp_gen ?flags kind env sigma ?(impls=empty_internalization_env) c =
2903 let c = intern_gen kind ~impls env sigma c in
2904 understand ?flags ~expected_type:kind env sigma c
2905
2906 let interp_constr ?flags ?(expected_type=WithoutTypeConstraint) env sigma ?(impls=empty_internalization_env) c =
2907 interp_gen ?flags expected_type env sigma c
2908
2909 let interp_type ?flags env sigma ?(impls=empty_internalization_env) c =
2910 interp_gen ?flags IsType env sigma ~impls c
2911
2912 let interp_casted_constr ?flags env sigma ?(impls=empty_internalization_env) c typ =
2913 interp_gen ?flags (OfType typ) env sigma ~impls c
2914
2915 (* Not all evars expected to be resolved *)
2916
2917 let interp_open_constr ?(expected_type=WithoutTypeConstraint) env sigma c =
2918 understand_tcc env sigma (intern_gen expected_type env sigma c)
2919
2920 (* Not all evars expected to be resolved and computation of implicit args *)
2921
2922 let interp_constr_evars_gen_impls ?(flags=Pretyping.all_no_fail_flags) env sigma
2923 ?(impls=empty_internalization_env) expected_type c =
2924 let c = intern_gen expected_type ~impls env sigma c in
2925 let imps = Implicit_quantifiers.implicits_of_glob_constr ~with_products:(expected_type == IsType) c in
2926 let sigma, c = understand_tcc ~flags env sigma ~expected_type c in
2927 sigma, (c, imps)
2928
2929 let interp_constr_evars_impls ?(program_mode=false) ?(poly = PolyFlags.default) env sigma ?(impls=empty_internalization_env) c =
2930 let flags = { Pretyping.all_no_fail_flags with program_mode ; poly } in
2931 interp_constr_evars_gen_impls ~flags env sigma ~impls WithoutTypeConstraint c
2932
2933 let interp_casted_constr_evars_impls ?(program_mode=false) ?(poly = PolyFlags.default) env evdref ?(impls=empty_internalization_env) c typ =
2934 let flags = { Pretyping.all_no_fail_flags with program_mode ; poly } in
2935 interp_constr_evars_gen_impls ~flags env evdref ~impls (OfType typ) c
2936
2937 let interp_type_evars_impls ?(flags=Pretyping.all_no_fail_flags) env sigma ?(impls=empty_internalization_env) c =
2938 interp_constr_evars_gen_impls ~flags env sigma ~impls IsType c
2939
2940 (* Not all evars expected to be resolved, with side-effect on evars *)
2941
2942 let interp_constr_evars_gen ?flags ?(program_mode=false) env sigma ?(impls=empty_internalization_env) expected_type c =
2943 let c = intern_gen expected_type ~impls env sigma c in
2944 let flags = Option.default { Pretyping.all_no_fail_flags with program_mode } flags in
2945 understand_tcc ~flags env sigma ~expected_type c
2946
2947 let interp_constr_evars ?program_mode env evdref ?(impls=empty_internalization_env) c =
2948 interp_constr_evars_gen ?program_mode env evdref WithoutTypeConstraint ~impls c
2949
2950 let interp_casted_constr_evars ?flags ?program_mode env sigma ?(impls=empty_internalization_env) c typ =
2951 interp_constr_evars_gen ?flags ?program_mode env sigma ~impls (OfType typ) c
2952
2953 let interp_type_evars ?program_mode env sigma ?(impls=empty_internalization_env) c =
2954 interp_constr_evars_gen ?program_mode env sigma IsType ~impls c
2955
2956 (* Miscellaneous *)
2957 let intern_constr_pattern env sigma ?(as_type=false) ?strict_check ?(ltacvars=empty_ltac_sign) c =
2958 let c = intern_gen (if as_type then IsType else WithoutTypeConstraint)
2959 ?strict_check ~pattern_mode:true ~ltacvars env sigma c in
2960 pattern_of_glob_constr env c
2961
2962 let interp_constr_pattern env sigma ?as_type ?strict_check c =
2963 let ids, pat = intern_constr_pattern env sigma ?as_type ?strict_check c in
2964 ids, Patternops.interp_pattern env sigma Glob_ops.empty_lvar pat
2965
2966 let intern_core kind env sigma ?strict_check ?(pattern_mode=false) ?(ltacvars=empty_ltac_sign)
2967 { Genintern.intern_ids = ids; Genintern.notation_variable_status = vl } c =
2968 let tmp_scope = scope_of_type_kind env sigma kind in
2969 let impls = empty_internalization_env in
2970 let k = allowed_binder_kind_of_type_kind kind in
2971 internalize env
2972 {ids; strict_check; pattern_mode;
2973 local_univs = { bound = bound_univs sigma; unb_univs = true };
2974 tmp_scope; scopes = []; impls;
2975 binder_block_names = Some (Some k); ntn_binding_ids = Id.Set.empty}
2976 (ltacvars, vl) c
2977
2978 let interp_notation_constr env ?(impls=empty_internalization_env) nenv a =
2979 let ids = extract_ids env in
2980 (* [vl] is intended to remember the scope of the free variables of [a] *)
2981 let make_status scopes typ = {
2982 Genintern.ntnvar_used = [];
2983 ntnvar_used_as_binder = false;
2984 ntnvar_scopes = scopes;
2985 ntnvar_binding_ids = None;
2986 ntnvar_typ = typ;
2987 }
2988 in
2989 let vl = Id.Map.map (function
2990 | (NtnInternTypeAny None | NtnInternTypeOnlyBinder) as typ -> make_status None typ
2991 | NtnInternTypeAny (Some scope) as typ -> make_status (Some ([scope],[])) typ)
2992 nenv.ninterp_var_type in
2993 let impls = Id.Map.fold (fun id _ impls -> Id.Map.remove id impls) nenv.ninterp_var_type impls in
2994 let c = internalize env
2995 {ids; strict_check = Some true; pattern_mode = false;
2996 local_univs = empty_local_univs;
2997 tmp_scope = []; scopes = []; impls; binder_block_names = None; ntn_binding_ids = Id.Set.empty}
2998 (empty_ltac_sign, vl) a
2999 in
3000 (* Splits variables into those that are binding, bound, or both *)
3001 (* Translate and check that [c] has all its free variables bound in [vars] *)
3002 let a, reversible = notation_constr_of_glob_constr nenv c in
3003 (* binding and bound *)
3004 let out_scope = function None -> [],[] | Some (a,l) -> a,l in
3005 let out_bindings = function None -> Id.Set.empty | Some a -> a in
3006 let unused = match reversible with NonInjective ids -> ids | _ -> [] in
3007 let vars = Id.Map.mapi (fun id status ->
3008 (status.Genintern.ntnvar_used_as_binder && not (List.mem_f Id.equal id unused),
3009 out_scope status.ntnvar_scopes, out_bindings status.ntnvar_binding_ids)) vl in
3010 (* Returns [a] and the ordered list of variables with their scopes *)
3011 vars, a, reversible
3012
3013 (* Interpret binders and contexts *)
3014
3015 let interp_binder env sigma na t =
3016 let t = intern_gen IsType env sigma t in
3017 let t' = locate_if_hole ?loc:(loc_of_glob_constr t) na t in
3018 understand ~expected_type:IsType env sigma t'
3019
3020 let interp_binder_evars env sigma na t =
3021 let t = intern_gen IsType env sigma t in
3022 let t' = locate_if_hole ?loc:(loc_of_glob_constr t) na t in
3023 understand_tcc env sigma ~expected_type:IsType t'
3024
3025 let my_intern_constr env lvar acc c =
3026 internalize env acc lvar c
3027
3028 let default_internalization_env ids bound_univs impl_env =
3029 {ids; strict_check = Some true; pattern_mode = false;
3030 local_univs = { bound = bound_univs; unb_univs = true };
3031 tmp_scope = []; scopes = []; impls = impl_env;
3032 binder_block_names = Some (Some AbsPi);
3033 ntn_binding_ids = Id.Set.empty}
3034
3035 let intern_context env ~bound_univs impl_env binders =
3036 let lvar = (empty_ltac_sign, Id.Map.empty) in
3037 let ids =
3038 (* We assume all ids around are parts of the prefix of the current
3039 context being interpreted *)
3040 extract_ids env in
3041 let lenv, bl = List.fold_left
3042 (fun (lenv, bl) b ->
3043 let (env, bl) = intern_local_binder_aux ~dump:false (my_intern_constr env lvar) Id.Map.empty (lenv, bl) b in
3044 (env, bl))
3045 (default_internalization_env ids bound_univs impl_env, [])
3046 binders in
3047 (lenv.impls, List.map glob_local_binder_of_extended bl)
3048
3049 let impl_of_binder_kind na = function
3050 | NonMaxImplicit -> CAst.make (Some (na,false))
3051 | MaxImplicit -> CAst.make (Some (na,true))
3052 | Explicit -> CAst.make None
3053
3054 let push_auto_implicit env sigma t int_env id =
3055 let var_info = Id.Map.find id int_env.impls in
3056 let imps = List.map (fun imp -> CAst.make (Option.map (fun imp -> (pi1 imp.impl_pos,imp.impl_max)) imp)) var_info.var_impls in
3057 let imps = compute_internalization_data env sigma ~silent:false id var_info.var_intern_typ t imps in (* add automatic implicit arguments to manual ones *)
3058 { int_env with impls = Id.Map.add id imps int_env.impls }
3059
3060 let interp_context_evars_gen ?(program_mode=false) ?(unconstrained_sorts = false) ?(poly = PolyFlags.default) ?(impl_env=empty_internalization_env) ?(autoimp_enable=true) ~dump env sigma make_decl push_decl bl =
3061 let lvar = (empty_ltac_sign, Id.Map.empty) in
3062 let ids =
3063 (* We assume all ids around are parts of the prefix of the current
3064 context being interpreted *)
3065 extract_ids env in
3066 let int_env = default_internalization_env ids (bound_univs sigma) impl_env in
3067 let flags = { Pretyping.all_no_fail_flags with program_mode; unconstrained_sorts; poly } in
3068 let (int_env, (env, sigma, bl, impls, locs)) =
3069 List.fold_left
3070 (fun (int_env, acc) b ->
3071 let int_env, bl = intern_local_binder_aux ~dump (my_intern_constr env lvar) Id.Map.empty (int_env,[]) b in
3072 let int_env, acc = List.fold_right (fun b' (int_env, (env,sigma,params,impls,locs)) ->
3073 let loc = b'.CAst.loc in
3074 let (na, _, bk, b', t) = glob_local_binder_of_extended b' in
3075 let sigma, t =
3076 let t' = if Option.is_empty b' then locate_if_hole ?loc:(loc_of_glob_constr t) na t else t in (* useful? *)
3077 let sigma, t, _ = Pretyping.ise_pretype_gen flags env sigma empty_lvar IsType t' in
3078 sigma, t
3079 in
3080 let r = Retyping.relevance_of_type env sigma t in
3081 match b' with
3082 | None ->
3083 let int_env = if autoimp_enable then Name.fold_left (push_auto_implicit env sigma t) int_env na else int_env in
3084 let d = make_decl ?loc (LocalAssum (make_annot na r,t)) in
3085 let impls = impl_of_binder_kind na bk :: impls in
3086 (int_env, (push_decl d env, sigma, d::params, impls, loc::locs))
3087 | Some b ->
3088 assert (bk = Explicit);
3089 let sigma, c, _ = Pretyping.ise_pretype_gen flags env sigma empty_lvar (OfType t) b in
3090 let d = make_decl ?loc (LocalDef (make_annot na r, c, t)) in
3091 (int_env, (push_decl d env, sigma, d::params, impls, loc::locs)))
3092 bl (int_env,acc) in
3093 int_env, acc)
3094 (int_env,(env,sigma,[],[],[])) bl
3095 in
3096 sigma, (int_env.impls, ((env, bl), List.rev impls, locs))
3097
3098 let interp_named_context_evars ?program_mode ?unconstrained_sorts ?poly ?impl_env ?autoimp_enable env sigma bl =
3099 let extract_name ?loc = function Name id -> id | Anonymous -> user_err ?loc Pp.(str "Unexpected anonymous variable.") in
3100 let make_decl ?loc = Context.Named.Declaration.of_rel_decl (extract_name ?loc) in
3101 interp_context_evars_gen ?program_mode ?unconstrained_sorts ?poly ?impl_env ?autoimp_enable ~dump:false env sigma make_decl EConstr.push_named bl
3102
3103 let interp_context_evars ?program_mode ?unconstrained_sorts ?poly ?impl_env env sigma bl =
3104 interp_context_evars_gen ?program_mode ?unconstrained_sorts ?poly ?impl_env ~autoimp_enable:false ~dump:true env sigma (fun ?loc d -> d) EConstr.push_rel bl
3105
3106 (** Local universe and constraint declarations. *)
3107
3108 let known_universe_level_name evd lid =
3109 try Evd.universe_of_name evd lid.CAst.v
3110 with Not_found ->
3111 let u = Nametab.locate_universe (Libnames.qualid_of_lident lid) in
3112 Univ.Level.make u
3113
3114 let known_glob_level evd = function
3115 | GSProp | GProp ->
3116 CErrors.user_err (Pp.str "Universe constraints cannot mention Prop or SProp.")
3117 | GSet -> Univ.Level.set
3118 | GUniv u -> u
3119 | GRawUniv u -> anomaly Pp.(str "Raw universe in known_glob_level.")
3120 | GLocalUniv lid ->
3121 try known_universe_level_name evd lid
3122 with Not_found ->
3123 user_err ?loc:lid.CAst.loc
3124 (str "Undeclared universe " ++ Id.print lid.CAst.v)
3125
3126 let interp_known_level evd u =
3127 let u = intern_sort_name ~local_univs:{bound = bound_univs evd; unb_univs=false} u in
3128 known_glob_level evd u
3129
3130 let interp_univ_constraint evd (u,c,v) =
3131 let u = interp_known_level evd u in
3132 let v = interp_known_level evd v in
3133 u,c,v
3134
3135 let interp_univ_constraints env evd cstrs =
3136 let interp (evd,cstrs) cstr =
3137 let cstr = interp_univ_constraint evd cstr in
3138 try
3139 let evd = Evd.add_univ_constraints evd (Univ.UnivConstraints.singleton cstr) in
3140 evd, Univ.UnivConstraints.add cstr cstrs
3141 with UGraph.UniverseInconsistency e as exn ->
3142 let _, info = Exninfo.capture exn in
3143 CErrors.user_err ~info
3144 (UGraph.explain_universe_inconsistency (Termops.pr_evd_qvar evd) (Termops.pr_evd_level evd) e)
3145 in
3146 List.fold_left interp (evd,Univ.UnivConstraints.empty) cstrs
3147
3148 let known_glob_quality evd q =
3149 match q with
3150 | GQConstant q -> Sorts.Quality.QConstant q
3151 | GQualVar (GLocalQVar _) -> assert false
3152 | GQualVar (GQVar q | GRawQVar q) -> Sorts.Quality.QVar q
3153
3154 let interp_known_quality evd q =
3155 let q = intern_quality ~local_univs:{bound = bound_univs evd; unb_univs=false} q in
3156 known_glob_quality evd q
3157
3158 let interp_elim_constraint evd (q1,k,q2) =
3159 let q1 = interp_known_quality evd q1 in
3160 let q2 = interp_known_quality evd q2 in
3161 q1,k,q2
3162
3163 let interp_elim_constraints env evd cstrs =
3164 let interp (evd,cstrs) cstr =
3165 let cstr = interp_elim_constraint evd cstr in
3166 try let evd = Evd.add_poly_constraints ~src:UState.Rigid evd @@
3167 PConstraints.of_qualities (Sorts.ElimConstraints.singleton cstr) in
3168 evd, Sorts.ElimConstraints.add cstr cstrs
3169 with QGraph.EliminationError e as exn ->
3170 let _, info = Exninfo.capture exn in
3171 CErrors.user_err ~info @@
3172 QGraph.explain_elimination_error (Termops.pr_evd_qvar evd) e
3173 in
3174 List.fold_left interp (evd, Sorts.ElimConstraints.empty) cstrs
3175
3176 let interp_univ_decl env decl =
3177 let open UState in
3178 let evd = Evd.from_env env in
3179 let evd, qualities = List.fold_left_map (fun evd lid ->
3180 Evd.new_quality_variable ?loc:lid.loc ~name:lid.v evd)
3181 evd
3182 decl.univdecl_qualities
3183 in
3184 let evd, instance = List.fold_left_map (fun evd lid ->
3185 Evd.new_univ_level_variable ?loc:lid.loc univ_rigid ~name:lid.v evd)
3186 evd
3187 decl.univdecl_instance
3188 in
3189 let evd, univ_cstrs = interp_univ_constraints env evd decl.univdecl_univ_constraints in
3190 let evd, elim_cstrs = interp_elim_constraints env evd decl.univdecl_elim_constraints in
3191 let decl = {
3192 univdecl_qualities = qualities;
3193 univdecl_extensible_qualities = decl.univdecl_extensible_qualities;
3194 univdecl_elim_constraints = elim_cstrs;
3195 univdecl_instance = instance;
3196 univdecl_extensible_instance = decl.univdecl_extensible_instance;
3197 univdecl_univ_constraints = univ_cstrs;
3198 univdecl_extensible_constraints = decl.univdecl_extensible_constraints;
3199 }
3200 in evd, decl
3201
3202 let interp_cumul_univ_decl env decl =
3203 let open UState in
3204 let binders = List.map fst decl.univdecl_instance in
3205 let variances = Array.map_of_list snd decl.univdecl_instance in
3206 let evd = Evd.from_env env in
3207 let evd, qualities = List.fold_left_map (fun evd lid ->
3208 Evd.new_quality_variable ?loc:lid.loc ~name:lid.v evd)
3209 evd
3210 decl.univdecl_qualities
3211 in
3212 let evd, instance = List.fold_left_map (fun evd lid ->
3213 Evd.new_univ_level_variable ?loc:lid.loc univ_rigid ~name:lid.v evd)
3214 evd
3215 binders
3216 in
3217 let evd, univ_cstrs = interp_univ_constraints env evd decl.univdecl_univ_constraints in
3218 let evd, elim_cstrs = interp_elim_constraints env evd decl.univdecl_elim_constraints in
3219 let decl = {
3220 univdecl_qualities = qualities;
3221 univdecl_extensible_qualities = decl.univdecl_extensible_qualities;
3222 univdecl_elim_constraints = elim_cstrs;
3223 univdecl_instance = instance;
3224 univdecl_extensible_instance = decl.univdecl_extensible_instance;
3225 univdecl_univ_constraints = univ_cstrs;
3226 univdecl_extensible_constraints = decl.univdecl_extensible_constraints;
3227 }
3228 in
3229 evd, decl, variances
3230
3231 let interp_univ_decl_opt env l =
3232 match l with
3233 | None -> Evd.from_env env, UState.default_univ_decl
3234 | Some decl -> interp_univ_decl env decl
3235
3236 let interp_cumul_univ_decl_opt env = function
3237 | None -> Evd.from_env env, UState.default_univ_decl, [| |]
3238 | Some decl -> interp_cumul_univ_decl env decl
3239
3240 let interp_mutual_univ_decl_opt env udecls =
3241 let udecl =
3242 List.fold_right (fun udecl acc ->
3243 match udecl , acc with
3244 | None , acc -> acc
3245 | x , None -> x
3246 | Some ls , Some us ->
3247 let open UState in
3248 let lsu = ls.univdecl_instance and usu = us.univdecl_instance in
3249 if not (CList.for_all2eq (fun x y -> Id.equal x.CAst.v y.CAst.v) lsu usu) then
3250 CErrors.user_err Pp.(str "Mutual definitions should all have the same universe binders.");
3251 Some us) udecls None
3252 in
3253 interp_univ_decl_opt env udecl