obj.h 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. #pragma once
  2. #include "safestl.h"
  3. typedef int64_t _Int;
  4. typedef double _Float;
  5. const _Int _Int_MAX_POS = 9223372036854775807LL;
  6. const _Int _Int_MAX_NEG = -9223372036854775807LL;
  7. const _Float _FLOAT_INF_POS = INFINITY;
  8. const _Float _FLOAT_INF_NEG = -INFINITY;
  9. #define PK_VERSION "0.2.9"
  10. class CodeObject;
  11. class BasePointer;
  12. class VM;
  13. class PkExportedResource {};
  14. typedef std::shared_ptr<const BasePointer> _Pointer;
  15. typedef PyVar (*_CppFunc)(VM*, const pkpy::ArgList&);
  16. typedef std::shared_ptr<CodeObject> _Code;
  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. _Int start = 0;
  37. _Int stop = -1;
  38. _Int step = 1;
  39. };
  40. struct _Slice {
  41. int start = 0;
  42. int stop = 2147483647; // container types always use int32 as index, no support for int64
  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 _Iterator {
  51. protected:
  52. PyVar _ref; // keep a reference to the object so it will not be deleted while iterating
  53. VM* vm;
  54. public:
  55. virtual PyVar next() = 0;
  56. virtual bool hasNext() = 0;
  57. _Pointer var;
  58. _Iterator(VM* vm, PyVar _ref) : vm(vm), _ref(_ref) {}
  59. };
  60. typedef std::shared_ptr<Function> _Func;
  61. typedef std::variant<_Int,_Float,bool,_Str,PyVarList,_CppFunc,_Func,std::shared_ptr<_Iterator>,_BoundedMethod,_Range,_Slice,_Pointer> _Value;
  62. const int _SIZEOF_VALUE = sizeof(_Value);
  63. struct PyObject {
  64. PyVarDict attribs;
  65. _Value _native;
  66. PyVar _type;
  67. inline bool isType(const PyVar& type){
  68. return this->_type == type;
  69. }
  70. inline void setType(const PyVar& type){
  71. this->_type = type;
  72. this->attribs[__class__] = type;
  73. }
  74. // currently __name__ is only used for 'type'
  75. _Str getName(){
  76. _Value val = attribs[__name__]->_native;
  77. return std::get<_Str>(val);
  78. }
  79. _Str getTypeName(){
  80. return _type->getName();
  81. }
  82. PyObject(const _Value& val): _native(val) {}
  83. PyObject(_Value&& val): _native(std::move(val)) {}
  84. };