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 inline const char *py2_const_cast(const char *s) { return s; } 185 186 enum class PyInitialValue { Invalid, Empty }; 187 188 // DOC: https://docs.python.org/3/c-api/arg.html#building-values 189 template <typename T, typename Enable = void> struct PythonFormat; 190 191 template <typename T, char F> struct PassthroughFormat { 192 static constexpr char format = F; 193 static constexpr T get(T t) { return t; } 194 }; 195 196 template <> struct PythonFormat<char *> : PassthroughFormat<char *, 's'> {}; 197 template <> struct PythonFormat<char> : PassthroughFormat<char, 'b'> {}; 198 template <> 199 struct PythonFormat<unsigned char> : PassthroughFormat<unsigned char, 'B'> {}; 200 template <> struct PythonFormat<short> : PassthroughFormat<short, 'h'> {}; 201 template <> 202 struct PythonFormat<unsigned short> : PassthroughFormat<unsigned short, 'H'> {}; 203 template <> struct PythonFormat<int> : PassthroughFormat<int, 'i'> {}; 204 template <> struct PythonFormat<bool> : PassthroughFormat<bool, 'p'> {}; 205 template <> 206 struct PythonFormat<unsigned int> : PassthroughFormat<unsigned int, 'I'> {}; 207 template <> struct PythonFormat<long> : PassthroughFormat<long, 'l'> {}; 208 template <> 209 struct PythonFormat<unsigned long> : PassthroughFormat<unsigned long, 'k'> {}; 210 template <> 211 struct PythonFormat<long long> : PassthroughFormat<long long, 'L'> {}; 212 template <> 213 struct PythonFormat<unsigned long long> 214 : PassthroughFormat<unsigned long long, 'K'> {}; 215 template <> 216 struct PythonFormat<PyObject *> : PassthroughFormat<PyObject *, 'O'> {}; 217 218 template <typename T> 219 struct PythonFormat< 220 T, typename std::enable_if<std::is_base_of<PythonObject, T>::value>::type> { 221 static constexpr char format = 'O'; 222 static auto get(const T &value) { return value.get(); } 223 }; 224 225 class PythonObject { 226 public: 227 PythonObject() = default; 228 229 PythonObject(PyRefType type, PyObject *py_obj) { 230 m_py_obj = py_obj; 231 // If this is a borrowed reference, we need to convert it to 232 // an owned reference by incrementing it. If it is an owned 233 // reference (for example the caller allocated it with PyDict_New() 234 // then we must *not* increment it. 235 if (m_py_obj && Py_IsInitialized() && type == PyRefType::Borrowed) 236 Py_XINCREF(m_py_obj); 237 } 238 239 PythonObject(const PythonObject &rhs) 240 : PythonObject(PyRefType::Borrowed, rhs.m_py_obj) {} 241 242 PythonObject(PythonObject &&rhs) { 243 m_py_obj = rhs.m_py_obj; 244 rhs.m_py_obj = nullptr; 245 } 246 247 ~PythonObject() { Reset(); } 248 249 void Reset(); 250 251 void Dump() const { 252 if (m_py_obj) 253 _PyObject_Dump(m_py_obj); 254 else 255 puts("NULL"); 256 } 257 258 void Dump(Stream &strm) const; 259 260 PyObject *get() const { return m_py_obj; } 261 262 PyObject *release() { 263 PyObject *result = m_py_obj; 264 m_py_obj = nullptr; 265 return result; 266 } 267 268 PythonObject &operator=(PythonObject other) { 269 Reset(); 270 m_py_obj = std::exchange(other.m_py_obj, nullptr); 271 return *this; 272 } 273 274 PyObjectType GetObjectType() const; 275 276 PythonString Repr() const; 277 278 PythonString Str() const; 279 280 static PythonObject ResolveNameWithDictionary(llvm::StringRef name, 281 const PythonDictionary &dict); 282 283 template <typename T> 284 static T ResolveNameWithDictionary(llvm::StringRef name, 285 const PythonDictionary &dict) { 286 return ResolveNameWithDictionary(name, dict).AsType<T>(); 287 } 288 289 PythonObject ResolveName(llvm::StringRef name) const; 290 291 template <typename T> T ResolveName(llvm::StringRef name) const { 292 return ResolveName(name).AsType<T>(); 293 } 294 295 bool HasAttribute(llvm::StringRef attribute) const; 296 297 PythonObject GetAttributeValue(llvm::StringRef attribute) const; 298 299 bool IsNone() const { return m_py_obj == Py_None; } 300 301 bool IsValid() const { return m_py_obj != nullptr; } 302 303 bool IsAllocated() const { return IsValid() && !IsNone(); } 304 305 explicit operator bool() const { return IsValid() && !IsNone(); } 306 307 template <typename T> T AsType() const { 308 if (!T::Check(m_py_obj)) 309 return T(); 310 return T(PyRefType::Borrowed, m_py_obj); 311 } 312 313 StructuredData::ObjectSP CreateStructuredObject() const; 314 315 template <typename... T> 316 llvm::Expected<PythonObject> CallMethod(const char *name, 317 const T &... t) const { 318 const char format[] = {'(', PythonFormat<T>::format..., ')', 0}; 319 PyObject *obj = 320 PyObject_CallMethod(m_py_obj, py2_const_cast(name), 321 py2_const_cast(format), PythonFormat<T>::get(t)...); 322 if (!obj) 323 return exception(); 324 return python::Take<PythonObject>(obj); 325 } 326 327 template <typename... T> 328 llvm::Expected<PythonObject> Call(const T &... t) const { 329 const char format[] = {'(', PythonFormat<T>::format..., ')', 0}; 330 PyObject *obj = PyObject_CallFunction(m_py_obj, py2_const_cast(format), 331 PythonFormat<T>::get(t)...); 332 if (!obj) 333 return exception(); 334 return python::Take<PythonObject>(obj); 335 } 336 337 llvm::Expected<PythonObject> GetAttribute(const llvm::Twine &name) const { 338 if (!m_py_obj) 339 return nullDeref(); 340 PyObject *obj = PyObject_GetAttrString(m_py_obj, NullTerminated(name)); 341 if (!obj) 342 return exception(); 343 return python::Take<PythonObject>(obj); 344 } 345 346 llvm::Expected<bool> IsTrue() { 347 if (!m_py_obj) 348 return nullDeref(); 349 int r = PyObject_IsTrue(m_py_obj); 350 if (r < 0) 351 return exception(); 352 return !!r; 353 } 354 355 llvm::Expected<long long> AsLongLong() const; 356 357 llvm::Expected<unsigned long long> AsUnsignedLongLong() const; 358 359 // wraps on overflow, instead of raising an error. 360 llvm::Expected<unsigned long long> AsModuloUnsignedLongLong() const; 361 362 llvm::Expected<bool> IsInstance(const PythonObject &cls) { 363 if (!m_py_obj || !cls.IsValid()) 364 return nullDeref(); 365 int r = PyObject_IsInstance(m_py_obj, cls.get()); 366 if (r < 0) 367 return exception(); 368 return !!r; 369 } 370 371 protected: 372 PyObject *m_py_obj = nullptr; 373 }; 374 375 376 // This is why C++ needs monads. 377 template <typename T> llvm::Expected<T> As(llvm::Expected<PythonObject> &&obj) { 378 if (!obj) 379 return obj.takeError(); 380 if (!T::Check(obj.get().get())) 381 return llvm::createStringError(llvm::inconvertibleErrorCode(), 382 "type error"); 383 return T(PyRefType::Borrowed, std::move(obj.get().get())); 384 } 385 386 template <> llvm::Expected<bool> As<bool>(llvm::Expected<PythonObject> &&obj); 387 388 template <> 389 llvm::Expected<long long> As<long long>(llvm::Expected<PythonObject> &&obj); 390 391 template <> 392 llvm::Expected<unsigned long long> 393 As<unsigned long long>(llvm::Expected<PythonObject> &&obj); 394 395 template <> 396 llvm::Expected<std::string> As<std::string>(llvm::Expected<PythonObject> &&obj); 397 398 399 template <class T> class TypedPythonObject : public PythonObject { 400 public: 401 TypedPythonObject(PyRefType type, PyObject *py_obj) { 402 if (!py_obj) 403 return; 404 if (T::Check(py_obj)) 405 PythonObject::operator=(PythonObject(type, py_obj)); 406 else if (type == PyRefType::Owned) 407 Py_DECREF(py_obj); 408 } 409 410 TypedPythonObject() = default; 411 }; 412 413 class PythonBytes : public TypedPythonObject<PythonBytes> { 414 public: 415 using TypedPythonObject::TypedPythonObject; 416 explicit PythonBytes(llvm::ArrayRef<uint8_t> bytes); 417 PythonBytes(const uint8_t *bytes, size_t length); 418 419 static bool Check(PyObject *py_obj); 420 421 llvm::ArrayRef<uint8_t> GetBytes() const; 422 423 size_t GetSize() const; 424 425 void SetBytes(llvm::ArrayRef<uint8_t> stringbytes); 426 427 StructuredData::StringSP CreateStructuredString() const; 428 }; 429 430 class PythonByteArray : public TypedPythonObject<PythonByteArray> { 431 public: 432 using TypedPythonObject::TypedPythonObject; 433 explicit PythonByteArray(llvm::ArrayRef<uint8_t> bytes); 434 PythonByteArray(const uint8_t *bytes, size_t length); 435 PythonByteArray(const PythonBytes &object); 436 437 static bool Check(PyObject *py_obj); 438 439 llvm::ArrayRef<uint8_t> GetBytes() const; 440 441 size_t GetSize() const; 442 443 void SetBytes(llvm::ArrayRef<uint8_t> stringbytes); 444 445 StructuredData::StringSP CreateStructuredString() const; 446 }; 447 448 class PythonString : public TypedPythonObject<PythonString> { 449 public: 450 using TypedPythonObject::TypedPythonObject; 451 static llvm::Expected<PythonString> FromUTF8(llvm::StringRef string); 452 453 PythonString() : TypedPythonObject() {} // MSVC requires this for some reason 454 455 explicit PythonString(llvm::StringRef string); // safe, null on error 456 457 static bool Check(PyObject *py_obj); 458 459 llvm::StringRef GetString() const; // safe, empty string on error 460 461 llvm::Expected<llvm::StringRef> AsUTF8() const; 462 463 size_t GetSize() const; 464 465 void SetString(llvm::StringRef string); // safe, null on error 466 467 StructuredData::StringSP CreateStructuredString() const; 468 }; 469 470 class PythonInteger : public TypedPythonObject<PythonInteger> { 471 public: 472 using TypedPythonObject::TypedPythonObject; 473 474 PythonInteger() : TypedPythonObject() {} // MSVC requires this for some reason 475 476 explicit PythonInteger(int64_t value); 477 478 static bool Check(PyObject *py_obj); 479 480 void SetInteger(int64_t value); 481 482 StructuredData::IntegerSP CreateStructuredInteger() const; 483 484 StructuredData::UnsignedIntegerSP CreateStructuredUnsignedInteger() const; 485 486 StructuredData::SignedIntegerSP CreateStructuredSignedInteger() const; 487 }; 488 489 class PythonBoolean : public TypedPythonObject<PythonBoolean> { 490 public: 491 using TypedPythonObject::TypedPythonObject; 492 493 explicit PythonBoolean(bool value); 494 495 static bool Check(PyObject *py_obj); 496 497 bool GetValue() const; 498 499 void SetValue(bool value); 500 501 StructuredData::BooleanSP CreateStructuredBoolean() const; 502 }; 503 504 class PythonList : public TypedPythonObject<PythonList> { 505 public: 506 using TypedPythonObject::TypedPythonObject; 507 508 PythonList() : TypedPythonObject() {} // MSVC requires this for some reason 509 510 explicit PythonList(PyInitialValue value); 511 explicit PythonList(int list_size); 512 513 static bool Check(PyObject *py_obj); 514 515 uint32_t GetSize() const; 516 517 PythonObject GetItemAtIndex(uint32_t index) const; 518 519 void SetItemAtIndex(uint32_t index, const PythonObject &object); 520 521 void AppendItem(const PythonObject &object); 522 523 StructuredData::ArraySP CreateStructuredArray() const; 524 }; 525 526 class PythonTuple : public TypedPythonObject<PythonTuple> { 527 public: 528 using TypedPythonObject::TypedPythonObject; 529 530 explicit PythonTuple(PyInitialValue value); 531 explicit PythonTuple(int tuple_size); 532 PythonTuple(std::initializer_list<PythonObject> objects); 533 PythonTuple(std::initializer_list<PyObject *> objects); 534 535 static bool Check(PyObject *py_obj); 536 537 uint32_t GetSize() const; 538 539 PythonObject GetItemAtIndex(uint32_t index) const; 540 541 void SetItemAtIndex(uint32_t index, const PythonObject &object); 542 543 StructuredData::ArraySP CreateStructuredArray() const; 544 }; 545 546 class PythonDictionary : public TypedPythonObject<PythonDictionary> { 547 public: 548 using TypedPythonObject::TypedPythonObject; 549 550 PythonDictionary() : TypedPythonObject() {} // MSVC requires this for some reason 551 552 explicit PythonDictionary(PyInitialValue value); 553 554 static bool Check(PyObject *py_obj); 555 556 uint32_t GetSize() const; 557 558 PythonList GetKeys() const; 559 560 PythonObject GetItemForKey(const PythonObject &key) const; // DEPRECATED 561 void SetItemForKey(const PythonObject &key, 562 const PythonObject &value); // DEPRECATED 563 564 llvm::Expected<PythonObject> GetItem(const PythonObject &key) const; 565 llvm::Expected<PythonObject> GetItem(const llvm::Twine &key) const; 566 llvm::Error SetItem(const PythonObject &key, const PythonObject &value) const; 567 llvm::Error SetItem(const llvm::Twine &key, const PythonObject &value) const; 568 569 StructuredData::DictionarySP CreateStructuredDictionary() const; 570 }; 571 572 class PythonModule : public TypedPythonObject<PythonModule> { 573 public: 574 using TypedPythonObject::TypedPythonObject; 575 576 static bool Check(PyObject *py_obj); 577 578 static PythonModule BuiltinsModule(); 579 580 static PythonModule MainModule(); 581 582 static PythonModule AddModule(llvm::StringRef module); 583 584 // safe, returns invalid on error; 585 static PythonModule ImportModule(llvm::StringRef name) { 586 std::string s = std::string(name); 587 auto mod = Import(s.c_str()); 588 if (!mod) { 589 llvm::consumeError(mod.takeError()); 590 return PythonModule(); 591 } 592 return std::move(mod.get()); 593 } 594 595 static llvm::Expected<PythonModule> Import(const llvm::Twine &name); 596 597 llvm::Expected<PythonObject> Get(const llvm::Twine &name); 598 599 PythonDictionary GetDictionary() const; 600 }; 601 602 class PythonCallable : public TypedPythonObject<PythonCallable> { 603 public: 604 using TypedPythonObject::TypedPythonObject; 605 606 struct ArgInfo { 607 /* the largest number of positional arguments this callable 608 * can accept, or UNBOUNDED, ie UINT_MAX if it's a varargs 609 * function and can accept an arbitrary number */ 610 unsigned max_positional_args; 611 static constexpr unsigned UNBOUNDED = UINT_MAX; // FIXME c++17 inline 612 }; 613 614 static bool Check(PyObject *py_obj); 615 616 llvm::Expected<ArgInfo> GetArgInfo() const; 617 618 PythonObject operator()(); 619 620 PythonObject operator()(std::initializer_list<PyObject *> args); 621 622 PythonObject operator()(std::initializer_list<PythonObject> args); 623 624 template <typename Arg, typename... Args> 625 PythonObject operator()(const Arg &arg, Args... args) { 626 return operator()({arg, args...}); 627 } 628 }; 629 630 class PythonFile : public TypedPythonObject<PythonFile> { 631 public: 632 using TypedPythonObject::TypedPythonObject; 633 634 PythonFile() : TypedPythonObject() {} // MSVC requires this for some reason 635 636 static bool Check(PyObject *py_obj); 637 638 static llvm::Expected<PythonFile> FromFile(File &file, 639 const char *mode = nullptr); 640 641 llvm::Expected<lldb::FileSP> ConvertToFile(bool borrowed = false); 642 llvm::Expected<lldb::FileSP> 643 ConvertToFileForcingUseOfScriptingIOMethods(bool borrowed = false); 644 }; 645 646 class PythonException : public llvm::ErrorInfo<PythonException> { 647 private: 648 PyObject *m_exception_type, *m_exception, *m_traceback; 649 PyObject *m_repr_bytes; 650 651 public: 652 static char ID; 653 const char *toCString() const; 654 PythonException(const char *caller = nullptr); 655 void Restore(); 656 ~PythonException() override; 657 void log(llvm::raw_ostream &OS) const override; 658 std::error_code convertToErrorCode() const override; 659 bool Matches(PyObject *exc) const; 660 std::string ReadBacktrace() const; 661 }; 662 663 // This extracts the underlying T out of an Expected<T> and returns it. 664 // If the Expected is an Error instead of a T, that error will be converted 665 // into a python exception, and this will return a default-constructed T. 666 // 667 // This is appropriate for use right at the boundary of python calling into 668 // C++, such as in a SWIG typemap. In such a context you should simply 669 // check if the returned T is valid, and if it is, return a NULL back 670 // to python. This will result in the Error being raised as an exception 671 // from python code's point of view. 672 // 673 // For example: 674 // ``` 675 // Expected<Foo *> efoop = some_cpp_function(); 676 // Foo *foop = unwrapOrSetPythonException(efoop); 677 // if (!foop) 678 // return NULL; 679 // do_something(*foop); 680 // 681 // If the Error returned was itself created because a python exception was 682 // raised when C++ code called into python, then the original exception 683 // will be restored. Otherwise a simple string exception will be raised. 684 template <typename T> T unwrapOrSetPythonException(llvm::Expected<T> expected) { 685 if (expected) 686 return expected.get(); 687 llvm::handleAllErrors( 688 expected.takeError(), [](PythonException &E) { E.Restore(); }, 689 [](const llvm::ErrorInfoBase &E) { 690 PyErr_SetString(PyExc_Exception, E.message().c_str()); 691 }); 692 return T(); 693 } 694 695 // This is only here to help incrementally migrate old, exception-unsafe 696 // code. 697 template <typename T> T unwrapIgnoringErrors(llvm::Expected<T> expected) { 698 if (expected) 699 return std::move(expected.get()); 700 llvm::consumeError(expected.takeError()); 701 return T(); 702 } 703 704 llvm::Expected<PythonObject> runStringOneLine(const llvm::Twine &string, 705 const PythonDictionary &globals, 706 const PythonDictionary &locals); 707 708 llvm::Expected<PythonObject> runStringMultiLine(const llvm::Twine &string, 709 const PythonDictionary &globals, 710 const PythonDictionary &locals); 711 712 // Sometimes the best way to interact with a python interpreter is 713 // to run some python code. You construct a PythonScript with 714 // script string. The script assigns some function to `_function_` 715 // and you get a C++ callable object that calls the python function. 716 // 717 // Example: 718 // 719 // const char script[] = R"( 720 // def main(x, y): 721 // .... 722 // )"; 723 // 724 // Expected<PythonObject> cpp_foo_wrapper(PythonObject x, PythonObject y) { 725 // // no need to synchronize access to this global, we already have the GIL 726 // static PythonScript foo(script) 727 // return foo(x, y); 728 // } 729 class PythonScript { 730 const char *script; 731 PythonCallable function; 732 733 llvm::Error Init(); 734 735 public: 736 PythonScript(const char *script) : script(script), function() {} 737 738 template <typename... Args> 739 llvm::Expected<PythonObject> operator()(Args &&... args) { 740 if (llvm::Error error = Init()) 741 return std::move(error); 742 return function.Call(std::forward<Args>(args)...); 743 } 744 }; 745 746 class StructuredPythonObject : public StructuredData::Generic { 747 public: 748 StructuredPythonObject() : StructuredData::Generic() {} 749 750 // Take ownership of the object we received. 751 StructuredPythonObject(PythonObject obj) 752 : StructuredData::Generic(obj.release()) {} 753 754 ~StructuredPythonObject() override { 755 // Hand ownership back to a (temporary) PythonObject instance and let it 756 // take care of releasing it. 757 PythonObject(PyRefType::Owned, static_cast<PyObject *>(GetValue())); 758 } 759 760 bool IsValid() const override { return GetValue() && GetValue() != Py_None; } 761 762 void Serialize(llvm::json::OStream &s) const override; 763 764 private: 765 StructuredPythonObject(const StructuredPythonObject &) = delete; 766 const StructuredPythonObject & 767 operator=(const StructuredPythonObject &) = delete; 768 }; 769 770 } // namespace python 771 } // namespace lldb_private 772 773 #endif 774 775 #endif // LLDB_PLUGINS_SCRIPTINTERPRETER_PYTHON_PYTHONDATAOBJECTS_H 776