You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

forward_call.py 3.8 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. # Copyright 2020 Huawei Technologies Co., Ltd
  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. # ============================================================================
  15. """Find out forward functions of script file"""
  16. import ast
  17. import pasta
  18. class ForwardCall(ast.NodeVisitor):
  19. """
  20. AST visitor that processes forward calls.
  21. Find the sub functions called by the forward function in the script file.
  22. """
  23. def __init__(self, ast_tree):
  24. self._tree = ast_tree
  25. self._name_stack = []
  26. self._forward_stack = []
  27. self.calls = {} # key is function name, value is forward function ast node.
  28. self._function_list = {} # key is function name, value is function ast node.
  29. self.process()
  30. def process(self):
  31. """visit ast tree to find the forward functions."""
  32. self.visit(self._tree)
  33. # first visit to find out all functions, so restores all variables except _function_list
  34. self._name_stack.clear()
  35. self._forward_stack.clear()
  36. self.calls.clear()
  37. self.visit(self._tree)
  38. def get_current_namespace(self):
  39. """Get the namespace when visit the AST node"""
  40. namespace = '.'.join(self._name_stack)
  41. return namespace
  42. @classmethod
  43. def get_call_name(cls, node):
  44. """Get functional call name."""
  45. if not isinstance(node, ast.Call):
  46. return None
  47. return pasta.dump(node.func)
  48. def visit_ClassDef(self, node):
  49. """Callback function when visit AST tree"""
  50. self._name_stack.append(node.name)
  51. self.generic_visit(node)
  52. self._name_stack.pop()
  53. def visit_FunctionDef(self, node):
  54. """Callback function when visit AST tree"""
  55. namespace = self.get_current_namespace()
  56. if namespace:
  57. func_name = f'{namespace}.{node.name}'
  58. else:
  59. func_name = node.name
  60. func_name = f'{self.get_current_namespace()}.{node.name}'
  61. is_in_chain = func_name in self.calls or node.name == 'forward'
  62. if is_in_chain:
  63. self._forward_stack.append(func_name)
  64. if node.name == 'forward':
  65. self.calls.update({func_name: node})
  66. self._function_list.update({func_name: node})
  67. self.generic_visit(node)
  68. if is_in_chain:
  69. self._forward_stack.pop()
  70. def visit_Call(self, node):
  71. """Callback function when visit AST tree"""
  72. for arg in node.args:
  73. self.visit(arg)
  74. for keyword in node.keywords:
  75. self.visit(keyword.value)
  76. func_name = self.get_call_name(node)
  77. if isinstance(node.func, ast.Name):
  78. if func_name not in ['super', 'str', 'repr']:
  79. if self._forward_stack:
  80. self.calls.update({func_name: self._function_list.get(func_name)})
  81. self.visit(node.func)
  82. else:
  83. if self._forward_stack:
  84. if func_name.startswith('self.'):
  85. whole_name = f'{self.get_current_namespace()}.{func_name.split(".")[-1]}'
  86. self.calls.update({whole_name: self._function_list.get(whole_name)})
  87. else:
  88. self.calls.update({func_name: self._function_list.get(func_name)})
  89. self.visit(node.func)