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