Commits

Jason R. Coombs  committed 2cbf247

Adding changes from 2.1 as released

  • Participants
  • Parent commits df60658

Comments (0)

Files changed (124)

-September 8, 2006
+October 2, 2006
 
-                  Announcing :  PLY-2.0 (Python Lex-Yacc)
+                  Announcing :  PLY-2.1 (Python Lex-Yacc)
 
                         http://www.dabeaz.com/ply
 
 I'm pleased to announce a significant new update to PLY---a 100% Python
-implementation of the common parsing tools lex and yacc.  PLY-2.0 features
-a completely new implementation of LALR(1) parsing that provides a
-significant speedup when generating the underlying parsing tables. This
-new implementation also (hopefully) fixes all outstanding bugs in LALR(1)
-parsing that were reported for previous versions of PLY-1.x.  
+implementation of the common parsing tools lex and yacc.  PLY-2.1 builds
+upon the reimplementation of LALR(1) parsing that appeared in PLY-2.0 and
+adds a number of significant new features.  These include:
 
-Here are a few PLY highlights:
+- Elimination of internal limitations due to the use of Python's re
+  module.
 
-  -  PLY is closely modeled after traditional lex/yacc.  If you know how 
-     to use these or similar tools in other languages, you will find
-     PLY to be comparable.
+- Better support for inherited attributes and embedded parsing 
+  actions.
 
-  -  PLY provides very extensive error reporting and diagnostic
-     information to assist in parser construction.  The original
-     implementation was developed for instructional purposes.  As
-     a result, the system tries to identify the most common types
-     of errors made by novice users.
+- Character literals (e.g., '+', '-') can now be included in
+  grammar specifications.
 
-  -  PLY provides full support for empty productions, error recovery,
-     precedence rules, and moderately ambiguous grammars.
+- Improved packaging.  PLY is now a proper Python package.
 
-  -  Parsing is based on LR-parsing which is fast, memory efficient,
-     better suited to large grammars, and which has a number of nice
-     properties when dealing with syntax errors and other parsing 
-     problems. Currently, PLY can build its parsing tables using 
-     either SLR or LALR(1) algorithms. 
+- Improved support for line number and column tracking.
 
-  -  PLY can be used to build parsers for large programming languages.
-     Although it is not ultra-fast due to its Python implementation,
-     PLY can be used to parse grammars consisting of several hundred
-     rules (as might be found for a language like C).  The lexer and LR
-     parser are also reasonably efficient when parsing normal
-     sized programs.
+- Added diagnostics.
+
+- New examples including a program to convert tradition yacc/bison
+  specifications to PLY.
+
+- A variety of minor enhancements and bug fixes.
+
+If you are new to PLY, here are a few highlights:
+
+-  PLY is closely modeled after traditional lex/yacc.  If you know how 
+   to use these or similar tools in other languages, you will find
+   PLY to be comparable.
+
+-  PLY provides very extensive error reporting and diagnostic
+   information to assist in parser construction.  The original
+   implementation was developed for instructional purposes.  As
+   a result, the system tries to identify the most common types
+   of errors made by novice users.
+
+-  PLY provides full support for empty productions, error recovery,
+   precedence rules, and ambiguous grammars.
+
+-  Parsing is based on LR-parsing which is fast, memory efficient,
+   better suited to large grammars, and which has a number of nice
+   properties when dealing with syntax errors and other parsing 
+   problems. Currently, PLY can build its parsing tables using 
+   either SLR or LALR(1) algorithms. 
+
+-  PLY can be used to build parsers for large programming languages.
+   Although it is not ultra-fast due to its Python implementation,
+   PLY can be used to parse grammars consisting of several hundred
+   rules (as might be found for a language like C).  The lexer and LR
+   parser are also reasonably efficient when parsing normal
+   sized programs.
 
 More information about PLY can be obtained on the PLY webpage at:
 
+Version 2.1
+------------------------------
+10/02/06: beazley
+          The last Lexer object built by lex() can be found in lex.lexer.
+          The last Parser object built  by yacc() can be found in yacc.parser.
+
+10/02/06: beazley
+          New example added:  examples/yply
+
+          This example uses PLY to convert Unix-yacc specification files to
+          PLY programs with the same grammar.   This may be useful if you
+          want to convert a grammar from bison/yacc to use with PLY.
+    
+10/02/06: beazley
+          Added support for a start symbol to be specified in the yacc
+          input file itself.  Just do this:
+
+               start = 'name'
+
+          where 'name' matches some grammar rule.  For example:
+
+               def p_name(p):
+                   'name : A B C'
+                   ...
+
+          This mirrors the functionality of the yacc %start specifier.
+
+09/30/06: beazley
+          Some new examples added.:
+
+          examples/GardenSnake : A simple indentation based language similar
+                                 to Python.  Shows how you might handle 
+                                 whitespace.  Contributed by Andrew Dalke.
+
+          examples/BASIC       : An implementation of 1964 Dartmouth BASIC.
+                                 Contributed by Dave against his better
+                                 judgement.
+
+09/28/06: beazley
+          Minor patch to allow named groups to be used in lex regular
+          expression rules.  For example:
+
+              t_QSTRING = r'''(?P<quote>['"]).*?(?P=quote)'''
+
+          Patch submitted by Adam Ring.
+ 
+09/28/06: beazley
+          LALR(1) is now the default parsing method.   To use SLR, use
+          yacc.yacc(method="SLR").  Note: there is no performance impact
+          on parsing when using LALR(1) instead of SLR. However, constructing
+          the parsing tables will take a little longer.
+
+09/26/06: beazley
+          Change to line number tracking.  To modify line numbers, modify
+          the line number of the lexer itself.  For example:
+
+          def t_NEWLINE(t):
+              r'\n'
+              t.lexer.lineno += 1
+
+          This modification is both cleanup and a performance optimization.
+          In past versions, lex was monitoring every token for changes in
+          the line number.  This extra processing is unnecessary for a vast
+          majority of tokens. Thus, this new approach cleans it up a bit.
+
+          *** POTENTIAL INCOMPATIBILITY ***
+          You will need to change code in your lexer that updates the line
+          number. For example, "t.lineno += 1" becomes "t.lexer.lineno += 1"
+         
+09/26/06: beazley
+          Added the lexing position to tokens as an attribute lexpos. This
+          is the raw index into the input text at which a token appears.
+          This information can be used to compute column numbers and other
+          details (e.g., scan backwards from lexpos to the first newline
+          to get a column position).
+
+09/25/06: beazley
+          Changed the name of the __copy__() method on the Lexer class
+          to clone().  This is used to clone a Lexer object (e.g., if
+          you're running different lexers at the same time).
+
+09/21/06: beazley
+          Limitations related to the use of the re module have been eliminated.
+          Several users reported problems with regular expressions exceeding
+          more than 100 named groups. To solve this, lex.py is now capable
+          of automatically splitting its master regular regular expression into
+          smaller expressions as needed.   This should, in theory, make it
+          possible to specify an arbitrarily large number of tokens.
+
+09/21/06: beazley
+          Improved error checking in lex.py.  Rules that match the empty string
+          are now rejected (otherwise they cause the lexer to enter an infinite
+          loop).  An extra check for rules containing '#' has also been added.
+          Since lex compiles regular expressions in verbose mode, '#' is interpreted
+          as a regex comment, it is critical to use '\#' instead.  
+
+09/18/06: beazley
+          Added a @TOKEN decorator function to lex.py that can be used to 
+          define token rules where the documentation string might be computed
+          in some way.
+          
+          digit            = r'([0-9])'
+          nondigit         = r'([_A-Za-z])'
+          identifier       = r'(' + nondigit + r'(' + digit + r'|' + nondigit + r')*)'        
+
+          from ply.lex import TOKEN
+
+          @TOKEN(identifier)
+          def t_ID(t):
+               # Do whatever
+
+          The @TOKEN decorator merely sets the documentation string of the
+          associated token function as needed for lex to work.  
+
+          Note: An alternative solution is the following:
+
+          def t_ID(t):
+              # Do whatever
+   
+          t_ID.__doc__ = identifier
+
+          Note: Decorators require the use of Python 2.4 or later.  If compatibility
+          with old versions is needed, use the latter solution.
+
+          The need for this feature was suggested by Cem Karan.
+
+09/14/06: beazley
+          Support for single-character literal tokens has been added to yacc.
+          These literals must be enclosed in quotes.  For example:
+
+          def p_expr(p):
+               "expr : expr '+' expr"
+               ...
+
+          def p_expr(p):
+               'expr : expr "-" expr'
+               ...
+
+          In addition to this, it is necessary to tell the lexer module about
+          literal characters.   This is done by defining the variable 'literals'
+          as a list of characters.  This should  be defined in the module that
+          invokes the lex.lex() function.  For example:
+
+             literals = ['+','-','*','/','(',')','=']
+ 
+          or simply
+
+             literals = '+=*/()='
+
+          It is important to note that literals can only be a single character.
+          When the lexer fails to match a token using its normal regular expression
+          rules, it will check the current character against the literal list.
+          If found, it will be returned with a token type set to match the literal
+          character.  Otherwise, an illegal character will be signalled.
+
+
+09/14/06: beazley
+          Modified PLY to install itself as a proper Python package called 'ply'.
+          This will make it a little more friendly to other modules.  This
+          changes the usage of PLY only slightly.  Just do this to import the
+          modules
+
+                import ply.lex as lex
+                import ply.yacc as yacc
+
+          Alternatively, you can do this:
+
+                from ply import *
+
+          Which imports both the lex and yacc modules.
+          Change suggested by Lee June.
+
+09/13/06: beazley
+          Changed the handling of negative indices when used in production rules.
+          A negative production index now accesses already parsed symbols on the
+          parsing stack.  For example, 
+
+              def p_foo(p):
+                   "foo: A B C D"
+                   print p[1]       # Value of 'A' symbol
+                   print p[2]       # Value of 'B' symbol
+                   print p[-1]      # Value of whatever symbol appears before A
+                                    # on the parsing stack.
+
+                   p[0] = some_val  # Sets the value of the 'foo' grammer symbol
+                                    
+          This behavior makes it easier to work with embedded actions within the
+          parsing rules. For example, in C-yacc, it is possible to write code like
+          this:
+
+               bar:   A { printf("seen an A = %d\n", $1); } B { do_stuff; }
+
+          In this example, the printf() code executes immediately after A has been
+          parsed.  Within the embedded action code, $1 refers to the A symbol on
+          the stack.
+
+          To perform this equivalent action in PLY, you need to write a pair
+          of rules like this:
+
+               def p_bar(p):
+                     "bar : A seen_A B"
+                     do_stuff
+
+               def p_seen_A(p):
+                     "seen_A :"
+                     print "seen an A =", p[-1]
+
+          The second rule "seen_A" is merely a empty production which should be
+          reduced as soon as A is parsed in the "bar" rule above.  The use 
+          of the negative index p[-1] is used to access whatever symbol appeared
+          before the seen_A symbol.
+
+          This feature also makes it possible to support inherited attributes.
+          For example:
+
+               def p_decl(p):
+                     "decl : scope name"
+
+               def p_scope(p):
+                     """scope : GLOBAL
+                              | LOCAL"""
+                   p[0] = p[1]
+
+               def p_name(p):
+                     "name : ID"
+                     if p[-1] == "GLOBAL":
+                          # ...
+                     else if p[-1] == "LOCAL":
+                          #...
+
+          In this case, the name rule is inheriting an attribute from the
+          scope declaration that precedes it.
+       
+          *** POTENTIAL INCOMPATIBILITY ***
+          If you are currently using negative indices within existing grammar rules,
+          your code will break.  This should be extremely rare if non-existent in
+          most cases.  The argument to various grammar rules is not usually not
+          processed in the same way as a list of items.
+          
 Version 2.0
 ------------------------------
 09/07/06: beazley
-PLY (Python Lex-Yacc)                   Version 2.0  (September 8, 2006)
+PLY (Python Lex-Yacc)                   Version 2.1  (October 2, 2006)
 
 David M. Beazley (dave@dabeaz.com)
 
 How to Use
 ==========
 
-PLY consists of two files : lex.py and yacc.py.  To use the system,
-simply copy these files to your project and import them like standard
-Python modules.
+PLY consists of two files : lex.py and yacc.py.  These are contained
+within the 'ply' directory which may also be used as a Python package.
+To use PLY, simply copy the 'ply' directory to your project and import
+lex and yacc from the associated 'ply' package.  For example:
+
+     import ply.lex as lex
+     import ply.yacc as yacc
+
+Alternatively, you can copy just the files lex.py and yacc.py
+individually and use them as modules.  For example:
+
+     import lex
+     import yacc
+
+The file setup.py can be used to install ply using distutils.
 
 The file doc/ply.html contains complete documentation on how to use
 the system.
 
 Resources
 =========
-
 More information about PLY can be obtained on the PLY webpage at:
 
      http://www.dabeaz.com/ply
 Ullman.  The topics found in "Lex & Yacc" by Levine, Mason, and Brown
 may also be useful.
 
+A Google group for PLY can be found at
+
+     http://groups.google.com/group/ply-hack
+
 Acknowledgments
 ===============
-
 A special thanks is in order for all of the students in CS326 who
 suffered through about 25 different versions of these tools :-).
 
 Example
 =======
 
