codeop.py 5.9 KB

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