Debian Codegraph @

parsing/procq.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 Genarg
13 open Gramlib
14
15 (** The parser of Rocq *)
16 include Grammar.GMake(CLexer.Lexer)
17
18 (** Marshallable representation of grammar extensions *)
19
20 module EntryCommand = Dyn.Make ()
21 module GrammarCommand = Dyn.Make ()
22 module GramState = Store.Make ()
23
24 type gramext = { ignore_kw:bool; entry:GrammarCommand.t }
25
26 type grammar_entry =
27 | GramExt of gramext
28 | EntryExt : ('a * 'b) EntryCommand.tag * 'a -> grammar_entry
29
30 (** State handling (non marshallable!) *)
31
32 type full_state = {
33 (* the state used for parsing *)
34 current_state : GState.t;
35 (* grammar state containing only non-marshallable extensions
36 (NB: this includes entries from Entry.make) *)
37 base_state : GState.t;
38 (* current_state = List.fold_right add_entry current_sync_extensions base_state
39 this means the list is in reverse order of addition *)
40 current_sync_extensions : grammar_entry list;
41 (* some user data tied to the grammar state, typically contains info on declared levels *)
42 user_state : GramState.t;
43 }
44
45 let empty_full_state =
46 let empty_gstate = { GState.estate = EState.empty; kwstate = CLexer.empty_keyword_state; recover = true; has_non_assoc = false } in
47 {
48 current_state = empty_gstate;
49 base_state = empty_gstate;
50 current_sync_extensions = [];
51 user_state = GramState.empty;
52 }
53
54 let assert_synterp () =
55 if !Flags.in_synterp_phase = Some false then
56 CErrors.anomaly Pp.(str "The grammar cannot be modified during the interp phase.")
57
58 (** Not marshallable! *)
59 let state = ref empty_full_state
60
61 let gramstate () = (!state).user_state
62
63 let gstate () = (!state).current_state
64
65 let get_keyword_state () = (gstate()).kwstate
66
67 let reset_to_base state = {
68 base_state = state.base_state;
69 current_state = state.base_state;
70 current_sync_extensions = [];
71 user_state = GramState.empty;
72 }
73
74 let modify_state_unsync f state =
75 let is_base = state.base_state == state.current_state in
76 let base_state = f state.base_state in
77 let current_state = if is_base then base_state else f state.current_state in
78 { state with base_state; current_state }
79
80 let modify_state_unsync f () =
81 assert_synterp ();
82 state := modify_state_unsync f !state
83
84 let modify_keyword_state f =
85 modify_state_unsync (fun {estate;kwstate;recover;has_non_assoc} -> {estate; kwstate = f kwstate; recover; has_non_assoc})
86 ()
87
88 let make_entry_unsync make remake state =
89 let is_base = state.base_state == state.current_state in
90 let base_estate, e = make state.base_state.estate in
91 let base_state = { state.base_state with estate = base_estate } in
92 let current_state = if is_base then base_state else
93 let current_estate = remake state.current_state.estate e in
94 { state.current_state with estate = current_estate }
95 in
96 { state with base_state; current_state }, e
97
98 let make_entry_unsync make remake () =
99 assert_synterp();
100 let statev, e = make_entry_unsync make remake !state in
101 state := statev;
102 e
103
104 let add_kw = { add_kw = CLexer.add_keyword_tok }
105
106 let no_add_kw = { add_kw = fun () _ -> () }
107
108 let epsilon_value (type s tr a) f (e : (s, tr, a) Symbol.t) =
109 let r = Production.make (Rule.next Rule.stop e) (fun x _ -> f x) in
110 let { GState.estate; kwstate; recover; has_non_assoc } = gstate() in
111 let estate, entry = Entry.make "epsilon" estate in
112 let ext = Fresh (Gramlib.Gramext.First, [None, None, [r]]) in
113 let estate, kwstate = safe_extend add_kw estate kwstate entry ext in
114 let strm = Stream.empty () in
115 let strm = Parsable.make strm in
116 try Some (Entry.parse entry strm {estate;kwstate;recover;has_non_assoc}) with e when CErrors.noncritical e -> None
117
118 let extend_gstate ~ignore_kw {GState.kwstate; estate; recover; has_non_assoc} e ext =
119 let estate, kwstate =
120 if ignore_kw then
121 let estate, () = safe_extend no_add_kw estate () e ext in
122 estate, kwstate
123 else safe_extend add_kw estate kwstate e ext
124 in
125 {GState.kwstate; estate; recover; has_non_assoc}
126
127 (* XXX rename to grammar_extend_unsync? *)
128 let grammar_extend ~ignore_kw e ext =
129 let extend_one g = extend_gstate ~ignore_kw g e ext in
130 modify_state_unsync extend_one ()
131
132 type extend_rule =
133 | ExtendRule : 'a Entry.t * 'a extend_statement -> extend_rule
134
135 let grammar_extend_sync ~ignore_kw user_state entry rules state =
136 let extend_one_sync state = function
137 | ExtendRule (e, ext) -> extend_gstate state e ext
138 in
139 let current_state = List.fold_left (extend_one_sync ~ignore_kw) state.current_state rules in
140 { state with
141 current_state;
142 user_state;
143 current_sync_extensions = GramExt {ignore_kw; entry} :: state.current_sync_extensions;
144 }
145
146 let grammar_extend_sync ~ignore_kw st e r () =
147 assert_synterp();
148 state := grammar_extend_sync ~ignore_kw st e r !state
149
150 type ('a,'b) entry_extension = {
151 eext_fun : 'a -> 'b Entry.t -> GramState.t -> GramState.t;
152 eext_name : 'a -> string;
153 eext_eq : 'a -> 'a -> bool;
154 }
155
156 let extend_entry_sync (type a b)
157 (tag : (a * b) EntryCommand.tag)
158 (interp:(a,b) entry_extension)
159 (data:a)
160 state
161 =
162 let name = interp.eext_name data in
163 let current_estate, e = Entry.make name state.current_state.estate in
164 let current_state = { state.current_state with estate = current_estate } in
165 let user_state = interp.eext_fun data e state.user_state in
166 let state = {
167 state with
168 current_state;
169 current_sync_extensions = EntryExt (tag,data) :: state.current_sync_extensions;
170 user_state;
171 }
172 in
173 state
174
175 let extend_entry_sync tag interp data () =
176 assert_synterp();
177 let statev = extend_entry_sync tag interp data !state in
178 state := statev
179
180 module Parsable = struct
181 include Parsable
182 let consume x len = consume x len (get_keyword_state())
183 end
184
185 module Entry = struct
186 include Entry
187 let make name = make_entry_unsync (fun estate -> Entry.make name estate) Unsafe.existing_entry ()
188 let parse e p = parse e p (gstate())
189 let of_parser na p = make_entry_unsync
190 (fun estate -> of_parser na p estate)
191 (fun estate e -> Unsafe.existing_of_parser estate e p)
192 ()
193 let parse_token_stream e strm = parse_token_stream e strm (gstate())
194 let print fmt e = let gstate = gstate() in print fmt e gstate.estate gstate.kwstate
195 let is_empty e = is_empty e (gstate()).estate
196 let accumulate_in e = accumulate_in e (gstate()).estate
197 let all_in () = all_in () (gstate()).estate
198 end
199
200 module Lookahead =
201 struct
202
203 type t = int -> CLexer.keyword_state -> (CLexer.keyword_state,Tok.t) LStream.t -> int option
204
205 let rec contiguous n m strm =
206 n == m ||
207 let (_, ep) = Loc.unloc (LStream.get_loc n strm) in
208 let (bp, _) = Loc.unloc (LStream.get_loc (n + 1) strm) in
209 Int.equal ep bp && contiguous (succ n) m strm
210
211 let check_no_space m _kwstate strm =
212 let n = LStream.count strm in
213 if contiguous n (n+m-1) strm then Some m else None
214
215 let to_entry s (lk : t) =
216 let run kwstate strm = match lk 0 kwstate strm with None -> Error () | Some _ -> Ok () in
217 Entry.(of_parser s { parser_fun = run })
218
219 let (>>) (lk1 : t) lk2 n kwstate strm = match lk1 n kwstate strm with
220 | None -> None
221 | Some n -> lk2 n kwstate strm
222
223 let (<+>) (lk1 : t) lk2 n kwstate strm = match lk1 n kwstate strm with
224 | None -> lk2 n kwstate strm
225 | Some n -> Some n
226
227 let lk_empty n kwstate strm = Some n
228
229 let lk_kw kw n kwstate strm = match LStream.peek_nth kwstate n strm with
230 | Some (Tok.KEYWORD kw' | Tok.IDENT kw') -> if String.equal kw kw' then Some (n + 1) else None
231 | _ -> None
232
233 let lk_kws kws n kwstate strm = match LStream.peek_nth kwstate n strm with
234 | Some (Tok.KEYWORD kw | Tok.IDENT kw) -> if List.mem_f String.equal kw kws then Some (n + 1) else None
235 | _ -> None
236
237 let lk_ident n kwstate strm = match LStream.peek_nth kwstate n strm with
238 | Some (Tok.IDENT _) -> Some (n + 1)
239 | _ -> None
240
241 let lk_name = lk_ident <+> lk_kw "_"
242
243 let lk_ident_except idents n kwstate strm = match LStream.peek_nth kwstate n strm with
244 | Some (Tok.IDENT ident) when not (List.mem_f String.equal ident idents) -> Some (n + 1)
245 | _ -> None
246
247 let lk_nat n kwstate strm = match LStream.peek_nth kwstate n strm with
248 | Some (Tok.NUMBER p) when NumTok.Unsigned.is_nat p -> Some (n + 1)
249 | _ -> None
250
251 let rec lk_list lk_elem n kwstate strm =
252 ((lk_elem >> lk_list lk_elem) <+> lk_empty) n kwstate strm
253
254 let lk_ident_list = lk_list lk_ident
255
256 let lk_field n kwstate strm = match LStream.peek_nth kwstate n strm with
257 | Some (Tok.FIELD _) -> Some (n+1)
258 | _ -> None
259
260 let lk_qualid = lk_ident >> lk_list lk_field
261
262 end
263
264 (** An entry that checks we reached the end of the input. *)
265 (* used by the Tactician plugin *)
266 let eoi_entry en =
267 let e = Entry.make ((Entry.name en) ^ "_eoi") in
268 let symbs = Rule.next (Rule.next Rule.stop (Symbol.nterm en)) (Symbol.token Tok.PEOI) in
269 let act = fun _ x loc -> x in
270 let ext = Fresh (Gramlib.Gramext.First, [None, None, [Production.make symbs act]]) in
271 (* ignore_kw: doesn't matter here, no potential keywords in the rule *)
272 grammar_extend ~ignore_kw:true e ext;
273 e
274
275 (* Parse a string, does NOT check if the entire string was read
276 (use eoi_entry) *)
277
278 let parse_string f ?loc x =
279 let strm = Stream.of_string x in
280 Entry.parse f (Parsable.make ?loc strm)
281
282 module GrammarObj =
283 struct
284 type ('r, _, _) obj = 'r Entry.t
285 let name = "grammar"
286 let default _ = None
287 end
288
289 module Grammar = Register(GrammarObj)
290
291 let register_grammar = Grammar.register0
292 let genarg_grammar x =
293 Grammar.obj x
294
295 let create_generic_entry2 (type a) s (etyp : a raw_abstract_argument_type) : a Entry.t =
296 let e = Entry.make s in
297 let Rawwit t = etyp in
298 let () = Grammar.register0 t e in
299 e
300
301 (* Initial grammar entries *)
302 module Prim =
303 struct
304
305 (* Entries that can be referred via the string -> Entry.t table *)
306 (* Typically for tactic or vernac extensions *)
307 let preident = Entry.make "preident"
308 let ident = Entry.make "ident"
309 let natural = Entry.make "natural"
310 let integer = Entry.make "integer"
311 let bignat = Entry.make "bignat"
312 let bigint = Entry.make "bigint"
313 let string = Entry.make "string"
314 let lstring = Entry.make "lstring"
315 let reference = Entry.make "reference"
316 let fields = Entry.make "fields"
317 let by_notation = Entry.make "by_notation"
318 let smart_global = Entry.make "smart_global"
319 let strategy_level = Entry.make "strategy_level"
320
321 (* parsed like ident but interpreted as a term *)
322 let hyp = Entry.make "hyp"
323
324 let name = Entry.make "name"
325 let identref = Entry.make "identref"
326 let univ_decl = Entry.make "univ_decl"
327 let ident_decl = Entry.make "ident_decl"
328 let pattern_ident = Entry.make "pattern_ident"
329
330 let qualid = Entry.make "qualid"
331 let fullyqualid = Entry.make "fullyqualid"
332 let dirpath = Entry.make "dirpath"
333
334 let ne_string = Entry.make "ne_string"
335 let ne_lstring = Entry.make "ne_lstring"
336
337 let bar_cbrace = Entry.make "'|}'"
338
339 end
340
341 module Constr =
342 struct
343
344 (* Entries that can be referred via the string -> Entry.t table *)
345 let constr = Entry.make "constr"
346 let term = Entry.make "term"
347 let constr_eoi = eoi_entry constr
348 let lconstr = Entry.make "lconstr"
349 let binder_constr = Entry.make "binder_constr"
350 let ident = Entry.make "ident"
351 let global = Entry.make "global"
352 let universe_name = Entry.make "universe_name"
353 let sort = Entry.make "sort"
354 let sort_quality_or_set = Entry.make "sort_quality_or_set"
355 let sort_quality_var = Entry.make "sort_quality_var"
356 let pattern = Entry.make "pattern"
357 let constr_pattern = Entry.make "constr_pattern"
358 let cpattern = Entry.make "cpattern"
359 let closed_binder = Entry.make "closed_binder"
360 let binder = Entry.make "binder"
361 let binders = Entry.make "binders"
362 let open_binders = Entry.make "open_binders"
363 let one_open_binder = Entry.make "one_open_binder"
364 let one_closed_binder = Entry.make "one_closed_binder"
365 let binders_fixannot = Entry.make "binders_fixannot"
366 let typeclass_constraint = Entry.make "typeclass_constraint"
367 let record_declaration = Entry.make "record_declaration"
368 let arg = Entry.make "arg"
369 let type_cstr = Entry.make "type_cstr"
370 end
371
372 module Module =
373 struct
374 let module_expr = Entry.make "module_expr"
375 let module_type = Entry.make "module_type"
376 end
377
378 (** Synchronized grammar extensions *)
379
380 type 'a grammar_extension = {
381 gext_fun : 'a -> GramState.t -> extend_rule list * GramState.t;
382 gext_eq : 'a -> 'a -> bool;
383 }
384
385 module GrammarInterp = struct type 'a t = 'a grammar_extension end
386 module GrammarInterpMap = GrammarCommand.Map(GrammarInterp)
387
388 let grammar_interp = ref GrammarInterpMap.empty
389
390 type 'a grammar_command = 'a GrammarCommand.tag
391
392 let create_grammar_command name interp : _ grammar_command =
393 let obj = GrammarCommand.create name in
394 let () = grammar_interp := GrammarInterpMap.add obj interp !grammar_interp in
395 obj
396
397 let extend_grammar_command ~ignore_kw tag g =
398 let modify = GrammarInterpMap.find tag !grammar_interp in
399 let grammar_state = (!state).user_state in
400 let (rules, st) = modify.gext_fun g grammar_state in
401 grammar_extend_sync ~ignore_kw st (Dyn (tag,g)) rules ()
402
403 module EntryInterp = struct type _ t = EExt : ('a,'b) entry_extension -> ('a * 'b) t end
404 module EntryInterpMap = EntryCommand.Map(EntryInterp)
405
406 let entry_interp = ref EntryInterpMap.empty
407
408 type ('a,'b) entry_command = ('a * 'b) EntryCommand.tag
409
410 let create_entry_command name interp : _ entry_command =
411 let obj = EntryCommand.create name in
412 let () = entry_interp := EntryInterpMap.add obj (EExt interp) !entry_interp in
413 obj
414
415 let extend_entry_command tag data =
416 let EExt interp = EntryInterpMap.find tag !entry_interp in
417 extend_entry_sync tag interp data ()
418
419 (** Registering extra grammar *)
420
421 let grammar_names : Entry.any_t list String.Map.t ref = ref String.Map.empty
422
423 let register_grammars_by_name name grams =
424 grammar_names := String.Map.add name grams !grammar_names
425
426 let find_grammars_by_name name =
427 (* XXX look through custom entries somehow? *)
428 Option.default [] (String.Map.find_opt name !grammar_names)
429
430 (** Summary functions: the state of the lexer is included in that of the parser.
431 Because the grammar affects the set of keywords when adding or removing
432 grammar rules. *)
433 type frozen_t = {
434 frozen_sync : grammar_entry list;
435 frozen_base_kw : CLexer.keyword_state;
436 frozen_kw : CLexer.keyword_state;
437 }
438
439 let unfreeze_only_keywords = function
440 | {frozen_base_kw; frozen_kw} ->
441 let is_base = !(state).base_state == (!state).current_state && frozen_base_kw == frozen_kw in
442 let base_state = { (!state).base_state with kwstate = frozen_base_kw } in
443 let current_state = if is_base then base_state else
444 { (!state).current_state with kwstate = frozen_kw }
445 in
446 state := {
447 !state with
448 base_state;
449 current_state;
450 }
451
452 let eq_grams g1 g2 = match g1, g2 with
453 | GramExt {ignore_kw=kw1;entry=GrammarCommand.Dyn (t1, v1)},
454 GramExt {ignore_kw=kw2;entry=GrammarCommand.Dyn (t2, v2)} ->
455 begin Bool.equal kw1 kw2 && match GrammarCommand.eq t1 t2 with
456 | None -> false
457 | Some Refl ->
458 let data = GrammarInterpMap.find t1 !grammar_interp in
459 data.gext_eq v1 v2
460 end
461 | EntryExt (t1, d1), EntryExt (t2, d2) ->
462 begin match EntryCommand.eq t1 t2 with
463 | None -> false
464 | Some Refl ->
465 let EExt interp = EntryInterpMap.find t1 !entry_interp in
466 interp.eext_eq d1 d2
467 end
468 | (GramExt _, EntryExt _) | (EntryExt _, GramExt _) -> false
469
470 (* We compare the current state of the grammar and the state to unfreeze,
471 by computing the longest common suffixes *)
472 let factorize_grams l1 l2 =
473 if l1 == l2 then ([], [], l1) else List.share_tails eq_grams l1 l2
474
475 let replay_sync_extension = function
476 | GramExt {ignore_kw;entry=Dyn(tag,g)} -> extend_grammar_command ~ignore_kw tag g
477 | EntryExt (tag,data) -> extend_entry_command tag data
478
479 let unfreeze ({frozen_sync;} as frozen) =
480 (* allow unfreezing synterp state even during interp phase *)
481 Flags.with_modified_ref Flags.in_synterp_phase (fun _ -> None) (fun () ->
482 let to_remove, to_add, _common = factorize_grams (!state).current_sync_extensions frozen_sync in
483 if CList.is_empty to_remove then begin
484 List.iter replay_sync_extension (List.rev to_add);
485 unfreeze_only_keywords frozen
486 end
487 else begin
488 state := reset_to_base !state;
489 List.iter replay_sync_extension (List.rev frozen_sync);
490 (* put back the keyword state, needed to support ssr hacks *)
491 unfreeze_only_keywords frozen
492 end)
493 ()
494
495 let freeze_state state = {
496 frozen_sync = state.current_sync_extensions;
497 frozen_base_kw = state.base_state.kwstate;
498 frozen_kw = state.current_state.kwstate;
499 }
500
501 let freeze () : frozen_t = freeze_state !state
502
503 (** No need to provide an init function : the grammar state is
504 statically available, and already empty initially, while
505 the lexer state should not be reset, since it contains
506 keywords declared in g_*.mlg
507
508 XXX is this still true? if not we can do (fun () -> unfreeze (FreezeFull empty_full_state)) *)
509
510 let parser_summary_tag =
511 Summary.declare_summary_tag "GRAMMAR_LEXER"
512 { stage = Summary.Stage.Synterp;
513 Summary.freeze_function = freeze;
514 Summary.unfreeze_function = unfreeze;
515 Summary.init_function = Summary.nop }
516
517 let with_grammar_rule_protection f x =
518 let open Memprof_coq.Resource_bind in
519 let& () = Util.protect_state ~freeze ~unfreeze in
520 f x
521
522 (* Usually we don't need to protect unfreeze, as for references doing
523 unfreeze again will restore them to a coherent state, however this
524 is not the case for Procq *)
525 let unfreeze = Util.atomify unfreeze