BISON.TEX 177 KB

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