
    `N`ep                        d Z ddlmZ ddlZddl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 dd	l
mZ dd
l
mZ ddl
mZ d,dZd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Z G d de          Z ej        dddg          Z  ej        ddd g          Z!d! Z"d" Z#d# Z$g a%d$ Z&d%Z'd&Z(d'Z)d( Z*d) Z+d* Z,d+ Z-dS )-a
  Decide what the format for the code should be.

The `unwrapped_line.UnwrappedLine`s are now ready to be formatted.
UnwrappedLines that can be merged together are. The best formatting is returned
as a string.

  Reformat(): the main function exported by this module.
    )unicode_literalsN)pytree)token)format_decision_state)format_token)line_joiner)pytree_utils)style)verifierFc                    g }d}t          j        d          }t          |           D ]}|j        }t	          ||j        ||           ||j        z  }t          j        ||          }	|	                                 |j	        s|j        j
        r3|j        j        j                                        |j        j        _        n>|j        j
        r2|j        j        j                                        |j        j        _        |r"|j	        rt          |j        |j        |           t!          d |j        D                       rt%          |           |j	        st'          |          r0t)          |           t+          |||           t-          |	           nt/          |          st1          |          r!t+          |||           t-          |	           nt3          |          rDt!          d |j        D                       s&|	j        r|	                    dd           |	j        ngt9          |	          sXt          j        ||          }	|	                                 t)          |           t+          ||d           t-          |	           |                    |           |}t=          |           t?          ||          S )ao  Reformat the unwrapped lines.

  Arguments:
    uwlines: (list of unwrapped_line.UnwrappedLine) Lines we want to format.
    verify: (bool) True if reformatted code should be verified for syntax.
    lines: (set of int) The lines which can be modified or None if there is no
      line range restriction.

  Returns:
    A string representing the reformatted code.
  NINDENT_WIDTHc              3   $   K   | ]}|j         V  d S N
is_comment.0toks     8lib/python3.11/site-packages/yapf/yapflib/reformatter.py	<genexpr>zReformat.<locals>.<genexpr>I   s$      55S^555555    c              3   $   K   | ]}|j         V  d S r   )
must_splitr   s     r   r   zReformat.<locals>.<genexpr>W   s@       3M 3M7: 47> 3M 3M 3M 3M 3M 3Mr   Fnewlinedry_run) r
   Get_SingleOrMergedLinesfirst_FormatFirstTokendepthr   FormatDecisionStateMoveStateToNextTokendisabler   nodevaluerstriplast+_RetainRequiredVerticalSpacingBetweenTokensanytokens$_RetainVerticalSpacingBeforeComments_LineHasContinuationMarkers_RetainHorizontalSpacing_RetainRequiredVerticalSpacing_EmitLineUnformatted%_LineContainsPylintDisableLineTooLong_LineContainsI18n_CanPlaceOnSingleLine
next_tokenAddTokenToState_AnalyzeSolutionSpaceappend_AlignTrailingComments_FormatFinalLines)
uwlinesverifylinesfinal_linesprev_uwlineindent_widthuwlinefirst_token
indent_amtstates
             r   ReformatrD   '   s    ++>**,$W-- 1 1f,Kk6<kJJJ,J!5fjIIE	   > 5		  A"(,"3"9"@"@"B"B;! A!'!1!7!>!>!@!@	 M, M 	4FL4?4De	M 	M 	M	55v}555	5	5 5,V444~ $4V<< $v&&&$V[%@@@5!!!!
/
7
7 $
F
#
#$ %V[%@@@5!!!!	v	&	& $s 3M 3M>Dm3M 3M 3M 0M 0M $  <eU;;;  < #5)) $ &9&*MM""$$$ (((&v{DAAAU###vKK%%%	;	/	//r   c                 d    | j         D ]'}|                    | j        j        | j                   (dS )z-Retain all horizontal spacing between tokens.N)r+   RetainHorizontalSpacingr   columnr!   )r@   r   s     r   r.   r.   n   sA    ] C Cc 3V\BBBBC Cr   c                     d}||j         }| j        D ]*}t          |||           |}| j        rt	                      }+dS )z*Retain all vertical spacing between lines.N)r(   r+   r)   r$   set)
cur_uwliner>   r<   prev_tokcur_toks        r   r/   r/   t   s_    (H"  g/5IIIH  eee r   c                    |dS |j         r#|j        |j                            d          z   }n/|j        r!|j        j        s|j        j        }n|j        }n|j        }| j        r#| j        | j                            d          z
  }n| j        }|j        s7|j                            d          r||j                            d          z  }||z
  }| j        r|j        sn|r|	                    t          ||dz                       rb| j                            d          }t          |dz   |          }t          |	                    |                    }t          ||z
  |          }|                     |           dS )zDRetain vertical spacing between two tokens if not in editable range.N
