o
    ,wi4                  	   @   s  d Z ddlZddlZddlZddlZddlmZmZmZm	Z	m
Z
mZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ejd	d
G dd dZd2dedefddZdejdefddZdededefddZejd	d
G dd dZejd	d
G dd dZdejdejde
ee  fddZdd Z		d3dejd edejfd!d"Z d	d#d$dejd%ededefd&d'Z!d#d(dededefd)d*Z"dededee fd+d,Z#dejd-e	ej$ dedefd.d/Z%dejdeeef fd0d1Z&dS )4z8Functions to output representations of `fdl.Buildable`s.    N)AnyDictIteratorListOptionalType)config)daglish)history)tagging)formatting_utilitiesT)frozenc                   @   s.   e Zd ZU dZdZejed< defddZ	dS )_UnsetValuez*A wrapper class indicating an unset value.)	parameterr   returnc                 C   s0   | j j| j ju r
dS t| j jdd}d| dS )N	<[unset]>Fraw_value_reprz<[unset; default: z]>)r   defaultempty_format_value)selfdefault_value r   Q/home/ubuntu/sommelier/.venv/lib/python3.10/site-packages/fiddle/_src/printing.py__repr__%   s   z_UnsetValue.__repr__N)
__name__
__module____qualname____doc__	__slots__inspect	Parameter__annotations__strr   r   r   r   r   r      s
   
 
r   valuer   c                 C   s6   |pt jt| }t| tjp|| ot|	| S N)
r	   MemoizedTraversalbegin_has_nested_builder
isinstancer   	Buildableis_traversableanyyield_map_child_values)r%   stater   r   r   r)   .   s   r)   pathc                 C   s.   t | }| rt| d t jr|dd S |S )a  Formats path in a way customized to this file.

  In the future, we may wish to consider a format that is readable for printing
  more arbitrary collections.

  Args:
    path: A path, which typically starts with an attribute.

  Returns:
    String representation of the path.
  r      N)r	   path_strr*   Attr)r0   r2   r   r   r   	_path_str5   s   
r4   r   c                C   s(   |rt | S t| trt | S t| S r&   )reprr*   r$   r   pretty_print)r%   r   r   r   r   r   F   s
   

r   c                   @   s(   e Zd ZU dZdZejed< dd ZdS )_TaggedValueWrapperz?Customizes representation for TaggedValues in flattened output.)wrappedr8   c                 C   sJ   | j jtju r
d}nt| j j}dtdd | j jD }| d| S )Nr    c                 s   s    | ]}t |V  qd S r&   )r$   ).0tr   r   r   	<genexpr>[   s    z/_TaggedValueWrapper.__repr__.<locals>.<genexpr>)r8   r%   r   NO_VALUEr5   joinsortedtags)r   
value_reprtag_strr   r   r   r   V   s
   z_TaggedValueWrapper.__repr__N)	r   r   r   r   r    r   TaggedValueClsr#   r   r   r   r   r   r7   P   s
   
 
r7   c                   @   s4   e Zd ZU dZejed< eee	  ed< e	ed< dS )_LeafSettingz(Represents a leaf configuration setting.r0   
annotationr%   N)
r   r   r   r   r	   Pathr#   r   r   r   r   r   r   r   rD   _   s
   
 
rD   cfgc                 C   s   |r
t |d tjsdS | }|dd D ]}||}qt |tjraz|jj|d j }W n( t	yU   |jj
 D ]}|j|jkrQ|j|ju rJdn|j   Y S q:Y dS w |j|ju r^dS |jS dS )z8Gets the type annotation associated with a Daglish path.N)r*   r	   r3   followr   r+   __signature_info__
parametersnameKeyErrorvalueskindVAR_KEYWORDrE   r   )rG   r0   r%   path_elementparamr   r   r   _get_annotationg   s"   rS   c                 C   sN   |r%|d }t |tjr#t| |dd }t |tjr#|j|jS dS dS )zEReturns the tags for a given Daglish path, or None if there are none.rH   N)	r*   r	   r3   follow_pathr   r+   __argument_tags__getrL   )rG   r0   childparentr   r   r   	_get_tags{   s   rY   insert_unset_sentinelsc                 C   s   t  | } t| j}i }| jj D ]"\}}|j|j|jhv r q||v r,|	|||< q|r4t
|||< q|| t| d| | S )a  Returns a copy of a Buildable with normalized arguments.

  This normalizes arguments by re-creating the __arguments__ dictionary in the
  order of the configured function or class' signature. It also inserts "unset"
  sentinels for values in the signature that don't have a value set.

  Args:
    value: Buildable to copy and normalize.
    insert_unset_sentinels: If true, insert unset sentinels to arguments as the
      default values.

  Returns:
    Copy of `value` with arguments normalized.
  __arguments__)copydictr[   rJ   rK   itemsrO   rP   VAR_POSITIONALpopr   updateobject__setattr__)r%   rZ   old_argumentsnew_arguments
param_namerR   r   r   r   _rearrange_buildable_args   s   


rg   F)include_typesr   rh   c                   s\   ddt t f fddtddi }ttd|dtffd	d
}dt| S )ac  Returns a string of cfg's paths and values, one pair per line.

  Some automated tools (e.g. grep, sort, diff, ...) handle data line-by-line.
  This output format contains the full path to a value and a string
  representation of said value on a single line.

  Args:
    cfg: A buildable to generate a string representation for.
    include_types: If true, include type annotations (where available) in the
      string representation of each leaf value.
    raw_value_repr: If true, use `repr` on values, otherwise, a custom
      pretty-printed format is used.
  Returns: a string representation of `cfg`.
  Nr   c                 3   s    |p	t j| }t |j}|rtj|| d} t| tj	r#t
