
    l0jP                     P   U 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 d dlmZmZmZmZmZmZmZmZmZ ddlmZmZmZmZmZ  G d d          Zdeed	f         d
eddez  defdZdedee         dedededefdZ dedee         defdZ!de
eeef                  de"e         fdZ# ed           ed          z   Z$ee%d<    e&edd          dk    r.e'(                    e$de)           e'(                    e$dd           d e"defd!Z*d e+defd"Z,d e-defd#Z.d edefd$Z/d edefd%Z0d&ed'edefd(Z1d e2defd)Z3ddez  fd*Z4defd+Z5d ej6        defd,Z7d ej8        d-e9defd.Z:defd/Z;defd0Z<defd1Z=d e>d2e9defd3Z? ed4          Z@ G d5 d6ee@                   ZAejB         e>ee9ef                   fZCejD         e>eAe                   fZEe> e>e          fZF[A[@e jG        d7             ZHd8 ZId9d:eId:d:d;d;d:df	d eded<e9d=e	egdez  f         d>e9d2e9d?e9d-e9d@e9dAde+e         z  defdBZJdCd9d:eId:d:d;d;d:dD	d edEeded<e9d=e	egdez  f         d>e9d2e9d?e9d-e9d@e9defdFZKdCd9d:eId:d:d;d;d:dD	d edEeded<e9d=e	egdez  f         d>e9d2e9d?e9d-e9d@e9ddfdGZLdHedIedefdJZMdS )K    N)CallableIterableSequence)	AnyGenericLiteral
NamedTupleTypeVarUnioncastget_args
get_origin   )AbstractDocBreakDoc	ConcatDocTextDocpformat_docc                   &    e Zd ZdefdZdefdZdS )	_WithReprstringc                     || _         d S Nr   )selfr   s     ]/home/wildlama/miniconda3/envs/lam/lib/python3.11/site-packages/wadler_lindig/_definitions.py__init__z_WithRepr.__init__   s        returnc                     | j         S r   r   )r   s    r   __repr__z_WithRepr.__repr__"   s
    {r   N)__name__
__module____qualname__strr   r!    r   r   r   r      sJ        s    #      r   r   shape.dtypekindr   c                 :   |                     dd                               dd                               dd                               dd          }d	                    t          t          |                     }| d
| d}|	|d| dz   }t	          |          S )a  Summarises an array based on its shape/dtype/kind. (Where 'kind' refers to NumPy
    vs PyTorch vs JAX etc.)

    **Arguments:**

    - `shape`: a tuple of integers.
    - `dtype`: a string, for which common dtypes will be contracted (`float -> f`,
        `uint -> u`, `int -> i`, `complex -> c`)
    - `kind`: optional. If provided it is written in brackets afterwards.

    **Returns:**

    A [`wadler_lindig.TextDoc`][] with text looking like e.g. `f32[2,3,4](numpy)` for a
    NumPy array of shape `(2, 3, 4)` and `float32` dtype.
    floatfuintuinticomplexc,[]N())replacejoinmapr%   r   )r'   r(   r)   short_dtypeshort_shapeouts         r   array_summaryr>   &   s    " 	gs##							C	 	 	  ((3sE??++K
)
);
)
)
)CKKKK3<<r   begindocssependindentc                 L   t          |          dk    r| |z                                   S d |D             }t          d          t          ||                                          z                       |          t          d          z   }| |z   |z                                   S )aC  A helper for formatting a 'bracketed' object: tuples, lists, classes, etc, which
    are all represented in essentially similar ways: a pair of brackets (whether round,
    square, etc.), a sequence of values in between -- which are indented if laid out in
    vertical mode, and possibly a name as prefix.

    See the [`(break-group).nest-break` example](./pattern.ipynb) for more on the
    pattern that this enables.

    **Arguments:**

    - `begin`: appears at the start, before any indent.
    - `docs:`: a sequence of documents. They will either be laid out horizontally
        together or vertically together.
    - `sep`: each element of `docs` will be separated by `sep`.
    - `end`: appears at the end, after any indent.
    - `indent`: how much to indent (for [`wadler_lindig.NestDoc`][] to use) when laying
        out vertically.

    **Returns:**

    A document in `(break-group).nest-break` form.

    !!! example

        Formatting a list, which do not have any name prefix:
        ```python
        import wadler_lindig as wl

        wl.bracketed(
            begin=wl.TextDoc("["),
            docs=[wl.pdoc(x) for x in obj],
            sep=wl.comma,
            end=wl.TextDoc("]"),
            indent=indent,
        )
        ```

        Formatting a frozenset, which does have a name prefix:
        ```python
        import wadler_lindig as wl

        wl.bracketed(
            begin=wl.TextDoc("frozenset({"),
            docs=[wl.pdoc(x) for x in obj],
            sep=wl.comma,
            end=wl.TextDoc("})"),
            indent=indent,
        )
        ```
    r   c                 6    g | ]}|                                 S r&   )group).0xs     r   