\   )	is_stringlinenor&   countis_pseudo_parenprevious_tokenis_multiline_stringr   endswithintersectionrangewhitespace_prefixlenmaxAdjustNewlinesBefore)	rL   rK   r<   prev_lineno
cur_linenorequired_newlinesdesired_newlineswhitespace_linesdeletable_liness	            r   r)   r)      s   
F "/HN$8$8$>$>>KK ""6 $+2kkOkk/K  '-"5"5d";";;JJJ		 .!8!8!>!> .8>''---K ;. . 3 . .##E+zA~$F$FGG .066t<<[1_j99%,,-=>>??O-?,. . 
011111r   c                     d}| j         D ]U}|j        rJ|rH|j        |j                            d          z
  |j        z
  dk    r|                    t                     |}VdS )z(Retain vertical spacing before comments.NrN   rP   )r+   r   rR   r&   rS   r]   ONE_BLANK_LINE)r@   
prev_tokenr   s      r   r,   r,      sv    *]  c
~ 1* 1	ciood++	+j.?	?!	C	C  000JJ r   c                    | j         rx| j         j        }|j        }|j        s|j        r||j                            d          z  }|j        rd}n| j         j        |k    }|                     |d           | j         vdS dS )a  Emit the line without formatting.

  The line contains code that if reformatted would break a non-syntactic
  convention. E.g., i18n comments and function calls are tightly bound by
  convention. Instead, we calculate when / if a newline should occur and honor
  that. But otherwise the code emitted will be the same as the original code.

  Arguments:
    state: (format_decision_state.FormatDecisionState) The format decision
      state.
  rN   Fr   N)	r4   rU   rR   rV   rQ   r&   rS   is_continuationr5   )rC   rU   previous_linenor   s       r   r0   r0      s     	 :%4N$+O) :^-E :-33D999o% :gg '/9g	'5999 	 : : : : :r   c                    t          j        d          r@| j        D ]8}|j        r/t	          j        t          j        d          |j                  r dS 9t          j        d          rnt          | j                  }d}||dz
  k     rO| j        |dz            j        dk    r(| j        |         j        t          j        d          v rdS |dz  }||dz
  k     OdS )au  Return true if there are i18n comments or function calls in the line.

  I18n comments and pseudo-function calls are closely related. They cannot
  be moved apart without breaking i18n.

  Arguments:
    uwline: (unwrapped_line.UnwrappedLine) The line currently being formatted.

  Returns:
    True if the line contains i18n comments or function calls. False otherwise.
  I18N_COMMENTTI18N_FUNCTION_CALLr   rP   (F)r
   r   r+   r   rematchr&   r[   )r@   r   lengthindexs       r   r2   r2      s     Y~ }  	 BHUY~%>%>	JJ tt
Y#$$ FE
&1*


-	
"
(C
/
/
-

$	2F(G(G
G
Gtqje	 &1*

 
r   c                 @    t          j        d| j        j                  S )zBReturn true if there is a "pylint: disable=line-too-long" comment.z#\bpylint:\s+disable=line-too-long\b)rn   searchr(   r&   r@   s    r   r1   r1      s    	96;;L	M	MMr   c                 >    t          d | j        D                       S )z7Return true if the line has continuation markers in it.c              3   $   K   | ]}|j         V  d S r   )rh   r   s     r   r   z._LineHasContinuationMarkers.<locals>.<genexpr>   s%      ::SS ::::::r   )r*   r+   rt   s    r   r-   r-      s!    	::FM:::	:	::r   c                 t   d | j         D             }t          j        d          rd|v rdS t          j        d          | j        z  }| j        }d}|j        s|j        s|j        r	|j        }d}|d	S |j	        |z   t          j        d
          k    o&t          d | j         d|         D                        S )zDetermine if the unwrapped line can go on a single line.

  Arguments:
    uwline: (unwrapped_line.UnwrappedLine) The line currently being formatted.

  Returns:
    True if the line can or should be added to a single line. False otherwise.
  c                     g | ]	}|j         
