obj.h 2.1 KB

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