
    ?dCn                        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.y),a  Decide what the format for the code should be.

The `logical_line.LogicalLine`s are now ready to be formatted. LogicalLInes 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)pytree_utils)format_decision_state)format_token)line_joiner)style)verifierc                 l   g }d}t        j                  d      }t        |       D ]v  }|j                  }t	        ||j
                  ||       ||j
                  z  }t        j                  ||      }	|	j                          |j                  s|j                  j                  r4|j                  j                  j                         |j                  _        nI|j                  j                  r3|j                  j                  j                         |j                  _        |r-|j                  r!t        |j                  |j                  |       t        d |j                   D              rt#        |       |j                  st%        |      r$t'        |       t)        |||       t+        |	       nt-        |      st/        |      rt)        |||       t+        |	       nt1        |      rIt        d |j                   D              s-|	j2                  ru|	j5                  dd       |	j2                  r nTt7        |	      sIt        j                  ||      }	|	j                          t'        |       t)        ||d       t+        |	       |j9                  |       |}y t;        |       t=        ||      S )ah  Reformat the logical lines.

  Arguments:
    llines: (list of logical_line.LogicalLine) 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   4   K   | ]  }|j                     y wN
is_comment.0toks     :/usr/lib/python3/dist-packages/yapf/yapflib/reformatter.py	<genexpr>zReformat.<locals>.<genexpr>I   s     4S^^4   c              3   4   K   | ]  }|j                     y wr   )must_break_beforer   s     r   r   zReformat.<locals>.<genexpr>W   s       2K69 362G2G 2Kr   Fnewlinedry_run)r
   Get_SingleOrMergedLinesfirst_FormatFirstTokendepthr   FormatDecisionStateMoveStateToNextTokendisabler   valuerstriplast+_RetainRequiredVerticalSpacingBetweenTokensanytokens$_RetainVerticalSpacingBeforeComments_LineHasContinuationMarkers_RetainHorizontalSpacing_RetainRequiredVerticalSpacing_EmitLineUnformatted%_LineContainsPylintDisableLineTooLong_LineContainsI18n_CanPlaceOnSingleLine
next_tokenAddTokenToState_AnalyzeSolutionSpaceappend_AlignTrailingComments_FormatFinalLines)
llinesverifylinesfinal_lines	prev_lineindent_widthllinefirst_token
indent_amtstates
             r   ReformatrC   '   s!    +)>*,#F+ 0e++Kk5;;	;G+J!55eZHE	 ==			!KK--446::   ::++224

	y(( 	4EKK49	;	4u||4	4,U3}}3E:u%$UIu=5!
/
6
E
"$UIu=5!	u	%c 2K=B\\2K /K eU;  #5) $77zJe  "u%$UIt<5!uIa0d %	;	//    c                     | j                   D ]2  }|j                  | j                  j                  | j                         4 y)z-Retain all horizontal spacing between tokens.N)r*   RetainHorizontalSpacingr   columnr!   )liner   s     r   r-   r-   m   s3    [[ ?c

 1 14::>?rD   c                     d}||j                   }| j                  r
t               }| j                  D ]  }t	        |||       |} y)z*Retain all vertical spacing between lines.N)r'   r$   setr*   r(   )cur_liner=   r;   prev_tokcur_toks        r   r.   r.   s   sL    (~~H EE g/5IHrD   c                 h   |y|j                   r)|j                  |j                  j                  d      z   }nR|j                  r:|j
                  j                  s|j
                  j                  }n|j                  }n|j                  }| j                  r)| j                  | j                  j                  d      z
  }n| j                  }|j                  s9|j                  j                  d      r||j                  j                  d      z  }||z
  }| j                  r|j                  sns|rq|j                  t        ||dz               rS| j                  j                  d      }t        |dz   |      }t        |j                  |            }t        ||z
  |      }| j                  |       y)zDRetain vertical spacing between two tokens if not in editable range.N
