error.hpp 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. #pragma once
  2. #include "pocketpy/common/str.hpp"
  3. #include "pocketpy/objects/sourcedata.hpp"
  4. namespace pkpy {
  5. struct NeedMoreLines {
  6. NeedMoreLines(bool is_compiling_class) : is_compiling_class(is_compiling_class) {}
  7. bool is_compiling_class;
  8. };
  9. enum class InternalExceptionType : int { Null, Handled, Unhandled, ToBeRaised };
  10. struct InternalException final {
  11. InternalExceptionType type;
  12. int arg;
  13. InternalException() : type(InternalExceptionType::Null), arg(-1) {}
  14. InternalException(InternalExceptionType type, int arg = -1) : type(type), arg(arg) {}
  15. };
  16. struct Exception {
  17. StrName type;
  18. Str msg;
  19. bool is_re;
  20. int _ip_on_error;
  21. void* _code_on_error;
  22. PyObject* _self; // weak reference
  23. struct Frame {
  24. std::shared_ptr<SourceData> src; // weak ref
  25. int lineno;
  26. const char* cursor;
  27. std::string name;
  28. Str snapshot() const { return src->snapshot(lineno, cursor, name); }
  29. Frame(std::shared_ptr<SourceData> src, int lineno, const char* cursor, std::string_view name) :
  30. src(src), lineno(lineno), cursor(cursor), name(name) {}
  31. };
  32. vector<Frame> stacktrace;
  33. Exception(StrName type) : type(type), is_re(true), _ip_on_error(-1), _code_on_error(nullptr), _self(nullptr) {}
  34. PyObject* self() const {
  35. assert(_self != nullptr);
  36. return _self;
  37. }
  38. template <typename... Args>
  39. void st_push(Args&&... args) {
  40. if(stacktrace.size() >= 7) return;
  41. stacktrace.emplace_back(std::forward<Args>(args)...);
  42. }
  43. Str summary() const;
  44. };
  45. struct TopLevelException : std::exception {
  46. VM* vm;
  47. Exception* ptr;
  48. TopLevelException(VM* vm, Exception* ptr) : vm(vm), ptr(ptr) {}
  49. Str summary() const { return ptr->summary(); }
  50. const char* what() const noexcept override {
  51. static Str cached_summary;
  52. cached_summary = summary();
  53. return cached_summary.c_str();
  54. }
  55. };
  56. struct Error{
  57. const char* type;
  58. std::shared_ptr<SourceData> src;
  59. int lineno;
  60. const char* cursor;
  61. char msg[100];
  62. i64 userdata;
  63. };
  64. } // namespace pkpy