S  )name)r   xs     r   
<listcomp>z)_CanPlaceOnSingleLine.<locals>.<listcomp>   s    ///A///r   FORCE_MULTILINE_DICTLBRACEFr   NTCOLUMN_LIMITc              3   $   K   | ]}|j         V  d S r   r   r   s     r   r   z(_CanPlaceOnSingleLine.<locals>.<genexpr>  s$      GGS#.GGGGGGr   )r+   r
   r   r!   r(   is_pylint_commentis_pytype_commentis_copybara_commentrU   total_lengthr*   )r@   token_namesrB   r(   
last_indexs        r   r3   r3      s     0////+i&'' H,C,C5y((6<7*	$*
  6 
DJ	\4

j
(EIn,E,E
E HGGFM+:+,FGGGGG
GIr   c                 *   d}|t          |           k     r|| |         }|j        sJ d}|j        D ]C}|j        r8t          |j        t
                    r|j                            d          rg }d}	 |t          |          z   t          |           k    rn@| |t          |          z            }|j        sJ |r&|j        d         j                            d          rn|j	        r|
                    g            d}g }	|j        D ]}
|
j        }|                    d          }|dk    r,t          |t          |                    }d}||d	z   d
         }|
j        r#|	
                    t          |                     z|d                    ||
j                  z  }|	rt          |t          |	                    }|
                    |	           e|dz  }d
}|j        D ]}||k    r|} n||}t          |          D ]R\  }}	|	s	| ||z            }d}|j        D ]}
|
j        r|t          |	          k     sJ |	|         |k     sJ d||	|         z
  d	z
  z  }|d	z  }g }t          |
j                            d                    D ]N\  }}|
                    d                    ||                                                     |dk    rd|d	z
  z  }Od                    |          }|
j                            d          }|                    |          r|t          |          d
         }||
_         |t          |	          k    sJ T|t          |          z  }d} nE|s|d	z  }|t          |           k     zd
S d
S )z+Align trailing comments to the same column.r   F#Tz

 rN   r   rP   Nz{}{}    )r[   r+   r   
isinstancespaces_required_beforelistr&   
startswithformatted_whitespace_prefixr$   r7   rfindr\   format	enumeratesplitstripjoinlstrip)r=   final_lines_indexlineprocessed_contentr   all_pc_line_lengthsmax_line_length	this_lineline_contentpc_line_lengthsline_tokrZ   newline_indexaligned_colpotential_colall_pc_line_lengths_indexpc_line_length_index
whitespacecomment_line_indexcomment_lineexisting_whitespace_prefixs                        r   r8   r8     s   C,,,,()D;{ r r
. qZ(BDII q
)

s
#
#q !)	6%8!9!99S=M=MMM!"3c:M6N6N"NO) !
!
!
!! q!=HHPP  &&r*** ,/#* O Oh ( D-33D99M"" #OS5F5F G Gol"3MA4E4F4F"G" O$$S%6%67777fmm,=x~NNNll I!/33G3GHHO

$
$_
5
5
5S)	6X 	1 7 	 	M_,,'KE - '+ ;D;! ;! )	> )	>6%  !"36O"OP)!"
#* , ,h" ,)C,@,@@@@@$%9:[HHHH 0D EEIKj"a'"l6?.&&t,,7. 7. 7 72$l##FMM*2>2D2D2F2F%H %H I I I &**"kAo6*!YY|44l
 4;;DAA ) (()CDD N+C0J,K,K,L,LM+hn%_)=)======S!4555  1w 	C,,,,,,,,r   c                 >   g }| D ] }g }|j         D ]}|j        s5|                    |j                   |                    |j                   >|j        j                            d          sR|j        j                            d          s3|j        j        dk    s|j        j        dvr|                    d           |                    d	                    |                     |rt          j        |d                    d	                    |          dz   S )z2Compose the final output from the finalized lines.rN   r   :z,}])r   r   )r+   rT   r7   r   r&   r4   rZ   r   rU   r   r   
