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