stack_ops.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. #include "pocketpy/pocketpy.h"
  2. #include "pocketpy/common/utils.h"
  3. #include "pocketpy/objects/object.h"
  4. #include "pocketpy/interpreter/vm.h"
  5. py_Ref py_getreg(int i) { return pk_current_vm->reg + i; }
  6. void py_setreg(int i, py_Ref val) { pk_current_vm->reg[i] = *val; }
  7. py_Ref py_getdict(py_Ref self, py_Name name) {
  8. assert(self && self->is_ptr);
  9. if(!py_ismagicname(name) || self->type != tp_type) {
  10. return NameDict__try_get(PyObject__dict(self->_obj), name);
  11. } else {
  12. py_Type* ud = py_touserdata(self);
  13. py_Ref slot = py_tpmagic(*ud, name);
  14. return py_isnil(slot) ? NULL : slot;
  15. }
  16. }
  17. void py_setdict(py_Ref self, py_Name name, py_Ref val) {
  18. assert(self && self->is_ptr);
  19. if(!py_ismagicname(name) || self->type != tp_type) {
  20. NameDict__set(PyObject__dict(self->_obj), name, *val);
  21. } else {
  22. py_Type* ud = py_touserdata(self);
  23. *py_tpmagic(*ud, name) = *val;
  24. }
  25. }
  26. py_TmpRef py_emplacedict(py_Ref self, py_Name name){
  27. py_setdict(self, name, py_NIL);
  28. return py_getdict(self, name);
  29. }
  30. bool py_deldict(py_Ref self, py_Name name) {
  31. assert(self && self->is_ptr);
  32. if(!py_ismagicname(name) || self->type != tp_type) {
  33. return NameDict__del(PyObject__dict(self->_obj), name);
  34. } else {
  35. py_Type* ud = py_touserdata(self);
  36. py_newnil(py_tpmagic(*ud, name));
  37. return true;
  38. }
  39. }
  40. py_Ref py_getslot(py_Ref self, int i) {
  41. assert(self && self->is_ptr);
  42. assert(i >= 0 && i < self->_obj->slots);
  43. return PyObject__slots(self->_obj) + i;
  44. }
  45. void py_setslot(py_Ref self, int i, py_Ref val) {
  46. assert(self && self->is_ptr);
  47. assert(i >= 0 && i < self->_obj->slots);
  48. PyObject__slots(self->_obj)[i] = *val;
  49. }
  50. void py_assign(py_Ref dst, py_Ref src) { *dst = *src; }
  51. /* Stack References */
  52. py_Ref py_peek(int i) {
  53. assert(i <= 0);
  54. return pk_current_vm->stack.sp + i;
  55. }
  56. void py_pop() {
  57. VM* vm = pk_current_vm;
  58. vm->stack.sp--;
  59. }
  60. void py_shrink(int n) {
  61. VM* vm = pk_current_vm;
  62. vm->stack.sp -= n;
  63. }
  64. void py_push(py_Ref src) {
  65. VM* vm = pk_current_vm;
  66. *vm->stack.sp++ = *src;
  67. }
  68. void py_pushnil() {
  69. VM* vm = pk_current_vm;
  70. py_newnil(vm->stack.sp++);
  71. }
  72. py_Ref py_pushtmp() {
  73. VM* vm = pk_current_vm;
  74. py_newnil(vm->stack.sp++);
  75. return py_peek(-1);
  76. }