PageRenderTime 91ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/External.LCA_RESTRICTED/Languages/IronPython/27/Doc/docutils/statemachine.py

http://github.com/IronLanguages/main
Python | 1490 lines | 1420 code | 20 blank | 50 comment | 7 complexity | 3cf3b14828965767b03b2f3125737fe1 MD5 | raw file
Possible License(s): CPL-1.0, BSD-3-Clause, ISC, GPL-2.0, MPL-2.0-no-copyleft-exception
  1. # $Id: statemachine.py 4564 2006-05-21 20:44:42Z wiemann $
  2. # Author: David Goodger <goodger@python.org>
  3. # Copyright: This module has been placed in the public domain.
  4. """
  5. A finite state machine specialized for regular-expression-based text filters,
  6. this module defines the following classes:
  7. - `StateMachine`, a state machine
  8. - `State`, a state superclass
  9. - `StateMachineWS`, a whitespace-sensitive version of `StateMachine`
  10. - `StateWS`, a state superclass for use with `StateMachineWS`
  11. - `SearchStateMachine`, uses `re.search()` instead of `re.match()`
  12. - `SearchStateMachineWS`, uses `re.search()` instead of `re.match()`
  13. - `ViewList`, extends standard Python lists.
  14. - `StringList`, string-specific ViewList.
  15. Exception classes:
  16. - `StateMachineError`
  17. - `UnknownStateError`
  18. - `DuplicateStateError`
  19. - `UnknownTransitionError`
  20. - `DuplicateTransitionError`
  21. - `TransitionPatternNotFound`
  22. - `TransitionMethodNotFound`
  23. - `UnexpectedIndentationError`
  24. - `TransitionCorrection`: Raised to switch to another transition.
  25. - `StateCorrection`: Raised to switch to another state & transition.
  26. Functions:
  27. - `string2lines()`: split a multi-line string into a list of one-line strings
  28. How To Use This Module
  29. ======================
  30. (See the individual classes, methods, and attributes for details.)
  31. 1. Import it: ``import statemachine`` or ``from statemachine import ...``.
  32. You will also need to ``import re``.
  33. 2. Derive a subclass of `State` (or `StateWS`) for each state in your state
  34. machine::
  35. class MyState(statemachine.State):
  36. Within the state's class definition:
  37. a) Include a pattern for each transition, in `State.patterns`::
  38. patterns = {'atransition': r'pattern', ...}
  39. b) Include a list of initial transitions to be set up automatically, in
  40. `State.initial_transitions`::
  41. initial_transitions = ['atransition', ...]
  42. c) Define a method for each transition, with the same name as the
  43. transition pattern::
  44. def atransition(self, match, context, next_state):
  45. # do something
  46. result = [...] # a list
  47. return context, next_state, result
  48. # context, next_state may be altered
  49. Transition methods may raise an `EOFError` to cut processing short.
  50. d) You may wish to override the `State.bof()` and/or `State.eof()` implicit
  51. transition methods, which handle the beginning- and end-of-file.
  52. e) In order to handle nested processing, you may wish to override the
  53. attributes `State.nested_sm` and/or `State.nested_sm_kwargs`.
  54. If you are using `StateWS` as a base class, in order to handle nested
  55. indented blocks, you may wish to:
  56. - override the attributes `StateWS.indent_sm`,
  57. `StateWS.indent_sm_kwargs`, `StateWS.known_indent_sm`, and/or
  58. `StateWS.known_indent_sm_kwargs`;
  59. - override the `StateWS.blank()` method; and/or
  60. - override or extend the `StateWS.indent()`, `StateWS.known_indent()`,
  61. and/or `StateWS.firstknown_indent()` methods.
  62. 3. Create a state machine object::
  63. sm = StateMachine(state_classes=[MyState, ...],
  64. initial_state='MyState')
  65. 4. Obtain the input text, which needs to be converted into a tab-free list of
  66. one-line strings. For example, to read text from a file called
  67. 'inputfile'::
  68. input_string = open('inputfile').read()
  69. input_lines = statemachine.string2lines(input_string)
  70. 5. Run the state machine on the input text and collect the results, a list::
  71. results = sm.run(input_lines)
  72. 6. Remove any lingering circular references::
  73. sm.unlink()
  74. """
  75. __docformat__ = 'restructuredtext'
  76. import sys
  77. import re
  78. import types
  79. import unicodedata
  80. class StateMachine:
  81. """
  82. A finite state machine for text filters using regular expressions.
  83. The input is provided in the form of a list of one-line strings (no
  84. newlines). States are subclasses of the `State` class. Transitions consist
  85. of regular expression patterns and transition methods, and are defined in
  86. each state.
  87. The state machine is started with the `run()` method, which returns the
  88. results of processing in a list.
  89. """
  90. def __init__(self, state_classes, initial_state, debug=0):
  91. """
  92. Initialize a `StateMachine` object; add state objects.
  93. Parameters:
  94. - `state_classes`: a list of `State` (sub)classes.
  95. - `initial_state`: a string, the class name of the initial state.
  96. - `debug`: a boolean; produce verbose output if true (nonzero).
  97. """
  98. self.input_lines = None
  99. """`StringList` of input lines (without newlines).
  100. Filled by `self.run()`."""
  101. self.input_offset = 0
  102. """Offset of `self.input_lines` from the beginning of the file."""
  103. self.line = None
  104. """Current input line."""
  105. self.line_offset = -1
  106. """Current input line offset from beginning of `self.input_lines`."""
  107. self.debug = debug
  108. """Debugging mode on/off."""
  109. self.initial_state = initial_state
  110. """The name of the initial state (key to `self.states`)."""
  111. self.current_state = initial_state
  112. """The name of the current state (key to `self.states`)."""
  113. self.states = {}
  114. """Mapping of {state_name: State_object}."""
  115. self.add_states(state_classes)
  116. self.observers = []
  117. """List of bound methods or functions to call whenever the current
  118. line changes. Observers are called with one argument, ``self``.
  119. Cleared at the end of `run()`."""
  120. def unlink(self):
  121. """Remove circular references to objects no longer required."""
  122. for state in self.states.values():
  123. state.unlink()
  124. self.states = None
  125. def run(self, input_lines, input_offset=0, context=None,
  126. input_source=None):
  127. """
  128. Run the state machine on `input_lines`. Return results (a list).
  129. Reset `self.line_offset` and `self.current_state`. Run the
  130. beginning-of-file transition. Input one line at a time and check for a
  131. matching transition. If a match is found, call the transition method
  132. and possibly change the state. Store the context returned by the
  133. transition method to be passed on to the next transition matched.
  134. Accumulate the results returned by the transition methods in a list.
  135. Run the end-of-file transition. Finally, return the accumulated
  136. results.
  137. Parameters:
  138. - `input_lines`: a list of strings without newlines, or `StringList`.
  139. - `input_offset`: the line offset of `input_lines` from the beginning
  140. of the file.
  141. - `context`: application-specific storage.
  142. - `input_source`: name or path of source of `input_lines`.
  143. """
  144. self.runtime_init()
  145. if isinstance(input_lines, StringList):
  146. self.input_lines = input_lines
  147. else:
  148. self.input_lines = StringList(input_lines, source=input_source)
  149. self.input_offset = input_offset
  150. self.line_offset = -1
  151. self.current_state = self.initial_state
  152. if self.debug:
  153. print >>sys.stderr, (
  154. '\nStateMachine.run: input_lines (line_offset=%s):\n| %s'
  155. % (self.line_offset, '\n| '.join(self.input_lines)))
  156. transitions = None
  157. results = []
  158. state = self.get_state()
  159. try:
  160. if self.debug:
  161. print >>sys.stderr, ('\nStateMachine.run: bof transition')
  162. context, result = state.bof(context)
  163. results.extend(result)
  164. while 1:
  165. try:
  166. try:
  167. self.next_line()
  168. if self.debug:
  169. source, offset = self.input_lines.info(
  170. self.line_offset)
  171. print >>sys.stderr, (
  172. '\nStateMachine.run: line (source=%r, '
  173. 'offset=%r):\n| %s'
  174. % (source, offset, self.line))
  175. context, next_state, result = self.check_line(
  176. context, state, transitions)
  177. except EOFError:
  178. if self.debug:
  179. print >>sys.stderr, (
  180. '\nStateMachine.run: %s.eof transition'
  181. % state.__class__.__name__)
  182. result = state.eof(context)
  183. results.extend(result)
  184. break
  185. else:
  186. results.extend(result)
  187. except TransitionCorrection, exception:
  188. self.previous_line() # back up for another try
  189. transitions = (exception.args[0],)
  190. if self.debug:
  191. print >>sys.stderr, (
  192. '\nStateMachine.run: TransitionCorrection to '
  193. 'state "%s", transition %s.'
  194. % (state.__class__.__name__, transitions[0]))
  195. continue
  196. except StateCorrection, exception:
  197. self.previous_line() # back up for another try
  198. next_state = exception.args[0]
  199. if len(exception.args) == 1:
  200. transitions = None
  201. else:
  202. transitions = (exception.args[1],)
  203. if self.debug:
  204. print >>sys.stderr, (
  205. '\nStateMachine.run: StateCorrection to state '
  206. '"%s", transition %s.'
  207. % (next_state, transitions[0]))
  208. else:
  209. transitions = None
  210. state = self.get_state(next_state)
  211. except:
  212. if self.debug:
  213. self.error()
  214. raise
  215. self.observers = []
  216. return results
  217. def get_state(self, next_state=None):
  218. """
  219. Return current state object; set it first if `next_state` given.
  220. Parameter `next_state`: a string, the name of the next state.
  221. Exception: `UnknownStateError` raised if `next_state` unknown.
  222. """
  223. if next_state:
  224. if self.debug and next_state != self.current_state:
  225. print >>sys.stderr, \
  226. ('\nStateMachine.get_state: Changing state from '
  227. '"%s" to "%s" (input line %s).'
  228. % (self.current_state, next_state,
  229. self.abs_line_number()))
  230. self.current_state = next_state
  231. try:
  232. return self.states[self.current_state]
  233. except KeyError:
  234. raise UnknownStateError(self.current_state)
  235. def next_line(self, n=1):
  236. """Load `self.line` with the `n`'th next line and return it."""
  237. try:
  238. try:
  239. self.line_offset += n
  240. self.line = self.input_lines[self.line_offset]
  241. except IndexError:
  242. self.line = None
  243. raise EOFError
  244. return self.line
  245. finally:
  246. self.notify_observers()
  247. def is_next_line_blank(self):
  248. """Return 1 if the next line is blank or non-existant."""
  249. try:
  250. return not self.input_lines[self.line_offset + 1].strip()
  251. except IndexError:
  252. return 1
  253. def at_eof(self):
  254. """Return 1 if the input is at or past end-of-file."""
  255. return self.line_offset >= len(self.input_lines) - 1
  256. def at_bof(self):
  257. """Return 1 if the input is at or before beginning-of-file."""
  258. return self.line_offset <= 0
  259. def previous_line(self, n=1):
  260. """Load `self.line` with the `n`'th previous line and return it."""
  261. self.line_offset -= n
  262. if self.line_offset < 0:
  263. self.line = None
  264. else:
  265. self.line = self.input_lines[self.line_offset]
  266. self.notify_observers()
  267. return self.line
  268. def goto_line(self, line_offset):
  269. """Jump to absolute line offset `line_offset`, load and return it."""
  270. try:
  271. try:
  272. self.line_offset = line_offset - self.input_offset
  273. self.line = self.input_lines[self.line_offset]
  274. except IndexError:
  275. self.line = None
  276. raise EOFError
  277. return self.line
  278. finally:
  279. self.notify_observers()
  280. def get_source(self, line_offset):
  281. """Return source of line at absolute line offset `line_offset`."""
  282. return self.input_lines.source(line_offset - self.input_offset)
  283. def abs_line_offset(self):
  284. """Return line offset of current line, from beginning of file."""
  285. return self.line_offset + self.input_offset
  286. def abs_line_number(self):
  287. """Return line number of current line (counting from 1)."""
  288. return self.line_offset + self.input_offset + 1
  289. def insert_input(self, input_lines, source):
  290. self.input_lines.insert(self.line_offset + 1, '',
  291. source='internal padding')
  292. self.input_lines.insert(self.line_offset + 1, '',
  293. source='internal padding')
  294. self.input_lines.insert(self.line_offset + 2,
  295. StringList(input_lines, source))
  296. def get_text_block(self, flush_left=0):
  297. """
  298. Return a contiguous block of text.
  299. If `flush_left` is true, raise `UnexpectedIndentationError` if an
  300. indented line is encountered before the text block ends (with a blank
  301. line).
  302. """
  303. try:
  304. block = self.input_lines.get_text_block(self.line_offset,
  305. flush_left)
  306. self.next_line(len(block) - 1)
  307. return block
  308. except UnexpectedIndentationError, error:
  309. block, source, lineno = error
  310. self.next_line(len(block) - 1) # advance to last line of block
  311. raise
  312. def check_line(self, context, state, transitions=None):
  313. """
  314. Examine one line of input for a transition match & execute its method.
  315. Parameters:
  316. - `context`: application-dependent storage.
  317. - `state`: a `State` object, the current state.
  318. - `transitions`: an optional ordered list of transition names to try,
  319. instead of ``state.transition_order``.
  320. Return the values returned by the transition method:
  321. - context: possibly modified from the parameter `context`;
  322. - next state name (`State` subclass name);
  323. - the result output of the transition, a list.
  324. When there is no match, ``state.no_match()`` is called and its return
  325. value is returned.
  326. """
  327. if transitions is None:
  328. transitions = state.transition_order
  329. state_correction = None
  330. if self.debug:
  331. print >>sys.stderr, (
  332. '\nStateMachine.check_line: state="%s", transitions=%r.'
  333. % (state.__class__.__name__, transitions))
  334. for name in transitions:
  335. pattern, method, next_state = state.transitions[name]
  336. match = self.match(pattern)
  337. if match:
  338. if self.debug:
  339. print >>sys.stderr, (
  340. '\nStateMachine.check_line: Matched transition '
  341. '"%s" in state "%s".'
  342. % (name, state.__class__.__name__))
  343. return method(match, context, next_state)
  344. else:
  345. if self.debug:
  346. print >>sys.stderr, (
  347. '\nStateMachine.check_line: No match in state "%s".'
  348. % state.__class__.__name__)
  349. return state.no_match(context, transitions)
  350. def match(self, pattern):
  351. """
  352. Return the result of a regular expression match.
  353. Parameter `pattern`: an `re` compiled regular expression.
  354. """
  355. return pattern.match(self.line)
  356. def add_state(self, state_class):
  357. """
  358. Initialize & add a `state_class` (`State` subclass) object.
  359. Exception: `DuplicateStateError` raised if `state_class` was already
  360. added.
  361. """
  362. statename = state_class.__name__
  363. if self.states.has_key(statename):
  364. raise DuplicateStateError(statename)
  365. self.states[statename] = state_class(self, self.debug)
  366. def add_states(self, state_classes):
  367. """
  368. Add `state_classes` (a list of `State` subclasses).
  369. """
  370. for state_class in state_classes:
  371. self.add_state(state_class)
  372. def runtime_init(self):
  373. """
  374. Initialize `self.states`.
  375. """
  376. for state in self.states.values():
  377. state.runtime_init()
  378. def error(self):
  379. """Report error details."""
  380. type, value, module, line, function = _exception_data()
  381. print >>sys.stderr, '%s: %s' % (type, value)
  382. print >>sys.stderr, 'input line %s' % (self.abs_line_number())
  383. print >>sys.stderr, ('module %s, line %s, function %s'
  384. % (module, line, function))
  385. def attach_observer(self, observer):
  386. """
  387. The `observer` parameter is a function or bound method which takes two
  388. arguments, the source and offset of the current line.
  389. """
  390. self.observers.append(observer)
  391. def detach_observer(self, observer):
  392. self.observers.remove(observer)
  393. def notify_observers(self):
  394. for observer in self.observers:
  395. try:
  396. info = self.input_lines.info(self.line_offset)
  397. except IndexError:
  398. info = (None, None)
  399. observer(*info)
  400. class State:
  401. """
  402. State superclass. Contains a list of transitions, and transition methods.
  403. Transition methods all have the same signature. They take 3 parameters:
  404. - An `re` match object. ``match.string`` contains the matched input line,
  405. ``match.start()`` gives the start index of the match, and
  406. ``match.end()`` gives the end index.
  407. - A context object, whose meaning is application-defined (initial value
  408. ``None``). It can be used to store any information required by the state
  409. machine, and the retured context is passed on to the next transition
  410. method unchanged.
  411. - The name of the next state, a string, taken from the transitions list;
  412. normally it is returned unchanged, but it may be altered by the
  413. transition method if necessary.
  414. Transition methods all return a 3-tuple:
  415. - A context object, as (potentially) modified by the transition method.
  416. - The next state name (a return value of ``None`` means no state change).
  417. - The processing result, a list, which is accumulated by the state
  418. machine.
  419. Transition methods may raise an `EOFError` to cut processing short.
  420. There are two implicit transitions, and corresponding transition methods
  421. are defined: `bof()` handles the beginning-of-file, and `eof()` handles
  422. the end-of-file. These methods have non-standard signatures and return
  423. values. `bof()` returns the initial context and results, and may be used
  424. to return a header string, or do any other processing needed. `eof()`
  425. should handle any remaining context and wrap things up; it returns the
  426. final processing result.
  427. Typical applications need only subclass `State` (or a subclass), set the
  428. `patterns` and `initial_transitions` class attributes, and provide
  429. corresponding transition methods. The default object initialization will
  430. take care of constructing the list of transitions.
  431. """
  432. patterns = None
  433. """
  434. {Name: pattern} mapping, used by `make_transition()`. Each pattern may
  435. be a string or a compiled `re` pattern. Override in subclasses.
  436. """
  437. initial_transitions = None
  438. """
  439. A list of transitions to initialize when a `State` is instantiated.
  440. Each entry is either a transition name string, or a (transition name, next
  441. state name) pair. See `make_transitions()`. Override in subclasses.
  442. """
  443. nested_sm = None
  444. """
  445. The `StateMachine` class for handling nested processing.
  446. If left as ``None``, `nested_sm` defaults to the class of the state's
  447. controlling state machine. Override it in subclasses to avoid the default.
  448. """
  449. nested_sm_kwargs = None
  450. """
  451. Keyword arguments dictionary, passed to the `nested_sm` constructor.
  452. Two keys must have entries in the dictionary:
  453. - Key 'state_classes' must be set to a list of `State` classes.
  454. - Key 'initial_state' must be set to the name of the initial state class.
  455. If `nested_sm_kwargs` is left as ``None``, 'state_classes' defaults to the
  456. class of the current state, and 'initial_state' defaults to the name of
  457. the class of the current state. Override in subclasses to avoid the
  458. defaults.
  459. """
  460. def __init__(self, state_machine, debug=0):
  461. """
  462. Initialize a `State` object; make & add initial transitions.
  463. Parameters:
  464. - `statemachine`: the controlling `StateMachine` object.
  465. - `debug`: a boolean; produce verbose output if true (nonzero).
  466. """
  467. self.transition_order = []
  468. """A list of transition names in search order."""
  469. self.transitions = {}
  470. """
  471. A mapping of transition names to 3-tuples containing
  472. (compiled_pattern, transition_method, next_state_name). Initialized as
  473. an instance attribute dynamically (instead of as a class attribute)
  474. because it may make forward references to patterns and methods in this
  475. or other classes.
  476. """
  477. self.add_initial_transitions()
  478. self.state_machine = state_machine
  479. """A reference to the controlling `StateMachine` object."""
  480. self.debug = debug
  481. """Debugging mode on/off."""
  482. if self.nested_sm is None:
  483. self.nested_sm = self.state_machine.__class__
  484. if self.nested_sm_kwargs is None:
  485. self.nested_sm_kwargs = {'state_classes': [self.__class__],
  486. 'initial_state': self.__class__.__name__}
  487. def runtime_init(self):
  488. """
  489. Initialize this `State` before running the state machine; called from
  490. `self.state_machine.run()`.
  491. """
  492. pass
  493. def unlink(self):
  494. """Remove circular references to objects no longer required."""
  495. self.state_machine = None
  496. def add_initial_transitions(self):
  497. """Make and add transitions listed in `self.initial_transitions`."""
  498. if self.initial_transitions:
  499. names, transitions = self.make_transitions(
  500. self.initial_transitions)
  501. self.add_transitions(names, transitions)
  502. def add_transitions(self, names, transitions):
  503. """
  504. Add a list of transitions to the start of the transition list.
  505. Parameters:
  506. - `names`: a list of transition names.
  507. - `transitions`: a mapping of names to transition tuples.
  508. Exceptions: `DuplicateTransitionError`, `UnknownTransitionError`.
  509. """
  510. for name in names:
  511. if self.transitions.has_key(name):
  512. raise DuplicateTransitionError(name)
  513. if not transitions.has_key(name):
  514. raise UnknownTransitionError(name)
  515. self.transition_order[:0] = names
  516. self.transitions.update(transitions)
  517. def add_transition(self, name, transition):
  518. """
  519. Add a transition to the start of the transition list.
  520. Parameter `transition`: a ready-made transition 3-tuple.
  521. Exception: `DuplicateTransitionError`.
  522. """
  523. if self.transitions.has_key(name):
  524. raise DuplicateTransitionError(name)
  525. self.transition_order[:0] = [name]
  526. self.transitions[name] = transition
  527. def remove_transition(self, name):
  528. """
  529. Remove a transition by `name`.
  530. Exception: `UnknownTransitionError`.
  531. """
  532. try:
  533. del self.transitions[name]
  534. self.transition_order.remove(name)
  535. except:
  536. raise UnknownTransitionError(name)
  537. def make_transition(self, name, next_state=None):
  538. """
  539. Make & return a transition tuple based on `name`.
  540. This is a convenience function to simplify transition creation.
  541. Parameters:
  542. - `name`: a string, the name of the transition pattern & method. This
  543. `State` object must have a method called '`name`', and a dictionary
  544. `self.patterns` containing a key '`name`'.
  545. - `next_state`: a string, the name of the next `State` object for this
  546. transition. A value of ``None`` (or absent) implies no state change
  547. (i.e., continue with the same state).
  548. Exceptions: `TransitionPatternNotFound`, `TransitionMethodNotFound`.
  549. """
  550. if next_state is None:
  551. next_state = self.__class__.__name__
  552. try:
  553. pattern = self.patterns[name]
  554. if not hasattr(pattern, 'match'):
  555. pattern = re.compile(pattern)
  556. except KeyError:
  557. raise TransitionPatternNotFound(
  558. '%s.patterns[%r]' % (self.__class__.__name__, name))
  559. try:
  560. method = getattr(self, name)
  561. except AttributeError:
  562. raise TransitionMethodNotFound(
  563. '%s.%s' % (self.__class__.__name__, name))
  564. return (pattern, method, next_state)
  565. def make_transitions(self, name_list):
  566. """
  567. Return a list of transition names and a transition mapping.
  568. Parameter `name_list`: a list, where each entry is either a transition
  569. name string, or a 1- or 2-tuple (transition name, optional next state
  570. name).
  571. """
  572. stringtype = type('')
  573. names = []
  574. transitions = {}
  575. for namestate in name_list:
  576. if type(namestate) is stringtype:
  577. transitions[namestate] = self.make_transition(namestate)
  578. names.append(namestate)
  579. else:
  580. transitions[namestate[0]] = self.make_transition(*namestate)
  581. names.append(namestate[0])
  582. return names, transitions
  583. def no_match(self, context, transitions):
  584. """
  585. Called when there is no match from `StateMachine.check_line()`.
  586. Return the same values returned by transition methods:
  587. - context: unchanged;
  588. - next state name: ``None``;
  589. - empty result list.
  590. Override in subclasses to catch this event.
  591. """
  592. return context, None, []
  593. def bof(self, context):
  594. """
  595. Handle beginning-of-file. Return unchanged `context`, empty result.
  596. Override in subclasses.
  597. Parameter `context`: application-defined storage.
  598. """
  599. return context, []
  600. def eof(self, context):
  601. """
  602. Handle end-of-file. Return empty result.
  603. Override in subclasses.
  604. Parameter `context`: application-defined storage.
  605. """
  606. return []
  607. def nop(self, match, context, next_state):
  608. """
  609. A "do nothing" transition method.
  610. Return unchanged `context` & `next_state`, empty result. Useful for
  611. simple state changes (actionless transitions).
  612. """
  613. return context, next_state, []
  614. class StateMachineWS(StateMachine):
  615. """
  616. `StateMachine` subclass specialized for whitespace recognition.
  617. There are three methods provided for extracting indented text blocks:
  618. - `get_indented()`: use when the indent is unknown.
  619. - `get_known_indented()`: use when the indent is known for all lines.
  620. - `get_first_known_indented()`: use when only the first line's indent is
  621. known.
  622. """
  623. def get_indented(self, until_blank=0, strip_indent=1):
  624. """
  625. Return a block of indented lines of text, and info.
  626. Extract an indented block where the indent is unknown for all lines.
  627. :Parameters:
  628. - `until_blank`: Stop collecting at the first blank line if true
  629. (1).
  630. - `strip_indent`: Strip common leading indent if true (1,
  631. default).
  632. :Return:
  633. - the indented block (a list of lines of text),
  634. - its indent,
  635. - its first line offset from BOF, and
  636. - whether or not it finished with a blank line.
  637. """
  638. offset = self.abs_line_offset()
  639. indented, indent, blank_finish = self.input_lines.get_indented(
  640. self.line_offset, until_blank, strip_indent)
  641. if indented:
  642. self.next_line(len(indented) - 1) # advance to last indented line
  643. while indented and not indented[0].strip():
  644. indented.trim_start()
  645. offset += 1
  646. return indented, indent, offset, blank_finish
  647. def get_known_indented(self, indent, until_blank=0, strip_indent=1):
  648. """
  649. Return an indented block and info.
  650. Extract an indented block where the indent is known for all lines.
  651. Starting with the current line, extract the entire text block with at
  652. least `indent` indentation (which must be whitespace, except for the
  653. first line).
  654. :Parameters:
  655. - `indent`: The number of indent columns/characters.
  656. - `until_blank`: Stop collecting at the first blank line if true
  657. (1).
  658. - `strip_indent`: Strip `indent` characters of indentation if true
  659. (1, default).
  660. :Return:
  661. - the indented block,
  662. - its first line offset from BOF, and
  663. - whether or not it finished with a blank line.
  664. """
  665. offset = self.abs_line_offset()
  666. indented, indent, blank_finish = self.input_lines.get_indented(
  667. self.line_offset, until_blank, strip_indent,
  668. block_indent=indent)
  669. self.next_line(len(indented) - 1) # advance to last indented line
  670. while indented and not indented[0].strip():
  671. indented.trim_start()
  672. offset += 1
  673. return indented, offset, blank_finish
  674. def get_first_known_indented(self, indent, until_blank=0, strip_indent=1,
  675. strip_top=1):
  676. """
  677. Return an indented block and info.
  678. Extract an indented block where the indent is known for the first line
  679. and unknown for all other lines.
  680. :Parameters:
  681. - `indent`: The first line's indent (# of columns/characters).
  682. - `until_blank`: Stop collecting at the first blank line if true
  683. (1).
  684. - `strip_indent`: Strip `indent` characters of indentation if true
  685. (1, default).
  686. - `strip_top`: Strip blank lines from the beginning of the block.
  687. :Return:
  688. - the indented block,
  689. - its indent,
  690. - its first line offset from BOF, and
  691. - whether or not it finished with a blank line.
  692. """
  693. offset = self.abs_line_offset()
  694. indented, indent, blank_finish = self.input_lines.get_indented(
  695. self.line_offset, until_blank, strip_indent,
  696. first_indent=indent)
  697. self.next_line(len(indented) - 1) # advance to last indented line
  698. if strip_top:
  699. while indented and not indented[0].strip():
  700. indented.trim_start()
  701. offset += 1
  702. return indented, indent, offset, blank_finish
  703. class StateWS(State):
  704. """
  705. State superclass specialized for whitespace (blank lines & indents).
  706. Use this class with `StateMachineWS`. The transitions 'blank' (for blank
  707. lines) and 'indent' (for indented text blocks) are added automatically,
  708. before any other transitions. The transition method `blank()` handles
  709. blank lines and `indent()` handles nested indented blocks. Indented
  710. blocks trigger a new state machine to be created by `indent()` and run.
  711. The class of the state machine to be created is in `indent_sm`, and the
  712. constructor keyword arguments are in the dictionary `indent_sm_kwargs`.
  713. The methods `known_indent()` and `firstknown_indent()` are provided for
  714. indented blocks where the indent (all lines' and first line's only,
  715. respectively) is known to the transition method, along with the attributes
  716. `known_indent_sm` and `known_indent_sm_kwargs`. Neither transition method
  717. is triggered automatically.
  718. """
  719. indent_sm = None
  720. """
  721. The `StateMachine` class handling indented text blocks.
  722. If left as ``None``, `indent_sm` defaults to the value of
  723. `State.nested_sm`. Override it in subclasses to avoid the default.
  724. """
  725. indent_sm_kwargs = None
  726. """
  727. Keyword arguments dictionary, passed to the `indent_sm` constructor.
  728. If left as ``None``, `indent_sm_kwargs` defaults to the value of
  729. `State.nested_sm_kwargs`. Override it in subclasses to avoid the default.
  730. """
  731. known_indent_sm = None
  732. """
  733. The `StateMachine` class handling known-indented text blocks.
  734. If left as ``None``, `known_indent_sm` defaults to the value of
  735. `indent_sm`. Override it in subclasses to avoid the default.
  736. """
  737. known_indent_sm_kwargs = None
  738. """
  739. Keyword arguments dictionary, passed to the `known_indent_sm` constructor.
  740. If left as ``None``, `known_indent_sm_kwargs` defaults to the value of
  741. `indent_sm_kwargs`. Override it in subclasses to avoid the default.
  742. """
  743. ws_patterns = {'blank': ' *$',
  744. 'indent': ' +'}
  745. """Patterns for default whitespace transitions. May be overridden in
  746. subclasses."""
  747. ws_initial_transitions = ('blank', 'indent')
  748. """Default initial whitespace transitions, added before those listed in
  749. `State.initial_transitions`. May be overridden in subclasses."""
  750. def __init__(self, state_machine, debug=0):
  751. """
  752. Initialize a `StateSM` object; extends `State.__init__()`.
  753. Check for indent state machine attributes, set defaults if not set.
  754. """
  755. State.__init__(self, state_machine, debug)
  756. if self.indent_sm is None:
  757. self.indent_sm = self.nested_sm
  758. if self.indent_sm_kwargs is None:
  759. self.indent_sm_kwargs = self.nested_sm_kwargs
  760. if self.known_indent_sm is None:
  761. self.known_indent_sm = self.indent_sm
  762. if self.known_indent_sm_kwargs is None:
  763. self.known_indent_sm_kwargs = self.indent_sm_kwargs
  764. def add_initial_transitions(self):
  765. """
  766. Add whitespace-specific transitions before those defined in subclass.
  767. Extends `State.add_initial_transitions()`.
  768. """
  769. State.add_initial_transitions(self)
  770. if self.patterns is None:
  771. self.patterns = {}
  772. self.patterns.update(self.ws_patterns)
  773. names, transitions = self.make_transitions(
  774. self.ws_initial_transitions)
  775. self.add_transitions(names, transitions)
  776. def blank(self, match, context, next_state):
  777. """Handle blank lines. Does nothing. Override in subclasses."""
  778. return self.nop(match, context, next_state)
  779. def indent(self, match, context, next_state):
  780. """
  781. Handle an indented text block. Extend or override in subclasses.
  782. Recursively run the registered state machine for indented blocks
  783. (`self.indent_sm`).
  784. """
  785. indented, indent, line_offset, blank_finish = \
  786. self.state_machine.get_indented()
  787. sm = self.indent_sm(debug=self.debug, **self.indent_sm_kwargs)
  788. results = sm.run(indented, input_offset=line_offset)
  789. return context, next_state, results
  790. def known_indent(self, match, context, next_state):
  791. """
  792. Handle a known-indent text block. Extend or override in subclasses.
  793. Recursively run the registered state machine for known-indent indented
  794. blocks (`self.known_indent_sm`). The indent is the length of the
  795. match, ``match.end()``.
  796. """
  797. indented, line_offset, blank_finish = \
  798. self.state_machine.get_known_indented(match.end())
  799. sm = self.known_indent_sm(debug=self.debug,
  800. **self.known_indent_sm_kwargs)
  801. results = sm.run(indented, input_offset=line_offset)
  802. return context, next_state, results
  803. def first_known_indent(self, match, context, next_state):
  804. """
  805. Handle an indented text block (first line's indent known).
  806. Extend or override in subclasses.
  807. Recursively run the registered state machine for known-indent indented
  808. blocks (`self.known_indent_sm`). The indent is the length of the
  809. match, ``match.end()``.
  810. """
  811. indented, line_offset, blank_finish = \
  812. self.state_machine.get_first_known_indented(match.end())
  813. sm = self.known_indent_sm(debug=self.debug,
  814. **self.known_indent_sm_kwargs)
  815. results = sm.run(indented, input_offset=line_offset)
  816. return context, next_state, results
  817. class _SearchOverride:
  818. """
  819. Mix-in class to override `StateMachine` regular expression behavior.
  820. Changes regular expression matching, from the default `re.match()`
  821. (succeeds only if the pattern matches at the start of `self.line`) to
  822. `re.search()` (succeeds if the pattern matches anywhere in `self.line`).
  823. When subclassing a `StateMachine`, list this class **first** in the
  824. inheritance list of the class definition.
  825. """
  826. def match(self, pattern):
  827. """
  828. Return the result of a regular expression search.
  829. Overrides `StateMachine.match()`.
  830. Parameter `pattern`: `re` compiled regular expression.
  831. """
  832. return pattern.search(self.line)
  833. class SearchStateMachine(_SearchOverride, StateMachine):
  834. """`StateMachine` which uses `re.search()` instead of `re.match()`."""
  835. pass
  836. class SearchStateMachineWS(_SearchOverride, StateMachineWS):
  837. """`StateMachineWS` which uses `re.search()` instead of `re.match()`."""
  838. pass
  839. class ViewList:
  840. """
  841. List with extended functionality: slices of ViewList objects are child
  842. lists, linked to their parents. Changes made to a child list also affect
  843. the parent list. A child list is effectively a "view" (in the SQL sense)
  844. of the parent list. Changes to parent lists, however, do *not* affect
  845. active child lists. If a parent list is changed, any active child lists
  846. should be recreated.
  847. The start and end of the slice can be trimmed using the `trim_start()` and
  848. `trim_end()` methods, without affecting the parent list. The link between
  849. child and parent lists can be broken by calling `disconnect()` on the
  850. child list.
  851. Also, ViewList objects keep track of the source & offset of each item.
  852. This information is accessible via the `source()`, `offset()`, and
  853. `info()` methods.
  854. """
  855. def __init__(self, initlist=None, source=None, items=None,
  856. parent=None, parent_offset=None):
  857. self.data = []
  858. """The actual list of data, flattened from various sources."""
  859. self.items = []
  860. """A list of (source, offset) pairs, same length as `self.data`: the
  861. source of each line and the offset of each line from the beginning of
  862. its source."""
  863. self.parent = parent
  864. """The parent list."""
  865. self.parent_offset = parent_offset
  866. """Offset of this list from the beginning of the parent list."""
  867. if isinstance(initlist, ViewList):
  868. self.data = initlist.data[:]
  869. self.items = initlist.items[:]
  870. elif initlist is not None:
  871. self.data = list(initlist)
  872. if items:
  873. self.items = items
  874. else:
  875. self.items = [(source, i) for i in range(len(initlist))]
  876. assert len(self.data) == len(self.items), 'data mismatch'
  877. def __str__(self):
  878. return str(self.data)
  879. def __repr__(self):
  880. return '%s(%s, items=%s)' % (self.__class__.__name__,
  881. self.data, self.items)
  882. def __lt__(self, other): return self.data < self.__cast(other)
  883. def __le__(self, other): return self.data <= self.__cast(other)
  884. def __eq__(self, other): return self.data == self.__cast(other)
  885. def __ne__(self, other): return self.data != self.__cast(other)
  886. def __gt__(self, other): return self.data > self.__cast(other)
  887. def __ge__(self, other): return self.data >= self.__cast(other)
  888. def __cmp__(self, other): return cmp(self.data, self.__cast(other))
  889. def __cast(self, other):
  890. if isinstance(other, ViewList):
  891. return other.data
  892. else:
  893. return other
  894. def __contains__(self, item): return item in self.data
  895. def __len__(self): return len(self.data)
  896. # The __getitem__()/__setitem__() methods check whether the index
  897. # is a slice first, since native list objects start supporting
  898. # them directly in Python 2.3 (no exception is raised when
  899. # indexing a list with a slice object; they just work).
  900. def __getitem__(self, i):
  901. if isinstance(i, types.SliceType):
  902. assert i.step in (None, 1), 'cannot handle slice with stride'
  903. return self.__class__(self.data[i.start:i.stop],
  904. items=self.items[i.start:i.stop],
  905. parent=self, parent_offset=i.start)
  906. else:
  907. return self.data[i]
  908. def __setitem__(self, i, item):
  909. if isinstance(i, types.SliceType):
  910. assert i.step in (None, 1), 'cannot handle slice with stride'
  911. if not isinstance(item, ViewList):
  912. raise TypeError('assigning non-ViewList to ViewList slice')
  913. self.data[i.start:i.stop] = item.data
  914. self.items[i.start:i.stop] = item.items
  915. assert len(self.data) == len(self.items), 'data mismatch'
  916. if self.parent:
  917. self.parent[i.start + self.parent_offset
  918. : i.stop + self.parent_offset] = item
  919. else:
  920. self.data[i] = item
  921. if self.parent:
  922. self.parent[i + self.parent_offset] = item
  923. def __delitem__(self, i):
  924. try:
  925. del self.data[i]
  926. del self.items[i]
  927. if self.parent:
  928. del self.parent[i + self.parent_offset]
  929. except TypeError:
  930. assert i.step is None, 'cannot handle slice with stride'
  931. del self.data[i.start:i.stop]
  932. del self.items[i.start:i.stop]
  933. if self.parent:
  934. del self.parent[i.start + self.parent_offset
  935. : i.stop + self.parent_offset]
  936. def __add__(self, other):
  937. if isinstance(other, ViewList):
  938. return self.__class__(self.data + other.data,
  939. items=(self.items + other.items))
  940. else:
  941. raise TypeError('adding non-ViewList to a ViewList')
  942. def __radd__(self, other):
  943. if isinstance(other, ViewList):
  944. return self.__class__(other.data + self.data,
  945. items=(other.items + self.items))
  946. else:
  947. raise TypeError('adding ViewList to a non-ViewList')
  948. def __iadd__(self, other):
  949. if isinstance(other, ViewList):
  950. self.data += other.data
  951. else:
  952. raise TypeError('argument to += must be a ViewList')
  953. return self
  954. def __mul__(self, n):
  955. return self.__class__(self.data * n, items=(self.items * n))
  956. __rmul__ = __mul__
  957. def __imul__(self, n):
  958. self.data *= n
  959. self.items *= n
  960. return self
  961. def extend(self, other):
  962. if not isinstance(other, ViewList):
  963. raise TypeError('extending a ViewList with a non-ViewList')
  964. if self.parent:
  965. self.parent.insert(len(self.data) + self.parent_offset, other)
  966. self.data.extend(other.data)
  967. self.items.extend(other.items)
  968. def append(self, item, source=None, offset=0):
  969. if source is None:
  970. self.extend(item)
  971. else:
  972. if self.parent:
  973. self.parent.insert(len(self.data) + self.parent_offset, item,
  974. source, offset)
  975. self.data.append(item)
  976. self.items.append((source, offset))
  977. def insert(self, i, item, source=None, offset=0):
  978. if source is None:
  979. if not isinstance(item, ViewList):
  980. raise TypeError('inserting non-ViewList with no source given')
  981. self.data[i:i] = item.data
  982. self.items[i:i] = item.items
  983. if self.parent:
  984. index = (len(self.data) + i) % len(self.data)
  985. self.parent.insert(index + self.parent_offset, item)
  986. else:
  987. self.data.insert(i, item)
  988. self.items.insert(i, (source, offset))
  989. if self.parent:
  990. index = (len(self.data) + i) % len(self.data)
  991. self.parent.insert(index + self.parent_offset, item,
  992. source, offset)
  993. def pop(self, i=-1):
  994. if self.parent:
  995. index = (len(self.data) + i) % len(self.data)
  996. self.parent.pop(index + self.parent_offset)
  997. self.items.pop(i)
  998. return self.data.pop(i)
  999. def trim_start(self, n=1):
  1000. """
  1001. Remove items from the start of the list, without touching the parent.
  1002. """
  1003. if n > len(self.data):
  1004. raise IndexError("Size of trim too large; can't trim %s items "
  1005. "from a list of size %s." % (n, len(self.data)))
  1006. elif n < 0:
  1007. raise IndexError('Trim size must be >= 0.')
  1008. del self.data[:n]
  1009. del self.items[:n]
  1010. if self.parent:
  1011. self.parent_offset += n
  1012. def trim_end(self, n=1):
  1013. """
  1014. Remove items from the end of the list, without touching the parent.
  1015. """
  1016. if n > len(self.data):
  1017. raise IndexError("Size of trim too large; can't trim %s items "
  1018. "from a list of size %s." % (n, len(self.data)))
  1019. elif n < 0:
  1020. raise IndexError('Trim size must be >= 0.')
  1021. del self.data[-n:]
  1022. del self.items[-n:]
  1023. def remove(self, item):
  1024. index = self.index(item)
  1025. del self[index]
  1026. def count(self, item): return self.data.count(item)
  1027. def index(self, item): return self.data.index(item)
  1028. def reverse(self):
  1029. self.data.reverse()
  1030. self.items.reverse()
  1031. self.parent = None
  1032. def sort(self, *args):
  1033. tmp = zip(self.data, self.items)
  1034. tmp.sort(*args)
  1035. self.data = [entry[0] for entry in tmp]
  1036. self.items = [entry[1] for entry in tmp]
  1037. self.parent = None
  1038. def info(self, i):
  1039. """Return source & offset for index `i`."""
  1040. try:
  1041. return self.items[i]
  1042. except IndexError:
  1043. if i == len(self.data): # Just past the end
  1044. return self.items[i - 1][0], None
  1045. else:
  1046. raise
  1047. def source(self, i):
  1048. """Return source for index `i`."""
  1049. return self.info(i)[0]
  1050. def offset(self, i):
  1051. """Return offset for index `i`."""
  1052. return self.info(i)[1]
  1053. def disconnect(self):
  1054. """Break link between this list and parent list."""
  1055. self.parent = None
  1056. class StringList(ViewList):
  1057. """A `ViewList` with string-specific methods."""
  1058. def trim_left(self, length, start=0, end=sys.maxint):
  1059. """
  1060. Trim `length` characters off the beginning of each item, in-place,
  1061. from index `start` to `end`. No whitespace-checking is done on the
  1062. trimmed text. Does not affect slice parent.
  1063. """
  1064. self.data[start:end] = [line[length:]
  1065. for line in self.data[start:end]]
  1066. def get_text_block(self, start, flush_left=0):
  1067. """
  1068. Return a contiguous block of text.
  1069. If `flush_left` is true, raise `UnexpectedIndentationError` if an
  1070. indented line is encountered before the text block ends (with a blank
  1071. line).
  1072. """
  1073. end = start
  1074. last = len(self.data)
  1075. while end < last:
  1076. line = self.data[end]
  1077. if not line.strip():
  1078. break
  1079. if flush_left and (line[0] == ' '):
  1080. source, offset = self.info(end)
  1081. raise UnexpectedIndentationError(self[start:end], source,
  1082. offset + 1)
  1083. end += 1
  1084. return self[start:end]
  1085. def get_indented(self, start=0, until_blank=0, strip_indent=1,
  1086. block_indent=None, first_indent=None):
  1087. """
  1088. Extract and return a StringList of indented lines of text.
  1089. Collect all lines with indentation, determine the minimum indentation,
  1090. remove the minimum indentation from all indented lines (unless
  1091. `strip_indent` is false), and return them. All lines up to but not
  1092. including the first unindented line will be returned.
  1093. :Parameters:
  1094. - `start`: The index of the first line to examine.
  1095. - `until_blank`: Stop collecting at the first blank line if true.
  1096. - `strip_indent`: Strip common leading indent if true (default).
  1097. - `block_indent`: The indent of the entire block, if known.
  1098. - `first_indent`: The indent of the first line, if known.
  1099. :Return:
  1100. - a StringList of indented lines with mininum indent removed;
  1101. - the amount of the indent;
  1102. - a boolean: did the indented block finish with a blank line or EOF?
  1103. """
  1104. indent = block_indent # start with None if unknown
  1105. end = start
  1106. if block_indent is not None and first_indent is None:
  1107. first_indent = block_indent
  1108. if first_indent is not None:
  1109. end += 1
  1110. last = len(self.data)
  1111. while end < last:
  1112. line = self.data[end]
  1113. if line and (line[0] != ' '
  1114. or (block_indent is not None
  1115. and line[:block_indent].strip())):
  1116. # Line not indented or insufficiently indented.
  1117. # Block finished properly iff the last indented line blank:
  1118. blank_finish = ((end > start)
  1119. and not self.data[end - 1].strip())
  1120. break
  1121. stripped = line.lstrip()
  1122. if not stripped: # blank line
  1123. if until_blank:
  1124. blank_finish = 1
  1125. break
  1126. elif block_indent is None:
  1127. line_indent = len(line) - len(stripped)
  1128. if indent is None:
  1129. indent = line_indent
  1130. else:
  1131. indent = min(indent, line_indent)
  1132. end += 1
  1133. else:
  1134. blank_finish = 1 # block ends at end of lines
  1135. block = self[start:end]
  1136. if first_indent is not None and block:
  1137. block.data[0] = block.data[0][first_indent:]
  1138. if indent and strip_indent:
  1139. block.trim_left(indent, start=(first_indent is not None))
  1140. return block, indent or 0, blank_finish
  1141. def get_2D_block(self, top, left, bottom, right, strip_indent=1):
  1142. block = self[top:bottom]
  1143. indent = right
  1144. for i in range(len(block.data)):
  1145. block.data[i] = line = block.data[i][left:right].rstrip()
  1146. if line:
  1147. indent = min(indent, len(line) - len(line.lstrip()))
  1148. if strip_indent and 0 < indent < right:
  1149. block.data = [line[indent:] for line in block.data]
  1150. return block
  1151. def pad_double_width(self, pad_char):
  1152. """
  1153. Pad all double-width characters in self by appending `pad_char` to each.
  1154. For East Asian language support.
  1155. """
  1156. if hasattr(unicodedata, 'east_asian_width'):
  1157. east_asian_width = unicodedata.east_asian_width
  1158. else:
  1159. return # new in Python 2.4
  1160. for i in range(len(self.data)):
  1161. line = self.data[i]
  1162. if isinstance(line, types.UnicodeType):
  1163. new = []
  1164. for char in line:
  1165. new.append(char)
  1166. if east_asian_width(char) in 'WF': # 'W'ide & 'F'ull-width
  1167. new.append(pad_char)
  1168. self.data[i] = ''.join(new)
  1169. def replace(self, old, new):
  1170. """Replace all occurrences of substring `old` with `new`."""
  1171. for i in range(len(self.data)):
  1172. self.data[i] = self.data[i].replace(old, new)
  1173. class StateMachineError(Exception): pass
  1174. class UnknownStateError(StateMachineError): pass
  1175. class DuplicateStateError(StateMachineError): pass
  1176. class UnknownTransitionError(StateMachineError): pass
  1177. class DuplicateTransitionError(StateMachineError): pass
  1178. class TransitionPatternNotFound(StateMachineError): pass
  1179. class TransitionMethodNotFound(StateMachineError): pass
  1180. class UnexpectedIndentationError(StateMachineError): pass
  1181. class TransitionCorrection(Exception):
  1182. """
  1183. Raise from within a transition method to switch to another transition.
  1184. Raise with one argument, the new transition name.
  1185. """
  1186. class StateCorrection(Exception):
  1187. """
  1188. Raise from within a transition method to switch to another state.
  1189. Raise with one or two arguments: new state name, and an optional new
  1190. transition name.
  1191. """
  1192. def string2lines(astring, tab_width=8, convert_whitespace=0,
  1193. whitespace=re.compile('[\v\f]')):
  1194. """
  1195. Return a list of one-line strings with tabs expanded, no newlines, and
  1196. trailing whitespace stripped.
  1197. Each tab is expanded with between 1 and `tab_width` spaces, so that the
  1198. next character's index becomes a multiple of `tab_width` (8 by default).
  1199. Parameters:
  1200. - `astring`: a multi-line string.
  1201. - `tab_width`: the number of columns between tab stops.
  1202. - `convert_whitespace`: convert form feeds and vertical tabs to spaces?
  1203. """
  1204. if convert_whitespace:
  1205. astring = whitespace.sub(' ', astring)
  1206. return [s.expandtabs(tab_width).rstrip() for s in astring.splitlines()]
  1207. def _exception_data():
  1208. """
  1209. Return exception information:
  1210. - the exception's class name;
  1211. - the exception object;
  1212. - the name of the file containing the offending code;
  1213. - the line number of the offending code;
  1214. - the function name of the offending code.
  1215. """
  1216. type, value, traceback = sys.exc_info()
  1217. while traceback.tb_next:
  1218. traceback = traceback.tb_next
  1219. code = traceback.tb_frame.f_code
  1220. return (type.__name__, value, code.co_filename, traceback.tb_lineno,
  1221. code.co_name)