if|vdZdZddlZddlZddlmZddlmZGddZGdd Z Gd d eZ Gd d e Z GddZ Gdde eZ Gdde e ZGddZGddeZGddeZGddeZGddeZGddeZGd d!eZGd"d#eZGd$d%eZGd&d'eZGd(d)eZGd*d+eZd,d-ejd.fd/Zd0ZdS)1a 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':: with open('inputfile', encoding='utf-8') as fp: input_string = fp.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() restructuredtextN)east_asian_width)utilsceZdZdZddZdZ ddZd dZd!d Zd Z d Z d Z d!dZ dZ dZdZdZd dZdZddZd dZdZdZdZdZdZdZdZdS)" StateMachinea 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. Fcd|_ d|_ d|_ d|_ ||_ ||_ ||_ i|_ ||g|_ dS)a+ 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). Nr) input_lines input_offsetline line_offsetdebug initial_state current_statestates add_states observers)self state_classesrrs u/builddir/build/BUILD/imunify360-venv-2.3.5/opt/imunify360/venv/lib/python3.11/site-packages/docutils/statemachine.py__init__zStateMachine.__init__s  #J !M $*C*C 4  &&& * *ct|jD]}|d|_dSz9Remove circular references to objects no longer required.N)rvaluesunlinkrstates rrzStateMachine.unlinks9[''))  E LLNNNN rrNc|t|tr||_nt|||_||_d|_|p|j|_|jr>td|jdd |jtj d}g}| } |jrtdtj ||\}} ||  ||jrK|j|j\} } td | d | d|jtj ||||\}} } || nj#t($r]|jr(td |jjztj ||} || YnwxYw d}n#t0$rf} || jd f}|jr2td|jjd|d dtj Yd} ~ sd} ~ wt6$r} || jd } t9| jdkrd}n| jdf}|jr(td| d|d dtj Yd} ~ nd} ~ wwxYw| | }n!#|jr|xYwg|_|S)a 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`. - `initial_state`: name of initial state. )sourcer z, StateMachine.run: input_lines (line_offset=z): | z | fileNz! StateMachine.run: bof transitionTz StateMachine.run: line (source=z , offset=z$ StateMachine.run: %s.eof transitionrz2 StateMachine.run: TransitionCorrection to state "z", transition .z- StateMachine.run: StateCorrection to state ") runtime_init isinstance StringListr r r rrrprintjoinsysstderr get_statebofextend next_lineinfor check_lineEOFError __class____name__eofTransitionCorrection previous_lineargsStateCorrectionlenerrorr)rr r context input_sourcer transitionsresultsrresultr offset next_state exceptions rrunzStateMachine.runs*.  k: . . L*D  )+lKKKD (*@d.@ : # E%%%v{{43C'D'D'DFz # # # #   4 z M:LLLL#ii00OGV NN6 " " "+ 3)'/(((:E-1-=-B-B $ 0.2.2NFF!#3-3#3#3@F#3#3'+y#3#39<EEEE7;oo#UK79793V v....$:O!"I$)O$<#=CF:OOOO!&7!3!3v... /,#'KK+,&&(((#,>!#4"6Kz/>(-(@>>,7N>>>$':////HHHH& / / /&&(((!*!2J9>**a//&* '0~a'8&: z/N",NNL/ LA9L L/LL//M c |rU|jrG||jkr>>+++ZZZ--////18;zCCCC",D  8;t12 2 8 8 8#D$677 7 8s A++B r$c |xj|z c_|j|j|_n#t$rd|_twxYw|j|S#|wxYw)z9Load `self.line` with the `n`'th next line and return it.N)r r r IndexErrorr2notify_observersrns rr/zStateMachine.next_line&s $   A%   ,T-=>       9  ! ! # # # #D ! ! # # # #s'+A"A A""A8cv |j|jdz S#t$rYdSwxYw)z6Return True if the next line is blank or non-existent.r$)r r striprJrs ris_next_line_blankzStateMachine.is_next_line_blank3sN '(81(<=CCEEE E   11 s '* 88cB|jt|jdz kS)z0Return 1 if the input is at or past end-of-file.r$)r r:r rPs rat_eofzStateMachine.at_eof:s 3t'7#8#81#<<s1$$rc|xj|zc_|jdkrd|_n|j|j|_||jS)z=Load `self.line` with the `n`'th previous line and return it.rN)r r r rKrLs rr7zStateMachine.previous_lineBsY A  a  DII()9:DI yrc ||jz |_|j|j|_n#t$rd|_t wxYw|j|S#|wxYw)z?Jump to absolute line offset `line_offset`, load and return it.N)r r r r rJr2rKrr s r goto_linezStateMachine.goto_lineLs $ #.1B#B  ,T-=>       9  ! ! # # # #D ! ! # # # #s&*A!A A!!A7cF|j||jz S)z%FFd//!3F &!-226::NC!mGG $ $ $33FT=N4NOOLC! # # # # & & &%LC & G|s"<1B/B?Bc&|j|jdzdd|zt||j|jdzdd|zd|j|jdzt ||dS)Nr$zinternal padding after )r rAzinternal padding before r )r insertr r:r')rr r s r insert_inputzStateMachine.insert_inputs  01 4b'@'G'*;'7'7  9 9 9  01 4b'A&'H')  + + +  01 4 *; ? ? A A A A Arc |j|j|}|t |dz |S#t $r8}|jd}|t |dz d}~wwxYw) 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). r$rN)r get_text_blockr r/r:UnexpectedIndentationErrorr8)r flush_leftblockerrs rrozStateMachine.get_text_blocks $33D4D4>@@E NN3u::> * * *L)   HQKE NN3u::> * * *  sAA B 3BB c||j}|jr,td|jjd|dt j|D]q}|j|\}}}||j }|rB|jr,td|d|jjdt j||||cSr|jr(td |jjzt j| ||S) a 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. Nz! StateMachine.check_line: state="z", transitions=r#r!z. StateMachine.check_line: Matched transition "z " in state "z".z1 StateMachine.check_line: No match in state "%s".) transition_orderrr(r3r4r*r+r>matchr no_match) rr<rr>namepatternmethodrBrvs rr1zStateMachine.check_lines](  0K : N E_---{{{>';77 7rcv|j}||jvrt||||j|j|<dS)z Initialize & add a `state_class` (`State` subclass) object. Exception: `DuplicateStateError` raised if `state_class` was already added. N)r4rDuplicateStateErrorr)r state_class statenames r add_statezStateMachine.add_statesG (  # #%i00 0!,T4:!>!> Irc:|D]}||dS)zE Add `state_classes` (a list of `State` subclasses). N)r)rrr}s rrzStateMachine.add_statess2) ( (K NN; ' ' ' ' ( (rcf|jD]}|dS)z+ Initialize `self.states`. N)rrr%rs rr%zStateMachine.runtime_inits@['')) ! !E     ! !rct\}}}}}t|d|tjtd|ztjtd|d|d|tjdS)zReport error details.z: r!z input line %szmodule z, line z , function N)_exception_datar(r*r+rF)rtypevaluemoduler functions rr;zStateMachine.errors.=.?.?+eVT8 $$$&SZ8888 o!5!5!7!78szJJJJ 666444J:      rc:|j|dS)z The `observer` parameter is a function or bound method which takes two arguments, the source and offset of the current line. N)rappendrobservers rattach_observerzStateMachine.attach_observers h'''''rc:|j|dSN)rremovers rdetach_observerzStateMachine.detach_observers h'''''rc|jD]:} |j|j}n#t$rd}YnwxYw||;dS)Nra)rr r0r rJ)rrr0s rrKzStateMachine.notify_observerssn  H $',,T-=>> $ $ $# $ HdOOO   s + ::F)rNNNrr$)r4 __module__ __qualname____doc__rrrDr,r/rQrSrUr7rYr[r^rFrcrlror1rrr%r;rrrKrrrrus  )*)*)*)*V 8<-1\\\\|8888( $ $ $ $===%%% $ $ $HHH4448886AAA$&8&8&8&8P ? ? ?(((!!!((((((rrc|eZdZdZdZ dZ dZ dZ ddZdZ dZ dZ dZ d Z d Zdd Zd Zd ZdZdZdZdS)Stateaw 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 returned 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. NFcg|_ i|_ |||_ ||_ |j|jj|_|j|jg|jjd|_dSdS)z Initialize a `State` object; make & add initial transitions. Parameters: - `statemachine`: the controlling `StateMachine` object. - `debug`: a boolean; produce verbose output if true. N)rr) rur>add_initial_transitions state_machiner nested_smr3nested_sm_kwargsr4rrrs rrzState.__init__Fs!#9  $$&&&*C $ > !!/9DN  (7;~6F6:n6M%O%OD ! ! ! ) (rcdS)z{ Initialize this `State` before running the state machine; called from `self.state_machine.run()`. NrrPs rr%zState.runtime_initjs rcd|_dSr)rrPs rrz State.unlinkqs!rc~|jr5||j\}}|||dSdS)z>Make and add transitions listed in `self.initial_transitions`.N)initial_transitionsmake_transitionsadd_transitionsrnamesr>s rrzState.add_initial_transitionsusS  # 5!%!6!6%)%="?"? E;   4 4 4 4 4 5 5rc|D]-}||jvrt|||vrt|.||jdd<|j|dS)a" 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`. Nr)r>DuplicateTransitionErrorUnknownTransitionErrorruupdate)rrr>rxs rrzState.add_transitions|s{ 3 3Dt'''.t444;&&,T222'$)bqb!  ,,,,,rcd||jvrt||g|jdd<||j|<dS)z Add a transition to the start of the transition list. Parameter `transition`: a ready-made transition 3-tuple. Exception: `DuplicateTransitionError`. Nr)r>rru)rrx transitions radd_transitionzState.add_transitionsF 4# # #*400 0%)Fbqb!!+rct |j|=|j|dS#t|xYw)z^ Remove a transition by `name`. Exception: `UnknownTransitionError`. N)r>rurr)rrxs rremove_transitionzState.remove_transitionsF  / &  ! ( ( . . . . . /(.. .s"&7cx| |jj} |j|}t|dst j|x}|j|<n-#t $r t|jjd|dwxYw t||}n,#t$rt|jjd|wxYw|||fS)a Make & return a transition tuple based on `name`. This is a convenience function to simplify transition creation. Parameters: - `name`: a string, the name of the transition pattern & method. This `State` object must have a method called '`name`', and a dictionary `self.patterns` containing a key '`name`'. - `next_state`: a string, the name of the next `State` object for this transition. A value of ``None`` (or absent) implies no state change (i.e., continue with the same state). Exceptions: `TransitionPatternNotFound`, `TransitionMethodNotFound`. Nrvz .patterns[]r#) r3r4patternshasattrrecompilerGTransitionPatternNotFoundgetattrAttributeErrorTransitionMethodNotFound)rrxrBryrzs rmake_transitionzState.make_transitions"  0J GmD)G7G,, D02 70C0CC$-- G G G+'+~'>'>'>EGG G G =T4((FF = = =*!^444dd;== = = **s;A *A6:B )B4cg}i}|D]s}t|tr.||||<||E|j|||d<||dt||fS)z Return a list of transition names and a transition mapping. Parameter `name_list`: a list, where each entry is either a transition name string, or a 1- or 2-tuple (transition name, optional next state name). r)r&strrr)r name_listrr> namestates rrzState.make_transitionss " + +I)S)) +)-)=)=i)H)H I& Y'''',@D,@),L IaL) Yq\****k!!rc |dgfS)a' Called when there is no match from `StateMachine.check_line()`. Return the same values returned by transition methods: - context: unchanged; - next state name: ``None``; - empty result list. Override in subclasses to catch this event. Nr)rr<r>s rrwzState.no_matchsb  rc |gfS)z Handle beginning-of-file. Return unchanged `context`, empty result. Override in subclasses. Parameter `context`: application-defined storage. rrr<s rr-z State.bofs{rcgS)z Handle end-of-file. Return empty result. Override in subclasses. Parameter `context`: application-defined storage. rrs rr5z State.eofs  rc ||gfS)z A "do nothing" transition method. Return unchanged `context` & `next_state`, empty result. Useful for simple state changes (actionless transitions). rrrvr<rBs rnopz State.nops B&&rrr)r4rrrrrrrrr%rrrrrrrrwr-r5rrrrrrs$%%NH  I "O"O"O"OH   """555---& , , , / / /++++B"""& ! ! !'''''rrc.eZdZdZddZddZ d dZdS) StateMachineWSaq `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. FTcp|}|j|j||\}}}|r%|t |dz |rO|ds5||dz }|r|d5||||fS)a 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. - `strip_indent`: Strip common leading indent if true (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. r$rr^r get_indentedr r/r:rO trim_start)r until_blank strip_indentrAindentedindent blank_finishs rrzStateMachineWS.get_indenteds %%'')-)9)F)F \*;*;&&,  . NN3x==1, - - - x{0022     ! ! ! aKF x{0022 55rcn|}|j|j|||\}}}|t |dz |rO|ds5||dz }|r|d5|||fS)a 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. - `strip_indent`: Strip `indent` characters of indentation if true (default). :Return: - the indented block, - its first line offset from BOF, and - whether or not it finished with a blank line. ) block_indentr$rr)rrrrrArrs rget_known_indentedz!StateMachineWS.get_known_indented/s(%%'')-)9)F)F \!*G*#*#&&, s8}}q())) x{0022     ! ! ! aKF x{0022 --rct|}|j|j|||\}}}|t |dz |rQ|rO|ds5||dz }|r|d5||||fS)a 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. ) first_indentr$rr)rrrr strip_toprArrs rget_first_known_indentedz'StateMachineWS.get_first_known_indentedMs,%%'')-)9)F)F \!*G*#*#&&, s8}}q()))   8A;#4#4#6#6 ##%%%!  8A;#4#4#6#6 55rN)FT)FTT)r4rrrrrrrrrrrsc  66664....<B666666rrceZdZdZdZ dZ dZ dZ ej dej ddZ dZ d dZ dZ d Zd Zd Zd ZdS)StateWSa State superclass specialized for whitespace (blank lines & indents). Use this class with `StateMachineWS`. The transitions 'blank' (for blank lines) and 'indent' (for indented text blocks) are added automatically, before any other transitions. The transition method `blank()` handles blank lines and `indent()` handles nested indented blocks. Indented blocks trigger a new state machine to be created by `indent()` and run. The class of the state machine to be created is in `indent_sm`, and the constructor keyword arguments are in the dictionary `indent_sm_kwargs`. The methods `known_indent()` and `firstknown_indent()` are provided for indented blocks where the indent (all lines' and first line's only, respectively) is known to the transition method, along with the attributes `known_indent_sm` and `known_indent_sm_kwargs`. Neither transition method is triggered automatically. Nz *$z +)blankrFct||||j |j|_|j |j|_|j |j|_|j|j|_dSdS)z Initialize a `StateSM` object; extends `State.__init__()`. Check for indent state machine attributes, set defaults if not set. N)rr indent_smrindent_sm_kwargsrknown_indent_smknown_indent_sm_kwargsrs rrzStateWS.__init__st t]E222 > !!^DN  ($($9D !   '#'>D  & .*.*?D ' ' ' / .rct||ji|_|j|j||j\}}|||dS)z Add whitespace-specific transitions before those defined in subclass. Extends `State.add_initial_transitions()`. N)rrrr ws_patternsrws_initial_transitionsrrs rrzStateWS.add_initial_transitionss| %%d+++ = DM T-...!22  ')){ UK00000rc0||||S)z9Handle blank lines. Does nothing. Override in subclasses.)rrs rrz StateWS.blanksxxw 333rc|j\}}}}|jdd|ji|j}|||} ||| fS)z Handle an indented text block. Extend or override in subclasses. Recursively run the registered state machine for indented blocks (`self.indent_sm`). rr r)rrrrrrD) rrvr<rBrrr rsmr?s rrzStateWS.indentsf  , , . . 6; T^ F F$* F0E F F&& &<< G++rc|j|\}}}|jdd|ji|j}|||}|||fS)a Handle a known-indent text block. Extend or override in subclasses. Recursively run the registered state machine for known-indent indented blocks (`self.known_indent_sm`). The indent is the length of the match, ``match.end()``. rrr)rrendrrrrD rrvr<rBrr rrr?s r known_indentzStateWS.known_indents  2 2599;; ? ? ; !T !AA A$($?AA&& &<< G++rc|j|\}}}|jdd|ji|j}|||}|||fS)a0 Handle an indented text block (first line's indent known). Extend or override in subclasses. Recursively run the registered state machine for known-indent indented blocks (`self.known_indent_sm`). The indent is the length of the match, ``match.end()``. rrr)rrrrrrrDrs rfirst_known_indentzStateWS.first_known_indents  8 8 E E ; !T !AA A$($?AA&& &<< G++rr)r4rrrrrrrrrrrrrrrrrrrrrros$IO"'BJu--'RZ--//K1F@@@@ 1 1 1444 , , , , , ,,,,,,rrceZdZdZdZdS)_SearchOverridea Mix-in class to override `StateMachine` regular expression behavior. Changes regular expression matching, from the default `re.match()` (succeeds only if the pattern matches at the start of `self.line`) to `re.search()` (succeeds if the pattern matches anywhere in `self.line`). When subclassing a `StateMachine`, list this class **first** in the inheritance list of the class definition. c6||jS)z Return the result of a regular expression search. Overrides `StateMachine.match()`. Parameter `pattern`: `re` compiled regular expression. )searchr )rrys rrvz_SearchOverride.matchs~~di(((rN)r4rrrrvrrrrrs-)))))rrceZdZdZdS)SearchStateMachinez@`StateMachine` which uses `re.search()` instead of `re.match()`.Nr4rrrrrrrrsJJDrrceZdZdZdS)SearchStateMachineWSzB`StateMachineWS` which uses `re.search()` instead of `re.match()`.NrrrrrrsLLDrrceZdZdZ d+dZdZdZdZdZdZ d Z d Z d Z d Z d ZdZdZdZdZdZdZdZdZeZdZdZd,dZd,dZd-dZd.dZd.dZd Zd!Z d"Z!d#Z"d$Z#d%Z$d&Z%d'Z&d(Z'd)Z(d*Z)dS)/ViewLista> List with extended functionality: slices of ViewList objects are child lists, linked to their parents. Changes made to a child list also affect the parent list. A child list is effectively a "view" (in the SQL sense) of the parent list. Changes to parent lists, however, do *not* affect active child lists. If a parent list is changed, any active child lists should be recreated. The start and end of the slice can be trimmed using the `trim_start()` and `trim_end()` methods, without affecting the parent list. The link between child and parent lists can be broken by calling `disconnect()` on the child list. Also, ViewList objects keep track of the source & offset of each item. This information is accessible via the `source()`, `offset()`, and `info()` methods. Ncg|_ g|_ ||_ ||_ t |t r)|jdd|_|jdd|_nM|Kt ||_|r||_n-fdtt|D|_t|jt|jks JddS)Ncg|]}|fSrr).0ir s r z%ViewList.__init__..IsHHHavqkHHHr data mismatch) dataitemsparent parent_offsetr&rlistranger:)rinitlistr rrrs ` rrzViewList.__init__1s F   *H h ) ) I aaa(DI!*DJJ  !XDI I" HHHH5X3G3GHHH 49~~TZ000/00000rc*t|jSr)rrrPs r__str__zViewList.__str__L49~~rc@|jjd|jd|jdS)N(z, items=))r3r4rrrPs r__repr__zViewList.__repr__Os*.)LLDILLtzLLLLrc>|j||kSrr_ViewList__castrothers r__lt__zViewList.__lt__RDI E0B0B$BBrc>|j||kSrrrs r__le__zViewList.__le__SDIU1C1C$CCrc>|j||kSrrrs r__eq__zViewList.__eq__Trrc>|j||kSrrrs r__ne__zViewList.__ne__Urrc>|j||kSrrrs r__gt__zViewList.__gt__Vrrc>|j||kSrrrs r__ge__zViewList.__ge__Wrrc>t|tr|jS|Sr)r&rrrs r__castzViewList.__castYs! eX & & : Lrc||jvSrrritems r __contains__zViewList.__contains___sty  rc*t|jSr)r:rrPs r__len__zViewList.__len__brrct|tra|jdvs Jd||j|j|j|j|j|j||jpdS|j|S)NNr$cannot handle slice with strider)rrr)r&slicestepr3rstartstoprrrs r __getitem__zViewList.__getitem__is a   6Y&&&(I&&&>>$)AGAFN";(, 1716>(B)-QW\"KK K9Q< rcHt|tr|jdvs Jdt|tst d|j|j|j|j<|j|j|j|j<t|jt|jks Jd|j r=|jpd|j z}|jpt||j z}||j ||<dSdS||j|<|j r||j ||j z<dSdS)Nr)r*z(assigning non-ViewList to ViewList slicerr) r&r+r,rrbrr-r.rr:rr)rrr$krMs r __setitem__zViewList.__setitem__rs9 a   ;6Y&&&(I&&&dH-- L JKKK(, DIagafn %)-DJqwqv~ &ty>>S__444o444{ (W\T%77V(s4yyD,>>#' AaC    ( (  DIaL{ ;6: A 22333 ; ;rct |j|=|j|=|jr|j||jz=dSdS#t$r|j Jd|j|j|j=|j|j|j=|jr<|jpd|jz}|jpt||jz}|j||=YdSYdSwxYw)Nr*r) rrrrrbr,r-r.r:)rrr2rMs r __delitem__zViewList.__delitem__s % !  1 { 8KD$6 6777 8 8 % % %6>>#D>>> !'!&.) 1716>*{ %W\T%77V(s4yyD,>>K!$$$$ % % %  %s'-BB76B7ct|tr1||j|jz|j|jzSt d)Nrz!adding non-ViewList to a ViewListr&rr3rrrbrs r__add__zViewList.__add__s[ eX & & A>>$)ej"8)-ek)A"DD D?@@ @rct|tr1||j|jz|j|jzSt d)Nr7z!adding ViewList to a non-ViewListr8rs r__radd__zViewList.__radd__s[ eX & & A>>%*ty"8).tz)A"DD D?@@ @rczt|tr|xj|jz c_ntd|S)Nz!argument to += must be a ViewList)r&rrrbrs r__iadd__zViewList.__iadd__s= eX & & A II #III?@@ @ rcP||j|z|j|zS)Nr7)r3rrrLs r__mul__zViewList.__mul__s$~~di!mDJN~DDDrcF|xj|zc_|xj|zc_|Sr)rrrLs r__imul__zViewList.__imul__s% Q  a  rcBt|tstd|jr5|jt |j|jz||j|j|j |j dS)Nz(extending a ViewList with a non-ViewList) r&rrbrrkr:rrr.rrs rr.zViewList.extends%** HFGG G ; K K  s49~~0BBE J J J $$$ %+&&&&&rrc |||dS|jr7|jt|j|jz||||j||j||fdSr)r.rrkr:rrrr)rr$r rAs rrzViewList.appends > KK     { 3 ""3ty>>D4F#F#)6333 I  T " " " J  vv. / / / / /rcn|t|tstd|j|j||<|j|j||<|jrQt |j|zt |jz}|j||jz|dSdS|j|||j|||f|jrSt |j|zt |jz}|j||jz|||dSdS)Nz+inserting non-ViewList with no source given) r&rrbrrrr:rkr)rrr$r rAindexs rrkzViewList.insertsF >dH-- O MNNN!YDIacN"jDJqsO{ ETY!+s49~~= ""54+=#=tDDDDD E E I  Q % % % J  a&&!1 2 2 2{ 3TY!+s49~~= ""54+=#=t#)633333 3 3rr c|jrNt|j|zt|jz}|j||jz|j||j|Sr)rr:rpoprr)rrrEs rrGz ViewList.popso ; 8^^a'3ty>>9E KOOED$66 7 7 7 qy}}Qrr$c |t|jkr(td|dt|jd|dkrtd|jd|=|jd|=|jr|xj|z c_dSdS)zW Remove items from the start of the list, without touching the parent. #Size of trim too large; can't trim  items from a list of size r#rTrim size must be >= 0.N)r:rrJrrrrLs rrzViewList.trim_starts s49~~  *:;!!S^^^^MNN N UU677 7 IbqbM JrrN ; $   ! #     $ $rc|t|jkr(td|dt|jd|dkrtd|j| d=|j| d=dS)zU Remove items from the end of the list, without touching the parent. rIrJr#rrKN)r:rrJrrLs rtrim_endzViewList.trim_ends s49~~  *:;!!S^^^^MNN N UU677 7 IqbccN JrssOOOrc6||}||=dSr)rE)rr$rEs rrzViewList.removes 4   KKKrc6|j|Sr)rcountr#s rrPzViewList.countyt$$$rc6|j|Sr)rrEr#s rrEzViewList.indexrQrcx|j|jd|_dSr)rreverserrrPs rrTzViewList.reverses5   rctt|j|jg|R}d|D|_d|D|_d|_dS)Ncg|] }|d S)rrrentrys rrz!ViewList.sort..s///%U1X///rcg|] }|d SrrrWs rrz!ViewList.sort..s0005eAh000r)sortedziprrr)rr8tmps rsortz ViewList.sortsZSDJ//7$777//3/// 00C000  rc |j|S#t$r4|t|jkr|j|dz ddfcYSwxYw)z%Return source & offset for index `i`.r$rN)rrJr:rr/s rr0z ViewList.info se :a=    C NN""z!a%(+T1111  s :A  A c8||dS)zReturn source for index `i`.rr0r/s rr zViewList.sourceyy||Arc8||dS)zReturn offset for index `i`.r$r`r/s rrAzViewList.offsetrarcd|_dS)z-Break link between this list and parent list.N)rrPs r disconnectzViewList.disconnects  rc#^Kt|j|jD]\}\}}|||fVdS)z8Return iterator yielding (source, offset, value) tuples.N)r[rr)rrr rAs rxitemszViewList.xitems sM),TY )C)C ( ( %U$VV&%' ' ' ' ' ( (rcX|D]}td|zdS)z=Print the list in `grep` format (`source:offset:value` lines)z%s:%d:%sN)rfr()rr s rpprintzViewList.pprint%s9KKMM % %D *t# $ $ $ $ % %r)NNNNN)Nr)r r)*r4rrrrrr rrrrrrrr%r'r0r3r5r9r;r=r?__rmul__rAr.rrkrGrrMrrPrErTr]r0r rArdrfrhrrrrrse$:>,0BBBB6MMMCBBCCCCCCCCCBBBCCC !!!   ;;;" % % %AAAAAAEEEH '''00003333"     $ $ $ $    %%%%%%  ((( %%%%%rrcPeZdZdZdejfdZd dZ d dZdd Z d Z d Z dS)r'z*A `ViewList` with string-specific methods.rcRfd|j||D|j||<dS)z 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. c$g|] }|d Srr)rr lengths rrz(StringList.trim_left..5s7 B B B$(!%VWW  B B BrNr")rrmr-rs ` r trim_leftzStringList.trim_left/sN  B B B B,0IeCi,@ B B B %)rFc,|}t|j}||kro|j|}|snM|r@|ddkr4||\}}t |||||dz|dz }||ko|||S)rnr r$)r:rrOr0rp)rr-rqrlastr r rAs rrozStringList.get_text_block8s49~~Djj9S>D::<<  =tAw#~~!%30eCi&17!=== 1HCDjjE#IrTNcz|}|}|||}||dz }t|j}||kr|j|} | rT| ddks|F| d|r*||ko"|j|dz  } n_| } | s|rd} nDn6|4t| t| z } || }nt || }|dz }||kd} |||} || r| jd|d| jd<|r|r| ||du| |pd| fS)a Extract and return a StringList of indented lines of text. Collect all lines with indentation, determine the minimum indentation, remove the minimum indentation from all indented lines (unless `strip_indent` is false), and return them. All lines up to but not including the first unindented line will be returned. :Parameters: - `start`: The index of the first line to examine. - `until_blank`: Stop collecting at the first blank line if true. - `strip_indent`: Strip common leading indent if true (default). - `block_indent`: The indent of the entire block, if known. - `first_indent`: The indent of the first line, if known. :Return: - a StringList of indented lines with minimum indent removed; - the amount of the indent; - a boolean: did the indented block finish with a blank line or EOF? Nr$rrp)r-)r:rrOlstripminrn)rr-rrrrrrrqr rstripped line_indentrrs rrzStringList.get_indentedMs,  # (<'L  # 1HC49~~Djj9S>D aC)5!%m|m!4!:!:!(FF 55F 1HC+Djj.LU3Y  # #!JqM,--8EJqM  Fl F OOF.s!???D$vww-???r) rr:rrcolumn_indicesrJrstriprtrs) rtopleftbottomrightrrrrcir rs @r get_2D_blockzStringList.get_2D_blocksSZ s5:'' E EA%ejm44B 5$x 5 5 5EJqM**SWW44 5 65  6 6 6UZ]++c"gg55 6#(:a=e#<#C#C#E#E EEJqMD EVSYYT[[]]1C1C%CDD  @A.........????EJ???EJ s$A7BBB""7CCcPtt|jD]}|j|}t|tr_g}|D]=}||t |dvr||>d||j|<dS)zrPad all double-width characters in `self` appending `pad_char`. For East Asian language support. WFriN)rr:rr&rrrr))rpad_charrr newchars rpad_double_widthzStringList.pad_double_widths s49~~&& , ,A9Q.s1 K K KALL # # * * , , K K Kr)sub splitlines)astringrconvert_whitespace whitespaces ` r string2linesrsF"/..g.. K K K Kg6H6H6J6J K K KKrctj\}}}|jr|j}|j|jj}|j||j|j|jfS)z Return exception information: - the exception's class name; - the exception object; - the name of the file containing the offending code; - the line number of the offending code; - the function name of the offending code. ) r*exc_infotb_nexttb_framef_coder4 co_filename tb_linenoco_name)rr tracebackcodes rrrsa!\^^D%  &%   &   $D M5$"2I4G L r)r __docformat__r*r unicodedatardocutilsrrrrrrrrrr' ExceptionrrHr|rrrrrpr6r9rrrrrrrso eeN# ((((((AAAAAAAAH L'L'L'L'L'L'L'L'^d6d6d6d6d6\d6d6d6NJ,J,J,J,J,eJ,J,J,Z)))))))).     ,        ?N   K%K%K%K%K%K%K%K%\E:E:E:E:E:E:E:E:P)(((( (((00000)00022222+22255555.55577777077788888 188877777077799999!29999i%&%&BJx00LLLL,r