-Here is a simple example showing a PLY implementation of a calculator with variables.
+Here is a simple example showing a PLY implementation of a calculator
+with variables.
 
 # -----------------------------------------------------------------------------
 # calc.py
 
 def t_newline(t):
     r'\n+'
-    t.lineno += t.value.count("\n")
+    t.lexer.lineno += t.value.count("\n")
     
 def t_error(t):
     print "Illegal character '%s'" % t.value[0]
     t.skip(1)
     
 # Build the lexer
-import lex
+import ply.lex as lex
 lex.lex()
 
 # Precedence rules for the arithmetic operators
 def p_error(p):
     print "Syntax error at '%s'" % p.value
 
-import yacc
+import ply.yacc as yacc
 yacc.yacc()
 
 while 1:
 contact me about bugs and/or new features, please send email to
 dave@dabeaz.com.
 
+In addition there is a Google group for discussing PLY related issues at
+
+    http://groups.google.com/group/ply-hack
+ 
 -- Dave
 
 

File doc/makedoc.py

+#!/usr/local/bin/python
+
+###############################################################################
+# Takes a chapter as input and adds internal links and numbering to all
+# of the H1, H2, H3, H4 and H5 sections.
+#
+# Every heading HTML tag (H1, H2 etc) is given an autogenerated name to link
+# to. However, if the name is not an autogenerated name from a previous run,
+# it will be kept. If it is autogenerated, it might change on subsequent runs
+# of this program. Thus if you want to create links to one of the headings,
+# then change the heading link name to something that does not look like an
+# autogenerated link name.
+###############################################################################
+
+import sys
+import re
+import string
+
+###############################################################################
+# Functions
+###############################################################################
+
+# Regexs for <a name="..."></a>
+alink = re.compile(r"<a *name *= *\"(.*)\"></a>", re.IGNORECASE)
+heading = re.compile(r"(_nn\d)", re.IGNORECASE)
+
+def getheadingname(m):
+    autogeneratedheading = True;
+    if m.group(1) != None:
+        amatch = alink.match(m.group(1))
+        if amatch:
+            # A non-autogenerated heading - keep it
+            headingname = amatch.group(1)
+            autogeneratedheading = heading.match(headingname)
+    if autogeneratedheading:
+        # The heading name was either non-existent or autogenerated,
+        # We can create a new heading / change the existing heading
+        headingname = "%s_nn%d" % (filenamebase, nameindex)
+    return headingname
+
+###############################################################################
+# Main program
+###############################################################################
+
+if len(sys.argv) != 2:
+    print "usage: makedoc.py filename"
+    sys.exit(1)
+
+filename = sys.argv[1]
+filenamebase = string.split(filename,".")[0]
+
+section = 0
+subsection = 0
+subsubsection = 0
+subsubsubsection = 0
+nameindex = 0
+
+name = ""
+
+# Regexs for <h1>,... <h5> sections
+
+h1 = re.compile(r".*?<H1>(<a.*a>)*[\d\.\s]*(.*?)</H1>", re.IGNORECASE)
+h2 = re.compile(r".*?<H2>(<a.*a>)*[\d\.\s]*(.*?)</H2>", re.IGNORECASE)
+h3 = re.compile(r".*?<H3>(<a.*a>)*[\d\.\s]*(.*?)</H3>", re.IGNORECASE)
+h4 = re.compile(r".*?<H4>(<a.*a>)*[\d\.\s]*(.*?)</H4>", re.IGNORECASE)
+h5 = re.compile(r".*?<H5>(<a.*a>)*[\d\.\s]*(.*?)</H5>", re.IGNORECASE)
+
+data = open(filename).read()            # Read data
+open(filename+".bak","w").write(data)   # Make backup
+
+lines = data.splitlines()
+result = [ ] # This is the result of postprocessing the file
+index = "<!-- INDEX -->\n<div class=\"sectiontoc\">\n" # index contains the index for adding at the top of the file. Also printed to stdout.
+
+skip = 0
+skipspace = 0
+
+for s in lines:
+    if s == "<!-- INDEX -->":
+        if not skip:
+            result.append("@INDEX@")
+            skip = 1
+        else:
+            skip = 0
+        continue;
+    if skip:
+        continue
+
+    if not s and skipspace:
+        continue
+
+    if skipspace:
+        result.append("")
+        result.append("")
+        skipspace = 0
+    
+    m = h2.match(s)
+    if m:
+        prevheadingtext = m.group(2)
+        nameindex += 1
+        section += 1
+        headingname = getheadingname(m)
+        result.append("""<H2><a name="%s"></a>%d. %s</H2>""" % (headingname,section, prevheadingtext))
+
+        if subsubsubsection:
+            index += "</ul>\n"
+        if subsubsection:
+            index += "</ul>\n"
+        if subsection:
+            index += "</ul>\n"
+        if section == 1:
+            index += "<ul>\n"
+
+        index += """<li><a href="#%s">%s</a>\n""" % (headingname,prevheadingtext)
+        subsection = 0
+        subsubsection = 0
+        subsubsubsection = 0
+        skipspace = 1        
+        continue
+    m = h3.match(s)
+    if m:
+        prevheadingtext = m.group(2)
+        nameindex += 1
+        subsection += 1
+        headingname = getheadingname(m)
+        result.append("""<H3><a name="%s"></a>%d.%d %s</H3>""" % (headingname,section, subsection, prevheadingtext))
+
+        if subsubsubsection:
+            index += "</ul>\n"
+        if subsubsection:
+            index += "</ul>\n"
+        if subsection == 1:
+            index += "<ul>\n"
+
+        index += """<li><a href="#%s">%s</a>\n""" % (headingname,prevheadingtext)
+        subsubsection = 0
+        skipspace = 1        
+        continue
+    m = h4.match(s)
+    if m:
+        prevheadingtext = m.group(2)
+        nameindex += 1
+        subsubsection += 1
+        subsubsubsection = 0
+        headingname = getheadingname(m)
+        result.append("""<H4><a name="%s"></a>%d.%d.%d %s</H4>""" % (headingname,section, subsection, subsubsection, prevheadingtext))
+
+        if subsubsubsection:
+            index += "</ul>\n"
+        if subsubsection == 1:
+            index += "<ul>\n"
+
+        index += """<li><a href="#%s">%s</a>\n""" % (headingname,prevheadingtext)
+        skipspace = 1        
+        continue
+    m = h5.match(s)
+    if m:
+        prevheadingtext = m.group(2)
+        nameindex += 1
+        subsubsubsection += 1
+        headingname = getheadingname(m)
+        result.append("""<H5><a name="%s"></a>%d.%d.%d.%d %s</H5>""" % (headingname,section, subsection, subsubsection, subsubsubsection, prevheadingtext))
+
+        if subsubsubsection == 1:
+            index += "<ul>\n"
+
+        index += """<li><a href="#%s">%s</a>\n""" % (headingname,prevheadingtext)
+        skipspace = 1
+        continue
+    
+    result.append(s)
+
+if subsubsubsection:
+    index += "</ul>\n"
+
+if subsubsection:
+    index += "</ul>\n"
+
+if subsection:
+    index += "</ul>\n"
+
+if section:
+    index += "</ul>\n"
+
+index += "</div>\n<!-- INDEX -->\n"
+
+data = "\n".join(result)
+
+data = data.replace("@INDEX@",index) + "\n";
+
+# Write the file back out
+open(filename,"w").write(data)
+
+