<listcomp>zbracketed.<locals>.<listcomp>   s     (((a		(((r    )lenrF   r   r9   nest)r?   r@   rA   rB   rC   nesteds         r   	bracketedrN   C   s    r 4yyA~~""$$$((4(((2,,c4!6!6!8!88>>vFFRTU$++---r   c                     t          |          dk    rt                      S |d         g}|dd         D ],}|                    |            |                    |           -t          | S )zConcatenates `objs` together separated by `sep`.

    **Arguments:**

    - `sep`: the separate to use.
    - `docs`: a sequence of documents to join.

    **Returns:**

    `ConcatDoc(docs[0], sep, docs[1], sep, docs[2], ..., sep, docs[-1])`
    r   r   N)rK   r   append)rA   r@   piecesobjs       r   r9   r9      sq     4yyA~~{{1gYFABBx  ccfr   pairsc                      fd| D             S )a8  Formats key-value pairs in the form 'key=value'.

    **Arguments:**

    - `pairs`: an iterable of `(key, value)` pairs.
    - `**kwargs`: passed on to each `pdoc(value, **kwargs)`

    **Returns:**

    A list of documents `TextDoc(key) + TextDoc("=") + pdoc(value, **kwargs)` for each
    key-value pair.
    c                 p    g | ]2\  }}t          |          t          d           z   t          |fi z   3S )=)r   pdocrG   keyvaluekwargss      r   rI   znamed_objs.<locals>.<listcomp>   sC    XXXJCGCLL73<<'$u*?*?*?*??XXXr   r&   )rS   r[   s    `r   
named_objsr\      s!     YXXXRWXXXXr   r3    commaGENERATING_DOCUMENTATIONrJ   zwadler-lindigr#   __doc__z/A shorthand for `TextDoc(',') + BreakDoc(' ')`.rR   c                     t          t          d          fd| D             t          t          d          d                   S )Nr4   c                 *    g | ]}t          |fi S r&   rW   rG   rH   r[   s     r   rI   z!_pformat_list.<locals>.<listcomp>   s)    ---Ad1---r   r5   rC   r?   r@   rA   rB   rC   )rN   r   r^   rR   r[   s    `r   _pformat_listrg      sN    cll-------CLLh   r   c                     t          |           dk    rt          d          S t          t          d          fd| D             t          t          d          d                   S )Nr   zset(){c                 *    g | ]}t          |fi S r&   rc   rd   s     r   rI   z _pformat_set.<locals>.<listcomp>   )    111$q##F##111r   }rC   re   rK   r   rN   r^   rf   s    `r   _pformat_setrn      sk    
3xx1}}w#,,1111S111(#
 
 
 	
