Show More
@@ -0,0 +1,346 b'' | |||||
|
1 | """Tests for the inputsplitter module. | |||
|
2 | """ | |||
|
3 | #----------------------------------------------------------------------------- | |||
|
4 | # Copyright (C) 2010 The IPython Development Team | |||
|
5 | # | |||
|
6 | # Distributed under the terms of the BSD License. The full license is in | |||
|
7 | # the file COPYING, distributed as part of this software. | |||
|
8 | #----------------------------------------------------------------------------- | |||
|
9 | ||||
|
10 | #----------------------------------------------------------------------------- | |||
|
11 | # Imports | |||
|
12 | #----------------------------------------------------------------------------- | |||
|
13 | # stdlib | |||
|
14 | import unittest | |||
|
15 | ||||
|
16 | # Third party | |||
|
17 | import nose.tools as nt | |||
|
18 | ||||
|
19 | # Our own | |||
|
20 | from IPython.core import inputsplitter as isp | |||
|
21 | ||||
|
22 | #----------------------------------------------------------------------------- | |||
|
23 | # Semi-complete examples (also used as tests) | |||
|
24 | #----------------------------------------------------------------------------- | |||
|
25 | def mini_interactive_loop(raw_input): | |||
|
26 | """Minimal example of the logic of an interactive interpreter loop. | |||
|
27 | ||||
|
28 | This serves as an example, and it is used by the test system with a fake | |||
|
29 | raw_input that simulates interactive input.""" | |||
|
30 | ||||
|
31 | from IPython.core.inputsplitter import InputSplitter | |||
|
32 | ||||
|
33 | isp = InputSplitter() | |||
|
34 | # In practice, this input loop would be wrapped in an outside loop to read | |||
|
35 | # input indefinitely, until some exit/quit command was issued. Here we | |||
|
36 | # only illustrate the basic inner loop. | |||
|
37 | while isp.push_accepts_more(): | |||
|
38 | indent = ' '*isp.indent_spaces | |||
|
39 | prompt = '>>> ' + indent | |||
|
40 | line = indent + raw_input(prompt) | |||
|
41 | isp.push(line) | |||
|
42 | ||||
|
43 | # Here we just return input so we can use it in a test suite, but a real | |||
|
44 | # interpreter would instead send it for execution somewhere. | |||
|
45 | src = isp.source_reset() | |||
|
46 | print 'Input source was:\n', src | |||
|
47 | return src | |||
|
48 | ||||
|
49 | #----------------------------------------------------------------------------- | |||
|
50 | # Test utilities, just for local use | |||
|
51 | #----------------------------------------------------------------------------- | |||
|
52 | ||||
|
53 | def assemble(block): | |||
|
54 | """Assemble a block into multi-line sub-blocks.""" | |||
|
55 | return ['\n'.join(sub_block)+'\n' for sub_block in block] | |||
|
56 | ||||
|
57 | ||||
|
58 | def pseudo_input(lines): | |||
|
59 | """Return a function that acts like raw_input but feeds the input list.""" | |||
|
60 | ilines = iter(lines) | |||
|
61 | def raw_in(prompt): | |||
|
62 | try: | |||
|
63 | return next(ilines) | |||
|
64 | except StopIteration: | |||
|
65 | return '' | |||
|
66 | return raw_in | |||
|
67 | ||||
|
68 | #----------------------------------------------------------------------------- | |||
|
69 | # Tests | |||
|
70 | #----------------------------------------------------------------------------- | |||
|
71 | def test_spaces(): | |||
|
72 | tests = [('', 0), | |||
|
73 | (' ', 1), | |||
|
74 | ('\n', 0), | |||
|
75 | (' \n', 1), | |||
|
76 | ('x', 0), | |||
|
77 | (' x', 1), | |||
|
78 | (' x',2), | |||
|
79 | (' x',4), | |||
|
80 | # Note: tabs are counted as a single whitespace! | |||
|
81 | ('\tx', 1), | |||
|
82 | ('\t x', 2), | |||
|
83 | ] | |||
|
84 | ||||
|
85 | for s, nsp in tests: | |||
|
86 | nt.assert_equal(isp.num_ini_spaces(s), nsp) | |||
|
87 | ||||
|
88 | ||||
|
89 | def test_remove_comments(): | |||
|
90 | tests = [('text', 'text'), | |||
|
91 | ('text # comment', 'text '), | |||
|
92 | ('text # comment\n', 'text \n'), | |||
|
93 | ('text # comment \n', 'text \n'), | |||
|
94 | ('line # c \nline\n','line \nline\n'), | |||
|
95 | ('line # c \nline#c2 \nline\nline #c\n\n', | |||
|
96 | 'line \nline\nline\nline \n\n'), | |||
|
97 | ] | |||
|
98 | ||||
|
99 | for inp, out in tests: | |||
|
100 | nt.assert_equal(isp.remove_comments(inp), out) | |||
|
101 | ||||
|
102 | ||||
|
103 | def test_get_input_encoding(): | |||
|
104 | encoding = isp.get_input_encoding() | |||
|
105 | nt.assert_true(isinstance(encoding, basestring)) | |||
|
106 | # simple-minded check that at least encoding a simple string works with the | |||
|
107 | # encoding we got. | |||
|
108 | nt.assert_equal('test'.encode(encoding), 'test') | |||
|
109 | ||||
|
110 | ||||
|
111 | class InputSplitterTestCase(unittest.TestCase): | |||
|
112 | def setUp(self): | |||
|
113 | self.isp = isp.InputSplitter() | |||
|
114 | ||||
|
115 | def test_reset(self): | |||
|
116 | isp = self.isp | |||
|
117 | isp.push('x=1') | |||
|
118 | isp.reset() | |||
|
119 | self.assertEqual(isp._buffer, []) | |||
|
120 | self.assertEqual(isp.indent_spaces, 0) | |||
|
121 | self.assertEqual(isp.source, '') | |||
|
122 | self.assertEqual(isp.code, None) | |||
|
123 | self.assertEqual(isp._is_complete, False) | |||
|
124 | ||||
|
125 | def test_source(self): | |||
|
126 | self.isp._store('1') | |||
|
127 | self.isp._store('2') | |||
|
128 | self.assertEqual(self.isp.source, '1\n2\n') | |||
|
129 | self.assertTrue(len(self.isp._buffer)>0) | |||
|
130 | self.assertEqual(self.isp.source_reset(), '1\n2\n') | |||
|
131 | self.assertEqual(self.isp._buffer, []) | |||
|
132 | self.assertEqual(self.isp.source, '') | |||
|
133 | ||||
|
134 | def test_indent(self): | |||
|
135 | isp = self.isp # shorthand | |||
|
136 | isp.push('x=1') | |||
|
137 | self.assertEqual(isp.indent_spaces, 0) | |||
|
138 | isp.push('if 1:\n x=1') | |||
|
139 | self.assertEqual(isp.indent_spaces, 4) | |||
|
140 | isp.push('y=2\n') | |||
|
141 | self.assertEqual(isp.indent_spaces, 0) | |||
|
142 | isp.push('if 1:') | |||
|
143 | self.assertEqual(isp.indent_spaces, 4) | |||
|
144 | isp.push(' x=1') | |||
|
145 | self.assertEqual(isp.indent_spaces, 4) | |||
|
146 | # Blank lines shouldn't change the indent level | |||
|
147 | isp.push(' '*2) | |||
|
148 | self.assertEqual(isp.indent_spaces, 4) | |||
|
149 | ||||
|
150 | def test_indent2(self): | |||
|
151 | isp = self.isp | |||
|
152 | # When a multiline statement contains parens or multiline strings, we | |||
|
153 | # shouldn't get confused. | |||
|
154 | isp.push("if 1:") | |||
|
155 | isp.push(" x = (1+\n 2)") | |||
|
156 | self.assertEqual(isp.indent_spaces, 4) | |||
|
157 | ||||
|
158 | def test_dedent(self): | |||
|
159 | isp = self.isp # shorthand | |||
|
160 | isp.push('if 1:') | |||
|
161 | self.assertEqual(isp.indent_spaces, 4) | |||
|
162 | isp.push(' pass') | |||
|
163 | self.assertEqual(isp.indent_spaces, 0) | |||
|
164 | ||||
|
165 | def test_push(self): | |||
|
166 | isp = self.isp | |||
|
167 | self.assertTrue(isp.push('x=1')) | |||
|
168 | ||||
|
169 | def test_push2(self): | |||
|
170 | isp = self.isp | |||
|
171 | self.assertFalse(isp.push('if 1:')) | |||
|
172 | for line in [' x=1', '# a comment', ' y=2']: | |||
|
173 | self.assertTrue(isp.push(line)) | |||
|
174 | ||||
|
175 | def test_push3(self): | |||
|
176 | """Test input with leading whitespace""" | |||
|
177 | isp = self.isp | |||
|
178 | isp.push(' x=1') | |||
|
179 | isp.push(' y=2') | |||
|
180 | self.assertEqual(isp.source, 'if 1:\n x=1\n y=2\n') | |||
|
181 | ||||
|
182 | def test_replace_mode(self): | |||
|
183 | isp = self.isp | |||
|
184 | isp.input_mode = 'replace' | |||
|
185 | isp.push('x=1') | |||
|
186 | self.assertEqual(isp.source, 'x=1\n') | |||
|
187 | isp.push('x=2') | |||
|
188 | self.assertEqual(isp.source, 'x=2\n') | |||
|
189 | ||||
|
190 | def test_push_accepts_more(self): | |||
|
191 | isp = self.isp | |||
|
192 | isp.push('x=1') | |||
|
193 | self.assertFalse(isp.push_accepts_more()) | |||
|
194 | ||||
|
195 | def test_push_accepts_more2(self): | |||
|
196 | isp = self.isp | |||
|
197 | isp.push('if 1:') | |||
|
198 | self.assertTrue(isp.push_accepts_more()) | |||
|
199 | isp.push(' x=1') | |||
|
200 | self.assertTrue(isp.push_accepts_more()) | |||
|
201 | isp.push('') | |||
|
202 | self.assertFalse(isp.push_accepts_more()) | |||
|
203 | ||||
|
204 | def test_push_accepts_more3(self): | |||
|
205 | isp = self.isp | |||
|
206 | isp.push("x = (2+\n3)") | |||
|
207 | self.assertFalse(isp.push_accepts_more()) | |||
|
208 | ||||
|
209 | def test_push_accepts_more4(self): | |||
|
210 | isp = self.isp | |||
|
211 | # When a multiline statement contains parens or multiline strings, we | |||
|
212 | # shouldn't get confused. | |||
|
213 | # FIXME: we should be able to better handle de-dents in statements like | |||
|
214 | # multiline strings and multiline expressions (continued with \ or | |||
|
215 | # parens). Right now we aren't handling the indentation tracking quite | |||
|
216 | # correctly with this, though in practice it may not be too much of a | |||
|
217 | # problem. We'll need to see. | |||
|
218 | isp.push("if 1:") | |||
|
219 | isp.push(" x = (2+") | |||
|
220 | isp.push(" 3)") | |||
|
221 | self.assertTrue(isp.push_accepts_more()) | |||
|
222 | isp.push(" y = 3") | |||
|
223 | self.assertTrue(isp.push_accepts_more()) | |||
|
224 | isp.push('') | |||
|
225 | self.assertFalse(isp.push_accepts_more()) | |||
|
226 | ||||
|
227 | def test_syntax_error(self): | |||
|
228 | isp = self.isp | |||
|
229 | # Syntax errors immediately produce a 'ready' block, so the invalid | |||
|
230 | # Python can be sent to the kernel for evaluation with possible ipython | |||
|
231 | # special-syntax conversion. | |||
|
232 | isp.push('run foo') | |||
|
233 | self.assertFalse(isp.push_accepts_more()) | |||
|
234 | ||||
|
235 | def check_split(self, block_lines, compile=True): | |||
|
236 | blocks = assemble(block_lines) | |||
|
237 | lines = ''.join(blocks) | |||
|
238 | oblock = self.isp.split_blocks(lines) | |||
|
239 | self.assertEqual(oblock, blocks) | |||
|
240 | if compile: | |||
|
241 | for block in blocks: | |||
|
242 | self.isp._compile(block) | |||
|
243 | ||||
|
244 | def test_split(self): | |||
|
245 | # All blocks of input we want to test in a list. The format for each | |||
|
246 | # block is a list of lists, with each inner lists consisting of all the | |||
|
247 | # lines (as single-lines) that should make up a sub-block. | |||
|
248 | ||||
|
249 | # Note: do NOT put here sub-blocks that don't compile, as the | |||
|
250 | # check_split() routine makes a final verification pass to check that | |||
|
251 | # each sub_block, as returned by split_blocks(), does compile | |||
|
252 | # correctly. | |||
|
253 | all_blocks = [ [['x=1']], | |||
|
254 | ||||
|
255 | [['x=1'], | |||
|
256 | ['y=2']], | |||
|
257 | ||||
|
258 | [['x=1'], | |||
|
259 | ['# a comment'], | |||
|
260 | ['y=11']], | |||
|
261 | ||||
|
262 | [['if 1:', | |||
|
263 | ' x=1'], | |||
|
264 | ['y=3']], | |||
|
265 | ||||
|
266 | [['def f(x):', | |||
|
267 | ' return x'], | |||
|
268 | ['x=1']], | |||
|
269 | ||||
|
270 | [['def f(x):', | |||
|
271 | ' x+=1', | |||
|
272 | ' ', | |||
|
273 | ' return x'], | |||
|
274 | ['x=1']], | |||
|
275 | ||||
|
276 | [['def f(x):', | |||
|
277 | ' if x>0:', | |||
|
278 | ' y=1', | |||
|
279 | ' # a comment', | |||
|
280 | ' else:', | |||
|
281 | ' y=4', | |||
|
282 | ' ', | |||
|
283 | ' return y'], | |||
|
284 | ['x=1'], | |||
|
285 | ['if 1:', | |||
|
286 | ' y=11'] ], | |||
|
287 | ||||
|
288 | [['for i in range(10):' | |||
|
289 | ' x=i**2']], | |||
|
290 | ||||
|
291 | [['for i in range(10):' | |||
|
292 | ' x=i**2'], | |||
|
293 | ['z = 1']], | |||
|
294 | ] | |||
|
295 | for block_lines in all_blocks: | |||
|
296 | self.check_split(block_lines) | |||
|
297 | ||||
|
298 | def test_split_syntax_errors(self): | |||
|
299 | # Block splitting with invalid syntax | |||
|
300 | all_blocks = [ [['a syntax error']], | |||
|
301 | ||||
|
302 | [['x=1'], | |||
|
303 | ['a syntax error']], | |||
|
304 | ||||
|
305 | [['for i in range(10):' | |||
|
306 | ' an error']], | |||
|
307 | ||||
|
308 | ] | |||
|
309 | for block_lines in all_blocks: | |||
|
310 | self.check_split(block_lines, compile=False) | |||
|
311 | ||||
|
312 | ||||
|
313 | class InteractiveLoopTestCase(unittest.TestCase): | |||
|
314 | """Tests for an interactive loop like a python shell. | |||
|
315 | """ | |||
|
316 | def check_ns(self, lines, ns): | |||
|
317 | """Validate that the given input lines produce the resulting namespace. | |||
|
318 | ||||
|
319 | Note: the input lines are given exactly as they would be typed in an | |||
|
320 | auto-indenting environment, as mini_interactive_loop above already does | |||
|
321 | auto-indenting and prepends spaces to the input. | |||
|
322 | """ | |||
|
323 | src = mini_interactive_loop(pseudo_input(lines)) | |||
|
324 | test_ns = {} | |||
|
325 | exec src in test_ns | |||
|
326 | # We can't check that the provided ns is identical to the test_ns, | |||
|
327 | # because Python fills test_ns with extra keys (copyright, etc). But | |||
|
328 | # we can check that the given dict is *contained* in test_ns | |||
|
329 | for k,v in ns.items(): | |||
|
330 | self.assertEqual(test_ns[k], v) | |||
|
331 | ||||
|
332 | def test_simple(self): | |||
|
333 | self.check_ns(['x=1'], dict(x=1)) | |||
|
334 | ||||
|
335 | def test_simple2(self): | |||
|
336 | self.check_ns(['if 1:', 'x=2'], dict(x=2)) | |||
|
337 | ||||
|
338 | def test_xy(self): | |||
|
339 | self.check_ns(['x=1; y=2'], dict(x=1, y=2)) | |||
|
340 | ||||
|
341 | def test_abc(self): | |||
|
342 | self.check_ns(['if 1:','a=1','b=2','c=3'], dict(a=1, b=2, c=3)) | |||
|
343 | ||||
|
344 | def test_multi(self): | |||
|
345 | self.check_ns(['x =(1+','1+','2)'], dict(x=4)) | |||
|
346 |
@@ -1,12 +1,11 b'' | |||||
1 | """Analysis of text input into executable blocks. |
|
1 | """Analysis of text input into executable blocks. | |
2 |
|
2 | |||
3 | This is a simple example of how an interactive terminal-based client can use |
|
3 | The main class in this module, :class:`InputSplitter`, is designed to break | |
4 | this tool:: |
|
4 | input from either interactive, line-by-line environments or block-based ones, | |
|
5 | into standalone blocks that can be executed by Python as 'single' statements | |||
|
6 | (thus triggering sys.displayhook). | |||
5 |
|
7 | |||
6 | bb = BlockBreaker() |
|
8 | For more details, see the class docstring below. | |
7 | while not bb.interactive_block_ready(): |
|
|||
8 | bb.push(raw_input('>>> ')) |
|
|||
9 | print 'Input source was:\n', bb.source, |
|
|||
10 | """ |
|
9 | """ | |
11 | #----------------------------------------------------------------------------- |
|
10 | #----------------------------------------------------------------------------- | |
12 | # Copyright (C) 2010 The IPython Development Team |
|
11 | # Copyright (C) 2010 The IPython Development Team | |
@@ -43,6 +42,10 b' def num_ini_spaces(s):' | |||||
43 | Parameters |
|
42 | Parameters | |
44 | ---------- |
|
43 | ---------- | |
45 | s : string |
|
44 | s : string | |
|
45 | ||||
|
46 | Returns | |||
|
47 | ------- | |||
|
48 | n : int | |||
46 | """ |
|
49 | """ | |
47 |
|
50 | |||
48 | ini_spaces = ini_spaces_re.match(s) |
|
51 | ini_spaces = ini_spaces_re.match(s) | |
@@ -72,7 +75,6 b' def remove_comments(src):' | |||||
72 |
|
75 | |||
73 | def get_input_encoding(): |
|
76 | def get_input_encoding(): | |
74 | """Return the default standard input encoding.""" |
|
77 | """Return the default standard input encoding.""" | |
75 |
|
||||
76 | # There are strange environments for which sys.stdin.encoding is None. We |
|
78 | # There are strange environments for which sys.stdin.encoding is None. We | |
77 | # ensure that a valid encoding is returned. |
|
79 | # ensure that a valid encoding is returned. | |
78 | encoding = getattr(sys.stdin, 'encoding', None) |
|
80 | encoding = getattr(sys.stdin, 'encoding', None) | |
@@ -84,29 +86,64 b' def get_input_encoding():' | |||||
84 | # Classes and functions |
|
86 | # Classes and functions | |
85 | #----------------------------------------------------------------------------- |
|
87 | #----------------------------------------------------------------------------- | |
86 |
|
88 | |||
87 |
class |
|
89 | class InputSplitter(object): | |
88 | # Command compiler |
|
90 | """An object that can split Python source input in executable blocks. | |
89 | compile = None |
|
91 | ||
90 | # Number of spaces of indentation |
|
92 | This object is designed to be used in one of two basic modes: | |
|
93 | ||||
|
94 | 1. By feeding it python source line-by-line, using :meth:`push`. In this | |||
|
95 | mode, it will return on each push whether the currently pushed code | |||
|
96 | could be executed already. In addition, it provides a method called | |||
|
97 | :meth:`push_accepts_more` that can be used to query whether more input | |||
|
98 | can be pushed into a single interactive block. | |||
|
99 | ||||
|
100 | 2. By calling :meth:`split_blocks` with a single, multiline Python string, | |||
|
101 | that is then split into blocks each of which can be executed | |||
|
102 | interactively as a single statement. | |||
|
103 | ||||
|
104 | This is a simple example of how an interactive terminal-based client can use | |||
|
105 | this tool:: | |||
|
106 | ||||
|
107 | isp = InputSplitter() | |||
|
108 | while isp.push_accepts_more(): | |||
|
109 | indent = ' '*isp.indent_spaces | |||
|
110 | prompt = '>>> ' + indent | |||
|
111 | line = indent + raw_input(prompt) | |||
|
112 | isp.push(line) | |||
|
113 | print 'Input source was:\n', isp.source_reset(), | |||
|
114 | """ | |||
|
115 | # Number of spaces of indentation computed from input that has been pushed | |||
|
116 | # so far. This is the attributes callers should query to get the current | |||
|
117 | # indentation level, in order to provide auto-indent facilities. | |||
91 | indent_spaces = 0 |
|
118 | indent_spaces = 0 | |
92 | # String, indicating the default input encoding |
|
119 | # String, indicating the default input encoding. It is computed by default | |
|
120 | # at initialization time via get_input_encoding(), but it can be reset by a | |||
|
121 | # client with specific knowledge of the encoding. | |||
93 | encoding = '' |
|
122 | encoding = '' | |
94 | # String where the current full source input is stored, properly encoded |
|
123 | # String where the current full source input is stored, properly encoded. | |
|
124 | # Reading this attribute is the normal way of querying the currently pushed | |||
|
125 | # source code, that has been properly encoded. | |||
95 | source = '' |
|
126 | source = '' | |
96 | # Code object corresponding to the current source |
|
127 | # Code object corresponding to the current source. It is automatically | |
|
128 | # synced to the source, so it can be queried at any time to obtain the code | |||
|
129 | # object; it will be None if the source doesn't compile to valid Python. | |||
97 | code = None |
|
130 | code = None | |
98 | # Boolean indicating whether the current block is complete |
|
|||
99 | is_complete = None |
|
|||
100 | # Input mode |
|
131 | # Input mode | |
101 | input_mode = 'append' |
|
132 | input_mode = 'append' | |
102 |
|
133 | |||
103 | # Private attributes |
|
134 | # Private attributes | |
104 |
|
135 | |||
105 | # List |
|
136 | # List with lines of input accumulated so far | |
106 | _buffer = None |
|
137 | _buffer = None | |
|
138 | # Command compiler | |||
|
139 | _compile = None | |||
|
140 | # Mark when input has changed indentation all the way back to flush-left | |||
|
141 | _full_dedent = False | |||
|
142 | # Boolean indicating whether the current block is complete | |||
|
143 | _is_complete = None | |||
107 |
|
144 | |||
108 | def __init__(self, input_mode=None): |
|
145 | def __init__(self, input_mode=None): | |
109 |
"""Create a new |
|
146 | """Create a new InputSplitter instance. | |
110 |
|
147 | |||
111 | Parameters |
|
148 | Parameters | |
112 | ---------- |
|
149 | ---------- | |
@@ -122,9 +159,9 b' class BlockBreaker(object):' | |||||
122 | while block-oriented ones will want to use 'replace'. |
|
159 | while block-oriented ones will want to use 'replace'. | |
123 | """ |
|
160 | """ | |
124 | self._buffer = [] |
|
161 | self._buffer = [] | |
125 | self.compile = codeop.CommandCompiler() |
|
162 | self._compile = codeop.CommandCompiler() | |
126 | self.encoding = get_input_encoding() |
|
163 | self.encoding = get_input_encoding() | |
127 |
self.input_mode = |
|
164 | self.input_mode = InputSplitter.input_mode if input_mode is None \ | |
128 | else input_mode |
|
165 | else input_mode | |
129 |
|
166 | |||
130 | def reset(self): |
|
167 | def reset(self): | |
@@ -133,6 +170,8 b' class BlockBreaker(object):' | |||||
133 | self._buffer[:] = [] |
|
170 | self._buffer[:] = [] | |
134 | self.source = '' |
|
171 | self.source = '' | |
135 | self.code = None |
|
172 | self.code = None | |
|
173 | self._is_complete = False | |||
|
174 | self._full_dedent = False | |||
136 |
|
175 | |||
137 | def source_reset(self): |
|
176 | def source_reset(self): | |
138 | """Return the input source and perform a full reset. |
|
177 | """Return the input source and perform a full reset. | |
@@ -147,7 +186,8 b' class BlockBreaker(object):' | |||||
147 | This stores the given lines and returns a status code indicating |
|
186 | This stores the given lines and returns a status code indicating | |
148 | whether the code forms a complete Python block or not. |
|
187 | whether the code forms a complete Python block or not. | |
149 |
|
188 | |||
150 |
Any exceptions generated in compilation are allowed |
|
189 | Any exceptions generated in compilation are swallowed, but if an | |
|
190 | exception was produced, the method returns True. | |||
151 |
|
191 | |||
152 | Parameters |
|
192 | Parameters | |
153 | ---------- |
|
193 | ---------- | |
@@ -159,8 +199,8 b' class BlockBreaker(object):' | |||||
159 | is_complete : boolean |
|
199 | is_complete : boolean | |
160 | True if the current input source (the result of the current input |
|
200 | True if the current input source (the result of the current input | |
161 | plus prior inputs) forms a complete Python execution block. Note that |
|
201 | plus prior inputs) forms a complete Python execution block. Note that | |
162 |
this value is also stored as a |
|
202 | this value is also stored as a private attribute (_is_complete), so it | |
163 | time. |
|
203 | can be queried at any time. | |
164 | """ |
|
204 | """ | |
165 | if self.input_mode == 'replace': |
|
205 | if self.input_mode == 'replace': | |
166 | self.reset() |
|
206 | self.reset() | |
@@ -175,34 +215,37 b' class BlockBreaker(object):' | |||||
175 | self._store(lines) |
|
215 | self._store(lines) | |
176 | source = self.source |
|
216 | source = self.source | |
177 |
|
217 | |||
178 | # Before calling compile(), reset the code object to None so that if an |
|
218 | # Before calling _compile(), reset the code object to None so that if an | |
179 | # exception is raised in compilation, we don't mislead by having |
|
219 | # exception is raised in compilation, we don't mislead by having | |
180 | # inconsistent code/source attributes. |
|
220 | # inconsistent code/source attributes. | |
181 | self.code, self.is_complete = None, None |
|
221 | self.code, self._is_complete = None, None | |
|
222 | ||||
|
223 | self._update_indent(lines) | |||
182 | try: |
|
224 | try: | |
183 | self.code = self.compile(source) |
|
225 | self.code = self._compile(source) | |
184 | # Invalid syntax can produce any of a number of different errors from |
|
226 | # Invalid syntax can produce any of a number of different errors from | |
185 | # inside the compiler, so we have to catch them all. Syntax errors |
|
227 | # inside the compiler, so we have to catch them all. Syntax errors | |
186 | # immediately produce a 'ready' block, so the invalid Python can be |
|
228 | # immediately produce a 'ready' block, so the invalid Python can be | |
187 | # sent to the kernel for evaluation with possible ipython |
|
229 | # sent to the kernel for evaluation with possible ipython | |
188 | # special-syntax conversion. |
|
230 | # special-syntax conversion. | |
189 |
except (SyntaxError, OverflowError, ValueError, TypeError, |
|
231 | except (SyntaxError, OverflowError, ValueError, TypeError, | |
190 | self.is_complete = True |
|
232 | MemoryError): | |
|
233 | self._is_complete = True | |||
191 | else: |
|
234 | else: | |
192 | # Compilation didn't produce any exceptions (though it may not have |
|
235 | # Compilation didn't produce any exceptions (though it may not have | |
193 | # given a complete code object) |
|
236 | # given a complete code object) | |
194 | self.is_complete = self.code is not None |
|
237 | self._is_complete = self.code is not None | |
195 | self._update_indent(lines) |
|
|||
196 |
|
238 | |||
197 | return self.is_complete |
|
239 | return self._is_complete | |
198 |
|
240 | |||
199 |
def |
|
241 | def push_accepts_more(self): | |
200 |
"""Return whether a block of interactive input |
|
242 | """Return whether a block of interactive input can accept more input. | |
201 |
|
243 | |||
202 | This method is meant to be used by line-oriented frontends, who need to |
|
244 | This method is meant to be used by line-oriented frontends, who need to | |
203 | guess whether a block is complete or not based solely on prior and |
|
245 | guess whether a block is complete or not based solely on prior and | |
204 |
current input lines. The |
|
246 | current input lines. The InputSplitter considers it has a complete | |
205 | interactive block when *all* of the following are true: |
|
247 | interactive block and will not accept more input only when either a | |
|
248 | SyntaxError is raised, or *all* of the following are true: | |||
206 |
|
249 | |||
207 | 1. The input compiles to a complete statement. |
|
250 | 1. The input compiles to a complete statement. | |
208 |
|
251 | |||
@@ -218,40 +261,147 b' class BlockBreaker(object):' | |||||
218 |
|
261 | |||
219 | Block-oriented frontends that have a separate keyboard event to |
|
262 | Block-oriented frontends that have a separate keyboard event to | |
220 | indicate execution should use the :meth:`split_blocks` method instead. |
|
263 | indicate execution should use the :meth:`split_blocks` method instead. | |
|
264 | ||||
|
265 | If the current input produces a syntax error, this method immediately | |||
|
266 | returns False but does *not* raise the syntax error exception, as | |||
|
267 | typically clients will want to send invalid syntax to an execution | |||
|
268 | backend which might convert the invalid syntax into valid Python via | |||
|
269 | one of the dynamic IPython mechanisms. | |||
221 | """ |
|
270 | """ | |
222 | if not self.is_complete: |
|
271 | ||
223 | return False |
|
272 | if not self._is_complete: | |
224 | if self.indent_spaces==0: |
|
|||
225 | return True |
|
|||
226 | last_line = self.source.splitlines()[-1] |
|
|||
227 | if not last_line or last_line.isspace(): |
|
|||
228 | return True |
|
273 | return True | |
229 | else: |
|
|||
230 | return False |
|
|||
231 |
|
274 | |||
|
275 | if self.indent_spaces==0: | |||
|
276 | return False | |||
|
277 | ||||
|
278 | last_line = self.source.splitlines()[-1] | |||
|
279 | return bool(last_line and not last_line.isspace()) | |||
|
280 | ||||
232 | def split_blocks(self, lines): |
|
281 | def split_blocks(self, lines): | |
233 |
"""Split a multiline string into multiple input blocks |
|
282 | """Split a multiline string into multiple input blocks. | |
234 | raise NotImplementedError |
|
283 | ||
|
284 | Note: this method starts by performing a full reset(). | |||
|
285 | ||||
|
286 | Parameters | |||
|
287 | ---------- | |||
|
288 | lines : str | |||
|
289 | A possibly multiline string. | |||
|
290 | ||||
|
291 | Returns | |||
|
292 | ------- | |||
|
293 | blocks : list | |||
|
294 | A list of strings, each possibly multiline. Each string corresponds | |||
|
295 | to a single block that can be compiled in 'single' mode (unless it | |||
|
296 | has a syntax error).""" | |||
|
297 | ||||
|
298 | # This code is fairly delicate. If you make any changes here, make | |||
|
299 | # absolutely sure that you do run the full test suite and ALL tests | |||
|
300 | # pass. | |||
|
301 | ||||
|
302 | self.reset() | |||
|
303 | blocks = [] | |||
|
304 | ||||
|
305 | # Reversed copy so we can use pop() efficiently and consume the input | |||
|
306 | # as a stack | |||
|
307 | lines = lines.splitlines()[::-1] | |||
|
308 | # Outer loop over all input | |||
|
309 | while lines: | |||
|
310 | # Inner loop to build each block | |||
|
311 | while True: | |||
|
312 | # Safety exit from inner loop | |||
|
313 | if not lines: | |||
|
314 | break | |||
|
315 | # Grab next line but don't push it yet | |||
|
316 | next_line = lines.pop() | |||
|
317 | # Blank/empty lines are pushed as-is | |||
|
318 | if not next_line or next_line.isspace(): | |||
|
319 | self.push(next_line) | |||
|
320 | continue | |||
|
321 | ||||
|
322 | # Check indentation changes caused by the *next* line | |||
|
323 | indent_spaces, _full_dedent = self._find_indent(next_line) | |||
|
324 | ||||
|
325 | # If the next line causes a dedent, it can be for two differnt | |||
|
326 | # reasons: either an explicit de-dent by the user or a | |||
|
327 | # return/raise/pass statement. These MUST be handled | |||
|
328 | # separately: | |||
|
329 | # | |||
|
330 | # 1. the first case is only detected when the actual explicit | |||
|
331 | # dedent happens, and that would be the *first* line of a *new* | |||
|
332 | # block. Thus, we must put the line back into the input buffer | |||
|
333 | # so that it starts a new block on the next pass. | |||
|
334 | # | |||
|
335 | # 2. the second case is detected in the line before the actual | |||
|
336 | # dedent happens, so , we consume the line and we can break out | |||
|
337 | # to start a new block. | |||
|
338 | ||||
|
339 | # Case 1, explicit dedent causes a break | |||
|
340 | if _full_dedent and not next_line.startswith(' '): | |||
|
341 | lines.append(next_line) | |||
|
342 | break | |||
|
343 | ||||
|
344 | # Otherwise any line is pushed | |||
|
345 | self.push(next_line) | |||
|
346 | ||||
|
347 | # Case 2, full dedent with full block ready: | |||
|
348 | if _full_dedent or \ | |||
|
349 | self.indent_spaces==0 and not self.push_accepts_more(): | |||
|
350 | break | |||
|
351 | # Form the new block with the current source input | |||
|
352 | blocks.append(self.source_reset()) | |||
|
353 | ||||
|
354 | return blocks | |||
235 |
|
355 | |||
236 | #------------------------------------------------------------------------ |
|
356 | #------------------------------------------------------------------------ | |
237 | # Private interface |
|
357 | # Private interface | |
238 | #------------------------------------------------------------------------ |
|
358 | #------------------------------------------------------------------------ | |
239 |
|
||||
240 | def _update_indent(self, lines): |
|
|||
241 | """Keep track of the indent level.""" |
|
|||
242 |
|
359 | |||
243 | for line in remove_comments(lines).splitlines(): |
|
360 | def _find_indent(self, line): | |
|
361 | """Compute the new indentation level for a single line. | |||
|
362 | ||||
|
363 | Parameters | |||
|
364 | ---------- | |||
|
365 | line : str | |||
|
366 | A single new line of non-whitespace, non-comment Python input. | |||
|
367 | ||||
|
368 | Returns | |||
|
369 | ------- | |||
|
370 | indent_spaces : int | |||
|
371 | New value for the indent level (it may be equal to self.indent_spaces | |||
|
372 | if indentation doesn't change. | |||
|
373 | ||||
|
374 | full_dedent : boolean | |||
|
375 | Whether the new line causes a full flush-left dedent. | |||
|
376 | """ | |||
|
377 | indent_spaces = self.indent_spaces | |||
|
378 | full_dedent = self._full_dedent | |||
|
379 | ||||
|
380 | inisp = num_ini_spaces(line) | |||
|
381 | if inisp < indent_spaces: | |||
|
382 | indent_spaces = inisp | |||
|
383 | if indent_spaces <= 0: | |||
|
384 | #print 'Full dedent in text',self.source # dbg | |||
|
385 | full_dedent = True | |||
|
386 | ||||
|
387 | if line[-1] == ':': | |||
|
388 | indent_spaces += 4 | |||
|
389 | elif dedent_re.match(line): | |||
|
390 | indent_spaces -= 4 | |||
|
391 | if indent_spaces <= 0: | |||
|
392 | full_dedent = True | |||
|
393 | ||||
|
394 | # Safety | |||
|
395 | if indent_spaces < 0: | |||
|
396 | indent_spaces = 0 | |||
|
397 | #print 'safety' # dbg | |||
244 |
|
398 | |||
|
399 | return indent_spaces, full_dedent | |||
|
400 | ||||
|
401 | def _update_indent(self, lines): | |||
|
402 | for line in remove_comments(lines).splitlines(): | |||
245 | if line and not line.isspace(): |
|
403 | if line and not line.isspace(): | |
246 | if self.code is not None: |
|
404 | self.indent_spaces, self._full_dedent = self._find_indent(line) | |
247 | inisp = num_ini_spaces(line) |
|
|||
248 | if inisp < self.indent_spaces: |
|
|||
249 | self.indent_spaces = inisp |
|
|||
250 |
|
||||
251 | if line[-1] == ':': |
|
|||
252 | self.indent_spaces += 4 |
|
|||
253 | elif dedent_re.match(line): |
|
|||
254 | self.indent_spaces -= 4 |
|
|||
255 |
|
405 | |||
256 | def _store(self, lines): |
|
406 | def _store(self, lines): | |
257 | """Store one or more lines of input. |
|
407 | """Store one or more lines of input. | |
@@ -263,4 +413,7 b' class BlockBreaker(object):' | |||||
263 | self._buffer.append(lines) |
|
413 | self._buffer.append(lines) | |
264 | else: |
|
414 | else: | |
265 | self._buffer.append(lines+'\n') |
|
415 | self._buffer.append(lines+'\n') | |
|
416 | self._set_source() | |||
|
417 | ||||
|
418 | def _set_source(self): | |||
266 | self.source = ''.join(self._buffer).encode(self.encoding) |
|
419 | self.source = ''.join(self._buffer).encode(self.encoding) |
1 | NO CONTENT: file was removed |
|
NO CONTENT: file was removed |
General Comments 0
You need to be logged in to leave comments.
Login now