xref: /llvm-project/lldb/source/Plugins/ScriptInterpreter/Python/PythonDataObjects.h (revision c154f397eeb86ea1a5b8fa46405104ace962cec3)
1 //===-- PythonDataObjects.h--------------------------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 //
10 // !! FIXME FIXME FIXME !!
11 //
12 // Python APIs nearly all can return an exception.   They do this
13 // by returning NULL, or -1, or some such value and setting
14 // the exception state with PyErr_Set*().   Exceptions must be
15 // handled before further python API functions are called.   Failure
16 // to do so will result in asserts on debug builds of python.
17 // It will also sometimes, but not usually result in crashes of
18 // release builds.
19 //
20 // Nearly all the code in this header does not handle python exceptions
21 // correctly.  It should all be converted to return Expected<> or
22 // Error types to capture the exception.
23 //
24 // Everything in this file except functions that return Error or
25 // Expected<> is considered deprecated and should not be
26 // used in new code.  If you need to use it, fix it first.
27 //
28 //
29 // TODOs for this file
30 //
31 // * Make all methods safe for exceptions.
32 //
33 // * Eliminate method signatures that must translate exceptions into
34 //   empty objects or NULLs.   Almost everything here should return
35 //   Expected<>.   It should be acceptable for certain operations that
36 //   can never fail to assert instead, such as the creation of
37 //   PythonString from a string literal.
38 //
39 // * Eliminate Reset(), and make all non-default constructors private.
40 //   Python objects should be created with Retain<> or Take<>, and they
41 //   should be assigned with operator=
42 //
43 // * Eliminate default constructors, make python objects always
44 //   nonnull, and use optionals where necessary.
45 //
46 
47 
48 #ifndef LLDB_PLUGINS_SCRIPTINTERPRETER_PYTHON_PYTHONDATAOBJECTS_H
49 #define LLDB_PLUGINS_SCRIPTINTERPRETER_PYTHON_PYTHONDATAOBJECTS_H
50 
51 #include "lldb/Host/Config.h"
52 
53 #if LLDB_ENABLE_PYTHON
54 
55 // LLDB Python header must be included first
56 #include "lldb-python.h"
57 
58 #include "lldb/Host/File.h"
59 #include "lldb/Utility/StructuredData.h"
60 
61 #include "llvm/ADT/ArrayRef.h"
62 
63 namespace lldb_private {
64 namespace python {
65 
66 class PythonObject;
67 class PythonBytes;
68 class PythonString;
69 class PythonList;
70 class PythonDictionary;
71 class PythonInteger;
72 class PythonException;
73 
74 class GIL {
75 public:
76   GIL() {
77     m_state = PyGILState_Ensure();
78     assert(!PyErr_Occurred());
79   }
80   ~GIL() { PyGILState_Release(m_state); }
81 
82 protected:
83   PyGILState_STATE m_state;
84 };
85 
86 enum class PyObjectType {
87   Unknown,
88   None,
89   Boolean,
90   Integer,
91   Dictionary,
92   List,
93   String,
94   Bytes,
95   ByteArray,
96   Module,
97   Callable,
98   Tuple,
99   File
100 };
101 
102 enum class PyRefType {
103   Borrowed, // We are not given ownership of the incoming PyObject.
104             // We cannot safely hold it without calling Py_INCREF.
105   Owned     // We have ownership of the incoming PyObject.  We should
106             // not call Py_INCREF.
107 };
108 
109 
110 // Take a reference that you already own, and turn it into
111 // a PythonObject.
112 //
113 // Most python API methods will return a +1 reference
114 // if they succeed or NULL if and only if
115 // they set an exception.   Use this to collect such return
116 // values, after checking for NULL.
117 //
118 // If T is not just PythonObject, then obj must be already be
119 // checked to be of the correct type.
120 template <typename T> T Take(PyObject *obj) {
121   assert(obj);
122   assert(!PyErr_Occurred());
123   T thing(PyRefType::Owned, obj);
124   assert(thing.IsValid());
125   return thing;
126 }
127 
128 // Retain a reference you have borrowed, and turn it into
129 // a PythonObject.
130 //
131 // A minority of python APIs return a borrowed reference
132 // instead of a +1.   They will also return NULL if and only
133 // if they set an exception.   Use this to collect such return
134 // values, after checking for NULL.
135 //
136 // If T is not just PythonObject, then obj must be already be
137 // checked to be of the correct type.
138 template <typename T> T Retain(PyObject *obj) {
139   assert(obj);
140   assert(!PyErr_Occurred());
141   T thing(PyRefType::Borrowed, obj);
142   assert(thing.IsValid());
143   return thing;
144 }
145 
146 // This class can be used like a utility function to convert from
147 // a llvm-friendly Twine into a null-terminated const char *,
148 // which is the form python C APIs want their strings in.
149 //
150 // Example:
151 // const llvm::Twine &some_twine;
152 // PyFoo_Bar(x, y, z, NullTerminated(some_twine));
153 //
154 // Why a class instead of a function?  If the twine isn't already null
155 // terminated, it will need a temporary buffer to copy the string
156 // into.   We need that buffer to stick around for the lifetime of the
157 // statement.
158 class NullTerminated {
159   const char *str;
160   llvm::SmallString<32> storage;
161 
162 public:
163   NullTerminated(const llvm::Twine &twine) {
164     llvm::StringRef ref = twine.toNullTerminatedStringRef(storage);
165     str = ref.begin();
166   }
167   operator const char *() { return str; }
168 };
169 
170 inline llvm::Error nullDeref() {
171   return llvm::createStringError(llvm::inconvertibleErrorCode(),
172                                  "A NULL PyObject* was dereferenced");
173 }
174 
175 inline llvm::Error exception(const char *s = nullptr) {
176   return llvm::make_error<PythonException>(s);
177 }
178 
179 inline llvm::Error keyError() {
180   return llvm::createStringError(llvm::inconvertibleErrorCode(),
181                                  "key not in dict");
182 }
183 
184 #if PY_MAJOR_VERSION < 3
185 // The python 2 API declares some arguments as char* that should
186 // be const char *, but it doesn't actually modify them.
187 inline char *py2_const_cast(const char *s) { return const_cast<char *>(s); }
188 #else
189 inline const char *py2_const_cast(const char *s) { return s; }
190 #endif
191 
192 enum class PyInitialValue { Invalid, Empty };
193 
194 template <typename T, typename Enable = void> struct PythonFormat;
195 
196 template <> struct PythonFormat<unsigned long long> {
197   static constexpr char format = 'K';
198   static auto get(unsigned long long value) { return value; }
199 };
200 
201 template <> struct PythonFormat<long long> {
202   static constexpr char format = 'L';
203   static auto get(long long value) { return value; }
204 };
205 
206 template <> struct PythonFormat<PyObject *> {
207   static constexpr char format = 'O';
208   static auto get(PyObject *value) { return value; }
209 };
210 
211 template <typename T>
212 struct PythonFormat<
213     T, typename std::enable_if<std::is_base_of<PythonObject, T>::value>::type> {
214   static constexpr char format = 'O';
215   static auto get(const T &value) { return value.get(); }
216 };
217 
218 class PythonObject {
219 public:
220   PythonObject() = default;
221 
222   PythonObject(PyRefType type, PyObject *py_obj) {
223     m_py_obj = py_obj;
224     // If this is a borrowed reference, we need to convert it to
225     // an owned reference by incrementing it.  If it is an owned
226     // reference (for example the caller allocated it with PyDict_New()
227     // then we must *not* increment it.
228     if (m_py_obj && Py_IsInitialized() && type == PyRefType::Borrowed)
229       Py_XINCREF(m_py_obj);
230   }
231 
232   PythonObject(const PythonObject &rhs)
233       : PythonObject(PyRefType::Borrowed, rhs.m_py_obj) {}
234 
235   PythonObject(PythonObject &&rhs) {
236     m_py_obj = rhs.m_py_obj;
237     rhs.m_py_obj = nullptr;
238   }
239 
240   ~PythonObject() { Reset(); }
241 
242   void Reset() {
243     if (m_py_obj && Py_IsInitialized()) {
244       if (_Py_IsFinalizing()) {
245         // Leak m_py_obj rather than crashing the process.
246         // https://docs.python.org/3/c-api/init.html#c.PyGILState_Ensure
247       } else {
248         PyGILState_STATE state = PyGILState_Ensure();
249         Py_DECREF(m_py_obj);
250         PyGILState_Release(state);
251       }
252     }
253     m_py_obj = nullptr;
254   }
255 
256   void Dump() const {
257     if (m_py_obj)
258       _PyObject_Dump(m_py_obj);
259     else
260       puts("NULL");
261   }
262 
263   void Dump(Stream &strm) const;
264 
265   PyObject *get() const { return m_py_obj; }
266 
267   PyObject *release() {
268     PyObject *result = m_py_obj;
269     m_py_obj = nullptr;
270     return result;
271   }
272 
273   PythonObject &operator=(PythonObject other) {
274     Reset();
275     m_py_obj = std::exchange(other.m_py_obj, nullptr);
276     return *this;
277   }
278 
279   PyObjectType GetObjectType() const;
280 
281   PythonString Repr() const;
282 
283   PythonString Str() const;
284 
285   static PythonObject ResolveNameWithDictionary(llvm::StringRef name,
286                                                 const PythonDictionary &dict);
287 
288   template <typename T>
289   static T ResolveNameWithDictionary(llvm::StringRef name,
290                                      const PythonDictionary &dict) {
291     return ResolveNameWithDictionary(name, dict).AsType<T>();
292   }
293 
294   PythonObject ResolveName(llvm::StringRef name) const;
295 
296   template <typename T> T ResolveName(llvm::StringRef name) const {
297     return ResolveName(name).AsType<T>();
298   }
299 
300   bool HasAttribute(llvm::StringRef attribute) const;
301 
302   PythonObject GetAttributeValue(llvm::StringRef attribute) const;
303 
304   bool IsNone() const { return m_py_obj == Py_None; }
305 
306   bool IsValid() const { return m_py_obj != nullptr; }
307 
308   bool IsAllocated() const { return IsValid() && !IsNone(); }
309 
310   explicit operator bool() const { return IsValid() && !IsNone(); }
311 
312   template <typename T> T AsType() const {
313     if (!T::Check(m_py_obj))
314       return T();
315     return T(PyRefType::Borrowed, m_py_obj);
316   }
317 
318   StructuredData::ObjectSP CreateStructuredObject() const;
319 
320   template <typename... T>
321   llvm::Expected<PythonObject> CallMethod(const char *name,
322                                           const T &... t) const {
323     const char format[] = {'(', PythonFormat<T>::format..., ')', 0};
324     PyObject *obj =
325         PyObject_CallMethod(m_py_obj, py2_const_cast(name),
326                             py2_const_cast(format), PythonFormat<T>::get(t)...);
327     if (!obj)
328       return exception();
329     return python::Take<PythonObject>(obj);
330   }
331 
332   template <typename... T>
333   llvm::Expected<PythonObject> Call(const T &... t) const {
334     const char format[] = {'(', PythonFormat<T>::format..., ')', 0};
335     PyObject *obj = PyObject_CallFunction(m_py_obj, py2_const_cast(format),
336                                           PythonFormat<T>::get(t)...);
337     if (!obj)
338       return exception();
339     return python::Take<PythonObject>(obj);
340   }
341 
342   llvm::Expected<PythonObject> GetAttribute(const llvm::Twine &name) const {
343     if (!m_py_obj)
344       return nullDeref();
345     PyObject *obj = PyObject_GetAttrString(m_py_obj, NullTerminated(name));
346     if (!obj)
347       return exception();
348     return python::Take<PythonObject>(obj);
349   }
350 
351   llvm::Expected<bool> IsTrue() {
352     if (!m_py_obj)
353       return nullDeref();
354     int r = PyObject_IsTrue(m_py_obj);
355     if (r < 0)
356       return exception();
357     return !!r;
358   }
359 
360   llvm::Expected<long long> AsLongLong() const;
361 
362   llvm::Expected<long long> AsUnsignedLongLong() const;
363 
364   // wraps on overflow, instead of raising an error.
365   llvm::Expected<unsigned long long> AsModuloUnsignedLongLong() const;
366 
367   llvm::Expected<bool> IsInstance(const PythonObject &cls) {
368     if (!m_py_obj || !cls.IsValid())
369       return nullDeref();
370     int r = PyObject_IsInstance(m_py_obj, cls.get());
371     if (r < 0)
372       return exception();
373     return !!r;
374   }
375 
376 protected:
377   PyObject *m_py_obj = nullptr;
378 };
379 
380 
381 // This is why C++ needs monads.
382 template <typename T> llvm::Expected<T> As(llvm::Expected<PythonObject> &&obj) {
383   if (!obj)
384     return obj.takeError();
385   if (!T::Check(obj.get().get()))
386     return llvm::createStringError(llvm::inconvertibleErrorCode(),
387                                    "type error");
388   return T(PyRefType::Borrowed, std::move(obj.get().get()));
389 }
390 
391 template <> llvm::Expected<bool> As<bool>(llvm::Expected<PythonObject> &&obj);
392 
393 template <>
394 llvm::Expected<long long> As<long long>(llvm::Expected<PythonObject> &&obj);
395 
396 template <>
397 llvm::Expected<unsigned long long>
398 As<unsigned long long>(llvm::Expected<PythonObject> &&obj);
399 
400 template <>
401 llvm::Expected<std::string> As<std::string>(llvm::Expected<PythonObject> &&obj);
402 
403 
404 template <class T> class TypedPythonObject : public PythonObject {
405 public:
406   // override to perform implicit type conversions on Reset
407   // This can be eliminated once we drop python 2 support.
408   static void Convert(PyRefType &type, PyObject *&py_obj) {}
409 
410   TypedPythonObject(PyRefType type, PyObject *py_obj) {
411     if (!py_obj)
412       return;
413     T::Convert(type, py_obj);
414     if (T::Check(py_obj))
415       PythonObject::operator=(PythonObject(type, py_obj));
416     else if (type == PyRefType::Owned)
417       Py_DECREF(py_obj);
418   }
419 
420   TypedPythonObject() = default;
421 };
422 
423 class PythonBytes : public TypedPythonObject<PythonBytes> {
424 public:
425   using TypedPythonObject::TypedPythonObject;
426   explicit PythonBytes(llvm::ArrayRef<uint8_t> bytes);
427   PythonBytes(const uint8_t *bytes, size_t length);
428 
429   static bool Check(PyObject *py_obj);
430 
431   llvm::ArrayRef<uint8_t> GetBytes() const;
432 
433   size_t GetSize() const;
434 
435   void SetBytes(llvm::ArrayRef<uint8_t> stringbytes);
436 
437   StructuredData::StringSP CreateStructuredString() const;
438 };
439 
440 class PythonByteArray : public TypedPythonObject<PythonByteArray> {
441 public:
442   using TypedPythonObject::TypedPythonObject;
443   explicit PythonByteArray(llvm::ArrayRef<uint8_t> bytes);
444   PythonByteArray(const uint8_t *bytes, size_t length);
445   PythonByteArray(const PythonBytes &object);
446 
447   static bool Check(PyObject *py_obj);
448 
449   llvm::ArrayRef<uint8_t> GetBytes() const;
450 
451   size_t GetSize() const;
452 
453   void SetBytes(llvm::ArrayRef<uint8_t> stringbytes);
454 
455   StructuredData::StringSP CreateStructuredString() const;
456 };
457 
458 class PythonString : public TypedPythonObject<PythonString> {
459 public:
460   using TypedPythonObject::TypedPythonObject;
461   static llvm::Expected<PythonString> FromUTF8(llvm::StringRef string);
462 
463   PythonString() : TypedPythonObject() {} // MSVC requires this for some reason
464 
465   explicit PythonString(llvm::StringRef string); // safe, null on error
466 
467   static bool Check(PyObject *py_obj);
468   static void Convert(PyRefType &type, PyObject *&py_obj);
469 
470   llvm::StringRef GetString() const; // safe, empty string on error
471 
472   llvm::Expected<llvm::StringRef> AsUTF8() const;
473 
474   size_t GetSize() const;
475 
476   void SetString(llvm::StringRef string); // safe, null on error
477 
478   StructuredData::StringSP CreateStructuredString() const;
479 };
480 
481 class PythonInteger : public TypedPythonObject<PythonInteger> {
482 public:
483   using TypedPythonObject::TypedPythonObject;
484 
485   PythonInteger() : TypedPythonObject() {} // MSVC requires this for some reason
486 
487   explicit PythonInteger(int64_t value);
488 
489   static bool Check(PyObject *py_obj);
490   static void Convert(PyRefType &type, PyObject *&py_obj);
491 
492   void SetInteger(int64_t value);
493 
494   StructuredData::IntegerSP CreateStructuredInteger() const;
495 };
496 
497 class PythonBoolean : public TypedPythonObject<PythonBoolean> {
498 public:
499   using TypedPythonObject::TypedPythonObject;
500 
501   explicit PythonBoolean(bool value);
502 
503   static bool Check(PyObject *py_obj);
504 
505   bool GetValue() const;
506 
507   void SetValue(bool value);
508 
509   StructuredData::BooleanSP CreateStructuredBoolean() const;
510 };
511 
512 class PythonList : public TypedPythonObject<PythonList> {
513 public:
514   using TypedPythonObject::TypedPythonObject;
515 
516   PythonList() : TypedPythonObject() {} // MSVC requires this for some reason
517 
518   explicit PythonList(PyInitialValue value);
519   explicit PythonList(int list_size);
520 
521   static bool Check(PyObject *py_obj);
522 
523   uint32_t GetSize() const;
524 
525   PythonObject GetItemAtIndex(uint32_t index) const;
526 
527   void SetItemAtIndex(uint32_t index, const PythonObject &object);
528 
529   void AppendItem(const PythonObject &object);
530 
531   StructuredData::ArraySP CreateStructuredArray() const;
532 };
533 
534 class PythonTuple : public TypedPythonObject<PythonTuple> {
535 public:
536   using TypedPythonObject::TypedPythonObject;
537 
538   explicit PythonTuple(PyInitialValue value);
539   explicit PythonTuple(int tuple_size);
540   PythonTuple(std::initializer_list<PythonObject> objects);
541   PythonTuple(std::initializer_list<PyObject *> objects);
542 
543   static bool Check(PyObject *py_obj);
544 
545   uint32_t GetSize() const;
546 
547   PythonObject GetItemAtIndex(uint32_t index) const;
548 
549   void SetItemAtIndex(uint32_t index, const PythonObject &object);
550 
551   StructuredData::ArraySP CreateStructuredArray() const;
552 };
553 
554 class PythonDictionary : public TypedPythonObject<PythonDictionary> {
555 public:
556   using TypedPythonObject::TypedPythonObject;
557 
558   PythonDictionary() : TypedPythonObject() {} // MSVC requires this for some reason
559 
560   explicit PythonDictionary(PyInitialValue value);
561 
562   static bool Check(PyObject *py_obj);
563 
564   uint32_t GetSize() const;
565 
566   PythonList GetKeys() const;
567 
568   PythonObject GetItemForKey(const PythonObject &key) const; // DEPRECATED
569   void SetItemForKey(const PythonObject &key,
570                      const PythonObject &value); // DEPRECATED
571 
572   llvm::Expected<PythonObject> GetItem(const PythonObject &key) const;
573   llvm::Expected<PythonObject> GetItem(const llvm::Twine &key) const;
574   llvm::Error SetItem(const PythonObject &key, const PythonObject &value) const;
575   llvm::Error SetItem(const llvm::Twine &key, const PythonObject &value) const;
576 
577   StructuredData::DictionarySP CreateStructuredDictionary() const;
578 };
579 
580 class PythonModule : public TypedPythonObject<PythonModule> {
581 public:
582   using TypedPythonObject::TypedPythonObject;
583 
584   static bool Check(PyObject *py_obj);
585 
586   static PythonModule BuiltinsModule();
587 
588   static PythonModule MainModule();
589 
590   static PythonModule AddModule(llvm::StringRef module);
591 
592   // safe, returns invalid on error;
593   static PythonModule ImportModule(llvm::StringRef name) {
594     std::string s = std::string(name);
595     auto mod = Import(s.c_str());
596     if (!mod) {
597       llvm::consumeError(mod.takeError());
598       return PythonModule();
599     }
600     return std::move(mod.get());
601   }
602 
603   static llvm::Expected<PythonModule> Import(const llvm::Twine &name);
604 
605   llvm::Expected<PythonObject> Get(const llvm::Twine &name);
606 
607   PythonDictionary GetDictionary() const;
608 };
609 
610 class PythonCallable : public TypedPythonObject<PythonCallable> {
611 public:
612   using TypedPythonObject::TypedPythonObject;
613 
614   struct ArgInfo {
615     /* the largest number of positional arguments this callable
616      * can accept, or UNBOUNDED, ie UINT_MAX if it's a varargs
617      * function and can accept an arbitrary number */
618     unsigned max_positional_args;
619     static constexpr unsigned UNBOUNDED = UINT_MAX; // FIXME c++17 inline
620   };
621 
622   static bool Check(PyObject *py_obj);
623 
624   llvm::Expected<ArgInfo> GetArgInfo() const;
625 
626   PythonObject operator()();
627 
628   PythonObject operator()(std::initializer_list<PyObject *> args);
629 
630   PythonObject operator()(std::initializer_list<PythonObject> args);
631 
632   template <typename Arg, typename... Args>
633   PythonObject operator()(const Arg &arg, Args... args) {
634     return operator()({arg, args...});
635   }
636 };
637 
638 class PythonFile : public TypedPythonObject<PythonFile> {
639 public:
640   using TypedPythonObject::TypedPythonObject;
641 
642   PythonFile() : TypedPythonObject() {} // MSVC requires this for some reason
643 
644   static bool Check(PyObject *py_obj);
645 
646   static llvm::Expected<PythonFile> FromFile(File &file,
647                                              const char *mode = nullptr);
648 
649   llvm::Expected<lldb::FileSP> ConvertToFile(bool borrowed = false);
650   llvm::Expected<lldb::FileSP>
651   ConvertToFileForcingUseOfScriptingIOMethods(bool borrowed = false);
652 };
653 
654 class PythonException : public llvm::ErrorInfo<PythonException> {
655 private:
656   PyObject *m_exception_type, *m_exception, *m_traceback;
657   PyObject *m_repr_bytes;
658 
659 public:
660   static char ID;
661   const char *toCString() const;
662   PythonException(const char *caller = nullptr);
663   void Restore();
664   ~PythonException();
665   void log(llvm::raw_ostream &OS) const override;
666   std::error_code convertToErrorCode() const override;
667   bool Matches(PyObject *exc) const;
668   std::string ReadBacktrace() const;
669 };
670 
671 // This extracts the underlying T out of an Expected<T> and returns it.
672 // If the Expected is an Error instead of a T, that error will be converted
673 // into a python exception, and this will return a default-constructed T.
674 //
675 // This is appropriate for use right at the boundary of python calling into
676 // C++, such as in a SWIG typemap.   In such a context you should simply
677 // check if the returned T is valid, and if it is, return a NULL back
678 // to python.   This will result in the Error being raised as an exception
679 // from python code's point of view.
680 //
681 // For example:
682 // ```
683 // Expected<Foo *> efoop = some_cpp_function();
684 // Foo *foop = unwrapOrSetPythonException(efoop);
685 // if (!foop)
686 //    return NULL;
687 // do_something(*foop);
688 //
689 // If the Error returned was itself created because a python exception was
690 // raised when C++ code called into python, then the original exception
691 // will be restored.   Otherwise a simple string exception will be raised.
692 template <typename T> T unwrapOrSetPythonException(llvm::Expected<T> expected) {
693   if (expected)
694     return expected.get();
695   llvm::handleAllErrors(
696       expected.takeError(), [](PythonException &E) { E.Restore(); },
697       [](const llvm::ErrorInfoBase &E) {
698         PyErr_SetString(PyExc_Exception, E.message().c_str());
699       });
700   return T();
701 }
702 
703 // This is only here to help incrementally migrate old, exception-unsafe
704 // code.
705 template <typename T> T unwrapIgnoringErrors(llvm::Expected<T> expected) {
706   if (expected)
707     return std::move(expected.get());
708   llvm::consumeError(expected.takeError());
709   return T();
710 }
711 
712 llvm::Expected<PythonObject> runStringOneLine(const llvm::Twine &string,
713                                               const PythonDictionary &globals,
714                                               const PythonDictionary &locals);
715 
716 llvm::Expected<PythonObject> runStringMultiLine(const llvm::Twine &string,
717                                                 const PythonDictionary &globals,
718                                                 const PythonDictionary &locals);
719 
720 // Sometimes the best way to interact with a python interpreter is
721 // to run some python code.   You construct a PythonScript with
722 // script string.   The script assigns some function to `_function_`
723 // and you get a C++ callable object that calls the python function.
724 //
725 // Example:
726 //
727 // const char script[] = R"(
728 // def main(x, y):
729 //    ....
730 // )";
731 //
732 // Expected<PythonObject> cpp_foo_wrapper(PythonObject x, PythonObject y) {
733 //   // no need to synchronize access to this global, we already have the GIL
734 //   static PythonScript foo(script)
735 //   return  foo(x, y);
736 // }
737 class PythonScript {
738   const char *script;
739   PythonCallable function;
740 
741   llvm::Error Init();
742 
743 public:
744   PythonScript(const char *script) : script(script), function() {}
745 
746   template <typename... Args>
747   llvm::Expected<PythonObject> operator()(Args &&... args) {
748     if (llvm::Error error = Init())
749       return std::move(error);
750     return function.Call(std::forward<Args>(args)...);
751   }
752 };
753 
754 class StructuredPythonObject : public StructuredData::Generic {
755 public:
756   StructuredPythonObject() : StructuredData::Generic() {}
757 
758   // Take ownership of the object we received.
759   StructuredPythonObject(PythonObject obj)
760       : StructuredData::Generic(obj.release()) {}
761 
762   ~StructuredPythonObject() override {
763     // Hand ownership back to a (temporary) PythonObject instance and let it
764     // take care of releasing it.
765     PythonObject(PyRefType::Owned, static_cast<PyObject *>(GetValue()));
766   }
767 
768   bool IsValid() const override { return GetValue() && GetValue() != Py_None; }
769 
770   void Serialize(llvm::json::OStream &s) const override;
771 
772 private:
773   StructuredPythonObject(const StructuredPythonObject &) = delete;
774   const StructuredPythonObject &
775   operator=(const StructuredPythonObject &) = delete;
776 };
777 
778 } // namespace python
779 } // namespace lldb_private
780 
781 #endif
782 
783 #endif // LLDB_PLUGINS_SCRIPTINTERPRETER_PYTHON_PYTHONDATAOBJECTS_H
784