Debian Codegraph @

IPython/core/inputtransformer2.py

raw
1 """Input transformer machinery to support IPython special syntax.
2
3 This includes the machinery to recognise and transform ``%magic`` commands,
4 ``!system`` commands, ``help?`` querying, prompt stripping, and so forth.
5
6 Added: IPython 7.0. Replaces inputsplitter and inputtransformer which were
7 deprecated in 7.0 and removed in 9.0
8 """
9
10 # Copyright (c) IPython Development Team.
11 # Distributed under the terms of the Modified BSD License.
12
13 import ast
14 from codeop import CommandCompiler, Compile
15 import re
16 import sys
17 import tokenize
18 from typing import List, Tuple, Optional, Any
19 import warnings
20 from textwrap import dedent
21
22 from IPython.utils import tokenutil
23
24 _indent_re = re.compile(r'^[ \t]+')
25
26 def leading_empty_lines(lines):
27 """Remove leading empty lines
28
29 If the leading lines are empty or contain only whitespace, they will be
30 removed.
31 """
32 if not lines:
33 return lines
34 for i, line in enumerate(lines):
35 if line and not line.isspace():
36 return lines[i:]
37 return lines
38
39 def leading_indent(lines):
40 """Remove leading indentation.
41
42 Removes the minimum common leading indentation from all lines.
43 """
44 if not lines:
45 return lines
46 return dedent("".join(lines)).splitlines(keepends=True)
47
48 class PromptStripper:
49 """Remove matching input prompts from a block of input.
50
51 Parameters
52 ----------
53 prompt_re : regular expression
54 A regular expression matching any input prompt (including continuation,
55 e.g. ``...``)
56 initial_re : regular expression, optional
57 A regular expression matching only the initial prompt, but not continuation.
58 If no initial expression is given, prompt_re will be used everywhere.
59 Used mainly for plain Python prompts (``>>>``), where the continuation prompt
60 ``...`` is a valid Python expression in Python 3, so shouldn't be stripped.
61
62 Notes
63 -----
64
65 If initial_re and prompt_re differ,
66 only initial_re will be tested against the first line.
67 If any prompt is found on the first two lines,
68 prompts will be stripped from the rest of the block.
69 """
70 def __init__(self, prompt_re, initial_re=None, *, doctest=False):
71 self.prompt_re = prompt_re
72 self.initial_re = initial_re or prompt_re
73 self.doctest = doctest
74 if doctest:
75 # Doctest/xdoctest prompts may be indented (e.g. " >>>").
76 # We only treat "..." as a continuation prompt when the same pasted
77 # block contains at least one ">>>" line, to avoid ambiguity with the
78 # Python Ellipsis literal.
79 self._doctest_initial_re = re.compile(r'^\s*>>>')
80 self._doctest_ps1_re = re.compile(r'^\s*>>>\s?')
81 self._doctest_ps2_re = re.compile(r'^\s*\.\.\.\s?')
82
83 # Very small state machine to detect triple-quoted strings in the
84 # *same* input block (e.g. user typed """ then pasted doctest).
85 # We preserve literal >>> / ... inside triple-quoted strings.
86 self._triple_quote_re = re.compile(r"(?<!\\)(\"\"\"|''')")
87
88
89 def _triple_quote_mask(self, lines: List[str]) -> List[bool]:
90 """
91 Return a boolean mask: True if the corresponding line is considered
92 inside a triple-quoted string literal.
93
94 This is intentionally heuristic (fast + good enough for paste handling).
95 """
96 mask: List[bool] = []
97 in_triple: str | None = None # either ''' or """
98 for line in lines:
99 mask.append(in_triple is not None)
100 # Toggle state for each occurrence of """ or ''' in the line.
101 for m in self._triple_quote_re.finditer(line):
102 q = m.group(1)
103 if in_triple is None:
104 in_triple = q
105 mask[-1] = True # current line is inside triple quotes
106 elif in_triple == q:
107 in_triple = None
108 # else: ignore mismatched triple quote while inside
109 return mask
110
111
112 def _strip(self, lines):
113 return [self.prompt_re.sub('', l, count=1) for l in lines]
114
115 def __call__(self, lines):
116 if not lines:
117 return lines
118
119 if self.doctest:
120 triple_mask = self._triple_quote_mask(lines)
121
122 # Detect doctest prompts only outside triple-quoted strings.
123 has_doctest_outside = any(
124 (not in_triple) and self._doctest_initial_re.match(l)
125 for l, in_triple in zip(lines, triple_mask)
126 )
127 if not has_doctest_outside:
128 return lines
129
130 out_lines: List[str] = []
131 stripped_mask: List[bool] = []
132
133 for l, in_triple in zip(lines, triple_mask):
134 if in_triple:
135 out_lines.append(l)
136 stripped_mask.append(False)
137 continue
138
139 if self._doctest_ps1_re.match(l):
140 new_l = self._doctest_ps1_re.sub('', l, count=1)
141 elif self._doctest_ps2_re.match(l):
142 new_l = self._doctest_ps2_re.sub('', l, count=1)
143 else:
144 new_l = l
145 out_lines.append(new_l)
146 stripped_mask.append(new_l != l)
147
148 # Dedent only the non-triple-quoted segments where stripping occurred.
149 dedented: List[str] = []
150 i = 0
151 while i < len(out_lines):
152 j = i
153 in_triple = triple_mask[i]
154 while j < len(out_lines) and triple_mask[j] == in_triple:
155 j += 1
156
157 segment = out_lines[i:j]
158 seg_stripped = any(stripped_mask[i:j])
159
160 if (not in_triple) and seg_stripped:
161 dedented.extend(dedent(''.join(segment)).splitlines(keepends=True))
162 else:
163 dedented.extend(segment)
164
165 i = j
166
167 return dedented
168
169 if self.initial_re.match(lines[0]) or \
170 (len(lines) > 1 and self.prompt_re.match(lines[1])):
171 return self._strip(lines)
172 return lines
173
174 classic_prompt = PromptStripper(
175 prompt_re=re.compile(r'^(>>>|\.\.\.)( |$)'),
176 initial_re=re.compile(r'^>>>( |$)'),
177 doctest=True,
178 )
179
180 ipython_prompt = PromptStripper(
181 re.compile(
182 r"""
183 ^( # Match from the beginning of a line, either:
184
185 # 1. First-line prompt:
186 ((\[nav\]|\[ins\])?\ )? # Vi editing mode prompt, if it's there
187 In\ # The 'In' of the prompt, with a space
188 \[\d+\]: # Command index, as displayed in the prompt
189 \ # With a mandatory trailing space
190
191 | # ... or ...
192
193 # 2. The three dots of the multiline prompt
194 \s* # All leading whitespace characters
195 \.{3,}: # The three (or more) dots
196 \ ? # With an optional trailing space
197
198 )
199 """,
200 re.VERBOSE,
201 )
202 )
203
204
205 def cell_magic(lines):
206 if not lines or not lines[0].startswith('%%'):
207 return lines
208 if re.match(r'%%\w+\?', lines[0]):
209 # This case will be handled by help_end
210 return lines
211 magic_name, _, first_line = lines[0][2:].rstrip().partition(' ')
212 body = ''.join(lines[1:])
213 return ['get_ipython().run_cell_magic(%r, %r, %r)\n'
214 % (magic_name, first_line, body)]
215
216
217 def _find_assign_op(token_line) -> Optional[int]:
218 """Get the index of the first assignment in the line ('=' not inside brackets)
219
220 Note: We don't try to support multiple special assignment (a = b = %foo)
221 """
222 paren_level = 0
223 for i, ti in enumerate(token_line):
224 s = ti.string
225 if s == '=' and paren_level == 0:
226 return i
227 if s in {'(','[','{'}:
228 paren_level += 1
229 elif s in {')', ']', '}'}:
230 if paren_level > 0:
231 paren_level -= 1
232 return None
233
234 def find_end_of_continued_line(lines, start_line: int):
235 """Find the last line of a line explicitly extended using backslashes.
236
237 Uses 0-indexed line numbers.
238 """
239 end_line = start_line
240 while lines[end_line].endswith('\\\n'):
241 end_line += 1
242 if end_line >= len(lines):
243 break
244 return end_line
245
246 def assemble_continued_line(lines, start: Tuple[int, int], end_line: int):
247 r"""Assemble a single line from multiple continued line pieces
248
249 Continued lines are lines ending in ``\``, and the line following the last
250 ``\`` in the block.
251
252 For example, this code continues over multiple lines::
253
254 if (assign_ix is not None) \
255 and (len(line) >= assign_ix + 2) \
256 and (line[assign_ix+1].string == '%') \
257 and (line[assign_ix+2].type == tokenize.NAME):
258
259 This statement contains four continued line pieces.
260 Assembling these pieces into a single line would give::
261
262 if (assign_ix is not None) and (len(line) >= assign_ix + 2) and (line[...
263
264 This uses 0-indexed line numbers. *start* is (lineno, colno).
265
266 Used to allow ``%magic`` and ``!system`` commands to be continued over
267 multiple lines.
268 """
269 parts = [lines[start[0]][start[1]:]] + lines[start[0]+1:end_line+1]
270 return ' '.join([p.rstrip()[:-1] for p in parts[:-1]] # Strip backslash+newline
271 + [parts[-1].rstrip()]) # Strip newline from last line
272
273 class TokenTransformBase:
274 """Base class for transformations which examine tokens.
275
276 Special syntax should not be transformed when it occurs inside strings or
277 comments. This is hard to reliably avoid with regexes. The solution is to
278 tokenise the code as Python, and recognise the special syntax in the tokens.
279
280 IPython's special syntax is not valid Python syntax, so tokenising may go
281 wrong after the special syntax starts. These classes therefore find and
282 transform *one* instance of special syntax at a time into regular Python
283 syntax. After each transformation, tokens are regenerated to find the next
284 piece of special syntax.
285
286 Subclasses need to implement one class method (find)
287 and one regular method (transform).
288
289 The priority attribute can select which transformation to apply if multiple
290 transformers match in the same place. Lower numbers have higher priority.
291 This allows "%magic?" to be turned into a help call rather than a magic call.
292 """
293 # Lower numbers -> higher priority (for matches in the same location)
294 priority = 10
295
296 def sortby(self):
297 return self.start_line, self.start_col, self.priority
298
299 def __init__(self, start):
300 self.start_line = start[0] - 1 # Shift from 1-index to 0-index
301 self.start_col = start[1]
302
303 @classmethod
304 def find(cls, tokens_by_line):
305 """Find one instance of special syntax in the provided tokens.
306
307 Tokens are grouped into logical lines for convenience,
308 so it is easy to e.g. look at the first token of each line.
309 *tokens_by_line* is a list of lists of tokenize.TokenInfo objects.
310
311 This should return an instance of its class, pointing to the start
312 position it has found, or None if it found no match.
313 """
314 raise NotImplementedError
315
316 def transform(self, lines: List[str]):
317 """Transform one instance of special syntax found by ``find()``
318
319 Takes a list of strings representing physical lines,
320 returns a similar list of transformed lines.
321 """
322 raise NotImplementedError
323
324 class MagicAssign(TokenTransformBase):
325 """Transformer for assignments from magics (a = %foo)"""
326 @classmethod
327 def find(cls, tokens_by_line):
328 """Find the first magic assignment (a = %foo) in the cell.
329 """
330 for line in tokens_by_line:
331 assign_ix = _find_assign_op(line)
332 if (assign_ix is not None) \
333 and (len(line) >= assign_ix + 2) \
334 and (line[assign_ix+1].string == '%') \
335 and (line[assign_ix+2].type == tokenize.NAME):
336 return cls(line[assign_ix+1].start)
337
338 def transform(self, lines: List[str]):
339 """Transform a magic assignment found by the ``find()`` classmethod.
340 """
341 start_line, start_col = self.start_line, self.start_col
342 lhs = lines[start_line][:start_col]
343 end_line = find_end_of_continued_line(lines, start_line)
344 rhs = assemble_continued_line(lines, (start_line, start_col), end_line)
345 assert rhs.startswith('%'), rhs
346 magic_name, _, args = rhs[1:].partition(' ')
347
348 lines_before = lines[:start_line]
349 call = "get_ipython().run_line_magic({!r}, {!r})".format(magic_name, args)
350 new_line = lhs + call + '\n'
351 lines_after = lines[end_line+1:]
352
353 return lines_before + [new_line] + lines_after
354
355
356 class SystemAssign(TokenTransformBase):
357 """Transformer for assignments from system commands (a = !foo)"""
358 @classmethod
359 def find(cls, tokens_by_line):
360 """Find the first system assignment (a = !foo) in the cell."""
361 for line in tokens_by_line:
362 assign_ix = _find_assign_op(line)
363 if (
364 (assign_ix is not None)
365 and not line[assign_ix].line.strip().startswith("=")
366 and (len(line) >= assign_ix + 2)
367 and (line[assign_ix + 1].type == tokenize.OP)
368 and (line[assign_ix + 1].string == "!")
369 ):
370 return cls(line[assign_ix + 1].start)
371
372 def transform(self, lines: List[str]):
373 """Transform a system assignment found by the ``find()`` classmethod.
374 """
375 start_line, start_col = self.start_line, self.start_col
376
377 lhs = lines[start_line][:start_col]
378 end_line = find_end_of_continued_line(lines, start_line)
379 rhs = assemble_continued_line(lines, (start_line, start_col), end_line)
380 assert rhs.startswith('!'), rhs
381 cmd = rhs[1:]
382
383 lines_before = lines[:start_line]
384 call = "get_ipython().getoutput({!r})".format(cmd)
385 new_line = lhs + call + '\n'
386 lines_after = lines[end_line + 1:]
387
388 return lines_before + [new_line] + lines_after
389
390 # The escape sequences that define the syntax transformations IPython will
391 # apply to user input. These can NOT be just changed here: many regular
392 # expressions and other parts of the code may use their hardcoded values, and
393 # for all intents and purposes they constitute the 'IPython syntax', so they
394 # should be considered fixed.
395
396 ESC_SHELL = '!' # Send line to underlying system shell
397 ESC_SH_CAP = '!!' # Send line to system shell and capture output
398 ESC_HELP = '?' # Find information about object
399 ESC_HELP2 = '??' # Find extra-detailed information about object
400 ESC_MAGIC = '%' # Call magic function
401 ESC_MAGIC2 = '%%' # Call cell-magic function
402 ESC_QUOTE = ',' # Split args on whitespace, quote each as string and call
403 ESC_QUOTE2 = ';' # Quote all args as a single string, call
404 ESC_PAREN = '/' # Call first argument with rest of line as arguments
405
406 ESCAPE_SINGLES = {'!', '?', '%', ',', ';', '/'}
407 ESCAPE_DOUBLES = {'!!', '??'} # %% (cell magic) is handled separately
408
409 def _make_help_call(target, esc):
410 """Prepares a pinfo(2)/psearch call from a target name and the escape
411 (i.e. ? or ??)"""
412 method = 'pinfo2' if esc == '??' \
413 else 'psearch' if '*' in target \
414 else 'pinfo'
415 arg = " ".join([method, target])
416 #Prepare arguments for get_ipython().run_line_magic(magic_name, magic_args)
417 t_magic_name, _, t_magic_arg_s = arg.partition(' ')
418 t_magic_name = t_magic_name.lstrip(ESC_MAGIC)
419 return "get_ipython().run_line_magic(%r, %r)" % (t_magic_name, t_magic_arg_s)
420
421
422 def _tr_help(content):
423 """Translate lines escaped with: ?
424
425 A naked help line should fire the intro help screen (shell.show_usage())
426 """
427 if not content:
428 return 'get_ipython().show_usage()'
429
430 return _make_help_call(content, '?')
431
432 def _tr_help2(content):
433 """Translate lines escaped with: ??
434
435 A naked help line should fire the intro help screen (shell.show_usage())
436 """
437 if not content:
438 return 'get_ipython().show_usage()'
439
440 return _make_help_call(content, '??')
441
442 def _tr_magic(content):
443 "Translate lines escaped with a percent sign: %"
444 name, _, args = content.partition(' ')
445 return 'get_ipython().run_line_magic(%r, %r)' % (name, args)
446
447 def _tr_quote(content):
448 "Translate lines escaped with a comma: ,"
449 name, _, args = content.partition(' ')
450 return '%s("%s")' % (name, '", "'.join(args.split()) )
451
452 def _tr_quote2(content):
453 "Translate lines escaped with a semicolon: ;"
454 name, _, args = content.partition(' ')
455 return '%s("%s")' % (name, args)
456
457 def _tr_paren(content):
458 "Translate lines escaped with a slash: /"
459 name, _, args = content.partition(" ")
460 if name == "":
461 raise SyntaxError(f'"{ESC_SHELL}" must be followed by a callable name')
462
463 return '%s(%s)' % (name, ", ".join(args.split()))
464
465 tr = { ESC_SHELL : 'get_ipython().system({!r})'.format,
466 ESC_SH_CAP : 'get_ipython().getoutput({!r})'.format,
467 ESC_HELP : _tr_help,
468 ESC_HELP2 : _tr_help2,
469 ESC_MAGIC : _tr_magic,
470 ESC_QUOTE : _tr_quote,
471 ESC_QUOTE2 : _tr_quote2,
472 ESC_PAREN : _tr_paren }
473
474 class EscapedCommand(TokenTransformBase):
475 """Transformer for escaped commands like %foo, !foo, or /foo"""
476 @classmethod
477 def find(cls, tokens_by_line):
478 """Find the first escaped command (%foo, !foo, etc.) in the cell.
479 """
480 for line in tokens_by_line:
481 if not line:
482 continue
483 ix = 0
484 ll = len(line)
485 while ll > ix and line[ix].type in {tokenize.INDENT, tokenize.DEDENT}:
486 ix += 1
487 if ix >= ll:
488 continue
489 if line[ix].string in ESCAPE_SINGLES:
490 return cls(line[ix].start)
491
492 def transform(self, lines):
493 """Transform an escaped line found by the ``find()`` classmethod.
494 """
495 start_line, start_col = self.start_line, self.start_col
496
497 indent = lines[start_line][:start_col]
498 end_line = find_end_of_continued_line(lines, start_line)
499 line = assemble_continued_line(lines, (start_line, start_col), end_line)
500
501 if len(line) > 1 and line[:2] in ESCAPE_DOUBLES:
502 escape, content = line[:2], line[2:]
503 else:
504 escape, content = line[:1], line[1:]
505
506 if escape in tr:
507 call = tr[escape](content)
508 else:
509 call = ''
510
511 lines_before = lines[:start_line]
512 new_line = indent + call + '\n'
513 lines_after = lines[end_line + 1:]
514
515 return lines_before + [new_line] + lines_after
516
517
518 _help_end_re = re.compile(
519 r"""(%{0,2}
520 (?!\d)[\w*]+ # Variable name
521 (\.(?!\d)[\w*]+|\[-?[0-9]+\])* # .etc.etc or [0], we only support literal integers.
522 )
523 (\?\??)$ # ? or ??
524 """,
525 re.VERBOSE,
526 )
527
528
529 class HelpEnd(TokenTransformBase):
530 """Transformer for help syntax: obj? and obj??"""
531 # This needs to be higher priority (lower number) than EscapedCommand so
532 # that inspecting magics (%foo?) works.
533 priority = 5
534
535 def __init__(self, start, q_locn):
536 super().__init__(start)
537 self.q_line = q_locn[0] - 1 # Shift from 1-indexed to 0-indexed
538 self.q_col = q_locn[1]
539
540 @classmethod
541 def find(cls, tokens_by_line):
542 """Find the first help command (foo?) in the cell.
543 """
544 for line in tokens_by_line:
545 # Last token is NEWLINE; look at last but one
546 if len(line) > 2 and line[-2].string == '?':
547 # Find the first token that's not INDENT/DEDENT
548 ix = 0
549 while line[ix].type in {tokenize.INDENT, tokenize.DEDENT}:
550 ix += 1
551 return cls(line[ix].start, line[-2].start)
552
553 def transform(self, lines):
554 """Transform a help command found by the ``find()`` classmethod.
555 """
556
557 piece = "".join(lines[self.start_line : self.q_line + 1])
558 indent, content = piece[: self.start_col], piece[self.start_col :]
559 lines_before = lines[: self.start_line]
560 lines_after = lines[self.q_line + 1 :]
561
562 m = _help_end_re.search(content)
563 if not m:
564 raise SyntaxError(content)
565 assert m is not None, content
566 target = m.group(1)
567 esc = m.group(3)
568
569
570 call = _make_help_call(target, esc)
571 new_line = indent + call + '\n'
572
573 return lines_before + [new_line] + lines_after
574
575 def make_tokens_by_line(lines:List[str]):
576 """Tokenize a series of lines and group tokens by line.
577
578 The tokens for a multiline Python string or expression are grouped as one
579 line. All lines except the last lines should keep their line ending ('\\n',
580 '\\r\\n') for this to properly work. Use `.splitlines(keeplineending=True)`
581 for example when passing block of text to this function.
582
583 """
584 # NL tokens are used inside multiline expressions, but also after blank
585 # lines or comments. This is intentional - see https://bugs.python.org/issue17061
586 # We want to group the former case together but split the latter, so we
587 # track parentheses level, similar to the internals of tokenize.
588
589 # reexported from token on 3.7+
590 NEWLINE, NL = tokenize.NEWLINE, tokenize.NL # type: ignore
591 tokens_by_line: List[List[Any]] = [[]]
592 if len(lines) > 1 and not lines[0].endswith(("\n", "\r", "\r\n", "\x0b", "\x0c")):
593 warnings.warn(
594 "`make_tokens_by_line` received a list of lines which do not have lineending markers ('\\n', '\\r', '\\r\\n', '\\x0b', '\\x0c'), behavior will be unspecified",
595 stacklevel=2,
596 )
597 parenlev = 0
598 try:
599 for token in tokenutil.generate_tokens_catch_errors(
600 iter(lines).__next__, extra_errors_to_catch=["expected EOF"]
601 ):
602 tokens_by_line[-1].append(token)
603 if (token.type == NEWLINE) \
604 or ((token.type == NL) and (parenlev <= 0)):
605 tokens_by_line.append([])
606 elif token.string in {'(', '[', '{'}:
607 parenlev += 1
608 elif token.string in {')', ']', '}'}:
609 if parenlev > 0:
610 parenlev -= 1
611 except tokenize.TokenError:
612 # Input ended in a multiline string or expression. That's OK for us.
613 pass
614
615
616 if not tokens_by_line[-1]:
617 tokens_by_line.pop()
618
619
620 return tokens_by_line
621
622
623 def has_sunken_brackets(tokens: List[tokenize.TokenInfo]):
624 """Check if the depth of brackets in the list of tokens drops below 0"""
625 parenlev = 0
626 for token in tokens:
627 if token.string in {"(", "[", "{"}:
628 parenlev += 1
629 elif token.string in {")", "]", "}"}:
630 parenlev -= 1
631 if parenlev < 0:
632 return True
633 return False
634
635 # Arbitrary limit to prevent getting stuck in infinite loops
636 TRANSFORM_LOOP_LIMIT = 500
637
638 class TransformerManager:
639 """Applies various transformations to a cell or code block.
640
641 The key methods for external use are ``transform_cell()``
642 and ``check_complete()``.
643 """
644 def __init__(self):
645 self.cleanup_transforms = [
646 leading_empty_lines,
647 leading_indent,
648 classic_prompt,
649 ipython_prompt,
650 ]
651 self.line_transforms = [
652 cell_magic,
653 ]
654 self.token_transformers = [
655 MagicAssign,
656 SystemAssign,
657 EscapedCommand,
658 HelpEnd,
659 ]
660
661 def do_one_token_transform(self, lines):
662 """Find and run the transform earliest in the code.
663
664 Returns (changed, lines).
665
666 This method is called repeatedly until changed is False, indicating
667 that all available transformations are complete.
668
669 The tokens following IPython special syntax might not be valid, so
670 the transformed code is retokenised every time to identify the next
671 piece of special syntax. Hopefully long code cells are mostly valid
672 Python, not using lots of IPython special syntax, so this shouldn't be
673 a performance issue.
674 """
675 tokens_by_line = make_tokens_by_line(lines)
676 candidates = []
677 for transformer_cls in self.token_transformers:
678 transformer = transformer_cls.find(tokens_by_line)
679 if transformer:
680 candidates.append(transformer)
681
682 if not candidates:
683 # Nothing to transform
684 return False, lines
685 ordered_transformers = sorted(candidates, key=TokenTransformBase.sortby)
686 for transformer in ordered_transformers:
687 try:
688 return True, transformer.transform(lines)
689 except SyntaxError:
690 pass
691 return False, lines
692
693 def do_token_transforms(self, lines):
694 for _ in range(TRANSFORM_LOOP_LIMIT):
695 changed, lines = self.do_one_token_transform(lines)
696 if not changed:
697 return lines
698
699 raise RuntimeError("Input transformation still changing after "
700 "%d iterations. Aborting." % TRANSFORM_LOOP_LIMIT)
701
702 def transform_cell(self, cell: str) -> str:
703 """Transforms a cell of input code"""
704 if not cell.endswith('\n'):
705 cell += '\n' # Ensure the cell has a trailing newline
706 lines = cell.splitlines(keepends=True)
707 for transform in self.cleanup_transforms + self.line_transforms:
708 lines = transform(lines)
709
710 lines = self.do_token_transforms(lines)
711 return ''.join(lines)
712
713 def check_complete(self, cell: str):
714 """Return whether a block of code is ready to execute, or should be continued
715
716 Parameters
717 ----------
718 cell : string
719 Python input code, which can be multiline.
720
721 Returns
722 -------
723 status : str
724 One of 'complete', 'incomplete', or 'invalid' if source is not a
725 prefix of valid code.
726 indent_spaces : int or None
727 The number of spaces by which to indent the next line of code. If
728 status is not 'incomplete', this is None.
729 """
730 # Remember if the lines ends in a new line.
731 ends_with_newline = False
732 for character in reversed(cell):
733 if character == '\n':
734 ends_with_newline = True
735 break
736 elif character.strip():
737 break
738 else:
739 continue
740
741 if not ends_with_newline:
742 # Append an newline for consistent tokenization
743 # See https://bugs.python.org/issue33899
744 cell += '\n'
745
746 lines = cell.splitlines(keepends=True)
747
748 if not lines:
749 return 'complete', None
750
751 for line in reversed(lines):
752 if not line.strip():
753 continue
754 elif line.strip("\n").endswith("\\"):
755 return "incomplete", find_last_indent(lines)
756 else:
757 break
758
759 try:
760 for transform in self.cleanup_transforms:
761 if not getattr(transform, 'has_side_effects', False):
762 lines = transform(lines)
763 except SyntaxError:
764 return 'invalid', None
765
766 if lines[0].startswith('%%'):
767 # Special case for cell magics - completion marked by blank line
768 if lines[-1].strip():
769 return 'incomplete', find_last_indent(lines)
770 else:
771 return 'complete', None
772
773 try:
774 for transform in self.line_transforms:
775 if not getattr(transform, 'has_side_effects', False):
776 lines = transform(lines)
777 lines = self.do_token_transforms(lines)
778 except SyntaxError:
779 return 'invalid', None
780
781 tokens_by_line = make_tokens_by_line(lines)
782
783 # Bail if we got one line and there are more closing parentheses than
784 # the opening ones
785 if (
786 len(lines) == 1
787 and tokens_by_line
788 and has_sunken_brackets(tokens_by_line[0])
789 ):
790 return "invalid", None
791
792 if not tokens_by_line:
793 return 'incomplete', find_last_indent(lines)
794
795 if (
796 tokens_by_line[-1][-1].type != tokenize.ENDMARKER
797 and tokens_by_line[-1][-1].type != tokenize.ERRORTOKEN
798 ):
799 # We're in a multiline string or expression
800 return 'incomplete', find_last_indent(lines)
801
802 newline_types = {tokenize.NEWLINE, tokenize.COMMENT, tokenize.ENDMARKER} # type: ignore
803
804 # Pop the last line which only contains DEDENTs and ENDMARKER
805 last_token_line = None
806 if {t.type for t in tokens_by_line[-1]} in [
807 {tokenize.DEDENT, tokenize.ENDMARKER},
808 {tokenize.ENDMARKER}
809 ] and len(tokens_by_line) > 1:
810 last_token_line = tokens_by_line.pop()
811
812 while tokens_by_line[-1] and tokens_by_line[-1][-1].type in newline_types:
813 tokens_by_line[-1].pop()
814
815 if not tokens_by_line[-1]:
816 return 'incomplete', find_last_indent(lines)
817
818 if tokens_by_line[-1][-1].string == ':':
819 # The last line starts a block (e.g. 'if foo:')
820 ix = 0
821 while tokens_by_line[-1][ix].type in {tokenize.INDENT, tokenize.DEDENT}:
822 ix += 1
823
824 indent = tokens_by_line[-1][ix].start[1]
825 return 'incomplete', indent + 4
826
827 if tokens_by_line[-1][0].line.endswith('\\'):
828 return 'incomplete', None
829
830 # At this point, our checks think the code is complete (or invalid).
831 # We'll use codeop.compile_command to check this with the real parser
832 try:
833 with warnings.catch_warnings():
834 warnings.simplefilter('error', SyntaxWarning)
835 res = compile_command(''.join(lines), symbol='exec')
836 except (SyntaxError, OverflowError, ValueError, TypeError,
837 MemoryError, SyntaxWarning):
838 return 'invalid', None
839 else:
840 if res is None:
841 return 'incomplete', find_last_indent(lines)
842
843 if last_token_line and last_token_line[0].type == tokenize.DEDENT:
844 if ends_with_newline:
845 return 'complete', None
846 return 'incomplete', find_last_indent(lines)
847
848 # If there's a blank line at the end, assume we're ready to execute
849 if not lines[-1].strip():
850 return 'complete', None
851
852 return 'complete', None
853
854
855 def find_last_indent(lines):
856 m = _indent_re.match(lines[-1])
857 if not m:
858 return 0
859 return len(m.group(0).replace('\t', ' '*4))
860
861
862 class MaybeAsyncCompile(Compile):
863 def __init__(self, extra_flags=0):
864 super().__init__()
865 self.flags |= extra_flags
866
867
868 class MaybeAsyncCommandCompiler(CommandCompiler):
869 def __init__(self, extra_flags=0):
870 self.compiler = MaybeAsyncCompile(extra_flags=extra_flags)
871
872
873 _extra_flags = ast.PyCF_ALLOW_TOP_LEVEL_AWAIT
874
875 compile_command = MaybeAsyncCommandCompiler(extra_flags=_extra_flags)