File: kwParsing.html

package info (click to toggle)
gadfly 1.0-2
  • links: PTS
  • area: main
  • in suites: slink
  • size: 796 kB
  • ctags: 1,697
  • sloc: python: 10,962; makefile: 35; sh: 19
file content (1086 lines) | stat: -rw-r--r-- 43,871 bytes parent folder | download | duplicates (3)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
<html>
<head>
<title>A parser generator in Python</title>
</head>
<body bgcolor="#ffffff">
<center>
<h1>A parser generator in Python: kwParsing</h1>


<blockquote>
Aaron Watters<br>
</blockquote>

<blockquote>
This is the documentation for the <strong>kjParsing</strong> package,
an experimental parser generator implemented in Python which generates
parsers implemented in Python.
It won't serve as a complete reference on programming
language syntax and interpretation, but it will review
terminology for the knowledgable and I hope it will pique
the interest of the less experienced.
</blockquote>
</center>

<h2>Introduction</h2>
<p>
The <code> kjParsing</code> package is a parser generator written
in Python which generates parsers for use in Python.
<p>
These modules and their documentation and demo files
may be of use for classes on parsing, compiling, or
formal languages, and may also be helpful to people
who like to create experimental interpreters or translators
or compilers.
<p>
The package consists of three Python modules:
<code> kjParser, kjParseBuild,</code> and <code> kjSet</code>.  Together these
modules are called the <code> kjParsing</code> package.
The package also includes some documentation and demo
files and a <code> COPYRIGHT</code> file which explains the
conditions for copying and propagating this code
and the fact that the author assumes no responsibility
for any difficulties resulting from the use of this
package by anyone (including himself).

<h2>What a Parser Does</h2>

Parsers can be part of a lot of different things:
compilers, interpreters, translators, or code generators,
among others.  Nevertheless, at an abstract level parsers
all translate expressions of a language into computational
actions.
<p>
Parsers generated by the <code> kjParseBuild</code> module may do three
different sorts of actions: 
<center><table bgcolor="#ffdd66" border>
<tr><th>Value Computation</th></tr><tr><td>
The parser may build a data structure
as the result of the expression.  For example the silly <code> LispG</code>
grammar
from the file
<code> ``DLispShort.py''</code> can construct integers, strings and
lists from string representations.
<pre>
>>> from DLispShort import LispG, Context
>>> LispG.DoParse1( ' ("list with string and int" 23) ', Context)
['list with string and int', 23]
>>>
</pre>
</td></tr><tr><th>Environment Modification</th></tr><tr><td>
The parser may modify the context of the computation.  For example
the <code> LispG</code> grammar allows the assignment of values to internal
variable names.
<pre>
>>> LispG.DoParse1( '(setq Variable (4 5 9))', Context)
[4, 5, 9]
>>> Context['Variable']
[4, 5, 9]
>>>
</pre>
(Here the second result indicates that the string <code> 'Variable'</code>
has been associated with the value <code> [4,5,9]</code> in
the <code> Context</code> structure, which in this case is a simple
python dictionary.)
</td></tr><tr><th> External Side Effects</th></tr><tr><td>
The parser may also perform external actions.  For example the
<code> LispG</code> grammar has the ability to print values to the terminal.
<pre>
>>> LispG.DoParse1( '( (print Variable) (print "bye bye")  )', Context )
[4, 5, 9]
bye bye
[[4, 5, 9], 'bye bye']
>>>
</pre>
(Here the first two lines are the results of printing
and the last is the value of the expression.)
</td></tr></table></center>
More realistic parsers will perform more interesting actions,
of course.
<p>
To implement a parser using <code> kjParseBuild</code> you must
define the grammar to parse and associate each rule and terminal
of the grammar with an action which defines the
computational meaning of each language construct.
<p>
The grammar generation process consists of two phases
<center><table bgcolor="#ffdd66" border>
<tr><th>Generation</th></tr><tr><td>
During this phase you must define the syntax of the
language and function bindings that define the semantics
of the language.  When you've debugged the syntax and 
semantics you can dump the grammar object
 representing the syntax only to a grammar file which
can be reloaded without re-analyzing the language syntax.
For large grammars each regeneration may require significant
time and computational resources.
</td></tr><tr><th>Use</th></tr><tr><td>
During this phase you may load the grammar file without
re-analyzing the grammar on each use. However,
the semantics functions must still be rebound on each
load.  The reloaded grammar object augmented with interpretation
functions may be used to parse strings of the language.
</td></tr></table></center>
Note that the functions that define the semantics of the
language are must be bound in both phases.
<p>
<center><table bgcolor="#ffdd66" border><tr><td>
<pre>
           # from file DLispShort.py (with small differences)
     ( 1)  def GrammarBuild():
     ( 2)      import kjParseBuild
     ( 3)      LispG = kjParseBuild.NullCGrammar()
     ( 4)      LispG.SetCaseSensitivity(0) 
     ( 5)      DeclareTerminals(LispG)
     ( 6)      LispG.Keywords("setq print")
     ( 7)      LispG.punct("().")
     ( 8)      LispG.Nonterms("Value ListTail")
     ( 9)      LispG.comments([LISPCOMMENTREGEX])
     (10)      LispG.Declarerules(GRAMMARSTRING)
     (11)      LispG.Compile()
               print "dumping as binary to TESTLispG.mar"
     (12)      outfile = open("TESTLispG.mar", "w")
     (13)      LispG.MarshalDump(outfile)
     (14)      outfile.close()
     (15)      BindRules(LispG)
     (16)      return LispG