\   )	is_stringlinenor%   count	is_pseudoprevious_tokenis_multiline_stringr   endswithintersectionrangewhitespace_prefixlenmaxAdjustNewlinesBefore)	rM   rL   r;   prev_lineno
cur_linenorequired_newlinesdesired_newlineswhitespace_linesdeletable_liness	            r   r(   r(      sm   
//HNN$8$8$>>K""66++22kOOk//K'--"5"5d";;JJ			!8!8!>8>>''--K ;. 3 3##E+zA~$FG0066t<[1_j9%,,-=>?O-?,. 
01rD   c                     d}| j                   D ]_  }|j                  rO|rM|j                  |j                  j	                  d      z
  |j                  z
  dkD  r|j                  t               |}a y)z(Retain vertical spacing before comments.NrO   rQ   )r*   r   rS   r%   rT   r^   ONE_BLANK_LINE)rH   
prev_tokenr   s      r   r+   r+      s_    *[[ c
~~*	ciiood+	+j.?.?	?!	C  0JrD   c                 ^   | j                   r| j                   j                  }|j                  }|j                  s|j                  r||j
                  j                  d      z  }|j                  rd}n| j                   j                  |kD  }| j                  |d       | j                   ryy)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.
  rO   Fr   N)	r3   rV   rS   rW   rR   r%   rT   is_continuationr4   )rB   rV   previous_linenor   s       r   r/   r/      s     	%%44N$++O))^-E-E--33D99o%%g  ''/9g	'59 	rD   c                    t        j                  d      rS| j                  D ]D  }|j                  st	        j
                  t        j                  d      |j                        sD y t        j                  d      rxt        | j                        }t        |dz
        D ]R  }| j                  |dz      j                  dk(  s#| j                  |   j                  t        j                  d      v sR y y)ao  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:
    line: (logical_line.LogicalLine) The line currently being formatted.

  Returns:
    True if the line contains i18n comments or function calls. False otherwise.
  I18N_COMMENTTI18N_FUNCTION_CALLrQ   (F)	r
   r   r*   r   rematchr%   r\   rZ   )rH   r   lengthindexs       r   r1   r1      s     YY~{{ 	BHHUYY~%>		J
 YY#$Fvz" 
++eai
 
&
&#
-
++e

"
"eii0D&E
E 
rD   c                 V    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)ro   searchr'   r%   rH   s    r   r0   r0      s    	9499??	KKrD   c                 :    t        d | j                  D              S )z7Return true if the line has continuation markers in it.c              3   4   K   | ]  }|j                     y wr   )ri   r   s     r   r   z._LineHasContinuationMarkers.<locals>.<genexpr>   s     8SS  8r   )r)   r*   ru   s    r   r,   r,      s    	8DKK8	88rD   c                    | j                   D cg c]  }|j                   }}t        j                  d      rd|v ryt        j                  d      | j                  z  }| j
                  }d}|j                  s|j                  s|j                  r|j                  }d}|y|j                  |z   t        j                  d	      k  xr  t        d
 | j                   d| D               S c c}w )zDetermine if the logical line can go on a single line.

  Arguments:
    line: (logical_line.LogicalLine) The line currently being formatted.

  Returns:
    True if the line can or should be added to a single line. False otherwise.
  FORCE_MULTILINE_DICTLBRACEFr   NTCOLUMN_LIMITc              3   4   K   | ]  }|j                     y wr   r   r   s     r   r   z(_CanPlaceOnSingleLine.<locals>.<genexpr>	  s     ES#..Er   )r*   namer
   r   r!   r'   is_pylint_commentis_pytype_commentis_copybara_commentrV   total_lengthr)   )rH   xtoken_namesrA   r'   
last_indexs         r   r2   r2      s     "&-A-+-ii&'H,Cyy(4::5*	$*
 6 6
DJ	\


j
(EIIn,E
E FEDKK,DEE
EG .s   C*c                    d}|t        |       k  rB| |   }|j                  sJ d}|j                  D ]  }|j                  st        |j                  t
              s,|j                  j                  d      sHg }d}	 |t        |      z   t        |       k(  rn.| |t        |      z      }|j                  sJ |r)|j                  d   j                  j                  d      rn|j                  r|j                  g        d}g }	|j                  D ]  }
