bison.texinfo 190 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159
  1. \input texinfo @c -*-texinfo-*-
  2. @comment %**start of header
  3. @setfilename bison.info
  4. @settitle Bison 1.20
  5. @setchapternewpage odd
  6. @c SMALL BOOK version
  7. @c This edition has been formatted so that you can format and print it in
  8. @c the smallbook format.
  9. @c @smallbook
  10. @c next time, consider using @set for edition number, etc...
  11. @c Set following if you have the new `shorttitlepage' command
  12. @c @clear shorttitlepage-enabled
  13. @c @set shorttitlepage-enabled
  14. @c ISPELL CHECK: done, 14 Jan 1993 --bob
  15. @c Check COPYRIGHT dates. should be updated in the titlepage, ifinfo
  16. @c titlepage; should NOT be changed in the GPL. --mew
  17. @iftex
  18. @syncodeindex fn cp
  19. @syncodeindex vr cp
  20. @syncodeindex tp cp
  21. @end iftex
  22. @ifinfo
  23. @synindex fn cp
  24. @synindex vr cp
  25. @synindex tp cp
  26. @end ifinfo
  27. @comment %**end of header
  28. @ifinfo
  29. This file documents the Bison parser generator.
  30. Copyright (C) 1988, 1989, 1990, 1991, 1992 Free Software Foundation, Inc.
  31. Permission is granted to make and distribute verbatim copies of
  32. this manual provided the copyright notice and this permission notice
  33. are preserved on all copies.
  34. @ignore
  35. Permission is granted to process this file through Tex and print the
  36. results, provided the printed document carries copying permission
  37. notice identical to this one except for the removal of this paragraph
  38. (this paragraph not being relevant to the printed manual).
  39. @end ignore
  40. Permission is granted to copy and distribute modified versions of this
  41. manual under the conditions for verbatim copying, provided also that the
  42. sections entitled ``GNU General Public License'' and ``Conditions for
  43. Using Bison'' are included exactly as in the original, and provided that
  44. the entire resulting derived work is distributed under the terms of a
  45. permission notice identical to this one.
  46. Permission is granted to copy and distribute translations of this manual
  47. into another language, under the above conditions for modified versions,
  48. except that the sections entitled ``GNU General Public License'',
  49. ``Conditions for Using Bison'' and this permission notice may be
  50. included in translations approved by the Free Software Foundation
  51. instead of in the original English.
  52. @end ifinfo
  53. @ifset shorttitlepage-enabled
  54. @shorttitlepage Bison
  55. @end ifset
  56. @titlepage
  57. @title Bison
  58. @subtitle The YACC-compatible Parser Generator
  59. @subtitle December 1992, Bison Version 1.20
  60. @author by Charles Donnelly and Richard Stallman
  61. @page
  62. @vskip 0pt plus 1filll
  63. Copyright @copyright{} 1988, 1989, 1990, 1991, 1992 Free Software
  64. Foundation
  65. @sp 2
  66. Published by the Free Software Foundation @*
  67. 675 Massachusetts Avenue @*
  68. Cambridge, MA 02139 USA @*
  69. Printed copies are available for $15 each.@*
  70. ISBN-1-882114-30-2
  71. Permission is granted to make and distribute verbatim copies of
  72. this manual provided the copyright notice and this permission notice
  73. are preserved on all copies.
  74. @ignore
  75. Permission is granted to process this file through TeX and print the
  76. results, provided the printed document carries copying permission
  77. notice identical to this one except for the removal of this paragraph
  78. (this paragraph not being relevant to the printed manual).
  79. @end ignore
  80. Permission is granted to copy and distribute modified versions of this
  81. manual under the conditions for verbatim copying, provided also that the
  82. sections entitled ``GNU General Public License'' and ``Conditions for
  83. Using Bison'' are included exactly as in the original, and provided that
  84. the entire resulting derived work is distributed under the terms of a
  85. permission notice identical to this one.
  86. Permission is granted to copy and distribute translations of this manual
  87. into another language, under the above conditions for modified versions,
  88. except that the sections entitled ``GNU General Public License'',
  89. ``Conditions for Using Bison'' and this permission notice may be
  90. included in translations approved by the Free Software Foundation
  91. instead of in the original English.
  92. @sp 2
  93. Cover art by Etienne Suvasa.
  94. @end titlepage
  95. @page
  96. @node Top, Introduction, (dir), (dir)
  97. @ifinfo
  98. This manual documents version 1.20 of Bison.
  99. @end ifinfo
  100. @menu
  101. * Introduction::
  102. * Conditions::
  103. * Copying:: The GNU General Public License says
  104. how you can copy and share Bison
  105. Tutorial sections:
  106. * Concepts:: Basic concepts for understanding Bison.
  107. * Examples:: Three simple explained examples of using Bison.
  108. Reference sections:
  109. * Grammar File:: Writing Bison declarations and rules.
  110. * Interface:: C-language interface to the parser function @code{yyparse}.
  111. * Algorithm:: How the Bison parser works at run-time.
  112. * Error Recovery:: Writing rules for error recovery.
  113. * Context Dependency:: What to do if your language syntax is too
  114. messy for Bison to handle straightforwardly.
  115. * Debugging:: Debugging Bison parsers that parse wrong.
  116. * Invocation:: How to run Bison (to produce the parser source file).
  117. * Table of Symbols:: All the keywords of the Bison language are explained.
  118. * Glossary:: Basic concepts are explained.
  119. * Index:: Cross-references to the text.
  120. --- The Detailed Node Listing ---
  121. The Concepts of Bison
  122. * Language and Grammar:: Languages and context-free grammars,
  123. as mathematical ideas.
  124. * Grammar in Bison:: How we represent grammars for Bison's sake.
  125. * Semantic Values:: Each token or syntactic grouping can have
  126. a semantic value (the value of an integer,
  127. the name of an identifier, etc.).
  128. * Semantic Actions:: Each rule can have an action containing C code.
  129. * Bison Parser:: What are Bison's input and output,
  130. how is the output used?
  131. * Stages:: Stages in writing and running Bison grammars.
  132. * Grammar Layout:: Overall structure of a Bison grammar file.
  133. Examples
  134. * RPN Calc:: Reverse polish notation calculator;
  135. a first example with no operator precedence.
  136. * Infix Calc:: Infix (algebraic) notation calculator.
  137. Operator precedence is introduced.
  138. * Simple Error Recovery:: Continuing after syntax errors.
  139. * Multi-function Calc:: Calculator with memory and trig functions.
  140. It uses multiple data-types for semantic values.
  141. * Exercises:: Ideas for improving the multi-function calculator.
  142. Reverse Polish Notation Calculator
  143. * Decls: Rpcalc Decls. Bison and C declarations for rpcalc.
  144. * Rules: Rpcalc Rules. Grammar Rules for rpcalc, with explanation.
  145. * Lexer: Rpcalc Lexer. The lexical analyzer.
  146. * Main: Rpcalc Main. The controlling function.
  147. * Error: Rpcalc Error. The error reporting function.
  148. * Gen: Rpcalc Gen. Running Bison on the grammar file.
  149. * Comp: Rpcalc Compile. Run the C compiler on the output code.
  150. Grammar Rules for @code{rpcalc}
  151. * Rpcalc Input::
  152. * Rpcalc Line::
  153. * Rpcalc Expr::
  154. Multi-Function Calculator: @code{mfcalc}
  155. * Decl: Mfcalc Decl. Bison declarations for multi-function calculator.
  156. * Rules: Mfcalc Rules. Grammar rules for the calculator.
  157. * Symtab: Mfcalc Symtab. Symbol table management subroutines.
  158. Bison Grammar Files
  159. * Grammar Outline:: Overall layout of the grammar file.
  160. * Symbols:: Terminal and nonterminal symbols.
  161. * Rules:: How to write grammar rules.
  162. * Recursion:: Writing recursive rules.
  163. * Semantics:: Semantic values and actions.
  164. * Declarations:: All kinds of Bison declarations are described here.
  165. * Multiple Parsers:: Putting more than one Bison parser in one program.
  166. Outline of a Bison Grammar
  167. * C Declarations:: Syntax and usage of the C declarations section.
  168. * Bison Declarations:: Syntax and usage of the Bison declarations section.
  169. * Grammar Rules:: Syntax and usage of the grammar rules section.
  170. * C Code:: Syntax and usage of the additional C code section.
  171. Defining Language Semantics
  172. * Value Type:: Specifying one data type for all semantic values.
  173. * Multiple Types:: Specifying several alternative data types.
  174. * Actions:: An action is the semantic definition of a grammar rule.
  175. * Action Types:: Specifying data types for actions to operate on.
  176. * Mid-Rule Actions:: Most actions go at the end of a rule.
  177. This says when, why and how to use the exceptional
  178. action in the middle of a rule.
  179. Bison Declarations
  180. * Token Decl:: Declaring terminal symbols.
  181. * Precedence Decl:: Declaring terminals with precedence and associativity.
  182. * Union Decl:: Declaring the set of all semantic value types.
  183. * Type Decl:: Declaring the choice of type for a nonterminal symbol.
  184. * Expect Decl:: Suppressing warnings about shift/reduce conflicts.
  185. * Start Decl:: Specifying the start symbol.
  186. * Pure Decl:: Requesting a reentrant parser.
  187. * Decl Summary:: Table of all Bison declarations.
  188. Parser C-Language Interface
  189. * Parser Function:: How to call @code{yyparse} and what it returns.
  190. * Lexical:: You must supply a function @code{yylex}
  191. which reads tokens.
  192. * Error Reporting:: You must supply a function @code{yyerror}.
  193. * Action Features:: Special features for use in actions.
  194. The Lexical Analyzer Function @code{yylex}
  195. * Calling Convention:: How @code{yyparse} calls @code{yylex}.
  196. * Token Values:: How @code{yylex} must return the semantic value
  197. of the token it has read.
  198. * Token Positions:: How @code{yylex} must return the text position
  199. (line number, etc.) of the token, if the
  200. actions want that.
  201. * Pure Calling:: How the calling convention differs
  202. in a pure parser (@pxref{Pure Decl, ,A Pure (Reentrant) Parser}).
  203. The Bison Parser Algorithm
  204. * Look-Ahead:: Parser looks one token ahead when deciding what to do.
  205. * Shift/Reduce:: Conflicts: when either shifting or reduction is valid.
  206. * Precedence:: Operator precedence works by resolving conflicts.
  207. * Contextual Precedence:: When an operator's precedence depends on context.
  208. * Parser States:: The parser is a finite-state-machine with stack.
  209. * Reduce/Reduce:: When two rules are applicable in the same situation.
  210. * Mystery Conflicts:: Reduce/reduce conflicts that look unjustified.
  211. * Stack Overflow:: What happens when stack gets full. How to avoid it.
  212. Operator Precedence
  213. * Why Precedence:: An example showing why precedence is needed.
  214. * Using Precedence:: How to specify precedence in Bison grammars.
  215. * Precedence Examples:: How these features are used in the previous example.
  216. * How Precedence:: How they work.
  217. Handling Context Dependencies
  218. * Semantic Tokens:: Token parsing can depend on the semantic context.
  219. * Lexical Tie-ins:: Token parsing can depend on the syntactic context.
  220. * Tie-in Recovery:: Lexical tie-ins have implications for how
  221. error recovery rules must be written.
  222. Invoking Bison
  223. * Bison Options:: All the options described in detail,
  224. in alphabetical order by short options.
  225. * Option Cross Key:: Alphabetical list of long options.
  226. * VMS Invocation:: Bison command syntax on VMS.
  227. @end menu
  228. @node Introduction, Conditions, Top, Top
  229. @unnumbered Introduction
  230. @cindex introduction
  231. @dfn{Bison} is a general-purpose parser generator that converts a
  232. grammar description for an LALR(1) context-free grammar into a C
  233. program to parse that grammar. Once you are proficient with Bison,
  234. you may use it to develop a wide range of language parsers, from those
  235. used in simple desk calculators to complex programming languages.
  236. Bison is upward compatible with Yacc: all properly-written Yacc grammars
  237. ought to work with Bison with no change. Anyone familiar with Yacc
  238. should be able to use Bison with little trouble. You need to be fluent in
  239. C programming in order to use Bison or to understand this manual.
  240. We begin with tutorial chapters that explain the basic concepts of using
  241. Bison and show three explained examples, each building on the last. If you
  242. don't know Bison or Yacc, start by reading these chapters. Reference
  243. chapters follow which describe specific aspects of Bison in detail.
  244. Bison was written primarily by Robert Corbett; Richard Stallman made
  245. it Yacc-compatible. This edition corresponds to version 1.20 of Bison.
  246. @node Conditions, Copying, Introduction, Top
  247. @unnumbered Conditions for Using Bison
  248. Bison grammars can be used only in programs that are free software. This
  249. is in contrast to what happens with the GNU C compiler and the other
  250. GNU programming tools.
  251. The reason Bison is special is that the output of the Bison utility---the
  252. Bison parser file---contains a verbatim copy of a sizable piece of Bison,
  253. which is the code for the @code{yyparse} function. (The actions from your
  254. grammar are inserted into this function at one point, but the rest of the
  255. function is not changed.)
  256. As a result, the Bison parser file is covered by the same copying
  257. conditions that cover Bison itself and the rest of the GNU system: any
  258. program containing it has to be distributed under the standard GNU copying
  259. conditions.
  260. Occasionally people who would like to use Bison to develop proprietary
  261. programs complain about this.
  262. We don't particularly sympathize with their complaints. The purpose of the
  263. GNU project is to promote the right to share software and the practice of
  264. sharing software; it is a means of changing society. The people who
  265. complain are planning to be uncooperative toward the rest of the world; why
  266. should they deserve our help in doing so?
  267. However, it's possible that a change in these conditions might encourage
  268. computer companies to use and distribute the GNU system. If so, then we
  269. might decide to change the terms on @code{yyparse} as a matter of the
  270. strategy of promoting the right to share. Such a change would be
  271. irrevocable. Since we stand by the copying permissions we have announced,
  272. we cannot withdraw them once given.
  273. We mustn't make an irrevocable change hastily. We have to wait until there
  274. is a complete GNU system and there has been time to learn how this issue
  275. affects its reception.
  276. @node Copying, Concepts, Conditions, Top
  277. @unnumbered GNU GENERAL PUBLIC LICENSE
  278. @center Version 2, June 1991
  279. @display
  280. Copyright @copyright{} 1989, 1991 Free Software Foundation, Inc.
  281. 675 Mass Ave, Cambridge, MA 02139, USA
  282. Everyone is permitted to copy and distribute verbatim copies
  283. of this license document, but changing it is not allowed.
  284. @end display
  285. @unnumberedsec Preamble
  286. The licenses for most software are designed to take away your
  287. freedom to share and change it. By contrast, the GNU General Public
  288. License is intended to guarantee your freedom to share and change free
  289. software---to make sure the software is free for all its users. This
  290. General Public License applies to most of the Free Software
  291. Foundation's software and to any other program whose authors commit to
  292. using it. (Some other Free Software Foundation software is covered by
  293. the GNU Library General Public License instead.) You can apply it to
  294. your programs, too.
  295. When we speak of free software, we are referring to freedom, not
  296. price. Our General Public Licenses are designed to make sure that you
  297. have the freedom to distribute copies of free software (and charge for
  298. this service if you wish), that you receive source code or can get it
  299. if you want it, that you can change the software or use pieces of it
  300. in new free programs; and that you know you can do these things.
  301. To protect your rights, we need to make restrictions that forbid
  302. anyone to deny you these rights or to ask you to surrender the rights.
  303. These restrictions translate to certain responsibilities for you if you
  304. distribute copies of the software, or if you modify it.
  305. For example, if you distribute copies of such a program, whether
  306. gratis or for a fee, you must give the recipients all the rights that
  307. you have. You must make sure that they, too, receive or can get the
  308. source code. And you must show them these terms so they know their
  309. rights.
  310. We protect your rights with two steps: (1) copyright the software, and
  311. (2) offer you this license which gives you legal permission to copy,
  312. distribute and/or modify the software.
  313. Also, for each author's protection and ours, we want to make certain
  314. that everyone understands that there is no warranty for this free
  315. software. If the software is modified by someone else and passed on, we
  316. want its recipients to know that what they have is not the original, so
  317. that any problems introduced by others will not reflect on the original
  318. authors' reputations.
  319. Finally, any free program is threatened constantly by software
  320. patents. We wish to avoid the danger that redistributors of a free
  321. program will individually obtain patent licenses, in effect making the
  322. program proprietary. To prevent this, we have made it clear that any
  323. patent must be licensed for everyone's free use or not licensed at all.
  324. The precise terms and conditions for copying, distribution and
  325. modification follow.
  326. @iftex
  327. @unnumberedsec TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
  328. @end iftex
  329. @ifinfo
  330. @center TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
  331. @end ifinfo
  332. @enumerate 0
  333. @item
  334. This License applies to any program or other work which contains
  335. a notice placed by the copyright holder saying it may be distributed
  336. under the terms of this General Public License. The ``Program'', below,
  337. refers to any such program or work, and a ``work based on the Program''
  338. means either the Program or any derivative work under copyright law:
  339. that is to say, a work containing the Program or a portion of it,
  340. either verbatim or with modifications and/or translated into another
  341. language. (Hereinafter, translation is included without limitation in
  342. the term ``modification''.) Each licensee is addressed as ``you''.
  343. Activities other than copying, distribution and modification are not
  344. covered by this License; they are outside its scope. The act of
  345. running the Program is not restricted, and the output from the Program
  346. is covered only if its contents constitute a work based on the
  347. Program (independent of having been made by running the Program).
  348. Whether that is true depends on what the Program does.
  349. @item
  350. You may copy and distribute verbatim copies of the Program's
  351. source code as you receive it, in any medium, provided that you
  352. conspicuously and appropriately publish on each copy an appropriate
  353. copyright notice and disclaimer of warranty; keep intact all the
  354. notices that refer to this License and to the absence of any warranty;
  355. and give any other recipients of the Program a copy of this License
  356. along with the Program.
  357. You may charge a fee for the physical act of transferring a copy, and
  358. you may at your option offer warranty protection in exchange for a fee.
  359. @item
  360. You may modify your copy or copies of the Program or any portion
  361. of it, thus forming a work based on the Program, and copy and
  362. distribute such modifications or work under the terms of Section 1
  363. above, provided that you also meet all of these conditions:
  364. @enumerate a
  365. @item
  366. You must cause the modified files to carry prominent notices
  367. stating that you changed the files and the date of any change.
  368. @item
  369. You must cause any work that you distribute or publish, that in
  370. whole or in part contains or is derived from the Program or any
  371. part thereof, to be licensed as a whole at no charge to all third
  372. parties under the terms of this License.
  373. @item
  374. If the modified program normally reads commands interactively
  375. when run, you must cause it, when started running for such
  376. interactive use in the most ordinary way, to print or display an
  377. announcement including an appropriate copyright notice and a
  378. notice that there is no warranty (or else, saying that you provide
  379. a warranty) and that users may redistribute the program under
  380. these conditions, and telling the user how to view a copy of this
  381. License. (Exception: if the Program itself is interactive but
  382. does not normally print such an announcement, your work based on
  383. the Program is not required to print an announcement.)
  384. @end enumerate
  385. These requirements apply to the modified work as a whole. If
  386. identifiable sections of that work are not derived from the Program,
  387. and can be reasonably considered independent and separate works in
  388. themselves, then this License, and its terms, do not apply to those
  389. sections when you distribute them as separate works. But when you
  390. distribute the same sections as part of a whole which is a work based
  391. on the Program, the distribution of the whole must be on the terms of
  392. this License, whose permissions for other licensees extend to the
  393. entire whole, and thus to each and every part regardless of who wrote it.
  394. Thus, it is not the intent of this section to claim rights or contest
  395. your rights to work written entirely by you; rather, the intent is to
  396. exercise the right to control the distribution of derivative or
  397. collective works based on the Program.
  398. In addition, mere aggregation of another work not based on the Program
  399. with the Program (or with a work based on the Program) on a volume of
  400. a storage or distribution medium does not bring the other work under
  401. the scope of this License.
  402. @item
  403. You may copy and distribute the Program (or a work based on it,
  404. under Section 2) in object code or executable form under the terms of
  405. Sections 1 and 2 above provided that you also do one of the following:
  406. @enumerate a
  407. @item
  408. Accompany it with the complete corresponding machine-readable
  409. source code, which must be distributed under the terms of Sections
  410. 1 and 2 above on a medium customarily used for software interchange; or,
  411. @item
  412. Accompany it with a written offer, valid for at least three
  413. years, to give any third party, for a charge no more than your
  414. cost of physically performing source distribution, a complete
  415. machine-readable copy of the corresponding source code, to be
  416. distributed under the terms of Sections 1 and 2 above on a medium
  417. customarily used for software interchange; or,
  418. @item
  419. Accompany it with the information you received as to the offer
  420. to distribute corresponding source code. (This alternative is
  421. allowed only for noncommercial distribution and only if you
  422. received the program in object code or executable form with such
  423. an offer, in accord with Subsection b above.)
  424. @end enumerate
  425. The source code for a work means the preferred form of the work for
  426. making modifications to it. For an executable work, complete source
  427. code means all the source code for all modules it contains, plus any
  428. associated interface definition files, plus the scripts used to
  429. control compilation and installation of the executable. However, as a
  430. special exception, the source code distributed need not include
  431. anything that is normally distributed (in either source or binary
  432. form) with the major components (compiler, kernel, and so on) of the
  433. operating system on which the executable runs, unless that component
  434. itself accompanies the executable.
  435. If distribution of executable or object code is made by offering
  436. access to copy from a designated place, then offering equivalent
  437. access to copy the source code from the same place counts as
  438. distribution of the source code, even though third parties are not
  439. compelled to copy the source along with the object code.
  440. @item
  441. You may not copy, modify, sublicense, or distribute the Program
  442. except as expressly provided under this License. Any attempt
  443. otherwise to copy, modify, sublicense or distribute the Program is
  444. void, and will automatically terminate your rights under this License.
  445. However, parties who have received copies, or rights, from you under
  446. this License will not have their licenses terminated so long as such
  447. parties remain in full compliance.
  448. @item
  449. You are not required to accept this License, since you have not
  450. signed it. However, nothing else grants you permission to modify or
  451. distribute the Program or its derivative works. These actions are
  452. prohibited by law if you do not accept this License. Therefore, by
  453. modifying or distributing the Program (or any work based on the
  454. Program), you indicate your acceptance of this License to do so, and
  455. all its terms and conditions for copying, distributing or modifying
  456. the Program or works based on it.
  457. @item
  458. Each time you redistribute the Program (or any work based on the
  459. Program), the recipient automatically receives a license from the
  460. original licensor to copy, distribute or modify the Program subject to
  461. these terms and conditions. You may not impose any further
  462. restrictions on the recipients' exercise of the rights granted herein.
  463. You are not responsible for enforcing compliance by third parties to
  464. this License.
  465. @item
  466. If, as a consequence of a court judgment or allegation of patent
  467. infringement or for any other reason (not limited to patent issues),
  468. conditions are imposed on you (whether by court order, agreement or
  469. otherwise) that contradict the conditions of this License, they do not
  470. excuse you from the conditions of this License. If you cannot
  471. distribute so as to satisfy simultaneously your obligations under this
  472. License and any other pertinent obligations, then as a consequence you
  473. may not distribute the Program at all. For example, if a patent
  474. license would not permit royalty-free redistribution of the Program by
  475. all those who receive copies directly or indirectly through you, then
  476. the only way you could satisfy both it and this License would be to
  477. refrain entirely from distribution of the Program.
  478. If any portion of this section is held invalid or unenforceable under
  479. any particular circumstance, the balance of the section is intended to
  480. apply and the section as a whole is intended to apply in other
  481. circumstances.
  482. It is not the purpose of this section to induce you to infringe any
  483. patents or other property right claims or to contest validity of any
  484. such claims; this section has the sole purpose of protecting the
  485. integrity of the free software distribution system, which is
  486. implemented by public license practices. Many people have made
  487. generous contributions to the wide range of software distributed
  488. through that system in reliance on consistent application of that
  489. system; it is up to the author/donor to decide if he or she is willing
  490. to distribute software through any other system and a licensee cannot
  491. impose that choice.
  492. This section is intended to make thoroughly clear what is believed to
  493. be a consequence of the rest of this License.
  494. @item
  495. If the distribution and/or use of the Program is restricted in
  496. certain countries either by patents or by copyrighted interfaces, the
  497. original copyright holder who places the Program under this License
  498. may add an explicit geographical distribution limitation excluding
  499. those countries, so that distribution is permitted only in or among
  500. countries not thus excluded. In such case, this License incorporates
  501. the limitation as if written in the body of this License.
  502. @item
  503. The Free Software Foundation may publish revised and/or new versions
  504. of the General Public License from time to time. Such new versions will
  505. be similar in spirit to the present version, but may differ in detail to
  506. address new problems or concerns.
  507. Each version is given a distinguishing version number. If the Program
  508. specifies a version number of this License which applies to it and ``any
  509. later version'', you have the option of following the terms and conditions
  510. either of that version or of any later version published by the Free
  511. Software Foundation. If the Program does not specify a version number of
  512. this License, you may choose any version ever published by the Free Software
  513. Foundation.
  514. @item
  515. If you wish to incorporate parts of the Program into other free
  516. programs whose distribution conditions are different, write to the author
  517. to ask for permission. For software which is copyrighted by the Free
  518. Software Foundation, write to the Free Software Foundation; we sometimes
  519. make exceptions for this. Our decision will be guided by the two goals
  520. of preserving the free status of all derivatives of our free software and
  521. of promoting the sharing and reuse of software generally.
  522. @iftex
  523. @heading NO WARRANTY
  524. @end iftex
  525. @ifinfo
  526. @center NO WARRANTY
  527. @end ifinfo
  528. @item
  529. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
  530. FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
  531. OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
  532. PROVIDE THE PROGRAM ``AS IS'' WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
  533. OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
  534. MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
  535. TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
  536. PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
  537. REPAIR OR CORRECTION.
  538. @item
  539. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
  540. WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
  541. REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
  542. INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
  543. OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
  544. TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
  545. YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
  546. PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
  547. POSSIBILITY OF SUCH DAMAGES.
  548. @end enumerate
  549. @iftex
  550. @heading END OF TERMS AND CONDITIONS
  551. @end iftex
  552. @ifinfo
  553. @center END OF TERMS AND CONDITIONS
  554. @end ifinfo
  555. @page
  556. @unnumberedsec How to Apply These Terms to Your New Programs
  557. If you develop a new program, and you want it to be of the greatest
  558. possible use to the public, the best way to achieve this is to make it
  559. free software which everyone can redistribute and change under these terms.
  560. To do so, attach the following notices to the program. It is safest
  561. to attach them to the start of each source file to most effectively
  562. convey the exclusion of warranty; and each file should have at least
  563. the ``copyright'' line and a pointer to where the full notice is found.
  564. @smallexample
  565. @var{one line to give the program's name and a brief idea of what it does.}
  566. Copyright (C) 19@var{yy} @var{name of author}
  567. This program is free software; you can redistribute it and/or modify
  568. it under the terms of the GNU General Public License as published by
  569. the Free Software Foundation; either version 2 of the License, or
  570. (at your option) any later version.
  571. This program is distributed in the hope that it will be useful,
  572. but WITHOUT ANY WARRANTY; without even the implied warranty of
  573. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  574. GNU General Public License for more details.
  575. You should have received a copy of the GNU General Public License
  576. along with this program; if not, write to the Free Software
  577. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  578. @end smallexample
  579. Also add information on how to contact you by electronic and paper mail.
  580. If the program is interactive, make it output a short notice like this
  581. when it starts in an interactive mode:
  582. @smallexample
  583. Gnomovision version 69, Copyright (C) 19@var{yy} @var{name of author}
  584. Gnomovision comes with ABSOLUTELY NO WARRANTY; for details
  585. type `show w'.
  586. This is free software, and you are welcome to redistribute it
  587. under certain conditions; type `show c' for details.
  588. @end smallexample
  589. The hypothetical commands @samp{show w} and @samp{show c} should show
  590. the appropriate parts of the General Public License. Of course, the
  591. commands you use may be called something other than @samp{show w} and
  592. @samp{show c}; they could even be mouse-clicks or menu items---whatever
  593. suits your program.
  594. You should also get your employer (if you work as a programmer) or your
  595. school, if any, to sign a ``copyright disclaimer'' for the program, if
  596. necessary. Here is a sample; alter the names:
  597. @smallexample
  598. Yoyodyne, Inc., hereby disclaims all copyright interest in the program
  599. `Gnomovision' (which makes passes at compilers) written by James Hacker.
  600. @var{signature of Ty Coon}, 1 April 1989
  601. Ty Coon, President of Vice
  602. @end smallexample
  603. This General Public License does not permit incorporating your program into
  604. proprietary programs. If your program is a subroutine library, you may
  605. consider it more useful to permit linking proprietary applications with the
  606. library. If this is what you want to do, use the GNU Library General
  607. Public License instead of this License.
  608. @node Concepts, Examples, Copying, Top
  609. @chapter The Concepts of Bison
  610. This chapter introduces many of the basic concepts without which the
  611. details of Bison will not make sense. If you do not already know how to
  612. use Bison or Yacc, we suggest you start by reading this chapter carefully.
  613. @menu
  614. * Language and Grammar:: Languages and context-free grammars,
  615. as mathematical ideas.
  616. * Grammar in Bison:: How we represent grammars for Bison's sake.
  617. * Semantic Values:: Each token or syntactic grouping can have
  618. a semantic value (the value of an integer,
  619. the name of an identifier, etc.).
  620. * Semantic Actions:: Each rule can have an action containing C code.
  621. * Bison Parser:: What are Bison's input and output,
  622. how is the output used?
  623. * Stages:: Stages in writing and running Bison grammars.
  624. * Grammar Layout:: Overall structure of a Bison grammar file.
  625. @end menu
  626. @node Language and Grammar, Grammar in Bison, , Concepts
  627. @section Languages and Context-Free Grammars
  628. @c !!! ``An expression can be an integer'' is not a valid Bison
  629. @c expression---Bison cannot read English! --rjc 6 Feb 1992
  630. @cindex context-free grammar
  631. @cindex grammar, context-free
  632. In order for Bison to parse a language, it must be described by a
  633. @dfn{context-free grammar}. This means that you specify one or more
  634. @dfn{syntactic groupings} and give rules for constructing them from their
  635. parts. For example, in the C language, one kind of grouping is called an
  636. `expression'. One rule for making an expression might be, ``An expression
  637. can be made of a minus sign and another expression''. Another would be,
  638. ``An expression can be an integer''. As you can see, rules are often
  639. recursive, but there must be at least one rule which leads out of the
  640. recursion.
  641. @cindex BNF
  642. @cindex Backus-Naur form
  643. The most common formal system for presenting such rules for humans to read
  644. is @dfn{Backus-Naur Form} or ``BNF'', which was developed in order to
  645. specify the language Algol 60. Any grammar expressed in BNF is a
  646. context-free grammar. The input to Bison is essentially machine-readable
  647. BNF.
  648. Not all context-free languages can be handled by Bison, only those
  649. that are LALR(1). In brief, this means that it must be possible to
  650. tell how to parse any portion of an input string with just a single
  651. token of look-ahead. Strictly speaking, that is a description of an
  652. LR(1) grammar, and LALR(1) involves additional restrictions that are
  653. hard to explain simply; but it is rare in actual practice to find an
  654. LR(1) grammar that fails to be LALR(1). @xref{Mystery Conflicts, ,
  655. Mysterious Reduce/Reduce Conflicts}, for more information on this.
  656. @cindex symbols (abstract)
  657. @cindex token
  658. @cindex syntactic grouping
  659. @cindex grouping, syntactic
  660. In the formal grammatical rules for a language, each kind of syntactic unit
  661. or grouping is named by a @dfn{symbol}. Those which are built by grouping
  662. smaller constructs according to grammatical rules are called
  663. @dfn{nonterminal symbols}; those which can't be subdivided are called
  664. @dfn{terminal symbols} or @dfn{token types}. We call a piece of input
  665. corresponding to a single terminal symbol a @dfn{token}, and a piece
  666. corresponding to a single nonterminal symbol a @dfn{grouping}.@refill
  667. We can use the C language as an example of what symbols, terminal and
  668. nonterminal, mean. The tokens of C are identifiers, constants (numeric and
  669. string), and the various keywords, arithmetic operators and punctuation
  670. marks. So the terminal symbols of a grammar for C include `identifier',
  671. `number', `string', plus one symbol for each keyword, operator or
  672. punctuation mark: `if', `return', `const', `static', `int', `char',
  673. `plus-sign', `open-brace', `close-brace', `comma' and many more. (These
  674. tokens can be subdivided into characters, but that is a matter of
  675. lexicography, not grammar.)
  676. Here is a simple C function subdivided into tokens:
  677. @example
  678. int /* @r{keyword `int'} */
  679. square (x) /* @r{identifier, open-paren,} */
  680. /* @r{identifier, close-paren} */
  681. int x; /* @r{keyword `int', identifier, semicolon} */
  682. @{ /* @r{open-brace} */
  683. return x * x; /* @r{keyword `return', identifier,} */
  684. /* @r{asterisk, identifier, semicolon} */
  685. @} /* @r{close-brace} */
  686. @end example
  687. The syntactic groupings of C include the expression, the statement, the
  688. declaration, and the function definition. These are represented in the
  689. grammar of C by nonterminal symbols `expression', `statement',
  690. `declaration' and `function definition'. The full grammar uses dozens of
  691. additional language constructs, each with its own nonterminal symbol, in
  692. order to express the meanings of these four. The example above is a
  693. function definition; it contains one declaration, and one statement. In
  694. the statement, each @samp{x} is an expression and so is @samp{x * x}.
  695. Each nonterminal symbol must have grammatical rules showing how it is made
  696. out of simpler constructs. For example, one kind of C statement is the
  697. @code{return} statement; this would be described with a grammar rule which
  698. reads informally as follows:
  699. @quotation
  700. A `statement' can be made of a `return' keyword, an `expression' and a
  701. `semicolon'.
  702. @end quotation
  703. @noindent
  704. There would be many other rules for `statement', one for each kind of
  705. statement in C.
  706. @cindex start symbol
  707. One nonterminal symbol must be distinguished as the special one which
  708. defines a complete utterance in the language. It is called the @dfn{start
  709. symbol}. In a compiler, this means a complete input program. In the C
  710. language, the nonterminal symbol `sequence of definitions and declarations'
  711. plays this role.
  712. For example, @samp{1 + 2} is a valid C expression---a valid part of a C
  713. program---but it is not valid as an @emph{entire} C program. In the
  714. context-free grammar of C, this follows from the fact that `expression' is
  715. not the start symbol.
  716. The Bison parser reads a sequence of tokens as its input, and groups the
  717. tokens using the grammar rules. If the input is valid, the end result is
  718. that the entire token sequence reduces to a single grouping whose symbol is
  719. the grammar's start symbol. If we use a grammar for C, the entire input
  720. must be a `sequence of definitions and declarations'. If not, the parser
  721. reports a syntax error.
  722. @node Grammar in Bison, Semantic Values, Language and Grammar, Concepts
  723. @section From Formal Rules to Bison Input
  724. @cindex Bison grammar
  725. @cindex grammar, Bison
  726. @cindex formal grammar
  727. A formal grammar is a mathematical construct. To define the language
  728. for Bison, you must write a file expressing the grammar in Bison syntax:
  729. a @dfn{Bison grammar} file. @xref{Grammar File, ,Bison Grammar Files}.
  730. A nonterminal symbol in the formal grammar is represented in Bison input
  731. as an identifier, like an identifier in C. By convention, it should be
  732. in lower case, such as @code{expr}, @code{stmt} or @code{declaration}.
  733. The Bison representation for a terminal symbol is also called a @dfn{token
  734. type}. Token types as well can be represented as C-like identifiers. By
  735. convention, these identifiers should be upper case to distinguish them from
  736. nonterminals: for example, @code{INTEGER}, @code{IDENTIFIER}, @code{IF} or
  737. @code{RETURN}. A terminal symbol that stands for a particular keyword in
  738. the language should be named after that keyword converted to upper case.
  739. The terminal symbol @code{error} is reserved for error recovery.
  740. @xref{Symbols}.@refill
  741. A terminal symbol can also be represented as a character literal, just like
  742. a C character constant. You should do this whenever a token is just a
  743. single character (parenthesis, plus-sign, etc.): use that same character in
  744. a literal as the terminal symbol for that token.
  745. The grammar rules also have an expression in Bison syntax. For example,
  746. here is the Bison rule for a C @code{return} statement. The semicolon in
  747. quotes is a literal character token, representing part of the C syntax for
  748. the statement; the naked semicolon, and the colon, are Bison punctuation
  749. used in every rule.
  750. @example
  751. stmt: RETURN expr ';'
  752. ;
  753. @end example
  754. @noindent
  755. @xref{Rules, ,Syntax of Grammar Rules}.
  756. @node Semantic Values, Semantic Actions, Grammar in Bison, Concepts
  757. @section Semantic Values
  758. @cindex semantic value
  759. @cindex value, semantic
  760. A formal grammar selects tokens only by their classifications: for example,
  761. if a rule mentions the terminal symbol `integer constant', it means that
  762. @emph{any} integer constant is grammatically valid in that position. The
  763. precise value of the constant is irrelevant to how to parse the input: if
  764. @samp{x+4} is grammatical then @samp{x+1} or @samp{x+3989} is equally
  765. grammatical.@refill
  766. But the precise value is very important for what the input means once it is
  767. parsed. A compiler is useless if it fails to distinguish between 4, 1 and
  768. 3989 as constants in the program! Therefore, each token in a Bison grammar
  769. has both a token type and a @dfn{semantic value}. @xref{Semantics, ,Defining Language Semantics},
  770. for details.
  771. The token type is a terminal symbol defined in the grammar, such as
  772. @code{INTEGER}, @code{IDENTIFIER} or @code{','}. It tells everything
  773. you need to know to decide where the token may validly appear and how to
  774. group it with other tokens. The grammar rules know nothing about tokens
  775. except their types.@refill
  776. The semantic value has all the rest of the information about the
  777. meaning of the token, such as the value of an integer, or the name of an
  778. identifier. (A token such as @code{','} which is just punctuation doesn't
  779. need to have any semantic value.)
  780. For example, an input token might be classified as token type
  781. @code{INTEGER} and have the semantic value 4. Another input token might
  782. have the same token type @code{INTEGER} but value 3989. When a grammar
  783. rule says that @code{INTEGER} is allowed, either of these tokens is
  784. acceptable because each is an @code{INTEGER}. When the parser accepts the
  785. token, it keeps track of the token's semantic value.
  786. Each grouping can also have a semantic value as well as its nonterminal
  787. symbol. For example, in a calculator, an expression typically has a
  788. semantic value that is a number. In a compiler for a programming
  789. language, an expression typically has a semantic value that is a tree
  790. structure describing the meaning of the expression.
  791. @node Semantic Actions, Bison Parser, Semantic Values, Concepts
  792. @section Semantic Actions
  793. @cindex semantic actions
  794. @cindex actions, semantic
  795. In order to be useful, a program must do more than parse input; it must
  796. also produce some output based on the input. In a Bison grammar, a grammar
  797. rule can have an @dfn{action} made up of C statements. Each time the
  798. parser recognizes a match for that rule, the action is executed.
  799. @xref{Actions}.
  800. Most of the time, the purpose of an action is to compute the semantic value
  801. of the whole construct from the semantic values of its parts. For example,
  802. suppose we have a rule which says an expression can be the sum of two
  803. expressions. When the parser recognizes such a sum, each of the
  804. subexpressions has a semantic value which describes how it was built up.
  805. The action for this rule should create a similar sort of value for the
  806. newly recognized larger expression.
  807. For example, here is a rule that says an expression can be the sum of
  808. two subexpressions:
  809. @example
  810. expr: expr '+' expr @{ $$ = $1 + $3; @}
  811. ;
  812. @end example
  813. @noindent
  814. The action says how to produce the semantic value of the sum expression
  815. from the values of the two subexpressions.
  816. @node Bison Parser, Stages, Semantic Actions, Concepts
  817. @section Bison Output: the Parser File
  818. @cindex Bison parser
  819. @cindex Bison utility
  820. @cindex lexical analyzer, purpose
  821. @cindex parser
  822. When you run Bison, you give it a Bison grammar file as input. The output
  823. is a C source file that parses the language described by the grammar.
  824. This file is called a @dfn{Bison parser}. Keep in mind that the Bison
  825. utility and the Bison parser are two distinct programs: the Bison utility
  826. is a program whose output is the Bison parser that becomes part of your
  827. program.
  828. The job of the Bison parser is to group tokens into groupings according to
  829. the grammar rules---for example, to build identifiers and operators into
  830. expressions. As it does this, it runs the actions for the grammar rules it
  831. uses.
  832. The tokens come from a function called the @dfn{lexical analyzer} that you
  833. must supply in some fashion (such as by writing it in C). The Bison parser
  834. calls the lexical analyzer each time it wants a new token. It doesn't know
  835. what is ``inside'' the tokens (though their semantic values may reflect
  836. this). Typically the lexical analyzer makes the tokens by parsing
  837. characters of text, but Bison does not depend on this. @xref{Lexical, ,The Lexical Analyzer Function @code{yylex}}.
  838. The Bison parser file is C code which defines a function named
  839. @code{yyparse} which implements that grammar. This function does not make
  840. a complete C program: you must supply some additional functions. One is
  841. the lexical analyzer. Another is an error-reporting function which the
  842. parser calls to report an error. In addition, a complete C program must
  843. start with a function called @code{main}; you have to provide this, and
  844. arrange for it to call @code{yyparse} or the parser will never run.
  845. @xref{Interface, ,Parser C-Language Interface}.
  846. Aside from the token type names and the symbols in the actions you
  847. write, all variable and function names used in the Bison parser file
  848. begin with @samp{yy} or @samp{YY}. This includes interface functions
  849. such as the lexical analyzer function @code{yylex}, the error reporting
  850. function @code{yyerror} and the parser function @code{yyparse} itself.
  851. This also includes numerous identifiers used for internal purposes.
  852. Therefore, you should avoid using C identifiers starting with @samp{yy}
  853. or @samp{YY} in the Bison grammar file except for the ones defined in
  854. this manual.
  855. @node Stages, Grammar Layout, Bison Parser, Concepts
  856. @section Stages in Using Bison
  857. @cindex stages in using Bison
  858. @cindex using Bison
  859. The actual language-design process using Bison, from grammar specification
  860. to a working compiler or interpreter, has these parts:
  861. @enumerate
  862. @item
  863. Formally specify the grammar in a form recognized by Bison
  864. (@pxref{Grammar File, ,Bison Grammar Files}). For each grammatical rule in the language,
  865. describe the action that is to be taken when an instance of that rule
  866. is recognized. The action is described by a sequence of C statements.
  867. @item
  868. Write a lexical analyzer to process input and pass tokens to the
  869. parser. The lexical analyzer may be written by hand in C
  870. (@pxref{Lexical, ,The Lexical Analyzer Function @code{yylex}}). It could also be produced using Lex, but the use
  871. of Lex is not discussed in this manual.
  872. @item
  873. Write a controlling function that calls the Bison-produced parser.
  874. @item
  875. Write error-reporting routines.
  876. @end enumerate
  877. To turn this source code as written into a runnable program, you
  878. must follow these steps:
  879. @enumerate
  880. @item
  881. Run Bison on the grammar to produce the parser.
  882. @item
  883. Compile the code output by Bison, as well as any other source files.
  884. @item
  885. Link the object files to produce the finished product.
  886. @end enumerate
  887. @node Grammar Layout, , Stages, Concepts
  888. @section The Overall Layout of a Bison Grammar
  889. @cindex grammar file
  890. @cindex file format
  891. @cindex format of grammar file
  892. @cindex layout of Bison grammar
  893. The input file for the Bison utility is a @dfn{Bison grammar file}. The
  894. general form of a Bison grammar file is as follows:
  895. @example
  896. %@{
  897. @var{C declarations}
  898. %@}
  899. @var{Bison declarations}
  900. %%
  901. @var{Grammar rules}
  902. %%
  903. @var{Additional C code}
  904. @end example
  905. @noindent
  906. The @samp{%%}, @samp{%@{} and @samp{%@}} are punctuation that appears
  907. in every Bison grammar file to separate the sections.
  908. The C declarations may define types and variables used in the actions.
  909. You can also use preprocessor commands to define macros used there, and use
  910. @code{#include} to include header files that do any of these things.
  911. The Bison declarations declare the names of the terminal and nonterminal
  912. symbols, and may also describe operator precedence and the data types of
  913. semantic values of various symbols.
  914. The grammar rules define how to construct each nonterminal symbol from its
  915. parts.
  916. The additional C code can contain any C code you want to use. Often the
  917. definition of the lexical analyzer @code{yylex} goes here, plus subroutines
  918. called by the actions in the grammar rules. In a simple program, all the
  919. rest of the program can go here.
  920. @node Examples, Grammar File, Concepts, Top
  921. @chapter Examples
  922. @cindex simple examples
  923. @cindex examples, simple
  924. Now we show and explain three sample programs written using Bison: a
  925. reverse polish notation calculator, an algebraic (infix) notation
  926. calculator, and a multi-function calculator. All three have been tested
  927. under BSD Unix 4.3; each produces a usable, though limited, interactive
  928. desk-top calculator.
  929. These examples are simple, but Bison grammars for real programming
  930. languages are written the same way.
  931. @ifinfo
  932. You can copy these examples out of the Info file and into a source file
  933. to try them.
  934. @end ifinfo
  935. @menu
  936. * RPN Calc:: Reverse polish notation calculator;
  937. a first example with no operator precedence.
  938. * Infix Calc:: Infix (algebraic) notation calculator.
  939. Operator precedence is introduced.
  940. * Simple Error Recovery:: Continuing after syntax errors.
  941. * Multi-function Calc:: Calculator with memory and trig functions.
  942. It uses multiple data-types for semantic values.
  943. * Exercises:: Ideas for improving the multi-function calculator.
  944. @end menu
  945. @node RPN Calc, Infix Calc, , Examples
  946. @section Reverse Polish Notation Calculator
  947. @cindex reverse polish notation
  948. @cindex polish notation calculator
  949. @cindex @code{rpcalc}
  950. @cindex calculator, simple
  951. The first example is that of a simple double-precision @dfn{reverse polish
  952. notation} calculator (a calculator using postfix operators). This example
  953. provides a good starting point, since operator precedence is not an issue.
  954. The second example will illustrate how operator precedence is handled.
  955. The source code for this calculator is named @file{rpcalc.y}. The
  956. @samp{.y} extension is a convention used for Bison input files.
  957. @menu
  958. * Decls: Rpcalc Decls. Bison and C declarations for rpcalc.
  959. * Rules: Rpcalc Rules. Grammar Rules for rpcalc, with explanation.
  960. * Lexer: Rpcalc Lexer. The lexical analyzer.
  961. * Main: Rpcalc Main. The controlling function.
  962. * Error: Rpcalc Error. The error reporting function.
  963. * Gen: Rpcalc Gen. Running Bison on the grammar file.
  964. * Comp: Rpcalc Compile. Run the C compiler on the output code.
  965. @end menu
  966. @node Rpcalc Decls, Rpcalc Rules, , RPN Calc
  967. @subsection Declarations for @code{rpcalc}
  968. Here are the C and Bison declarations for the reverse polish notation
  969. calculator. As in C, comments are placed between @samp{/*@dots{}*/}.
  970. @example
  971. /* Reverse polish notation calculator. */
  972. %@{
  973. #define YYSTYPE double
  974. #include <math.h>
  975. %@}
  976. %token NUM
  977. %% /* Grammar rules and actions follow */
  978. @end example
  979. The C declarations section (@pxref{C Declarations, ,The C Declarations Section}) contains two
  980. preprocessor directives.
  981. The @code{#define} directive defines the macro @code{YYSTYPE}, thus
  982. specifying the C data type for semantic values of both tokens and groupings
  983. (@pxref{Value Type, ,Data Types of Semantic Values}). The Bison parser will use whatever type
  984. @code{YYSTYPE} is defined as; if you don't define it, @code{int} is the
  985. default. Because we specify @code{double}, each token and each expression
  986. has an associated value, which is a floating point number.
  987. The @code{#include} directive is used to declare the exponentiation
  988. function @code{pow}.
  989. The second section, Bison declarations, provides information to Bison about
  990. the token types (@pxref{Bison Declarations, ,The Bison Declarations Section}). Each terminal symbol that is
  991. not a single-character literal must be declared here. (Single-character
  992. literals normally don't need to be declared.) In this example, all the
  993. arithmetic operators are designated by single-character literals, so the
  994. only terminal symbol that needs to be declared is @code{NUM}, the token
  995. type for numeric constants.
  996. @node Rpcalc Rules, Rpcalc Lexer, Rpcalc Decls, RPN Calc
  997. @subsection Grammar Rules for @code{rpcalc}
  998. Here are the grammar rules for the reverse polish notation calculator.
  999. @example
  1000. input: /* empty */
  1001. | input line
  1002. ;
  1003. line: '\n'
  1004. | exp '\n' @{ printf ("\t%.10g\n", $1); @}
  1005. ;
  1006. exp: NUM @{ $$ = $1; @}
  1007. | exp exp '+' @{ $$ = $1 + $2; @}
  1008. | exp exp '-' @{ $$ = $1 - $2; @}
  1009. | exp exp '*' @{ $$ = $1 * $2; @}
  1010. | exp exp '/' @{ $$ = $1 / $2; @}
  1011. /* Exponentiation */
  1012. | exp exp '^' @{ $$ = pow ($1, $2); @}
  1013. /* Unary minus */
  1014. | exp 'n' @{ $$ = -$1; @}
  1015. ;
  1016. %%
  1017. @end example
  1018. The groupings of the rpcalc ``language'' defined here are the expression
  1019. (given the name @code{exp}), the line of input (@code{line}), and the
  1020. complete input transcript (@code{input}). Each of these nonterminal
  1021. symbols has several alternate rules, joined by the @samp{|} punctuator
  1022. which is read as ``or''. The following sections explain what these rules
  1023. mean.
  1024. The semantics of the language is determined by the actions taken when a
  1025. grouping is recognized. The actions are the C code that appears inside
  1026. braces. @xref{Actions}.
  1027. You must specify these actions in C, but Bison provides the means for
  1028. passing semantic values between the rules. In each action, the
  1029. pseudo-variable @code{$$} stands for the semantic value for the grouping
  1030. that the rule is going to construct. Assigning a value to @code{$$} is the
  1031. main job of most actions. The semantic values of the components of the
  1032. rule are referred to as @code{$1}, @code{$2}, and so on.
  1033. @menu
  1034. * Rpcalc Input::
  1035. * Rpcalc Line::
  1036. * Rpcalc Expr::
  1037. @end menu
  1038. @node Rpcalc Input, Rpcalc Line, , Rpcalc Rules
  1039. @subsubsection Explanation of @code{input}
  1040. Consider the definition of @code{input}:
  1041. @example
  1042. input: /* empty */
  1043. | input line
  1044. ;
  1045. @end example
  1046. This definition reads as follows: ``A complete input is either an empty
  1047. string, or a complete input followed by an input line''. Notice that
  1048. ``complete input'' is defined in terms of itself. This definition is said
  1049. to be @dfn{left recursive} since @code{input} appears always as the
  1050. leftmost symbol in the sequence. @xref{Recursion, ,Recursive Rules}.
  1051. The first alternative is empty because there are no symbols between the
  1052. colon and the first @samp{|}; this means that @code{input} can match an
  1053. empty string of input (no tokens). We write the rules this way because it
  1054. is legitimate to type @kbd{Ctrl-d} right after you start the calculator.
  1055. It's conventional to put an empty alternative first and write the comment
  1056. @samp{/* empty */} in it.
  1057. The second alternate rule (@code{input line}) handles all nontrivial input.
  1058. It means, ``After reading any number of lines, read one more line if
  1059. possible.'' The left recursion makes this rule into a loop. Since the
  1060. first alternative matches empty input, the loop can be executed zero or
  1061. more times.
  1062. The parser function @code{yyparse} continues to process input until a
  1063. grammatical error is seen or the lexical analyzer says there are no more
  1064. input tokens; we will arrange for the latter to happen at end of file.
  1065. @node Rpcalc Line, Rpcalc Expr, Rpcalc Input, Rpcalc Rules
  1066. @subsubsection Explanation of @code{line}
  1067. Now consider the definition of @code{line}:
  1068. @example
  1069. line: '\n'
  1070. | exp '\n' @{ printf ("\t%.10g\n", $1); @}
  1071. ;
  1072. @end example
  1073. The first alternative is a token which is a newline character; this means
  1074. that rpcalc accepts a blank line (and ignores it, since there is no
  1075. action). The second alternative is an expression followed by a newline.
  1076. This is the alternative that makes rpcalc useful. The semantic value of
  1077. the @code{exp} grouping is the value of @code{$1} because the @code{exp} in
  1078. question is the first symbol in the alternative. The action prints this
  1079. value, which is the result of the computation the user asked for.
  1080. This action is unusual because it does not assign a value to @code{$$}. As
  1081. a consequence, the semantic value associated with the @code{line} is
  1082. uninitialized (its value will be unpredictable). This would be a bug if
  1083. that value were ever used, but we don't use it: once rpcalc has printed the
  1084. value of the user's input line, that value is no longer needed.
  1085. @node Rpcalc Expr, , Rpcalc Line, Rpcalc Rules
  1086. @subsubsection Explanation of @code{expr}
  1087. The @code{exp} grouping has several rules, one for each kind of expression.
  1088. The first rule handles the simplest expressions: those that are just numbers.
  1089. The second handles an addition-expression, which looks like two expressions
  1090. followed by a plus-sign. The third handles subtraction, and so on.
  1091. @example
  1092. exp: NUM
  1093. | exp exp '+' @{ $$ = $1 + $2; @}
  1094. | exp exp '-' @{ $$ = $1 - $2; @}
  1095. @dots{}
  1096. ;
  1097. @end example
  1098. We have used @samp{|} to join all the rules for @code{exp}, but we could
  1099. equally well have written them separately:
  1100. @example
  1101. exp: NUM ;
  1102. exp: exp exp '+' @{ $$ = $1 + $2; @} ;
  1103. exp: exp exp '-' @{ $$ = $1 - $2; @} ;
  1104. @dots{}
  1105. @end example
  1106. Most of the rules have actions that compute the value of the expression in
  1107. terms of the value of its parts. For example, in the rule for addition,
  1108. @code{$1} refers to the first component @code{exp} and @code{$2} refers to
  1109. the second one. The third component, @code{'+'}, has no meaningful
  1110. associated semantic value, but if it had one you could refer to it as
  1111. @code{$3}. When @code{yyparse} recognizes a sum expression using this
  1112. rule, the sum of the two subexpressions' values is produced as the value of
  1113. the entire expression. @xref{Actions}.
  1114. You don't have to give an action for every rule. When a rule has no
  1115. action, Bison by default copies the value of @code{$1} into @code{$$}.
  1116. This is what happens in the first rule (the one that uses @code{NUM}).
  1117. The formatting shown here is the recommended convention, but Bison does
  1118. not require it. You can add or change whitespace as much as you wish.
  1119. For example, this:
  1120. @example
  1121. exp : NUM | exp exp '+' @{$$ = $1 + $2; @} | @dots{}
  1122. @end example
  1123. @noindent
  1124. means the same thing as this:
  1125. @example
  1126. exp: NUM
  1127. | exp exp '+' @{ $$ = $1 + $2; @}
  1128. | @dots{}
  1129. @end example
  1130. @noindent
  1131. The latter, however, is much more readable.
  1132. @node Rpcalc Lexer, Rpcalc Main, Rpcalc Rules, RPN Calc
  1133. @subsection The @code{rpcalc} Lexical Analyzer
  1134. @cindex writing a lexical analyzer
  1135. @cindex lexical analyzer, writing
  1136. The lexical analyzer's job is low-level parsing: converting characters or
  1137. sequences of characters into tokens. The Bison parser gets its tokens by
  1138. calling the lexical analyzer. @xref{Lexical, ,The Lexical Analyzer Function @code{yylex}}.
  1139. Only a simple lexical analyzer is needed for the RPN calculator. This
  1140. lexical analyzer skips blanks and tabs, then reads in numbers as
  1141. @code{double} and returns them as @code{NUM} tokens. Any other character
  1142. that isn't part of a number is a separate token. Note that the token-code
  1143. for such a single-character token is the character itself.
  1144. The return value of the lexical analyzer function is a numeric code which
  1145. represents a token type. The same text used in Bison rules to stand for
  1146. this token type is also a C expression for the numeric code for the type.
  1147. This works in two ways. If the token type is a character literal, then its
  1148. numeric code is the ASCII code for that character; you can use the same
  1149. character literal in the lexical analyzer to express the number. If the
  1150. token type is an identifier, that identifier is defined by Bison as a C
  1151. macro whose definition is the appropriate number. In this example,
  1152. therefore, @code{NUM} becomes a macro for @code{yylex} to use.
  1153. The semantic value of the token (if it has one) is stored into the global
  1154. variable @code{yylval}, which is where the Bison parser will look for it.
  1155. (The C data type of @code{yylval} is @code{YYSTYPE}, which was defined
  1156. at the beginning of the grammar; @pxref{Rpcalc Decls, ,Declarations for @code{rpcalc}}.)
  1157. A token type code of zero is returned if the end-of-file is encountered.
  1158. (Bison recognizes any nonpositive value as indicating the end of the
  1159. input.)
  1160. Here is the code for the lexical analyzer:
  1161. @example
  1162. @group
  1163. /* Lexical analyzer returns a double floating point
  1164. number on the stack and the token NUM, or the ASCII
  1165. character read if not a number. Skips all blanks
  1166. and tabs, returns 0 for EOF. */
  1167. #include <ctype.h>
  1168. @end group
  1169. @group
  1170. yylex ()
  1171. @{
  1172. int c;
  1173. /* skip white space */
  1174. while ((c = getchar ()) == ' ' || c == '\t')
  1175. ;
  1176. @end group
  1177. @group
  1178. /* process numbers */
  1179. if (c == '.' || isdigit (c))
  1180. @{
  1181. ungetc (c, stdin);
  1182. scanf ("%lf", &yylval);
  1183. return NUM;
  1184. @}
  1185. @end group
  1186. @group
  1187. /* return end-of-file */
  1188. if (c == EOF)
  1189. return 0;
  1190. /* return single chars */
  1191. return c;
  1192. @}
  1193. @end group
  1194. @end example
  1195. @node Rpcalc Main, Rpcalc Error, Rpcalc Lexer, RPN Calc
  1196. @subsection The Controlling Function
  1197. @cindex controlling function
  1198. @cindex main function in simple example
  1199. In keeping with the spirit of this example, the controlling function is
  1200. kept to the bare minimum. The only requirement is that it call
  1201. @code{yyparse} to start the process of parsing.
  1202. @example
  1203. @group
  1204. main ()
  1205. @{
  1206. yyparse ();
  1207. @}
  1208. @end group
  1209. @end example
  1210. @node Rpcalc Error, Rpcalc Gen, Rpcalc Main, RPN Calc
  1211. @subsection The Error Reporting Routine
  1212. @cindex error reporting routine
  1213. When @code{yyparse} detects a syntax error, it calls the error reporting
  1214. function @code{yyerror} to print an error message (usually but not always
  1215. @code{"parse error"}). It is up to the programmer to supply @code{yyerror}
  1216. (@pxref{Interface, ,Parser C-Language Interface}), so here is the definition we will use:
  1217. @example
  1218. @group
  1219. #include <stdio.h>
  1220. yyerror (s) /* Called by yyparse on error */
  1221. char *s;
  1222. @{
  1223. printf ("%s\n", s);
  1224. @}
  1225. @end group
  1226. @end example
  1227. After @code{yyerror} returns, the Bison parser may recover from the error
  1228. and continue parsing if the grammar contains a suitable error rule
  1229. (@pxref{Error Recovery}). Otherwise, @code{yyparse} returns nonzero. We
  1230. have not written any error rules in this example, so any invalid input will
  1231. cause the calculator program to exit. This is not clean behavior for a
  1232. real calculator, but it is adequate in the first example.
  1233. @node Rpcalc Gen, Rpcalc Compile, Rpcalc Error, RPN Calc
  1234. @subsection Running Bison to Make the Parser
  1235. @cindex running Bison (introduction)
  1236. Before running Bison to produce a parser, we need to decide how to arrange
  1237. all the source code in one or more source files. For such a simple example,
  1238. the easiest thing is to put everything in one file. The definitions of
  1239. @code{yylex}, @code{yyerror} and @code{main} go at the end, in the
  1240. ``additional C code'' section of the file (@pxref{Grammar Layout, ,The Overall Layout of a Bison Grammar}).
  1241. For a large project, you would probably have several source files, and use
  1242. @code{make} to arrange to recompile them.
  1243. With all the source in a single file, you use the following command to
  1244. convert it into a parser file:
  1245. @example
  1246. bison @var{file_name}.y
  1247. @end example
  1248. @noindent
  1249. In this example the file was called @file{rpcalc.y} (for ``Reverse Polish
  1250. CALCulator''). Bison produces a file named @file{@var{file_name}.tab.c},
  1251. removing the @samp{.y} from the original file name. The file output by
  1252. Bison contains the source code for @code{yyparse}. The additional
  1253. functions in the input file (@code{yylex}, @code{yyerror} and @code{main})
  1254. are copied verbatim to the output.
  1255. @node Rpcalc Compile, , Rpcalc Gen, RPN Calc
  1256. @subsection Compiling the Parser File
  1257. @cindex compiling the parser
  1258. Here is how to compile and run the parser file:
  1259. @example
  1260. @group
  1261. # @r{List files in current directory.}
  1262. % ls
  1263. rpcalc.tab.c rpcalc.y
  1264. @end group
  1265. @group
  1266. # @r{Compile the Bison parser.}
  1267. # @r{@samp{-lm} tells compiler to search math library for @code{pow}.}
  1268. % cc rpcalc.tab.c -lm -o rpcalc
  1269. @end group
  1270. @group
  1271. # @r{List files again.}
  1272. % ls
  1273. rpcalc rpcalc.tab.c rpcalc.y
  1274. @end group
  1275. @end example
  1276. The file @file{rpcalc} now contains the executable code. Here is an
  1277. example session using @code{rpcalc}.
  1278. @example
  1279. % rpcalc
  1280. 4 9 +
  1281. 13
  1282. 3 7 + 3 4 5 *+-
  1283. -13
  1284. 3 7 + 3 4 5 * + - n @r{Note the unary minus, @samp{n}}
  1285. 13
  1286. 5 6 / 4 n +
  1287. -3.166666667
  1288. 3 4 ^ @r{Exponentiation}
  1289. 81
  1290. ^D @r{End-of-file indicator}
  1291. %
  1292. @end example
  1293. @node Infix Calc, Simple Error Recovery, RPN Calc, Examples
  1294. @section Infix Notation Calculator: @code{calc}
  1295. @cindex infix notation calculator
  1296. @cindex @code{calc}
  1297. @cindex calculator, infix notation
  1298. We now modify rpcalc to handle infix operators instead of postfix. Infix
  1299. notation involves the concept of operator precedence and the need for
  1300. parentheses nested to arbitrary depth. Here is the Bison code for
  1301. @file{calc.y}, an infix desk-top calculator.
  1302. @example
  1303. /* Infix notation calculator--calc */
  1304. %@{
  1305. #define YYSTYPE double
  1306. #include <math.h>
  1307. %@}
  1308. /* BISON Declarations */
  1309. %token NUM
  1310. %left '-' '+'
  1311. %left '*' '/'
  1312. %left NEG /* negation--unary minus */
  1313. %right '^' /* exponentiation */
  1314. /* Grammar follows */
  1315. %%
  1316. input: /* empty string */
  1317. | input line
  1318. ;
  1319. line: '\n'
  1320. | exp '\n' @{ printf ("\t%.10g\n", $1); @}
  1321. ;
  1322. exp: NUM @{ $$ = $1; @}
  1323. | exp '+' exp @{ $$ = $1 + $3; @}
  1324. | exp '-' exp @{ $$ = $1 - $3; @}
  1325. | exp '*' exp @{ $$ = $1 * $3; @}
  1326. | exp '/' exp @{ $$ = $1 / $3; @}
  1327. | '-' exp %prec NEG @{ $$ = -$2; @}
  1328. | exp '^' exp @{ $$ = pow ($1, $3); @}
  1329. | '(' exp ')' @{ $$ = $2; @}
  1330. ;
  1331. %%
  1332. @end example
  1333. @noindent
  1334. The functions @code{yylex}, @code{yyerror} and @code{main} can be the same
  1335. as before.
  1336. There are two important new features shown in this code.
  1337. In the second section (Bison declarations), @code{%left} declares token
  1338. types and says they are left-associative operators. The declarations
  1339. @code{%left} and @code{%right} (right associativity) take the place of
  1340. @code{%token} which is used to declare a token type name without
  1341. associativity. (These tokens are single-character literals, which
  1342. ordinarily don't need to be declared. We declare them here to specify
  1343. the associativity.)
  1344. Operator precedence is determined by the line ordering of the
  1345. declarations; the higher the line number of the declaration (lower on
  1346. the page or screen), the higher the precedence. Hence, exponentiation
  1347. has the highest precedence, unary minus (@code{NEG}) is next, followed
  1348. by @samp{*} and @samp{/}, and so on. @xref{Precedence, ,Operator Precedence}.
  1349. The other important new feature is the @code{%prec} in the grammar section
  1350. for the unary minus operator. The @code{%prec} simply instructs Bison that
  1351. the rule @samp{| '-' exp} has the same precedence as @code{NEG}---in this
  1352. case the next-to-highest. @xref{Contextual Precedence, ,Context-Dependent Precedence}.
  1353. Here is a sample run of @file{calc.y}:
  1354. @need 500
  1355. @example
  1356. % calc
  1357. 4 + 4.5 - (34/(8*3+-3))
  1358. 6.880952381
  1359. -56 + 2
  1360. -54
  1361. 3 ^ 2
  1362. 9
  1363. @end example
  1364. @node Simple Error Recovery, Multi-function Calc, Infix Calc, Examples
  1365. @section Simple Error Recovery
  1366. @cindex error recovery, simple
  1367. Up to this point, this manual has not addressed the issue of @dfn{error
  1368. recovery}---how to continue parsing after the parser detects a syntax
  1369. error. All we have handled is error reporting with @code{yyerror}. Recall
  1370. that by default @code{yyparse} returns after calling @code{yyerror}. This
  1371. means that an erroneous input line causes the calculator program to exit.
  1372. Now we show how to rectify this deficiency.
  1373. The Bison language itself includes the reserved word @code{error}, which
  1374. may be included in the grammar rules. In the example below it has
  1375. been added to one of the alternatives for @code{line}:
  1376. @example
  1377. @group
  1378. line: '\n'
  1379. | exp '\n' @{ printf ("\t%.10g\n", $1); @}
  1380. | error '\n' @{ yyerrok; @}
  1381. ;
  1382. @end group
  1383. @end example
  1384. This addition to the grammar allows for simple error recovery in the event
  1385. of a parse error. If an expression that cannot be evaluated is read, the
  1386. error will be recognized by the third rule for @code{line}, and parsing
  1387. will continue. (The @code{yyerror} function is still called upon to print
  1388. its message as well.) The action executes the statement @code{yyerrok}, a
  1389. macro defined automatically by Bison; its meaning is that error recovery is
  1390. complete (@pxref{Error Recovery}). Note the difference between
  1391. @code{yyerrok} and @code{yyerror}; neither one is a misprint.@refill
  1392. This form of error recovery deals with syntax errors. There are other
  1393. kinds of errors; for example, division by zero, which raises an exception
  1394. signal that is normally fatal. A real calculator program must handle this
  1395. signal and use @code{longjmp} to return to @code{main} and resume parsing
  1396. input lines; it would also have to discard the rest of the current line of
  1397. input. We won't discuss this issue further because it is not specific to
  1398. Bison programs.
  1399. @node Multi-function Calc, Exercises, Simple Error Recovery, Examples
  1400. @section Multi-Function Calculator: @code{mfcalc}
  1401. @cindex multi-function calculator
  1402. @cindex @code{mfcalc}
  1403. @cindex calculator, multi-function
  1404. Now that the basics of Bison have been discussed, it is time to move on to
  1405. a more advanced problem. The above calculators provided only five
  1406. functions, @samp{+}, @samp{-}, @samp{*}, @samp{/} and @samp{^}. It would
  1407. be nice to have a calculator that provides other mathematical functions such
  1408. as @code{sin}, @code{cos}, etc.
  1409. It is easy to add new operators to the infix calculator as long as they are
  1410. only single-character literals. The lexical analyzer @code{yylex} passes
  1411. back all non-number characters as tokens, so new grammar rules suffice for
  1412. adding a new operator. But we want something more flexible: built-in
  1413. functions whose syntax has this form:
  1414. @example
  1415. @var{function_name} (@var{argument})
  1416. @end example
  1417. @noindent
  1418. At the same time, we will add memory to the calculator, by allowing you
  1419. to create named variables, store values in them, and use them later.
  1420. Here is a sample session with the multi-function calculator:
  1421. @example
  1422. % acalc
  1423. pi = 3.141592653589
  1424. 3.1415926536
  1425. sin(pi)
  1426. 0.0000000000
  1427. alpha = beta1 = 2.3
  1428. 2.3000000000
  1429. alpha
  1430. 2.3000000000
  1431. ln(alpha)
  1432. 0.8329091229
  1433. exp(ln(beta1))
  1434. 2.3000000000
  1435. %
  1436. @end example
  1437. Note that multiple assignment and nested function calls are permitted.
  1438. @menu
  1439. * Decl: Mfcalc Decl. Bison declarations for multi-function calculator.
  1440. * Rules: Mfcalc Rules. Grammar rules for the calculator.
  1441. * Symtab: Mfcalc Symtab. Symbol table management subroutines.
  1442. @end menu
  1443. @node Mfcalc Decl, Mfcalc Rules, , Multi-function Calc
  1444. @subsection Declarations for @code{mfcalc}
  1445. Here are the C and Bison declarations for the multi-function calculator.
  1446. @smallexample
  1447. %@{
  1448. #include <math.h> /* For math functions, cos(), sin(), etc. */
  1449. #include "calc.h" /* Contains definition of `symrec' */
  1450. %@}
  1451. %union @{
  1452. double val; /* For returning numbers. */
  1453. symrec *tptr; /* For returning symbol-table pointers */
  1454. @}
  1455. %token <val> NUM /* Simple double precision number */
  1456. %token <tptr> VAR FNCT /* Variable and Function */
  1457. %type <val> exp
  1458. %right '='
  1459. %left '-' '+'
  1460. %left '*' '/'
  1461. %left NEG /* Negation--unary minus */
  1462. %right '^' /* Exponentiation */
  1463. /* Grammar follows */
  1464. %%
  1465. @end smallexample
  1466. The above grammar introduces only two new features of the Bison language.
  1467. These features allow semantic values to have various data types
  1468. (@pxref{Multiple Types, ,More Than One Value Type}).
  1469. The @code{%union} declaration specifies the entire list of possible types;
  1470. this is instead of defining @code{YYSTYPE}. The allowable types are now
  1471. double-floats (for @code{exp} and @code{NUM}) and pointers to entries in
  1472. the symbol table. @xref{Union Decl, ,The Collection of Value Types}.
  1473. Since values can now have various types, it is necessary to associate a
  1474. type with each grammar symbol whose semantic value is used. These symbols
  1475. are @code{NUM}, @code{VAR}, @code{FNCT}, and @code{exp}. Their
  1476. declarations are augmented with information about their data type (placed
  1477. between angle brackets).
  1478. The Bison construct @code{%type} is used for declaring nonterminal symbols,
  1479. just as @code{%token} is used for declaring token types. We have not used
  1480. @code{%type} before because nonterminal symbols are normally declared
  1481. implicitly by the rules that define them. But @code{exp} must be declared
  1482. explicitly so we can specify its value type. @xref{Type Decl, ,Nonterminal Symbols}.
  1483. @node Mfcalc Rules, Mfcalc Symtab, Mfcalc Decl, Multi-function Calc
  1484. @subsection Grammar Rules for @code{mfcalc}
  1485. Here are the grammar rules for the multi-function calculator.
  1486. Most of them are copied directly from @code{calc}; three rules,
  1487. those which mention @code{VAR} or @code{FNCT}, are new.
  1488. @smallexample
  1489. input: /* empty */
  1490. | input line
  1491. ;
  1492. line:
  1493. '\n'
  1494. | exp '\n' @{ printf ("\t%.10g\n", $1); @}
  1495. | error '\n' @{ yyerrok; @}
  1496. ;
  1497. exp: NUM @{ $$ = $1; @}
  1498. | VAR @{ $$ = $1->value.var; @}
  1499. | VAR '=' exp @{ $$ = $3; $1->value.var = $3; @}
  1500. | FNCT '(' exp ')' @{ $$ = (*($1->value.fnctptr))($3); @}
  1501. | exp '+' exp @{ $$ = $1 + $3; @}
  1502. | exp '-' exp @{ $$ = $1 - $3; @}
  1503. | exp '*' exp @{ $$ = $1 * $3; @}
  1504. | exp '/' exp @{ $$ = $1 / $3; @}
  1505. | '-' exp %prec NEG @{ $$ = -$2; @}
  1506. | exp '^' exp @{ $$ = pow ($1, $3); @}
  1507. | '(' exp ')' @{ $$ = $2; @}
  1508. ;
  1509. /* End of grammar */
  1510. %%
  1511. @end smallexample
  1512. @node Mfcalc Symtab, , Mfcalc Rules, Multi-function Calc
  1513. @subsection The @code{mfcalc} Symbol Table
  1514. @cindex symbol table example
  1515. The multi-function calculator requires a symbol table to keep track of the
  1516. names and meanings of variables and functions. This doesn't affect the
  1517. grammar rules (except for the actions) or the Bison declarations, but it
  1518. requires some additional C functions for support.
  1519. The symbol table itself consists of a linked list of records. Its
  1520. definition, which is kept in the header @file{calc.h}, is as follows. It
  1521. provides for either functions or variables to be placed in the table.
  1522. @smallexample
  1523. @group
  1524. /* Data type for links in the chain of symbols. */
  1525. struct symrec
  1526. @{
  1527. char *name; /* name of symbol */
  1528. int type; /* type of symbol: either VAR or FNCT */
  1529. union @{
  1530. double var; /* value of a VAR */
  1531. double (*fnctptr)(); /* value of a FNCT */
  1532. @} value;
  1533. struct symrec *next; /* link field */
  1534. @};
  1535. @end group
  1536. @group
  1537. typedef struct symrec symrec;
  1538. /* The symbol table: a chain of `struct symrec'. */
  1539. extern symrec *sym_table;
  1540. symrec *putsym ();
  1541. symrec *getsym ();
  1542. @end group
  1543. @end smallexample
  1544. The new version of @code{main} includes a call to @code{init_table}, a
  1545. function that initializes the symbol table. Here it is, and
  1546. @code{init_table} as well:
  1547. @smallexample
  1548. @group
  1549. #include <stdio.h>
  1550. main ()
  1551. @{
  1552. init_table ();
  1553. yyparse ();
  1554. @}
  1555. @end group
  1556. @group
  1557. yyerror (s) /* Called by yyparse on error */
  1558. char *s;
  1559. @{
  1560. printf ("%s\n", s);
  1561. @}
  1562. struct init
  1563. @{
  1564. char *fname;
  1565. double (*fnct)();
  1566. @};
  1567. @end group
  1568. @group
  1569. struct init arith_fncts[]
  1570. = @{
  1571. "sin", sin,
  1572. "cos", cos,
  1573. "atan", atan,
  1574. "ln", log,
  1575. "exp", exp,
  1576. "sqrt", sqrt,
  1577. 0, 0
  1578. @};
  1579. /* The symbol table: a chain of `struct symrec'. */
  1580. symrec *sym_table = (symrec *)0;
  1581. @end group
  1582. @group
  1583. init_table () /* puts arithmetic functions in table. */
  1584. @{
  1585. int i;
  1586. symrec *ptr;
  1587. for (i = 0; arith_fncts[i].fname != 0; i++)
  1588. @{
  1589. ptr = putsym (arith_fncts[i].fname, FNCT);
  1590. ptr->value.fnctptr = arith_fncts[i].fnct;
  1591. @}
  1592. @}
  1593. @end group
  1594. @end smallexample
  1595. By simply editing the initialization list and adding the necessary include
  1596. files, you can add additional functions to the calculator.
  1597. Two important functions allow look-up and installation of symbols in the
  1598. symbol table. The function @code{putsym} is passed a name and the type
  1599. (@code{VAR} or @code{FNCT}) of the object to be installed. The object is
  1600. linked to the front of the list, and a pointer to the object is returned.
  1601. The function @code{getsym} is passed the name of the symbol to look up. If
  1602. found, a pointer to that symbol is returned; otherwise zero is returned.
  1603. @smallexample
  1604. symrec *
  1605. putsym (sym_name,sym_type)
  1606. char *sym_name;
  1607. int sym_type;
  1608. @{
  1609. symrec *ptr;
  1610. ptr = (symrec *) malloc (sizeof (symrec));
  1611. ptr->name = (char *) malloc (strlen (sym_name) + 1);
  1612. strcpy (ptr->name,sym_name);
  1613. ptr->type = sym_type;
  1614. ptr->value.var = 0; /* set value to 0 even if fctn. */
  1615. ptr->next = (struct symrec *)sym_table;
  1616. sym_table = ptr;
  1617. return ptr;
  1618. @}
  1619. symrec *
  1620. getsym (sym_name)
  1621. char *sym_name;
  1622. @{
  1623. symrec *ptr;
  1624. for (ptr = sym_table; ptr != (symrec *) 0;
  1625. ptr = (symrec *)ptr->next)
  1626. if (strcmp (ptr->name,sym_name) == 0)
  1627. return ptr;
  1628. return 0;
  1629. @}
  1630. @end smallexample
  1631. The function @code{yylex} must now recognize variables, numeric values, and
  1632. the single-character arithmetic operators. Strings of alphanumeric
  1633. characters with a leading nondigit are recognized as either variables or
  1634. functions depending on what the symbol table says about them.
  1635. The string is passed to @code{getsym} for look up in the symbol table. If
  1636. the name appears in the table, a pointer to its location and its type
  1637. (@code{VAR} or @code{FNCT}) is returned to @code{yyparse}. If it is not
  1638. already in the table, then it is installed as a @code{VAR} using
  1639. @code{putsym}. Again, a pointer and its type (which must be @code{VAR}) is
  1640. returned to @code{yyparse}.@refill
  1641. No change is needed in the handling of numeric values and arithmetic
  1642. operators in @code{yylex}.
  1643. @smallexample
  1644. @group
  1645. #include <ctype.h>
  1646. yylex ()
  1647. @{
  1648. int c;
  1649. /* Ignore whitespace, get first nonwhite character. */
  1650. while ((c = getchar ()) == ' ' || c == '\t');
  1651. if (c == EOF)
  1652. return 0;
  1653. @end group
  1654. @group
  1655. /* Char starts a number => parse the number. */
  1656. if (c == '.' || isdigit (c))
  1657. @{
  1658. ungetc (c, stdin);
  1659. scanf ("%lf", &yylval.val);
  1660. return NUM;
  1661. @}
  1662. @end group
  1663. @group
  1664. /* Char starts an identifier => read the name. */
  1665. if (isalpha (c))
  1666. @{
  1667. symrec *s;
  1668. static char *symbuf = 0;
  1669. static int length = 0;
  1670. int i;
  1671. @end group
  1672. @group
  1673. /* Initially make the buffer long enough
  1674. for a 40-character symbol name. */
  1675. if (length == 0)
  1676. length = 40, symbuf = (char *)malloc (length + 1);
  1677. i = 0;
  1678. do
  1679. @end group
  1680. @group
  1681. @{
  1682. /* If buffer is full, make it bigger. */
  1683. if (i == length)
  1684. @{
  1685. length *= 2;
  1686. symbuf = (char *)realloc (symbuf, length + 1);
  1687. @}
  1688. /* Add this character to the buffer. */
  1689. symbuf[i++] = c;
  1690. /* Get another character. */
  1691. c = getchar ();
  1692. @}
  1693. @end group
  1694. @group
  1695. while (c != EOF && isalnum (c));
  1696. ungetc (c, stdin);
  1697. symbuf[i] = '\0';
  1698. @end group
  1699. @group
  1700. s = getsym (symbuf);
  1701. if (s == 0)
  1702. s = putsym (symbuf, VAR);
  1703. yylval.tptr = s;
  1704. return s->type;
  1705. @}
  1706. /* Any other character is a token by itself. */
  1707. return c;
  1708. @}
  1709. @end group
  1710. @end smallexample
  1711. This program is both powerful and flexible. You may easily add new
  1712. functions, and it is a simple job to modify this code to install predefined
  1713. variables such as @code{pi} or @code{e} as well.
  1714. @node Exercises, , Multi-function Calc, Examples
  1715. @section Exercises
  1716. @cindex exercises
  1717. @enumerate
  1718. @item
  1719. Add some new functions from @file{math.h} to the initialization list.
  1720. @item
  1721. Add another array that contains constants and their values. Then
  1722. modify @code{init_table} to add these constants to the symbol table.
  1723. It will be easiest to give the constants type @code{VAR}.
  1724. @item
  1725. Make the program report an error if the user refers to an
  1726. uninitialized variable in any way except to store a value in it.
  1727. @end enumerate
  1728. @node Grammar File, Interface, Examples, Top
  1729. @chapter Bison Grammar Files
  1730. Bison takes as input a context-free grammar specification and produces a
  1731. C-language function that recognizes correct instances of the grammar.
  1732. The Bison grammar input file conventionally has a name ending in @samp{.y}.
  1733. @menu
  1734. * Grammar Outline:: Overall layout of the grammar file.
  1735. * Symbols:: Terminal and nonterminal symbols.
  1736. * Rules:: How to write grammar rules.
  1737. * Recursion:: Writing recursive rules.
  1738. * Semantics:: Semantic values and actions.
  1739. * Declarations:: All kinds of Bison declarations are described here.
  1740. * Multiple Parsers:: Putting more than one Bison parser in one program.
  1741. @end menu
  1742. @node Grammar Outline, Symbols, , Grammar File
  1743. @section Outline of a Bison Grammar
  1744. A Bison grammar file has four main sections, shown here with the
  1745. appropriate delimiters:
  1746. @example
  1747. %@{
  1748. @var{C declarations}
  1749. %@}
  1750. @var{Bison declarations}
  1751. %%
  1752. @var{Grammar rules}
  1753. %%
  1754. @var{Additional C code}
  1755. @end example
  1756. Comments enclosed in @samp{/* @dots{} */} may appear in any of the sections.
  1757. @menu
  1758. * C Declarations:: Syntax and usage of the C declarations section.
  1759. * Bison Declarations:: Syntax and usage of the Bison declarations section.
  1760. * Grammar Rules:: Syntax and usage of the grammar rules section.
  1761. * C Code:: Syntax and usage of the additional C code section.
  1762. @end menu
  1763. @node C Declarations, Bison Declarations, , Grammar Outline
  1764. @subsection The C Declarations Section
  1765. @cindex C declarations section
  1766. @cindex declarations, C
  1767. The @var{C declarations} section contains macro definitions and
  1768. declarations of functions and variables that are used in the actions in the
  1769. grammar rules. These are copied to the beginning of the parser file so
  1770. that they precede the definition of @code{yyparse}. You can use
  1771. @samp{#include} to get the declarations from a header file. If you don't
  1772. need any C declarations, you may omit the @samp{%@{} and @samp{%@}}
  1773. delimiters that bracket this section.
  1774. @node Bison Declarations, Grammar Rules, C Declarations, Grammar Outline
  1775. @subsection The Bison Declarations Section
  1776. @cindex Bison declarations (introduction)
  1777. @cindex declarations, Bison (introduction)
  1778. The @var{Bison declarations} section contains declarations that define
  1779. terminal and nonterminal symbols, specify precedence, and so on.
  1780. In some simple grammars you may not need any declarations.
  1781. @xref{Declarations, ,Bison Declarations}.
  1782. @node Grammar Rules, C Code, Bison Declarations, Grammar Outline
  1783. @subsection The Grammar Rules Section
  1784. @cindex grammar rules section
  1785. @cindex rules section for grammar
  1786. The @dfn{grammar rules} section contains one or more Bison grammar
  1787. rules, and nothing else. @xref{Rules, ,Syntax of Grammar Rules}.
  1788. There must always be at least one grammar rule, and the first
  1789. @samp{%%} (which precedes the grammar rules) may never be omitted even
  1790. if it is the first thing in the file.
  1791. @node C Code, , Grammar Rules, Grammar Outline
  1792. @subsection The Additional C Code Section
  1793. @cindex additional C code section
  1794. @cindex C code, section for additional
  1795. The @var{additional C code} section is copied verbatim to the end of
  1796. the parser file, just as the @var{C declarations} section is copied to
  1797. the beginning. This is the most convenient place to put anything
  1798. that you want to have in the parser file but which need not come before
  1799. the definition of @code{yyparse}. For example, the definitions of
  1800. @code{yylex} and @code{yyerror} often go here. @xref{Interface, ,Parser C-Language Interface}.
  1801. If the last section is empty, you may omit the @samp{%%} that separates it
  1802. from the grammar rules.
  1803. The Bison parser itself contains many static variables whose names start
  1804. with @samp{yy} and many macros whose names start with @samp{YY}. It is a
  1805. good idea to avoid using any such names (except those documented in this
  1806. manual) in the additional C code section of the grammar file.
  1807. @node Symbols, Rules, Grammar Outline, Grammar File
  1808. @section Symbols, Terminal and Nonterminal
  1809. @cindex nonterminal symbol
  1810. @cindex terminal symbol
  1811. @cindex token type
  1812. @cindex symbol
  1813. @dfn{Symbols} in Bison grammars represent the grammatical classifications
  1814. of the language.
  1815. A @dfn{terminal symbol} (also known as a @dfn{token type}) represents a
  1816. class of syntactically equivalent tokens. You use the symbol in grammar
  1817. rules to mean that a token in that class is allowed. The symbol is
  1818. represented in the Bison parser by a numeric code, and the @code{yylex}
  1819. function returns a token type code to indicate what kind of token has been
  1820. read. You don't need to know what the code value is; you can use the
  1821. symbol to stand for it.
  1822. A @dfn{nonterminal symbol} stands for a class of syntactically equivalent
  1823. groupings. The symbol name is used in writing grammar rules. By convention,
  1824. it should be all lower case.
  1825. Symbol names can contain letters, digits (not at the beginning),
  1826. underscores and periods. Periods make sense only in nonterminals.
  1827. There are two ways of writing terminal symbols in the grammar:
  1828. @itemize @bullet
  1829. @item
  1830. A @dfn{named token type} is written with an identifier, like an
  1831. identifier in C. By convention, it should be all upper case. Each
  1832. such name must be defined with a Bison declaration such as
  1833. @code{%token}. @xref{Token Decl, ,Token Type Names}.
  1834. @item
  1835. @cindex character token
  1836. @cindex literal token
  1837. @cindex single-character literal
  1838. A @dfn{character token type} (or @dfn{literal token}) is written in
  1839. the grammar using the same syntax used in C for character constants;
  1840. for example, @code{'+'} is a character token type. A character token
  1841. type doesn't need to be declared unless you need to specify its
  1842. semantic value data type (@pxref{Value Type, ,Data Types of Semantic Values}), associativity, or
  1843. precedence (@pxref{Precedence, ,Operator Precedence}).
  1844. By convention, a character token type is used only to represent a
  1845. token that consists of that particular character. Thus, the token
  1846. type @code{'+'} is used to represent the character @samp{+} as a
  1847. token. Nothing enforces this convention, but if you depart from it,
  1848. your program will confuse other readers.
  1849. All the usual escape sequences used in character literals in C can be
  1850. used in Bison as well, but you must not use the null character as a
  1851. character literal because its ASCII code, zero, is the code
  1852. @code{yylex} returns for end-of-input (@pxref{Calling Convention, ,Calling Convention for @code{yylex}}).
  1853. @end itemize
  1854. How you choose to write a terminal symbol has no effect on its
  1855. grammatical meaning. That depends only on where it appears in rules and
  1856. on when the parser function returns that symbol.
  1857. The value returned by @code{yylex} is always one of the terminal symbols
  1858. (or 0 for end-of-input). Whichever way you write the token type in the
  1859. grammar rules, you write it the same way in the definition of @code{yylex}.
  1860. The numeric code for a character token type is simply the ASCII code for
  1861. the character, so @code{yylex} can use the identical character constant to
  1862. generate the requisite code. Each named token type becomes a C macro in
  1863. the parser file, so @code{yylex} can use the name to stand for the code.
  1864. (This is why periods don't make sense in terminal symbols.)
  1865. @xref{Calling Convention, ,Calling Convention for @code{yylex}}.
  1866. If @code{yylex} is defined in a separate file, you need to arrange for the
  1867. token-type macro definitions to be available there. Use the @samp{-d}
  1868. option when you run Bison, so that it will write these macro definitions
  1869. into a separate header file @file{@var{name}.tab.h} which you can include
  1870. in the other source files that need it. @xref{Invocation, ,Invoking Bison}.
  1871. The symbol @code{error} is a terminal symbol reserved for error recovery
  1872. (@pxref{Error Recovery}); you shouldn't use it for any other purpose.
  1873. In particular, @code{yylex} should never return this value.
  1874. @node Rules, Recursion, Symbols, Grammar File
  1875. @section Syntax of Grammar Rules
  1876. @cindex rule syntax
  1877. @cindex grammar rule syntax
  1878. @cindex syntax of grammar rules
  1879. A Bison grammar rule has the following general form:
  1880. @example
  1881. @var{result}: @var{components}@dots{}
  1882. ;
  1883. @end example
  1884. @noindent
  1885. where @var{result} is the nonterminal symbol that this rule describes
  1886. and @var{components} are various terminal and nonterminal symbols that
  1887. are put together by this rule (@pxref{Symbols}).
  1888. For example,
  1889. @example
  1890. @group
  1891. exp: exp '+' exp
  1892. ;
  1893. @end group
  1894. @end example
  1895. @noindent
  1896. says that two groupings of type @code{exp}, with a @samp{+} token in between,
  1897. can be combined into a larger grouping of type @code{exp}.
  1898. Whitespace in rules is significant only to separate symbols. You can add
  1899. extra whitespace as you wish.
  1900. Scattered among the components can be @var{actions} that determine
  1901. the semantics of the rule. An action looks like this:
  1902. @example
  1903. @{@var{C statements}@}
  1904. @end example
  1905. @noindent
  1906. Usually there is only one action and it follows the components.
  1907. @xref{Actions}.
  1908. @findex |
  1909. Multiple rules for the same @var{result} can be written separately or can
  1910. be joined with the vertical-bar character @samp{|} as follows:
  1911. @ifinfo
  1912. @example
  1913. @var{result}: @var{rule1-components}@dots{}
  1914. | @var{rule2-components}@dots{}
  1915. @dots{}
  1916. ;
  1917. @end example
  1918. @end ifinfo
  1919. @iftex
  1920. @example
  1921. @group
  1922. @var{result}: @var{rule1-components}@dots{}
  1923. | @var{rule2-components}@dots{}
  1924. @dots{}
  1925. ;
  1926. @end group
  1927. @end example
  1928. @end iftex
  1929. @noindent
  1930. They are still considered distinct rules even when joined in this way.
  1931. If @var{components} in a rule is empty, it means that @var{result} can
  1932. match the empty string. For example, here is how to define a
  1933. comma-separated sequence of zero or more @code{exp} groupings:
  1934. @example
  1935. @group
  1936. expseq: /* empty */
  1937. | expseq1
  1938. ;
  1939. @end group
  1940. @group
  1941. expseq1: exp
  1942. | expseq1 ',' exp
  1943. ;
  1944. @end group
  1945. @end example
  1946. @noindent
  1947. It is customary to write a comment @samp{/* empty */} in each rule
  1948. with no components.
  1949. @node Recursion, Semantics, Rules, Grammar File
  1950. @section Recursive Rules
  1951. @cindex recursive rule
  1952. A rule is called @dfn{recursive} when its @var{result} nonterminal appears
  1953. also on its right hand side. Nearly all Bison grammars need to use
  1954. recursion, because that is the only way to define a sequence of any number
  1955. of somethings. Consider this recursive definition of a comma-separated
  1956. sequence of one or more expressions:
  1957. @example
  1958. @group
  1959. expseq1: exp
  1960. | expseq1 ',' exp
  1961. ;
  1962. @end group
  1963. @end example
  1964. @cindex left recursion
  1965. @cindex right recursion
  1966. @noindent
  1967. Since the recursive use of @code{expseq1} is the leftmost symbol in the
  1968. right hand side, we call this @dfn{left recursion}. By contrast, here
  1969. the same construct is defined using @dfn{right recursion}:
  1970. @example
  1971. @group
  1972. expseq1: exp
  1973. | exp ',' expseq1
  1974. ;
  1975. @end group
  1976. @end example
  1977. @noindent
  1978. Any kind of sequence can be defined using either left recursion or
  1979. right recursion, but you should always use left recursion, because it
  1980. can parse a sequence of any number of elements with bounded stack
  1981. space. Right recursion uses up space on the Bison stack in proportion
  1982. to the number of elements in the sequence, because all the elements
  1983. must be shifted onto the stack before the rule can be applied even
  1984. once. @xref{Algorithm, ,The Bison Parser Algorithm }, for
  1985. further explanation of this.
  1986. @cindex mutual recursion
  1987. @dfn{Indirect} or @dfn{mutual} recursion occurs when the result of the
  1988. rule does not appear directly on its right hand side, but does appear
  1989. in rules for other nonterminals which do appear on its right hand
  1990. side.
  1991. For example:
  1992. @example
  1993. @group
  1994. expr: primary
  1995. | primary '+' primary
  1996. ;
  1997. @end group
  1998. @group
  1999. primary: constant
  2000. | '(' expr ')'
  2001. ;
  2002. @end group
  2003. @end example
  2004. @noindent
  2005. defines two mutually-recursive nonterminals, since each refers to the
  2006. other.
  2007. @node Semantics, Declarations, Recursion, Grammar File
  2008. @section Defining Language Semantics
  2009. @cindex defining language semantics
  2010. @cindex language semantics, defining
  2011. The grammar rules for a language determine only the syntax. The semantics
  2012. are determined by the semantic values associated with various tokens and
  2013. groupings, and by the actions taken when various groupings are recognized.
  2014. For example, the calculator calculates properly because the value
  2015. associated with each expression is the proper number; it adds properly
  2016. because the action for the grouping @w{@samp{@var{x} + @var{y}}} is to add
  2017. the numbers associated with @var{x} and @var{y}.
  2018. @menu
  2019. * Value Type:: Specifying one data type for all semantic values.
  2020. * Multiple Types:: Specifying several alternative data types.
  2021. * Actions:: An action is the semantic definition of a grammar rule.
  2022. * Action Types:: Specifying data types for actions to operate on.
  2023. * Mid-Rule Actions:: Most actions go at the end of a rule.
  2024. This says when, why and how to use the exceptional
  2025. action in the middle of a rule.
  2026. @end menu
  2027. @node Value Type, Multiple Types, , Semantics
  2028. @subsection Data Types of Semantic Values
  2029. @cindex semantic value type
  2030. @cindex value type, semantic
  2031. @cindex data types of semantic values
  2032. @cindex default data type
  2033. In a simple program it may be sufficient to use the same data type for
  2034. the semantic values of all language constructs. This was true in the
  2035. RPN and infix calculator examples (@pxref{RPN Calc, ,Reverse Polish Notation Calculator}).
  2036. Bison's default is to use type @code{int} for all semantic values. To
  2037. specify some other type, define @code{YYSTYPE} as a macro, like this:
  2038. @example
  2039. #define YYSTYPE double
  2040. @end example
  2041. @noindent
  2042. This macro definition must go in the C declarations section of the grammar
  2043. file (@pxref{Grammar Outline, ,Outline of a Bison Grammar}).
  2044. @node Multiple Types, Actions, Value Type, Semantics
  2045. @subsection More Than One Value Type
  2046. In most programs, you will need different data types for different kinds
  2047. of tokens and groupings. For example, a numeric constant may need type
  2048. @code{int} or @code{long}, while a string constant needs type @code{char *},
  2049. and an identifier might need a pointer to an entry in the symbol table.
  2050. To use more than one data type for semantic values in one parser, Bison
  2051. requires you to do two things:
  2052. @itemize @bullet
  2053. @item
  2054. Specify the entire collection of possible data types, with the
  2055. @code{%union} Bison declaration (@pxref{Union Decl, ,The Collection of Value Types}).
  2056. @item
  2057. Choose one of those types for each symbol (terminal or nonterminal)
  2058. for which semantic values are used. This is done for tokens with the
  2059. @code{%token} Bison declaration (@pxref{Token Decl, ,Token Type Names}) and for groupings
  2060. with the @code{%type} Bison declaration (@pxref{Type Decl, ,Nonterminal Symbols}).
  2061. @end itemize
  2062. @node Actions, Action Types, Multiple Types, Semantics
  2063. @subsection Actions
  2064. @cindex action
  2065. @vindex $$
  2066. @vindex $@var{n}
  2067. An action accompanies a syntactic rule and contains C code to be executed
  2068. each time an instance of that rule is recognized. The task of most actions
  2069. is to compute a semantic value for the grouping built by the rule from the
  2070. semantic values associated with tokens or smaller groupings.
  2071. An action consists of C statements surrounded by braces, much like a
  2072. compound statement in C. It can be placed at any position in the rule; it
  2073. is executed at that position. Most rules have just one action at the end
  2074. of the rule, following all the components. Actions in the middle of a rule
  2075. are tricky and used only for special purposes (@pxref{Mid-Rule Actions, ,Actions in Mid-Rule}).
  2076. The C code in an action can refer to the semantic values of the components
  2077. matched by the rule with the construct @code{$@var{n}}, which stands for
  2078. the value of the @var{n}th component. The semantic value for the grouping
  2079. being constructed is @code{$$}. (Bison translates both of these constructs
  2080. into array element references when it copies the actions into the parser
  2081. file.)
  2082. Here is a typical example:
  2083. @example
  2084. @group
  2085. exp: @dots{}
  2086. | exp '+' exp
  2087. @{ $$ = $1 + $3; @}
  2088. @end group
  2089. @end example
  2090. @noindent
  2091. This rule constructs an @code{exp} from two smaller @code{exp} groupings
  2092. connected by a plus-sign token. In the action, @code{$1} and @code{$3}
  2093. refer to the semantic values of the two component @code{exp} groupings,
  2094. which are the first and third symbols on the right hand side of the rule.
  2095. The sum is stored into @code{$$} so that it becomes the semantic value of
  2096. the addition-expression just recognized by the rule. If there were a
  2097. useful semantic value associated with the @samp{+} token, it could be
  2098. referred to as @code{$2}.@refill
  2099. @cindex default action
  2100. If you don't specify an action for a rule, Bison supplies a default:
  2101. @w{@code{$$ = $1}.} Thus, the value of the first symbol in the rule becomes
  2102. the value of the whole rule. Of course, the default rule is valid only
  2103. if the two data types match. There is no meaningful default action for
  2104. an empty rule; every empty rule must have an explicit action unless the
  2105. rule's value does not matter.
  2106. @code{$@var{n}} with @var{n} zero or negative is allowed for reference
  2107. to tokens and groupings on the stack @emph{before} those that match the
  2108. current rule. This is a very risky practice, and to use it reliably
  2109. you must be certain of the context in which the rule is applied. Here
  2110. is a case in which you can use this reliably:
  2111. @example
  2112. @group
  2113. foo: expr bar '+' expr @{ @dots{} @}
  2114. | expr bar '-' expr @{ @dots{} @}
  2115. ;
  2116. @end group
  2117. @group
  2118. bar: /* empty */
  2119. @{ previous_expr = $0; @}
  2120. ;
  2121. @end group
  2122. @end example
  2123. As long as @code{bar} is used only in the fashion shown here, @code{$0}
  2124. always refers to the @code{expr} which precedes @code{bar} in the
  2125. definition of @code{foo}.
  2126. @node Action Types, Mid-Rule Actions, Actions, Semantics
  2127. @subsection Data Types of Values in Actions
  2128. @cindex action data types
  2129. @cindex data types in actions
  2130. If you have chosen a single data type for semantic values, the @code{$$}
  2131. and @code{$@var{n}} constructs always have that data type.
  2132. If you have used @code{%union} to specify a variety of data types, then you
  2133. must declare a choice among these types for each terminal or nonterminal
  2134. symbol that can have a semantic value. Then each time you use @code{$$} or
  2135. @code{$@var{n}}, its data type is determined by which symbol it refers to
  2136. in the rule. In this example,@refill
  2137. @example
  2138. @group
  2139. exp: @dots{}
  2140. | exp '+' exp
  2141. @{ $$ = $1 + $3; @}
  2142. @end group
  2143. @end example
  2144. @noindent
  2145. @code{$1} and @code{$3} refer to instances of @code{exp}, so they all
  2146. have the data type declared for the nonterminal symbol @code{exp}. If
  2147. @code{$2} were used, it would have the data type declared for the
  2148. terminal symbol @code{'+'}, whatever that might be.@refill
  2149. Alternatively, you can specify the data type when you refer to the value,
  2150. by inserting @samp{<@var{type}>} after the @samp{$} at the beginning of the
  2151. reference. For example, if you have defined types as shown here:
  2152. @example
  2153. @group
  2154. %union @{
  2155. int itype;
  2156. double dtype;
  2157. @}
  2158. @end group
  2159. @end example
  2160. @noindent
  2161. then you can write @code{$<itype>1} to refer to the first subunit of the
  2162. rule as an integer, or @code{$<dtype>1} to refer to it as a double.
  2163. @node Mid-Rule Actions, , Action Types, Semantics
  2164. @subsection Actions in Mid-Rule
  2165. @cindex actions in mid-rule
  2166. @cindex mid-rule actions
  2167. Occasionally it is useful to put an action in the middle of a rule.
  2168. These actions are written just like usual end-of-rule actions, but they
  2169. are executed before the parser even recognizes the following components.
  2170. A mid-rule action may refer to the components preceding it using
  2171. @code{$@var{n}}, but it may not refer to subsequent components because
  2172. it is run before they are parsed.
  2173. The mid-rule action itself counts as one of the components of the rule.
  2174. This makes a difference when there is another action later in the same rule
  2175. (and usually there is another at the end): you have to count the actions
  2176. along with the symbols when working out which number @var{n} to use in
  2177. @code{$@var{n}}.
  2178. The mid-rule action can also have a semantic value. The action can set
  2179. its value with an assignment to @code{$$}, and actions later in the rule
  2180. can refer to the value using @code{$@var{n}}. Since there is no symbol
  2181. to name the action, there is no way to declare a data type for the value
  2182. in advance, so you must use the @samp{$<@dots{}>} construct to specify a
  2183. data type each time you refer to this value.
  2184. There is no way to set the value of the entire rule with a mid-rule
  2185. action, because assignments to @code{$$} do not have that effect. The
  2186. only way to set the value for the entire rule is with an ordinary action
  2187. at the end of the rule.
  2188. Here is an example from a hypothetical compiler, handling a @code{let}
  2189. statement that looks like @samp{let (@var{variable}) @var{statement}} and
  2190. serves to create a variable named @var{variable} temporarily for the
  2191. duration of @var{statement}. To parse this construct, we must put
  2192. @var{variable} into the symbol table while @var{statement} is parsed, then
  2193. remove it afterward. Here is how it is done:
  2194. @example
  2195. @group
  2196. stmt: LET '(' var ')'
  2197. @{ $<context>$ = push_context ();
  2198. declare_variable ($3); @}
  2199. stmt @{ $$ = $6;
  2200. pop_context ($<context>5); @}
  2201. @end group
  2202. @end example
  2203. @noindent
  2204. As soon as @samp{let (@var{variable})} has been recognized, the first
  2205. action is run. It saves a copy of the current semantic context (the
  2206. list of accessible variables) as its semantic value, using alternative
  2207. @code{context} in the data-type union. Then it calls
  2208. @code{declare_variable} to add the new variable to that list. Once the
  2209. first action is finished, the embedded statement @code{stmt} can be
  2210. parsed. Note that the mid-rule action is component number 5, so the
  2211. @samp{stmt} is component number 6.
  2212. After the embedded statement is parsed, its semantic value becomes the
  2213. value of the entire @code{let}-statement. Then the semantic value from the
  2214. earlier action is used to restore the prior list of variables. This
  2215. removes the temporary @code{let}-variable from the list so that it won't
  2216. appear to exist while the rest of the program is parsed.
  2217. Taking action before a rule is completely recognized often leads to
  2218. conflicts since the parser must commit to a parse in order to execute the
  2219. action. For example, the following two rules, without mid-rule actions,
  2220. can coexist in a working parser because the parser can shift the open-brace
  2221. token and look at what follows before deciding whether there is a
  2222. declaration or not:
  2223. @example
  2224. @group
  2225. compound: '@{' declarations statements '@}'
  2226. | '@{' statements '@}'
  2227. ;
  2228. @end group
  2229. @end example
  2230. @noindent
  2231. But when we add a mid-rule action as follows, the rules become nonfunctional:
  2232. @example
  2233. @group
  2234. compound: @{ prepare_for_local_variables (); @}
  2235. '@{' declarations statements '@}'
  2236. @end group
  2237. @group
  2238. | '@{' statements '@}'
  2239. ;
  2240. @end group
  2241. @end example
  2242. @noindent
  2243. Now the parser is forced to decide whether to run the mid-rule action
  2244. when it has read no farther than the open-brace. In other words, it
  2245. must commit to using one rule or the other, without sufficient
  2246. information to do it correctly. (The open-brace token is what is called
  2247. the @dfn{look-ahead} token at this time, since the parser is still
  2248. deciding what to do about it. @xref{Look-Ahead, ,Look-Ahead Tokens}.)
  2249. You might think that you could correct the problem by putting identical
  2250. actions into the two rules, like this:
  2251. @example
  2252. @group
  2253. compound: @{ prepare_for_local_variables (); @}
  2254. '@{' declarations statements '@}'
  2255. | @{ prepare_for_local_variables (); @}
  2256. '@{' statements '@}'
  2257. ;
  2258. @end group
  2259. @end example
  2260. @noindent
  2261. But this does not help, because Bison does not realize that the two actions
  2262. are identical. (Bison never tries to understand the C code in an action.)
  2263. If the grammar is such that a declaration can be distinguished from a
  2264. statement by the first token (which is true in C), then one solution which
  2265. does work is to put the action after the open-brace, like this:
  2266. @example
  2267. @group
  2268. compound: '@{' @{ prepare_for_local_variables (); @}
  2269. declarations statements '@}'
  2270. | '@{' statements '@}'
  2271. ;
  2272. @end group
  2273. @end example
  2274. @noindent
  2275. Now the first token of the following declaration or statement,
  2276. which would in any case tell Bison which rule to use, can still do so.
  2277. Another solution is to bury the action inside a nonterminal symbol which
  2278. serves as a subroutine:
  2279. @example
  2280. @group
  2281. subroutine: /* empty */
  2282. @{ prepare_for_local_variables (); @}
  2283. ;
  2284. @end group
  2285. @group
  2286. compound: subroutine
  2287. '@{' declarations statements '@}'
  2288. | subroutine
  2289. '@{' statements '@}'
  2290. ;
  2291. @end group
  2292. @end example
  2293. @noindent
  2294. Now Bison can execute the action in the rule for @code{subroutine} without
  2295. deciding which rule for @code{compound} it will eventually use. Note that
  2296. the action is now at the end of its rule. Any mid-rule action can be
  2297. converted to an end-of-rule action in this way, and this is what Bison
  2298. actually does to implement mid-rule actions.
  2299. @node Declarations, Multiple Parsers, Semantics, Grammar File
  2300. @section Bison Declarations
  2301. @cindex declarations, Bison
  2302. @cindex Bison declarations
  2303. The @dfn{Bison declarations} section of a Bison grammar defines the symbols
  2304. used in formulating the grammar and the data types of semantic values.
  2305. @xref{Symbols}.
  2306. All token type names (but not single-character literal tokens such as
  2307. @code{'+'} and @code{'*'}) must be declared. Nonterminal symbols must be
  2308. declared if you need to specify which data type to use for the semantic
  2309. value (@pxref{Multiple Types, ,More Than One Value Type}).
  2310. The first rule in the file also specifies the start symbol, by default.
  2311. If you want some other symbol to be the start symbol, you must declare
  2312. it explicitly (@pxref{Language and Grammar, ,Languages and Context-Free Grammars}).
  2313. @menu
  2314. * Token Decl:: Declaring terminal symbols.
  2315. * Precedence Decl:: Declaring terminals with precedence and associativity.
  2316. * Union Decl:: Declaring the set of all semantic value types.
  2317. * Type Decl:: Declaring the choice of type for a nonterminal symbol.
  2318. * Expect Decl:: Suppressing warnings about shift/reduce conflicts.
  2319. * Start Decl:: Specifying the start symbol.
  2320. * Pure Decl:: Requesting a reentrant parser.
  2321. * Decl Summary:: Table of all Bison declarations.
  2322. @end menu
  2323. @node Token Decl, Precedence Decl, , Declarations
  2324. @subsection Token Type Names
  2325. @cindex declaring token type names
  2326. @cindex token type names, declaring
  2327. @findex %token
  2328. The basic way to declare a token type name (terminal symbol) is as follows:
  2329. @example
  2330. %token @var{name}
  2331. @end example
  2332. Bison will convert this into a @code{#define} directive in
  2333. the parser, so that the function @code{yylex} (if it is in this file)
  2334. can use the name @var{name} to stand for this token type's code.
  2335. Alternatively, you can use @code{%left}, @code{%right}, or @code{%nonassoc}
  2336. instead of @code{%token}, if you wish to specify precedence.
  2337. @xref{Precedence Decl, ,Operator Precedence}.
  2338. You can explicitly specify the numeric code for a token type by appending
  2339. an integer value in the field immediately following the token name:
  2340. @example
  2341. %token NUM 300
  2342. @end example
  2343. @noindent
  2344. It is generally best, however, to let Bison choose the numeric codes for
  2345. all token types. Bison will automatically select codes that don't conflict
  2346. with each other or with ASCII characters.
  2347. In the event that the stack type is a union, you must augment the
  2348. @code{%token} or other token declaration to include the data type
  2349. alternative delimited by angle-brackets (@pxref{Multiple Types, ,More Than One Value Type}).
  2350. For example:
  2351. @example
  2352. @group
  2353. %union @{ /* define stack type */
  2354. double val;
  2355. symrec *tptr;
  2356. @}
  2357. %token <val> NUM /* define token NUM and its type */
  2358. @end group
  2359. @end example
  2360. @node Precedence Decl, Union Decl, Token Decl, Declarations
  2361. @subsection Operator Precedence
  2362. @cindex precedence declarations
  2363. @cindex declaring operator precedence
  2364. @cindex operator precedence, declaring
  2365. Use the @code{%left}, @code{%right} or @code{%nonassoc} declaration to
  2366. declare a token and specify its precedence and associativity, all at
  2367. once. These are called @dfn{precedence declarations}.
  2368. @xref{Precedence, ,Operator Precedence}, for general information on operator precedence.
  2369. The syntax of a precedence declaration is the same as that of
  2370. @code{%token}: either
  2371. @example
  2372. %left @var{symbols}@dots{}
  2373. @end example
  2374. @noindent
  2375. or
  2376. @example
  2377. %left <@var{type}> @var{symbols}@dots{}
  2378. @end example
  2379. And indeed any of these declarations serves the purposes of @code{%token}.
  2380. But in addition, they specify the associativity and relative precedence for
  2381. all the @var{symbols}:
  2382. @itemize @bullet
  2383. @item
  2384. The associativity of an operator @var{op} determines how repeated uses
  2385. of the operator nest: whether @samp{@var{x} @var{op} @var{y} @var{op}
  2386. @var{z}} is parsed by grouping @var{x} with @var{y} first or by
  2387. grouping @var{y} with @var{z} first. @code{%left} specifies
  2388. left-associativity (grouping @var{x} with @var{y} first) and
  2389. @code{%right} specifies right-associativity (grouping @var{y} with
  2390. @var{z} first). @code{%nonassoc} specifies no associativity, which
  2391. means that @samp{@var{x} @var{op} @var{y} @var{op} @var{z}} is
  2392. considered a syntax error.
  2393. @item
  2394. The precedence of an operator determines how it nests with other operators.
  2395. All the tokens declared in a single precedence declaration have equal
  2396. precedence and nest together according to their associativity.
  2397. When two tokens declared in different precedence declarations associate,
  2398. the one declared later has the higher precedence and is grouped first.
  2399. @end itemize
  2400. @node Union Decl, Type Decl, Precedence Decl, Declarations
  2401. @subsection The Collection of Value Types
  2402. @cindex declaring value types
  2403. @cindex value types, declaring
  2404. @findex %union
  2405. The @code{%union} declaration specifies the entire collection of possible
  2406. data types for semantic values. The keyword @code{%union} is followed by a
  2407. pair of braces containing the same thing that goes inside a @code{union} in
  2408. C.
  2409. For example:
  2410. @example
  2411. @group
  2412. %union @{
  2413. double val;
  2414. symrec *tptr;
  2415. @}
  2416. @end group
  2417. @end example
  2418. @noindent
  2419. This says that the two alternative types are @code{double} and @code{symrec
  2420. *}. They are given names @code{val} and @code{tptr}; these names are used
  2421. in the @code{%token} and @code{%type} declarations to pick one of the types
  2422. for a terminal or nonterminal symbol (@pxref{Type Decl, ,Nonterminal Symbols}).
  2423. Note that, unlike making a @code{union} declaration in C, you do not write
  2424. a semicolon after the closing brace.
  2425. @node Type Decl, Expect Decl, Union Decl, Declarations
  2426. @subsection Nonterminal Symbols
  2427. @cindex declaring value types, nonterminals
  2428. @cindex value types, nonterminals, declaring
  2429. @findex %type
  2430. @noindent
  2431. When you use @code{%union} to specify multiple value types, you must
  2432. declare the value type of each nonterminal symbol for which values are
  2433. used. This is done with a @code{%type} declaration, like this:
  2434. @example
  2435. %type <@var{type}> @var{nonterminal}@dots{}
  2436. @end example
  2437. @noindent
  2438. Here @var{nonterminal} is the name of a nonterminal symbol, and @var{type}
  2439. is the name given in the @code{%union} to the alternative that you want
  2440. (@pxref{Union Decl, ,The Collection of Value Types}). You can give any number of nonterminal symbols in
  2441. the same @code{%type} declaration, if they have the same value type. Use
  2442. spaces to separate the symbol names.
  2443. @node Expect Decl, Start Decl, Type Decl, Declarations
  2444. @subsection Suppressing Conflict Warnings
  2445. @cindex suppressing conflict warnings
  2446. @cindex preventing warnings about conflicts
  2447. @cindex warnings, preventing
  2448. @cindex conflicts, suppressing warnings of
  2449. @findex %expect
  2450. Bison normally warns if there are any conflicts in the grammar
  2451. (@pxref{Shift/Reduce, ,Shift/Reduce Conflicts}), but most real grammars have harmless shift/reduce
  2452. conflicts which are resolved in a predictable way and would be difficult to
  2453. eliminate. It is desirable to suppress the warning about these conflicts
  2454. unless the number of conflicts changes. You can do this with the
  2455. @code{%expect} declaration.
  2456. The declaration looks like this:
  2457. @example
  2458. %expect @var{n}
  2459. @end example
  2460. Here @var{n} is a decimal integer. The declaration says there should be no
  2461. warning if there are @var{n} shift/reduce conflicts and no reduce/reduce
  2462. conflicts. The usual warning is given if there are either more or fewer
  2463. conflicts, or if there are any reduce/reduce conflicts.
  2464. In general, using @code{%expect} involves these steps:
  2465. @itemize @bullet
  2466. @item
  2467. Compile your grammar without @code{%expect}. Use the @samp{-v} option
  2468. to get a verbose list of where the conflicts occur. Bison will also
  2469. print the number of conflicts.
  2470. @item
  2471. Check each of the conflicts to make sure that Bison's default
  2472. resolution is what you really want. If not, rewrite the grammar and
  2473. go back to the beginning.
  2474. @item
  2475. Add an @code{%expect} declaration, copying the number @var{n} from the
  2476. number which Bison printed.
  2477. @end itemize
  2478. Now Bison will stop annoying you about the conflicts you have checked, but
  2479. it will warn you again if changes in the grammar result in additional
  2480. conflicts.
  2481. @node Start Decl, Pure Decl, Expect Decl, Declarations
  2482. @subsection The Start-Symbol
  2483. @cindex declaring the start symbol
  2484. @cindex start symbol, declaring
  2485. @cindex default start symbol
  2486. @findex %start
  2487. Bison assumes by default that the start symbol for the grammar is the first
  2488. nonterminal specified in the grammar specification section. The programmer
  2489. may override this restriction with the @code{%start} declaration as follows:
  2490. @example
  2491. %start @var{symbol}
  2492. @end example
  2493. @node Pure Decl, Decl Summary, Start Decl, Declarations
  2494. @subsection A Pure (Reentrant) Parser
  2495. @cindex reentrant parser
  2496. @cindex pure parser
  2497. @findex %pure_parser
  2498. A @dfn{reentrant} program is one which does not alter in the course of
  2499. execution; in other words, it consists entirely of @dfn{pure} (read-only)
  2500. code. Reentrancy is important whenever asynchronous execution is possible;
  2501. for example, a nonreentrant program may not be safe to call from a signal
  2502. handler. In systems with multiple threads of control, a nonreentrant
  2503. program must be called only within interlocks.
  2504. The Bison parser is not normally a reentrant program, because it uses
  2505. statically allocated variables for communication with @code{yylex}. These
  2506. variables include @code{yylval} and @code{yylloc}.
  2507. The Bison declaration @code{%pure_parser} says that you want the parser
  2508. to be reentrant. It looks like this:
  2509. @example
  2510. %pure_parser
  2511. @end example
  2512. The effect is that the two communication variables become local
  2513. variables in @code{yyparse}, and a different calling convention is used for
  2514. the lexical analyzer function @code{yylex}. @xref{Pure Calling, ,Calling for Pure Parsers}, for the
  2515. details of this. The variable @code{yynerrs} also becomes local in
  2516. @code{yyparse} (@pxref{Error Reporting, ,The Error Reporting Function @code{yyerror}}). The convention for calling
  2517. @code{yyparse} itself is unchanged.
  2518. @node Decl Summary, , Pure Decl, Declarations
  2519. @subsection Bison Declaration Summary
  2520. @cindex Bison declaration summary
  2521. @cindex declaration summary
  2522. @cindex summary, Bison declaration
  2523. Here is a summary of all Bison declarations:
  2524. @table @code
  2525. @item %union
  2526. Declare the collection of data types that semantic values may have
  2527. (@pxref{Union Decl, ,The Collection of Value Types}).
  2528. @item %token
  2529. Declare a terminal symbol (token type name) with no precedence
  2530. or associativity specified (@pxref{Token Decl, ,Token Type Names}).
  2531. @item %right
  2532. Declare a terminal symbol (token type name) that is right-associative
  2533. (@pxref{Precedence Decl, ,Operator Precedence}).
  2534. @item %left
  2535. Declare a terminal symbol (token type name) that is left-associative
  2536. (@pxref{Precedence Decl, ,Operator Precedence}).
  2537. @item %nonassoc
  2538. Declare a terminal symbol (token type name) that is nonassociative
  2539. (using it in a way that would be associative is a syntax error)
  2540. (@pxref{Precedence Decl, ,Operator Precedence}).
  2541. @item %type
  2542. Declare the type of semantic values for a nonterminal symbol
  2543. (@pxref{Type Decl, ,Nonterminal Symbols}).
  2544. @item %start
  2545. Specify the grammar's start symbol (@pxref{Start Decl, ,The Start-Symbol}).
  2546. @item %expect
  2547. Declare the expected number of shift-reduce conflicts
  2548. (@pxref{Expect Decl, ,Suppressing Conflict Warnings}).
  2549. @item %pure_parser
  2550. Request a pure (reentrant) parser program (@pxref{Pure Decl, ,A Pure (Reentrant) Parser}).
  2551. @end table
  2552. @node Multiple Parsers, , Declarations, Grammar File
  2553. @section Multiple Parsers in the Same Program
  2554. Most programs that use Bison parse only one language and therefore contain
  2555. only one Bison parser. But what if you want to parse more than one
  2556. language with the same program? Then you need to avoid a name conflict
  2557. between different definitions of @code{yyparse}, @code{yylval}, and so on.
  2558. The easy way to do this is to use the option @samp{-p @var{prefix}}
  2559. (@pxref{Invocation, ,Invoking Bison}). This renames the interface functions and
  2560. variables of the Bison parser to start with @var{prefix} instead of
  2561. @samp{yy}. You can use this to give each parser distinct names that do
  2562. not conflict.
  2563. The precise list of symbols renamed is @code{yyparse}, @code{yylex},
  2564. @code{yyerror}, @code{yylval}, @code{yychar} and @code{yydebug}. For
  2565. example, if you use @samp{-p c}, the names become @code{cparse},
  2566. @code{clex}, and so on.
  2567. @strong{All the other variables and macros associated with Bison are not
  2568. renamed.} These others are not global; there is no conflict if the same
  2569. name is used in different parsers. For example, @code{YYSTYPE} is not
  2570. renamed, but defining this in different ways in different parsers causes
  2571. no trouble (@pxref{Value Type, ,Data Types of Semantic Values}).
  2572. The @samp{-p} option works by adding macro definitions to the beginning
  2573. of the parser source file, defining @code{yyparse} as
  2574. @code{@var{prefix}parse}, and so on. This effectively substitutes one
  2575. name for the other in the entire parser file.
  2576. @node Interface, Algorithm, Grammar File, Top
  2577. @chapter Parser C-Language Interface
  2578. @cindex C-language interface
  2579. @cindex interface
  2580. The Bison parser is actually a C function named @code{yyparse}. Here we
  2581. describe the interface conventions of @code{yyparse} and the other
  2582. functions that it needs to use.
  2583. Keep in mind that the parser uses many C identifiers starting with
  2584. @samp{yy} and @samp{YY} for internal purposes. If you use such an
  2585. identifier (aside from those in this manual) in an action or in additional
  2586. C code in the grammar file, you are likely to run into trouble.
  2587. @menu
  2588. * Parser Function:: How to call @code{yyparse} and what it returns.
  2589. * Lexical:: You must supply a function @code{yylex}
  2590. which reads tokens.
  2591. * Error Reporting:: You must supply a function @code{yyerror}.
  2592. * Action Features:: Special features for use in actions.
  2593. @end menu
  2594. @node Parser Function, Lexical, , Interface
  2595. @section The Parser Function @code{yyparse}
  2596. @findex yyparse
  2597. You call the function @code{yyparse} to cause parsing to occur. This
  2598. function reads tokens, executes actions, and ultimately returns when it
  2599. encounters end-of-input or an unrecoverable syntax error. You can also
  2600. write an action which directs @code{yyparse} to return immediately without
  2601. reading further.
  2602. The value returned by @code{yyparse} is 0 if parsing was successful (return
  2603. is due to end-of-input).
  2604. The value is 1 if parsing failed (return is due to a syntax error).
  2605. In an action, you can cause immediate return from @code{yyparse} by using
  2606. these macros:
  2607. @table @code
  2608. @item YYACCEPT
  2609. @findex YYACCEPT
  2610. Return immediately with value 0 (to report success).
  2611. @item YYABORT
  2612. @findex YYABORT
  2613. Return immediately with value 1 (to report failure).
  2614. @end table
  2615. @node Lexical, Error Reporting, Parser Function, Interface
  2616. @section The Lexical Analyzer Function @code{yylex}
  2617. @findex yylex
  2618. @cindex lexical analyzer
  2619. The @dfn{lexical analyzer} function, @code{yylex}, recognizes tokens from
  2620. the input stream and returns them to the parser. Bison does not create
  2621. this function automatically; you must write it so that @code{yyparse} can
  2622. call it. The function is sometimes referred to as a lexical scanner.
  2623. In simple programs, @code{yylex} is often defined at the end of the Bison
  2624. grammar file. If @code{yylex} is defined in a separate source file, you
  2625. need to arrange for the token-type macro definitions to be available there.
  2626. To do this, use the @samp{-d} option when you run Bison, so that it will
  2627. write these macro definitions into a separate header file
  2628. @file{@var{name}.tab.h} which you can include in the other source files
  2629. that need it. @xref{Invocation, ,Invoking Bison}.@refill
  2630. @menu
  2631. * Calling Convention:: How @code{yyparse} calls @code{yylex}.
  2632. * Token Values:: How @code{yylex} must return the semantic value
  2633. of the token it has read.
  2634. * Token Positions:: How @code{yylex} must return the text position
  2635. (line number, etc.) of the token, if the
  2636. actions want that.
  2637. * Pure Calling:: How the calling convention differs
  2638. in a pure parser (@pxref{Pure Decl, ,A Pure (Reentrant) Parser}).
  2639. @end menu
  2640. @node Calling Convention, Token Values, , Lexical
  2641. @subsection Calling Convention for @code{yylex}
  2642. The value that @code{yylex} returns must be the numeric code for the type
  2643. of token it has just found, or 0 for end-of-input.
  2644. When a token is referred to in the grammar rules by a name, that name
  2645. in the parser file becomes a C macro whose definition is the proper
  2646. numeric code for that token type. So @code{yylex} can use the name
  2647. to indicate that type. @xref{Symbols}.
  2648. When a token is referred to in the grammar rules by a character literal,
  2649. the numeric code for that character is also the code for the token type.
  2650. So @code{yylex} can simply return that character code. The null character
  2651. must not be used this way, because its code is zero and that is what
  2652. signifies end-of-input.
  2653. Here is an example showing these things:
  2654. @example
  2655. yylex ()
  2656. @{
  2657. @dots{}
  2658. if (c == EOF) /* Detect end of file. */
  2659. return 0;
  2660. @dots{}
  2661. if (c == '+' || c == '-')
  2662. return c; /* Assume token type for `+' is '+'. */
  2663. @dots{}
  2664. return INT; /* Return the type of the token. */
  2665. @dots{}
  2666. @}
  2667. @end example
  2668. @noindent
  2669. This interface has been designed so that the output from the @code{lex}
  2670. utility can be used without change as the definition of @code{yylex}.
  2671. @node Token Values, Token Positions, Calling Convention, Lexical
  2672. @subsection Semantic Values of Tokens
  2673. @vindex yylval
  2674. In an ordinary (nonreentrant) parser, the semantic value of the token must
  2675. be stored into the global variable @code{yylval}. When you are using
  2676. just one data type for semantic values, @code{yylval} has that type.
  2677. Thus, if the type is @code{int} (the default), you might write this in
  2678. @code{yylex}:
  2679. @example
  2680. @group
  2681. @dots{}
  2682. yylval = value; /* Put value onto Bison stack. */
  2683. return INT; /* Return the type of the token. */
  2684. @dots{}
  2685. @end group
  2686. @end example
  2687. When you are using multiple data types, @code{yylval}'s type is a union
  2688. made from the @code{%union} declaration (@pxref{Union Decl, ,The Collection of Value Types}). So when
  2689. you store a token's value, you must use the proper member of the union.
  2690. If the @code{%union} declaration looks like this:
  2691. @example
  2692. @group
  2693. %union @{
  2694. int intval;
  2695. double val;
  2696. symrec *tptr;
  2697. @}
  2698. @end group
  2699. @end example
  2700. @noindent
  2701. then the code in @code{yylex} might look like this:
  2702. @example
  2703. @group
  2704. @dots{}
  2705. yylval.intval = value; /* Put value onto Bison stack. */
  2706. return INT; /* Return the type of the token. */
  2707. @dots{}
  2708. @end group
  2709. @end example
  2710. @node Token Positions, Pure Calling, Token Values, Lexical
  2711. @subsection Textual Positions of Tokens
  2712. @vindex yylloc
  2713. If you are using the @samp{@@@var{n}}-feature (@pxref{Action Features, ,Special Features for Use in Actions}) in
  2714. actions to keep track of the textual locations of tokens and groupings,
  2715. then you must provide this information in @code{yylex}. The function
  2716. @code{yyparse} expects to find the textual location of a token just parsed
  2717. in the global variable @code{yylloc}. So @code{yylex} must store the
  2718. proper data in that variable. The value of @code{yylloc} is a structure
  2719. and you need only initialize the members that are going to be used by the
  2720. actions. The four members are called @code{first_line},
  2721. @code{first_column}, @code{last_line} and @code{last_column}. Note that
  2722. the use of this feature makes the parser noticeably slower.
  2723. @tindex YYLTYPE
  2724. The data type of @code{yylloc} has the name @code{YYLTYPE}.
  2725. @node Pure Calling, , Token Positions, Lexical
  2726. @subsection Calling for Pure Parsers
  2727. When you use the Bison declaration @code{%pure_parser} to request a pure,
  2728. reentrant parser, the global communication variables @code{yylval} and
  2729. @code{yylloc} cannot be used. (@xref{Pure Decl, ,A Pure (Reentrant) Parser}.) In such parsers the
  2730. two global variables are replaced by pointers passed as arguments to
  2731. @code{yylex}. You must declare them as shown here, and pass the
  2732. information back by storing it through those pointers.
  2733. @example
  2734. yylex (lvalp, llocp)
  2735. YYSTYPE *lvalp;
  2736. YYLTYPE *llocp;
  2737. @{
  2738. @dots{}
  2739. *lvalp = value; /* Put value onto Bison stack. */
  2740. return INT; /* Return the type of the token. */
  2741. @dots{}
  2742. @}
  2743. @end example
  2744. If the grammar file does not use the @samp{@@} constructs to refer to
  2745. textual positions, then the type @code{YYLTYPE} will not be defined. In
  2746. this case, omit the second argument; @code{yylex} will be called with
  2747. only one argument.
  2748. @node Error Reporting, Action Features, Lexical, Interface
  2749. @section The Error Reporting Function @code{yyerror}
  2750. @cindex error reporting function
  2751. @findex yyerror
  2752. @cindex parse error
  2753. @cindex syntax error
  2754. The Bison parser detects a @dfn{parse error} or @dfn{syntax error}
  2755. whenever it reads a token which cannot satisfy any syntax rule. A
  2756. action in the grammar can also explicitly proclaim an error, using the
  2757. macro @code{YYERROR} (@pxref{Action Features, ,Special Features for Use in Actions}).
  2758. The Bison parser expects to report the error by calling an error
  2759. reporting function named @code{yyerror}, which you must supply. It is
  2760. called by @code{yyparse} whenever a syntax error is found, and it
  2761. receives one argument. For a parse error, the string is normally
  2762. @w{@code{"parse error"}}.
  2763. @findex YYERROR_VERBOSE
  2764. If you define the macro @code{YYERROR_VERBOSE} in the Bison declarations
  2765. section (@pxref{Bison Declarations, ,The Bison Declarations Section}), then Bison provides a more verbose
  2766. and specific error message string instead of just plain @w{@code{"parse
  2767. error"}}. It doesn't matter what definition you use for
  2768. @code{YYERROR_VERBOSE}, just whether you define it.
  2769. The parser can detect one other kind of error: stack overflow. This
  2770. happens when the input contains constructions that are very deeply
  2771. nested. It isn't likely you will encounter this, since the Bison
  2772. parser extends its stack automatically up to a very large limit. But
  2773. if overflow happens, @code{yyparse} calls @code{yyerror} in the usual
  2774. fashion, except that the argument string is @w{@code{"parser stack
  2775. overflow"}}.
  2776. The following definition suffices in simple programs:
  2777. @example
  2778. @group
  2779. yyerror (s)
  2780. char *s;
  2781. @{
  2782. @end group
  2783. @group
  2784. fprintf (stderr, "%s\n", s);
  2785. @}
  2786. @end group
  2787. @end example
  2788. After @code{yyerror} returns to @code{yyparse}, the latter will attempt
  2789. error recovery if you have written suitable error recovery grammar rules
  2790. (@pxref{Error Recovery}). If recovery is impossible, @code{yyparse} will
  2791. immediately return 1.
  2792. @vindex yynerrs
  2793. The variable @code{yynerrs} contains the number of syntax errors
  2794. encountered so far. Normally this variable is global; but if you
  2795. request a pure parser (@pxref{Pure Decl, ,A Pure (Reentrant) Parser}) then it is a local variable
  2796. which only the actions can access.
  2797. @node Action Features, , Error Reporting, Interface
  2798. @section Special Features for Use in Actions
  2799. @cindex summary, action features
  2800. @cindex action features summary
  2801. Here is a table of Bison constructs, variables and macros that
  2802. are useful in actions.
  2803. @table @samp
  2804. @item $$
  2805. Acts like a variable that contains the semantic value for the
  2806. grouping made by the current rule. @xref{Actions}.
  2807. @item $@var{n}
  2808. Acts like a variable that contains the semantic value for the
  2809. @var{n}th component of the current rule. @xref{Actions}.
  2810. @item $<@var{typealt}>$
  2811. Like @code{$$} but specifies alternative @var{typealt} in the union
  2812. specified by the @code{%union} declaration. @xref{Action Types, ,Data Types of Values in Actions}.
  2813. @item $<@var{typealt}>@var{n}
  2814. Like @code{$@var{n}} but specifies alternative @var{typealt} in the
  2815. union specified by the @code{%union} declaration.
  2816. @xref{Action Types, ,Data Types of Values in Actions}.@refill
  2817. @item YYABORT;
  2818. Return immediately from @code{yyparse}, indicating failure.
  2819. @xref{Parser Function, ,The Parser Function @code{yyparse}}.
  2820. @item YYACCEPT;
  2821. Return immediately from @code{yyparse}, indicating success.
  2822. @xref{Parser Function, ,The Parser Function @code{yyparse}}.
  2823. @item YYBACKUP (@var{token}, @var{value});
  2824. @findex YYBACKUP
  2825. Unshift a token. This macro is allowed only for rules that reduce
  2826. a single value, and only when there is no look-ahead token.
  2827. It installs a look-ahead token with token type @var{token} and
  2828. semantic value @var{value}; then it discards the value that was
  2829. going to be reduced by this rule.
  2830. If the macro is used when it is not valid, such as when there is
  2831. a look-ahead token already, then it reports a syntax error with
  2832. a message @samp{cannot back up} and performs ordinary error
  2833. recovery.
  2834. In either case, the rest of the action is not executed.
  2835. @item YYEMPTY
  2836. @vindex YYEMPTY
  2837. Value stored in @code{yychar} when there is no look-ahead token.
  2838. @item YYERROR;
  2839. @findex YYERROR
  2840. Cause an immediate syntax error. This statement initiates error
  2841. recovery just as if the parser itself had detected an error; however, it
  2842. does not call @code{yyerror}, and does not print any message. If you
  2843. want to print an error message, call @code{yyerror} explicitly before
  2844. the @samp{YYERROR;} statement. @xref{Error Recovery}.
  2845. @item YYRECOVERING
  2846. This macro stands for an expression that has the value 1 when the parser
  2847. is recovering from a syntax error, and 0 the rest of the time.
  2848. @xref{Error Recovery}.
  2849. @item yychar
  2850. Variable containing the current look-ahead token. (In a pure parser,
  2851. this is actually a local variable within @code{yyparse}.) When there is
  2852. no look-ahead token, the value @code{YYEMPTY} is stored in the variable.
  2853. @xref{Look-Ahead, ,Look-Ahead Tokens}.
  2854. @item yyclearin;
  2855. Discard the current look-ahead token. This is useful primarily in
  2856. error rules. @xref{Error Recovery}.
  2857. @item yyerrok;
  2858. Resume generating error messages immediately for subsequent syntax
  2859. errors. This is useful primarily in error rules.
  2860. @xref{Error Recovery}.
  2861. @item @@@var{n}
  2862. @findex @@@var{n}
  2863. Acts like a structure variable containing information on the line
  2864. numbers and column numbers of the @var{n}th component of the current
  2865. rule. The structure has four members, like this:
  2866. @example
  2867. struct @{
  2868. int first_line, last_line;
  2869. int first_column, last_column;
  2870. @};
  2871. @end example
  2872. Thus, to get the starting line number of the third component, use
  2873. @samp{@@3.first_line}.
  2874. In order for the members of this structure to contain valid information,
  2875. you must make @code{yylex} supply this information about each token.
  2876. If you need only certain members, then @code{yylex} need only fill in
  2877. those members.
  2878. The use of this feature makes the parser noticeably slower.
  2879. @end table
  2880. @node Algorithm, Error Recovery, Interface, Top
  2881. @chapter The Bison Parser Algorithm
  2882. @cindex Bison parser algorithm
  2883. @cindex algorithm of parser
  2884. @cindex shifting
  2885. @cindex reduction
  2886. @cindex parser stack
  2887. @cindex stack, parser
  2888. As Bison reads tokens, it pushes them onto a stack along with their
  2889. semantic values. The stack is called the @dfn{parser stack}. Pushing a
  2890. token is traditionally called @dfn{shifting}.
  2891. For example, suppose the infix calculator has read @samp{1 + 5 *}, with a
  2892. @samp{3} to come. The stack will have four elements, one for each token
  2893. that was shifted.
  2894. But the stack does not always have an element for each token read. When
  2895. the last @var{n} tokens and groupings shifted match the components of a
  2896. grammar rule, they can be combined according to that rule. This is called
  2897. @dfn{reduction}. Those tokens and groupings are replaced on the stack by a
  2898. single grouping whose symbol is the result (left hand side) of that rule.
  2899. Running the rule's action is part of the process of reduction, because this
  2900. is what computes the semantic value of the resulting grouping.
  2901. For example, if the infix calculator's parser stack contains this:
  2902. @example
  2903. 1 + 5 * 3
  2904. @end example
  2905. @noindent
  2906. and the next input token is a newline character, then the last three
  2907. elements can be reduced to 15 via the rule:
  2908. @example
  2909. expr: expr '*' expr;
  2910. @end example
  2911. @noindent
  2912. Then the stack contains just these three elements:
  2913. @example
  2914. 1 + 15
  2915. @end example
  2916. @noindent
  2917. At this point, another reduction can be made, resulting in the single value
  2918. 16. Then the newline token can be shifted.
  2919. The parser tries, by shifts and reductions, to reduce the entire input down
  2920. to a single grouping whose symbol is the grammar's start-symbol
  2921. (@pxref{Language and Grammar, ,Languages and Context-Free Grammars}).
  2922. This kind of parser is known in the literature as a bottom-up parser.
  2923. @menu
  2924. * Look-Ahead:: Parser looks one token ahead when deciding what to do.
  2925. * Shift/Reduce:: Conflicts: when either shifting or reduction is valid.
  2926. * Precedence:: Operator precedence works by resolving conflicts.
  2927. * Contextual Precedence:: When an operator's precedence depends on context.
  2928. * Parser States:: The parser is a finite-state-machine with stack.
  2929. * Reduce/Reduce:: When two rules are applicable in the same situation.
  2930. * Mystery Conflicts:: Reduce/reduce conflicts that look unjustified.
  2931. * Stack Overflow:: What happens when stack gets full. How to avoid it.
  2932. @end menu
  2933. @node Look-Ahead, Shift/Reduce, , Algorithm
  2934. @section Look-Ahead Tokens
  2935. @cindex look-ahead token
  2936. The Bison parser does @emph{not} always reduce immediately as soon as the
  2937. last @var{n} tokens and groupings match a rule. This is because such a
  2938. simple strategy is inadequate to handle most languages. Instead, when a
  2939. reduction is possible, the parser sometimes ``looks ahead'' at the next
  2940. token in order to decide what to do.
  2941. When a token is read, it is not immediately shifted; first it becomes the
  2942. @dfn{look-ahead token}, which is not on the stack. Now the parser can
  2943. perform one or more reductions of tokens and groupings on the stack, while
  2944. the look-ahead token remains off to the side. When no more reductions
  2945. should take place, the look-ahead token is shifted onto the stack. This
  2946. does not mean that all possible reductions have been done; depending on the
  2947. token type of the look-ahead token, some rules may choose to delay their
  2948. application.
  2949. Here is a simple case where look-ahead is needed. These three rules define
  2950. expressions which contain binary addition operators and postfix unary
  2951. factorial operators (@samp{!}), and allow parentheses for grouping.
  2952. @example
  2953. @group
  2954. expr: term '+' expr
  2955. | term
  2956. ;
  2957. @end group
  2958. @group
  2959. term: '(' expr ')'
  2960. | term '!'
  2961. | NUMBER
  2962. ;
  2963. @end group
  2964. @end example
  2965. Suppose that the tokens @w{@samp{1 + 2}} have been read and shifted; what
  2966. should be done? If the following token is @samp{)}, then the first three
  2967. tokens must be reduced to form an @code{expr}. This is the only valid
  2968. course, because shifting the @samp{)} would produce a sequence of symbols
  2969. @w{@code{term ')'}}, and no rule allows this.
  2970. If the following token is @samp{!}, then it must be shifted immediately so
  2971. that @w{@samp{2 !}} can be reduced to make a @code{term}. If instead the
  2972. parser were to reduce before shifting, @w{@samp{1 + 2}} would become an
  2973. @code{expr}. It would then be impossible to shift the @samp{!} because
  2974. doing so would produce on the stack the sequence of symbols @code{expr
  2975. '!'}. No rule allows that sequence.
  2976. @vindex yychar
  2977. The current look-ahead token is stored in the variable @code{yychar}.
  2978. @xref{Action Features, ,Special Features for Use in Actions}.
  2979. @node Shift/Reduce, Precedence, Look-Ahead, Algorithm
  2980. @section Shift/Reduce Conflicts
  2981. @cindex conflicts
  2982. @cindex shift/reduce conflicts
  2983. @cindex dangling @code{else}
  2984. @cindex @code{else}, dangling
  2985. Suppose we are parsing a language which has if-then and if-then-else
  2986. statements, with a pair of rules like this:
  2987. @example
  2988. @group
  2989. if_stmt:
  2990. IF expr THEN stmt
  2991. | IF expr THEN stmt ELSE stmt
  2992. ;
  2993. @end group
  2994. @end example
  2995. @noindent
  2996. Here we assume that @code{IF}, @code{THEN} and @code{ELSE} are
  2997. terminal symbols for specific keyword tokens.
  2998. When the @code{ELSE} token is read and becomes the look-ahead token, the
  2999. contents of the stack (assuming the input is valid) are just right for
  3000. reduction by the first rule. But it is also legitimate to shift the
  3001. @code{ELSE}, because that would lead to eventual reduction by the second
  3002. rule.
  3003. This situation, where either a shift or a reduction would be valid, is
  3004. called a @dfn{shift/reduce conflict}. Bison is designed to resolve
  3005. these conflicts by choosing to shift, unless otherwise directed by
  3006. operator precedence declarations. To see the reason for this, let's
  3007. contrast it with the other alternative.
  3008. Since the parser prefers to shift the @code{ELSE}, the result is to attach
  3009. the else-clause to the innermost if-statement, making these two inputs
  3010. equivalent:
  3011. @example
  3012. if x then if y then win (); else lose;
  3013. if x then do; if y then win (); else lose; end;
  3014. @end example
  3015. But if the parser chose to reduce when possible rather than shift, the
  3016. result would be to attach the else-clause to the outermost if-statement,
  3017. making these two inputs equivalent:
  3018. @example
  3019. if x then if y then win (); else lose;
  3020. if x then do; if y then win (); end; else lose;
  3021. @end example
  3022. The conflict exists because the grammar as written is ambiguous: either
  3023. parsing of the simple nested if-statement is legitimate. The established
  3024. convention is that these ambiguities are resolved by attaching the
  3025. else-clause to the innermost if-statement; this is what Bison accomplishes
  3026. by choosing to shift rather than reduce. (It would ideally be cleaner to
  3027. write an unambiguous grammar, but that is very hard to do in this case.)
  3028. This particular ambiguity was first encountered in the specifications of
  3029. Algol 60 and is called the ``dangling @code{else}'' ambiguity.
  3030. To avoid warnings from Bison about predictable, legitimate shift/reduce
  3031. conflicts, use the @code{%expect @var{n}} declaration. There will be no
  3032. warning as long as the number of shift/reduce conflicts is exactly @var{n}.
  3033. @xref{Expect Decl, ,Suppressing Conflict Warnings}.
  3034. The definition of @code{if_stmt} above is solely to blame for the
  3035. conflict, but the conflict does not actually appear without additional
  3036. rules. Here is a complete Bison input file that actually manifests the
  3037. conflict:
  3038. @example
  3039. @group
  3040. %token IF THEN ELSE variable
  3041. %%
  3042. @end group
  3043. @group
  3044. stmt: expr
  3045. | if_stmt
  3046. ;
  3047. @end group
  3048. @group
  3049. if_stmt:
  3050. IF expr THEN stmt
  3051. | IF expr THEN stmt ELSE stmt
  3052. ;
  3053. @end group
  3054. expr: variable
  3055. ;
  3056. @end example
  3057. @node Precedence, Contextual Precedence, Shift/Reduce, Algorithm
  3058. @section Operator Precedence
  3059. @cindex operator precedence
  3060. @cindex precedence of operators
  3061. Another situation where shift/reduce conflicts appear is in arithmetic
  3062. expressions. Here shifting is not always the preferred resolution; the
  3063. Bison declarations for operator precedence allow you to specify when to
  3064. shift and when to reduce.
  3065. @menu
  3066. * Why Precedence:: An example showing why precedence is needed.
  3067. * Using Precedence:: How to specify precedence in Bison grammars.
  3068. * Precedence Examples:: How these features are used in the previous example.
  3069. * How Precedence:: How they work.
  3070. @end menu
  3071. @node Why Precedence, Using Precedence, , Precedence
  3072. @subsection When Precedence is Needed
  3073. Consider the following ambiguous grammar fragment (ambiguous because the
  3074. input @w{@samp{1 - 2 * 3}} can be parsed in two different ways):
  3075. @example
  3076. @group
  3077. expr: expr '-' expr
  3078. | expr '*' expr
  3079. | expr '<' expr
  3080. | '(' expr ')'
  3081. @dots{}
  3082. ;
  3083. @end group
  3084. @end example
  3085. @noindent
  3086. Suppose the parser has seen the tokens @samp{1}, @samp{-} and @samp{2};
  3087. should it reduce them via the rule for the addition operator? It depends
  3088. on the next token. Of course, if the next token is @samp{)}, we must
  3089. reduce; shifting is invalid because no single rule can reduce the token
  3090. sequence @w{@samp{- 2 )}} or anything starting with that. But if the next
  3091. token is @samp{*} or @samp{<}, we have a choice: either shifting or
  3092. reduction would allow the parse to complete, but with different
  3093. results.
  3094. To decide which one Bison should do, we must consider the
  3095. results. If the next operator token @var{op} is shifted, then it
  3096. must be reduced first in order to permit another opportunity to
  3097. reduce the sum. The result is (in effect) @w{@samp{1 - (2
  3098. @var{op} 3)}}. On the other hand, if the subtraction is reduced
  3099. before shifting @var{op}, the result is @w{@samp{(1 - 2) @var{op}
  3100. 3}}. Clearly, then, the choice of shift or reduce should depend
  3101. on the relative precedence of the operators @samp{-} and
  3102. @var{op}: @samp{*} should be shifted first, but not @samp{<}.
  3103. @cindex associativity
  3104. What about input such as @w{@samp{1 - 2 - 5}}; should this be
  3105. @w{@samp{(1 - 2) - 5}} or should it be @w{@samp{1 - (2 - 5)}}? For
  3106. most operators we prefer the former, which is called @dfn{left
  3107. association}. The latter alternative, @dfn{right association}, is
  3108. desirable for assignment operators. The choice of left or right
  3109. association is a matter of whether the parser chooses to shift or
  3110. reduce when the stack contains @w{@samp{1 - 2}} and the look-ahead
  3111. token is @samp{-}: shifting makes right-associativity.
  3112. @node Using Precedence, Precedence Examples, Why Precedence, Precedence
  3113. @subsection Specifying Operator Precedence
  3114. @findex %left
  3115. @findex %right
  3116. @findex %nonassoc
  3117. Bison allows you to specify these choices with the operator precedence
  3118. declarations @code{%left} and @code{%right}. Each such declaration
  3119. contains a list of tokens, which are operators whose precedence and
  3120. associativity is being declared. The @code{%left} declaration makes all
  3121. those operators left-associative and the @code{%right} declaration makes
  3122. them right-associative. A third alternative is @code{%nonassoc}, which
  3123. declares that it is a syntax error to find the same operator twice ``in a
  3124. row''.
  3125. The relative precedence of different operators is controlled by the
  3126. order in which they are declared. The first @code{%left} or
  3127. @code{%right} declaration in the file declares the operators whose
  3128. precedence is lowest, the next such declaration declares the operators
  3129. whose precedence is a little higher, and so on.
  3130. @node Precedence Examples, How Precedence, Using Precedence, Precedence
  3131. @subsection Precedence Examples
  3132. In our example, we would want the following declarations:
  3133. @example
  3134. %left '<'
  3135. %left '-'
  3136. %left '*'
  3137. @end example
  3138. In a more complete example, which supports other operators as well, we
  3139. would declare them in groups of equal precedence. For example, @code{'+'} is
  3140. declared with @code{'-'}:
  3141. @example
  3142. %left '<' '>' '=' NE LE GE
  3143. %left '+' '-'
  3144. %left '*' '/'
  3145. @end example
  3146. @noindent
  3147. (Here @code{NE} and so on stand for the operators for ``not equal''
  3148. and so on. We assume that these tokens are more than one character long
  3149. and therefore are represented by names, not character literals.)
  3150. @node How Precedence, , Precedence Examples, Precedence
  3151. @subsection How Precedence Works
  3152. The first effect of the precedence declarations is to assign precedence
  3153. levels to the terminal symbols declared. The second effect is to assign
  3154. precedence levels to certain rules: each rule gets its precedence from the
  3155. last terminal symbol mentioned in the components. (You can also specify
  3156. explicitly the precedence of a rule. @xref{Contextual Precedence, ,Context-Dependent Precedence}.)
  3157. Finally, the resolution of conflicts works by comparing the
  3158. precedence of the rule being considered with that of the
  3159. look-ahead token. If the token's precedence is higher, the
  3160. choice is to shift. If the rule's precedence is higher, the
  3161. choice is to reduce. If they have equal precedence, the choice
  3162. is made based on the associativity of that precedence level. The
  3163. verbose output file made by @samp{-v} (@pxref{Invocation, ,Invoking Bison}) says
  3164. how each conflict was resolved.
  3165. Not all rules and not all tokens have precedence. If either the rule or
  3166. the look-ahead token has no precedence, then the default is to shift.
  3167. @node Contextual Precedence, Parser States, Precedence, Algorithm
  3168. @section Context-Dependent Precedence
  3169. @cindex context-dependent precedence
  3170. @cindex unary operator precedence
  3171. @cindex precedence, context-dependent
  3172. @cindex precedence, unary operator
  3173. @findex %prec
  3174. Often the precedence of an operator depends on the context. This sounds
  3175. outlandish at first, but it is really very common. For example, a minus
  3176. sign typically has a very high precedence as a unary operator, and a
  3177. somewhat lower precedence (lower than multiplication) as a binary operator.
  3178. The Bison precedence declarations, @code{%left}, @code{%right} and
  3179. @code{%nonassoc}, can only be used once for a given token; so a token has
  3180. only one precedence declared in this way. For context-dependent
  3181. precedence, you need to use an additional mechanism: the @code{%prec}
  3182. modifier for rules.@refill
  3183. The @code{%prec} modifier declares the precedence of a particular rule by
  3184. specifying a terminal symbol whose precedence should be used for that rule.
  3185. It's not necessary for that symbol to appear otherwise in the rule. The
  3186. modifier's syntax is:
  3187. @example
  3188. %prec @var{terminal-symbol}
  3189. @end example
  3190. @noindent
  3191. and it is written after the components of the rule. Its effect is to
  3192. assign the rule the precedence of @var{terminal-symbol}, overriding
  3193. the precedence that would be deduced for it in the ordinary way. The
  3194. altered rule precedence then affects how conflicts involving that rule
  3195. are resolved (@pxref{Precedence, ,Operator Precedence}).
  3196. Here is how @code{%prec} solves the problem of unary minus. First, declare
  3197. a precedence for a fictitious terminal symbol named @code{UMINUS}. There
  3198. are no tokens of this type, but the symbol serves to stand for its
  3199. precedence:
  3200. @example
  3201. @dots{}
  3202. %left '+' '-'
  3203. %left '*'
  3204. %left UMINUS
  3205. @end example
  3206. Now the precedence of @code{UMINUS} can be used in specific rules:
  3207. @example
  3208. @group
  3209. exp: @dots{}
  3210. | exp '-' exp
  3211. @dots{}
  3212. | '-' exp %prec UMINUS
  3213. @end group
  3214. @end example
  3215. @node Parser States, Reduce/Reduce, Contextual Precedence, Algorithm
  3216. @section Parser States
  3217. @cindex finite-state machine
  3218. @cindex parser state
  3219. @cindex state (of parser)
  3220. The function @code{yyparse} is implemented using a finite-state machine.
  3221. The values pushed on the parser stack are not simply token type codes; they
  3222. represent the entire sequence of terminal and nonterminal symbols at or
  3223. near the top of the stack. The current state collects all the information
  3224. about previous input which is relevant to deciding what to do next.
  3225. Each time a look-ahead token is read, the current parser state together
  3226. with the type of look-ahead token are looked up in a table. This table
  3227. entry can say, ``Shift the look-ahead token.'' In this case, it also
  3228. specifies the new parser state, which is pushed onto the top of the
  3229. parser stack. Or it can say, ``Reduce using rule number @var{n}.''
  3230. This means that a certain number of tokens or groupings are taken off
  3231. the top of the stack, and replaced by one grouping. In other words,
  3232. that number of states are popped from the stack, and one new state is
  3233. pushed.
  3234. There is one other alternative: the table can say that the look-ahead token
  3235. is erroneous in the current state. This causes error processing to begin
  3236. (@pxref{Error Recovery}).
  3237. @node Reduce/Reduce, Mystery Conflicts, Parser States, Algorithm
  3238. @section Reduce/Reduce Conflicts
  3239. @cindex reduce/reduce conflict
  3240. @cindex conflicts, reduce/reduce
  3241. A reduce/reduce conflict occurs if there are two or more rules that apply
  3242. to the same sequence of input. This usually indicates a serious error
  3243. in the grammar.
  3244. For example, here is an erroneous attempt to define a sequence
  3245. of zero or more @code{word} groupings.
  3246. @example
  3247. sequence: /* empty */
  3248. @{ printf ("empty sequence\n"); @}
  3249. | maybeword
  3250. | sequence word
  3251. @{ printf ("added word %s\n", $2); @}
  3252. ;
  3253. maybeword: /* empty */
  3254. @{ printf ("empty maybeword\n"); @}
  3255. | word
  3256. @{ printf ("single word %s\n", $1); @}
  3257. ;
  3258. @end example
  3259. @noindent
  3260. The error is an ambiguity: there is more than one way to parse a single
  3261. @code{word} into a @code{sequence}. It could be reduced to a
  3262. @code{maybeword} and then into a @code{sequence} via the second rule.
  3263. Alternatively, nothing-at-all could be reduced into a @code{sequence}
  3264. via the first rule, and this could be combined with the @code{word}
  3265. using the third rule for @code{sequence}.
  3266. There is also more than one way to reduce nothing-at-all into a
  3267. @code{sequence}. This can be done directly via the first rule,
  3268. or indirectly via @code{maybeword} and then the second rule.
  3269. You might think that this is a distinction without a difference, because it
  3270. does not change whether any particular input is valid or not. But it does
  3271. affect which actions are run. One parsing order runs the second rule's
  3272. action; the other runs the first rule's action and the third rule's action.
  3273. In this example, the output of the program changes.
  3274. Bison resolves a reduce/reduce conflict by choosing to use the rule that
  3275. appears first in the grammar, but it is very risky to rely on this. Every
  3276. reduce/reduce conflict must be studied and usually eliminated. Here is the
  3277. proper way to define @code{sequence}:
  3278. @example
  3279. sequence: /* empty */
  3280. @{ printf ("empty sequence\n"); @}
  3281. | sequence word
  3282. @{ printf ("added word %s\n", $2); @}
  3283. ;
  3284. @end example
  3285. Here is another common error that yields a reduce/reduce conflict:
  3286. @example
  3287. sequence: /* empty */
  3288. | sequence words
  3289. | sequence redirects
  3290. ;
  3291. words: /* empty */
  3292. | words word
  3293. ;
  3294. redirects:/* empty */
  3295. | redirects redirect
  3296. ;
  3297. @end example
  3298. @noindent
  3299. The intention here is to define a sequence which can contain either
  3300. @code{word} or @code{redirect} groupings. The individual definitions of
  3301. @code{sequence}, @code{words} and @code{redirects} are error-free, but the
  3302. three together make a subtle ambiguity: even an empty input can be parsed
  3303. in infinitely many ways!
  3304. Consider: nothing-at-all could be a @code{words}. Or it could be two
  3305. @code{words} in a row, or three, or any number. It could equally well be a
  3306. @code{redirects}, or two, or any number. Or it could be a @code{words}
  3307. followed by three @code{redirects} and another @code{words}. And so on.
  3308. Here are two ways to correct these rules. First, to make it a single level
  3309. of sequence:
  3310. @example
  3311. sequence: /* empty */
  3312. | sequence word
  3313. | sequence redirect
  3314. ;
  3315. @end example
  3316. Second, to prevent either a @code{words} or a @code{redirects}
  3317. from being empty:
  3318. @example
  3319. sequence: /* empty */
  3320. | sequence words
  3321. | sequence redirects
  3322. ;
  3323. words: word
  3324. | words word
  3325. ;
  3326. redirects:redirect
  3327. | redirects redirect
  3328. ;
  3329. @end example
  3330. @node Mystery Conflicts, Stack Overflow, Reduce/Reduce, Algorithm
  3331. @section Mysterious Reduce/Reduce Conflicts
  3332. Sometimes reduce/reduce conflicts can occur that don't look warranted.
  3333. Here is an example:
  3334. @example
  3335. @group
  3336. %token ID
  3337. %%
  3338. def: param_spec return_spec ','
  3339. ;
  3340. param_spec:
  3341. type
  3342. | name_list ':' type
  3343. ;
  3344. @end group
  3345. @group
  3346. return_spec:
  3347. type
  3348. | name ':' type
  3349. ;
  3350. @end group
  3351. @group
  3352. type: ID
  3353. ;
  3354. @end group
  3355. @group
  3356. name: ID
  3357. ;
  3358. name_list:
  3359. name
  3360. | name ',' name_list
  3361. ;
  3362. @end group
  3363. @end example
  3364. It would seem that this grammar can be parsed with only a single token
  3365. of look-ahead: when a @code{param_spec} is being read, an @code{ID} is
  3366. a @code{name} if a comma or colon follows, or a @code{type} if another
  3367. @code{ID} follows. In other words, this grammar is LR(1).
  3368. @cindex LR(1)
  3369. @cindex LALR(1)
  3370. However, Bison, like most parser generators, cannot actually handle all
  3371. LR(1) grammars. In this grammar, two contexts, that after an @code{ID}
  3372. at the beginning of a @code{param_spec} and likewise at the beginning of
  3373. a @code{return_spec}, are similar enough that Bison assumes they are the
  3374. same. They appear similar because the same set of rules would be
  3375. active---the rule for reducing to a @code{name} and that for reducing to
  3376. a @code{type}. Bison is unable to determine at that stage of processing
  3377. that the rules would require different look-ahead tokens in the two
  3378. contexts, so it makes a single parser state for them both. Combining
  3379. the two contexts causes a conflict later. In parser terminology, this
  3380. occurrence means that the grammar is not LALR(1).
  3381. In general, it is better to fix deficiencies than to document them. But
  3382. this particular deficiency is intrinsically hard to fix; parser
  3383. generators that can handle LR(1) grammars are hard to write and tend to
  3384. produce parsers that are very large. In practice, Bison is more useful
  3385. as it is now.
  3386. When the problem arises, you can often fix it by identifying the two
  3387. parser states that are being confused, and adding something to make them
  3388. look distinct. In the above example, adding one rule to
  3389. @code{return_spec} as follows makes the problem go away:
  3390. @example
  3391. @group
  3392. %token BOGUS
  3393. @dots{}
  3394. %%
  3395. @dots{}
  3396. return_spec:
  3397. type
  3398. | name ':' type
  3399. /* This rule is never used. */
  3400. | ID BOGUS
  3401. ;
  3402. @end group
  3403. @end example
  3404. This corrects the problem because it introduces the possibility of an
  3405. additional active rule in the context after the @code{ID} at the beginning of
  3406. @code{return_spec}. This rule is not active in the corresponding context
  3407. in a @code{param_spec}, so the two contexts receive distinct parser states.
  3408. As long as the token @code{BOGUS} is never generated by @code{yylex},
  3409. the added rule cannot alter the way actual input is parsed.
  3410. In this particular example, there is another way to solve the problem:
  3411. rewrite the rule for @code{return_spec} to use @code{ID} directly
  3412. instead of via @code{name}. This also causes the two confusing
  3413. contexts to have different sets of active rules, because the one for
  3414. @code{return_spec} activates the altered rule for @code{return_spec}
  3415. rather than the one for @code{name}.
  3416. @example
  3417. param_spec:
  3418. type
  3419. | name_list ':' type
  3420. ;
  3421. return_spec:
  3422. type
  3423. | ID ':' type
  3424. ;
  3425. @end example
  3426. @node Stack Overflow, , Mystery Conflicts, Algorithm
  3427. @section Stack Overflow, and How to Avoid It
  3428. @cindex stack overflow
  3429. @cindex parser stack overflow
  3430. @cindex overflow of parser stack
  3431. The Bison parser stack can overflow if too many tokens are shifted and
  3432. not reduced. When this happens, the parser function @code{yyparse}
  3433. returns a nonzero value, pausing only to call @code{yyerror} to report
  3434. the overflow.
  3435. @vindex YYMAXDEPTH
  3436. By defining the macro @code{YYMAXDEPTH}, you can control how deep the
  3437. parser stack can become before a stack overflow occurs. Define the
  3438. macro with a value that is an integer. This value is the maximum number
  3439. of tokens that can be shifted (and not reduced) before overflow.
  3440. It must be a constant expression whose value is known at compile time.
  3441. The stack space allowed is not necessarily allocated. If you specify a
  3442. large value for @code{YYMAXDEPTH}, the parser actually allocates a small
  3443. stack at first, and then makes it bigger by stages as needed. This
  3444. increasing allocation happens automatically and silently. Therefore,
  3445. you do not need to make @code{YYMAXDEPTH} painfully small merely to save
  3446. space for ordinary inputs that do not need much stack.
  3447. @cindex default stack limit
  3448. The default value of @code{YYMAXDEPTH}, if you do not define it, is
  3449. 10000.
  3450. @vindex YYINITDEPTH
  3451. You can control how much stack is allocated initially by defining the
  3452. macro @code{YYINITDEPTH}. This value too must be a compile-time
  3453. constant integer. The default is 200.
  3454. @node Error Recovery, Context Dependency, Algorithm, Top
  3455. @chapter Error Recovery
  3456. @cindex error recovery
  3457. @cindex recovery from errors
  3458. It is not usually acceptable to have a program terminate on a parse
  3459. error. For example, a compiler should recover sufficiently to parse the
  3460. rest of the input file and check it for errors; a calculator should accept
  3461. another expression.
  3462. In a simple interactive command parser where each input is one line, it may
  3463. be sufficient to allow @code{yyparse} to return 1 on error and have the
  3464. caller ignore the rest of the input line when that happens (and then call
  3465. @code{yyparse} again). But this is inadequate for a compiler, because it
  3466. forgets all the syntactic context leading up to the error. A syntax error
  3467. deep within a function in the compiler input should not cause the compiler
  3468. to treat the following line like the beginning of a source file.
  3469. @findex error
  3470. You can define how to recover from a syntax error by writing rules to
  3471. recognize the special token @code{error}. This is a terminal symbol that
  3472. is always defined (you need not declare it) and reserved for error
  3473. handling. The Bison parser generates an @code{error} token whenever a
  3474. syntax error happens; if you have provided a rule to recognize this token
  3475. in the current context, the parse can continue.
  3476. For example:
  3477. @example
  3478. stmnts: /* empty string */
  3479. | stmnts '\n'
  3480. | stmnts exp '\n'
  3481. | stmnts error '\n'
  3482. @end example
  3483. The fourth rule in this example says that an error followed by a newline
  3484. makes a valid addition to any @code{stmnts}.
  3485. What happens if a syntax error occurs in the middle of an @code{exp}? The
  3486. error recovery rule, interpreted strictly, applies to the precise sequence
  3487. of a @code{stmnts}, an @code{error} and a newline. If an error occurs in
  3488. the middle of an @code{exp}, there will probably be some additional tokens
  3489. and subexpressions on the stack after the last @code{stmnts}, and there
  3490. will be tokens to read before the next newline. So the rule is not
  3491. applicable in the ordinary way.
  3492. But Bison can force the situation to fit the rule, by discarding part of
  3493. the semantic context and part of the input. First it discards states and
  3494. objects from the stack until it gets back to a state in which the
  3495. @code{error} token is acceptable. (This means that the subexpressions
  3496. already parsed are discarded, back to the last complete @code{stmnts}.) At
  3497. this point the @code{error} token can be shifted. Then, if the old
  3498. look-ahead token is not acceptable to be shifted next, the parser reads
  3499. tokens and discards them until it finds a token which is acceptable. In
  3500. this example, Bison reads and discards input until the next newline
  3501. so that the fourth rule can apply.
  3502. The choice of error rules in the grammar is a choice of strategies for
  3503. error recovery. A simple and useful strategy is simply to skip the rest of
  3504. the current input line or current statement if an error is detected:
  3505. @example
  3506. stmnt: error ';' /* on error, skip until ';' is read */
  3507. @end example
  3508. It is also useful to recover to the matching close-delimiter of an
  3509. opening-delimiter that has already been parsed. Otherwise the
  3510. close-delimiter will probably appear to be unmatched, and generate another,
  3511. spurious error message:
  3512. @example
  3513. primary: '(' expr ')'
  3514. | '(' error ')'
  3515. @dots{}
  3516. ;
  3517. @end example
  3518. Error recovery strategies are necessarily guesses. When they guess wrong,
  3519. one syntax error often leads to another. In the above example, the error
  3520. recovery rule guesses that an error is due to bad input within one
  3521. @code{stmnt}. Suppose that instead a spurious semicolon is inserted in the
  3522. middle of a valid @code{stmnt}. After the error recovery rule recovers
  3523. from the first error, another syntax error will be found straightaway,
  3524. since the text following the spurious semicolon is also an invalid
  3525. @code{stmnt}.
  3526. To prevent an outpouring of error messages, the parser will output no error
  3527. message for another syntax error that happens shortly after the first; only
  3528. after three consecutive input tokens have been successfully shifted will
  3529. error messages resume.
  3530. Note that rules which accept the @code{error} token may have actions, just
  3531. as any other rules can.
  3532. @findex yyerrok
  3533. You can make error messages resume immediately by using the macro
  3534. @code{yyerrok} in an action. If you do this in the error rule's action, no
  3535. error messages will be suppressed. This macro requires no arguments;
  3536. @samp{yyerrok;} is a valid C statement.
  3537. @findex yyclearin
  3538. The previous look-ahead token is reanalyzed immediately after an error. If
  3539. this is unacceptable, then the macro @code{yyclearin} may be used to clear
  3540. this token. Write the statement @samp{yyclearin;} in the error rule's
  3541. action.
  3542. For example, suppose that on a parse error, an error handling routine is
  3543. called that advances the input stream to some point where parsing should
  3544. once again commence. The next symbol returned by the lexical scanner is
  3545. probably correct. The previous look-ahead token ought to be discarded
  3546. with @samp{yyclearin;}.
  3547. @vindex YYRECOVERING
  3548. The macro @code{YYRECOVERING} stands for an expression that has the
  3549. value 1 when the parser is recovering from a syntax error, and 0 the
  3550. rest of the time. A value of 1 indicates that error messages are
  3551. currently suppressed for new syntax errors.
  3552. @node Context Dependency, Debugging, Error Recovery, Top
  3553. @chapter Handling Context Dependencies
  3554. The Bison paradigm is to parse tokens first, then group them into larger
  3555. syntactic units. In many languages, the meaning of a token is affected by
  3556. its context. Although this violates the Bison paradigm, certain techniques
  3557. (known as @dfn{kludges}) may enable you to write Bison parsers for such
  3558. languages.
  3559. @menu
  3560. * Semantic Tokens:: Token parsing can depend on the semantic context.
  3561. * Lexical Tie-ins:: Token parsing can depend on the syntactic context.
  3562. * Tie-in Recovery:: Lexical tie-ins have implications for how
  3563. error recovery rules must be written.
  3564. @end menu
  3565. (Actually, ``kludge'' means any technique that gets its job done but is
  3566. neither clean nor robust.)
  3567. @node Semantic Tokens, Lexical Tie-ins, , Context Dependency
  3568. @section Semantic Info in Token Types
  3569. The C language has a context dependency: the way an identifier is used
  3570. depends on what its current meaning is. For example, consider this:
  3571. @example
  3572. foo (x);
  3573. @end example
  3574. This looks like a function call statement, but if @code{foo} is a typedef
  3575. name, then this is actually a declaration of @code{x}. How can a Bison
  3576. parser for C decide how to parse this input?
  3577. The method used in GNU C is to have two different token types,
  3578. @code{IDENTIFIER} and @code{TYPENAME}. When @code{yylex} finds an
  3579. identifier, it looks up the current declaration of the identifier in order
  3580. to decide which token type to return: @code{TYPENAME} if the identifier is
  3581. declared as a typedef, @code{IDENTIFIER} otherwise.
  3582. The grammar rules can then express the context dependency by the choice of
  3583. token type to recognize. @code{IDENTIFIER} is accepted as an expression,
  3584. but @code{TYPENAME} is not. @code{TYPENAME} can start a declaration, but
  3585. @code{IDENTIFIER} cannot. In contexts where the meaning of the identifier
  3586. is @emph{not} significant, such as in declarations that can shadow a
  3587. typedef name, either @code{TYPENAME} or @code{IDENTIFIER} is
  3588. accepted---there is one rule for each of the two token types.
  3589. This technique is simple to use if the decision of which kinds of
  3590. identifiers to allow is made at a place close to where the identifier is
  3591. parsed. But in C this is not always so: C allows a declaration to
  3592. redeclare a typedef name provided an explicit type has been specified
  3593. earlier:
  3594. @example
  3595. typedef int foo, bar, lose;
  3596. static foo (bar); /* @r{redeclare @code{bar} as static variable} */
  3597. static int foo (lose); /* @r{redeclare @code{foo} as function} */
  3598. @end example
  3599. Unfortunately, the name being declared is separated from the declaration
  3600. construct itself by a complicated syntactic structure---the ``declarator''.
  3601. As a result, the part of Bison parser for C needs to be duplicated, with
  3602. all the nonterminal names changed: once for parsing a declaration in which
  3603. a typedef name can be redefined, and once for parsing a declaration in
  3604. which that can't be done. Here is a part of the duplication, with actions
  3605. omitted for brevity:
  3606. @example
  3607. initdcl:
  3608. declarator maybeasm '='
  3609. init
  3610. | declarator maybeasm
  3611. ;
  3612. notype_initdcl:
  3613. notype_declarator maybeasm '='
  3614. init
  3615. | notype_declarator maybeasm
  3616. ;
  3617. @end example
  3618. @noindent
  3619. Here @code{initdcl} can redeclare a typedef name, but @code{notype_initdcl}
  3620. cannot. The distinction between @code{declarator} and
  3621. @code{notype_declarator} is the same sort of thing.
  3622. There is some similarity between this technique and a lexical tie-in
  3623. (described next), in that information which alters the lexical analysis is
  3624. changed during parsing by other parts of the program. The difference is
  3625. here the information is global, and is used for other purposes in the
  3626. program. A true lexical tie-in has a special-purpose flag controlled by
  3627. the syntactic context.
  3628. @node Lexical Tie-ins, Tie-in Recovery, Semantic Tokens, Context Dependency
  3629. @section Lexical Tie-ins
  3630. @cindex lexical tie-in
  3631. One way to handle context-dependency is the @dfn{lexical tie-in}: a flag
  3632. which is set by Bison actions, whose purpose is to alter the way tokens are
  3633. parsed.
  3634. For example, suppose we have a language vaguely like C, but with a special
  3635. construct @samp{hex (@var{hex-expr})}. After the keyword @code{hex} comes
  3636. an expression in parentheses in which all integers are hexadecimal. In
  3637. particular, the token @samp{a1b} must be treated as an integer rather than
  3638. as an identifier if it appears in that context. Here is how you can do it:
  3639. @example
  3640. @group
  3641. %@{
  3642. int hexflag;
  3643. %@}
  3644. %%
  3645. @dots{}
  3646. @end group
  3647. @group
  3648. expr: IDENTIFIER
  3649. | constant
  3650. | HEX '('
  3651. @{ hexflag = 1; @}
  3652. expr ')'
  3653. @{ hexflag = 0;
  3654. $$ = $4; @}
  3655. | expr '+' expr
  3656. @{ $$ = make_sum ($1, $3); @}
  3657. @dots{}
  3658. ;
  3659. @end group
  3660. @group
  3661. constant:
  3662. INTEGER
  3663. | STRING
  3664. ;
  3665. @end group
  3666. @end example
  3667. @noindent
  3668. Here we assume that @code{yylex} looks at the value of @code{hexflag}; when
  3669. it is nonzero, all integers are parsed in hexadecimal, and tokens starting
  3670. with letters are parsed as integers if possible.
  3671. The declaration of @code{hexflag} shown in the C declarations section of
  3672. the parser file is needed to make it accessible to the actions
  3673. (@pxref{C Declarations, ,The C Declarations Section}). You must also write the code in @code{yylex}
  3674. to obey the flag.
  3675. @node Tie-in Recovery, , Lexical Tie-ins, Context Dependency
  3676. @section Lexical Tie-ins and Error Recovery
  3677. Lexical tie-ins make strict demands on any error recovery rules you have.
  3678. @xref{Error Recovery}.
  3679. The reason for this is that the purpose of an error recovery rule is to
  3680. abort the parsing of one construct and resume in some larger construct.
  3681. For example, in C-like languages, a typical error recovery rule is to skip
  3682. tokens until the next semicolon, and then start a new statement, like this:
  3683. @example
  3684. stmt: expr ';'
  3685. | IF '(' expr ')' stmt @{ @dots{} @}
  3686. @dots{}
  3687. error ';'
  3688. @{ hexflag = 0; @}
  3689. ;
  3690. @end example
  3691. If there is a syntax error in the middle of a @samp{hex (@var{expr})}
  3692. construct, this error rule will apply, and then the action for the
  3693. completed @samp{hex (@var{expr})} will never run. So @code{hexflag} would
  3694. remain set for the entire rest of the input, or until the next @code{hex}
  3695. keyword, causing identifiers to be misinterpreted as integers.
  3696. To avoid this problem the error recovery rule itself clears @code{hexflag}.
  3697. There may also be an error recovery rule that works within expressions.
  3698. For example, there could be a rule which applies within parentheses
  3699. and skips to the close-parenthesis:
  3700. @example
  3701. @group
  3702. expr: @dots{}
  3703. | '(' expr ')'
  3704. @{ $$ = $2; @}
  3705. | '(' error ')'
  3706. @dots{}
  3707. @end group
  3708. @end example
  3709. If this rule acts within the @code{hex} construct, it is not going to abort
  3710. that construct (since it applies to an inner level of parentheses within
  3711. the construct). Therefore, it should not clear the flag: the rest of
  3712. the @code{hex} construct should be parsed with the flag still in effect.
  3713. What if there is an error recovery rule which might abort out of the
  3714. @code{hex} construct or might not, depending on circumstances? There is no
  3715. way you can write the action to determine whether a @code{hex} construct is
  3716. being aborted or not. So if you are using a lexical tie-in, you had better
  3717. make sure your error recovery rules are not of this kind. Each rule must
  3718. be such that you can be sure that it always will, or always won't, have to
  3719. clear the flag.
  3720. @node Debugging, Invocation, Context Dependency, Top
  3721. @chapter Debugging Your Parser
  3722. @findex YYDEBUG
  3723. @findex yydebug
  3724. @cindex debugging
  3725. @cindex tracing the parser
  3726. If a Bison grammar compiles properly but doesn't do what you want when it
  3727. runs, the @code{yydebug} parser-trace feature can help you figure out why.
  3728. To enable compilation of trace facilities, you must define the macro
  3729. @code{YYDEBUG} when you compile the parser. You could use
  3730. @samp{-DYYDEBUG=1} as a compiler option or you could put @samp{#define
  3731. YYDEBUG 1} in the C declarations section of the grammar file
  3732. (@pxref{C Declarations, ,The C Declarations Section}). Alternatively, use the @samp{-t} option when
  3733. you run Bison (@pxref{Invocation, ,Invoking Bison}). We always define @code{YYDEBUG} so that
  3734. debugging is always possible.
  3735. The trace facility uses @code{stderr}, so you must add @w{@code{#include
  3736. <stdio.h>}} to the C declarations section unless it is already there.
  3737. Once you have compiled the program with trace facilities, the way to
  3738. request a trace is to store a nonzero value in the variable @code{yydebug}.
  3739. You can do this by making the C code do it (in @code{main}, perhaps), or
  3740. you can alter the value with a C debugger.
  3741. Each step taken by the parser when @code{yydebug} is nonzero produces a
  3742. line or two of trace information, written on @code{stderr}. The trace
  3743. messages tell you these things:
  3744. @itemize @bullet
  3745. @item
  3746. Each time the parser calls @code{yylex}, what kind of token was read.
  3747. @item
  3748. Each time a token is shifted, the depth and complete contents of the
  3749. state stack (@pxref{Parser States}).
  3750. @item
  3751. Each time a rule is reduced, which rule it is, and the complete contents
  3752. of the state stack afterward.
  3753. @end itemize
  3754. To make sense of this information, it helps to refer to the listing file
  3755. produced by the Bison @samp{-v} option (@pxref{Invocation, ,Invoking Bison}). This file
  3756. shows the meaning of each state in terms of positions in various rules, and
  3757. also what each state will do with each possible input token. As you read
  3758. the successive trace messages, you can see that the parser is functioning
  3759. according to its specification in the listing file. Eventually you will
  3760. arrive at the place where something undesirable happens, and you will see
  3761. which parts of the grammar are to blame.
  3762. The parser file is a C program and you can use C debuggers on it, but it's
  3763. not easy to interpret what it is doing. The parser function is a
  3764. finite-state machine interpreter, and aside from the actions it executes
  3765. the same code over and over. Only the values of variables show where in
  3766. the grammar it is working.
  3767. @findex YYPRINT
  3768. The debugging information normally gives the token type of each token
  3769. read, but not its semantic value. You can optionally define a macro
  3770. named @code{YYPRINT} to provide a way to print the value. If you define
  3771. @code{YYPRINT}, it should take three arguments. The parser will pass a
  3772. standard I/O stream, the numeric code for the token type, and the token
  3773. value (from @code{yylval}).
  3774. Here is an example of @code{YYPRINT} suitable for the multi-function
  3775. calculator (@pxref{Mfcalc Decl, ,Declarations for @code{mfcalc}}):
  3776. @smallexample
  3777. #define YYPRINT(file, type, value) yyprint (file, type, value)
  3778. static void
  3779. yyprint (file, type, value)
  3780. FILE *file;
  3781. int type;
  3782. YYSTYPE value;
  3783. @{
  3784. if (type == VAR)
  3785. fprintf (file, " %s", value.tptr->name);
  3786. else if (type == NUM)
  3787. fprintf (file, " %d", value.val);
  3788. @}
  3789. @end smallexample
  3790. @node Invocation, Table of Symbols, Debugging, Top
  3791. @chapter Invoking Bison
  3792. @cindex invoking Bison
  3793. @cindex Bison invocation
  3794. @cindex options for invoking Bison
  3795. The usual way to invoke Bison is as follows:
  3796. @example
  3797. bison @var{infile}
  3798. @end example
  3799. Here @var{infile} is the grammar file name, which usually ends in
  3800. @samp{.y}. The parser file's name is made by replacing the @samp{.y}
  3801. with @samp{.tab.c}. Thus, the @samp{bison foo.y} filename yields
  3802. @file{foo.tab.c}, and the @samp{bison hack/foo.y} filename yields
  3803. @file{hack/foo.tab.c}.@refill
  3804. @menu
  3805. * Bison Options:: All the options described in detail,
  3806. in alphabetical order by short options.
  3807. * Option Cross Key:: Alphabetical list of long options.
  3808. * VMS Invocation:: Bison command syntax on VMS.
  3809. @end menu
  3810. @node Bison Options, Option Cross Key, , Invocation
  3811. @section Bison Options
  3812. Bison supports both traditional single-letter options and mnemonic long
  3813. option names. Long option names are indicated with @samp{--} instead of
  3814. @samp{-}. Abbreviations for option names are allowed as long as they
  3815. are unique. When a long option takes an argument, like
  3816. @samp{--file-prefix}, connect the option name and the argument with
  3817. @samp{=}.
  3818. Here is a list of options that can be used with Bison, alphabetized by
  3819. short option. It is followed by a cross key alphabetized by long
  3820. option.
  3821. @table @samp
  3822. @item -b @var{file-prefix}
  3823. @itemx --file-prefix=@var{prefix}
  3824. Specify a prefix to use for all Bison output file names. The names are
  3825. chosen as if the input file were named @file{@var{prefix}.c}.
  3826. @item -d
  3827. @itemx --defines
  3828. Write an extra output file containing macro definitions for the token
  3829. type names defined in the grammar and the semantic value type
  3830. @code{YYSTYPE}, as well as a few @code{extern} variable declarations.
  3831. If the parser output file is named @file{@var{name}.c} then this file
  3832. is named @file{@var{name}.h}.@refill
  3833. This output file is essential if you wish to put the definition of
  3834. @code{yylex} in a separate source file, because @code{yylex} needs to
  3835. be able to refer to token type codes and the variable
  3836. @code{yylval}. @xref{Token Values, ,Semantic Values of Tokens}.@refill
  3837. @item -l
  3838. @itemx --no-lines
  3839. Don't put any @code{#line} preprocessor commands in the parser file.
  3840. Ordinarily Bison puts them in the parser file so that the C compiler
  3841. and debuggers will associate errors with your source file, the
  3842. grammar file. This option causes them to associate errors with the
  3843. parser file, treating it an independent source file in its own right.
  3844. @item -o @var{outfile}
  3845. @itemx --output-file=@var{outfile}
  3846. Specify the name @var{outfile} for the parser file.
  3847. The other output files' names are constructed from @var{outfile}
  3848. as described under the @samp{-v} and @samp{-d} switches.
  3849. @item -p @var{prefix}
  3850. @itemx --name-prefix=@var{prefix}
  3851. Rename the external symbols used in the parser so that they start with
  3852. @var{prefix} instead of @samp{yy}. The precise list of symbols renamed
  3853. is @code{yyparse}, @code{yylex}, @code{yyerror}, @code{yylval},
  3854. @code{yychar} and @code{yydebug}.
  3855. For example, if you use @samp{-p c}, the names become @code{cparse},
  3856. @code{clex}, and so on.
  3857. @xref{Multiple Parsers, ,Multiple Parsers in the Same Program}.
  3858. @item -t
  3859. @itemx --debug
  3860. Output a definition of the macro @code{YYDEBUG} into the parser file,
  3861. so that the debugging facilities are compiled. @xref{Debugging, ,Debugging Your Parser}.
  3862. @item -v
  3863. @itemx --verbose
  3864. Write an extra output file containing verbose descriptions of the
  3865. parser states and what is done for each type of look-ahead token in
  3866. that state.
  3867. This file also describes all the conflicts, both those resolved by
  3868. operator precedence and the unresolved ones.
  3869. The file's name is made by removing @samp{.tab.c} or @samp{.c} from
  3870. the parser output file name, and adding @samp{.output} instead.@refill
  3871. Therefore, if the input file is @file{foo.y}, then the parser file is
  3872. called @file{foo.tab.c} by default. As a consequence, the verbose
  3873. output file is called @file{foo.output}.@refill
  3874. @item -V
  3875. @itemx --version
  3876. Print the version number of Bison and exit.
  3877. @item -h
  3878. @itemx --help
  3879. Print a summary of the command-line options to Bison and exit.
  3880. @need 1750
  3881. @item -y
  3882. @itemx --yacc
  3883. @itemx --fixed-output-files
  3884. Equivalent to @samp{-o y.tab.c}; the parser output file is called
  3885. @file{y.tab.c}, and the other outputs are called @file{y.output} and
  3886. @file{y.tab.h}. The purpose of this switch is to imitate Yacc's output
  3887. file name conventions. Thus, the following shell script can substitute
  3888. for Yacc:@refill
  3889. @example
  3890. bison -y $*
  3891. @end example
  3892. @end table
  3893. @node Option Cross Key, VMS Invocation, Bison Options, Invocation
  3894. @section Option Cross Key
  3895. Here is a list of options, alphabetized by long option, to help you find
  3896. the corresponding short option.
  3897. @tex
  3898. \def\leaderfill{\leaders\hbox to 1em{\hss.\hss}\hfill}
  3899. {\tt
  3900. \line{ --debug \leaderfill -t}
  3901. \line{ --defines \leaderfill -d}
  3902. \line{ --file-prefix \leaderfill -b}
  3903. \line{ --fixed-output-files \leaderfill -y}
  3904. \line{ --help \leaderfill -h}
  3905. \line{ --name-prefix \leaderfill -p}
  3906. \line{ --no-lines \leaderfill -l}
  3907. \line{ --output-file \leaderfill -o}
  3908. \line{ --verbose \leaderfill -v}
  3909. \line{ --version \leaderfill -V}
  3910. \line{ --yacc \leaderfill -y}
  3911. }
  3912. @end tex
  3913. @ifinfo
  3914. @example
  3915. --debug -t
  3916. --defines -d
  3917. --file-prefix=@var{prefix} -b @var{file-prefix}
  3918. --fixed-output-files --yacc -y
  3919. --help -h
  3920. --name-prefix -p
  3921. --no-lines -l
  3922. --output-file=@var{outfile} -o @var{outfile}
  3923. --verbose -v
  3924. --version -V
  3925. @end example
  3926. @end ifinfo
  3927. @node VMS Invocation, , Option Cross Key, Invocation
  3928. @section Invoking Bison under VMS
  3929. @cindex invoking Bison under VMS
  3930. @cindex VMS
  3931. The command line syntax for Bison on VMS is a variant of the usual
  3932. Bison command syntax---adapted to fit VMS conventions.
  3933. To find the VMS equivalent for any Bison option, start with the long
  3934. option, and substitute a @samp{/} for the leading @samp{--}, and
  3935. substitute a @samp{_} for each @samp{-} in the name of the long option.
  3936. For example, the following invocation under VMS:
  3937. @example
  3938. bison /debug/name_prefix=bar foo.y
  3939. @end example
  3940. @noindent
  3941. is equivalent to the following command under POSIX.
  3942. @example
  3943. bison --debug --name-prefix=bar foo.y
  3944. @end example
  3945. The VMS file system does not permit filenames such as
  3946. @file{foo.tab.c}. In the above example, the output file
  3947. would instead be named @file{foo_tab.c}.
  3948. @node Table of Symbols, Glossary, Invocation, Top
  3949. @appendix Bison Symbols
  3950. @cindex Bison symbols, table of
  3951. @cindex symbols in Bison, table of
  3952. @table @code
  3953. @item error
  3954. A token name reserved for error recovery. This token may be used in
  3955. grammar rules so as to allow the Bison parser to recognize an error in
  3956. the grammar without halting the process. In effect, a sentence
  3957. containing an error may be recognized as valid. On a parse error, the
  3958. token @code{error} becomes the current look-ahead token. Actions
  3959. corresponding to @code{error} are then executed, and the look-ahead
  3960. token is reset to the token that originally caused the violation.
  3961. @xref{Error Recovery}.
  3962. @item YYABORT
  3963. Macro to pretend that an unrecoverable syntax error has occurred, by
  3964. making @code{yyparse} return 1 immediately. The error reporting
  3965. function @code{yyerror} is not called. @xref{Parser Function, ,The Parser Function @code{yyparse}}.
  3966. @item YYACCEPT
  3967. Macro to pretend that a complete utterance of the language has been
  3968. read, by making @code{yyparse} return 0 immediately.
  3969. @xref{Parser Function, ,The Parser Function @code{yyparse}}.
  3970. @item YYBACKUP
  3971. Macro to discard a value from the parser stack and fake a look-ahead
  3972. token. @xref{Action Features, ,Special Features for Use in Actions}.
  3973. @item YYERROR
  3974. Macro to pretend that a syntax error has just been detected: call
  3975. @code{yyerror} and then perform normal error recovery if possible
  3976. (@pxref{Error Recovery}), or (if recovery is impossible) make
  3977. @code{yyparse} return 1. @xref{Error Recovery}.
  3978. @item YYERROR_VERBOSE
  3979. Macro that you define with @code{#define} in the Bison declarations
  3980. section to request verbose, specific error message strings when
  3981. @code{yyerror} is called.
  3982. @item YYINITDEPTH
  3983. Macro for specifying the initial size of the parser stack.
  3984. @xref{Stack Overflow}.
  3985. @item YYLTYPE
  3986. Macro for the data type of @code{yylloc}; a structure with four
  3987. members. @xref{Token Positions, ,Textual Positions of Tokens}.
  3988. @item YYMAXDEPTH
  3989. Macro for specifying the maximum size of the parser stack.
  3990. @xref{Stack Overflow}.
  3991. @item YYRECOVERING
  3992. Macro whose value indicates whether the parser is recovering from a
  3993. syntax error. @xref{Action Features, ,Special Features for Use in Actions}.
  3994. @item YYSTYPE
  3995. Macro for the data type of semantic values; @code{int} by default.
  3996. @xref{Value Type, ,Data Types of Semantic Values}.
  3997. @item yychar
  3998. External integer variable that contains the integer value of the
  3999. current look-ahead token. (In a pure parser, it is a local variable
  4000. within @code{yyparse}.) Error-recovery rule actions may examine this
  4001. variable. @xref{Action Features, ,Special Features for Use in Actions}.
  4002. @item yyclearin
  4003. Macro used in error-recovery rule actions. It clears the previous
  4004. look-ahead token. @xref{Error Recovery}.
  4005. @item yydebug
  4006. External integer variable set to zero by default. If @code{yydebug}
  4007. is given a nonzero value, the parser will output information on input
  4008. symbols and parser action. @xref{Debugging, ,Debugging Your Parser}.
  4009. @item yyerrok
  4010. Macro to cause parser to recover immediately to its normal mode
  4011. after a parse error. @xref{Error Recovery}.
  4012. @item yyerror
  4013. User-supplied function to be called by @code{yyparse} on error. The
  4014. function receives one argument, a pointer to a character string
  4015. containing an error message. @xref{Error Reporting, ,The Error Reporting Function @code{yyerror}}.
  4016. @item yylex
  4017. User-supplied lexical analyzer function, called with no arguments
  4018. to get the next token. @xref{Lexical, ,The Lexical Analyzer Function @code{yylex}}.
  4019. @item yylval
  4020. External variable in which @code{yylex} should place the semantic
  4021. value associated with a token. (In a pure parser, it is a local
  4022. variable within @code{yyparse}, and its address is passed to
  4023. @code{yylex}.) @xref{Token Values, ,Semantic Values of Tokens}.
  4024. @item yylloc
  4025. External variable in which @code{yylex} should place the line and
  4026. column numbers associated with a token. (In a pure parser, it is a
  4027. local variable within @code{yyparse}, and its address is passed to
  4028. @code{yylex}.) You can ignore this variable if you don't use the
  4029. @samp{@@} feature in the grammar actions. @xref{Token Positions, ,Textual Positions of Tokens}.
  4030. @item yynerrs
  4031. Global variable which Bison increments each time there is a parse
  4032. error. (In a pure parser, it is a local variable within
  4033. @code{yyparse}.) @xref{Error Reporting, ,The Error Reporting Function @code{yyerror}}.
  4034. @item yyparse
  4035. The parser function produced by Bison; call this function to start
  4036. parsing. @xref{Parser Function, ,The Parser Function @code{yyparse}}.
  4037. @item %left
  4038. Bison declaration to assign left associativity to token(s).
  4039. @xref{Precedence Decl, ,Operator Precedence}.
  4040. @item %nonassoc
  4041. Bison declaration to assign nonassociativity to token(s).
  4042. @xref{Precedence Decl, ,Operator Precedence}.
  4043. @item %prec
  4044. Bison declaration to assign a precedence to a specific rule.
  4045. @xref{Contextual Precedence, ,Context-Dependent Precedence}.
  4046. @item %pure_parser
  4047. Bison declaration to request a pure (reentrant) parser.
  4048. @xref{Pure Decl, ,A Pure (Reentrant) Parser}.
  4049. @item %right
  4050. Bison declaration to assign right associativity to token(s).
  4051. @xref{Precedence Decl, ,Operator Precedence}.
  4052. @item %start
  4053. Bison declaration to specify the start symbol. @xref{Start Decl, ,The Start-Symbol}.
  4054. @item %token
  4055. Bison declaration to declare token(s) without specifying precedence.
  4056. @xref{Token Decl, ,Token Type Names}.
  4057. @item %type
  4058. Bison declaration to declare nonterminals. @xref{Type Decl, ,Nonterminal Symbols}.
  4059. @item %union
  4060. Bison declaration to specify several possible data types for semantic
  4061. values. @xref{Union Decl, ,The Collection of Value Types}.
  4062. @end table
  4063. These are the punctuation and delimiters used in Bison input:
  4064. @table @samp
  4065. @item %%
  4066. Delimiter used to separate the grammar rule section from the
  4067. Bison declarations section or the additional C code section.
  4068. @xref{Grammar Layout, ,The Overall Layout of a Bison Grammar}.
  4069. @item %@{ %@}
  4070. All code listed between @samp{%@{} and @samp{%@}} is copied directly
  4071. to the output file uninterpreted. Such code forms the ``C
  4072. declarations'' section of the input file. @xref{Grammar Outline, ,Outline of a Bison Grammar}.
  4073. @item /*@dots{}*/
  4074. Comment delimiters, as in C.
  4075. @item :
  4076. Separates a rule's result from its components. @xref{Rules, ,Syntax of Grammar Rules}.
  4077. @item ;
  4078. Terminates a rule. @xref{Rules, ,Syntax of Grammar Rules}.
  4079. @item |
  4080. Separates alternate rules for the same result nonterminal.
  4081. @xref{Rules, ,Syntax of Grammar Rules}.
  4082. @end table
  4083. @node Glossary, Index, Table of Symbols, Top
  4084. @appendix Glossary
  4085. @cindex glossary
  4086. @table @asis
  4087. @item Backus-Naur Form (BNF)
  4088. Formal method of specifying context-free grammars. BNF was first used
  4089. in the @cite{ALGOL-60} report, 1963. @xref{Language and Grammar, ,Languages and Context-Free Grammars}.
  4090. @item Context-free grammars
  4091. Grammars specified as rules that can be applied regardless of context.
  4092. Thus, if there is a rule which says that an integer can be used as an
  4093. expression, integers are allowed @emph{anywhere} an expression is
  4094. permitted. @xref{Language and Grammar, ,Languages and Context-Free Grammars}.
  4095. @item Dynamic allocation
  4096. Allocation of memory that occurs during execution, rather than at
  4097. compile time or on entry to a function.
  4098. @item Empty string
  4099. Analogous to the empty set in set theory, the empty string is a
  4100. character string of length zero.
  4101. @item Finite-state stack machine
  4102. A ``machine'' that has discrete states in which it is said to exist at
  4103. each instant in time. As input to the machine is processed, the
  4104. machine moves from state to state as specified by the logic of the
  4105. machine. In the case of the parser, the input is the language being
  4106. parsed, and the states correspond to various stages in the grammar
  4107. rules. @xref{Algorithm, ,The Bison Parser Algorithm }.
  4108. @item Grouping
  4109. A language construct that is (in general) grammatically divisible;
  4110. for example, `expression' or `declaration' in C.
  4111. @xref{Language and Grammar, ,Languages and Context-Free Grammars}.
  4112. @item Infix operator
  4113. An arithmetic operator that is placed between the operands on which it
  4114. performs some operation.
  4115. @item Input stream
  4116. A continuous flow of data between devices or programs.
  4117. @item Language construct
  4118. One of the typical usage schemas of the language. For example, one of
  4119. the constructs of the C language is the @code{if} statement.
  4120. @xref{Language and Grammar, ,Languages and Context-Free Grammars}.
  4121. @item Left associativity
  4122. Operators having left associativity are analyzed from left to right:
  4123. @samp{a+b+c} first computes @samp{a+b} and then combines with
  4124. @samp{c}. @xref{Precedence, ,Operator Precedence}.
  4125. @item Left recursion
  4126. A rule whose result symbol is also its first component symbol;
  4127. for example, @samp{expseq1 : expseq1 ',' exp;}. @xref{Recursion, ,Recursive Rules}.
  4128. @item Left-to-right parsing
  4129. Parsing a sentence of a language by analyzing it token by token from
  4130. left to right. @xref{Algorithm, ,The Bison Parser Algorithm }.
  4131. @item Lexical analyzer (scanner)
  4132. A function that reads an input stream and returns tokens one by one.
  4133. @xref{Lexical, ,The Lexical Analyzer Function @code{yylex}}.
  4134. @item Lexical tie-in
  4135. A flag, set by actions in the grammar rules, which alters the way
  4136. tokens are parsed. @xref{Lexical Tie-ins}.
  4137. @item Look-ahead token
  4138. A token already read but not yet shifted. @xref{Look-Ahead, ,Look-Ahead Tokens}.
  4139. @item LALR(1)
  4140. The class of context-free grammars that Bison (like most other parser
  4141. generators) can handle; a subset of LR(1). @xref{Mystery Conflicts, ,
  4142. Mysterious Reduce/Reduce Conflicts}.
  4143. @item LR(1)
  4144. The class of context-free grammars in which at most one token of
  4145. look-ahead is needed to disambiguate the parsing of any piece of input.
  4146. @item Nonterminal symbol
  4147. A grammar symbol standing for a grammatical construct that can
  4148. be expressed through rules in terms of smaller constructs; in other
  4149. words, a construct that is not a token. @xref{Symbols}.
  4150. @item Parse error
  4151. An error encountered during parsing of an input stream due to invalid
  4152. syntax. @xref{Error Recovery}.
  4153. @item Parser
  4154. A function that recognizes valid sentences of a language by analyzing
  4155. the syntax structure of a set of tokens passed to it from a lexical
  4156. analyzer.
  4157. @item Postfix operator
  4158. An arithmetic operator that is placed after the operands upon which it
  4159. performs some operation.
  4160. @item Reduction
  4161. Replacing a string of nonterminals and/or terminals with a single
  4162. nonterminal, according to a grammar rule. @xref{Algorithm, ,The Bison Parser Algorithm }.
  4163. @item Reentrant
  4164. A reentrant subprogram is a subprogram which can be in invoked any
  4165. number of times in parallel, without interference between the various
  4166. invocations. @xref{Pure Decl, ,A Pure (Reentrant) Parser}.
  4167. @item Reverse polish notation
  4168. A language in which all operators are postfix operators.
  4169. @item Right recursion
  4170. A rule whose result symbol is also its last component symbol;
  4171. for example, @samp{expseq1: exp ',' expseq1;}. @xref{Recursion, ,Recursive Rules}.
  4172. @item Semantics
  4173. In computer languages, the semantics are specified by the actions
  4174. taken for each instance of the language, i.e., the meaning of
  4175. each statement. @xref{Semantics, ,Defining Language Semantics}.
  4176. @item Shift
  4177. A parser is said to shift when it makes the choice of analyzing
  4178. further input from the stream rather than reducing immediately some
  4179. already-recognized rule. @xref{Algorithm, ,The Bison Parser Algorithm }.
  4180. @item Single-character literal
  4181. A single character that is recognized and interpreted as is.
  4182. @xref{Grammar in Bison, ,From Formal Rules to Bison Input}.
  4183. @item Start symbol
  4184. The nonterminal symbol that stands for a complete valid utterance in
  4185. the language being parsed. The start symbol is usually listed as the
  4186. first nonterminal symbol in a language specification.
  4187. @xref{Start Decl, ,The Start-Symbol}.
  4188. @item Symbol table
  4189. A data structure where symbol names and associated data are stored
  4190. during parsing to allow for recognition and use of existing
  4191. information in repeated uses of a symbol. @xref{Multi-function Calc}.
  4192. @item Token
  4193. A basic, grammatically indivisible unit of a language. The symbol
  4194. that describes a token in the grammar is a terminal symbol.
  4195. The input of the Bison parser is a stream of tokens which comes from
  4196. the lexical analyzer. @xref{Symbols}.
  4197. @item Terminal symbol
  4198. A grammar symbol that has no rules in the grammar and therefore
  4199. is grammatically indivisible. The piece of text it represents
  4200. is a token. @xref{Language and Grammar, ,Languages and Context-Free Grammars}.
  4201. @end table
  4202. @node Index, , Glossary, Top
  4203. @unnumbered Index
  4204. @printindex cp
  4205. @contents
  4206. @bye
  4207. @c old menu
  4208. * Introduction::
  4209. * Conditions::
  4210. * Copying:: The GNU General Public License says
  4211. how you can copy and share Bison
  4212. Tutorial sections:
  4213. * Concepts:: Basic concepts for understanding Bison.
  4214. * Examples:: Three simple explained examples of using Bison.
  4215. Reference sections:
  4216. * Grammar File:: Writing Bison declarations and rules.
  4217. * Interface:: C-language interface to the parser function @code{yyparse}.
  4218. * Algorithm:: How the Bison parser works at run-time.
  4219. * Error Recovery:: Writing rules for error recovery.
  4220. * Context Dependency::What to do if your language syntax is too
  4221. messy for Bison to handle straightforwardly.
  4222. * Debugging:: Debugging Bison parsers that parse wrong.
  4223. * Invocation:: How to run Bison (to produce the parser source file).
  4224. * Table of Symbols:: All the keywords of the Bison language are explained.
  4225. * Glossary:: Basic concepts are explained.
  4226. * Index:: Cross-references to the text.