home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2010 May / maximum-cd-2010-05.iso / DiscContents / boxee-0.9.20.10711.exe / system / python / local / simplejson / decoder.pyo (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2009-11-02  |  10.8 KB  |  385 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyo (Python 2.4)
  3.  
  4. '''Implementation of JSONDecoder
  5. '''
  6. import re
  7. import sys
  8. import struct
  9. from simplejson.scanner import make_scanner
  10.  
  11. try:
  12.     from simplejson._speedups import scanstring as c_scanstring
  13. except ImportError:
  14.     c_scanstring = None
  15.  
  16. __all__ = [
  17.     'JSONDecoder']
  18. FLAGS = re.VERBOSE | re.MULTILINE | re.DOTALL
  19.  
  20. def _floatconstants():
  21.     _BYTES = '7FF80000000000007FF0000000000000'.decode('hex')
  22.     if sys.byteorder != 'big':
  23.         _BYTES = _BYTES[:8][::-1] + _BYTES[8:][::-1]
  24.     
  25.     (nan, inf) = struct.unpack('dd', _BYTES)
  26.     return (nan, inf, -inf)
  27.  
  28. (NaN, PosInf, NegInf) = _floatconstants()
  29.  
  30. def linecol(doc, pos):
  31.     lineno = doc.count('\n', 0, pos) + 1
  32.     if lineno == 1:
  33.         colno = pos
  34.     else:
  35.         colno = pos - doc.rindex('\n', 0, pos)
  36.     return (lineno, colno)
  37.  
  38.  
  39. def errmsg(msg, doc, pos, end = None):
  40.     (lineno, colno) = linecol(doc, pos)
  41.     if end is None:
  42.         fmt = '%s: line %d column %d (char %d)'
  43.         return fmt % (msg, lineno, colno, pos)
  44.     
  45.     (endlineno, endcolno) = linecol(doc, end)
  46.     fmt = '%s: line %d column %d - line %d column %d (char %d - %d)'
  47.     return fmt % (msg, lineno, colno, endlineno, endcolno, pos, end)
  48.  
  49. _CONSTANTS = {
  50.     '-Infinity': NegInf,
  51.     'Infinity': PosInf,
  52.     'NaN': NaN }
  53. STRINGCHUNK = re.compile('(.*?)(["\\\\\\x00-\\x1f])', FLAGS)
  54. BACKSLASH = {
  55.     '"': u'"',
  56.     '\\': u'\\',
  57.     '/': u'/',
  58.     'b': u'\x08',
  59.     'f': u'\x0c',
  60.     'n': u'\n',
  61.     'r': u'\r',
  62.     't': u'\t' }
  63. DEFAULT_ENCODING = 'utf-8'
  64.  
  65. def py_scanstring(s, end, encoding = None, strict = True, _b = BACKSLASH, _m = STRINGCHUNK.match):
  66.     '''Scan the string s for a JSON string. End is the index of the
  67.     character in s after the quote that started the JSON string.
  68.     Unescapes all valid JSON string escape sequences and raises ValueError
  69.     on attempt to decode an invalid string. If strict is False then literal
  70.     control characters are allowed in the string.
  71.     
  72.     Returns a tuple of the decoded string and the index of the character in s
  73.     after the end quote.'''
  74.     if encoding is None:
  75.         encoding = DEFAULT_ENCODING
  76.     
  77.     chunks = []
  78.     _append = chunks.append
  79.     begin = end - 1
  80.     while None:
  81.         chunk = _m(s, end)
  82.         if chunk is None:
  83.             raise ValueError(errmsg('Unterminated string starting at', s, begin))
  84.         
  85.         end = chunk.end()
  86.         (content, terminator) = chunk.groups()
  87.         if content:
  88.             if not isinstance(content, unicode):
  89.                 content = unicode(content, encoding)
  90.             
  91.             _append(content)
  92.         
  93.         if terminator == '"':
  94.             break
  95.         elif terminator != '\\':
  96.             if strict:
  97.                 msg = 'Invalid control character %r at' % (terminator,)
  98.                 raise ValueError(errmsg(msg, s, end))
  99.             else:
  100.                 _append(terminator)
  101.         
  102.         
  103.         try:
  104.             esc = s[end]
  105.         except IndexError:
  106.             raise ValueError(errmsg('Unterminated string starting at', s, begin))
  107.  
  108.         if esc != 'u':
  109.             
  110.             try:
  111.                 char = _b[esc]
  112.             except KeyError:
  113.                 msg = 'Invalid \\escape: ' + repr(esc)
  114.                 raise ValueError(errmsg(msg, s, end))
  115.  
  116.             end += 1
  117.         else:
  118.             esc = s[end + 1:end + 5]
  119.             next_end = end + 5
  120.             if len(esc) != 4:
  121.                 msg = 'Invalid \\uXXXX escape'
  122.                 raise ValueError(errmsg(msg, s, end))
  123.             
  124.             uni = int(esc, 16)
  125.             if uni <= uni:
  126.                 pass
  127.             elif uni <= 56319 and sys.maxunicode > 65535:
  128.                 msg = 'Invalid \\uXXXX\\uXXXX surrogate pair'
  129.                 if not s[end + 5:end + 7] == '\\u':
  130.                     raise ValueError(errmsg(msg, s, end))
  131.                 
  132.                 esc2 = s[end + 7:end + 11]
  133.                 if len(esc2) != 4:
  134.                     raise ValueError(errmsg(msg, s, end))
  135.                 
  136.                 uni2 = int(esc2, 16)
  137.                 uni = 65536 + (uni - 55296 << 10 | uni2 - 56320)
  138.                 next_end += 6
  139.             
  140.             char = unichr(uni)
  141.             end = next_end
  142.     return (u''.join(chunks), end)
  143.  
  144. if not c_scanstring:
  145.     pass
  146. scanstring = py_scanstring
  147. WHITESPACE = re.compile('[ \\t\\n\\r]*', FLAGS)
  148. WHITESPACE_STR = ' \t\n\r'
  149.  
  150. def JSONObject(.0, encoding, strict, scan_once, object_hook, _w = WHITESPACE.match, _ws = WHITESPACE_STR):
  151.     (s, end) = .0
  152.     pairs = { }
  153.     nextchar = s[end:end + 1]
  154.     if nextchar != '"':
  155.         if nextchar in _ws:
  156.             end = _w(s, end).end()
  157.             nextchar = s[end:end + 1]
  158.         
  159.         if nextchar == '}':
  160.             return (pairs, end + 1)
  161.         elif nextchar != '"':
  162.             raise ValueError(errmsg('Expecting property name', s, end))
  163.         
  164.     
  165.     end += 1
  166.     while True:
  167.         (key, end) = scanstring(s, end, encoding, strict)
  168.         if s[end:end + 1] != ':':
  169.             end = _w(s, end).end()
  170.             if s[end:end + 1] != ':':
  171.                 raise ValueError(errmsg('Expecting : delimiter', s, end))
  172.             
  173.         
  174.         end += 1
  175.         
  176.         try:
  177.             if s[end] in _ws:
  178.                 end += 1
  179.                 if s[end] in _ws:
  180.                     end = _w(s, end + 1).end()
  181.                 
  182.         except IndexError:
  183.             pass
  184.  
  185.         
  186.         try:
  187.             (value, end) = scan_once(s, end)
  188.         except StopIteration:
  189.             raise ValueError(errmsg('Expecting object', s, end))
  190.  
  191.         pairs[key] = value
  192.         
  193.         try:
  194.             nextchar = s[end]
  195.             if nextchar in _ws:
  196.                 end = _w(s, end + 1).end()
  197.                 nextchar = s[end]
  198.         except IndexError:
  199.             nextchar = ''
  200.  
  201.         end += 1
  202.         if nextchar == '}':
  203.             break
  204.         elif nextchar != ',':
  205.             raise ValueError(errmsg('Expecting , delimiter', s, end - 1))
  206.         
  207.         
  208.         try:
  209.             nextchar = s[end]
  210.             if nextchar in _ws:
  211.                 end += 1
  212.                 nextchar = s[end]
  213.                 if nextchar in _ws:
  214.                     end = _w(s, end + 1).end()
  215.                     nextchar = s[end]
  216.                 
  217.         except IndexError:
  218.             nextchar = ''
  219.  
  220.         end += 1
  221.         if nextchar != '"':
  222.             raise ValueError(errmsg('Expecting property name', s, end - 1))
  223.             continue
  224.     if object_hook is not None:
  225.         pairs = object_hook(pairs)
  226.     
  227.     return (pairs, end)
  228.  
  229.  
  230. def JSONArray(.0, scan_once, _w = WHITESPACE.match, _ws = WHITESPACE_STR):
  231.     (s, end) = .0
  232.     values = []
  233.     nextchar = s[end:end + 1]
  234.     if nextchar in _ws:
  235.         end = _w(s, end + 1).end()
  236.         nextchar = s[end:end + 1]
  237.     
  238.     if nextchar == ']':
  239.         return (values, end + 1)
  240.     
  241.     _append = values.append
  242.     while True:
  243.         
  244.         try:
  245.             (value, end) = scan_once(s, end)
  246.         except StopIteration:
  247.             raise ValueError(errmsg('Expecting object', s, end))
  248.  
  249.         _append(value)
  250.         nextchar = s[end:end + 1]
  251.         if nextchar in _ws:
  252.             end = _w(s, end + 1).end()
  253.             nextchar = s[end:end + 1]
  254.         
  255.         end += 1
  256.         if nextchar == ']':
  257.             break
  258.         elif nextchar != ',':
  259.             raise ValueError(errmsg('Expecting , delimiter', s, end))
  260.         
  261.         
  262.         try:
  263.             if s[end] in _ws:
  264.                 end += 1
  265.                 if s[end] in _ws:
  266.                     end = _w(s, end + 1).end()
  267.                 
  268.         continue
  269.         except IndexError:
  270.             continue
  271.         
  272.  
  273.         None<EXCEPTION MATCH>IndexError
  274.     return (values, end)
  275.  
  276.  
  277. class JSONDecoder(object):
  278.     '''Simple JSON <http://json.org> decoder
  279.  
  280.     Performs the following translations in decoding by default:
  281.  
  282.     +---------------+-------------------+
  283.     | JSON          | Python            |
  284.     +===============+===================+
  285.     | object        | dict              |
  286.     +---------------+-------------------+
  287.     | array         | list              |
  288.     +---------------+-------------------+
  289.     | string        | unicode           |
  290.     +---------------+-------------------+
  291.     | number (int)  | int, long         |
  292.     +---------------+-------------------+
  293.     | number (real) | float             |
  294.     +---------------+-------------------+
  295.     | true          | True              |
  296.     +---------------+-------------------+
  297.     | false         | False             |
  298.     +---------------+-------------------+
  299.     | null          | None              |
  300.     +---------------+-------------------+
  301.  
  302.     It also understands ``NaN``, ``Infinity``, and ``-Infinity`` as
  303.     their corresponding ``float`` values, which is outside the JSON spec.
  304.  
  305.     '''
  306.     
  307.     def __init__(self, encoding = None, object_hook = None, parse_float = None, parse_int = None, parse_constant = None, strict = True):
  308.         '''``encoding`` determines the encoding used to interpret any ``str``
  309.         objects decoded by this instance (utf-8 by default).  It has no
  310.         effect when decoding ``unicode`` objects.
  311.  
  312.         Note that currently only encodings that are a superset of ASCII work,
  313.         strings of other encodings should be passed in as ``unicode``.
  314.  
  315.         ``object_hook``, if specified, will be called with the result
  316.         of every JSON object decoded and its return value will be used in
  317.         place of the given ``dict``.  This can be used to provide custom
  318.         deserializations (e.g. to support JSON-RPC class hinting).
  319.  
  320.         ``parse_float``, if specified, will be called with the string
  321.         of every JSON float to be decoded. By default this is equivalent to
  322.         float(num_str). This can be used to use another datatype or parser
  323.         for JSON floats (e.g. decimal.Decimal).
  324.  
  325.         ``parse_int``, if specified, will be called with the string
  326.         of every JSON int to be decoded. By default this is equivalent to
  327.         int(num_str). This can be used to use another datatype or parser
  328.         for JSON integers (e.g. float).
  329.  
  330.         ``parse_constant``, if specified, will be called with one of the
  331.         following strings: -Infinity, Infinity, NaN.
  332.         This can be used to raise an exception if invalid JSON numbers
  333.         are encountered.
  334.  
  335.         '''
  336.         self.encoding = encoding
  337.         self.object_hook = object_hook
  338.         if not parse_float:
  339.             pass
  340.         self.parse_float = float
  341.         if not parse_int:
  342.             pass
  343.         self.parse_int = int
  344.         if not parse_constant:
  345.             pass
  346.         self.parse_constant = _CONSTANTS.__getitem__
  347.         self.strict = strict
  348.         self.parse_object = JSONObject
  349.         self.parse_array = JSONArray
  350.         self.parse_string = scanstring
  351.         self.scan_once = make_scanner(self)
  352.  
  353.     
  354.     def decode(self, s, _w = WHITESPACE.match):
  355.         '''Return the Python representation of ``s`` (a ``str`` or ``unicode``
  356.         instance containing a JSON document)
  357.  
  358.         '''
  359.         (obj, end) = self.raw_decode(s, idx = _w(s, 0).end())
  360.         end = _w(s, end).end()
  361.         if end != len(s):
  362.             raise ValueError(errmsg('Extra data', s, end, len(s)))
  363.         
  364.         return obj
  365.  
  366.     
  367.     def raw_decode(self, s, idx = 0):
  368.         '''Decode a JSON document from ``s`` (a ``str`` or ``unicode`` beginning
  369.         with a JSON document) and return a 2-tuple of the Python
  370.         representation and the index in ``s`` where the document ended.
  371.  
  372.         This can be used to decode a JSON document from a string that may
  373.         have extraneous data at the end.
  374.  
  375.         '''
  376.         
  377.         try:
  378.             (obj, end) = self.scan_once(s, idx)
  379.         except StopIteration:
  380.             raise ValueError('No JSON object could be decoded')
  381.  
  382.         return (obj, end)
  383.  
  384.  
  385.