
    g                       d Z ddlZddlZddlmZ ddlmZmZ ddlm	Z	m
Z
mZmZmZ e G d de             ZdZd	ZdOd
Z G d dee      Z G d dee      ZdPdZd ZdPdZd ZdPdZd Z	 dQdZd Zd ZdPdZd Z  G d d      Z! e!       Z"	 	 	 	 	 	 dRdZ# G d de$      Z%d  Z&d! Z'd" Z(d# Z)d$ Z*d% Z+d& Z,d' Z-d( Z.d) Z/d* Z0d+ Z1dSd,Z2d- Z3d. Z4d/ Z5 G d0 d1e      Z6 G d2 d3e6e7      Z8 G d4 d5e6e9      Z: G d6 d7e6e9      Z; G d8 d9e6e7      Z<d: Z=e G d; d<             Z> G d= d>e>      Z? G d? d@e>      Z@ e?dAddAB      ZA e>dCdDE      ZBe G dF dG             ZC G dH dI      ZDdTdJZEdUdKZFdUdLZGeHdMk(  r eG        g dNZIy)VaY  
Basic data classes for representing feature structures, and for
performing basic operations on those feature structures.  A feature
structure is a mapping from feature identifiers to feature values,
where each feature value is either a basic value (such as a string or
an integer), or a nested feature structure.  There are two types of
feature structure, implemented by two subclasses of ``FeatStruct``:

    - feature dictionaries, implemented by ``FeatDict``, act like
      Python dictionaries.  Feature identifiers may be strings or
      instances of the ``Feature`` class.
    - feature lists, implemented by ``FeatList``, act like Python
      lists.  Feature identifiers are integers.

Feature structures are typically used to represent partial information
about objects.  A feature identifier that is not mapped to a value
stands for a feature whose value is unknown (*not* a feature without
a value).  Two feature structures that represent (potentially
overlapping) information about the same object can be combined by
unification.  When two inconsistent feature structures are unified,
the unification fails and returns None.

Features can be specified using "feature paths", or tuples of feature
identifiers that specify path through the nested feature structures to
a value.  Feature structures may contain reentrant feature values.  A
"reentrant feature value" is a single feature value that can be
accessed via multiple feature paths.  Unification preserves the
reentrance relations imposed by both of the unified feature
structures.  In the feature structure resulting from unification, any
modifications to a reentrant feature value will be visible using any
of its feature paths.

Feature structure variables are encoded using the ``nltk.sem.Variable``
class.  The variables' values are tracked using a bindings
dictionary, which maps variables to their values.  When two feature
structures are unified, a fresh bindings dictionary is created to
track their values; and before unification completes, all bound
variables are replaced by their values.  Thus, the bindings
dictionaries are usually strictly internal to the unification process.
However, it is possible to track the bindings of variables if you
choose to, by supplying your own initial bindings dictionary to the
``unify()`` function.

When unbound variables are unified with one another, they become
aliased.  This is encoded by binding one variable to the other.

Lightweight Feature Structures
==============================
Many of the functions defined by ``nltk.featstruct`` can be applied
directly to simple Python dictionaries and lists, rather than to
full-fledged ``FeatDict`` and ``FeatList`` objects.  In other words,
Python ``dicts`` and ``lists`` can be used as "light-weight" feature
structures.

    >>> from nltk.featstruct import unify
    >>> unify(dict(x=1, y=dict()), dict(a='a', y=dict(b='b')))  # doctest: +SKIP
    {'y': {'b': 'b'}, 'x': 1, 'a': 'a'}

However, you should keep in mind the following caveats:

  - Python dictionaries & lists ignore reentrance when checking for
    equality between values.  But two FeatStructs with different
    reentrances are considered nonequal, even if all their base
    values are equal.

  - FeatStructs can be easily frozen, allowing them to be used as
    keys in hash tables.  Python dictionaries and lists can not.

  - FeatStructs display reentrance in their string representations;
    Python dictionaries and lists do not.

  - FeatStructs may *not* be mixed with Python dictionaries and lists
    (e.g., when performing unification).

  - FeatStructs provide a number of useful methods, such as ``walk()``
    and ``cyclic()``, which are not available for Python dicts and lists.

In general, if your feature structures will contain any reentrances,
or if you plan to use them as dictionary keys, it is strongly
recommended that you use full-fledged ``FeatStruct`` objects.
    N)total_ordering)raise_unorderable_typesread_str)
ExpressionLogicalExpressionExceptionLogicParserSubstituteBindingsIVariablec                        e Zd ZdZdZ	 d" fd	Zd Zd Zd Zd#dZ	d Z
d	 Zd
 Zd Zd Zd ZdZd Zd Zd Zd$dZd Zd Zd Zd Zd Zd Zd Zd Zd Zd%dZd Zd&dZd Z d  Z!d! Z" xZ#S )'
FeatStructa  
    A mapping from feature identifiers to feature values, where each
    feature value is either a basic value (such as a string or an
    integer), or a nested feature structure.  There are two types of
    feature structure:

      - feature dictionaries, implemented by ``FeatDict``, act like
        Python dictionaries.  Feature identifiers may be strings or
        instances of the ``Feature`` class.
      - feature lists, implemented by ``FeatList``, act like Python
        lists.  Feature identifiers are integers.

    Feature structures may be indexed using either simple feature
    identifiers or 'feature paths.'  A feature path is a sequence
    of feature identifiers that stand for a corresponding sequence of
    indexing operations.  In particular, ``fstruct[(f1,f2,...,fn)]`` is
    equivalent to ``fstruct[f1][f2]...[fn]``.

    Feature structures may contain reentrant feature structures.  A
    "reentrant feature structure" is a single feature structure
    object that can be accessed via multiple feature paths.  Feature
    structures may also be cyclic.  A feature structure is "cyclic"
    if there is any feature path from the feature structure to itself.

    Two feature structures are considered equal if they assign the
    same values to all features, and have the same reentrancies.

    By default, feature structures are mutable.  They may be made
    immutable with the ``freeze()`` method.  Once they have been
    frozen, they may be hashed, and thus used as dictionary keys.
    Fc                    | t         u r|t        j                  t        fi |S t        |      rt        j                  t        |fi |S |rt	        d      t        |t              rUt        j                  j                  |      rt        j                  t        |fi |S t        j                  t        |fi |S t        |      rt        j                  t        |      S t	        d      t        |   | |fi |S )a  
        Construct and return a new feature structure.  If this
        constructor is called directly, then the returned feature
        structure will be an instance of either the ``FeatDict`` class
        or the ``FeatList`` class.

        :param features: The initial feature values for this feature
            structure:

            - FeatStruct(string) -> FeatStructReader().read(string)
            - FeatStruct(mapping) -> FeatDict(mapping)
            - FeatStruct(sequence) -> FeatList(sequence)
            - FeatStruct() -> FeatDict()
        :param morefeatures: If ``features`` is a mapping or None,
            then ``morefeatures`` provides additional features for the
            ``FeatDict`` constructor.
        zLKeyword arguments may only be specified if features is None or is a mapping.z&Expected string or mapping or sequence)r   FeatDict__new___is_mapping	TypeError
isinstancestrFeatStructReader_START_FDICT_REmatchFeatList_is_sequencesuper)clsfeaturesmorefeatures	__class__s      D/var/www/openai/venv/lib/python3.12/site-packages/nltk/featstruct.pyr   zFeatStruct.__new__   s    * *''ALAAX&''(KlKK;  (C(#3399(C#++HhO,OO#++HhO,OOh'''(;; HII 7?3ALAA    c                     t               )zNReturn an iterable of the feature identifiers used by this
        FeatStruct.NotImplementedErrorselfs    r   _keyszFeatStruct._keys        "##r   c                     t               )zUReturn an iterable of the feature values directly defined
        by this FeatStruct.r!   r#   s    r   _valueszFeatStruct._values   r&   r   c                     t               )zReturn an iterable of (fid,fval) pairs, where fid is a
        feature identifier and fval is the corresponding feature
        value, for all features defined by this FeatStruct.r!   r#   s    r   _itemszFeatStruct._items   s     "##r   c                 \    | j                  ||t               t               t                     S )aB  
        Return True if ``self`` and ``other`` assign the same value to
        to every feature.  In particular, return true if
        ``self[p]==other[p]`` for every feature path *p* such
        that ``self[p]`` or ``other[p]`` is a base value (i.e.,
        not a nested feature structure).

        :param check_reentrance: If True, then also return False if
            there is any difference between the reentrances of ``self``
            and ``other``.
        :note: the ``==`` is equivalent to ``equal_values()`` with
            ``check_reentrance=True``.
        _equalset)r$   othercheck_reentrances      r   equal_valueszFeatStruct.equal_values   s"     {{5"2CE35#%HHr   c                 \    | j                  |dt               t               t                     S )a  
        Return true if ``self`` and ``other`` are both feature structures,
        assign the same values to all features, and contain the same
        reentrances.  I.e., return
        ``self.equal_values(other, check_reentrance=True)``.

        :see: ``equal_values()``
        Tr,   r$   r/   s     r   __eq__zFeatStruct.__eq__   s!     {{5$suce<<r   c                     | |k(   S N r3   s     r   __ne__zFeatStruct.__ne__       5=  r   c                     t        |t              s-| j                  j                  |j                  j                  k  S t	        |       t	        |      k  S r6   )r   r   r   __name__lenr3   s     r   __lt__zFeatStruct.__lt__   s@    %, >>**U__-E-EEEt9s5z))r   c                     | j                   st        d      	 | j                  S # t        $ r- | j	                  t                     | _        | j                  cY S w xY w)zu
        If this feature structure is frozen, return its hash value;
        otherwise, raise ``TypeError``.
        z5FeatStructs must be frozen before they can be hashed.)_frozenr   _hashAttributeError_calculate_hashvaluer.   r#   s    r   __hash__zFeatStruct.__hash__	  sS    
 ||VWW	:: 	22359DJ::	s   % 3AAc                    | |u ry| j                   |j                   k7  ryt        |       t        |      k7  ryt        | j                               t        |j                               k7  ry|r2t	        |       |v st	        |      |v r1t	        |       t	        |      f|v S t	        |       t	        |      f|v ry|j                  t	        |              |j                  t	        |             |j                  t	        |       t	        |      f       | j                         D ]9  \  }}||   }t        |t              r|j                  |||||      r1 y||k7  s9 y y)a  
        Return True iff self and other have equal values.

        :param visited_self: A set containing the ids of all ``self``
            feature structures we've already visited.
        :param visited_other: A set containing the ids of all ``other``
            feature structures we've already visited.
        :param visited_pairs: A set containing ``(selfid, otherid)`` pairs
            for all pairs of feature structures we've already visited.
        TF)
