BISON.TEX 161 KB

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