r   c                     t          |           dk    rt          d          S t          t          d          fd| D             t          t          d          d                   S )Nr   zfrozenset()zfrozenset({c                 *    g | ]}t          |fi S r&   rc   rd   s     r   rI   z&_pformat_frozenset.<locals>.<listcomp>   rk   r   z})rC   re   rm   rf   s    `r   _pformat_frozensetrq      sm    
3xx1}}}%%%-((1111S111(#
 
 
 	
r   c                    t          |           dk    r%t          | d         fi t          d          z   g}nfd| D             }t          t          d          |t          t          d          d                   S )	Nr   r   r3   c                 *    g | ]}t          |fi S r&   rc   rd   s     r   rI   z"_pformat_tuple.<locals>.<listcomp>   s)    ///aQ!!&!!///r   r6   r7   rC   re   )rK   rW   r   rN   r^   rR   r[   objss    ` r   _pformat_tuplerv      s    
3xx1}}SV&&v&&56////3///cllCLLh   r   c                      t           fd j        D             fi |}t          t           j        j        dz             |t          t          d          |d                   S )Nc                 4    g | ]}|t          |          fS r&   )getattr)rG   namerR   s     r   rI   z'_pformat_namedtuple.<locals>.<listcomp>   s(    JJJdgc4001JJJr   r6   r7   rC   re   )r\   _fieldsrN   r   	__class__r"   r^   rt   s   `  r   _pformat_namedtupler}      sr    JJJJckJJJUUfUUDcm,s233CLLh   r   rY   rZ   c                 x    t          | fi |t          d          z   t          d          z   t          |fi |z   S )N:r]   )rW   r   r   )rY   rZ   r[   s      r   _dict_entryr      sC    v-=U@U@Uf@U@UUUr   c                     fd|                                  D             }t          t          d          |t          t          d          d                   S )Nc                 2    g | ]\  }}t          ||fi S r&   )r   rX   s      r   rI   z!_pformat_dict.<locals>.<listcomp>   s/    LLL*#uKU--f--LLLr   ri   rl   rC   re   )itemsrN   r   r^   rt   s    ` r   _pformat_dictr      s[    LLLL		LLLDcllCLLh   r   c                     dD ]E\  }}|t           j        v r2t          | t          t           j        |         |                    r|c S Fd S )N))numpyndarray)torchTensor)jaxArray)zmlx.corearray)sysmodules
isinstancery   )rH   moduler   s      r   _array_kindr      sV       S[  Z73;v;NPU3V3V%W%W MMM4r   c                     |d         }|rSt          |           }|J t          | j                                      d          ^ }}t	          | j        ||          S t          t          |                     S )Nshort_arrays.)r   r%   r(   rsplitr>   r'   r   repr)rR   r[   r   r)   _r(   s         r   _pformat_ndarrayr     st    .)L 53	NN))#..	ESYt444499r   c                    t          | j        fi gfd| j        D             z   t          | j                                        fi z   }t          t          d          |t          t          d          d                   S )Nc                 *    g | ]}t          |fi S r&   rc   rd   s     r   rI   z$_pformat_partial.<locals>.<listcomp>  s)    
/
/
/4V
/
/
/r   zpartial(r7   rC   re   )	rW   funcargsr\   keywordsr   rN   r   r^   rt   s    ` r   _pformat_partialr     s    	ch	!	!&	!	!"
/
/
/
/ch
/
/
/	0
S\''))
4
4V
4
4	5 	
 j!!CLLh   r   show_function_modulec                    ~t          | d          rd}nd}|r| j         d| j         }n| j        }t          d| d| d          S )N__wrapped__zwrapped functionfunctionr   <r]   >)hasattrr#   r$   r   )rR   r   r[   fnrz   s        r   _pformat_functionr   %  sq     	sM""   .553#355#r##D###$$$r   c                 *   dt          |           j        z   }t          d          }g }t          j        |           D ]_}|j        rVt          | |j        |          }|d         r	||j        u s/|	                    |j        
                    |          |f           `t          |fi |}|                                }|d         |d<   t          t          | j        fi |t!          d          z   |t"          t!          d          |d         	          S )
