U
    øÕ/e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
   ú0/tmp/pip-unpacked-wheel-dbjnr7gq/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k	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 )z…Copy 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 | ]}|ˆ kr|‘qS r
   r
   ©Ú.0Út©Úvarsr
   r   Ú
<listcomp>·   s      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<   rE   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 )z—Create a `RuleSet` for a number of rules

        Parameters
        ----------
        rules
            One or more instances of RewriteRule
        N)r+   Ú_netÚrulesÚadd)r   rI   Úpr
   r
   r   r   ñ   s    zRuleSet.__init__c                 C   s–   t |tƒstdƒ‚|j}| j}t| jƒ}t|jƒD ]@}|}||krFt	}||j
k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   r9   r7   rH   ÚlenrI   r   r:   ÚVARr/   r+   r0   Úappend)r   Úruler7   Z	curr_nodeÚindr5   Z	prev_noder
   r
   r   rJ   þ   s    


zRuleSet.addc                 c   sR   t |ƒ}t|| jƒD ]8\}}|D ]*}| j| }t||ƒ}|dk	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   Ú_matchrH   rI   Ú_process_match)r   r   ÚSÚmÚsymsÚirO   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   rO   Ú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   rJ   rW   rY   r\   r
   r
   r
   r   rG   È   s   (rG   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  s     z_bottom_up.<locals>.<genexpr>c                    s   g | ]}t ˆ |ƒ‘qS r
   r`   r3   rb   r
   r   r8   m  s     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kr$|j|fV  z@|j | jd¡}|rb|sb| |  ¡ ||f¡ |}|  ¡  W qW n t	k
rx   Y nX |j t
d¡}|rªd}|| jf }|  ¡  |}qz| ¡ \} }}d}W q tk
rÖ   Y dS X qdS )z;Structural matching of term S to discrimination net node N.Fr
   NT)r   r   r   r0   r/   ÚgetrN   r   r   r9   rM   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 ]*\}}||k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>   rL   ÚRuntimeErrorÚzip)rO   rU   r   ZvarlistÚvÚsr
   r
   r   rR   š  s    
rR   N)Úcollectionsr   Z	dask.corer   r   r   r   r   r%   rM   r   r,   r+   r2   rG   r_   ra   r[   rQ   rR   r
   r
   r
   r   Ú<module>   s    <H 
&