r   r<   r.   r%   idaddr*   r   r   r-   )	r$   r/   r0   visited_selfvisited_othervisited_pairsfname	self_fval
other_fvals	            r   r-   zFeatStruct._equal  sD    5= >>U__,
 t9E
"tzz|EKKM 22 $x<'2e9+E4"U),== 4"U)$5 	D""U)$2d8RY/0 !%E9uJ)Z0 ''$ !! !
*  !.  r   c                 N   t        |       |v ry|j                  t        |              d}t        | j                               D ]^  \  }}|dz  }|t	        |      z  }|dz  }t        |t              r||j                  |      z  }n|t	        |      z  }t        |dz        }` |S )z
        Return a hash value for this feature structure.

        :require: ``self`` must be frozen.
        :param visited: A set containing the ids of all feature
            structures we've already visited while hashing.
           i  %   i)	rE   rF   sortedr*   hashr   r   rB   int)r$   visitedhashvalrJ   fvals        r   rB   zFeatStruct._calculate_hashvalue]  s     d8wBtH!$++-0KE4rMGtE{"GrMG$
+444W==4:%'J./G 1 r   'Frozen FeatStructs may not be modified.c                 P    | j                   ry| j                  t                      y)a  
        Make this feature structure, and any feature structures it
        contains, immutable.  Note: this method does not attempt to
        'freeze' any feature value that is not a ``FeatStruct``; it
        is recommended that you use only immutable feature values.
        N)r?   _freezer.   r#   s    r   freezezFeatStruct.freeze~  s     <<SUr   c                     | j                   S )a$  
        Return True if this feature structure is immutable.  Feature
        structures can be made immutable with the ``freeze()`` method.
        Immutable feature structures may not be made mutable again,
        but new mutable copies can be produced with the ``copy()`` method.
        )r?   r#   s    r   frozenzFeatStruct.frozen  s     ||r   c                     t        |       |v ry|j                  t        |              d| _        t        | j	                               D ]'  \  }}t        |t              s|j                  |       ) y)z
        Make this feature structure, and any feature structure it
        contains, immutable.

        :param visited: A set containing the ids of all feature
            structures we've already visited while freezing.
        NT)rE   rF   r?   rP   r*   r   r   rX   )r$   rS   rJ   rU   s       r   rX   zFeatStruct._freeze  sY     d8wBtH!$++-0KE4$
+W% 1r   c                 R    |rt        j                  |       S | j                  |       S )z
        Return a new copy of ``self``.  The new copy will not be frozen.

        :param deep: If true, create a deep copy; if false, create
            a shallow copy.
        )copydeepcopyr   )r$   deeps     r   r^   zFeatStruct.copy  s%     ==&&>>$''r   c                     t               r6   r!   )r$   memos     r   __deepcopy__zFeatStruct.__deepcopy__  s    !##r   c                 <    | j                  i       t        |          S )zH
        Return True if this feature structure contains itself.
        )_find_reentrancesrE   r#   s    r   cycliczFeatStruct.cyclic  s     %%b)"T(33r   c                 4    | j                  t                     S )z
        Return an iterator that generates this feature structure, and
        each feature structure it contains.  Each feature structure will
        be generated exactly once.
        )_walkr.   r#   s    r   walkzFeatStruct.walk  s     zz#%  r   c                     t               )z
        Return an iterator that generates this feature structure, and
        each feature structure it contains.

        :param visited: A set containing the ids of all feature
            structures we've already visited while freezing.
        r!   )r$   rS   s     r   rh   zFeatStruct._walk  s     "##r   c              #      K   t        |       |v ry |j                  t        |              |  | j                         D ],  }t        |t              s|j                  |      E d {    . y 7 wr6   )rE   rF   r(   r   r   rh   )r$   rS   rU   s      r   rh   zFeatStruct._walk  sY     d8wBtH
LLND$
+::g... #.s   AA1A1'A/(A1c                     t        |       |v rd|t        |       <   |S d|t        |       <   | j                         D ]$  }t        |t              s|j	                  |       & |S )z
        Return a dictionary that maps from the ``id`` of each feature
        structure contained in ``self`` (including ``self``) to a
        boolean value, indicating whether it is reentrant or not.
        TF)rE   r(   r   r   re   )r$   reentrancesrU   s      r   re   zFeatStruct._find_reentrances  sh     d8{"$(K4!  %*K4! dJ/**;7 ' r   c                     t        | |      S )z/:see: ``nltk.featstruct.substitute_bindings()``)substitute_bindingsr$   bindingss     r   ro   zFeatStruct.substitute_bindings  s    "422r   c                     t        | |      S )z,:see: ``nltk.featstruct.retract_bindings()``)retract_bindingsrp   s     r   rs   zFeatStruct.retract_bindings  s    h//r   c                     t        |       S )z*:see: ``nltk.featstruct.find_variables()``)find_variablesr#   s    r   	variableszFeatStruct.variables  s    d##r   c                     t        | |||      S )z,:see: ``nltk.featstruct.rename_variables()``)rename_variables)r$   vars	used_varsnew_varss       r   rx   zFeatStruct.rename_variables  s    dIx@@r   c                     t        |       S )z
        Return the feature structure that is obtained by deleting
        any feature whose value is a ``Variable``.

        :rtype: FeatStruct
        )remove_variablesr#   s    r   r}   zFeatStruct.remove_variables  s      %%r   c                 "    t        | |||||      S r6   unify)r$   r/   rq   tracefailrename_varss         r   r   zFeatStruct.unify  s    T5(E4EEr   c                     t        | |      S )z
        Return True if ``self`` subsumes ``other``.  I.e., return true
        If unifying ``self`` with ``other`` would result in a feature
        structure equal to ``other``.
        )subsumesr3   s     r   r   zFeatStruct.subsumes  s     e$$r   c                 D    | j                  | j                  i       i       S )z
        Display a single-line representation of this feature structure,
        suitable for embedding in other representations.
        )_reprre   r#   s    r   __repr__zFeatStruct.__repr__#  s     
 zz$004b99r   c                     t               )a  
        Return a string representation of this feature structure.

        :param reentrances: A dictionary that maps from the ``id`` of
            each feature value in self, indicating whether that value
            is reentrant or not.
        :param reentrance_ids: A dictionary mapping from each ``id``
            of a feature value to a unique identifier.  This is modified
            by ``repr``: the first time a reentrant feature value is
            displayed, an identifier is added to ``reentrance_ids`` for it.
        r!   )r$   rm   reentrance_idss      r   r   zFeatStruct._repr*  s     "##r   r6   F)T)Nr7   N)NFNT)$r;   
__module____qualname____doc__r?   r   r%   r(   r*   r1   r4   r8   r=   rC   r-   rB   _FROZEN_ERRORrY   r[   rX   r^   rc   rf   ri   rh   re   ro   rs   rv   rx   r}   r   r   r   r   __classcell__)r   s   @r   r   r   n   s    @ G+Bh$
$
$I 	=!*EN> >M	&(
($4!$/030$A&F%:$r   r   rV   z'
%sIf self is frozen, raise ValueError.c                 r      fd} j                   |_          j                  xs dt        |z  z   |_        |S )z
    Given a method function, return a new method function that first
    checks if ``self._frozen`` is true; and if so, raises ``ValueError``
    with an appropriate message.  Otherwise, call the method and return
    its result.
    c                 R    | j                   rt        t               | g|i |S r6   )r?   
ValueErrorr   )r$   argskwargsmethods      r   wrappedz_check_frozen.<locals>.wrappedF  s*    <<]++$0000r    )r;   r   _FROZEN_NOTICE)r   indentr   s   `  r   _check_frozenr   >  s5    1 G~~+0GHGONr   c                      e Zd ZdZddZdZd ZddZd Zd Z	d	 Z
d
 Z eej                        Z eej                        Z eej                         Z eej"                        ZddZd Zd Zd Zd Zd Zd Zd Zy)r   a  
    A feature structure that acts like a Python dictionary.  I.e., a
    mapping from feature identifiers to feature values, where a feature
    identifier can be a string or a ``Feature``; and where a feature value
    can be either a basic value (such as a string or an integer), or a nested
    feature structure.  A feature identifiers for a ``FeatDict`` is
    sometimes called a "feature name".

    Two feature dicts are considered equal if they assign the same
    values to all features, and have the same reentrances.

    :see: ``FeatStruct`` for information about feature paths, reentrance,
        cyclic feature structures, mutability, freezing, and hashing.
    Nc                     t        |t              r-t               j                  ||         | j                  di | y | j                  |fi | y)a3  
        Create a new feature dictionary, with the specified features.

        :param features: The initial value for this feature
            dictionary.  If ``features`` is a ``FeatStruct``, then its
            features are copied (shallow copy).  If ``features`` is a
            dict, then a feature is created for each item, mapping its
            key to its value.  If ``features`` is a string, then it is
            processed using ``FeatStructReader``.  If ``features`` is a list of
            tuples ``(name, val)``, then a feature is created for each tuple.
        :param morefeatures: Additional features for the new feature
            dictionary.  If a feature is listed under both ``features`` and
            ``morefeatures``, then the value from ``morefeatures`` will be
            used.
        Nr7   )r   r   r   
fromstringupdate)r$   r   r   s      r   __init__zFeatDict.__init__f  sG      h$))(D9DKK',' DKK1L1r   z'Expected feature name or path.  Got %r.c                 >   t        |t        t        f      rt        j	                  | |      S t        |t
              r'	 | }|D ]  }t        |t              st        ||   } |S t        | j                  |z        # t        t        f$ r}t        |      |d}~ww xY w)zkIf the feature with the given name or path exists, return
        its value; otherwise, raise ``KeyError``.N)r   r   Featuredict__getitem__tupler   KeyError
