o
    qoi(                  
   @   sZ  d Z ddlZddlZddlZddl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 ddl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 G d	d
 d
ejZdedede	fddZejddG dd dZdedejfddZdedede	fddZdededeej dedef
ddZ d ej!d!eddfd"d#Z"G d$d% d%Z#dS )&z;Utilities to use command line flags with Fiddle Buildables.    N)AnyDictOptionalTuple)config)daglish)daglish_extensions)module_reflection)serializationc                   @   s*   e Zd ZdZdZdZdedefddZdS )	ImportDottedNameDebugContextz2Context of importing a sumbol, for error messages.      namereturnc                 C   s,   | t jkr
d|S | t jksJ d|S )Nz Could not init a buildable from zCould not load fiddler )r   BASE_CONFIGFIDDLER)selfr    r   P/home/ubuntu/.local/lib/python3.10/site-packages/fiddle/_src/absl_flags/utils.pyerror_prefix*   s   


z)ImportDottedNameDebugContext.error_prefixN)__name__
__module____qualname____doc__r   r   strr   r   r   r   r   r   $   s
    r   r   moder   c           
      C   s*  |  d}t|dk rt||  dtt|d ddD ]l}z\td|d| }t||d D ]B\}}zt	||}W q6 t
yx   dd	d
 t|D }d|d||  }|||  }	t||  d|d|	d| dw |W   S  ty   |dkr Y qw td|d )a  Returns the Python object with the given dotted name.

  Args:
    name: The dotted name of a Python object, including the module name.
    mode: Whether we're looking for a base config function or a fiddler.

  Returns:
    The named value.

  Raises:
    ValueError: If `name` is not a dotted name.
    ModuleNotFoundError: If no dotted prefix of `name` can be imported.
    AttributeError: If the imported module does not contain a value with
      the indicated name.
  .r   z3: Expected a dotted name including the module name.r   r   N, c                 s   s"    | ]}| d st|V  qdS )_N)
startswithrepr).0nr   r   r   	<genexpr>Q   s    

z%import_dotted_name.<locals>.<genexpr>z	: module z has no attribute ; available names: zNo module named )splitlen
ValueErrorr   range	importlibimport_modulejoin	enumerategetattrAttributeErrordirModuleNotFoundError)
r   r   name_piecesivaluej
name_pieceavailable_namesmodule_namefailing_namer   r   r   import_dotted_name1   sD   



r:   T)frozenc                   @   sb   e Zd ZU dZeed< eeedf  ed< ee	eef  ed< e
dZededd fd	d
ZdS )CallExpressiona(  Parsed components of a call expression (or bare function name).

  Examples:

  >>> CallExpression.parse("fn('foo', False, x=[1, 2])")
  CallExpression(func_name='fn', args=('foo', False'), kwargs={'x': [1, 2]})
  >>> CallExpression.parse("fn")  # Bare function name: empty args/kwargs.
  CallExpression(func_name='fn', args=()), kwargs={})

  Attributes:
    func_name: The name fo the function that should be called.
    args: Parsed values of positional arguments for the function.
    kwargs: Parsed values of keyword arguments for the function.
  	func_name.argskwargsz+(?P<func_name>[\w\.]+)(?:\((?P<args>.*)\))?r4   r   c           
      C   s  t | j|}|du rtd||ddu r"t|ddi S t|}t|tj	rGt
|jdkrGt|jd tjrGt|jd jtjsNtd||jd j}g }|jD ]1}t|tjretdz
|t| W qY ty } ztd	t|d
|d|d}~ww i }|jD ]2}	|	jdu rtdzt|	j||	j< W q ty } ztd	t|	jd
|d|d}~ww t|dt||S )a  Returns a CallExpression parsed from a string.

    Args:
      value: A string containing positional and keyword arguments for a
        function.  Must consist of an open paren followed by comma-separated
        argument values followed by a close paren.  Argument values must be
        literal constants (i.e., must be parsable with `ast.literal_eval`).
        var-positional and var-keyword arguments are not supported.

    Raises:
      SyntaxError: If `value` is not a simple call expression with literal
        arguments.
    Nz2Expected a function name or call expression; got: r>   r=   r   r   r   z*args is not supported.z.Expected arguments to be simple literals; got z (while parsing )z**kwargs is not supported.)re	fullmatch	_PARSE_RESyntaxErrorgroupr<   astparse
