pocketpy.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  1. #pragma once
  2. #include <stdint.h>
  3. #include <stdbool.h>
  4. #include <stdarg.h>
  5. #include "pocketpy/common/config.h"
  6. #include "pocketpy/common/export.h"
  7. /************* Public Types *************/
  8. typedef struct py_TValue py_TValue;
  9. typedef uint16_t py_Name;
  10. typedef int16_t py_Type;
  11. typedef int64_t py_i64;
  12. typedef double py_f64;
  13. /* string_view */
  14. typedef struct c11_sv{
  15. const char* data;
  16. int size;
  17. } c11_sv;
  18. /// Generic reference.
  19. typedef py_TValue* py_Ref;
  20. /// An object reference which has the same lifespan as the object.
  21. typedef py_TValue* py_ObjectRef;
  22. /// A global reference which has the same lifespan as the VM.
  23. typedef py_TValue* py_GlobalRef;
  24. /// A specific location in the stack.
  25. typedef py_TValue* py_StackRef;
  26. /// A temporary reference which has a short or unknown lifespan.
  27. typedef py_TValue* py_TmpRef;
  28. /// Native function signature.
  29. /// @param argc number of arguments.
  30. /// @param argv array of arguments. Use `py_arg(i)` macro to get the i-th argument.
  31. /// @return true if the function is successful.
  32. typedef bool (*py_CFunction)(int argc, py_StackRef argv);
  33. enum BindType {
  34. BindType_FUNCTION,
  35. BindType_STATICMETHOD,
  36. BindType_CLASSMETHOD,
  37. };
  38. enum CompileMode { EXEC_MODE, EVAL_MODE, REPL_MODE, JSON_MODE, CELL_MODE };
  39. /************* Global VMs *************/
  40. void py_initialize();
  41. void py_finalize();
  42. /// Run a simple source string. Do not change the stack.
  43. bool py_exec(const char* source);
  44. /// Eval a simple expression.
  45. /// The result will be set to `py_retval()`.
  46. bool py_eval(const char* source);
  47. bool py_exec2(const char* source, const char* filename, enum CompileMode mode);
  48. /************* Values Creation *************/
  49. void py_newint(py_Ref, py_i64);
  50. void py_newfloat(py_Ref, py_f64);
  51. void py_newbool(py_Ref, bool);
  52. void py_newstr(py_Ref, const char*);
  53. void py_newstrn(py_Ref, const char*, int);
  54. unsigned char* py_newbytes(py_Ref, int);
  55. void py_newnone(py_Ref);
  56. void py_newnotimplemented(py_Ref out);
  57. void py_newellipsis(py_Ref out);
  58. void py_newnil(py_Ref);
  59. /// Create a tuple with n UNINITIALIZED elements.
  60. /// You should initialize all elements before using it.
  61. void py_newtuple(py_Ref, int n);
  62. /// Create a list.
  63. void py_newlist(py_Ref);
  64. /// Create a list with n UNINITIALIZED elements.
  65. /// You should initialize all elements before using it.
  66. void py_newlistn(py_Ref, int n);
  67. py_Name py_name(const char*);
  68. const char* py_name2str(py_Name);
  69. py_Name py_namev(c11_sv name);
  70. c11_sv py_name2sv(py_Name);
  71. bool py_ismagicname(py_Name);
  72. // opaque types
  73. void py_newdict(py_Ref);
  74. void py_newset(py_Ref);
  75. void py_newslice(py_Ref);
  76. // old style argc-based function
  77. void py_newnativefunc(py_Ref out, py_CFunction);
  78. /// Create a new object.
  79. /// @param out output reference.
  80. /// @param type type of the object.
  81. /// @param slots number of slots. Use -1 to create a `__dict__`.
  82. /// @param udsize size of your userdata. You can use `py_touserdata()` to get the pointer to it.
  83. void* py_newobject(py_Ref out, py_Type type, int slots, int udsize);
  84. /************* Type Cast *************/
  85. py_i64 py_toint(const py_Ref);
  86. py_f64 py_tofloat(const py_Ref);
  87. bool py_castfloat(const py_Ref, py_f64* out);
  88. bool py_tobool(const py_Ref);
  89. py_Type py_totype(const py_Ref);
  90. const char* py_tostr(const py_Ref);
  91. const char* py_tostrn(const py_Ref, int* size);
  92. c11_sv py_tosv(const py_Ref);
  93. unsigned char* py_tobytes(const py_Ref, int* size);
  94. void* py_touserdata(const py_Ref);
  95. #define py_isint(self) py_istype(self, tp_int)
  96. #define py_isfloat(self) py_istype(self, tp_float)
  97. #define py_isbool(self) py_istype(self, tp_bool)
  98. #define py_isstr(self) py_istype(self, tp_str)
  99. bool py_istype(const py_Ref, py_Type);
  100. bool py_isinstance(const py_Ref obj, py_Type type);
  101. bool py_issubclass(py_Type derived, py_Type base);
  102. /************* References *************/
  103. #define PY_CHECK_ARGC(n) \
  104. if(argc != n) return TypeError("expected %d arguments, got %d", n, argc)
  105. #define PY_CHECK_ARG_TYPE(i, type) \
  106. if(!py_checktype(py_arg(i), type)) return false
  107. #define py_offset(p, i) ((py_Ref)((char*)p + ((i) << 4)))
  108. #define py_arg(i) py_offset(argv, i)
  109. py_GlobalRef py_tpmagic(py_Type type, py_Name name);
  110. #define py_bindmagic(type, __magic__, f) py_newnativefunc(py_tpmagic((type), __magic__), (f))
  111. // new style decl-based bindings
  112. void py_bind(py_Ref obj, const char* sig, py_CFunction f);
  113. py_ObjectRef py_bind2(py_Ref obj,
  114. const char* sig,
  115. py_CFunction f,
  116. enum BindType bt,
  117. const char* docstring,
  118. int slots);
  119. py_ObjectRef py_bind3(py_Ref obj,
  120. py_CFunction f,
  121. c11_sv name,
  122. c11_sv* args,
  123. int argc,
  124. c11_sv starred_arg,
  125. c11_sv* kwargs,
  126. int kwargc,
  127. py_Ref kwdefaults, // a tuple contains default values
  128. c11_sv starred_kwarg,
  129. enum BindType bt,
  130. const char* docstring,
  131. int slots);
  132. // old style argc-based bindings
  133. void py_bindmethod(py_Type type, const char* name, py_CFunction f);
  134. void py_bindmethod2(py_Type type, const char* name, py_CFunction f, enum BindType bt);
  135. void py_bindnativefunc(py_Ref obj, const char* name, py_CFunction f);
  136. /// Get the reference to the i-th register.
  137. /// All registers are located in a contiguous memory.
  138. py_GlobalRef py_reg(int i);
  139. /// Get the reference of the object's `__dict__`.
  140. /// The object must have a `__dict__`.
  141. /// Returns a reference to the value or NULL if not found.
  142. py_ObjectRef py_getdict(const py_Ref self, py_Name name);
  143. void py_setdict(py_Ref self, py_Name name, const py_Ref val);
  144. /// Get the reference of the i-th slot of the object.
  145. /// The object must have slots and `i` must be in range.
  146. py_ObjectRef py_getslot(const py_Ref self, int i);
  147. void py_setslot(py_Ref self, int i, const py_Ref val);
  148. py_TmpRef py_getupvalue(py_StackRef argv);
  149. void py_setupvalue(py_StackRef argv, const py_Ref val);
  150. /// Gets the attribute of the object.
  151. /// 1: success, 0: not found, -1: error
  152. int py_getattr(const py_Ref self, py_Name name, py_Ref out);
  153. /// Sets the attribute of the object.
  154. bool py_setattr(py_Ref self, py_Name name, const py_Ref val);
  155. /// Deletes the attribute of the object.
  156. bool py_delattr(py_Ref self, py_Name name);
  157. /// Gets the unbound method of the object.
  158. bool py_getunboundmethod(py_Ref self, py_Name name, py_Ref out, py_Ref out_self);
  159. bool py_getitem(const py_Ref self, const py_Ref key, py_Ref out);
  160. bool py_setitem(py_Ref self, const py_Ref key, const py_Ref val);
  161. bool py_delitem(py_Ref self, const py_Ref key);
  162. /// Perform a binary operation on the stack.
  163. /// It assumes `lhs` and `rhs` are already pushed to the stack.
  164. /// The result will be set to `py_retval()`.
  165. bool py_binaryop(const py_Ref lhs, const py_Ref rhs, py_Name op, py_Name rop);
  166. #define py_binaryadd(lhs, rhs) py_binaryop(lhs, rhs, __add__, __radd__)
  167. #define py_binarysub(lhs, rhs) py_binaryop(lhs, rhs, __sub__, __rsub__)
  168. #define py_binarymul(lhs, rhs) py_binaryop(lhs, rhs, __mul__, __rmul__)
  169. #define py_binarytruediv(lhs, rhs) py_binaryop(lhs, rhs, __truediv__, __rtruediv__)
  170. #define py_binaryfloordiv(lhs, rhs) py_binaryop(lhs, rhs, __floordiv__, __rfloordiv__)
  171. #define py_binarymod(lhs, rhs) py_binaryop(lhs, rhs, __mod__, __rmod__)
  172. #define py_binarypow(lhs, rhs) py_binaryop(lhs, rhs, __pow__, __rpow__)
  173. #define py_binarylshift(lhs, rhs) py_binaryop(lhs, rhs, __lshift__, 0)
  174. #define py_binaryrshift(lhs, rhs) py_binaryop(lhs, rhs, __rshift__, 0)
  175. #define py_binaryand(lhs, rhs) py_binaryop(lhs, rhs, __and__, 0)
  176. #define py_binaryor(lhs, rhs) py_binaryop(lhs, rhs, __or__, 0)
  177. #define py_binaryxor(lhs, rhs) py_binaryop(lhs, rhs, __xor__, 0)
  178. #define py_binarymatmul(lhs, rhs) py_binaryop(lhs, rhs, __matmul__, 0)
  179. /// Equivalent to `*dst = *src`.
  180. void py_assign(py_Ref dst, const py_Ref src);
  181. /************* Stack Operations *************/
  182. /// Return a reference to the i-th object from the top of the stack.
  183. /// i should be negative, e.g. (-1) means TOS.
  184. py_StackRef py_peek(int i);
  185. /// Push the object to the stack.
  186. void py_push(const py_Ref src);
  187. /// Push a nil object to the stack.
  188. void py_pushnil();
  189. /// Pop an object from the stack.
  190. void py_pop();
  191. /// Shrink the stack by n.
  192. void py_shrink(int n);
  193. /// Get a temporary variable from the stack and returns the reference to it.
  194. py_StackRef py_pushtmp();
  195. /// Free n temporary variable.
  196. #define py_poptmp(n) py_shrink(n)
  197. #define py_gettop() py_peek(-1)
  198. #define py_getsecond() py_peek(-2)
  199. #define py_settop(v) py_assign(py_peek(-1), v)
  200. #define py_setsecond(v) py_assign(py_peek(-2), v)
  201. #define py_duptop() py_push(py_peek(-1))
  202. #define py_dupsecond() py_push(py_peek(-2))
  203. /************* Modules *************/
  204. py_TmpRef py_newmodule(const char* name, const char* package);
  205. py_TmpRef py_getmodule(const char* name);
  206. /// Import a module.
  207. /// The result will be set to `py_retval()`.
  208. bool py_import(const char* name);
  209. /************* Errors *************/
  210. bool py_exception(const char* name, const char* fmt, ...);
  211. /// Print the last error to the console.
  212. void py_printexc();
  213. /// Format the last error to a string.
  214. void py_formatexc(char* out);
  215. #define KeyError(q) py_exception("KeyError", "%q", (q))
  216. #define NameError(n) py_exception("NameError", "name '%n' is not defined", (n))
  217. #define TypeError(...) py_exception("TypeError", __VA_ARGS__)
  218. #define ValueError(...) py_exception("ValueError", __VA_ARGS__)
  219. #define IndexError(...) py_exception("IndexError", __VA_ARGS__)
  220. #define NotImplementedError() py_exception("NotImplementedError", "")
  221. #define AttributeError(self, n) \
  222. py_exception("AttributeError", "'%t' object has no attribute '%n'", (self)->type, (n))
  223. #define UnboundLocalError(n) \
  224. py_exception("UnboundLocalError", "local variable '%n' referenced before assignment", (n))
  225. bool StopIteration();
  226. /************* Operators *************/
  227. /// Equivalent to `bool(val)`.
  228. /// Returns 1 if `val` is truthy, otherwise 0.
  229. /// Returns -1 if an error occurred.
  230. int py_bool(const py_Ref val);
  231. int py_eq(const py_Ref, const py_Ref);
  232. int py_ne(const py_Ref, const py_Ref);
  233. int py_le(const py_Ref, const py_Ref);
  234. int py_lt(const py_Ref, const py_Ref);
  235. int py_ge(const py_Ref, const py_Ref);
  236. int py_gt(const py_Ref, const py_Ref);
  237. bool py_hash(const py_Ref, py_i64* out);
  238. /// Get the iterator of the object.
  239. bool py_iter(const py_Ref);
  240. /// Get the next element from the iterator.
  241. /// 1: success, 0: StopIteration, -1: error
  242. int py_next(const py_Ref);
  243. /// Python equivalent to `lhs is rhs`.
  244. bool py_isidentical(const py_Ref, const py_Ref);
  245. /// A stack operation that calls a function.
  246. /// It assumes `argc + kwargc` arguments are already pushed to the stack.
  247. /// The result will be set to `py_retval()`.
  248. /// The stack size will be reduced by `argc + kwargc`.
  249. bool py_vectorcall(uint16_t argc, uint16_t kwargc);
  250. /// Call a function.
  251. /// It prepares the stack and then performs a `vectorcall(argc, 0, false)`.
  252. /// The result will be set to `py_retval()`.
  253. /// The stack remains unchanged after the operation.
  254. bool py_call(py_Ref f, int argc, py_Ref argv);
  255. /// Call a non-magic method.
  256. /// It prepares the stack and then performs a `vectorcall(argc+1, 0, false)`.
  257. /// The result will be set to `py_retval()`.
  258. /// The stack remains unchanged after the operation.
  259. bool py_callmethod(py_Ref self, py_Name, int argc, py_Ref argv);
  260. /// Call a magic method using a continuous buffer.
  261. /// The result will be set to `py_retval()`.
  262. /// The stack remains unchanged after the operation.
  263. bool py_callmagic(py_Name name, int argc, py_Ref argv);
  264. bool py_str(py_Ref val);
  265. #define py_repr(val) py_callmagic(__repr__, 1, val)
  266. #define py_len(val) py_callmagic(__len__, 1, val)
  267. /// The return value of the most recent call.
  268. py_GlobalRef py_retval();
  269. #define py_isnil(self) ((self)->type == 0)
  270. #define py_isnone(self) ((self)->type == tp_none_type)
  271. /* tuple */
  272. // unchecked functions, if self is not a tuple, the behavior is undefined
  273. py_ObjectRef py_tuple__getitem(const py_Ref self, int i);
  274. void py_tuple__setitem(py_Ref self, int i, const py_Ref val);
  275. int py_tuple__len(const py_Ref self);
  276. // unchecked functions, if self is not a list, the behavior is undefined
  277. py_ObjectRef py_list__getitem(const py_Ref self, int i);
  278. py_ObjectRef py_list__data(const py_Ref self);
  279. void py_list__setitem(py_Ref self, int i, const py_Ref val);
  280. void py_list__delitem(py_Ref self, int i);
  281. int py_list__len(const py_Ref self);
  282. void py_list__append(py_Ref self, const py_Ref val);
  283. void py_list__clear(py_Ref self);
  284. void py_list__insert(py_Ref self, int i, const py_Ref val);
  285. // internal functions
  286. typedef struct pk_TypeInfo pk_TypeInfo;
  287. pk_TypeInfo* pk_tpinfo(const py_Ref self);
  288. /// Search the magic method from the given type to the base type.
  289. /// Return the reference or NULL if not found.
  290. py_GlobalRef py_tpfindmagic(py_Type, py_Name name);
  291. /// Search the name from the given type to the base type.
  292. /// Return the reference or NULL if not found.
  293. py_GlobalRef py_tpfindname(py_Type, py_Name name);
  294. /// Get the type object of the given type.
  295. py_GlobalRef py_tpobject(py_Type type);
  296. /// Get the type name.
  297. const char* py_tpname(py_Type type);
  298. /// Call a type to create a new instance.
  299. bool py_tpcall(py_Type type, int argc, py_Ref argv);
  300. /// Check if the object is an instance of the given type.
  301. bool py_checktype(const py_Ref self, py_Type type);
  302. #define py_checkint(self) py_checktype(self, tp_int)
  303. #define py_checkfloat(self) py_checktype(self, tp_float)
  304. #define py_checkbool(self) py_checktype(self, tp_bool)
  305. #define py_checkstr(self) py_checktype(self, tp_str)
  306. int py_replinput(char* buf);
  307. /// Python favored string formatting.
  308. /// %d: int
  309. /// %i: py_i64 (int64_t)
  310. /// %f: py_f64 (double)
  311. /// %s: const char*
  312. /// %q: c11_sv
  313. /// %v: c11_sv
  314. /// %c: char
  315. /// %p: void*
  316. /// %t: py_Type
  317. /// %n: py_Name
  318. enum py_MagicNames {
  319. py_MagicNames__NULL, // 0 is reserved
  320. #define MAGIC_METHOD(x) x,
  321. #include "pocketpy/xmacros/magics.h"
  322. #undef MAGIC_METHOD
  323. };
  324. enum py_PredefinedTypes {
  325. tp_object = 1,
  326. tp_type, // py_Type
  327. tp_int,
  328. tp_float,
  329. tp_bool,
  330. tp_str,
  331. tp_str_iterator,
  332. tp_list, // c11_vector
  333. tp_tuple, // N slots
  334. tp_array_iterator,
  335. tp_slice, // 3 slots (start, stop, step)
  336. tp_range,
  337. tp_range_iterator,
  338. tp_module,
  339. tp_function,
  340. tp_nativefunc,
  341. tp_bound_method,
  342. tp_super, // 1 slot + py_Type
  343. tp_base_exception,
  344. tp_exception,
  345. tp_bytes,
  346. tp_mappingproxy,
  347. tp_dict,
  348. tp_property, // 2 slots (getter + setter)
  349. tp_star_wrapper,
  350. tp_staticmethod, // 1 slot
  351. tp_classmethod, // 1 slot
  352. tp_none_type,
  353. tp_not_implemented_type,
  354. tp_ellipsis,
  355. tp_syntax_error,
  356. tp_stop_iteration,
  357. };
  358. #ifdef __cplusplus
  359. }
  360. #endif
  361. /*
  362. Some notes:
  363. ## Macros
  364. 1. Function macros are partial functions. They can be used as normal expressions. Use the same
  365. naming convention as functions.
  366. 2. Snippet macros are `do {...} while(0)` blocks. They cannot be used as expressions. Use
  367. `UPPER_CASE` naming convention.
  368. 3. Constant macros are used for global constants. Use `UPPER_CASE` or k-prefix naming convention.
  369. */