home *** CD-ROM | disk | FTP | other *** search
/ Chip 2011 November / CHIP_2011_11.iso / Programy / Narzedzia / Calibre / calibre-0.8.18.msi / file_262 / tokenize.pyo (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2011-09-09  |  10.1 KB  |  351 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyo (Python 2.7)
  3.  
  4. __author__ = 'Ka-Ping Yee <ping@lfw.org>'
  5. __credits__ = 'GvR, ESR, Tim Peters, Thomas Wouters, Fred Drake, Skip Montanaro, Raymond Hettinger'
  6. import string
  7. import re
  8. from token import *
  9. import token
  10. __all__ = [ x for x in dir(token) if x.startswith('_') ]
  11. __all__ += [
  12.     'COMMENT',
  13.     'tokenize',
  14.     'generate_tokens',
  15.     'NL',
  16.     'untokenize']
  17. del x
  18. del token
  19. COMMENT = N_TOKENS
  20. tok_name[COMMENT] = 'COMMENT'
  21. NL = N_TOKENS + 1
  22. tok_name[NL] = 'NL'
  23. N_TOKENS += 2
  24.  
  25. def group(*choices):
  26.     return '(' + '|'.join(choices) + ')'
  27.  
  28.  
  29. def any(*choices):
  30.     return group(*choices) + '*'
  31.  
  32.  
  33. def maybe(*choices):
  34.     return group(*choices) + '?'
  35.  
  36. Whitespace = '[ \\f\\t]*'
  37. Comment = '#[^\\r\\n]*'
  38. Ignore = Whitespace + any('\\\\\\r?\\n' + Whitespace) + maybe(Comment)
  39. Name = '[a-zA-Z_]\\w*'
  40. Hexnumber = '0[xX][\\da-fA-F]+[lL]?'
  41. Octnumber = '(0[oO][0-7]+)|(0[0-7]*)[lL]?'
  42. Binnumber = '0[bB][01]+[lL]?'
  43. Decnumber = '[1-9]\\d*[lL]?'
  44. Intnumber = group(Hexnumber, Binnumber, Octnumber, Decnumber)
  45. Exponent = '[eE][-+]?\\d+'
  46. Pointfloat = group('\\d+\\.\\d*', '\\.\\d+') + maybe(Exponent)
  47. Expfloat = '\\d+' + Exponent
  48. Floatnumber = group(Pointfloat, Expfloat)
  49. Imagnumber = group('\\d+[jJ]', Floatnumber + '[jJ]')
  50. Number = group(Imagnumber, Floatnumber, Intnumber)
  51. Single = "[^'\\\\]*(?:\\\\.[^'\\\\]*)*'"
  52. Double = '[^"\\\\]*(?:\\\\.[^"\\\\]*)*"'
  53. Single3 = "[^'\\\\]*(?:(?:\\\\.|'(?!''))[^'\\\\]*)*'''"
  54. Double3 = '[^"\\\\]*(?:(?:\\\\.|"(?!""))[^"\\\\]*)*"""'
  55. Triple = group("[uU]?[rR]?'''", '[uU]?[rR]?"""')
  56. String = group("[uU]?[rR]?'[^\\n'\\\\]*(?:\\\\.[^\\n'\\\\]*)*'", '[uU]?[rR]?"[^\\n"\\\\]*(?:\\\\.[^\\n"\\\\]*)*"')
  57. Operator = group('\\*\\*=?', '>>=?', '<<=?', '<>', '!=', '//=?', '[+\\-*/%&|^=<>]=?', '~')
  58. Bracket = '[][(){}]'
  59. Special = group('\\r?\\n', '[:;.,`@]')
  60. Funny = group(Operator, Bracket, Special)
  61. PlainToken = group(Number, Funny, String, Name)
  62. Token = Ignore + PlainToken
  63. ContStr = group("[uU]?[rR]?'[^\\n'\\\\]*(?:\\\\.[^\\n'\\\\]*)*" + group("'", '\\\\\\r?\\n'), '[uU]?[rR]?"[^\\n"\\\\]*(?:\\\\.[^\\n"\\\\]*)*' + group('"', '\\\\\\r?\\n'))
  64. PseudoExtras = group('\\\\\\r?\\n', Comment, Triple)
  65. PseudoToken = Whitespace + group(PseudoExtras, Number, Funny, ContStr, Name)
  66. (tokenprog, pseudoprog, single3prog, double3prog) = map(re.compile, (Token, PseudoToken, Single3, Double3))
  67. endprogs = {
  68.     "'": re.compile(Single),
  69.     '"': re.compile(Double),
  70.     "'''": single3prog,
  71.     '"""': double3prog,
  72.     "r'''": single3prog,
  73.     'r"""': double3prog,
  74.     "u'''": single3prog,
  75.     'u"""': double3prog,
  76.     "ur'''": single3prog,
  77.     'ur"""': double3prog,
  78.     "R'''": single3prog,
  79.     'R"""': double3prog,
  80.     "U'''": single3prog,
  81.     'U"""': double3prog,
  82.     "uR'''": single3prog,
  83.     'uR"""': double3prog,
  84.     "Ur'''": single3prog,
  85.     'Ur"""': double3prog,
  86.     "UR'''": single3prog,
  87.     'UR"""': double3prog,
  88.     "b'''": single3prog,
  89.     'b"""': double3prog,
  90.     "br'''": single3prog,
  91.     'br"""': double3prog,
  92.     "B'''": single3prog,
  93.     'B"""': double3prog,
  94.     "bR'''": single3prog,
  95.     'bR"""': double3prog,
  96.     "Br'''": single3prog,
  97.     'Br"""': double3prog,
  98.     "BR'''": single3prog,
  99.     'BR"""': double3prog,
  100.     'r': None,
  101.     'R': None,
  102.     'u': None,
  103.     'U': None,
  104.     'b': None,
  105.     'B': None }
  106. triple_quoted = { }
  107. for t in ("'''", '"""', "r'''", 'r"""', "R'''", 'R"""', "u'''", 'u"""', "U'''", 'U"""', "ur'''", 'ur"""', "Ur'''", 'Ur"""', "uR'''", 'uR"""', "UR'''", 'UR"""', "b'''", 'b"""', "B'''", 'B"""', "br'''", 'br"""', "Br'''", 'Br"""', "bR'''", 'bR"""', "BR'''", 'BR"""'):
  108.     triple_quoted[t] = t
  109.  
  110. single_quoted = { }
  111. for t in ("'", '"', "r'", 'r"', "R'", 'R"', "u'", 'u"', "U'", 'U"', "ur'", 'ur"', "Ur'", 'Ur"', "uR'", 'uR"', "UR'", 'UR"', "b'", 'b"', "B'", 'B"', "br'", 'br"', "Br'", 'Br"', "bR'", 'bR"', "BR'", 'BR"'):
  112.     single_quoted[t] = t
  113.  
  114. tabsize = 8
  115.  
  116. class TokenError(Exception):
  117.     pass
  118.  
  119.  
  120. class StopTokenizing(Exception):
  121.     pass
  122.  
  123.  
  124. def printtoken(type, token, srow_scol, erow_ecol, line):
  125.     (srow, scol) = srow_scol
  126.     (erow, ecol) = erow_ecol
  127.     print '%d,%d-%d,%d:\t%s\t%s' % (srow, scol, erow, ecol, tok_name[type], repr(token))
  128.  
  129.  
  130. def tokenize(readline, tokeneater = printtoken):
  131.     
  132.     try:
  133.         tokenize_loop(readline, tokeneater)
  134.     except StopTokenizing:
  135.         pass
  136.  
  137.  
  138.  
  139. def tokenize_loop(readline, tokeneater):
  140.     for token_info in generate_tokens(readline):
  141.         tokeneater(*token_info)
  142.     
  143.  
  144.  
  145. class Untokenizer:
  146.     
  147.     def __init__(self):
  148.         self.tokens = []
  149.         self.prev_row = 1
  150.         self.prev_col = 0
  151.  
  152.     
  153.     def add_whitespace(self, start):
  154.         (row, col) = start
  155.         col_offset = col - self.prev_col
  156.         if col_offset:
  157.             self.tokens.append(' ' * col_offset)
  158.  
  159.     
  160.     def untokenize(self, iterable):
  161.         for t in iterable:
  162.             if len(t) == 2:
  163.                 self.compat(t, iterable)
  164.                 break
  165.             (tok_type, token, start, end, line) = t
  166.             self.add_whitespace(start)
  167.             self.tokens.append(token)
  168.             (self.prev_row, self.prev_col) = end
  169.             if tok_type in (NEWLINE, NL):
  170.                 self.prev_row += 1
  171.                 self.prev_col = 0
  172.                 continue
  173.         return ''.join(self.tokens)
  174.  
  175.     
  176.     def compat(self, token, iterable):
  177.         startline = False
  178.         indents = []
  179.         toks_append = self.tokens.append
  180.         (toknum, tokval) = token
  181.         if toknum in (NAME, NUMBER):
  182.             tokval += ' '
  183.         if toknum in (NEWLINE, NL):
  184.             startline = True
  185.         prevstring = False
  186.         for tok in iterable:
  187.             (toknum, tokval) = tok[:2]
  188.             if toknum in (NAME, NUMBER):
  189.                 tokval += ' '
  190.             if toknum == STRING:
  191.                 if prevstring:
  192.                     tokval = ' ' + tokval
  193.                 prevstring = True
  194.             else:
  195.                 prevstring = False
  196.             if toknum == INDENT:
  197.                 indents.append(tokval)
  198.                 continue
  199.             elif toknum == DEDENT:
  200.                 indents.pop()
  201.                 continue
  202.             elif toknum in (NEWLINE, NL):
  203.                 startline = True
  204.             elif startline and indents:
  205.                 toks_append(indents[-1])
  206.                 startline = False
  207.             toks_append(tokval)
  208.         
  209.  
  210.  
  211.  
  212. def untokenize(iterable):
  213.     ut = Untokenizer()
  214.     return ut.untokenize(iterable)
  215.  
  216.  
  217. def generate_tokens(readline):
  218.     lnum = parenlev = continued = 0
  219.     namechars = string.ascii_letters + '_'
  220.     numchars = '0123456789'
  221.     (contstr, needcont) = ('', 0)
  222.     contline = None
  223.     indents = [
  224.         0]
  225.     while None:
  226.         
  227.         try:
  228.             line = readline()
  229.         except StopIteration:
  230.             line = ''
  231.  
  232.         lnum += 1
  233.         pos = 0
  234.         max = len(line)
  235.         if contstr:
  236.             if not line:
  237.                 raise TokenError, ('EOF in multi-line string', strstart)
  238.             endmatch = endprog.match(line)
  239.             if endmatch:
  240.                 pos = end = endmatch.end(0)
  241.                 yield (STRING, contstr + line[:end], strstart, (lnum, end), contline + line)
  242.                 (contstr, needcont) = ('', 0)
  243.                 contline = None
  244.             elif needcont and line[-2:] != '\\\n' and line[-3:] != '\\\r\n':
  245.                 yield (ERRORTOKEN, contstr + line, strstart, (lnum, len(line)), contline)
  246.                 contstr = ''
  247.                 contline = None
  248.                 continue
  249.             else:
  250.                 contstr = contstr + line
  251.                 contline = contline + line
  252.         elif parenlev == 0 and not continued:
  253.             if not line:
  254.                 break
  255.             column = 0
  256.             while pos < max:
  257.                 if line[pos] == ' ':
  258.                     column += 1
  259.                 elif line[pos] == '\t':
  260.                     column = (column // tabsize + 1) * tabsize
  261.                 elif line[pos] == '\x0c':
  262.                     column = 0
  263.                 else:
  264.                     break
  265.                 pos += 1
  266.             if pos == max:
  267.                 break
  268.             if line[pos] in '#\r\n':
  269.                 if line[pos] == '#':
  270.                     comment_token = line[pos:].rstrip('\r\n')
  271.                     nl_pos = pos + len(comment_token)
  272.                     yield (COMMENT, comment_token, (lnum, pos), (lnum, pos + len(comment_token)), line)
  273.                     yield (NL, line[nl_pos:], (lnum, nl_pos), (lnum, len(line)), line)
  274.                     continue
  275.                 yield ((NL, COMMENT)[line[pos] == '#'], line[pos:], (lnum, pos), (lnum, len(line)), line)
  276.                 continue
  277.             if column > indents[-1]:
  278.                 indents.append(column)
  279.                 yield (INDENT, line[:pos], (lnum, 0), (lnum, pos), line)
  280.             while column < indents[-1]:
  281.                 if column not in indents:
  282.                     raise IndentationError('unindent does not match any outer indentation level', ('<tokenize>', lnum, pos, line))
  283.                 indents = indents[:-1]
  284.                 yield (DEDENT, '', (lnum, pos), (lnum, pos), line)
  285.         elif not line:
  286.             raise TokenError, ('EOF in multi-line statement', (lnum, 0))
  287.         continued = 0
  288.         while pos < max:
  289.             pseudomatch = pseudoprog.match(line, pos)
  290.             if pseudomatch:
  291.                 (start, end) = pseudomatch.span(1)
  292.                 spos = (lnum, start)
  293.                 epos = (lnum, end)
  294.                 pos = end
  295.                 token = line[start:end]
  296.                 initial = line[start]
  297.                 if (initial in numchars or initial == '.') and token != '.':
  298.                     yield (NUMBER, token, spos, epos, line)
  299.                 elif initial in '\r\n':
  300.                     yield (NL if parenlev > 0 else NEWLINE, token, spos, epos, line)
  301.                 elif initial == '#':
  302.                     yield (COMMENT, token, spos, epos, line)
  303.                 elif token in triple_quoted:
  304.                     endprog = endprogs[token]
  305.                     endmatch = endprog.match(line, pos)
  306.                     if endmatch:
  307.                         pos = endmatch.end(0)
  308.                         token = line[start:pos]
  309.                         yield (STRING, token, spos, (lnum, pos), line)
  310.                     else:
  311.                         strstart = (lnum, start)
  312.                         contstr = line[start:]
  313.                         contline = line
  314.                         break
  315.                 elif initial in single_quoted and token[:2] in single_quoted or token[:3] in single_quoted:
  316.                     if token[-1] == '\n':
  317.                         strstart = (lnum, start)
  318.                         if not endprogs[initial] and endprogs[token[1]]:
  319.                             pass
  320.                         endprog = endprogs[token[2]]
  321.                         contstr = line[start:]
  322.                         needcont = 1
  323.                         contline = line
  324.                         break
  325.                     else:
  326.                         yield (STRING, token, spos, epos, line)
  327.                 elif initial in namechars:
  328.                     yield (NAME, token, spos, epos, line)
  329.                 elif initial == '\\':
  330.                     continued = 1
  331.                 elif initial in '([{':
  332.                     parenlev += 1
  333.                 elif initial in ')]}':
  334.                     parenlev -= 1
  335.                 yield (OP, token, spos, epos, line)
  336.                 continue
  337.             yield (ERRORTOKEN, line[pos], (lnum, pos), (lnum, pos + 1), line)
  338.             pos += 1
  339.         continue
  340.         for indent in indents[1:]:
  341.             yield (DEDENT, '', (lnum, 0), (lnum, 0), '')
  342.         
  343.     yield (ENDMARKER, '', (lnum, 0), (lnum, 0), '')
  344.  
  345. if __name__ == '__main__':
  346.     import sys
  347.     if len(sys.argv) > 1:
  348.         tokenize(open(sys.argv[1]).readline)
  349.     else:
  350.         tokenize(sys.stdin.readline)
  351.