Debian Codegraph @

src/Base/Interpreter.h

raw
1 // SPDX-License-Identifier: LGPL-2.1-or-later
2
3 /***************************************************************************
4 * Copyright (c) 2002 Jürgen Riegel <[email protected]> *
5 * *
6 * This file is part of the FreeCAD CAx development system. *
7 * *
8 * This program is free software; you can redistribute it and/or modify *
9 * it under the terms of the GNU Library General Public License (LGPL) *
10 * as published by the Free Software Foundation; either version 2 of *
11 * the License, or (at your option) any later version. *
12 * for detail see the LICENCE text file. *
13 * *
14 * FreeCAD is distributed in the hope that it will be useful, *
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
17 * GNU Library General Public License for more details. *
18 * *
19 * You should have received a copy of the GNU Library General Public *
20 * License along with FreeCAD; if not, write to the Free Software *
21 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 *
22 * USA *
23 * *
24 ***************************************************************************/
25
26 #ifndef BASE_INTERPRETER_H
27 #define BASE_INTERPRETER_H
28
29 #if defined(_POSIX_C_SOURCE)
30 # undef _POSIX_C_SOURCE
31 #endif // (re-)defined in pyconfig.h
32 #if defined(_XOPEN_SOURCE)
33 # undef _XOPEN_SOURCE
34 #endif // (re-)defined in pyconfig.h
35
36 #include <FCConfig.h>
37
38 #ifdef FC_OS_MACOSX
39 # undef toupper
40 # undef tolower
41 # undef isupper
42 # undef islower
43 # undef isspace
44 # undef isalpha
45 # undef isalnum
46 #endif
47
48 #include <CXX/Extensions.hxx>
49 #include <list>
50 #include <string>
51 #include "Exception.h"
52
53
54 // NOLINTBEGIN
55 /** Helper macro to obtain callable from an object
56 *
57 * @param _pyobj: PyObject pointer
58 * @param _name: the callable string name
59 * @param _var: the callable variable to be assigned
60 *
61 * See FeaturePythonImp::init() for example usage
62 */
63 #define FC_PY_GetCallable(_pyobj, _name, _var) \
64 do { \
65 _var = Py::Object(); \
66 if (PyObject_HasAttrString(_pyobj, _name)) { \
67 Py::Object _obj(PyObject_GetAttrString(_pyobj, _name), true); \
68 if (_obj.isCallable()) \
69 _var = _obj; \
70 } \
71 } while (0)
72
73 /** Helper macro to obtain attribute from an object
74 *
75 * @param _pyobj: PyObject pointer
76 * @param _name: the attribute string name
77 * @param _var: the attribute variable to be assigned
78 *
79 * See FeaturePythonImp::init() for example usage
80 */
81 #define FC_PY_GetObject(_pyobj, _name, _var) \
82 do { \
83 _var = Py::Object(); \
84 if (PyObject_HasAttrString(_pyobj, _name)) \
85 _var = Py::asObject(PyObject_GetAttrString(_pyobj, _name)); \
86 } while (0)
87 // NOLINTEND
88
89
90 namespace Base
91 {
92
93
94 class BaseExport PyException: public Exception
95 {
96 public:
97 /// constructor does the whole job
98 PyException();
99 explicit PyException(const Py::Object& obj);
100 PyException(const PyException&) = default;
101 PyException(PyException&&) = default;
102 ~PyException() noexcept override;
103
104 PyException& operator=(const PyException&) = default;
105 PyException& operator=(PyException&&) = default;
106 void raiseException();
107
108 /// this method determines if the original exception
109 /// can be reconstructed or not, if yes throws the reconstructed version
110 /// if not, throws a generic PyException.
111 static void throwException();
112
113 /// this function returns the stack trace
114 const std::string& getStackTrace() const
115 {
116 return _stackTrace;
117 }
118 const std::string& getErrorType() const
119 {
120 return _errorType;
121 }
122 PyObject* getPyExceptionType() const override
123 {
124 return _exceptionType;
125 }
126 void reportException() const override;
127 /// Sets the Python error indicator and an error message
128 void setPyException() const override;
129
130 private:
131 std::string _stackTrace;
132 std::string _errorType;
133 PyObject* _exceptionType;
134 };
135
136 inline Py::Object pyCall(PyObject* callable, PyObject* args = nullptr)
137 {
138 PyObject* result = PyObject_CallObject(callable, args);
139 if (!result) {
140 throw Py::Exception();
141 }
142 return Py::asObject(result);
143 }
144
145 inline Py::Object pyCallWithKeywords(PyObject* callable, PyObject* args, PyObject* kwds = nullptr)
146 {
147 PyObject* result = PyObject_Call(callable, args, kwds);
148 if (!result) {
149 throw Py::Exception();
150 }
151 return Py::asObject(result);
152 }
153
154 /**
155 * The SystemExitException is thrown if the Python-internal PyExc_SystemExit exception
156 * was thrown.
157 * @author Werner Mayer
158 */
159 class BaseExport SystemExitException: public Exception
160 {
161 public:
162 SystemExitException();
163 SystemExitException(const SystemExitException&) = default;
164 SystemExitException(SystemExitException&&) = default;
165 ~SystemExitException() noexcept override = default;
166 SystemExitException& operator=(const SystemExitException&) = default;
167 SystemExitException& operator=(SystemExitException&&) = default;
168 long getExitCode() const
169 {
170 return _exitCode;
171 }
172
173 private:
174 long _exitCode;
175 };
176
177 /** If the application starts we release immediately the global interpreter lock
178 * (GIL) once the Python interpreter is initialized, i.e. no thread -- including
179 * the main thread doesn't hold the GIL. Thus, every thread must instantiate an
180 * object of PyGILStateLocker if it needs to access protected areas in Python or
181 * areas where the lock is needed. It's best to create the instance on the stack,
182 * not on the heap.
183 */
184 class BaseExport PyGILStateLocker
185 {
186 public:
187 PyGILStateLocker()
188 {
189 gstate = PyGILState_Ensure(); // NOLINT
190 }
191 ~PyGILStateLocker()
192 {
193 PyGILState_Release(gstate);
194 }
195
196 PyGILStateLocker(const PyGILStateLocker&) = delete;
197 PyGILStateLocker(PyGILStateLocker&&) = delete;
198 PyGILStateLocker& operator=(const PyGILStateLocker&) = delete;
199 PyGILStateLocker& operator=(PyGILStateLocker&&) = delete;
200
201 private:
202 PyGILState_STATE gstate;
203 };
204
205 /**
206 * If a thread holds the global interpreter lock (GIL) but runs a long operation
207 * in C where it doesn't need to hold the GIL it can release it temporarily. Or
208 * if the thread has to run code in the main thread where Python code may be
209 * executed it must release the GIL to avoid a deadlock. In either case the thread
210 * must hold the GIL when instantiating an object of PyGILStateRelease.
211 * As PyGILStateLocker it's best to create an instance of PyGILStateRelease on the
212 * stack.
213 */
214 class BaseExport PyGILStateRelease
215 {
216 public:
217 PyGILStateRelease()
218 {
219 // release the global interpreter lock
220 state = PyEval_SaveThread(); // NOLINT
221 }
222 ~PyGILStateRelease()
223 {
224 // grab the global interpreter lock again
225 PyEval_RestoreThread(state);
226 }
227
228 PyGILStateRelease(const PyGILStateRelease&) = delete;
229 PyGILStateRelease(PyGILStateRelease&&) = delete;
230 PyGILStateRelease& operator=(const PyGILStateRelease&) = delete;
231 PyGILStateRelease& operator=(PyGILStateRelease&&) = delete;
232
233 private:
234 PyThreadState* state;
235 };
236
237
238 /** The Interpreter class
239 * This class manage the python interpreter and hold a lot
240 * helper functions for handling python stuff
241 */
242 class BaseExport InterpreterSingleton
243 {
244 public:
245 InterpreterSingleton();
246 ~InterpreterSingleton();
247
248 InterpreterSingleton(const InterpreterSingleton&) = delete;
249 InterpreterSingleton(InterpreterSingleton&&) = delete;
250 InterpreterSingleton& operator=(const InterpreterSingleton&) = delete;
251 InterpreterSingleton& operator=(InterpreterSingleton&&) = delete;
252
253 /** @name execution methods
254 */
255 //@{
256 /// Run a statement on the python interpreter and gives back a string with the representation of
257 /// the result.
258 std::string runString(const char* psCmd);
259 /// Run a statement on the python interpreter with a key for exchanging strings
260 std::string runStringWithKey(const char* psCmd, const char* key, const char* key_initial_value = "");
261 /// Run a statement on the python interpreter and return back the result object.
262 Py::Object runStringObject(const char* sCmd);
263 /// Run a statement on the python interpreter and gives back a string with the representation of
264 /// the result.
265 void runInteractiveString(const char* psCmd);
266 /// Run file (script) on the python interpreter
267 void runFile(const char* pxFileName, bool local);
268 /// Run a statement with arguments on the python interpreter
269 void runStringArg(const char* psCom, ...);
270 /// runs a python object method with no return value and no arguments
271 void runMethodVoid(PyObject* pobject, const char* method);
272 /// runs a python object method which returns a arbitrary object
273 PyObject* runMethodObject(PyObject* pobject, const char* method);
274 /// runs a python method with arbitrary params
275 void runMethod(
276 PyObject* pobject,
277 const char* method,
278 const char* resfmt = nullptr,
279 void* cresult = nullptr,
280 const char* argfmt = "()",
281 ...
282 );
283 //@}
284
285 /** @name Module handling
286 */
287 //@{
288 /* Loads a module
289 */
290 bool loadModule(const char* psModName);
291 /// Add an additional python path
292 void addPythonPath(const char* Path);
293 /// Get the path (replaces the deprecated Py_GetPath method)
294 std::string getPythonPath();
295 static void addType(PyTypeObject* Type, PyObject* Module, const char* Name);
296 /// Add a module and return a PyObject to it
297 PyObject* addModule(Py::ExtensionModuleBase*);
298 /// Clean-up registered modules
299 void cleanupModules();
300 //@}
301
302 /** @name Cleanup
303 */
304 //@{
305 /** Register a cleanup function to be called by finalize(). The cleanup function will be called
306 * with no arguments and should return no value. At most 32 cleanup functions can be registered.
307 * When the registration is successful 0 is returned; on failure -1 is returned. The cleanup
308 * function registered last is called first. Each cleanup function will be called at most once.
309 * Since Python's internal finalization will have completed before the cleanup function, no
310 * Python APIs should be called by \a func.
311 */
312 int cleanup(void (*func)());
313 /** This calls the registered cleanup functions. @see cleanup() for more details. */
314 void finalize();
315 /// This shuts down the application.
316 void systemExit();
317 //@}
318
319 /** @name startup and singletons
320 */
321 //@{
322 /// init the interpreter and returns the module search path
323 std::string init(int argc, char* argv[]);
324 int runCommandLine(const char* prompt);
325 void replaceStdOutput();
326 static InterpreterSingleton& Instance();
327 static void Destruct();
328 //@}
329
330 /** @name external wrapper libs
331 * here we can access external dynamically loaded wrapper libs
332 * done e.g. by SWIG or SIP
333 */
334 //@{
335 /// generate a SWIG object
336 PyObject* createSWIGPointerObj(const char* Module, const char* TypeName, void* Pointer, int own);
337 bool convertSWIGPointerObj(
338 const char* Module,
339 const char* TypeName,
340 PyObject* obj,
341 void** ptr,
342 int flags
343 );
344 void cleanupSWIG(const char* TypeName);
345 PyTypeObject* getSWIGPointerTypeObj(const char* Module, const char* TypeName);
346 //@}
347
348 /** @name methods for debugging facility
349 */
350 //@{
351 /// sets the file name which should be debugged
352 void dbgObserveFile(const char* sFileName = "");
353 //@}
354
355
356 /** @name static helper functions
357 */
358 //@{
359 /// replaces all char with escapes for usage in python console
360 static std::string strToPython(const char* Str);
361 static std::string strToPython(const std::string& Str)
362 {
363 return strToPython(Str.c_str());
364 }
365 //@}
366
367 PyObject* getValue(const char* key, const char* result_var);
368
369 protected:
370 // singleton
371 static InterpreterSingleton* _pcSingleton;
372
373 private:
374 std::string _cDebugFileName;
375 PyThreadState* _global;
376 std::list<Py::ExtensionModuleBase*> _modules;
377 };
378
379
380 /** Access to the InterpreterSingleton object
381 * This method is used to gain access to the one and only instance of
382 * the InterpreterSingleton class.
383 */
384 inline InterpreterSingleton& Interpreter()
385 {
386 return InterpreterSingleton::Instance();
387 }
388
389 } // namespace Base
390
391 #endif // BASE_INTERPRETER_H