IndexErrorr   _INDEX_ERRORr$   name_or_pathvalfides        r   r   zFeatDict.__getitem__  s     lS'N3##D,77e,4'C%c:6&c(C ( 
 D--<== j) 4|,!34s   %A< <BBBc                 0    	 | |   S # t         $ r |cY S w xY w)zkIf the feature with the given name or path exists, return its
        value; otherwise, return ``default``.r   )r$   r   defaults      r   getzFeatDict.get  s&    	%% 	N	s    c                 .    	 | |    y# t         $ r Y yw xY w)<Return true if a feature with the given name or path exists.TFr   r$   r   s     r   __contains__zFeatDict.__contains__  s$    	 		s    	c                 
    || v S )r   r7   r   s     r   has_keyzFeatDict.has_key  s    t##r   c                 f   | j                   rt        t              t        |t        t
        f      rt        j                  | |      S t        |t              rCt        |      dk(  rt        d      | |dd    }t        |t              st        |      ||d   = yt        | j                  |z        zkIf the feature with the given name or path exists, delete
        its value; otherwise, raise ``KeyError``.r   The path () can not be setN)r?   r   r   r   r   r   r   __delitem__r   r<   r   r   r   r   r$   r   parents      r   r   zFeatDict.__delitem__  s     <<]++lS'N3##D,77e,< A% !=>>l3B/0!&*5"<00<+,D--<==r   c                 l   | j                   rt        t              t        |t        t
        f      rt        j                  | ||      S t        |t              rEt        |      dk(  rt        d      | |dd    }t        |t              st        |      |||d   <   yt        | j                  |z        zSet the value for the feature with the given name or path
        to ``value``.  If ``name_or_path`` is an invalid path, raise
        ``KeyError``.r   r   Nr   )r?   r   r   r   r   r   r   __setitem__r   r<   r   r   r   r   r$   r   valuer   s       r   r   zFeatDict.__setitem__  s     <<]++lS'N3##D,>>e,< A% !=>>l3B/0!&*5"<00+0|B'(D--<==r   c                    | j                   rt        t              |d}nLt        |d      r&t	        |j
                        r|j                         }nt        |d      r|}nt        d      |D ]+  \  }}t        |t        t        f      st        d      || |<   - |j                         D ]+  \  }}t        |t        t        f      st        d      || |<   - y )Nr7   items__iter__z"Expected mapping or list of tupleszFeature names must be strings)
r?   r   r   hasattrcallabler   r   r   r   r   )r$   r   r   r   keyr   s         r   r   zFeatDict.update  s    <<]++EXw'HX^^,DNN$EXz*EABBHCcC>2 ?@@DI  %**,HCcC>2 ?@@DI -r   c                     | j                         x|t        |       <   }| j                         D ]2  \  }}t        j                  ||      |t        j                  ||      <   4 |S r6   )r   rE   r*   r^   r_   )r$   rb   selfcopyr   r   s        r   rc   zFeatDict.__deepcopy__  sT    $(NN$44RXHC15sD1IHT]]3-. &r   c                 "    | j                         S r6   )keysr#   s    r   r%   zFeatDict._keys  s    yy{r   c                 "    | j                         S r6   )valuesr#   s    r   r(   zFeatDict._values  s    {{}r   c                 "    | j                         S r6   )r   r#   s    r   r*   zFeatDict._items  s    zz|r   c                 b    dj                  | j                  | j                  i       i             S )zz
        Display a multi-line representation of this feature dictionary
        as an FVM (feature value matrix).
        
)join_strre   r#   s    r   __str__zFeatDict.__str__  s)    
 yy4#9#9"#=rBCCr   c           	      V   g }d}d}|t        |          r2t        |       |vsJ t        t        |      dz         |t        |       <   t        | j	                               D ]  \  }}t        |dd       }t        |      |v r$|j                  | d|t        |          d       E|dk(  r|st        |t        t        f      rd|z  }h|dk(  r1|s/t        |t              rd	|j                  z  }d	t        |      z  }t        |t              r!|j                  | d
|j                          |du r|j                  d|z         |du r|j                  d|z         t        |t              r|j                  | d| d       +t        |t              s!|j                  | d
t        |              \|j                  ||      }	|j                  | d
|	         |t        |          rd|t        |           d| }dj                  |dj                  |      |      S )Nr   rN   displayz->()prefix%sslashz/%s=Tz+%sFz-%sz=<>(z{}[{}]{}, )rE   reprr<   rP   r   getattrappendr   r
   r   namer   r   r   formatr   )
r$   rm   r   segmentsr   suffixrJ   rU   r   	fval_reprs
             r   r   zFeatDict._repr	  s    r$x d8>111'+C,?!,C'DN2d8$ "$**,/KE4eY5G$x>)5'^BtH-E,Fa HI8#Fz$SV7XG#FdH-"TYY.F"T$Z/FD(+5'499+ 67..D*-5'D6 34j15'4:, 78 JJ{NC	5'9+ 673 06 r$x 412!F8<F  8)<fEEr   c                 ,   |t        |          r2t        |       |vsJ t        t        |      dz         |t        |       <   t        |       dk(  r#|t        |          rd|t        |          z  gS dgS t        d | j	                         D              }g }t        | j                               D ]  \  }}d|z  j                  |      }t        |t              r!|j                  | d|j                          Lt        |t              r|j                  | d| d	       tt        |t              r2|j                  ||      }|j                  | dt        |              t        |t              s |j                  | dt        |              t        |      |v r%|j                  | d
|t        |          d       |r|d   dk7  r|j                  d       |j!                  ||      }|D 	cg c]  }	d|dz   z  |	z    }}	t        |      dz
  dz  }
|dz   ||
   |dz   d z   ||
<   ||z  }|j                  d        |d   dk(  r|j#                          t        d |D              }|D cg c]#  }dj%                  |d|t        |      z
  z        % }}|t        |          rWd|t        |          z  }|D 	cg c]  }	dt        |      z  |	z    }}	t        |      dz
  dz  }|||   t        |      d z   ||<   |S c c}	w c c}w c c}	w )aL  
        :return: A list of lines composing a string representation of
            this feature dictionary.
        :param reentrances: A dictionary that maps from the ``id`` of
            each feature value in self, indicating whether that value
            is reentrant or not.
        :param reentrance_ids: A dictionary mapping from each ``id``
            of a feature value to a unique identifier.  This is modified
            by ``repr``: the first time a reentrant feature value is
            displayed, an identifier is added to ``reentrance_ids`` for
            it.
        rN   r   z(%s) []z[]c              3   8   K   | ]  }t        d |z          ywr   Nr<   ).0ks     r   	<genexpr>z FeatDict._str.<locals>.<genexpr>P  s     =A#dQh-s   r   z = z = <r   z -> (r   r   r          z =Nc              3   2   K   | ]  }t        |        y wr6   r   )r   lines     r   r   z FeatDict._str.<locals>.<genexpr>  s     154SY5s   z[ {}{} ]z(%s) )rE   r   r<   maxr   rP   r   ljustr   r
   r   r   r   r   r   r   r   popr   )r$   rm   r   maxfnamelenlinesrJ   rU   r   
fval_lineslnamelinemaxlenr   idstridlines                  r   r   zFeatDict._str5  s"    r$x d8>111'+C,?!,C'DN2d8$ t9>2d8$!N2d8$<<==v === "$**,/KE4E\((5E$)wc$))56D*-wd4&23D(+ JJ{NC	wc$y/):;<h/wc$t*67D^+ weN2d8,D+EQGH
 U2Y"_LL$ "YY{NC
 FPPZskAo6!;Z
P  
Oa/A5DL:h#7a8I#JJ 8$
 # R W 0\ 9?IIK 1511QVWQV""4T0B)CDQVW r$x nRX66E5:;UcCJ&!+UE;%j1n*F!E&M#e*,$??E&M; Q( X
 <s   6L6(LLr6   )r;   r   r   r   r   r   r   r   r   r   r   r   r   r   clearr   popitem
setdefaultr   rc   r%   r(   r*   r   r   r   r7   r   r   r   r   V  s    24 =L>$$>$>& $**%E

!CDLL)Gt/J2D*FX\r   r   c                      e Zd ZdZddZdZd Zd Zd Z e	e
j                        Z e	e
j                        Z e	e
j                        Z e	e
j                        Z e	e
j                        Z e	e
j                         Z e	e
j"                        Z e	e
j$                        Z e	e
j&                        Zd Zd Zd	 Zd
 Zd Zy)r   ay  
    A list of feature values, where each feature value is either a
    basic value (such as a string or an integer), or a nested feature
    structure.

    Feature lists may contain reentrant feature values.  A "reentrant
    feature value" is a single feature value that can be accessed via
    multiple feature paths.  Feature lists may also be cyclic.

    Two feature lists are considered equal if they assign the same
    values to all features, and have the same reentrances.

    :see: ``FeatStruct`` for information about feature paths, reentrance,
        cyclic feature structures, mutability, freezing, and hashing.
    c                     t        |t              rt               j                  ||        yt        j                  | |       y)aZ  
        Create a new feature list, with the specified features.

        :param features: The initial list of features for this feature
            list.  If ``features`` is a string, then it is paresd using
            ``FeatStructReader``.  Otherwise, it should be a sequence
            of basic values and nested feature structures.
        N)r   r   r   r   listr   )r$   r   s     r   r   zFeatList.__init__  s/     h$))(D9MM$)r   z&Expected int or feature path.  Got %r.c                 2   t        |t              rt        j                  | |      S t        |t              r'	 | }|D ]  }t        |t
              st        ||   } |S t        | j                  |z        # t        t        f$ r}t        |      |d }~ww xY wr6   )
r   rR   r  r   r   r   r   r   r   r   r   s        r   r   zFeatList.__getitem__  s    lC(##D,77e,4'C%c:6&c(C ( 
 D--<== j) 4|,!34s   %A6 6BBBc                 f   | j                   rt        t              t        |t        t
        f      rt        j                  | |      S t        |t              rCt        |      dk(  rt        d      | |dd    }t        |t              st        |      ||d   = yt        | j                  |z        r   )r?   r   r   r   rR   slicer  r   r   r<   r   r   r   r   r   s      r   r   zFeatList.__delitem__  s     <<]++lS%L1##D,77e,< A% !=>>l3B/0!&*5"<00<+,D--<==r   c                 l   | j                   rt        t              t        |t        t
        f      rt        j                  | ||      S t        |t              rEt        |      dk(  rt        d      | |dd    }t        |t              st        |      |||d   <   yt        | j                  |z        r   )r?   r   r   r   rR   r  r  r   r   r<   r   r   r   r   r   s       r   r   zFeatList.__setitem__  s     <<]++lS%L1##D,>>e,< A% !=>>l3B/0!&*5"<00+0|B'(D--<==r   c                 x    | j                         xt        |       <   }|j                  fd| D               |S )Nc              3   J   K   | ]  }t        j                  |        y wr6   )r^   r_   )r   rU   rb   s     r   r   z(FeatList.__deepcopy__.<locals>.<genexpr>  s     CdddD1ds    #)r   rE   extend)r$   rb   r   s    ` r   rc   zFeatList.__deepcopy__  s3    $(NN$44RXCdCCr   c                 <    t        t        t        |                   S r6   )r  ranger<   r#   s    r   r%   zFeatList._keys  s    E#d)$%%r   c                     | S r6   r7   r#   s    r   r(   zFeatList._values  s    r   c                     t        |       S r6   )	enumerater#   s    r   r*   zFeatList._items  s    r   c                    |t        |          rDt        |       |vsJ t        t        |      dz         |t        |       <   d|t        |          z  }nd}g }| D ]  }t        |      |v r!|j                  d|t        |         z         1t	        |t
              r|j                  |j                         ]t	        |t              r|j                  d|z         t	        |t              r"|j                  |j                  ||             |j                  dt        |      z          dj                  |dj                  |            S )NrN   (%s)r   z->(%s)r   z{}[{}]r   )rE   r   r<   r   r   r
   r   r   r   r   r   r   )r$   rm   r   r   r   rU   s         r   r   zFeatList._repr  s    r$x d8>111'+C,?!,C'DN2d8$nRX66FFD$x>)>"T(+C CDD(+		*D*-t,D*-

