cast.c 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. #include "pocketpy/objects/base.h"
  2. #include "pocketpy/pocketpy.h"
  3. #include "pocketpy/objects/object.h"
  4. #include "pocketpy/interpreter/vm.h"
  5. int64_t py_toint(py_Ref self) {
  6. assert(self->type == tp_int);
  7. return self->_i64;
  8. }
  9. double py_tofloat(py_Ref self) {
  10. assert(self->type == tp_float);
  11. return self->_f64;
  12. }
  13. bool py_castfloat(py_Ref self, double* out) {
  14. switch(self->type) {
  15. case tp_int: *out = (double)self->_i64; return true;
  16. case tp_float: *out = self->_f64; return true;
  17. default: return TypeError("expected 'int' or 'float', got '%t'", self->type);
  18. }
  19. }
  20. bool py_castfloat32(py_Ref self, float* out) {
  21. switch(self->type) {
  22. case tp_int: *out = (float)self->_i64; return true;
  23. case tp_float: *out = (float)self->_f64; return true;
  24. default: return TypeError("expected 'int' or 'float', got '%t'", self->type);
  25. }
  26. }
  27. bool py_castint(py_Ref self, int64_t* out) {
  28. if(self->type == tp_int) {
  29. *out = self->_i64;
  30. return true;
  31. }
  32. return TypeError("expected 'int', got '%t'", self->type);
  33. }
  34. bool py_tobool(py_Ref self) {
  35. assert(self->type == tp_bool);
  36. return self->_bool;
  37. }
  38. py_Type py_totype(py_Ref self) {
  39. assert(self->type == tp_type);
  40. py_Type* ud = py_touserdata(self);
  41. return *ud;
  42. }
  43. void* py_touserdata(py_Ref self) {
  44. assert(self && self->is_ptr);
  45. return PyObject__userdata(self->_obj);
  46. }
  47. bool py_istype(py_Ref self, py_Type type) { return self->type == type; }
  48. bool py_checktype(py_Ref self, py_Type type) {
  49. if(self->type == type) return true;
  50. return TypeError("expected '%t', got '%t'", type, self->type);
  51. }
  52. bool py_isinstance(py_Ref obj, py_Type type) { return py_issubclass(obj->type, type); }
  53. bool py_issubclass(py_Type derived, py_Type base) {
  54. TypeList* types = &pk_current_vm->types;
  55. do {
  56. if(derived == base) return true;
  57. derived = TypeList__get(types, derived)->base;
  58. } while(derived);
  59. return false;
  60. }
  61. py_Type py_typeof(py_Ref self) { return self->type; }
  62. py_Type py_gettype(const char* module, py_Name name) {
  63. py_Ref mod;
  64. if(module != NULL) {
  65. mod = py_getmodule(module);
  66. if(!mod) return 0;
  67. } else {
  68. mod = &pk_current_vm->builtins;
  69. }
  70. py_Ref object = py_getdict(mod, name);
  71. if(object && py_istype(object, tp_type)) return py_totype(object);
  72. return 0;
  73. }