Professional Documents
Culture Documents
Topdownparsing:
Thetopdownconstructionofaparsetreeisdonebystartingwiththe root,labeledwiththestartingnonterminal,andrepeatedlyperformingthe followingtwosteps
1. atnoden,labeledwithnonterminalA,selectoneoftheproductionsforA
andconstruct childrenatnforthesymbolsontherightsideoftheproduction
2. Findthenextnodeatwhichthesubtreeisconstructed. Forsomegrammars,theabovestepscanbeimplementedduringasingleleft torightscanoftheinputstring.Thecurrenttokenbeingscannedontheinput isoftencalledasthelookaheadsymbol.Initiallythelookaheadsymbolisthe firsti.etheleftmosttokenoftheinputstring. Letusconsiderthefollowinggrammar. A>BA |a |aa B> BB |b andnowconsidertheinputstringbbaa
Thetopdownparsingwouldlooklikethisindifferentsteps
1.
input:bbaa,thehighlightedcharacterindicatesthelookahead. 2. A
B 3. A
B B 4. B A B B b
5. input:bbaa
A B
B B
A A B
b
6. input:bbaa
b A B A Baa b
B b
Thisisgeneralformoftopdownparsing,calledrecursivedescent parsingwherebacktrackingmaybeinvolved.Thisisabadtypeof parsingwhichinvolvesrepeatedtryingtogetthecorrectoutput.This canalsobetermedasbruteforcetypeofparsing.Presently,thistype ofparsingisoutdated,justbecausetherearemuchbettermethodsof parsingwhichwewillbediscussinglater. Considerthegrammar: S> cAd|bd A>ab|a
A a
PREDICTIVEPARSING: Thisisatopdownparsingmethodwhereweexecuteasetof recursivesetofprocedurestoprocesstheinput.Aprocedureis associatedwithanonterminalofagrammar.Herethelookahead symbolunambiguouslydeterminestheprocedureselectedforeach nonterminal.Thesequenceofprocedurescalledinprocessingthe inputimplicitlydefinesaparsetreefortheinput. Considerthegrammar: S> cAd|bd A>ab|e PSEUDOCODEforapredictiveparser functionmatch(tokent) { iflookahead=t then lookahead=nexttoken() elseerror }
functionS { iflookaheadisin{c} match(c),A(),match(d); elseiflookaheadisin{b} match(b),match(d); elseiflookaheadisin{a,e} A(); elseerror } functionA { iflookaheadisin{a} match(a),match(b); elseiflookaheadisin{e} match(e); elseiferror }
iflookaheadisin{c} match(c),A(),match(d); onceitmatched'c',thefunctionA()iscalledandchecksoutthatthe nextinputsymbol'e'isthenintheset{e},itexecutesthecode: elseiflookaheadisin{e} match(e); Afterthematchingof'e'isoveritreturnsfromthefunctionA()and matchesthenexttokenwith'd'. someimportantpoints: Predictiveparsingreliesoninformationaboutwhatfirstsymbolscan begeneratedbyrightsideofaproduction.
IfA>isaproduction,thenFIRST(
Also,thisparsingwouldfalterifthereisLEFTRECURSIONinthegrammar. Inthatcasetheparserwillloopforever.
Considertheleftrecursiveproductionexpr>expr+term supposetheprocedureforexprdecidestoapplythisproduction.Therightside
P.NagenderReddy 03CS1021