; GHtDz 12  vtyy':;;r   N)r7   )r;   r   r   r   r   r   r   r   r   r   r  __iadd____imul__r   r  insertr   removereversesortrc   r%   r(   r*   r   r7   r   r   r   r     s     *" <L> >$>* T]]+HT]]+H4;;'F4;;'F4;;'F

!C4;;'FDLL)G#D&<r   r   c                 |    |dk(  rt        |       }t        j                  |       } t        | ||t	                      | S )a  
    Return the feature structure that is obtained by replacing each
    variable bound by ``bindings`` with its binding.  If a variable is
    aliased to a bound variable, then it will be replaced by that
    variable's value.  If a variable is aliased to an unbound
    variable, then it will be replaced by that variable.

    :type bindings: dict(Variable -> any)
    :param bindings: A dictionary mapping from variables to values.
    r   )_default_fs_classr^   r_   _substitute_bindingsr.   )fstructrq   fs_classs      r   ro   ro   8  s9     9$W-mmG$G(Hce<Nr   c                    t        |       |v ry |j                  t        |              t        |       r| j                         }n"t	        |       rt        |       }nt        d      |D ]x  \  }}t        |t              r#||v r||   x}| |<   t        |t              r||v rt        ||      rt        ||||       Tt        |t              se|j                  |      | |<   z y NExpected mapping or sequence)rE   rF   r   r   r   r  r   r   r
   r  r	   ro   )r  rq   r  rS   r   rJ   rU   s          r   r  r  J  s    	'{gKK77	g	'"788tx(TX-=$,TN2D75> x(TX-=dH% x7C12!55h?GEN r   c                    |dk(  rt        |       }t        j                  | |f      \  } }|j                  |       |j	                         D ci c]  \  }}t        |      | }}}t        | ||t                      | S c c}}w )a  
    Return the feature structure that is obtained by replacing each
    feature structure value that is bound by ``bindings`` with the
    variable that binds it.  A feature structure value must be
    identical to a bound value (i.e., have equal id) to be replaced.

    ``bindings`` is modified to point to this new feature structure,
    rather than the original feature structure.  Feature structure
    values in ``bindings`` may be modified if they are contained in
    ``fstruct``.
    r   )r  r^   r_   r   r   rE   _retract_bindingsr.   )r  rq   r  new_bindingsvarr   inv_bindingss          r   rs   rs   _  s~     9$W-"mmWh,?@WlOOL!3;>>3CD3CZc3BsGSL3CLDg|Xsu=N Es   B c                 V   t        |       |v ry |j                  t        |              t        |       r| j                         }n"t	        |       rt        |       }nt        d      |D ]>  \  }}t        ||      st        |      |v r|t        |         | |<   t        ||||       @ y r  )	rE   rF   r   r   r   r  r   r   r"  )r  r%  r  rS   r   rJ   rU   s          r   r"  r"  t  s    	'{gKK77	g	'"788tdH%$x<'!-bh!7dL(GD	 r   c                 ^    |dk(  rt        |       }t        | t               |t                     S )za
    :return: The set of variables used by this feature structure.
    :rtype: set(Variable)
    r   )r  
_variablesr.   r  r  s     r   ru   ru     s+    
 9$W-gsuh66r   c                    t        |       |v ry |j                  t        |              t        |       r| j                         }n"t	        |       rt        |       }nt        d      |D ]r  \  }}t        |t              r|j                  |       (t        ||      rt        ||||       Ct        |t              sT|j                  |j                                t |S r  )rE   rF   r   r   r   r  r   r   r
   r(  r	   r   rv   )r  ry   r  rS   r   rJ   rU   s          r   r(  r(    s    	'{gKK77	g	'"788tdH%HHTNh'tT8W512KK()  Kr   c           	          |dk(  rt        |       }|i }|t        | |      }nt        |      }t        | |      j                  |      }t	        t        j                  |       ||||t                     S )a  
    Return the feature structure that is obtained by replacing
    any of this feature structure's variables that are in ``vars``
    with new variables.  The names for these new variables will be
    names that are not used by any variable in ``vars``, or in
    ``used_vars``, or in this feature structure.

    :type vars: set
    :param vars: The set of variables that should be renamed.
        If not specified, ``find_variables(fstruct)`` is used; i.e., all
        variables will be given new names.
    :type used_vars: set
    :param used_vars: A set of variables whose names should not be
        used by the new variables.
    :type new_vars: dict(Variable -> Variable)
    :param new_vars: A dictionary that is used to hold the mapping
        from old variables to new variables.  For each variable *v*
        in this feature structure:

        - If ``new_vars`` maps *v* to *v'*, then *v* will be
          replaced by *v'*.
        - If ``new_vars`` does not contain *v*, but ``vars``
          does contain *v*, then a new entry will be added to
          ``new_vars``, mapping *v* to the new variable that is used
          to replace it.

    To consistently rename the variables in a set of feature
    structures, simply apply rename_variables to each one, using
    the same dictionary:

        >>> from nltk.featstruct import FeatStruct
        >>> fstruct1 = FeatStruct('[subj=[agr=[gender=?y]], obj=[agr=[gender=?y]]]')
        >>> fstruct2 = FeatStruct('[subj=[agr=[number=?z,gender=?y]], obj=[agr=[number=?z,gender=?y]]]')
        >>> new_vars = {}  # Maps old vars to alpha-renamed vars
        >>> fstruct1.rename_variables(new_vars=new_vars)
        [obj=[agr=[gender=?y2]], subj=[agr=[gender=?y2]]]
        >>> fstruct2.rename_variables(new_vars=new_vars)
        [obj=[agr=[gender=?y2, number=?z2]], subj=[agr=[gender=?y2, number=?z2]]]

    If new_vars is not specified, then an empty dictionary is used.
    r   )r  ru   r.   union_rename_variablesr^   r_   )r  ry   rz   r{   r  s        r   rx   rx     s~    X 9$W- |gx04y w177	BI gi8SU r   c           	         t        |       |v ry |j                  t        |              t        |       r| j                         }n"t	        |       rt        |       }nt        d      |D ]  \  }}t        |t              r>||v r	||   | |<   #||v s(t        ||      ||<   ||   | |<   |j                  ||          Tt        ||      rt        ||||||       qt        |t              s|j                         D ]/  }	|	|v s|	|vst        |	|      ||	<   |j                  ||	          1 |j                  |      | |<    | S r  )rE   rF   r   r   r   r  r   r   r
   _rename_variabler-  r	   rv   ro   )
r  ry   rz   r{   r  rS   r   rJ   rU   r$  s
             r   r-  r-    s6   	'{gKK77	g	'"788tdH%x!)$!1$	!B!)$htn-h'dD)XxQ12~~'$;3h#6$4S)$DHSMMM(3-0 (
 "55h?GEN' ( Nr   c                     t        j                  dd| j                        d}}|sd}t        | |       |v r|dz  }t        | |       |v rt        | |       S )Nz\d+$r   r   ?rN   )resubr   r
   )r$  rz   r   ns       r   r/  r/    sl    ffWb#((+Q!D
dVA3<
 I
-	Q dVA3<
 I
-tfQCL!!r   c                 r    |dk(  rt        |       }t        t        j                  |       |t	                     S )z
    :rtype: FeatStruct
    :return: The feature structure that is obtained by deleting
        all features whose values are ``Variables``.
    r   )r  _remove_variablesr^   r_   r.   r)  s     r   r}   r}     s0     9$W-T]]73XsuEEr   c                 f   t        |       |v ry |j                  t        |              t        |       rt        | j	                               }n+t        |       rt        t        |             }nt        d      |D ]3  \  }}t        |t              r| |= t        ||      s't        |||       5 | S r  )rE   rF   r   r  r   r   r  r   r   r
   r6  )r  r  rS   r   rJ   rU   s         r   r6  r6    s    	'{gKK77W]]_%	g	Yw'(788tdH%h'dHg6	 
 Nr   c                       e Zd Zd Zy)_UnificationFailurec                      y)Nz"nltk.featstruct.UnificationFailurer7   r#   s    r   r   z_UnificationFailure.__repr__5  s    3r   N)r;   r   r   r   r7   r   r   r9  r9  4  s    4r   r9  Fc           
         |dk(  r$t        |       }t        |      |k7  rt        d      t        | |      sJ t        ||      sJ |du}|i }t        j                  | ||f      \  }}	}