Nr   z<uninitialised>hide_defaultsshow_dataclass_moduleshow_type_moduler6   r7   rC   re   )typer"   r   dataclassesfieldsr   ry   rz   defaultrP   removeprefixr\   copyrN   rW   r|   r   r^   )rR   r[   	type_nameuninitialisedru   fieldrZ   name_kwargss           r   _pformat_dataclassr   4  s%   d3ii((I/00MD#C(( I I: 	IC];;E?+ I0F0FUZ44Y??GHHHd%%f%%D++--K&,-D&EK"#3=00K0073<<?CLLh   r   c                     t          d          t          d          z   }fdt          |           D             }t          ||          S )Nr]   z| c                 *    g | ]}t          |fi S r&   rc   rd   s     r   rI   z"_pformat_union.<locals>.<listcomp>K  )    555!Df555r   )r   r   r   r9   )rR   r[   barr@   s    `  r   _pformat_unionr   I  sF    
3--'$--
'C5555x}}555DT??r   c                     fdt          |           D             }t          t          t          |           fi t	          d          z   |t
          t	          d          d                   S )Nc                 *    g | ]}t          |fi S r&   rc   rd   s     r   rI   z*_pformat_generic_alias.<locals>.<listcomp>P  r   r   r4   r5   rC   re   )r   rN   rW   r   r   r^   )rR   r[   r@   s    ` r   _pformat_generic_aliasr   O  st    5555x}}555D:c??--f--<CLLh   r   r   c                    ~t          | d          rMt          | d          r=|r	| j        dv rt          | j                  S t          | j         d| j                   S t          t	          |                     S )Nr#   r$   )builtinstypingtyping_extensionszcollections.abcr   )r   r#   r   r$   r   )rR   r   r[   s      r   _pformat_typer   Z  s    sL!! "gc>&B&B " 	C3> 6
 $
 $
 3+,,,cnAAs/?AABBB tCyy!!!r   _Tc                       e Zd ZdS )_FooN)r"   r#   r$   r&   r   r   r   r   n  s        Dr   r   c              #      K   t          |          }|                     |           	 d V  |                     |           d S # |                     |           w xY wr   )idaddremove)seenrR   id_s      r   _seen_contextr   x  s^      
S''CHHSMMMCCs   A Ac                     d S r   r&   )r   s    r   _noner     s    4r      TFr   customr   r   respect_pdocseen_idsc
                 B   |	t                      }	t          |           |	v rt          d          S t          | t                    r| S ||
d<   ||
d<   ||
d<   ||
d<   |	|
d<   ||
d<   ||
d	<   ||
d
<   ||
d<   t          |	|           5   ||           }||cddd           S |r_t          t          |           d          rB | j        di |
}t          |t                    r |	                                cddd           S | | t          j        u rt          d          cddd           S t          | t                    rUt          | d          r,t          t          t          |           fi |
cddd           S t!          | fi |
cddd           S t          | t"                    rt%          | fi |
cddd           S t          | t&                    rt)          | fi |
cddd           S t          | t                     rt+          | fi |
cddd           S t          | t,                    rt/          | fi |
cddd           S t          | t0          j                  rt5          | fi |
cddd           S t          | t          j                  rt9          | fi |
cddd           S | t:          u rt          d          cddd           S t          | t<                    rt?          | fi |
cddd           S t          | t@                    rtC          | fi |
cddd           S t          | tD                    rtG          | fi |
cddd           S tI          j%        |           r.t          | t                    stM          | fi |
cddd           S tO          |           tQ          | fi |
cddd           S | du rt          d          cddd           S t          tS          |                     cddd           S # 1 swxY w Y   dS )u 	  Formats an object into a Wadler–Lindig document. Such documents are essentially
    strings that haven't yet been pretty-formatted to a particular width.

    **Arguments:**

    - `obj`: the object to pretty-doc.
    - `indent`: when the contents of a structured type are too large to fit on one line,
        they will be indented by this amount and placed on separate lines.
    - `short_arrays`: whether to print a NumPy array / PyTorch tensor / JAX array as a
        short summary of the form `f32[3,4]` (here indicating a `float32` matrix of
        shape `(3, 4)`)
    - `custom`: a way to pretty-doc custom types. This will be called on every object it
        encounters. If its return is `None` then the usual behaviour will be performed.
        If its return is an `AbstractDoc` then that will be used instead.
    - `hide_defaults`: whether to show the default values of dataclass fields.
    - `show_type_module`: whether to show the name of the module for a type:
         `somelib.SomeClass` versus `SomeClass`.
    - `show_dataclass_module`: whether to show the name of the module for a dataclass
         instance: `somelib.SomeClass()` versus `SomeClass()`.
    - `show_function_module`: whether to show the name of the module for a function:
         `<function some_fn>` versus `<function somelib.some_fn>`.
    - `seen_ids`: the `id(...)` of any Python objects that have already been seen, and
        should not be further introspected to avoid recursion errors (e.g.
        `x = []; x.append(x)`). Note that for efficiency, this argument will be mutated
        with the ids encountered.
    - `**kwargs`: all kwargs are forwarded on to all `__pdoc__` calls, as an
        escape hatch for custom behaviour.

    **Returns:**

    A pretty-doc representing `obj`.

    !!! info

        The behaviour of this function can be customised in two ways.

        First, any object which implements a
        `__pdoc__(self, **kwargs) -> None | AbstractDoc` method will have that method
        called to determine its pretty-doc.

        Second, the `custom` argument to this function can be used. This is particularly
        useful to provide custom pretty-docs for objects provided by third-party
        libraries. (For which you cannot add a `__pdoc__` method yourself.)
    Nz<recursive>rC   r   r   r   r   r   r   r   r   __pdoc__Noner{   r   .z...r&   )*setr   r   r   r   r   r   r   r   rF   typesNoneTypetupler}   r   r	   rv   listrg   dictr   rn   	frozensetrq   ftpartialr   FunctionTyper   r   _union_typesr   _generic_alias_typesr   _type_typesr   r   is_dataclassr   r   r   r   )rR   rC   r   r   r   r   r   r   r   r   r[   maybe_custom	custom_pps                r   rW   rW     s   t 55	#ww(}%%%#{## 
F8)F>F8+F?!F:!1F&;F"#%9F!")F>	x	%	% -" -"vc{{#-" -" -" -" -" -" -" -"
  	)GDIIz:: 	)$..v..I)[11 ) ((-" -" -" -" -" -" -" -" ;#//6??-" -" -" -" -" -" -" -" c5!! 	1sI&& L*4
C+@+@KKFKK-" -" -" -" -" -" -" -"  "#0000!-" -" -" -" -" -" -" -"" c4   	0 ////%-" -" -" -" -" -" -" -"& c4   	0 ////)-" -" -" -" -" -" -" -"* c3 	/..v..--" -" -" -" -" -" -" -". c9%% 	5%c44V441-" -" -" -" -" -" -" -"2 c2:&& 	3#C226225-" -" -" -" -" -" -" -"6 c5-.. 	4$S33F339-" -" -" -" -" -" -" -": #::5>>=-" -" -" -" -" -" -" -"> c<(( 	1!#0000A-" -" -" -" -" -" -" -"D c/00 	9)#8888G-" -" -" -" -" -" -" -"H c;'' 	0 ////K-" -" -" -" -" -" -" -"L #C(( 	5C1F1F 	5%c44V44O-" -" -" -" -" -" -" -"P s'#C22622S-" -" -" -" -" -" -" -"T #::5>>W-" -" -" -" -" -" -" -"Z tCyy!![-" -" -" -" -" -" -" -" -" -" -" -" -" -" -" -" -" -"s   P!APP-AP>P!P!P3!P!!P&P&P5P!P!P5!P#5P%PP,PPPX   	widthrC   r   r   r   r   r   r   r   r   c       	         N    t          | f||||||||	d|
}t          ||          S )z[As [`wadler_lindig.pprint`][], but returns a string instead of printing to
    stdout.
    )rC   r   r   r   r   r   r   r   )rW   r   )rR   r   rC   r   r   r   r   r   r   r   r[   docs               r   pformatr     sT    $ !#)31!   C sE"""r   c       	         N    t          t          | f|||||||||	d	|
           dS )a  Pretty-prints an object to stdout.

    **Arguments:**

    - `obj`: the object to pretty-print.
    - `width`: a best-effort maximum width to allow. May be exceeded if there are
        unbroken pieces of text which are wider than this.
    - `indent`: when the contents of a structured type are too large to fit on one line,
        they will be indented by this amount and placed on separate lines.
    - `short_arrays`: whether to print a NumPy array / PyTorch tensor / JAX array as a
        short summary of the form `f32[3,4]` (here indicating a `float32` matrix of
        shape `(3, 4)`)
    - `custom`: a way to pretty-print custom types. This will be called on every object
        it . If its return is `None` then the default behaviour will be performed. If
        its return is an [`wadler_lindig.AbstractDoc`][] then that will be used instead.
    - `hide_defaults`: whether to show the default values of dataclass fields.
    - `show_type_module`: whether to show the name of the module for a type:
         `somelib.SomeClass` versus `SomeClass`.
    - `show_dataclass_module`: whether to show the name of the module for a dataclass
         instance: `somelib.SomeClass()` versus `SomeClass()`.
    - `show_function_module`: whether to show the name of the module for a function:
         `<function some_fn>` versus `<function somelib.some_fn>`.
    - `**kwargs`: all other unrecognized kwargs are forwarded on to any `__pdoc__`
        methods encountered, as an escape hatch for custom behaviour.

    **Returns:**

    A string representing `obj`.

    !!! info

        The behaviour of this function can be customised in two ways.

        First, any object which implements a
        `__pdoc__(self, **kwargs) -> None | AbstractDoc` method will have that method
        called to determine its pretty-doc.

        Second, the `custom` argument to this function can be used. This is particularly
        useful to provide custom pretty-docs for objects provided by third-party
        libraries. (For which you cannot add a `__pdoc__` method.)
    r   N)printr   )rR   r   rC   r   r   r   r   r   r   r   r[   s              r   pprintr   $  s`    p 
	
%'-"7!5%	
 	
 	
 	
    r   minusplusc                     t          j        |                                 |                                          }d                    d |D                       }|S )u  Returns a pretty-diff between two strings.

    (This is just a thin wrapper around the builtin `difflib`, and is just here as a
    helper for common use-cases.)

    !!! example

        ```python
        minus = "hello\nthere\nobi wan kenobi"
        plus = "hello\nthere\npatrick kidger"
        print(wadler_lindig.pdiff(minus, plus))
        #   hello
        #   there
        # - obi wan kenobi
        # + patrick kidger
        ```

    **Arguments:**

    - `minus`: any lines unique to this string will be prefixed with a `-`.
    - `plus`: any lines unique to this string will be prefixed with a `+`.

    **Returns:**

    A diff between the two tsrings `minus` and `plus`, showing their shared lines once
    and the unique lines from each.
    
