obj.h 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. #pragma once
  2. #include "safestl.h"
  3. struct CodeObject;
  4. struct BaseRef;
  5. class VM;
  6. class Frame;
  7. //typedef PyVar (*_CppFuncRaw)(VM*, const pkpy::ArgList&);
  8. typedef std::function<PyVar(VM*, const pkpy::ArgList&)> _CppFuncRaw;
  9. typedef pkpy::shared_ptr<CodeObject> _Code;
  10. struct _CppFunc {
  11. _CppFuncRaw f;
  12. int argc; // DONOT include self
  13. bool method;
  14. _CppFunc(_CppFuncRaw f, int argc, bool method) : f(f), argc(argc), method(method) {}
  15. inline PyVar operator()(VM* vm, const pkpy::ArgList& args) const;
  16. };
  17. struct Function {
  18. _Str name;
  19. _Code code;
  20. std::vector<_Str> args;
  21. _Str starredArg; // empty if no *arg
  22. PyVarDict kwArgs; // empty if no k=v
  23. std::vector<_Str> kwArgsOrder;
  24. bool hasName(const _Str& val) const {
  25. bool _0 = std::find(args.begin(), args.end(), val) != args.end();
  26. bool _1 = starredArg == val;
  27. bool _2 = kwArgs.find(val) != kwArgs.end();
  28. return _0 || _1 || _2;
  29. }
  30. };
  31. struct _BoundedMethod {
  32. PyVar obj;
  33. PyVar method;
  34. };
  35. struct _Range {
  36. i64 start = 0;
  37. i64 stop = -1;
  38. i64 step = 1;
  39. };
  40. struct _Slice {
  41. int start = 0;
  42. int stop = 0x7fffffff;
  43. void normalize(int len){
  44. if(start < 0) start += len;
  45. if(stop < 0) stop += len;
  46. if(start < 0) start = 0;
  47. if(stop > len) stop = len;
  48. }
  49. };
  50. class BaseIterator {
  51. protected:
  52. VM* vm;
  53. PyVar _ref; // keep a reference to the object so it will not be deleted while iterating
  54. public:
  55. virtual PyVar next() = 0;
  56. virtual bool hasNext() = 0;
  57. PyVarRef var;
  58. BaseIterator(VM* vm, PyVar _ref) : vm(vm), _ref(_ref) {}
  59. virtual ~BaseIterator() = default;
  60. };
  61. typedef pkpy::shared_ptr<Function> _Func;
  62. typedef pkpy::shared_ptr<BaseIterator> _Iterator;
  63. struct PyObject {
  64. PyVar _type;
  65. PyVarDict attribs;
  66. inline bool is_type(const PyVar& type) const noexcept{ return this->_type == type; }
  67. inline virtual void* value() = 0;
  68. PyObject(const PyVar& type) : _type(type) {}
  69. virtual ~PyObject() = default;
  70. };
  71. template <typename T>
  72. struct Py_ : PyObject {
  73. T _valueT;
  74. Py_(T val, const PyVar& type) : PyObject(type), _valueT(val) {}
  75. virtual void* value() override { return &_valueT; }
  76. };
  77. #define UNION_GET(T, obj) (((Py_<T>*)((obj).get()))->_valueT)
  78. #define UNION_NAME(obj) UNION_GET(_Str, (obj)->attribs[__name__])
  79. #define UNION_TP_NAME(obj) UNION_GET(_Str, (obj)->_type->attribs[__name__])