|j                  |
       |r0t        ||      }t        |	|      }t        |	||i |t                      i }|rt        d||	       	 t        ||	|||||d      }|t        u r|y |||	d      S t        |||t                     }|rt        ||       t        |       t!        |||t                      |rt#        d|       |rt%        d|       |S # t        $ r Y yw xY w)a!  
    Unify ``fstruct1`` with ``fstruct2``, and return the resulting feature
    structure.  This unified feature structure is the minimal
    feature structure that contains all feature value assignments from both
    ``fstruct1`` and ``fstruct2``, and that preserves all reentrancies.

    If no such feature structure exists (because ``fstruct1`` and
    ``fstruct2`` specify incompatible values for some feature), then
    unification fails, and ``unify`` returns None.

    Bound variables are replaced by their values.  Aliased
    variables are replaced by their representative variable
    (if unbound) or the value of their representative variable
    (if bound).  I.e., if variable *v* is in ``bindings``,
    then *v* is replaced by ``bindings[v]``.  This will
    be repeated until the variable is replaced by an unbound
    variable or a non-variable value.

    Unbound variables are bound when they are unified with
    values; and aliased when they are unified with variables.
    I.e., if variable *v* is not in ``bindings``, and is
    unified with a variable or value *x*, then
    ``bindings[v]`` is set to *x*.

    If ``bindings`` is unspecified, then all variables are
    assumed to be unbound.  I.e., ``bindings`` defaults to an
    empty dict.

        >>> from nltk.featstruct import FeatStruct
        >>> FeatStruct('[a=?x]').unify(FeatStruct('[b=?x]'))
        [a=?x, b=?x2]

    :type bindings: dict(Variable -> any)
    :param bindings: A set of variable bindings to be used and
        updated during unification.
    :type trace: bool
    :param trace: If true, generate trace output.
    :type rename_vars: bool
    :param rename_vars: If True, then rename any variables in
        ``fstruct2`` that are also used in ``fstruct1``, in order to
        avoid collisions on variable names.
    r   zGMixing FeatStruct objects with Python dicts and lists is not supported.Nr7   )r  r   r   r^   r_   r   ru   r-  r.   _trace_unify_start_destructively_unify_UnificationFailureErrorUnificationFailure_apply_forwards_apply_forwards_to_bindings_resolve_aliasesr  _trace_unify_succeed_trace_bindings)fstruct1fstruct2rq   r   r   r   r  user_bindingsfstruct1copyfstruct2copybindings_copyvars1vars2forwardresults                  r   r   r   D  s   j 9$X.X&(24  h)))h))) D(M 37--	8X&3/\<
 OOM"|X6|X6,ub(CEJ G2|\:%,'5$RT
 ##<lB77 VWh>F#GX6 X8SU; R(H%M5 $ s   ?E	 		EEc                       e Zd ZdZy)r>  zmAn exception that is used by ``_destructively_unify`` to abort
    unification when a failure is encountered.N)r;   r   r   r   r7   r   r   r>  r>    s    2r   r>  c                     | |u r|rt        ||        | S | |t        |      <   t        |       rt        |      r| D ],  }t        |dd      |j	                  ||j
                         . |D ],  }t        |dd      | j	                  ||j
                         . t        |j                               D ],  \  }}	|| v rt        || |   |	|||||||fz   	      | |<   (|	| |<   . | S t        |       rct        |      rXt        |       t        |      k7  rt        S t        t        |             D ]"  }
t        |
| |
   ||
   |||||||
fz   	      | |
<   $ | S t        |       st        |       rt        |      st        |      rt        S t        d      )aC  
    Attempt to unify ``fstruct1`` and ``fstruct2`` by modifying them
    in-place.  If the unification succeeds, then ``fstruct1`` will
    contain the unified value, the value of ``fstruct2`` is undefined,
    and forward[id(fstruct2)] is set to fstruct1.  If the unification
    fails, then a _UnificationFailureError is raised, and the
    values of ``fstruct1`` and ``fstruct2`` are undefined.

    :param bindings: A dictionary mapping variables to values.
    :param forward: A dictionary mapping feature structures ids
        to replacement structures.  When two feature structures
        are merged, a mapping from one to the other will be added
        to the forward dictionary; and changes will be made only
        to the target of the forward dictionary.
        ``_destructively_unify`` will always 'follow' any links
        in the forward dictionary for fstruct1 and fstruct2 before
        actually unifying them.
    :param trace: If true, generate trace output
    :param path: The feature path that led us to this unification
        step.  Used for trace output.
    r   NzExpected mappings or sequences)_trace_unify_identityrE   r   r   r  r   rP   r   _unify_feature_valuesr   r<   r?  r  r   )rE  rF  rq   rM  r   r   r  pathrJ   fval2findexs              r   r=  r=    s   6 8!$1 %GBxL 8X!6Eui.:##E5==9  Eui.:##E5==9  #8>>#34LE5 "7UOE8O
# #( 5   
h	L$:x=CM)%% CM*F4  y 
 HV +  x
 K$9X+h"7!! 4
55r   c	                    |rt        |||       t        |      |v r|t        |         }t        |      |v rt        |      |v r|t        |         }t        |      |v rdx}	}
t        |t              r ||v r|}	||   }t        |t              r||v rt        |t              r ||v r|}
||   }t        |t              r||v rt        ||      r t        ||      rt	        ||||||||      }n\t        |t              rt        |t              r||k7  r|||<   |}n.t        |t              r	|||<   |}nt        |t              r|||<   |}nt        ||      st        ||      rt
        }nt        | t              r| j                  |||      }nt        |t              r[|j                  |      }t        |t              rj||j                  |      k7  rVt        d|d|d|d|j                  |            t        |t              r|j                  |      }n||k(  r|}nt
        }|t
        ur|	|||	<   |	}|
|
|	k7  r|||
<   |
}|t
        u r+|
 ||||      }|rt        |dd |       |t
        u rt        t        ||      rt        |||t                     }|rt        ||       |rt        ||      rt!        ||       |S )a  
    Attempt to unify ``fval1`` and and ``fval2``, and return the
    resulting unified value.  The method of unification will depend on
    the types of ``fval1`` and ``fval2``:

      1. If they're both feature structures, then destructively
         unify them (see ``_destructively_unify()``.
      2. If they're both unbound variables, then alias one variable
         to the other (by setting bindings[v2]=v1).
      3. If one is an unbound variable, and the other is a value,
         then bind the unbound variable to the value.
      4. If one is a feature structure, and the other is a base value,
         then fail.
      5. If they're both base values, then unify them.  By default,
         this will succeed if they are equal, and fail otherwise.
    NzCustomFeatureValue objects z and z# disagree about unification value: z vs. r   )r<  rE   r   r
   r=  r?  r   unify_base_valuesCustomFeatureValuer   AssertionError_trace_unify_failr>  r@  r.   rC  rD  )rJ   fval1rT  rq   rM  r   r   r  fpathfvar1fvar2rN  s               r   rR  rR  *  s   & 5%/ U)w
5	" U)w

U)w
5	" U)w
 EE
UH
%%8*; UH
%%8*; UH
%%8*; UH
%%8*;
 %"z%'B%5(GUD(E

 
E8	$E8)DE>#HUO 
E8	$	E8	$ 
E8	$
5((C#
 eW%,,UE8DF12[['F%!345;;uCU9U$ eVU[[-?A 
 12[['F ~+
 ++ "( Ue^"( ##%.FeCRj&1''** &(# (CEBUF+FH-x(Mr   c                     |j                         D ]3  \  }}t        |      | v r| t        |         }t        |      | v r|||<   5 y)
    Replace any feature structure that has a forward pointer with
    the target of its forward pointer (to preserve reentrancy).
    N)r   rE   )rM  rq   r$  r   s       r   rA  rA    sJ    
 nn&
Ui7"BuI&E i7" 'r   c                    t        |       |v r|t        |          } t        |       |v rt        |       |v ry|j                  t        |              t        |       r| j                         }n"t	        |       rt        |       }nt        d      |D ]N  \  }}t        ||      st        |      |v r|t        |         }t        |      |v r|| |<   t        ||||       P | S )r`  Nr   )	rE   rF   r   r   r   r  r   r   r@  )r  rM  r  rS   r   rJ   rU   s          r   r@  r@    s     W+
 "W+& W+
  
'{gKK77	g	'"788tdH%T(g%r$x( T(g%!GEND'8W=  Nr   c                     | j                         D ];  \  }}t        |t              s|| v s| |   x}| |<   t        |t              s7|| v r = y)z
    Replace any bound aliased vars with their binding; and replace
    any unbound aliased vars with their representative var.
    N)r   r   r
   )rq   r$  r   s      r   rB  rB    sO    
 nn&
U)ex.?$,UO3EHSM )ex.? 'r   c                    | dk(  rt        d       n[dj                  d | D              }t        ddt        |       dz
  z  z   dz          t        ddt        |       dz
  z  z   d	|z  z          t        ddt        |       z  z   d
z   t        |      z          t        ddt        |       z  z   dz   t        |      z          y )Nr7   z
Unification trace:.c              3   &   K   | ]	  }d |z    ywr   r7   )r   r4  s     r   r   z%_trace_unify_start.<locals>.<genexpr>  s     3dD1Hds     |   rN   |z| Unify feature: %sz / z|\ )printr   r<   _trace_valrepr)rS  r[  rT  fullnames       r   r<  r<    s    rz$%883d33dVs4y1}--34dVs4y1}--0E0PPQ	$#d)#
#e
+nU.C
CD	$#d)#
#f
,~e/D
DEr   c                    t        ddt        |       z  z   dz          t        ddt        |       z  z   dz          t        ddt        |       z  z   dz          t        ddt        |       z  z   dz   t        |      z          y )Nrf  rg  rh  z| (identical objects)+-->ri  r<   r   rS  r[  s     r   rQ  rQ    sx    	$#d)#
#c
)*	$#d)#
#&=
=>	$#d)#
#c
)*	$#d)#
#f
,tE{
:;r   c                     |t         u rd}nd}t        ddt        |       z  z   dz          t        ddt        |       z  z   dz   |z          y )Nr   z (nonfatal)rf  rg  z|   |zX   zX   X <-- FAIL)r?  ri  r<   )rS  rN  resumes      r   rZ  rZ    sQ    ##	$#d)#
#g
-.	$#d)#
#&6
6
?@r   c                     t        ddt        |       z  z   dz          t        ddt        |       z  z   dz   t        |      z          y )Nrf  rg  rh  rm  rn  ro  s     r   rC  rC    sA    	$#d)#
#c
)*	$#d)#
#f
,tE{
:;r   c                     t        |      dkD  rXt        |j                         d       }ddj                  d |D              z  }t	        ddt        |       z  z   d	z   |z          y y )
Nr   c                      | d   j                   S )Nr   r   vs    r   <lambda>z!_trace_bindings.<locals>.<lambda>  s    1Q499r   )r   {%s}r   c              3   B   K   | ]  \  }}| d t        |         yw)z: N)rj  )r   r$  r   s      r   r   z"_trace_bindings.<locals>.<genexpr>  s)      %
>G
cse2nS)*+is   rf  rg  z    Bindings: )r<   rP   r   r   ri  )rS  rq   	binditemsbindstrs       r   rD  rD    sl    
8}q8>>+1DE	499 %
>G%
 
 
 	dVc$i''*::WDE r   c                 H    t        | t              rd| z  S dt        |       z  S )Nr   )r   r
   r   )r   s    r   rj  rj    s%    #x czd3ir   c                      |t        | |      k(  S )z
    Return True if ``fstruct1`` subsumes ``fstruct2``.  I.e., return
    true if unifying ``fstruct1`` with ``fstruct2`` would result in a
    feature structure equal to ``fstruct2.``

    :rtype: bool
    r   )rE  rF  s     r   r   r   
  s     uXx000r   c                 4    g fd}t        | |||       S )z
    Return a list of the feature paths of all features which are
    assigned incompatible values by ``fstruct1`` and ``fstruct2``.

    :rtype: list(tuple)
    c                 *    j                  |       | S r6   )r   )r[  rT  rS  conflict_lists      r   add_conflictzconflicts.<locals>.add_conflict  s    T"r   )r   r   r   )rE  rF  r   r  r  s       @r   	conflictsr    s%     M 
(H<u=r   c                 6    t        | d      xr t        | d      S )Nr   r   )r   rv  s    r   r   r   +  s    1n%<'!V*<<r   c                 \    t        | d      xr t        | d      xr t        | t               S )Nr   __len__)r   r   r   rv  s    r   r   r   /  s+    1j!Vga&;VJqRUDV@VVr   c                     t        | t              rt        S t        | t        t        f      rt        t        fS t	        d| j
                  j                  z        )NzBTo unify objects of type %s, you must specify fs_class explicitly.)r   r   r   r  r   r   r;   )objs    r   r  r  3  sN    #z"#d|$d|#%(]]%;%;<
 	
