inputsplitter.py 28 KB

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