a
    S/b1                     @   s   d dl mZ d dlmZmZ dd Zdd ZG dd dZG d	d
 d
ZedZ	edZ
G dd deZG dd dZG dd dZdd Zdd ZeedZdd Zdd ZdS )    )deque)istasksubsc                 C   s&   t | r| d S t| trtS | S dS )z#Return the top level node of a taskr   Nr   
isinstancelisttask r
   +lib/python3.9/site-packages/dask/rewrite.pyhead   s
    
r   c                 C   s*   t | r| dd S t| tr"| S dS dS )z&Get the arguments for the current task   Nr
   r   r   r
   r
   r   args   s
    
r   c                   @   sF   e Zd ZdZdddZdd Zdd Zd	d
 Zedd Z	dd Z
dS )	Traversera  Traverser interface for tasks.

    Class for storing the state while performing a preorder-traversal of a
    task.

    Parameters
    ----------
    term : task
        The task to be traversed

    Attributes
    ----------
    term
        The current element in the traversal
    current
        The head of the current element in the traversal. This is simply `head`
        applied to the attribute `term`.
    Nc                 C   s"   || _ |sttg| _n|| _d S N)termr   END_stack)selfr   stackr
   r
   r   __init__0   s    zTraverser.__init__c                 c   s    | j tur| j V  |   q d S r   )currentr   nextr   r
   r
   r   __iter__7   s    
zTraverser.__iter__c                 C   s   t | jt| jS )zCopy the traverser in its current state.

        This allows the traversal to be pushed onto a stack, for easy
        backtracking.)r   r   r   r   r   r
   r
   r   copy<   s    zTraverser.copyc                 C   sB   t | j}|s| j | _n"|d | _| jt|dd  dS )z3Proceed to the next term in the preorder traversal.r   r   N)r   r   r   popextendreversed)r   Zsubtermsr
   r
   r   r   D   s
    

zTraverser.nextc                 C   s
   t | jS r   )r   r   r   r
   r
   r   r   O   s    zTraverser.currentc                 C   s   | j  | _dS )z<Skip over all subterms of the current level in the traversalN)r   r   r   r   r
   r
   r   skipS   s    zTraverser.skip)N)__name__
__module____qualname____doc__r   r   r   r   propertyr   r   r
   r
   r
   r   r      s   

