m iEc@sdZdZdkZdkZdkZdkZdfdYZdfdYZdefdYZd efd YZ d fd YZ d e efdYZ de efdYZ dfdYZ de fdYZdefdYZdefdYZdefdYZdefdYZdefdYZdefd YZd!efd"YZd#efd$YZd%efd&YZd'efd(YZd)d*eid+d,Zd-ZdS(.s A finite state machine specialized for regular-expression-based text filters, this module defines the following classes: - `StateMachine`, a state machine - `State`, a state superclass - `StateMachineWS`, a whitespace-sensitive version of `StateMachine` - `StateWS`, a state superclass for use with `StateMachineWS` - `SearchStateMachine`, uses `re.search()` instead of `re.match()` - `SearchStateMachineWS`, uses `re.search()` instead of `re.match()` - `ViewList`, extends standard Python lists. - `StringList`, string-specific ViewList. Exception classes: - `StateMachineError` - `UnknownStateError` - `DuplicateStateError` - `UnknownTransitionError` - `DuplicateTransitionError` - `TransitionPatternNotFound` - `TransitionMethodNotFound` - `UnexpectedIndentationError` - `TransitionCorrection`: Raised to switch to another transition. - `StateCorrection`: Raised to switch to another state & transition. Functions: - `string2lines()`: split a multi-line string into a list of one-line strings How To Use This Module ====================== (See the individual classes, methods, and attributes for details.) 1. Import it: ``import statemachine`` or ``from statemachine import ...``. You will also need to ``import re``. 2. Derive a subclass of `State` (or `StateWS`) for each state in your state machine:: class MyState(statemachine.State): Within the state's class definition: a) Include a pattern for each transition, in `State.patterns`:: patterns = {'atransition': r'pattern', ...} b) Include a list of initial transitions to be set up automatically, in `State.initial_transitions`:: initial_transitions = ['atransition', ...] c) Define a method for each transition, with the same name as the transition pattern:: def atransition(self, match, context, next_state): # do something result = [...] # a list return context, next_state, result # context, next_state may be altered Transition methods may raise an `EOFError` to cut processing short. d) You may wish to override the `State.bof()` and/or `State.eof()` implicit transition methods, which handle the beginning- and end-of-file. e) In order to handle nested processing, you may wish to override the attributes `State.nested_sm` and/or `State.nested_sm_kwargs`. If you are using `StateWS` as a base class, in order to handle nested indented blocks, you may wish to: - override the attributes `StateWS.indent_sm`, `StateWS.indent_sm_kwargs`, `StateWS.known_indent_sm`, and/or `StateWS.known_indent_sm_kwargs`; - override the `StateWS.blank()` method; and/or - override or extend the `StateWS.indent()`, `StateWS.known_indent()`, and/or `StateWS.firstknown_indent()` methods. 3. Create a state machine object:: sm = StateMachine(state_classes=[MyState, ...], initial_state='MyState') 4. Obtain the input text, which needs to be converted into a tab-free list of one-line strings. For example, to read text from a file called 'inputfile':: input_string = open('inputfile').read() input_lines = statemachine.string2lines(input_string) 5. Run the state machine on the input text and collect the results, a list:: results = sm.run(input_lines) 6. Remove any lingering circular references:: sm.unlink() trestructuredtextNt StateMachinecBstZdZddZdZdeedZedZddZdZ d Z d Z dd Z d Z d ZdZdZdZddZedZdZdZdZdZdZdZdZdZRS(s A finite state machine for text filters using regular expressions. The input is provided in the form of a list of one-line strings (no newlines). States are subclasses of the `State` class. Transitions consist of regular expression patterns and transition methods, and are defined in each state. The state machine is started with the `run()` method, which returns the results of processing in a list. icCsbd|_d|_d|_d|_||_||_||_h|_ |i |g|_ dS(s+ Initialize a `StateMachine` object; add state objects. Parameters: - `state_classes`: a list of `State` (sub)classes. - `initial_state`: a string, the class name of the initial state. - `debug`: a boolean; produce verbose output if true (nonzero). iiN( tNonetselft input_linest input_offsettlinet line_offsettdebugt initial_statet current_statetstatest add_statest state_classest observers(RR R R((t4/data/zmath/zope/lib/python/docutils/statemachine.pyt__init__s&          cCs1x!|iiD]}|iqWd|_dS(s9Remove circular references to objects no longer required.N(RR tvalueststatetunlinkR(RR((RRs c Cs|it|to ||_nt|d||_||_d|_|i|_ |i o*t i d|idi |ifIJnd }g}|i}y!|i ot i dIJn|i|\}} |i| xyyr|i|i o<|ii|i\}} t i d|| |ifIJn|i|||\}} } WnUtj oI|i ot i d|ii IJn|i!|} |i| PnX|i| Wnt"j oU} |i$| i%d f}|i o%t i d |ii |d fIJqqnt&j oy} |i$| i%d } t'| i%djo d }n| i%df}|i ot i d | |d fIJqnXd }|i| }qWWn"|i o|i(nnXg|_)|S( s Run the state machine on `input_lines`. Return results (a list). Reset `self.line_offset` and `self.current_state`. Run the beginning-of-file transition. Input one line at a time and check for a matching transition. If a match is found, call the transition method and possibly change the state. Store the context returned by the transition method to be passed on to the next transition matched. Accumulate the results returned by the transition methods in a list. Run the end-of-file transition. Finally, return the accumulated results. Parameters: - `input_lines`: a list of strings without newlines, or `StringList`. - `input_offset`: the line offset of `input_lines` from the beginning of the file. - `context`: application-specific storage. - `input_source`: name or path of source of `input_lines`. tsourceis5 StateMachine.run: input_lines (line_offset=%s): | %ss | s! StateMachine.run: bof transitionis4 StateMachine.run: line (source=%r, offset=%r): | %ss$ StateMachine.run: %s.eof transitionisE StateMachine.run: TransitionCorrection to state "%s", transition %s.s@ StateMachine.run: StateCorrection to state "%s", transition %s.N(*Rt runtime_initt isinstanceRt StringListt input_sourceRRR R RtsyststderrtjoinRt transitionstresultst get_stateRtboftcontexttresulttextendt next_linetinfoRtoffsetRt check_linet next_statetEOFErrort __class__t__name__teoftTransitionCorrectiont exceptiont previous_linetargstStateCorrectiontlenterrorR( RRRR RRRRRR-R!R%R'((Rtrunsp      *     !"    %    $  cCs|oN|io7||ijo'tid|i||ifIJn||_ny|i|iSWn"tj ot |inXdS(s Return current state object; set it first if `next_state` given. Parameter `next_state`: a string, the name of the next state. Exception: `UnknownStateError` raised if `next_state` unknown. sJ StateMachine.get_state: Changing state from "%s" to "%s" (input line %s).N( R'RRR RRtabs_line_numberR tKeyErrortUnknownStateError(RR'((RRs' icCshzVy&|i|7_|i|i|_Wn"tj od|_tnX|iSWd|iXdS(s9Load `self.line` with the `n`'th next line and return it.N( RRtnRRt IndexErrorRR(tnotify_observers(RR7((RR#)s   cCs;y|i|idi SWntj o dSnXdS(s3Return 1 if the next line is blank or non-existant.iN(RRRtstripR8(R((Rtis_next_line_blank6s cCs|it|idjS(s0Return 1 if the input is at or past end-of-file.iN(RRR1R(R((Rtat_eof=scCs |idjS(s8Return 1 if the input is at or before beginning-of-file.iN(RR(R((Rtat_bofAscCsP|i|8_|idjo d|_n|i|i|_|i|iS(s=Load `self.line` with the `n`'th previous line and return it.iN(RRR7RRRR9(RR7((RR.Es  cCsizWy'||i|_|i|i|_Wn"tj od|_tnX|iSWd|iXdS(s?Jump to absolute line offset `line_offset`, load and return it.N( RRRRRR8RR(R9(RR((Rt goto_lineOs   cCs|ii||iS(s<Return source of line at absolute line offset `line_offset`.N(RRRRR(RR((Rt get_source\scCs|i|iS(s;Return line offset of current line, from beginning of file.N(RRR(R((Rtabs_line_offset`scCs|i|idS(s5Return line number of current line (counting from 1).iN(RRR(R((RR4dscCsg|ii|idddd|ii|idddd|ii|idt||dS(NitRsinternal paddingi(RRtinsertRRR(RRR((Rt insert_inpuths   cCs|y7|ii|i|}|it|d|SWn>tj o2}|\}}}|it|dnXdS(s Return a contiguous block of text. If `flush_left` is true, raise `UnexpectedIndentationError` if an indented line is encountered before the text block ends (with a blank line). iN( RRtget_text_blockRt flush_lefttblockR#R1tUnexpectedIndentationErrorR2Rtlineno(RRERRHR2RF((RRDps c Cs|djo |i}nd}|io!tid|i i |fIJnx|D]q}|i|\}}} |i|}|o?|io!tid||i i fIJn|||| SqRqRW|iotid|i i IJn|i||SdS(s Examine one line of input for a transition match & execute its method. Parameters: - `context`: application-dependent storage. - `state`: a `State` object, the current state. - `transitions`: an optional ordered list of transition names to try, instead of ``state.transition_order``. Return the values returned by the transition method: - context: possibly modified from the parameter `context`; - next state name (`State` subclass name); - the result output of the transition, a list. When there is no match, ``state.no_match()`` is called and its return value is returned. s5 StateMachine.check_line: state="%s", transitions=%r.s@ StateMachine.check_line: Matched transition "%s" in state "%s".s1 StateMachine.check_line: No match in state "%s".N(RRRttransition_ordertstate_correctionRRRRR)R*tnametpatterntmethodR'tmatchR tno_match( RR RRRKRLRJRMRNR'((RR&s"   ! ! cCs|i|iS(s Return the result of a regular expression match. Parameter `pattern`: an `re` compiled regular expression. N(RLRNRR(RRL((RRNscCsI|i}|ii|ot|n|||i|i|R?R@R4RCRDR&RNRTR RR2R\R^R9(((RRus2  + `          ,      tStatecBstZdZeZeZeZeZddZdZ dZ dZ dZ dZ dZed Zd Zd Zd Zd ZdZRS(sv State superclass. Contains a list of transitions, and transition methods. Transition methods all have the same signature. They take 3 parameters: - An `re` match object. ``match.string`` contains the matched input line, ``match.start()`` gives the start index of the match, and ``match.end()`` gives the end index. - A context object, whose meaning is application-defined (initial value ``None``). It can be used to store any information required by the state machine, and the retured context is passed on to the next transition method unchanged. - The name of the next state, a string, taken from the transitions list; normally it is returned unchanged, but it may be altered by the transition method if necessary. Transition methods all return a 3-tuple: - A context object, as (potentially) modified by the transition method. - The next state name (a return value of ``None`` means no state change). - The processing result, a list, which is accumulated by the state machine. Transition methods may raise an `EOFError` to cut processing short. There are two implicit transitions, and corresponding transition methods are defined: `bof()` handles the beginning-of-file, and `eof()` handles the end-of-file. These methods have non-standard signatures and return values. `bof()` returns the initial context and results, and may be used to return a header string, or do any other processing needed. `eof()` should handle any remaining context and wrap things up; it returns the final processing result. Typical applications need only subclass `State` (or a subclass), set the `patterns` and `initial_transitions` class attributes, and provide corresponding transition methods. The default object initialization will take care of constructing the list of transitions. icCsg|_h|_|i||_||_|idjo|ii|_n|i djo+hd|ig<d|ii <|_ ndS(s Initialize a `State` object; make & add initial transitions. Parameters: - `statemachine`: the controlling `StateMachine` object. - `debug`: a boolean; produce verbose output if true (nonzero). R R N( RRIRtadd_initial_transitionst state_machineRt nested_smRR)tnested_sm_kwargsR*(RRcR((RR8s     cCsdS(s{ Initialize this `State` before running the state machine; called from `self.state_machine.run()`. N((R((RR\scCs d|_dS(s9Remove circular references to objects no longer required.N(RRRc(R((RRcscCs:|io,|i|i\}}|i||ndS(s>Make and add transitions listed in `self.initial_transitions`.N(Rtinitial_transitionstmake_transitionstnamesRtadd_transitions(RRRh((RRbgs cCsuxQ|D]I}|ii|ot|n|i|pt|qqW||id*|ii|dS(s" Add a list of transitions to the start of the transition list. Parameters: - `names`: a list of transition names. - `transitions`: a mapping of names to transition tuples. Exceptions: `DuplicateTransitionError`, `UnknownTransitionError`. iN( RhRKRRRRtDuplicateTransitionErrortUnknownTransitionErrorRItupdate(RRhRRK((RRins  cCsD|ii|ot|n|g|id*||i|tZdZdddZdddZddddZRS(su `StateMachine` subclass specialized for whitespace recognition. There are three methods provided for extracting indented text blocks: - `get_indented()`: use when the indent is unknown. - `get_known_indented()`: use when the indent is known for all lines. - `get_first_known_indented()`: use when only the first line's indent is known. iicCs|i}|ii|i||\}}}|o|i t |dnx2|o*|di o|i|d7}qUW||||fS(s= Return a block of indented lines of text, and info. Extract an indented block where the indent is unknown for all lines. :Parameters: - `until_blank`: Stop collecting at the first blank line if true (1). - `strip_indent`: Strip common leading indent if true (1, default). :Return: - the indented block (a list of lines of text), - its indent, - its first line offset from BOF, and - whether or not it finished with a blank line. iiN(RR@R%Rt get_indentedRt until_blankt strip_indenttindentedtindentt blank_finishR#R1R:t trim_start(RRRRRRR%((RR~s $ cCs|i}|ii|i||d|\}}}|i t |dx2|o*|di o|i|d7}qPW|||fS(s Return an indented block and info. Extract an indented block where the indent is known for all lines. Starting with the current line, extract the entire text block with at least `indent` indentation (which must be whitespace, except for the first line). :Parameters: - `indent`: The number of indent columns/characters. - `until_blank`: Stop collecting at the first blank line if true (1). - `strip_indent`: Strip `indent` characters of indentation if true (1, default). :Return: - the indented block, - its first line offset from BOF, and - whether or not it finished with a blank line. t block_indentiiN(RR@R%RR~RRRRRRR#R1R:R(RRRRRRR%((Rtget_known_indented$s  cCs|i}|ii|i||d|\}}}|i t |d|o9x6|o*|di o|i|d7}qWWn||||fS(s Return an indented block and info. Extract an indented block where the indent is known for the first line and unknown for all other lines. :Parameters: - `indent`: The first line's indent (# of columns/characters). - `until_blank`: Stop collecting at the first blank line if true (1). - `strip_indent`: Strip `indent` characters of indentation if true (1, default). - `strip_top`: Strip blank lines from the beginning of the block. :Return: - the indented block, - its indent, - its first line offset from BOF, and - whether or not it finished with a blank line. t first_indentiiN(RR@R%RR~RRRRRRR#R1t strip_topR:R(RRRRRRRR%((Rtget_first_known_indentedCs  (R*R_R`R~RR(((RR}s tStateWScBs}tZdZeZeZeZeZhdd<ddt |i|t |i}|i i ||i|qn{|ii |||i i |||f|i oDt |i|t |i}|i i ||i|||ndS(Ns+inserting non-ViewList with no source given(RRRRRRRRRRRR1tindexRBRR%(RRRRR%R((RRBs   "  icCse|io;t|i|t|i}|ii||in|ii||ii|S(N( RRR1RRRtpopRR(RRR((RRs   icCs|t|ijo#td|t|ifn|djotdn|i|4|i|4|io|i|7_ndS(sW Remove items from the start of the list, without touching the parent. sCSize of trim too large; can't trim %s items from a list of size %s.isTrim size must be >= 0.N(R7R1RRR8RRR(RR7((RRs#    cCsp|t|ijo#td|t|ifn|djotdn|i| 3|i| 3dS(sU Remove items from the end of the list, without touching the parent. sCSize of trim too large; can't trim %s items from a list of size %s.isTrim size must be >= 0.N(R7R1RRR8R(RR7((Rttrim_ends#  cCs|i|}||=dS(N(RRR(RRR((RR]scCs|ii|S(N(RRtcountR(RR((RRscCs|ii|S(N(RRRR(RR((RRscCs'|ii|iid|_dS(N(RRtreverseRRR(R((RRs  cGst|i|i}|i|g}|D]}||dq-~|_g}|D]}||dqU~|_d|_ dS(Nii( tzipRRRttmptsortR/RtentryRR(RR/RRR((RRs  ((cCs_y|i|SWnItj o=|t|ijo|i|dddfSq[nXdS(s%Return source & offset for index `i`.iiN(RRRR8R1RR(RR((RR$scCs|i|dS(sReturn source for index `i`.iN(RR$R(RR((RRscCs|i|dS(sReturn offset for index `i`.iN(RR$R(RR((RR% scCs d|_dS(s-Break link between this list and parent list.N(RRR(R((Rt disconnects()R*R_R`RRRRRRRRRRRRRRRRRRRRRt__rmul__RR"RZRBRRRR]RRRRR$RR%R(((RRsL                               RcBsbtZdZdeidZddZdddeedZddZ dZ dZ RS( s*A `ViewList` with string-specific methods.icCs=g}|i||!D]}|||q~|i||+dS(s Trim `length` characters off the beginning of each item, in-place, from index `start` to `end`. No whitespace-checking is done on the trimmed text. Does not affect slice parent. N(RRRRRRtlength(RRRRRR((Rt trim_leftscCs|}t|i}x||jo{|i|}|ipPn|oG|ddjo6|i |\}}t |||!||dn|d7}qW|||!S(s Return a contiguous block of text. If `flush_left` is true, raise `UnexpectedIndentationError` if an indented line is encountered before the text block ends (with a blank line). it iN( RRR1RRtlastRR:RER$RR%RG(RRRERRR%RR((RRD s   icCs|}|} |dj o|djo |}n|dj o| d7} nt|i}x| |jo|i| } | oY| ddjp|dj o;| | i o*| |jo|i| di }Pn| i } | p|o d}PqMnN|djo@t| t| } |djo | }qMt|| }n| d7} q]Wd}||| !} |dj o#| o| id|| id