base.h 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. #pragma once
  2. #include "stdint.h"
  3. #include "stdbool.h"
  4. #include "stdlib.h"
  5. #include "assert.h"
  6. #include "string.h"
  7. #include "pocketpy/common/utils.h"
  8. #ifdef __cplusplus
  9. extern "C" {
  10. #endif
  11. typedef int16_t pkpy_Type;
  12. typedef struct PyObject PyObject;
  13. typedef struct PyVar{
  14. pkpy_Type type;
  15. bool is_ptr;
  16. int extra;
  17. union {
  18. int64_t _i64;
  19. double _f64;
  20. bool _bool;
  21. PyObject* _obj;
  22. void* _ptr;
  23. // Vec2
  24. };
  25. } PyVar;
  26. #define PyVar__as(T, self) _Generic((T), \
  27. int64_t: self->_i64, \
  28. double: self->_f64, \
  29. bool: self->_bool, \
  30. PyObject*: self->_obj, \
  31. void*: self->_ptr, \
  32. )
  33. static_assert(sizeof(PyVar) == 16, "sizeof(PyVar) != 16");
  34. /* predefined vars */
  35. static const pkpy_Type tp_object = 1, tp_type = 2;
  36. static const pkpy_Type tp_int = 3, tp_float = 4, tp_bool = 5, tp_str = 6;
  37. static const pkpy_Type tp_list = 7, tp_tuple = 8;
  38. static const pkpy_Type tp_slice = 9, tp_range = 10, tp_module = 11;
  39. static const pkpy_Type tp_function = 12, tp_native_func = 13, tp_bound_method = 14;
  40. static const pkpy_Type tp_super = 15, tp_exception = 16, tp_bytes = 17, tp_mappingproxy = 18;
  41. static const pkpy_Type tp_dict = 19, tp_property = 20, tp_star_wrapper = 21;
  42. static const pkpy_Type tp_staticmethod = 22, tp_classmethod = 23;
  43. static const pkpy_Type tp_none_type = 24, tp_not_implemented_type = 25;
  44. static const pkpy_Type tp_ellipsis = 26;
  45. static const pkpy_Type tp_op_call = 27, tp_op_yield = 28;
  46. PK_INLINE bool PyVar__is_null(const PyVar* self) { return self->type == 0; }
  47. PK_INLINE int64_t PyVar__hash(const PyVar* self) { return self->extra + self->_i64; }
  48. PK_INLINE void PyVar__ctor(PyVar* self, pkpy_Type type, PyObject* obj){
  49. self->type = type;
  50. self->is_ptr = true;
  51. self->_obj = obj;
  52. }
  53. void PyVar__ctor3(PyVar* self, PyObject* existing);
  54. PK_INLINE bool PyVar__IS_OP(const PyVar* a, const PyVar* b){
  55. return a->is_ptr && b->is_ptr && a->_obj == b->_obj;
  56. }
  57. #define pkpy_Var__is_null(self) ((self)->type == 0)
  58. #define pkpy_Var__set_null(self) do { (self)->type = 0; } while(0)
  59. bool pkpy_Var__eq__(void *vm, PyVar a, PyVar b);
  60. int64_t pkpy_Var__hash__(void *vm, PyVar a);
  61. extern PyVar pkpy_True, pkpy_False, pkpy_None;
  62. extern PyVar pkpy_NotImplemented, pkpy_Ellipsis;
  63. extern PyVar pkpy_NULL, pkpy_OP_CALL, pkpy_OP_YIELD;
  64. #ifdef __cplusplus
  65. }
  66. #endif
  67. /*
  68. SSO types:
  69. 1. int64_t
  70. 2. double
  71. 3. bool (dummy)
  72. 4. tuple (extra + void*)
  73. 5. string (extra + void* or buf)
  74. */