File doc/ply.html

 <body bgcolor="#ffffff">
 
 <h1>PLY (Python Lex-Yacc)</h1>
-
+ 
 <b>
 David M. Beazley <br>
 dave@dabeaz.com<br>
 </b>
 
 <p>
-<b>PLY Version: 2.0</b>
+<b>PLY Version: 2.1</b>
 <p>
 
-<h2>Introduction</h2>
+<!-- INDEX -->
+<div class="sectiontoc">
+<ul>
+<li><a href="#ply_nn1">Introduction</a>
+<li><a href="#ply_nn2">PLY Overview</a>
+<li><a href="#ply_nn3">Lex</a>
+<ul>
+<li><a href="#ply_nn4">Lex Example</a>
+<li><a href="#ply_nn5">The tokens list</a>
+<li><a href="#ply_nn6">Specification of tokens</a>
+<li><a href="#ply_nn7">Token values</a>
+<li><a href="#ply_nn8">Discarded tokens</a>
+<li><a href="#ply_nn9">Line numbers and positional information</a>
+<li><a href="#ply_nn10">Ignored characters</a>
+<li><a href="#ply_nn11">Literal characters</a>
+<li><a href="#ply_nn12">Error handling</a>
+<li><a href="#ply_nn13">Building and using the lexer</a>
+<li><a href="#ply_nn14">The @TOKEN decorator</a>
+<li><a href="#ply_nn15">Optimized mode</a>
+<li><a href="#ply_nn16">Debugging</a>
+<li><a href="#ply_nn17">Alternative specification of lexers</a>
+<li><a href="#ply_nn18">Maintaining state</a>
+<li><a href="#ply_nn19">Duplicating lexers</a>
+<li><a href="#ply_nn20">Internal lexer state</a>
+<li><a href="#ply_nn21">Miscellaneous Issues</a>
+</ul>
+<li><a href="#ply_nn22">Parsing basics</a>
+<li><a href="#ply_nn23">Yacc reference</a>
+<ul>
+<li><a href="#ply_nn24">An example</a>
+<li><a href="#ply_nn25">Combining Grammar Rule Functions</a>
+<li><a href="#ply_nn26">Character Literals</a>
+<li><a href="#ply_nn26">Empty Productions</a>
+<li><a href="#ply_nn28">Changing the starting symbol</a>
+<li><a href="#ply_nn27">Dealing With Ambiguous Grammars</a>
+<li><a href="#ply_nn28">The parser.out file</a>
+<li><a href="#ply_nn29">Syntax Error Handling</a>
+<ul>
+<li><a href="#ply_nn30">Recovery and resynchronization with error rules</a>
+<li><a href="#ply_nn31">Panic mode recovery</a>
+<li><a href="#ply_nn32">General comments on error handling</a>
+</ul>
+<li><a href="#ply_nn33">Line Number Tracking</a>
+<li><a href="#ply_nn34">AST Construction</a>
+<li><a href="#ply_nn35">Embedded Actions</a>
+<li><a href="#ply_nn36">Yacc implementation notes</a>
+</ul>
+<li><a href="#ply_nn37">Parser and Lexer State Management</a>
+<li><a href="#ply_nn38">Using Python's Optimized Mode</a>
+<li><a href="#ply_nn39">Where to go from here?</a>
+</ul>
+</div>
+<!-- INDEX -->
+
+
+
+
+<H2><a name="ply_nn1"></a>1. Introduction</H2>
+
 
 PLY is a pure-Python implementation of the popular compiler
 construction tools lex and yacc. The main goal of PLY is to stay
 fairly faithful to the way in which traditional lex/yacc tools work.
-This includes supporting the LALR(1) parsing as well as providing
+This includes supporting LALR(1) parsing as well as providing
 extensive input validation, error reporting, and diagnostics.  Thus,
 if you've used yacc in another programming language, it should be
 relatively straightforward to use PLY.  
 include lexical analysis, parsing, type checking, type inference,
 nested scoping, and code generation for the SPARC processor.
 Approximately 30 different compiler implementations were completed in
-this course.  Most of PLY's interface and operation has been motivated by common
+this course.  Most of PLY's interface and operation has been influenced by common
 usability problems encountered by students.
 
 <p>
 Because PLY was primarily developed as an instructional tool, you will
 find it to be <em>MUCH</em> more picky about token and grammar rule
-specification than most other Python parsing tools.  In part, this
+specification than many other Python parsing tools.  In part, this
 added formality is meant to catch common programming mistakes made by
 novice users.  However, advanced users will also find such features to
 be useful when building complicated grammars for real programming
 
 <p>
 The rest of this document assumes that you are somewhat familar with
-parsing theory, syntax directed translation, and compiler construction tools such
-as lex and yacc. If you are unfamilar with these topics, you will
-probably want to consult an introductory text such as "Compilers:
-Principles, Techniques, and Tools", by Aho, Sethi, and Ullman.  O'Reilly's "Lex
-and Yacc" by John Levine may also be handy.
-
-<h2>PLY Overview</h2>
+parsing theory, syntax directed translation, and the use of compiler
+construction tools such as lex and yacc in other programming
+languages. If you are unfamilar with these topics, you will probably
+want to consult an introductory text such as "Compilers: Principles,
+Techniques, and Tools", by Aho, Sethi, and Ullman.  O'Reilly's "Lex
+and Yacc" by John Levine may also be handy.  In fact, the O'Reilly book can be
+used as a handy reference for PLY as the concepts are virtually identical.
+
+<H2><a name="ply_nn2"></a>2. PLY Overview</H2>
+
 
 PLY consists of two separate modules; <tt>lex.py</tt> and
-<tt>yacc.py</tt>.  <tt>lex.py</tt> is used to break input text into a
+<tt>yacc.py</tt>, both of which are found in a Python package
+called <tt>ply</tt>. The <tt>lex.py</tt> module is used to break input text into a
 collection of tokens specified by a collection of regular expression
 rules.  <tt>yacc.py</tt> is used to recognize language syntax that has
 been specified in the form of a context free grammar. <tt>yacc.py</tt> uses LR parsing and generates its parsing tables
-using either the SLR (the default) or LALR(1) table generation algorithms.
+using either the LALR(1) (the default) or SLR table generation algorithms.
 
 <p>
 The two tools are meant to work together.  Specifically,
 features you expect including extensive error checking, grammar
 validation, support for empty productions, error tokens, and ambiguity
 resolution via precedence rules.  The primary difference between
