forked from ocaml/ocaml
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmenhirLib.mli
1705 lines (1234 loc) · 67.9 KB
/
menhirLib.mli
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
module General : sig
(******************************************************************************)
(* *)
(* Menhir *)
(* *)
(* François Pottier, Inria Paris *)
(* Yann Régis-Gianas, PPS, Université Paris Diderot *)
(* *)
(* Copyright Inria. All rights reserved. This file is distributed under the *)
(* terms of the GNU Library General Public License version 2, with a *)
(* special exception on linking, as described in the file LICENSE. *)
(* *)
(******************************************************************************)
(* This module offers general-purpose functions on lists and streams. *)
(* As of 2017/03/31, this module is DEPRECATED. It might be removed in
the future. *)
(* --------------------------------------------------------------------------- *)
(* Lists. *)
(* [take n xs] returns the [n] first elements of the list [xs]. It is
acceptable for the list [xs] to have length less than [n], in
which case [xs] itself is returned. *)
val take: int -> 'a list -> 'a list
(* [drop n xs] returns the list [xs], deprived of its [n] first elements.
It is acceptable for the list [xs] to have length less than [n], in
which case an empty list is returned. *)
val drop: int -> 'a list -> 'a list
(* [uniq cmp xs] assumes that the list [xs] is sorted according to the
ordering [cmp] and returns the list [xs] deprived of any duplicate
elements. *)
val uniq: ('a -> 'a -> int) -> 'a list -> 'a list
(* [weed cmp xs] returns the list [xs] deprived of any duplicate elements. *)
val weed: ('a -> 'a -> int) -> 'a list -> 'a list
(* --------------------------------------------------------------------------- *)
(* A stream is a list whose elements are produced on demand. *)
type 'a stream =
'a head Lazy.t
and 'a head =
| Nil
| Cons of 'a * 'a stream
(* The length of a stream. *)
val length: 'a stream -> int
(* Folding over a stream. *)
val foldr: ('a -> 'b -> 'b) -> 'a stream -> 'b -> 'b
end
module Convert : sig
(******************************************************************************)
(* *)
(* Menhir *)
(* *)
(* François Pottier, Inria Paris *)
(* Yann Régis-Gianas, PPS, Université Paris Diderot *)
(* *)
(* Copyright Inria. All rights reserved. This file is distributed under the *)
(* terms of the GNU Library General Public License version 2, with a *)
(* special exception on linking, as described in the file LICENSE. *)
(* *)
(******************************************************************************)
(* An ocamlyacc-style, or Menhir-style, parser requires access to
the lexer, which must be parameterized with a lexing buffer, and
to the lexing buffer itself, where it reads position information. *)
(* This traditional API is convenient when used with ocamllex, but
inelegant when used with other lexer generators. *)
type ('token, 'semantic_value) traditional =
(Lexing.lexbuf -> 'token) -> Lexing.lexbuf -> 'semantic_value
(* This revised API is independent of any lexer generator. Here, the
parser only requires access to the lexer, and the lexer takes no
parameters. The tokens returned by the lexer may contain position
information. *)
type ('token, 'semantic_value) revised =
(unit -> 'token) -> 'semantic_value
(* --------------------------------------------------------------------------- *)
(* Converting a traditional parser, produced by ocamlyacc or Menhir,
into a revised parser. *)
(* A token of the revised lexer is essentially a triple of a token
of the traditional lexer (or raw token), a start position, and
and end position. The three [get] functions are accessors. *)
(* We do not require the type ['token] to actually be a triple type.
This enables complex applications where it is a record type with
more than three fields. It also enables simple applications where
positions are of no interest, so ['token] is just ['raw_token]
and [get_startp] and [get_endp] return dummy positions. *)
val traditional2revised:
('token -> 'raw_token) ->
('token -> Lexing.position) ->
('token -> Lexing.position) ->
('raw_token, 'semantic_value) traditional ->
('token, 'semantic_value) revised
(* --------------------------------------------------------------------------- *)
(* Converting a revised parser back to a traditional parser. *)
val revised2traditional:
('raw_token -> Lexing.position -> Lexing.position -> 'token) ->
('token, 'semantic_value) revised ->
('raw_token, 'semantic_value) traditional
(* --------------------------------------------------------------------------- *)
(* Simplified versions of the above, where concrete triples are used. *)
module Simplified : sig
val traditional2revised:
('token, 'semantic_value) traditional ->
('token * Lexing.position * Lexing.position, 'semantic_value) revised
val revised2traditional:
('token * Lexing.position * Lexing.position, 'semantic_value) revised ->
('token, 'semantic_value) traditional
end
end
module IncrementalEngine : sig
(******************************************************************************)
(* *)
(* Menhir *)
(* *)
(* François Pottier, Inria Paris *)
(* Yann Régis-Gianas, PPS, Université Paris Diderot *)
(* *)
(* Copyright Inria. All rights reserved. This file is distributed under the *)
(* terms of the GNU Library General Public License version 2, with a *)
(* special exception on linking, as described in the file LICENSE. *)
(* *)
(******************************************************************************)
type position = Lexing.position
open General
(* This signature describes the incremental LR engine. *)
(* In this mode, the user controls the lexer, and the parser suspends
itself when it needs to read a new token. *)
module type INCREMENTAL_ENGINE = sig
type token
(* A value of type [production] is (an index for) a production. The start
productions (which do not exist in an \mly file, but are constructed by
Menhir internally) are not part of this type. *)
type production
(* The type ['a checkpoint] represents an intermediate or final state of the
parser. An intermediate checkpoint is a suspension: it records the parser's
current state, and allows parsing to be resumed. The parameter ['a] is
the type of the semantic value that will eventually be produced if the
parser succeeds. *)
(* [Accepted] and [Rejected] are final checkpoints. [Accepted] carries a
semantic value. *)
(* [InputNeeded] is an intermediate checkpoint. It means that the parser wishes
to read one token before continuing. *)
(* [Shifting] is an intermediate checkpoint. It means that the parser is taking
a shift transition. It exposes the state of the parser before and after
the transition. The Boolean parameter tells whether the parser intends to
request a new token after this transition. (It always does, except when
it is about to accept.) *)
(* [AboutToReduce] is an intermediate checkpoint. It means that the parser is
about to perform a reduction step. It exposes the parser's current
state as well as the production that is about to be reduced. *)
(* [HandlingError] is an intermediate checkpoint. It means that the parser has
detected an error and is currently handling it, in several steps. *)
(* A value of type ['a env] represents a configuration of the automaton:
current state, stack, lookahead token, etc. The parameter ['a] is the
type of the semantic value that will eventually be produced if the parser
succeeds. *)
(* In normal operation, the parser works with checkpoints: see the functions
[offer] and [resume]. However, it is also possible to work directly with
environments (see the functions [pop], [force_reduction], and [feed]) and
to reconstruct a checkpoint out of an environment (see [input_needed]).
This is considered advanced functionality; its purpose is to allow error
recovery strategies to be programmed by the user. *)
type 'a env
type 'a checkpoint = private
| InputNeeded of 'a env
| Shifting of 'a env * 'a env * bool
| AboutToReduce of 'a env * production
| HandlingError of 'a env
| Accepted of 'a
| Rejected
(* [offer] allows the user to resume the parser after it has suspended
itself with a checkpoint of the form [InputNeeded env]. [offer] expects the
old checkpoint as well as a new token and produces a new checkpoint. It does not
raise any exception. *)
val offer:
'a checkpoint ->
token * position * position ->
'a checkpoint
(* [resume] allows the user to resume the parser after it has suspended
itself with a checkpoint of the form [AboutToReduce (env, prod)] or
[HandlingError env]. [resume] expects the old checkpoint and produces a new
checkpoint. It does not raise any exception. *)
val resume:
'a checkpoint ->
'a checkpoint
(* A token supplier is a function of no arguments which delivers a new token
(together with its start and end positions) every time it is called. *)
type supplier =
unit -> token * position * position
(* A pair of a lexer and a lexing buffer can be easily turned into a supplier. *)
val lexer_lexbuf_to_supplier:
(Lexing.lexbuf -> token) ->
Lexing.lexbuf ->
supplier
(* The functions [offer] and [resume] are sufficient to write a parser loop.
One can imagine many variations (which is why we expose these functions
in the first place!). Here, we expose a few variations of the main loop,
ready for use. *)
(* [loop supplier checkpoint] begins parsing from [checkpoint], reading
tokens from [supplier]. It continues parsing until it reaches a
checkpoint of the form [Accepted v] or [Rejected]. In the former case, it
returns [v]. In the latter case, it raises the exception [Error]. *)
val loop: supplier -> 'a checkpoint -> 'a
(* [loop_handle succeed fail supplier checkpoint] begins parsing from
[checkpoint], reading tokens from [supplier]. It continues parsing until
it reaches a checkpoint of the form [Accepted v] or [HandlingError env]
(or [Rejected], but that should not happen, as [HandlingError _] will be
observed first). In the former case, it calls [succeed v]. In the latter
case, it calls [fail] with this checkpoint. It cannot raise [Error].
This means that Menhir's traditional error-handling procedure (which pops
the stack until a state that can act on the [error] token is found) does
not get a chance to run. Instead, the user can implement her own error
handling code, in the [fail] continuation. *)
val loop_handle:
('a -> 'answer) ->
('a checkpoint -> 'answer) ->
supplier -> 'a checkpoint -> 'answer
(* [loop_handle_undo] is analogous to [loop_handle], except it passes a pair
of checkpoints to the failure continuation.
The first (and oldest) checkpoint is the last [InputNeeded] checkpoint that
was encountered before the error was detected. The second (and newest)
checkpoint is where the error was detected, as in [loop_handle]. Going back
to the first checkpoint can be thought of as undoing any reductions that
were performed after seeing the problematic token. (These reductions must
be default reductions or spurious reductions.)
[loop_handle_undo] must initially be applied to an [InputNeeded] checkpoint.
The parser's initial checkpoints satisfy this constraint. *)
val loop_handle_undo:
('a -> 'answer) ->
('a checkpoint -> 'a checkpoint -> 'answer) ->
supplier -> 'a checkpoint -> 'answer
(* [shifts checkpoint] assumes that [checkpoint] has been obtained by
submitting a token to the parser. It runs the parser from [checkpoint],
through an arbitrary number of reductions, until the parser either
accepts this token (i.e., shifts) or rejects it (i.e., signals an error).
If the parser decides to shift, then [Some env] is returned, where [env]
is the parser's state just before shifting. Otherwise, [None] is
returned. *)
(* It is desirable that the semantic actions be side-effect free, or that
their side-effects be harmless (replayable). *)
val shifts: 'a checkpoint -> 'a env option
(* The function [acceptable] allows testing, after an error has been
detected, which tokens would have been accepted at this point. It is
implemented using [shifts]. Its argument should be an [InputNeeded]
checkpoint. *)
(* For completeness, one must undo any spurious reductions before carrying out
this test -- that is, one must apply [acceptable] to the FIRST checkpoint
that is passed by [loop_handle_undo] to its failure continuation. *)
(* This test causes some semantic actions to be run! The semantic actions
should be side-effect free, or their side-effects should be harmless. *)
(* The position [pos] is used as the start and end positions of the
hypothetical token, and may be picked up by the semantic actions. We
suggest using the position where the error was detected. *)
val acceptable: 'a checkpoint -> token -> position -> bool
(* The abstract type ['a lr1state] describes the non-initial states of the
LR(1) automaton. The index ['a] represents the type of the semantic value
associated with this state's incoming symbol. *)
type 'a lr1state
(* The states of the LR(1) automaton are numbered (from 0 and up). *)
val number: _ lr1state -> int
(* Productions are numbered. *)
(* [find_production i] requires the index [i] to be valid. Use with care. *)
val production_index: production -> int
val find_production: int -> production
(* An element is a pair of a non-initial state [s] and a semantic value [v]
associated with the incoming symbol of this state. The idea is, the value
[v] was pushed onto the stack just before the state [s] was entered. Thus,
for some type ['a], the state [s] has type ['a lr1state] and the value [v]
has type ['a]. In other words, the type [element] is an existential type. *)
type element =
| Element: 'a lr1state * 'a * position * position -> element
(* The parser's stack is (or, more precisely, can be viewed as) a stream of
elements. The type [stream] is defined by the module [General]. *)
(* As of 2017/03/31, the types [stream] and [stack] and the function [stack]
are DEPRECATED. They might be removed in the future. An alternative way
of inspecting the stack is via the functions [top] and [pop]. *)
type stack = (* DEPRECATED *)
element stream
(* This is the parser's stack, a stream of elements. This stream is empty if
the parser is in an initial state; otherwise, it is non-empty. The LR(1)
automaton's current state is the one found in the top element of the
stack. *)
val stack: 'a env -> stack (* DEPRECATED *)
(* [top env] returns the parser's top stack element. The state contained in
this stack element is the current state of the automaton. If the stack is
empty, [None] is returned. In that case, the current state of the
automaton must be an initial state. *)
val top: 'a env -> element option
(* [pop_many i env] pops [i] cells off the automaton's stack. This is done
via [i] successive invocations of [pop]. Thus, [pop_many 1] is [pop]. The
index [i] must be nonnegative. The time complexity is O(i). *)
val pop_many: int -> 'a env -> 'a env option
(* [get i env] returns the parser's [i]-th stack element. The index [i] is
0-based: thus, [get 0] is [top]. If [i] is greater than or equal to the
number of elements in the stack, [None] is returned. The time complexity
is O(i). *)
val get: int -> 'a env -> element option
(* [current_state_number env] is (the integer number of) the automaton's
current state. This works even if the automaton's stack is empty, in
which case the current state is an initial state. This number can be
passed as an argument to a [message] function generated by [menhir
--compile-errors]. *)
val current_state_number: 'a env -> int
(* [equal env1 env2] tells whether the parser configurations [env1] and
[env2] are equal in the sense that the automaton's current state is the
same in [env1] and [env2] and the stack is *physically* the same in
[env1] and [env2]. If [equal env1 env2] is [true], then the sequence of
the stack elements, as observed via [pop] and [top], must be the same in
[env1] and [env2]. Also, if [equal env1 env2] holds, then the checkpoints
[input_needed env1] and [input_needed env2] must be equivalent. The
function [equal] has time complexity O(1). *)
val equal: 'a env -> 'a env -> bool
(* These are the start and end positions of the current lookahead token. If
invoked in an initial state, this function returns a pair of twice the
initial position. *)
val positions: 'a env -> position * position
(* When applied to an environment taken from a checkpoint of the form
[AboutToReduce (env, prod)], the function [env_has_default_reduction]
tells whether the reduction that is about to take place is a default
reduction. *)
val env_has_default_reduction: 'a env -> bool
(* [state_has_default_reduction s] tells whether the state [s] has a default
reduction. This includes the case where [s] is an accepting state. *)
val state_has_default_reduction: _ lr1state -> bool
(* [pop env] returns a new environment, where the parser's top stack cell
has been popped off. (If the stack is empty, [None] is returned.) This
amounts to pretending that the (terminal or nonterminal) symbol that
corresponds to this stack cell has not been read. *)
val pop: 'a env -> 'a env option
(* [force_reduction prod env] should be called only if in the state [env]
the parser is capable of reducing the production [prod]. If this
condition is satisfied, then this production is reduced, which means that
its semantic action is executed (this can have side effects!) and the
automaton makes a goto (nonterminal) transition. If this condition is not
satisfied, [Invalid_argument _] is raised. *)
val force_reduction: production -> 'a env -> 'a env
(* [input_needed env] returns [InputNeeded env]. That is, out of an [env]
that might have been obtained via a series of calls to the functions
[pop], [force_reduction], [feed], etc., it produces a checkpoint, which
can be used to resume normal parsing, by supplying this checkpoint as an
argument to [offer]. *)
(* This function should be used with some care. It could "mess up the
lookahead" in the sense that it allows parsing to resume in an arbitrary
state [s] with an arbitrary lookahead symbol [t], even though Menhir's
reachability analysis (menhir --list-errors) might well think that it is
impossible to reach this particular configuration. If one is using
Menhir's new error reporting facility, this could cause the parser to
reach an error state for which no error message has been prepared. *)
val input_needed: 'a env -> 'a checkpoint
end
(* This signature is a fragment of the inspection API that is made available
to the user when [--inspection] is used. This fragment contains type
definitions for symbols. *)
module type SYMBOLS = sig
(* The type ['a terminal] represents a terminal symbol. The type ['a
nonterminal] represents a nonterminal symbol. In both cases, the index
['a] represents the type of the semantic values associated with this
symbol. The concrete definitions of these types are generated. *)
type 'a terminal
type 'a nonterminal
(* The type ['a symbol] represents a terminal or nonterminal symbol. It is
the disjoint union of the types ['a terminal] and ['a nonterminal]. *)
type 'a symbol =
| T : 'a terminal -> 'a symbol
| N : 'a nonterminal -> 'a symbol
(* The type [xsymbol] is an existentially quantified version of the type
['a symbol]. This type is useful in situations where the index ['a]
is not statically known. *)
type xsymbol =
| X : 'a symbol -> xsymbol
end
(* This signature describes the inspection API that is made available to the
user when [--inspection] is used. *)
module type INSPECTION = sig
(* The types of symbols are described above. *)
include SYMBOLS
(* The type ['a lr1state] is meant to be the same as in [INCREMENTAL_ENGINE]. *)
type 'a lr1state
(* The type [production] is meant to be the same as in [INCREMENTAL_ENGINE].
It represents a production of the grammar. A production can be examined
via the functions [lhs] and [rhs] below. *)
type production
(* An LR(0) item is a pair of a production [prod] and a valid index [i] into
this production. That is, if the length of [rhs prod] is [n], then [i] is
comprised between 0 and [n], inclusive. *)
type item =
production * int
(* Ordering functions. *)
val compare_terminals: _ terminal -> _ terminal -> int
val compare_nonterminals: _ nonterminal -> _ nonterminal -> int
val compare_symbols: xsymbol -> xsymbol -> int
val compare_productions: production -> production -> int
val compare_items: item -> item -> int
(* [incoming_symbol s] is the incoming symbol of the state [s], that is,
the symbol that the parser must recognize before (has recognized when)
it enters the state [s]. This function gives access to the semantic
value [v] stored in a stack element [Element (s, v, _, _)]. Indeed,
by case analysis on the symbol [incoming_symbol s], one discovers the
type ['a] of the value [v]. *)
val incoming_symbol: 'a lr1state -> 'a symbol
(* [items s] is the set of the LR(0) items in the LR(0) core of the LR(1)
state [s]. This set is not epsilon-closed. This set is presented as a
list, in an arbitrary order. *)
val items: _ lr1state -> item list
(* [lhs prod] is the left-hand side of the production [prod]. This is
always a non-terminal symbol. *)
val lhs: production -> xsymbol
(* [rhs prod] is the right-hand side of the production [prod]. This is
a (possibly empty) sequence of (terminal or nonterminal) symbols. *)
val rhs: production -> xsymbol list
(* [nullable nt] tells whether the non-terminal symbol [nt] is nullable.
That is, it is true if and only if this symbol produces the empty
word [epsilon]. *)
val nullable: _ nonterminal -> bool
(* [first nt t] tells whether the FIRST set of the nonterminal symbol [nt]
contains the terminal symbol [t]. That is, it is true if and only if
[nt] produces a word that begins with [t]. *)
val first: _ nonterminal -> _ terminal -> bool
(* [xfirst] is analogous to [first], but expects a first argument of type
[xsymbol] instead of [_ terminal]. *)
val xfirst: xsymbol -> _ terminal -> bool
(* [foreach_terminal] enumerates the terminal symbols, including [error].
[foreach_terminal_but_error] enumerates the terminal symbols, excluding
[error]. *)
val foreach_terminal: (xsymbol -> 'a -> 'a) -> 'a -> 'a
val foreach_terminal_but_error: (xsymbol -> 'a -> 'a) -> 'a -> 'a
(* The type [env] is meant to be the same as in [INCREMENTAL_ENGINE]. *)
type 'a env
(* [feed symbol startp semv endp env] causes the parser to consume the
(terminal or nonterminal) symbol [symbol], accompanied with the semantic
value [semv] and with the start and end positions [startp] and [endp].
Thus, the automaton makes a transition, and reaches a new state. The
stack grows by one cell. This operation is permitted only if the current
state (as determined by [env]) has an outgoing transition labeled with
[symbol]. Otherwise, [Invalid_argument _] is raised. *)
val feed: 'a symbol -> position -> 'a -> position -> 'b env -> 'b env
end
(* This signature combines the incremental API and the inspection API. *)
module type EVERYTHING = sig
include INCREMENTAL_ENGINE
include INSPECTION
with type 'a lr1state := 'a lr1state
with type production := production
with type 'a env := 'a env
end
end
module EngineTypes : sig
(******************************************************************************)
(* *)
(* Menhir *)
(* *)
(* François Pottier, Inria Paris *)
(* Yann Régis-Gianas, PPS, Université Paris Diderot *)
(* *)
(* Copyright Inria. All rights reserved. This file is distributed under the *)
(* terms of the GNU Library General Public License version 2, with a *)
(* special exception on linking, as described in the file LICENSE. *)
(* *)
(******************************************************************************)
(* This file defines several types and module types that are used in the
specification of module [Engine]. *)
(* --------------------------------------------------------------------------- *)
(* It would be nice if we could keep the structure of stacks and environments
hidden. However, stacks and environments must be accessible to semantic
actions, so the following data structure definitions must be public. *)
(* --------------------------------------------------------------------------- *)
(* A stack is a linked list of cells. A sentinel cell -- which is its own
successor -- is used to mark the bottom of the stack. The sentinel cell
itself is not significant -- it contains dummy values. *)
type ('state, 'semantic_value) stack = {
(* The state that we should go back to if we pop this stack cell. *)
(* This convention means that the state contained in the top stack cell is
not the current state [env.current]. It also means that the state found
within the sentinel is a dummy -- it is never consulted. This convention
is the same as that adopted by the code-based back-end. *)
state: 'state;
(* The semantic value associated with the chunk of input that this cell
represents. *)
semv: 'semantic_value;
(* The start and end positions of the chunk of input that this cell
represents. *)
startp: Lexing.position;
endp: Lexing.position;
(* The next cell down in the stack. If this is a self-pointer, then this
cell is the sentinel, and the stack is conceptually empty. *)
next: ('state, 'semantic_value) stack;
}
(* --------------------------------------------------------------------------- *)
(* A parsing environment contains all of the parser's state (except for the
current program point). *)
type ('state, 'semantic_value, 'token) env = {
(* If this flag is true, then the first component of [env.triple] should
be ignored, as it has been logically overwritten with the [error]
pseudo-token. *)
error: bool;
(* The last token that was obtained from the lexer, together with its start
and end positions. Warning: before the first call to the lexer has taken
place, a dummy (and possibly invalid) token is stored here. *)
triple: 'token * Lexing.position * Lexing.position;
(* The stack. In [CodeBackend], it is passed around on its own,
whereas, here, it is accessed via the environment. *)
stack: ('state, 'semantic_value) stack;
(* The current state. In [CodeBackend], it is passed around on its
own, whereas, here, it is accessed via the environment. *)
current: 'state;
}
(* --------------------------------------------------------------------------- *)
(* This signature describes the parameters that must be supplied to the LR
engine. *)
module type TABLE = sig
(* The type of automaton states. *)
type state
(* States are numbered. *)
val number: state -> int
(* The type of tokens. These can be thought of as real tokens, that is,
tokens returned by the lexer. They carry a semantic value. This type
does not include the [error] pseudo-token. *)
type token
(* The type of terminal symbols. These can be thought of as integer codes.
They do not carry a semantic value. This type does include the [error]
pseudo-token. *)
type terminal
(* The type of nonterminal symbols. *)
type nonterminal
(* The type of semantic values. *)
type semantic_value
(* A token is conceptually a pair of a (non-[error]) terminal symbol and
a semantic value. The following two functions are the pair projections. *)
val token2terminal: token -> terminal
val token2value: token -> semantic_value
(* Even though the [error] pseudo-token is not a real token, it is a
terminal symbol. Furthermore, for regularity, it must have a semantic
value. *)
val error_terminal: terminal
val error_value: semantic_value
(* [foreach_terminal] allows iterating over all terminal symbols. *)
val foreach_terminal: (terminal -> 'a -> 'a) -> 'a -> 'a
(* The type of productions. *)
type production
val production_index: production -> int
val find_production: int -> production
(* If a state [s] has a default reduction on production [prod], then, upon
entering [s], the automaton should reduce [prod] without consulting the
lookahead token. The following function allows determining which states
have default reductions. *)
(* Instead of returning a value of a sum type -- either [DefRed prod], or
[NoDefRed] -- it accepts two continuations, and invokes just one of
them. This mechanism allows avoiding a memory allocation. *)
val default_reduction:
state ->
('env -> production -> 'answer) ->
('env -> 'answer) ->
'env -> 'answer
(* An LR automaton can normally take three kinds of actions: shift, reduce,
or fail. (Acceptance is a particular case of reduction: it consists in
reducing a start production.) *)
(* There are two variants of the shift action. [shift/discard s] instructs
the automaton to discard the current token, request a new one from the
lexer, and move to state [s]. [shift/nodiscard s] instructs it to move to
state [s] without requesting a new token. This instruction should be used
when [s] has a default reduction on [#]. See [CodeBackend.gettoken] for
details. *)
(* This is the automaton's action table. It maps a pair of a state and a
terminal symbol to an action. *)
(* Instead of returning a value of a sum type -- one of shift/discard,
shift/nodiscard, reduce, or fail -- this function accepts three
continuations, and invokes just one them. This mechanism allows avoiding
a memory allocation. *)
(* In summary, the parameters to [action] are as follows:
- the first two parameters, a state and a terminal symbol, are used to
look up the action table;
- the next parameter is the semantic value associated with the above
terminal symbol; it is not used, only passed along to the shift
continuation, as explained below;
- the shift continuation expects an environment; a flag that tells
whether to discard the current token; the terminal symbol that
is being shifted; its semantic value; and the target state of
the transition;
- the reduce continuation expects an environment and a production;
- the fail continuation expects an environment;
- the last parameter is the environment; it is not used, only passed
along to the selected continuation. *)
val action:
state ->
terminal ->
semantic_value ->
('env -> bool -> terminal -> semantic_value -> state -> 'answer) ->
('env -> production -> 'answer) ->
('env -> 'answer) ->
'env -> 'answer
(* This is the automaton's goto table. This table maps a pair of a state
and a nonterminal symbol to a new state. By extension, it also maps a
pair of a state and a production to a new state. *)
(* The function [goto_nt] can be applied to [s] and [nt] ONLY if the state
[s] has an outgoing transition labeled [nt]. Otherwise, its result is
undefined. Similarly, the call [goto_prod prod s] is permitted ONLY if
the state [s] has an outgoing transition labeled with the nonterminal
symbol [lhs prod]. The function [maybe_goto_nt] involves an additional
dynamic check and CAN be called even if there is no outgoing transition. *)
val goto_nt : state -> nonterminal -> state
val goto_prod: state -> production -> state
val maybe_goto_nt: state -> nonterminal -> state option
(* [is_start prod] tells whether the production [prod] is a start production. *)
val is_start: production -> bool
(* By convention, a semantic action is responsible for:
1. fetching whatever semantic values and positions it needs off the stack;
2. popping an appropriate number of cells off the stack, as dictated
by the length of the right-hand side of the production;
3. computing a new semantic value, as well as new start and end positions;
4. pushing a new stack cell, which contains the three values
computed in step 3;
5. returning the new stack computed in steps 2 and 4.
Point 1 is essentially forced upon us: if semantic values were fetched
off the stack by this interpreter, then the calling convention for
semantic actions would be variadic: not all semantic actions would have
the same number of arguments. The rest follows rather naturally. *)
(* Semantic actions are allowed to raise [Error]. *)
exception Error
type semantic_action =
(state, semantic_value, token) env -> (state, semantic_value) stack
val semantic_action: production -> semantic_action
(* [may_reduce state prod] tests whether the state [state] is capable of
reducing the production [prod]. This function is currently costly and
is not used by the core LR engine. It is used in the implementation
of certain functions, such as [force_reduction], which allow the engine
to be driven programmatically. *)
val may_reduce: state -> production -> bool
(* The LR engine requires a number of hooks, which are used for logging. *)
(* The comments below indicate the conventional messages that correspond
to these hooks in the code-based back-end; see [CodeBackend]. *)
(* If the flag [log] is false, then the logging functions are not called.
If it is [true], then they are called. *)
val log : bool
module Log : sig
(* State %d: *)
val state: state -> unit
(* Shifting (<terminal>) to state <state> *)
val shift: terminal -> state -> unit
(* Reducing a production should be logged either as a reduction
event (for regular productions) or as an acceptance event (for
start productions). *)
(* Reducing production <production> / Accepting *)
val reduce_or_accept: production -> unit
(* Lookahead token is now <terminal> (<pos>-<pos>) *)
val lookahead_token: terminal -> Lexing.position -> Lexing.position -> unit
(* Initiating error handling *)
val initiating_error_handling: unit -> unit
(* Resuming error handling *)
val resuming_error_handling: unit -> unit
(* Handling error in state <state> *)
val handling_error: state -> unit
end
end
(* --------------------------------------------------------------------------- *)
(* This signature describes the monolithic (traditional) LR engine. *)
(* In this interface, the parser controls the lexer. *)
module type MONOLITHIC_ENGINE = sig
type state
type token
type semantic_value
(* An entry point to the engine requires a start state, a lexer, and a lexing
buffer. It either succeeds and produces a semantic value, or fails and
raises [Error]. *)
exception Error
val entry:
state ->
(Lexing.lexbuf -> token) ->
Lexing.lexbuf ->
semantic_value
end
(* --------------------------------------------------------------------------- *)
(* The following signatures describe the incremental LR engine. *)
(* First, see [INCREMENTAL_ENGINE] in the file [IncrementalEngine.ml]. *)
(* The [start] function is set apart because we do not wish to publish
it as part of the generated [parser.mli] file. Instead, the table
back-end will publish specialized versions of it, with a suitable
type cast. *)
module type INCREMENTAL_ENGINE_START = sig
(* [start] is an entry point. It requires a start state and a start position
and begins the parsing process. If the lexer is based on an OCaml lexing
buffer, the start position should be [lexbuf.lex_curr_p]. [start] produces
a checkpoint, which usually will be an [InputNeeded] checkpoint. (It could
be [Accepted] if this starting state accepts only the empty word. It could
be [Rejected] if this starting state accepts no word at all.) It does not
raise any exception. *)
(* [start s pos] should really produce a checkpoint of type ['a checkpoint],
for a fixed ['a] that depends on the state [s]. We cannot express this, so
we use [semantic_value checkpoint], which is safe. The table back-end uses
[Obj.magic] to produce safe specialized versions of [start]. *)
type state
type semantic_value
type 'a checkpoint
val start:
state ->
Lexing.position ->
semantic_value checkpoint
end
(* --------------------------------------------------------------------------- *)
(* This signature describes the LR engine, which combines the monolithic
and incremental interfaces. *)
module type ENGINE = sig
include MONOLITHIC_ENGINE
include IncrementalEngine.INCREMENTAL_ENGINE
with type token := token