xref: /llvm-project/lldb/source/Plugins/ScriptInterpreter/Python/PythonDataObjects.h (revision 1dfb1a85e7cbc37bf6fff9bb046c6e8be0c26b8e)
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 // * Elimintate 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 #ifndef LLDB_DISABLE_PYTHON
52 
53 // LLDB Python header must be included first
54 #include "lldb-python.h"
55 
56 #include "lldb/Host/File.h"
57 #include "lldb/Utility/StructuredData.h"
58 
59 #include "llvm/ADT/ArrayRef.h"
60 
61 namespace lldb_private {
62 namespace python {
63 
64 class PythonObject;
65 class PythonBytes;
66 class PythonString;
67 class PythonList;
68 class PythonDictionary;
69 class PythonInteger;
70 class PythonException;
71 
72 class StructuredPythonObject : public StructuredData::Generic {
73 public:
74   StructuredPythonObject() : StructuredData::Generic() {}
75 
76   StructuredPythonObject(void *obj) : StructuredData::Generic(obj) {
77     Py_XINCREF(GetValue());
78   }
79 
80   ~StructuredPythonObject() override {
81     if (Py_IsInitialized())
82       Py_XDECREF(GetValue());
83     SetValue(nullptr);
84   }
85 
86   bool IsValid() const override { return GetValue() && GetValue() != Py_None; }
87 
88   void Serialize(llvm::json::OStream &s) const override;
89 
90 private:
91   DISALLOW_COPY_AND_ASSIGN(StructuredPythonObject);
92 };
93 
94 enum class PyObjectType {
95   Unknown,
96   None,
97   Boolean,
98   Integer,
99   Dictionary,
100   List,
101   String,
102   Bytes,
103   ByteArray,
104   Module,
105   Callable,
106   Tuple,
107   File
108 };
109 
110 enum class PyRefType {
111   Borrowed, // We are not given ownership of the incoming PyObject.
112             // We cannot safely hold it without calling Py_INCREF.
113   Owned     // We have ownership of the incoming PyObject.  We should
114             // not call Py_INCREF.
115 };
116 
117 
118 // Take a reference that you already own, and turn it into
119 // a PythonObject.
120 //
121 // Most python API methods will return a +1 reference
122 // if they succeed or NULL if and only if
123 // they set an exception.   Use this to collect such return
124 // values, after checking for NULL.
125 //
126 // If T is not just PythonObject, then obj must be already be
127 // checked to be of the correct type.
128 template <typename T> T Take(PyObject *obj) {
129   assert(obj);
130   assert(!PyErr_Occurred());
131   T thing(PyRefType::Owned, obj);
132   assert(thing.IsValid());
133   return thing;
134 }
135 
136 // Retain a reference you have borrowed, and turn it into
137 // a PythonObject.
138 //
139 // A minority of python APIs return a borrowed reference
140 // instead of a +1.   They will also return NULL if and only
141 // if they set an exception.   Use this to collect such return
142 // values, after checking for NULL.
143 //
144 // If T is not just PythonObject, then obj must be already be
145 // checked to be of the correct type.
146 template <typename T> T Retain(PyObject *obj) {
147   assert(obj);
148   assert(!PyErr_Occurred());
149   T thing(PyRefType::Borrowed, obj);
150   assert(thing.IsValid());
151   return thing;
152 }
153 
154 // This class can be used like a utility function to convert from
155 // a llvm-friendly Twine into a null-terminated const char *,
156 // which is the form python C APIs want their strings in.
157 //
158 // Example:
159 // const llvm::Twine &some_twine;
160 // PyFoo_Bar(x, y, z, NullTerminated(some_twine));
161 //
162 // Why a class instead of a function?  If the twine isn't already null
163 // terminated, it will need a temporary buffer to copy the string
164 // into.   We need that buffer to stick around for the lifetime of the
165 // statement.
166 class NullTerminated {
167   const char *str;
168   llvm::SmallString<32> storage;
169 
170 public:
171   NullTerminated(const llvm::Twine &twine) {
172     llvm::StringRef ref = twine.toNullTerminatedStringRef(storage);
173     str = ref.begin();
174   }
175   operator const char *() { return str; }
176 };
177 
178 inline llvm::Error nullDeref() {
179   return llvm::createStringError(llvm::inconvertibleErrorCode(),
180                                  "A NULL PyObject* was dereferenced");
181 }
182 
183 inline llvm::Error exception(const char *s = nullptr) {
184   return llvm::make_error<PythonException>(s);
185 }
186 
187 inline llvm::Error keyError() {
188   return llvm::createStringError(llvm::inconvertibleErrorCode(),
189                                  "key not in dict");
190 }
191 
192 #if PY_MAJOR_VERSION < 3
193 // The python 2 API declares some arguments as char* that should
194 // be const char *, but it doesn't actually modify them.
195 inline char *py2_const_cast(const char *s) { return const_cast<char *>(s); }
196 #else
197 inline const char *py2_const_cast(const char *s) { return s; }
198 #endif
199 
200 enum class PyInitialValue { Invalid, Empty };
201 
202 template <typename T, typename Enable = void> struct PythonFormat;
203 
204 template <> struct PythonFormat<unsigned long long> {
205   static constexpr char format = 'K';
206   static auto get(unsigned long long value) { return value; }
207 };
208 
209 template <> struct PythonFormat<long long> {
210   static constexpr char format = 'L';
211   static auto get(long long value) { return value; }
212 };
213 
214 template <> struct PythonFormat<PyObject *> {
215   static constexpr char format = 'O';
216   static auto get(PyObject *value) { return value; }
217 };
218 
219 template <typename T>
220 struct PythonFormat<
221     T, typename std::enable_if<std::is_base_of<PythonObject, T>::value>::type> {
222   static constexpr char format = 'O';
223   static auto get(const T &value) { return value.get(); }
224 };
225 
226 class PythonObject {
227 public:
228   PythonObject() : m_py_obj(nullptr) {}
229 
230   PythonObject(PyRefType type, PyObject *py_obj) {
231     m_py_obj = py_obj;
232     // If this is a borrowed reference, we need to convert it to
233     // an owned reference by incrementing it.  If it is an owned
234     // reference (for example the caller allocated it with PyDict_New()
235     // then we must *not* increment it.
236     if (m_py_obj && Py_IsInitialized() && type == PyRefType::Borrowed)
237       Py_XINCREF(m_py_obj);
238   }
239 
240   PythonObject(const PythonObject &rhs)
241       : PythonObject(PyRefType::Borrowed, rhs.m_py_obj) {}
242 
243   PythonObject(PythonObject &&rhs) {
244     m_py_obj = rhs.m_py_obj;
245     rhs.m_py_obj = nullptr;
246   }
247 
248   ~PythonObject() { Reset(); }
249 
250   void Reset() {
251     if (m_py_obj && Py_IsInitialized())
252       Py_DECREF(m_py_obj);
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 public:
321   template <typename... T>
322   llvm::Expected<PythonObject> CallMethod(const char *name,
323                                           const T &... t) const {
324     const char format[] = {'(', PythonFormat<T>::format..., ')', 0};
325     PyObject *obj =
326         PyObject_CallMethod(m_py_obj, py2_const_cast(name),
327                             py2_const_cast(format), PythonFormat<T>::get(t)...);
328     if (!obj)
329       return exception();
330     return python::Take<PythonObject>(obj);
331   }
332 
333   template <typename... T>
334   llvm::Expected<PythonObject> Call(const T &... t) const {
335     const char format[] = {'(', PythonFormat<T>::format..., ')', 0};
336     PyObject *obj = PyObject_CallFunction(m_py_obj, py2_const_cast(format),
337                                           PythonFormat<T>::get(t)...);
338     if (!obj)
339       return exception();
340     return python::Take<PythonObject>(obj);
341   }
342 
343   llvm::Expected<PythonObject> GetAttribute(const llvm::Twine &name) const {
344     if (!m_py_obj)
345       return nullDeref();
346     PyObject *obj = PyObject_GetAttrString(m_py_obj, NullTerminated(name));
347     if (!obj)
348       return exception();
349     return python::Take<PythonObject>(obj);
350   }
351 
352   llvm::Expected<bool> IsTrue() {
353     if (!m_py_obj)
354       return nullDeref();
355     int r = PyObject_IsTrue(m_py_obj);
356     if (r < 0)
357       return exception();
358     return !!r;
359   }
360 
361   llvm::Expected<long long> AsLongLong() {
362     if (!m_py_obj)
363       return nullDeref();
364     assert(!PyErr_Occurred());
365     long long r = PyLong_AsLongLong(m_py_obj);
366     if (PyErr_Occurred())
367       return exception();
368     return r;
369   }
370 
371   llvm::Expected<bool> IsInstance(const PythonObject &cls) {
372     if (!m_py_obj || !cls.IsValid())
373       return nullDeref();
374     int r = PyObject_IsInstance(m_py_obj, cls.get());
375     if (r < 0)
376       return exception();
377     return !!r;
378   }
379 
380 protected:
381   PyObject *m_py_obj;
382 };
383 
384 
385 // This is why C++ needs monads.
386 template <typename T> llvm::Expected<T> As(llvm::Expected<PythonObject> &&obj) {
387   if (!obj)
388     return obj.takeError();
389   if (!T::Check(obj.get().get()))
390     return llvm::createStringError(llvm::inconvertibleErrorCode(),
391                                    "type error");
392   return T(PyRefType::Borrowed, std::move(obj.get().get()));
393 }
394 
395 template <> llvm::Expected<bool> As<bool>(llvm::Expected<PythonObject> &&obj);
396 
397 template <>
398 llvm::Expected<long long> As<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() {}
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   int64_t GetInteger() const;
493 
494   void SetInteger(int64_t value);
495 
496   StructuredData::IntegerSP CreateStructuredInteger() const;
497 };
498 
499 class PythonBoolean : public TypedPythonObject<PythonBoolean> {
500 public:
501   using TypedPythonObject::TypedPythonObject;
502 
503   explicit PythonBoolean(bool value);
504 
505   static bool Check(PyObject *py_obj);
506 
507   bool GetValue() const;
508 
509   void SetValue(bool value);
510 
511   StructuredData::BooleanSP CreateStructuredBoolean() const;
512 };
513 
514 class PythonList : public TypedPythonObject<PythonList> {
515 public:
516   using TypedPythonObject::TypedPythonObject;
517 
518   PythonList() : TypedPythonObject() {} // MSVC requires this for some reason
519 
520   explicit PythonList(PyInitialValue value);
521   explicit PythonList(int list_size);
522 
523   static bool Check(PyObject *py_obj);
524 
525   uint32_t GetSize() const;
526 
527   PythonObject GetItemAtIndex(uint32_t index) const;
528 
529   void SetItemAtIndex(uint32_t index, const PythonObject &object);
530 
531   void AppendItem(const PythonObject &object);
532 
533   StructuredData::ArraySP CreateStructuredArray() const;
534 };
535 
536 class PythonTuple : public TypedPythonObject<PythonTuple> {
537 public:
538   using TypedPythonObject::TypedPythonObject;
539 
540   explicit PythonTuple(PyInitialValue value);
541   explicit PythonTuple(int tuple_size);
542   PythonTuple(std::initializer_list<PythonObject> objects);
543   PythonTuple(std::initializer_list<PyObject *> objects);
544 
545   static bool Check(PyObject *py_obj);
546 
547   uint32_t GetSize() const;
548 
549   PythonObject GetItemAtIndex(uint32_t index) const;
550 
551   void SetItemAtIndex(uint32_t index, const PythonObject &object);
552 
553   StructuredData::ArraySP CreateStructuredArray() const;
554 };
555 
556 class PythonDictionary : public TypedPythonObject<PythonDictionary> {
557 public:
558   using TypedPythonObject::TypedPythonObject;
559 
560   PythonDictionary() : TypedPythonObject() {} // MSVC requires this for some reason
561 
562   explicit PythonDictionary(PyInitialValue value);
563 
564   static bool Check(PyObject *py_obj);
565 
566   uint32_t GetSize() const;
567 
568   PythonList GetKeys() const;
569 
570   PythonObject GetItemForKey(const PythonObject &key) const; // DEPRECATED
571   void SetItemForKey(const PythonObject &key,
572                      const PythonObject &value); // DEPRECATED
573 
574   llvm::Expected<PythonObject> GetItem(const PythonObject &key) const;
575   llvm::Expected<PythonObject> GetItem(const llvm::Twine &key) const;
576   llvm::Error SetItem(const PythonObject &key, const PythonObject &value) const;
577   llvm::Error SetItem(const llvm::Twine &key, const PythonObject &value) const;
578 
579   StructuredData::DictionarySP CreateStructuredDictionary() const;
580 };
581 
582 class PythonModule : public TypedPythonObject<PythonModule> {
583 public:
584   using TypedPythonObject::TypedPythonObject;
585 
586   static bool Check(PyObject *py_obj);
587 
588   static PythonModule BuiltinsModule();
589 
590   static PythonModule MainModule();
591 
592   static PythonModule AddModule(llvm::StringRef module);
593 
594   // safe, returns invalid on error;
595   static PythonModule ImportModule(llvm::StringRef name) {
596     std::string s = name;
597     auto mod = Import(s.c_str());
598     if (!mod) {
599       llvm::consumeError(mod.takeError());
600       return PythonModule();
601     }
602     return std::move(mod.get());
603   }
604 
605   static llvm::Expected<PythonModule> Import(const llvm::Twine &name);
606 
607   llvm::Expected<PythonObject> Get(const llvm::Twine &name);
608 
609   PythonDictionary GetDictionary() const;
610 };
611 
612 class PythonCallable : public TypedPythonObject<PythonCallable> {
613 public:
614   using TypedPythonObject::TypedPythonObject;
615 
616   struct ArgInfo {
617     /* the largest number of positional arguments this callable
618      * can accept, or UNBOUNDED, ie UINT_MAX if it's a varargs
619      * function and can accept an arbitrary number */
620     unsigned max_positional_args;
621     static constexpr unsigned UNBOUNDED = UINT_MAX; // FIXME c++17 inline
622   };
623 
624   static bool Check(PyObject *py_obj);
625 
626   llvm::Expected<ArgInfo> GetArgInfo() const;
627 
628   PythonObject operator()();
629 
630   PythonObject operator()(std::initializer_list<PyObject *> args);
631 
632   PythonObject operator()(std::initializer_list<PythonObject> args);
633 
634   template <typename Arg, typename... Args>
635   PythonObject operator()(const Arg &arg, Args... args) {
636     return operator()({arg, args...});
637   }
638 };
639 
640 class PythonFile : public TypedPythonObject<PythonFile> {
641 public:
642   using TypedPythonObject::TypedPythonObject;
643 
644   PythonFile() : TypedPythonObject() {} // MSVC requires this for some reason
645 
646   static bool Check(PyObject *py_obj);
647 
648   static llvm::Expected<PythonFile> FromFile(File &file,
649                                              const char *mode = nullptr);
650 
651   llvm::Expected<lldb::FileSP> ConvertToFile(bool borrowed = false);
652   llvm::Expected<lldb::FileSP>
653   ConvertToFileForcingUseOfScriptingIOMethods(bool borrowed = false);
654 };
655 
656 class PythonException : public llvm::ErrorInfo<PythonException> {
657 private:
658   PyObject *m_exception_type, *m_exception, *m_traceback;
659   PyObject *m_repr_bytes;
660 
661 public:
662   static char ID;
663   const char *toCString() const;
664   PythonException(const char *caller = nullptr);
665   void Restore();
666   ~PythonException();
667   void log(llvm::raw_ostream &OS) const override;
668   std::error_code convertToErrorCode() const override;
669   bool Matches(PyObject *exc) const;
670   std::string ReadBacktrace() const;
671 };
672 
673 // This extracts the underlying T out of an Expected<T> and returns it.
674 // If the Expected is an Error instead of a T, that error will be converted
675 // into a python exception, and this will return a default-constructed T.
676 //
677 // This is appropriate for use right at the boundary of python calling into
678 // C++, such as in a SWIG typemap.   In such a context you should simply
679 // check if the returned T is valid, and if it is, return a NULL back
680 // to python.   This will result in the Error being raised as an exception
681 // from python code's point of view.
682 //
683 // For example:
684 // ```
685 // Expected<Foo *> efoop = some_cpp_function();
686 // Foo *foop = unwrapOrSetPythonException(efoop);
687 // if (!foop)
688 //    return NULL;
689 // do_something(*foop);
690 //
691 // If the Error returned was itself created because a python exception was
692 // raised when C++ code called into python, then the original exception
693 // will be restored.   Otherwise a simple string exception will be raised.
694 template <typename T> T unwrapOrSetPythonException(llvm::Expected<T> expected) {
695   if (expected)
696     return expected.get();
697   llvm::handleAllErrors(
698       expected.takeError(), [](PythonException &E) { E.Restore(); },
699       [](const llvm::ErrorInfoBase &E) {
700         PyErr_SetString(PyExc_Exception, E.message().c_str());
701       });
702   return T();
703 }
704 
705 // This is only here to help incrementally migrate old, exception-unsafe
706 // code.
707 template <typename T> T unwrapIgnoringErrors(llvm::Expected<T> expected) {
708   if (expected)
709     return std::move(expected.get());
710   llvm::consumeError(expected.takeError());
711   return T();
712 }
713 
714 llvm::Expected<PythonObject> runStringOneLine(const llvm::Twine &string,
715                                               const PythonDictionary &globals,
716                                               const PythonDictionary &locals);
717 
718 llvm::Expected<PythonObject> runStringMultiLine(const llvm::Twine &string,
719                                                 const PythonDictionary &globals,
720                                                 const PythonDictionary &locals);
721 
722 // Sometimes the best way to interact with a python interpreter is
723 // to run some python code.   You construct a PythonScript with
724 // script string.   The script assigns some function to `_function_`
725 // and you get a C++ callable object that calls the python function.
726 //
727 // Example:
728 //
729 // const char script[] = R"(
730 // def main(x, y):
731 //    ....
732 // )";
733 //
734 // Expected<PythonObject> cpp_foo_wrapper(PythonObject x, PythonObject y) {
735 //   // no need to synchronize access to this global, we already have the GIL
736 //   static PythonScript foo(script)
737 //   return  foo(x, y);
738 // }
739 class PythonScript {
740   const char *script;
741   PythonCallable function;
742 
743   llvm::Error Init();
744 
745 public:
746   PythonScript(const char *script) : script(script), function() {}
747 
748   template <typename... Args>
749   llvm::Expected<PythonObject> operator()(Args &&... args) {
750     if (llvm::Error error = Init())
751       return std::move(error);
752     return function.Call(std::forward<Args>(args)...);
753   }
754 };
755 
756 } // namespace python
757 } // namespace lldb_private
758 
759 #endif
760 
761 #endif // LLDB_PLUGINS_SCRIPTINTERPRETER_PYTHON_PYTHONDATAOBJECTS_H
762