Docsity

Skeleton Parser - Compiler Construction - Lecture Notes, Study notes of Compiler Construction

Toggle sidebar
bg1
Sohail Aslam Compiler Construction Notes Set:2-1
1
L
Le
ec
ct
tu
ur
re
e
2
28
8
LR(1) Skeleton Parser
stack.push(dummy); stack.push(0);
done = false; token = scanner.next();
while (!done) {
s = stack.top();
if( Action[s,token] == “reduce A→β”) {
stack.pop(2×|β|);
s = stack.top();
stack.push(A);
stack.push(Goto[s,A]);
}
else if( Action[s,token] == “shift i”){
stack.push(token); stack.push(i);
token = scanner.next();
}
else if(Action[s,token] == “accept”
&& token == “$” )
done = true;
else
report error and recover;
}
report success;
Shift/Reduce Conflicts
If a DFA states contains both [X → α•aβ, b] and [Y → γ•, a]
Then on input “a” we could either shift into state [X → αa•β,b], or reduce with Y → γ.
This is called a shift-reduce conflict. Typically, this is due to ambiguities in the grammar.
The classic example of a shift-reduce conflict is the dangling else. Consider the grammar
stmt → if E then stmt
| if E then stmt else stmt
We will have DFA state containing
[stmt → if E then stmt•, else]
[stmt → if E then stmt •else stmt, x]
If else follows, we can shift
[stmt → if E then stmt else • stmt, x]
pf2

Partial preview of the text

Download Skeleton Parser - Compiler Construction - Lecture Notes and more Study notes Compiler Construction in PDF only on Docsity!

Sohail Aslam Compiler Construction Notes Set:2-

Le Leccttuurree 2 288

LR(1) Skeleton Parser

stack.push(dummy); stack.push(0); done = false; token = scanner.next(); while (!done) { s = stack.top(); if( Action[s,token] == “reduce A→β”) { stack.pop(2×|β|); s = stack.top(); stack.push(A); stack.push(Goto[s,A]); } else if( Action[s,token] == “shift i”){ stack.push(token); stack.push(i); token = scanner.next(); } else if(Action[s,token] == “accept” && token == “$” ) done = true; else report error and recover; } report success;

Shift/Reduce Conflicts

If a DFA states contains both [X → α•aβ, b] and [Y → γ•, a] Then on input “a” we could either shift into state [X → αa•β,b], or reduce with Y → γ. This is called a shift-reduce conflict. Typically, this is due to ambiguities in the grammar. The classic example of a shift-reduce conflict is the dangling else. Consider the grammar

stmt → if E then stmt | if E then stmt else stmt

We will have DFA state containing

[stmt → if E then stmt•, else] [stmt → if E then stmt • else stmt, x]

If else follows, we can shift

[stmt → if E then stmt else • stmt, x]

Sohail Aslam Compiler Construction Notes Set:2-

or reduce

[stmt → if E then stmt•, else]

Typical action is shift so that else matches with most recent if.