home *** CD-ROM | disk | FTP | other *** search
/ PC Extra 07 & 08 / pca1507.iso / Software / psp8 / Data1.cab / tokenize.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2003-04-22  |  10.3 KB  |  266 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.2)
  3.  
  4. '''Tokenization help for Python programs.
  5.  
  6. generate_tokens(readline) is a generator that breaks a stream of
  7. text into Python tokens.  It accepts a readline-like method which is called
  8. repeatedly to get the next line of input (or "" for EOF).  It generates
  9. 5-tuples with these members:
  10.  
  11.     the token type (see token.py)
  12.     the token (a string)
  13.     the starting (row, column) indices of the token (a 2-tuple of ints)
  14.     the ending (row, column) indices of the token (a 2-tuple of ints)
  15.     the original line (string)
  16.  
  17. It is designed to match the working of the Python tokenizer exactly, except
  18. that it produces COMMENT tokens for comments and gives type OP for all
  19. operators
  20.  
  21. Older entry points
  22.     tokenize_loop(readline, tokeneater)
  23.     tokenize(readline, tokeneater=printtoken)
  24. are the same, except instead of generating tokens, tokeneater is a callback
  25. function to which the 5 fields described above are passed as 5 arguments,
  26. each time a new token is found.'''
  27. from __future__ import generators
  28. __author__ = 'Ka-Ping Yee <ping@lfw.org>'
  29. __credits__ = 'GvR, ESR, Tim Peters, Thomas Wouters, Fred Drake, Skip Montanaro'
  30. import string
  31. import re
  32. from token import *
  33. import token
  34. __all__ = None if x[0] != '_' else [] + [
  35.     'COMMENT',
  36.     'tokenize',
  37.     'NL']
  38. del token
  39. COMMENT = N_TOKENS
  40. tok_name[COMMENT] = 'COMMENT'
  41. NL = N_TOKENS + 1
  42. tok_name[NL] = 'NL'
  43. N_TOKENS += 2
  44.  
  45. def group(*choices):
  46.     return '(' + '|'.join(choices) + ')'
  47.  
  48.  
  49. def any(*choices):
  50.     return apply(group, choices) + '*'
  51.  
  52.  
  53. def maybe(*choices):
  54.     return apply(group, choices) + '?'
  55.  
  56. Whitespace = '[ \\f\\t]*'
  57. Comment = '#[^\\r\\n]*'
  58. Ignore = Whitespace + any('\\\\\\r?\\n' + Whitespace) + maybe(Comment)
  59. Name = '[a-zA-Z_]\\w*'
  60. Hexnumber = '0[xX][\\da-fA-F]*[lL]?'
  61. Octnumber = '0[0-7]*[lL]?'
  62. Decnumber = '[1-9]\\d*[lL]?'
  63. Intnumber = group(Hexnumber, Octnumber, Decnumber)
  64. Exponent = '[eE][-+]?\\d+'
  65. Pointfloat = group('\\d+\\.\\d*', '\\.\\d+') + maybe(Exponent)
  66. Expfloat = '\\d+' + Exponent
  67. Floatnumber = group(Pointfloat, Expfloat)
  68. Imagnumber = group('\\d+[jJ]', Floatnumber + '[jJ]')
  69. Number = group(Imagnumber, Floatnumber, Intnumber)
  70. Single = "[^'\\\\]*(?:\\\\.[^'\\\\]*)*'"
  71. Double = '[^"\\\\]*(?:\\\\.[^"\\\\]*)*"'
  72. Single3 = "[^'\\\\]*(?:(?:\\\\.|'(?!''))[^'\\\\]*)*'''"
  73. Double3 = '[^"\\\\]*(?:(?:\\\\.|"(?!""))[^"\\\\]*)*"""'
  74. Triple = group("[uU]?[rR]?'''", '[uU]?[rR]?"""')
  75. String = group("[uU]?[rR]?'[^\\n'\\\\]*(?:\\\\.[^\\n'\\\\]*)*'", '[uU]?[rR]?"[^\\n"\\\\]*(?:\\\\.[^\\n"\\\\]*)*"')
  76. Operator = group('\\*\\*=?', '>>=?', '<<=?', '<>', '!=', '//=?', '[+\\-*/%&|^=<>]=?', '~')
  77. Bracket = '[][(){}]'
  78. Special = group('\\r?\\n', '[:;.,`]')
  79. Funny = group(Operator, Bracket, Special)
  80. PlainToken = group(Number, Funny, String, Name)
  81. Token = Ignore + PlainToken
  82. ContStr = group("[uU]?[rR]?'[^\\n'\\\\]*(?:\\\\.[^\\n'\\\\]*)*" + group("'", '\\\\\\r?\\n'), '[uU]?[rR]?"[^\\n"\\\\]*(?:\\\\.[^\\n"\\\\]*)*' + group('"', '\\\\\\r?\\n'))
  83. PseudoExtras = group('\\\\\\r?\\n', Comment, Triple)
  84. PseudoToken = Whitespace + group(PseudoExtras, Number, Funny, ContStr, Name)
  85. (tokenprog, pseudoprog, single3prog, double3prog) = map(re.compile, (Token, PseudoToken, Single3, Double3))
  86. endprogs = {
  87.     "'": re.compile(Single),
  88.     '"': re.compile(Double),
  89.     "'''": single3prog,
  90.     '"""': double3prog,
  91.     "r'''": single3prog,
  92.     'r"""': double3prog,
  93.     "u'''": single3prog,
  94.     'u"""': double3prog,
  95.     "ur'''": single3prog,
  96.     'ur"""': double3prog,
  97.     "R'''": single3prog,
  98.     'R"""': double3prog,
  99.     "U'''": single3prog,
  100.     'U"""': double3prog,
  101.     "uR'''": single3prog,
  102.     'uR"""': double3prog,
  103.     "Ur'''": single3prog,
  104.     'Ur"""': double3prog,
  105.     "UR'''": single3prog,
  106.     'UR"""': double3prog,
  107.     'r': None,
  108.     'R': None,
  109.     'u': None,
  110.     'U': None }
  111. tabsize = 8
  112.  
  113. class TokenError(Exception):
  114.     pass
  115.  
  116.  
  117. class StopTokenizing(Exception):
  118.     pass
  119.  
  120.  
  121. def printtoken(type, token, .4, .6, line):
  122.     (srow, scol) = .4
  123.     (erow, ecol) = .6
  124.     print '%d,%d-%d,%d:\t%s\t%s' % (srow, scol, erow, ecol, tok_name[type], repr(token))
  125.  
  126.  
  127. def tokenize(readline, tokeneater = printtoken):
  128.     
  129.     try:
  130.         tokenize_loop(readline, tokeneater)
  131.     except StopTokenizing:
  132.         pass
  133.  
  134.  
  135.  
  136. def tokenize_loop(readline, tokeneater):
  137.     for token_info in generate_tokens(readline):
  138.         apply(tokeneater, token_info)
  139.     
  140.  
  141.  
  142. def generate_tokens(readline):
  143.     lnum = parenlev = continued = 0
  144.     (namechars, numchars) = (string.ascii_letters + '_', '0123456789')
  145.     (contstr, needcont) = ('', 0)
  146.     contline = None
  147.     indents = [
  148.         0]
  149.     while 1:
  150.         line = readline()
  151.         lnum = lnum + 1
  152.         (pos, max) = (0, len(line))
  153.         if contstr:
  154.             if not line:
  155.                 raise TokenError, ('EOF in multi-line string', strstart)
  156.             
  157.             endmatch = endprog.match(line)
  158.             if endmatch:
  159.                 pos = end = endmatch.end(0)
  160.                 yield (STRING, contstr + line[:end], strstart, (lnum, end), contline + line)
  161.                 (contstr, needcont) = ('', 0)
  162.                 contline = None
  163.             elif needcont and line[-2:] != '\\\n' and line[-3:] != '\\\r\n':
  164.                 yield (ERRORTOKEN, contstr + line, strstart, (lnum, len(line)), contline)
  165.                 contstr = ''
  166.                 contline = None
  167.                 continue
  168.             else:
  169.                 contstr = contstr + line
  170.                 contline = contline + line
  171.         elif parenlev == 0 and not continued:
  172.             if not line:
  173.                 break
  174.             
  175.             column = 0
  176.             while pos < max:
  177.                 if line[pos] == ' ':
  178.                     column = column + 1
  179.                 elif line[pos] == '\t':
  180.                     column = (column / tabsize + 1) * tabsize
  181.                 elif line[pos] == '\x0c':
  182.                     column = 0
  183.                 else:
  184.                     break
  185.                 pos = pos + 1
  186.             if pos == max:
  187.                 break
  188.             
  189.             if line[pos] in '#\r\n':
  190.                 yield ((NL, COMMENT)[line[pos] == '#'], line[pos:], (lnum, pos), (lnum, len(line)), line)
  191.                 continue
  192.             
  193.             if column > indents[-1]:
  194.                 indents.append(column)
  195.                 yield (INDENT, line[:pos], (lnum, 0), (lnum, pos), line)
  196.             
  197.             while column < indents[-1]:
  198.                 indents = indents[:-1]
  199.                 yield (DEDENT, '', (lnum, pos), (lnum, pos), line)
  200.         elif not line:
  201.             raise TokenError, ('EOF in multi-line statement', (lnum, 0))
  202.         
  203.         continued = 0
  204.         while pos < max:
  205.             pseudomatch = pseudoprog.match(line, pos)
  206.             if pseudomatch:
  207.                 (start, end) = pseudomatch.span(1)
  208.                 (spos, epos, pos) = ((lnum, start), (lnum, end), end)
  209.                 (token, initial) = (line[start:end], line[start])
  210.                 if initial in numchars and initial == '.' and token != '.':
  211.                     yield (NUMBER, token, spos, epos, line)
  212.                 elif initial in '\r\n':
  213.                     if not parenlev > 0 and NL:
  214.                         pass
  215.                     yield (NEWLINE, token, spos, epos, line)
  216.                 elif initial == '#':
  217.                     yield (COMMENT, token, spos, epos, line)
  218.                 elif token in ("'''", '"""', "r'''", 'r"""', "R'''", 'R"""', "u'''", 'u"""', "U'''", 'U"""', "ur'''", 'ur"""', "Ur'''", 'Ur"""', "uR'''", 'uR"""', "UR'''", 'UR"""'):
  219.                     endprog = endprogs[token]
  220.                     endmatch = endprog.match(line, pos)
  221.                     if endmatch:
  222.                         pos = endmatch.end(0)
  223.                         token = line[start:pos]
  224.                         yield (STRING, token, spos, (lnum, pos), line)
  225.                     else:
  226.                         strstart = (lnum, start)
  227.                         contstr = line[start:]
  228.                         contline = line
  229.                         break
  230.                 elif initial in ("'", '"') and token[:2] in ("r'", 'r"', "R'", 'R"', "u'", 'u"', "U'", 'U"') or token[:3] in ("ur'", 'ur"', "Ur'", 'Ur"', "uR'", 'uR"', "UR'", 'UR"'):
  231.                     if token[-1] == '\n':
  232.                         strstart = (lnum, start)
  233.                         if not endprogs[initial] and endprogs[token[1]]:
  234.                             pass
  235.                         endprog = endprogs[token[2]]
  236.                         (contstr, needcont) = (line[start:], 1)
  237.                         contline = line
  238.                         break
  239.                     else:
  240.                         yield (STRING, token, spos, epos, line)
  241.                 elif initial in namechars:
  242.                     yield (NAME, token, spos, epos, line)
  243.                 elif initial == '\\':
  244.                     continued = 1
  245.                 elif initial in '([{':
  246.                     parenlev = parenlev + 1
  247.                 elif initial in ')]}':
  248.                     parenlev = parenlev - 1
  249.                 
  250.                 yield (OP, token, spos, epos, line)
  251.             else:
  252.                 yield (ERRORTOKEN, line[pos], (lnum, pos), (lnum, pos + 1), line)
  253.                 pos = pos + 1
  254.     for indent in indents[1:]:
  255.         yield (DEDENT, '', (lnum, 0), (lnum, 0), '')
  256.     
  257.     yield (ENDMARKER, '', (lnum, 0), (lnum, 0), '')
  258.  
  259. if __name__ == '__main__':
  260.     import sys
  261.     if len(sys.argv) > 1:
  262.         tokenize(open(sys.argv[1]).readline)
  263.     else:
  264.         tokenize(sys.stdin.readline)
  265.  
  266.