isinstanceModuler'   bodyExprr4   Callr>   Starredappendliteral_evalr(   unparsekeywordsargtuple)
clsr4   mnode	call_noder>   rR   excr?   kwargr   r   r   rG   {   sp   





zCallExpression.parseN)r   r   r   r   r   __annotations__r   r   r   r   rA   compilerC   classmethodrG   r   r   r   r   r<   d   s   
 
r<   pathc                 C   s(   |  ds|  dsd|  } t| S )z@Parses a path into a list of either attributes or index lookups.[r   )r    r   
parse_path)r]   r   r   r   r_      s   

r_   r4   c                 C   sv   |   dkrdS |   dkrdS zt| W S  ty: } ztd|  d| d| d|  d	| d
|  d|d}~ww )zFParses a string `value` (e.g. from the command line) to a Python type.falseFtrueTzCould not parse literal value "z" while trying to set "zR". Does a string need to be quoted? For example, you might want to pass --fdl_set=z='z' instead of --fdl_set==r   N)lowerrF   rO   	Exceptionr(   )r4   r]   er   r   r   parse_value   s0   rf   function_namemoduleallow_importsfailure_msg_prefixc              
   C   s   t || r
t|| S |r-zt| |dW S  ty, } zt| d| d| |d}~ww t|}t| d| dd| d)a  Returns function that produces `fdl.Buildable` from its name.

  Args:
    function_name: The name of the function.
    mode: Whether we're looking for a base config function or a fiddler.
    module: A common namespace to use as the basis for finding configs and
      fiddlers. May be `None`; if `None`, only fully qualified Fiddler imports
      will be used (or alternatively a base configuration can be specified using
      the `--fdl_config_file` flag.)
    allow_imports: If true, then fully qualified dotted names may be used to
      specify configs or fiddlers that should be automatically imported.
    failure_msg_prefix: Prefix string to prefix log messages in case of
      failures.

  Returns:
    The named value.
  )r    z: Nr%   r   r   )hasattrr.   r:   r1   r(   r	   find_base_config_like_thingsr,   )rg   r   rh   ri   rj   re   r7   r   r   r   resolve_function_reference   s$   


rn   cfg
assignmentc           
   
   C   s   |j ddd\}}t|^ }}tt| }z|D ]}||}qW n ty7 } z	td| d|d}~ww t||d}	z&t	|t
jrOt||j|	 W dS t	|t
jr]|	||j< W dS td| d	 ty| } ztd
| d| d|d}~ww )zSet an attribute's value.

  Args:
    cfg: A `fdl.Buildable` whose attribute is to be overridden.
    assignment: String representing attribute's override expression. Of the form
      `attribute=value`.
  rb   r   )maxsplitzInvalid path "z".N)r4   r]   zUnexpected path element r   zCould not set "z" to ")r&   r_   typingcastr   followrd   r(   rf   rH   r   Attrsetattrr   Keykey)
ro   rp   r]   r4   parentslastwalkparentre   literal_valuer   r   r   	set_value   s,   r~   c                   @   sT   e Zd ZdZ	ddejdeej de	fddZ
	dde	deej dejfd	d
ZdS )ZlibJSONSerializerz5Serializer that uses JSON, zlib, and base64 encoding.Nro   pyref_policyr   c                 C   s"   t tt|| dS )Nascii)base64urlsafe_b64encodezlibcompressr
   	dump_jsonencodedecode)r   ro   r   r   r   r   	serialize  s
   zZlibJSONSerializer.serialize
serializedc                 C   s   t jtt| |dS )N)r   )r
   	load_jsonr   
decompressr   urlsafe_b64decoder   )r   r   r   r   r   r   deserialize'  s   zZlibJSONSerializer.deserialize)N)r   r   r   r   r   	Buildabler   r
   PyrefPolicyr   r   r   r   r   r   r   r     s$    
r   )$r   rF   r   dataclassesenumr*   rA   typesrr   r   r   r   r   r   fiddle._srcr   r   r   r	   fiddle._src.experimentalr
   Enumr   r   r:   	dataclassr<   Pathr_   rf   
ModuleTypeboolrn   r   r~   r   r   r   r   r   <module>   sF   
3Q
*