ply.html 112 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496
  1. <html>
  2. <head>
  3. <title>PLY (Python Lex-Yacc)</title>
  4. </head>
  5. <body bgcolor="#ffffff">
  6. <h1>PLY (Python Lex-Yacc)</h1>
  7. <b>
  8. David M. Beazley <br>
  9. dave@dabeaz.com<br>
  10. </b>
  11. <p>
  12. <b>PLY Version: 3.11</b>
  13. <p>
  14. <!-- INDEX -->
  15. <div class="sectiontoc">
  16. <ul>
  17. <li><a href="#ply_nn0">Preface and Requirements</a>
  18. <li><a href="#ply_nn1">Introduction</a>
  19. <li><a href="#ply_nn2">PLY Overview</a>
  20. <li><a href="#ply_nn3">Lex</a>
  21. <ul>
  22. <li><a href="#ply_nn4">Lex Example</a>
  23. <li><a href="#ply_nn5">The tokens list</a>
  24. <li><a href="#ply_nn6">Specification of tokens</a>
  25. <li><a href="#ply_nn7">Token values</a>
  26. <li><a href="#ply_nn8">Discarded tokens</a>
  27. <li><a href="#ply_nn9">Line numbers and positional information</a>
  28. <li><a href="#ply_nn10">Ignored characters</a>
  29. <li><a href="#ply_nn11">Literal characters</a>
  30. <li><a href="#ply_nn12">Error handling</a>
  31. <li><a href="#ply_nn14">EOF Handling</a>
  32. <li><a href="#ply_nn13">Building and using the lexer</a>
  33. <li><a href="#ply_nn14b">The @TOKEN decorator</a>
  34. <li><a href="#ply_nn15">Optimized mode</a>
  35. <li><a href="#ply_nn16">Debugging</a>
  36. <li><a href="#ply_nn17">Alternative specification of lexers</a>
  37. <li><a href="#ply_nn18">Maintaining state</a>
  38. <li><a href="#ply_nn19">Lexer cloning</a>
  39. <li><a href="#ply_nn20">Internal lexer state</a>
  40. <li><a href="#ply_nn21">Conditional lexing and start conditions</a>
  41. <li><a href="#ply_nn21b">Miscellaneous Issues</a>
  42. </ul>
  43. <li><a href="#ply_nn22">Parsing basics</a>
  44. <li><a href="#ply_nn23">Yacc</a>
  45. <ul>
  46. <li><a href="#ply_nn24">An example</a>
  47. <li><a href="#ply_nn25">Combining Grammar Rule Functions</a>
  48. <li><a href="#ply_nn26">Character Literals</a>
  49. <li><a href="#ply_nn26b">Empty Productions</a>
  50. <li><a href="#ply_nn28">Changing the starting symbol</a>
  51. <li><a href="#ply_nn27">Dealing With Ambiguous Grammars</a>
  52. <li><a href="#ply_nn28b">The parser.out file</a>
  53. <li><a href="#ply_nn29">Syntax Error Handling</a>
  54. <ul>
  55. <li><a href="#ply_nn30">Recovery and resynchronization with error rules</a>
  56. <li><a href="#ply_nn31">Panic mode recovery</a>
  57. <li><a href="#ply_nn35">Signalling an error from a production</a>
  58. <li><a href="#ply_nn38">When Do Syntax Errors Get Reported</a>
  59. <li><a href="#ply_nn32">General comments on error handling</a>
  60. </ul>
  61. <li><a href="#ply_nn33">Line Number and Position Tracking</a>
  62. <li><a href="#ply_nn34">AST Construction</a>
  63. <li><a href="#ply_nn35b">Embedded Actions</a>
  64. <li><a href="#ply_nn36">Miscellaneous Yacc Notes</a>
  65. </ul>
  66. <li><a href="#ply_nn37">Multiple Parsers and Lexers</a>
  67. <li><a href="#ply_nn38b">Using Python's Optimized Mode</a>
  68. <li><a href="#ply_nn44">Advanced Debugging</a>
  69. <ul>
  70. <li><a href="#ply_nn45">Debugging the lex() and yacc() commands</a>
  71. <li><a href="#ply_nn46">Run-time Debugging</a>
  72. </ul>
  73. <li><a href="#ply_nn49">Packaging Advice</a>
  74. <li><a href="#ply_nn39">Where to go from here?</a>
  75. </ul>
  76. </div>
  77. <!-- INDEX -->
  78. <H2><a name="ply_nn0"></a>1. Preface and Requirements</H2>
  79. <p>
  80. This document provides an overview of lexing and parsing with PLY.
  81. Given the intrinsic complexity of parsing, I would strongly advise
  82. that you read (or at least skim) this entire document before jumping
  83. into a big development project with PLY.
  84. </p>
  85. <p>
  86. PLY-3.5 is compatible with both Python 2 and Python 3. If you are using
  87. Python 2, you have to use Python 2.6 or newer.
  88. </p>
  89. <H2><a name="ply_nn1"></a>2. Introduction</H2>
  90. PLY is a pure-Python implementation of the popular compiler
  91. construction tools lex and yacc. The main goal of PLY is to stay
  92. fairly faithful to the way in which traditional lex/yacc tools work.
  93. This includes supporting LALR(1) parsing as well as providing
  94. extensive input validation, error reporting, and diagnostics. Thus,
  95. if you've used yacc in another programming language, it should be
  96. relatively straightforward to use PLY.
  97. <p>
  98. Early versions of PLY were developed to support an Introduction to
  99. Compilers Course I taught in 2001 at the University of Chicago.
  100. Since PLY was primarily developed as an instructional tool, you will
  101. find it to be fairly picky about token and grammar rule
  102. specification. In part, this
  103. added formality is meant to catch common programming mistakes made by
  104. novice users. However, advanced users will also find such features to
  105. be useful when building complicated grammars for real programming
  106. languages. It should also be noted that PLY does not provide much in
  107. the way of bells and whistles (e.g., automatic construction of
  108. abstract syntax trees, tree traversal, etc.). Nor would I consider it
  109. to be a parsing framework. Instead, you will find a bare-bones, yet
  110. fully capable lex/yacc implementation written entirely in Python.
  111. <p>
  112. The rest of this document assumes that you are somewhat familiar with
  113. parsing theory, syntax directed translation, and the use of compiler
  114. construction tools such as lex and yacc in other programming
  115. languages. If you are unfamiliar with these topics, you will probably
  116. want to consult an introductory text such as "Compilers: Principles,
  117. Techniques, and Tools", by Aho, Sethi, and Ullman. O'Reilly's "Lex
  118. and Yacc" by John Levine may also be handy. In fact, the O'Reilly book can be
  119. used as a reference for PLY as the concepts are virtually identical.
  120. <H2><a name="ply_nn2"></a>3. PLY Overview</H2>
  121. <p>
  122. PLY consists of two separate modules; <tt>lex.py</tt> and
  123. <tt>yacc.py</tt>, both of which are found in a Python package
  124. called <tt>ply</tt>. The <tt>lex.py</tt> module is used to break input text into a
  125. collection of tokens specified by a collection of regular expression
  126. rules. <tt>yacc.py</tt> is used to recognize language syntax that has
  127. been specified in the form of a context free grammar.
  128. </p>
  129. <p>
  130. The two tools are meant to work together. Specifically,
  131. <tt>lex.py</tt> provides an external interface in the form of a
  132. <tt>token()</tt> function that returns the next valid token on the
  133. input stream. <tt>yacc.py</tt> calls this repeatedly to retrieve
  134. tokens and invoke grammar rules. The output of <tt>yacc.py</tt> is
  135. often an Abstract Syntax Tree (AST). However, this is entirely up to
  136. the user. If desired, <tt>yacc.py</tt> can also be used to implement
  137. simple one-pass compilers.
  138. <p>
  139. Like its Unix counterpart, <tt>yacc.py</tt> provides most of the
  140. features you expect including extensive error checking, grammar
  141. validation, support for empty productions, error tokens, and ambiguity
  142. resolution via precedence rules. In fact, almost everything that is possible in traditional yacc
  143. should be supported in PLY.
  144. <p>
  145. The primary difference between
  146. <tt>yacc.py</tt> and Unix <tt>yacc</tt> is that <tt>yacc.py</tt>
  147. doesn't involve a separate code-generation process.
  148. Instead, PLY relies on reflection (introspection)
  149. to build its lexers and parsers. Unlike traditional lex/yacc which
  150. require a special input file that is converted into a separate source
  151. file, the specifications given to PLY <em>are</em> valid Python
  152. programs. This means that there are no extra source files nor is
  153. there a special compiler construction step (e.g., running yacc to
  154. generate Python code for the compiler). Since the generation of the
  155. parsing tables is relatively expensive, PLY caches the results and
  156. saves them to a file. If no changes are detected in the input source,
  157. the tables are read from the cache. Otherwise, they are regenerated.
  158. <H2><a name="ply_nn3"></a>4. Lex</H2>
  159. <tt>lex.py</tt> is used to tokenize an input string. For example, suppose
  160. you're writing a programming language and a user supplied the following input string:
  161. <blockquote>
  162. <pre>
  163. x = 3 + 42 * (s - t)
  164. </pre>
  165. </blockquote>
  166. A tokenizer splits the string into individual tokens
  167. <blockquote>
  168. <pre>
  169. 'x','=', '3', '+', '42', '*', '(', 's', '-', 't', ')'
  170. </pre>
  171. </blockquote>
  172. Tokens are usually given names to indicate what they are. For example:
  173. <blockquote>
  174. <pre>
  175. 'ID','EQUALS','NUMBER','PLUS','NUMBER','TIMES',
  176. 'LPAREN','ID','MINUS','ID','RPAREN'
  177. </pre>
  178. </blockquote>
  179. More specifically, the input is broken into pairs of token types and values. For example:
  180. <blockquote>
  181. <pre>
  182. ('ID','x'), ('EQUALS','='), ('NUMBER','3'),
  183. ('PLUS','+'), ('NUMBER','42), ('TIMES','*'),
  184. ('LPAREN','('), ('ID','s'), ('MINUS','-'),
  185. ('ID','t'), ('RPAREN',')'
  186. </pre>
  187. </blockquote>
  188. The identification of tokens is typically done by writing a series of regular expression
  189. rules. The next section shows how this is done using <tt>lex.py</tt>.
  190. <H3><a name="ply_nn4"></a>4.1 Lex Example</H3>
  191. The following example shows how <tt>lex.py</tt> is used to write a simple tokenizer.
  192. <blockquote>
  193. <pre>
  194. # ------------------------------------------------------------
  195. # calclex.py
  196. #
  197. # tokenizer for a simple expression evaluator for
  198. # numbers and +,-,*,/
  199. # ------------------------------------------------------------
  200. import ply.lex as lex
  201. # List of token names. This is always required
  202. tokens = (
  203. 'NUMBER',
  204. 'PLUS',
  205. 'MINUS',
  206. 'TIMES',
  207. 'DIVIDE',
  208. 'LPAREN',
  209. 'RPAREN',
  210. )
  211. # Regular expression rules for simple tokens
  212. t_PLUS = r'\+'
  213. t_MINUS = r'-'
  214. t_TIMES = r'\*'
  215. t_DIVIDE = r'/'
  216. t_LPAREN = r'\('
  217. t_RPAREN = r'\)'
  218. # A regular expression rule with some action code
  219. def t_NUMBER(t):
  220. r'\d+'
  221. t.value = int(t.value)
  222. return t
  223. # Define a rule so we can track line numbers
  224. def t_newline(t):
  225. r'\n+'
  226. t.lexer.lineno += len(t.value)
  227. # A string containing ignored characters (spaces and tabs)
  228. t_ignore = ' \t'
  229. # Error handling rule
  230. def t_error(t):
  231. print("Illegal character '%s'" % t.value[0])
  232. t.lexer.skip(1)
  233. # Build the lexer
  234. lexer = lex.lex()
  235. </pre>
  236. </blockquote>
  237. To use the lexer, you first need to feed it some input text using
  238. its <tt>input()</tt> method. After that, repeated calls
  239. to <tt>token()</tt> produce tokens. The following code shows how this
  240. works:
  241. <blockquote>
  242. <pre>
  243. # Test it out
  244. data = '''
  245. 3 + 4 * 10
  246. + -20 *2
  247. '''
  248. # Give the lexer some input
  249. lexer.input(data)
  250. # Tokenize
  251. while True:
  252. tok = lexer.token()
  253. if not tok:
  254. break # No more input
  255. print(tok)
  256. </pre>
  257. </blockquote>
  258. When executed, the example will produce the following output:
  259. <blockquote>
  260. <pre>
  261. $ python example.py
  262. LexToken(NUMBER,3,2,1)
  263. LexToken(PLUS,'+',2,3)
  264. LexToken(NUMBER,4,2,5)
  265. LexToken(TIMES,'*',2,7)
  266. LexToken(NUMBER,10,2,10)
  267. LexToken(PLUS,'+',3,14)
  268. LexToken(MINUS,'-',3,16)
  269. LexToken(NUMBER,20,3,18)
  270. LexToken(TIMES,'*',3,20)
  271. LexToken(NUMBER,2,3,21)
  272. </pre>
  273. </blockquote>
  274. Lexers also support the iteration protocol. So, you can write the above loop as follows:
  275. <blockquote>
  276. <pre>
  277. for tok in lexer:
  278. print(tok)
  279. </pre>
  280. </blockquote>
  281. The tokens returned by <tt>lexer.token()</tt> are instances
  282. of <tt>LexToken</tt>. This object has
  283. attributes <tt>tok.type</tt>, <tt>tok.value</tt>,
  284. <tt>tok.lineno</tt>, and <tt>tok.lexpos</tt>. The following code shows an example of
  285. accessing these attributes:
  286. <blockquote>
  287. <pre>
  288. # Tokenize
  289. while True:
  290. tok = lexer.token()
  291. if not tok:
  292. break # No more input
  293. print(tok.type, tok.value, tok.lineno, tok.lexpos)
  294. </pre>
  295. </blockquote>
  296. The <tt>tok.type</tt> and <tt>tok.value</tt> attributes contain the
  297. type and value of the token itself.
  298. <tt>tok.line</tt> and <tt>tok.lexpos</tt> contain information about
  299. the location of the token. <tt>tok.lexpos</tt> is the index of the
  300. token relative to the start of the input text.
  301. <H3><a name="ply_nn5"></a>4.2 The tokens list</H3>
  302. <p>
  303. All lexers must provide a list <tt>tokens</tt> that defines all of the possible token
  304. names that can be produced by the lexer. This list is always required
  305. and is used to perform a variety of validation checks. The tokens list is also used by the
  306. <tt>yacc.py</tt> module to identify terminals.
  307. </p>
  308. <p>
  309. In the example, the following code specified the token names:
  310. <blockquote>
  311. <pre>
  312. tokens = (
  313. 'NUMBER',
  314. 'PLUS',
  315. 'MINUS',
  316. 'TIMES',
  317. 'DIVIDE',
  318. 'LPAREN',
  319. 'RPAREN',
  320. )
  321. </pre>
  322. </blockquote>
  323. <H3><a name="ply_nn6"></a>4.3 Specification of tokens</H3>
  324. Each token is specified by writing a regular expression rule compatible with Python's <tt>re</tt> module. Each of these rules
  325. are defined by making declarations with a special prefix <tt>t_</tt> to indicate that it
  326. defines a token. For simple tokens, the regular expression can
  327. be specified as strings such as this (note: Python raw strings are used since they are the
  328. most convenient way to write regular expression strings):
  329. <blockquote>
  330. <pre>
  331. t_PLUS = r'\+'
  332. </pre>
  333. </blockquote>
  334. In this case, the name following the <tt>t_</tt> must exactly match one of the
  335. names supplied in <tt>tokens</tt>. If some kind of action needs to be performed,
  336. a token rule can be specified as a function. For example, this rule matches numbers and
  337. converts the string into a Python integer.
  338. <blockquote>
  339. <pre>
  340. def t_NUMBER(t):
  341. r'\d+'
  342. t.value = int(t.value)
  343. return t
  344. </pre>
  345. </blockquote>
  346. When a function is used, the regular expression rule is specified in the function documentation string.
  347. The function always takes a single argument which is an instance of
  348. <tt>LexToken</tt>. This object has attributes of <tt>t.type</tt> which is the token type (as a string),
  349. <tt>t.value</tt> which is the lexeme (the actual text matched), <tt>t.lineno</tt> which is the current line number, and <tt>t.lexpos</tt> which
  350. is the position of the token relative to the beginning of the input text.
  351. By default, <tt>t.type</tt> is set to the name following the <tt>t_</tt> prefix. The action
  352. function can modify the contents of the <tt>LexToken</tt> object as appropriate. However,
  353. when it is done, the resulting token should be returned. If no value is returned by the action
  354. function, the token is simply discarded and the next token read.
  355. <p>
  356. Internally, <tt>lex.py</tt> uses the <tt>re</tt> module to do its pattern matching. Patterns are compiled
  357. using the <tt>re.VERBOSE</tt> flag which can be used to help readability. However, be aware that unescaped
  358. whitespace is ignored and comments are allowed in this mode. If your pattern involves whitespace, make sure you
  359. use <tt>\s</tt>. If you need to match the <tt>#</tt> character, use <tt>[#]</tt>.
  360. </p>
  361. <p>
  362. When building the master regular expression,
  363. rules are added in the following order:
  364. </p>
  365. <p>
  366. <ol>
  367. <li>All tokens defined by functions are added in the same order as they appear in the lexer file.
  368. <li>Tokens defined by strings are added next by sorting them in order of decreasing regular expression length (longer expressions
  369. are added first).
  370. </ol>
  371. <p>
  372. Without this ordering, it can be difficult to correctly match certain types of tokens. For example, if you
  373. wanted to have separate tokens for "=" and "==", you need to make sure that "==" is checked first. By sorting regular
  374. expressions in order of decreasing length, this problem is solved for rules defined as strings. For functions,
  375. the order can be explicitly controlled since rules appearing first are checked first.
  376. <p>
  377. To handle reserved words, you should write a single rule to match an
  378. identifier and do a special name lookup in a function like this:
  379. <blockquote>
  380. <pre>
  381. reserved = {
  382. 'if' : 'IF',
  383. 'then' : 'THEN',
  384. 'else' : 'ELSE',
  385. 'while' : 'WHILE',
  386. ...
  387. }
  388. tokens = ['LPAREN','RPAREN',...,'ID'] + list(reserved.values())
  389. def t_ID(t):
  390. r'[a-zA-Z_][a-zA-Z_0-9]*'
  391. t.type = reserved.get(t.value,'ID') # Check for reserved words
  392. return t
  393. </pre>
  394. </blockquote>
  395. This approach greatly reduces the number of regular expression rules and is likely to make things a little faster.
  396. <p>
  397. <b>Note:</b> You should avoid writing individual rules for reserved words. For example, if you write rules like this,
  398. <blockquote>
  399. <pre>
  400. t_FOR = r'for'
  401. t_PRINT = r'print'
  402. </pre>
  403. </blockquote>
  404. those rules will be triggered for identifiers that include those words as a prefix such as "forget" or "printed". This is probably not
  405. what you want.
  406. <H3><a name="ply_nn7"></a>4.4 Token values</H3>
  407. When tokens are returned by lex, they have a value that is stored in the <tt>value</tt> attribute. Normally, the value is the text
  408. that was matched. However, the value can be assigned to any Python object. For instance, when lexing identifiers, you may
  409. want to return both the identifier name and information from some sort of symbol table. To do this, you might write a rule like this:
  410. <blockquote>
  411. <pre>
  412. def t_ID(t):
  413. ...
  414. # Look up symbol table information and return a tuple
  415. t.value = (t.value, symbol_lookup(t.value))
  416. ...
  417. return t
  418. </pre>
  419. </blockquote>
  420. It is important to note that storing data in other attribute names is <em>not</em> recommended. The <tt>yacc.py</tt> module only exposes the
  421. contents of the <tt>value</tt> attribute. Thus, accessing other attributes may be unnecessarily awkward. If you
  422. need to store multiple values on a token, assign a tuple, dictionary, or instance to <tt>value</tt>.
  423. <H3><a name="ply_nn8"></a>4.5 Discarded tokens</H3>
  424. To discard a token, such as a comment, simply define a token rule that returns no value. For example:
  425. <blockquote>
  426. <pre>
  427. def t_COMMENT(t):
  428. r'\#.*'
  429. pass
  430. # No return value. Token discarded
  431. </pre>
  432. </blockquote>
  433. Alternatively, you can include the prefix "ignore_" in the token declaration to force a token to be ignored. For example:
  434. <blockquote>
  435. <pre>
  436. t_ignore_COMMENT = r'\#.*'
  437. </pre>
  438. </blockquote>
  439. Be advised that if you are ignoring many different kinds of text, you may still want to use functions since these provide more precise
  440. control over the order in which regular expressions are matched (i.e., functions are matched in order of specification whereas strings are
  441. sorted by regular expression length).
  442. <H3><a name="ply_nn9"></a>4.6 Line numbers and positional information</H3>
  443. <p>By default, <tt>lex.py</tt> knows nothing about line numbers. This is because <tt>lex.py</tt> doesn't know anything
  444. about what constitutes a "line" of input (e.g., the newline character or even if the input is textual data).
  445. To update this information, you need to write a special rule. In the example, the <tt>t_newline()</tt> rule shows how to do this.
  446. <blockquote>
  447. <pre>
  448. # Define a rule so we can track line numbers
  449. def t_newline(t):
  450. r'\n+'
  451. t.lexer.lineno += len(t.value)
  452. </pre>
  453. </blockquote>
  454. Within the rule, the <tt>lineno</tt> attribute of the underlying lexer <tt>t.lexer</tt> is updated.
  455. After the line number is updated, the token is simply discarded since nothing is returned.
  456. <p>
  457. <tt>lex.py</tt> does not perform any kind of automatic column tracking. However, it does record positional
  458. information related to each token in the <tt>lexpos</tt> attribute. Using this, it is usually possible to compute
  459. column information as a separate step. For instance, just count backwards until you reach a newline.
  460. <blockquote>
  461. <pre>
  462. # Compute column.
  463. # input is the input text string
  464. # token is a token instance
  465. def find_column(input, token):
  466. line_start = input.rfind('\n', 0, token.lexpos) + 1
  467. return (token.lexpos - line_start) + 1
  468. </pre>
  469. </blockquote>
  470. Since column information is often only useful in the context of error handling, calculating the column
  471. position can be performed when needed as opposed to doing it for each token.
  472. <H3><a name="ply_nn10"></a>4.7 Ignored characters</H3>
  473. <p>
  474. The special <tt>t_ignore</tt> rule is reserved by <tt>lex.py</tt> for characters
  475. that should be completely ignored in the input stream.
  476. Usually this is used to skip over whitespace and other non-essential characters.
  477. Although it is possible to define a regular expression rule for whitespace in a manner
  478. similar to <tt>t_newline()</tt>, the use of <tt>t_ignore</tt> provides substantially better
  479. lexing performance because it is handled as a special case and is checked in a much
  480. more efficient manner than the normal regular expression rules.
  481. </p>
  482. <p>
  483. The characters given in <tt>t_ignore</tt> are not ignored when such characters are part of
  484. other regular expression patterns. For example, if you had a rule to capture quoted text,
  485. that pattern can include the ignored characters (which will be captured in the normal way). The
  486. main purpose of <tt>t_ignore</tt> is to ignore whitespace and other padding between the
  487. tokens that you actually want to parse.
  488. </p>
  489. <H3><a name="ply_nn11"></a>4.8 Literal characters</H3>
  490. <p>
  491. Literal characters can be specified by defining a variable <tt>literals</tt> in your lexing module. For example:
  492. <blockquote>
  493. <pre>
  494. literals = [ '+','-','*','/' ]
  495. </pre>
  496. </blockquote>
  497. or alternatively
  498. <blockquote>
  499. <pre>
  500. literals = "+-*/"
  501. </pre>
  502. </blockquote>
  503. A literal character is simply a single character that is returned "as is" when encountered by the lexer. Literals are checked
  504. after all of the defined regular expression rules. Thus, if a rule starts with one of the literal characters, it will always
  505. take precedence.
  506. <p>
  507. When a literal token is returned, both its <tt>type</tt> and <tt>value</tt> attributes are set to the character itself. For example, <tt>'+'</tt>.
  508. </p>
  509. <p>
  510. It's possible to write token functions that perform additional actions
  511. when literals are matched. However, you'll need to set the token type
  512. appropriately. For example:
  513. </p>
  514. <blockquote>
  515. <pre>
  516. literals = [ '{', '}' ]
  517. def t_lbrace(t):
  518. r'\{'
  519. t.type = '{' # Set token type to the expected literal
  520. return t
  521. def t_rbrace(t):
  522. r'\}'
  523. t.type = '}' # Set token type to the expected literal
  524. return t
  525. </pre>
  526. </blockquote>
  527. <H3><a name="ply_nn12"></a>4.9 Error handling</H3>
  528. <p>
  529. The <tt>t_error()</tt>
  530. function is used to handle lexing errors that occur when illegal
  531. characters are detected. In this case, the <tt>t.value</tt> attribute contains the
  532. rest of the input string that has not been tokenized. In the example, the error function
  533. was defined as follows:
  534. <blockquote>
  535. <pre>
  536. # Error handling rule
  537. def t_error(t):
  538. print("Illegal character '%s'" % t.value[0])
  539. t.lexer.skip(1)
  540. </pre>
  541. </blockquote>
  542. In this case, we simply print the offending character and skip ahead one character by calling <tt>t.lexer.skip(1)</tt>.
  543. <H3><a name="ply_nn14"></a>4.10 EOF Handling</H3>
  544. <p>
  545. The <tt>t_eof()</tt> function is used to handle an end-of-file (EOF) condition in the input. As input, it
  546. receives a token type <tt>'eof'</tt> with the <tt>lineno</tt> and <tt>lexpos</tt> attributes set appropriately.
  547. The main use of this function is provide more input to the lexer so that it can continue to parse. Here is an
  548. example of how this works:
  549. </p>
  550. <blockquote>
  551. <pre>
  552. # EOF handling rule
  553. def t_eof(t):
  554. # Get more input (Example)
  555. more = raw_input('... ')
  556. if more:
  557. self.lexer.input(more)
  558. return self.lexer.token()
  559. return None
  560. </pre>
  561. </blockquote>
  562. <p>
  563. The EOF function should return the next available token (by calling <tt>self.lexer.token())</tt> or <tt>None</tt> to
  564. indicate no more data. Be aware that setting more input with the <tt>self.lexer.input()</tt> method does
  565. NOT reset the lexer state or the <tt>lineno</tt> attribute used for position tracking. The <tt>lexpos</tt>
  566. attribute is reset so be aware of that if you're using it in error reporting.
  567. </p>
  568. <H3><a name="ply_nn13"></a>4.11 Building and using the lexer</H3>
  569. <p>
  570. To build the lexer, the function <tt>lex.lex()</tt> is used. For example:</p>
  571. <blockquote>
  572. <pre>
  573. lexer = lex.lex()
  574. </pre>
  575. </blockquote>
  576. <p>This function
  577. uses Python reflection (or introspection) to read the regular expression rules
  578. out of the calling context and build the lexer. Once the lexer has been built, two methods can
  579. be used to control the lexer.
  580. </p>
  581. <ul>
  582. <li><tt>lexer.input(data)</tt>. Reset the lexer and store a new input string.
  583. <li><tt>lexer.token()</tt>. Return the next token. Returns a special <tt>LexToken</tt> instance on success or
  584. None if the end of the input text has been reached.
  585. </ul>
  586. <H3><a name="ply_nn14b"></a>4.12 The @TOKEN decorator</H3>
  587. In some applications, you may want to define build tokens from as a series of
  588. more complex regular expression rules. For example:
  589. <blockquote>
  590. <pre>
  591. digit = r'([0-9])'
  592. nondigit = r'([_A-Za-z])'
  593. identifier = r'(' + nondigit + r'(' + digit + r'|' + nondigit + r')*)'
  594. def t_ID(t):
  595. # want docstring to be identifier above. ?????
  596. ...
  597. </pre>
  598. </blockquote>
  599. In this case, we want the regular expression rule for <tt>ID</tt> to be one of the variables above. However, there is no
  600. way to directly specify this using a normal documentation string. To solve this problem, you can use the <tt>@TOKEN</tt>
  601. decorator. For example:
  602. <blockquote>
  603. <pre>
  604. from ply.lex import TOKEN
  605. @TOKEN(identifier)
  606. def t_ID(t):
  607. ...
  608. </pre>
  609. </blockquote>
  610. <p>
  611. This will attach <tt>identifier</tt> to the docstring for <tt>t_ID()</tt> allowing <tt>lex.py</tt> to work normally.
  612. </p>
  613. <H3><a name="ply_nn15"></a>4.13 Optimized mode</H3>
  614. For improved performance, it may be desirable to use Python's
  615. optimized mode (e.g., running Python with the <tt>-O</tt>
  616. option). However, doing so causes Python to ignore documentation
  617. strings. This presents special problems for <tt>lex.py</tt>. To
  618. handle this case, you can create your lexer using
  619. the <tt>optimize</tt> option as follows:
  620. <blockquote>
  621. <pre>
  622. lexer = lex.lex(optimize=1)
  623. </pre>
  624. </blockquote>
  625. Next, run Python in its normal operating mode. When you do
  626. this, <tt>lex.py</tt> will write a file called <tt>lextab.py</tt> in
  627. the same directory as the module containing the lexer specification.
  628. This file contains all of the regular
  629. expression rules and tables used during lexing. On subsequent
  630. executions,
  631. <tt>lextab.py</tt> will simply be imported to build the lexer. This
  632. approach substantially improves the startup time of the lexer and it
  633. works in Python's optimized mode.
  634. <p>
  635. To change the name of the lexer-generated module, use the <tt>lextab</tt> keyword argument. For example:
  636. </p>
  637. <blockquote>
  638. <pre>
  639. lexer = lex.lex(optimize=1,lextab="footab")
  640. </pre>
  641. </blockquote>
  642. When running in optimized mode, it is important to note that lex disables most error checking. Thus, this is really only recommended
  643. if you're sure everything is working correctly and you're ready to start releasing production code.
  644. <H3><a name="ply_nn16"></a>4.14 Debugging</H3>
  645. For the purpose of debugging, you can run <tt>lex()</tt> in a debugging mode as follows:
  646. <blockquote>
  647. <pre>
  648. lexer = lex.lex(debug=1)
  649. </pre>
  650. </blockquote>
  651. <p>
  652. This will produce various sorts of debugging information including all of the added rules,
  653. the master regular expressions used by the lexer, and tokens generating during lexing.
  654. </p>
  655. <p>
  656. In addition, <tt>lex.py</tt> comes with a simple main function which
  657. will either tokenize input read from standard input or from a file specified
  658. on the command line. To use it, simply put this in your lexer:
  659. </p>
  660. <blockquote>
  661. <pre>
  662. if __name__ == '__main__':
  663. lex.runmain()
  664. </pre>
  665. </blockquote>
  666. Please refer to the "Debugging" section near the end for some more advanced details
  667. of debugging.
  668. <H3><a name="ply_nn17"></a>4.15 Alternative specification of lexers</H3>
  669. As shown in the example, lexers are specified all within one Python module. If you want to
  670. put token rules in a different module from the one in which you invoke <tt>lex()</tt>, use the
  671. <tt>module</tt> keyword argument.
  672. <p>
  673. For example, you might have a dedicated module that just contains
  674. the token rules:
  675. <blockquote>
  676. <pre>
  677. # module: tokrules.py
  678. # This module just contains the lexing rules
  679. # List of token names. This is always required
  680. tokens = (
  681. 'NUMBER',
  682. 'PLUS',
  683. 'MINUS',
  684. 'TIMES',
  685. 'DIVIDE',
  686. 'LPAREN',
  687. 'RPAREN',
  688. )
  689. # Regular expression rules for simple tokens
  690. t_PLUS = r'\+'
  691. t_MINUS = r'-'
  692. t_TIMES = r'\*'
  693. t_DIVIDE = r'/'
  694. t_LPAREN = r'\('
  695. t_RPAREN = r'\)'
  696. # A regular expression rule with some action code
  697. def t_NUMBER(t):
  698. r'\d+'
  699. t.value = int(t.value)
  700. return t
  701. # Define a rule so we can track line numbers
  702. def t_newline(t):
  703. r'\n+'
  704. t.lexer.lineno += len(t.value)
  705. # A string containing ignored characters (spaces and tabs)
  706. t_ignore = ' \t'
  707. # Error handling rule
  708. def t_error(t):
  709. print("Illegal character '%s'" % t.value[0])
  710. t.lexer.skip(1)
  711. </pre>
  712. </blockquote>
  713. Now, if you wanted to build a tokenizer from these rules from within a different module, you would do the following (shown for Python interactive mode):
  714. <blockquote>
  715. <pre>
  716. >>> import tokrules
  717. >>> <b>lexer = lex.lex(module=tokrules)</b>
  718. >>> lexer.input("3 + 4")
  719. >>> lexer.token()
  720. LexToken(NUMBER,3,1,1,0)
  721. >>> lexer.token()
  722. LexToken(PLUS,'+',1,2)
  723. >>> lexer.token()
  724. LexToken(NUMBER,4,1,4)
  725. >>> lexer.token()
  726. None
  727. >>>
  728. </pre>
  729. </blockquote>
  730. The <tt>module</tt> option can also be used to define lexers from instances of a class. For example:
  731. <blockquote>
  732. <pre>
  733. import ply.lex as lex
  734. class MyLexer(object):
  735. # List of token names. This is always required
  736. tokens = (
  737. 'NUMBER',
  738. 'PLUS',
  739. 'MINUS',
  740. 'TIMES',
  741. 'DIVIDE',
  742. 'LPAREN',
  743. 'RPAREN',
  744. )
  745. # Regular expression rules for simple tokens
  746. t_PLUS = r'\+'
  747. t_MINUS = r'-'
  748. t_TIMES = r'\*'
  749. t_DIVIDE = r'/'
  750. t_LPAREN = r'\('
  751. t_RPAREN = r'\)'
  752. # A regular expression rule with some action code
  753. # Note addition of self parameter since we're in a class
  754. def t_NUMBER(self,t):
  755. r'\d+'
  756. t.value = int(t.value)
  757. return t
  758. # Define a rule so we can track line numbers
  759. def t_newline(self,t):
  760. r'\n+'
  761. t.lexer.lineno += len(t.value)
  762. # A string containing ignored characters (spaces and tabs)
  763. t_ignore = ' \t'
  764. # Error handling rule
  765. def t_error(self,t):
  766. print("Illegal character '%s'" % t.value[0])
  767. t.lexer.skip(1)
  768. <b># Build the lexer
  769. def build(self,**kwargs):
  770. self.lexer = lex.lex(module=self, **kwargs)</b>
  771. # Test it output
  772. def test(self,data):
  773. self.lexer.input(data)
  774. while True:
  775. tok = self.lexer.token()
  776. if not tok:
  777. break
  778. print(tok)
  779. # Build the lexer and try it out
  780. m = MyLexer()
  781. m.build() # Build the lexer
  782. m.test("3 + 4") # Test it
  783. </pre>
  784. </blockquote>
  785. When building a lexer from class, <em>you should construct the lexer from
  786. an instance of the class</em>, not the class object itself. This is because
  787. PLY only works properly if the lexer actions are defined by bound-methods.
  788. <p>
  789. When using the <tt>module</tt> option to <tt>lex()</tt>, PLY collects symbols
  790. from the underlying object using the <tt>dir()</tt> function. There is no
  791. direct access to the <tt>__dict__</tt> attribute of the object supplied as a
  792. module value. </p>
  793. <P>
  794. Finally, if you want to keep things nicely encapsulated, but don't want to use a
  795. full-fledged class definition, lexers can be defined using closures. For example:
  796. <blockquote>
  797. <pre>
  798. import ply.lex as lex
  799. # List of token names. This is always required
  800. tokens = (
  801. 'NUMBER',
  802. 'PLUS',
  803. 'MINUS',
  804. 'TIMES',
  805. 'DIVIDE',
  806. 'LPAREN',
  807. 'RPAREN',
  808. )
  809. def MyLexer():
  810. # Regular expression rules for simple tokens
  811. t_PLUS = r'\+'
  812. t_MINUS = r'-'
  813. t_TIMES = r'\*'
  814. t_DIVIDE = r'/'
  815. t_LPAREN = r'\('
  816. t_RPAREN = r'\)'
  817. # A regular expression rule with some action code
  818. def t_NUMBER(t):
  819. r'\d+'
  820. t.value = int(t.value)
  821. return t
  822. # Define a rule so we can track line numbers
  823. def t_newline(t):
  824. r'\n+'
  825. t.lexer.lineno += len(t.value)
  826. # A string containing ignored characters (spaces and tabs)
  827. t_ignore = ' \t'
  828. # Error handling rule
  829. def t_error(t):
  830. print("Illegal character '%s'" % t.value[0])
  831. t.lexer.skip(1)
  832. # Build the lexer from my environment and return it
  833. return lex.lex()
  834. </pre>
  835. </blockquote>
  836. <p>
  837. <b>Important note:</b> If you are defining a lexer using a class or closure, be aware that PLY still requires you to only
  838. define a single lexer per module (source file). There are extensive validation/error checking parts of the PLY that
  839. may falsely report error messages if you don't follow this rule.
  840. </p>
  841. <H3><a name="ply_nn18"></a>4.16 Maintaining state</H3>
  842. In your lexer, you may want to maintain a variety of state
  843. information. This might include mode settings, symbol tables, and
  844. other details. As an example, suppose that you wanted to keep
  845. track of how many NUMBER tokens had been encountered.
  846. <p>
  847. One way to do this is to keep a set of global variables in the module
  848. where you created the lexer. For example:
  849. <blockquote>
  850. <pre>
  851. num_count = 0
  852. def t_NUMBER(t):
  853. r'\d+'
  854. global num_count
  855. num_count += 1
  856. t.value = int(t.value)
  857. return t
  858. </pre>
  859. </blockquote>
  860. If you don't like the use of a global variable, another place to store
  861. information is inside the Lexer object created by <tt>lex()</tt>.
  862. To this, you can use the <tt>lexer</tt> attribute of tokens passed to
  863. the various rules. For example:
  864. <blockquote>
  865. <pre>
  866. def t_NUMBER(t):
  867. r'\d+'
  868. t.lexer.num_count += 1 # Note use of lexer attribute
  869. t.value = int(t.value)
  870. return t
  871. lexer = lex.lex()
  872. lexer.num_count = 0 # Set the initial count
  873. </pre>
  874. </blockquote>
  875. This latter approach has the advantage of being simple and working
  876. correctly in applications where multiple instantiations of a given
  877. lexer exist in the same application. However, this might also feel
  878. like a gross violation of encapsulation to OO purists.
  879. Just to put your mind at some ease, all
  880. internal attributes of the lexer (with the exception of <tt>lineno</tt>) have names that are prefixed
  881. by <tt>lex</tt> (e.g., <tt>lexdata</tt>,<tt>lexpos</tt>, etc.). Thus,
  882. it is perfectly safe to store attributes in the lexer that
  883. don't have names starting with that prefix or a name that conflicts with one of the
  884. predefined methods (e.g., <tt>input()</tt>, <tt>token()</tt>, etc.).
  885. <p>
  886. If you don't like assigning values on the lexer object, you can define your lexer as a class as
  887. shown in the previous section:
  888. <blockquote>
  889. <pre>
  890. class MyLexer:
  891. ...
  892. def t_NUMBER(self,t):
  893. r'\d+'
  894. self.num_count += 1
  895. t.value = int(t.value)
  896. return t
  897. def build(self, **kwargs):
  898. self.lexer = lex.lex(object=self,**kwargs)
  899. def __init__(self):
  900. self.num_count = 0
  901. </pre>
  902. </blockquote>
  903. The class approach may be the easiest to manage if your application is
  904. going to be creating multiple instances of the same lexer and you need
  905. to manage a lot of state.
  906. <p>
  907. State can also be managed through closures. For example, in Python 3:
  908. <blockquote>
  909. <pre>
  910. def MyLexer():
  911. num_count = 0
  912. ...
  913. def t_NUMBER(t):
  914. r'\d+'
  915. nonlocal num_count
  916. num_count += 1
  917. t.value = int(t.value)
  918. return t
  919. ...
  920. </pre>
  921. </blockquote>
  922. <H3><a name="ply_nn19"></a>4.17 Lexer cloning</H3>
  923. <p>
  924. If necessary, a lexer object can be duplicated by invoking its <tt>clone()</tt> method. For example:
  925. <blockquote>
  926. <pre>
  927. lexer = lex.lex()
  928. ...
  929. newlexer = lexer.clone()
  930. </pre>
  931. </blockquote>
  932. When a lexer is cloned, the copy is exactly identical to the original lexer
  933. including any input text and internal state. However, the clone allows a
  934. different set of input text to be supplied which may be processed separately.
  935. This may be useful in situations when you are writing a parser/compiler that
  936. involves recursive or reentrant processing. For instance, if you
  937. needed to scan ahead in the input for some reason, you could create a
  938. clone and use it to look ahead. Or, if you were implementing some kind of preprocessor,
  939. cloned lexers could be used to handle different input files.
  940. <p>
  941. Creating a clone is different than calling <tt>lex.lex()</tt> in that
  942. PLY doesn't regenerate any of the internal tables or regular expressions.
  943. <p>
  944. Special considerations need to be made when cloning lexers that also
  945. maintain their own internal state using classes or closures. Namely,
  946. you need to be aware that the newly created lexers will share all of
  947. this state with the original lexer. For example, if you defined a
  948. lexer as a class and did this:
  949. <blockquote>
  950. <pre>
  951. m = MyLexer()
  952. a = lex.lex(object=m) # Create a lexer
  953. b = a.clone() # Clone the lexer
  954. </pre>
  955. </blockquote>
  956. Then both <tt>a</tt> and <tt>b</tt> are going to be bound to the same
  957. object <tt>m</tt> and any changes to <tt>m</tt> will be reflected in both lexers. It's
  958. important to emphasize that <tt>clone()</tt> is only meant to create a new lexer
  959. that reuses the regular expressions and environment of another lexer. If you
  960. need to make a totally new copy of a lexer, then call <tt>lex()</tt> again.
  961. <H3><a name="ply_nn20"></a>4.18 Internal lexer state</H3>
  962. A Lexer object <tt>lexer</tt> has a number of internal attributes that may be useful in certain
  963. situations.
  964. <p>
  965. <tt>lexer.lexpos</tt>
  966. <blockquote>
  967. This attribute is an integer that contains the current position within the input text. If you modify
  968. the value, it will change the result of the next call to <tt>token()</tt>. Within token rule functions, this points
  969. to the first character <em>after</em> the matched text. If the value is modified within a rule, the next returned token will be
  970. matched at the new position.
  971. </blockquote>
  972. <p>
  973. <tt>lexer.lineno</tt>
  974. <blockquote>
  975. The current value of the line number attribute stored in the lexer. PLY only specifies that the attribute
  976. exists---it never sets, updates, or performs any processing with it. If you want to track line numbers,
  977. you will need to add code yourself (see the section on line numbers and positional information).
  978. </blockquote>
  979. <p>
  980. <tt>lexer.lexdata</tt>
  981. <blockquote>
  982. The current input text stored in the lexer. This is the string passed with the <tt>input()</tt> method. It
  983. would probably be a bad idea to modify this unless you really know what you're doing.
  984. </blockquote>
  985. <P>
  986. <tt>lexer.lexmatch</tt>
  987. <blockquote>
  988. This is the raw <tt>Match</tt> object returned by the Python <tt>re.match()</tt> function (used internally by PLY) for the
  989. current token. If you have written a regular expression that contains named groups, you can use this to retrieve those values.
  990. Note: This attribute is only updated when tokens are defined and processed by functions.
  991. </blockquote>
  992. <H3><a name="ply_nn21"></a>4.19 Conditional lexing and start conditions</H3>
  993. In advanced parsing applications, it may be useful to have different
  994. lexing states. For instance, you may want the occurrence of a certain
  995. token or syntactic construct to trigger a different kind of lexing.
  996. PLY supports a feature that allows the underlying lexer to be put into
  997. a series of different states. Each state can have its own tokens,
  998. lexing rules, and so forth. The implementation is based largely on
  999. the "start condition" feature of GNU flex. Details of this can be found
  1000. at <a
  1001. href="http://flex.sourceforge.net/manual/Start-Conditions.html">http://flex.sourceforge.net/manual/Start-Conditions.html</a>.
  1002. <p>
  1003. To define a new lexing state, it must first be declared. This is done by including a "states" declaration in your
  1004. lex file. For example:
  1005. <blockquote>
  1006. <pre>
  1007. states = (
  1008. ('foo','exclusive'),
  1009. ('bar','inclusive'),
  1010. )
  1011. </pre>
  1012. </blockquote>
  1013. This declaration declares two states, <tt>'foo'</tt>
  1014. and <tt>'bar'</tt>. States may be of two types; <tt>'exclusive'</tt>
  1015. and <tt>'inclusive'</tt>. An exclusive state completely overrides the
  1016. default behavior of the lexer. That is, lex will only return tokens
  1017. and apply rules defined specifically for that state. An inclusive
  1018. state adds additional tokens and rules to the default set of rules.
  1019. Thus, lex will return both the tokens defined by default in addition
  1020. to those defined for the inclusive state.
  1021. <p>
  1022. Once a state has been declared, tokens and rules are declared by including the
  1023. state name in token/rule declaration. For example:
  1024. <blockquote>
  1025. <pre>
  1026. t_foo_NUMBER = r'\d+' # Token 'NUMBER' in state 'foo'
  1027. t_bar_ID = r'[a-zA-Z_][a-zA-Z0-9_]*' # Token 'ID' in state 'bar'
  1028. def t_foo_newline(t):
  1029. r'\n'
  1030. t.lexer.lineno += 1
  1031. </pre>
  1032. </blockquote>
  1033. A token can be declared in multiple states by including multiple state names in the declaration. For example:
  1034. <blockquote>
  1035. <pre>
  1036. t_foo_bar_NUMBER = r'\d+' # Defines token 'NUMBER' in both state 'foo' and 'bar'
  1037. </pre>
  1038. </blockquote>
  1039. Alternative, a token can be declared in all states using the 'ANY' in the name.
  1040. <blockquote>
  1041. <pre>
  1042. t_ANY_NUMBER = r'\d+' # Defines a token 'NUMBER' in all states
  1043. </pre>
  1044. </blockquote>
  1045. If no state name is supplied, as is normally the case, the token is associated with a special state <tt>'INITIAL'</tt>. For example,
  1046. these two declarations are identical:
  1047. <blockquote>
  1048. <pre>
  1049. t_NUMBER = r'\d+'
  1050. t_INITIAL_NUMBER = r'\d+'
  1051. </pre>
  1052. </blockquote>
  1053. <p>
  1054. States are also associated with the special <tt>t_ignore</tt>, <tt>t_error()</tt>, and <tt>t_eof()</tt> declarations. For example, if a state treats
  1055. these differently, you can declare:</p>
  1056. <blockquote>
  1057. <pre>
  1058. t_foo_ignore = " \t\n" # Ignored characters for state 'foo'
  1059. def t_bar_error(t): # Special error handler for state 'bar'
  1060. pass
  1061. </pre>
  1062. </blockquote>
  1063. By default, lexing operates in the <tt>'INITIAL'</tt> state. This state includes all of the normally defined tokens.
  1064. For users who aren't using different states, this fact is completely transparent. If, during lexing or parsing, you want to change
  1065. the lexing state, use the <tt>begin()</tt> method. For example:
  1066. <blockquote>
  1067. <pre>
  1068. def t_begin_foo(t):
  1069. r'start_foo'
  1070. t.lexer.begin('foo') # Starts 'foo' state
  1071. </pre>
  1072. </blockquote>
  1073. To get out of a state, you use <tt>begin()</tt> to switch back to the initial state. For example:
  1074. <blockquote>
  1075. <pre>
  1076. def t_foo_end(t):
  1077. r'end_foo'
  1078. t.lexer.begin('INITIAL') # Back to the initial state
  1079. </pre>
  1080. </blockquote>
  1081. The management of states can also be done with a stack. For example:
  1082. <blockquote>
  1083. <pre>
  1084. def t_begin_foo(t):
  1085. r'start_foo'
  1086. t.lexer.push_state('foo') # Starts 'foo' state
  1087. def t_foo_end(t):
  1088. r'end_foo'
  1089. t.lexer.pop_state() # Back to the previous state
  1090. </pre>
  1091. </blockquote>
  1092. <p>
  1093. The use of a stack would be useful in situations where there are many ways of entering a new lexing state and you merely want to go back
  1094. to the previous state afterwards.
  1095. <P>
  1096. An example might help clarify. Suppose you were writing a parser and you wanted to grab sections of arbitrary C code enclosed by
  1097. curly braces. That is, whenever you encounter a starting brace '{', you want to read all of the enclosed code up to the ending brace '}'
  1098. and return it as a string. Doing this with a normal regular expression rule is nearly (if not actually) impossible. This is because braces can
  1099. be nested and can be included in comments and strings. Thus, simply matching up to the first matching '}' character isn't good enough. Here is how
  1100. you might use lexer states to do this:
  1101. <blockquote>
  1102. <pre>
  1103. # Declare the state
  1104. states = (
  1105. ('ccode','exclusive'),
  1106. )
  1107. # Match the first {. Enter ccode state.
  1108. def t_ccode(t):
  1109. r'\{'
  1110. t.lexer.code_start = t.lexer.lexpos # Record the starting position
  1111. t.lexer.level = 1 # Initial brace level
  1112. t.lexer.begin('ccode') # Enter 'ccode' state
  1113. # Rules for the ccode state
  1114. def t_ccode_lbrace(t):
  1115. r'\{'
  1116. t.lexer.level +=1
  1117. def t_ccode_rbrace(t):
  1118. r'\}'
  1119. t.lexer.level -=1
  1120. # If closing brace, return the code fragment
  1121. if t.lexer.level == 0:
  1122. t.value = t.lexer.lexdata[t.lexer.code_start:t.lexer.lexpos+1]
  1123. t.type = "CCODE"
  1124. t.lexer.lineno += t.value.count('\n')
  1125. t.lexer.begin('INITIAL')
  1126. return t
  1127. # C or C++ comment (ignore)
  1128. def t_ccode_comment(t):
  1129. r'(/\*(.|\n)*?\*/)|(//.*)'
  1130. pass
  1131. # C string
  1132. def t_ccode_string(t):
  1133. r'\"([^\\\n]|(\\.))*?\"'
  1134. # C character literal
  1135. def t_ccode_char(t):
  1136. r'\'([^\\\n]|(\\.))*?\''
  1137. # Any sequence of non-whitespace characters (not braces, strings)
  1138. def t_ccode_nonspace(t):
  1139. r'[^\s\{\}\'\"]+'
  1140. # Ignored characters (whitespace)
  1141. t_ccode_ignore = " \t\n"
  1142. # For bad characters, we just skip over it
  1143. def t_ccode_error(t):
  1144. t.lexer.skip(1)
  1145. </pre>
  1146. </blockquote>
  1147. In this example, the occurrence of the first '{' causes the lexer to record the starting position and enter a new state <tt>'ccode'</tt>. A collection of rules then match
  1148. various parts of the input that follow (comments, strings, etc.). All of these rules merely discard the token (by not returning a value).
  1149. However, if the closing right brace is encountered, the rule <tt>t_ccode_rbrace</tt> collects all of the code (using the earlier recorded starting
  1150. position), stores it, and returns a token 'CCODE' containing all of that text. When returning the token, the lexing state is restored back to its
  1151. initial state.
  1152. <H3><a name="ply_nn21b"></a>4.20 Miscellaneous Issues</H3>
  1153. <P>
  1154. <li>The lexer requires input to be supplied as a single input string. Since most machines have more than enough memory, this
  1155. rarely presents a performance concern. However, it means that the lexer currently can't be used with streaming data
  1156. such as open files or sockets. This limitation is primarily a side-effect of using the <tt>re</tt> module. You might be
  1157. able to work around this by implementing an appropriate <tt>def t_eof()</tt> end-of-file handling rule. The main complication
  1158. here is that you'll probably need to ensure that data is fed to the lexer in a way so that it doesn't split in in the middle
  1159. of a token.</p>
  1160. <p>
  1161. <li>The lexer should work properly with both Unicode strings given as token and pattern matching rules as
  1162. well as for input text.
  1163. <p>
  1164. <li>If you need to supply optional flags to the re.compile() function, use the reflags option to lex. For example:
  1165. <blockquote>
  1166. <pre>
  1167. lex.lex(reflags=re.UNICODE | re.VERBOSE)
  1168. </pre>
  1169. </blockquote>
  1170. Note: by default, <tt>reflags</tt> is set to <tt>re.VERBOSE</tt>. If you provide
  1171. your own flags, you may need to include this for PLY to preserve its normal behavior.
  1172. <p>
  1173. <li>Since the lexer is written entirely in Python, its performance is
  1174. largely determined by that of the Python <tt>re</tt> module. Although
  1175. the lexer has been written to be as efficient as possible, it's not
  1176. blazingly fast when used on very large input files. If
  1177. performance is concern, you might consider upgrading to the most
  1178. recent version of Python, creating a hand-written lexer, or offloading
  1179. the lexer into a C extension module.
  1180. <p>
  1181. If you are going to create a hand-written lexer and you plan to use it with <tt>yacc.py</tt>,
  1182. it only needs to conform to the following requirements:
  1183. <ul>
  1184. <li>It must provide a <tt>token()</tt> method that returns the next token or <tt>None</tt> if no more
  1185. tokens are available.
  1186. <li>The <tt>token()</tt> method must return an object <tt>tok</tt> that has <tt>type</tt> and <tt>value</tt> attributes. If
  1187. line number tracking is being used, then the token should also define a <tt>lineno</tt> attribute.
  1188. </ul>
  1189. <H2><a name="ply_nn22"></a>5. Parsing basics</H2>
  1190. <tt>yacc.py</tt> is used to parse language syntax. Before showing an
  1191. example, there are a few important bits of background that must be
  1192. mentioned. First, <em>syntax</em> is usually specified in terms of a BNF grammar.
  1193. For example, if you wanted to parse
  1194. simple arithmetic expressions, you might first write an unambiguous
  1195. grammar specification like this:
  1196. <blockquote>
  1197. <pre>
  1198. expression : expression + term
  1199. | expression - term
  1200. | term
  1201. term : term * factor
  1202. | term / factor
  1203. | factor
  1204. factor : NUMBER
  1205. | ( expression )
  1206. </pre>
  1207. </blockquote>
  1208. In the grammar, symbols such as <tt>NUMBER</tt>, <tt>+</tt>, <tt>-</tt>, <tt>*</tt>, and <tt>/</tt> are known
  1209. as <em>terminals</em> and correspond to raw input tokens. Identifiers such as <tt>term</tt> and <tt>factor</tt> refer to
  1210. grammar rules comprised of a collection of terminals and other rules. These identifiers are known as <em>non-terminals</em>.
  1211. <P>
  1212. The semantic behavior of a language is often specified using a
  1213. technique known as syntax directed translation. In syntax directed
  1214. translation, attributes are attached to each symbol in a given grammar
  1215. rule along with an action. Whenever a particular grammar rule is
  1216. recognized, the action describes what to do. For example, given the
  1217. expression grammar above, you might write the specification for a
  1218. simple calculator like this:
  1219. <blockquote>
  1220. <pre>
  1221. Grammar Action
  1222. -------------------------------- --------------------------------------------
  1223. expression0 : expression1 + term expression0.val = expression1.val + term.val
  1224. | expression1 - term expression0.val = expression1.val - term.val
  1225. | term expression0.val = term.val
  1226. term0 : term1 * factor term0.val = term1.val * factor.val
  1227. | term1 / factor term0.val = term1.val / factor.val
  1228. | factor term0.val = factor.val
  1229. factor : NUMBER factor.val = int(NUMBER.lexval)
  1230. | ( expression ) factor.val = expression.val
  1231. </pre>
  1232. </blockquote>
  1233. A good way to think about syntax directed translation is to
  1234. view each symbol in the grammar as a kind of object. Associated
  1235. with each symbol is a value representing its "state" (for example, the
  1236. <tt>val</tt> attribute above). Semantic
  1237. actions are then expressed as a collection of functions or methods
  1238. that operate on the symbols and associated values.
  1239. <p>
  1240. Yacc uses a parsing technique known as LR-parsing or shift-reduce parsing. LR parsing is a
  1241. bottom up technique that tries to recognize the right-hand-side of various grammar rules.
  1242. Whenever a valid right-hand-side is found in the input, the appropriate action code is triggered and the
  1243. grammar symbols are replaced by the grammar symbol on the left-hand-side.
  1244. <p>
  1245. LR parsing is commonly implemented by shifting grammar symbols onto a
  1246. stack and looking at the stack and the next input token for patterns that
  1247. match one of the grammar rules.
  1248. The details of the algorithm can be found in a compiler textbook, but the
  1249. following example illustrates the steps that are performed if you
  1250. wanted to parse the expression
  1251. <tt>3 + 5 * (10 - 20)</tt> using the grammar defined above. In the example,
  1252. the special symbol <tt>$</tt> represents the end of input.
  1253. <blockquote>
  1254. <pre>
  1255. Step Symbol Stack Input Tokens Action
  1256. ---- --------------------- --------------------- -------------------------------
  1257. 1 3 + 5 * ( 10 - 20 )$ Shift 3
  1258. 2 3 + 5 * ( 10 - 20 )$ Reduce factor : NUMBER
  1259. 3 factor + 5 * ( 10 - 20 )$ Reduce term : factor
  1260. 4 term + 5 * ( 10 - 20 )$ Reduce expr : term
  1261. 5 expr + 5 * ( 10 - 20 )$ Shift +
  1262. 6 expr + 5 * ( 10 - 20 )$ Shift 5
  1263. 7 expr + 5 * ( 10 - 20 )$ Reduce factor : NUMBER
  1264. 8 expr + factor * ( 10 - 20 )$ Reduce term : factor
  1265. 9 expr + term * ( 10 - 20 )$ Shift *
  1266. 10 expr + term * ( 10 - 20 )$ Shift (
  1267. 11 expr + term * ( 10 - 20 )$ Shift 10
  1268. 12 expr + term * ( 10 - 20 )$ Reduce factor : NUMBER
  1269. 13 expr + term * ( factor - 20 )$ Reduce term : factor
  1270. 14 expr + term * ( term - 20 )$ Reduce expr : term
  1271. 15 expr + term * ( expr - 20 )$ Shift -
  1272. 16 expr + term * ( expr - 20 )$ Shift 20
  1273. 17 expr + term * ( expr - 20 )$ Reduce factor : NUMBER
  1274. 18 expr + term * ( expr - factor )$ Reduce term : factor
  1275. 19 expr + term * ( expr - term )$ Reduce expr : expr - term
  1276. 20 expr + term * ( expr )$ Shift )
  1277. 21 expr + term * ( expr ) $ Reduce factor : (expr)
  1278. 22 expr + term * factor $ Reduce term : term * factor
  1279. 23 expr + term $ Reduce expr : expr + term
  1280. 24 expr $ Reduce expr
  1281. 25 $ Success!
  1282. </pre>
  1283. </blockquote>
  1284. When parsing the expression, an underlying state machine and the
  1285. current input token determine what happens next. If the next token
  1286. looks like part of a valid grammar rule (based on other items on the
  1287. stack), it is generally shifted onto the stack. If the top of the
  1288. stack contains a valid right-hand-side of a grammar rule, it is
  1289. usually "reduced" and the symbols replaced with the symbol on the
  1290. left-hand-side. When this reduction occurs, the appropriate action is
  1291. triggered (if defined). If the input token can't be shifted and the
  1292. top of stack doesn't match any grammar rules, a syntax error has
  1293. occurred and the parser must take some kind of recovery step (or bail
  1294. out). A parse is only successful if the parser reaches a state where
  1295. the symbol stack is empty and there are no more input tokens.
  1296. <p>
  1297. It is important to note that the underlying implementation is built
  1298. around a large finite-state machine that is encoded in a collection of
  1299. tables. The construction of these tables is non-trivial and
  1300. beyond the scope of this discussion. However, subtle details of this
  1301. process explain why, in the example above, the parser chooses to shift
  1302. a token onto the stack in step 9 rather than reducing the
  1303. rule <tt>expr : expr + term</tt>.
  1304. <H2><a name="ply_nn23"></a>6. Yacc</H2>
  1305. The <tt>ply.yacc</tt> module implements the parsing component of PLY.
  1306. The name "yacc" stands for "Yet Another Compiler Compiler" and is
  1307. borrowed from the Unix tool of the same name.
  1308. <H3><a name="ply_nn24"></a>6.1 An example</H3>
  1309. Suppose you wanted to make a grammar for simple arithmetic expressions as previously described. Here is
  1310. how you would do it with <tt>yacc.py</tt>:
  1311. <blockquote>
  1312. <pre>
  1313. # Yacc example
  1314. import ply.yacc as yacc
  1315. # Get the token map from the lexer. This is required.
  1316. from calclex import tokens
  1317. def p_expression_plus(p):
  1318. 'expression : expression PLUS term'
  1319. p[0] = p[1] + p[3]
  1320. def p_expression_minus(p):
  1321. 'expression : expression MINUS term'
  1322. p[0] = p[1] - p[3]
  1323. def p_expression_term(p):
  1324. 'expression : term'
  1325. p[0] = p[1]
  1326. def p_term_times(p):
  1327. 'term : term TIMES factor'
  1328. p[0] = p[1] * p[3]
  1329. def p_term_div(p):
  1330. 'term : term DIVIDE factor'
  1331. p[0] = p[1] / p[3]
  1332. def p_term_factor(p):
  1333. 'term : factor'
  1334. p[0] = p[1]
  1335. def p_factor_num(p):
  1336. 'factor : NUMBER'
  1337. p[0] = p[1]
  1338. def p_factor_expr(p):
  1339. 'factor : LPAREN expression RPAREN'
  1340. p[0] = p[2]
  1341. # Error rule for syntax errors
  1342. def p_error(p):
  1343. print("Syntax error in input!")
  1344. # Build the parser
  1345. parser = yacc.yacc()
  1346. while True:
  1347. try:
  1348. s = raw_input('calc > ')
  1349. except EOFError:
  1350. break
  1351. if not s: continue
  1352. result = parser.parse(s)
  1353. print(result)
  1354. </pre>
  1355. </blockquote>
  1356. In this example, each grammar rule is defined by a Python function
  1357. where the docstring to that function contains the appropriate
  1358. context-free grammar specification. The statements that make up the
  1359. function body implement the semantic actions of the rule. Each function
  1360. accepts a single argument <tt>p</tt> that is a sequence containing the
  1361. values of each grammar symbol in the corresponding rule. The values
  1362. of <tt>p[i]</tt> are mapped to grammar symbols as shown here:
  1363. <blockquote>
  1364. <pre>
  1365. def p_expression_plus(p):
  1366. 'expression : expression PLUS term'
  1367. # ^ ^ ^ ^
  1368. # p[0] p[1] p[2] p[3]
  1369. p[0] = p[1] + p[3]
  1370. </pre>
  1371. </blockquote>
  1372. <p>
  1373. For tokens, the "value" of the corresponding <tt>p[i]</tt> is the
  1374. <em>same</em> as the <tt>p.value</tt> attribute assigned in the lexer
  1375. module. For non-terminals, the value is determined by whatever is
  1376. placed in <tt>p[0]</tt> when rules are reduced. This value can be
  1377. anything at all. However, it probably most common for the value to be
  1378. a simple Python type, a tuple, or an instance. In this example, we
  1379. are relying on the fact that the <tt>NUMBER</tt> token stores an
  1380. integer value in its value field. All of the other rules simply
  1381. perform various types of integer operations and propagate the result.
  1382. </p>
  1383. <p>
  1384. Note: The use of negative indices have a special meaning in
  1385. yacc---specially <tt>p[-1]</tt> does not have the same value
  1386. as <tt>p[3]</tt> in this example. Please see the section on "Embedded
  1387. Actions" for further details.
  1388. </p>
  1389. <p>
  1390. The first rule defined in the yacc specification determines the
  1391. starting grammar symbol (in this case, a rule for <tt>expression</tt>
  1392. appears first). Whenever the starting rule is reduced by the parser
  1393. and no more input is available, parsing stops and the final value is
  1394. returned (this value will be whatever the top-most rule placed
  1395. in <tt>p[0]</tt>). Note: an alternative starting symbol can be
  1396. specified using the <tt>start</tt> keyword argument to
  1397. <tt>yacc()</tt>.
  1398. <p>The <tt>p_error(p)</tt> rule is defined to catch syntax errors.
  1399. See the error handling section below for more detail.
  1400. <p>
  1401. To build the parser, call the <tt>yacc.yacc()</tt> function. This
  1402. function looks at the module and attempts to construct all of the LR
  1403. parsing tables for the grammar you have specified. The first
  1404. time <tt>yacc.yacc()</tt> is invoked, you will get a message such as
  1405. this:
  1406. <blockquote>
  1407. <pre>
  1408. $ python calcparse.py
  1409. Generating LALR tables
  1410. calc >
  1411. </pre>
  1412. </blockquote>
  1413. <p>
  1414. Since table construction is relatively expensive (especially for large
  1415. grammars), the resulting parsing table is written to
  1416. a file called <tt>parsetab.py</tt>. In addition, a
  1417. debugging file called <tt>parser.out</tt> is created. On subsequent
  1418. executions, <tt>yacc</tt> will reload the table from
  1419. <tt>parsetab.py</tt> unless it has detected a change in the underlying
  1420. grammar (in which case the tables and <tt>parsetab.py</tt> file are
  1421. regenerated). Both of these files are written to the same directory
  1422. as the module in which the parser is specified.
  1423. The name of the <tt>parsetab</tt> module can be changed using the
  1424. <tt>tabmodule</tt> keyword argument to <tt>yacc()</tt>. For example:
  1425. </p>
  1426. <blockquote>
  1427. <pre>
  1428. parser = yacc.yacc(tabmodule='fooparsetab')
  1429. </pre>
  1430. </blockquote>
  1431. <p>
  1432. If any errors are detected in your grammar specification, <tt>yacc.py</tt> will produce
  1433. diagnostic messages and possibly raise an exception. Some of the errors that can be detected include:
  1434. <ul>
  1435. <li>Duplicated function names (if more than one rule function have the same name in the grammar file).
  1436. <li>Shift/reduce and reduce/reduce conflicts generated by ambiguous grammars.
  1437. <li>Badly specified grammar rules.
  1438. <li>Infinite recursion (rules that can never terminate).
  1439. <li>Unused rules and tokens
  1440. <li>Undefined rules and tokens
  1441. </ul>
  1442. The next few sections discuss grammar specification in more detail.
  1443. <p>
  1444. The final part of the example shows how to actually run the parser
  1445. created by
  1446. <tt>yacc()</tt>. To run the parser, you simply have to call
  1447. the <tt>parse()</tt> with a string of input text. This will run all
  1448. of the grammar rules and return the result of the entire parse. This
  1449. result return is the value assigned to <tt>p[0]</tt> in the starting
  1450. grammar rule.
  1451. <H3><a name="ply_nn25"></a>6.2 Combining Grammar Rule Functions</H3>
  1452. When grammar rules are similar, they can be combined into a single function.
  1453. For example, consider the two rules in our earlier example:
  1454. <blockquote>
  1455. <pre>
  1456. def p_expression_plus(p):
  1457. 'expression : expression PLUS term'
  1458. p[0] = p[1] + p[3]
  1459. def p_expression_minus(t):
  1460. 'expression : expression MINUS term'
  1461. p[0] = p[1] - p[3]
  1462. </pre>
  1463. </blockquote>
  1464. Instead of writing two functions, you might write a single function like this:
  1465. <blockquote>
  1466. <pre>
  1467. def p_expression(p):
  1468. '''expression : expression PLUS term
  1469. | expression MINUS term'''
  1470. if p[2] == '+':
  1471. p[0] = p[1] + p[3]
  1472. elif p[2] == '-':
  1473. p[0] = p[1] - p[3]
  1474. </pre>
  1475. </blockquote>
  1476. In general, the doc string for any given function can contain multiple grammar rules. So, it would
  1477. have also been legal (although possibly confusing) to write this:
  1478. <blockquote>
  1479. <pre>
  1480. def p_binary_operators(p):
  1481. '''expression : expression PLUS term
  1482. | expression MINUS term
  1483. term : term TIMES factor
  1484. | term DIVIDE factor'''
  1485. if p[2] == '+':
  1486. p[0] = p[1] + p[3]
  1487. elif p[2] == '-':
  1488. p[0] = p[1] - p[3]
  1489. elif p[2] == '*':
  1490. p[0] = p[1] * p[3]
  1491. elif p[2] == '/':
  1492. p[0] = p[1] / p[3]
  1493. </pre>
  1494. </blockquote>
  1495. When combining grammar rules into a single function, it is usually a good idea for all of the rules to have
  1496. a similar structure (e.g., the same number of terms). Otherwise, the corresponding action code may be more
  1497. complicated than necessary. However, it is possible to handle simple cases using len(). For example:
  1498. <blockquote>
  1499. <pre>
  1500. def p_expressions(p):
  1501. '''expression : expression MINUS expression
  1502. | MINUS expression'''
  1503. if (len(p) == 4):
  1504. p[0] = p[1] - p[3]
  1505. elif (len(p) == 3):
  1506. p[0] = -p[2]
  1507. </pre>
  1508. </blockquote>
  1509. If parsing performance is a concern, you should resist the urge to put
  1510. too much conditional processing into a single grammar rule as shown in
  1511. these examples. When you add checks to see which grammar rule is
  1512. being handled, you are actually duplicating the work that the parser
  1513. has already performed (i.e., the parser already knows exactly what rule it
  1514. matched). You can eliminate this overhead by using a
  1515. separate <tt>p_rule()</tt> function for each grammar rule.
  1516. <H3><a name="ply_nn26"></a>6.3 Character Literals</H3>
  1517. If desired, a grammar may contain tokens defined as single character literals. For example:
  1518. <blockquote>
  1519. <pre>
  1520. def p_binary_operators(p):
  1521. '''expression : expression '+' term
  1522. | expression '-' term
  1523. term : term '*' factor
  1524. | term '/' factor'''
  1525. if p[2] == '+':
  1526. p[0] = p[1] + p[3]
  1527. elif p[2] == '-':
  1528. p[0] = p[1] - p[3]
  1529. elif p[2] == '*':
  1530. p[0] = p[1] * p[3]
  1531. elif p[2] == '/':
  1532. p[0] = p[1] / p[3]
  1533. </pre>
  1534. </blockquote>
  1535. A character literal must be enclosed in quotes such as <tt>'+'</tt>. In addition, if literals are used, they must be declared in the
  1536. corresponding <tt>lex</tt> file through the use of a special <tt>literals</tt> declaration.
  1537. <blockquote>
  1538. <pre>
  1539. # Literals. Should be placed in module given to lex()
  1540. literals = ['+','-','*','/' ]
  1541. </pre>
  1542. </blockquote>
  1543. <b>Character literals are limited to a single character</b>. Thus, it is not legal to specify literals such as <tt>'&lt;='</tt> or <tt>'=='</tt>. For this, use
  1544. the normal lexing rules (e.g., define a rule such as <tt>t_EQ = r'=='</tt>).
  1545. <H3><a name="ply_nn26b"></a>6.4 Empty Productions</H3>
  1546. <tt>yacc.py</tt> can handle empty productions by defining a rule like this:
  1547. <blockquote>
  1548. <pre>
  1549. def p_empty(p):
  1550. 'empty :'
  1551. pass
  1552. </pre>
  1553. </blockquote>
  1554. Now to use the empty production, simply use 'empty' as a symbol. For example:
  1555. <blockquote>
  1556. <pre>
  1557. def p_optitem(p):
  1558. 'optitem : item'
  1559. ' | empty'
  1560. ...
  1561. </pre>
  1562. </blockquote>
  1563. Note: You can write empty rules anywhere by simply specifying an empty
  1564. right hand side. However, I personally find that writing an "empty"
  1565. rule and using "empty" to denote an empty production is easier to read
  1566. and more clearly states your intentions.
  1567. <H3><a name="ply_nn28"></a>6.5 Changing the starting symbol</H3>
  1568. Normally, the first rule found in a yacc specification defines the starting grammar rule (top level rule). To change this, simply
  1569. supply a <tt>start</tt> specifier in your file. For example:
  1570. <blockquote>
  1571. <pre>
  1572. start = 'foo'
  1573. def p_bar(p):
  1574. 'bar : A B'
  1575. # This is the starting rule due to the start specifier above
  1576. def p_foo(p):
  1577. 'foo : bar X'
  1578. ...
  1579. </pre>
  1580. </blockquote>
  1581. The use of a <tt>start</tt> specifier may be useful during debugging
  1582. since you can use it to have yacc build a subset of a larger grammar.
  1583. For this purpose, it is also possible to specify a starting symbol as
  1584. an argument to <tt>yacc()</tt>. For example:
  1585. <blockquote>
  1586. <pre>
  1587. parser = yacc.yacc(start='foo')
  1588. </pre>
  1589. </blockquote>
  1590. <H3><a name="ply_nn27"></a>6.6 Dealing With Ambiguous Grammars</H3>
  1591. The expression grammar given in the earlier example has been written
  1592. in a special format to eliminate ambiguity. However, in many
  1593. situations, it is extremely difficult or awkward to write grammars in
  1594. this format. A much more natural way to express the grammar is in a
  1595. more compact form like this:
  1596. <blockquote>
  1597. <pre>
  1598. expression : expression PLUS expression
  1599. | expression MINUS expression
  1600. | expression TIMES expression
  1601. | expression DIVIDE expression
  1602. | LPAREN expression RPAREN
  1603. | NUMBER
  1604. </pre>
  1605. </blockquote>
  1606. Unfortunately, this grammar specification is ambiguous. For example,
  1607. if you are parsing the string "3 * 4 + 5", there is no way to tell how
  1608. the operators are supposed to be grouped. For example, does the
  1609. expression mean "(3 * 4) + 5" or is it "3 * (4+5)"?
  1610. <p>
  1611. When an ambiguous grammar is given to <tt>yacc.py</tt> it will print
  1612. messages about "shift/reduce conflicts" or "reduce/reduce conflicts".
  1613. A shift/reduce conflict is caused when the parser generator can't
  1614. decide whether or not to reduce a rule or shift a symbol on the
  1615. parsing stack. For example, consider the string "3 * 4 + 5" and the
  1616. internal parsing stack:
  1617. <blockquote>
  1618. <pre>
  1619. Step Symbol Stack Input Tokens Action
  1620. ---- --------------------- --------------------- -------------------------------
  1621. 1 $ 3 * 4 + 5$ Shift 3
  1622. 2 $ 3 * 4 + 5$ Reduce : expression : NUMBER
  1623. 3 $ expr * 4 + 5$ Shift *
  1624. 4 $ expr * 4 + 5$ Shift 4
  1625. 5 $ expr * 4 + 5$ Reduce: expression : NUMBER
  1626. 6 $ expr * expr + 5$ SHIFT/REDUCE CONFLICT ????
  1627. </pre>
  1628. </blockquote>
  1629. In this case, when the parser reaches step 6, it has two options. One
  1630. is to reduce the rule <tt>expr : expr * expr</tt> on the stack. The
  1631. other option is to shift the token <tt>+</tt> on the stack. Both
  1632. options are perfectly legal from the rules of the
  1633. context-free-grammar.
  1634. <p>
  1635. By default, all shift/reduce conflicts are resolved in favor of
  1636. shifting. Therefore, in the above example, the parser will always
  1637. shift the <tt>+</tt> instead of reducing. Although this strategy
  1638. works in many cases (for example, the case of
  1639. "if-then" versus "if-then-else"), it is not enough for arithmetic expressions. In fact,
  1640. in the above example, the decision to shift <tt>+</tt> is completely
  1641. wrong---we should have reduced <tt>expr * expr</tt> since
  1642. multiplication has higher mathematical precedence than addition.
  1643. <p>To resolve ambiguity, especially in expression
  1644. grammars, <tt>yacc.py</tt> allows individual tokens to be assigned a
  1645. precedence level and associativity. This is done by adding a variable
  1646. <tt>precedence</tt> to the grammar file like this:
  1647. <blockquote>
  1648. <pre>
  1649. precedence = (
  1650. ('left', 'PLUS', 'MINUS'),
  1651. ('left', 'TIMES', 'DIVIDE'),
  1652. )
  1653. </pre>
  1654. </blockquote>
  1655. This declaration specifies that <tt>PLUS</tt>/<tt>MINUS</tt> have the
  1656. same precedence level and are left-associative and that
  1657. <tt>TIMES</tt>/<tt>DIVIDE</tt> have the same precedence and are
  1658. left-associative. Within the <tt>precedence</tt> declaration, tokens
  1659. are ordered from lowest to highest precedence. Thus, this declaration
  1660. specifies that <tt>TIMES</tt>/<tt>DIVIDE</tt> have higher precedence
  1661. than <tt>PLUS</tt>/<tt>MINUS</tt> (since they appear later in the
  1662. precedence specification).
  1663. <p>
  1664. The precedence specification works by associating a numerical
  1665. precedence level value and associativity direction to the listed
  1666. tokens. For example, in the above example you get:
  1667. <blockquote>
  1668. <pre>
  1669. PLUS : level = 1, assoc = 'left'
  1670. MINUS : level = 1, assoc = 'left'
  1671. TIMES : level = 2, assoc = 'left'
  1672. DIVIDE : level = 2, assoc = 'left'
  1673. </pre>
  1674. </blockquote>
  1675. These values are then used to attach a numerical precedence value and
  1676. associativity direction to each grammar rule. <em>This is always
  1677. determined by looking at the precedence of the right-most terminal
  1678. symbol.</em> For example:
  1679. <blockquote>
  1680. <pre>
  1681. expression : expression PLUS expression # level = 1, left
  1682. | expression MINUS expression # level = 1, left
  1683. | expression TIMES expression # level = 2, left
  1684. | expression DIVIDE expression # level = 2, left
  1685. | LPAREN expression RPAREN # level = None (not specified)
  1686. | NUMBER # level = None (not specified)
  1687. </pre>
  1688. </blockquote>
  1689. When shift/reduce conflicts are encountered, the parser generator resolves the conflict by
  1690. looking at the precedence rules and associativity specifiers.
  1691. <p>
  1692. <ol>
  1693. <li>If the current token has higher precedence than the rule on the stack, it is shifted.
  1694. <li>If the grammar rule on the stack has higher precedence, the rule is reduced.
  1695. <li>If the current token and the grammar rule have the same precedence, the
  1696. rule is reduced for left associativity, whereas the token is shifted for right associativity.
  1697. <li>If nothing is known about the precedence, shift/reduce conflicts are resolved in
  1698. favor of shifting (the default).
  1699. </ol>
  1700. For example, if "expression PLUS expression" has been parsed and the
  1701. next token is "TIMES", the action is going to be a shift because
  1702. "TIMES" has a higher precedence level than "PLUS". On the other hand,
  1703. if "expression TIMES expression" has been parsed and the next token is
  1704. "PLUS", the action is going to be reduce because "PLUS" has a lower
  1705. precedence than "TIMES."
  1706. <p>
  1707. When shift/reduce conflicts are resolved using the first three
  1708. techniques (with the help of precedence rules), <tt>yacc.py</tt> will
  1709. report no errors or conflicts in the grammar (although it will print
  1710. some information in the <tt>parser.out</tt> debugging file).
  1711. <p>
  1712. One problem with the precedence specifier technique is that it is
  1713. sometimes necessary to change the precedence of an operator in certain
  1714. contexts. For example, consider a unary-minus operator in "3 + 4 *
  1715. -5". Mathematically, the unary minus is normally given a very high
  1716. precedence--being evaluated before the multiply. However, in our
  1717. precedence specifier, MINUS has a lower precedence than TIMES. To
  1718. deal with this, precedence rules can be given for so-called "fictitious tokens"
  1719. like this:
  1720. <blockquote>
  1721. <pre>
  1722. precedence = (
  1723. ('left', 'PLUS', 'MINUS'),
  1724. ('left', 'TIMES', 'DIVIDE'),
  1725. ('right', 'UMINUS'), # Unary minus operator
  1726. )
  1727. </pre>
  1728. </blockquote>
  1729. Now, in the grammar file, we can write our unary minus rule like this:
  1730. <blockquote>
  1731. <pre>
  1732. def p_expr_uminus(p):
  1733. 'expression : MINUS expression %prec UMINUS'
  1734. p[0] = -p[2]
  1735. </pre>
  1736. </blockquote>
  1737. In this case, <tt>%prec UMINUS</tt> overrides the default rule precedence--setting it to that
  1738. of UMINUS in the precedence specifier.
  1739. <p>
  1740. At first, the use of UMINUS in this example may appear very confusing.
  1741. UMINUS is not an input token or a grammar rule. Instead, you should
  1742. think of it as the name of a special marker in the precedence table. When you use the <tt>%prec</tt> qualifier, you're simply
  1743. telling yacc that you want the precedence of the expression to be the same as for this special marker instead of the usual precedence.
  1744. <p>
  1745. It is also possible to specify non-associativity in the <tt>precedence</tt> table. This would
  1746. be used when you <em>don't</em> want operations to chain together. For example, suppose
  1747. you wanted to support comparison operators like <tt>&lt;</tt> and <tt>&gt;</tt> but you didn't want to allow
  1748. combinations like <tt>a &lt; b &lt; c</tt>. To do this, simply specify a rule like this:
  1749. <blockquote>
  1750. <pre>
  1751. precedence = (
  1752. ('nonassoc', 'LESSTHAN', 'GREATERTHAN'), # Nonassociative operators
  1753. ('left', 'PLUS', 'MINUS'),
  1754. ('left', 'TIMES', 'DIVIDE'),
  1755. ('right', 'UMINUS'), # Unary minus operator
  1756. )
  1757. </pre>
  1758. </blockquote>
  1759. <p>
  1760. If you do this, the occurrence of input text such as <tt> a &lt; b &lt; c</tt> will result in a syntax error. However, simple
  1761. expressions such as <tt>a &lt; b</tt> will still be fine.
  1762. <p>
  1763. Reduce/reduce conflicts are caused when there are multiple grammar
  1764. rules that can be applied to a given set of symbols. This kind of
  1765. conflict is almost always bad and is always resolved by picking the
  1766. rule that appears first in the grammar file. Reduce/reduce conflicts
  1767. are almost always caused when different sets of grammar rules somehow
  1768. generate the same set of symbols. For example:
  1769. <blockquote>
  1770. <pre>
  1771. assignment : ID EQUALS NUMBER
  1772. | ID EQUALS expression
  1773. expression : expression PLUS expression
  1774. | expression MINUS expression
  1775. | expression TIMES expression
  1776. | expression DIVIDE expression
  1777. | LPAREN expression RPAREN
  1778. | NUMBER
  1779. </pre>
  1780. </blockquote>
  1781. In this case, a reduce/reduce conflict exists between these two rules:
  1782. <blockquote>
  1783. <pre>
  1784. assignment : ID EQUALS NUMBER
  1785. expression : NUMBER
  1786. </pre>
  1787. </blockquote>
  1788. For example, if you wrote "a = 5", the parser can't figure out if this
  1789. is supposed to be reduced as <tt>assignment : ID EQUALS NUMBER</tt> or
  1790. whether it's supposed to reduce the 5 as an expression and then reduce
  1791. the rule <tt>assignment : ID EQUALS expression</tt>.
  1792. <p>
  1793. It should be noted that reduce/reduce conflicts are notoriously
  1794. difficult to spot simply looking at the input grammar. When a
  1795. reduce/reduce conflict occurs, <tt>yacc()</tt> will try to help by
  1796. printing a warning message such as this:
  1797. <blockquote>
  1798. <pre>
  1799. WARNING: 1 reduce/reduce conflict
  1800. WARNING: reduce/reduce conflict in state 15 resolved using rule (assignment -> ID EQUALS NUMBER)
  1801. WARNING: rejected rule (expression -> NUMBER)
  1802. </pre>
  1803. </blockquote>
  1804. This message identifies the two rules that are in conflict. However,
  1805. it may not tell you how the parser arrived at such a state. To try
  1806. and figure it out, you'll probably have to look at your grammar and
  1807. the contents of the
  1808. <tt>parser.out</tt> debugging file with an appropriately high level of
  1809. caffeination.
  1810. <H3><a name="ply_nn28b"></a>6.7 The parser.out file</H3>
  1811. Tracking down shift/reduce and reduce/reduce conflicts is one of the finer pleasures of using an LR
  1812. parsing algorithm. To assist in debugging, <tt>yacc.py</tt> creates a debugging file called
  1813. 'parser.out' when it generates the parsing table. The contents of this file look like the following:
  1814. <blockquote>
  1815. <pre>
  1816. Unused terminals:
  1817. Grammar
  1818. Rule 1 expression -> expression PLUS expression
  1819. Rule 2 expression -> expression MINUS expression
  1820. Rule 3 expression -> expression TIMES expression
  1821. Rule 4 expression -> expression DIVIDE expression
  1822. Rule 5 expression -> NUMBER
  1823. Rule 6 expression -> LPAREN expression RPAREN
  1824. Terminals, with rules where they appear
  1825. TIMES : 3
  1826. error :
  1827. MINUS : 2
  1828. RPAREN : 6
  1829. LPAREN : 6
  1830. DIVIDE : 4
  1831. PLUS : 1
  1832. NUMBER : 5
  1833. Nonterminals, with rules where they appear
  1834. expression : 1 1 2 2 3 3 4 4 6 0
  1835. Parsing method: LALR
  1836. state 0
  1837. S' -> . expression
  1838. expression -> . expression PLUS expression
  1839. expression -> . expression MINUS expression
  1840. expression -> . expression TIMES expression
  1841. expression -> . expression DIVIDE expression
  1842. expression -> . NUMBER
  1843. expression -> . LPAREN expression RPAREN
  1844. NUMBER shift and go to state 3
  1845. LPAREN shift and go to state 2
  1846. state 1
  1847. S' -> expression .
  1848. expression -> expression . PLUS expression
  1849. expression -> expression . MINUS expression
  1850. expression -> expression . TIMES expression
  1851. expression -> expression . DIVIDE expression
  1852. PLUS shift and go to state 6
  1853. MINUS shift and go to state 5
  1854. TIMES shift and go to state 4
  1855. DIVIDE shift and go to state 7
  1856. state 2
  1857. expression -> LPAREN . expression RPAREN
  1858. expression -> . expression PLUS expression
  1859. expression -> . expression MINUS expression
  1860. expression -> . expression TIMES expression
  1861. expression -> . expression DIVIDE expression
  1862. expression -> . NUMBER
  1863. expression -> . LPAREN expression RPAREN
  1864. NUMBER shift and go to state 3
  1865. LPAREN shift and go to state 2
  1866. state 3
  1867. expression -> NUMBER .
  1868. $ reduce using rule 5
  1869. PLUS reduce using rule 5
  1870. MINUS reduce using rule 5
  1871. TIMES reduce using rule 5
  1872. DIVIDE reduce using rule 5
  1873. RPAREN reduce using rule 5
  1874. state 4
  1875. expression -> expression TIMES . expression
  1876. expression -> . expression PLUS expression
  1877. expression -> . expression MINUS expression
  1878. expression -> . expression TIMES expression
  1879. expression -> . expression DIVIDE expression
  1880. expression -> . NUMBER
  1881. expression -> . LPAREN expression RPAREN
  1882. NUMBER shift and go to state 3
  1883. LPAREN shift and go to state 2
  1884. state 5
  1885. expression -> expression MINUS . expression
  1886. expression -> . expression PLUS expression
  1887. expression -> . expression MINUS expression
  1888. expression -> . expression TIMES expression
  1889. expression -> . expression DIVIDE expression
  1890. expression -> . NUMBER
  1891. expression -> . LPAREN expression RPAREN
  1892. NUMBER shift and go to state 3
  1893. LPAREN shift and go to state 2
  1894. state 6
  1895. expression -> expression PLUS . expression
  1896. expression -> . expression PLUS expression
  1897. expression -> . expression MINUS expression
  1898. expression -> . expression TIMES expression
  1899. expression -> . expression DIVIDE expression
  1900. expression -> . NUMBER
  1901. expression -> . LPAREN expression RPAREN
  1902. NUMBER shift and go to state 3
  1903. LPAREN shift and go to state 2
  1904. state 7
  1905. expression -> expression DIVIDE . expression
  1906. expression -> . expression PLUS expression
  1907. expression -> . expression MINUS expression
  1908. expression -> . expression TIMES expression
  1909. expression -> . expression DIVIDE expression
  1910. expression -> . NUMBER
  1911. expression -> . LPAREN expression RPAREN
  1912. NUMBER shift and go to state 3
  1913. LPAREN shift and go to state 2
  1914. state 8
  1915. expression -> LPAREN expression . RPAREN
  1916. expression -> expression . PLUS expression
  1917. expression -> expression . MINUS expression
  1918. expression -> expression . TIMES expression
  1919. expression -> expression . DIVIDE expression
  1920. RPAREN shift and go to state 13
  1921. PLUS shift and go to state 6
  1922. MINUS shift and go to state 5
  1923. TIMES shift and go to state 4
  1924. DIVIDE shift and go to state 7
  1925. state 9
  1926. expression -> expression TIMES expression .
  1927. expression -> expression . PLUS expression
  1928. expression -> expression . MINUS expression
  1929. expression -> expression . TIMES expression
  1930. expression -> expression . DIVIDE expression
  1931. $ reduce using rule 3
  1932. PLUS reduce using rule 3
  1933. MINUS reduce using rule 3
  1934. TIMES reduce using rule 3
  1935. DIVIDE reduce using rule 3
  1936. RPAREN reduce using rule 3
  1937. ! PLUS [ shift and go to state 6 ]
  1938. ! MINUS [ shift and go to state 5 ]
  1939. ! TIMES [ shift and go to state 4 ]
  1940. ! DIVIDE [ shift and go to state 7 ]
  1941. state 10
  1942. expression -> expression MINUS expression .
  1943. expression -> expression . PLUS expression
  1944. expression -> expression . MINUS expression
  1945. expression -> expression . TIMES expression
  1946. expression -> expression . DIVIDE expression
  1947. $ reduce using rule 2
  1948. PLUS reduce using rule 2
  1949. MINUS reduce using rule 2
  1950. RPAREN reduce using rule 2
  1951. TIMES shift and go to state 4
  1952. DIVIDE shift and go to state 7
  1953. ! TIMES [ reduce using rule 2 ]
  1954. ! DIVIDE [ reduce using rule 2 ]
  1955. ! PLUS [ shift and go to state 6 ]
  1956. ! MINUS [ shift and go to state 5 ]
  1957. state 11
  1958. expression -> expression PLUS expression .
  1959. expression -> expression . PLUS expression
  1960. expression -> expression . MINUS expression
  1961. expression -> expression . TIMES expression
  1962. expression -> expression . DIVIDE expression
  1963. $ reduce using rule 1
  1964. PLUS reduce using rule 1
  1965. MINUS reduce using rule 1
  1966. RPAREN reduce using rule 1
  1967. TIMES shift and go to state 4
  1968. DIVIDE shift and go to state 7
  1969. ! TIMES [ reduce using rule 1 ]
  1970. ! DIVIDE [ reduce using rule 1 ]
  1971. ! PLUS [ shift and go to state 6 ]
  1972. ! MINUS [ shift and go to state 5 ]
  1973. state 12
  1974. expression -> expression DIVIDE expression .
  1975. expression -> expression . PLUS expression
  1976. expression -> expression . MINUS expression
  1977. expression -> expression . TIMES expression
  1978. expression -> expression . DIVIDE expression
  1979. $ reduce using rule 4
  1980. PLUS reduce using rule 4
  1981. MINUS reduce using rule 4
  1982. TIMES reduce using rule 4
  1983. DIVIDE reduce using rule 4
  1984. RPAREN reduce using rule 4
  1985. ! PLUS [ shift and go to state 6 ]
  1986. ! MINUS [ shift and go to state 5 ]
  1987. ! TIMES [ shift and go to state 4 ]
  1988. ! DIVIDE [ shift and go to state 7 ]
  1989. state 13
  1990. expression -> LPAREN expression RPAREN .
  1991. $ reduce using rule 6
  1992. PLUS reduce using rule 6
  1993. MINUS reduce using rule 6
  1994. TIMES reduce using rule 6
  1995. DIVIDE reduce using rule 6
  1996. RPAREN reduce using rule 6
  1997. </pre>
  1998. </blockquote>
  1999. The different states that appear in this file are a representation of
  2000. every possible sequence of valid input tokens allowed by the grammar.
  2001. When receiving input tokens, the parser is building up a stack and
  2002. looking for matching rules. Each state keeps track of the grammar
  2003. rules that might be in the process of being matched at that point. Within each
  2004. rule, the "." character indicates the current location of the parse
  2005. within that rule. In addition, the actions for each valid input token
  2006. are listed. When a shift/reduce or reduce/reduce conflict arises,
  2007. rules <em>not</em> selected are prefixed with an !. For example:
  2008. <blockquote>
  2009. <pre>
  2010. ! TIMES [ reduce using rule 2 ]
  2011. ! DIVIDE [ reduce using rule 2 ]
  2012. ! PLUS [ shift and go to state 6 ]
  2013. ! MINUS [ shift and go to state 5 ]
  2014. </pre>
  2015. </blockquote>
  2016. By looking at these rules (and with a little practice), you can usually track down the source
  2017. of most parsing conflicts. It should also be stressed that not all shift-reduce conflicts are
  2018. bad. However, the only way to be sure that they are resolved correctly is to look at <tt>parser.out</tt>.
  2019. <H3><a name="ply_nn29"></a>6.8 Syntax Error Handling</H3>
  2020. If you are creating a parser for production use, the handling of
  2021. syntax errors is important. As a general rule, you don't want a
  2022. parser to simply throw up its hands and stop at the first sign of
  2023. trouble. Instead, you want it to report the error, recover if possible, and
  2024. continue parsing so that all of the errors in the input get reported
  2025. to the user at once. This is the standard behavior found in compilers
  2026. for languages such as C, C++, and Java.
  2027. In PLY, when a syntax error occurs during parsing, the error is immediately
  2028. detected (i.e., the parser does not read any more tokens beyond the
  2029. source of the error). However, at this point, the parser enters a
  2030. recovery mode that can be used to try and continue further parsing.
  2031. As a general rule, error recovery in LR parsers is a delicate
  2032. topic that involves ancient rituals and black-magic. The recovery mechanism
  2033. provided by <tt>yacc.py</tt> is comparable to Unix yacc so you may want
  2034. consult a book like O'Reilly's "Lex and Yacc" for some of the finer details.
  2035. <p>
  2036. When a syntax error occurs, <tt>yacc.py</tt> performs the following steps:
  2037. <ol>
  2038. <li>On the first occurrence of an error, the user-defined <tt>p_error()</tt> function
  2039. is called with the offending token as an argument. However, if the syntax error is due to
  2040. reaching the end-of-file, <tt>p_error()</tt> is called with an
  2041. argument of <tt>None</tt>.
  2042. Afterwards, the parser enters
  2043. an "error-recovery" mode in which it will not make future calls to <tt>p_error()</tt> until it
  2044. has successfully shifted at least 3 tokens onto the parsing stack.
  2045. <p>
  2046. <li>If no recovery action is taken in <tt>p_error()</tt>, the offending lookahead token is replaced
  2047. with a special <tt>error</tt> token.
  2048. <p>
  2049. <li>If the offending lookahead token is already set to <tt>error</tt>, the top item of the parsing stack is
  2050. deleted.
  2051. <p>
  2052. <li>If the entire parsing stack is unwound, the parser enters a restart state and attempts to start
  2053. parsing from its initial state.
  2054. <p>
  2055. <li>If a grammar rule accepts <tt>error</tt> as a token, it will be
  2056. shifted onto the parsing stack.
  2057. <p>
  2058. <li>If the top item of the parsing stack is <tt>error</tt>, lookahead tokens will be discarded until the
  2059. parser can successfully shift a new symbol or reduce a rule involving <tt>error</tt>.
  2060. </ol>
  2061. <H4><a name="ply_nn30"></a>6.8.1 Recovery and resynchronization with error rules</H4>
  2062. The most well-behaved approach for handling syntax errors is to write grammar rules that include the <tt>error</tt>
  2063. token. For example, suppose your language had a grammar rule for a print statement like this:
  2064. <blockquote>
  2065. <pre>
  2066. def p_statement_print(p):
  2067. 'statement : PRINT expr SEMI'
  2068. ...
  2069. </pre>
  2070. </blockquote>
  2071. To account for the possibility of a bad expression, you might write an additional grammar rule like this:
  2072. <blockquote>
  2073. <pre>
  2074. def p_statement_print_error(p):
  2075. 'statement : PRINT error SEMI'
  2076. print("Syntax error in print statement. Bad expression")
  2077. </pre>
  2078. </blockquote>
  2079. In this case, the <tt>error</tt> token will match any sequence of
  2080. tokens that might appear up to the first semicolon that is
  2081. encountered. Once the semicolon is reached, the rule will be
  2082. invoked and the <tt>error</tt> token will go away.
  2083. <p>
  2084. This type of recovery is sometimes known as parser resynchronization.
  2085. The <tt>error</tt> token acts as a wildcard for any bad input text and
  2086. the token immediately following <tt>error</tt> acts as a
  2087. synchronization token.
  2088. <p>
  2089. It is important to note that the <tt>error</tt> token usually does not appear as the last token
  2090. on the right in an error rule. For example:
  2091. <blockquote>
  2092. <pre>
  2093. def p_statement_print_error(p):
  2094. 'statement : PRINT error'
  2095. print("Syntax error in print statement. Bad expression")
  2096. </pre>
  2097. </blockquote>
  2098. This is because the first bad token encountered will cause the rule to
  2099. be reduced--which may make it difficult to recover if more bad tokens
  2100. immediately follow.
  2101. <H4><a name="ply_nn31"></a>6.8.2 Panic mode recovery</H4>
  2102. An alternative error recovery scheme is to enter a panic mode recovery in which tokens are
  2103. discarded to a point where the parser might be able to recover in some sensible manner.
  2104. <p>
  2105. Panic mode recovery is implemented entirely in the <tt>p_error()</tt> function. For example, this
  2106. function starts discarding tokens until it reaches a closing '}'. Then, it restarts the
  2107. parser in its initial state.
  2108. <blockquote>
  2109. <pre>
  2110. def p_error(p):
  2111. print("Whoa. You are seriously hosed.")
  2112. if not p:
  2113. print("End of File!")
  2114. return
  2115. # Read ahead looking for a closing '}'
  2116. while True:
  2117. tok = parser.token() # Get the next token
  2118. if not tok or tok.type == 'RBRACE':
  2119. break
  2120. parser.restart()
  2121. </pre>
  2122. </blockquote>
  2123. <p>
  2124. This function simply discards the bad token and tells the parser that the error was ok.
  2125. <blockquote>
  2126. <pre>
  2127. def p_error(p):
  2128. if p:
  2129. print("Syntax error at token", p.type)
  2130. # Just discard the token and tell the parser it's okay.
  2131. parser.errok()
  2132. else:
  2133. print("Syntax error at EOF")
  2134. </pre>
  2135. </blockquote>
  2136. <P>
  2137. More information on these methods is as follows:
  2138. </p>
  2139. <p>
  2140. <ul>
  2141. <li><tt>parser.errok()</tt>. This resets the parser state so it doesn't think it's in error-recovery
  2142. mode. This will prevent an <tt>error</tt> token from being generated and will reset the internal
  2143. error counters so that the next syntax error will call <tt>p_error()</tt> again.
  2144. <p>
  2145. <li><tt>parser.token()</tt>. This returns the next token on the input stream.
  2146. <p>
  2147. <li><tt>parser.restart()</tt>. This discards the entire parsing stack and resets the parser
  2148. to its initial state.
  2149. </ul>
  2150. <p>
  2151. To supply the next lookahead token to the parser, <tt>p_error()</tt> can return a token. This might be
  2152. useful if trying to synchronize on special characters. For example:
  2153. <blockquote>
  2154. <pre>
  2155. def p_error(p):
  2156. # Read ahead looking for a terminating ";"
  2157. while True:
  2158. tok = parser.token() # Get the next token
  2159. if not tok or tok.type == 'SEMI': break
  2160. parser.errok()
  2161. # Return SEMI to the parser as the next lookahead token
  2162. return tok
  2163. </pre>
  2164. </blockquote>
  2165. <p>
  2166. Keep in mind in that the above error handling functions,
  2167. <tt>parser</tt> is an instance of the parser created by
  2168. <tt>yacc()</tt>. You'll need to save this instance someplace in your
  2169. code so that you can refer to it during error handling.
  2170. </p>
  2171. <H4><a name="ply_nn35"></a>6.8.3 Signalling an error from a production</H4>
  2172. If necessary, a production rule can manually force the parser to enter error recovery. This
  2173. is done by raising the <tt>SyntaxError</tt> exception like this:
  2174. <blockquote>
  2175. <pre>
  2176. def p_production(p):
  2177. 'production : some production ...'
  2178. raise SyntaxError
  2179. </pre>
  2180. </blockquote>
  2181. The effect of raising <tt>SyntaxError</tt> is the same as if the last symbol shifted onto the
  2182. parsing stack was actually a syntax error. Thus, when you do this, the last symbol shifted is popped off
  2183. of the parsing stack and the current lookahead token is set to an <tt>error</tt> token. The parser
  2184. then enters error-recovery mode where it tries to reduce rules that can accept <tt>error</tt> tokens.
  2185. The steps that follow from this point are exactly the same as if a syntax error were detected and
  2186. <tt>p_error()</tt> were called.
  2187. <P>
  2188. One important aspect of manually setting an error is that the <tt>p_error()</tt> function will <b>NOT</b> be
  2189. called in this case. If you need to issue an error message, make sure you do it in the production that
  2190. raises <tt>SyntaxError</tt>.
  2191. <P>
  2192. Note: This feature of PLY is meant to mimic the behavior of the YYERROR macro in yacc.
  2193. <H4><a name="ply_nn38"></a>6.8.4 When Do Syntax Errors Get Reported</H4>
  2194. <p>
  2195. In most cases, yacc will handle errors as soon as a bad input token is
  2196. detected on the input. However, be aware that yacc may choose to
  2197. delay error handling until after it has reduced one or more grammar
  2198. rules first. This behavior might be unexpected, but it's related to
  2199. special states in the underlying parsing table known as "defaulted
  2200. states." A defaulted state is parsing condition where the same
  2201. grammar rule will be reduced regardless of what <em>valid</em> token
  2202. comes next on the input. For such states, yacc chooses to go ahead
  2203. and reduce the grammar rule <em>without reading the next input
  2204. token</em>. If the next token is bad, yacc will eventually get around to reading it and
  2205. report a syntax error. It's just a little unusual in that you might
  2206. see some of your grammar rules firing immediately prior to the syntax
  2207. error.
  2208. </p>
  2209. <p>
  2210. Usually, the delayed error reporting with defaulted states is harmless
  2211. (and there are other reasons for wanting PLY to behave in this way).
  2212. However, if you need to turn this behavior off for some reason. You
  2213. can clear the defaulted states table like this:
  2214. </p>
  2215. <blockquote>
  2216. <pre>
  2217. parser = yacc.yacc()
  2218. parser.defaulted_states = {}
  2219. </pre>
  2220. </blockquote>
  2221. <p>
  2222. Disabling defaulted states is not recommended if your grammar makes use
  2223. of embedded actions as described in Section 6.11.</p>
  2224. <H4><a name="ply_nn32"></a>6.8.5 General comments on error handling</H4>
  2225. For normal types of languages, error recovery with error rules and resynchronization characters is probably the most reliable
  2226. technique. This is because you can instrument the grammar to catch errors at selected places where it is relatively easy
  2227. to recover and continue parsing. Panic mode recovery is really only useful in certain specialized applications where you might want
  2228. to discard huge portions of the input text to find a valid restart point.
  2229. <H3><a name="ply_nn33"></a>6.9 Line Number and Position Tracking</H3>
  2230. Position tracking is often a tricky problem when writing compilers.
  2231. By default, PLY tracks the line number and position of all tokens.
  2232. This information is available using the following functions:
  2233. <ul>
  2234. <li><tt>p.lineno(num)</tt>. Return the line number for symbol <em>num</em>
  2235. <li><tt>p.lexpos(num)</tt>. Return the lexing position for symbol <em>num</em>
  2236. </ul>
  2237. For example:
  2238. <blockquote>
  2239. <pre>
  2240. def p_expression(p):
  2241. 'expression : expression PLUS expression'
  2242. line = p.lineno(2) # line number of the PLUS token
  2243. index = p.lexpos(2) # Position of the PLUS token
  2244. </pre>
  2245. </blockquote>
  2246. As an optional feature, <tt>yacc.py</tt> can automatically track line
  2247. numbers and positions for all of the grammar symbols as well.
  2248. However, this extra tracking requires extra processing and can
  2249. significantly slow down parsing. Therefore, it must be enabled by
  2250. passing the
  2251. <tt>tracking=True</tt> option to <tt>yacc.parse()</tt>. For example:
  2252. <blockquote>
  2253. <pre>
  2254. yacc.parse(data,tracking=True)
  2255. </pre>
  2256. </blockquote>
  2257. Once enabled, the <tt>lineno()</tt> and <tt>lexpos()</tt> methods work
  2258. for all grammar symbols. In addition, two additional methods can be
  2259. used:
  2260. <ul>
  2261. <li><tt>p.linespan(num)</tt>. Return a tuple (startline,endline) with the starting and ending line number for symbol <em>num</em>.
  2262. <li><tt>p.lexspan(num)</tt>. Return a tuple (start,end) with the starting and ending positions for symbol <em>num</em>.
  2263. </ul>
  2264. For example:
  2265. <blockquote>
  2266. <pre>
  2267. def p_expression(p):
  2268. 'expression : expression PLUS expression'
  2269. p.lineno(1) # Line number of the left expression
  2270. p.lineno(2) # line number of the PLUS operator
  2271. p.lineno(3) # line number of the right expression
  2272. ...
  2273. start,end = p.linespan(3) # Start,end lines of the right expression
  2274. starti,endi = p.lexspan(3) # Start,end positions of right expression
  2275. </pre>
  2276. </blockquote>
  2277. Note: The <tt>lexspan()</tt> function only returns the range of values up to the start of the last grammar symbol.
  2278. <p>
  2279. Although it may be convenient for PLY to track position information on
  2280. all grammar symbols, this is often unnecessary. For example, if you
  2281. are merely using line number information in an error message, you can
  2282. often just key off of a specific token in the grammar rule. For
  2283. example:
  2284. <blockquote>
  2285. <pre>
  2286. def p_bad_func(p):
  2287. 'funccall : fname LPAREN error RPAREN'
  2288. # Line number reported from LPAREN token
  2289. print("Bad function call at line", p.lineno(2))
  2290. </pre>
  2291. </blockquote>
  2292. <p>
  2293. Similarly, you may get better parsing performance if you only
  2294. selectively propagate line number information where it's needed using
  2295. the <tt>p.set_lineno()</tt> method. For example:
  2296. <blockquote>
  2297. <pre>
  2298. def p_fname(p):
  2299. 'fname : ID'
  2300. p[0] = p[1]
  2301. p.set_lineno(0,p.lineno(1))
  2302. </pre>
  2303. </blockquote>
  2304. PLY doesn't retain line number information from rules that have already been
  2305. parsed. If you are building an abstract syntax tree and need to have line numbers,
  2306. you should make sure that the line numbers appear in the tree itself.
  2307. <H3><a name="ply_nn34"></a>6.10 AST Construction</H3>
  2308. <tt>yacc.py</tt> provides no special functions for constructing an
  2309. abstract syntax tree. However, such construction is easy enough to do
  2310. on your own.
  2311. <p>A minimal way to construct a tree is to simply create and
  2312. propagate a tuple or list in each grammar rule function. There
  2313. are many possible ways to do this, but one example would be something
  2314. like this:
  2315. <blockquote>
  2316. <pre>
  2317. def p_expression_binop(p):
  2318. '''expression : expression PLUS expression
  2319. | expression MINUS expression
  2320. | expression TIMES expression
  2321. | expression DIVIDE expression'''
  2322. p[0] = ('binary-expression',p[2],p[1],p[3])
  2323. def p_expression_group(p):
  2324. 'expression : LPAREN expression RPAREN'
  2325. p[0] = ('group-expression',p[2])
  2326. def p_expression_number(p):
  2327. 'expression : NUMBER'
  2328. p[0] = ('number-expression',p[1])
  2329. </pre>
  2330. </blockquote>
  2331. <p>
  2332. Another approach is to create a set of data structure for different
  2333. kinds of abstract syntax tree nodes and assign nodes to <tt>p[0]</tt>
  2334. in each rule. For example:
  2335. <blockquote>
  2336. <pre>
  2337. class Expr: pass
  2338. class BinOp(Expr):
  2339. def __init__(self,left,op,right):
  2340. self.type = "binop"
  2341. self.left = left
  2342. self.right = right
  2343. self.op = op
  2344. class Number(Expr):
  2345. def __init__(self,value):
  2346. self.type = "number"
  2347. self.value = value
  2348. def p_expression_binop(p):
  2349. '''expression : expression PLUS expression
  2350. | expression MINUS expression
  2351. | expression TIMES expression
  2352. | expression DIVIDE expression'''
  2353. p[0] = BinOp(p[1],p[2],p[3])
  2354. def p_expression_group(p):
  2355. 'expression : LPAREN expression RPAREN'
  2356. p[0] = p[2]
  2357. def p_expression_number(p):
  2358. 'expression : NUMBER'
  2359. p[0] = Number(p[1])
  2360. </pre>
  2361. </blockquote>
  2362. The advantage to this approach is that it may make it easier to attach more complicated
  2363. semantics, type checking, code generation, and other features to the node classes.
  2364. <p>
  2365. To simplify tree traversal, it may make sense to pick a very generic
  2366. tree structure for your parse tree nodes. For example:
  2367. <blockquote>
  2368. <pre>
  2369. class Node:
  2370. def __init__(self,type,children=None,leaf=None):
  2371. self.type = type
  2372. if children:
  2373. self.children = children
  2374. else:
  2375. self.children = [ ]
  2376. self.leaf = leaf
  2377. def p_expression_binop(p):
  2378. '''expression : expression PLUS expression
  2379. | expression MINUS expression
  2380. | expression TIMES expression
  2381. | expression DIVIDE expression'''
  2382. p[0] = Node("binop", [p[1],p[3]], p[2])
  2383. </pre>
  2384. </blockquote>
  2385. <H3><a name="ply_nn35b"></a>6.11 Embedded Actions</H3>
  2386. The parsing technique used by yacc only allows actions to be executed at the end of a rule. For example,
  2387. suppose you have a rule like this:
  2388. <blockquote>
  2389. <pre>
  2390. def p_foo(p):
  2391. "foo : A B C D"
  2392. print("Parsed a foo", p[1],p[2],p[3],p[4])
  2393. </pre>
  2394. </blockquote>
  2395. <p>
  2396. In this case, the supplied action code only executes after all of the
  2397. symbols <tt>A</tt>, <tt>B</tt>, <tt>C</tt>, and <tt>D</tt> have been
  2398. parsed. Sometimes, however, it is useful to execute small code
  2399. fragments during intermediate stages of parsing. For example, suppose
  2400. you wanted to perform some action immediately after <tt>A</tt> has
  2401. been parsed. To do this, write an empty rule like this:
  2402. <blockquote>
  2403. <pre>
  2404. def p_foo(p):
  2405. "foo : A seen_A B C D"
  2406. print("Parsed a foo", p[1],p[3],p[4],p[5])
  2407. print("seen_A returned", p[2])
  2408. def p_seen_A(p):
  2409. "seen_A :"
  2410. print("Saw an A = ", p[-1]) # Access grammar symbol to left
  2411. p[0] = some_value # Assign value to seen_A
  2412. </pre>
  2413. </blockquote>
  2414. <p>
  2415. In this example, the empty <tt>seen_A</tt> rule executes immediately
  2416. after <tt>A</tt> is shifted onto the parsing stack. Within this
  2417. rule, <tt>p[-1]</tt> refers to the symbol on the stack that appears
  2418. immediately to the left of the <tt>seen_A</tt> symbol. In this case,
  2419. it would be the value of <tt>A</tt> in the <tt>foo</tt> rule
  2420. immediately above. Like other rules, a value can be returned from an
  2421. embedded action by simply assigning it to <tt>p[0]</tt>
  2422. <p>
  2423. The use of embedded actions can sometimes introduce extra shift/reduce conflicts. For example,
  2424. this grammar has no conflicts:
  2425. <blockquote>
  2426. <pre>
  2427. def p_foo(p):
  2428. """foo : abcd
  2429. | abcx"""
  2430. def p_abcd(p):
  2431. "abcd : A B C D"
  2432. def p_abcx(p):
  2433. "abcx : A B C X"
  2434. </pre>
  2435. </blockquote>
  2436. However, if you insert an embedded action into one of the rules like this,
  2437. <blockquote>
  2438. <pre>
  2439. def p_foo(p):
  2440. """foo : abcd
  2441. | abcx"""
  2442. def p_abcd(p):
  2443. "abcd : A B C D"
  2444. def p_abcx(p):
  2445. "abcx : A B seen_AB C X"
  2446. def p_seen_AB(p):
  2447. "seen_AB :"
  2448. </pre>
  2449. </blockquote>
  2450. an extra shift-reduce conflict will be introduced. This conflict is
  2451. caused by the fact that the same symbol <tt>C</tt> appears next in
  2452. both the <tt>abcd</tt> and <tt>abcx</tt> rules. The parser can either
  2453. shift the symbol (<tt>abcd</tt> rule) or reduce the empty
  2454. rule <tt>seen_AB</tt> (<tt>abcx</tt> rule).
  2455. <p>
  2456. A common use of embedded rules is to control other aspects of parsing
  2457. such as scoping of local variables. For example, if you were parsing C code, you might
  2458. write code like this:
  2459. <blockquote>
  2460. <pre>
  2461. def p_statements_block(p):
  2462. "statements: LBRACE new_scope statements RBRACE"""
  2463. # Action code
  2464. ...
  2465. pop_scope() # Return to previous scope
  2466. def p_new_scope(p):
  2467. "new_scope :"
  2468. # Create a new scope for local variables
  2469. s = new_scope()
  2470. push_scope(s)
  2471. ...
  2472. </pre>
  2473. </blockquote>
  2474. In this case, the embedded action <tt>new_scope</tt> executes
  2475. immediately after a <tt>LBRACE</tt> (<tt>{</tt>) symbol is parsed.
  2476. This might adjust internal symbol tables and other aspects of the
  2477. parser. Upon completion of the rule <tt>statements_block</tt>, code
  2478. might undo the operations performed in the embedded action
  2479. (e.g., <tt>pop_scope()</tt>).
  2480. <H3><a name="ply_nn36"></a>6.12 Miscellaneous Yacc Notes</H3>
  2481. <ul>
  2482. <li>By default, <tt>yacc.py</tt> relies on <tt>lex.py</tt> for tokenizing. However, an alternative tokenizer
  2483. can be supplied as follows:
  2484. <blockquote>
  2485. <pre>
  2486. parser = yacc.parse(lexer=x)
  2487. </pre>
  2488. </blockquote>
  2489. in this case, <tt>x</tt> must be a Lexer object that minimally has a <tt>x.token()</tt> method for retrieving the next
  2490. token. If an input string is given to <tt>yacc.parse()</tt>, the lexer must also have an <tt>x.input()</tt> method.
  2491. <p>
  2492. <li>By default, the yacc generates tables in debugging mode (which produces the parser.out file and other output).
  2493. To disable this, use
  2494. <blockquote>
  2495. <pre>
  2496. parser = yacc.yacc(debug=False)
  2497. </pre>
  2498. </blockquote>
  2499. <p>
  2500. <li>To change the name of the <tt>parsetab.py</tt> file, use:
  2501. <blockquote>
  2502. <pre>
  2503. parser = yacc.yacc(tabmodule="foo")
  2504. </pre>
  2505. </blockquote>
  2506. <P>
  2507. Normally, the <tt>parsetab.py</tt> file is placed into the same directory as
  2508. the module where the parser is defined. If you want it to go somewhere else, you can
  2509. given an absolute package name for <tt>tabmodule</tt> instead. In that case, the
  2510. tables will be written there.
  2511. </p>
  2512. <p>
  2513. <li>To change the directory in which the <tt>parsetab.py</tt> file (and other output files) are written, use:
  2514. <blockquote>
  2515. <pre>
  2516. parser = yacc.yacc(tabmodule="foo",outputdir="somedirectory")
  2517. </pre>
  2518. </blockquote>
  2519. <p>
  2520. Note: Be aware that unless the directory specified is also on Python's path (<tt>sys.path</tt>), subsequent
  2521. imports of the table file will fail. As a general rule, it's better to specify a destination using the
  2522. <tt>tabmodule</tt> argument instead of directly specifying a directory using the <tt>outputdir</tt> argument.
  2523. </p>
  2524. <p>
  2525. <li>To prevent yacc from generating any kind of parser table file, use:
  2526. <blockquote>
  2527. <pre>
  2528. parser = yacc.yacc(write_tables=False)
  2529. </pre>
  2530. </blockquote>
  2531. Note: If you disable table generation, yacc() will regenerate the parsing tables
  2532. each time it runs (which may take awhile depending on how large your grammar is).
  2533. <P>
  2534. <li>To print copious amounts of debugging during parsing, use:
  2535. <blockquote>
  2536. <pre>
  2537. parser.parse(input_text, debug=True)
  2538. </pre>
  2539. </blockquote>
  2540. <p>
  2541. <li>Since the generation of the LALR tables is relatively expensive, previously generated tables are
  2542. cached and reused if possible. The decision to regenerate the tables is determined by taking an MD5
  2543. checksum of all grammar rules and precedence rules. Only in the event of a mismatch are the tables regenerated.
  2544. <p>
  2545. It should be noted that table generation is reasonably efficient, even for grammars that involve around a 100 rules
  2546. and several hundred states. </li>
  2547. <p>
  2548. <li>Since LR parsing is driven by tables, the performance of the parser is largely independent of the
  2549. size of the grammar. The biggest bottlenecks will be the lexer and the complexity of the code in your grammar rules.
  2550. </li>
  2551. </p>
  2552. <p>
  2553. <li><tt>yacc()</tt> also allows parsers to be defined as classes and as closures (see the section on alternative specification of
  2554. lexers). However, be aware that only one parser may be defined in a single module (source file). There are various
  2555. error checks and validation steps that may issue confusing error messages if you try to define multiple parsers
  2556. in the same source file.
  2557. </li>
  2558. </p>
  2559. <p>
  2560. <li>Decorators of production rules have to update the wrapped function's line number. <tt>wrapper.co_firstlineno = func.__code__.co_firstlineno</tt>:
  2561. <blockquote>
  2562. <pre>
  2563. from functools import wraps
  2564. from nodes import Collection
  2565. def strict(*types):
  2566. def decorate(func):
  2567. @wraps(func)
  2568. def wrapper(p):
  2569. func(p)
  2570. if not isinstance(p[0], types):
  2571. raise TypeError
  2572. wrapper.co_firstlineno = func.__code__.co_firstlineno
  2573. return wrapper
  2574. return decorate
  2575. @strict(Collection)
  2576. def p_collection(p):
  2577. """
  2578. collection : sequence
  2579. | map
  2580. """
  2581. p[0] = p[1]
  2582. </pre>
  2583. </blockquote>
  2584. </li>
  2585. </p>
  2586. </ul>
  2587. </p>
  2588. <H2><a name="ply_nn37"></a>7. Multiple Parsers and Lexers</H2>
  2589. In advanced parsing applications, you may want to have multiple
  2590. parsers and lexers.
  2591. <p>
  2592. As a general rules this isn't a problem. However, to make it work,
  2593. you need to carefully make sure everything gets hooked up correctly.
  2594. First, make sure you save the objects returned by <tt>lex()</tt> and
  2595. <tt>yacc()</tt>. For example:
  2596. <blockquote>
  2597. <pre>
  2598. lexer = lex.lex() # Return lexer object
  2599. parser = yacc.yacc() # Return parser object
  2600. </pre>
  2601. </blockquote>
  2602. Next, when parsing, make sure you give the <tt>parse()</tt> function a reference to the lexer it
  2603. should be using. For example:
  2604. <blockquote>
  2605. <pre>
  2606. parser.parse(text,lexer=lexer)
  2607. </pre>
  2608. </blockquote>
  2609. If you forget to do this, the parser will use the last lexer
  2610. created--which is not always what you want.
  2611. <p>
  2612. Within lexer and parser rule functions, these objects are also
  2613. available. In the lexer, the "lexer" attribute of a token refers to
  2614. the lexer object that triggered the rule. For example:
  2615. <blockquote>
  2616. <pre>
  2617. def t_NUMBER(t):
  2618. r'\d+'
  2619. ...
  2620. print(t.lexer) # Show lexer object
  2621. </pre>
  2622. </blockquote>
  2623. In the parser, the "lexer" and "parser" attributes refer to the lexer
  2624. and parser objects respectively.
  2625. <blockquote>
  2626. <pre>
  2627. def p_expr_plus(p):
  2628. 'expr : expr PLUS expr'
  2629. ...
  2630. print(p.parser) # Show parser object
  2631. print(p.lexer) # Show lexer object
  2632. </pre>
  2633. </blockquote>
  2634. If necessary, arbitrary attributes can be attached to the lexer or parser object.
  2635. For example, if you wanted to have different parsing modes, you could attach a mode
  2636. attribute to the parser object and look at it later.
  2637. <H2><a name="ply_nn38b"></a>8. Using Python's Optimized Mode</H2>
  2638. Because PLY uses information from doc-strings, parsing and lexing
  2639. information must be gathered while running the Python interpreter in
  2640. normal mode (i.e., not with the -O or -OO options). However, if you
  2641. specify optimized mode like this:
  2642. <blockquote>
  2643. <pre>
  2644. lex.lex(optimize=1)
  2645. yacc.yacc(optimize=1)
  2646. </pre>
  2647. </blockquote>
  2648. then PLY can later be used when Python runs in optimized mode. To make this work,
  2649. make sure you first run Python in normal mode. Once the lexing and parsing tables
  2650. have been generated the first time, run Python in optimized mode. PLY will use
  2651. the tables without the need for doc strings.
  2652. <p>
  2653. Beware: running PLY in optimized mode disables a lot of error
  2654. checking. You should only do this when your project has stabilized
  2655. and you don't need to do any debugging. One of the purposes of
  2656. optimized mode is to substantially decrease the startup time of
  2657. your compiler (by assuming that everything is already properly
  2658. specified and works).
  2659. <H2><a name="ply_nn44"></a>9. Advanced Debugging</H2>
  2660. <p>
  2661. Debugging a compiler is typically not an easy task. PLY provides some
  2662. advanced diagostic capabilities through the use of Python's
  2663. <tt>logging</tt> module. The next two sections describe this:
  2664. <H3><a name="ply_nn45"></a>9.1 Debugging the lex() and yacc() commands</H3>
  2665. <p>
  2666. Both the <tt>lex()</tt> and <tt>yacc()</tt> commands have a debugging
  2667. mode that can be enabled using the <tt>debug</tt> flag. For example:
  2668. <blockquote>
  2669. <pre>
  2670. lex.lex(debug=True)
  2671. yacc.yacc(debug=True)
  2672. </pre>
  2673. </blockquote>
  2674. Normally, the output produced by debugging is routed to either
  2675. standard error or, in the case of <tt>yacc()</tt>, to a file
  2676. <tt>parser.out</tt>. This output can be more carefully controlled
  2677. by supplying a logging object. Here is an example that adds
  2678. information about where different debugging messages are coming from:
  2679. <blockquote>
  2680. <pre>
  2681. # Set up a logging object
  2682. import logging
  2683. logging.basicConfig(
  2684. level = logging.DEBUG,
  2685. filename = "parselog.txt",
  2686. filemode = "w",
  2687. format = "%(filename)10s:%(lineno)4d:%(message)s"
  2688. )
  2689. log = logging.getLogger()
  2690. lex.lex(debug=True,debuglog=log)
  2691. yacc.yacc(debug=True,debuglog=log)
  2692. </pre>
  2693. </blockquote>
  2694. If you supply a custom logger, the amount of debugging
  2695. information produced can be controlled by setting the logging level.
  2696. Typically, debugging messages are either issued at the <tt>DEBUG</tt>,
  2697. <tt>INFO</tt>, or <tt>WARNING</tt> levels.
  2698. <p>
  2699. PLY's error messages and warnings are also produced using the logging
  2700. interface. This can be controlled by passing a logging object
  2701. using the <tt>errorlog</tt> parameter.
  2702. <blockquote>
  2703. <pre>
  2704. lex.lex(errorlog=log)
  2705. yacc.yacc(errorlog=log)
  2706. </pre>
  2707. </blockquote>
  2708. If you want to completely silence warnings, you can either pass in a
  2709. logging object with an appropriate filter level or use the <tt>NullLogger</tt>
  2710. object defined in either <tt>lex</tt> or <tt>yacc</tt>. For example:
  2711. <blockquote>
  2712. <pre>
  2713. yacc.yacc(errorlog=yacc.NullLogger())
  2714. </pre>
  2715. </blockquote>
  2716. <H3><a name="ply_nn46"></a>9.2 Run-time Debugging</H3>
  2717. <p>
  2718. To enable run-time debugging of a parser, use the <tt>debug</tt> option to parse. This
  2719. option can either be an integer (which simply turns debugging on or off) or an instance
  2720. of a logger object. For example:
  2721. <blockquote>
  2722. <pre>
  2723. log = logging.getLogger()
  2724. parser.parse(input,debug=log)
  2725. </pre>
  2726. </blockquote>
  2727. If a logging object is passed, you can use its filtering level to control how much
  2728. output gets generated. The <tt>INFO</tt> level is used to produce information
  2729. about rule reductions. The <tt>DEBUG</tt> level will show information about the
  2730. parsing stack, token shifts, and other details. The <tt>ERROR</tt> level shows information
  2731. related to parsing errors.
  2732. <p>
  2733. For very complicated problems, you should pass in a logging object that
  2734. redirects to a file where you can more easily inspect the output after
  2735. execution.
  2736. <H2><a name="ply_nn49"></a>10. Packaging Advice</H2>
  2737. <p>
  2738. If you are distributing a package that makes use of PLY, you should
  2739. spend a few moments thinking about how you want to handle the files
  2740. that are automatically generated. For example, the <tt>parsetab.py</tt>
  2741. file generated by the <tt>yacc()</tt> function.</p>
  2742. <p>
  2743. Starting in PLY-3.6, the table files are created in the same directory
  2744. as the file where a parser is defined. This means that the
  2745. <tt>parsetab.py</tt> file will live side-by-side with your parser
  2746. specification. In terms of packaging, this is probably the easiest and
  2747. most sane approach to manage. You don't need to give <tt>yacc()</tt>
  2748. any extra arguments and it should just "work."</p>
  2749. <p>
  2750. One concern is the management of the <tt>parsetab.py</tt> file itself.
  2751. For example, should you have this file checked into version control (e.g., GitHub),
  2752. should it be included in a package distribution as a normal file, or should you
  2753. just let PLY generate it automatically for the user when they install your package?
  2754. </p>
  2755. <p>
  2756. As of PLY-3.6, the <tt>parsetab.py</tt> file should be compatible across all versions
  2757. of Python including Python 2 and 3. Thus, a table file generated in Python 2 should
  2758. work fine if it's used on Python 3. Because of this, it should be relatively harmless
  2759. to distribute the <tt>parsetab.py</tt> file yourself if you need to. However, be aware
  2760. that older/newer versions of PLY may try to regenerate the file if there are future
  2761. enhancements or changes to its format.
  2762. </p>
  2763. <p>
  2764. To make the generation of table files easier for the purposes of installation, you might
  2765. way to make your parser files executable using the <tt>-m</tt> option or similar. For
  2766. example:
  2767. </p>
  2768. <blockquote>
  2769. <pre>
  2770. # calc.py
  2771. ...
  2772. ...
  2773. def make_parser():
  2774. parser = yacc.yacc()
  2775. return parser
  2776. if __name__ == '__main__':
  2777. make_parser()
  2778. </pre>
  2779. </blockquote>
  2780. <p>
  2781. You can then use a command such as <tt>python -m calc.py</tt> to generate the tables. Alternatively,
  2782. a <tt>setup.py</tt> script, can import the module and use <tt>make_parser()</tt> to create the
  2783. parsing tables.
  2784. </p>
  2785. <p>
  2786. If you're willing to sacrifice a little startup time, you can also instruct PLY to never write the
  2787. tables using <tt>yacc.yacc(write_tables=False, debug=False)</tt>. In this mode, PLY will regenerate
  2788. the parsing tables from scratch each time. For a small grammar, you probably won't notice. For a
  2789. large grammar, you should probably reconsider--the parsing tables are meant to dramatically speed up this process.
  2790. </p>
  2791. <p>
  2792. During operation, is is normal for PLY to produce diagnostic error
  2793. messages (usually printed to standard error). These are generated
  2794. entirely using the <tt>logging</tt> module. If you want to redirect
  2795. these messages or silence them, you can provide your own logging
  2796. object to <tt>yacc()</tt>. For example:
  2797. </p>
  2798. <blockquote>
  2799. <pre>
  2800. import logging
  2801. log = logging.getLogger('ply')
  2802. ...
  2803. parser = yacc.yacc(errorlog=log)
  2804. </pre>
  2805. </blockquote>
  2806. <H2><a name="ply_nn39"></a>11. Where to go from here?</H2>
  2807. The <tt>examples</tt> directory of the PLY distribution contains several simple examples. Please consult a
  2808. compilers textbook for the theory and underlying implementation details or LR parsing.
  2809. </body>
  2810. </html>