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.3 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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 os
  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, filename):
  24. self.filename = filename
  25. self.module_name = os.path.basename(filename).replace('.py', '')
  26. self.name_stack = []
  27. self.forward_stack = []
  28. self.calls = set()
  29. self.process()
  30. def process(self):
  31. """Parse the python source file to find the forward functions."""
  32. with open(self.filename, 'rt', encoding='utf-8') as file:
  33. content = file.read()
  34. self.visit(ast.parse(content, self.filename))
  35. def get_current_namespace(self):
  36. """Get the namespace when visit the AST node"""
  37. namespace = '.'.join(self.name_stack)
  38. return namespace
  39. @classmethod
  40. def get_ast_node_name(cls, node):
  41. """Get AST node name."""
  42. if isinstance(node, ast.Attribute):
  43. return f'{cls.get_ast_node_name(node.value)}.{node.attr}'
  44. if isinstance(node, ast.Name):
  45. return node.id
  46. return node
  47. def visit_ClassDef(self, node):
  48. """Callback function when visit AST tree"""
  49. self.name_stack.append(node.name)
  50. self.generic_visit(node)
  51. self.name_stack.pop()
  52. def visit_FunctionDef(self, node):
  53. """Callback function when visit AST tree"""
  54. func_name = f'{self.get_current_namespace()}.{node.name}'
  55. is_in_chain = func_name in self.calls or node.name == 'forward'
  56. if is_in_chain:
  57. self.forward_stack.append(func_name)
  58. if node.name == 'forward':
  59. self.calls.add(func_name)
  60. self.generic_visit(node)
  61. if is_in_chain:
  62. self.forward_stack.pop()
  63. def visit_Call(self, node):
  64. """Callback function when visit AST tree"""
  65. for arg in node.args:
  66. self.visit(arg)
  67. for kw in node.keywords:
  68. self.visit(kw.value)
  69. func_name = self.get_ast_node_name(node.func)
  70. if isinstance(node.func, ast.Name):
  71. if func_name not in ['super', 'str', 'repr']:
  72. if self.forward_stack:
  73. self.calls.add(func_name)
  74. self.visit(node.func)
  75. else:
  76. if self.forward_stack:
  77. if 'self' in func_name:
  78. self.calls.add(f'{self.get_current_namespace()}.{func_name.split(".")[-1]}')
  79. else:
  80. self.calls.add(func_name)
  81. self.visit(node.func)