blob: 3335f098d4020739b56724ccbcc33046d415ac67 [file] [log] [blame]
Guido van Rossumc41c1a91998-10-22 21:56:15 +00001"""Utility to compile possibly incomplete Python source code."""
2
Skip Montanaroe99d5ea2001-01-20 19:54:20 +00003__all__ = ["compile_command"]
4
Guido van Rossumc41c1a91998-10-22 21:56:15 +00005def compile_command(source, filename="<input>", symbol="single"):
6 r"""Compile a command and determine whether it is incomplete.
7
8 Arguments:
9
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"
13
14 Return value / exceptions raised:
15
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)
20
21 Approach:
22
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.
26
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.
35
36 Caveat:
37
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.
44
45 """
46
47 # Check for source consisting of only blank lines and comments
Eric S. Raymond6b71e742001-02-09 08:56:30 +000048 for line in source.split("\n"):
49 line = line.strip()
Guido van Rossumc41c1a91998-10-22 21:56:15 +000050 if line and line[0] != '#':
51 break # Leave it alone
52 else:
53 source = "pass" # Replace it with a 'pass' statement
54
55 err = err1 = err2 = None
56 code = code1 = code2 = None
57
58 try:
59 code = compile(source, filename, symbol)
60 except SyntaxError, err:
61 pass
62
63 try:
64 code1 = compile(source + "\n", filename, symbol)
65 except SyntaxError, err1:
66 pass
67
68 try:
69 code2 = compile(source + "\n\n", filename, symbol)
70 except SyntaxError, err2:
71 pass
72
73 if code:
74 return code
75 try:
76 e1 = err1.__dict__
77 except AttributeError:
78 e1 = err1
79 try:
80 e2 = err2.__dict__
81 except AttributeError:
82 e2 = err2
83 if not code1 and e1 == e2:
84 raise SyntaxError, err1