You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1538 lines
56 KiB

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