|
1 | 1 | """Tools for preparing code to be run in the REPL (removing blank lines, |
2 | 2 | etc)""" |
3 | 3 |
|
4 | | -from ..lazyre import LazyReCompile |
| 4 | +from codeop import CommandCompiler |
| 5 | +from typing import Match |
5 | 6 | from itertools import tee, islice, chain |
6 | 7 |
|
| 8 | +from ..lazyre import LazyReCompile |
| 9 | + |
7 | 10 | # TODO specifically catch IndentationErrors instead of any syntax errors |
8 | 11 |
|
9 | 12 | indent_empty_lines_re = LazyReCompile(r"\s*") |
10 | 13 | tabs_to_spaces_re = LazyReCompile(r"^\t+") |
11 | 14 |
|
12 | 15 |
|
13 | | -def indent_empty_lines(s, compiler): |
| 16 | +def indent_empty_lines(s: str, compiler: CommandCompiler) -> str: |
14 | 17 | """Indents blank lines that would otherwise cause early compilation |
15 | 18 |
|
16 | 19 | Only really works if starting on a new line""" |
17 | | - lines = s.split("\n") |
| 20 | + initial_lines = s.split("\n") |
18 | 21 | ends_with_newline = False |
19 | | - if lines and not lines[-1]: |
| 22 | + if initial_lines and not initial_lines[-1]: |
20 | 23 | ends_with_newline = True |
21 | | - lines.pop() |
| 24 | + initial_lines.pop() |
22 | 25 | result_lines = [] |
23 | 26 |
|
24 | | - prevs, lines, nexts = tee(lines, 3) |
| 27 | + prevs, lines, nexts = tee(initial_lines, 3) |
25 | 28 | prevs = chain(("",), prevs) |
26 | 29 | nexts = chain(islice(nexts, 1, None), ("",)) |
27 | 30 |
|
28 | 31 | for p_line, line, n_line in zip(prevs, lines, nexts): |
29 | 32 | if len(line) == 0: |
30 | | - p_indent = indent_empty_lines_re.match(p_line).group() |
31 | | - n_indent = indent_empty_lines_re.match(n_line).group() |
| 33 | + # "\s*" always matches |
| 34 | + p_indent = indent_empty_lines_re.match(p_line).group() # type: ignore |
| 35 | + n_indent = indent_empty_lines_re.match(n_line).group() # type: ignore |
32 | 36 | result_lines.append(min([p_indent, n_indent], key=len) + line) |
33 | 37 | else: |
34 | 38 | result_lines.append(line) |
35 | 39 |
|
36 | 40 | return "\n".join(result_lines) + ("\n" if ends_with_newline else "") |
37 | 41 |
|
38 | 42 |
|
39 | | -def leading_tabs_to_spaces(s): |
40 | | - lines = s.split("\n") |
41 | | - result_lines = [] |
42 | | - |
43 | | - def tab_to_space(m): |
| 43 | +def leading_tabs_to_spaces(s: str) -> str: |
| 44 | + def tab_to_space(m: Match[str]) -> str: |
44 | 45 | return len(m.group()) * 4 * " " |
45 | 46 |
|
46 | | - for line in lines: |
47 | | - result_lines.append(tabs_to_spaces_re.sub(tab_to_space, line)) |
48 | | - return "\n".join(result_lines) |
| 47 | + return "\n".join( |
| 48 | + tabs_to_spaces_re.sub(tab_to_space, line) for line in s.split("\n") |
| 49 | + ) |
49 | 50 |
|
50 | 51 |
|
51 | | -def preprocess(s, compiler): |
| 52 | +def preprocess(s: str, compiler: CommandCompiler) -> str: |
52 | 53 | return indent_empty_lines(leading_tabs_to_spaces(s), compiler) |
0 commit comments