Format: text/x-python
⬇ Download File (28.5 KB)
   1  """DEPRECATED: Input handling and transformation machinery.
   2  
   3  This module was deprecated in IPython 7.0, in favour of inputtransformer2.
   4  
   5  The first class in this module, :class:`InputSplitter`, is designed to tell when
   6  input from a line-oriented frontend is complete and should be executed, and when
   7  the user should be prompted for another line of code instead. The name 'input
   8  splitter' is largely for historical reasons.
   9  
  10  A companion, :class:`IPythonInputSplitter`, provides the same functionality but
  11  with full support for the extended IPython syntax (magics, system calls, etc).
  12  The code to actually do these transformations is in :mod:`IPython.core.inputtransformer`.
  13  :class:`IPythonInputSplitter` feeds the raw code to the transformers in order
  14  and stores the results.
  15  
  16  For more details, see the class docstrings below.
  17  """
  18  
  19  from __future__ import annotations
  20  
  21  from warnings import warn
  22  
  23  warn('IPython.core.inputsplitter is deprecated since IPython 7 in favor of `IPython.core.inputtransformer2`',
  24       DeprecationWarning)
  25  
  26  # Copyright (c) IPython Development Team.
  27  # Distributed under the terms of the Modified BSD License.
  28  import ast
  29  import codeop
  30  import io
  31  import re
  32  import sys
  33  import tokenize
  34  import warnings
  35  
  36  from typing import List, Tuple, Union, Optional, TYPE_CHECKING
  37  from types import CodeType
  38  
  39  from IPython.core.inputtransformer import (leading_indent,
  40                                             classic_prompt,
  41                                             ipy_prompt,
  42                                             cellmagic,
  43                                             assemble_logical_lines,
  44                                             help_end,
  45                                             escaped_commands,
  46                                             assign_from_magic,
  47                                             assign_from_system,
  48                                             assemble_python_lines,
  49                                             )
  50  from IPython.utils import tokenutil
  51  
  52  # These are available in this module for backwards compatibility.
  53  from IPython.core.inputtransformer import (ESC_SHELL, ESC_SH_CAP, ESC_HELP,
  54                                          ESC_HELP2, ESC_MAGIC, ESC_MAGIC2,
  55                                          ESC_QUOTE, ESC_QUOTE2, ESC_PAREN, ESC_SEQUENCES)
  56  
  57  if TYPE_CHECKING:
  58      from typing_extensions import Self
  59  #-----------------------------------------------------------------------------
  60  # Utilities
  61  #-----------------------------------------------------------------------------
  62  
  63  # FIXME: These are general-purpose utilities that later can be moved to the
  64  # general ward.  Kept here for now because we're being very strict about test
  65  # coverage with this code, and this lets us ensure that we keep 100% coverage
  66  # while developing.
  67  
  68  # compiled regexps for autoindent management
  69  dedent_re = re.compile('|'.join([
  70      r'^\s+raise(\s.*)?$', # raise statement (+ space + other stuff, maybe)
  71      r'^\s+raise\([^\)]*\).*$', # wacky raise with immediate open paren
  72      r'^\s+return(\s.*)?$', # normal return (+ space + other stuff, maybe)
  73      r'^\s+return\([^\)]*\).*$', # wacky return with immediate open paren
  74      r'^\s+pass\s*$', # pass (optionally followed by trailing spaces)
  75      r'^\s+break\s*$', # break (optionally followed by trailing spaces)
  76      r'^\s+continue\s*$', # continue (optionally followed by trailing spaces)
  77  ]))
  78  ini_spaces_re = re.compile(r'^([ \t\r\f\v]+)')
  79  
  80  # regexp to match pure comment lines so we don't accidentally insert 'if 1:'
  81  # before pure comments
  82  comment_line_re = re.compile(r'^\s*\#')
  83  
  84  
  85  def num_ini_spaces(s):
  86      """Return the number of initial spaces in a string.
  87  
  88      Note that tabs are counted as a single space.  For now, we do *not* support
  89      mixing of tabs and spaces in the user's input.
  90  
  91      Parameters
  92      ----------
  93      s : string
  94  
  95      Returns
  96      -------
  97      n : int
  98      """
  99      warnings.warn(
 100          "`num_ini_spaces` is Pending Deprecation since IPython 8.17."
 101          "It is considered for removal in in future version. "
 102          "Please open an issue if you believe it should be kept.",
 103          stacklevel=2,
 104          category=PendingDeprecationWarning,
 105      )
 106      ini_spaces = ini_spaces_re.match(s)
 107      if ini_spaces:
 108          return ini_spaces.end()
 109      else:
 110          return 0
 111  
 112  # Fake token types for partial_tokenize:
 113  INCOMPLETE_STRING = tokenize.N_TOKENS
 114  IN_MULTILINE_STATEMENT = tokenize.N_TOKENS + 1
 115  
 116  # The 2 classes below have the same API as TokenInfo, but don't try to look up
 117  # a token type name that they won't find.
 118  class IncompleteString:
 119      type = exact_type = INCOMPLETE_STRING
 120      def __init__(self, s, start, end, line):
 121          self.s = s
 122          self.start = start
 123          self.end = end
 124          self.line = line
 125  
 126  class InMultilineStatement:
 127      type = exact_type = IN_MULTILINE_STATEMENT
 128      def __init__(self, pos, line):
 129          self.s = ''
 130          self.start = self.end = pos
 131          self.line = line
 132  
 133  def partial_tokens(s):
 134      """Iterate over tokens from a possibly-incomplete string of code.
 135  
 136      This adds two special token types: INCOMPLETE_STRING and
 137      IN_MULTILINE_STATEMENT. These can only occur as the last token yielded, and
 138      represent the two main ways for code to be incomplete.
 139      """
 140      readline = io.StringIO(s).readline
 141      token = tokenize.TokenInfo(tokenize.NEWLINE, '', (1, 0), (1, 0), '')
 142      try:
 143          for token in tokenutil.generate_tokens_catch_errors(readline):
 144              yield token
 145      except tokenize.TokenError as e:
 146          # catch EOF error
 147          lines = s.splitlines(keepends=True)
 148          end = len(lines), len(lines[-1])
 149          if 'multi-line string' in e.args[0]:
 150              l, c = start = token.end
 151              s = lines[l-1][c:] + ''.join(lines[l:])
 152              yield IncompleteString(s, start, end, lines[-1])
 153          elif 'multi-line statement' in e.args[0]:
 154              yield InMultilineStatement(end, lines[-1])
 155          else:
 156              raise
 157  
 158  def find_next_indent(code) -> int:
 159      """Find the number of spaces for the next line of indentation"""
 160      tokens = list(partial_tokens(code))
 161      if tokens[-1].type == tokenize.ENDMARKER:
 162          tokens.pop()
 163      if not tokens:
 164          return 0
 165  
 166      while tokens[-1].type in {
 167          tokenize.DEDENT,
 168          tokenize.NEWLINE,
 169          tokenize.COMMENT,
 170          tokenize.ERRORTOKEN,
 171      }:
 172          tokens.pop()
 173  
 174      # Starting in Python 3.12, the tokenize module adds implicit newlines at the end
 175      # of input. We need to remove those if we're in a multiline statement
 176      if tokens[-1].type == IN_MULTILINE_STATEMENT:
 177          while tokens[-2].type in {tokenize.NL}:
 178              tokens.pop(-2)
 179  
 180  
 181      if tokens[-1].type == INCOMPLETE_STRING:
 182          # Inside a multiline string
 183          return 0
 184  
 185      # Find the indents used before
 186      prev_indents = [0]
 187      def _add_indent(n):
 188          if n != prev_indents[-1]:
 189              prev_indents.append(n)
 190  
 191      tokiter = iter(tokens)
 192      for tok in tokiter:
 193          if tok.type in {tokenize.INDENT, tokenize.DEDENT}:
 194              _add_indent(tok.end[1])
 195          elif (tok.type == tokenize.NL):
 196              try:
 197                  _add_indent(next(tokiter).start[1])
 198              except StopIteration:
 199                  break
 200  
 201      last_indent = prev_indents.pop()
 202  
 203      # If we've just opened a multiline statement (e.g. 'a = ['), indent more
 204      if tokens[-1].type == IN_MULTILINE_STATEMENT:
 205          if tokens[-2].exact_type in {tokenize.LPAR, tokenize.LSQB, tokenize.LBRACE}:
 206              return last_indent + 4
 207          return last_indent
 208  
 209      if tokens[-1].exact_type == tokenize.COLON:
 210          # Line ends with colon - indent
 211          return last_indent + 4
 212  
 213      if last_indent:
 214          # Examine the last line for dedent cues - statements like return or
 215          # raise which normally end a block of code.
 216          last_line_starts = 0
 217          for i, tok in enumerate(tokens):
 218              if tok.type == tokenize.NEWLINE:
 219                  last_line_starts = i + 1
 220  
 221          last_line_tokens = tokens[last_line_starts:]
 222          names = [t.string for t in last_line_tokens if t.type == tokenize.NAME]
 223          if names and names[0] in {'raise', 'return', 'pass', 'break', 'continue'}:
 224              # Find the most recent indentation less than the current level
 225              for indent in reversed(prev_indents):
 226                  if indent < last_indent:
 227                      return indent
 228  
 229      return last_indent
 230  
 231  
 232  def last_blank(src):
 233      """Determine if the input source ends in a blank.
 234  
 235      A blank is either a newline or a line consisting of whitespace.
 236  
 237      Parameters
 238      ----------
 239      src : string
 240          A single or multiline string.
 241      """
 242      if not src: return False
 243      ll  = src.splitlines()[-1]
 244      return (ll == '') or ll.isspace()
 245  
 246  
 247  last_two_blanks_re = re.compile(r'\n\s*\n\s*$', re.MULTILINE)
 248  last_two_blanks_re2 = re.compile(r'.+\n\s*\n\s+$', re.MULTILINE)
 249  
 250  def last_two_blanks(src):
 251      """Determine if the input source ends in two blanks.
 252  
 253      A blank is either a newline or a line consisting of whitespace.
 254  
 255      Parameters
 256      ----------
 257      src : string
 258          A single or multiline string.
 259      """
 260      if not src: return False
 261      # The logic here is tricky: I couldn't get a regexp to work and pass all
 262      # the tests, so I took a different approach: split the source by lines,
 263      # grab the last two and prepend '###\n' as a stand-in for whatever was in
 264      # the body before the last two lines.  Then, with that structure, it's
 265      # possible to analyze with two regexps.  Not the most elegant solution, but
 266      # it works.  If anyone tries to change this logic, make sure to validate
 267      # the whole test suite first!
 268      new_src = '\n'.join(['###\n'] + src.splitlines()[-2:])
 269      return (bool(last_two_blanks_re.match(new_src)) or
 270              bool(last_two_blanks_re2.match(new_src)) )
 271  
 272  
 273  def remove_comments(src):
 274      """Remove all comments from input source.
 275  
 276      Note: comments are NOT recognized inside of strings!
 277  
 278      Parameters
 279      ----------
 280      src : string
 281          A single or multiline input string.
 282  
 283      Returns
 284      -------
 285      String with all Python comments removed.
 286      """
 287  
 288      return re.sub('#.*', '', src)
 289  
 290  
 291  def get_input_encoding():
 292      """Return the default standard input encoding.
 293  
 294      If sys.stdin has no encoding, 'ascii' is returned."""
 295      # There are strange environments for which sys.stdin.encoding is None. We
 296      # ensure that a valid encoding is returned.
 297      encoding = getattr(sys.stdin, 'encoding', None)
 298      if encoding is None:
 299          encoding = 'ascii'
 300      return encoding
 301  
 302  #-----------------------------------------------------------------------------
 303  # Classes and functions for normal Python syntax handling
 304  #-----------------------------------------------------------------------------
 305  
 306  class InputSplitter(object):
 307      r"""An object that can accumulate lines of Python source before execution.
 308  
 309      This object is designed to be fed python source line-by-line, using
 310      :meth:`push`. It will return on each push whether the currently pushed
 311      code could be executed already. In addition, it provides a method called
 312      :meth:`push_accepts_more` that can be used to query whether more input
 313      can be pushed into a single interactive block.
 314  
 315      This is a simple example of how an interactive terminal-based client can use
 316      this tool::
 317  
 318          isp = InputSplitter()
 319          while isp.push_accepts_more():
 320              indent = ' '*isp.indent_spaces
 321              prompt = '>>> ' + indent
 322              line = indent + raw_input(prompt)
 323              isp.push(line)
 324          print('Input source was:\n', isp.source_reset())
 325      """
 326      # A cache for storing the current indentation
 327      # The first value stores the most recently processed source input
 328      # The second value is the number of spaces for the current indentation 
 329      # If self.source matches the first value, the second value is a valid
 330      # current indentation. Otherwise, the cache is invalid and the indentation
 331      # must be recalculated.
 332      _indent_spaces_cache: Union[Tuple[None, None], Tuple[str, int]] = None, None
 333      # String, indicating the default input encoding.  It is computed by default
 334      # at initialization time via get_input_encoding(), but it can be reset by a
 335      # client with specific knowledge of the encoding.
 336      encoding = ''
 337      # String where the current full source input is stored, properly encoded.
 338      # Reading this attribute is the normal way of querying the currently pushed
 339      # source code, that has been properly encoded.
 340      source: str = ""
 341      # Code object corresponding to the current source.  It is automatically
 342      # synced to the source, so it can be queried at any time to obtain the code
 343      # object; it will be None if the source doesn't compile to valid Python.
 344      code: Optional[CodeType] = None
 345  
 346      # Private attributes
 347  
 348      # List with lines of input accumulated so far
 349      _buffer: List[str]
 350      # Command compiler
 351      _compile: codeop.CommandCompiler
 352      # Boolean indicating whether the current block is complete
 353      _is_complete: Optional[bool] = None
 354      # Boolean indicating whether the current block has an unrecoverable syntax error
 355      _is_invalid: bool = False
 356  
 357      def __init__(self) -> None:
 358          """Create a new InputSplitter instance."""
 359          self._buffer = []
 360          self._compile = codeop.CommandCompiler()
 361          self.encoding = get_input_encoding()
 362  
 363      def reset(self):
 364          """Reset the input buffer and associated state."""
 365          self._buffer[:] = []
 366          self.source = ''
 367          self.code = None
 368          self._is_complete = False
 369          self._is_invalid = False
 370  
 371      def source_reset(self):
 372          """Return the input source and perform a full reset.
 373          """
 374          out = self.source
 375          self.reset()
 376          return out
 377  
 378      def check_complete(self, source):
 379          """Return whether a block of code is ready to execute, or should be continued
 380  
 381          This is a non-stateful API, and will reset the state of this InputSplitter.
 382  
 383          Parameters
 384          ----------
 385          source : string
 386              Python input code, which can be multiline.
 387  
 388          Returns
 389          -------
 390          status : str
 391              One of 'complete', 'incomplete', or 'invalid' if source is not a
 392              prefix of valid code.
 393          indent_spaces : int or None
 394              The number of spaces by which to indent the next line of code. If
 395              status is not 'incomplete', this is None.
 396          """
 397          self.reset()
 398          try:
 399              self.push(source)
 400          except SyntaxError:
 401              # Transformers in IPythonInputSplitter can raise SyntaxError,
 402              # which push() will not catch.
 403              return 'invalid', None
 404          else:
 405              if self._is_invalid:
 406                  return 'invalid', None
 407              elif self.push_accepts_more():
 408                  return 'incomplete', self.get_indent_spaces()
 409              else:
 410                  return 'complete', None
 411          finally:
 412              self.reset()
 413  
 414      def push(self, lines:str) -> bool:
 415          """Push one or more lines of input.
 416  
 417          This stores the given lines and returns a status code indicating
 418          whether the code forms a complete Python block or not.
 419  
 420          Any exceptions generated in compilation are swallowed, but if an
 421          exception was produced, the method returns True.
 422  
 423          Parameters
 424          ----------
 425          lines : string
 426              One or more lines of Python input.
 427  
 428          Returns
 429          -------
 430          is_complete : boolean
 431              True if the current input source (the result of the current input
 432              plus prior inputs) forms a complete Python execution block.  Note that
 433              this value is also stored as a private attribute (``_is_complete``), so it
 434              can be queried at any time.
 435          """
 436          assert isinstance(lines, str)
 437          self._store(lines)
 438          source = self.source
 439  
 440          # Before calling _compile(), reset the code object to None so that if an
 441          # exception is raised in compilation, we don't mislead by having
 442          # inconsistent code/source attributes.
 443          self.code, self._is_complete = None, None
 444          self._is_invalid = False
 445  
 446          # Honor termination lines properly
 447          if source.endswith('\\\n'):
 448              return False
 449  
 450          try:
 451              with warnings.catch_warnings():
 452                  warnings.simplefilter('error', SyntaxWarning)
 453                  self.code = self._compile(source, symbol="exec")
 454          # Invalid syntax can produce any of a number of different errors from
 455          # inside the compiler, so we have to catch them all.  Syntax errors
 456          # immediately produce a 'ready' block, so the invalid Python can be
 457          # sent to the kernel for evaluation with possible ipython
 458          # special-syntax conversion.
 459          except (SyntaxError, OverflowError, ValueError, TypeError,
 460                  MemoryError, SyntaxWarning):
 461              self._is_complete = True
 462              self._is_invalid = True
 463          else:
 464              # Compilation didn't produce any exceptions (though it may not have
 465              # given a complete code object)
 466              self._is_complete = self.code is not None
 467  
 468          return self._is_complete
 469  
 470      def push_accepts_more(self):
 471          """Return whether a block of interactive input can accept more input.
 472  
 473          This method is meant to be used by line-oriented frontends, who need to
 474          guess whether a block is complete or not based solely on prior and
 475          current input lines.  The InputSplitter considers it has a complete
 476          interactive block and will not accept more input when either:
 477  
 478          * A SyntaxError is raised
 479  
 480          * The code is complete and consists of a single line or a single
 481            non-compound statement
 482  
 483          * The code is complete and has a blank line at the end
 484  
 485          If the current input produces a syntax error, this method immediately
 486          returns False but does *not* raise the syntax error exception, as
 487          typically clients will want to send invalid syntax to an execution
 488          backend which might convert the invalid syntax into valid Python via
 489          one of the dynamic IPython mechanisms.
 490          """
 491  
 492          # With incomplete input, unconditionally accept more
 493          # A syntax error also sets _is_complete to True - see push()
 494          if not self._is_complete:
 495              #print("Not complete")  # debug
 496              return True
 497          
 498          # The user can make any (complete) input execute by leaving a blank line
 499          last_line = self.source.splitlines()[-1]
 500          if (not last_line) or last_line.isspace():
 501              #print("Blank line")  # debug
 502              return False
 503          
 504          # If there's just a single line or AST node, and we're flush left, as is
 505          # the case after a simple statement such as 'a=1', we want to execute it
 506          # straight away.
 507          if self.get_indent_spaces() == 0:
 508              if len(self.source.splitlines()) <= 1:
 509                  return False
 510              
 511              try:
 512                  code_ast = ast.parse("".join(self._buffer))
 513              except Exception:
 514                  #print("Can't parse AST")  # debug
 515                  return False
 516              else:
 517                  if len(code_ast.body) == 1 and \
 518                                      not hasattr(code_ast.body[0], 'body'):
 519                      #print("Simple statement")  # debug
 520                      return False
 521  
 522          # General fallback - accept more code
 523          return True
 524  
 525      def get_indent_spaces(self) -> int:
 526          sourcefor, n = self._indent_spaces_cache
 527          if sourcefor == self.source:
 528              assert n is not None
 529              return n
 530  
 531          # self.source always has a trailing newline
 532          n = find_next_indent(self.source[:-1])
 533          self._indent_spaces_cache = (self.source, n)
 534          return n
 535  
 536      # Backwards compatibility. I think all code that used .indent_spaces was
 537      # inside IPython, but we can leave this here until IPython 7 in case any
 538      # other modules are using it. -TK, November 2017
 539      indent_spaces = property(get_indent_spaces)
 540  
 541      def _store(self, lines, buffer=None, store='source'):
 542          """Store one or more lines of input.
 543  
 544          If input lines are not newline-terminated, a newline is automatically
 545          appended."""
 546  
 547          if buffer is None:
 548              buffer = self._buffer
 549  
 550          if lines.endswith('\n'):
 551              buffer.append(lines)
 552          else:
 553              buffer.append(lines+'\n')
 554          setattr(self, store, self._set_source(buffer))
 555  
 556      def _set_source(self, buffer):
 557          return u''.join(buffer)
 558  
 559  
 560  class IPythonInputSplitter(InputSplitter):
 561      """An input splitter that recognizes all of IPython's special syntax."""
 562  
 563      # String with raw, untransformed input.
 564      source_raw = ''
 565      
 566      # Flag to track when a transformer has stored input that it hasn't given
 567      # back yet.
 568      transformer_accumulating = False
 569      
 570      # Flag to track when assemble_python_lines has stored input that it hasn't
 571      # given back yet.
 572      within_python_line = False
 573  
 574      # Private attributes
 575  
 576      # List with lines of raw input accumulated so far.
 577      _buffer_raw: List[str]
 578  
 579      def __init__(self, line_input_checker=True, physical_line_transforms=None,
 580                      logical_line_transforms=None, python_line_transforms=None):
 581          super(IPythonInputSplitter, self).__init__()
 582          self._buffer_raw = []
 583          self._validate = True
 584          
 585          if physical_line_transforms is not None:
 586              self.physical_line_transforms = physical_line_transforms
 587          else:
 588              self.physical_line_transforms = [
 589                                               leading_indent(),
 590                                               classic_prompt(),
 591                                               ipy_prompt(),
 592                                               cellmagic(end_on_blank_line=line_input_checker),
 593                                              ]
 594          
 595          self.assemble_logical_lines = assemble_logical_lines()
 596          if logical_line_transforms is not None:
 597              self.logical_line_transforms = logical_line_transforms
 598          else:
 599              self.logical_line_transforms = [
 600                                              help_end(),
 601                                              escaped_commands(),
 602                                              assign_from_magic(),
 603                                              assign_from_system(),
 604                                             ]
 605          
 606          self.assemble_python_lines = assemble_python_lines()
 607          if python_line_transforms is not None:
 608              self.python_line_transforms = python_line_transforms
 609          else:
 610              # We don't use any of these at present
 611              self.python_line_transforms = []
 612      
 613      @property
 614      def transforms(self):
 615          "Quick access to all transformers."
 616          return self.physical_line_transforms + \
 617              [self.assemble_logical_lines] + self.logical_line_transforms + \
 618              [self.assemble_python_lines]  + self.python_line_transforms
 619      
 620      @property
 621      def transforms_in_use(self):
 622          """Transformers, excluding logical line transformers if we're in a
 623          Python line."""
 624          t = self.physical_line_transforms[:]
 625          if not self.within_python_line:
 626              t += [self.assemble_logical_lines] + self.logical_line_transforms
 627          return t + [self.assemble_python_lines] + self.python_line_transforms
 628  
 629      def reset(self):
 630          """Reset the input buffer and associated state."""
 631          super(IPythonInputSplitter, self).reset()
 632          self._buffer_raw[:] = []
 633          self.source_raw = ''
 634          self.transformer_accumulating = False
 635          self.within_python_line = False
 636  
 637          for t in self.transforms:
 638              try:
 639                  t.reset()
 640              except SyntaxError:
 641                  # Nothing that calls reset() expects to handle transformer
 642                  # errors
 643                  pass
 644  
 645      def flush_transformers(self: Self):
 646          def _flush(transform, outs: List[str]):
 647              """yield transformed lines
 648  
 649              always strings, never None
 650  
 651              transform: the current transform
 652              outs: an iterable of previously transformed inputs.
 653                   Each may be multiline, which will be passed
 654                   one line at a time to transform.
 655              """
 656              for out in outs:
 657                  for line in out.splitlines():
 658                      # push one line at a time
 659                      tmp = transform.push(line)
 660                      if tmp is not None:
 661                          yield tmp
 662              
 663              # reset the transform
 664              tmp = transform.reset()
 665              if tmp is not None:
 666                  yield tmp
 667  
 668          out: List[str] = []
 669          for t in self.transforms_in_use:
 670              out = _flush(t, out)
 671          
 672          out = list(out)
 673          if out:
 674              self._store('\n'.join(out))
 675  
 676      def raw_reset(self):
 677          """Return raw input only and perform a full reset.
 678          """
 679          out = self.source_raw
 680          self.reset()
 681          return out
 682      
 683      def source_reset(self):
 684          try:
 685              self.flush_transformers()
 686              return self.source
 687          finally:
 688              self.reset()
 689  
 690      def push_accepts_more(self):
 691          if self.transformer_accumulating:
 692              return True
 693          else:
 694              return super(IPythonInputSplitter, self).push_accepts_more()
 695  
 696      def transform_cell(self, cell):
 697          """Process and translate a cell of input.
 698          """
 699          self.reset()
 700          try:
 701              self.push(cell)
 702              self.flush_transformers()
 703              return self.source
 704          finally:
 705              self.reset()
 706  
 707      def push(self, lines:str) -> bool:
 708          """Push one or more lines of IPython input.
 709  
 710          This stores the given lines and returns a status code indicating
 711          whether the code forms a complete Python block or not, after processing
 712          all input lines for special IPython syntax.
 713  
 714          Any exceptions generated in compilation are swallowed, but if an
 715          exception was produced, the method returns True.
 716  
 717          Parameters
 718          ----------
 719          lines : string
 720              One or more lines of Python input.
 721  
 722          Returns
 723          -------
 724          is_complete : boolean
 725              True if the current input source (the result of the current input
 726              plus prior inputs) forms a complete Python execution block.  Note that
 727              this value is also stored as a private attribute (_is_complete), so it
 728              can be queried at any time.
 729          """
 730          assert isinstance(lines, str)
 731          # We must ensure all input is pure unicode
 732          # ''.splitlines() --> [], but we need to push the empty line to transformers
 733          lines_list = lines.splitlines()
 734          if not lines_list:
 735              lines_list = ['']
 736  
 737          # Store raw source before applying any transformations to it.  Note
 738          # that this must be done *after* the reset() call that would otherwise
 739          # flush the buffer.
 740          self._store(lines, self._buffer_raw, 'source_raw')
 741  
 742          transformed_lines_list = []
 743          for line in lines_list:
 744              transformed = self._transform_line(line)
 745              if transformed is not None:
 746                  transformed_lines_list.append(transformed)
 747  
 748          if transformed_lines_list:
 749              transformed_lines = '\n'.join(transformed_lines_list)
 750              return super(IPythonInputSplitter, self).push(transformed_lines)
 751          else:
 752              # Got nothing back from transformers - they must be waiting for
 753              # more input.
 754              return False
 755  
 756      def _transform_line(self, line):
 757          """Push a line of input code through the various transformers.
 758  
 759          Returns any output from the transformers, or None if a transformer
 760          is accumulating lines.
 761  
 762          Sets self.transformer_accumulating as a side effect.
 763          """
 764          def _accumulating(dbg):
 765              #print(dbg)
 766              self.transformer_accumulating = True
 767              return None
 768  
 769          for transformer in self.physical_line_transforms:
 770              line = transformer.push(line)
 771              if line is None:
 772                  return _accumulating(transformer)
 773  
 774          if not self.within_python_line:
 775              line = self.assemble_logical_lines.push(line)
 776              if line is None:
 777                  return _accumulating('acc logical line')
 778  
 779              for transformer in self.logical_line_transforms:
 780                  line = transformer.push(line)
 781                  if line is None:
 782                      return _accumulating(transformer)
 783  
 784          line = self.assemble_python_lines.push(line)
 785          if line is None:
 786              self.within_python_line = True
 787              return _accumulating('acc python line')
 788          else:
 789              self.within_python_line = False
 790  
 791          for transformer in self.python_line_transforms:
 792              line = transformer.push(line)
 793              if line is None:
 794                  return _accumulating(transformer)
 795  
 796          #print("transformers clear") #debug
 797          self.transformer_accumulating = False
 798          return line
 799  
 800