obj.h 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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. class PyObject;
  11. class CodeObject;
  12. class BasePointer;
  13. class VM;
  14. typedef std::shared_ptr<PyObject> PyVar;
  15. typedef PyVar PyVarOrNull;
  16. typedef std::vector<PyVar> PyVarList;
  17. typedef std::unordered_map<_Str, PyVar> StlDict;
  18. typedef std::shared_ptr<const BasePointer> _Pointer;
  19. typedef PyVar (*_CppFunc)(VM*, PyVarList);
  20. typedef std::shared_ptr<CodeObject> _Code;
  21. struct _Func {
  22. _Str name;
  23. _Code code;
  24. std::vector<_Str> args;
  25. _Str starredArg; // empty if no *arg
  26. StlDict kwArgs; // empty if no k=v
  27. _Str doubleStarredArg; // empty if no **kwargs
  28. bool hasName(const _Str& val) const {
  29. bool _0 = std::find(args.begin(), args.end(), val) != args.end();
  30. bool _1 = starredArg == val;
  31. bool _2 = kwArgs.find(val) != kwArgs.end();
  32. bool _3 = doubleStarredArg == val;
  33. return _0 || _1 || _2 || _3;
  34. }
  35. };
  36. struct BoundedMethod {
  37. PyVar obj;
  38. PyVar method;
  39. };
  40. struct _Range {
  41. int start = 0;
  42. int stop = -1;
  43. int step = 1;
  44. };
  45. struct _Slice {
  46. int start = 0;
  47. int stop = 2147483647;
  48. void normalize(int len){
  49. if(start < 0) start += len;
  50. if(stop < 0) stop += len;
  51. if(start < 0) start = 0;
  52. if(stop > len) stop = len;
  53. }
  54. };
  55. class _Iterator {
  56. private:
  57. PyVar _ref; // keep a reference to the object so it will not be deleted while iterating
  58. public:
  59. virtual PyVar next() = 0;
  60. virtual bool hasNext() = 0;
  61. _Iterator(PyVar _ref) : _ref(_ref) {}
  62. };
  63. typedef std::variant<int,float,bool,_Str,PyVarList,_CppFunc,_Func,std::shared_ptr<_Iterator>,BoundedMethod,_Range,_Slice,_Pointer> _Value;
  64. #define UNREACHABLE() throw std::runtime_error("Unreachable code")
  65. struct PyObject {
  66. StlDict attribs;
  67. _Value _native;
  68. inline bool isType(const PyVar& type){
  69. return attribs[__class__] == type;
  70. }
  71. // currently __name__ is only used for 'type'
  72. _Str getName(){
  73. _Value val = attribs["__name__"]->_native;
  74. return std::get<_Str>(val);
  75. }
  76. _Str getTypeName(){
  77. return attribs[__class__]->getName();
  78. }
  79. PyObject(_Value val): _native(val) {}
  80. };