-<tt>yacc.py</tt> and Unix <tt>yacc</tt> is that <tt>yacc.py</tt> uses the SLR parsing 
-algorithm instead of LALR(1) as the default.  For simple grammars, SLR is often
-sufficient.  However, LALR(1) support can be enabled as an option.
+<tt>yacc.py</tt> and Unix <tt>yacc</tt> is that <tt>yacc.py</tt> 
+doesn't involve a separate code-generation process. 
 
 <p>
-It is important to note that PLY relies on reflection (introspection)
+Instead, PLY relies on reflection (introspection)
 to build its lexers and parsers.  Unlike traditional lex/yacc which
 require a special input file that is converted into a separate source
 file, the specifications given to PLY <em>are</em> valid Python
 saves them to a file.  If no changes are detected in the input source,
 the tables are read from the cache. Otherwise, they are regenerated.
 
-<h2>Lex Example</h2>
-
-<tt>lex.py</tt> is used to write tokenizers.  To do this, each token
-must be defined by a regular expression rule.  The following file
-implements a very simple lexer for tokenizing simple integer expressions:
+<H2><a name="ply_nn3"></a>3. Lex</H2>
+
+
+<tt>lex.py</tt> is used to tokenize an input string.  For example, suppose
+you're writing a programming language and a user supplied the following input string:
+
+<blockquote>
+<pre>
+x = 3 + 42 * (s - t)
+</pre>
+</blockquote>
+
+A tokenizer splits the string into individual tokens
+
+<blockquote>
+<pre>
+['x','=', '3', '+', '42', '*', '(', 's', '-', 't', ')']
+</pre>
+</blockquote>
+
+Tokens are usually given names to indicate what they are. For example:
+
+<blockquote>
+<pre>
+['ID','EQUALS','NUMBER','PLUS','NUMBER','TIMES',
+  'LPAREN','ID','MINUS','ID','LPAREN']
+</pre>
+</blockquote>
+
+The identification of tokens is typically done by writing a series of regular expression
+rules.  The next section shows how this is done using <tt>lex.py</tt>.
+
+<H3><a name="ply_nn4"></a>3.1 Lex Example</H3>
+
+
+The following example shows how <tt>lex.py</tt> is used to write a simple tokenizer.
 
 <blockquote>
 <pre>
 # tokenizer for a simple expression evaluator for
 # numbers and +,-,*,/
 # ------------------------------------------------------------
