inputsplitter.py 28 KB

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