codeop.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  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. import warnings
  45. _features = [getattr(__future__, fname)
  46. for fname in __future__.all_feature_names]
  47. __all__ = ["compile_command", "Compile", "CommandCompiler"]
  48. PyCF_DONT_IMPLY_DEDENT = 0x200 # Matches pythonrun.h
  49. def _maybe_compile(compiler, source, filename, symbol):
  50. # Check for source consisting of only blank lines and comments
  51. for line in source.split("\n"):
  52. line = line.strip()
  53. if line and line[0] != '#':
  54. break # Leave it alone
  55. else:
  56. if symbol != "eval":
  57. source = "pass" # Replace it with a 'pass' statement
  58. err = err1 = err2 = None
  59. code = code1 = code2 = None
  60. try:
  61. code = compiler(source, filename, symbol)
  62. except SyntaxError:
  63. pass
  64. # Catch syntax warnings after the first compile
  65. # to emit warnings (SyntaxWarning, DeprecationWarning) at most once.
  66. with warnings.catch_warnings():
  67. warnings.simplefilter("error")
  68. try:
  69. code1 = compiler(source + "\n", filename, symbol)
  70. except SyntaxError as e:
  71. err1 = e
  72. try:
  73. code2 = compiler(source + "\n\n", filename, symbol)
  74. except SyntaxError as e:
  75. err2 = e
  76. try:
  77. if code:
  78. return code
  79. if not code1 and repr(err1) == repr(err2):
  80. raise err1
  81. finally:
  82. err1 = err2 = None
  83. def _compile(source, filename, symbol):
  84. return compile(source, filename, symbol, PyCF_DONT_IMPLY_DEDENT)
  85. def compile_command(source, filename="<input>", symbol="single"):
  86. r"""Compile a command and determine whether it is incomplete.
  87. Arguments:
  88. source -- the source string; may contain \n characters
  89. filename -- optional filename from which source was read; default
  90. "<input>"
  91. symbol -- optional grammar start symbol; "single" (default), "exec"
  92. or "eval"
  93. Return value / exceptions raised:
  94. - Return a code object if the command is complete and valid
  95. - Return None if the command is incomplete
  96. - Raise SyntaxError, ValueError or OverflowError if the command is a
  97. syntax error (OverflowError and ValueError can be produced by
  98. malformed literals).
  99. """
  100. return _maybe_compile(_compile, source, filename, symbol)
  101. class Compile:
  102. """Instances of this class behave much like the built-in compile
  103. function, but if one is used to compile text containing a future
  104. statement, it "remembers" and compiles all subsequent program texts
  105. with the statement in force."""
  106. def __init__(self):
  107. self.flags = PyCF_DONT_IMPLY_DEDENT
  108. def __call__(self, source, filename, symbol):
  109. codeob = compile(source, filename, symbol, self.flags, True)
  110. for feature in _features:
  111. if codeob.co_flags & feature.compiler_flag:
  112. self.flags |= feature.compiler_flag
  113. return codeob
  114. class CommandCompiler:
  115. """Instances of this class have __call__ methods identical in
  116. signature to compile_command; the difference is that if the
  117. instance compiles program text containing a __future__ statement,
  118. the instance 'remembers' and compiles all subsequent program texts
  119. with the statement in force."""
  120. def __init__(self,):
  121. self.compiler = Compile()
  122. def __call__(self, source, filename="<input>", symbol="single"):
  123. r"""Compile a command and determine whether it is incomplete.
  124. Arguments:
  125. source -- the source string; may contain \n characters
  126. filename -- optional filename from which source was read;
  127. default "<input>"
  128. symbol -- optional grammar start symbol; "single" (default) or
  129. "eval"
  130. Return value / exceptions raised:
  131. - Return a code object if the command is complete and valid
  132. - Return None if the command is incomplete
  133. - Raise SyntaxError, ValueError or OverflowError if the command is a
  134. syntax error (OverflowError and ValueError can be produced by
  135. malformed literals).
  136. """
  137. return _maybe_compile(self.compiler, source, filename, symbol)