obj.h 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. #pragma once
  2. #include <unordered_map>
  3. #include <memory>
  4. #include <variant>
  5. #include <functional>
  6. #include <stack>
  7. #include <cmath>
  8. #include <stdexcept>
  9. #include "str.h"
  10. typedef int64_t _Int;
  11. typedef double _Float;
  12. class PyObject;
  13. class CodeObject;
  14. class BasePointer;
  15. class VM;
  16. typedef std::shared_ptr<PyObject> PyVar;
  17. typedef PyVar PyVarOrNull;
  18. typedef std::vector<PyVar> PyVarList;
  19. typedef std::unordered_map<_Str, PyVar> PyVarDict;
  20. typedef std::shared_ptr<const BasePointer> _Pointer;
  21. typedef PyVar (*_CppFunc)(VM*, PyVarList);
  22. typedef std::shared_ptr<CodeObject> _Code;
  23. struct _Func {
  24. _Str name;
  25. _Code code;
  26. std::vector<_Str> args;
  27. _Str starredArg; // empty if no *arg
  28. PyVarDict kwArgs; // empty if no k=v
  29. _Str doubleStarredArg; // empty if no **kwargs
  30. bool hasName(const _Str& val) const {
  31. bool _0 = std::find(args.begin(), args.end(), val) != args.end();
  32. bool _1 = starredArg == val;
  33. bool _2 = kwArgs.find(val) != kwArgs.end();
  34. bool _3 = doubleStarredArg == val;
  35. return _0 || _1 || _2 || _3;
  36. }
  37. };
  38. struct BoundedMethod {
  39. PyVar obj;
  40. PyVar method;
  41. };
  42. struct _Range {
  43. _Int start = 0;
  44. _Int stop = -1;
  45. _Int step = 1;
  46. };
  47. struct _Slice {
  48. int start = 0;
  49. int stop = 2147483647; // contain types always use int32 as index, no support for int64
  50. void normalize(int len){
  51. if(start < 0) start += len;
  52. if(stop < 0) stop += len;
  53. if(start < 0) start = 0;
  54. if(stop > len) stop = len;
  55. }
  56. };
  57. class _Iterator {
  58. private:
  59. PyVar _ref; // keep a reference to the object so it will not be deleted while iterating
  60. public:
  61. virtual PyVar next() = 0;
  62. virtual bool hasNext() = 0;
  63. _Pointer var;
  64. _Iterator(PyVar _ref) : _ref(_ref) {}
  65. };
  66. typedef std::variant<_Int,_Float,bool,_Str,PyVarList,_CppFunc,_Func,std::shared_ptr<_Iterator>,BoundedMethod,_Range,_Slice,_Pointer> _Value;
  67. #define UNREACHABLE() throw std::runtime_error("Unreachable code")
  68. struct PyObject {
  69. PyVarDict attribs;
  70. _Value _native;
  71. inline bool isType(const PyVar& type){
  72. return 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 attribs[__class__]->getName();
  81. }
  82. PyObject(_Value val): _native(val) {}
  83. };