inputsplitter.py 24 KB

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