Debian Codegraph @

vernac/egramrocq.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 Util
12 open CErrors
13 open Names
14 open Libnames
15 open Constrexpr
16 open Extend
17 open Notationextern
18 open Notation_gram
19 open Procq
20 open Globnames
21
22 (**********************************************************************)
23 (* This determines (depending on the associativity of the current
24 level and on the expected associativity) if a reference to constr_n is
25 a reference to the current level (to be translated into "SELF" on the
26 left border and into "constr LEVEL n" elsewhere), to the level below
27 (to be translated into "NEXT") or to an below wrt associativity (to be
28 translated in camlp5 into "constr" without level) or to another level
29 (to be translated into "constr LEVEL n")
30
31 The boolean is true if the entry was existing _and_ empty;
32 cf use in find_positions_gen *)
33
34 let constr_level = string_of_int
35
36 type one_level_info = int * Gramlib.Gramext.g_assoc * bool
37 type entry_level_info = one_level_info list
38
39 let default_constr_levels : entry_level_info =
40 [200,Gramlib.Gramext.RightA,true;
41 100,Gramlib.Gramext.RightA,false;
42 99,Gramlib.Gramext.RightA,true;
43 90,Gramlib.Gramext.RightA,true;
44 10,Gramlib.Gramext.LeftA,false;
45 9,Gramlib.Gramext.RightA,false;
46 8,Gramlib.Gramext.RightA,true;
47 1,Gramlib.Gramext.LeftA,false;
48 0,Gramlib.Gramext.RightA,false]
49
50 let default_pattern_levels : entry_level_info =
51 [200,Gramlib.Gramext.RightA,true;
52 100,Gramlib.Gramext.RightA,false;
53 99,Gramlib.Gramext.RightA,true;
54 90,Gramlib.Gramext.RightA,true;
55 10,Gramlib.Gramext.LeftA,false;
56 1,Gramlib.Gramext.LeftA,false;
57 0,Gramlib.Gramext.RightA,false]
58
59 module ConstrEntryOrd = struct
60 type t = notation_entry
61 let compare = notation_entry_compare
62 end
63
64 module ConstrEntryMap = Map.Make(ConstrEntryOrd)
65
66 let default_levels =
67 ConstrEntryMap.singleton InConstrEntry (default_constr_levels, default_pattern_levels)
68
69 let find_levels levels entry =
70 try levels, ConstrEntryMap.find entry levels
71 with Not_found ->
72 let info = [], [] in
73 ConstrEntryMap.add entry info levels, info
74
75 let save_levels levels custom lev =
76 ConstrEntryMap.add custom lev levels
77
78 (* At a same level, LeftA takes precedence over RightA and NoneA *)
79 (* In case, several associativity exists for a level, we make two levels, *)
80 (* first LeftA, then RightA and NoneA together *)
81
82 let admissible_assoc = function
83 | Gramlib.Gramext.LeftA, Some (Gramlib.Gramext.RightA | Gramlib.Gramext.NonA) -> false
84 | Gramlib.Gramext.RightA, Some Gramlib.Gramext.LeftA -> false
85 | Gramlib.Gramext.BothA, _ | _, Some Gramlib.Gramext.BothA -> assert false
86 | _ -> true
87
88 let create_assoc = function
89 | None -> Gramlib.Gramext.RightA
90 | Some a -> a
91
92 exception NotationLevelMismatch
93 of entry_level * Gramlib.Gramext.g_assoc * Gramlib.Gramext.g_assoc
94
95 let () = CErrors.register_handler (function
96 | NotationLevelMismatch (p, current, expected) ->
97 Some Pp.(str "Level " ++ int p ++ str " is already declared to have " ++
98 Gramlib.Gramext.pr_assoc current ++
99 str " while it is now expected to have " ++
100 Gramlib.Gramext.pr_assoc expected ++ str ".")
101 | _ -> None)
102
103 let error_level_assoc p current expected =
104 raise @@ NotationLevelMismatch (p, current, expected)
105
106 type position = NewFirst | NewAfter of int | ReuseFirst | ReuseLevel of int
107
108 let create_pos = function
109 | None -> NewFirst
110 | Some lev -> NewAfter lev
111
112 let find_position_gen current ensure assoc lev =
113 match lev with
114 | None ->
115 current, (ReuseFirst, None, None)
116 | Some n ->
117 let rec add_level previous = function
118 | (p,_,_ as pa)::l when p > n ->
119 let updated, res = add_level (Some p) l in
120 pa :: updated, res
121 | (p,a,empty)::l when Int.equal p n ->
122 if empty then
123 (* XXX we ignore preexisting associativity for empty levels, is that what we want? *)
124 let a' = create_assoc assoc in
125 let updated = (p,a',false)::l in
126 updated, (ReuseLevel n, None, None)
127 else if admissible_assoc (a,assoc) then
128 raise_notrace Exit
129 else
130 error_level_assoc p a (Option.get assoc)
131 | l ->
132 let assoc = create_assoc assoc in
133 let updated = (n,assoc,ensure)::l in
134 updated, (create_pos previous, Some assoc, Some (constr_level n))
135 in
136 try add_level None current
137 with
138 (* Nothing has changed *)
139 Exit ->
140 (* Just inherit the existing associativity and name (None) *)
141 current, (ReuseLevel n, None, None)
142
143 let rec list_mem_assoc_triple x = function
144 | [] -> false
145 | (a,b,c) :: l -> Int.equal a x || list_mem_assoc_triple x l
146
147 let register_empty_levels accu forpat levels =
148 let rec filter accu = function
149 | [] -> ([], accu)
150 | (where,n) :: rem ->
151 let rem, accu = filter accu rem in
152 let accu, (clev, plev) = find_levels accu where in
153 let levels = if forpat then plev else clev in
154 if not (list_mem_assoc_triple n levels) then
155 let nlev, ans = find_position_gen levels true None (Some n) in
156 let nlev = if forpat then (clev, nlev) else (nlev, plev) in
157 (where, ans) :: rem, save_levels accu where nlev
158 else rem, accu
159 in
160 let (l,accu) = filter accu levels in
161 List.rev l, accu
162
163 let find_position accu custom forpat assoc level =
164 let accu, (clev, plev) = find_levels accu custom in
165 let levels = if forpat then plev else clev in
166 let nlev, ans = find_position_gen levels false assoc level in
167 let nlev = if forpat then (clev, nlev) else (nlev, plev) in
168 (ans, save_levels accu custom nlev)
169
170 (**************************************************************************)
171 (*
172 * --- Note on the mapping of grammar productions to camlp5 actions ---
173 *
174 * Translation of environments: a production
175 * [ nt1(x1) ... nti(xi) ] -> act(x1..xi)
176 * is written (with camlp5 conventions):
177 * (fun vi -> .... (fun v1 -> act(v1 .. vi) )..)
178 * where v1..vi are the values generated by non-terminals nt1..nti.
179 * Since the actions are executed by substituting an environment,
180 * the make_*_action family build the following closure:
181 *
182 * ((fun env ->
183 * (fun vi ->
184 * (fun env -> ...
185 *
186 * (fun v1 ->
187 * (fun env -> gram_action .. env act)
188 * ((x1,v1)::env))
189 * ...)
190 * ((xi,vi)::env)))
191 * [])
192 *)
193
194 (**********************************************************************)
195 (** Declare Notations grammar rules *)
196
197 (**********************************************************************)
198 (* Binding constr entry keys to entries *)
199
200 (* Camlp5 levels do not treat NonA: use RightA with a NEXT on the left *)
201 let camlp5_assoc =
202 let open Gramlib.Gramext in function
203 | Some NonA | Some RightA -> RightA
204 | None | Some LeftA -> LeftA
205 | Some BothA -> assert false
206
207 let assoc_eq al ar =
208 let open Gramlib.Gramext in
209 match al, ar with
210 | NonA, NonA
211 | RightA, RightA
212 | LeftA, LeftA -> true
213 | BothA, _ | _, BothA -> assert false
214 | _, _ -> false
215
216 (** [adjust_level assoc fromlev prod] where [assoc] and [fromlev] are the name
217 and associativity of the level where to add the rule; the meaning of
218 the result is
219
220 DefaultLevel = entry name
221 NextLevel = NEXT
222 NumLevel n = constr LEVEL n *)
223 let adjust_level custom assoc {notation_entry = custom'; notation_level = fromlev} p =
224 let open Gramlib.Gramext in match p with
225 (* If a level in a different grammar, no other choice than denoting it by absolute level *)
226 | (NumLevel n,_) when not (notation_entry_eq custom custom') -> NumLevel n
227 (* If a default level in a different grammar, the entry name is ok *)
228 | (DefaultLevel,InternalProd) ->
229 if notation_entry_eq custom InConstrEntry then NumLevel 200 else DefaultLevel
230 | (DefaultLevel,BorderProd _) when not (notation_entry_eq custom custom') ->
231 if notation_entry_eq custom InConstrEntry then NumLevel 200 else DefaultLevel
232 (* Associativity is None means force the level *)
233 | (NumLevel n,BorderProd (_,None)) -> NumLevel n
234 | (DefaultLevel,BorderProd (_,None)) -> assert false
235 (* Compute production name on the right side *)
236 (* If NonA or LeftA on the right-hand side, set to NEXT *)
237 | ((NumLevel _ | DefaultLevel),BorderProd (Right,Some (NonA|LeftA))) -> NextLevel
238 (* If RightA on the right-hand side, set to the explicit (current) level *)
239 | (NumLevel n,BorderProd (Right,Some RightA)) -> NumLevel n
240 | (DefaultLevel,BorderProd (Right,Some RightA)) -> NumLevel fromlev
241 (* Compute production name on the left side *)
242 (* If NonA on the left-hand side, adopt the current assoc ?? *)
243 | ((NumLevel _ | DefaultLevel),BorderProd (Left,Some NonA)) -> DefaultLevel
244 (* If the expected assoc is the current one, set to SELF *)
245 | ((NumLevel _ | DefaultLevel),BorderProd (Left,Some a)) when assoc_eq a (camlp5_assoc assoc) ->
246 DefaultLevel
247 (* Otherwise, force the level, n or n-1, according to expected assoc *)
248 | (NumLevel n,BorderProd (Left,Some LeftA)) -> NumLevel n
249 | ((NumLevel _ | DefaultLevel),BorderProd (Left,Some _)) -> NextLevel
250 (* None means NEXT *)
251 | (NextLevel,_) -> assert (notation_entry_eq custom custom'); NextLevel
252 (* Compute production name elsewhere *)
253 | (NumLevel n,InternalProd) ->
254 if fromlev = n + 1 then NextLevel else NumLevel n
255 | (_,BorderProd (_,Some BothA)) -> assert false
256
257 type _ target =
258 | ForConstr : constr_expr target
259 | ForPattern : cases_pattern_expr target
260
261 type prod_info = production_level * production_position
262
263 type (_, _) entry =
264 | TTIdent : ('self, lident) entry
265 | TTName : ('self, lname) entry
266 | TTGlobal : ('r, qualid) entry
267 | TTBigint : ('r, string) entry
268 | TTBinder : bool -> ('self, kinded_cases_pattern_expr) entry
269 | TTConstr : notation_entry * prod_info * 'r target -> ('r, 'r) entry
270 | TTConstrList : notation_entry * prod_info * (bool * string) list * 'r target -> ('r, 'r list) entry
271 | TTPattern : int -> ('self, cases_pattern_expr) entry
272 | TTOpenBinderList : ('self, local_binder_expr list) entry
273 | TTClosedBinderListPure : (bool * string) list -> ('self, local_binder_expr list list) entry
274 | TTClosedBinderListOther : ('self, 'a) entry * (bool * string) list -> ('self, 'a list) entry
275
276 type _ any_entry = TTAny : ('s, 'r) entry -> 's any_entry
277
278 let constr_custom_map : Constrexpr.constr_expr Entry.t CustomName.Map.t GramState.field =
279 GramState.field "constr_custom_map"
280
281 let pattern_custom_map : Constrexpr.cases_pattern_expr Entry.t CustomName.Map.t GramState.field =
282 GramState.field "pattern_custom_map"
283
284 let make_custom_interp field prefix = {
285 eext_fun = (fun kn e state ->
286 let map = Option.default CustomName.Map.empty (GramState.get state field) in
287 let map = CustomName.Map.add kn e map in
288 GramState.set state field map);
289 eext_name = (fun kn -> prefix^CustomName.to_string kn);
290 eext_eq = CustomName.equal;
291 }
292
293 let constr_custom_entry : (CustomName.t, Constrexpr.constr_expr) entry_command =
294 create_entry_command "constr" (make_custom_interp constr_custom_map "custom:")
295 let pattern_custom_entry : (CustomName.t, Constrexpr.cases_pattern_expr) entry_command =
296 create_entry_command "pattern" (make_custom_interp pattern_custom_map "pattern:")
297
298 let create_custom_entry s =
299 let () = extend_entry_command constr_custom_entry s in
300 let () = extend_entry_command pattern_custom_entry s in
301 ()
302
303 let find_custom_entry s =
304 let state = gramstate() in
305 let find_aux field = match GramState.get state field with
306 | None -> raise Not_found
307 | Some m -> CustomName.Map.find s m
308 in
309 try (find_aux constr_custom_map, find_aux pattern_custom_map)
310 with Not_found ->
311 anomaly Pp.(str "Undeclared custom entry: " ++ CustomName.print s ++ str ".")
312
313 (** This computes the name of the level where to add a new rule *)
314 let interp_constr_entry_key : type r. _ -> r target -> r Entry.t * int option =
315 fun {notation_entry = custom; notation_level = level} forpat ->
316 match custom with
317 | InCustomEntry s ->
318 (let (entry_for_constr, entry_for_patttern) = find_custom_entry s in
319 match forpat with
320 | ForConstr -> entry_for_constr, Some level
321 | ForPattern -> entry_for_patttern, Some level)
322 | InConstrEntry ->
323 match forpat with
324 | ForConstr ->
325 if level = 200 then Constr.binder_constr, None
326 else Constr.term, Some level
327 | ForPattern -> Constr.pattern, Some level
328
329 let target_entry : type s. notation_entry -> s target -> s Entry.t = function
330 | InConstrEntry ->
331 (function
332 | ForConstr -> Constr.term
333 | ForPattern -> Constr.pattern)
334 | InCustomEntry s ->
335 let (entry_for_constr, entry_for_patttern) = find_custom_entry s in
336 function
337 | ForConstr -> entry_for_constr
338 | ForPattern -> entry_for_patttern
339
340 let is_self custom {notation_entry = custom'; notation_level = fromlev} e =
341 notation_entry_eq custom custom' && match e with
342 | (NumLevel n, BorderProd (Right, _ (* Some(NonA|LeftA) *))) -> false
343 | (NumLevel n, BorderProd (Left, _)) -> Int.equal fromlev n
344 | _ -> false
345
346 let is_binder_level custom {notation_entry = custom'; notation_level = fromlev} e =
347 match e with
348 | (NumLevel 200, (BorderProd (Right, _) | InternalProd)) ->
349 custom = InConstrEntry && custom' = InConstrEntry && fromlev = 200
350 | _ -> false
351
352 let make_pattern (keyword,s) =
353 if keyword then TPattern (Tok.PKEYWORD s) else
354 match NumTok.Unsigned.parse_string s with
355 | Some n -> TPattern (Tok.PNUMBER (Some n))
356 | None ->
357 match String.unquote_coq_string s with
358 | Some s -> TPattern (Tok.PSTRING (Some s))
359 | None -> TPattern (Tok.PIDENT (Some s))
360
361 let make_sep_rules tkl =
362 Procq.Symbol.tokens (List.map make_pattern tkl)
363
364 type ('s, 'a) mayrec_symbol =
365 | MayRecNo : ('s, Gramlib.Grammar.norec, 'a) Symbol.t -> ('s, 'a) mayrec_symbol
366 | MayRecMay : ('s, Gramlib.Grammar.mayrec, 'a) Symbol.t -> ('s, 'a) mayrec_symbol
367
368 let symbol_of_target : type s. _ -> _ -> _ -> _ -> s target -> (s, s) mayrec_symbol = fun custom p assoc from forpat ->
369 if is_binder_level custom from p
370 then
371 (* Prevent self *)
372 MayRecNo (Procq.Symbol.nterml (target_entry custom forpat) "200")
373 else if is_self custom from p then MayRecMay Procq.Symbol.self
374 else
375 let g = target_entry custom forpat in
376 let lev = adjust_level custom assoc from p in
377 begin match lev with
378 | DefaultLevel -> MayRecNo (Procq.Symbol.nterm g)
379 | NextLevel -> MayRecMay Procq.Symbol.next
380 | NumLevel lev -> MayRecNo (Procq.Symbol.nterml g (string_of_int lev))
381 end
382
383 let rec symbol_of_entry : type s r. _ -> _ -> (s, r) entry -> (s, r) mayrec_symbol = fun assoc from typ -> match typ with
384 | TTConstr (s, p, forpat) -> symbol_of_target s p assoc from forpat
385 | TTConstrList (s, typ', [], forpat) ->
386 begin match symbol_of_target s typ' assoc from forpat with
387 | MayRecNo s -> MayRecNo (Procq.Symbol.list1 s)
388 | MayRecMay s -> MayRecMay (Procq.Symbol.list1 s) end
389 | TTConstrList (s, typ', tkl, forpat) ->
390 begin match symbol_of_target s typ' assoc from forpat with
391 | MayRecNo s -> MayRecNo (Procq.Symbol.list1sep s (make_sep_rules tkl))
392 | MayRecMay s -> MayRecMay (Procq.Symbol.list1sep s (make_sep_rules tkl)) end
393 | TTPattern p -> MayRecNo (Procq.Symbol.nterml Constr.pattern (string_of_int p))
394 | TTOpenBinderList -> MayRecNo (Procq.Symbol.nterm Constr.open_binders)
395 | TTClosedBinderListPure [] -> MayRecNo (Procq.Symbol.list1 (Procq.Symbol.nterm Constr.binder))
396 | TTClosedBinderListPure tkl -> MayRecNo (Procq.Symbol.list1sep (Procq.Symbol.nterm Constr.binder) (make_sep_rules tkl))
397 | TTClosedBinderListOther (typ,[]) ->
398 begin match symbol_of_entry assoc from typ with
399 | MayRecNo s -> MayRecNo (Procq.Symbol.list1 s)
400 | MayRecMay s -> MayRecMay (Procq.Symbol.list1 s) end
401 | TTClosedBinderListOther (typ,tkl) ->
402 begin match symbol_of_entry assoc from typ with
403 | MayRecNo s -> MayRecNo (Procq.Symbol.list1sep s (make_sep_rules tkl))
404 | MayRecMay s -> MayRecMay (Procq.Symbol.list1sep s (make_sep_rules tkl)) end
405 | TTIdent -> MayRecNo (Procq.Symbol.nterm Prim.identref)
406 | TTName -> MayRecNo (Procq.Symbol.nterm Prim.name)
407 | TTBinder true -> MayRecNo (Procq.Symbol.nterm Constr.one_open_binder)
408 | TTBinder false -> MayRecNo (Procq.Symbol.nterm Constr.one_closed_binder)
409 | TTBigint -> MayRecNo (Procq.Symbol.nterm Prim.bignat)
410 | TTGlobal -> MayRecNo (Procq.Symbol.nterm Constr.global)
411
412 let rec interp_entry forpat e = match e with
413 | ETProdIdent -> TTAny TTIdent
414 | ETProdName -> TTAny TTName
415 | ETProdGlobal -> TTAny TTGlobal
416 | ETProdBigint -> TTAny TTBigint
417 | ETProdOneBinder o -> TTAny (TTBinder o)
418 | ETProdConstr (s,p) -> TTAny (TTConstr (s, p, forpat))
419 | ETProdPattern p -> TTAny (TTPattern p)
420 | ETProdConstrList (s, p, tkl) -> TTAny (TTConstrList (s, p, tkl, forpat))
421 | ETProdBinderList ETBinderOpen -> TTAny TTOpenBinderList
422 | ETProdBinderList (ETBinderClosed (None, tkl)) -> TTAny (TTClosedBinderListPure tkl)
423 | ETProdBinderList (ETBinderClosed (Some e, tkl)) ->
424 let TTAny e = interp_entry forpat e in TTAny (TTClosedBinderListOther (e, tkl))
425
426 let cases_pattern_expr_of_id { CAst.loc; v = id } =
427 CAst.make ?loc @@ CPatAtom (Some (qualid_of_ident ?loc id))
428
429 let cases_pattern_expr_of_name { CAst.loc; v = na } = CAst.make ?loc @@ match na with
430 | Anonymous -> CPatAtom None
431 | Name id -> CPatAtom (Some (qualid_of_ident ?loc id))
432
433 type 'r env = {
434 constrs : 'r list;
435 constrlists : 'r list list;
436 binders : kinded_cases_pattern_expr list;
437 binderlists : local_binder_expr list list;
438 }
439
440 let push_constr subst v = { subst with constrs = v :: subst.constrs }
441
442 let push_item : type s r. s target -> (s, r) entry -> s env -> r -> s env = fun forpat e subst v ->
443 match e with
444 | TTConstr _ -> push_constr subst v
445 | TTIdent -> { subst with binders = (cases_pattern_expr_of_id v, Glob_term.Explicit) :: subst.binders }
446 | TTName -> { subst with binders = (cases_pattern_expr_of_name v, Glob_term.Explicit) :: subst.binders }
447 | TTPattern _ -> { subst with binders = (v, Glob_term.Explicit) :: subst.binders }
448 | TTBinder o -> { subst with binders = v :: subst.binders }
449 | TTOpenBinderList -> { subst with binderlists = v :: subst.binderlists }
450 | TTClosedBinderListPure _ -> { subst with binderlists = List.flatten v :: subst.binderlists }
451 | TTClosedBinderListOther (TTIdent, _) -> { subst with binderlists = List.map (fun a -> CLocalPattern (cases_pattern_expr_of_id a)) v :: subst.binderlists }
452 | TTClosedBinderListOther (TTName, _) -> { subst with binderlists = List.map (fun a -> CLocalPattern (cases_pattern_expr_of_name a)) v :: subst.binderlists }
453 | TTClosedBinderListOther (TTPattern _, _) -> { subst with binderlists = List.map (fun a -> CLocalPattern a) v :: subst.binderlists }
454 | TTClosedBinderListOther _ -> user_err (Pp.str "Invalid binder list entry.")
455 | TTBigint ->
456 begin match forpat with
457 | ForConstr -> push_constr subst (CAst.make @@ CPrim (Number (NumTok.Signed.of_int_string v)))
458 | ForPattern -> push_constr subst (CAst.make @@ CPatPrim (Number (NumTok.Signed.of_int_string v)))
459 end
460 | TTGlobal ->
461 begin match forpat with
462 | ForConstr -> push_constr subst (CAst.make @@ CRef (v, None))
463 | ForPattern -> push_constr subst (CAst.make @@ CPatAtom (Some v))
464 end
465 | TTConstrList _ -> { subst with constrlists = v :: subst.constrlists }
466
467 type (_, _) ty_symbol =
468 | TyTerm : 'a Tok.p -> ('s, 'a) ty_symbol
469 | TyNonTerm : 's target * ('s, 'a) entry * ('s, 'a) mayrec_symbol * bool -> ('s, 'a) ty_symbol
470
471 type ('self, _, 'r) ty_rule =
472 | TyStop : ('self, 'r, 'r) ty_rule
473 | TyNext : ('self, 'a, 'r) ty_rule * ('self, 'b) ty_symbol -> ('self, 'b -> 'a, 'r) ty_rule
474 | TyMark : int * bool * int * ('self, 'a, 'r) ty_rule -> ('self, 'a, 'r) ty_rule
475
476 type 'r gen_eval = Loc.t -> 'r env -> 'r
477
478 let rec ty_eval : type s a. (s, a, Loc.t -> s) ty_rule -> s gen_eval -> s env -> a = function
479 | TyStop ->
480 fun f env loc -> f loc env
481 | TyNext (rem, TyTerm _) ->
482 fun f env _ -> ty_eval rem f env
483 | TyNext (rem, TyNonTerm (_, _, _, false)) ->
484 fun f env _ -> ty_eval rem f env
485 | TyNext (rem, TyNonTerm (forpat, e, _, true)) ->
486 fun f env v ->
487 ty_eval rem f (push_item forpat e env v)
488 | TyMark (n, b, p, rem) ->
489 fun f env ->
490 let heads, constrs = List.chop n env.constrs in
491 let constrlists, constrs =
492 if b then
493 (* We rearrange constrs = c1..cn rem and constrlists = [d1..dr e1..ep] rem' into
494 constrs = e1..ep rem and constrlists [c1..cn d1..dr] rem' *)
495 let constrlist = List.hd env.constrlists in
496 let constrlist, tail = List.chop (List.length constrlist - p) constrlist in
497 (heads @ constrlist) :: List.tl env.constrlists, tail @ constrs
498 else
499 (* We rearrange constrs = c1..cn e1..ep rem into
500 constrs = e1..ep rem and add a constr list [c1..cn] *)
501 let constrlist, tail = List.chop (n - p) heads in
502 constrlist :: env.constrlists, tail @ constrs
503 in
504 ty_eval rem f { env with constrs; constrlists; }
505
506 type ('s, 'a, 'r) mayrec_rule =
507 | MayRecRNo : ('s, Gramlib.Grammar.norec, 'a, 'r) Rule.t -> ('s, 'a, 'r) mayrec_rule
508 | MayRecRMay : ('s, Gramlib.Grammar.mayrec, 'a, 'r) Rule.t -> ('s, 'a, 'r) mayrec_rule
509
510 let rec ty_erase : type s a r. (s, a, r) ty_rule -> (s, a, r) mayrec_rule = function
511 | TyStop -> MayRecRNo Rule.stop
512 | TyMark (_, _, _, r) -> ty_erase r
513 | TyNext (rem, TyTerm tok) ->
514 begin match ty_erase rem with
515 | MayRecRNo rem -> MayRecRMay (Rule.next rem (Symbol.token tok))
516 | MayRecRMay rem -> MayRecRMay (Rule.next rem (Symbol.token tok)) end
517 | TyNext (rem, TyNonTerm (_, _, s, _)) ->
518 begin match ty_erase rem, s with
519 | MayRecRNo rem, MayRecNo s -> MayRecRMay (Rule.next rem s)
520 | MayRecRNo rem, MayRecMay s -> MayRecRMay (Rule.next rem s)
521 | MayRecRMay rem, MayRecNo s -> MayRecRMay (Rule.next rem s)
522 | MayRecRMay rem, MayRecMay s -> MayRecRMay (Rule.next rem s) end
523
524 type ('self, 'r) any_ty_rule =
525 | AnyTyRule : ('self, 'act, Loc.t -> 'r) ty_rule -> ('self, 'r) any_ty_rule
526
527 let make_ty_rule assoc from forpat prods =
528 let rec make_ty_rule = function
529 | [] -> AnyTyRule TyStop
530 | GramConstrTerminal (kw,s) :: rem ->
531 let AnyTyRule r = make_ty_rule rem in
532 let TPattern tk = make_pattern (kw,s) in
533 AnyTyRule (TyNext (r, TyTerm tk))
534 | GramConstrNonTerminal (e, var) :: rem ->
535 let AnyTyRule r = make_ty_rule rem in
536 let TTAny e = interp_entry forpat e in
537 let s = symbol_of_entry assoc from e in
538 let bind = match var with None -> false | Some _ -> true in
539 AnyTyRule (TyNext (r, TyNonTerm (forpat, e, s, bind)))
540 | GramConstrListMark (n, b, p) :: rem ->
541 let AnyTyRule r = make_ty_rule rem in
542 AnyTyRule (TyMark (n, b, p, r))
543 in
544 make_ty_rule (List.rev prods)
545
546 let target_to_bool : type r. r target -> bool = function
547 | ForConstr -> false
548 | ForPattern -> true
549
550 let prepare_empty_levels forpat (where,(pos,p4assoc,name)) =
551 let empty = match pos with
552 | ReuseFirst -> Procq.Reuse (None, [])
553 | ReuseLevel n -> Procq.Reuse (Some (constr_level n), [])
554 | NewFirst -> Procq.Fresh (Gramlib.Gramext.First, [(name, p4assoc, [])])
555 | NewAfter n -> Procq.Fresh (Gramlib.Gramext.After (constr_level n), [(name, p4assoc, [])])
556 in
557 ExtendRule (target_entry where forpat, empty)
558
559 let different_levels (custom,opt_level) (custom',string_level) =
560 match opt_level with
561 | None -> true
562 | Some level -> not (notation_entry_eq custom custom') || level <> int_of_string string_level
563
564 let rec pure_sublevels' assoc from forpat level = function
565 | [] -> []
566 | GramConstrNonTerminal (e,_) :: rem ->
567 let rem = pure_sublevels' assoc from forpat level rem in
568 let push where p rem =
569 match symbol_of_target where p assoc from forpat with
570 | MayRecNo sym ->
571 (match Procq.level_of_nonterm sym with
572 | None -> rem
573 | Some i ->
574 if different_levels (from.notation_entry,level) (where,i) then
575 (where,int_of_string i) :: rem
576 else rem)
577 | _ -> rem in
578 (match e with
579 | ETProdPattern i -> push InConstrEntry (NumLevel i,InternalProd) rem
580 | ETProdConstr (s,p) -> push s p rem
581 | _ -> rem)
582 | (GramConstrTerminal _ | GramConstrListMark _) :: rem -> pure_sublevels' assoc from forpat level rem
583
584 let make_act : type r. r target -> _ -> r gen_eval = function
585 | ForConstr -> fun notation loc env ->
586 let env = (env.constrs, env.constrlists, env.binders, env.binderlists) in
587 CAst.make ~loc @@ CNotation (None, notation, env)
588 | ForPattern -> fun notation loc env ->
589 let env = (env.constrs, env.constrlists, env.binders) in
590 CAst.make ~loc @@ CPatNotation (None, notation, env, [])
591
592 let extend_constr state forpat ng =
593 let {notation_entry = custom; notation_level = _} as fromlev,_ = ng.notgram_level in
594 let assoc = ng.notgram_assoc in
595 let (entry, level) = interp_constr_entry_key fromlev forpat in
596 let fold (accu, state) pt =
597 let AnyTyRule r = make_ty_rule assoc fromlev forpat pt in
598 let pure_sublevels = pure_sublevels' assoc fromlev forpat level pt in
599 let isforpat = target_to_bool forpat in
600 let needed_levels, state = register_empty_levels state isforpat pure_sublevels in
601 let (pos,p4assoc,name), state = find_position state custom isforpat assoc level in
602 let empty_rules = List.map (prepare_empty_levels forpat) needed_levels in
603 let empty = { constrs = []; constrlists = []; binders = []; binderlists = [] } in
604 let act = ty_eval r (make_act forpat ng.notgram_notation) empty in
605 let rule =
606 let r = match ty_erase r with
607 | MayRecRNo symbs -> Procq.Production.make symbs act
608 | MayRecRMay symbs -> Procq.Production.make symbs act
609 in
610 let rule = name, p4assoc, [r] in
611 match pos with
612 | NewFirst -> Procq.Fresh (Gramlib.Gramext.First, [rule])
613 | NewAfter n -> Procq.Fresh (Gramlib.Gramext.After (constr_level n), [rule])
614 | ReuseFirst -> Procq.Reuse (None, [r])
615 | ReuseLevel n -> Procq.Reuse (Some (constr_level n), [r])
616 in
617 let r = ExtendRule (entry, rule) in
618 (accu @ empty_rules @ [r], state)
619 in
620 List.fold_left fold ([], state) ng.notgram_prods
621
622 let constr_levels = GramState.field "constr_levels"
623
624 let is_disjunctive_pattern_rule ng =
625 String.is_sub "( _ | " (snd ng.notgram_notation) 0
626
627 let warn_disj_pattern_notation =
628 let open Pp in
629 let pp ng = str "Use of " ++ Notation.pr_notation ng.notgram_notation ++
630 str " Notation is deprecated as it is inconsistent with pattern syntax." in
631 CWarnings.create ~name:"disj-pattern-notation" ~category:CWarnings.CoreCategories.syntax ~default:CWarnings.Disabled pp
632
633 let extend_constr_notation ng state =
634 let levels = match GramState.get state constr_levels with
635 | None -> default_levels
636 | Some lev -> lev
637 in
638 (* Add the notation in constr *)
639 let (r, levels) = extend_constr levels ForConstr ng in
640 (* Add the notation in cases_pattern, unless it would disrupt *)
641 (* parsing nested disjunctive patterns. *)
642 let (r', levels) =
643 if is_disjunctive_pattern_rule ng then begin
644 warn_disj_pattern_notation ng;
645 ([], levels)
646 end else extend_constr levels ForPattern ng in
647 let state = GramState.set state constr_levels levels in
648 (r @ r', state)
649
650 let constr_grammar : one_notation_grammar grammar_command =
651 create_grammar_command "Notation" { gext_fun = extend_constr_notation; gext_eq = (==) (* FIXME *) }
652
653 let extend_constr_grammar ntn = extend_grammar_command ~ignore_kw:false constr_grammar ntn