pocketpy.h 22 KB

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