VerifyCode)r=   r;   formatted_coder   formatted_liner   s         r   r9   r9     s)   . . .dN{ 	' 	'  'c=>>>ci((((0;;DAA 	'0;;C@@	' &#--n"&00!!#&&&"''.11222 ..,---		 	 4	''r   c                       e Zd ZdZd Zd ZdS )
_StateNodea]  An edge in the solution space from 'previous.state' to 'state'.

  Attributes:
    state: (format_decision_state.FormatDecisionState) The format decision state
      for this node.
    newline: If True, then on the edge from 'previous.state' to 'state' a
      newline is inserted.
    previous: (_StateNode) The previous state node in the graph.
  c                 T    |                                 | _        || _        || _        d S r   )ClonerC   r   previous)selfrC   r   r   s       r   __init__z_StateNode.__init__  s#    DJDLDMMMr   c                 B    d                     | j        | j                  S )Nz%StateNode(state=[
{0}
], newline={1}))r   rC   r   )r   s    r   __repr__z_StateNode.__repr__  s#    4;;
DL" " "r   N)__name__
__module____qualname____doc__r   r   ry   r   r   r   r     s<           
" " " " "r   r   OrderedPenaltypenaltyrS   	QueueItemordered_penalty
state_nodec           	      F   d}t                      }g }t          | dd          }t          j        |t	          t          d|          |                     |dz  }|r|d         }|j        j        }|j        }|j	        j
        snrt          j        |           |dk    rd|j	        _        |j	        |v rZ|                    |j	                   t          ||d||          }t          ||d||          }||sdS t          | t          j        |          j                   dS )a  Analyze the entire solution space starting from initial_state.

  This implements a variant of Dijkstra's algorithm on the graph that spans
  the solution space (LineStates are the nodes). The algorithm tries to find
  the shortest path (the one with the lowest penalty) from 'initial_state' to
  the state where all tokens are placed.

  Arguments:
    initial_state: (format_decision_state.FormatDecisionState) The initial state
      to start the search from.

  Returns:
    True if a formatting solution was found. False otherwise.
  r   FNrP   i'  T)rI   r   heapqheappush
