Viable Prefix is a prefix of a right-sentential form that does not continue past the right end of the rightmost handle of that sentential form.
This clearly means that a viable prefix has a handle at its rightmost end.Not all prefixes of right sentential form can appear on the stack of a shift reduce parser.
This can be shown with the help of following example.
A=>B+id=>(E)+id (rightmost derivation, sentential form)
Bottom-up parser gives reverse rightmost derivation,so in the above example if we get the string (E)+id during the reverse rightmost derivation then the following operations are performed:
|(E.)+id||( E||shift E|
|(E).+id||( E )||shift )|
|B.+id||B||reduce (E) to B|
|B+.id||B +||shift +|
|B+id.||B + id||shift id|
|A||A||reduce B + id to A|
As we can see in the above table before shifting + to the stack we have reduced (E) to B. So we can only have (, (E, (E) on stack but we cannot have (E)+ on stack because (E) is a handle and the items in the stack cannot exceed beyond the handle.So here (, (E, (E) are all viable prefixes for the handle (E) and only these prefixes are present in stack of shift reduce parser.
So we keep on shifting the items until we reach the handle or an error occurs. Once a handle is reached we reduce it with a non-terminal using the suitable production. Thus viable prefixes help in taking appropriate shift-reduce decisions.As long as stack contains these prefixes there cannot be any error.
All viable prefixes can be recognized by the LR(0) automaton.Therefore the set of viable prefixes for a given SLR(1) parser is a regular language.This combination of stack with finite state machine is in fact a push-down automaton which is actually used to recognize a context-free language.
The following example illustrates all viable prefixes for the given grammar.
S -> AA A -> bA | a
Given string –
As we know that bottom-up parsing is the reverse of rightmost derivation of a string for a given grammar.So we use the reverse rightmost derivation of the string to demonstrate this example.
|S.No.||Reverse Rightmost Derivation with Handles||Viable Prefix||Comments|
|1.||S -> bbbaa||b, bb, bbb, bbba||Here, a is the handle so viable prefix cannot exceed beyond a.|
|2.||S -> bbbAa||b, bb, bbb, bbbA||Here, bA is the handle so viable prefix cannot exceed beyond bA.|
|3.||S -> bbAa||b, bb, bbA||Here also, bA is the handle so viable prefix cannot exceed beyond bA.|
|4.||S -> bAa||b, bA||Here also, bA is the handle so viable prefix cannot exceed beyond bA.|
|5.||S -> Aa||A, Aa||Here, a is the handle so viable prefix cannot exceed beyond a.|
|6.||S -> AA||A, AA||Here, AA is the handle so viable prefix cannot exceed beyond AA.|
Attention reader! Don’t stop learning now. Get hold of all the important CS Theory concepts for SDE interviews with the CS Theory Course at a student-friendly price and become industry ready.