Debian Codegraph @

gramlib/grammar.ml

raw symbols SCIP
1 (* camlp5r *)
2 (* grammar.ml,v *)
3 (* Copyright (c) INRIA 2007-2017 *)
4
5 open Gramext
6 open Format
7 open Util
8
9 exception ParseError of string
10 (** Raised by parsers when the first component of a stream pattern is
11 accepted, but one of the following components is rejected. *)
12
13 (* Functorial interface *)
14
15 type norec = private [ `norec ]
16 type mayrec = private [ `mayrec ]
17
18 module type S = sig
19 type keyword_state
20 type te
21 type 'c pattern
22 type ty_pattern = TPattern : 'a pattern -> ty_pattern
23
24 type peek_error = unit
25
26 type 'a parser_v = ('a, peek_error) result
27
28 (** Type combinators to factor the module type between explicit
29 state passing in Grammar and global state in Procq *)
30
31 type 'a with_gstate
32 (** Reader of grammar state *)
33
34 type 'a with_kwstate
35 (** Read keyword state *)
36
37 type 'a with_estate
38 (** Read entry state *)
39
40 type 'a mod_estate
41 (** Read/write entry state *)
42
43 module Parsable : sig
44 type t
45 (** [Parsable.t] Stream tokenizers with Rocq-specific functionality *)
46
47 val make : ?loc:Loc.t -> (unit,char) Stream.t -> t
48 (** [make ?loc strm] Build a parsable from stream [strm], resuming
49 at position [?loc] *)
50
51 val comments : t -> ((int * int) * string) list
52
53 val loc : t -> Loc.t
54 (** [loc pa] Return parsing position for [pa] *)
55
56 val consume : t -> int -> unit with_kwstate
57 (** [consume pa n] Discard [n] tokens from [pa], updating the
58 parsing position *)
59
60 end
61
62 module Entry : sig
63 type 'a t
64 val make : string -> 'a t mod_estate
65 val parse : 'a t -> Parsable.t -> 'a with_gstate
66 val name : 'a t -> string
67 type 'a parser_fun = { parser_fun : keyword_state -> (keyword_state,te) LStream.t -> 'a parser_v }
68 val of_parser : string -> 'a parser_fun -> 'a t mod_estate
69 val parse_token_stream : 'a t -> (keyword_state,te) LStream.t -> 'a parser_v with_gstate
70 val print : Format.formatter -> 'a t -> unit with_kwstate with_estate
71 val is_empty : 'a t -> bool with_estate
72 type any_t = Any : 'a t -> any_t
73 val accumulate_in : any_t list -> any_t list CString.Map.t with_estate
74 val all_in : unit -> any_t list CString.Map.t with_estate
75 end
76
77 module rec Symbol : sig
78
79 type ('self, 'trec, 'a) t
80 val nterm : 'a Entry.t -> ('self, norec, 'a) t
81 val nterml : 'a Entry.t -> string -> ('self, norec, 'a) t
82 val list0 : ('self, 'trec, 'a) t -> ('self, 'trec, 'a list) t
83 val list0sep :
84 ('self, 'trec, 'a) t -> ('self, norec, unit) t ->
85 ('self, 'trec, 'a list) t
86 val list1 : ('self, 'trec, 'a) t -> ('self, 'trec, 'a list) t
87 val list1sep :
88 ('self, 'trec, 'a) t -> ('self, norec, unit) t ->
89 ('self, 'trec, 'a list) t
90 val opt : ('self, 'trec, 'a) t -> ('self, 'trec, 'a option) t
91 val self : ('self, mayrec, 'self) t
92 val next : ('self, mayrec, 'self) t
93 val token : 'c pattern -> ('self, norec, 'c) t
94 val tokens : ty_pattern list -> ('self, norec, unit) t
95 val rules : 'a Rules.t list -> ('self, norec, 'a) t
96
97 end and Rule : sig
98
99 type ('self, 'trec, 'f, 'r) t
100
101 val stop : ('self, norec, 'r, 'r) t
102 val next :
103 ('self, _, 'a, 'r) t -> ('self, _, 'b) Symbol.t ->
104 ('self, mayrec, 'b -> 'a, 'r) t
105 val next_norec :
106 ('self, norec, 'a, 'r) Rule.t -> ('self, norec, 'b) Symbol.t ->
107 ('self, norec, 'b -> 'a, 'r) t
108
109 end and Rules : sig
110
111 type 'a t
112 val make : (_, norec, 'f, Loc.t -> 'a) Rule.t -> 'f -> 'a t
113
114 end
115
116 module Production : sig
117 type 'a t
118 val make : ('a, _, 'f, Loc.t -> 'a) Rule.t -> 'f -> 'a t
119 end
120
121 type 'a single_extend_statement =
122 string option * Gramext.g_assoc option * 'a Production.t list
123
124 type 'a extend_statement =
125 | Reuse of string option * 'a Production.t list
126 | Fresh of Gramext.position * 'a single_extend_statement list
127
128 val generalize_symbol : ('a, 'tr, 'c) Symbol.t -> ('b, norec, 'c) Symbol.t option
129
130 (* Used in custom entries, should tweak? *)
131 val level_of_nonterm : ('a, norec, 'c) Symbol.t -> string option
132
133 end
134
135 module type ExtS = sig
136
137 type keyword_state
138
139 module EState : sig
140 type t
141 val empty : t
142 end
143 module GState : sig
144 type t = {
145 estate : EState.t;
146 kwstate : keyword_state;
147 recover : bool;
148 has_non_assoc : bool;
149 }
150 end
151
152 include S
153 with type keyword_state := keyword_state
154 and type 'a with_gstate := GState.t -> 'a
155 and type 'a with_kwstate := keyword_state -> 'a
156 and type 'a with_estate := EState.t -> 'a
157 and type 'a mod_estate := EState.t -> EState.t * 'a
158
159 type 's add_kw = { add_kw : 'c. 's -> 'c pattern -> 's }
160
161 val safe_extend : 's add_kw -> EState.t -> 's -> 'a Entry.t -> 'a extend_statement -> EState.t * 's
162
163 module Unsafe : sig
164 val existing_entry : EState.t -> 'a Entry.t -> EState.t
165 val existing_of_parser : EState.t -> 'a Entry.t -> 'a Entry.parser_fun -> EState.t
166 end
167
168 end
169
170 (* Implementation *)
171 module GMake (L : Plexing.S) : ExtS
172 with type keyword_state := L.keyword_state
173 and type te := L.te
174 and type 'c pattern := 'c L.pattern
175 = struct
176
177 type te = L.te
178 type 'c pattern = 'c L.pattern
179 type ty_pattern = TPattern : 'a pattern -> ty_pattern
180
181 type peek_error = unit
182
183 type 'a parser_v = ('a, peek_error) result
184
185 type 'a parser_t = (L.keyword_state,L.te) LStream.t -> 'a parser_v
186
187 let (let*) : 'a parser_v -> ('a -> 'b parser_v) -> 'b parser_v = Result.bind
188 let (let+) : 'a parser_v -> ('a ->' b) -> 'b parser_v = fun x f -> Result.map f x
189
190 let (<+>) (x: 'a parser_v) (y:unit -> 'a parser_v) : 'a parser_v =
191 match x with
192 | Ok _ -> x
193 | Error () -> y ()
194
195 (** Used to propagate possible presence of SELF/NEXT in a rule (binary and) *)
196 type ('a, 'b, 'c) ty_and_rec =
197 | NoRec2 : (norec, norec, norec) ty_and_rec
198 | MayRec2 : ('a, 'b, mayrec) ty_and_rec
199
200 (** Used to propagate possible presence of SELF/NEXT in a tree (ternary and) *)
201 type ('a, 'b, 'c, 'd) ty_and_rec3 =
202 | NoRec3 : (norec, norec, norec, norec) ty_and_rec3
203 | MayRec3 : ('a, 'b, 'c, mayrec) ty_and_rec3
204
205 type _ tag = ..
206 module DMap = PolyMap.Make (struct type nonrec 'a tag = 'a tag = .. end)
207
208 type 'a ty_entry = {
209 ename : string;
210 etag : 'a DMap.onetag;
211 }
212
213 and ('self, 'trec, 'a) ty_symbol =
214 | Stoken : 'c pattern -> ('self, norec, 'c) ty_symbol
215 | Stokens : ty_pattern list -> ('self, norec, unit) ty_symbol
216 | Slist1 : ('self, 'trec, 'a) ty_symbol -> ('self, 'trec, 'a list) ty_symbol
217 | Slist1sep : ('self, 'trec, 'a) ty_symbol * ('self, norec, unit) ty_symbol -> ('self, 'trec, 'a list) ty_symbol
218 | Slist0 : ('self, 'trec, 'a) ty_symbol -> ('self, 'trec, 'a list) ty_symbol
219 | Slist0sep : ('self, 'trec, 'a) ty_symbol * ('self, norec, unit) ty_symbol -> ('self, 'trec, 'a list) ty_symbol
220 | Sopt : ('self, 'trec, 'a) ty_symbol -> ('self, 'trec, 'a option) ty_symbol
221 | Sself : ('self, mayrec, 'self) ty_symbol
222 | Snext : ('self, mayrec, 'self) ty_symbol
223 | Snterm : 'a ty_entry -> ('self, norec, 'a) ty_symbol
224 (* norec but the entry can nevertheless introduce a loop with the current entry*)
225 | Snterml : 'a ty_entry * string -> ('self, norec, 'a) ty_symbol
226 | Stree : ('self, 'trec, Loc.t -> 'a) ty_tree -> ('self, 'trec, 'a) ty_symbol
227
228 and ('self, _, _, 'r) ty_rule =
229 | TStop : ('self, norec, 'r, 'r) ty_rule
230 | TNext : ('trr, 'trs, 'tr) ty_and_rec * ('self, 'trr, 'a, 'r) ty_rule * ('self, 'trs, 'b) ty_symbol -> ('self, 'tr, 'b -> 'a, 'r) ty_rule
231
232 and ('self, 'trec, 'a) ty_tree =
233 | Node : ('trn, 'trs, 'trb, 'tr) ty_and_rec3 * ('self, 'trn, 'trs, 'trb, 'b, 'a) ty_node -> ('self, 'tr, 'a) ty_tree
234 | LocAct : 'k -> ('self, norec, 'k) ty_tree
235 | DeadEnd : ('self, norec, 'k) ty_tree
236
237 and ('self, 'trec, 'trecs, 'trecb, 'a, 'r) ty_node = {
238 node : ('self, 'trec, 'a) ty_symbol;
239 son : ('self, 'trecs, 'a -> 'r) ty_tree;
240 brother : ('self, 'trecb, 'r) ty_tree;
241 }
242
243 type ('trecs, 'trecp, 'a) ty_rec_level = {
244 assoc : g_assoc;
245 lname : string option;
246 lsuffix : ('a, 'trecs, 'a -> Loc.t -> 'a) ty_tree;
247 lprefix : ('a, 'trecp, Loc.t -> 'a) ty_tree;
248 }
249
250 type 'a ty_level = Level : (_, _, 'a) ty_rec_level -> 'a ty_level
251
252 type 'a ty_desc =
253 | Dlevels of 'a ty_level list
254 | Dparser of (L.keyword_state -> 'a parser_t)
255
256 (** The closures are built by partially applying the parsing functions
257 to [edesc] but without depending on the state (so when we update
258 an entry we don't need to update closures in unrelated entries).
259 This is an important optimisation, see eg https://gitlab.com/coq/coq/-/jobs/3585529623
260 (+40% on mathcomp-ssreflect, +15% on stdlib without this,
261 significant slowdowns on most developments)
262 *)
263 type ('t,'a) entry_data = {
264 eentry : 'a ty_entry;
265 edesc : 'a ty_desc;
266 estart : 't -> int -> 'a parser_t;
267 econtinue : 't -> int option -> int -> int -> 'a -> 'a parser_t;
268 }
269
270 module rec EState : DMap.MapS
271 with type 'a value := (GState.t, 'a) entry_data
272 = DMap.Map(struct type 'a t = (GState.t, 'a) entry_data end)
273
274 and GState : sig
275 type t = {
276 estate : EState.t;
277 kwstate : L.keyword_state;
278 recover : bool;
279 has_non_assoc : bool;
280 }
281 end = struct
282 type t = {
283 estate : EState.t;
284 kwstate : L.keyword_state;
285 recover : bool;
286 has_non_assoc : bool;
287 }
288 end
289 open GState
290
291 let get_entry estate e = try EState.find (DMap.tag_of_onetag e.etag) estate
292 with Not_found -> assert false
293
294 type 'a ty_rules =
295 | TRules : (_, norec, 'act, Loc.t -> 'a) ty_rule * 'act -> 'a ty_rules
296
297 type 'a ty_production =
298 | TProd : ('a, _, 'act, Loc.t -> 'a) ty_rule * 'act -> 'a ty_production
299
300 let rec derive_eps : type s r a. (s, r, a) ty_symbol -> bool =
301 function
302 Slist0 _ -> true
303 | Slist0sep (_, _) -> true
304 | Sopt _ -> true
305 | Stree t -> tree_derive_eps t
306 | Slist1 _ -> false
307 | Slist1sep (_, _) -> false
308 | Snterm _ -> false | Snterml (_, _) -> false
309 | Snext -> false
310 | Sself -> false
311 | Stoken _ -> false
312 | Stokens _ -> false
313 and tree_derive_eps : type s tr a. (s, tr, a) ty_tree -> bool =
314 function
315 LocAct _ -> true
316 | Node (_, {node = s; brother = bro; son = son}) ->
317 derive_eps s && tree_derive_eps son || tree_derive_eps bro
318 | DeadEnd -> false
319
320 let eq_entry : type a1 a2. a1 ty_entry -> a2 ty_entry -> (a1, a2) eq option = fun e1 e2 ->
321 DMap.eq_onetag e1.etag (DMap.tag_of_onetag e2.etag)
322
323 let tok_pattern_eq_list pl1 pl2 =
324 let f (TPattern p1) (TPattern p2) = Option.has_some (L.tok_pattern_eq p1 p2) in
325 if List.for_all2eq f pl1 pl2 then Some Refl else None
326
327 let rec eq_symbol : type s r1 r2 a1 a2. (s, r1, a1) ty_symbol -> (s, r2, a2) ty_symbol -> (a1, a2) eq option = fun s1 s2 ->
328 match s1, s2 with
329 Snterm e1, Snterm e2 -> eq_entry e1 e2
330 | Snterml (e1, l1), Snterml (e2, l2) ->
331 if String.equal l1 l2 then eq_entry e1 e2 else None
332 | Slist0 s1, Slist0 s2 ->
333 begin match eq_symbol s1 s2 with None -> None | Some Refl -> Some Refl end
334 | Slist0sep (s1, sep1), Slist0sep (s2, sep2) ->
335 begin match eq_symbol s1 s2 with
336 | None -> None
337 | Some Refl ->
338 match eq_symbol sep1 sep2 with
339 | None -> None
340 | Some Refl -> Some Refl
341 end
342 | Slist1 s1, Slist1 s2 ->
343 begin match eq_symbol s1 s2 with None -> None | Some Refl -> Some Refl end
344 | Slist1sep (s1, sep1), Slist1sep (s2, sep2) ->
345 begin match eq_symbol s1 s2 with
346 | None -> None
347 | Some Refl ->
348 match eq_symbol sep1 sep2 with
349 | None -> None
350 | Some Refl -> Some Refl
351 end
352 | Sopt s1, Sopt s2 ->
353 begin match eq_symbol s1 s2 with None -> None | Some Refl -> Some Refl end
354 | Stree _, Stree _ -> None
355 | Sself, Sself -> Some Refl
356 | Snext, Snext -> Some Refl
357 | Stoken p1, Stoken p2 -> L.tok_pattern_eq p1 p2
358 | Stokens pl1, Stokens pl2 -> tok_pattern_eq_list pl1 pl2
359 | _ -> None
360
361 let is_before : type s1 s2 r1 r2 a1 a2. (s1, r1, a1) ty_symbol -> (s2, r2, a2) ty_symbol -> bool = fun s1 s2 ->
362 match s1, s2 with
363 | Stoken p1, Stoken p2 ->
364 L.tok_pattern_exact p1
365 && not (L.tok_pattern_exact p2)
366 | Stoken _, _ -> true
367 | _ -> false
368
369 (** Ancillary datatypes *)
370
371 type 'a ty_rec = MayRec : mayrec ty_rec | NoRec : norec ty_rec
372
373 type ('a, 'b, 'c) ty_and_ex =
374 | NR00 : (mayrec, mayrec, mayrec) ty_and_ex
375 | NR01 : (mayrec, norec, mayrec) ty_and_ex
376 | NR10 : (norec, mayrec, mayrec) ty_and_ex
377 | NR11 : (norec, norec, norec) ty_and_ex
378
379 type ('a, 'b) ty_mayrec_and_ex =
380 | MayRecNR : ('a, 'b, _) ty_and_ex -> ('a, 'b) ty_mayrec_and_ex
381
382 type ('s, 'a) ty_mayrec_symbol =
383 | MayRecSymbol : ('s, _, 'a) ty_symbol -> ('s, 'a) ty_mayrec_symbol
384
385 type ('s, 'a) ty_mayrec_tree =
386 | MayRecTree : ('s, 'tr, 'a) ty_tree -> ('s, 'a) ty_mayrec_tree
387
388 type ('s, 'a, 'r) ty_mayrec_rule =
389 | MayRecRule : ('s, _, 'a, 'r) ty_rule -> ('s, 'a, 'r) ty_mayrec_rule
390
391 type ('self, 'trec, _) ty_symbols =
392 | TNil : ('self, norec, unit) ty_symbols
393 | TCns : ('trh, 'trt, 'tr) ty_and_rec * ('self, 'trh, 'a) ty_symbol * ('self, 'trt, 'b) ty_symbols -> ('self, 'tr, 'a * 'b) ty_symbols
394
395 (** ('i, 'p, 'f, 'r) rel_prod0 ~
396 ∃ α₁ ... αₙ.
397 p ≡ αₙ * ... α₁ * 'i ∧
398 f ≡ α₁ -> ... -> αₙ -> 'r
399 *)
400 type ('i, _, 'f, _) rel_prod0 =
401 | Rel0 : ('i, 'i, 'f, 'f) rel_prod0
402 | RelS : ('i, 'p, 'f, 'a -> 'r) rel_prod0 -> ('i, 'a * 'p, 'f, 'r) rel_prod0
403
404 type ('p, 'k, 'r) rel_prod = (unit, 'p, 'k, 'r) rel_prod0
405
406 type ('s, 'tr, 'i, 'k, 'r) any_symbols =
407 | AnyS : ('s, 'tr, 'p) ty_symbols * ('i, 'p, 'k, 'r) rel_prod0 -> ('s, 'tr, 'i, 'k, 'r) any_symbols
408
409 type ('s, 'tr, 'k, 'r) ty_belast_rule =
410 | Belast : ('trr, 'trs, 'tr) ty_and_rec * ('s, 'trr, 'k, 'a -> 'r) ty_rule * ('s, 'trs, 'a) ty_symbol -> ('s, 'tr, 'k, 'r) ty_belast_rule
411
412 (* unfortunately, this is quadratic, but ty_rules aren't too long
413 * (99% of the time of length less or equal 10 and maximum is 22
414 * when compiling Rocq and its standard library) *)
415 let rec get_symbols : type s trec k r. (s, trec, k, r) ty_rule -> (s, trec, unit, k, r) any_symbols =
416 let rec belast_rule : type s trr trs tr a k r. (trr, trs, tr) ty_and_rec -> (s, trr, k, r) ty_rule -> (s, trs, a) ty_symbol -> (s, tr, a -> k, r) ty_belast_rule =
417 fun ar r s -> match ar, r with
418 | NoRec2, TStop -> Belast (NoRec2, TStop, s)
419 | MayRec2, TStop -> Belast (MayRec2, TStop, s)
420 | NoRec2, TNext (NoRec2, r, s') ->
421 let Belast (NoRec2, r, s') = belast_rule NoRec2 r s' in
422 Belast (NoRec2, TNext (NoRec2, r, s), s')
423 | MayRec2, TNext (_, r, s') ->
424 let Belast (_, r, s') = belast_rule MayRec2 r s' in
425 Belast (MayRec2, TNext (MayRec2, r, s), s') in
426 function
427 | TStop -> AnyS (TNil, Rel0)
428 | TNext (MayRec2, r, s) ->
429 let Belast (MayRec2, r, s) = belast_rule MayRec2 r s in
430 let AnyS (r, pf) = get_symbols r in
431 AnyS (TCns (MayRec2, s, r), RelS pf)
432 | TNext (NoRec2, r, s) ->
433 let Belast (NoRec2, r, s) = belast_rule NoRec2 r s in
434 let AnyS (r, pf) = get_symbols r in
435 AnyS (TCns (NoRec2, s, r), RelS pf)
436
437 let get_rec_symbols (type s tr p) (s : (s, tr, p) ty_symbols) : tr ty_rec =
438 match s with TCns (MayRec2, _, _) -> MayRec
439 | TCns (NoRec2, _, _) -> NoRec | TNil -> NoRec
440
441 let get_rec_tree (type s tr f) (s : (s, tr, f) ty_tree) : tr ty_rec =
442 match s with Node (MayRec3, _) -> MayRec
443 | Node (NoRec3, _) -> NoRec | LocAct _ -> NoRec | DeadEnd -> NoRec
444
445 let and_symbols_tree (type s trs trt p f) (s : (s, trs, p) ty_symbols) (t : (s, trt, f) ty_tree) : (trs, trt) ty_mayrec_and_ex =
446 match get_rec_symbols s, get_rec_tree t with
447 | MayRec, MayRec -> MayRecNR NR00 | MayRec, NoRec -> MayRecNR NR01
448 | NoRec, MayRec -> MayRecNR NR10 | NoRec, NoRec -> MayRecNR NR11
449
450 let and_and_tree (type s tr' trt tr trn trs trb f) (ar : (tr', trt, tr) ty_and_rec) (arn : (trn, trs, trb, trt) ty_and_rec3) (t : (s, trb, f) ty_tree) : (tr', trb, tr) ty_and_rec =
451 match ar, arn, get_rec_tree t with
452 | MayRec2, _, MayRec -> MayRec2 | MayRec2, _, NoRec -> MayRec2
453 | NoRec2, NoRec3, NoRec -> NoRec2
454
455 let insert_tree (type s trs trt tr p k a) entry_name (ar : (trs, trt, tr) ty_and_ex) (gsymbols : (s, trs, p) ty_symbols) (pf : (p, k, a) rel_prod) (action : k) (tree : (s, trt, a) ty_tree) : (s, tr, a) ty_tree =
456 let rec insert : type trs trt tr p f k. (trs, trt, tr) ty_and_ex -> (s, trs, p) ty_symbols -> (p, k, f) rel_prod -> (s, trt, f) ty_tree -> k -> (s, tr, f) ty_tree =
457 fun ar symbols pf tree action ->
458 match symbols, pf with
459 TCns (ars, s, sl), RelS pf ->
460 (* descent in tree at symbol [s] *)
461 insert_in_tree ar ars s sl pf tree action
462 | TNil, Rel0 ->
463 (* insert the action *)
464 let node (type tb) ({node = s; son = son; brother = bro} : (_, _, _, tb, _, _) ty_node) =
465 let ar : (norec, tb, tb) ty_and_ex =
466 match get_rec_tree bro with MayRec -> NR10 | NoRec -> NR11 in
467 {node = s; son = son; brother = insert ar TNil Rel0 bro action} in
468 match ar, tree with
469 | NR10, Node (_, n) -> Node (MayRec3, node n)
470 | NR11, Node (NoRec3, n) -> Node (NoRec3, node n)
471 | NR11, LocAct old_action ->
472 (* What to do about this warning? For now it is disabled *)
473 if false then
474 begin
475 let msg =
476 "<W> Grammar extension: " ^
477 (if entry_name = "" then "" else "in ["^entry_name^"%s], ") ^
478 "some rule has been masked" in
479 Feedback.msg_warning (Pp.str msg)
480 end;
481 LocAct action
482 | NR11, DeadEnd -> LocAct action
483 and insert_in_tree : type trs trs' trs'' trt tr a p f k. (trs'', trt, tr) ty_and_ex -> (trs, trs', trs'') ty_and_rec -> (s, trs, a) ty_symbol -> (s, trs', p) ty_symbols -> (p, k, a -> f) rel_prod -> (s, trt, f) ty_tree -> k -> (s, tr, f) ty_tree =
484 fun ar ars s sl pf tree action ->
485 let ar : (trs'', trt, tr) ty_and_rec = match ar with NR11 -> NoRec2
486 | NR00 -> MayRec2 | NR01 -> MayRec2 | NR10 -> MayRec2 in
487 match try_insert ar ars s sl pf tree action with
488 Some t -> t
489 | None ->
490 let node ar =
491 {node = s; son = insert ar sl pf DeadEnd action; brother = tree} in
492 match ar, ars, get_rec_symbols sl with
493 | MayRec2, MayRec2, MayRec -> Node (MayRec3, node NR01)
494 | MayRec2, _, NoRec -> Node (MayRec3, node NR11)
495 | NoRec2, NoRec2, NoRec -> Node (NoRec3, node NR11)
496 and try_insert : type trs trs' trs'' trt tr a p f k. (trs'', trt, tr) ty_and_rec -> (trs, trs', trs'') ty_and_rec -> (s, trs, a) ty_symbol -> (s, trs', p) ty_symbols -> (p, k, a -> f) rel_prod -> (s, trt, f) ty_tree -> k -> (s, tr, f) ty_tree option =
497 fun ar ars symb symbl pf tree action ->
498 match tree with
499 Node (arn, {node = symb1; son = son; brother = bro}) ->
500 (* merging rule [symb; symbl -> action] in tree [symb1; son | bro] *)
501 begin match eq_symbol symb symb1 with
502 | Some Refl ->
503 (* reducing merge of [symb; symbl -> action] with [symb1; son] to merge of [symbl -> action] with [son] *)
504 let MayRecNR arss = and_symbols_tree symbl son in
505 let son = insert arss symbl pf son action in
506 let node = {node = symb1; son = son; brother = bro} in
507 (* propagate presence of SELF/NEXT *)
508 begin match ar, ars, arn, arss with
509 | MayRec2, _, _, _ -> Some (Node (MayRec3, node))
510 | NoRec2, NoRec2, NoRec3, NR11 -> Some (Node (NoRec3, node)) end
511 | None ->
512 let ar' = and_and_tree ar arn bro in
513 if is_before symb1 symb || derive_eps symb && not (derive_eps symb1) then
514 (* inserting new rule after current rule, i.e. in [bro] *)
515 let bro =
516 match try_insert ar' ars symb symbl pf bro action with
517 Some bro ->
518 (* could insert in [bro] *)
519 bro
520 | None ->
521 (* not ok to insert in [bro] or after; we insert now *)
522 let MayRecNR arss = and_symbols_tree symbl DeadEnd in
523 let son = insert arss symbl pf DeadEnd action in
524 let node = {node = symb; son = son; brother = bro} in
525 (* propagate presence of SELF/NEXT *)
526 match ar, ars, arn, arss with
527 | MayRec2, _, _, _ -> Node (MayRec3, node)
528 | NoRec2, NoRec2, NoRec3, NR11 -> Node (NoRec3, node)
529 in
530 let node = {node = symb1; son = son; brother = bro} in
531 (* propagate presence of SELF/NEXT *)
532 match ar, arn with
533 | MayRec2, _ -> Some (Node (MayRec3, node))
534 | NoRec2, NoRec3 -> Some (Node (NoRec3, node))
535 else
536 (* should insert in [bro] or before the tree [symb1; son | bro] *)
537 match try_insert ar' ars symb symbl pf bro action with
538 Some bro ->
539 (* could insert in [bro] *)
540 let node = {node = symb1; son = son; brother = bro} in
541 begin match ar, arn with
542 | MayRec2, _ -> Some (Node (MayRec3, node))
543 | NoRec2, NoRec3 -> Some (Node (NoRec3, node)) end
544 | None ->
545 (* should insert before [symb1; son | bro] *)
546 None
547 end
548 | LocAct _ -> None | DeadEnd -> None
549 in
550 insert ar gsymbols pf tree action
551
552 let insert_tree_norec (type s p k a) entry_name (gsymbols : (s, norec, p) ty_symbols) (pf : (p, k, a) rel_prod) (action : k) (tree : (s, norec, a) ty_tree) : (s, norec, a) ty_tree =
553 insert_tree entry_name NR11 gsymbols pf action tree
554
555 let insert_tree (type s trs trt p k a) entry_name (gsymbols : (s, trs, p) ty_symbols) (pf : (p, k, a) rel_prod) (action : k) (tree : (s, trt, a) ty_tree) : (s, a) ty_mayrec_tree =
556 let MayRecNR ar = and_symbols_tree gsymbols tree in
557 MayRecTree (insert_tree entry_name ar gsymbols pf action tree)
558
559 let srules (type self a) (rl : a ty_rules list) : (self, norec, a) ty_symbol =
560 let rec retype_tree : type s a. (s, norec, a) ty_tree -> (self, norec, a) ty_tree =
561 function
562 | Node (NoRec3, {node = s; son = son; brother = bro}) ->
563 Node (NoRec3, {node = retype_symbol s; son = retype_tree son; brother = retype_tree bro})
564 | LocAct k -> LocAct k
565 | DeadEnd -> DeadEnd
566 and retype_symbol : type s a. (s, norec, a) ty_symbol -> (self, norec, a) ty_symbol =
567 function
568 | Stoken p -> Stoken p
569 | Stokens l -> Stokens l
570 | Slist1 s -> Slist1 (retype_symbol s)
571 | Slist1sep (s, sep) -> Slist1sep (retype_symbol s, retype_symbol sep)
572 | Slist0 s -> Slist0 (retype_symbol s)
573 | Slist0sep (s, sep) -> Slist0sep (retype_symbol s, retype_symbol sep)
574 | Sopt s -> Sopt (retype_symbol s)
575 | Snterm e -> Snterm e
576 | Snterml (e, l) -> Snterml (e, l)
577 | Stree t -> Stree (retype_tree t) in
578 let rec retype_rule : type s k r. (s, norec, k, r) ty_rule -> (self, norec, k, r) ty_rule =
579 function
580 | TStop -> TStop
581 | TNext (NoRec2, r, s) -> TNext (NoRec2, retype_rule r, retype_symbol s) in
582 let t =
583 List.fold_left
584 (fun tree (TRules (symbols, action)) ->
585 let symbols = retype_rule symbols in
586 let AnyS (symbols, pf) = get_symbols symbols in
587 insert_tree_norec "" symbols pf action tree)
588 DeadEnd rl
589 in
590 Stree t
591
592 let is_level_labelled n (Level lev) =
593 match lev.lname with
594 Some n1 -> n = n1
595 | None -> false
596
597 let insert_level (type s tr p k) entry_name (symbols : (s, tr, p) ty_symbols) (pf : (p, k, Loc.t -> s) rel_prod) (action : k) (slev : s ty_level) : s ty_level =
598 match symbols with
599 | TCns (_, Sself, symbols) ->
600 (* Insert a rule of the form "SELF; ...." *)
601 let Level slev = slev in
602 let RelS pf = pf in
603 let MayRecTree lsuffix = insert_tree entry_name symbols pf action slev.lsuffix in
604 Level
605 {assoc = slev.assoc; lname = slev.lname;
606 lsuffix = lsuffix;
607 lprefix = slev.lprefix}
608 | _ ->
609 (* Insert a rule not starting with SELF *)
610 let Level slev = slev in
611 let MayRecTree lprefix = insert_tree entry_name symbols pf action slev.lprefix in
612 Level
613 {assoc = slev.assoc; lname = slev.lname; lsuffix = slev.lsuffix;
614 lprefix = lprefix}
615
616 let empty_lev lname assoc =
617 let assoc =
618 match assoc with
619 Some a -> a
620 | None -> LeftA
621 in
622 Level
623 {assoc = assoc; lname = lname; lsuffix = DeadEnd; lprefix = DeadEnd}
624
625 let err_no_level lev e =
626 let msg = sprintf "Grammar.extend: No level labelled \"%s\" in entry \"%s\"" lev e in
627 failwith msg
628
629 let get_position entry position levs =
630 match position with
631 First -> [], levs
632 | Last -> levs, []
633 | Before n ->
634 let rec get =
635 function
636 [] -> err_no_level n entry.ename
637 | lev :: levs ->
638 if is_level_labelled n lev then [], lev :: levs
639 else
640 let (levs1, levs2) = get levs in lev :: levs1, levs2
641 in
642 get levs
643 | After n ->
644 let rec get =
645 function
646 [] -> err_no_level n entry.ename
647 | lev :: levs ->
648 if is_level_labelled n lev then [lev], levs
649 else
650 let (levs1, levs2) = get levs in lev :: levs1, levs2
651 in
652 get levs
653
654 let get_level entry name levs = match name with
655 | Some n ->
656 let rec get =
657 function
658 [] -> err_no_level n entry.ename
659 | lev :: levs ->
660 if is_level_labelled n lev then [], lev, levs
661 else
662 let (levs1, rlev, levs2) = get levs in lev :: levs1, rlev, levs2
663 in
664 get levs
665 | None ->
666 begin match levs with
667 lev :: levs -> [], lev, levs
668 | [] ->
669 let msg = sprintf "Grammar.extend: No top level in entry \"%s\"" entry.ename in
670 failwith msg
671 end
672
673 let change_to_self0 (type s) (type trec) (type a) (entry : s ty_entry) : (s, trec, a) ty_symbol -> (s, a) ty_mayrec_symbol =
674 function
675 | Snterm e ->
676 begin match eq_entry e entry with
677 | None -> MayRecSymbol (Snterm e)
678 | Some Refl -> MayRecSymbol (Sself)
679 end
680 | x -> MayRecSymbol x
681
682 let rec change_to_self : type s trec a r. s ty_entry -> (s, trec, a, r) ty_rule -> (s, a, r) ty_mayrec_rule = fun e r -> match r with
683 | TStop -> MayRecRule TStop
684 | TNext (_, r, t) ->
685 let MayRecRule r = change_to_self e r in
686 let MayRecSymbol t = change_to_self0 e t in
687 MayRecRule (TNext (MayRec2, r, t))
688
689 type 's add_kw = { add_kw : 'c. 's -> 'c pattern -> 's }
690
691 let insert_tokens {add_kw} lstate symbols =
692 let rec insert : type s trec a. _ -> (s, trec, a) ty_symbol -> _ =
693 fun lstate -> function
694 | Slist0 s -> insert lstate s
695 | Slist1 s -> insert lstate s
696 | Slist0sep (s, t) -> let lstate = insert lstate s in insert lstate t
697 | Slist1sep (s, t) -> let lstate = insert lstate s in insert lstate t
698 | Sopt s -> insert lstate s
699 | Stree t -> tinsert lstate t
700 | Stoken tok -> add_kw lstate tok
701 | Stokens (TPattern tok::_) ->
702 (* Only the first token is liable to trigger a keyword effect *)
703 add_kw lstate tok
704 | Stokens [] -> assert false
705 | Snterm _
706 | Snterml _
707 | Snext
708 | Sself -> lstate
709 and tinsert : type s tr a. _ -> (s, tr, a) ty_tree -> _ =
710 fun lstate -> function
711 Node (_, {node = s; brother = bro; son = son}) ->
712 let lstate = insert lstate s in
713 let lstate = tinsert lstate bro in
714 tinsert lstate son
715 | LocAct _ | DeadEnd -> lstate
716 and linsert : type s tr p. _ -> (s, tr, p) ty_symbols -> _ =
717 fun lstate -> function
718 | TNil -> lstate
719 | TCns (_, s, r) -> let lstate = insert lstate s in linsert lstate r
720 in
721 linsert lstate symbols
722
723 type 'a single_extend_statement =
724 string option * Gramext.g_assoc option * 'a ty_production list
725
726 type 'a extend_statement =
727 | Reuse of string option * 'a ty_production list
728 | Fresh of Gramext.position * 'a single_extend_statement list
729
730 let add_prod add_kw entry (lstate, lev) (TProd (symbols, action)) =
731 let MayRecRule symbols = change_to_self entry symbols in
732 let AnyS (symbols, pf) = get_symbols symbols in
733 let lstate = insert_tokens add_kw lstate symbols in
734 lstate, insert_level entry.ename symbols pf action lev
735
736 let levels_of_rules add_kw lstate entry edata st =
737 let elev =
738 match edata.edesc with
739 Dlevels elev -> elev
740 | Dparser _ ->
741 let msg = sprintf "Grammar.extend: entry not extensible: \"%s\"" entry.ename in
742 failwith msg
743 in
744 match st with
745 | Reuse (name, []) -> lstate, elev
746 | Reuse (name, prods) ->
747 let (levs1, lev, levs2) = get_level entry name elev in
748 let lstate, lev = List.fold_left (fun lev prod -> add_prod add_kw entry lev prod) (lstate, lev) prods in
749 lstate, levs1 @ [lev] @ levs2
750 | Fresh (position, rules) ->
751 let (levs1, levs2) = get_position entry position elev in
752 let fold (lstate, levs) (lname, assoc, prods) =
753 let lev = empty_lev lname assoc in
754 let lstate, lev = List.fold_left (fun lev prod -> add_prod add_kw entry lev prod) (lstate, lev) prods in
755 lstate, lev :: levs
756 in
757 let lstate, levs = List.fold_left fold (lstate, []) rules in
758 lstate, levs1 @ List.rev levs @ levs2
759
760 type 's ex_symbols =
761 | ExS : ('s, 'tr, 'p) ty_symbols -> 's ex_symbols
762
763 let rec flatten_tree : type s tr a. (s, tr, a) ty_tree -> s ex_symbols list =
764 function
765 DeadEnd -> []
766 | LocAct _ -> [ExS TNil]
767 | Node (_, {node = n; brother = b; son = s}) ->
768 List.map (fun (ExS l) -> ExS (TCns (MayRec2, n, l))) (flatten_tree s) @ flatten_tree b
769
770 let utf8_string_escaped s =
771 let b = Buffer.create (String.length s) in
772 let rec loop i =
773 if i = String.length s then Buffer.contents b
774 else
775 begin
776 begin match s.[i] with
777 '"' -> Buffer.add_string b "\\\""
778 | '\\' -> Buffer.add_string b "\\\\"
779 | '\n' -> Buffer.add_string b "\\n"
780 | '\t' -> Buffer.add_string b "\\t"
781 | '\r' -> Buffer.add_string b "\\r"
782 | '\b' -> Buffer.add_string b "\\b"
783 | c -> Buffer.add_char b c
784 end;
785 loop (i + 1)
786 end
787 in
788 loop 0
789
790 let string_escaped s = utf8_string_escaped s
791
792 let print_str ppf s = fprintf ppf "\"%s\"" (string_escaped s)
793
794 let print_token kwstate b ppf p =
795 match L.tok_pattern_strings kwstate p with
796 | "", Some s -> print_str ppf s
797 | con, Some prm -> if b then fprintf ppf "%s@ %a" con print_str prm else fprintf ppf "(%s@ %a)" con print_str prm
798 | con, None -> fprintf ppf "%s" con
799
800 let print_tokens kwstate ppf = function
801 | [] -> assert false
802 | TPattern p :: pl ->
803 fprintf ppf "[%a%a]"
804 (print_token kwstate true) p
805 (fun ppf -> List.iter (function TPattern p -> fprintf ppf ";@ "; print_token kwstate true ppf p))
806 pl
807
808 let rec print_symbol : type s tr r. _ -> formatter -> (s, tr, r) ty_symbol -> unit =
809 fun kwstate ppf ->
810 function
811 | Slist0 s -> fprintf ppf "LIST0 %a" (print_symbol1 kwstate) s
812 | Slist0sep (s, t) ->
813 fprintf ppf "LIST0 %a SEP %a" (print_symbol1 kwstate) s (print_symbol1 kwstate) t
814 | Slist1 s -> fprintf ppf "LIST1 %a" (print_symbol1 kwstate) s
815 | Slist1sep (s, t) ->
816 fprintf ppf "LIST1 %a SEP %a" (print_symbol1 kwstate) s (print_symbol1 kwstate) t
817 | Sopt s -> fprintf ppf "OPT %a" (print_symbol1 kwstate) s
818 | Stoken p -> print_token kwstate true ppf p
819 | Stokens [TPattern p] -> print_token kwstate true ppf p
820 | Stokens pl -> print_tokens kwstate ppf pl
821 | Snterml (e, l) ->
822 fprintf ppf "%s%s@ LEVEL@ %a" e.ename ""
823 print_str l
824 | s -> (print_symbol1 kwstate) ppf s
825 and print_symbol1 : type s tr r. _ -> formatter -> (s, tr, r) ty_symbol -> unit =
826 fun kwstate ppf ->
827 function
828 | Snterm e -> fprintf ppf "%s%s" e.ename ""
829 | Sself -> pp_print_string ppf "SELF"
830 | Snext -> pp_print_string ppf "NEXT"
831 | Stoken p -> print_token kwstate false ppf p
832 | Stokens [TPattern p] -> print_token kwstate false ppf p
833 | Stokens pl -> print_tokens kwstate ppf pl
834 | Stree t -> print_level kwstate ppf pp_print_space (flatten_tree t)
835 | s ->
836 fprintf ppf "(%a)" (print_symbol kwstate) s
837 and print_rule : type s tr p. _ -> formatter -> (s, tr, p) ty_symbols -> unit =
838 fun kwstate ppf symbols ->
839 fprintf ppf "@[<hov 0>";
840 let rec fold : type s tr p. _ -> (s, tr, p) ty_symbols -> unit =
841 fun sep symbols ->
842 match symbols with
843 | TNil -> ()
844 | TCns (_, symbol, symbols) ->
845 fprintf ppf "%t%a" sep (print_symbol kwstate) symbol;
846 fold (fun ppf -> fprintf ppf ";@ ") symbols
847 in
848 let () = fold (fun ppf -> ()) symbols in
849 fprintf ppf "@]"
850 and print_level : type s. _ -> _ -> _ -> s ex_symbols list -> _ =
851 fun kwstate ppf pp_print_space rules ->
852 fprintf ppf "@[<hov 0>[ ";
853 let () =
854 Format.pp_print_list ~pp_sep:(fun ppf () -> fprintf ppf "%a| " pp_print_space ())
855 (fun ppf (ExS rule) -> print_rule kwstate ppf rule)
856 ppf rules
857 in
858 fprintf ppf " ]@]"
859
860 let print_levels kwstate ppf elev =
861 Format.pp_print_list ~pp_sep:(fun ppf () -> fprintf ppf "@,| ")
862 (fun ppf (Level lev) ->
863 let rules =
864 List.map (fun (ExS t) -> ExS (TCns (MayRec2, Sself, t))) (flatten_tree lev.lsuffix) @
865 flatten_tree lev.lprefix
866 in
867 fprintf ppf "@[<hov 2>";
868 begin match lev.lname with
869 Some n -> fprintf ppf "%a@;<1 2>" print_str n
870 | None -> ()
871 end;
872 begin match lev.assoc with
873 BothA -> fprintf ppf "BOTHA"
874 | LeftA -> fprintf ppf "LEFTA"
875 | RightA -> fprintf ppf "RIGHTA"
876 | NonA -> fprintf ppf "NONA"
877 end;
878 fprintf ppf "@]@;<1 2>";
879 print_level kwstate ppf pp_force_newline rules)
880 ppf elev
881
882 let print_entry estate kwstate ppf e =
883 fprintf ppf "@[<v 0>[ ";
884 begin match (get_entry estate e).edesc with
885 Dlevels elev -> print_levels kwstate ppf elev
886 | Dparser _ -> fprintf ppf "<parser>"
887 end;
888 fprintf ppf " ]@]"
889
890 let name_of_symbol : type s tr a. s ty_entry -> (s, tr, a) ty_symbol -> string =
891 fun entry ->
892 function
893 Snterm e -> "[" ^ e.ename ^ "]"
894 | Snterml (e, l) -> "[" ^ e.ename ^ " level " ^ l ^ "]"
895 | Sself -> "[" ^ entry.ename ^ "]"
896 | Snext -> "[" ^ entry.ename ^ "]"
897 | Stoken tok -> L.tok_text tok
898 | Stokens tokl -> String.concat " " (List.map (function TPattern tok -> L.tok_text tok) tokl)
899 | Slist0 _ -> assert false
900 | Slist1sep _ -> assert false
901 | Slist1 _ -> assert false
902 | Slist0sep _ -> assert false
903 | Sopt _ -> assert false
904 | Stree _ -> assert false
905
906 type ('r, 'f) tok_list =
907 | TokNil : ('f, 'f) tok_list
908 | TokCns : 'a pattern * ('r, 'f) tok_list -> ('a -> 'r, 'f) tok_list
909
910 type ('s, 'f) tok_tree = TokTree : 'a pattern * ('s, _, 'a -> 'r) ty_tree * ('r, 'f) tok_list -> ('s, 'f) tok_tree
911
912 let rec get_token_list : type s tr a r f.
913 s ty_entry -> a pattern -> (r, f) tok_list -> (s, tr, a -> r) ty_tree -> (s, f) tok_tree option =
914 fun entry last_tok rev_tokl tree ->
915 match tree with
916 Node (_, {node = Stoken tok; son = son; brother = DeadEnd}) ->
917 get_token_list entry tok (TokCns (last_tok, rev_tokl)) son
918 | _ ->
919 match rev_tokl with
920 | TokNil -> None
921 | _ -> Some (TokTree (last_tok, tree, rev_tokl))
922
923 let rec name_of_symbol_failed : type s tr a. s ty_entry -> (s, tr, a) ty_symbol -> _ =
924 fun entry ->
925 function
926 | Slist0 s -> name_of_symbol_failed entry s
927 | Slist0sep (s, _) -> name_of_symbol_failed entry s
928 | Slist1 s -> name_of_symbol_failed entry s
929 | Slist1sep (s, _) -> name_of_symbol_failed entry s
930 | Sopt s -> name_of_symbol_failed entry s
931 | Stree t -> name_of_tree_failed entry t
932 | s -> name_of_symbol entry s
933 and name_of_tree_failed : type s tr a. s ty_entry -> (s, tr, a) ty_tree -> _ =
934 fun entry ->
935 function
936 Node (_, {node = s; son = son; brother = bro}) ->
937 let tokl =
938 match s with
939 Stoken tok -> get_token_list entry tok TokNil son
940 | _ -> None
941 in
942 let txt =
943 match tokl with
944 | None ->
945 let txt = name_of_symbol_failed entry s in
946 let txt =
947 match s, son with
948 Sopt _, Node _ -> txt ^ " or " ^ name_of_tree_failed entry son
949 | _ -> txt
950 in
951 txt
952 | Some (TokTree (last_tok, _, rev_tokl)) ->
953 let rec build_str : type a b. string -> (a, b) tok_list -> string =
954 fun s -> function
955 | TokNil -> s
956 | TokCns (tok, t) -> build_str (L.tok_text tok ^ " " ^ s) t in
957 build_str (L.tok_text last_tok) rev_tokl
958 in
959 begin match bro with
960 | DeadEnd -> txt
961 | LocAct _ -> "nothing else"
962 | Node _ -> txt ^ " or " ^ name_of_tree_failed entry bro
963 end
964 | DeadEnd -> "???" | LocAct _ -> "nothing else"
965
966 let tree_failed (type s tr a) (entry : s ty_entry) (prev_symb_result : a) (prev_symb : (s, tr, a) ty_symbol) tree =
967 let txt = name_of_tree_failed entry tree in
968 let txt =
969 match prev_symb with
970 Slist0 s ->
971 let txt1 = name_of_symbol_failed entry s in
972 txt1 ^ " or " ^ txt ^ " expected"
973 | Slist1 s ->
974 let txt1 = name_of_symbol_failed entry s in
975 txt1 ^ " or " ^ txt ^ " expected"
976 | Slist0sep (s, sep) ->
977 begin match prev_symb_result with
978 [] ->
979 let txt1 = name_of_symbol_failed entry s in
980 txt1 ^ " or " ^ txt ^ " expected"
981 | _ ->
982 let txt1 = name_of_symbol_failed entry sep in
983 txt1 ^ " or " ^ txt ^ " expected"
984 end
985 | Slist1sep (s, sep) ->
986 begin match prev_symb_result with
987 [] ->
988 let txt1 = name_of_symbol_failed entry s in
989 txt1 ^ " or " ^ txt ^ " expected"
990 | _ ->
991 let txt1 = name_of_symbol_failed entry sep in
992 txt1 ^ " or " ^ txt ^ " expected"
993 end
994 | Sopt _ -> txt ^ " expected"
995 | Stree _ -> txt ^ " expected"
996 | Snterm _ | Snterml _ | Sself | Snext
997 | Stoken _ | Stokens _ -> txt ^ " expected after " ^ name_of_symbol_failed entry prev_symb
998 in
999 txt ^ " (in [" ^ entry.ename ^ "])"
1000
1001 let symb_failed entry prev_symb_result prev_symb symb =
1002 let tree = Node (MayRec3, {node = symb; brother = DeadEnd; son = DeadEnd}) in
1003 tree_failed entry prev_symb_result prev_symb tree
1004
1005 (* XXX don't use exceptions for this *)
1006 exception TokenListFailed : 's ty_entry * 'a * ('s, 'tr, 'a) ty_symbol * ('s, 'b, 'c) ty_tree -> exn
1007
1008 let level_number entry lab =
1009 let rec lookup levn =
1010 function
1011 [] -> failwith ("unknown level " ^ lab)
1012 | lev :: levs ->
1013 if is_level_labelled lab lev then levn else lookup (succ levn) levs
1014 in
1015 match entry.edesc with
1016 Dlevels elev -> lookup 0 elev
1017 | Dparser _ -> raise Not_found
1018
1019 let rec top_symb : type s tr a. s ty_entry -> (s, tr, a) ty_symbol -> (s, norec, a) ty_symbol parser_v =
1020 fun entry ->
1021 function
1022 Sself -> Ok (Snterm entry)
1023 | Snext -> Ok (Snterm entry)
1024 | Snterml (e, _) -> Ok (Snterm e)
1025 | Slist1sep (s, sep) -> let+ s = top_symb entry s in Slist1sep (s, sep)
1026 | _ -> Error ()
1027
1028 let entry_of_symb : type s tr a. s ty_entry -> (s, tr, a) ty_symbol -> a ty_entry parser_v =
1029 fun entry ->
1030 function
1031 Sself -> Ok entry
1032 | Snext -> Ok entry
1033 | Snterm e -> Ok e
1034 | Snterml (e, _) -> Ok e
1035 | _ -> Error ()
1036
1037 let top_tree : type s tr a. s ty_entry -> (s, tr, a) ty_tree -> (s, tr, a) ty_tree parser_v =
1038 fun entry ->
1039 function
1040 | Node (MayRec3, {node = s; brother = bro; son = son}) ->
1041 let+ s' = top_symb entry s in
1042 Node (MayRec3, {node = s'; brother = bro; son = son})
1043 | Node (NoRec3, {node = s; brother = bro; son = son}) ->
1044 let+ s' = top_symb entry s in
1045 Node (NoRec3, {node = s'; brother = bro; son = son})
1046 | LocAct _ | DeadEnd -> Error ()
1047
1048 let warn_tolerance =
1049 CWarnings.(create_in (create_warning ~name:"level-tolerance"
1050 ~from:[CoreCategories.parsing; Deprecation.Version.v9_2] ())
1051 ~quickfix:(fun ~loc (_, _, qf) -> qf)
1052 Pp.(fun (e, msg, _) ->
1053 strbrk "In " ++ str e ++ str ", tolerating this expression at" ++
1054 strbrk " a higher level than expected " ++ strbrk msg ++ str "." ++
1055 strbrk " This tolerance will be eventually removed." ++
1056 strbrk " Insert parentheses or try to lower the level at which the top symbol of this expression is parsed."))
1057
1058 let warn_recover_qf ename bp ?ep strm__ msg =
1059 let has_ep = Option.has_some ep in
1060 let ep = Option.default (LStream.count strm__) ep in
1061 let loc = LStream.interval_loc bp ep strm__ in
1062 let qf =
1063 let paren_enames = ["term"; "pattern"; "ltac_expr"] in
1064 if not (has_ep && List.mem ename paren_enames) then [] else
1065 let qf le s = Quickfix.make ~loc:(le loc 0 0) (Pp.str s) in
1066 [qf Loc.sub "("; qf Loc.after ")"] in
1067 warn_tolerance ~loc (ename, msg, qf)
1068
1069 let warn_recover ename bp ?ep strm__ =
1070 warn_recover_qf ename bp ?ep strm__ "by the notation started on the left"
1071
1072 let warn_recover_continuation ename bp ep strm__ strict =
1073 let msg = "by the notation continuing on the right"
1074 ^ if not strict then "" else " (which is not left-associative)" in
1075 warn_recover_qf ename bp ~ep strm__ msg
1076
1077 let warn_recover_last_start ename bp ep strm__ =
1078 warn_recover_qf ename bp ~ep strm__ "(there is no next level of last level)"
1079
1080 let empty_entry ename levn strm =
1081 raise (ParseError ("entry [" ^ ename ^ "] is empty"))
1082
1083 let start_parser_of_entry gstate entry levn (strm:_ LStream.t) =
1084 (get_entry gstate.estate entry).estart gstate levn strm
1085
1086 let continue_parser_of_entry gstate entry levfrom levn bp a (strm:_ LStream.t) =
1087 (get_entry gstate.estate entry).econtinue gstate levfrom levn bp a strm
1088
1089 (**
1090 nlevn: level for Snext
1091 alevn: level for recursive calls on the right-hand side of the rule (depending on associativity)
1092 *)
1093 let rec parser_of_tree : type s tr r. s ty_entry -> int -> int -> (s, tr, r) ty_tree -> GState.t -> r parser_t =
1094 fun entry nlevn alevn ->
1095 function
1096 | DeadEnd -> (fun _ (strm__ : _ LStream.t) -> Error ())
1097 | LocAct act -> (fun _ (strm__ : _ LStream.t) -> Ok act)
1098 | Node (_, {node = Sself; son = LocAct act; brother = DeadEnd}) ->
1099 (* SELF on the right-hand side of the last rule *)
1100 (fun gstate (strm__ : _ LStream.t) ->
1101 let+ a = start_parser_of_entry gstate entry alevn strm__ in act a)
1102 | Node (_, {node = Sself; son = LocAct act; brother = bro}) ->
1103 (* SELF on the right-hand side of a rule *)
1104 let p2 = parser_of_tree entry nlevn alevn bro in
1105 (fun gstate (strm__ : _ LStream.t) ->
1106 match start_parser_of_entry gstate entry alevn strm__ with
1107 | Ok a -> Ok (act a)
1108 | Error () -> p2 gstate strm__)
1109 | Node (_, {node = Stoken tok; son = son; brother = DeadEnd}) ->
1110 parser_of_token_list entry nlevn alevn tok son
1111 | Node (_, {node = Stoken tok; son = son; brother = bro}) ->
1112 let p2 = parser_of_tree entry nlevn alevn bro in
1113 let p1 = parser_of_token_list entry nlevn alevn tok son in
1114 (fun gstate (strm__ : _ LStream.t) ->
1115 p1 gstate strm__ <+> (fun () -> p2 gstate strm__))
1116 | Node (_, {node = s; son = son; brother = DeadEnd}) ->
1117 let ps = parser_of_symbol entry nlevn s in
1118 let p1 = parser_of_tree entry nlevn alevn son in
1119 let p1 = parser_cont p1 entry nlevn alevn s son in
1120 (fun gstate (strm__ : _ LStream.t) ->
1121 let bp = LStream.count strm__ in
1122 let* a = ps gstate strm__ in
1123 p1 gstate bp a strm__)
1124 | Node (_, {node = s; son = son; brother = bro}) ->
1125 let ps = parser_of_symbol entry nlevn s in
1126 let p1 = parser_of_tree entry nlevn alevn son in
1127 let p1 = parser_cont p1 entry nlevn alevn s son in
1128 let p2 = parser_of_tree entry nlevn alevn bro in
1129 (fun gstate (strm : _ LStream.t) ->
1130 let bp = LStream.count strm in
1131 match ps gstate strm with
1132 | Ok a -> p1 gstate bp a strm
1133 | Error () -> p2 gstate strm)
1134
1135 and parser_cont : type s tr tr' a r.
1136 (GState.t -> (a -> r) parser_t) -> s ty_entry -> int -> int -> (s, tr, a) ty_symbol -> (s, tr', a -> r) ty_tree -> GState.t -> int -> a -> _ -> r parser_v =
1137 fun p1 entry nlevn alevn s son gstate bp a0 (strm__ : _ LStream.t) ->
1138 match p1 gstate strm__ with
1139 | Ok v -> Ok (v a0)
1140 | Error () ->
1141 let fail a = raise (ParseError (tree_failed entry a s son)) in
1142 let or_fail a x = match x with Ok x -> x | Error () -> fail a in
1143 (* Recover from a success on [s] with result [a] followed by a
1144 failure on [son] in a rule of the form [a = s; son] *)
1145 (* Discard the rule if what has been consumed before failing is
1146 the empty sequence (due to some OPT or LIST0); example:
1147 « OPT "!"; ident » fails to see an ident and the OPT was resolved
1148 into the empty sequence, with application e.g. to being able to
1149 safely write « LIST1 [ OPT "!"; id = ident -> id] ». *)
1150 if LStream.count strm__ == bp then Error ()
1151 else if not gstate.recover then fail a0
1152 else
1153 (* Try to replay the son with the top occurrence of NEXT (by
1154 default at level nlevn) and trailing SELF (by default at alevn)
1155 replaced with self at top level;
1156 This allows for instance to recover from a failure on the
1157 second SELF of « SELF; "\/"; SELF » by doing as if it were
1158 « SELF; "\/"; same-entry-at-top-level » with application e.g. to
1159 accept "A \/ forall x, x = x" w/o requiring the expected
1160 parentheses as in "A \/ (forall x, x = x)". *)
1161 match let* top = top_tree entry son in parser_of_tree entry nlevn alevn top gstate strm__ with
1162 | Ok a ->
1163 warn_recover entry.ename bp strm__;
1164 Ok (a a0)
1165 | Error () ->
1166 (* In case of success on just SELF, NEXT or an explicit call to
1167 a subentry followed by a failure on the rest (son), retry
1168 parsing as if this entry had been called at its toplevel;
1169 example: « "{"; entry-at-some-level; "}" » fails on "}" and
1170 is retried with « "{"; same-entry-at-top-level; "}" », allowing
1171 e.g. to parse « {1 + 1} » while « {(1 + 1)} » would
1172 have been expected according to the level. *)
1173 let p1 = parser_of_tree entry nlevn alevn son in
1174 let a =
1175 let* s' = entry_of_symb entry s in
1176 continue_parser_of_entry gstate s' None 0 bp a0 strm__
1177 in
1178 let ep = LStream.count strm__ in
1179 let a = or_fail a0 a in
1180 let act = or_fail a (p1 gstate strm__) in
1181 warn_recover entry.ename bp ~ep strm__;
1182 Ok (act a)
1183
1184 (** [parser_of_token_list] attempts to look-ahead an arbitrary-long
1185 finite sequence of tokens. E.g., in
1186 [ [ "foo"; "bar1"; "bar3"; ... -> action1
1187 | "foo"; "bar2"; ... -> action2
1188 | other-rules ] ]
1189 compiled as:
1190 [ [ "foo"; ["bar1"; "bar3"; ... -> action1
1191 |"bar2"; ... -> action2]
1192 | other-rules ] ]
1193 this is able to look ahead "foo"; "bar1"; "bar3" and if not found
1194 "foo"; "bar1", then, if still not found, "foo"; "bar2" _without_
1195 consuming the tokens until it is sure that a longest chain of tokens
1196 (before finding non-terminals or the end of the production) is found
1197 (and backtracking to [other-rules] if no such longest chain can be
1198 found). *)
1199 and parser_of_token_list : type s tr lt r.
1200 s ty_entry -> int -> int -> lt pattern -> (s, tr, lt -> r) ty_tree -> GState.t -> r parser_t =
1201 fun entry nlevn alevn tok tree ->
1202 let rec loop : type tr lt r. int -> lt pattern -> (s, tr, r) ty_tree -> GState.t -> lt -> r parser_t =
1203 fun n last_tok tree -> match tree with
1204 | Node (_, {node = Stoken tok; son = son; brother = bro}) ->
1205 let p2 = loop n last_tok bro in
1206 let p1 = loop (n+1) tok son in
1207 fun gstate last_a strm ->
1208 (match Option.bind (LStream.peek_nth gstate.kwstate n strm) (L.tok_match tok) with
1209 | Some a ->
1210 (match p1 gstate a strm with
1211 | Ok act -> Ok (act a)
1212 | Error () ->
1213 (try p2 gstate last_a strm
1214 with TokenListFailed _ -> raise (TokenListFailed (entry, a, Stoken tok, son))))
1215 | None ->
1216 (try p2 gstate last_a strm
1217 with TokenListFailed _ -> raise (TokenListFailed (entry, last_a, Stoken last_tok, tree))))
1218 | DeadEnd -> fun gstate last_a strm -> Error ()
1219 | _ ->
1220 let ps = parser_of_tree entry nlevn alevn tree in
1221 fun gstate last_a strm ->
1222 for _i = 1 to n do LStream.junk gstate.kwstate strm done;
1223 let v = ps gstate strm in
1224 let v =
1225 if not gstate.recover then v else
1226 v <+> fun () ->
1227 (* Tolerance: retry w/o granting the level constraint (see recover) *)
1228 let bp = LStream.count strm in
1229 let* top = top_tree entry tree in
1230 let+ a = parser_of_tree entry nlevn alevn top gstate strm in
1231 warn_recover entry.ename bp strm;
1232 a
1233 in
1234 match v with
1235 | Ok v -> Ok v
1236 | Error () -> raise (TokenListFailed (entry, last_a, (Stoken last_tok), tree))
1237 in
1238 let ps = loop 1 tok tree in
1239 fun gstate strm ->
1240 match LStream.peek gstate.kwstate strm with
1241 | Some tok' ->
1242 (match L.tok_match tok tok' with
1243 | Some a ->
1244 begin
1245 try let+ act = ps gstate a strm in act a
1246 with TokenListFailed (entry, a, tok, tree) ->
1247 raise (ParseError (tree_failed entry a tok tree))
1248 end
1249 | None -> Error ())
1250 | None -> Error ()
1251 and parser_of_symbol : type s tr a.
1252 s ty_entry -> int -> (s, tr, a) ty_symbol -> GState.t -> a parser_t =
1253 fun entry nlevn ->
1254 function
1255 | Slist0 s ->
1256 let ps = parser_of_symbol entry nlevn s in
1257 let rec loop gstate al (strm__ : _ LStream.t) =
1258 match ps gstate strm__ with
1259 | Ok a -> loop gstate (a::al) strm__
1260 | Error () -> al
1261 in
1262 (fun gstate (strm__ : _ LStream.t) ->
1263 let a = loop gstate [] strm__ in Ok (List.rev a))
1264 | Slist0sep (symb, sep) ->
1265 let ps = parser_of_symbol entry nlevn symb in
1266 let pt = parser_of_symbol entry nlevn sep in
1267 let rec kont gstate al (strm__ : _ LStream.t) =
1268 match pt gstate strm__ with
1269 | Ok v ->
1270 let a = match ps gstate strm__ with
1271 | Ok a -> a
1272 | Error () ->
1273 raise (ParseError (symb_failed entry v sep symb))
1274 in
1275 kont gstate (a::al) strm__
1276 | Error () -> al
1277 in
1278 (fun gstate (strm__ : _ LStream.t) ->
1279 match ps gstate strm__ with
1280 | Ok a -> let a = kont gstate [a] strm__ in Ok (List.rev a)
1281 | Error () -> Ok [])
1282 | Slist1 s ->
1283 let ps = parser_of_symbol entry nlevn s in
1284 let rec loop gstate al (strm__ : _ LStream.t) =
1285 match ps gstate strm__ with
1286 | Ok a -> loop gstate (a::al) strm__
1287 | Error () -> al
1288 in
1289 (fun gstate (strm__ : _ LStream.t) ->
1290 let* a = ps gstate strm__ in
1291 let a = loop gstate [a] strm__ in Ok (List.rev a))
1292 | Slist1sep (symb, sep) ->
1293 let ps = parser_of_symbol entry nlevn symb in
1294 let pt = parser_of_symbol entry nlevn sep in
1295 let rec kont gstate al (strm__ : _ LStream.t) =
1296 match pt gstate strm__ with
1297 | Ok v ->
1298 let* a =
1299 match ps gstate strm__ with
1300 | Ok a -> Ok a
1301 | Error () ->
1302 if not gstate.recover then Error () else
1303 let bp = LStream.count strm__ in
1304 let a =
1305 match
1306 let* top = top_symb entry symb in
1307 parser_of_symbol entry 0 top gstate strm__
1308 with
1309 | Ok a -> a
1310 | Error () ->
1311 raise (ParseError (symb_failed entry v sep symb))
1312 in
1313 let () = warn_recover entry.ename bp strm__ in
1314 Ok a
1315 in
1316 kont gstate (a::al) strm__
1317 | Error () -> Ok al
1318 in
1319 (fun gstate (strm__ : _ LStream.t) ->
1320 let* a = ps gstate strm__ in
1321 let+ a = kont gstate [a] strm__ in List.rev a)
1322 | Sopt s ->
1323 let ps = parser_of_symbol entry nlevn s in
1324 (fun gstate (strm__ : _ LStream.t) ->
1325 match ps gstate strm__ with
1326 | Ok a -> Ok (Some a)
1327 | Error () -> Ok None)
1328 | Stree t ->
1329 let pt = parser_of_tree entry 1 0 t in
1330 (fun gstate (strm__ : _ LStream.t) ->
1331 let bp = LStream.count strm__ in
1332 let+ a = pt gstate strm__ in
1333 let ep = LStream.count strm__ in
1334 let loc = LStream.interval_loc bp ep strm__ in a loc)
1335 | Snterm e -> (fun gstate (strm__ : _ LStream.t) -> start_parser_of_entry gstate e 0 strm__)
1336 | Snterml (e, l) ->
1337 (fun gstate (strm__ : _ LStream.t) ->
1338 start_parser_of_entry gstate e (level_number (get_entry gstate.estate e) l) strm__)
1339 | Sself -> (fun gstate (strm__ : _ LStream.t) -> start_parser_of_entry gstate entry 0 strm__)
1340 | Snext -> (fun gstate (strm__ : _ LStream.t) -> start_parser_of_entry gstate entry nlevn strm__)
1341 | Stoken tok -> let p = parser_of_token entry tok in (fun gstate strm -> p gstate.kwstate strm)
1342 | Stokens tokl -> let p = parser_of_tokens entry tokl in (fun gstate strm -> p gstate.kwstate strm)
1343 and parser_of_token : type s a.
1344 s ty_entry -> a pattern -> L.keyword_state -> a parser_t =
1345 fun entry tok ->
1346 let f = L.tok_match tok in
1347 fun kwstate strm ->
1348 match LStream.peek kwstate strm with
1349 | Some tok ->
1350 (match f tok with
1351 | Some r -> LStream.junk kwstate strm; Ok r
1352 | None -> Error ())
1353 | None -> Error ()
1354 and parser_of_tokens : type s.
1355 s ty_entry -> ty_pattern list -> L.keyword_state -> unit parser_t =
1356 fun entry tokl ->
1357 let rec loop n = function
1358 | [] -> fun kwstate strm -> for _i = 1 to n do LStream.junk kwstate strm done; Ok ()
1359 | TPattern tok :: tokl ->
1360 fun kwstate strm ->
1361 let tok' = LStream.peek_nth kwstate n strm in
1362 match Option.bind tok' (L.tok_match tok) with
1363 | Some _ -> loop (n+1) tokl kwstate strm
1364 | None -> Error ()
1365 in
1366 loop 0 tokl
1367
1368 (** [start_parser_of_levels entry clevn levels levn strm] goes
1369 top-down from level [clevn] to the last level, ignoring rules
1370 between [levn] and [clevn], as if starting from
1371 [max(clevn,levn)]. On each rule of the form [prefix] (where
1372 [prefix] is a rule not starting with [SELF]), it tries to consume
1373 the stream [strm].
1374
1375 The interesting case is [entry.estart] which is
1376 [start_parser_of_levels entry 0 entry.edesc], thus practically
1377 going from [levn] to the end.
1378
1379 More schematically, assuming each level has the normalized form
1380
1381 level n: [ a = SELF; b = suffix_tree_n -> action_n(a,b)
1382 | a = prefix_tree_n -> action'_n(a) ]
1383
1384 then the main loop does the following:
1385
1386 estart n =
1387 if prefix_tree_n matches the stream as a then econtinue n (action'_n(a))
1388 else start (n+1)
1389
1390 econtinue n a =
1391 if suffix_tree_n matches the stream as b then econtinue n (action_n(a,b))
1392 else if n=0 then a else econtinue (n-1) a
1393 *)
1394
1395 let rec start_parser_of_levels entry clevn =
1396 function
1397 [] -> (fun _gstate levn (strm__ : _ LStream.t) -> Error ())
1398 | Level lev :: levs ->
1399 let p1 = start_parser_of_levels entry (succ clevn) levs in
1400 match lev.lprefix with
1401 DeadEnd -> p1
1402 | tree ->
1403 let alevn = if self_on_the_right lev.assoc then clevn else succ clevn in
1404 let p2 = parser_of_tree entry (succ clevn) alevn tree in
1405 match levs with
1406 [] ->
1407 (fun gstate levn strm ->
1408 (* Recovery here means that a grammar entry e: [[ "x"; a = e | "y" ]]
1409 works even though it should be: e: [RIGHTA[ "x"; a = e | "y" ]] *)
1410 if not gstate.recover && levn > clevn then Error ()
1411 else
1412 let (strm__ : _ LStream.t) = strm in
1413 let bp = LStream.count strm__ in
1414 let* act = p2 gstate strm__ in
1415 let ep = LStream.count strm__ in
1416 let a = act (LStream.interval_loc bp ep strm__) in
1417 let () = if levn > clevn then
1418 warn_recover_last_start entry.ename bp ep strm__
1419 in
1420 continue_parser_of_entry gstate entry (Some clevn) levn bp a strm)
1421 | _ ->
1422 fun gstate levn strm ->
1423 if levn > clevn then
1424 (* Skip rules before [levn] *)
1425 p1 gstate levn strm
1426 else
1427 let (strm__ : _ LStream.t) = strm in
1428 let bp = LStream.count strm__ in
1429 match p2 gstate strm__ with
1430 | Ok act ->
1431 let ep = LStream.count strm__ in
1432 let a = act (LStream.interval_loc bp ep strm__) in
1433 continue_parser_of_entry gstate entry (Some clevn) levn bp a strm
1434 | Error () -> p1 gstate levn strm__
1435
1436 (** [continue_parser_of_levels entry clevn levels levn bp a strm] goes
1437 bottom-up from the last level to level [clevn], ignoring rules
1438 between [levn] and [clevn], as if stopping at [max(clevn,levn)].
1439 It tries to consume the stream [strm] on the suffix of rules of
1440 the form [SELF; suffix] knowing that [a] is what consumed [SELF]
1441 at level [levn] (or [levn+1] depending on associativity).
1442
1443 The interesting case is [entry.econtinue levn bp a] which is [try
1444 continue_parser_of_levels entry 0 entry.edesc levn bp a with
1445 Failure -> a], thus practically going from the end to [levn].
1446 *)
1447 let rec continue_parser_of_levels entry clevn =
1448 function
1449 [] -> (fun _gstate levfrom levn bp a (strm__ : _ LStream.t) -> Error ())
1450 | Level lev :: levs ->
1451 let p1 = continue_parser_of_levels entry (succ clevn) levs in
1452 match lev.lsuffix with
1453 DeadEnd -> p1
1454 | tree ->
1455 let alevn = if self_on_the_right lev.assoc then clevn else succ clevn in
1456 let p2 = parser_of_tree entry (succ clevn) alevn tree in
1457 fun gstate levfrom levn bp a strm ->
1458 let tolerance = match levfrom with
1459 | Some levfrom when levfrom = clevn && not (self_on_the_left lev.assoc) -> Some true
1460 | Some levfrom when levfrom < clevn -> Some false
1461 | _ -> None
1462 in
1463 (* Apply the lsuffix continuation if the level is in the interval [levn;levfrom] *)
1464 if levn > clevn then
1465 (* Skip rules before [levn] *)
1466 p1 gstate levfrom levn bp a strm
1467 else if (not gstate.recover && Option.has_some tolerance) then
1468 Error ()
1469 else
1470 let (strm__ : _ LStream.t) = strm in
1471 let ep = LStream.count strm__ in
1472 let+ c = p1 gstate levfrom levn bp a strm__ <+> fun () ->
1473 let* act = p2 gstate strm__ in
1474 let ep = LStream.count strm__ in
1475 let a = act a (LStream.interval_loc bp ep strm__) in
1476 if gstate.has_non_assoc && lev.assoc = NonA then
1477 if clevn = levn then
1478 Ok a
1479 else
1480 continue_parser_of_entry gstate entry (Some (clevn-1)) levn bp a strm
1481 else
1482 continue_parser_of_entry gstate entry (Some clevn) levn bp a strm in
1483 let () = Option.iter (warn_recover_continuation entry.ename bp ep strm__) tolerance in
1484 c
1485
1486 let make_continue_parser_of_entry entry = function
1487 | [] -> (fun _ _ _ _ _ (_ : _ LStream.t) -> Error ())
1488 | elev ->
1489 let p = lazy (continue_parser_of_levels entry 0 elev) in
1490 (fun gstate levfrom levn bp a (strm__ : _ LStream.t) ->
1491 Lazy.force p gstate levfrom levn bp a strm__ <+> fun () -> Ok a)
1492
1493 let make_start_parser_of_entry entry = function
1494 | [] -> empty_entry entry.ename
1495 | elev ->
1496 let p = lazy (start_parser_of_levels entry 0 elev) in
1497 (fun gstate levn (strm:_ LStream.t) -> Lazy.force p gstate levn strm)
1498
1499 let make_entry_data entry elev = {
1500 eentry = entry;
1501 edesc = Dlevels elev;
1502 estart = make_start_parser_of_entry entry elev;
1503 econtinue = make_continue_parser_of_entry entry elev;
1504 }
1505
1506 (* Extend syntax *)
1507
1508 let modify_entry estate e f = try EState.modify (DMap.tag_of_onetag e.etag) f estate
1509 with Not_found -> CErrors.anomaly Pp.(str "modify_entry: " ++ str e.ename ++ str " not found")
1510
1511 let add_entry otag estate e v =
1512 assert (not (EState.mem (DMap.tag_of_onetag e.etag) estate));
1513 EState.add otag v estate
1514
1515 let extend_entry add_kw estate kwstate entry statement =
1516 let kwstate = ref kwstate in
1517 let estate = modify_entry estate entry (fun edata ->
1518 let kwstate', elev = levels_of_rules add_kw !kwstate entry edata statement in
1519 kwstate := kwstate';
1520 make_entry_data entry elev)
1521 in
1522 estate, !kwstate
1523
1524 (* Normal interface *)
1525
1526 module Parsable = struct
1527
1528 type t =
1529 { pa_tok_strm : (L.keyword_state,L.te) LStream.t
1530 ; lexer_state : L.State.t ref }
1531
1532 let parse_parsable gstate entry p =
1533 let efun = start_parser_of_entry gstate entry 0 in
1534 let ts = p.pa_tok_strm in
1535 let get_parsing_loc () =
1536 (* Build the loc spanning from just after what is consumed (count)
1537 up to the further token known to have been read (max_peek).
1538 Being a parsing error, there needs to be a next token that
1539 caused the failure, except when the rule is empty (e.g. an
1540 empty custom entry); thus, we need to ensure that the token
1541 at location cnt has been peeked (which in turn ensures that
1542 the max peek is at least the current position) *)
1543 let _ = LStream.peek gstate.kwstate ts in
1544 let loc' = LStream.max_peek_loc ts in
1545 let loc = LStream.get_loc (LStream.count ts) ts in
1546 Loc.merge loc loc'
1547 in
1548 match efun ts with
1549 | Ok v -> v
1550 | Error () ->
1551 let loc = get_parsing_loc () in
1552 let exn = ParseError ("illegal begin of " ^ entry.ename) in
1553 Loc.raise ~loc exn
1554 | exception (ParseError _ as exn) ->
1555 let exn, info = Exninfo.capture exn in
1556 let loc = get_parsing_loc () in
1557 let info = Loc.add_loc info loc in
1558 Exninfo.iraise (exn, info)
1559 | exception exc ->
1560 (* An error produced by the evaluation of the right-hand side *)
1561 (* of a rule, or a signal such as Sys.Break; we leave to the *)
1562 (* error the responsibility of locating itself *)
1563 let exc,info = Exninfo.capture exc in
1564 Exninfo.iraise (exc,info)
1565
1566 let parse_parsable gstate e p =
1567 L.State.set !(p.lexer_state);
1568 try
1569 let c = parse_parsable gstate e p in
1570 p.lexer_state := L.State.get ();
1571 c
1572 with exn ->
1573 let exn,info = Exninfo.capture exn in
1574 L.State.drop ();
1575 Exninfo.iraise (exn,info)
1576
1577 let make ?loc cs =
1578 let lexer_state = ref (L.State.init ()) in
1579 L.State.set !lexer_state;
1580 let ts = L.tok_func ?loc cs in
1581 lexer_state := L.State.get ();
1582 {pa_tok_strm = ts; lexer_state}
1583
1584 let comments p = L.State.get_comments !(p.lexer_state)
1585
1586 let loc t = LStream.current_loc t.pa_tok_strm
1587 let consume { pa_tok_strm } len kwstate = LStream.njunk kwstate len pa_tok_strm
1588 end
1589
1590 module Entry = struct
1591 type 'a t = 'a ty_entry
1592
1593 let fresh n =
1594 let etag = DMap.make () in
1595 { ename = n; etag }, etag
1596
1597 let empty_entry_val e = {
1598 eentry = e;
1599 edesc = Dlevels [];
1600 estart = empty_entry e.ename;
1601 econtinue = (fun _ _ _ _ _ (strm__ : _ LStream.t) -> assert false);
1602 }
1603
1604 let make n estate =
1605 let e, otag = fresh n in
1606 let estate = add_entry otag estate e (empty_entry_val e)
1607 in
1608 estate, e
1609
1610 let parse (e : 'a t) p gstate : 'a =
1611 Parsable.parse_parsable gstate e p
1612 let parse_token_stream (e : 'a t) ts gstate : 'a parser_v =
1613 start_parser_of_entry gstate e 0 ts
1614 let name e = e.ename
1615
1616 type 'a parser_fun = { parser_fun : L.keyword_state -> (L.keyword_state,te) LStream.t -> 'a parser_v }
1617 let of_parser_val e { parser_fun = p } = {
1618 eentry = e;
1619 estart = (fun gstate _ (strm:_ LStream.t) -> p gstate.kwstate strm);
1620 econtinue = (fun _ _ _ _ _ (strm__ : _ LStream.t) -> Error ());
1621 edesc = Dparser p;
1622 }
1623 let of_parser n p estate =
1624 let e, otag = fresh n in
1625 let estate = add_entry otag estate e (of_parser_val e p) in
1626 estate, e
1627
1628 let print ppf e estate kwstate = fprintf ppf "%a@." (print_entry estate kwstate) e
1629
1630 let is_empty e estate = match (get_entry estate e).edesc with
1631 | Dparser _ -> failwith "Arbitrary parser entry"
1632 | Dlevels elev -> List.is_empty elev
1633
1634 type any_t = Any : 'a t -> any_t
1635
1636 let rec iter_in_symbols : type s tr p. _ -> (s, tr, p) ty_symbols -> unit = fun f symbols ->
1637 match symbols with
1638 | TNil -> ()
1639 | TCns (_, symbol, symbols) ->
1640 iter_in_symbol f symbol;
1641 iter_in_symbols f symbols
1642
1643 and iter_in_symbol : type s tr r. _ -> (s, tr, r) ty_symbol -> unit = fun f ->
1644 function
1645 | Snterml (e, _) | Snterm e -> f (Any e)
1646 | Slist0 s -> iter_in_symbol f s
1647 | Slist0sep (s, t) -> iter_in_symbol f s; iter_in_symbol f t
1648 | Slist1 s -> iter_in_symbol f s
1649 | Slist1sep (s, t) -> iter_in_symbol f s; iter_in_symbol f t
1650 | Sopt s -> iter_in_symbol f s
1651 | Stoken _ | Stokens _ -> ()
1652 | Sself | Snext -> ()
1653 | Stree t -> List.iter (fun (ExS rule) -> iter_in_symbols f rule) (flatten_tree t)
1654
1655 let iter_in estate f e = match (get_entry estate e).edesc with
1656 | Dparser _ -> ()
1657 | Dlevels elev ->
1658 List.iter (fun (Level lev) ->
1659 let rules =
1660 List.map (fun (ExS t) -> ExS (TCns (MayRec2, Sself, t))) (flatten_tree lev.lsuffix) @
1661 flatten_tree lev.lprefix
1662 in
1663 List.iter (fun (ExS rule) -> iter_in_symbols f rule) rules)
1664 elev
1665
1666 let same_entry (Any e) (Any e') = Option.has_some (eq_entry e e')
1667
1668 let all_in () estate =
1669 let add_entry (Any e as a) acc = String.Map.update e.ename (function
1670 | None -> Some [a]
1671 | Some l -> Some (a::l))
1672 acc
1673 in
1674 EState.fold { fold = fun _ data acc -> add_entry (Any data.eentry) acc} estate String.Map.empty
1675
1676 let accumulate_in initial estate =
1677 let add_visited visited (Any e as any) =
1678 String.Map.update e.ename (function
1679 | None -> Some [any]
1680 | Some vl as v ->
1681 if List.mem_f same_entry any vl then v else Some (any :: vl))
1682 visited
1683 in
1684 let todo = ref initial in
1685 let visited = List.fold_left add_visited String.Map.empty initial in
1686 let visited = ref visited in
1687 while not (List.is_empty !todo) do
1688 let Any e = List.hd !todo in
1689 todo := List.tl !todo;
1690 iter_in estate (fun (Any e as any) ->
1691 let visited' = add_visited !visited any in
1692 if not (!visited == visited') then begin
1693 visited := visited';
1694 todo := any :: !todo
1695 end)
1696 e
1697 done;
1698 !visited
1699 end
1700
1701 module rec Symbol : sig
1702
1703 type ('self, 'trec, 'a) t = ('self, 'trec, 'a) ty_symbol
1704
1705 val nterm : 'a Entry.t -> ('self, norec, 'a) t
1706 val nterml : 'a Entry.t -> string -> ('self, norec, 'a) t
1707 val list0 : ('self, 'trec, 'a) t -> ('self, 'trec, 'a list) t
1708 val list0sep :
1709 ('self, 'trec, 'a) t -> ('self, norec, unit) t ->
1710 ('self, 'trec, 'a list) t
1711 val list1 : ('self, 'trec, 'a) t -> ('self, 'trec, 'a list) t
1712 val list1sep :
1713 ('self, 'trec, 'a) t -> ('self, norec, unit) t ->
1714 ('self, 'trec, 'a list) t
1715 val opt : ('self, 'trec, 'a) t -> ('self, 'trec, 'a option) t
1716 val self : ('self, mayrec, 'self) t
1717 val next : ('self, mayrec, 'self) t
1718 val token : 'c pattern -> ('self, norec, 'c) t
1719 val tokens : ty_pattern list -> ('self, norec, unit) t
1720 val rules : 'a Rules.t list -> ('self, norec, 'a) t
1721
1722 end = struct
1723
1724 type ('self, 'trec, 'a) t = ('self, 'trec, 'a) ty_symbol
1725 let nterm e = Snterm e
1726 let nterml e l = Snterml (e, l)
1727 let list0 s = Slist0 s
1728 let list0sep s sep = Slist0sep (s, sep)
1729 let list1 s = Slist1 s
1730 let list1sep s sep = Slist1sep (s, sep)
1731 let opt s = Sopt s
1732 let self = Sself
1733 let next = Snext
1734 let token tok = Stoken tok
1735 let tokens tokl = Stokens tokl
1736 let rules (t : 'a Rules.t list) = srules t
1737
1738 end and Rule : sig
1739
1740 type ('self, 'trec, 'f, 'r) t = ('self, 'trec, 'f, 'r) ty_rule
1741
1742 val stop : ('self, norec, 'r, 'r) t
1743 val next :
1744 ('self, _, 'a, 'r) t -> ('self, _, 'b) Symbol.t ->
1745 ('self, mayrec, 'b -> 'a, 'r) t
1746 val next_norec :
1747 ('self, norec, 'a, 'r) Rule.t -> ('self, norec, 'b) Symbol.t ->
1748 ('self, norec, 'b -> 'a, 'r) t
1749
1750 end = struct
1751
1752 type ('self, 'trec, 'f, 'r) t = ('self, 'trec, 'f, 'r) ty_rule
1753
1754 let stop = TStop
1755 let next r s = TNext (MayRec2, r, s)
1756 let next_norec r s = TNext (NoRec2, r, s)
1757
1758 end and Rules : sig
1759
1760 type 'a t = 'a ty_rules
1761 val make : (_, norec, 'f, Loc.t -> 'a) Rule.t -> 'f -> 'a t
1762
1763 end = struct
1764
1765 type 'a t = 'a ty_rules
1766 let make p act = TRules (p, act)
1767
1768 end
1769
1770 module Production = struct
1771
1772 type 'a t = 'a ty_production
1773 let make p act = TProd (p, act)
1774
1775 end
1776
1777 module Unsafe = struct
1778 let existing_entry estate e =
1779 add_entry e.etag estate e (Entry.empty_entry_val e)
1780
1781 let existing_of_parser estate e p =
1782 add_entry e.etag estate e (Entry.of_parser_val e p)
1783 end
1784
1785 let safe_extend = extend_entry
1786
1787 let level_of_nonterm sym = match sym with
1788 | Snterml (_,l) -> Some l
1789 | _ -> None
1790
1791 exception SelfSymbol
1792
1793 let rec generalize_symbol :
1794 type a tr s u. (s, tr, a) Symbol.t -> (u, norec, a) ty_symbol =
1795 function
1796 | Stoken tok ->
1797 Stoken tok
1798 | Stokens tokl ->
1799 Stokens tokl
1800 | Slist1 e ->
1801 Slist1 (generalize_symbol e)
1802 | Slist1sep (e, sep) ->
1803 let e = generalize_symbol e in
1804 let sep = generalize_symbol sep in
1805 Slist1sep (e, sep)
1806 | Slist0 e ->
1807 Slist0 (generalize_symbol e)
1808 | Slist0sep (e, sep) ->
1809 let e = generalize_symbol e in
1810 let sep = generalize_symbol sep in
1811 Slist0sep (e, sep)
1812 | Sopt e ->
1813 Sopt (generalize_symbol e)
1814 | Sself ->
1815 raise SelfSymbol
1816 | Snext ->
1817 raise SelfSymbol
1818 | Snterm e ->
1819 Snterm e
1820 | Snterml (e, l) ->
1821 Snterml (e, l)
1822 | Stree r ->
1823 Stree (generalize_tree r)
1824 and generalize_tree : type a tr s u.
1825 (s, tr, a) ty_tree -> (u, norec, a) ty_tree = fun r ->
1826 match r with
1827 | Node (fi, n) ->
1828 let fi = match fi with
1829 | NoRec3 -> NoRec3
1830 | MayRec3 -> raise SelfSymbol
1831 in
1832 let n = match n with
1833 | { node; son; brother } ->
1834 let node = generalize_symbol node in
1835 let son = generalize_tree son in
1836 let brother = generalize_tree brother in
1837 { node; son; brother }
1838 in
1839 Node (fi, n)
1840 | LocAct _ as r -> r
1841 | DeadEnd as r -> r
1842
1843 let generalize_symbol s =
1844 try Some (generalize_symbol s)
1845 with SelfSymbol -> None
1846
1847 end