Mantid
Loading...
Searching...
No Matches
CodeExecution.cpp
Go to the documentation of this file.
1// Mantid Repository : https://github.com/mantidproject/mantid
2//
3// Copyright © 2020 ISIS Rutherford Appleton Laboratory UKRI,
4// NScD Oak Ridge National Laboratory, European Spallation Source,
5// Institut Laue - Langevin & CSNS, Institute of High Energy Physics, CAS
6// SPDX - License - Identifier: GPL - 3.0 +
11#include <QHash>
12#include <QString>
13#include <frameobject.h>
14
16
17namespace {
18
19struct ScriptEditorDetails {
20 ScriptEditor *editor;
21 int lineOffset;
22};
23
24// Map co_filename objects from PyCodeObject to an editor object
26
39int traceLineNumber(PyObject *obj, PyFrameObject *frame, int event, PyObject *arg) {
40 Q_UNUSED(obj);
41 Q_UNUSED(arg);
42 if (event != PyTrace_LINE)
43 return 0;
44 auto iter = EDITOR_LOOKUP.constFind(frame->f_code->co_filename);
45 if (iter != EDITOR_LOOKUP.constEnd()) {
46 const auto &details = iter.value();
47 int lineLoc = frame->f_lineno + details.lineOffset;
48 details.editor->updateProgressMarkerFromThread(lineLoc, false);
49 }
50 return 0;
51}
52} // namespace
53
55
61CodeExecution::CodeExecution(ScriptEditor *editor) : m_editor(editor) {}
62
71PyObject *CodeExecution::execute(const QString &codeStr, const QString &filename, int flags, PyObject *globals,
72 int lineOffset) const {
74 PyCompilerFlags compileFlags;
75 compileFlags.cf_flags = flags;
76 auto compiledCode =
77 Py_CompileStringFlags(codeStr.toUtf8().constData(), filename.toUtf8().constData(), Py_file_input, &compileFlags);
78 if (!compiledCode) {
79 return nullptr;
80 }
81
82 if (!m_editor) {
83 return PyEval_EvalCode(CODE_OBJECT(compiledCode), globals, globals);
84 }
85
86 ScriptEditorDetails editor_details{m_editor, lineOffset};
87 const auto coFileObject = ((PyCodeObject *)compiledCode)->co_filename;
88 const auto posIter = EDITOR_LOOKUP.insert(coFileObject, editor_details);
89 PyEval_SetTrace((Py_tracefunc)&traceLineNumber, nullptr);
90 const auto result = PyEval_EvalCode(CODE_OBJECT(compiledCode), globals, globals);
91 PyEval_SetTrace(nullptr, nullptr);
92 EDITOR_LOOKUP.erase(posIter);
93 return result;
94
95} // namespace MantidQt::Widgets::Common::Python
96
97} // namespace MantidQt::Widgets::Common::Python
double obj
the value of the quadratic function
#define CODE_OBJECT(x)
Definition: VersionCompat.h:28
CodeExecution(ScriptEditor *editor)
Construct a LineTrackingExecutor for a given editor.
PyObject * execute(const QString &codeStr, const QString &filename, int flags, PyObject *globals, int lineOffset) const
Execute the code string from the given filename and return the result.
Defines a structure for acquiring/releasing the Python GIL using the RAII pattern.
This class provides an area to write scripts.
Definition: ScriptEditor.h:37