obj.h 2.2 KB

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