r   c                   "    e Zd ZdZd Zd Zd Zy)SubstituteBindingsSequencez
    A mixin class for sequence classes that distributes variables() and
    substitute_bindings() over the object's elements.
    c                 v    | D cg c]  }t        |t              s| c}t        d | D        g       z   S c c}w )Nc              3   n   K   | ]-  }t        |t              rt        |j                                / y wr6   )r   r	   r  rv   )r   elts     r   r   z7SubstituteBindingsSequence.variables.<locals>.<genexpr>L  s.      Cc#67 S]]_%s   35)r   r
   sum)r$   r  s     r   rv   z$SubstituteBindingsSequence.variablesJ  sD    #Atz#x'@tAC
 E
 
 	
As   66c           	      j    | j                  | D cg c]  }| j                  ||       c}      S c c}w r6   )r   subst)r$   rq   rw  s      r   ro   z.SubstituteBindingsSequence.substitute_bindingsT  s.    ~~E1tzz!X6EFFEs   0c                 h    t        |t              r|j                  |      S |j                  ||      S r6   )r   r	   ro   r   )r$   rw  rq   s      r   r  z SubstituteBindingsSequence.substW  s/    a,-((22<<1%%r   N)r;   r   r   r   rv   ro   r  r7   r   r   r  r  D  s    

G&r   r  c                       e Zd ZdZd Zy)FeatureValueTuplea  
    A base feature value that is a tuple of other base feature values.
    FeatureValueTuple implements ``SubstituteBindingsI``, so it any
    variable substitutions will be propagated to the elements
    contained by the set.  A ``FeatureValueTuple`` is immutable.
    c                 V    t        |       dk(  ryddj                  d | D              z  S )Nr   z()r  r   c              3   "   K   | ]  }|  	 y wr6   r7   r   bs     r   r   z-FeatureValueTuple.__repr__.<locals>.<genexpr>i  s     !7$QQC&$   )r<   r   r#   s    r   r   zFeatureValueTuple.__repr__f  s*    t9>		!7$!7777r   N)r;   r   r   r   r   r7   r   r   r  r  ^  s    8r   r  c                       e Zd ZdZd ZeZy)FeatureValueSeta	  
    A base feature value that is a set of other base feature values.
    FeatureValueSet implements ``SubstituteBindingsI``, so it any
    variable substitutions will be propagated to the elements
    contained by the set.  A ``FeatureValueSet`` is immutable.
    c                 h    t        |       dk(  ryddj                  t        d | D                    z  S )Nr   z{/}ry  r   c              3   "   K   | ]  }|  	 y wr6   r7   r  s     r   r   z+FeatureValueSet.__repr__.<locals>.<genexpr>y  s     (>AA3r  )r<   r   rP   r#   s    r   r   zFeatureValueSet.__repr__t  s1    t9> 		&(>(>">???r   N)r;   r   r   r   r   r   r7   r   r   r  r  l  s    @ Gr   r  c                       e Zd ZdZd Zd Zy)FeatureValueUnionzp
    A base feature value that represents the union of two or more
    ``FeatureValueSet`` or ``Variable``.
    c                     t        |t              }t        d |D              dk(  rt        |t              }t        |      S t	        |      dk(  rt        |      d   S t        j                  | |      S )Nc              3   <   K   | ]  }t        |t                y wr6   r   r
   r   rw  s     r   r   z,FeatureValueUnion.__new__.<locals>.<genexpr>       71z!X&   r   rN   )_flattenr  r  r  r<   r  	frozensetr   r   r   s     r   r   zFeatureValueUnion.__new__  sl    &"34 7771<fo6F"6** v;!<?"   f--r   c                 J    ddj                  t        d | D                    z  S )Nry  +c              3   "   K   | ]  }|  	 y wr6   r7   r  s     r   r   z-FeatureValueUnion.__repr__.<locals>.<genexpr>  s     '=11#r  )r   rP   r#   s    r   r   zFeatureValueUnion.__repr__  s#     '='=!=>>>r   Nr;   r   r   r   r   r   r7   r   r   r  r  ~  s    
."?r   r  c                       e Zd ZdZd Zd Zy)FeatureValueConcatzz
    A base feature value that represents the concatenation of two or
    more ``FeatureValueTuple`` or ``Variable``.
    c                     t        |t              }t        d |D              dk(  rt        |t              }t        |      S t	        |      dk(  rt        |      d   S t        j                  | |      S )Nc              3   <   K   | ]  }t        |t                y wr6   r  r  s     r   r   z-FeatureValueConcat.__new__.<locals>.<genexpr>  r  r  r   rN   )r  r  r  r  r<   r  r   r   r  s     r   r   zFeatureValueConcat.__new__  sk    &"45 7771<f&78F$V,, v;!<?" }}S&))r   c                 8    ddj                  d | D              z  S )Nr  r  c              3   "   K   | ]  }|  	 y wr6   r7   r  s     r   r   z.FeatureValueConcat.__repr__.<locals>.<genexpr>  s      6AA3r  )r   r#   s    r   r   zFeatureValueConcat.__repr__  s     6 6666r   Nr  r7   r   r   r  r    s    
*"7r   r  c                 v    g }| D ]1  }t        ||      r|j                  |       !|j                  |       3 |S )z}
    Helper function -- return a copy of list, with all elements of
    type ``cls`` spliced in rather than appended in.
    )r   r  r   )lstr   rN  r  s       r   r  r    s<    
 Fc3MM#MM#	 
 Mr   c                   r    e Zd ZdZddZed        Zed        Zed        Zd Z	d Z
d	 Zd
 Zd Zd Zd Zy)r   zi
    A feature identifier that's specialized to put additional
    constraints, default values, etc.
    Nc                     |dv sJ || _         || _        || _        | j                  dk(  rd| j                   f| _        y | j                  dk(  rd| j                   f| _        y d| j                   f| _        y )N)Nr   r   r   r   r   rN   r   )_name_default_display_sortkey)r$   r   r   r   s       r   r   zFeature.__init__  sl    3333
==H$,DM]]g%

ODM

ODMr   c                     | j                   S )zThe name of this feature.)r  r#   s    r   r   zFeature.name  s     zzr   c                     | j                   S )zDefault value for this feature.)r  r#   s    r   r   zFeature.default       }}r   c                     | j                   S )z1Custom display location: can be prefix, or slash.)r  r#   s    r   r   zFeature.display  r  r   c                      d| j                   z  S )Nz*%s*ru  r#   s    r   r   zFeature.__repr__  s    		!!r   c                     t        |t              ryt        |t              st        d| |       | j                  |j                  k  S )NT<)r   r   r   r   r  r3   s     r   r=   zFeature.__lt__  s8    eS!%)#Cu5}}u~~--r   c                 f    t        |       t        |      k(  xr | j                  |j                  k(  S r6   )typer  r3   s     r   r4   zFeature.__eq__  s'    DzT%[(FTZZ5;;-FFr   c                     | |k(   S r6   r7   r3   s     r   r8   zFeature.__ne__  r9   r   c                 ,    t        | j                        S r6   )rQ   r  r#   s    r   rC   zFeature.__hash__  s    DJJr   c                 (    |j                  |||      S r6   )
read_valuer$   spositionrm   parsers        r   r  zFeature.read_value  s      Hk::r   c                     ||k(  r|S t         S )zp
        If possible, return a single value..  If not, return
        the value ``UnificationFailure``.
        )r?  )r$   r[  rT  rq   s       r   rW  zFeature.unify_base_values	  s    
 E>L%%r   )NN)r;   r   r   r   r   propertyr   r   r   r   r=   r4   r8   rC   r  rW  r7   r   r   r   r     sl    
