-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathyacc.html
1221 lines (1098 loc) · 48.5 KB
/
yacc.html
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
<!DOCTYPE HTML>
<html lang="en">
<head>
<title>YACC</title>
<meta charset="UTF-8">
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<header class="center clearfix" id="navtop">
<a href="index.html" class="logo fleft"><img src="img/logo.png" alt=""></a>
<nav class="fright">
<ul>
<li><a href="index.html">Home</a></li>
<li><a href="about.html">About</a></li>
<li><a href="roadmap.html">Roadmap</a></li>
<li><a href="documentation.html" class="navactive">Documentation</a></li>
</ul>
</nav>
</header>
<div class="about center part clearfix">
<header class="title">
<h3 class="fleft">YACC</h3>
</header>
<aside class="column4 mright">
<menu>
<ul>
<li><a href="#navintro" class="sec">Introduction to YACC</a></li>
<li><a href="#navstructure" class="sec">Structure of YACC programs</a></li>
<li><a href="#navshiftreduce" class="sec">Shift-reduce parsing</a></li>
<li><a href="#navconflict" class="sec">Conflicts in parsing using YACC</a></li>
<li><a href="#navpassingvalues" class="sec">Token attributes</a></li>
<li><!--For blank space between lines and download button--> </li>
<li><a href="https://github.com/silcnitc/documentation/blob/master/yacc/yacc.odt?raw=true" class="button"> Download as pdf</a></li>
<li><!--Blank line for space between download button and main title--> </li>
</ul>
</menu>
</aside>
<section class="columnthird content"><h1 class="mright">USING YACC</h1>
<article id="navintro" class="detail">
<h2>Introduction to YACC</h2>
<p>
YACC (Yet Another Compiler Compiler) is a tool used to generate a parser.
This document is a tutorial for the use of YACC to generate a parser for ExpL.
YACC translates a given <a href="#navcfg"> Context Free Grammar (CFG)</a>
specifications (input in input_file.y) into a C implementation (y.tab.c) of
a corresponding <a href="http://en.wikipedia.org/wiki/Pushdown_automaton" target="_blank"> push down automaton </a> (i.e., a finite state machine with a stack).
This C program when compiled, yields an executable parser.
</p>
<center>
<img src="img/yacc_1.png" style="max-width:70%">
</center><br>
<p> The source SIL program is fed as the input to the generated parser ( a.out ).
The <i>parser</i> checks whether the program satisfies the syntax specification given in the input_file.y file.
<p>
<a href="https://en.wikipedia.org/wiki/Yacc" target="_blank">YACC</a> was developed by <a href="https://en.wikipedia.org/wiki/Stephen_C._Johnson" target="_blank">Stephen C. Johnson</a> at <a href="https://en.wikipedia.org/wiki/Bell_Labs" target="_blank">Bell labs</a>.
</p>
<p>
<big><b>Parser</b>:</big></p><p>A parser is a program that checks whether its input (viewed as a stream of tokens) meets a given grammar specification. The syntax of SIL can be specified
using a Context Free Grammar. As mentioned earlier, YACC takes this specification and generates a parser for SIL. </p>
<p id="navcfg">
<big><b>Context Free Grammar (CFG)</b>:</big></p>
<p>
A context free grammar is defined by a four tuple (N,T,P,S) - a set N of non-terminals,
a set T of terminals (in our project, these are the <a href="lex.html#navintro">tokens</a> returned by the lexical analyzer and hence we refer to them as tokens frequently), set P of productions and a start variable S.
Each production consists of a non-terminal on the left side (head part) and a sequence of tokens and
non-terminals (of zero or more length) on the right side (body part). We will explore productions further in detail <a href="#navprod">later</a> in this documentation.
For more about context free grammars refer to this<a href="https://en.wikipedia.org/wiki/Context-free_grammar" target="_blank"> wiki </a>.
</p>
<p id="navgramex1">
<b>Example:</b> This example is an
Infix to Postfix converter implemented using YACC. The rules part of the YACC program has been shown below:
</p>
<pre>
start: expr '\n' {exit(1);}
;
expr: expr '+' expr {printf("+ ");}
| expr '*' expr {printf("* ");}
| '(' expr ')'
| DIGIT {printf("NUM%d ",pos);}
;
</pre>
<p>
In this example:<br> The set of non-terminals are N = {start, expr}<br> The set of terminals are
T = {'\n', '+', '*', '(', ')' , DIGIT } <br>The start symbol S = start.
</p>
<p>Sample Input/Output :</p>
<div class="syntax">
I: 1+5<br>
O: NUM1 NUM2 +
</div>
<p>
When the input expression 1+5 is given to the parser generated by YACC, the parser prints a <a href="http://en.wikipedia.org/wiki/Reverse_Polish_notation" target="_blank">postfix</a> form of the original expression 1+5 as NUM1 NUM2 + where, NUM1 represents the first number ( 1 ) in the input and NUM2 represents the second number ( 5 ) in the input.
</p>
<p>Sample Input/Output :</p>
<div class="syntax">
I: 3+(1*9)+5<br>
O: NUM1 NUM2 NUM3 * + NUM4 + <br><br>
I: 5$<br>
O: NUM1 error <br>
</div>
<p>
The <a href="#navgramex1">example</a> above demonstrates the specification of rules in YACC. In this example there are five rules. Each rule has a <i>production part</i> and an <i>action part </i> .The action part consists of C statements enclosed within a { and }. Each production part has a <i>head</i> and a <i>body</i> separated by a '<b>:</b>'. For example, the first rule
above has production part with start as the head and expr '\n' as the body.
The action part for the rule is {exit(1);}.
The parser reads the input sequentially
and tries to find a pattern match with the body part of each production.
When it finds a matching production,
the action part of the corresponding rule is executed.
The process is repeated till the end of the input.
</p>
<p> In the above example, when the input 1+5 is given to the parser,
it attempts to match the input with the body of the production of the first rule.
When the input has been parsed completely and correctly matched with the start production start: expr '\n' the
parser executes the action exit(1);. The statements printf("NUM "); and printf("+ ");
are executed as result of the input being matched with the productions expr: DIGIT and
expr: expr '+' expr respectively.
If the parser fails to find any matching body part, it invokes a special yyerror() function.
In our example, the yyerror() function is programmed to print the message “error”.
</p>
</article>
<div class="up grid col-one-third" style="float:right">
<a href="#navtop" title="Go back up"> top ↑</a>
</div>
<article id="navyyparse" class="detail">
<h2>yyparse()</h2>
<p>
The y.tab.c file contains a function yyparse() which is an implementation (in C) of
a <a href="http://en.wikipedia.org/wiki/Pushdown_automaton" target="_blank">push down automaton</a>. yyparse() is responsible for parsing the given input file.
The function yylex() is invoked by yyparse() to read tokens from the input file.
Click <a href="#navexy0al">here</a> to view an example of yylex() definition.
Note that the yyparse() function is automatically generated by YACC in the y.tab.c file.
Although YACC declares yylex() in the y.tab.c file, it <u>does not generate</u> the definition for yylex().
Hence the yylex() function definition has to be supplied by you (either directly by defining yylex() in
the <i>auxiliary functions</i> section (explained in the next section) or using a lexical analyzer generator like LEX).
Each invocation of yylex() must return the next token (from the input steam) to yyparse().
The action corresponding to a production is executed by yyparse() only after sufficient number of tokens
has been read (through repeated invocations of yylex()) to get a complete match with the body of the production.
</p>
</article>
<div class="up grid col-one-third" style="float:right">
<a href="#navtop" title="Go back up"> top ↑</a>
</div>
<article id="navstructure" class="detail">
<h2>The structure of YACC programs</h2>
<p>
A YACC program consists of three sections: Declarations, Rules and Auxiliary functions.
(Note the similarity with the structure of LEX programs).
</p>
<pre>
DECLARATIONS
%%
RULES
%%
AUXILIARY FUNCTIONS
</pre>
<br>
<h3>2.1 Declarations</h3>
<p>
The declarations section consists of two parts: (i) C declarations and (ii) YACC declarations .
The C Declarations are delimited by <b>%{</b> and <b>%}</b>.
This part consists of all the declarations required for the C
code written in the <i>Actions</i> section and the <i>Auxiliary functions</i> section. YACC copies the contents of this section into the generated y.tab.c file without any modification.
<br>
The following example shows an abstract outline of the structure of the declarations part of a YACC program:
</p>
<p><b>Example : </b></p>
<div id="decl">
<pre>
/* Beginning of Declarations part */
%{
/*Beginning of C declarations*/
/*End of C declarations*/
%}
/*Beginning of YACC declarations */
/*End of YACC declarations */
/* End of Declarations Part */
%%
</pre>
</div>
The YACC declarations part comprises of declarations of tokens (usually returned by the lexical analyzer).
The parser reads the tokens by invoking the function yylex() (To be discussed in detail later).
<br>
<br>
<h3>2.2 Rules</h3>
</p>
<p>
A rule in a YACC program comprises of two parts (i) the production part and (ii) the action part.
In this project, the syntax of SIL programming language will be specified in
the form of a context free grammar. A rule in YACC is of the form:
</p>
<div class="syntax">
production_head : production_body {action in C } ;
</div>
The following example shows an abstract outline of the structure of the rules part of a YACC program:
<div class="syntax">
%% <br>
/* Rules Section begins here */ <br>
<br>
/* Rules Section ends here */ <br>
%%
</div>
<p> The rules in our example can be found <a href="#navexy0r">here</a> </p>
<big id="navprod"><b>2.2.1 Productions</b></big>
</p>
Each production consists of a production head and a production body.
Consider a production from our <a href="#navexy0r">example</a>:
<div class="syntax">
expr : expr '+' expr
</div>
<p>The expr on the LHS of the <b>:</b> in the production is called the <i>head</i> of
the production and the expr '+' expr on the RHS of the : is called the <i>body</i> of the production. In the above example, '+' is a terminal (token) and expr is a non-terminal. Users can give name to a token.
(for instance we can give the name 'PLUS' to the token '+').
In such cases, the names must be defined in the declarations section. For example have a look at the definition of the token DIGIT <a href="#navexy0yd">here</a>. The head of a production is always a non-terminal.
Every non-terminal in the grammar must appear in the head part of at least one production.
</p>
<p>Note that a non-terminal in the head part of a production may have one or more production bodies separated by a “|”.
Consider the non-terminal expr in our <a href="#navexy0">example</a>.
The non-terminal has four production bodies expr '+' expr , expr '*' expr , '(' expr ')' and DIGIT.
The first production body has an associated print action op_printf("+") and the second production body has an associated action op_print("*").
yyparse() executes the action only when the body expr '+' expr has been matched with the input.
The action part of a single production may have several statements of C code.
</p>
<p> <big><b>2.2.2 Actions</b></big></p>
<p> The action part of a rule consists of C statements enclose within a '{' and '}'. These statements are
executed when the input is matched with the body of a production and a <i>reduction</i> takes place. The notion of a <i>reduction</i> will be explained later. From the <a href="#navexy0r">example</a> below, consider the following rule:
</p>
<div class="syntax">
expr: DIGIT {printf("NUM%d ",pos);}
</div>
<p>In this rule, when the input matches with the body of the production DIGIT, it is <i>reduced</i> to expr and the action {printf("NUM%d ",pos);} is executed. </p>
<p> <big><b>2.2.3 Auxiliary Functions</b></big> </p>
<p> The Auxiliary functions section contains the definitions of three mandatory functions main(), yylex() and yyerror().
You may wish to add your own functions (depending on the the requirement for the application) in the y.tab.c file.
Such functions are written in the auxiliary functions section.
The <a href="#navexy0al">main()</a> function must invoke <a href="#navexy0al">yyparse()</a> to parse the input. You will need to write your supporting functions later in this project. </p>
<b>Example: intopost.y</b>
<div id = "navexy0">
<pre id = "navexy0d">
%{
<b>/*** Auxiliary declarations section ***/</b>
#include<e><</e>stdio.h<e>></e>
#include<e><</e>stdlib.h<e>></e>
/* Custom function to print an operator*/
void print_operator(char op);
/* Variable to keep track of the position of the number in the input */
int pos=0;
%}
<c id = "navexy0yd"></c>
<b> /*** YACC Declarations section ***/</b>
%token DIGIT
%left '+'
%left '*'
%%
<c id="navexy0r"></c>
<b>/*** Rules Section ***/</b>
start : expr '\n' {exit(1);}
;
expr: expr '+' expr {print_operator('+');}
| expr '*' expr {print_operator('*');}
| '(' expr ')'
| DIGIT {printf("NUM%d ",pos);}
;
%%
<c id="navexy0al"></c>
<b>/*** Auxiliary functions section ***/</b>
void print_operator(char c){
switch(c){
case '+' : printf("PLUS ");
break;
case '*' : printf("MUL ");
break;
}
return;
}
yyerror(char const *s)
{
printf("yyerror %s",s);
}
yylex(){
char c;
c = getchar();
if(isdigit(c)){
pos++;
return DIGIT;
}
else if(c == ' '){
yylex(); /*This is to ignore whitespaces in the input*/
}
else {
return c;
}
}
main()
{
yyparse();
return 1;
}</pre>
</div>
<p><i>y.tab.c</i> file can be generated using the command
<pre>
yacc intopost.y
</pre>
<i>y.tab.c</i> is compiled using C compiler
<pre>
gcc y.tab.c
</pre>
</p>
<p>NOTE: <i>%left </i> option is used to resolve shift/reduce conflicts. It is explained in detail later. </p>
<p>Sample Input/Output:
<div class="syntax">
I: 2+2<br>
O: NUM1 NUM2 PLUS
</div>
<p>
When yyparse() matches the input 2+2 with the production body expr '+' expr, it executes the action op_print('+');
and as a result prints “PLUS” in place of '+' as per the definition of op_print().
</p>
<p>
<b>NOTE</b>: op_print() is used in the example just to show an example of the declaration, definition and usage of a user defined auxliary function. Generally in this project, we use printf() to display content.
</p>
</article>
<div class="up grid col-one-third" style="float:right">
<a href="#navtop" title="Go back up"> top ↑</a>
</div>
<article id="navshiftreduce" class="detail">
<h2> A working introduction to shift-reduce parsing </h2>
<p> YACC uses shift-reduce parsing methodology to parse the given input.
The shift-reduce parser is essentially a <a href="http://en.wikipedia.org/wiki/Pushdown_automaton" target="_blank"> push down automaton </a>. It consists of a finite state machine with a stack.
The stack is used to hold terminal and/or non-terminal symbols.
The following is a gentle introduction to shift-reduce parsing.
</p>
<p> Take note of the following points before we proceed:</p>
<p>A shift-reduce parser is initialized in the following <i>configuration</i>.</p>
<pre>
STACK: $ I/P BUFFER: <Input to be parsed> $
</pre>
<p>
The input to be parsed, which is a sequence of terminal symbols, is stored in an input buffer with '$' symbol
at the end (used as an end-marker). The stack is initialized to contain just the symbol '$'.
</p>
<p>The parser works by repeatedly performing the following actions :<br>
1. Read the next terminal symbol from the input and push it into the stack and removing it from the input.
This operation is called a shift. (The shift operation will be explained in detail <a href="#navparseact">later</a>.)<br>
2. Do some conditional operations on the stack. These operations are called reductions.
Not every iteration may involve reductions. (Reductions will be explained in detail <a href="#navparseact">later</a>.) <br>
3. Until an error is encountered or the input is successfully parsed.</p>
</p>
<p>Parsing ends successfully when the input buffer is
empty (except for the end-marker '$') and the stack contains nothing but the '$'
followed by the start symbol of the grammar.
Error condition occurs when the input does not belong to
the language of the grammar and the parser detects the same. We will look at error conditions later. </p>
<!-----------------------NOTHING ON ERROR CONDITIONS YET------------------------>
<p>
Consider the following context free grammar. This will be used as a running example for this section. </p>
<pre>
expr : expr '+' expr (Production 1)
| expr '*' expr (Production 2)
| '(' expr ')' (Production 3)
| '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' (Production 4)
;
</pre>
<p>
The terminal set is {+,*,(,),0,1,2,3,4,5,6,7,8,9}. The only non-terminal is 'expr'.
Production 4 is actually a collection of 10 productions. We refer them collectively with one production number for simplicity.</p>
<p>
Let us consider parsing of the input 2+2*3 using this grammar.
When the parsing process begins, the contents of the stack and the input buffer would be as follows: </p>
<pre>
STACK: $ I/P BUFFER:     2 + 2 $
</pre>
<p>
The contents of the stack and the contents of the input buffer together define the <i>configuration</i> of the parser. On successful completion of parsing, the configuration would be:</p>
<pre>
STACK:     $ expr       I/P BUFFER:     $
</pre>
<p> Note here that expr is the start variable of the parser's context free grammar. This is the accepting configuration.</p>
<p>
At each step of parsing, the parser takes an action resulting in a configuration change.
A shift-reduce parser can take four possible <i>parser-actions</i>:
<ul id="navparseact">
<li> 1. <b>Shift</b> is the parser-action of removing the next unread terminal from the input buffer and pushing it into the stack.
(The input terminal gets “shifted” to the stack).</li>
<li> 2. <b>Reduce</b> is the parser-action of replacing one or more grammar symbols from the top of the stack that matches a body of a production,
with the corresponding production head. The contents on top of the stack which matches the right side of a production is called a <i><big>handle</big></i>.
The process of replacing a handle with the corresponding production head is called a <i>reduction</i>.</li>
<li> 3.<b> Accept</b> is the parser-action indicating that the entire input has been parsed successfully.
The parser executes an accept action only if it reaches the accepting configuration – one in which
the input buffer is empty and the stack contains just the start variable followed by '$'. Accepting state would be of the form:
<pre>
STACK: $ <start_variable> I/P BUFFER: $
</pre>
</li>
<li> 4. <b>Error</b> indicates that an error was encountered while parsing the input.
In our example, there is no error. We will see error conditions later.
</li>
</ul>
</p>
<h3>The parser's Iteration Steps</h3>
<p>After initialization, the parser executes the following algorithm.</p>
<pre>
Repeat
shift the next terminal from the input to the stack.
While there is a “valid” reduction
perform the reduction.
Until accepting configuration is reached.
</pre>
<p>At each step of parsing, the shift-reduce parser decides on an action depending on the configuration of the parser.
</p>
<p>
Several details are left out in this description.
For instance, what is a “valid reduction”, or what the error conditions are etc.
have not been specified. These are determined by the contents of a parsing table maintained by the parser and
we will not go into the details here.
Instead, we will try to see how the parser operates in the case of our running example.
</p>
<pre>
(1) STACK: $ I/P BUFFER: 2 + 3 * ( 4 + 5 ) $
</pre>
<br>
At this configuration, the parser executes a <i>shift</i> action i.e. 2 is pushed onto the stack resulting in the configuration:
<pre>
(2) STACK: $ 2 I/P BUFFER: + 3 * ( 4+ 5 ) $
</pre>
<br>
Now, the top of the stack matches the right side (body) of Production 4 i.e., the 2 on the stack is
the handle in this case and a reduction takes place replacing the handle with the production head <i>expr</i>.
<pre>
(3) STACK: $ expr I/P BUFFER: + 3 * ( 4 + 5 ) $
</pre>
<br>
As there is no further handles to perform reductions, the parser shifts the next terminal '+' from the input to the stack.
<pre>
(4) STACK: $ expr + I/P BUFFER: 3 * ( 4 + 5 ) $
</pre>
<br>
In the next iteration, as no reductions are possible, the parser again shifts the next input:
<pre>
(5) STACK: $ expr + 3 I/P BUFFER: * ( 4 + 5 ) $
</pre>
<br>
Now, the parser can apply Production 4 and <i>reduce</i> the handle '3' on the top of the stack to <i>expr</i>.
Thus the parser reduces by Production 4 and replaces '3' with expr.
<pre>
(6) STACK: $ expr + expr I/P BUFFER: * ( 4 + 5 ) $
</pre>
<br>
At this point there is a further reduction possible using Production 1.
However, the “valid” action here is not to perform the reduction, but shift the next input to the stack.
The reason being that '*' has higher precedence over '+'.
(similar issues occur with associativity of operators). Unless the parser is somehow is informed about
what the correct action is (shift/reduce), under every such situation, the correct precedence/associativity may not be respected. For the time being, it is sufficient to understand that there are ways by which the user can force the parser to act in the right way in most practical situations, particularly when using a parser generator like YACC. Hence we hide these issues for now and assume that the parser is somehow capable of finding the “valid” actions.
(Some more details on how this will be done will be explained in the <a href="#navconflict">later</a> sections.) Hence, the next action is a shift.
<pre>
(7) STACK: $ expr + expr * I/P BUFFER: ( 4 + 5 )$
</pre>
<br>
In the next few iterations, the parser continuously shifts and reduces to reach the configuration:
<pre>
(8) STACK: $ expr + expr * ( expr + expr I/P BUFFER: ) $
</pre>
<br>
Now, the handle “expr+expr” matches the body of production 1, hence the parser reduces by production 1.
<pre>
(9) STACK: $ expr + expr * ( expr I/P BUFFER: ) $
</pre>
<br>
The parser continues to iterate as the accepting configuration has not been reached.
In the next iteration, the parser shifts, as a result emptying the input buffer.
<pre>
(10) STACK: $ expr + expr * ( expr ) I/P BUFFER: $
</pre>
<br>
Now the parser reduces the handle “ ( expr ) ” by production 3,
<pre>
(11) STACK: $ expr + expr * expr I/P BUFFER: $
</pre>
<br>
In the next iteration, as yet another valid reduction is possible, the parser reduces by Production 2
<pre>
(12) STACK: $ expr + expr I/P BUFFER: $
</pre>
<br>
As the parser has not reached accepting configuration and there exists another handle top of the stack, the parser further reduces the entire contents of the stack,
i.e., the handle “expr + expr” with production 1 and thus puts the start symbol expr on the stack.
<pre>
(13) STACK: $ expr I/P BUFFER: $
</pre>
<br>
On reaching accepting configuration, the parser quits iterating.
Since the I/P BUFFER is empty and the stack contains only the start variable,
the parser executes an accept action, indicating that the input has been parsed successfully.
<br>
The following table summarizes the step-by-step change in the parser's configuration after each action taken by a shift reduce parser.
<br>
</p>
<table class="tg">
<tr>
<th class="tg-e3zv">STACK</th>
<th class="tg-e3zv">I/P BUFFER<br></th>
<th class="tg-e3zv">PARSER-ACTION EXECUTED<br></th>
</tr>
<tr>
<td class="tg-031e"></td>
<td class="tg-031e">2 + 3 * (4 + 5) $<br></td>
<td class="tg-031e">_</td>
</tr>
<tr>
<td class="tg-031e">$2</td>
<td class="tg-031e">+ 3 * ( 4 + 5 ) $<br></td>
<td class="tg-031e">SHIFT</td>
</tr>
<tr>
<td class="tg-031e">$expr</td>
<td class="tg-031e">+ 3 * ( 4 + 5 ) $</td>
<td class="tg-031e">REDUCE</td>
</tr>
<tr>
<td class="tg-031e">$expr +<br></td>
<td class="tg-031e">3 * ( 4 + 5 ) $</td>
<td class="tg-031e">SHIFT</td>
</tr>
<tr>
<td class="tg-031e">$expr + 3<br></td>
<td class="tg-031e">* ( 4 + 5 ) $</td>
<td class="tg-031e">SHIFT</td>
</tr>
<tr>
<td class="tg-031e">$expr + expr<br></td>
<td class="tg-031e">* ( 4 + 5) $<br></td>
<td class="tg-031e">REDUCE</td>
</tr>
<tr>
<td class="tg-031e">$expr + expr *<br></td>
<td class="tg-031e">( 4 + 5 ) $</td>
<td class="tg-031e">SHIFT</td>
</tr>
<tr>
<td class="tg-031e">$expr + expr * (<br></td>
<td class="tg-031e">4 + 5 ) $<br></td>
<td class="tg-031e">SHIFT</td>
</tr>
<tr>
<td class="tg-031e">$expr + expr * ( 4<br></td>
<td class="tg-031e">+ 5 ) $</td>
<td class="tg-031e">SHIFT</td>
</tr>
<tr>
<td class="tg-031e">$expr + expr * ( expr<br></td>
<td class="tg-031e">+ 5 ) $</td>
<td class="tg-031e">REDUCE</td>
</tr>
<tr>
<td class="tg-031e">$expr + expr * ( expr +<br></td>
<td class="tg-031e">5 ) $</td>
<td class="tg-031e">SHIFT</td>
</tr>
<tr>
<td class="tg-031e">$expr + expr * ( expr + 5<br></td>
<td class="tg-031e">) $<br></td>
<td class="tg-031e">SHIFT</td>
</tr>
<tr>
<td class="tg-031e">$expr + expr * ( expr + expr <br></td>
<td class="tg-031e">) $<br></td>
<td class="tg-031e">REDUCE</td>
</tr>
<tr>
<td class="tg-031e">$expr + expr * ( expr<br></td>
<td class="tg-031e">) $<br></td>
<td class="tg-031e">REDUCE</td>
</tr>
<tr>
<td class="tg-031e">$expr + expr * ( expr )<br></td>
<td class="tg-031e">$</td>
<td class="tg-031e">SHIFT</td>
</tr>
<tr>
<td class="tg-031e">$expr + expr * expr<br></td>
<td class="tg-031e">$</td>
<td class="tg-031e">REDUCE</td>
</tr>
<tr>
<td class="tg-031e">$expr + expr <br></td>
<td class="tg-031e">$</td>
<td class="tg-031e">REDUCE</td>
</tr>
<tr>
<td class="tg-031e">$expr</td>
<td class="tg-031e">$</td>
<td class="tg-031e">REDUCE</td>
</tr>
<tr>
<td class="tg-031e">$expr</td>
<td class="tg-031e">$</td>
<td class="tg-031e">ACCEPT</td>
</tr>
</table>
<br>
<p>There are several variants of shift-reduce parsing like the LR(1),
SLR(1) and LALR(1) parsing methods. The notion of valid shift or a valid reduce
depends on the particular parsing method and can be fairly involved.
We will see how routine situations like precedence and associativity of operators can be easily handled when you are using YACC.
YACC uses an <a href="http://en.wikipedia.org/wiki/LALR_parser">LALR(1) parsing method</a>. An understanding of the general
principles of shift-reduce parsing at the level presented here will be sufficient for most of this project. </p>
</article>
<div class="up grid col-one-third" style="float:right">
<a href="#navtop" title="Go back up"> top ↑</a>
</div>
<article id="navinfixtopostfix" class="detail">
<h2>Infix to Postfix program</h2>
<p> When yacc_file.y is fed to YACC, it generates a y.tab.c file.
When compiled, this program yields a <a href="#navintro">parser</a>.
The generated parser uses shift-reduce parsing to parse the given input.
Yacc copies the C declarations (in the Declaration section of input_file.y) and all
the auxiliary functions (in the Auxiliary functions section of input_file.y) directly into y.tab.c without any modification.
In addition to these, YACC generates the definition of yyparse() in y.tab.c.
</p>
<p>It is important to understand that, y.tab.c contains the following :
</p>
<p>
<li>1. The C declarations from the input_file.y file </li>
<li>2. Generated yyparse() definition </li>
<li>3. All the auxiliary functions from the input_file.y </li>
<p>Recall our <a href="#navexy0">infix to postfix program</a>.</p>
<p>Here is a Sample Input and Output:</p>
<div id="navsam1">
<pre>
I: 2+3*(4+5)
O: NUM1 NUM2 NUM3 NUM4 + * +
</pre>
</div>
<p>When the expression 2+3 is fed as the input to the generated parser,
the main() function in the auxiliary functions section invokes yyparse() as below: (The code for main() from the example is copied below) </p>
<pre>
main()
{
yyparse();
return 1;
}
</pre>
As noted earlier, yyparse() invokes yylex() to read tokens from the input.
For example, when yylex() reads the input 2 and returns the token DIGIT (code of yylex() shown below)
<pre>
yylex()
{
int c;
c = getchar();
if(isdigit(c)) /* Every time a number is found in the input stream,
yylex() increments pos and returns a token DIGIT */
{
pos++;
return DIGIT;
}
return c; /* If any character other than a number is found,
yylex() simply returns the character itself to yyparse() */
}
</pre>
<p>NOTE: As pos was initialized to 0, it holds the value 1 after returning the first DIGIT, 2 after returning the second DIGIT and so on.
</p>
<p>yyparse() is the function that parses the given input using shift-reduce parsing.
When the reduction of a handle takes place, yyparse() executes the action
(specified in the action part of the rule) corresponding to the handle's production in the yacc program.
On successful parsing of the given input, yyparse() returns 0.
If yyparse() fails to parse the given input, it returns 1.
</p>
<p>A generalized algorithm of yyparse() would look like: </p>
<pre>
Initialize the stack with the end-marker $
new_token = yylex() /* read the first token from the input */
while (true)
switch(parser_action(stack, new_token))
case 'reduce':
pop the handle from stack, replace it with the
head of the handle's production.Execute action
part in the yacc file corresponding to the handle's production
case 'shift':
push new_token into the stack.
new_token = yylex() /* read the next token from the input */
case 'accept':
return 0
case 'error':
return 1
</pre>
The following table summarizes the parsing process in every iteration of the above algorithm.
<br><br>
<table class="tg">
<tr>
<th class="tg-e3zv">Input buffer<br></th>
<th class="tg-e3zv">new_ token<br></th>
<th class="tg-e3zv">parser_action() returns<br></th>
<th class="tg-e3zv">Stack contents after parser-action <br></th>
<th class="tg-e3zv">Action executed by yyparse()<br></th>
<th class="tg-e3zv">Output</th>
</tr>
<tr>
<td class="tg-031e">1+2$</td>
<td class="tg-031e">DIGIT</td>
<td class="tg-031e">_</td>
<td class="tg-031e">_</td>
<td class="tg-031e">_</td>
<td class="tg-031e">_</td>
</tr>
<tr>
<td class="tg-031e">1+2$</td>
<td class="tg-031e">DIGIT</td>
<td class="tg-031e">SHIFT</td>
<td class="tg-031e">DIGIT $<br></td>
<td class="tg-031e">_</td>
<td class="tg-031e">_</td>
</tr>
<tr>
<td class="tg-031e">+2$</td>
<td class="tg-031e">+</td>
<td class="tg-031e">REDUCE</td>
<td class="tg-031e">expr $<br></td>
<td class="tg-031e">printf("NUM%d", pos);</td>
<td class="tg-031e">NUM1</td>
</tr>
<tr>
<td class="tg-031e">+2$</td>
<td class="tg-031e">+</td>
<td class="tg-031e">SHIFT</td>
<td class="tg-031e">+ expr $<br></td>
<td class="tg-031e">_</td>
<td class="tg-031e">NUM1</td>
</tr>
<tr>
<td class="tg-031e">2$</td>
<td class="tg-031e">DIGIT</td>
<td class="tg-031e">SHIFT</td>
<td class="tg-031e">DIGIT + expr $<br></td>
<td class="tg-031e">_</td>
<td class="tg-031e">NUM1</td>
</tr>
<tr>
<td class="tg-031e">$</td>
<td class="tg-031e">$</td>
<td class="tg-031e">REDUCE</td>
<td class="tg-031e">expr + expr $<br></td>
<td class="tg-031e">printf("NUM%d", pos);</td>
<td class="tg-031e">NUM1 NUM2<br></td>
</tr>
<tr>
<td class="tg-031e">$</td>
<td class="tg-031e">$</td>
<td class="tg-031e">REDUCE</td>
<td class="tg-031e">expr $<br></td>
<td class="tg-031e">printf("+ ");<br></td>
<td class="tg-031e">NUM1 NUM2 +<br></td>
</tr>
<tr>
<td class="tg-031e">$</td>
<td class="tg-031e">$<br></td>
<td class="tg-031e">ACCEPT</td>
<td class="tg-031e">expr $<br></td>
<td class="tg-031e">_</td>
<td class="tg-031e">NUM1 NUM2 +<br></td>
</tr>
</table>
</p>
<br>
<br>
</article>
<div class="up grid col-one-third" style="float:right">
<a href="#navtop" title="Go back up"> top ↑</a>
</div>
<article id="navconflict" class="detail">
<h2>CONFLICTS IN PARSING USING YACC</h2>
<p>As noted earlier, YACC uses the shift-reduce parsing methodology. Conflicts arise when the parser is unable to make a decision on the action to execute.
These conflicts are practically of two-types: shift/reduce conflict and reduce/reduce conflict.
</p>
<h4>5.1.   resolving shift/reduce conflicts</h4>
<p>When the parser cannot decide whether to shift or to
reduce in a configuration where both the actions seem to be viable options.
Consider the following grammar:</p>
<pre>
expr : expr '+' expr
| '(' expr ')'
| '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'
;</pre>
When the above grammar is fed to YACC, it produces a warning as shown below
<div class="syntax">
yacc: 1 shift/reduce conflict
</div>
<p>Let us consider an example to demonstrate a shift-reduce conflict.
Consider an input of 1+2+3 to the parser generated by YACC for the above context free grammar.
The input can be interpreted as [1+2]+3 or 1+[2+3].</p>
<p><big>Case 1: </big>When the parser reaches a configuration of:</p>
<pre>STACK: $ expr+expr</td>  I/P BUFFER: +3 $</pre>
<p>The parser can choose to reduce by reducing the handle expr+expr on top of the stack to expr.</p>
<p><big>Case 2: </big>When the parser reaches the configuration as in Case 1, it could chose to shift instead of reduce, hence resulting in the configuration of:</p>
<pre>STACK: $ expr+expr+expr  I/P BUFFER: $</pre>
<p>Now, the parser can reduce expr+expr on top of the stack to expr, following which the contents of the stack expr +expr can be reduced to the expr.</p>
<p id="associativity">The example showed how the parser faced a conflict on deciding between the shift and reduce actions. Such conflicts are called shift/reduce conflicts. If the parser had chosen to reduce (like in Case 1), the input would be interpreted as [1+2]+3 (left associative). If the parser chooses to shift (like in Case 2), the input would be interpreted as 1+[2+3] (right associative). The difference in the interpretations is the associativity of the '+' operator. As the + operator is left associative, we would want the input to be interpreted as (1+2)+3. This can be done by specifying the associativity of the token '+' using the YACC keyword <b>%left</b> in the Declarations section as shown below:</p>
<div class="syntax">
%left '+'
</div>
<p>
Once this had been done, when the parser faces a conflict it
refers to the declaration and decides to reduce as the token '+' has been declared left associative. Tokens can be declared to be right associative or non-associative by using the YACC keywords <b>%right</b> and <b>%nonassoc</b>. As an example, if you add the production expr -> expr <c>'<'</c> expr then declaring
<div class="syntax">
% nonassoc '<'
</div>
makes the parser return a parser error on inputs like (a<b<c) ).
</p>
<p>
The conflict in our example arises because the grammar is an <a href="http://en.wikipedia.org/wiki/Ambiguous_grammar" target="_blank">ambiguous</a>. Note that, a shift-reduce parser cannot successfully parse ambiguous grammars. To overcome this difficulty, YACC offers certain features like the provision for specifying the associativity
(seen above) and precedence (to be seen below) that allows the use of certain ambiguous grammars.
</p>
<p>
Consider another ambiguous grammar:</p>
<pre>
expr: expr '+' expr
| expr '*' expr
| '(' expr ')'
| '0'|'1'|'2'|'3'|'4'|'5'|'6'|'7'|'8'|'9'
</pre>
When fed to YACC, it produces a warning
<div class="syntax">
yacc: 4 shift/reduce conflicts.
</div>
<p>
The expressions 2+3+5, 2*3+5, 2+3*5 and 2*3*5 are examples that demonstrate
the four different shift reduce conflict cases. In the first example, after
reading 2+3 the parser must do a reduce operation because + is left associative (why?).
In the third expression, the parser should not perform a reduce operation after reading 2+3 because * has
higher precedence over +, whereas, in the second expression, the parser must indeed reduce after reading 2*3 (why?).
Thus, the parser must be told the precedence and associativity of operators to avoid such conflicts. <br><br>
The precedence of these operators can be specified as shown below:
</p>
<pre>
%left '+' /* '+' is left associative */
%left '*' /* '*' is left associative and has higher precedence over '+' */
</pre>
Here '*' gets higher precedence over '+' as it has been listed below the '+' operator.
The declarations for the associativity of operators must be made in increasing order of precedence, with operators declared in each line assuming higher precedence over those declared above.
If more than one tokens are listed on the same line, they will be assigned equal precedence.
<pre>
%left '+' '-'
%left '*' '/'
</pre>
<p>
Here '*' and '/' have the same precedence, but both have higher precedence than '+' and '-'.</p>
<p> YACC resolves shift/reduce conflicts using the precedence and associativity declarations. YACC assigns precedence and associativity for a production as well.<u> A handle's precedence and associativity is the precedence and associativity of
the last token (not non-terminal) in the handle.</u>
</p>
<p>
When YACC encounters a shift/reduce conflict, it shifts if the token in
the input buffer has a greater precedence than the production of the handle on top of
the stack and reduces if the production of the handle on top of the stack has a higher
precedence than the token. If the production and the token have same precedence, it reduces
if the production corresponding to the handle is left associative and shifts if they are right associative.
(NOTE: If the production and token in such a case of equal
precedence occur and they both are non associative, YACC reports an error).
</p>
<table class="tg">
<tr>
<th class="tg-e3zv">STACK</th>
<th class="tg-e3zv">I/P BUFFER<br></th>
<th class="tg-e3zv">PARSER-ACTION EXECUTED<br></th>
</tr>
<tr>
<td class="tg-031e"></td>
<td class="tg-031e">2 + 3 * (4 + 5) $<br></td>
<td class="tg-031e">_</td>
</tr>
<tr>
<td class="tg-031e">$2</td>
<td class="tg-031e">+ 3 * ( 4 + 5 ) $<br></td>
<td class="tg-031e">SHIFT</td>
</tr>
<tr>
<td class="tg-031e">$expr</td>
<td class="tg-031e">+ 3 * ( 4 + 5 ) $</td>
<td class="tg-031e">REDUCE</td>
</tr>
<tr>
<td class="tg-031e">$expr +<br></td>
<td class="tg-031e">3 * ( 4 + 5 ) $</td>
<td class="tg-031e">SHIFT</td>
</tr>
<tr>
<td class="tg-031e">$expr + 3<br></td>
<td class="tg-031e">* ( 4 + 5 ) $</td>
<td class="tg-031e">SHIFT</td>
</tr>
<tr>
<td class="tg-031e">$expr + expr<br></td>
<td class="tg-031e">* ( 4 + 5) $<br></td>
<td class="tg-031e">REDUCE</td>
</tr>
</table><br>
At the last configuration of the above table,
The parser faces a shift reduce configuration. To resolve this the parser refers to the precedence declarations (Assuming precedence has been declared), and finds:
<pre>
%left '+' '-'
%left '*' '/'
</pre>
On finding that the '*' token has a greater precedence than '+', the parser chooses
to shift '*' instead of reducing the handle “expr + expr”. Recall, that a handle's precedence and associativity is the precedence and associativity of the last token in the handle. Hence, the handle “expr+expr” has the same precedence as its last token '+'. On comparing the precedence of “expr + expr” and '*', parser finds that '*' has a
greater precedence, and hence it decides to shift, resulting in the configuration:<br><br>
<table class="tg">
<tr>
<td class="tg-031e">$expr + expr * <br></td>
<td class="tg-031e">( 4 + 5) $<br></td>
<td class="tg-031e">SHIFT</td>
</tr>