obj.h 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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 std::shared_ptr<const BasePointer> _Pointer;
  10. typedef PyVar (*_CppFunc)(VM*, const pkpy::ArgList&);
  11. typedef std::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. PyVar _ref; // keep a reference to the object so it will not be deleted while iterating
  48. VM* vm;
  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. };
  55. typedef std::shared_ptr<Function> _Func;
  56. typedef std::variant<PyVar,_Int,_Float,bool,_Str,PyVarList,_CppFunc,_Func,std::shared_ptr<_Iterator>,_BoundedMethod,_Range,_Slice,_Pointer> _Value;
  57. const int _SIZEOF_VALUE = sizeof(_Value);
  58. struct PyObject {
  59. PyVarDict attribs;
  60. _Value _native;
  61. PyVar _type;
  62. inline bool isType(const PyVar& type){
  63. return this->_type == type;
  64. }
  65. inline void setType(const PyVar& type){
  66. this->_type = type;
  67. this->attribs[__class__] = type;
  68. }
  69. // currently __name__ is only used for 'type'
  70. _Str getName(){
  71. _Value val = attribs[__name__]->_native;
  72. return std::get<_Str>(val);
  73. }
  74. _Str getTypeName(){
  75. return _type->getName();
  76. }
  77. PyObject(const _Value& val): _native(val) {}
  78. PyObject(_Value&& val): _native(std::move(val)) {}
  79. };