identify_container.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. # Copyright 2018 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. """Identify containers for lib2to3 trees.
  15. This module identifies containers and the elements in them. Each element points
  16. to the opening bracket and vice-versa.
  17. IdentifyContainers(): the main function exported by this module.
  18. """
  19. from yapf_third_party._ylib2to3.pgen2 import token as grammar_token
  20. from yapf.pytree import pytree_utils
  21. from yapf.pytree import pytree_visitor
  22. def IdentifyContainers(tree):
  23. """Run the identify containers visitor over the tree, modifying it in place.
  24. Arguments:
  25. tree: the top-level pytree node to annotate with subtypes.
  26. """
  27. identify_containers = _IdentifyContainers()
  28. identify_containers.Visit(tree)
  29. class _IdentifyContainers(pytree_visitor.PyTreeVisitor):
  30. """_IdentifyContainers - see file-level docstring for detailed description."""
  31. def Visit_trailer(self, node): # pylint: disable=invalid-name
  32. for child in node.children:
  33. self.Visit(child)
  34. if len(node.children) != 3:
  35. return
  36. if node.children[0].type != grammar_token.LPAR:
  37. return
  38. if pytree_utils.NodeName(node.children[1]) == 'arglist':
  39. for child in node.children[1].children:
  40. pytree_utils.SetOpeningBracket(
  41. pytree_utils.FirstLeafNode(child), node.children[0])
  42. else:
  43. pytree_utils.SetOpeningBracket(
  44. pytree_utils.FirstLeafNode(node.children[1]), node.children[0])
  45. def Visit_atom(self, node): # pylint: disable=invalid-name
  46. for child in node.children:
  47. self.Visit(child)
  48. if len(node.children) != 3:
  49. return
  50. if node.children[0].type != grammar_token.LPAR:
  51. return
  52. for child in node.children[1].children:
  53. pytree_utils.SetOpeningBracket(
  54. pytree_utils.FirstLeafNode(child), node.children[0])