-import lex
+import ply.lex as lex
 
 # List of token names.   This is always required
 tokens = (
 # Define a rule so we can track line numbers
 def t_newline(t):
     r'\n+'
-    t.lineno += len(t.value)
+    t.lexer.lineno += len(t.value)
 
 # A string containing ignored characters (spaces and tabs)
 t_ignore  = ' \t'
 </pre>
 </blockquote>
 
-In the example, the <tt>tokens</tt> list defines all of the possible
-token names that can be produced by the lexer.  This list is always required
-and is used to perform a variety of validation checks.  Following the <tt>tokens</tt>
-list, regular expressions are written for each token.  Each of these
-rules are defined by making declarations with a special prefix <tt>t_</tt> to indicate that it
+When executed, the example will produce the following output:
+
+<blockquote>
+<pre>
+$ python example.py
+LexToken(NUMBER,3,2,1)
+LexToken(PLUS,'+',2,3)
+LexToken(NUMBER,4,2,5)
+LexToken(TIMES,'*',2,7)
+LexToken(NUMBER,10,2,10)
+LexToken(PLUS,'+',3,14)
+LexToken(MINUS,'-',3,16)
+LexToken(NUMBER,20,3,18)
+LexToken(TIMES,'*',3,20)
+LexToken(NUMBER,2,3,21)
+</pre>
+</blockquote>
+
+The tokens returned by <tt>lex.token()</tt> are instances
+of <tt>LexToken</tt>.  This object has
+attributes <tt>tok.type</tt>, <tt>tok.value</tt>,
+<tt>tok.lineno</tt>, and <tt>tok.lexpos</tt>.  The following code shows an example of
+accessing these attributes:
+
+<blockquote>
+<pre>
+# Tokenize
+while 1:
+    tok = lex.token()
+    if not tok: break      # No more input
+    print tok.type, tok.value, tok.line, tok.lexpos
+</pre>
+</blockquote>
+
+The <tt>tok.type</tt> and <tt>tok.value</tt> attributes contain the
+type and value of the token itself. 
+<tt>tok.line</tt> and <tt>tok.lexpos</tt> contain information about
+the location of the token.  <tt>tok.lexpos</tt> is the index of the
+token relative to the start of the input text.
+
+<H3><a name="ply_nn5"></a>3.2 The tokens list</H3>
+
+
+All lexers must provide a list <tt>tokens</tt> that defines all of the possible token
+names that can be produced by the lexer.  This list is always required
+and is used to perform a variety of validation checks.  The tokens list is also used by the
+<tt>yacc.py</tt> module to identify terminals.
+
+<p>
+In the example, the following code specified the token names:
+
+<blockquote>
+<pre>
+tokens = (
+   'NUMBER',
+   'PLUS',
+   'MINUS',
+   'TIMES',
+   'DIVIDE',
+   'LPAREN',
+   'RPAREN',
+)
+</pre>
+</blockquote>
+
+<H3><a name="ply_nn6"></a>3.3 Specification of tokens</H3>
+
+
+Each token is specified by writing a regular expression rule.  Each of these rules are
+are defined by  making declarations with a special prefix <tt>t_</tt> to indicate that it
 defines a token.  For simple tokens, the regular expression can
 be specified as strings such as this (note: Python raw strings are used since they are the
 most convenient way to write regular expression strings):
 
 In this case, the name following the <tt>t_</tt> must exactly match one of the
 names supplied in <tt>tokens</tt>.   If some kind of action needs to be performed,
-a token rule can be specified as a function.  For example:
+a token rule can be specified as a function.  For example, this rule matches numbers and
+converts the string into a Python integer.
 
 <blockquote>
 <pre>
 </pre>
 </blockquote>
 
-In this case, the regular expression rule is specified in the function documentation string. 
+When a function is used, the regular expression rule is specified in the function documentation string. 
 The function always takes a single argument which is an instance of 
-<tt>LexToken</tt>.   This object has attributes of <tt>t.type</tt> which is the token type,
-<tt>t.value</tt> which is the lexeme, and <tt>t.lineno</tt> which is the current line number.
+<tt>LexToken</tt>.   This object has attributes of <tt>t.type</tt> which is the token type (as a string),
+<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
+is the position of the token relative to the beginning of the input text.
 By default, <tt>t.type</tt> is set to the name following the <tt>t_</tt> prefix.  The action
 function can modify the contents of the <tt>LexToken</tt> object as appropriate.  However, 
 when it is done, the resulting token should be returned.  If no value is returned by the action
 function, the token is simply discarded and the next token read.
 
 <p>
-The rule <tt>t_newline()</tt> illustrates a regular expression rule
-for a discarded token.  In this case, a rule is written to match
-newlines so that proper line number tracking can be performed.
-By returning no value, the function causes the newline character to be 
-discarded.   The tokenizer is, however, monitoring the line number attribute for changes. 
-
-<p>
-The special <tt>t_ignore</tt> rule is reserved by <tt>lex.py</tt> for characters
-that should be completely ignored in the input stream. 
-Usually this is used to skip over whitespace and other non-essential characters. 
-Although it is possible to define a regular expression rule for whitespace in a manner
-similar to <tt>t_newline()</tt>, the use of <tt>t_ignore</tt> provides substantially better
-lexing performance because it is handled as a special case and is checked in a much
-more efficient manner than the normal regular expression rules.
-
-<p>
-Finally, the <tt>t_error()</tt>
-function is used to handle lexing errors that occur when illegal
-characters are detected.  In this case, the <tt>t.value</tt> attribute contains the
-rest of the input string that has not been tokenized.  In the example, we simply print
-the offending character and skip ahead one character by calling <tt>t.skip(1)</tt>.
-
-<p>
-To build the lexer, the function <tt>lex.lex()</tt> is used.  This function
-uses Python reflection (or introspection) to read the the regular expression rules
-out of the calling context and build the lexer. Once the lexer has been built, two functions can
-be used to control the lexer.
-
-<ul>
-<li><tt>lex.input(data)</tt>.   Reset the lexer and store a new input string.
-<li><tt>lex.token()</tt>.  Return the next token.  Returns a special <tt>LexToken</tt> instance on success or
-None if the end of the input text has been reached.
-</ul>
-
-The code at the bottom of the example shows how the lexer is actually used.  When executed,
-the following output will be produced:
-
-<blockquote>
-<pre>
-$ python example.py
-LexToken(NUMBER,3,2)
-LexToken(PLUS,'+',2)
-LexToken(NUMBER,4,2)
-LexToken(TIMES,'*',2)
-LexToken(NUMBER,10,2)
-LexToken(PLUS,'+',3)
-LexToken(MINUS,'-',3)
-LexToken(NUMBER,20,3)
-LexToken(TIMES,'*',3)
-LexToken(NUMBER,2,3)
-</pre>
-</blockquote>
-
-<h2>Lex Implementation Notes</h2>
-
-<ul>
-<li><tt>lex.py</tt> uses the <tt>re</tt> module to do its patten matching.  When building the master regular expression,
+Internally, <tt>lex.py</tt> uses the <tt>re</tt> module to do its patten matching.  When building the master regular expression,
 rules are added in the following order:
 <p>
 <ol>
 <li>All tokens defined by functions are added in the same order as they appear in the lexer file.
-<li>Tokens defined by strings are added by sorting them in order of decreasing regular expression length (longer expressions
+<li>Tokens defined by strings are added next by sorting them in order of decreasing regular expression length (longer expressions
 are added first).
 </ol>
 <p>
 expressions in order of decreasing length, this problem is solved for rules defined as strings.  For functions,
 the order can be explicitly controlled since rules appearing first are checked first.
 
-<P>
-<li>The lexer requires input to be supplied as a single input string.  Since most machines have more than enough memory, this 
-rarely presents a performance concern.  However, it means that the lexer currently can't be used with streaming data
-such as open files or sockets.  This limitation is primarily a side-effect of using the <tt>re</tt> module.
-
 <p>
-<li>
 To handle reserved words, it is usually easier to just match an identifier and do a special name lookup in a function
 like this:
 
 </pre>
 </blockquote>
 
-<p>
-<li>The lexer requires tokens to be defined as class instances with <tt>t.type</tt>, <tt>t.value</tt>, and <tt>t.lineno</tt>
-attributes.   By default, tokens are created as instances of the <tt>LexToken</tt> class defined internally to <tt>lex.py</tt>.
-If desired, you can create new kinds of tokens provided that they have the three required attributes.   However,
-in practice, it is probably safer to stick with the default.
-
-<p>
-<li>The only safe attribute for assigning token properties is <tt>t.value</tt>.   In some cases, you may want to attach
-a number of different properties to a token (e.g., symbol table entries for identifiers).  To do this, replace <tt>t.value</tt>
-with a tuple or class instance. For example:
+This approach greatly reduces the number of regular expression rules and is likely to make things a little faster.
+
+<H3><a name="ply_nn7"></a>3.4 Token values</H3>
+
+
+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
+that was matched.   However, the value can be assigned to any Python object.   For instance, when lexing identifiers, you may
+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:
 
 <blockquote>
 <pre>
 def t_ID(t):
     ...
-    # For identifiers, create a (lexeme, symtab) tuple
+    # Look up symbol table information and return a tuple
     t.value = (t.value, symbol_lookup(t.value))
     ...
     return t
 </pre>
 </blockquote>
 
-Although allowed, do NOT assign additional attributes to the token object.  For example,
+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
+contents of the <tt>value</tt> attribute.  Thus, accessing other attributes may  be unnecessarily awkward.
+
+<H3><a name="ply_nn8"></a>3.5 Discarded tokens</H3>
+
+
+To discard a token, such as a comment, simply define a token rule that returns no value.  For example:
+
 <blockquote>
 <pre>
-def t_ID(t):
-    ...
-    # Bad implementation of above
-    t.symtab = symbol_lookup(t.value)
-    ...
+def t_COMMENT(t):
+    r'\#.*'
+    pass
+    # No return value. Token discarded
 </pre>
 </blockquote>
 
-The reason you don't want to do this is that the <tt>yacc.py</tt>
-module only provides public access to the <tt>t.value</tt> attribute of each token.
-Therefore, any other attributes you assign are inaccessible (if you are familiar
-with the internals of C lex/yacc, <tt>t.value</tt> is the same as <tt>yylval.tok</tt>).
+<H3><a name="ply_nn9"></a>3.6 Line numbers and positional information</H3>
+
+
+<p>By default, <tt>lex.py</tt> knows nothing about line numbers.  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.
+
+<blockquote>
+<pre>
+# Define a rule so we can track line numbers
+def t_newline(t):
+    r'\n+'
+    t.lexer.lineno += len(t.value)
+</pre>
+</blockquote>
+Within the rule, the <tt>lineno</tt> attribute of the underlying lexer <tt>t.lexer</tt> is updated.
+After the line number is updated, the token is simply discarded since nothing is returned.
 
 <p>
-<li>To track line numbers, the lexer internally maintains a line
-number variable.  Each token automatically gets the value of the
-current line number in the <tt>t.lineno</tt> attribute. To modify the
-current line number, simply change the <tt>t.lineno</tt> attribute
-in a function rule (as previously shown for
-<tt>t_newline()</tt>).  Even if the resulting token is discarded,
-changes to the line number remain in effect for subsequent tokens.
+<tt>lex.py</tt> does not perform and kind of automatic column tracking.  However, it does record positional
+information related to each token in the <tt>lexpos</tt> attribute.   Using this, it is usually possible to compute 
+column information as a separate step.   For instance, just count backwards until you reach a newline.
+
+<blockquote>
+<pre>
+# Compute column. 
+#     input is the input text string
+#     token is a token instance
+def find_column(input,token):
+    i = token.lexpos
+    while i > 0:
+        if input[i] == '\n': break
+        i -= 1
+    column = (token.lexpos - i)+1
+    return column
+</pre>
+</blockquote>
+
+<H3><a name="ply_nn10"></a>3.7 Ignored characters</H3>
+
 
 <p>
-<li>To support multiple scanners in the same application, the <tt>lex.lex()</tt> function
-actually returns a special <tt>Lexer</tt> object.   This object has two methods 
-<tt>input()</tt> and <tt>token()</tt> that can be used to supply input and get tokens.  For example:
+The special <tt>t_ignore</tt> rule is reserved by <tt>lex.py</tt> for characters
+that should be completely ignored in the input stream. 
+Usually this is used to skip over whitespace and other non-essential characters. 
+Although it is possible to define a regular expression rule for whitespace in a manner
+similar to <tt>t_newline()</tt>, the use of <tt>t_ignore</tt> provides substantially better
+lexing performance because it is handled as a special case and is checked in a much
+more efficient manner than the normal regular expression rules.
+
+<H3><a name="ply_nn11"></a>3.8 Literal characters</H3>
+
+
+<p>
+Literal characters can be specified by defining a variable <tt>literals</tt> in your lexing module.  For example:
+
+<blockquote>
+<pre>
+literals = [ '+','-','*','/' ]
+</pre>
+</blockquote>
+
+or alternatively
+
+<blockquote>
+<pre>
+literals = "+-*/"
+</pre>
+</blockquote>
+
+A literal character is simply a single character that is returned "as is" when encountered by the lexer.  Literals are checked
+after all of the defined regular expression rules.  Thus, if a rule starts with one of the literal characters, it will always 
+take precedence.
+<p>
+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>.
+
+<H3><a name="ply_nn12"></a>3.9 Error handling</H3>
+
+
+<p>
+Finally, the <tt>t_error()</tt>
+function is used to handle lexing errors that occur when illegal
+characters are detected.  In this case, the <tt>t.value</tt> attribute contains the
+rest of the input string that has not been tokenized.  In the example, the error function
+was defined as follows:
+
+<blockquote>
+<pre>
+# Error handling rule
+def t_error(t):
+    print "Illegal character '%s'" % t.value[0]
+    t.skip(1)
+</pre>
+</blockquote>
+
+In this case, we simply print the offending character and skip ahead one character by calling <tt>t.skip(1)</tt>.
+
+<H3><a name="ply_nn13"></a>3.10 Building and using the lexer</H3>
+
+
+<p>
+To build the lexer, the function <tt>lex.lex()</tt> is used.  This function
+uses Python reflection (or introspection) to read the the regular expression rules
+out of the calling context and build the lexer. Once the lexer has been built, two functions can
+be used to control the lexer.
+
+<ul>
+<li><tt>lex.input(data)</tt>.   Reset the lexer and store a new input string.
+<li><tt>lex.token()</tt>.  Return the next token.  Returns a special <tt>LexToken</tt> instance on success or
+None if the end of the input text has been reached.
+</ul>
+
+If desired, the lexer can also be used as an object.  The <tt>lex()</tt> returns a <tt>Lexer</tt> object that
+can be used for this purpose.  For example:
 
 <blockquote>
 <pre>
 </pre>
 </blockquote>
 
-The functions <tt>lex.input()</tt> and <tt>lex.token()</tt> are bound to the <tt>input()</tt> 
+<p>
+This latter technique should be used if you intend to use multiple lexers in your application.  Simply define each
+lexer in its own module and use the object returned by <tt>lex()</tt> as appropriate.
+
+<p>
+Note: The global functions <tt>lex.input()</tt> and <tt>lex.token()</tt> are bound to the <tt>input()</tt> 
 and <tt>token()</tt> methods of the last lexer created by the lex module. 
 
-
-<p>
-<li>To reduce compiler startup time and improve performance, the lexer can be built in optimized mode as follows:
+<H3><a name="ply_nn14"></a>3.11 The @TOKEN decorator</H3>
+
+
+In some applications, you may want to define build tokens from as a series of
+more complex regular expression rules.  For example:
 
 <blockquote>
 <pre>
-lex.lex(optimize=1)
+digit            = r'([0-9])'
+nondigit         = r'([_A-Za-z])'
+identifier       = r'(' + nondigit + r'(' + digit + r'|' + nondigit + r')*)'        
+
+def t_ID(t):
+    # want docstring to be identifier above. ?????
+    ...
 </pre>
 </blockquote>
 
-When used, most error checking and validation is disabled.   This provides a slight performance
-gain while tokenizing and tends to chop a few tenths of a second off startup time.  Since it disables
-error checking, this mode is not the default and is not recommended during development.  However, once
-you have your compiler fully working, it is usually safe to disable the error checks.
-
-<p>
-<li>You can enable some additional debugging by building the lexer like this:
+In this case, we want the regular expression rule for <tt>ID</tt> to be one of the variables above. However, there is no
+way to directly specify this using a normal documentation string.   To solve this problem, you can use the <tt>@TOKEN</tt>
+decorator.  For example:
 
 <blockquote>
 <pre>
-lex.lex(debug=1)
+from ply.lex import TOKEN
+
+@TOKEN(identifier)
+def t_ID(t):
+    ...
 </pre>
 </blockquote>
 
+This will attach <tt>identifier</tt> to the docstring for <tt>t_ID()</tt> allowing <tt>lex.py</tt> to work normally.  An alternative
+approach this problem is to set the docstring directly like this:
+
+<blockquote>
+<pre>
+def t_ID(t):
+    ...
+
+t_ID.__doc__ = identifier
+</pre>
+</blockquote>
+
+<b>NOTE:</b> Use of <tt>@TOKEN</tt> requires Python-2.4 or newer.  If you're concerned about backwards compatibility with older
+versions of Python, use the alternative approach of setting the docstring directly.
+
+<H3><a name="ply_nn15"></a>3.12 Optimized mode</H3>
+
+
+For improved performance, it may be desirable to use Python's
+optimized mode (e.g., running Python with the <tt>-O</tt>
+option). However, doing so causes Python to ignore documentation
+strings.  This presents special problems for <tt>lex.py</tt>.  To
+handle this case, you can create your lexer using
+the <tt>optimize</tt> option as follows:
+
+<blockquote>
+<pre>
+lexer = lex.lex(optimize=1)
+</pre>
+</blockquote>
+
+Next, run Python in its normal operating mode.  When you do
+this, <tt>lex.py</tt> will write a file called <tt>lextab.py</tt> to
+the current directory.  This file contains all of the regular
+expression rules and tables used during lexing.  On subsequent
+executions,
+<tt>lextab.py</tt> will simply be imported to build the lexer.  This
+approach substantially improves the startup time of the lexer and it
+works in Python's optimized mode.
+
 <p>
-<li>To help you debug your lexer, <tt>lex.py</tt> comes with a simple main program which will either
-tokenize input read from standard input or from a file.  To use it, simply put this in your lexer:
+To change the name of the lexer-generated file, use the <tt>lextab</tt> keyword argument.  For example:
+
+<blockquote>
+<pre>
+lexer = lex.lex(optimize=1,lextab="footab")
+</pre>
+</blockquote>
+
+When running in optimized mode, it is important to note that lex disables most error checking.  Thus, this is really only recommended
+if you're sure everything is working correctly and you're ready to start releasing production code.
+
+<H3><a name="ply_nn16"></a>3.13 Debugging</H3>
+
+
+For the purpose of debugging, you can run <tt>lex()</tt> in a debugging mode as follows:
+
+<blockquote>
+<pre>
+lexer = lex.lex(debug=1)
+</pre>
+</blockquote>
+
+This will result in a large amount of debugging information to be printed including all of the added rules and the master
+regular expressions.
+
+In addition, <tt>lex.py</tt> comes with a simple main function which
+will either tokenize input read from standard input or from a file specified
+on the command line. To use it, simply put this in your lexer:
 
 <blockquote>
 <pre>
 </pre>
 </blockquote>
 
-Then, run you lexer as a main program such as <tt>python mylex.py</tt>
+<H3><a name="ply_nn17"></a>3.14 Alternative specification of lexers</H3>
+
+
+As shown in the example, lexers are specified all within one Python module.   If you want to
+put token rules in a different module from the one in which you invoke <tt>lex()</tt>, use the
+<tt>module</tt> keyword argument.
+
+<p>
+For example, you might have a dedicated module that just contains
+the token rules:
+
+<blockquote>
+<pre>
+# module: tokrules.py
+# This module just contains the lexing rules
+
+# List of token names.   This is always required
+tokens = (
+   'NUMBER',
+   'PLUS',
+   'MINUS',
+   'TIMES',
+   'DIVIDE',
+   'LPAREN',
+   'RPAREN',
+)
+
+# Regular expression rules for simple tokens
+t_PLUS    = r'\+'
+t_MINUS   = r'-'
+t_TIMES   = r'\*'
+t_DIVIDE  = r'/'
+t_LPAREN  = r'\('
+t_RPAREN  = r'\)'
+
+# A regular expression rule with some action code
+def t_NUMBER(t):
+    r'\d+'
+    try:
+         t.value = int(t.value)    
+    except ValueError:
+         print "Line %d: Number %s is too large!" % (t.lineno,t.value)
+	 t.value = 0
+    return t
+
+# Define a rule so we can track line numbers
+def t_newline(t):
+    r'\n+'
+    t.lexer.lineno += len(t.value)
+
+# A string containing ignored characters (spaces and tabs)
+t_ignore  = ' \t'
+
+# Error handling rule
+def t_error(t):
+    print "Illegal character '%s'" % t.value[0]
+    t.skip(1)
+</pre>
+</blockquote>
+
+Now, if you wanted to build a tokenizer from these rules in a different module, you would do the following (shown for Python interactive mode):
+
+<blockquote>
+<pre>
+>>> import tokrules
+>>> <b>lexer = lex.lex(module=tokrules)</b>
+>>> lexer.input("3 + 4")
+>>> lexer.token()
+LexToken(NUMBER,3,1,1,0)
+>>> lexer.token()
+LexToken(PLUS,'+',1,2)
+>>> lexer.token()
+LexToken(NUMBER,4,1,4)
+>>> lexer.token()
+None
+>>>
+</pre>
+</blockquote>
+
+The <tt>object</tt> option can be used to define lexers as a class instead of a module.  For example:
+
+<blockquote>
+<pre>
+import ply.lex as lex
+
+class MyLexer:
+    # List of token names.   This is always required
+    tokens = (
+       'NUMBER',
+       'PLUS',
+       'MINUS',
+       'TIMES',
+       'DIVIDE',
+       'LPAREN',
+       'RPAREN',
+    )
+
+    # Regular expression rules for simple tokens
+    t_PLUS    = r'\+'
+    t_MINUS   = r'-'
+    t_TIMES   = r'\*'
+    t_DIVIDE  = r'/'
+    t_LPAREN  = r'\('
+    t_RPAREN  = r'\)'
+
+    # A regular expression rule with some action code
+    # Note addition of self parameter since we're in a class
+    def t_NUMBER(self,t):
+        r'\d+'
+        try:
+             t.value = int(t.value)    
+        except ValueError:
+             print "Line %d: Number %s is too large!" % (t.lineno,t.value)
+             t.value = 0
+        return t
+
+    # Define a rule so we can track line numbers
+    def t_newline(self,t):
+        r'\n+'
+        t.lexer.lineno += len(t.value)
+
+    # A string containing ignored characters (spaces and tabs)
+    t_ignore  = ' \t'
+
+    # Error handling rule
+    def t_error(self,t):
+        print "Illegal character '%s'" % t.value[0]
+        t.skip(1)
+
+    <b># Build the lexer
+    def build(self,**kwargs):
+        self.lexer = lex.lex(object=self, **kwargs)</b>
+    
+    # Test it output
+    def test(self,data):
+        self.lexer.input(data)
+        while 1:
+             tok = lexer.token()
+             if not tok: break
+             print tok
+
+# Build the lexer and try it out
+m = MyLexer()
+m.build()           # Build the lexer
+m.test("3 + 4")     # Test it
+</pre>
+</blockquote>
+
+For reasons that are subtle, you should <em>NOT</em> invoke <tt>lex.lex()</tt> inside the <tt>__init__()</tt> method of your class.  If you
+do, it may cause bizarre behavior if someone tries to duplicate a lexer object.  Keep reading.
+
+<H3><a name="ply_nn18"></a>3.15 Maintaining state</H3>
+
+
+In your lexer, you may want to maintain a variety of state information.  This might include mode settings, symbol tables, and other details.  There are a few
+different ways to handle this situation.  First, you could just keep some global variables:
+
+<blockquote>
+<pre>
+num_count = 0
+def t_NUMBER(t):
+    r'\d+'
+    global num_count
+    num_count += 1
+    try:
+         t.value = int(t.value)    
+    except ValueError:
+         print "Line %d: Number %s is too large!" % (t.lineno,t.value)
+	 t.value = 0
+    return t
+</pre>
+</blockquote>
+
+Alternatively, you can store this information inside the Lexer object created by <tt>lex()</tt>.  To this, you can use the <tt>lexer</tt> attribute
+of tokens passed to the various rules. For example:
+
+<blockquote>
+<pre>
+def t_NUMBER(t):
+    r'\d+'
+    t.lexer.num_count += 1     # Note use of lexer attribute
+    try:
+         t.value = int(t.value)    
+    except ValueError:
+         print "Line %d: Number %s is too large!" % (t.lineno,t.value)
+	 t.value = 0
+    return t
+
+lexer = lex.lex()
+lexer.num_count = 0            # Set the initial count
+</pre>
+</blockquote>
+
+This latter approach has the advantage of storing information inside
+the lexer itself---something that may be useful if multiple instances
+of the same lexer have been created.  However, it may also feel kind
+of "hacky" to the purists.  Just to put their mind at some ease, all
+internal attributes of the lexer have names that are prefixed
+by <tt>lex</tt> (e.g., <tt>lexdata</tt>,<tt>lexpos</tt>, etc.).  Thus,
+it should be perfectly safe to store attributes in the lexer that
+don't have names starting with that prefix.
+
+<p>
+A third approach is to define the lexer as a class as shown in the previous example:
+
+<blockquote>
+<pre>
+class MyLexer:
+    ...
+    def t_NUMBER(self,t):
+        r'\d+'
+        self.num_count += 1
+        try:
+             t.value = int(t.value)    
+        except ValueError:
+             print "Line %d: Number %s is too large!" % (t.lineno,t.value)
+             t.value = 0
+        return t
+
+    def build(self, **kwargs):
+        self.lexer = lex.lex(object=self,**kwargs)
+
+    def __init__(self):
+        self.num_count = 0
+
+# Create a lexer 
+m = MyLexer()
+lexer = lex.lex(object=m)
+</pre>
+</blockquote>
+
+The class approach is probably the easiest to manage if your application is going to be creating multiple instances of the same lexer.
+
+<H3><a name="ply_nn19"></a>3.16 Duplicating lexers</H3>
+
+
+If necessary, a lexer object can be quickly duplicated by invoking its <tt>clone()</tt> method.  For example:
+
+<blockquote>
+<pre>
+lexer = lex.lex()
+...
+newlexer = lexer.clone()
+</pre>
+</blockquote>
+
+When a lexer is cloned, the copy is identical to the original lexer,
+including any input text. However, once created, different text can be
+fed to the clone which can be used independently.  This capability may
+be useful in situations when you are writing a parser/compiler that
+involves recursive or reentrant processing.  For instance, if you
+needed to scan ahead in the input for some reason, you could create a
+clone and use it to look ahead.
+
+<p>
+The advantage of using <tt>clone()</tt> instead of reinvoking <tt>lex()</tt> is
+that it is significantly faster.  Namely, it is not necessary to re-examine all of the 
+token rules, build a regular expression, and construct internal tables.  All of this
+information can simply be reused in the new lexer.
+
+<p>
+Special considerations need to be made when cloning a lexer that is defined as a class.  Previous sections
+showed an example of a class <tt>MyLexer</tt>.  If you have the following code:
+
+<blockquote>
+<pre>
+m = MyLexer()
+a = lex.lex(object=m)      # Create a lexer
+
+b = a.clone()              # Clone the lexer
+</pre>
+</blockquote>
+
+Then both <tt>a</tt> and <tt>b</tt> are going to be bound to the same
+object <tt>m</tt>.  If the object <tt>m</tt> contains internal state
+related to lexing, this sharing may lead to quite a bit of confusion. To fix this,
+the <tt>clone()</tt> method accepts an optional argument that can be used to supply a new object.  This
+can be used to clone the lexer and bind it to a new instance.  For example:
+
+<blockquote>
+<pre>
+m = MyLexer()              # Create a lexer
+a = lex.lex(object=m)
+
+# Create a clone 
+n = MyLexer()              # New instance of MyLexer
+b = a.clone(n)             # New lexer bound to n
+</pre>
+</blockquote>
+
+It may make sense to encapsulate all of this inside a method:
+
+<blockquote>
+<pre>
+class MyLexer:
+     ...
+     def clone(self):
+         c = MyLexer()        # Create a new instance of myself
+         # Copy attributes from self to c as appropriate
+         ...
+         # Clone the lexer
+         c.lexer = self.lexer.clone(c)
+         return c
+</pre>
+</blockquote>
+
+The fact that a new instance of <tt>MyLexer</tt> may be created while cloning a lexer is the reason why you should never
+invoke <tt>lex.lex()</tt> inside <tt>__init__()</tt>.  If you do, the lexer will be rebuilt from scratch and you lose
+all of the performance benefits of using <tt>clone()</tt> in the first place.
+
+<H3><a name="ply_nn20"></a>3.17 Internal lexer state</H3>
+
+
+A Lexer object <tt>lexer</tt> has a number of internal attributes that may be useful in certain
+situations. 
+
+<p>
+<tt>lexer.lexpos</tt>
+<blockquote>
+This attribute is an integer that contains the current position within the input text.  If you modify
+the value, it will change the result of the next call to <tt>token()</tt>.  Within token rule functions, this points
+to the first character <em>after</em> the matched text.  If the value is modified within a rule, the next returned token will be
+matched at the new position.
+</blockquote>
+
+<p>
+<tt>lexer.lineno</tt>
+<blockquote>
+The current value of the line number attribute stored in the lexer.  This can be modified as needed to
+change the line number.
+</blockquote>
+
+<p>
+<tt>lexer.lexdata</tt>
+<blockquote>
+The current input text stored in the lexer.  This is the string passed with the <tt>input()</tt> method. It
+would probably be a bad idea to modify this unless you really know what you're doing.
+</blockquote>
+
+<H3><a name="ply_nn21"></a>3.18 Miscellaneous Issues</H3>
+
+
+<P>
+<li>The lexer requires input to be supplied as a single input string.  Since most machines have more than enough memory, this 
+rarely presents a performance concern.  However, it means that the lexer currently can't be used with streaming data
+such as open files or sockets.  This limitation is primarily a side-effect of using the <tt>re</tt> module.
 
 <p>
 <li>The lexer should work properly with both Unicode strings given as token and pattern matching rules as
 blazingly fast when used on very large input files.  If
 performance is concern, you might consider upgrading to the most
 recent version of Python, creating a hand-written lexer, or offloading
-the lexer into a C extension module.  In defense of <tt>lex.py</tt>,
-it's performance is not <em>that</em> bad when used on reasonably
-sized input files.  For instance, lexing a 4700 line C program with
-32000 input tokens takes about 20 seconds on a 200 Mhz PC.  Obviously,
-it will run much faster on a more speedy machine.
-
+the lexer into a C extension module.  
+
+<p>
+If you are going to create a hand-written lexer and you plan to use it with <tt>yacc.py</tt>, 
+it only needs to conform to the following requirements:
+
+<ul>
+<li>It must provide a <tt>token()</tt> method that returns the next token or <tt>None</tt> if no more
+tokens are available.
+<li>The <tt>token()</tt> method must return an object <tt>tok</tt> that has <tt>type</tt> and <tt>value</tt> attributes.
 </ul>
 
-<h2>Parsing basics</h2>
+<H2><a name="ply_nn22"></a>4. Parsing basics</H2>
+
 
 <tt>yacc.py</tt> is used to parse language syntax.  Before showing an
 example, there are a few important bits of background that must be
 However, subtle details of this process explain why, in the example above, the parser chooses to shift a token
 onto the stack in step 9 rather than reducing the rule <tt>expr : expr + term</tt>.
 
-<h2>Yacc example</h2>
+<H2><a name="ply_nn23"></a>5. Yacc reference</H2>
+
+
+This section describes how to use write parsers in PLY.
+
+<H3><a name="ply_nn24"></a>5.1 An example</H3>
+
 
 Suppose you wanted to make a grammar for simple arithmetic expressions as previously described.   Here is
 how you would do it with <tt>yacc.py</tt>:
 <pre>
 # Yacc example
 
-import yacc
+import ply.yacc as yacc
 
 # Get the token map from the lexer.  This is required.
 from calclex import tokens
 # Build the parser
 yacc.yacc()
 
-# Use this if you want to build the parser using LALR(1) instead of SLR
-# yacc.yacc(method="LALR")
+# Use this if you want to build the parser using SLR instead of LALR
+# yacc.yacc(method="SLR")
 
 while 1:
    try:
 field.  All of the other rules simply perform various types of integer operations and store
 the result.
 
+<P>
+Note: The use of negative indices have a special meaning in yacc---specially <tt>p[-1]</tt> does
+not have the same value as <tt>p[3]</tt> in this example.  Please see the section on "Embedded Actions" for further
+details.
+
 <p>
 The first rule defined in the yacc specification determines the starting grammar
 symbol (in this case, a rule for <tt>expression</tt> appears first).  Whenever
 <blockquote>
 <pre>
 $ python calcparse.py
-yacc: Generating SLR parsing table...  
+yacc: Generating LALR parsing table...  
 calc > 
 </pre>
 </blockquote>
 
 The next few sections now discuss a few finer points of grammar construction.
 
-<h2>Combining Grammar Rule Functions</h2>
+<H3><a name="ply_nn25"></a>5.2 Combining Grammar Rule Functions</H3>
+
 
 When grammar rules are similar, they can be combined into a single function.
 For example, consider the two rules in our earlier example:
 </pre>
 </blockquote>
 
-<h2>Empty Productions</h2>
+<H3><a name="ply_nn26"></a>5.3 Character Literals</H3>
+
+
+If desired, a grammar may contain tokens defined as single character literals.   For example:
+
+<blockquote>
+<pre>
+def p_binary_operators(p):
+    '''expression : expression '+' term
+                  | expression '-' term
+       term       : term '*' factor
+                  | term '/' factor'''
+    if p[2] == '+':
+        p[0] = p[1] + p[3]
+    elif p[2] == '-':
+        p[0] = p[1] - p[3]
+    elif p[2] == '*':
+        p[0] = p[1] * p[3]
+    elif p[2] == '/':
+        p[0] = p[1] / p[3]
+</pre>
+</blockquote>
+
+A character literal must be enclosed in quotes such as <tt>'+'</tt>.  In addition, if literals are used, they must be declared in the
+corresponding <tt>lex</tt> file through the use of a special <tt>literals</tt> declaration.
+
+<blockquote>
+<pre>
+# Literals.  Should be placed in module given to lex()
+literals = ['+','-','*','/' ]
+</pre>
+</blockquote>
+
+Character literals are limited to a single character.  Thus, it is not legal to specify literals such as <tt>'&lt;='</tt> or <tt>'=='</tt>.  For this, use
+the normal lexing rules (e.g., define a rule such as <tt>t_EQ = r'=='</tt>).
+
+<H3><a name="ply_nn26"></a>5.4 Empty Productions</H3>
+
 
 <tt>yacc.py</tt> can handle empty productions by defining a rule like this:
 
 </pre>
 </blockquote>
 
-<h2>Dealing With Ambiguous Grammars</h2>
+<H3><a name="ply_nn28"></a>5.5 Changing the starting symbol</H3>
+
+
+Normally, the first rule found in a yacc specification defines the starting grammar rule (top level rule).  To change this, simply
+supply a <tt>start</tt> specifier in your file.  For example:
+
+<blockquote>
+<pre>
+start = 'foo'
+
+def p_bar(p):
+    'bar : A B'
+
+# This is the starting rule due to the start specifier above
+def p_foo(p):
+    'foo : bar X'
+...
+</pre>
+</blockquote>
+
+The use of a <tt>start</tt> specifier may be useful during debugging since you can use it to have yacc build a subset of
+a larger grammar.  For this purpose, it is also possible to specify a starting symbol as an argument to <tt>yacc()</tt>. For example:
+
+<blockquote>
+<pre>
+yacc.yacc(start='foo')
+</pre>
+</blockquote>
+
+<H3><a name="ply_nn27"></a>5.6 Dealing With Ambiguous Grammars</H3>
+
 
 The expression grammar given in the earlier example has been written in a special format to eliminate ambiguity. 
 However, in many situations, it is extremely difficult or awkward to write grammars in this format.  A
 simply looking at the input grammer.    To locate these, it is usually easier to look at the
 <tt>parser.out</tt> debugging file with an appropriately high level of caffeination.
 
-<h2>The parser.out file</h2>
+<H3><a name="ply_nn28"></a>5.7 The parser.out file</H3>
+
 
 Tracking down shift/reduce and reduce/reduce conflicts is one of the finer pleasures of using an LR
 parsing algorithm.  To assist in debugging, <tt>yacc.py</tt> creates a debugging file called
 expression           : 1 1 2 2 3 3 4 4 6 0
 
 
-Parsing method: SLR
+Parsing method: LALR
 
 
 state 0
 of most parsing conflicts.  It should also be stressed that not all shift-reduce conflicts are
 bad.  However, the only way to be sure that they are resolved correctly is to look at <tt>parser.out</tt>.
   
-<h2>Syntax Error Handling</h2>
+<H3><a name="ply_nn29"></a>5.8 Syntax Error Handling</H3>
+
 
 When a syntax error occurs during parsing, the error is immediately
 detected (i.e., the parser does not read any more tokens beyond the
 parser can successfully shift a new symbol or reduce a rule involving <tt>error</tt>.
 </ol>
 
-<h4>Recovery and resynchronization with error rules</h4>
+<H4><a name="ply_nn30"></a>5.8.1 Recovery and resynchronization with error rules</H4>
+
 
 The most well-behaved approach for handling syntax errors is to write grammar rules that include the <tt>error</tt>
 token.  For example, suppose your language had a grammar rule for a print statement like this:
 be reduced--which may make it difficult to recover if more bad tokens
 immediately follow.   
 
-<h4>Panic mode recovery</h4>
+<H4><a name="ply_nn31"></a>5.8.2 Panic mode recovery</H4>
+
 
 An alternative error recovery scheme is to enter a panic mode recovery in which tokens are
 discarded to a point where the parser might be able to recover in some sensible manner.
 </pre>
 </blockquote>
 
-<h4>General comments on error handling</h4>
+<H4><a name="ply_nn32"></a>5.8.3 General comments on error handling</H4>
+
 
 For normal types of languages, error recovery with error rules and resynchronization characters is probably the most reliable
 technique. This is because you can instrument the grammar to catch errors at selected places where it is relatively easy 
 to recover and continue parsing.  Panic mode recovery is really only useful in certain specialized applications where you might want
 to discard huge portions of the input text to find a valid restart point.
 
-<h2>Line Number Tracking</h2>
+<H3><a name="ply_nn33"></a>5.9 Line Number Tracking</H3>
+
 
 <tt>yacc.py</tt> automatically tracks line numbers for all of the grammar symbols and tokens it processes.  To retrieve the line
 numbers, two functions are used in grammar rules:
 numbers.  However, if you want to save the line numbers in a parse-tree node, you will need to make your own
 private copy.
 
-<h2>AST Construction</h2>
+<H3><a name="ply_nn34"></a>5.10 AST Construction</H3>
+
 
 <tt>yacc.py</tt> provides no special functions for constructing an abstract syntax tree.  However, such
 construction is easy enough to do on your own.  Simply create a data structure for abstract syntax tree nodes
 </pre>
 </blockquote>
 
-<h2>Yacc implementation notes</h2>
-
-<ul>
-<li>The default parsing method is SLR. To use LALR(1) instead, run yacc() as follows:
+<H3><a name="ply_nn35"></a>5.11 Embedded Actions</H3>
+
+
+The parsing technique used by yacc only allows actions to be executed at the end of a rule.  For example,
+suppose you have a rule like this:
 
 <blockquote>
 <pre>
-yacc.yacc(method="LALR")
+def p_foo(p):
+    "foo : A B C D"
+    print "Parsed a foo", p[1],p[2],p[3],p[4]
+</pre>
+</blockquote>
+
+<p>
+In this case, the supplied action code only executes after all of the
+symbols <tt>A</tt>, <tt>B</tt>, <tt>C</tt>, and <tt>D</tt> have been
+parsed. Sometimes, however, it is useful to execute small code
+fragments during intermediate stages of parsing.  For example, suppose
+you wanted to perform some action immediately after <tt>A</tt> has
+been parsed. To do this, you can write a empty rule like this:
+
+<blockquote>
+<pre>
+def p_foo(p):
+    "foo : A seen_A B C D"
+    print "Parsed a foo", p[1],p[3],p[4],p[5]
+    print "seen_A returned", p[2]
+
+def p_seen_A(p):
+    "seen_A :"
+    print "Saw an A = ", p[-1]   # Access grammar symbol to left
+    p[0] = some_value            # Assign value to seen_A
+
+</pre>
+</blockquote>
+
+<p>
+In this example, the empty <tt>seen_A</tt> rule executes immediately
+after <tt>A</tt> is shifted onto the parsing stack.  Within this
+rule, <tt>p[-1]</tt> refers to the symbol on the stack that appears
+immediately to the left of the <tt>seem_A</tt> symbol.  In this case,
+it would be the value of <tt>A</tt> in the <tt>foo</tt> rule
+immediately above.  Like other rules, a value can be returned from an
+embedded action by simply assigning it to <tt>p[0]</tt>
+
+<p>
+The use of embedded actions can sometimes introduce extra shift/reduce conflicts.  For example,
+this grammar has no conflicts:
+
+<blockquote>
+<pre>
+def p_foo(p):
+    """foo : abcd
+           | abcx"""
+
+def p_abcd(p):
+    "abcd : A B C D"
+
+def p_abcx(p):
+    "abcx : A B C X"
+</pre>
+</blockquote>
+
+However, if you insert an embedded action into one of the rules like this,
+
+<blockquote>
+<pre>
+def p_foo(p):
+    """foo : abcd
+           | abcx"""
+
+def p_abcd(p):
+    "abcd : A B C D"
+
+def p_abcx(p):
+    "abcx : A B seen_AB C X"
+
+def p_seen_AB(p):