Salome HOME
Reverted some changes in salome build/run scripts.
[modules/shaper.git] / src / InitializationPlugin / InitializationPlugin_PyInterp.cpp
1 // Copyright (C) 2014-2017  CEA/DEN, EDF R&D
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or
18 // email : webmaster.salome@opencascade.com<mailto:webmaster.salome@opencascade.com>
19 //
20
21 #include <InitializationPlugin_PyInterp.h>
22
23 #include <string>
24 #include <stdexcept>
25 #include <clocale>
26
27 InitializationPlugin_PyInterp::InitializationPlugin_PyInterp()
28 : PyInterp_Interp()
29 {
30 }
31
32 InitializationPlugin_PyInterp::~InitializationPlugin_PyInterp()
33 {
34 }
35
36 const char* aSearchCode =
37   "import ast\n"
38   "class FindName(ast.NodeVisitor):\n"
39   "    def __init__(self, name):\n"
40   "        self.name = name\n"
41   "    def visit_Name(self, node):\n"
42   "        if node.id == self.name:\n"
43   "            positions.append((node.lineno, node.col_offset))\n"
44   "FindName(name).visit(ast.parse(expression))";
45
46 // make the expression be correct for the python interpreter even for the
47 // beta=alfa*2 expressions
48 static std::string adjustExpression(const std::string& theExpression) {
49   std::string anExpression = theExpression;
50   if (!anExpression.empty() && anExpression.back() == '=') {
51     anExpression = anExpression.substr(0, anExpression.length() - 1);
52   }
53   return anExpression;
54 }
55
56 std::list<std::pair<int, int> >
57 InitializationPlugin_PyInterp::positions(const std::string& theExpression,
58                                      const std::string& theName)
59 {
60   PyLockWrapper lck; // Acquire GIL until the end of the method
61
62   std::list<std::pair<int, int> > aResult;
63
64   // prepare a context
65   PyObject* aContext = PyDict_New();
66   PyObject* aBuiltinModule = PyImport_AddModule("__builtin__");
67   PyDict_SetItemString(aContext, "__builtins__", aBuiltinModule);
68
69   std::string anExpression = adjustExpression(theExpression);
70   // extend aContext with variables
71   PyDict_SetItemString(aContext, "expression", PyUnicode_FromString(anExpression.c_str()));
72   PyDict_SetItemString(aContext, "name", PyUnicode_FromString(theName.c_str()));
73   PyDict_SetItemString(aContext, "positions", Py_BuildValue("[]"));
74
75   // run the search code
76   PyObject* aExecResult = PyRun_String(aSearchCode, Py_file_input, aContext, aContext);
77   Py_XDECREF(aExecResult);
78
79   // receive results from context
80   PyObject* aPositions = PyDict_GetItemString(aContext, "positions");
81   for (int anIndex = 0; anIndex < PyList_Size(aPositions); ++anIndex) {
82     PyObject* aPosition = PyList_GetItem(aPositions, anIndex);
83     PyObject* aLineNo = PyTuple_GetItem(aPosition, 0);
84     PyObject* aColOffset = PyTuple_GetItem(aPosition, 1);
85
86     aResult.push_back(
87         std::pair<int, int>((int)PyLong_AsLong(aLineNo),
88                             (int)PyLong_AsLong(aColOffset)));
89   }
90
91   // TODO(spo): after this refCount of the variable is not 0. Is there memory leak?
92   Py_DECREF(aContext);
93
94   return aResult;
95 }
96
97
98 std::list<std::string> InitializationPlugin_PyInterp::compile(const std::string& theExpression)
99 {
100   PyLockWrapper lck; // Acquire GIL until the end of the method
101   std::list<std::string> aResult;
102   PyObject *aCodeopModule = PyImport_AddModule("codeop");
103   if(!aCodeopModule) { // Fatal error. No way to go on.
104     PyErr_Print();
105     return aResult;
106   }
107   // support "variable_name=" expression as "variable_name"
108   std::string anExpression = adjustExpression(theExpression);
109
110   PyObject *aCodePyObj =
111     PyObject_CallMethod(aCodeopModule, (char*)"compile_command", (char*)"(s)",
112                         anExpression.c_str());
113
114   if(!aCodePyObj || aCodePyObj == Py_None || !PyCode_Check(aCodePyObj)) {
115     Py_XDECREF(aCodePyObj);
116     return aResult;
117   }
118
119   PyCodeObject* aCodeObj = (PyCodeObject*) aCodePyObj;
120   std::string aCodeName(PyBytes_AsString(aCodeObj->co_code));
121   // co_names should be tuple, but can be changed in modern versions of python (>2.7.3)
122   if(!PyTuple_Check(aCodeObj->co_names)) {
123     return aResult;
124   }
125
126   size_t params_size = PyTuple_Size(aCodeObj->co_names);
127   if (params_size > 0) {
128     for (size_t i = 0; i < params_size; i++) {
129       PyObject* aParamObj = PyTuple_GetItem(aCodeObj->co_names, i);
130       PyObject* aParamObjStr = PyObject_Str(aParamObj);
131       std::string aParamName(PyUnicode_AsUTF8(aParamObjStr));
132       aResult.push_back(aParamName);
133       Py_XDECREF(aParamObjStr);
134     }
135   }
136   Py_XDECREF(aCodeObj);
137   return aResult;
138 }
139
140 void InitializationPlugin_PyInterp::extendLocalContext(const std::list<std::string>& theParameters)
141 {
142   PyLockWrapper lck; // Acquire GIL until the end of the method
143   if (theParameters.empty())
144     return;
145   std::list<std::string>::const_iterator it = theParameters.begin();
146   for ( ; it != theParameters.cend(); it++) {
147     std::string aParamValue = *it;
148     simpleRun(aParamValue.c_str(), false);
149   }
150 }
151
152 void InitializationPlugin_PyInterp::clearLocalContext()
153 {
154   PyLockWrapper lck;
155   PyDict_Clear(_local_context);
156 }
157
158 double InitializationPlugin_PyInterp::evaluate(const std::string& theExpression,
159                                                std::string& theError)
160 {
161   // support "variable_name=" expression as "variable_name"
162   std::string anExpression = adjustExpression(theExpression);
163
164   PyLockWrapper lck; // Acquire GIL until the end of the method
165   PyCompilerFlags aFlags = {CO_FUTURE_DIVISION};
166   aFlags.cf_flags = CO_FUTURE_DIVISION;
167   PyCodeObject* anExprCode = (PyCodeObject *) Py_CompileStringFlags(anExpression.c_str(),
168                                 "<string>", Py_eval_input, &aFlags);
169   if(!anExprCode) {
170     theError = errorMessage();
171     Py_XDECREF(anExprCode);
172     return 0.;
173   }
174
175   PyObject* anEvalResult = PyEval_EvalCode((PyObject *)anExprCode, _global_context, _local_context);
176   if(!anEvalResult) {
177     theError = errorMessage();
178     Py_XDECREF(anExprCode);
179     Py_XDECREF(anEvalResult);
180     return 0.;
181   }
182
183   PyObject* anEvalStrObj = PyObject_Str(anEvalResult);
184   std::string anEvalStr(PyUnicode_AsUTF8(anEvalStrObj));
185   Py_XDECREF(anExprCode);
186   Py_XDECREF(anEvalResult);
187   Py_XDECREF(anEvalStrObj);
188   double result = 0.;
189   try {
190     // set locale due to the #2485
191     std::string aCurLocale = std::setlocale(LC_NUMERIC, 0);
192     std::setlocale(LC_NUMERIC, "C");
193     result = std::stod(anEvalStr);
194     std::setlocale(LC_NUMERIC, aCurLocale.c_str());
195   }
196   catch (const std::invalid_argument&) {
197     theError = "Unable to eval " + anEvalStr;
198   }
199
200   return result;
201 }
202
203 std::string InitializationPlugin_PyInterp::errorMessage()
204 {
205   std::string aPyError;
206   if (PyErr_Occurred()) {
207     PyObject *pstr, *ptype, *pvalue, *ptraceback;
208     PyErr_Fetch(&ptype, &pvalue, &ptraceback);
209     PyErr_NormalizeException(&ptype, &pvalue, &ptraceback);
210     pstr = PyObject_Str(pvalue);
211     aPyError = std::string(PyUnicode_AsUTF8(pstr));
212     Py_XDECREF(pstr);
213     Py_XDECREF(ptype);
214     Py_XDECREF(pvalue);
215     Py_XDECREF(ptraceback);
216   }
217   return aPyError;
218 }
219
220 bool InitializationPlugin_PyInterp::initContext()
221 {
222   PyObject *m = PyImport_AddModule("__main__");  // interpreter main module (module context)
223   if(!m){
224     PyErr_Print();
225     return false;
226   }
227   _global_context = PyModule_GetDict(m);          // get interpreter global variable context
228   Py_INCREF(_global_context);
229   _local_context = PyDict_New();
230   Py_INCREF(_local_context);
231
232   return PyRun_SimpleString("from math import *") == 0;
233 }
234
235 void InitializationPlugin_PyInterp::closeContext()
236 {
237   Py_XDECREF(_local_context);
238   PyInterp_Interp::closeContext();
239 }