This repository has been archived by the owner on Mar 25, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
recce.ltx
3341 lines (3040 loc) · 101 KB
/
recce.ltx
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
% Copyright 2013 Jeffrey Kegler
% This document is licensed under
% a Creative Commons Attribution-NoDerivs 3.0 United States License.
\documentclass[12pt]{amsart}
\usepackage{algorithm}
\usepackage{algpseudocode}
\usepackage{url}
% This is now a "paper", but may be a chapter
% or something else someday
% This command will make any such change easier.
\newcommand{\doc}{paper}
\newcommand{\todo}[1]{\par{\large\bf Todo: #1}\par}
\newcommand{\mymathop}[1]{\mathop{\texttt{#1}}}
% For a type name, when it occurs in text
\newcommand{\type}[1]{\ensuremath{#1}}
\newcommand{\defined}{\underset{\text{def}}{\equiv}}
\newcommand{\dfn}[1]{{\bf #1}}
\newcommand{\sep}{\,\mid\,}
\newcommand{\mydot}{\raisebox{.05em}{$\,\bullet\,$}}
\newcommand{\cat}{\,.\,}
\newcommand{\size}[1]{\ensuremath{\left | {#1} \right |}}
\newcommand{\bigsize}[1]{\ensuremath{\bigl| {#1} \bigr|}}
\newcommand{\order}[1]{\ensuremath{{\mathcal O}(#1)}}
\newcommand{\Oc}{\order{1}}
\newcommand{\On}{\order{\var{n}}}
\newcommand{\inference}[2]{\genfrac{}{}{1pt}{}{#1}{#2}}
% I use hyphens in variable names,
% so I need to ensure that subtraction is
% clearly distinguished by the typography
\newcommand{\subtract}{\,-\,}
\newcommand{\var}[1]{\ensuremath{\texttt{#1}}}
\newcommand{\cfg}{CFG}
\newcommand{\de}{\rightarrow}
\newcommand{\derives}{\Rightarrow}
\newcommand{\destar}
{\mathrel{\mbox{$\:\stackrel{\!{\ast}}{\Rightarrow\!}\:$}}}
\newcommand{\deplus}
{\mathrel{\mbox{$\:\stackrel{\!{+}}{\Rightarrow\!}\:$}}}
\newcommand{\derivg}[1]{\mathrel{\mbox{$\:\Rightarrow\:$}}}
\newcommand{\derivrg}[2]{\mathrel{\mbox{$\:\stackrel{\!{#1}}%
{\Rightarrow\!}\:$}}}
\newcommand{\set}[1]{{\left\lbrace #1 \right\rbrace} }
\newcommand{\bigset}[1]{{\bigl\lbrace #1 \bigr\rbrace} }
\newcommand{\Bigset}[1]{{\Bigl\lbrace #1 \Bigr\rbrace} }
\newcommand{\ah}[1]{#1_{AH}}
\newcommand{\Vah}[1]{\ensuremath{\var{#1}_{AH}}}
\newcommand{\bool}[1]{\var{#1}_{BOOL}}
\newcommand{\Vbool}[1]{\ensuremath{\bool{#1}}}
\newcommand{\dr}[1]{#1_{DR}}
\newcommand{\Vdr}[1]{\ensuremath{\var{#1}_{DR}}}
\newcommand{\Vdrset}[1]{\ensuremath{\var{#1}_{\set{DR}}}}
\newcommand{\eim}[1]{#1_{EIM}}
\newcommand{\Veim}[1]{\ensuremath{\var{#1}_{EIM}}}
\newcommand{\Veimt}[1]{\ensuremath{\var{#1}_{EIMT}}}
\newcommand{\Veimset}[1]{\ensuremath{\var{#1}_{\set{EIM}}}}
\newcommand{\Veimtset}[1]{\ensuremath{\var{#1}_{\set{EIMT}}}}
\newcommand{\Ees}[1]{\ensuremath{#1_{ES}}}
\newcommand{\Vlim}[1]{\ensuremath{\var{#1}_{LIM}}}
\newcommand{\Vlimt}[1]{\ensuremath{\var{#1}_{LIMT}}}
\newcommand{\Eloc}[1]{\ensuremath{{#1}_{LOC}}}
\newcommand{\Vloc}[1]{\Eloc{\var{#1}}}
\newcommand{\Ves}[1]{\Ees{\var{#1}}}
\newcommand{\Vrule}[1]{\ensuremath{\var{#1}_{RULE}}}
\newcommand{\Vruleset}[1]{\ensuremath{\var{#1}_{\set{RULE}}}}
\newcommand{\Vsize}[1]{\ensuremath{\size{\var{#1}}}}
\newcommand{\Vstr}[1]{\ensuremath{\var{#1}_{STR}}}
\newcommand{\sym}[1]{#1_{SYM}}
\newcommand{\Vsym}[1]{\ensuremath{\var{#1}_{SYM}}}
\newcommand{\Vorig}[1]{\ensuremath{\var{#1}_{ORIG}}}
\newcommand{\symset}[1]{#1_{\lbrace SYM \rbrace} }
\newcommand{\Vsymset}[1]{\ensuremath{\var{#1}_{\set{SYM}}}}
\newcommand{\term}[1]{#1_{TERM}}
\newcommand{\token}[1]{#1_{TOK}}
\newcommand{\alg}[1]{\ensuremath{\textsc{#1}}}
\newcommand{\AH}{\ensuremath{\alg{AH}}}
\newcommand{\Earley}{\ensuremath{\alg{Earley}}}
\newcommand{\Leo}{\ensuremath{\alg{Leo}}}
\newcommand{\Marpa}{\ensuremath{\alg{Marpa}}}
\newcommand{\Cfa}{\var{fa}}
\newcommand{\Cg}{\var{g}}
\newcommand{\Cw}{\var{w}}
\newcommand{\CVw}[1]{\ensuremath{\sym{\Cw[\var{#1}]}}}
\newcommand{\Crules}{\var{rules}}
\newcommand{\GOTO}{\mymathop{GOTO}}
\newcommand{\Next}[1]{\mymathop{Next}(#1)}
\newcommand{\Predict}[1]{\mymathop{Predict}(#1)}
\newcommand{\Postdot}[1]{\mymathop{Postdot}(#1)}
\newcommand{\Penult}[1]{\mymathop{Penult}(#1)}
\newcommand{\LHS}[1]{\mymathop{LHS}(#1)}
\newcommand{\RHS}[1]{\mymathop{RHS}(#1)}
\newcommand{\RightRecursive}[1]{\mymathop{Right-Recursive}(#1)}
\newcommand{\RightNN}[1]{\mymathop{Right-NN}(#1)}
\newcommand{\LeoEligible}[1]{\mymathop{Leo-Eligible}(#1)}
\newcommand{\LeoUnique}[1]{\mymathop{Leo-Unique}(#1)}
\newcommand{\ID}[1]{\mymathop{ID}(#1)}
\newcommand{\PSL}[2]{\mymathop{PSL}[#1][#2]}
\newcommand{\myL}[1]{\mymathop{L}(#1)}
\newcommand\Etable[1]{\ensuremath{\mymathop{table}[#1]}}
\newcommand\bigEtable[1]{\ensuremath{\mymathop{table}\bigl[#1\bigr]}}
\newcommand\Rtable[1]{\ensuremath{\mymathop{table}[#1]}}
\newcommand\Rtablesize[1]{\ensuremath{\bigl| \mymathop{table}[#1] \bigr|}}
\newcommand\Vtable[1]{\Etable{\var{#1}}}
\newcommand\EEtable[2]{\ensuremath{\mymathop{table}[#1,#2]}}
\newcommand\EVtable[2]{\EEtable{#1}{\var{#2}}}
% I want to use 'call' outside of pseudocode
\newcommand\call[2]{\textproc{#1}\ifthenelse{\equal{#2}{}}{}{(#2)}}%
\newtheorem{theorem}{Theorem}[section]
\newtheorem{lemma}[theorem]{Lemma}
\theoremstyle{definition}
\newtheorem*{definition}{Definition}
\theoremstyle{remark}
\newtheorem*{remark}{Remark}
\newtheorem{observation}[theorem]{Observation}
\hyphenation{oper-and oper-ands}
\hyphenation{look-ahead}
\hyphenation{memo-ization}
\begin{document}
\date{\today}
\title{Marpa, a practical general parser: the recognizer}
\author{Jeffrey Kegler}
\thanks{%
Copyright \copyright\ 2013 Jeffrey Kegler.
}
\thanks{%
This document is licensed under
a Creative Commons Attribution-NoDerivs 3.0 United States License.
}
\begin{abstract}
The Marpa recognizer is described.
Marpa is
a practical and fully implemented
algorithm for the recognition,
parsing and evaluation of context-free grammars.
The Marpa recognizer is the first
to unite the improvements
to Earley's algorithm found in
Joop Leo's 1991 paper
to those in Aycock and Horspool's 2002 paper.
Marpa tracks the full state of the parse,
at it proceeds,
in a form convenient for the application.
This greatly improves error detection
and enables event-driven parsing.
One such technique is
``Ruby Slippers'' parsing,
in which
the input is altered in response
to the parser's expectations.
\end{abstract}
\maketitle
\section{Introduction}
Despite the promise of general context-free parsing,
and the strong academic literature behind it,
it has never been incorporated into a highly available tool
like those that exist for LALR\cite{Johnson} or
regular expressions.
The Marpa project was intended
to take the best results from the literature
on Earley parsing off the pages
of the journals and bring them
to a wider audience.
Marpa::XS\cite{Marpa-XS},
a stable version of this tool,
was uploaded to the CPAN Perl archive
on Solstice Day in 2011.
This paper describes the algorithm of Marpa::R2\cite{Marpa-R2},
a later version.
As implemented,
Marpa parses,
without exception,
all context-free grammars.
Time bounds are the best of Leo\cite{Leo1991}
and Earley\cite{Earley1970}.
The Leo bound,
\On{} for LR-regular grammars,
is especially relevant to
Marpa's goal of being a practical parser:
If a grammar is in a class of grammar currently in practical use,
Marpa parses it in linear time.
Error-detection properties,
extremely important,
have been overlooked in the past.
Marpa breaks new ground in this respect.
Marpa has the immediate error detection property,
but goes well beyond that:
it is fully aware of the state of the parse,
and can report this to the user while tokens are
being scanned.
Marpa allows the lexer to check its list
of acceptable tokens before a token is scanned.
Because rejection of tokens is easily and
efficiently recoverable,
the lexer is also free to take an event-driven
approach.
Error detection is no longer
an act of desperation,
but a parsing technique in its own right.
If a token is rejected,
the lexer is free to create a new token
in the light of the parser's expectations.
This approach can be described
as making the parser's
``wishes'' come true,
and we have called this
``Ruby Slippers Parsing''.
One use of the Ruby Slippers technique is to
parse with a clean
but oversimplified grammar,
programming the lexical analyzer to make up for the grammar's
short-comings on the fly.
The author has implemented an HTML parser\cite{Marpa-HTML},
based on a grammar that assumes that all start
and end tags are present.
Such an HTML grammar is too simple even to describe perfectly
standard-conformant HTML,
but the lexical analyzer is
programmed to supply start and end tags as requested by the parser.
The result is a very simply and cleanly designed parser
that parses very liberal HTML
and accepts all input files,
in the worst case
treating them as highly defective HTML.
Section
\ref{s:preliminaries} describes the notation and conventions
of this \doc.
Section \ref{s:rewrite} deals with Marpa's
grammar rewrites.
Sections \ref{s:earley} and \ref{s:earley-ops}
introduce Earley's algorithm.
Section \ref{s:leo} describes Leo's modification
to Earley's algorithm.
Section \ref{s:AHFA} describes the modifications
proposed by Aycock and Horspool.
Section \ref{s:pseudocode} presents the pseudocode
for Marpa's recognizer.
Section
\ref{s:proof-preliminaries}
describes notation and deals with other
preliminaries
to the theoretical results.
Section
\ref{s:correct}
contain a proof of Marpa's correctness,
while Section \ref{s:complexity} contains
its complexity results.
Finally,
section \ref{s:input}
generalizes Marpa's input model.
\section{Preliminaries}
\label{s:preliminaries}
\label{s:start-prelim}
We assume familiarity with the theory of parsing,
as well as Earley's algorithm.
This \doc{} will
use subscripts to indicate commonly occurring types.
\begin{center}
\begin{tabular}{ll}
$\var{X}_T$ & The variable \var{X} of type $T$ \\
$\var{set-one}_\set{T}$ & The variable \var{set-one} of type set of $T$ \\
$SYM$ & The type for a symbol \\
\Vsym{a} & The variable \var{a} of type $SYM$ \\
\Vsymset{set-two} & The variable \var{set-two}, a set of symbols \\
\end{tabular}
\end{center}
Subscripts may be omitted when the type
is obvious from the context.
The notation for
constants is the same as that for variables.
Multi-character variable names will be common,
and operations will never be implicit.
\begin{center}
\begin{tabular}{ll}
Multiplication & $\var{a} \times \var{b}$ \\
Concatenation & $\var{a} \cat \var{b}$ \\
Subtraction & $\var{symbol-count} \subtract \var{terminal-count}$ \\
\end{tabular}
\end{center}
Type names are often used in the text
as a convenient way to refer to
their type.
Where \Vsymset{vocab} is non-empty set of symbols,
let $\var{vocab}^\ast$ be the set of all strings
(type \type{STR}) formed
from those symbols.
Where \Vstr{s} is a string,
let \size{\Vstr{s}} be its length, counted in symbols.
Let $\var{vocab}^+$ be
\begin{equation*}
\bigl\{ \Vstr{x}
\bigm| \Vstr{x} \in \var{vocab}* \land \Vsize{\Vstr{x}} > 0
\bigr\}.
\end{equation*}
In this \doc{} we use,
without loss of generality,
the grammar \Cg{},
where \Cg{} is the 3-tuple
\begin{equation*}
(\Vsymset{vocab}, \var{rules}, \Vsym{accept}).
\end{equation*}
Here $\Vsym{accept} \in \var{vocab}$.
Call the language of \var{g}, $\myL{\Cg}$,
where $\myL{\Cg} \subseteq \var{vocab}^\ast$.
\Vruleset{rules} is a set of rules (type \type{RULE}),
where a rule is a duple
of the form $[\Vsym{lhs} \de \Vstr{rhs}]$,
such that
\begin{equation*}
\Vsym{lhs} \in \var{vocab} \quad \text{and}
\quad \Vstr{rhs} \in \var{vocab}^+.
\end{equation*}
\Vsym{lhs} is referred to as the left hand side (LHS)
of \Vrule{r}.
\Vstr{rhs} is referred to as the right hand side (RHS)
of \Vrule{r}.
The LHS and RHS of \Vrule{r} may also be
referred to as
$\LHS{\Vrule{r}}$ and $\RHS{\Vrule{r}}$, respectively.
This definition follows \cite{AH2002},
which departs from tradition by disallowing an empty RHS.
The rules imply the traditional rewriting system,
in which $\Vstr{x} \derives \Vstr{y}$
states that \Vstr{x} derives \Vstr{y} in exactly one step;
$\Vstr{x} \deplus \Vstr{y}$
states that \Vstr{x} derives \Vstr{y} in one or more steps;
and $\Vstr{x} \destar \Vstr{y}$
states that \Vstr{x} derives \Vstr{y} in zero or more steps.
We say that symbol \Vsym{x} is \dfn{nullable} if and only if
$\Vsym{x} \destar \epsilon$.
\Vsym{x} is \dfn{nonnull} if and only if it is not nullable.
Following Aycock and Horspool\cite{AH2002},
all nullable symbols in grammar \Cg{} are nulling -- every symbol
which can derive the null string always derives the null string.
It is shown in \cite{AH2002} how to do this without losing generality
or the ability to efficiently evaluate a semantics that is
defined in terms of an original grammar that includes symbols which
are both nullable and non-nulling,
empty rules, etc.
Also without loss of generality,
it is assumed
that there is a dedicated acceptance rule, \Vrule{accept}
and a dedicated acceptance symbol, $\Vsym{accept} = \LHS{\Vrule{accept}}$,
such that
for all \Vrule{x},
\begin{equation*}
\begin{split}
& \Vsym{accept} \notin \RHS{\Vrule{x}} \\
\land \quad & (\Vsym{accept} = \LHS{\Vrule{x}} \implies \Vrule{accept} = \Vrule{x}).
\end{split}
\end{equation*}
We define rightmost non-null symbol of a string
as
\begin{equation*}
\begin{split}
& \RightNN{\Vstr{x}} \defined \Vsym{rnn} \quad \text{such that} \quad
\exists \, \Vstr{pre}, \Vstr{post} \mid \\
& \qquad \qquad \Vstr{x} = \Vstr{pre} \cat \Vsym{rnn} \cat \Vstr{post} \\
& \qquad \qquad \land \Vstr{post} \destar \epsilon \\
& \qquad \qquad \land \neg (\Vsym{rnn} \destar \epsilon).
\end{split}
\end{equation*}
We define the rightmost non-null symbol of a rule as
\begin{equation*}
\RightNN{[\Vsym{lhs} \de \Vstr{rhs}]} \defined \RightNN{\Vstr{rhs}}.
\end{equation*}
A rule \Vrule{x} is \dfn{directly right-recursive}
if and only if
\begin{equation*}
\LHS{\Vrule{x}} = \RightNN{\Vrule{x}}.
\end{equation*}
\Vrule{x} is \dfn{indirectly right-recursive}
if and only if
\begin{equation*}
\exists \, \Vstr{y} \mid \RightNN{\Vrule{x}} \deplus \Vstr{y} \land \RightNN{\Vstr{y}} = \LHS{\Vrule{x}}.
\end{equation*}
\Vrule{x} is \dfn{right recursive},
$\RightRecursive{\Vrule{x}}$,
if and only if is either directly or indirectly right-recursive.
The definition of \Cg{} does not sharply distinguish terminals
from non-terminals.
\Marpa{}'s implementations allow terminals to be the LHS
of rules,
and every symbol except \Vsym{accept} can be a terminal.
The implementations have options that allow
the user to reinstate
the traditional restrictions,
in part or in whole.
Note that,
as a result of these definitions,
sentential forms will be of type \type{STR}.
Let the input to
the parse be \Cw{} such that $\Cw \in \var{vocab}^+$.
Locations in the input will be of type \type{LOC}.
Let \Vsize{w} be the length of the input, counted in symbols.
When we state our complexity results later,
they will often be in terms of $\var{n}$,
where $\var{n} = \Vsize{w}$.
Let \CVw{i} be character \var{i}
of the input,
$0 \le \Vloc{i} < \Vsize{w}$.
The alert reader may have noticed that the previous definition
of \Cw{} did not allow zero-length inputs.
To simplify the mathematics, we exclude null parses
and trivial grammars from consideration.
In its implementations,
the Marpa parser
deals with null parses and trivial grammars as special cases.
(Trivial grammars are those that recognize only the null string.)
In this \doc{},
\Earley{} will refer to the Earley's original
recognizer\cite{Earley1970}.
\Leo{} will refer to Leo's revision of \Earley{}
as described in~\cite{Leo1991}.
\AH{} will refer to the Aycock and Horspool's revision
of \Earley{}
as described in~\cite{AH2002}.
\Marpa{} will refer to the parser described in
this \doc{}.
Where $\alg{Recce}$ is a recognizer,
$\myL{\alg{Recce},\Cg}$ will be the language accepted by $\alg{Recce}$
when parsing \Cg{}.
\section{Rewriting the grammar}
\label{s:rewrite}
We have already noted
that no rules of \Cg{}
have a zero-length RHS,
and that all symbols must be either nulling or non-nullable.
These restrictions follow Aycock and Horspool\cite{AH2002}.
The elimination of empty rules and proper nullables
is done by rewriting the grammar.
\cite{AH2002} shows how to do this
without loss of generality.
Because Marpa claims to be a practical parser,
it is important to emphasize
that all grammar rewrites in this \doc{}
are done in such a way that the semantics
of the original grammar can be reconstructed
simply and efficiently at evaluation time.
As one example,
when a rewrite involves the introduction of new rule,
semantics for the new rule can be defined to pass its operands
up to a parent rule as a list.
Where needed, the original semantics
of a pre-existing parent rule can
be ``wrapped'' to reassemble these lists
into operands that are properly formed
for that original semantics.
As implemented,
the Marpa parser allows users to associate
semantics with an original grammar
that has none of the restrictions imposed
on grammars in this \doc{}.
The user of a Marpa parser
may specify any context-free grammar,
including one with properly nullable symbols,
empty rules, etc.
The user specifies his semantics in terms
of this original, ``free-form'', grammar.
Marpa implements the rewrites,
and performs evaluation,
in such a way as to keep them invisible to
the user.
From the user's point of view,
the ``free-form'' of his grammar is the
one being used for the parse,
and the one to which
his semantics are applied.
\section{Earley's algorithm}
\label{s:earley}
Let $\Vrule{r} \in \Crules$
be a rule,
and $\Vsize{r}$ the length of its RHS.
A dotted rule (type \type{DR}) is a duple, $[\Vrule{r}, \var{pos}]$,
where $0 \le \var{pos} \le \size{\Vrule{r}}$.
The position, \var{pos}, indicates the extent to which
the rule has been recognized,
and is represented with a large raised dot,
so that if
\begin{equation*}
[\Vsym{A} \de \Vsym{X} \cat \Vsym{Y} \cat \Vsym{Z}]
\end{equation*}
is a rule,
\begin{equation*}
[\Vsym{A} \de \var{X} \cat \var{Y} \mydot \var{Z}]
\end{equation*}
is the dotted rule with the dot at
$\var{pos} = 2$,
between \Vsym{Y} and \Vsym{Z}.
If we let \Vdr{x} be a dotted rule, such that
\begin{equation*}
\Vdr{x} =
\bigl[ [\Vsym{A} \de \Vstr{pre} \cat \Vsym{next} \cat \Vstr{post}],
\var{pos} \bigr],
\end{equation*}
then
%
\begin{gather*}
%
\LHS{\Vdr{x}} \defined \Vsym{A} \\
%
\Postdot{\Vdr{x}} \defined
\begin{cases}
\Vsym{next}, \quad \text{if $\var{x} = [\var{A} \de \var{pre} \mydot \var{next} \cat \var{post}]$} \\
\Lambda, \quad \text{if $\var{x} = [\var{A} \de \var{pre} \cat \var{next} \cat \var{post} \mydot]$}
\end{cases} \\
%
\Next{\Vdr{x}} \defined
\begin{cases}
[\var{A} \de \var{pre} \cat \var{next} \mydot \var{post}], \\
\qquad \text{if $\Postdot{\Vdr{x}} = \var{next}$} \\
\text{$\Lambda$, otherwise}
\end{cases} \\
%
\Penult{\Vdr{x}} \defined
\begin{cases}
\Vsym{next}, \quad \text{if} \\
\qquad \Postdot{\Vdr{x}} = \var{next} \\
\qquad \land \quad \Vstr{post} \destar \epsilon \\
\qquad \land \quad \neg (\Vsym{next} \destar \epsilon) \\
\Lambda, \quad \text{otherwise}
\end{cases}
%
\end{gather*}
A \dfn{penult} is a dotted rule \Vdr{d} such that $\Penult{\var{d}} \neq \Lambda$.
Note that $\Penult{\Vdr{x}}$
is never a nullable symbol.
The \dfn{initial dotted rule} is
\begin{equation*}
\Vdr{initial} = [\Vsym{accept} \de \mydot \Vsym{start} ].
\end{equation*}
A \dfn{predicted dotted rule} is a dotted rule,
other than the initial dotted rule,
with a dot position of zero,
for example,
\begin{equation*}
\Vdr{predicted} = [\Vsym{A} \de \mydot \Vstr{alpha} ].
\end{equation*}
A \dfn{confirmed dotted rule}
is the initial dotted rule,
or a dotted rule
with a dot position greater than zero.
A \dfn{completed dotted rule} is a dotted rule with its dot
position after the end of its RHS,
for example,
\begin{equation*}
\Vdr{completed} = [\Vsym{A} \de \Vstr{alpha} \mydot ].
\end{equation*}
Predicted, confirmed and completed dotted rules
are also called, respectively,
\dfn{predictions}, \dfn{confirmations} and \dfn{completions}.
A traditional Earley item (type \type{EIMT}) is a duple
\[
[\Vdr{dotted-rule}, \Vorig{x}]
\]
of dotted rule and origin.
(The origin is the location where recognition of the rule
started.
It is sometimes called the ``parent''.)
For convenience, the type \type{ORIG} will be a synonym
for \type{LOC}, indicating that the variable designates
the origin element of an Earley item.
An Earley parser builds a table of Earley sets,
\begin{equation*}
\EVtable{\Earley}{i},
\quad \text{where} \quad
0 \le \Vloc{i} \le \size{\Cw}.
\end{equation*}
Earley sets are of type \type{ES}.
Earley sets are often named by their location,
so that \Ves{i} means the Earley set at \Vloc{i}.
The type designator \type{ES} is often omitted to avoid clutter,
especially in cases where the Earley set is not
named by location.
At points,
we will need to compare the Earley sets
produced by the different recognizers.
\EVtable{\alg{Recce}}{i} will be
the Earley set at \Vloc{i}
in the table of Earley sets of
the \alg{Recce} recognizer.
For example,
\EVtable{\Marpa}{j} will be Earley set \Vloc{j}
in \Marpa's table of Earley sets.
In contexts where it is clear which recognizer is
intended,
\Vtable{k}, or \Ves{k}, will symbolize Earley set \Vloc{k}
in that recognizer's table of Earley sets.
If \Ees{\var{working}} is an Earley set,
$\size{\Ees{\var{working}}}$ is the number of Earley items
in \Ees{\var{working}}.
\Rtablesize{\alg{Recce}} is the total number
of Earley items in all Earley sets for \alg{Recce},
\begin{equation*}
\Rtablesize{\alg{Recce}} =
\sum\limits_{\Vloc{i}=0}^{\size{\Cw}}
{\bigsize{\EVtable{\alg{Recce}}{i}}}.
\end{equation*}
For example,
\Rtablesize{\Marpa} is the total number
of Earley items in all the Earley sets of
a \Marpa{} parse.
Recall that
there was a unique acceptance symbol,
\Vsym{accept}, in \Cg{}.
The input \Cw{} is accepted if and only if,
for some \Vstr{rhs},
\begin{equation*}
\bigl[[\Vsym{accept} \de \Vstr{rhs} \mydot], 0\bigr] \in \bigEtable{\Vsize{\Cw}}
\end{equation*}
\section{Operations of the Earley algorithm}
\label{s:earley-ops}
In this section,
each Earley operation is shown in the form of
an inference rule,
the conclusion of which
is the set of the Earley items
that is that operation's \dfn{result}.
The Earley sets correspond to parse locations,
and for any Earley operation there is a
current parse location, \Vloc{current}, and
a current Earley set, \Ves{current}.
Each location starts with an empty Earley set.
For the purposes of this description of
\Earley{}, the order of the
Earley operations
when building an
Earley set is non-deterministic.
After each Earley operation is performed,
its result is unioned with the
current Earley set.
When no more Earley items
can be added, the Earley set is
complete.
The Earley sets are built in
order from 0 to \Vsize{w}.
\subsection{Initialization}
\label{d:initial}
\begin{equation*}
\inference{
\Vloc{current} = 0
}{
\Bigset{\bigl[ [ \Vsym{accept} \de \mydot \Vsym{start} ], 0 \bigr]}
}
\end{equation*}
Earley {\bf initialization} has no operands
and only takes
place in Earley set 0.
\subsection{Scanning}
\label{d:scan}
\begin{equation*}
\inference{
\begin{array}{c}
\Vloc{current} > 0 \\
\Vloc{previous} = \Vloc{current} \subtract 1
\\[3pt]
\Vsym{token} = \Cw\bigl[\Vloc{previous}\bigr]
\\[3pt]
\Veimt{predecessor} = [ \Vdr{before}, \Vorig{predecessor} ] \\
\Veimt{predecessor} \in \Ves{previous} \\
\Postdot{\Vdr{before}} = \Vsym{token}
\end{array}
}{
\bigset{ [ \Next{\Vdr{before}}, \Vorig{predecessor} ] }
}
\end{equation*}
\Veimt{predecessor}
and \Vsym{token} are the operands of an Earley scan.
\Veimt{predecessor} is called the predecessor of the scanning operation.
The token, \Vsym{token}, is the transition symbol
of the scanning operation.
\subsection{Reduction}
\label{d:reduction}
\begin{equation*}
\inference{
\begin{array}{c}
\Veimt{component} = \bigl[
[ \Vsym{lhs} \de \Vstr{rhs} \mydot ]
, \Vloc{component-orig} \bigr] \\
\Veimt{component} \in \Ves{current} \\[3pt]
\Veimt{predecessor} = [ \Vdr{before}, \Vorig{predecessor} ] \\
\Veimt{predecessor} \in \Ves{component-orig} \\
\Postdot{\Vdr{before}} = \Vsym{lhs} \\
\end{array}
}{
\bigset{ [ \Next{\Vdr{before}}, \Vorig{predecessor} ] }
}
\end{equation*}
\Veimt{component} is called
the component of the reduction operation.\footnote{
The term ``component'' comes from Irons \cite{Irons}.
}
\Veimt{predecessor} is the predecessor
of the reduction operation.
\Vsym{lhs} is the transition symbol
of the reduction operation.
\Veimt{predecessor} and
\Veimt{component} are the operands of the reduction
operation.
In some contexts, it is convenient to treat the transition
symbol
as an operand,
so that the operands
are \Veimt{predecessor} and \Vsym{lhs}.
\subsection{Prediction}
\label{d:prediction}
\begin{equation*}
\inference{
\begin{array}{c}
\Veimt{predecessor} = [ \Vdr{predecessor}, \Vorig{predecessor} ] \\
\Veimt{predecessor} \in \Ves{current}
\end{array}
}{
\left\{
\begin{aligned}
& \Bigl[ \bigl[ \Vsym{L} \de \mydot \Vstr{rh} \bigr],
\Vloc{current}
\Bigr]
\quad \text{such that} \\
& \qquad \bigl[ \Vsym{L} \de \Vstr{rh} \bigr] \in \Crules \\
& \qquad \land \bigl( \exists \, \Vstr{z} \mid
\Postdot{\Vdr{predecessor}} \destar \Vsym{L} \cat \Vstr{z} \bigr)
\end{aligned}
\right\}
}
\end{equation*}
A prediction operation can add several Earley items
to Earley set \Vloc{current}.
\Veimt{predecessor} is called the predecessor of the prediction operation,
and is its only operand.
\subsection{Causation}
An operand of an operation is also called a \dfn{cause}
of that operation,
and the set of operands for an Earley operation
is its \dfn{causation}.
\section{The Leo algorithm}
\label{s:leo}
In \cite{Leo1991}, Joop Leo presented a method for
dealing with right recursion in \On{} time.
Leo shows that,
with his modification, Earley's algorithm
is \On{} for all LR-regular grammars.
(LR-regular is LR where lookahead
is infinite length, but restricted to
distinguishing between regular expressions.)
Summarizing Leo's method,
it consists of spotting potential right recursions
and memoizing them.
Leo restricts the memoization to situations where
the right recursion is unambiguous.
Potential right recursions are memoized by
Earley set, using what Leo called
``transitive items''.
In this \doc{} Leo's ``transitive items''
will be called Leo items.
Leo items in the form that Marpa uses
will be type \type{LIM}.
``Traditional'' Leo items,
that is, those of the form used in Leo's paper\cite{Leo1991},
will be type \type{LIMT}.
In each Earley set, there is at most one Leo item per symbol.
A traditional Leo item (LIMT) is the triple
\begin{equation*}
[ \Vdr{top}, \Vsym{transition}, \Vorig{top} ]
\end{equation*}
where \Vsym{transition} is the transition symbol,
and
\begin{equation*}
\Veimt{top} = [\Vdr{top}, \Vorig{top}]
\end{equation*}
is the Earley item to be added on reductions over
\Vsym{transition}.
Leo items memoize what would otherwise be sequences
of Earley items.
Leo items only memoize unambiguous (or
deterministic) sequences,
so that the top of the sequence can represent
the entire sequence --
the only role the other EIMT's in the sequence
play in the parse is to derive the top EIMT.
We will call these memoized sequences, Leo sequences.
To quarantee that a Leo sequence is deterministic,
\Leo{} enforced \dfn{Leo uniqueness}.
Define containment of a dotted rule in a Earley set
of EIMT's as
\begin{equation*}
\begin{split}
& \mymathop{Contains}(\Ves{i}, \Vdr{d}) \defined \exists \, \Veimt{b}, \Vorig{j} \mid \\
& \qquad \Veimt{b} = [ \Vdr{d}, \Vorig{j} ]
\land \Veimt{b} \in \Ves{i}.
\end{split}
\end{equation*}
A dotted rule \Vdr{d} is \dfn{Leo unique} in the Earley set
at \Ves{i}
if and only if
\begin{equation*}
\begin{split}
& \Penult{\Vdr{d}} \neq \Lambda \\
& \land \forall \, \Vdr{d2} \bigl( \mymathop{Contains}(\Ves{i}, \Vdr{d2}) \implies \\
& \qquad \Postdot{\Vdr{d}} = \Postdot{\Vdr{d2}} \implies \Vdr{d} = \Vdr{d2} \bigr).
\end{split}
\end{equation*}
If \Vdr{d} is Leo unique, then the symbol $\Postdot{\Vdr{d}}$ is
also said to be \dfn{Leo unique}.
In cases where a symbol \Vsym{transition} is Leo unique in \Ves{i},
we can speak of the dotted rule for \Vsym{transition},
and the rule for \Vsym{transition},
because there can be only one of each.
In the previous definitions,
it is important to emphasize that \Vdr{d2} ranges over all the dotted
rules of Earley set \Ves{i},
even those which are ineligible for Leo memoization.
Let \var{n} be the length of a Leo sequence.
In \Earley, each such sequence would be expanded in every
Earley set that is the origin of an EIMT included in the
sequence, and the total number of EIMT's would be
\order{\var{n}^2}.
With Leo memoization, a single EIMT stands in for the sequence.
There are \Oc{} Leo items per Earley set,
so the cost of the sequence is \Oc{} per Earley set,
or \On{} for the entire sequence.
If, at evaluation time,
it is desirable to expand the Leo sequence,
only those items actually involved in the parse
need to be expanded.
All the EIMT's of a potential right-recursion
will be in one Earley set and the number of EIMT's
will be \On{},
so that even including expansion of the Leo sequence
for evaluation, the time and space complexity of
the sequence remains \On{}.
\begin{sloppypar}
Recall that we
call a dotted rule \Vdr{d} a \dfn{penult} if $\Penult{\var{d}} \neq \Lambda$.
In Leo's original algorithm, any penult
was treated as a potential right-recursion.
\Marpa{} applies the Leo memoizations in more restricted circumstances.
For \Marpa{} to consider a dotted rule
\begin{equation*}
\Vdr{candidate} = [\Vrule{candidate}, \var{i}]
\end{equation*}
for Leo memoization,
\Vdr{candidate} must be a penult and
\Vrule{candidate} must be right-recursive.
\end{sloppypar}
By restricting Leo memoization to right-recursive rules,
\Marpa{} incurs the cost of Leo memoization only in cases
where Leo sequences could be infinitely
long.
This more careful targeting of the memoization is for efficiency reasons.
If all penults are memoized,
many memoizations will be performed where
the longest potential Leo sequence is short,
and the payoff is therefore very limited.
One future extension might be to identify
non-right-recursive rules
which generate Leo sequences long enough to
justify inclusion in the Leo memoizations.
Such cases are unusual, but may occur.
Omission of a memoization does not affect correctness,
so \Marpa{}'s restriction of Leo memoization
preserves the correctness as shown in Leo\cite{Leo1991}.
Later in this \doc{} we will
show that this change also leaves
the complexity results of
Leo\cite{Leo1991} intact.
Implementing the Leo logic requires
adding Leo reduction as a new basic operation,
adding a new premise to the Earley reduction
operation,
and extending the Earley sets to memoize Earley
items as LIMT's.
\subsection{Leo reduction}
\begin{equation*}
\inference{
\begin{array}{c}
\Veimt{component} = \bigl[
[ \Vsym{lhs} \de \Vstr{rhs} \mydot ]
, \Vloc{component-origin} \bigr] \\
\Veimt{component} \in \Ves{current} \\[3pt]
\Vlimt{predecessor} = [ \Vdr{top}, \Vsym{lhs}, \Vorig{top} ] \\
\Vlimt{predecessor} \in \Ves{component-orig} \\
\end{array}
}{
\bigset{ [ \Vdr{top}, \Vorig{top} ] }
}
\end{equation*}
The new Leo reduction operation resembles the Earley reduction
operation, except that it looks for an LIMT,
instead of a predecessor EIMT.
\Vlimt{predecessor} and
\Veimt{component} are the operands of the Leo reduction
operation.
\Vsym{lhs} is the transition symbol
of the Leo reduction.
As with Earley reduction,
it may be convenient to treat the transition
symbol as an operand,
so that the operands
are \Vlimt{predecessor} and \Vsym{lhs}.
\subsection{Changes to Earley reduction}
Earley reduction still applies, with an additional premise:
\begin{multline*}
\neg \exists \, \Vlimt{x} \; \mid \; \Vlimt{x} \in \Ves{component-orig} \\
\land \Vlimt{x} = [ \Vdr{x}, \Vsym{lhs}, \Vorig{x} ]
\end{multline*}
The additional premise
prevents Earley reduction from being applied
where there is an LIMT with \Vsym{lhs} as its transition symbol.
This reflects the fact that
Leo reduction replaces Earley reduction if and only if
there is a Leo memoization.
\subsection{Leo memoization}
We define uniqueness of a penult in an Earley set as
\begin{equation*}
\begin{split}
& \mymathop{Penult-Unique}(\Vsym{penult},\Ves{i}) \defined \\
& \qquad \forall \, \Vdr{y} \bigl( \mymathop{Contains}(\Ves{current}, \Vdr{y})