</pre>
<caption>A function for building simple grammar (GrammarBuild)</caption>
</td></tr></td></tr></table></center>

<h2>Defining a Grammar</h2>

A programming language grammar is conventionally divided into
several components:
<center><table bgcolor="#ffdd66" border>
<tr><th>Keywords</th></tr><tr><td>
These are special strings that ``highlight'' a language construct.
Familiar keywords from Python and Pascal and C are ``if'', ``else'',
and ``while''.
</td></tr><tr><th>Terminals</th></tr><tr><td>
These are special patterns of characters that indicate a value
in the language.  For example many programming languages will
classify the string <code> 123</code> as an instance of the integer
nonterminal and the string <code> snark</code> (not contained in quotes)
as an instance of the nonterminal identifier or
variable.  Terminals are usually restricted to very simple
constructs like identifiers, numbers, and strings.  More complex
things (such as a ``date'' data type) might be better handled
by nonterminals and rules.
</td></tr><tr><th>Nonterminals</th></tr><tr><td>
These are ``place holders'' for language constructs of the
grammar.  They represent parts of the grammar which sometimes
expand to great size and complexity.  For instance the
C language grammar presented by Kernigan and Ritchie has
a nonterminal translationUnit which represents a
complete C language module, a nonterminal 
conditionalExpression which represents a truth valued
expression of the language.
</td></tr><tr><th>Punctuations</th></tr><tr><td>
These are special characters or strings which are recognized
as separate entities even if they aren't physically separated
from other strings by white space.  For example, most languages
would ``see'' the string <code> if0</code> as a single token
(probably an identifier) even if <code> if</code> is a keyword,
whereas <code> if(0)</code> would be recognized
the same as <code> if ( 0 )</code> because parentheses are normally
considered punctuations.  Except for the special treatment
at recognition, punctuations are similar to keywords.
</td></tr></table></center>
The syntax of a language describes how to recognize
the components of the language.  To define a language syntax using
<code> kjParseBuild</code> you must create a null compilable grammar object
to contain the grammar (in Figure GrammarBuild this
is done on line 3 using the class constructor
<code> kjParseBuild.NullCGrammar()</code>
creating the grammar object <code> LispG</code>) and define the components
of the grammar and the rules for recognizing the components.
The component definitions
and rule declarations, as well as the specification of case sensitivity
and comment patterns, are performed on lines 4 through 10 of
Figure GrammarBuild for the <code> LispG</code> grammar.

<h3>Declaring Case Sensitivity and Comments</h3>

There are two nuances to parsing not yet mentioned:
case sensitivity and comments.  
<p>
Some grammars are not
case sensitive in recognizing keywords or identifiers.
For example ANSI standard SQL (which is not
case sensitive for keywords or identifiers) recognizes
<code> Select, select, SELECT,</code> and <code> SeLect</code> all 
as the keyword <code> SELECT</code>.
To specify the case sensitivity of the grammar for keywords only use
<pre>
     GRAMMAROBJECT.SetCaseSensitivity(TrueOrFalse) 
</pre>
where <code> TrueOrFalse</code> is 0 for no case sensitivity or
1 for case sensitivity.  This must be done before
any keyword declarations for the grammar.  All other
syntax declarations may be done in any order before
the compilation of the grammar object.
In Figure GrammarBuild the <code> LispG</code> grammar object
is declared to be case insensitive on line 4.
<p>
Comments are patterns in the input string which are ignored
(or more precisely interpreted as white space) by the language.
To declare a sequence of regular expressions to be interpreted as a comment
in a grammar use
<pre>
    GRAMMAROBJECT.comments(LIST_OF_COMMENT_REGULAR_EXPR_STRINGS)
</pre>
For example, line 9 or Figure GrammarBuild declares
the constant string previously declared as
<pre>
    LISPCOMMENTREGEX = ";.*"
</pre>
to represent a comment of the grammar <code> LispG</code>.
For the syntax of regular expression strings you must look
elsewhere, but as a hint <code> ";.*"</code> represents any string
commencing with a semicolon, followed by any sequence of
characters up to, but not including, a newline.

<h3>Declaring Keywords, Punctuations, and Terminals</h3>

To declare keywords for your grammar use
<pre>
      GRAMMAROBJECT.Keywords( STRING )
</pre>
where <code> STRING</code> is a white space separated string of keywords.
Line 6 of Figure GrammarBuild declares <code> setq</code> and <code> print</code>
as keywords of <code> LispG</code>.
<p>
To declare nonterminals for your grammar, similarly, use
<pre>
      GRAMMAROBJECT.Nonterms( STRING )
</pre>
where <code> STRING</code> is a white space separated string of nonterminal
names. Line 8 of Figure GrammarBuild declares <code> Value</code>
and <code> ListTail</code> as nonterminals of the <code> LispG</code>.
<p>
Similarly, use
<pre>
      GRAMMAROBJECT.punct( STRING )
