pocketpy.h 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  1. #pragma once
  2. #include <stdint.h>
  3. #include <stdbool.h>
  4. #include <stdarg.h>
  5. #include <stddef.h>
  6. #include "pocketpy/common/config.h"
  7. #include "pocketpy/common/export.h"
  8. #ifdef __cplusplus
  9. extern "C" {
  10. #endif
  11. /************* Public Types *************/
  12. typedef struct py_TValue py_TValue;
  13. typedef uint16_t py_Name;
  14. typedef int16_t py_Type;
  15. typedef int64_t py_i64;
  16. typedef double py_f64;
  17. typedef void (*py_Dtor)(void*);
  18. #define PY_RAISE // mark a function that can raise an exception
  19. typedef struct c11_sv {
  20. const char* data;
  21. int size;
  22. } c11_sv;
  23. /// Generic reference.
  24. typedef py_TValue* py_Ref;
  25. /// An object reference which has the same lifespan as the object.
  26. typedef py_TValue* py_ObjectRef;
  27. /// A global reference which has the same lifespan as the VM.
  28. typedef py_TValue* py_GlobalRef;
  29. /// A specific location in the stack.
  30. typedef py_TValue* py_StackRef;
  31. /// An item of a container. It invalidates after the container is modified.
  32. typedef py_TValue* py_ItemRef;
  33. /// Native function signature.
  34. /// @param argc number of arguments.
  35. /// @param argv array of arguments. Use `py_arg(i)` macro to get the i-th argument.
  36. /// @return true if the function is successful.
  37. typedef bool (*py_CFunction)(int argc, py_StackRef argv) PY_RAISE;
  38. enum py_CompileMode { EXEC_MODE, EVAL_MODE, SINGLE_MODE };
  39. extern py_GlobalRef py_True;
  40. extern py_GlobalRef py_False;
  41. extern py_GlobalRef py_None;
  42. extern py_GlobalRef py_NIL;
  43. /************* Global Setup *************/
  44. /// Initialize pocketpy and the default VM.
  45. void py_initialize();
  46. /// Finalize pocketpy.
  47. void py_finalize();
  48. /// Get the current VM index.
  49. int py_currentvm();
  50. /// Switch to a VM.
  51. /// @param index index of the VM ranging from 0 to 16 (exclusive). `0` is the default VM.
  52. void py_switchvm(int index);
  53. /// Run a source string.
  54. /// @param source source string.
  55. /// @param filename filename (for error messages).
  56. /// @param mode compile mode. Use `EXEC_MODE` for statements `EVAL_MODE` for expressions.
  57. /// @param module target module. Use NULL for the main module.
  58. /// @return true if the execution is successful.
  59. bool py_exec(const char* source,
  60. const char* filename,
  61. enum py_CompileMode mode,
  62. py_Ref module) PY_RAISE;
  63. /// Compile a source string into a code object.
  64. /// Use python's `exec()` or `eval()` to execute it.
  65. bool py_compile(const char* source,
  66. const char* filename,
  67. enum py_CompileMode mode,
  68. bool is_dynamic) PY_RAISE;
  69. /// Python equivalent to `globals()`.
  70. void py_newglobals(py_Ref);
  71. /// Python equivalent to `locals()`.
  72. /// NOTE: Return a temporary object, which expires on the associated function return.
  73. void py_newlocals(py_Ref);
  74. /************* Values Creation *************/
  75. /// Create an `int` object.
  76. void py_newint(py_Ref, py_i64);
  77. /// Create a `float` object.
  78. void py_newfloat(py_Ref, py_f64);
  79. /// Create a `bool` object.
  80. void py_newbool(py_Ref, bool);
  81. /// Create a `str` object from a null-terminated string (utf-8).
  82. void py_newstr(py_Ref, const char*);
  83. /// Create a `str` object from a char array (utf-8).
  84. void py_newstrn(py_Ref, const char*, int);
  85. /// Create a `bytes` object with `n` UNINITIALIZED bytes.
  86. unsigned char* py_newbytes(py_Ref, int n);
  87. /// Create a `None` object.
  88. void py_newnone(py_Ref);
  89. /// Create a `NotImplemented` object.
  90. void py_newnotimplemented(py_Ref out);
  91. /// Create a `...` object.
  92. void py_newellipsis(py_Ref out);
  93. /// Create a `nil` object. `nil` is an invalid representation of an object.
  94. /// Don't use it unless you know what you are doing.
  95. void py_newnil(py_Ref);
  96. /// Create a `tuple` with `n` UNINITIALIZED elements.
  97. /// You should initialize all elements before using it.
  98. void py_newtuple(py_Ref, int n);
  99. /// Create an empty `list`.
  100. void py_newlist(py_Ref);
  101. /// Create a `list` with `n` UNINITIALIZED elements.
  102. /// You should initialize all elements before using it.
  103. void py_newlistn(py_Ref, int n);
  104. /// Create an empty `dict`.
  105. void py_newdict(py_Ref);
  106. /// Create an UNINITIALIZED `slice` object.
  107. /// You should use `py_setslot()` to set `start`, `stop`, and `step`.
  108. void py_newslice(py_Ref);
  109. /// Create a `nativefunc` object.
  110. void py_newnativefunc(py_Ref out, py_CFunction);
  111. /// Create a `function` object.
  112. py_Name
  113. py_newfunction(py_Ref out, const char* sig, py_CFunction f, const char* docstring, int slots);
  114. /// Create a `boundmethod` object.
  115. void py_newboundmethod(py_Ref out, py_Ref self, py_Ref func);
  116. /************* Name Convertions *************/
  117. /// Convert a null-terminated string to a name.
  118. py_Name py_name(const char*);
  119. /// Convert a name to a null-terminated string.
  120. const char* py_name2str(py_Name);
  121. /// Convert a name to a `c11_sv`.
  122. py_Name py_namev(c11_sv name);
  123. /// Convert a `c11_sv` to a name.
  124. c11_sv py_name2sv(py_Name);
  125. #define py_ismagicname(name) (name <= __missing__)
  126. /************* Meta Operations *************/
  127. /// Create a new type.
  128. /// @param name name of the type.
  129. /// @param base base type.
  130. /// @param module module where the type is defined. Use `NULL` for built-in types.
  131. /// @param dtor destructor function. Use `NULL` if not needed.
  132. py_Type py_newtype(const char* name, py_Type base, const py_GlobalRef module, py_Dtor dtor);
  133. /// Create a new object.
  134. /// @param out output reference.
  135. /// @param type type of the object.
  136. /// @param slots number of slots. Use -1 to create a `__dict__`.
  137. /// @param udsize size of your userdata.
  138. /// @return pointer to the userdata.
  139. void* py_newobject(py_Ref out, py_Type type, int slots, int udsize);
  140. /************* Type Cast *************/
  141. /// Convert an `int` object in python to `int64_t`.
  142. py_i64 py_toint(py_Ref);
  143. /// Convert a `float` object in python to `double`.
  144. py_f64 py_tofloat(py_Ref);
  145. /// Cast a `int` or `float` object in python to `double`.
  146. /// If successful, returns true and set the value to `out`.
  147. /// Otherwise, return false and raise `TypeError`.
  148. bool py_castfloat(py_Ref, py_f64* out) PY_RAISE;
  149. /// Convert a `bool` object in python to `bool`.
  150. bool py_tobool(py_Ref);
  151. /// Convert a `type` object in python to `py_Type`.
  152. py_Type py_totype(py_Ref);
  153. /// Convert a `str` object in python to null-terminated string.
  154. const char* py_tostr(py_Ref);
  155. /// Convert a `str` object in python to char array.
  156. const char* py_tostrn(py_Ref, int* size);
  157. /// Convert a `str` object in python to `c11_sv`.
  158. c11_sv py_tosv(py_Ref);
  159. /// Convert a `bytes` object in python to char array.
  160. unsigned char* py_tobytes(py_Ref, int* size);
  161. /// Convert a user-defined object to its userdata.
  162. void* py_touserdata(py_Ref);
  163. #define py_isint(self) py_istype(self, tp_int)
  164. #define py_isfloat(self) py_istype(self, tp_float)
  165. #define py_isbool(self) py_istype(self, tp_bool)
  166. #define py_isstr(self) py_istype(self, tp_str)
  167. #define py_islist(self) py_istype(self, tp_list)
  168. #define py_istuple(self) py_istype(self, tp_tuple)
  169. #define py_isdict(self) py_istype(self, tp_dict)
  170. #define py_isnil(self) py_istype(self, 0)
  171. #define py_isnone(self) py_istype(self, tp_NoneType)
  172. /// Get the type of the object.
  173. py_Type py_typeof(py_Ref self);
  174. /// Check if the object is exactly the given type.
  175. bool py_istype(py_Ref, py_Type);
  176. /// Check if the object is an instance of the given type.
  177. bool py_isinstance(py_Ref obj, py_Type type);
  178. /// Check if the derived type is a subclass of the base type.
  179. bool py_issubclass(py_Type derived, py_Type base);
  180. /// Search the magic method from the given type to the base type.
  181. /// Return `NULL` if not found.
  182. py_ItemRef py_tpfindmagic(py_Type, py_Name name);
  183. /// Search the name from the given type to the base type.
  184. /// Return `NULL` if not found.
  185. py_ItemRef py_tpfindname(py_Type, py_Name name);
  186. /// Get the magic method from the given type only.
  187. /// The returned reference is always valid. However, its value may be `nil`.
  188. py_ItemRef py_tpgetmagic(py_Type type, py_Name name);
  189. /// Get the type object of the given type.
  190. py_ItemRef py_tpobject(py_Type type);
  191. /// Get the type name.
  192. const char* py_tpname(py_Type type);
  193. /// Call a type to create a new instance.
  194. bool py_tpcall(py_Type type, int argc, py_Ref argv) PY_RAISE;
  195. /// Check if the object is an instance of the given type.
  196. /// Raise `TypeError` if the check fails.
  197. bool py_checktype(py_Ref self, py_Type type) PY_RAISE;
  198. #define py_checkint(self) py_checktype(self, tp_int)
  199. #define py_checkfloat(self) py_checktype(self, tp_float)
  200. #define py_checkbool(self) py_checktype(self, tp_bool)
  201. #define py_checkstr(self) py_checktype(self, tp_str)
  202. /************* References *************/
  203. /// Get the i-th register.
  204. /// All registers are located in a contiguous memory.
  205. py_GlobalRef py_getreg(int i);
  206. /// Set the i-th register.
  207. void py_setreg(int i, py_Ref val);
  208. /// Get variable in the `__main__` module.
  209. py_ItemRef py_getglobal(py_Name name);
  210. /// Set variable in the `__main__` module.
  211. void py_setglobal(py_Name name, py_Ref val);
  212. /// Get variable in the `builtins` module.
  213. py_ItemRef py_getbuiltin(py_Name name);
  214. /// Equivalent to `*dst = *src`.
  215. void py_assign(py_Ref dst, py_Ref src);
  216. /// Get the last return value.
  217. py_GlobalRef py_retval();
  218. /// Get an item from the object's `__dict__`.
  219. /// Return `NULL` if not found.
  220. py_ItemRef py_getdict(py_Ref self, py_Name name);
  221. /// Set an item to the object's `__dict__`.
  222. void py_setdict(py_Ref self, py_Name name, py_Ref val);
  223. /// Delete an item from the object's `__dict__`.
  224. /// Return `true` if the deletion is successful.
  225. bool py_deldict(py_Ref self, py_Name name);
  226. /// Prepare an insertion to the object's `__dict__`.
  227. py_ItemRef py_emplacedict(py_Ref self, py_Name name);
  228. /// Get the i-th slot of the object.
  229. /// The object must have slots and `i` must be in valid range.
  230. py_ObjectRef py_getslot(py_Ref self, int i);
  231. /// Set the i-th slot of the object.
  232. void py_setslot(py_Ref self, int i, py_Ref val);
  233. /************* Inspection *************/
  234. /// Get the current `function` object from the stack.
  235. /// Return `NULL` if not available.
  236. py_StackRef py_inspect_currentfunction();
  237. /************* Bindings *************/
  238. /// Bind a function to the object via "decl-based" style.
  239. /// @param obj the target object.
  240. /// @param sig signature of the function. e.g. `add(x, y)`.
  241. /// @param f function to bind.
  242. void py_bind(py_Ref obj, const char* sig, py_CFunction f);
  243. /// Bind a method to type via "argc-based" style.
  244. /// @param type the target type.
  245. /// @param name name of the method.
  246. /// @param f function to bind.
  247. void py_bindmethod(py_Type type, const char* name, py_CFunction f);
  248. /// Bind a function to the object via "argc-based" style.
  249. /// @param obj the target object.
  250. /// @param name name of the function.
  251. /// @param f function to bind.
  252. void py_bindfunc(py_Ref obj, const char* name, py_CFunction f);
  253. /// Bind a property to type.
  254. /// @param type the target type.
  255. /// @param name name of the property.
  256. /// @param getter getter function.
  257. /// @param setter setter function. Use `NULL` if not needed.
  258. void py_bindproperty(py_Type type, const char* name, py_CFunction getter, py_CFunction setter);
  259. #define py_bindmagic(type, __magic__, f) py_newnativefunc(py_tpgetmagic((type), __magic__), (f))
  260. #define PY_CHECK_ARGC(n) \
  261. if(argc != n) return TypeError("expected %d arguments, got %d", n, argc)
  262. #define PY_CHECK_ARG_TYPE(i, type) \
  263. if(!py_checktype(py_arg(i), type)) return false
  264. #define py_offset(p, i) ((py_Ref)((char*)p + ((i) << 4)))
  265. #define py_arg(i) py_offset(argv, i)
  266. /************* Python Equivalents *************/
  267. /// Python equivalent to `getattr(self, name)`.
  268. bool py_getattr(py_Ref self, py_Name name) PY_RAISE;
  269. /// Python equivalent to `setattr(self, name, val)`.
  270. bool py_setattr(py_Ref self, py_Name name, py_Ref val) PY_RAISE;
  271. /// Python equivalent to `delattr(self, name)`.
  272. bool py_delattr(py_Ref self, py_Name name) PY_RAISE;
  273. /// Python equivalent to `self[key]`.
  274. bool py_getitem(py_Ref self, py_Ref key) PY_RAISE;
  275. /// Python equivalent to `self[key] = val`.
  276. bool py_setitem(py_Ref self, py_Ref key, py_Ref val) PY_RAISE;
  277. /// Python equivalent to `del self[key]`.
  278. bool py_delitem(py_Ref self, py_Ref key) PY_RAISE;
  279. /// Perform a binary operation.
  280. /// The result will be set to `py_retval()`.
  281. /// The stack remains unchanged after the operation.
  282. bool py_binaryop(py_Ref lhs, py_Ref rhs, py_Name op, py_Name rop) PY_RAISE;
  283. #define py_binaryadd(lhs, rhs) py_binaryop(lhs, rhs, __add__, __radd__)
  284. #define py_binarysub(lhs, rhs) py_binaryop(lhs, rhs, __sub__, __rsub__)
  285. #define py_binarymul(lhs, rhs) py_binaryop(lhs, rhs, __mul__, __rmul__)
  286. #define py_binarytruediv(lhs, rhs) py_binaryop(lhs, rhs, __truediv__, __rtruediv__)
  287. #define py_binaryfloordiv(lhs, rhs) py_binaryop(lhs, rhs, __floordiv__, __rfloordiv__)
  288. #define py_binarymod(lhs, rhs) py_binaryop(lhs, rhs, __mod__, __rmod__)
  289. #define py_binarypow(lhs, rhs) py_binaryop(lhs, rhs, __pow__, __rpow__)
  290. #define py_binarylshift(lhs, rhs) py_binaryop(lhs, rhs, __lshift__, 0)
  291. #define py_binaryrshift(lhs, rhs) py_binaryop(lhs, rhs, __rshift__, 0)
  292. #define py_binaryand(lhs, rhs) py_binaryop(lhs, rhs, __and__, 0)
  293. #define py_binaryor(lhs, rhs) py_binaryop(lhs, rhs, __or__, 0)
  294. #define py_binaryxor(lhs, rhs) py_binaryop(lhs, rhs, __xor__, 0)
  295. #define py_binarymatmul(lhs, rhs) py_binaryop(lhs, rhs, __matmul__, 0)
  296. /************* Stack Operations *************/
  297. /// Get the i-th object from the top of the stack.
  298. /// `i` should be negative, e.g. (-1) means TOS.
  299. py_StackRef py_peek(int i);
  300. /// Push the object to the stack.
  301. void py_push(py_Ref src);
  302. /// Push a `nil` object to the stack.
  303. void py_pushnil();
  304. /// Push a `None` object to the stack.
  305. void py_pushnone();
  306. /// Pop an object from the stack.
  307. void py_pop();
  308. /// Shrink the stack by n.
  309. void py_shrink(int n);
  310. /// Get a temporary variable from the stack.
  311. py_StackRef py_pushtmp();
  312. /// Get the unbound method of the object.
  313. /// Assume the object is located at the top of the stack.
  314. /// If return true: `[self] -> [unbound, self]`.
  315. /// If return false: `[self] -> [self]` (no change).
  316. bool py_pushmethod(py_Name name);
  317. /// Call a callable object.
  318. /// Assume `argc + kwargc` arguments are already pushed to the stack.
  319. /// The result will be set to `py_retval()`.
  320. /// The stack size will be reduced by `argc + kwargc`.
  321. bool py_vectorcall(uint16_t argc, uint16_t kwargc) PY_RAISE;
  322. /************* Modules *************/
  323. /// Create a new module.
  324. py_GlobalRef py_newmodule(const char* path);
  325. /// Get a module by path.
  326. py_GlobalRef py_getmodule(const char* path);
  327. /// Import a module.
  328. /// The result will be set to `py_retval()`.
  329. /// -1: error, 0: not found, 1: success
  330. int py_import(const char* path) PY_RAISE;
  331. /************* Errors *************/
  332. /// Raise an exception by type and message. Always return false.
  333. bool py_exception(py_Type type, const char* fmt, ...) PY_RAISE;
  334. /// Raise an expection object. Always return false.
  335. bool py_raise(py_Ref) PY_RAISE;
  336. /// Print the current exception.
  337. /// The exception will be set as handled.
  338. void py_printexc();
  339. /// Format the current exception and return a null-terminated string.
  340. /// The result should be freed by the caller.
  341. /// The exception will be set as handled.
  342. char* py_formatexc();
  343. /// Check if an exception is raised.
  344. bool py_checkexc(bool ignore_handled);
  345. /// Check if the exception is an instance of the given type.
  346. /// If match, the exception will be set as handled.
  347. bool py_matchexc(py_Type type);
  348. /// Clear the current exception.
  349. /// @param p0 the unwinding point. Use `NULL` if not needed.
  350. void py_clearexc(py_StackRef p0);
  351. #define NameError(n) py_exception(tp_NameError, "name '%n' is not defined", (n))
  352. #define TypeError(...) py_exception(tp_TypeError, __VA_ARGS__)
  353. #define RuntimeError(...) py_exception(tp_RuntimeError, __VA_ARGS__)
  354. #define ValueError(...) py_exception(tp_ValueError, __VA_ARGS__)
  355. #define IndexError(...) py_exception(tp_IndexError, __VA_ARGS__)
  356. #define ImportError(...) py_exception(tp_ImportError, __VA_ARGS__)
  357. #define ZeroDivisionError(...) py_exception(tp_ZeroDivisionError, __VA_ARGS__)
  358. #define AttributeError(self, n) \
  359. py_exception(tp_AttributeError, "'%t' object has no attribute '%n'", (self)->type, (n))
  360. #define UnboundLocalError(n) \
  361. py_exception(tp_UnboundLocalError, "local variable '%n' referenced before assignment", (n))
  362. bool StopIteration();
  363. bool KeyError(py_Ref key) PY_RAISE;
  364. /************* Operators *************/
  365. /// Python equivalent to `bool(val)`.
  366. /// 1: true, 0: false, -1: error
  367. int py_bool(py_Ref val) PY_RAISE;
  368. /// Compare two objects.
  369. /// 1: lhs == rhs, 0: lhs != rhs, -1: error
  370. int py_equal(py_Ref lhs, py_Ref rhs) PY_RAISE;
  371. /// Compare two objects.
  372. /// 1: lhs < rhs, 0: lhs >= rhs, -1: error
  373. int py_less(py_Ref lhs, py_Ref rhs) PY_RAISE;
  374. #define py_eq(lhs, rhs) py_binaryop(lhs, rhs, __eq__, __eq__)
  375. #define py_ne(lhs, rhs) py_binaryop(lhs, rhs, __ne__, __ne__)
  376. #define py_lt(lhs, rhs) py_binaryop(lhs, rhs, __lt__, __gt__)
  377. #define py_le(lhs, rhs) py_binaryop(lhs, rhs, __le__, __ge__)
  378. #define py_gt(lhs, rhs) py_binaryop(lhs, rhs, __gt__, __lt__)
  379. #define py_ge(lhs, rhs) py_binaryop(lhs, rhs, __ge__, __le__)
  380. /// Get the hash value of the object.
  381. bool py_hash(py_Ref, py_i64* out) PY_RAISE;
  382. /// Get the iterator of the object.
  383. bool py_iter(py_Ref) PY_RAISE;
  384. /// Get the next element from the iterator.
  385. /// 1: success, 0: StopIteration, -1: error
  386. int py_next(py_Ref) PY_RAISE;
  387. /// Python equivalent to `lhs is rhs`.
  388. bool py_isidentical(py_Ref, py_Ref);
  389. /// Call a function.
  390. /// It prepares the stack and then performs a `vectorcall(argc, 0, false)`.
  391. /// The result will be set to `py_retval()`.
  392. /// The stack remains unchanged after the operation.
  393. bool py_call(py_Ref f, int argc, py_Ref argv) PY_RAISE;
  394. #if PK_DEBUG
  395. /// Call a py_CFunction in a safe way.
  396. /// This function does extra checks to help you debug `py_CFunction`.
  397. bool py_callcfunc(py_CFunction f, int argc, py_Ref argv) PY_RAISE;
  398. #else
  399. #define py_callcfunc(f, argc, argv) (f((argc), (argv)))
  400. #endif
  401. /// Python equivalent to `str(val)`.
  402. bool py_str(py_Ref val) PY_RAISE;
  403. /// Python equivalent to `repr(val)`.
  404. bool py_repr(py_Ref val) PY_RAISE;
  405. /// Python equivalent to `len(val)`.
  406. bool py_len(py_Ref val) PY_RAISE;
  407. /// Python equivalent to `json.dumps(val)`.
  408. bool py_json(py_Ref val) PY_RAISE;
  409. /************* Unchecked Functions *************/
  410. py_ObjectRef py_tuple_data(py_Ref self);
  411. py_ObjectRef py_tuple_getitem(py_Ref self, int i);
  412. void py_tuple_setitem(py_Ref self, int i, py_Ref val);
  413. int py_tuple_len(py_Ref self);
  414. py_ItemRef py_list_data(py_Ref self);
  415. py_ItemRef py_list_getitem(py_Ref self, int i);
  416. void py_list_setitem(py_Ref self, int i, py_Ref val);
  417. void py_list_delitem(py_Ref self, int i);
  418. int py_list_len(py_Ref self);
  419. void py_list_swap(py_Ref self, int i, int j);
  420. void py_list_append(py_Ref self, py_Ref val);
  421. void py_list_clear(py_Ref self);
  422. void py_list_insert(py_Ref self, int i, py_Ref val);
  423. /// -1: error, 0: not found, 1: found
  424. int py_dict_getitem(py_Ref self, py_Ref key) PY_RAISE;
  425. /// true: success, false: error
  426. bool py_dict_setitem(py_Ref self, py_Ref key, py_Ref val) PY_RAISE;
  427. /// -1: error, 0: not found, 1: found (and deleted)
  428. int py_dict_delitem(py_Ref self, py_Ref key) PY_RAISE;
  429. /// -1: error, 0: not found, 1: found
  430. int py_dict_contains(py_Ref self, py_Ref key) PY_RAISE;
  431. /// true: success, false: error
  432. bool py_dict_apply(py_Ref self, bool (*f)(py_Ref key, py_Ref val, void* ctx), void* ctx) PY_RAISE;
  433. /// noexcept
  434. int py_dict_len(py_Ref self);
  435. /************* Others *************/
  436. /// An utility function to read a line from stdin for REPL.
  437. int py_replinput(char* buf, int max_size);
  438. /// Python favored string formatting. (just put here, not for users)
  439. /// %d: int
  440. /// %i: py_i64 (int64_t)
  441. /// %f: py_f64 (double)
  442. /// %s: const char*
  443. /// %q: c11_sv
  444. /// %v: c11_sv
  445. /// %c: char
  446. /// %p: void*
  447. /// %t: py_Type
  448. /// %n: py_Name
  449. enum py_MagicNames {
  450. py_MagicNames__NULL, // 0 is reserved
  451. #define MAGIC_METHOD(x) x,
  452. #include "pocketpy/xmacros/magics.h"
  453. #undef MAGIC_METHOD
  454. };
  455. enum py_PredefinedTypes {
  456. tp_object = 1,
  457. tp_type, // py_Type
  458. tp_int,
  459. tp_float,
  460. tp_bool,
  461. tp_str,
  462. tp_str_iterator,
  463. tp_list, // c11_vector
  464. tp_tuple, // N slots
  465. tp_array_iterator,
  466. tp_slice, // 3 slots (start, stop, step)
  467. tp_range,
  468. tp_range_iterator,
  469. tp_module,
  470. tp_function,
  471. tp_nativefunc,
  472. tp_boundmethod,
  473. tp_super, // 1 slot + py_Type
  474. tp_BaseException, // 2 slots (arg + inner exc)
  475. tp_Exception,
  476. tp_bytes,
  477. tp_namedict,
  478. tp_locals,
  479. tp_code,
  480. tp_dict,
  481. tp_dict_items, // 1 slot
  482. tp_property, // 2 slots (getter + setter)
  483. tp_star_wrapper, // 1 slot + int level
  484. tp_staticmethod, // 1 slot
  485. tp_classmethod, // 1 slot
  486. tp_NoneType,
  487. tp_NotImplementedType,
  488. tp_ellipsis,
  489. tp_generator,
  490. /* builtin exceptions */
  491. tp_StopIteration,
  492. tp_SyntaxError,
  493. tp_StackOverflowError,
  494. tp_IOError,
  495. tp_OSError,
  496. tp_NotImplementedError,
  497. tp_TypeError,
  498. tp_IndexError,
  499. tp_ValueError,
  500. tp_RuntimeError,
  501. tp_ZeroDivisionError,
  502. tp_NameError,
  503. tp_UnboundLocalError,
  504. tp_AttributeError,
  505. tp_ImportError,
  506. tp_AssertionError,
  507. tp_KeyError,
  508. };
  509. #ifdef __cplusplus
  510. }
  511. #endif
  512. /*
  513. Some notes:
  514. ## Macros
  515. 1. Function macros are partial functions. They can be used as normal expressions. Use the same
  516. naming convention as functions.
  517. 2. Snippet macros are `do {...} while(0)` blocks. They cannot be used as expressions. Use
  518. `UPPER_CASE` naming convention.
  519. 3. Constant macros are used for global constants. Use `UPPER_CASE` or k-prefix naming convention.
  520. */