_QueueItem_OrderedPenaltyr   r   r   rC   r4   heappopignore_stack_for_comparisonadd_AddNextStateToQueue_ReconstructPath)initial_staterS   seenp_queuer%   itemr   s          r   r6   r6     s<    %	$' 
M5$	/	/$.*_Q%>%>EEFFF1*% F1:D"*G?D:  	M'u}}/3dj,zTHHTZ !$ugFFE $eWEEE' 	 F* 
 5=%-"8"8"CDDD	r   c           	      T   |j                                         }|r|j                             |          s|S |s|r|S t          |j         ||          }| |j                             |d|          z  } t          j        |t          t          | |          |                     |dz   S )aY  Add the following state to the analysis queue.

  Assume the current state is 'previous_node' and has been reached with a
  penalty of 'penalty'. Insert a line break if 'newline' is True.

  Arguments:
    penalty: (int) The penalty associated with the path up to this point.
    previous_node: (_StateNode) The last _StateNode inserted into the priority
      queue.
    newline: (bool) Add a newline if True.
    count: (int) The number of elements in the queue.
    p_queue: (heapq) The priority queue representing the solution space.

  Returns:
    The updated number of elements in the queue.
  T)r   r   r   rP   )	rC   	MustSplitCanSplitr   r5   r   r   r   r   )r   previous_noder   rS   r   r   r%   s          r   r   r      s    " ",,..* ](11*== L	 Z L	M'-	@	@$	TZ''t
 ( < < <'.*_We%D%DdKKLLL	r   c                     t          j                    }|j        r#|                    |           |j        }|j        #|D ]}|                     |j        d           dS )a6  Reconstruct the path through the queue with lowest penalty.

  Arguments:
    initial_state: (format_decision_state.FormatDecisionState) The initial state
      to start the search from.
    current: (_StateNode) The node in the decision graph that is the end point
      of the path with the least penalty.
  Fr   N)collectionsdequer   
appendleftr5   r   )r   currentpathr%   s       r   r   r      s     
			$ OOGG 	   G Gd!!$,!FFFFG Gr   c           	      z   t           rBt           d         |k    r1t                                            t           rt           d         |k    1d}t          |           r8t           s|ga n-t           d         |k     rd}t                               |           |                     t          | ||||          |           dS )a  Format the first token in the unwrapped line.

  Add a newline and the required indent before the first token of the unwrapped
  line.

  Arguments:
    first_token: (format_token.FormatToken) The first token in the unwrapped
      line.
    indent_depth: (int) The line's indentation depth.
    prev_uwline: (list of unwrapped_line.UnwrappedLine) The unwrapped line
      previous to this line.
    final_lines: (list of unwrapped_line.UnwrappedLine) The unwrapped lines
      that have already been processed.
  r   FT)indent_levelN)NESTED_DEPTHpop_IsClassOrDefr7   AddWhitespacePrefix_CalculateNumberOfNewlines)rA   indent_depthr>   r=   first_nesteds        r   r    r    6  s      	 b)L88 	 b)L88 ,; ( ("^ll	b	L	(	(l,'''!! lK!,l< < " ! ! ! ! !r   rP   r      c                 \    | j         dv rdS | j        o| j         dk    o| j        j         dk    S )N>   defclass@Tasyncr   )r&   r4   )r   s    r   r   r   \  s?    Y'''4
. (SY'1 (
.
%
')r   c                    |3| j         *t          j        | j        t          j        j        d           dS | j        rl|j        j        dk    rt          j
        d          rt          S |j        j                            d          rt          j
        d          rt          S t          S | j        r9|s7|j        j        dk    s|j        j        dk    rd	t          j
        d
          z   S |j        }|j        r|s | j        dv rd	t          j
        d          z   S |rTt          j
        d          s@t!          |           r1t          j        | j        t          j        j        d           t          S t#          |j        | |          rt          S t          S t!          |           rx|s|j                            d          dk    }|j        s|j        r|st#          |j        | |          rt-          |          d	z
  }|dk    r||d	z
           j        sn|d	z  }|dk    ||d	z
           j        j        dk    r&||         j                            t                     n*|                    d	t          j
        d          z              | j         *t          j        | j        t          j        j        d           t          S n[t!          |j                  rG|rEt          j
        d          s1t          j        | j        t          j        j        d           t          S | j        r#| j        | j                            d          z
  }n| j        }|j        }	|j        r|	|j                            d          z  }	||	z
  d	k    rt          S t          S )aB  Calculate the number of newlines we need to add.

  Arguments:
    first_token: (format_token.FormatToken) The first token in the unwrapped
      line.
    indent_depth: (int) The line's indentation depth.
    prev_uwline: (list of unwrapped_line.UnwrappedLine) The unwrapped line
      previous to this line.
    final_lines: (list of unwrapped_line.UnwrappedLine) The unwrapped lines
      that have already been processed.
    first_nested: (boolean) Whether this is the first nested class or function.

  Returns:
    The number of newlines needed before the first token.
  Nr   r   !BLANK_LINE_BEFORE_CLASS_DOCSTRINGr   "BLANK_LINE_BEFORE_MODULE_DOCSTRINGfromimportrP   3BLANK_LINES_BETWEEN_TOP_LEVEL_IMPORTS_AND_VARIABLES>   r   r   r   'BLANK_LINES_AROUND_TOP_LEVEL_DEFINITION%BLANK_LINE_BEFORE_NESTED_CLASS_OR_DEFrN   r   )newlinesr	   SetNodeAnnotationr%   
AnnotationNEWLINESis_docstringr   r&   r
   r   re   r   NO_BLANK_LINESis_namer(   r   _NoBlankLinesBeforeCurrentTokenrZ   rS   r$   r   r[   r]   rR   rV   )
rA   r   r>   r=   r   prev_last_tokenis_inline_commentrq   first_token_linenoprev_last_token_linenos
             r   r   r   c  s   &  '$[%5%1%<%EtM M M1 
7**	566 	+ 


!
,
,S
1
1 
)8
9
9  A A6))8++ 
?A A A A  $/!  F[.2KKK DEEEE I=>>k"" $[%5%1%<%EtM M M&'<k'68 8 ; !  );AA$GG1L!  o&@    +?+@++:< < 	  k""Q&%		uqy)4 QJE 		 #)/366$99.IIII00EIGHHHJ J J!-*;+;+7+B+K+/1 1 1  
	{(	)	) 	 ei
13 3 &{'7'3'>'G	O 	O 	O  ,$+k.?.E.Ed.K.KK$+*1( @o399$???00144	r   c              #     K   d}d}|t          |           k     r| |         j        r| |         }|dz  }|t          |           k     r|j        j        dz   }| |         j        |j        k    rn|j        j        dk    rQt          j        t          j	        dd|j        |ff          }|
                    t          j        |                     | |         j        D ]}|
                    |           |dz  }|t          |           k     |V  nt          j        | |d	         |          rs| |dz            }|j        D ]}| |         
                    |           t          |j                  dk    r|j        j        rd
| |         _        | |         V  |dz  }d
}n| |         V  |dz  }d}|t          |           k     d	S d	S )a  Generate the lines we want to format.

  Arguments:
    uwlines: (list of unwrapped_line.UnwrappedLine) Lines we want to format.

  Yields:
    Either a single line, if the current line cannot be merged with the
    succeeding line, or the next two lines merged into one line.
  r   FrP   r   r   ;r   )typer&   contextNT)r[   r$   r(   rG   rR   r&   r   Leafr   SEMIAppendTokenr   FormatTokenr+   r   CanMergeMultipleLinesr   rV   )r:   rq   last_was_mergedr@   rG   leafr   next_uwlines           r   r   r     s      %/Gu~  u~fqjeCLL  #a'5> FM11
;##:S2v7N2OQ Q Q$


\5d;;
<
<
<5>( 	" 	"C


S
!
!
!
!
 CLL   llll		*7566?O	L	L  EAI&k# ( (#""3''''