r   c                   @   s    e Zd ZdZdd Zdd ZdS )Tokenz[A token object.

    Used to express certain objects in the traversal of a task or pattern.c                 C   s
   || _ d S r   name)r   r'   r
   r
   r   r   ]   s    zToken.__init__c                 C   s   | j S r   r&   r   r
   r
   r   __repr__`   s    zToken.__repr__N)r    r!   r"   r#   r   r(   r
   r
   r
   r   r%   X   s   r%   ?endc                   @   s6   e Zd ZdZdZd
ddZedd Zedd	 ZdS )NodezA Discrimination Net node.r
   Nc                 C   s(   |r|ni }|r|ng }t | ||fS r   )tuple__new__)clsedgespatternsr
   r
   r   r-   p   s    zNode.__new__c                 C   s   | d S )z@A dictionary, where the keys are edges, and the values are nodesr   r
   r   r
   r
   r   r/   u   s    z
Node.edgesc                 C   s   | d S )z8A list of all patterns that currently match at this noder   r
   r   r
   r
   r   r0   z   s    zNode.patterns)NN)	r    r!   r"   r#   	__slots__r-   r$   r/   r0   r
   r
   r
   r   r+   k   s   

r+   c                   @   s2   e Zd ZdZdddZdd Zdd Zd	d
 ZdS )RewriteRulea  A rewrite rule.

    Expresses `lhs` -> `rhs`, for variables `vars`.

    Parameters
    ----------
    lhs : task
        The left-hand-side of the rewrite rule.
    rhs : task or function
        The right-hand-side of the rewrite rule. If it's a task, variables in
        `rhs` will be replaced by terms in the subject that match the variables
        in `lhs`. If it's a function, the function will be called with a dict
        of such matches.
    vars: tuple, optional
        Tuple of variables found in the lhs. Variables can be represented as
        any hashable object; a good convention is to use strings. If there are
        no variables, this can be omitted.

    Examples
    --------
    Here's a `RewriteRule` to replace all nested calls to `list`, so that
    `(list, (list, 'x'))` is replaced with `(list, 'x')`, where `'x'` is a
    variable.

    >>> import dask.rewrite as dr
    >>> lhs = (list, (list, 'x'))
    >>> rhs = (list, 'x')
    >>> variables = ('x',)
    >>> rule = dr.RewriteRule(lhs, rhs, variables)

    Here's a more complicated rule that uses a callable right-hand-side. A
    callable `rhs` takes in a dictionary mapping variables to their matching
    values. This rule replaces all occurrences of `(list, 'x')` with `'x'` if
    `'x'` is a list itself.

    >>> lhs = (list, 'x')
    >>> def repl_list(sd):
    ...     x = sd['x']
    ...     if isinstance(x, list):
    ...         return x
    ...     else:
    ...         return (list, x)
    >>> rule = dr.RewriteRule(lhs, repl_list, variables)
    r
   c                    sf   t  tstd|| _t|r(|| _n| j| _|| _ fddt|D | _	tt
t| j	| _d S )Nz!vars must be a tuple of variablesc                    s   g | ]}| v r|qS r
   r
   .0tvarsr
   r   
<listcomp>       z(RewriteRule.__init__.<locals>.<listcomp>)r   r,   	TypeErrorlhscallabler   _applyrhsr   _varlistsortedsetr7   )r   r;   r>   r7   r
   r6   r   r      s    
zRewriteRule.__init__c                 C   s(   | j }| D ]\}}t|||}q|S r   )r>   itemsr   )r   Zsub_dictr   keyvalr
   r
   r   r=      s    zRewriteRule._applyc                 C   s   d| j  d| j d| j dS )NzRewriteRule(z, ))r;   r>   r7   r   r
   r
   r   __str__   s    zRewriteRule.__str__c                 C   s   t | S r   )strr   r
   r
   r   r(      s    zRewriteRule.__repr__N)r
   )r    r!   r"   r#   r   r=   rF   r(   r
   r
   r
   r   r2      s
   -
r2   c                   @   s:   e Zd ZdZdd Zdd Zdd Zdd	 ZdddZdS )RuleSeta%  A set of rewrite rules.

    Forms a structure for fast rewriting over a set of rewrite rules. This
    allows for syntactic matching of terms to patterns for many patterns at
    the same time.

    Examples
    --------

    >>> import dask.rewrite as dr
    >>> def f(*args): pass
    >>> def g(*args): pass
    >>> def h(*args): pass
    >>> from operator import add

    >>> rs = dr.RuleSet(
    ...         dr.RewriteRule((add, 'x', 0), 'x', ('x',)),
    ...         dr.RewriteRule((f, (g, 'x'), 'y'),
    ...                        (h, 'x', 'y'),
    ...                        ('x', 'y')))

    >>> rs.rewrite((add, 2, 0))
    2

    >>> rs.rewrite((f, (g, 'a', 3)))    # doctest: +ELLIPSIS
    (<function h at ...>, 'a', 3)

    >>> dsk = {'a': (add, 2, 0),
    ...        'b': (f, (g, 'a', 3))}

    >>> from toolz import valmap
    >>> valmap(rs.rewrite, dsk)         # doctest: +ELLIPSIS
    {'a': 2, 'b': (<function h at ...>, 'a', 3)}

    Attributes
    ----------
    rules : list
        A list of `RewriteRule`s included in the `RuleSet`.
    c                 G   s&   t  | _g | _|D ]}| | qdS )zCreate a `RuleSet` for a number of rules

        Parameters
        ----------
        rules
            One or more instances of RewriteRule
        N)r+   _netrulesadd)r   rJ   pr
   r
   r   r      s    zRuleSet.__init__c                 C   s   t |tstd|j}| j}t| j}t|jD ]@}|}||v rFt	}||j
v r\|j
| }q2t |j
|< |j
| }q2|j
| j| | j| dS )zeAdd a rule to the RuleSet.

        Parameters
        ----------
        rule : RewriteRule
        z$rule must be instance of RewriteRuleN)r   r2   r:   r7   rI   lenrJ   r   r;   VARr/   r+   r0   append)r   ruler7   Z	curr_nodeZindr5   Z	prev_noder
   r
   r   rK      s    


zRuleSet.addc                 c   sR   t |}t|| jD ]8\}}|D ]*}| j| }t||}|dur ||fV  q qdS )al  A generator that lazily finds matchings for term from the RuleSet.

        Parameters
        ----------
        term : task

        Yields
        ------
        Tuples of `(rule, subs)`, where `rule` is the rewrite rule being
        matched, and `subs` is a dictionary mapping the variables in the lhs
        of the rule to their matching values in the term.N)r   _matchrI   rJ   _process_match)r   r   SmsymsirP   r   r
   r
   r   iter_matches  s    

zRuleSet.iter_matchesc                 C   s&   |  |D ]\}}||} q"q
|S )z7Apply the rewrite rules in RuleSet to top level of term)rW   r   )r   r   rP   sdr
   r
   r   _rewrite.  s    
zRuleSet._rewrite	bottom_upc                 C   s   t | | |S )ae  Apply the `RuleSet` to `task`.

        This applies the most specific matching rule in the RuleSet to the
        task, using the provided strategy.

        Parameters
        ----------
        term: a task
            The task to be rewritten
        strategy: str, optional
            The rewriting strategy to use. Options are "bottom_up" (default),
            or "top_level".

        Examples
        --------
        Suppose there was a function `add` that returned the sum of 2 numbers,
        and another function `double` that returned twice its input:

        >>> add = lambda x, y: x + y
        >>> double = lambda x: 2*x

        Now suppose `double` was *significantly* faster than `add`, so
        you'd like to replace all expressions `(add, x, x)` with `(double,
        x)`, where `x` is a variable. This can be expressed as a rewrite rule:

        >>> rule = RewriteRule((add, 'x', 'x'), (double, 'x'), ('x',))
        >>> rs = RuleSet(rule)

        This can then be applied to terms to perform the rewriting:

        >>> term = (add, (add, 2, 2), (add, 2, 2))
        >>> rs.rewrite(term)  # doctest: +SKIP
        (double, (double, 2))

        If we only wanted to apply this to the top level of the term, the
        `strategy` kwarg can be set to "top_level".

        >>> rs.rewrite(term)  # doctest: +SKIP
        (double, (add, 2, 2))
        )
strategies)r   r	   Zstrategyr
   r
   r   rewrite9  s    )zRuleSet.rewriteN)rZ   )	r    r!   r"   r#   r   rK   rW   rY   r\   r
   r
   r
   r   rH      s   (rH   c                 C   s
   |  |S r   )rY   netr   r
   r
   r   
_top_levele  s    r_   c                    sX   t |r.t|ft fddt|D  }n t|trN fddt|D } |S )Nc                 3   s   | ]}t  |V  qd S r   
_bottom_upr3   r^   r
   r   	<genexpr>k  r9   z_bottom_up.<locals>.<genexpr>c                    s   g | ]}t  |qS r
   r`   r3   rb   r
   r   r8   m  r9   z_bottom_up.<locals>.<listcomp>)r   r   r,   r   r   r   rY   r]   r
   rb   r   ra   i  s
    &