,      ".G! ;&r   r   c                       e Zd Zd Zy)SlashFeaturec                 (    |j                  |||      S r6   read_partialr  s        r   r  zSlashFeature.read_value  s    ""1h<<r   N)r;   r   r   r  r7   r   r   r  r    s    =r   r  c                   <    e Zd Z ej                  d      Zd Zd Zy)RangeFeaturez(-?\d+):(-?\d+)c                     | j                   j                  ||      }|st        d|      t        |j	                  d            t        |j	                  d            f|j                         fS )Nr  rN   r   )RANGE_REr   r   rR   groupend)r$   r  r  rm   r  ms         r   r  zRangeFeature.read_value  sV    MM8,Wh//AGGAJQWWQZ11557::r   c                     ||S ||S t        |d   |d         t        |d   |d         f}|d   |d   k  rt        S |S )Nr   rN   )r   minr?  )r$   r[  rT  rq   rngs        r   rW  zRangeFeature.unify_base_values"  sX    =L=L%(E!H%s58U1X'>>q6CF?%%
r   N)r;   r   r   r2  compiler  r  rW  r7   r   r   r  r    s    rzz,-H;r   r  r   )r   r   r  r   )r   c                   .    e Zd ZdZd Zd Zd Zd Zd Zy)rX  a  
    An abstract base class for base values that define a custom
    unification method.  The custom unification method of
    ``CustomFeatureValue`` will be used during unification if:

      - The ``CustomFeatureValue`` is unified with another base value.
      - The ``CustomFeatureValue`` is not the value of a customized
        ``Feature`` (which defines its own unification method).

    If two ``CustomFeatureValue`` objects are unified with one another
    during feature structure unification, then the unified base values
    they return *must* be equal; otherwise, an ``AssertionError`` will
    be raised.

    Subclasses must define ``unify()``, ``__eq__()`` and ``__lt__()``.
    Subclasses may also wish to define ``__hash__()``.
    c                     t        d      )z
        If this base value unifies with ``other``, then return the
        unified value.  Otherwise, return ``UnificationFailure``.
        zabstract base classr!   r3   s     r   r   zCustomFeatureValue.unifyJ  s    
 ""788r   c                     t         S r6   NotImplementedr3   s     r   r4   zCustomFeatureValue.__eq__Q      r   c                     | |k(   S r6   r7   r3   s     r   r8   zCustomFeatureValue.__ne__T  r9   r   c                     t         S r6   r  r3   s     r   r=   zCustomFeatureValue.__lt__W  r  r   c                 F    t        d| j                  j                  z        )Nz%s objects or unhashable)r   r   r;   r#   s    r   rC   zCustomFeatureValue.__hash__Z  s    2T^^5L5LLMMr   N)	r;   r   r   r   r   r4   r8   r=   rC   r7   r   r   rX  rX  6  s!    $9!Nr   rX  c                      e Zd ZeefeedfdZd8dZ e	j                  d      Z e	j                  d      Z e	j                  d      Z e	j                  d      Z e	j                  d      Z e	j                  d	      Z e	j                  d
      Z e	j                  d      Z e	j                  d      Z e	j                  dej(                  dej(                  dej(                  dej(                  d	      Zd9dZd8dZd Zd Zd Zd Zd Zd Zdefd e	j                  d      fd e	j                  d      fd e	j                  d       fd! e	j                  d"      fd# e	j                  d$      fd% e	j                  d&      fd' e	j                  d(      fd) e	j                  d*      fg	Zd+ Zd, Z d- Z!d. Z"dd/d0d1Z#d2 Z$d3 Z%d4 Z&d5 Z'd6 Z(d7 Z)y):r   Nc                    |D ci c]  }|j                   | c}| _        || _        || _        d | _        d | _        |D ]]  }|j                  dk(  r| j
                  rt        d      || _        |j                  dk(  s@| j                  rt        d      || _        _ |D cg c]  }|j                  | c}| _	        |
t               }|| _        y c c}w c c}w )Nr   z"Multiple features w/ display=slashr   z#Multiple features w/ display=prefix)r   	_features_fdict_class_flist_class_prefix_feature_slash_featurer   r   r   _features_with_defaultsr   _logic_parser)r$   r   fdict_classflist_classlogic_parserffeatures          r   r   zFeatStructReader.__init__d  s     .66X!&&!)X6''#"G')&&$%IJJ&-#(*''$%JKK'.$   $,(
#+w/JG8(
$ &=L)' 7(
s   C#C5Cc                     |j                         }| j                  |di |      \  }}|t        |      k7  r| j                  |d|       |S )aK  
        Convert a string representation of a feature structure (as
        displayed by repr) into a ``FeatStruct``.  This process
        imposes the following restrictions on the string
        representation:

        - Feature names cannot contain any of the following:
          whitespace, parentheses, quote marks, equals signs,
          dashes, commas, and square brackets.  Feature names may
          not begin with plus signs or minus signs.
        - Only the following basic feature value are supported:
          strings, integers, variables, None, and unquoted
          alphanumeric strings.
        - For reentrant values, the first mention must specify
          a reentrance identifier and a value; and any subsequent
          mentions must use arrows (``'->'``) to reference the
          reentrance identifier.
        r   zend of string)stripr  r<   _error)r$   r  r  r   r  s        r   r   zFeatStructReader.fromstring  sJ    & GGI++Aq"g>xs1vKK?H5r   z$\s*(?:\((\d+)\)\s*)?(\??[\w-]+)?(\[)z\s*]\s*/z&\s*([+-]?)([^\s\(\)<>"\'\-=\[\],]+)\s*z\s*->\s*z\s*\((\d+)\)\s*z\s*=\s*z\s*,\s*z$\s*(?:\((\d+)\)\s*)?(\??[\w-]+\s*)()r   z)|(z\s*(z\s*(=|->)|[+-]z|\]))c                     |i }	 | j                  ||||      S # t        $ r@}t        |j                        dk7  r  | j                  |g|j                    Y d}~yd}~ww xY w)a  
        Helper function that reads in a feature structure.

        :param s: The string to read.
        :param position: The position in the string to start parsing.
        :param reentrances: A dictionary from reentrance ids to values.
            Defaults to an empty dictionary.
        :return: A tuple (val, pos) of the feature structure created by
            parsing and the position where the parsed feature structure ends.
        :rtype: bool
        Nr   )_read_partialr   r<   r   r  )r$   r  r  rm   r  r   s         r   r  zFeatStructReader.read_partial  sh     K	$%%a;HH 	$166{aDKK#AFF##	$s    	A#6AA#c                 Z   |=| j                   j                  ||      r| j                         }n| j                         }| j                  j                  ||      }|s*| j
                  j                  ||      }|st        d|      |j                         }|j                  d      r5|j                  d      }||v rt        d|j                  d            |||<   t        |t              r%|j                          | j                  |||||      S |d d = | j                  |||||      S )Nopen bracket or identifierrN   znew identifier)r   r   r  r  _START_FSTRUCT_RE_BARE_PREFIX_REr   r  r  startr   r   r   _read_partial_featdict_read_partial_featlist)r$   r  r  rm   r  r   
identifiers          r   r  zFeatStructReader._read_partial  s   ?##))!X6++-++- &&,,Q9((..q(;E !=xHH99; ;;q>QJ[( !15;;q>BB&-K
#gx(MMO..q(E;PWXX
..q(E;PWXXr   c                 d   |j                  d      rt        d      |j                  d      st        d      |t        |      k  r^| j                  j	                  ||      }|||j                         fS | j                  j	                  ||      }|r|j                         }| j                  j	                  ||      }|st        d|      |j                  d      }||vrt        d|      |j                         }|j                  ||          n(| j                  d|||      \  }}|j                  |       | j                  j	                  ||      r#| j                  j	                  ||      }|t        d|      |j                         }|t        |      k  r^t        d	|      )
Nr   zopen bracketr   r  rN   bound identifierr   commaclose bracket)r  r   r<   _END_FSTRUCT_REr   r  _REENTRANCE_RE
_TARGET_REr   _read_value	_COMMA_RE)r$   r  r  r   rm   r  targetr   s           r   r   z'FeatStructReader._read_partial_featlist  s   ;;q>^,,{{1~^,, Q((..q(;E 		++ ''--a:E 99;--a:$\8<<Q,$%7BB 99;{623 #'"2"21a;"Oxu% ##))!X6 NN((H5E} (33yy{HA QF (33r   c                    |j                  d      rq| j                  t        d|j                  d            |j                  d      j	                         }|j                  d      rt        |      }||| j                  <   |j                  d      s"| j                  ||j                         ||      S |t        |      k  rvd x}}| j                  j                  ||      }|"| j                  ||j                         ||      S | j                  j                  ||      }|t        d|      |j                  d      }|j                         }|d   dk(  rC|d   dk(  r;| j                  j                  |d	d       }|t        d
|j                  d            ||v rt        d|j                  d            |j                  d	      dk(  rd}|j                  d	      dk(  rd}|| j                  j                  ||      }|p|j                         }| j                   j                  ||      }|st        d|      |j                  d	      }	|	|vrt        d|      |j                         }||	   }|R| j"                  j                  ||      }|r(|j                         }| j%                  ||||      \  }}nt        d|      |||<   | j                  j                  ||      r;| j&                  j                  ||      }|t        d|      |j                         }|t        |      k  rvt        d|      )Nr   r  r1  r   zfeature namer   *r   rN   zknown special featureznew namer  T-Fr  r  zequals signr  r  )r  r  r   r  r  
startswithr
   	_finalizer  r<   r  r   _FEATURE_NAME_REr  r   r  r  
_ASSIGN_REr	  r
  )
r$   r  r  r   rm   r  	prefixvalr   r   r  s
             r   r  z'FeatStructReader._read_partial_featdict	  s   ;;q>##+ !=u{{1~NNA,,.I##C($Y/	,5GD(() {{1~>>!UYY[+wGG QD5 ((..q(;E ~~ak7KK ))//8<E} ::;;q>Dyy{H Aw#~$r(c/~~))$q*5<$%<ekk!nMM w U[[^<< {{1~${{1~$ }++11!X>$$yy{H OO11!X>E (x@@"[[^F[0();XFF$yy{H'/E }--a:$yy{H&*&6&6tQ+&VOE8 %]H== "GDM ##))!X6 NN((H5E} (33yy{HG QL (33r   c                     | j                   j                  ||      }|r6| j                  }| j                  |||j	                         |      \  }}|||<   ||fS )zw
        Called when we see the close brace -- checks for a slash feature,
        and adds in default values.
        )	_SLASH_REr   r  r	  r  )r$   r  posrm   r  r   r   rw  s           r   r  zFeatStructReader._finalizek	  s]     $$Q,&&D%%dAuyy{KHFAsGDM
 |r   c                 p    t        |t              r|j                  ||||       S | j                  |||      S r6   )r   r   r  )r$   r   r  r  rm   s        r   r	  zFeatStructReader._read_value|	  s4    dG$??1hTBB??1h<<r   c                     | j                   D ]2  \  }}|j                  ||      }|st        | |      } |||||      c S  t        d|      )Nr   )VALUE_HANDLERSr   r   r   )r$   r  r  rm   handlerregexpr   handler_funcs           r   r  zFeatStructReader.read_value	  sU    #22OGVLLH-E&tW5#AxeDD	  3
 (++r   c                     |j                  d      }|t        |d         kD  r2|t        |j                  d            dz   z  }|t        |d         kD  r2d|d   z   dz   d|z  z   dz   d|z  z   }t        |      )	Nr   r   rN   z$Error parsing feature structure
    z
    r   z^ zExpected %s)splitr<   r   r   )r$   r  expectedr  r   estrs         r   r  zFeatStructReader._error	  s    U1X&EIIaL)A--H U1X& 4Ah Hn 	
 h&' 	 r   read_fstruct_valueread_var_valuez\?[a-zA-Z_][a-zA-Z0-9_]*read_str_valuez[uU]?[rR]?(['"])read_int_valuez-?\d+read_sym_valuez[a-zA-Z_][a-zA-Z0-9_]*read_app_valuez0<(app)\((\?[a-z][a-z]*)\s*,\s*(\?[a-z][a-z]*)\)>read_logic_valuez<(.*?)(?<!-)>read_set_value{read_tuple_valuez\(c                 (    | j                  |||      S r6   r  r$   r  r  rm   r   s        r   r!  z#FeatStructReader.read_fstruct_value	  s      Hk::r   c                     t        ||      S r6   )r   r,  s        r   r#  zFeatStructReader.read_str_value	  s    8$$r   c                 T    t        |j                               |j                         fS r6   )rR   r  r  r,  s        r   r$  zFeatStructReader.read_int_value	  s    5;;=!599;..r   c                 T    t        |j                               |j                         fS r6   )r
   r  r  r,  s        r   r"  zFeatStructReader.read_var_value	  s    &		33r   TF)NoneTrueFalsec                 ~    |j                         |j                         }}| j                  j                  ||      |fS r6   )r  r  _SYM_CONSTSr   )r$   r  r  rm   r   r   r  s          r   r%  zFeatStructReader.read_sym_value	  s5    ;;=%))+S##C-s22r   c                 ~    | j                   j                  d|j                  dd      z        |j                         fS )z%Mainly included for backwards compat.z%s(%s)r   r   )r  parser  r  r,  s        r   r&  zFeatStructReader.read_app_value	  s4    !!''5;;q!3D(DEuyy{RRr   c                    	 	 | j                   j                  |j                  d            }||j                         fS # t        $ r}t        |d }~ww xY w# t        $ r!}t	        d|j                  d            |d }~ww xY w)NrN   zlogic expression)r  r6  r  r   r   r  r  )r$   r  r  rm   r   exprr   s          r   r'  z!FeatStructReader.read_logic_value	  s    	H())//A? $$ . ( a'(  	H/Q@aG	Hs2   *? A 	AAAA 	B A<<Bc           	      @    | j                  ||||dt        t              S )Nr   )_read_seq_valuer  r  r,  s        r   r*  z!FeatStructReader.read_tuple_value	  s&    ##xeS2CEW
 	