k 
!
!Q
&
&


/ ' "&ENqjeooENqjeoC 	Gr   c                     |j         }|j        r||j                            d          z  }|j        s|                     d          nd}|j         |z   |dz
  k    S )a  Determine if there are no blank lines before the current token.

  The previous token is a docstring or comment. The prev_token_lineno is the
  start of the text of that token. Counting the number of newlines in its text
  gives us the extent and thus where the line number of the end of the
  docstring or comment. After that, we just compare it to the current token's
  line number to see if there are blank lines between them.

  Arguments:
    text: (unicode) The text of the docstring or comment before the current
      token.
    cur_token: (format_token.FormatToken) The current token in the unwrapped
      line.
    prev_token: (format_token.FormatToken) The previous token in the unwrapped
      line.

  Returns:
    True if there is no blank line before the current token.
  rN   r   rP   )rR   r   r&   rS   )text	cur_tokenrf   cur_token_linenonum_newliness        r   r   r     sj    ( % 4	--d333)3)>ED!!!A,		\	)-=-A	AAr   )FN).r   
__future__r   r   r   rn   lib2to3r   lib2to3.pgen2r   yapf.yapflibr   r   r   r	   r
   r   rD   r.   r/   r)   r,   r0   r2   r1   r-   r3   r8   r9   objectr   
namedtupler   r   r6   r   r   r   r    r   re   TWO_BLANK_LINESr   r   r   r   ry   r   r   <module>r     s    ( ' ' ' ' '      				             . . . . . . % % % % % % $ $ $ $ $ $ % % % % % %       ! ! ! ! ! !D0 D0 D0 D0NC C C   "2 "2 "2J  : : :6  <N N N
; ; ;
I I I2~ ~ ~B( ( (." " " " " " " "6 )+()9Iw;OPP $[#K%6$EG G
2 2 2j  @G G G& ! ! !B ) ) )r r rj- - -`B B B B Br   