|
j                  }|j                  d      }|dk7  rt        |t        |            }d}||d	z   d
 }|
j                  r|	j                  t        |             k|dj                  ||
j                        z  } |	rt        |t        |	            }|j                  |	       J|dz  }d
}|j                  D ]  }||kD  s	|} n ||}t        |      D ]+  \  }}	|	s
| ||z      }d}|j                  D ]  }
|
j                  s|t        |	      k  sJ |	|   |k  sJ d||	|   z
  d	z
  z  }|d	z  }g }t        |
j                  j                  d            D ]B  \  }}|j                  dj                  ||j!                                      |dk(  s;d|d	z
  z  }D dj#                  |      }|
j                  j%                  d      }|j                  |      r|t        |      d
 }||
_         |t        |	      k(  r,J  |t        |      z  }d} n |s|d	z  }|t        |       k  rAy
y
)z+Align trailing comments to the same column.r   F#Tz

 rO   r{   rQ   Nz{}{}    )r\   r*   r   
isinstancespaces_required_beforelistr%   
startswithformatted_whitespace_prefixr$   r6   rfindr]   format	enumeratesplitstripjoinlstrip)r<   final_lines_indexrH   processed_contentr   all_pc_line_lengthsmax_line_length	this_lineline_contentpc_line_lengthsline_tokr[   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   r7   r7     s   C,,()D;;;{{ r
..Z(B(BDI
))

s
# !%8!99S=MM!"3c:M6N"NO) !!
!!!q!==HHP&&r* ,/#** Oh ( D D-33D9M" #OS5F Gol"3MA4E4F"G""$$S%67fmm,=x~~NNlO !/33GHO

$
$_
5S X 	1 77 	M_,'K	
 '+ ;D;! )	>6% !"36O"OP)!"
#** ,h"")C,@@@@$%9:[HHH 0D EEIKj"a'"l6?..&&t,7. 72$l##FMM*2>2D2D2F%H I &*"kAo6*7 "YY|4l
 44;;DA ) (()CD+C0J,K,LM+hn?,B &_)==
==S)	>V 	S!455 erh 1w 	C,,rD   c                    g }| D ]$  }g }|j                   D ]  }|j                  s7|j                  |j                         |j                  |j                         F|j
                  j                  j                  d      rl|j
                  j                  j                  d      r|j                  j                  dk(  s|j
                  j                  dvs|j                  d        |j                  dj                  |             |st        j                  |d          ' dj                  |      dz   S )z2Compose the final output from the finalized lines.rO   r   :z,}])r   r{   )r*   rU   r6   r   r%   r3   r[   r   rV   r   r   
VerifyCode)r<   r:   formatted_coderH   formatted_liner   s         r   r8   r8     s   . .dN{{ %]]c==>cii(00;;DA00;;C@$$+NN  .



$% "''.12.,-.  
	 4	''rD   c                       e Zd ZdZd Zd Zy)
_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                 J    |j                         | _        || _        || _        y r   )ClonerB   r   previous)selfrB   r   r   s       r   __init__z_StateNode.__init__  s    DJDLDMrD   c                 N    dj                  | j                  | j                        S )Nz%StateNode(state=[
{0}
], newline={1}))r   rB   r   )r   s    r   __repr__z_StateNode.__repr__  s"    4;;

