U
    d                  	   @   sh   d dl Z d dlmZmZmZmZ G dd dZedkrdedZe	ej
ddgd	d
gddddgg d dS )    N)MatchOptionalSequenceMappingc                   @   s   e Zd ZU dZeddZeeejZe	e
d< e	e
d< ee	d dddZde	e	d
dddZdeee	ef  ee	dddZd
S )CodeTemplatez5(^[^\n\S]*[^\n\S]?)?\$([^\d\W]\w*|\{,?[^\d\W]\w*\,?})z\wz[a-zA-Z0-9_]patternfilename)r   returnc              
   C   s0   t | d}t| | W  5 Q R  S Q R X d S )Nr)openr   read)r   f r   :/tmp/pip-unpacked-wheel-ua33x9lu/torchgen/code_template.py	from_file   s    zCodeTemplate.from_file N)r   r   r	   c                 C   s   || _ || _d S N)r   r   )selfr   r   r   r   r   __init__$   s    zCodeTemplate.__init__)envkwargsr	   c                    sb    d kri  t td fddt tt t dddtt  t dfdd	}| j|| jS )
N)vr	   c                    s$    d k	st | kr|  S  |  S r   )AssertionError)r   )r   r   r   r   lookup.   s    z'CodeTemplate.substitute.<locals>.lookup)indentr   r	   c                    s   d  fdd|D  S )Nr   c                    s*   g | ]"}t | D ]} | d  qqS )
)str
splitlines).0elr   r   r   
<listcomp>4   s       zACodeTemplate.substitute.<locals>.indent_lines.<locals>.<listcomp>)joinrstrip)r   r   r   r!   r   indent_lines2   s    z-CodeTemplate.substitute.<locals>.indent_lines)matchr	   c                    s   |  d}|  d}d}d}|d dkrl|dd }|d dkrPd}|dd  }|d dkrld}|d d }|}|d k	rt|ts|g} ||S t|trdd	d
 |D }t|dkr|S || | S t|S d S )N      r   r   {,z, c                 S   s   g | ]}t |qS r   )r   )r   xr   r   r   r"   J   s     z<CodeTemplate.substitute.<locals>.replace.<locals>.<listcomp>)group
isinstancelistr#   lenr   )r&   r   keyZcomma_beforeZcomma_afterr   Zmiddle)r%   r   r   r   replace7   s.    




z(CodeTemplate.substitute.<locals>.replace)r   objectr   r   substitutionsubr   )r   r   r   r2   r   )r   r%   r   r   r   
substitute(   s    zCodeTemplate.substitute)r   )N)__name__
__module____qualname__Zsubstitution_strr2   recompile	MULTILINEr4   r   __annotations__staticmethodr   r   r   r   r3   r6   r   r   r   r   r      s   
  r   __main__z    int foo($args) {

        $bar
            $bar
        $a+$b
    }
    int commatest(int a${,stuff})
    int notest(int a${,empty,})
    hi   what         z	things...Zothers)argsbarabstuffempty)r:   typingr   r   r   r   r   r7   cprintr6   r   r   r   r   <module>   s    F