PageRenderTime 94ms CodeModel.GetById 38ms RepoModel.GetById 0ms app.codeStats 1ms

/ext/ply/doc/ply.html

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