ra   )Z	top_levelrZ   c                 c   s   t  }d}d}| jtu r$|j|fV  z@|j| jd}|rb|sb||  ||f |}|   W qW n t	yv   Y n0 |jt
d}|rd}|| jf }|   |}qz| \} }}d}W q ty   Y dS 0 qdS )z;Structural matching of term S to discrimination net node N.Fr
   NT)r   r   r   r0   r/   getrO   r   r   r:   rN   r   r   r   	Exception)rS   Nr   Zrestore_state_flagmatchesnr
   r
   r   rQ   t  s4    
rQ   c                 C   s\   i }| j }t|t|ks"tdt||D ]*\}}||v rN|| |krN dS |||< q,|S )a  Process a match to determine if it is correct, and to find the correct
    substitution that will convert the term into the pattern.

    Parameters
    ----------
    rule : RewriteRule
    syms : iterable
        Iterable of subterms that match a corresponding variable.

    Returns
    -------
    A dictionary of {vars : subterms} describing the substitution to make the
    pattern equivalent with the term. Returns `None` if the match is
    invalid.z/length of varlist doesn't match length of syms.N)r?   rM   RuntimeErrorzip)rP   rU   r   Zvarlistvsr
   r
   r   rR     s    
rR   N)collectionsr   Z	dask.corer   r   r   r   r   r%   rN   r   r,   r+   r2   rH   r_   ra   r[   rQ   rR   r
   r
   r
   r   <module>   s    <H 
&