| } t| tjr=t| } t |j}t|j|| V  d S t| sQt |j}t|j|| V  d S || sXJ || D ]}|E d H  q]d S )N)r@   r   )r	   BasicTraversalr(   rY   current_pathr   TaggedValuer*   r   r+   rg   rC   r7   rS   rD   r)   r,   r.   )r%   r/   r@   rE   
sub_result)rG   generater   r   rm      s$   z"as_str_flattened.<locals>.generate r   GenericAliaslinec                    sp   d}r%| j d ur%t| j  }t| j tr|sd| j j }nd| j  }t| jd}t| j | d| S )Nrn   z: r    = )rE   r*   typer   r   r%   r4   r0   )rp   type_annotationis_parameterized_genericr%   )generic_aliasrh   r   r   r   format_line   s   z%as_str_flattened.<locals>.format_line
r&   )r   rD   rr   getattrtypesr>   map)rG   rh   r   
dummy_typerv   r   )rG   rm   ru   rh   r   r   as_str_flattened   s
   r|   r   c                C   s   d t| |dS )an  Returns a string representing the history of cfg's leaf params.

  Because Buildable's are designed to be mutated, tracking down when and where
  a particular parameter's value is changed can be difficult. This function
  returns a string representation of each parameter and (in
  reverse-chronological order) its current and past values.

  This representation elides the "DAG"-construction aspects of constructing the
  `cfg`, and instead only prints the history of the "outer-most" parameters
  (ones that don't contain a reference to another Buildable).

  Args:
    cfg: A buildable, or collection containing buildables, to generate a history
      for. For non-Buildable collections, either (a) the entire collection will
      be printed as a history element or (b) only nested Buildable elements will
      be printed, since we can't store assignment history for normal Python
      collections like lists/dicts.
    raw_value_repr: If true, use `repr` when string-ifying values, otherwise use
      a customized pretty-printing routine.

  Returns:
    A string representation of `cfg`'s history, organized by param name.
  rw   r   )r>   "_make_per_leaf_histories_recursiverG   r   r   r   r   history_per_leaf_parameter   s   
r   c                    s"   ddt t f fdd| S )zFRecursively traverses `cfg` and generates per-param history summaries.Nr   c                 3   s   |p	t j| }t| tjrm| j D ],\}}t| |}t	|r/|
|t |E d H  qg |jt |R }t|| V  qtt| jj t| j  }|D ]}g |jt |R }t| dV  qUd S || r|| D ]}|E d H  qwd S t|j d|  V  d S )Nz = <[unset]>rq   )r	   ri   r(   r*   r   r+   __argument_history__r^   rx   r)   callr3   rj   _make_per_leaf_history_textr?   setrJ   rK   keysr4   r,   r.   )r%   r/   rL   param_history	sub_valuer0   unset_fieldsrl   r   traverser   r   r     s.   

z4_make_per_leaf_histories_recursive.<locals>.traverser&   )r   r$   r~   r   r   r   r}     s   r}   r   c                    s   |sJ ddt jdtffdd dd |D }t|dkr8 fd	dt|d
d D }d|}d| }nd}t|d jd}| d|d j }t	|  d| | S )af  Returns a string representing a parameter's history.

  Args:
    path: The path to the parameter.
    param_history: The parameter's history.
    raw_value_repr: If True, use `repr` unmodified, otherwise, use a custom
      pretty-printing routine.

  Returns:
    A string representation of the parameter's history that can be displayed to
    the user.
  z$param_history should never be empty.entryr   c                    s    t | j d}d| d| j S )Nr   z  - previously:  @ )r   	new_valuelocation)r   r%   r   r   r   make_previous_text<  s   z7_make_per_leaf_history_text.<locals>.make_previous_textc                 S   s   g | ]}|j tjjkr|qS r   )rO   r
   
ChangeKind	NEW_VALUEr:   r   r   r   r   
<listcomp>A  s
    z/_make_per_leaf_history_text.<locals>.<listcomp>r1   c                    s   g | ]} |qS r   r   r   )r   r   r   r   F  s    NrH   rw   rn   r   r   rq   )
r
   HistoryEntryr$   lenreversedr>   r   r   r   r4   )r0   r   r   value_historyvalue_updatespastcurrent_valuecurrentr   )r   r   r   r   +  s"   



r   c                    s>   ddt t f fdd i } | D ]
}|j|t|j< q|S )a  Returns a flattened dict of cfg's paths (dot syntax) and values.

  Default values and tags won't be included in the flattened dict.

  Args:
    cfg: A buildable to generate a flattened dict representation for.

  Returns: A flattened Dict representation of `cfg`.
  Nr   c                 3   st    |p	t j | }t| tjrt| dd} t| s$t|j	d | V  d S |
| s+J || D ]}|E d H  q0d S )NF)rZ   )r	   ri   r(   r*   r   r+   rg   r)   rD   rj   r,   r.   )r%   r/   rl   dict_generater   r   r   ^  s   z(as_dict_flattened.<locals>.dict_generater&   )r   rD   r%   r4   r0   )rG   	args_dictleafr   r   r   as_dict_flattenedS  s
   r   r&   )T)'r   r\   dataclassesr!   ry   typingr   r   r   r   r   r   fiddle._srcr   r	   r
   r   fiddle._src.codegenr   	dataclassr   boolr)   rF   r$   r4   r   r7   rD   r+   rS   rY   rg   r|   r   r}   r   r   r   r   r   r   r   <module>   s    






$
C


$
 (