1 """Utility to compile possibly incomplete Python source code."""
3 __all__
= ["compile_command"]
5 def compile_command(source
, filename
="<input>", symbol
="single"):
6 r
"""Compile a command and determine whether it is incomplete.
10 source -- the source string; may contain \n characters
11 filename -- optional filename from which source was read; default "<input>"
12 symbol -- optional grammar start symbol; "single" (default) or "eval"
14 Return value / exceptions raised:
16 - Return a code object if the command is complete and valid
17 - Return None if the command is incomplete
18 - Raise SyntaxError or OverflowError if the command is a syntax error
19 (OverflowError if the error is in a numeric constant)
23 First, check if the source consists entirely of blank lines and
24 comments; if so, replace it with 'pass', because the built-in
25 parser doesn't always do the right thing for these.
27 Compile three times: as is, with \n, and with \n\n appended. If
28 it compiles as is, it's complete. If it compiles with one \n
29 appended, we expect more. If it doesn't compile either way, we
30 compare the error we get when compiling with \n or \n\n appended.
31 If the errors are the same, the code is broken. But if the errors
32 are different, we expect more. Not intuitive; not even guaranteed
33 to hold in future releases; but this matches the compiler's
34 behavior from Python 1.4 through 1.5.2, at least.
38 It is possible (but not likely) that the parser stops parsing
39 with a successful outcome before reaching the end of the source;
40 in this case, trailing symbols may be ignored instead of causing an
41 error. For example, a backslash followed by two newlines may be
42 followed by arbitrary garbage. This will be fixed once the API
43 for the parser is better.
47 # Check for source consisting of only blank lines and comments
48 for line
in source
.split("\n"):
50 if line
and line
[0] != '#':
51 break # Leave it alone
53 source
= "pass" # Replace it with a 'pass' statement
55 err
= err1
= err2
= None
56 code
= code1
= code2
= None
59 code
= compile(source
, filename
, symbol
)
60 except SyntaxError, err
:
64 code1
= compile(source
+ "\n", filename
, symbol
)
65 except SyntaxError, err1
:
69 code2
= compile(source
+ "\n\n", filename
, symbol
)
70 except SyntaxError, err2
:
77 except AttributeError:
81 except AttributeError:
83 if not code1
and e1
== e2
:
84 raise SyntaxError, err1