codeop.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  1. r"""Utilities to compile possibly incomplete Python source code.
  2. This module provides two interfaces, broadly similar to the builtin
  3. function compile(), which take program text, a filename and a 'mode'
  4. and:
  5. - Return code object if the command is complete and valid
  6. - Return None if the command is incomplete
  7. - Raise SyntaxError, ValueError or OverflowError if the command is a
  8. syntax error (OverflowError and ValueError can be produced by
  9. malformed literals).
  10. Approach:
  11. First, check if the source consists entirely of blank lines and
  12. comments; if so, replace it with 'pass', because the built-in
  13. parser doesn't always do the right thing for these.
  14. Compile three times: as is, with \n, and with \n\n appended. If it
  15. compiles as is, it's complete. If it compiles with one \n appended,
  16. we expect more. If it doesn't compile either way, we compare the
  17. error we get when compiling with \n or \n\n appended. If the errors
  18. are the same, the code is broken. But if the errors are different, we
  19. expect more. Not intuitive; not even guaranteed to hold in future
  20. releases; but this matches the compiler's behavior from Python 1.4
  21. through 2.2, at least.
  22. Caveat:
  23. It is possible (but not likely) that the parser stops parsing with a
  24. successful outcome before reaching the end of the source; in this
  25. case, trailing symbols may be ignored instead of causing an error.
  26. For example, a backslash followed by two newlines may be followed by
  27. arbitrary garbage. This will be fixed once the API for the parser is
  28. better.
  29. The two interfaces are:
  30. compile_command(source, filename, symbol):
  31. Compiles a single command in the manner described above.
  32. CommandCompiler():
  33. Instances of this class have __call__ methods identical in
  34. signature to compile_command; the difference is that if the
  35. instance compiles program text containing a __future__ statement,
  36. the instance 'remembers' and compiles all subsequent program texts
  37. with the statement in force.
  38. The module also provides another class:
  39. Compile():
  40. Instances of this class act like the built-in function compile,
  41. but with 'memory' in the sense described above.
  42. """
  43. import __future__
  44. _features = [getattr(__future__, fname)
  45. for fname in __future__.all_feature_names]
  46. __all__ = ["compile_command", "Compile", "CommandCompiler"]
  47. PyCF_DONT_IMPLY_DEDENT = 0x200 # Matches pythonrun.h
  48. def _maybe_compile(compiler, source, filename, symbol):
  49. # Check for source consisting of only blank lines and comments
  50. for line in source.split("\n"):
  51. line = line.strip()
  52. if line and line[0] != '#':
  53. break # Leave it alone
  54. else:
  55. if symbol != "eval":
  56. source = "pass" # Replace it with a 'pass' statement
  57. err = err1 = err2 = None
  58. code = code1 = code2 = None
  59. try:
  60. code = compiler(source, filename, symbol)
  61. except SyntaxError as err:
  62. pass
  63. try:
  64. code1 = compiler(source + "\n", filename, symbol)
  65. except SyntaxError as e:
  66. err1 = e
  67. try:
  68. code2 = compiler(source + "\n\n", filename, symbol)
  69. except SyntaxError as e:
  70. err2 = e
  71. try:
  72. if code:
  73. return code
  74. if not code1 and repr(err1) == repr(err2):
  75. raise err1
  76. finally:
  77. err1 = err2 = None
  78. def _compile(source, filename, symbol):
  79. return compile(source, filename, symbol, PyCF_DONT_IMPLY_DEDENT)
  80. def compile_command(source, filename="<input>", symbol="single"):
  81. r"""Compile a command and determine whether it is incomplete.
  82. Arguments:
  83. source -- the source string; may contain \n characters
  84. filename -- optional filename from which source was read; default
  85. "<input>"
  86. symbol -- optional grammar start symbol; "single" (default) or "eval"
  87. Return value / exceptions raised:
  88. - Return a code object if the command is complete and valid
  89. - Return None if the command is incomplete
  90. - Raise SyntaxError, ValueError or OverflowError if the command is a
  91. syntax error (OverflowError and ValueError can be produced by
  92. malformed literals).
  93. """
  94. return _maybe_compile(_compile, source, filename, symbol)
  95. class Compile:
  96. """Instances of this class behave much like the built-in compile
  97. function, but if one is used to compile text containing a future
  98. statement, it "remembers" and compiles all subsequent program texts
  99. with the statement in force."""
  100. def __init__(self):
  101. self.flags = PyCF_DONT_IMPLY_DEDENT
  102. def __call__(self, source, filename, symbol):
  103. codeob = compile(source, filename, symbol, self.flags, 1)
  104. for feature in _features:
  105. if codeob.co_flags & feature.compiler_flag:
  106. self.flags |= feature.compiler_flag
  107. return codeob
  108. class CommandCompiler:
  109. """Instances of this class have __call__ methods identical in
  110. signature to compile_command; the difference is that if the
  111. instance compiles program text containing a __future__ statement,
  112. the instance 'remembers' and compiles all subsequent program texts
  113. with the statement in force."""
  114. def __init__(self,):
  115. self.compiler = Compile()
  116. def __call__(self, source, filename="<input>", symbol="single"):
  117. r"""Compile a command and determine whether it is incomplete.
  118. Arguments:
  119. source -- the source string; may contain \n characters
  120. filename -- optional filename from which source was read;
  121. default "<input>"
  122. symbol -- optional grammar start symbol; "single" (default) or
  123. "eval"
  124. Return value / exceptions raised:
  125. - Return a code object if the command is complete and valid
  126. - Return None if the command is incomplete
  127. - Raise SyntaxError, ValueError or OverflowError if the command is a
  128. syntax error (OverflowError and ValueError can be produced by
  129. malformed literals).
  130. """
  131. return _maybe_compile(self.compiler, source, filename, symbol)