obj.h 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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 _Iterator {
  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. _Iterator(VM* vm, PyVar _ref) : vm(vm), _ref(_ref) {}
  54. virtual ~_Iterator() = default;
  55. };
  56. typedef pkpy::shared_ptr<Function> _Func;
  57. typedef std::variant<PyVar,_Int,_Float,bool,_Str,PyVarList,_CppFunc,_Func,pkpy::shared_ptr<_Iterator>,_BoundedMethod,_Range,_Slice,_Pointer> _Value;
  58. const int VALUE_SIZE = sizeof(_Value);
  59. struct PyObject {
  60. PyVarDict attribs;
  61. _Value _native;
  62. PyVar _type;
  63. inline bool isType(const PyVar& type){
  64. return this->_type == type;
  65. }
  66. inline void setType(const PyVar& type){
  67. this->_type = type;
  68. // this->attribs[__class__] = type;
  69. }
  70. // currently __name__ is only used for 'type'
  71. _Str getName(){
  72. _Value val = attribs[__name__]->_native;
  73. return std::get<_Str>(val);
  74. }
  75. _Str getTypeName(){
  76. return _type->getName();
  77. }
  78. PyObject(const _Value& val): _native(val) {}
  79. PyObject(_Value&& val): _native(std::move(val)) {}
  80. };