inputsplitter.py 27 KB

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