</pre>
to declare a sequence of punctuations for the grammar, except
that in this case the string must not contain any white space.
Line 7 of Figure GrammarBuild declares parentheses and dot
to be punctuations of the <code> LispG</code>.
<p>
If you have a lot of keywords, punctuations,
or nonterminals you can make many separate
calls to the appropriate declaration methods
with different strings.
<p>
These declarations will cause the grammar to recognize
the declared keyword strings (when separated from other
strings by white space or punctuations) and punctuations
as special tokens of the grammar at the lowest level of
parsing.  The parsing process derives nonterminals of the
grammar at a higher level as discussed 
below.  
<p>
A small difficulty with
<code> kjParseBuild</code> is that the strings <code> @R, ::, >>,</code>
and <code> ##</code> cannot be used as names of keywords for the
grammar because they are used to specify rule syntax
in the ``metagrammar''.  
If you need these in your grammar they may
be implemented as ``trivial'' terminals.  For example,
<center><table bgcolor="#ffdd66" border><tr><td>
  <code>    Grammar.Addterm("poundpound", "##", echo)</code>
</td></tr></table></center>
I'm unsure whether this patch is good enough.
Does anyone have any advice for me?  If this is a bad
problem for some grammar the keywords of the meta grammar
can be changed of course, but this is a hack.

<h3>Declaring Terminals</h3>

<center><table bgcolor="#ffdd66" border><tr><td>
<pre>
        # from DLispShort.py
        def DeclareTerminals(Grammar):
   (1)      Grammar.Addterm("int", INTREGEX, intInterp)
   (2)      Grammar.Addterm("str", STRREGEX, stripQuotes)
   (3)      Grammar.Addterm("var", VARREGEX, echo)
</pre>
</td></tr>
<caption>Defining the terminals of a grammar. 
(TermDef)</caption></table></center>

<p>
Figure TermDef shows the declarations for installing
the <code> int, str,</code> and <code> var</code> terminals in the grammar.
This is given as a separate function because the declarations
define both the syntax and semantics for the terminals,
and therefore must be called both during grammar generation
and after loading the generated grammar object.
To declare a terminal for a grammar use
<pre>
      GRAMMAROBJECT.Addterm(NAMESTR, REGEXSTR, FUNCTION)
</pre>
This declaration associates both a regular expression string
<code> REGEXSTR</code>
and an interpretation function <code> FUNCTION</code> to the
terminal of the grammar named by the string <code> NAMESTR</code>.
The <code> FUNCTION</code> defines the semantics of the terminal
as describe below and the <code> REGEXSTR</code> specifies a regular
expression for recognizing the string.  For example on
line 2 of Figure TermDef the <code> var</code> terminal
is associated with the regular expression string
<pre>
      STRREGEX = '"[^\n"]*"'
</pre>
which matches any string starting with double quotes and ending
with double quotes which contains neither double quotes nor
a newline.

<h3>Declaring Rules of the Grammar</h3>


<center><table bgcolor="#ffdd66" border><tr><td>
<pre>
# from DLispShort.py
GRAMMARSTRING ="""
       Value ::  ## indicates Value is the root nonterminal for the grammar
         @R SetqRule :: Value >> ( setq var Value )
         @R ListRule :: Value >> ( ListTail
         @R TailFull :: ListTail >> Value ListTail
         @R TailEmpty :: ListTail >> )
         @R Varrule :: Value >> var
         @R Intrule :: Value >> int
         @R Strrule :: Value >> str
         @R PrintRule :: Value >> ( print Value )
"""
</pre>
</td></tr>
<caption>A grammar definition string.</caption>
</table></center>

<p>
To declare the rules of a grammar use the simple rule
definition language which comes with <code> kjParseBuild</code>, for example
as shown in Figure GramStr.  Line 10 of 
Figure GrammarBuild uses the string defined in
Figure GramStr to associate the rules with the
grammar using
<pre>
      GRAMMAROBJECT.DeclareRules(RULE_DEFINITION_STRING)
</pre>
This declaration does not analyse the string; analysis
and syntax/semantics errors are reported by <code> *.Compile()</code>
described below.
<p>
The rule definition language allows you to identify
the root nonterminal of your grammar and specify a
sequence of named derivation rules for the 
grammar.  It also allows comments
which start with <code> ##</code> and end with a newline.
An acceptible string for the rule definition language
looks like
<center><table bgcolor="#ffdd66" border><tr><td>
RootNonterminalName <code> ::</code> NamedRule1 NamedRule2 ...
</td></tr></table></center>
Here the Root nonterminal name should be the nonterminal
that ``stands for'' any complete string of the language.
Furthermore, each named rule looks like
<center><table bgcolor="#ffdd66" border><tr><td>
<code> @R</code> NameString <code> ::</code> GoalNonterm <code> >></code> RuleBody
</td></tr></table></center>
where the name string for the rule is a string without
whitespace, the goal nonterminal is the
nonterminal that the rule derives,
and the rule body is a sequence of keywords, punctuations
and nonterminals separated by white space.
Rule names are used for mapping rules to semantic interpretations
and should be unique.
<p>
Note that punctuations for the grammar you are defining
are not punctuations for the rule definition language
(which has none), so they must be separated from
other tokens by white space.  The keyword for the rule
definition language <code> @R, ::, >></code> must also be
separated from other tokens by whitespace in the rule
definition string.
Furthermore, all
punctuations, keywords, nonterminals, and terminals
used in the rules must be declared for the grammar before
the grammar is compiled (if one isn't the compilation will
fail with an error).
<p>
As a bit of sugar you may break up the declarations of rules.
<pre>
    LispG.DeclareRules("Value::\n")
    LispG.DeclareRules("  @R SetqRule :: Value >> ( setq var Value )\n")
    LispG.DeclareRules("  @R ListRule :: Value >> ( ListTail\n")
    ...
