py_object.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. #include "pocketpy/interpreter/vm.h"
  2. #include "pocketpy/common/sstream.h"
  3. #include "pocketpy/pocketpy.h"
  4. static bool _py_object__new__(int argc, py_Ref argv) {
  5. if(argc == 0) return TypeError("object.__new__(): not enough arguments");
  6. py_Type cls = py_totype(py_arg(0));
  7. pk_TypeInfo* ti = c11__at(pk_TypeInfo, &pk_current_vm->types, cls);
  8. if(!ti->is_python) {
  9. return TypeError("object.__new__(%t) is not safe, use %t.__new__()", cls, cls);
  10. }
  11. py_newobject(py_retval(), cls, -1, 0);
  12. return true;
  13. }
  14. static bool _py_object__hash__(int argc, py_Ref argv) {
  15. PY_CHECK_ARGC(1);
  16. assert(argv->is_ptr);
  17. py_newint(py_retval(), (py_i64)argv->_obj);
  18. return true;
  19. }
  20. static bool _py_object__eq__(int argc, py_Ref argv) {
  21. PY_CHECK_ARGC(2);
  22. bool res = py_isidentical(py_arg(0), py_arg(1));
  23. py_newbool(py_retval(), res);
  24. return true;
  25. }
  26. static bool _py_object__ne__(int argc, py_Ref argv) {
  27. PY_CHECK_ARGC(2);
  28. bool res = py_isidentical(py_arg(0), py_arg(1));
  29. py_newbool(py_retval(), !res);
  30. return true;
  31. }
  32. static bool _py_object__repr__(int argc, py_Ref argv) {
  33. PY_CHECK_ARGC(1);
  34. assert(argv->is_ptr);
  35. c11_sbuf buf;
  36. c11_sbuf__ctor(&buf);
  37. pk_sprintf(&buf, "<%t object at %p>", argv->type, argv->_obj);
  38. c11_sbuf__py_submit(&buf, py_retval());
  39. return true;
  40. }
  41. static bool _py_type__repr__(int argc, py_Ref argv) {
  42. PY_CHECK_ARGC(1);
  43. c11_sbuf buf;
  44. c11_sbuf__ctor(&buf);
  45. pk_sprintf(&buf, "<class '%t'>", py_totype(argv));
  46. c11_sbuf__py_submit(&buf, py_retval());
  47. return true;
  48. }
  49. static bool _py_type__new__(int argc, py_Ref argv){
  50. PY_CHECK_ARGC(2);
  51. py_Type type = py_typeof(py_arg(1));
  52. py_assign(py_retval(), py_tpobject(type));
  53. return true;
  54. }
  55. void pk_object__register() {
  56. // use staticmethod
  57. py_bindmagic(tp_object, __new__, _py_object__new__);
  58. py_bindmagic(tp_object, __hash__, _py_object__hash__);
  59. py_bindmagic(tp_object, __eq__, _py_object__eq__);
  60. py_bindmagic(tp_object, __ne__, _py_object__ne__);
  61. py_bindmagic(tp_object, __repr__, _py_object__repr__);
  62. // type patch...
  63. py_bindmagic(tp_type, __repr__, _py_type__repr__);
  64. py_bindmagic(tp_type, __new__, _py_type__new__);
  65. }