1 // Copyright (C) 2014-2022 CEA/DEN, EDF R&D
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.
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.
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
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
20 #include <InitializationPlugin_PyInterp.h>
22 #include <Locale_Convert.h>
29 InitializationPlugin_PyInterp::InitializationPlugin_PyInterp()
34 InitializationPlugin_PyInterp::~InitializationPlugin_PyInterp()
38 const char* aSearchCode =
40 "class FindName(ast.NodeVisitor):\n"
41 " def __init__(self, name):\n"
43 " def visit_Name(self, node):\n"
44 " if node.id == self.name:\n"
45 " positions.append((node.lineno, node.col_offset))\n"
46 "FindName(name).visit(ast.parse(expression))";
48 // make the expression be correct for the python interpreter even for the
49 // beta=alfa*2 expressions
50 static std::wstring adjustExpression(const std::wstring& theExpression) {
51 std::wstring anExpression = theExpression;
52 if (!anExpression.empty() && anExpression.back() == L'=') {
53 anExpression = anExpression.substr(0, anExpression.length() - 1);
58 std::list<std::pair<int, int> >
59 InitializationPlugin_PyInterp::positions(const std::wstring& theExpression,
60 const std::wstring& theName)
62 PyLockWrapper lck; // Acquire GIL until the end of the method
64 std::list<std::pair<int, int> > aResult;
67 PyObject* aContext = PyDict_New();
68 PyDict_SetItemString(aContext, "__builtins__", PyEval_GetBuiltins());
70 std::wstring anExpression = adjustExpression(theExpression);
71 // extend aContext with variables
72 PyDict_SetItemString(aContext, "expression",
73 PyUnicode_FromWideChar(anExpression.c_str(), anExpression.size()));
74 PyDict_SetItemString(aContext, "name", PyUnicode_FromWideChar(theName.c_str(), theName.size()));
75 PyDict_SetItemString(aContext, "positions", Py_BuildValue("[]"));
77 // run the search code
78 PyObject* aExecResult = PyRun_String(aSearchCode, Py_file_input, aContext, aContext);
79 Py_XDECREF(aExecResult);
81 // receive results from context
82 PyObject* aPositions = PyDict_GetItemString(aContext, "positions");
83 for (int anIndex = 0; anIndex < PyList_Size(aPositions); ++anIndex) {
84 PyObject* aPosition = PyList_GetItem(aPositions, anIndex);
85 PyObject* aLineNo = PyTuple_GetItem(aPosition, 0);
86 PyObject* aColOffset = PyTuple_GetItem(aPosition, 1);
89 std::pair<int, int>((int)PyLong_AsLong(aLineNo),
90 (int)PyLong_AsLong(aColOffset)));
93 // TODO(spo): after this refCount of the variable is not 0. Is there memory leak?
100 std::list<std::wstring> InitializationPlugin_PyInterp::compile(const std::wstring& theExpression)
102 PyLockWrapper lck; // Acquire GIL until the end of the method
103 std::list<std::wstring> aResult;
104 PyObject *aCodeopModule = PyImport_AddModule("codeop");
105 if(!aCodeopModule) { // Fatal error. No way to go on.
109 // support "variable_name=" expression as "variable_name"
110 std::wstring anExpression = adjustExpression(theExpression);
112 PyObject *aCodePyObj =
113 PyObject_CallMethod(aCodeopModule, (char*)"compile_command", (char*)"(s)",
114 Locale::Convert::toString(anExpression).c_str());
116 if(!aCodePyObj || aCodePyObj == Py_None || !PyCode_Check(aCodePyObj)) {
117 Py_XDECREF(aCodePyObj);
121 PyCodeObject* aCodeObj = (PyCodeObject*) aCodePyObj;
122 #if PY_VERSION_HEX >= 0x030B0000
123 std::string aCodeName(PyBytes_AsString(PyObject_GetAttrString((PyObject *)(aCodeObj), "co_code")));
125 std::string aCodeName(PyBytes_AsString(aCodeObj->co_code));
127 // co_names should be tuple, but can be changed in modern versions of python (>2.7.3)
128 if(!PyTuple_Check(aCodeObj->co_names)) {
132 size_t params_size = PyTuple_Size(aCodeObj->co_names);
133 if (params_size > 0) {
134 for (size_t i = 0; i < params_size; i++) {
135 PyObject* aParamObj = PyTuple_GetItem(aCodeObj->co_names, i);
136 PyObject* aParamObjStr = PyObject_Str(aParamObj);
138 std::wstring aParamName(PyUnicode_AsWideCharString(aParamObjStr, &aSize));
139 aResult.push_back(aParamName);
140 Py_XDECREF(aParamObjStr);
143 Py_XDECREF(aCodeObj);
147 void InitializationPlugin_PyInterp::extendLocalContext(const std::list<std::wstring>& theParameters)
149 PyLockWrapper lck; // Acquire GIL until the end of the method
150 if (theParameters.empty())
152 std::list<std::wstring>::const_iterator it = theParameters.begin();
153 for ( ; it != theParameters.cend(); it++) {
154 std::string aParamValue = Locale::Convert::toString(*it);
155 simpleRun(aParamValue.c_str(), false);
159 void InitializationPlugin_PyInterp::clearLocalContext()
162 PyDict_Clear(_local_context);
165 double InitializationPlugin_PyInterp::evaluate(const std::wstring& theExpression,
166 std::string& theError)
168 // support "variable_name=" expression as "variable_name"
169 std::wstring anExpression = adjustExpression(theExpression);
171 PyLockWrapper lck; // Acquire GIL until the end of the method
172 PyCompilerFlags aFlags = {CO_FUTURE_DIVISION};
173 aFlags.cf_flags = CO_FUTURE_DIVISION;
174 PyCodeObject* anExprCode = (PyCodeObject *) Py_CompileStringFlags(
175 Locale::Convert::toString(anExpression).c_str(),
176 "<string>", Py_eval_input, &aFlags);
178 theError = errorMessage();
179 Py_XDECREF(anExprCode);
183 PyObject* anEvalResult = PyEval_EvalCode((PyObject *)anExprCode, _global_context, _local_context);
185 theError = errorMessage();
186 Py_XDECREF(anExprCode);
187 Py_XDECREF(anEvalResult);
191 PyObject* anEvalStrObj = PyObject_Str(anEvalResult);
192 std::string anEvalStr(PyUnicode_AsUTF8(anEvalStrObj));
193 Py_XDECREF(anExprCode);
194 Py_XDECREF(anEvalResult);
195 Py_XDECREF(anEvalStrObj);
198 // set locale due to the #2485
199 std::string aCurLocale = std::setlocale(LC_NUMERIC, 0);
200 std::setlocale(LC_NUMERIC, "C");
201 result = std::stod(anEvalStr);
202 std::setlocale(LC_NUMERIC, aCurLocale.c_str());
204 catch (const std::invalid_argument&) {
205 theError = "Unable to eval " + anEvalStr;
211 std::string InitializationPlugin_PyInterp::errorMessage()
213 std::string aPyError;
214 if (PyErr_Occurred()) {
215 PyObject *pstr, *ptype, *pvalue, *ptraceback;
216 PyErr_Fetch(&ptype, &pvalue, &ptraceback);
217 PyErr_NormalizeException(&ptype, &pvalue, &ptraceback);
218 pstr = PyObject_Str(pvalue);
219 aPyError = std::string(PyUnicode_AsUTF8(pstr));
223 Py_XDECREF(ptraceback);
228 bool InitializationPlugin_PyInterp::initContext()
230 PyObject *m = PyImport_AddModule("__main__"); // interpreter main module (module context)
235 _global_context = PyModule_GetDict(m); // get interpreter global variable context
236 Py_INCREF(_global_context);
237 _local_context = PyDict_New();
238 Py_INCREF(_local_context);
240 return PyRun_SimpleString("from math import *") == 0;
243 void InitializationPlugin_PyInterp::closeContext()
245 Py_XDECREF(_local_context);
246 PyInterp_Interp::closeContext();
249 bool InitializationPlugin_PyInterp::runString(std::string theString)
251 PyLockWrapper lck; // Acquire GIL until the end of the method
252 return PyRun_SimpleString(theString.c_str());