Salome HOME
Fix error on 'from . import'.
[modules/yacs.git] / src / py2yacs / py2yacs.py
1 #!/usr/bin/env python3
2 # -*- coding: utf-8 *-
3 # Copyright (C) 2007-2024  CEA, EDF
4 #
5 # This library is free software; you can redistribute it and/or
6 # modify it under the terms of the GNU Lesser General Public
7 # License as published by the Free Software Foundation; either
8 # version 2.1 of the License, or (at your option) any later version.
9 #
10 # This library is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13 # Lesser General Public License for more details.
14 #
15 # You should have received a copy of the GNU Lesser General Public
16 # License along with this library; if not, write to the Free Software
17 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
18 #
19 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
20 #
21 import ast
22
23 class FunctionProperties:
24   def __init__(self, function_name):
25     self.name = function_name
26     self.inputs=[]
27     self.outputs=None
28     self.errors=[]
29     self.imports=[]
30     pass
31   def __str__(self):
32     result = "Function:" + self.name + "\n"
33     result+= "  Inputs:" + str(self.inputs) + "\n"
34     result+= "  Outputs:"+ str(self.outputs) + "\n"
35     result+= "  Errors:" + str(self.errors) + "\n"
36     result+= "  Imports:"+ str(self.imports) + "\n"
37     return result
38
39 class VisitAST(ast.NodeVisitor):
40   def visit_Module(self, node):
41     accepted_tokens = ["Import", "ImportFrom", "FunctionDef", "ClassDef", "If"]
42     self.global_errors=[]
43     for e in node.body:
44       type_name = type(e).__name__
45       if type_name not in accepted_tokens:
46         error="py2yacs error at line %s: not accepted statement '%s'." % (
47                e.lineno, type_name)
48         self.global_errors.append(error)
49     self.functions=[]
50     self.lastfn=""
51     self.infunc=False
52     self.inargs=False
53     self.generic_visit(node)
54     pass
55   def visit_FunctionDef(self, node):
56     if not self.infunc:
57       self.lastfn = FunctionProperties(node.name)
58       self.functions.append(self.lastfn)
59       self.infunc=True
60       #
61       self.generic_visit(node)
62       #
63       self.lastfn = None
64       self.infunc=False
65     pass
66   def visit_arg(self, node):
67     self.lastfn.inputs.append(node.arg)
68     pass
69   def visit_Return(self, node):
70     if self.lastfn.outputs is not None :
71       error="py2yacs error at line %s: multiple returns." % node.lineno
72       self.lastfn.errors.append(error)
73       return
74     self.lastfn.outputs = []
75     if node.value is None :
76       pass
77     elif 'Tuple' == type(node.value).__name__ :
78       for e in node.value.elts:
79         if 'Name' == type(e).__name__ :
80           self.lastfn.outputs.append(e.id)
81         else :
82           error="py2yacs error at line %s: invalid type returned '%s'." % (
83                   node.lineno, type(e).__name__)
84           self.lastfn.errors.append(error)
85     else:
86       if 'Name' == type(node.value).__name__ :
87         self.lastfn.outputs.append(node.value.id)
88       else :
89         error="py2yacs error at line %s: invalid type returned '%s'." %(
90                   node.lineno, type(node.value).__name__)
91         self.lastfn.errors.append(error)
92         pass
93       pass
94     pass
95
96   def visit_ClassDef(self, node):
97     # just ignore classes
98     pass
99
100   def visit_Import(self, node):
101     if self.infunc:
102       for n in node.names:
103         self.lastfn.imports.append(n.name)
104   def visit_ImportFrom(self, node):
105     if self.infunc:
106       if node.module :
107         m=str(node.module)
108       else:
109         m=""
110       for n in node.names:
111         self.lastfn.imports.append(m+"."+n.name)
112
113 class vtest(ast.NodeVisitor):
114   def generic_visit(self, node):
115     ast.NodeVisitor.generic_visit(self, node)
116
117 def create_yacs_schema(text, fn_name, fn_args, fn_returns, file_name):
118   import pilot
119   import SALOMERuntime
120   SALOMERuntime.RuntimeSALOME_setRuntime()
121   runtime = pilot.getRuntime()
122   schema = runtime.createProc("schema")
123   node = runtime.createScriptNode("", "default_name")
124   schema.edAddChild(node)
125   fncall = "\n%s=%s(%s)\n"%(",".join(fn_returns),
126                             fn_name,
127                             ",".join(fn_args))
128   node.setScript(text+fncall)
129   td=schema.getTypeCode("double")
130   for p in fn_args:
131     newport = node.edAddInputPort(p, td)
132     newport.edInit(0.0)
133   for p in fn_returns:
134     node.edAddOutputPort(p, td)
135   myContainer=schema.createContainer("Py2YacsContainer")
136   node.setExecutionMode(pilot.InlineNode.REMOTE_STR)
137   node.setContainer(myContainer)
138   schema.saveSchema(file_name)
139
140 def get_properties(text_file):
141   try:
142     bt=ast.parse(text_file)
143   except SyntaxError as err:
144     import traceback
145     return [], ["".join(traceback.format_exception_only(SyntaxError,err))]
146   w=VisitAST()
147   w.visit(bt)
148   return w.functions, w.global_errors
149
150 def function_properties(python_path, fn_name):
151   """
152   python_path : path to a python file
153   fn_name : name of a function in the file
154   return : properties of the function. see class FunctionProperties
155   """
156   with open(python_path, 'r') as f:
157     text_file = f.read()
158   functions,errors = get_properties(text_file)
159   result = [fn for fn in functions if fn.name == fn_name]
160   if len(result) < 1:
161     raise Exception("Function not found: {}".format(fn_name))
162   result = result[0]
163   error_string = ""
164   if len(errors) > 0:
165     error_string += "Global errors in file {}\n".format(python_path)
166     error_string += '\n'.join(errors)
167     raise Exception(error_string)
168   if len(result.errors) > 0:
169     error_string += "Errors when parsing function {}\n".format(fn_name)
170     error_string += '\n'.join(result.errors)
171     raise Exception(error_string)
172   return result
173
174
175 def main(python_path, yacs_path, function_name="_exec"):
176   with open(python_path, 'r') as f:
177     text_file = f.read()
178   fn_name = function_name
179   functions,errors = get_properties(text_file)
180   error_string = ""
181   if len(errors) > 0:
182     error_string += "global errors:\n"
183     error_string += '\n'.join(errors)
184     return error_string
185   fn_properties = next((f for f in functions if f.name == fn_name), None)
186   if fn_properties is not None :
187     if not fn_properties.errors :
188       create_yacs_schema(text_file, fn_name,
189                          fn_properties.inputs, fn_properties.outputs,
190                          yacs_path)
191     else:
192       error_string += '\n'.join(fn_properties.errors)
193   else:
194     error_string += "Function not found:"
195     error_string += fn_name
196   return error_string
197
198 if __name__ == '__main__':
199   import argparse
200   parser = argparse.ArgumentParser(description="Generate a YACS schema from a python file containing a function to run.")
201   parser.add_argument("file", help='Path to the python file')
202   parser.add_argument("-o","--output",
203         help='Path to the output file (yacs_schema.xml by default)',
204         default='yacs_schema.xml')
205   parser.add_argument("-d","--def_name",
206         help='Name of the function to call in the yacs node (_exec by default)',
207         default='_exec')
208   args = parser.parse_args()
209   erreurs = main(args.file, args.output, args.def_name)
210   import sys
211   if len(erreurs) > 0:
212     print(erreurs)
213     sys.exit(1)
214   else:
215     sys.exit(0)