PageRenderTime 80ms CodeModel.GetById 26ms 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

Large files files are truncated, but you can click here to view the full file

  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 -

Large files files are truncated, but you can click here to view the full file