c              3   D   K   | ]}|                     d           |V  dS )?N)
startswith)rG   lines     r   	<genexpr>zpdiff.<locals>.<genexpr>  s3      GGd$//#2F2FGTGGGGGGr   )difflibndiff
splitlinesr9   )r   r   diffs      r   pdiffr   m  sP    8 =))++T__->->??D99GGdGGGGGDKr   )N
contextlibr   r   	functoolsr   r   r   r   collections.abcr   r   r   r   r   r   r	   r
   r   r   r   r   _wadler_lindigr   r   r   r   r   r   r   r/   r%   r>   rN   r9   r   r\   r^   __annotations__ry   object__setattr__r"   rg   r   rn   r   rq   rv   r}   r   r   r   r   r   r   r   r   boolr   r   r   r   r   r   r   r   	UnionTyper   GenericAliasr   r   contextmanagerr   r   rW   r   r   r   r&   r   r   <module>r	     s                 



   8 8 8 8 8 8 8 8 8 8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
                    sCx  D3J 7    :>.>.
;
>. 
>. 
	>.
 >. >. >. >. >.Bk +!6 ;    *YhuS#X/ Yd;>O Y Y Y Y  WS\\HHSMM1{ 1 1 1
76-r22oEE
ulH555
yO  
t +    

c 

 

 

 

 



I 

K 

 

 

 

 K    Z k    VS V V; V V V Vt +    dSj    {    "* ;    %		%6:%% % % %    *[    [    "t "$ "[ " " " "" WT]]	 	 	 	 	72; 	 	 	 eD#I&6!7!78*DDcOO< TT']]#"      27!"'!& $z" z"	z"z" z" cUD;../	z"
 z" z"  z" z" z" SXoz" z" z" z" z"@ 27!"'!&# # #	# # 	#
 # cUD;../# # #  # # # 	# # # #H 27!"'!&F F F	F F 	F
 F cUD;../F F F  F F F 
F F F FR C C      r   