Check input for Python syntax errors.
(self, document: Document)
| 22 | self.get_compiler_flags = get_compiler_flags |
| 23 | |
| 24 | def validate(self, document: Document) -> None: |
| 25 | """ |
| 26 | Check input for Python syntax errors. |
| 27 | """ |
| 28 | text = unindent_code(document.text) |
| 29 | |
| 30 | # When the input starts with Ctrl-Z, always accept. This means EOF in a |
| 31 | # Python REPL. |
| 32 | if text.startswith("\x1a"): |
| 33 | return |
| 34 | |
| 35 | # When the input starts with an exclamation mark. Accept as shell |
| 36 | # command. |
| 37 | if text.lstrip().startswith("!"): |
| 38 | return |
| 39 | |
| 40 | try: |
| 41 | if self.get_compiler_flags: |
| 42 | flags = self.get_compiler_flags() |
| 43 | else: |
| 44 | flags = 0 |
| 45 | |
| 46 | compile(text, "<input>", "exec", flags=flags, dont_inherit=True) |
| 47 | except SyntaxError as e: |
| 48 | # Note, the 'or 1' for offset is required because Python 2.7 |
| 49 | # gives `None` as offset in case of '4=4' as input. (Looks like |
| 50 | # fixed in Python 3.) |
| 51 | # TODO: This is not correct if indentation was removed. |
| 52 | index = document.translate_row_col_to_index( |
| 53 | (e.lineno or 1) - 1, (e.offset or 1) - 1 |
| 54 | ) |
| 55 | raise ValidationError(index, f"Syntax Error: {e}") |
| 56 | except TypeError as e: |
| 57 | # e.g. "compile() expected string without null bytes" |
| 58 | raise ValidationError(0, str(e)) |
| 59 | except ValueError as e: |
| 60 | # In Python 2, compiling "\x9" (an invalid escape sequence) raises |
| 61 | # ValueError instead of SyntaxError. |
| 62 | raise ValidationError(0, f"Syntax Error: {e}") |
nothing calls this directly
no test coverage detected