pytree_unwrapper.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  1. # Copyright 2015 Google Inc. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """PyTreeUnwrapper - produces a list of logical lines from a pytree.
  15. [for a description of what a logical line is, see logical_line.py]
  16. This is a pytree visitor that goes over a parse tree and produces a list of
  17. LogicalLine containers from it, each with its own depth and containing all the
  18. tokens that could fit on the line if there were no maximal line-length
  19. limitations.
  20. Note: a precondition to running this visitor and obtaining correct results is
  21. for the tree to have its comments spliced in as nodes. Prefixes are ignored.
  22. For most uses, the convenience function UnwrapPyTree should be sufficient.
  23. """
  24. # The word "token" is overloaded within this module, so for clarity rename
  25. # the imported pgen2.token module.
  26. from yapf_third_party._ylib2to3 import pytree
  27. from yapf_third_party._ylib2to3.pgen2 import token as grammar_token
  28. from yapf.pytree import pytree_utils
  29. from yapf.pytree import pytree_visitor
  30. from yapf.pytree import split_penalty
  31. from yapf.yapflib import format_token
  32. from yapf.yapflib import logical_line
  33. from yapf.yapflib import object_state
  34. from yapf.yapflib import style
  35. from yapf.yapflib import subtypes
  36. _OPENING_BRACKETS = frozenset({'(', '[', '{'})
  37. _CLOSING_BRACKETS = frozenset({')', ']', '}'})
  38. def UnwrapPyTree(tree):
  39. """Create and return a list of logical lines from the given pytree.
  40. Arguments:
  41. tree: the top-level pytree node to unwrap..
  42. Returns:
  43. A list of LogicalLine objects.
  44. """
  45. unwrapper = PyTreeUnwrapper()
  46. unwrapper.Visit(tree)
  47. llines = unwrapper.GetLogicalLines()
  48. llines.sort(key=lambda x: x.lineno)
  49. return llines
  50. # Grammar tokens considered as whitespace for the purpose of unwrapping.
  51. _WHITESPACE_TOKENS = frozenset([
  52. grammar_token.NEWLINE, grammar_token.DEDENT, grammar_token.INDENT,
  53. grammar_token.ENDMARKER
  54. ])
  55. class PyTreeUnwrapper(pytree_visitor.PyTreeVisitor):
  56. """PyTreeUnwrapper - see file-level docstring for detailed description.
  57. Note: since this implements PyTreeVisitor and node names in lib2to3 are
  58. underscore_separated, the visiting methods of this class are named as
  59. Visit_node_name. invalid-name pragmas are added to each such method to silence
  60. a style warning. This is forced on us by the usage of lib2to3, and re-munging
  61. method names to make them different from actual node names sounded like a
  62. confusing and brittle affair that wasn't worth it for this small & controlled
  63. deviation from the style guide.
  64. To understand the connection between visitor methods in this class, some
  65. familiarity with the Python grammar is required.
  66. """
  67. def __init__(self):
  68. # A list of all logical lines finished visiting so far.
  69. self._logical_lines = []
  70. # Builds up a "current" logical line while visiting pytree nodes. Some nodes
  71. # will finish a line and start a new one.
  72. self._cur_logical_line = logical_line.LogicalLine(0)
  73. # Current indentation depth.
  74. self._cur_depth = 0
  75. def GetLogicalLines(self):
  76. """Fetch the result of the tree walk.
  77. Note: only call this after visiting the whole tree.
  78. Returns:
  79. A list of LogicalLine objects.
  80. """
  81. # Make sure the last line that was being populated is flushed.
  82. self._StartNewLine()
  83. return self._logical_lines
  84. def _StartNewLine(self):
  85. """Finish current line and start a new one.
  86. Place the currently accumulated line into the _logical_lines list and
  87. start a new one.
  88. """
  89. if self._cur_logical_line.tokens:
  90. self._logical_lines.append(self._cur_logical_line)
  91. _MatchBrackets(self._cur_logical_line)
  92. _IdentifyParameterLists(self._cur_logical_line)
  93. _AdjustSplitPenalty(self._cur_logical_line)
  94. self._cur_logical_line = logical_line.LogicalLine(self._cur_depth)
  95. _STMT_TYPES = frozenset({
  96. 'if_stmt',
  97. 'while_stmt',
  98. 'for_stmt',
  99. 'try_stmt',
  100. 'expect_clause',
  101. 'with_stmt',
  102. 'match_stmt',
  103. 'case_block',
  104. 'funcdef',
  105. 'classdef',
  106. })
  107. # pylint: disable=invalid-name,missing-docstring
  108. def Visit_simple_stmt(self, node):
  109. # A 'simple_stmt' conveniently represents a non-compound Python statement,
  110. # i.e. a statement that does not contain other statements.
  111. # When compound nodes have a single statement as their suite, the parser
  112. # can leave it in the tree directly without creating a suite. But we have
  113. # to increase depth in these cases as well. However, don't increase the
  114. # depth of we have a simple_stmt that's a comment node. This represents a
  115. # standalone comment and in the case of it coming directly after the
  116. # funcdef, it is a "top" comment for the whole function.
  117. # TODO(eliben): add more relevant compound statements here.
  118. single_stmt_suite = (
  119. node.parent and pytree_utils.NodeName(node.parent) in self._STMT_TYPES)
  120. is_comment_stmt = pytree_utils.IsCommentStatement(node)
  121. is_inside_match = node.parent and pytree_utils.NodeName(
  122. node.parent) == 'match_stmt'
  123. if (single_stmt_suite and not is_comment_stmt) or is_inside_match:
  124. self._cur_depth += 1
  125. self._StartNewLine()
  126. self.DefaultNodeVisit(node)
  127. if (single_stmt_suite and not is_comment_stmt) or is_inside_match:
  128. self._cur_depth -= 1
  129. def _VisitCompoundStatement(self, node, substatement_names):
  130. """Helper for visiting compound statements.
  131. Python compound statements serve as containers for other statements. Thus,
  132. when we encounter a new compound statement, we start a new logical line.
  133. Arguments:
  134. node: the node to visit.
  135. substatement_names: set of node names. A compound statement will be
  136. recognized as a NAME node with a name in this set.
  137. """
  138. for child in node.children:
  139. # A pytree is structured in such a way that a single 'if_stmt' node will
  140. # contain all the 'if', 'elif' and 'else' nodes as children (similar
  141. # structure applies to 'while' statements, 'try' blocks, etc). Therefore,
  142. # we visit all children here and create a new line before the requested
  143. # set of nodes.
  144. if (child.type == grammar_token.NAME and
  145. child.value in substatement_names):
  146. self._StartNewLine()
  147. self.Visit(child)
  148. _IF_STMT_ELEMS = frozenset({'if', 'else', 'elif'})
  149. def Visit_if_stmt(self, node): # pylint: disable=invalid-name
  150. self._VisitCompoundStatement(node, self._IF_STMT_ELEMS)
  151. _WHILE_STMT_ELEMS = frozenset({'while', 'else'})
  152. def Visit_while_stmt(self, node): # pylint: disable=invalid-name
  153. self._VisitCompoundStatement(node, self._WHILE_STMT_ELEMS)
  154. _FOR_STMT_ELEMS = frozenset({'for', 'else'})
  155. def Visit_for_stmt(self, node): # pylint: disable=invalid-name
  156. self._VisitCompoundStatement(node, self._FOR_STMT_ELEMS)
  157. _TRY_STMT_ELEMS = frozenset({'try', 'except', 'else', 'finally'})
  158. def Visit_try_stmt(self, node): # pylint: disable=invalid-name
  159. self._VisitCompoundStatement(node, self._TRY_STMT_ELEMS)
  160. _EXCEPT_STMT_ELEMS = frozenset({'except'})
  161. def Visit_except_clause(self, node): # pylint: disable=invalid-name
  162. self._VisitCompoundStatement(node, self._EXCEPT_STMT_ELEMS)
  163. _FUNC_DEF_ELEMS = frozenset({'def'})
  164. def Visit_funcdef(self, node): # pylint: disable=invalid-name
  165. self._VisitCompoundStatement(node, self._FUNC_DEF_ELEMS)
  166. def Visit_async_funcdef(self, node): # pylint: disable=invalid-name
  167. self._StartNewLine()
  168. index = 0
  169. for child in node.children:
  170. index += 1
  171. self.Visit(child)
  172. if child.type == grammar_token.ASYNC:
  173. break
  174. for child in node.children[index].children:
  175. self.Visit(child)
  176. _CLASS_DEF_ELEMS = frozenset({'class'})
  177. def Visit_classdef(self, node): # pylint: disable=invalid-name
  178. self._VisitCompoundStatement(node, self._CLASS_DEF_ELEMS)
  179. def Visit_async_stmt(self, node): # pylint: disable=invalid-name
  180. self._StartNewLine()
  181. index = 0
  182. for child in node.children:
  183. index += 1
  184. self.Visit(child)
  185. if child.type == grammar_token.ASYNC:
  186. break
  187. for child in node.children[index].children:
  188. if child.type == grammar_token.NAME and child.value == 'else':
  189. self._StartNewLine()
  190. self.Visit(child)
  191. def Visit_decorator(self, node): # pylint: disable=invalid-name
  192. for child in node.children:
  193. self.Visit(child)
  194. if child.type == grammar_token.COMMENT and child == node.children[0]:
  195. self._StartNewLine()
  196. def Visit_decorators(self, node): # pylint: disable=invalid-name
  197. for child in node.children:
  198. self._StartNewLine()
  199. self.Visit(child)
  200. def Visit_decorated(self, node): # pylint: disable=invalid-name
  201. for child in node.children:
  202. self._StartNewLine()
  203. self.Visit(child)
  204. _WITH_STMT_ELEMS = frozenset({'with'})
  205. def Visit_with_stmt(self, node): # pylint: disable=invalid-name
  206. self._VisitCompoundStatement(node, self._WITH_STMT_ELEMS)
  207. _MATCH_STMT_ELEMS = frozenset({'match', 'case'})
  208. def Visit_match_stmt(self, node): # pylint: disable=invalid-name
  209. self._VisitCompoundStatement(node, self._MATCH_STMT_ELEMS)
  210. # case_block refers to the grammar element name in Grammar.txt
  211. _CASE_BLOCK_ELEMS = frozenset({'case'})
  212. def Visit_case_block(self, node):
  213. self._cur_depth += 1
  214. self._StartNewLine()
  215. self._VisitCompoundStatement(node, self._CASE_BLOCK_ELEMS)
  216. self._cur_depth -= 1
  217. def Visit_suite(self, node): # pylint: disable=invalid-name
  218. # A 'suite' starts a new indentation level in Python.
  219. self._cur_depth += 1
  220. self._StartNewLine()
  221. self.DefaultNodeVisit(node)
  222. self._cur_depth -= 1
  223. def Visit_listmaker(self, node): # pylint: disable=invalid-name
  224. _DetermineMustSplitAnnotation(node)
  225. self.DefaultNodeVisit(node)
  226. def Visit_dictsetmaker(self, node): # pylint: disable=invalid-name
  227. _DetermineMustSplitAnnotation(node)
  228. self.DefaultNodeVisit(node)
  229. def Visit_import_as_names(self, node): # pylint: disable=invalid-name
  230. if node.prev_sibling.value == '(':
  231. _DetermineMustSplitAnnotation(node)
  232. self.DefaultNodeVisit(node)
  233. def Visit_testlist_gexp(self, node): # pylint: disable=invalid-name
  234. _DetermineMustSplitAnnotation(node)
  235. self.DefaultNodeVisit(node)
  236. def Visit_arglist(self, node): # pylint: disable=invalid-name
  237. _DetermineMustSplitAnnotation(node)
  238. self.DefaultNodeVisit(node)
  239. def Visit_typedargslist(self, node): # pylint: disable=invalid-name
  240. _DetermineMustSplitAnnotation(node)
  241. self.DefaultNodeVisit(node)
  242. def Visit_subscriptlist(self, node): # pylint: disable=invalid-name
  243. _DetermineMustSplitAnnotation(node)
  244. self.DefaultNodeVisit(node)
  245. def DefaultLeafVisit(self, leaf):
  246. """Default visitor for tree leaves.
  247. A tree leaf is always just gets appended to the current logical line.
  248. Arguments:
  249. leaf: the leaf to visit.
  250. """
  251. if leaf.type in _WHITESPACE_TOKENS:
  252. self._StartNewLine()
  253. elif leaf.type != grammar_token.COMMENT or leaf.value.strip():
  254. # Add non-whitespace tokens and comments that aren't empty.
  255. self._cur_logical_line.AppendToken(
  256. format_token.FormatToken(leaf, pytree_utils.NodeName(leaf)))
  257. _BRACKET_MATCH = {')': '(', '}': '{', ']': '['}
  258. def _MatchBrackets(line):
  259. """Visit the node and match the brackets.
  260. For every open bracket ('[', '{', or '('), find the associated closing bracket
  261. and "match" them up. I.e., save in the token a pointer to its associated open
  262. or close bracket.
  263. Arguments:
  264. line: (LogicalLine) A logical line.
  265. """
  266. bracket_stack = []
  267. for token in line.tokens:
  268. if token.value in _OPENING_BRACKETS:
  269. bracket_stack.append(token)
  270. elif token.value in _CLOSING_BRACKETS:
  271. bracket_stack[-1].matching_bracket = token
  272. token.matching_bracket = bracket_stack[-1]
  273. bracket_stack.pop()
  274. for bracket in bracket_stack:
  275. if id(pytree_utils.GetOpeningBracket(token.node)) == id(bracket.node):
  276. bracket.container_elements.append(token)
  277. token.container_opening = bracket
  278. def _IdentifyParameterLists(line):
  279. """Visit the node to create a state for parameter lists.
  280. For instance, a parameter is considered an "object" with its first and last
  281. token uniquely identifying the object.
  282. Arguments:
  283. line: (LogicalLine) A logical line.
  284. """
  285. func_stack = []
  286. param_stack = []
  287. for tok in line.tokens:
  288. # Identify parameter list objects.
  289. if subtypes.FUNC_DEF in tok.subtypes:
  290. assert tok.next_token.value == '('
  291. func_stack.append(tok.next_token)
  292. continue
  293. if func_stack and tok.value == ')':
  294. if tok == func_stack[-1].matching_bracket:
  295. func_stack.pop()
  296. continue
  297. # Identify parameter objects.
  298. if subtypes.PARAMETER_START in tok.subtypes:
  299. param_stack.append(tok)
  300. # Not "elif", a parameter could be a single token.
  301. if param_stack and subtypes.PARAMETER_STOP in tok.subtypes:
  302. start = param_stack.pop()
  303. func_stack[-1].parameters.append(object_state.Parameter(start, tok))
  304. def _AdjustSplitPenalty(line):
  305. """Visit the node and adjust the split penalties if needed.
  306. A token shouldn't be split if it's not within a bracket pair. Mark any token
  307. that's not within a bracket pair as "unbreakable".
  308. Arguments:
  309. line: (LogicalLine) An logical line.
  310. """
  311. bracket_level = 0
  312. for index, token in enumerate(line.tokens):
  313. if index and not bracket_level:
  314. pytree_utils.SetNodeAnnotation(token.node,
  315. pytree_utils.Annotation.SPLIT_PENALTY,
  316. split_penalty.UNBREAKABLE)
  317. if token.value in _OPENING_BRACKETS:
  318. bracket_level += 1
  319. elif token.value in _CLOSING_BRACKETS:
  320. bracket_level -= 1
  321. def _DetermineMustSplitAnnotation(node):
  322. """Enforce a split in the list if the list ends with a comma."""
  323. if style.Get('DISABLE_ENDING_COMMA_HEURISTIC'):
  324. return
  325. if not _ContainsComments(node):
  326. token = next(node.parent.leaves())
  327. if token.value == '(':
  328. if sum(1 for ch in node.children if ch.type == grammar_token.COMMA) < 2:
  329. return
  330. if (not isinstance(node.children[-1], pytree.Leaf) or
  331. node.children[-1].value != ','):
  332. return
  333. num_children = len(node.children)
  334. index = 0
  335. _SetMustSplitOnFirstLeaf(node.children[0])
  336. while index < num_children - 1:
  337. child = node.children[index]
  338. if isinstance(child, pytree.Leaf) and child.value == ',':
  339. next_child = node.children[index + 1]
  340. if next_child.type == grammar_token.COMMENT:
  341. index += 1
  342. if index >= num_children - 1:
  343. break
  344. _SetMustSplitOnFirstLeaf(node.children[index + 1])
  345. index += 1
  346. def _ContainsComments(node):
  347. """Return True if the list has a comment in it."""
  348. if isinstance(node, pytree.Leaf):
  349. return node.type == grammar_token.COMMENT
  350. for child in node.children:
  351. if _ContainsComments(child):
  352. return True
  353. return False
  354. def _SetMustSplitOnFirstLeaf(node):
  355. """Set the "must split" annotation on the first leaf node."""
  356. pytree_utils.SetNodeAnnotation(
  357. pytree_utils.FirstLeafNode(node), pytree_utils.Annotation.MUST_SPLIT,
  358. True)