statemachine.py 56 KB

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