scanner.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. """JSON token scanner
  2. """
  3. import re
  4. def _import_c_make_scanner():
  5. try:
  6. from simplejson._speedups import make_scanner
  7. return make_scanner
  8. except ImportError:
  9. return None
  10. c_make_scanner = _import_c_make_scanner()
  11. __all__ = ['make_scanner']
  12. NUMBER_RE = re.compile(
  13. r'(-?(?:0|[1-9]\d*))(\.\d+)?([eE][-+]?\d+)?',
  14. (re.VERBOSE | re.MULTILINE | re.DOTALL))
  15. def py_make_scanner(context):
  16. parse_object = context.parse_object
  17. parse_array = context.parse_array
  18. parse_string = context.parse_string
  19. match_number = NUMBER_RE.match
  20. encoding = context.encoding
  21. strict = context.strict
  22. parse_float = context.parse_float
  23. parse_int = context.parse_int
  24. parse_constant = context.parse_constant
  25. object_hook = context.object_hook
  26. object_pairs_hook = context.object_pairs_hook
  27. memo = context.memo
  28. def _scan_once(string, idx):
  29. try:
  30. nextchar = string[idx]
  31. except IndexError:
  32. raise StopIteration
  33. if nextchar == '"':
  34. return parse_string(string, idx + 1, encoding, strict)
  35. elif nextchar == '{':
  36. return parse_object((string, idx + 1), encoding, strict,
  37. _scan_once, object_hook, object_pairs_hook, memo)
  38. elif nextchar == '[':
  39. return parse_array((string, idx + 1), _scan_once)
  40. elif nextchar == 'n' and string[idx:idx + 4] == 'null':
  41. return None, idx + 4
  42. elif nextchar == 't' and string[idx:idx + 4] == 'true':
  43. return True, idx + 4
  44. elif nextchar == 'f' and string[idx:idx + 5] == 'false':
  45. return False, idx + 5
  46. m = match_number(string, idx)
  47. if m is not None:
  48. integer, frac, exp = m.groups()
  49. if frac or exp:
  50. res = parse_float(integer + (frac or '') + (exp or ''))
  51. else:
  52. res = parse_int(integer)
  53. return res, m.end()
  54. elif nextchar == 'N' and string[idx:idx + 3] == 'NaN':
  55. return parse_constant('NaN'), idx + 3
  56. elif nextchar == 'I' and string[idx:idx + 8] == 'Infinity':
  57. return parse_constant('Infinity'), idx + 8
  58. elif nextchar == '-' and string[idx:idx + 9] == '-Infinity':
  59. return parse_constant('-Infinity'), idx + 9
  60. else:
  61. raise StopIteration
  62. def scan_once(string, idx):
  63. try:
  64. return _scan_once(string, idx)
  65. finally:
  66. memo.clear()
  67. return scan_once
  68. make_scanner = c_make_scanner or py_make_scanner