r   c           	      @    | j                  ||||dt        t              S )N})r:  r  r  r,  s        r   r(  zFeatStructReader.read_set_value	  s%    ##xeS/CT
 	
r   c                    t        j                  |      }|j                         }t        j                  d|z        j	                  ||      }	|	r |       |	j                         fS g }
d}	 t        j                  d|z        j	                  ||      }	|	r2|r ||
      |	j                         fS  ||
      |	j                         fS | j                  |||      \  }}|
j                  |       t        j                  d|z        j	                  ||      }	|	st        d|z  |      |	j                  d      dk(  rd}|	j                         })	zN
        Helper function used by read_tuple_value and read_set_value.
        z
\s*/?\s*%sFTz\s*%sz\s*(,|\+|(?=%s))\s*z',' or '+' or '%s'rN   r  )	r2  escaper  r  r   r  r   r   r  )r$   r  r  rm   r   close_paren	seq_class
plus_classcpr  r   	seen_plusr   s                r   r:  z FeatStructReader._read_seq_value	  s3    YY{#99;JJ}r)*00H=;''	

8b=)//8<A%f-quuw66$V,aeeg55 !OOAxEMCMM# 

1B67==aJA !5!:HEEwwqzS  	uuwH' r   r6   )r   NN)*r;   r   r   SLASHTYPEr   r   r   r   r2  r  r  r  r  r  r  r  r  r
  r  patternr   r  r  r   r  r  r	  r  r  r  r!  r#  r$  r"  r4  r%  r&  r'  r*  r(  r:  r7   r   r   r   r   c  s    *82 #

#JK bjj,O

4 I!rzz"KLRZZ,N./JJ'J

:&I bjj!HIO bjj ##%%$$$$	
O$*Y<,4\[4z"=,: 
01	:2::&ABC	:2::&9:;	:2::h/0	:2::&?@ABJJNO	
 
ZRZZ(89:	:2::d+,	ZRZZ./N";%/4  >K3SH



"r   r   c                 V  
 d| z  j                  d      }d|z  j                  d      }t        |      t        |      kD  r-ddt        |d         dz
  z  z   dz   }||gt        |      z  z  }n,ddt        |d         dz
  z  z   dz   }||gt        |      z  z  }t        ||      D ]  \  }}t        |z   dz   |z           t        d	t        |d         z  z   dz   d	t        |d         z  z          t        |d         dz  d
z   
t        dj	                  
      z          t        dj	                  
      z          t        dj	                  
      z          t        dj	                  
      z          i }| j                  ||      }	|	t        dj	                  
      z          |	S t        dj                  
fdd|	z  j                  d      D                     |r?t        |j                               dkD  r#t        t        |      j	                  
             |	S )Nr   r   [r   r   r   ]z   r  r   z|               |z+-----UNIFY-----+rh  Vz(FAILED)c              3   F   K   | ]  }|j                        z     y wr6   )center)r   r   r   linelens     r   r   z&display_unification.<locals>.<genexpr>'
  s"     V:UQfqxx00:Us   !)	r  r<   zipri  rL  r   r   bound_variablesr   )fs1fs2r   	fs1_lines	fs2_lines	blanklinefs1_linefs2_linerq   rN  rM  s     `       @r   display_unificationrW  
  s   ""4(I""4(I
9~I&#Yq\!2Q!677#=	i[3y>11	#Yq\!2Q!677#=	i[3y>11	!)Y7(fx%'(23 8	&3Yq\**
*U
2S3y|;L5L
LM)A,!#a'G	&&--g6
67	&&--g6
67	&3::g&
&'	&3::g&
&'HYYsH%F~fz((112 M 	IIV4&=:O:OPT:UVV	
 H4467!;$x.''01Mr   c                    dd l }dd l}d}t        d       t        d       |j                  j	                          g d}t        t        |            D cg c]  }|t        ||         f }}d }	 d}t        |      |kD  rt        |j                  ||            }	n|}	t        d       t        d	        ||	       d d g}
d
D ]  \  }}|
|   t        d|t        |      fz  d       	 |j                  j	                         j                         }|dv r y |dv r|  } t        d| z         f|dv rt        |t        |	      z         |dv r	 ||       t        |      dz
  }||   d   |
|<   t                |
|    | r|
d   j                  |
d   d      }nt        |
d   |
d         }|?|D ]  \  }}t        |      t        |      k(  s n |j                  t        |      |f       t        d       |j                  j	                         j                         }|dv ry c c}w #  t        d       Y xxY w)Nr   z
    1-%d: Select the corresponding feature structure
    q: Quit
    t: Turn tracing on or off
    l: List all feature structures
    ?: Help
    a  
    This demo will repeatedly present you with a list of feature
    structures, and ask you to choose two for unification.  Whenever a
    new feature structure is generated, it is added to the list of
    choices that you can pick from.  However, since this can be a
    large number of feature structures, the demo will only print out a
    random subset for you to choose between at a given time.  If you
    want to see the complete lists, type "l".  For a list of valid
    commands, type "?".
    zPress "Enter" to continue...z [agr=[number=sing, gender=masc]]z[agr=[gender=masc, person=3]]z[agr=[gender=fem, person=3]]z[subj=[agr=(1)[]], agr->(1)]z[obj=?x]z	[subj=?x]z[/=None]z[/=NP]z[cat=NP]z[cat=VP]z[cat=PP]z/[subj=[agr=[gender=?y]], obj=[agr=[gender=?y]]]z[gender=masc, agr=?C]z%[gender=?S, agr=[gender=?S,person=3]]c                     | D ]Q  \  }}t                d|z  j                  d      }t        d|dz   |d   fz         |dd  D ]  }t        d|z           S t                y )Nr   r   z%3d: %srN   r   z     )ri  r  )fstructsir  r   r   s        r   list_fstructsz'interactive_demo.<locals>.list_fstructs^
  sf    "JAwGG^**40E)q1ueAh//0ab	gn% "	 # 	r      K___________________________________________________________________________z'Choose two feature structures to unify:))Firstr   )SecondrN   z%%s feature structure (1-%d,q,t,l,?): r   )r  )qQxX)tTz   Trace = %s)hHr1  )r   LrN   zBad sentence number)r   z3
Type "Enter" to continue unifying; or "q" to quit.)randomsysri  stdinreadliner  r<   r   rP   sampler  rR   r   rW  r   r   )r   rk  rl  HELPfstruct_stringsr\  all_fstructsr]  MAX_CHOICESr[  selectednthinputnumrN  r  s                   r   interactive_demorx  .
  sz   D 
		 

()IIO$ 6;3;O5P5PJq)*+5P   |{*fmmL+FGH#Hh78h$<3FC1+%?L 123 II..0668E 44
*$)	o56 /dS]23 
*%l3 e*q.C".s"3A"6HQKG1 1+% 4< a[&&x{!&<F(!hqkBF*
7<4=0 + ##S%6$?@DE		""$**,((u j/0s*   H-,,H2H20H2H2#H22Ic                     g d}|D cg c]  }t        |       }}|D ]'  }|D ]   }t        d|d|dt        ||             " ) yc c}w )z
    Just for testing
    rY  z
*******************
fs1 is:
z


fs2 is:
z

result is:
N)r   ri  r   )r   rq  fssrr  rP  rQ  s         r   demor{  
  sY    O  0??JsOL? CU3_.    @s   A
__main__)r   r   r   r   r   r  r   r  r  rD  rE  r   )r   )r   )Nr7   Nr   )NFNTr   )r   )rf  r   )Jr   r^   r2  	functoolsr   nltk.internalsr   r   nltk.sem.logicr   r   r   r	   r
   r   r   r   r   r   r   r  r   ro   r  rs   r"  ru   r(  rx   r-  r/  r}   r6  r9  r?  r   	Exceptionr>  r=  rR  rA  r@  rB  r<  rQ  rZ  rC  rD  rj  r   r  r   r   r  r  r   r  r  r  r  r  r  r   r  r  rD  rE  rX  r   rW  rx  r{  r;   __all__r7   r   r   <module>r     sB  Pd  	 $ <  G$$ G$ G$V :;0{z4 {F
W<z4 W<~$@**E&7, ?H=@B"F24 4
 )* : 
	wt2y 2
d6Nvr@4F<A<F 1,=W	
"&!4 &482E 80) $?2I ?<73U 78& E& E& E&P=7 =
7 ( 	WeW=vx( $N $N $NXa aRDsl$N zFr   