CD Unit-2 Notes
CD Unit-2 Notes
UNIT-2
SYNTAXANALYSIS
Parser obtains a string of tokens from the lexical analyzer and verifies that it can be generated
by the language for the source program. The parser should report any syntax errors in an
intelligible fashion. The two types of parsers employed are:
1. Topdownparser: whichbuild parsetreesfrom top(root)to bottom(leaves)
2. Bottomupparser:whichbuildparsetreesfromleavesandworkuptheroot.
Thereforetherearetwo types of parsing methods– top-down parsing and bottom-up parsing
ContextfreeGrammars(CFG)
CFGisusedtospecifythesyntaxofalanguage.Agrammarnaturallydescribesthe hierarchical
structure of most program-ming language constructs.
FormalDefinitionofGrammars
Acontext-freegrammarhasfour components:
1. Asetofterminalsymbols,sometimesreferredtoas"tokens."Theterminalsaretheelementary
symbols of the language defined by the grammar.
2. Asetofnonterminals,sometimescalled"syntacticvariables."Eachnon-terminalrepresentsasetof strings
of terminals, in a manner we shall describe.
3. A set of productions, where each production consists of a nonterminal, called the head or left
sideoftheproduction,anarrow,andasequenceofterminalsand1ornonterminals,called thebodyorright
sideof the production. The intuitive intent of a production is to specify one of the written forms of a
construct; if the head nonterminal represents a construct, then the bodyrepresents a written form of
the construct.
.
4. Adesignation ofone of the nonterminalsas thestartsymbol.
Production is for a nonterminal if the nonterminal is the head of the production. A string of
terminalsisasequenceofzeroormoreterminals.Thestringofzeroterminals,writtenas E,iscalled the empty
string.
Derivations
A grammar derives strings by beginning with the start symbol and repeatedly replacing a nonterminal
bythebodyofaproductionforthatnonterminal.Theterminalstringsthatcanbederivedfromthestart symbol
form the language defined by the grammar.
LeftmostandRightmostDerivationofa String
• Leftmostderivation−Aleftmostderivationisobtainedbyapplyingproductiontotheleftmost
variableineachstep.
• Rightmostderivation −Arightmostderivationisobtainedbyapplyingproductiontothe rightmost
variable in each step.
• Example
Letanysetofproduction rulesinaCFG be
X→ X+X |X*X |X|a
overanalphabet{a}.
Theleftmost derivation for thestring"a+a*a"is
X→ X+X→ a+X → a+X*X→a+a*X→a+a*a
Therightmost derivation for theabovestring"a+a*a"is
X→ X*X→X*a→X+X*a→ X+a*a→ a+a*a
DerivationorYield ofaTree
The derivation or the yield of a parse tree is the final string obtained by concatenating the labels of the
leaves ofthetree from leftto right, ignoring theNulls. However,if all theleaves areNull, derivation is
Null.
parse tree pictorially shows how the start symbol of a grammar derives a string in the language. If
nonterminal A has a production A→XYZ , then a parse tree may have an interior node labeled Awith
three children labeled X, Y, and Z, from left to right:
Givenacontext-freegrammar,aparsetreeaccordingtothegrammarisatreewiththefollowing properties:
1. Theroot islabeled bythestart symbol.
2. Eachleafislabeledby a terminalorbye.
3. Eachinteriornodeislabeled by a nonterminal
.
IfAisthenonterminallabelingsomeinteriornodeandXI, Xz, ...,Xnarethelabelsofthechildren of that node
from left to right, then there mustbe a productionA→ X1X2 . . Xn .Here, X1, X2,.
. . , Xn,each stand for a symbol that is either a terminal or a nonterminal. As a special case,
ifA→cis aproduction, then anodelabeled Amay haveasinglechild labeledE
Ambiguity
Agrammar canhavemorethanoneparsetreegeneratingagivenstringofterminals.Suchagrammaris said to be
ambiguous. To show that a grammar is ambiguous, all we need to do is find a terminal string that is the
yield of more than one parse tree. Since a string with more than one parse tree usually has
morethanonemeaning,weneedtodesignunambiguousgrammarsforcompilingapplications,ortouse
ambiguous grammars with additional rules to resolve the ambiguities.
Example::Supposeweusedasinglenonterminalstringanddidnotdistinguishbetweendigitsand lists,
Twoparsetreesfor9-5+2
Example
Ifthereisagrammar
G:N={S, A,B} T ={a,b} P ={S→ AB, A→a, B → b}
HereSproducesAB,and wecan replaceAbya, andBbyb.Here,theonly acceptedstringisab,i.e., L(G) = {ab}
.
Writinga grammar
Agrammarconsistsofanumberofproductions.Eachproductionhasanabstractsymbol
calledanonterminal asits left-handside,andasequenceofoneormorenonterminal andterminalsymbols as
itsright-hand side. For each grammar, theterminal symbols aredrawn from a specified alphabet.
Startingfromasentenceconsistingofasingledistinguishednonterminal,called
thegoalsymbol,agivencontext-freegrammarspecifiesa language,namely,thesetof possiblesequences of
terminal symbols that can result from repeatedly replacing any nonterminal in the sequence with a
right-hand side of a production for which the nonterminal is the left-hand side.
Thereare fourcategories inwritingagrammar:
1. LexicalVsSyntaxAnalysis
2. Eliminatingambiguousgrammar.
3. Eliminatingleft-recursion
4. Left-factoring.
Eachparsingmethodcanhandlegrammarsonlyofacertainformhence,theinitialgrammarmayhave to be
rewritten to make it parsable
1. LexicalVsSyntax Analysis
Reasonsforusing theregularexpression todefinethelexicalsyntax of alanguage
a) Regularexpressionsprovideamoreconciseandeasiertounderstandnotationfor tokensthan
grammars.
b) Thelexicalrulesofalanguagearesimpleandtodescribethem,wedonotneednotationas powerful as
grammars.
c) EfficientlexicalanalyzerscanbeconstructedautomaticallyfromREthanfromgrammars.
d) Separatingthesyntacticstructureofalanguageintolexicalandnonlexicalpartsprovidesa convenient
way of modularizing the front end into two manageable-sized components.
2. Eliminatingambiguousgrammar.
Ambiguityofthegrammarthatproducesmorethanoneparsetreeforleftmostorrightmost
derivation can be eliminated by re-writing the grammar.
Considerthis example,
G:stmt→ifexpr then stmt
|ifexpr thenstmtelsestmt
|other
Thisgrammarisambiguoussincethestring ifE1thenifE2thenS1elseS2hasthe followingtwo parse trees
for leftmost derivation
.
Thegeneralruleis“Matcheach elsewiththeclosestunmatchedthen.Thisdisambiguatingrulecanbe
useddirectlyinthegrammar,
Toeliminateambiguity,thefollowinggrammarmaybeused:
stmt→matched|unmatchedstmt
matched→ifexprstmtthenmatchedelsematchedstmt|other
unmatched→ifexprthenstmt|ifexprthenmatchedelseunmatchedstmt
3. Eliminatingleft-recursion
.
Becausewetrytogeneratealeftmostderivationbyscanningtheinputfromlefttoright,grammarsofthe formA → A x
may cause endless recursion.Such grammars are called left-recursive and they must be transformed if we want
to use a top-down parser.
◼ Agrammarisleftrecursiveifforanon-terminalA,thereisaderivationA+A
◼ Toeliminatedirectleftrecursionreplace
1) A→ A| with A’→A’|
2) A→A1|A2|...|Am|1|2 |...|n
with
A→1B|2B|...|nB
B→1B|2B|...|mB |
4. Left-factoring
Leftfactoringisagrammartransformationthatisusefulforproducingagrammarsuitableforpredictive
parsing.Whenitisnotclearwhichoftwoalternativeproductionstousetoexpandanon-terminalA,we can rewrite
the A-productions to defer the decision until we have seen enough of the input to make the right choice.
◼ ConsiderS →if E thenS else S |if E then S
◼ Whichofthetwoproductionsshouldweusetoexpandnon-terminalSwhenthenext token is
if?
Wecan solve thisproblem by factoringout thecommonpart in theserules.
A→1|2|...|n|
becomes
A→B|
B →1|2|...|n
Considerthegrammar , G: S→iEtS|iEtSeS |a
E→ b
Leftfactored,thisgrammarbecomes
S→iEtSS’|a S’
→ eS |ε
E→b
PARSING
It is the process of analyzing a continuous stream of input in order to determine its grammatical
structure with respect to a given formal grammar.
Typesof parsing:
1. Topdown parsing
2. Bottom up parsing
Top-downparsing:Aparsercanstartwiththestartsymbolandtrytotransformittothe input
string. Example : LL Parsers.
.
Bottom-upparsing:Aparser can startwithinputandattemptto rewriteitintothestart symbol.
Example : LRParsers.
TOP-DOWNPARSING
Itcanbeviewedasanattempttofindaleft-mostderivationforaninputstringoran attempt to
construct a parse tree for the input starting from the root to the leaves.
TypesofTOP-DOWNPARSING
1. Recursivedescentparsing
2. Predictive parsing
RECURSIVEDESCENT PARSING
Recursive descent is a top-down parsing technique that constructs the parse tree from the top and the
inputisreadfromlefttoright.Itusesprocedures foreverynon-terminalentity.Thisparsingtechnique
recursively parses the input to make a parse tree, which may or may not require back-tracking. But the
grammar associated with it (if not left factored) cannot avoid back-tracking. A form of recursive-
descent parsing that does not require any back-tracking is known as predictive parsing.
Thisparsingtechniqueisregardedrecursiveasitusescontext-freegrammarwhichisrecursivein nature.
Thisparsingmethodmayinvolvebacktracking.
Examplefor :backtracking
ConsiderthegrammarG: S→ cAd
A→ab|a
andthe input string w=cad.
Theparsetreecan beconstructedusing thefollowing top-down approach :
Step1:
InitiallycreateatreewithsinglenodelabeledS.Aninputpointerpointsto‘c’,thefirstsymbolofw.
ExpandthetreewiththeproductionofS.
Step2:
The leftmost leaf ‘c’ matches the first symbol of w, so advance the input pointer to the second
symbolof w ‘a’ and consider the next leaf ‘A’. Expand A using the first alternative.
.
Step3:
The second symbol ‘a’ of w also matches with second leaf of tree. So advance the input pointer to third
symbol of w ‘d’. But the third leaf of tree is b which does not match with the input symbol d. Hence
discard the chosen production and reset the pointer to second backtracking.
Step4:Nowtrythesecondalternativefor A.
Predictiveparsing
It is possible to build a nonrecursive predictive parser by maintaining a stack explicitly, rather than
implicitly via recursive calls. The key problem during predictive parsing is that of determining the
productiontobeappliedforanonterminal.Thenonrecursiveparserinfigurelooksuptheproductionto be applied
in parsing table. In what follows, we shall see how the table can be constructed directly from certain
grammars.
A table-driven predictive parser has an input buffer, a stack, a parsing table, and an output
stream. The input buffer contains the string to be parsed, followed by $, a symbol used as a right
endmarkertoindicatetheendoftheinputstring.Thestackcontainsasequenceofgrammarsymbols
.
with $ on the bottom, indicating the bottom of the stack. Initially, the stack contains the start symbol of
thegrammarontopof$.TheparsingtableisatwodimensionalarrayM[A,a]whereAisanonterminal, and a is a
terminal or the symbol $. The parser is controlled by a program that behaves as follows. The program
considers X, the symbol on the top of the stack, and a, the current input symbol. These two symbols
determine the action of the parser. There are three possibilities.
Implementationofpredictive parser:
1. Eliminationofleftrecursion,leftfactoringandambiguous grammar.
2. ConstructFIRST()andFOLLOW()forallnon-terminals.
3. Constructpredictiveparsingtable.
4. Parsethegiven inputstring usingstack andparsing table
AlgorithmforNonrecursivepredictive parsing.
Method. Initially, theparseris in aconfiguration in which it has $S on thestack with S, thestart symbol of
G on top, and w$ in the input buffer. The program that utilizes the predictive parsing table M to produce
a parse for the input is shown in Fig.
FIRSTAND FOLLOW
Theconstruction ofapredictiveparsing tableis aidedby twofunctions associatedwith a grammar:
1. FIRST
2. FOLLOW
RulesforFIRST( ):
1. IfXisterminal,thenFIRST(X)is{X}.
2. IfX→ εisaproduction, thenadd ε to FIRST(X).
3. IfXis non-terminaland X→ aαisaproduction thenadd ato FIRST(X).
4. IfXisnon-terminalandX→Y1Y2…Ykisaproduction,thenplaceainFIRST(X)iffor some i, a
is in FIRST(Yi), and ε is in all of FIRST(Y1),…,FIRST(Yi-1);that is,
Y1,….Yi-1=>ε.IfεisinFIRST(Yj)for allj=1,2,..,k,thenaddεtoFIRST(X).
RulesforFOLLOW( ):
1. IfSis astartsymbol, thenFOLLOW(S) contains $.
2. IfthereisaproductionA→αBβ,theneverythinginFIRST(β)exceptεisplaced in
follow(B).
3. IfthereisaproductionA→αB,oraproductionA→αBβwhereFIRST(β)contains ε, then
everything in FOLLOW(A) is in FOLLOW(B).
Algorithmforconstructionofpredictiveparsingtable:
Input : Grammar G
Output:ParsingtableM
Method :
1. ForeachproductionA → αofthegrammar, do steps2and 3.
2. ForeachterminalainFIRST(α),addA→αtoM[A,a].
3. IfεisinFIRST(α),addA→αtoM[A,b]foreachterminalbinFOLLOW(A).Ifεisin FIRST(α) and $ is
in FOLLOW(A) , add A → α to M[A, $].
4. Makeeach undefined entryofM beerror.
.
Example:
Considerthefollowinggrammar:
E→E+T|T
T→T*F|F
F→(E)|id
Aftereliminatingleft-recursionthegrammaris
E→TE’
E’→+TE’|ε T
→FT’
T’→*FT’|ε F
→ (E)|id
First():
FIRST(E)={(,id}
FIRST(E’)={+,ε}
FIRST(T)={(,id}
FIRST(T’)={*,ε}
FIRST(F)={( ,id}
Follow():
FOLLOW(E)={$,)}
FOLLOW(E’)={$,)}
FOLLOW(T)={+,$,)}
FOLLOW(T’)={+,$,)}
FOLLOW(F)={+,*,$ ,)}
Predictiveparsing Table
.
Stack Implementation
-24 -
.
2.5.5.LL(1) GRAMMAR
The parsing table algorithm can be applied to any grammar G to produce a parsing table M.
For some Grammars, for example if G is left recursive or ambiguous, then M will have at
least one multiply-defined entry. A grammar whose parsing table has no multiply defined
entries is said to be LL(1). It can be shown that the above algorithm can be used to produce
for every LL(1) grammar G, a parsing table M that parses all and only the sentences of G.
LL(1) grammars have several distinctive properties. No ambiguous or left recursive grammar
can be LL(1). There remains a question of what should be done in case of multiply defined
entries. One easy solution is to eliminate all left recursion and left factoring, hoping to
produce a grammar which will produce no multiply defined entries in the parse tables.
Unfortunately there are some grammars which will give an LL(1) grammar after any kind of
alteration. In general, there are no universal rules to convert multiply defined entries into
single valued entries without affecting the language recognized by the parser.
The main difficulty in using predictive parsing is in writing a grammar for the source
language such that a predictive parser can be constructed from the grammar. Although
leftrecursion elimination and left factoring are easy to do, they make the resulting grammar
hard toreadanddifficulttousethetranslationpurposes.Toalleviatesomeofthisdifficulty,a
common organization for a parser in a compiler is to use a predictive parser for control
constructs and to use operator precedence for expressions.however, if an lr parser
generatorisavailable,onecangetallthebenefitsofpredictiveparsingandoperatorprecedenceautom
atically.
2.5.6.ERRORRECOVERYINPREDICTIVE PARSING
The stack of a nonrecursive predictive parser makes explicit the terminals and nonterminals
that the parser hopes to match with the remainder of the input. We shall therefore refer to
symbols on the parser stack in the following discussion. An error is detected duringpredictive
parsing when the terminal on top of the stack does not match the next inputsymbol or when
nonterminal A is on top of the stack, a is the next input symbol, and the parsing table entry
M[A,a] is empty.
Considererrorrecoverypredictiveparsingusingthefollowingtwomethods
Panic-Mode recovery
PhraseLevel recovery
Panic-mode error recovery is based on the idea of skipping symbols on the input until a
token in a selected set of synchronizing tokens appears. Its effectiveness depends on the
choice of synchronizing set. The sets should be chosen so that the parser recovers quickly
from errors that are likely to occur in practice.
As a starting point, we can place all symbols in FOLLOW(A) into the synchronizing set for
nonterminal A. If we skip tokens until an element of FOLLOW(A) is seen and pop A from
the stack, it is likely that parsing can continue.
It is not enough to use FOLLOW(A) as the synchronizingset for A. Fo example , if
semicolons terminate statements, as in C, then keywords that begin statements may not
appear in the FOLLOW set of the nonterminal generating expressions. A missing semicolon
after an assignment may therefore result in the keyword beginning the next statement being
skipped. Often, there is a hierarchica structure on constructs in a language; e.g., expressions
appearwithinstatement,whichappearwithinbblocks,andsoon.Wecanaddtothe
.
synchronizing set of a lower construct the symbols that begin higher constructs. For
example, we might add keywords that begin statements to the synchronizing sets for the
nonterminals generaitn expressions.
If a nonterminal can generate the empty string, then the production deriving e can be
used as a default. Doing so may postpone some error detection, but cannot cause an errorto
be missed. Thisapproach reduces the number of nonterminals that have to be considered
during error recovery.
If a terminal on top of the stack cannot be matched, a simple idea is to pop the
terminal, issue a message saying that the terminal was inserted, and continue parsing. In
effect, this approach takes the synchronizing set of a token to consist of all other tokens.
PhraseLevelrecovery
BOTTOM-UPPARSING
Constructingaparsetree foraninputstringbeginningattheleavesandgoingtowardstherootis called
bottom-up parsing. A general type of bottom-up parser is a shift-reduce parser.
SHIFT-REDUCEPARSING
Shift-reduceparsingisatypeofbottom-upparsingthatattemptstoconstructaparsetreefor an input
string beginning at the leaves (the bottom) and working up towards the root (the top).
Example:
Considerthegrammar:S→ aABe
A→ Abc|b
B→d
Thesentencetobe recognizedis abbcde.
REDUCTION(LEFTMOST) RIGHTMOSTDERIVATION
abbcde (A → b) S→aABe
aAbcde(A→Abc) → aAde
aAde(B → d) → aAbcde
aABe(S→ aABe) → abbcde
S
Thereductions traceout theright-mostderivation in reverse.
.
Handles: A handle of a string is a substring that matches the right side of a production, and
whose reduction to the non-terminal on the left side of the production represents one step
along the reverse of a rightmost derivation.
Example:
Considerthe grammar:
E→E+E
E→E*E
E→(E)
E→id
Andtheinputstringid1+id2*id3 The
rightmost derivation is :
E→E+E
→ E+E*E
→ E+E*id3
→ E+id2*id3
→ id1+id2*
Intheabovederivationthe underlinedsubstringsarecalled handles.
Handlepruning:
Arightmostderivationinreversecanbeobtainedby“handlepruning”.(i.e.)ifwisasentence or string
of the grammar at hand, then w = γn, where γn is the nth right sentential form of
somerightmost derivation.
Actionsinshift-reduceparser:
• shift-Thenext input symbol isshifted onto thetopof the stack.
• reduce-Theparserreplaces thehandlewithin astack witha non-terminal.
• accept-Theparserannouncessuccessful completionof parsing.
• error-Theparserdiscoversthatasyntaxerrorhasoccurredandcallsanerror recoveryroutine.
Conflictsinshift-reduce parsing:
Therearetwoconflicts thatoccurinshift-reduceparsing:
1. Shift-reduceconflict:Theparsercannotdecide whethertoshiftortoreduce.
2. Reduce-reduceconflict:Theparser cannotdecidewhichofseveralreductionsto make.
.
Stackimplementationofshift-reduceparsing:
1. Shift-reduceconflict:
Example:
Considerthe grammar:
E→E+E|E*E|id and input id+id*id
.
2. Reduce-reduceconflict:
Considerthegrammar: M→R+R|R+c|R
R→c
input c+c
INTRODUCTIONTO LR PARSERS
An efficient bottom-up syntax analysis technique that can be used CFG is called LR(k) parsing.
The ‘L’ is for left-to-right scanning of the input, the ‘R’ for constructing a rightmost derivation in
reverse, and the ‘k’ for the number of input symbols. When ‘k’ is omitted, it is assumed to be 1.
Advantagesof LR parsing:
1. ItrecognizesvirtuallyallprogramminglanguageconstructsforwhichCFGcanbewritten.
2. Itisanefficientnon-backtrackingshift-reduce parsingmethod.
3. AgrammarthatcanbeparsedusingLRmethodisapropersupersetofagrammarthat can be
parsed with predictive parser
4. Itdetectsa syntacticerroras soonas possible.
DrawbacksofLR method:
ItistoomuchofworktoconstructaLRparserbyhandforaprogramminglanguagegrammar.
Aspecializedtool,called aLRparsergenerator,isneeded.Example:YACC.
Typesof LR parsing method:
1. SLR-Simple LR
Easiesttoimplement,leastpowerful.
2. CLR-CanonicalLR
Mostpowerful,mostexpensive.
3. LALR-Look-AheadLR
Intermediateinsizeandcost betweentheothertwo methods.
.
a. Thedriverprogramisthe sameforallLRparser.
b. Theparsingprogram readscharactersfrom aninputbuffer oneata time.
c. Theprogramusesastacktostore a stringofthe form s0X1s1X2s2…Xmsm,wheresmis
ontop. Each Xiis agrammarsymbol and eachsi is a state.
d. Theparsing tableconsistsof two parts :action and goto functions.
LRParsing algorithm:
Input:AninputstringwandanLRparsingtablewithfunctionsactionandgotoforgrammarG. Output: If w is in
L(G), a bottom-up-parse for w; otherwise, an error indication.
Method:Initially,theparser hass0on itsstack,wheres0istheinitial state,andw$ intheinput buffer.
Theparserthenexecutes thefollowingprogram:
.
setipto pointtothe firstinput symbolofw$; repeatforever begin
let s bethe state on top of thestack andathe symbol pointed to by ip;
ifaction[s,a] =shifts’then begin
push a then s’ on top of the stack; advance ip to the next input symbol end
elseifaction[s,a]=reduceA→βthenbeginpop2*|β|symbolsoffthestack;
lets’bethestatenowontopofthestack;pushAthengoto[s’,A] ontopofthestack;outputthe
productionA→β
end
elseifaction[s,a]=acceptthen return
elseerror()
end
CONSTRUCTINGSLR(1)PARSING TABLE
ToperformSLRparsing,takegrammarasinput anddothe following:
1. FindLR(0) items.
2. Completingthe closure.
3. Computegoto(I,X),where,Iissetofitems and Xisgrammar symbol.
LR(0) items:
AnLR(0)itemofagrammarGisaproductionofGwithadotatsomepositionoftherightside.For
example,productionA →XYZ yieldsthefouritems :
A→.XYZ
A→X.YZ
A→XY.Z A
→ XYZ .
Closure operation:
IfIisasetofitemsforagrammarG,thenclosure(I)isthesetofitemsconstructedfromIby the two
rules:
1. Initially,everyitem inIis addedto closure(I).
2. IfA→ α. Bβ isin closure(I)andB → γ isa production, then add theitem B → . γ to I, if it
isnotalready there.Weapplythisrule untilno morenewitems canbeaddedto closure(I).
Goto operation:
ExampleonSLR(1)Grammar
S→E
E → E +T|T
T→T*F|F F
→ id
AddAugmentProductionandinsert'•'symbolatthefirstpositionforeveryproductioninG S` → •E
E→•E+T E
→ •T
T→•T*F T
→ •F
F→ •id
I0 State:
I0 = Closure(S` → •E)
AddallproductionsstartingwithEintoI0Statebecause"."isfollowedbythenon-terminal.So,theI0 State
becomes
I0 = S` → •E
E→•E+T E
→ •T
I1=Goto(I0,E)=closure(S`→E•,E→E•+T) I2= Go
to (I0, T) = closure (E → T•T, T• → * F) I3= Go to
(I0, F) = Closure ( T → F• ) = T → F• I4= Go to
(I0, id) = closure ( F → id•) = F → id• I5= Go to
(I1, +) = Closure (E → E +•T)
I5 = E → E +•T
T→•T*F T
→ •F
F→ •id
I6 = T → T * •F
F→ •id
SLR (1)Table
Explanation:
First(E)=First(E+T)∪ First(T)
First (T) =First (T * F) ∪ First (F)
First (F) = {id}
First(T)={id}
First(E)={id}
Follow(E)=First(+T)∪ {$}={+,$}
Follow (T) = First (*F) ∪ First (F)
={*, +, $}
Follow(F)={*,+,$}
1) I1 containsthefinalitemwhichdrivesS→E•andfollow(S)={$},soaction{I1,$}= Accept
2) I2 containsthefinalitemwhichdrivesE→T•andfollow(E)={+,$},soaction{I2,+}=R2,
action{I2,$}=R2
3) I3 containsthefinalitemwhichdrivesT→F•andfollow(T)={+,*,$},soaction{I3,+}=
R4,action{I3,*}=R4,action{I3, $}=R4
4) I4 containsthefinalitem whichdrivesF→id•andfollow(F)={+,*,$}, soaction{I4,+}=
R5,action{I4,*} =R5, action{I4,$}=R5
5) I7 containsthefinalitemwhichdrivesE→E+T•andfollow(E) ={+,$},soaction{I7,+}=
R1,action{I7,$}=R1
6) I8 containsthefinalitemwhichdrivesT→T*F•andfollow(T) ={+,*,$},soaction{I8,+}
=R3,action {I8,*} =R3, action{I8, $}=R3.
-27 -