DLL" "rD   N)__name__
__module____qualname____doc__r   r    rD   r   r   r     s    
"rD   r   OrderedPenaltypenaltyrT   	QueueItemordered_penalty
state_nodec           	      r   d}t               }g }t        | dd      }t        j                  |t	        t        d|      |             |dz  }|r|d   }|j                  j                  }|j                  }|j                  j                  snt        j                  |       |dkD  rd|j                  _        t        |      }|j                  |j                         |t        |      k(  rt        ||d||      }t        ||d||      }|r|syt!        | t        j                  |      j                         y)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   FNrQ   i'  T)rJ   r   heapqheappush
_QueueItem_OrderedPenaltyr   r   r   rB   r3   heappopignore_stack_for_comparisonr\   add_AddNextStateToQueue_ReconstructPath)initial_staterT   seenp_queuenodeitemr   before_seen_counts           r   r5   r5     s    %	$' 
M5$	/$..*_Q%>EF1*%1:D""**G??D::  	MM'u}/3djj, D	HHTZZCI% !$ugFE $eWEE- 	0 
=%--"8"C"CD	rD   c           	      N   |j                   j                         }|r|j                   j                  |      s|S |s|r|S t        |j                   ||      }| |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   
must_splitrQ   )	rB   	MustSplitCanSplitr   r4   r   r   r   r   )r   previous_noder   rT   r   r   r   s          r   r   r     s    " "",,.*]((11*=L	ZL	M''-	@$	TZZ''t
 ( < <'..*_We%DdKL	rD   c                     t        j                         }|j                  r*|j                  |       |j                  }|j                  r*|D ]  }| j	                  |j
                  d       ! y)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   
appendleftr4   r   )r   currentpathr   s       r   r   r     sg     
			$OOGG 	  Gd!!$,,!FGrD   c           	      *   t         r3t         d   |kD  r't         j                          t         rt         d   |kD  r'd}t        |       r-t         s|ga n#t         d   |k  rd}t         j                  |       | j	                  t        | ||||      |       y)a  Format the first token in the logical line.

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

  Arguments:
    first_token: (format_token.FormatToken) The first token in the logical line.
    indent_depth: (int) The line's indentation depth.
    prev_line: (list of logical_line.LogicalLine) The logical line previous to
      this line.
    final_lines: (list of logical_line.LogicalLine) The logical lines that have
      already been processed.
  r{   FT)indent_levelN)NESTED_DEPTHpop_IsClassOrDefr6   AddWhitespacePrefix_CalculateNumberOfNewlines)r@   indent_depthr=   r<   first_nesteds        r   r    r    4  s     	b)L8 	b)L8 ,;"^l	b	L	(l,'!! lI!,l< " !rD   rQ   r      c                     | j                   dv ry| j                  xr* | j                   dk(  xr | j                  j                   dk(  S )N>   defclass@Tasyncr   )r%   r3   )r   s    r   r   r   Y  sE    YY''
.. (SYY'1 (
..

%
')rD   c                    || j                   d| _         y| j                  rz|j                  j                  dk(  rt	        j
                  d      rt        S |j                  j                  j                  d      rt	        j
                  d      rt        S t        S | j                  r2|s0|j                  j                  dv rdt	        j
                  d	      z   S |j                  }|j                  rz|s&| j                  d
