Salome HOME
Copyright update 2021
[modules/yacs.git] / src / py2yacs / py2yacs.py
index 028e47c01f0c45a74b0c3fa643d718fe7e94014a..8bf41d4a5df8a0a9e90f0d6f98d314c2ecc8babf 100644 (file)
@@ -1,9 +1,6 @@
 #!/usr/bin/env python3
 # -*- coding: utf-8 *-
-# Copyright (C) 2007-2019  CEA/DEN, EDF R&D, OPEN CASCADE
-#
-# Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
-# CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
+# Copyright (C) 2007-2021  CEA/DEN, EDF R&D
 #
 # This library is free software; you can redistribute it and/or
 # modify it under the terms of the GNU Lesser General Public
@@ -39,9 +36,9 @@ class FunctionProperties:
     result+= "  Imports:"+ str(self.imports) + "\n"
     return result
 
-class v(ast.NodeVisitor):
+class VisitAST(ast.NodeVisitor):
   def visit_Module(self, node):
-    accepted_tokens = ["Import", "ImportFrom", "FunctionDef", "ClassDef"]
+    accepted_tokens = ["Import", "ImportFrom", "FunctionDef", "ClassDef", "If"]
     self.global_errors=[]
     for e in node.body:
       type_name = type(e).__name__
@@ -138,11 +135,40 @@ def create_yacs_schema(text, fn_name, fn_args, fn_returns, file_name):
   schema.saveSchema(file_name)
 
 def get_properties(text_file):
-  bt=ast.parse(text_file)
-  w=v()
+  try:
+    bt=ast.parse(text_file)
+  except SyntaxError as err:
+    import traceback
+    return [], ["".join(traceback.format_exception_only(SyntaxError,err))]
+  w=VisitAST()
   w.visit(bt)
   return w.functions, w.global_errors
 
+def function_properties(python_path, fn_name):
+  """
+  python_path : path to a python file
+  fn_name : name of a function in the file
+  return : properties of the function. see class FunctionProperties
+  """
+  with open(python_path, 'r') as f:
+    text_file = f.read()
+  functions,errors = get_properties(text_file)
+  result = [fn for fn in functions if fn.name == fn_name]
+  if len(result) < 1:
+    raise Exception("Function not found: {}".format(fn_name))
+  result = result[0]
+  error_string = ""
+  if len(errors) > 0:
+    error_string += "Global errors in file {}\n".format(python_path)
+    error_string += '\n'.join(errors)
+    raise Exception(error_string)
+  if len(result.errors) > 0:
+    error_string += "Errors when parsing function {}\n".format(fn_name)
+    error_string += '\n'.join(result.errors)
+    raise Exception(error_string)
+  return result
+
+
 def main(python_path, yacs_path, function_name="_exec"):
   with open(python_path, 'r') as f:
     text_file = f.read()