Guido van Rossum | 1557a73 | 1997-07-18 16:57:52 +0000 | [diff] [blame] | 1 | """Utilities dealing with code objects.""" |
| 2 | |
| 3 | def compile_command(source, filename="<input>", symbol="single"): |
| 4 | r"""Compile a command and determine whether it is incomplete. |
| 5 | |
| 6 | Arguments: |
| 7 | |
| 8 | source -- the source string; may contain \n characters |
| 9 | filename -- optional filename from which source was read; default "<input>" |
| 10 | symbol -- optional grammar start symbol; "single" (default) or "eval" |
| 11 | |
| 12 | Return value / exception raised: |
| 13 | |
| 14 | - Return a code object if the command is complete and valid |
| 15 | - Return None if the command is incomplete |
| 16 | - Raise SyntaxError if the command is a syntax error |
| 17 | |
| 18 | Approach: |
| 19 | |
| 20 | Compile three times: as is, with \n, and with \n\n appended. If |
| 21 | it compiles as is, it's complete. If it compiles with one \n |
| 22 | appended, we expect more. If it doesn't compile either way, we |
| 23 | compare the error we get when compiling with \n or \n\n appended. |
| 24 | If the errors are the same, the code is broken. But if the errors |
| 25 | are different, we expect more. Not intuitive; not even guaranteed |
| 26 | to hold in future releases; but this matches the compiler's |
| 27 | behavior in Python 1.4 and 1.5. |
| 28 | |
| 29 | """ |
| 30 | |
| 31 | err = err1 = err2 = None |
| 32 | code = code1 = code2 = None |
| 33 | |
| 34 | try: |
| 35 | code = compile(source, filename, symbol) |
| 36 | except SyntaxError, err: |
| 37 | pass |
| 38 | |
| 39 | try: |
| 40 | code1 = compile(source + "\n", filename, symbol) |
| 41 | except SyntaxError, err1: |
| 42 | pass |
| 43 | |
| 44 | try: |
| 45 | code2 = compile(source + "\n\n", filename, symbol) |
| 46 | except SyntaxError, err2: |
| 47 | pass |
| 48 | |
| 49 | if code: |
| 50 | return code |
| 51 | if not code1 and err1 == err2: |
| 52 | raise SyntaxError, err1 |