bison.texinfo 192 KB

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