codeop.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  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, err:
  62. pass
  63. try:
  64. code1 = compiler(source + "\n", filename, symbol)
  65. except SyntaxError, err1:
  66. pass
  67. try:
  68. code2 = compiler(source + "\n\n", filename, symbol)
  69. except SyntaxError, err2:
  70. pass
  71. if code:
  72. return code
  73. try:
  74. e1 = err1.__dict__
  75. except AttributeError:
  76. e1 = err1
  77. try:
  78. e2 = err2.__dict__
  79. except AttributeError:
  80. e2 = err2
  81. if not code1 and e1 == e2:
  82. raise SyntaxError, err1
  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) or "eval"
  92. Return value / exceptions raised:
  93. - Return a code object if the command is complete and valid
  94. - Return None if the command is incomplete
  95. - Raise SyntaxError, ValueError or OverflowError if the command is a
  96. syntax error (OverflowError and ValueError can be produced by
  97. malformed literals).
  98. """
  99. return _maybe_compile(_compile, source, filename, symbol)
  100. class Compile:
  101. """Instances of this class behave much like the built-in compile
  102. function, but if one is used to compile text containing a future
  103. statement, it "remembers" and compiles all subsequent program texts
  104. with the statement in force."""
  105. def __init__(self):
  106. self.flags = PyCF_DONT_IMPLY_DEDENT
  107. def __call__(self, source, filename, symbol):
  108. codeob = compile(source, filename, symbol, self.flags, 1)
  109. for feature in _features:
  110. if codeob.co_flags & feature.compiler_flag:
  111. self.flags |= feature.compiler_flag
  112. return codeob
  113. class CommandCompiler:
  114. """Instances of this class have __call__ methods identical in
  115. signature to compile_command; the difference is that if the
  116. instance compiles program text containing a __future__ statement,
  117. the instance 'remembers' and compiles all subsequent program texts
  118. with the statement in force."""
  119. def __init__(self,):
  120. self.compiler = Compile()
  121. def __call__(self, source, filename="<input>", symbol="single"):
  122. r"""Compile a command and determine whether it is incomplete.
  123. Arguments:
  124. source -- the source string; may contain \n characters
  125. filename -- optional filename from which source was read;
  126. default "<input>"
  127. symbol -- optional grammar start symbol; "single" (default) or
  128. "eval"
  129. Return value / exceptions raised:
  130. - Return a code object if the command is complete and valid
  131. - Return None if the command is incomplete
  132. - Raise SyntaxError, ValueError or OverflowError if the command is a
  133. syntax error (OverflowError and ValueError can be produced by
  134. malformed literals).
  135. """
  136. return _maybe_compile(self.compiler, source, filename, symbol)