v rdt	        j
                  d      z   S |r-t	        j
                  d      st        |       rd| _         t        S t        |j                  | |      rt        S t        S t        |       rA|s|j                  j                  d      dk(  }|j                  s|j                   r|st        |j                  | |      rt#        |      dz
  }|dkD  r||dz
     j                   sn|dz  }|dkD  r||dz
     j                  j                  dk(  r#||   j                  j%                  t               n'|j%                  dt	        j
                  d      z          | j                   d| _         t        S t        |j                        r$|r"t	        j
                  d      sd| _         t        S | j                   r)| j&                  | j                  j                  d      z
  }n| j&                  }|j&                  }	|j(                  r|	|j                  j                  d      z  }	||	z
  dkD  rt        S t        S )a2  Calculate the number of newlines we need to add.

  Arguments:
    first_token: (format_token.FormatToken) The first token in the logical
      line.
    indent_depth: (int) The line's indentation depth.
    prev_line: (list of logical_line.LogicalLine) The logical line previous to
      this line.
    final_lines: (list of logical_line.LogicalLine) The logical 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importrQ   3BLANK_LINES_BETWEEN_TOP_LEVEL_IMPORTS_AND_VARIABLES>   r   r   r   'BLANK_LINES_AROUND_TOP_LEVEL_DEFINITION%BLANK_LINE_BEFORE_NESTED_CLASS_OR_DEFrO   r   )newlinesis_docstringr   r%   r
   r   rf   r   NO_BLANK_LINESis_namer'   r   _NoBlankLinesBeforeCurrentTokenr[   rT   r$   r   r\   r^   rS   rW   )
r@   r   r=   r<   r   prev_last_tokenis_inline_commentrr   first_token_linenoprev_last_token_linenos
             r   r   r   `  s   &  '!k(		56
//


*
*3
/
))8
9 22 
?A A A NN/!![..2KK DEEEII=>k"!k&'<'<k'68; );;AA$G1LO$>$>*?+@+@++:< k"Q&%	uqy)44QJE 	 #))//36$$99.I00EIIGHHJ!!-#'K 
	y	'	eii
13# $++k.?.?.E.Ed.KK$++*11((o3399$??0014	rD   c              #     K   d}d}|t        |       k  r| |   j                  r| |   }|dz  }|t        |       k  r|j                  j                  dz   }| |   j                  |j                  k7  rn|j                  j
                  dk7  rlt        j                  t        j                  dd|j                  |ff      }|j                  t        j                  |t        j                  |                   | |   j                  D ]  }|j                  |        |dz  }|t        |       k  r| nt!        j"                  | |d	 |      rt| |dz      }|j                  D ]  }| |   j                  |        t        |j                        dk(  r |j$                  j&                  r
d
| |   _        | |    |dz  }d
}n| |    |dz  }d}|t        |       k  ry	y	w)a  Generate the lines we want to format.

  Arguments:
    lines: (list of logical_line.LogicalLine) 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   FrQ   r   r   ;r   )typer%   contextNT)r\   r$   r'   rG   rS   r%   r   Leafr   SEMIAppendTokenr   FormatTokenr   NodeNamer*   r	   CanMergeMultipleLinesr   rW   )r;   rr   last_was_mergedrH   rG   leafr   	next_lines           r   r   r     s     %/E
U|5\dqjeCJ!!A%<$++-
99??c!::S2V7L2MO$


&&t\-B-B4-HIK<&& 	 C


3
	 
 CJ j		*	*5=/	J 	"i!! &#e  %&
i
1
$)L)L  $e%Lqjeo%LqjeoC 	E
s   D/G$2B.G$"G$c                     |j                   }|j                  r||j                  j                  d      z  }|j                  s| j                  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 logical line.
    prev_token: (format_token.FormatToken) The previous token in the logical
      line.

  Returns:
    True if there is no blank line before the current token.
  rO   r   rQ   )rS   r   r%   rT   )text	cur_tokenrg   cur_token_linenonum_newliness        r   r   r     sg    & %%	--d33)3)>)>D!A,			\	)-=-A	AArD   )FN)/r   
__future__r   r   r   ro   lib2to3r   lib2to3.pgen2r   yapf.pytreer   yapf.yapflibr   r   r	   r
   r   rC   r-   r.   r(   r+   r/   r1   r0   r,   r2   r7   r8   objectr   
namedtupler   r   r5   r   r   r   r    r   rf   TWO_BLANK_LINESr   r   r   r   r   rD   r   <module>r     s   (   	   $ . % $  !C0L? "2J:66L
9
G2~B(," "6 )+(()9Iw;OP $[##K%6$EG
5p@G& !@ )l^-`BrD   