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