obj.h 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  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.3.1"
  10. class CodeObject;
  11. class BasePointer;
  12. class VM;
  13. class Frame;
  14. class PkExportedResource {};
  15. typedef std::shared_ptr<const BasePointer> _Pointer;
  16. typedef PyVar (*_CppFunc)(VM*, const pkpy::ArgList&);
  17. typedef std::shared_ptr<CodeObject> _Code;
  18. struct Function {
  19. _Str name;
  20. _Code code;
  21. std::vector<_Str> args;
  22. _Str starredArg; // empty if no *arg
  23. PyVarDict kwArgs; // empty if no k=v
  24. std::vector<_Str> kwArgsOrder;
  25. bool hasName(const _Str& val) const {
  26. bool _0 = std::find(args.begin(), args.end(), val) != args.end();
  27. bool _1 = starredArg == val;
  28. bool _2 = kwArgs.find(val) != kwArgs.end();
  29. return _0 || _1 || _2;
  30. }
  31. };
  32. struct _BoundedMethod {
  33. PyVar obj;
  34. PyVar method;
  35. };
  36. struct _Range {
  37. _Int start = 0;
  38. _Int stop = -1;
  39. _Int step = 1;
  40. };
  41. struct _Slice {
  42. int start = 0;
  43. int stop = 2147483647; // container types always use int32 as index, no support for int64
  44. void normalize(int len){
  45. if(start < 0) start += len;
  46. if(stop < 0) stop += len;
  47. if(start < 0) start = 0;
  48. if(stop > len) stop = len;
  49. }
  50. };
  51. class _Iterator {
  52. protected:
  53. PyVar _ref; // keep a reference to the object so it will not be deleted while iterating
  54. VM* vm;
  55. public:
  56. virtual PyVar next() = 0;
  57. virtual bool hasNext() = 0;
  58. _Pointer var;
  59. _Iterator(VM* vm, PyVar _ref) : vm(vm), _ref(_ref) {}
  60. };
  61. typedef std::shared_ptr<Function> _Func;
  62. typedef std::variant<PyVar,_Int,_Float,bool,_Str,PyVarList,_CppFunc,_Func,std::shared_ptr<_Iterator>,_BoundedMethod,_Range,_Slice,_Pointer> _Value;
  63. const int _SIZEOF_VALUE = sizeof(_Value);
  64. struct PyObject {
  65. PyVarDict attribs;
  66. _Value _native;
  67. PyVar _type;
  68. inline bool isType(const PyVar& type){
  69. return this->_type == type;
  70. }
  71. inline void setType(const PyVar& type){
  72. this->_type = type;
  73. this->attribs[__class__] = type;
  74. }
  75. // currently __name__ is only used for 'type'
  76. _Str getName(){
  77. _Value val = attribs[__name__]->_native;
  78. return std::get<_Str>(val);
  79. }
  80. _Str getTypeName(){
  81. return _type->getName();
  82. }
  83. PyObject(const _Value& val): _native(val) {}
  84. PyObject(_Value&& val): _native(std::move(val)) {}
  85. };