</pre>
This might be useful for larger grammars.

<h3>A Brief Discussion of Derivations</h3>

The rules for a grammar don't really describe how to
parse a string of the language, they actually
describe how to derive a string of the 
grammar.  For this reason it is possible
to create a grammar which derives the same string
in two different ways; such grammars are termed
ambiguous.  If you try to generate a parser
for an ambiguous grammar the parse generation process will
cause the parser generation process to complain.
<p>
For a more precise definition of the derivation of a
language string from a grammar see the ``further readings''
below.  For illustrative purposes, and to help explain
how to define semantics functions, consider the following
derivation of the string
<center><table bgcolor="#ffdd66" border><tr><td>
<code> ( 123 ( setq x "this" ) )</code>
</td></tr></table></center>
using the rules declared in Figure GramStr.
<center><table bgcolor="#ffdd66" border><tr><td>
Derivation</td><td> Rule used </td></tr><tr><td>
<code> Value1 >> ( ListTail1</code> </td><td> <code> ListRule</code> </td></tr><tr><td>
<code> ListTail1 >> Value2 ListTail2</code> </td><td> <code> TailFull</code> </td></tr><tr><td>
<code> Value2 >> [int = 123]</code> </td><td> <code> Intrule</code> </td></tr><tr><td>
<code> ListTail2 >> Value3 ListTail3</code> </td><td> <code> TailFull</code> </td></tr><tr><td>
<code> Value3 >> (setq [var='x'] Value4)</code> </td><td> <code> SetqRule</code> </td></tr><tr><td>
<code> Value4 >> [string='this']</code> </td><td> <code> StrRule</code> </td></tr><tr><td>
<code> ListTail3 >> )</code> </td><td> <code> TailEmpty</code>
</td></tr></table></center>
To obtain the string derived we simply substitute the
representations derived for each of the numbered nonterminals
and terminals of the derivation as shown
in Figure Derive.
<center><table bgcolor="#ffdd66" border><tr><td>
<pre>
(1)    Value1 
(2)    ( ListTail1                        (ListRule)
(3)    ( Value2 ListTail2                 (TailFull)
(4)    ( 123 ListTail2                    (Intrule)
(5)    ( 123 Value3 ListTail3             (TailFull)
(6)    ( 123 ( setq x Value4 ) ListTail3  (SetqRule)
(7)    ( 123 ( setq x "this" ) ListTail3  (StrRule)
(8)    ( 123 ( setq x "this" ) )          (TailEmpty)
</pre>
</td></tr>
<caption>Right-to-left derivation steps for 
<code> (123 (setq x "this"))</code>.
         (Derive) </caption>
</table></center>

<h3>Compiling the Grammar Syntax, and Storing the Compilation</h3>

Once you have defined all the keywords, comments, terminals,
nonterminals, punctuations, and rules of your grammer you
may create the datastructures needed for parsing by
compiling the grammar using
<pre>
      GRAMMAROBJECT.Compile()
</pre>
Line 11 of Figure GrammarBuild performs the compilation
for the LispG grammar.
<p>
If the compilation succeeds you may use
<pre>
      GRAMMAROBJECT.MarshalDump( OUTPUTFILE )
</pre>
to store the compiled grammar structure to a file that
may be later loaded without recompiling the grammar.
Here <code> MarshalDump</code> will create a binary ``marshalled''
representation for the grammar in the <code> OUTPUTFILE</code>.
For example line 13 of figure GrammarBuild 
marshalls a representation for <code> LispG</code> to the
file <code> TESTLispG.mar</code>.
<code> TESTLisp.GRAMMAR()</code> will 
then reconstruct the internal
structure of LispG as a grammar object and return the
grammar object as the result of the function.
<p>
Nevertheless, compilation of the grammar by itself does
not yeild a grammar that will do any useful 
parsing [Actually, it will do ``parsing'' using
default actions (implemented as a function which simply return
the list argument).]
Rules must be associated with computational actions before
useful parsing can be done.

<h2>Defining a Semantics</h2>
<p>
Two sorts of objects require semantic actions that
define their meaning: rules and terminals.
All semantic actions must be defined as Python functions
and bound in the grammar before parsing can be performed.
<p>
Before you can define the semantics of your language
in Python you better have a pretty good idea of what
the components of the language are supposed to represent,
of course.  Using your intuitive understanding of the
language you can:
<center><table bgcolor="#ffdd66" border><tr><td>
</td></tr><tr><td>
Decide what the context of the computation should be
and how it should be implemented as a Python structure.
If the process of Parsing must modify the context, then
then the context structure must be a ``mutable'' python
structure.
In the case of <code> LispG</code> the context is simply a structure
that maps ``internal'' variable names to values,
implemented as a simple Python dictionary mapping
name strings to the appropriate value.
</td></tr><tr><td>
Decide what kind of Python value each terminal of the grammar
represents.  In the case of <code> LispG</code>
<center><table bgcolor="#ffdd66" border>
<tr><th> str</th></tr><tr><td>
should represent a string value corresponding to the string
recognized (minus the surrounding quotes).
</td></tr><tr><th> int</th></tr><tr><td>
should represent an integer value corresponding to the
string recognized.
</td></tr><tr><th> var</th></tr><tr><td>
should represent the string representing the variable name
recognized (the name must be translated to a corresponding
value at a higher level since the terminal interpretation
functions don't have access to the context 
structure).
</td></tr></table></center>
</td></tr><tr><td>
Decide what kind of Python structure or value each
nonterminal represents.  In the case of the <code> LispG</code>
grammar:
<center><table bgcolor="#ffdd66" border>
</td></tr><tr><th> Value</th></tr><tr><td> 
represents a Python integer, string, or list.
</td></tr><tr><th> ListTail</th></tr><tr><td> 
represents a Python list containing the
  members of the tail of a list.
</td></tr></table></center>
</td></tr><tr><td>
Decide how each rule should derive a structure corresponding
to the Goal (left hand side) of the rule based on the
values corresponding to the terminals and nonterminals
on the right hand side of the rule.
In the case of the <code> LispG</code> grammar
(refer to Figure GramStr for rule definitions):
<center><table bgcolor="#ffdd66" border>
<tr><th> SetqRule</th></tr><tr><td>
  should return whatever the <code> Value</code> terminal in the body
  represents.
</td></tr><tr><th> ListRule</th></tr><tr><td>
  should return the list represented by the 
  <code> ListTail</code> nonterminal of the body.
</td></tr><tr><th> TailFull</th></tr><tr><td>
  should return the result of adding the value corresponding
  to the <code> Value</code> nonterminal of the list to the front
  of the list corresponding to the <code> Listtail</code> nonterminal
  of the body.
</td></tr><tr><th> Varrule</th></tr><tr><td>
  should return the value from the computational
  context that corresponds to the variable
  name represented by the <code> var</code> terminal of the body.
</td></tr><tr><th> Intrule</th></tr><tr><td>
  should return the integer corresponding to the <code> int</code>
  terminal of the body.
</td></tr><tr><th> Strrule</th></tr><tr><td>
  should return the string corresponding to the <code> str</code>
  terminal of the body.
</td></tr><tr><th> PrintRule</th></tr><tr><td>
  should return the value represented by the <code> Value</code>
  nonterminal of the body.
</td></tr></table></center>
</td></tr><tr><td>
Decide what side effects, if any, each rule should have on
the computational context or 
externally.
In the case of the <code> LispG</code> grammar:
<center><table bgcolor="#ffdd66" border>
<tr><th> SetqRule</th></tr><tr><td>
  should associate the variable name represented by <code> var</code>
  to the value represented by <code> Value</code> in the body.
</td></tr><tr><th> PrintRule</th></tr><tr><td>
  should print the value corresponding to the <code> Value</code>
  nonterminal to the screen.
</td></tr></table></center>
The other rules of <code> LispG</code>
should have no internal or external side effects.
</td></tr></table></center>
More complex languages may require much more complex contexts,
values and side effects, including
function definitions, modules, database
table accesses, user authorization
verifications, and/or file creation, among other possibilities.
<p>
Having determined the intuitive semantics of the language you
may now specify implement the semantic functions and
bind them in your grammar.

<h3>Semantics for Terminals</h3>
<p>
To define the meaning of a terminal you must create a Python
function that translates a string (which the parser has recognized
as an instance of the terminal)
into an appropriate value.
For instance, when the LispG grammar recognizes a string
<pre>
      "this is a string"
</pre>
the interpretation function should translate the recognized
string into the Python string it represents: namely,
the same string but with the double quotes stripped off.
The following ``string intepretation function'' will perform
this simple interpretation.

<pre>
        # from DLispShort.py
        def stripQuotes( str ):
            return str[1:len(str)-1]
</pre>
Similarly, when the parser recognizes a string as
an integer, the associated interpretation function
should translate the string into a Python integer.
<p>
The binding of interpretation functions to terminal
names is performed by the <code> Addterm</code> method previously
mentioned.  For example, line 2 of Figure TermDef
associates the <code> stripQuotes</code> function to the
nonterminal named <code> str</code>.  
<p>
All functions passed to
<code> Addterm</code> should take a single string argument
which represents the recognized string, and return
a value which represents the semantic interpretation
for the input string.

<h3>Semantics for Rules</h3>
<p>
The semantics of rules is more interesting since they may
have side effects and require the kind of recursive thinking
that gives most people headaches.  The semantics for rules
are specified by functions.  To perform the
semantic action associated with a rule, the ``reduction
function'' should
perform any side effects (to the computational context or
externally) and return a result value that represents
the interpretation for the nonterminal at the head of the rule.

<center><table bgcolor="#ffdd66" border><tr><td>
<pre>
      # from DLispShort.py
      def EchoValue( list, Context ):
          return list[0]
      
      def VarValue( list, Context ):
          varName = list[0]
          if Context.has_key(varName):
             return Context[varName]
          else:
             raise NameError, "no such lisp variable in context "+varName
      
      def NilTail( list, Context ):
          return []
      
      def AddToList( list, Context ):
          return [ list[0] ] + list[1]
      
      def MakeList( list, Context ):
          return list[1]
      
      def DoSetq( list, Context):
          Context[ list[2] ] = list[3]
          return list[3]
      
      def DoPrint( list, Context ):
          print list[2]
          return list[2]
</pre>
</td></tr>
<caption>The reduction functions for the rules. (RedFun)</caption>
</table></center>



<center><table bgcolor="#ffdd66" border><tr><td>
<pre>
        # from DLispShort.py
        def BindRules(LispG):
            LispG.Bind( "Intrule", EchoValue )
            LispG.Bind( "Strrule", EchoValue )
            LispG.Bind( "Varrule", VarValue )
            LispG.Bind( "TailEmpty", NilTail )
            LispG.Bind( "TailFull", AddToList )
            LispG.Bind( "ListRule", MakeList )
            LispG.Bind( "SetqRule", DoSetq )
            LispG.Bind( "PrintRule", DoPrint )
</pre>
</td></tr>
<caption>Binding named rules to interpretation functions. 
(ruleBind)</caption>
</table></center>

The Python functions that define the semantics of the rules of
<code> LispG</code> appear in Figure RedFun and the declarations
that bind the rule names to the functions in the grammar object
<code> LispG</code> appear in Figure ruleBind.
<p>
Each ``reduction function'' for a rule must take two arguments:
a list representing the body of the rule and a context
structure which represents the computational context of the
computation.  The list argument will have the same length
as the body of the rule, counting the keywords and punctuations
as well as the terminals and nonterminals.
<p>
For example the <code> SetqRule</code> has a body with five tokens, 
<pre>
      @R SetqRule :: Value >> ( setq var Value )
</pre>
so the
<code> DoSetq</code> function should expect the parser to deliver a
Python list argument with five elements of form
<pre>
      list = [ '(', 'SETQ', VARIABLE_NAME, VALUE_RESULT, ')' ]
</pre>
note that the ``names'' of keywords and punctuations appear
in the appropriate positions (0, 1, and 4) of the <code> list</code>
corresponding to their positions in <code> SetqRule</code>.
Furthermore, the position occupied by the terminal
<code> var</code> in <code> SetqRule</code> has been replaced by a string
representing a variable name in the <code> list</code> and the
position occupied by the nonterminal <code> Value</code> in
<code> SetqRule</code> has been replaced by a Python value.
<p>
More generally, the parser will call reduction functions for
rules with a <code> list</code> representing the ``interpreted
body of the rule'' where
<center><table bgcolor="#ffdd66" border>
<tr><th>keywords and punctuations</th></tr><tr><td>
are interpreted as themselves (i.e., their names),
except that letters will be in upper case if the grammar
is not case sensitive;
</td></tr><tr><th>terminals</th></tr><tr><td>
are interpreted as values previously returned by a call to
the appropriate terminal interpretation function; and
</td></tr><tr><th>nonterminals</th></tr><tr><td>
are interpreted as values previously returned by a
reduction function for a rule that derived this terminal.
</td></tr></table></center>
Although, the occurrence of the keyword names in the list may seem
useless, it may have its purposes.  For example,
a careful programmer might check them during debugging
to make sure the right function was bound to the right rule.
<p>
To determine how to implement the semantics of a rule
you must refer to the semantic decisions you made earlier.
For example, above we specified that the <code> setq</code> construct
should bind the variable name recieved  (<code> list[2]</code>) 
to the value (<code> list[3]</code>) in the <code> Context</code>,
and return the value (<code> list[3]</code>) 
as the result of the expression.
Translated into the more concise language of Python this is
exactly what <code> DoSetq</code> shown in Figure RedFun
does.
<p>
To bind a rule name to a (previously declared)
reduction function use
<pre>
      GRAMMAROBJECT.Bind( RULENAME, FUNCTION )
</pre>
where <code> RULENAME</code> is the string name for the rule previously
declared for the grammar <code> GRAMMAROBJECT</code> and 
<code> FUNCTION</code> is
the appropriate reduction function for the rule.
These bindings for <code> LispG</code> are shown in Figure ruleBind.

<h3>A Bit on the Parsing Process</h3>
<p>
The following is not a precise definition
of the actions of a Parser, but it may help
you understand how the parsing process
works and the order in which rules are recognized
and functions are evaluated.
<p>
<center><table bgcolor="#ffdd66" border><tr><td>
</td><td>Tokens seen S </td><td> input remaining</td><td> 
     rule R and function call </tr><tr>
<td>0</td><td><code> </code> </td><td> <code> (123 (setq x "this"))</code> </td><td>  </tr><tr>
<td>1</td><td><code> ( 123</code> </td><td> <code> (setq x "this"))</code> </td><td> Intrule </tr><tr>
<td> </td><td></td><td></td><td> <code> Value2 = EchoValue([123],C))</code> </tr><tr>
<td>2</td><td><code> ( Value2 ( setq x "this"</code> </td><td> <code> ))</code> </td><td> StrRule </tr><tr>
 <td></td><td></td><td></td><td> <code> Value4 = EchoValue(['this'],C)</code> </tr><tr>
<td>3</td><td><code> ( Value2 ( setq x Value4 )</code> </td><td> <code> )</code> </td><td> SetqRule </tr><tr> 
 <td></td><td></td><td></td><td> <code> Value3 = DoSetq(['(','SETQ','x',Value4,')'],C)</code> </tr><tr>
<td>4</td><td><code> ( Value2 Value3 )</code> </td><td> </td><td> TailEmpty </tr><tr>
 <td></td><td></td><td></td><td> <code> ListTail3 = NilTail([')'],C)</code> </tr><tr>
<td>5</td><td><code> ( Value2 Value3 ListTail3</code> </td><td> </td><td> TailFull </tr><tr>
 <td></td><td></td><td></td><td> <code> ListTail2 = AddToList([Value3,ListTail3],C)</code> </tr><tr>
<td>6</td><td><code> ( Value2 ListTail2</code> </td><td> </td><td> TailFull </tr><tr>
 <td></td><td></td><td></td><td> <code> ListTail3 = AddToList([Value2,ListTail2],C)</code> </tr><tr>
<td>7</td><td><code> ( ListTail3</code> </td><td> </td><td> ListRule </tr><tr> 
 <td></td><td></td><td></td><td> <code> Value1 = MakeList(['(',Value1],C)</code> </tr><tr>
<td>8</td><td><code> Value1</code> </td><td> </td><td> 
</td></tr>
<caption>Parsing <code> (123 (setq x "this"))</code>
         (Parse)</caption>
</table>
<em>Technically, each entry of S is tagged with the kind of token
  it represents (keyword, nonterminal, or terminal) and the name
  of the token it represents (e.g., <code> Value</code>, <code> str</code>)
  as well as the
  values shown.</em>
</center>

<p>
Figure Parse illustrates the sequence of reduction actions
performed by <code> LispG</code> when parsing the input string
<code> (123 (setq x "this"))</code>.  We can think of this parse as
``reversing'' the derivation process shown in Figure Derive
using the rule reduction functions to obtain semantic
interpretations for the nonterminals.
<p>
At the lowest level of parsing a lexical analyser
examines the unread portion of the input string tries
to match a prefix of the input string with a keyword
or a regular expression for a terminal (ignoring comments
and whitespace, except as separators).  The analyser ``passes''
the recognized
token to the higher level parser
together with its interpreted value.  The interpreted
value of a terminal is determined by using the appropriate
interpretation function and the interpreted value of 
a keyword is simply its name (in upper case, if the
grammer is not case sensitive).  For example the <code> LispG</code>
lexical analyser recognizes <code> '('</code> as a keyword with the
value <code> '('</code> and <code> "this"</code> as an instance of the nonterminal
<code> str</code> with the value <code> 'this'</code>.
<p>
The higher level parser accepts tokens T from the lexical analyser
and does one of two things with them
<center><table bgcolor="#ffdd66" border>
<tr><td>
If the most recent
token values V the parser has saved on its ``tokens seen'' stack S
``looks like'' the body B of a
 rule R and the current token is a token that
could follow the nonterminal N at the head of R, then
the parser evaluates the reduction function F associated
with R, using the values V from the stack S that match the body
B together with the computational context C.  The resulting
value F(V,C) replaces the values V
</td></tr><tr><td>
Otherwise the current token is shifted onto the ``tokens seen''
stack S and the parser moves on to the next token.
</td></tr></table></center>
The above is a lie.
Actually, the parsing process is much smarter than this, but
from a users perspective this simplification may be 
helpful.
<p>
Figure Parse shows ``reduction'' steps and not
the ``shifts'', and glosses over the lexical analysis and
other nuances,
but it illustrates the idea of the parsing process nonetheless.
For example at step 2 the parse recognizes the last token
on the stack S
(an instance of the <code> "str"</code> terminal with value <code> "this"</code>)
as matching the body of <code> StrRule</code>, and replaces it
with the an instance of the nonterminal <code> Value</code>
with value determined by the reduction of <code> StrRule</code>.
In this case <code> StrRule</code> is associated with the reduction
function <code> EchoValue</code>, so the result of the reduction
is given by <code> EchoValue( 'this', C )</code> where C is the
context structure for the Parse.
<p>
At Step 3 the most recent entries of S 
<pre>
      V = ['(', 'SETQ', 'x', Value4, ')']
</pre>
match the body of the rule
<code> SetqRule</code>, so they are replaced on S by an instance
of the <code> Value</code> nonterminal with value determined by
<pre>
      Value3 = DoSet( V, C )
</pre>
Finally, at step 8, the interpretation associated
with <code> Value1</code> (an instance of the root nonterminal for
<code> LispG</code>) is  considered the result of the computation.

<h2>Parsing with a Grammar</h2>
<p>
Before you can perform a parse you probably must create a
computational context for the parse.  In the case of <code> LispG</code>
the context is simply a dictionary so we may initialize
<pre>
      Context = {}
</pre>
To create a context for Parsing.
<p>
There are two methods which provide the primary interfaces for
the parsing process for a grammar.
<pre>
      RESULT = GRAMMAROBJECT.Parse1(STRING, CONTEXT)
      (RESULT, CONTEXT) = GRAMMAROBJECT.Parse(STRING, CONTEXT)
</pre>
The second allows you to make explicit in code that uses parsing
the possibility that a parse may alter the context of the parse
-- aside from that the two functions are identical.  Example
usage for <code> Parse1</code> using <code> LispG</code> were given earlier.

<h2>Storing and Reloading a Grammar Object</h2>
<p>
The process of compiling a grammar may take significant time
and consume significant quantities of 
memory.  To
free up memory from structures in a 
compilable grammar object that aren't
needed after compilation use <code> GRAMMAR.CleanUp()</code>.
<p>
Once you have
debugged the syntax and semantics of your grammar you may
store syntactic information for the
grammar using the <code> Reconstruct</code>
method already mentioned.  The declarations created by <code>
Reconstruct</code> only defines the syntax for the grammar.
The semantics must be rebound separately.  But it is much better to
use UnMarshalGram as shown below, which stores the grammar
in a binary format.
<p>
For example, lines 12 through 14 of 
Figure GrammarBuild create a file <code> TESTLispG.py</code>
containing a function <code> GRAMMAR()</code> which will reconstruct
the syntax for the <code> LispG</code> grammar.


<center><table bgcolor="#ffdd66" border><tr><td>
<pre>
        # from DLispShort.py

def unMarshalLispG():
    import kjParser
    infile = open("TESTLispG.mar", "r")
    LispG = kjParser.UnMarshalGram(infile)
    infile.close()
    DeclareTerminals(LispG)
    BindRules(LispG)
    return LispG
</pre>
This function can then be used in another file,
provided <code>DLispShort.GrammarBuild()</code> has been executed
at some point in the past, thusly:
<pre>
        import DLispShort
        LGrammar = DLispShort.unMarshalLispG()
</pre>
</td></tr>
<caption>Loading a precomputed grammar object.</caption>
</table></center>
<p>
Figure Load shows a function <code> LoadLispG</code>
that reloads the syntactic
portion of <code> LispG</code> from <code> TESTLispG.mar</code>.  
To rebind the semantics as well the
function re-declares the terminals and re-binds the rules
to make the reconstructed <code> LispG</code> suitable for use in parsing.

<h2>Errors raised</h2>
<p>
You may see the following errors:
<center><table bgcolor="#ffdd66" border>
<tr><th> LexTokenError</th></tr><tr><td>
This usually means the lowest level of the parser ran into a string
it couldn't recognize.
</td></tr><tr><th> BadPunctError</th></tr><tr><td>
You tried to make a whitespace character a punctuation.  
This is not currently allowed.
</td></tr><tr><th> EOFError, SyntaxError</th></tr><tr><td>
You tried to parse a string that is not valid for the grammar.
</td></tr><tr><th> TokenError</th></tr><tr><td>
During parser generation you used a string in the rule definitions
that wasn't previously registered as a terminal, nonterminal, or
punctuation.
</td></tr><tr><th> NotSLRError</th></tr><tr><td>
You attempted to build a grammar that is not ``SLR'' according
to the definition of Aho and Ullman.  Either the grammar is
ambiguous, or it doesn't have a derivation for the root
nonterminal, or it is too tricky for the generator.
</td></tr></table></center>
Furthermore
<code> NondetError, ReductError, FlowError, ParseInitError,
UnkTermError</code>
or errors raised by other modules
shouldn't happen.
If an error that shouldn't happen happens there are
two possibilities (1) you have fiddled with the code or
data structures and you broke something, or (2) there
is a serious bug in the module.

<h2>Possible Gotchas</h2>
<p>
This package has a number of known deficiencies, and there
are probably many that are yet to be discovered.
<p>
Syntax errors are not reported nicely.  Sorry.
<p>
Currently, there is no way to to resolve grammar
ambiguities.  For example a C construct
<pre>
if (x)
   if (y)
      x = 0;
   else
      y = 1;
</pre>
could have the <code> else</code> associated with either the
first or second if; the grammar doesn't indicate which.  
This is normally resolved by informing
the parser generator to prefer one binding or the other.
No method for providing a preference is implemented here, yet.
Let me know if you need such a method or if you have any suggestions.
<p>
Keywords of the meta-grammar cannot name tokens of
the object grammar (see footnote above).
<p>
If you want keywords to be recognized without case
sensitivity you must declare <code> G.SetCaseSensitivity(0)</code>
before any keyword declarations.
<p>
Name and regular expression collisions are not always
checked and reported.  If you name two rules the same,
for example, you may get undefined behavior.
<p>
The lexical analysis implementation is not as fast as it
could be (of course).
It also sees all white space as a
`single space'
so, for example, if indentation is significant in your grammar
(as in Python) you'll need a different lexical analyzer.
Also if <code> x=+y</code> means something different from 
<code> x = + y</code> (as it did in the original C, I believe)
you may have trouble.  Happily the lexical component can
be easily ``plug replaced'' by another implementation if needed.
<p>
Also, the system currently only handles SLR grammars (as defined
by Aho and Ullman), as mentioned above.  If you get a
<code> NonSLRError</code> during grammar compilation you need a better
parser generator.  I may provide one, if I have motivation and time.
<p>
I know of no outright bugs.  Trust me, they're there.  Please
find them for me and tell me about them.  I'm not a big
expert on parsing so I'm sure I've made some errors, particularly
at the lexical level.

<h2>Further Reading</h2>
<p>
A standard reference for parsing and compiler, interpreter,
and translator implementation is Principles of Compiler
Design, by Aho and Ullman (Addison Wesley).  The best thing
to say about this book is that its competitors don't seem to
be much better.

<p>
<a href="mailto:arw@ifu.net">feedback</a><br>
<a href="../index.html">home</a><br>
<a href="index.html">Gadfly home</a>
</body>
</html>