ceval.c 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253
  1. #include "pocketpy/common/config.h"
  2. #include "pocketpy/common/utils.h"
  3. #include "pocketpy/interpreter/frame.h"
  4. #include "pocketpy/interpreter/vm.h"
  5. #include "pocketpy/common/memorypool.h"
  6. #include "pocketpy/common/sstream.h"
  7. #include "pocketpy/objects/codeobject.h"
  8. #include "pocketpy/pocketpy.h"
  9. #include "pocketpy/objects/error.h"
  10. #include <stdbool.h>
  11. static bool stack_unpack_sequence(VM* self, uint16_t arg);
  12. static bool format_object(py_Ref obj, c11_sv spec);
  13. #define DISPATCH() \
  14. do { \
  15. frame->ip++; \
  16. goto __NEXT_STEP; \
  17. } while(0)
  18. #define DISPATCH_JUMP(__offset) \
  19. do { \
  20. frame->ip += __offset; \
  21. goto __NEXT_STEP; \
  22. } while(0)
  23. #define DISPATCH_JUMP_ABSOLUTE(__target) \
  24. do { \
  25. frame->ip = c11__at(Bytecode, &frame->co->codes, __target); \
  26. goto __NEXT_STEP; \
  27. } while(0)
  28. /* Stack manipulation macros */
  29. // https://github.com/python/cpython/blob/3.9/Python/ceval.c#L1123
  30. #define TOP() (self->stack.sp - 1)
  31. #define SECOND() (self->stack.sp - 2)
  32. #define THIRD() (self->stack.sp - 3)
  33. #define FOURTH() (self->stack.sp - 4)
  34. #define STACK_SHRINK(n) (self->stack.sp -= n)
  35. #define STACK_GROW(n) (self->stack.sp += n)
  36. #define PUSH(v) \
  37. do { \
  38. *self->stack.sp = *(v); \
  39. self->stack.sp++; \
  40. } while(0)
  41. #define POP() (--self->stack.sp)
  42. #define POPX() (*--self->stack.sp)
  43. #define SP() (self->stack.sp)
  44. // [a, b] -> [?, a, b]
  45. #define INSERT_THIRD() \
  46. do { \
  47. PUSH(TOP()); \
  48. *SECOND() = *THIRD(); \
  49. } while(0)
  50. #define vectorcall_opcall(argc, kwargc) \
  51. do { \
  52. FrameResult res = VM__vectorcall(self, (argc), (kwargc), true); \
  53. switch(res) { \
  54. case RES_RETURN: PUSH(&self->last_retval); break; \
  55. case RES_CALL: frame = self->top_frame; goto __NEXT_FRAME; \
  56. case RES_ERROR: goto __ERROR; \
  57. default: c11__unreachedable(); \
  58. } \
  59. } while(0)
  60. static bool unpack_dict_to_buffer(py_Ref key, py_Ref val, void* ctx) {
  61. py_TValue** p = ctx;
  62. if(py_isstr(key)) {
  63. py_Name name = py_namev(py_tosv(key));
  64. py_newint(*p, name);
  65. py_assign(*p + 1, val);
  66. (*p) += 2;
  67. return true;
  68. }
  69. return TypeError("keywords must be strings, not '%t'", key->type);
  70. }
  71. FrameResult VM__run_top_frame(VM* self) {
  72. Frame* frame = self->top_frame;
  73. const Frame* base_frame = frame;
  74. while(true) {
  75. Bytecode byte;
  76. __NEXT_FRAME:
  77. frame->ip++;
  78. __NEXT_STEP:
  79. byte = *frame->ip;
  80. pk_print_stack(self, frame, byte);
  81. switch((Opcode)byte.op) {
  82. case OP_NO_OP: DISPATCH();
  83. /*****************************************/
  84. case OP_POP_TOP: POP(); DISPATCH();
  85. case OP_DUP_TOP: PUSH(TOP()); DISPATCH();
  86. case OP_DUP_TOP_TWO:
  87. // [a, b]
  88. PUSH(SECOND()); // [a, b, a]
  89. PUSH(SECOND()); // [a, b, a, b]
  90. DISPATCH();
  91. case OP_ROT_TWO: {
  92. py_TValue tmp = *TOP();
  93. *TOP() = *SECOND();
  94. *SECOND() = tmp;
  95. DISPATCH();
  96. }
  97. case OP_ROT_THREE: {
  98. // [a, b, c] -> [c, a, b]
  99. py_TValue tmp = *TOP();
  100. *TOP() = *SECOND();
  101. *SECOND() = *THIRD();
  102. *THIRD() = tmp;
  103. DISPATCH();
  104. }
  105. case OP_PRINT_EXPR:
  106. if(TOP()->type != tp_NoneType) {
  107. bool ok = py_repr(TOP());
  108. if(!ok) goto __ERROR;
  109. self->print(py_tostr(&self->last_retval));
  110. self->print("\n");
  111. }
  112. POP();
  113. DISPATCH();
  114. /*****************************************/
  115. case OP_LOAD_CONST: PUSH(c11__at(py_TValue, &frame->co->consts, byte.arg)); DISPATCH();
  116. case OP_LOAD_NONE: py_newnone(SP()++); DISPATCH();
  117. case OP_LOAD_TRUE: py_newbool(SP()++, true); DISPATCH();
  118. case OP_LOAD_FALSE: py_newbool(SP()++, false); DISPATCH();
  119. /*****************************************/
  120. case OP_LOAD_SMALL_INT: py_newint(SP()++, (int16_t)byte.arg); DISPATCH();
  121. /*****************************************/
  122. case OP_LOAD_ELLIPSIS: py_newellipsis(SP()++); DISPATCH();
  123. case OP_LOAD_FUNCTION: {
  124. FuncDecl_ decl = c11__getitem(FuncDecl_, &frame->co->func_decls, byte.arg);
  125. Function* ud = py_newobject(SP(), tp_function, 0, sizeof(Function));
  126. Function__ctor(ud, decl, frame->module);
  127. if(decl->nested) {
  128. ud->closure = FastLocals__to_namedict(frame->locals, frame->co);
  129. py_Name name = py_name(decl->code.name->data);
  130. // capture itself to allow recursion
  131. NameDict__set(ud->closure, name, *SP());
  132. }
  133. SP()++;
  134. DISPATCH();
  135. }
  136. case OP_LOAD_NULL:
  137. py_newnil(SP()++);
  138. DISPATCH();
  139. /*****************************************/
  140. case OP_LOAD_FAST: {
  141. PUSH(&frame->locals[byte.arg]);
  142. if(py_isnil(TOP())) {
  143. py_Name name = c11__getitem(uint16_t, &frame->co->varnames, byte.arg);
  144. UnboundLocalError(name);
  145. goto __ERROR;
  146. }
  147. DISPATCH();
  148. }
  149. case OP_LOAD_NAME: {
  150. py_Name name = byte.arg;
  151. py_TValue* tmp;
  152. if(!frame->is_dynamic) {
  153. // locals
  154. tmp = Frame__f_locals_try_get(frame, name);
  155. if(tmp != NULL) {
  156. if(py_isnil(tmp)) {
  157. UnboundLocalError(name);
  158. goto __ERROR;
  159. }
  160. PUSH(tmp);
  161. DISPATCH();
  162. }
  163. // closure
  164. tmp = Frame__f_closure_try_get(frame, name);
  165. if(tmp != NULL) {
  166. PUSH(tmp);
  167. DISPATCH();
  168. }
  169. // globals
  170. tmp = py_getdict(frame->module, name);
  171. if(tmp != NULL) {
  172. PUSH(tmp);
  173. DISPATCH();
  174. }
  175. } else {
  176. py_newstr(SP()++, py_name2str(name));
  177. // locals
  178. if(py_getitem(&frame->p0[1], TOP())) {
  179. py_assign(TOP(), py_retval());
  180. DISPATCH();
  181. } else {
  182. if(py_matchexc(tp_KeyError)) {
  183. py_clearexc(NULL);
  184. } else {
  185. goto __ERROR;
  186. }
  187. }
  188. // closure
  189. tmp = Frame__f_closure_try_get(frame, name);
  190. if(tmp != NULL) {
  191. py_assign(TOP(), tmp);
  192. DISPATCH();
  193. }
  194. // globals
  195. if(py_getitem(&frame->p0[0], TOP())) {
  196. py_assign(TOP(), py_retval());
  197. DISPATCH();
  198. } else {
  199. if(py_matchexc(tp_KeyError)) {
  200. py_clearexc(NULL);
  201. } else {
  202. goto __ERROR;
  203. }
  204. }
  205. }
  206. // builtins
  207. tmp = py_getdict(&self->builtins, name);
  208. if(tmp != NULL) {
  209. py_assign(TOP(), tmp);
  210. DISPATCH();
  211. }
  212. NameError(name);
  213. goto __ERROR;
  214. }
  215. case OP_LOAD_NONLOCAL: {
  216. py_Name name = byte.arg;
  217. py_Ref tmp = Frame__f_closure_try_get(frame, name);
  218. if(tmp != NULL) {
  219. PUSH(tmp);
  220. DISPATCH();
  221. }
  222. tmp = py_getdict(frame->module, name);
  223. if(tmp != NULL) {
  224. PUSH(tmp);
  225. DISPATCH();
  226. }
  227. tmp = py_getdict(&self->builtins, name);
  228. if(tmp != NULL) {
  229. PUSH(tmp);
  230. DISPATCH();
  231. }
  232. NameError(name);
  233. goto __ERROR;
  234. }
  235. case OP_LOAD_GLOBAL: {
  236. py_Name name = byte.arg;
  237. py_Ref tmp = py_getdict(frame->module, name);
  238. if(tmp != NULL) {
  239. PUSH(tmp);
  240. DISPATCH();
  241. }
  242. tmp = py_getdict(&self->builtins, name);
  243. if(tmp != NULL) {
  244. PUSH(tmp);
  245. DISPATCH();
  246. }
  247. NameError(name);
  248. goto __ERROR;
  249. }
  250. case OP_LOAD_ATTR: {
  251. if(py_getattr(TOP(), byte.arg)) {
  252. py_assign(TOP(), py_retval());
  253. } else {
  254. goto __ERROR;
  255. }
  256. DISPATCH();
  257. }
  258. case OP_LOAD_CLASS_GLOBAL: {
  259. py_Name name = byte.arg;
  260. py_Ref tmp = py_getdict(self->__curr_class, name);
  261. if(tmp) {
  262. PUSH(tmp);
  263. DISPATCH();
  264. }
  265. // load global if attribute not found
  266. tmp = py_getdict(frame->module, name);
  267. if(tmp) {
  268. PUSH(tmp);
  269. DISPATCH();
  270. }
  271. tmp = py_getdict(&self->builtins, name);
  272. if(tmp) {
  273. PUSH(tmp);
  274. DISPATCH();
  275. }
  276. NameError(name);
  277. goto __ERROR;
  278. }
  279. case OP_LOAD_METHOD: {
  280. // [self] -> [unbound, self]
  281. bool ok = py_pushmethod(byte.arg);
  282. if(!ok) {
  283. // fallback to getattr
  284. if(py_getattr(TOP(), byte.arg)) {
  285. py_assign(TOP(), py_retval());
  286. py_newnil(SP()++);
  287. } else {
  288. goto __ERROR;
  289. }
  290. }
  291. DISPATCH();
  292. }
  293. case OP_LOAD_SUBSCR: {
  294. // [a, b] -> a[b]
  295. py_Ref magic = py_tpfindmagic(SECOND()->type, __getitem__);
  296. if(magic) {
  297. if(magic->type == tp_nativefunc) {
  298. if(!py_callcfunc(magic->_cfunc, 2, SECOND())) goto __ERROR;
  299. POP();
  300. } else {
  301. INSERT_THIRD(); // [?, a, b]
  302. *THIRD() = *magic; // [__getitem__, a, b]
  303. if(!py_vectorcall(1, 0)) goto __ERROR;
  304. }
  305. *TOP() = self->last_retval;
  306. DISPATCH();
  307. }
  308. TypeError("'%t' object is not subscriptable", SECOND()->type);
  309. goto __ERROR;
  310. }
  311. case OP_STORE_FAST: frame->locals[byte.arg] = POPX(); DISPATCH();
  312. case OP_STORE_NAME: {
  313. assert(frame->is_dynamic);
  314. py_Name name = byte.arg;
  315. py_newstr(SP()++, py_name2str(name));
  316. // [value, name]
  317. if(!py_isnone(&frame->p0[1])){
  318. // locals
  319. if(py_setitem(&frame->p0[1], TOP(), SECOND())) {
  320. STACK_SHRINK(2);
  321. DISPATCH();
  322. } else {
  323. if(py_matchexc(tp_KeyError)) {
  324. py_clearexc(NULL);
  325. NameError(name);
  326. }
  327. goto __ERROR;
  328. }
  329. }else{
  330. // globals
  331. if(py_setitem(&frame->p0[0], TOP(), SECOND())) {
  332. STACK_SHRINK(2);
  333. DISPATCH();
  334. } else {
  335. if(py_matchexc(tp_KeyError)) {
  336. py_clearexc(NULL);
  337. NameError(name);
  338. }
  339. goto __ERROR;
  340. }
  341. }
  342. DISPATCH();
  343. }
  344. case OP_STORE_GLOBAL: {
  345. py_setdict(frame->module, byte.arg, TOP());
  346. POP();
  347. DISPATCH();
  348. }
  349. case OP_STORE_ATTR: {
  350. // [val, a] -> a.b = val
  351. if(!py_setattr(TOP(), byte.arg, SECOND())) goto __ERROR;
  352. STACK_SHRINK(2);
  353. DISPATCH();
  354. }
  355. case OP_STORE_SUBSCR: {
  356. // [val, a, b] -> a[b] = val
  357. py_Ref magic = py_tpfindmagic(SECOND()->type, __setitem__);
  358. if(magic) {
  359. PUSH(THIRD()); // [val, a, b, val]
  360. if(magic->type == tp_nativefunc) {
  361. if(!py_callcfunc(magic->_cfunc, 3, THIRD())) goto __ERROR;
  362. STACK_SHRINK(4);
  363. } else {
  364. *FOURTH() = *magic; // [__selitem__, a, b, val]
  365. if(!py_vectorcall(2, 0)) goto __ERROR;
  366. POP(); // discard retval
  367. }
  368. DISPATCH();
  369. }
  370. TypeError("'%t' object does not support item assignment", SECOND()->type);
  371. goto __ERROR;
  372. }
  373. case OP_DELETE_FAST: {
  374. py_Ref tmp = &frame->locals[byte.arg];
  375. if(py_isnil(tmp)) {
  376. py_Name name = c11__getitem(py_Name, &frame->co->varnames, byte.arg);
  377. UnboundLocalError(name);
  378. goto __ERROR;
  379. }
  380. py_newnil(tmp);
  381. DISPATCH();
  382. }
  383. case OP_DELETE_NAME: {
  384. assert(frame->is_dynamic);
  385. py_Name name = byte.arg;
  386. py_newstr(SP()++, py_name2str(name));
  387. if(!py_isnone(&frame->p0[1])){
  388. // locals
  389. if(py_delitem(&frame->p0[1], TOP())) {
  390. POP();
  391. DISPATCH();
  392. } else {
  393. if(py_matchexc(tp_KeyError)) {
  394. py_clearexc(NULL);
  395. NameError(name);
  396. }
  397. goto __ERROR;
  398. }
  399. }else{
  400. // globals
  401. if(py_delitem(&frame->p0[0], TOP())) {
  402. POP();
  403. DISPATCH();
  404. } else {
  405. if(py_matchexc(tp_KeyError)) {
  406. py_clearexc(NULL);
  407. NameError(name);
  408. }
  409. goto __ERROR;
  410. }
  411. }
  412. DISPATCH();
  413. }
  414. case OP_DELETE_GLOBAL: {
  415. py_Name name = byte.arg;
  416. bool ok = py_deldict(frame->module, name);
  417. if(!ok) {
  418. NameError(name);
  419. goto __ERROR;
  420. }
  421. DISPATCH();
  422. }
  423. case OP_DELETE_ATTR: {
  424. if(!py_delattr(TOP(), byte.arg)) goto __ERROR;
  425. DISPATCH();
  426. }
  427. case OP_DELETE_SUBSCR: {
  428. // [a, b] -> del a[b]
  429. py_Ref magic = py_tpfindmagic(SECOND()->type, __delitem__);
  430. if(magic) {
  431. if(magic->type == tp_nativefunc) {
  432. if(!py_callcfunc(magic->_cfunc, 2, SECOND())) goto __ERROR;
  433. STACK_SHRINK(2);
  434. } else {
  435. INSERT_THIRD(); // [?, a, b]
  436. *THIRD() = *magic; // [__delitem__, a, b]
  437. if(!py_vectorcall(1, 0)) goto __ERROR;
  438. POP(); // discard retval
  439. }
  440. DISPATCH();
  441. }
  442. TypeError("'%t' object does not support item deletion", SECOND()->type);
  443. goto __ERROR;
  444. }
  445. /*****************************************/
  446. case OP_BUILD_LONG: {
  447. // [x]
  448. py_Ref f = py_getdict(&self->builtins, py_name("long"));
  449. assert(f != NULL);
  450. if(!py_call(f, 1, TOP())) goto __ERROR;
  451. *TOP() = self->last_retval;
  452. DISPATCH();
  453. }
  454. case OP_BUILD_IMAG: {
  455. // [x]
  456. py_Ref f = py_getdict(&self->builtins, py_name("complex"));
  457. assert(f != NULL);
  458. py_TValue tmp = *TOP();
  459. *TOP() = *f; // [complex]
  460. py_newnil(SP()++); // [complex, NULL]
  461. py_newint(SP()++, 0); // [complex, NULL, 0]
  462. *SP()++ = tmp; // [complex, NULL, 0, x]
  463. if(!py_vectorcall(2, 0)) goto __ERROR;
  464. PUSH(py_retval());
  465. DISPATCH();
  466. }
  467. case OP_BUILD_BYTES: {
  468. int size;
  469. const char* data = py_tostrn(TOP(), &size);
  470. unsigned char* p = py_newbytes(TOP(), size);
  471. memcpy(p, data, size);
  472. DISPATCH();
  473. }
  474. case OP_BUILD_TUPLE: {
  475. py_TValue tmp;
  476. py_newtuple(&tmp, byte.arg);
  477. py_TValue* begin = SP() - byte.arg;
  478. for(int i = 0; i < byte.arg; i++) {
  479. py_tuple_setitem(&tmp, i, begin + i);
  480. }
  481. SP() = begin;
  482. PUSH(&tmp);
  483. DISPATCH();
  484. }
  485. case OP_BUILD_LIST: {
  486. py_TValue tmp;
  487. py_newlistn(&tmp, byte.arg);
  488. py_TValue* begin = SP() - byte.arg;
  489. for(int i = 0; i < byte.arg; i++) {
  490. py_list_setitem(&tmp, i, begin + i);
  491. }
  492. SP() = begin;
  493. PUSH(&tmp);
  494. DISPATCH();
  495. }
  496. case OP_BUILD_DICT: {
  497. py_TValue* begin = SP() - byte.arg * 2;
  498. py_Ref tmp = py_pushtmp();
  499. py_newdict(tmp);
  500. for(int i = 0; i < byte.arg * 2; i += 2) {
  501. py_dict_setitem(tmp, begin + i, begin + i + 1);
  502. if(py_checkexc()) goto __ERROR;
  503. }
  504. SP() = begin;
  505. PUSH(tmp);
  506. DISPATCH();
  507. }
  508. case OP_BUILD_SET: {
  509. py_TValue* begin = SP() - byte.arg;
  510. py_Ref typeobject_set = py_getdict(&self->builtins, py_name("set"));
  511. assert(typeobject_set != NULL);
  512. py_push(typeobject_set);
  513. py_pushnil();
  514. if(!py_vectorcall(0, 0)) goto __ERROR;
  515. py_push(py_retval()); // empty set
  516. py_Name id_add = py_name("add");
  517. for(int i = 0; i < byte.arg; i++) {
  518. py_push(TOP());
  519. if(!py_pushmethod(id_add)) {
  520. c11__abort("OP_BUILD_SET: failed to load method 'add'");
  521. }
  522. py_push(begin + i);
  523. if(!py_vectorcall(1, 0)) goto __ERROR;
  524. }
  525. py_TValue tmp = *TOP();
  526. SP() = begin;
  527. PUSH(&tmp);
  528. DISPATCH();
  529. }
  530. case OP_BUILD_SLICE: {
  531. // [start, stop, step]
  532. py_TValue tmp;
  533. py_newslice(&tmp);
  534. py_setslot(&tmp, 0, THIRD());
  535. py_setslot(&tmp, 1, SECOND());
  536. py_setslot(&tmp, 2, TOP());
  537. STACK_SHRINK(3);
  538. PUSH(&tmp);
  539. DISPATCH();
  540. }
  541. case OP_BUILD_STRING: {
  542. py_TValue* begin = SP() - byte.arg;
  543. c11_sbuf ss;
  544. c11_sbuf__ctor(&ss);
  545. for(int i = 0; i < byte.arg; i++) {
  546. if(!py_str(begin + i)) goto __ERROR;
  547. c11_sbuf__write_sv(&ss, py_tosv(&self->last_retval));
  548. }
  549. SP() = begin;
  550. c11_sbuf__py_submit(&ss, SP()++);
  551. DISPATCH();
  552. }
  553. /*****************************/
  554. case OP_BINARY_OP: {
  555. py_Name op = byte.arg & 0xFF;
  556. py_Name rop = byte.arg >> 8;
  557. if(!pk_stack_binaryop(self, op, rop)) goto __ERROR;
  558. POP();
  559. *TOP() = self->last_retval;
  560. DISPATCH();
  561. }
  562. case OP_IS_OP: {
  563. bool res = py_isidentical(SECOND(), TOP());
  564. POP();
  565. if(byte.arg) res = !res;
  566. py_newbool(TOP(), res);
  567. DISPATCH();
  568. }
  569. case OP_CONTAINS_OP: {
  570. // [b, a] -> b __contains__ a (a in b) -> [retval]
  571. py_Ref magic = py_tpfindmagic(SECOND()->type, __contains__);
  572. if(magic) {
  573. if(magic->type == tp_nativefunc) {
  574. if(!py_callcfunc(magic->_cfunc, 2, SECOND())) goto __ERROR;
  575. STACK_SHRINK(2);
  576. } else {
  577. INSERT_THIRD(); // [?, b, a]
  578. *THIRD() = *magic; // [__contains__, a, b]
  579. if(!py_vectorcall(1, 0)) goto __ERROR;
  580. }
  581. bool res = py_tobool(py_retval());
  582. if(byte.arg) res = !res;
  583. py_newbool(SP()++, res);
  584. DISPATCH();
  585. }
  586. TypeError("'%t' type does not support '__contains__'", SECOND()->type);
  587. goto __ERROR;
  588. }
  589. /*****************************************/
  590. case OP_JUMP_FORWARD: DISPATCH_JUMP((int16_t)byte.arg);
  591. case OP_POP_JUMP_IF_FALSE: {
  592. int res = py_bool(TOP());
  593. if(res < 0) goto __ERROR;
  594. POP();
  595. if(!res) DISPATCH_JUMP((int16_t)byte.arg);
  596. DISPATCH();
  597. }
  598. case OP_POP_JUMP_IF_TRUE: {
  599. int res = py_bool(TOP());
  600. if(res < 0) goto __ERROR;
  601. POP();
  602. if(res) DISPATCH_JUMP((int16_t)byte.arg);
  603. DISPATCH();
  604. }
  605. case OP_JUMP_IF_TRUE_OR_POP: {
  606. int res = py_bool(TOP());
  607. if(res < 0) goto __ERROR;
  608. if(res) {
  609. DISPATCH_JUMP((int16_t)byte.arg);
  610. } else {
  611. POP();
  612. DISPATCH();
  613. }
  614. }
  615. case OP_JUMP_IF_FALSE_OR_POP: {
  616. int res = py_bool(TOP());
  617. if(res < 0) goto __ERROR;
  618. if(!res) {
  619. DISPATCH_JUMP((int16_t)byte.arg);
  620. } else {
  621. POP();
  622. DISPATCH();
  623. }
  624. }
  625. case OP_SHORTCUT_IF_FALSE_OR_POP: {
  626. int res = py_bool(TOP());
  627. if(res < 0) goto __ERROR;
  628. if(!res) { // [b, False]
  629. STACK_SHRINK(2); // []
  630. py_newbool(SP()++, false); // [False]
  631. DISPATCH_JUMP((int16_t)byte.arg);
  632. } else {
  633. POP(); // [b]
  634. DISPATCH();
  635. }
  636. }
  637. case OP_LOOP_CONTINUE:
  638. // just an alias of OP_JUMP_FORWARD
  639. DISPATCH_JUMP((int16_t)byte.arg);
  640. case OP_LOOP_BREAK: {
  641. int target = Frame__ip(frame) + byte.arg;
  642. Frame__prepare_jump_break(frame, &self->stack, target);
  643. DISPATCH_JUMP((int16_t)byte.arg);
  644. }
  645. case OP_JUMP_ABSOLUTE_TOP: {
  646. int target = py_toint(TOP());
  647. POP();
  648. DISPATCH_JUMP_ABSOLUTE(target);
  649. }
  650. case OP_GOTO: {
  651. int target = c11_smallmap_n2i__get(&frame->co->labels, byte.arg, -1);
  652. if(target < 0) {
  653. RuntimeError("label '%n' not found", byte.arg);
  654. goto __ERROR;
  655. }
  656. Frame__prepare_jump_break(frame, &self->stack, target);
  657. DISPATCH_JUMP_ABSOLUTE(target);
  658. }
  659. /*****************************************/
  660. case OP_REPR: {
  661. if(!py_repr(TOP())) goto __ERROR;
  662. py_assign(TOP(), py_retval());
  663. DISPATCH();
  664. }
  665. case OP_CALL: {
  666. ManagedHeap__collect_if_needed(&self->heap);
  667. vectorcall_opcall(byte.arg & 0xFF, byte.arg >> 8);
  668. DISPATCH();
  669. }
  670. case OP_CALL_VARGS: {
  671. // [_0, _1, _2 | k1, v1, k2, v2]
  672. uint16_t argc = byte.arg & 0xFF;
  673. uint16_t kwargc = byte.arg >> 8;
  674. int n = 0;
  675. py_TValue* sp = SP();
  676. py_TValue* p1 = sp - kwargc * 2;
  677. py_TValue* base = p1 - argc;
  678. py_TValue* buf = self->__vectorcall_buffer;
  679. for(py_TValue* curr = base; curr != p1; curr++) {
  680. if(curr->type != tp_star_wrapper) {
  681. buf[n++] = *curr;
  682. } else {
  683. py_TValue* args = py_getslot(curr, 0);
  684. int length;
  685. py_TValue* p = pk_arrayview(args, &length);
  686. if(p) {
  687. for(int j = 0; j < length; j++) {
  688. buf[n++] = p[j];
  689. }
  690. argc += length - 1;
  691. } else {
  692. TypeError("*args must be a list or tuple, got '%t'", args->type);
  693. goto __ERROR;
  694. }
  695. }
  696. }
  697. for(py_TValue* curr = p1; curr != sp; curr += 2) {
  698. if(curr[1].type != tp_star_wrapper) {
  699. buf[n++] = curr[0];
  700. buf[n++] = curr[1];
  701. } else {
  702. assert(py_toint(&curr[0]) == 0);
  703. py_TValue* kwargs = py_getslot(&curr[1], 0);
  704. if(kwargs->type == tp_dict) {
  705. py_TValue* p = buf + n;
  706. if(!py_dict_apply(kwargs, unpack_dict_to_buffer, &p)) goto __ERROR;
  707. n = p - buf;
  708. kwargc += py_dict_len(kwargs) - 1;
  709. } else {
  710. TypeError("**kwargs must be a dict, got '%t'", kwargs->type);
  711. goto __ERROR;
  712. }
  713. }
  714. }
  715. memcpy(base, buf, n * sizeof(py_TValue));
  716. SP() = base + n;
  717. vectorcall_opcall(argc, kwargc);
  718. DISPATCH();
  719. }
  720. case OP_RETURN_VALUE: {
  721. if(byte.arg == BC_NOARG) {
  722. self->last_retval = POPX();
  723. } else {
  724. py_newnone(&self->last_retval);
  725. }
  726. VM__pop_frame(self);
  727. if(frame == base_frame) { // [ frameBase<- ]
  728. return RES_RETURN;
  729. } else {
  730. frame = self->top_frame;
  731. PUSH(&self->last_retval);
  732. goto __NEXT_FRAME;
  733. }
  734. DISPATCH();
  735. }
  736. case OP_YIELD_VALUE: {
  737. py_assign(py_retval(), TOP());
  738. POP();
  739. return RES_YIELD;
  740. }
  741. /////////
  742. case OP_LIST_APPEND: {
  743. // [list, iter, value]
  744. py_list_append(THIRD(), TOP());
  745. POP();
  746. DISPATCH();
  747. }
  748. case OP_DICT_ADD: {
  749. // [dict, iter, key, value]
  750. py_dict_setitem(FOURTH(), SECOND(), TOP());
  751. if(py_checkexc()) goto __ERROR;
  752. STACK_SHRINK(2);
  753. DISPATCH();
  754. }
  755. case OP_SET_ADD: {
  756. // [set, iter, value]
  757. py_push(THIRD()); // [| set]
  758. if(!py_pushmethod(py_name("add"))) {
  759. c11__abort("OP_SET_ADD: failed to load method 'add'");
  760. } // [|add() set]
  761. py_push(THIRD());
  762. if(!py_vectorcall(1, 0)) goto __ERROR;
  763. POP();
  764. DISPATCH();
  765. }
  766. /////////
  767. case OP_UNARY_NEGATIVE: {
  768. if(!pk_callmagic(__neg__, 1, TOP())) goto __ERROR;
  769. *TOP() = self->last_retval;
  770. DISPATCH();
  771. }
  772. case OP_UNARY_NOT: {
  773. int res = py_bool(TOP());
  774. if(res < 0) goto __ERROR;
  775. py_newbool(TOP(), !res);
  776. DISPATCH();
  777. }
  778. case OP_UNARY_STAR: {
  779. py_TValue value = POPX();
  780. int* level = py_newobject(SP()++, tp_star_wrapper, 1, sizeof(int));
  781. *level = byte.arg;
  782. py_setslot(TOP(), 0, &value);
  783. DISPATCH();
  784. }
  785. case OP_UNARY_INVERT: {
  786. if(!pk_callmagic(__invert__, 1, TOP())) goto __ERROR;
  787. *TOP() = self->last_retval;
  788. DISPATCH();
  789. }
  790. ////////////////
  791. case OP_GET_ITER: {
  792. if(!py_iter(TOP())) goto __ERROR;
  793. *TOP() = *py_retval();
  794. DISPATCH();
  795. }
  796. case OP_FOR_ITER: {
  797. int res = py_next(TOP());
  798. if(res == -1) goto __ERROR;
  799. if(res) {
  800. PUSH(py_retval());
  801. DISPATCH();
  802. } else {
  803. int target = Frame__prepare_loop_break(frame, &self->stack);
  804. DISPATCH_JUMP_ABSOLUTE(target);
  805. }
  806. }
  807. ////////
  808. case OP_IMPORT_PATH: {
  809. py_Ref path_object = c11__at(py_TValue, &frame->co->consts, byte.arg);
  810. const char* path = py_tostr(path_object);
  811. int res = py_import(path);
  812. if(res == -1) goto __ERROR;
  813. if(res == 0) {
  814. ImportError("module '%s' not found", path);
  815. goto __ERROR;
  816. }
  817. PUSH(py_retval());
  818. DISPATCH();
  819. }
  820. case OP_POP_IMPORT_STAR: {
  821. // [module]
  822. NameDict* dict = PyObject__dict(TOP()->_obj);
  823. py_Ref all = NameDict__try_get(dict, __all__);
  824. if(all) {
  825. int length;
  826. py_TValue* p = pk_arrayview(all, &length);
  827. if(!p) {
  828. TypeError("'__all__' must be a list or tuple, got '%t'", all->type);
  829. goto __ERROR;
  830. }
  831. for(int i = 0; i < length; i++) {
  832. py_Name name = py_namev(py_tosv(p + i));
  833. py_Ref value = NameDict__try_get(dict, name);
  834. if(value == NULL) {
  835. ImportError("cannot import name '%n'", name);
  836. goto __ERROR;
  837. } else {
  838. py_setdict(frame->module, name, value);
  839. }
  840. }
  841. } else {
  842. for(int i = 0; i < dict->count; i++) {
  843. NameDict_KV* kv = c11__at(NameDict_KV, dict, i);
  844. if(!kv->key) continue;
  845. c11_sv name = py_name2sv(kv->key);
  846. if(name.size == 0 || name.data[0] == '_') continue;
  847. py_setdict(frame->module, kv->key, &kv->value);
  848. }
  849. }
  850. POP();
  851. DISPATCH();
  852. }
  853. ////////
  854. case OP_UNPACK_SEQUENCE: {
  855. if(!stack_unpack_sequence(self, byte.arg)) goto __ERROR;
  856. DISPATCH();
  857. }
  858. case OP_UNPACK_EX: {
  859. int length;
  860. py_TValue* p = pk_arrayview(TOP(), &length);
  861. if(!p) {
  862. TypeError("expected list or tuple to unpack, got '%t'", TOP()->type);
  863. goto __ERROR;
  864. }
  865. int exceed = length - byte.arg;
  866. if(exceed < 0) {
  867. ValueError("not enough values to unpack");
  868. goto __ERROR;
  869. }
  870. POP();
  871. for(int i = 0; i < byte.arg; i++) {
  872. PUSH(p + i);
  873. }
  874. py_newlistn(SP()++, exceed);
  875. for(int i = 0; i < exceed; i++) {
  876. py_list_setitem(TOP(), i, p + byte.arg + i);
  877. }
  878. DISPATCH();
  879. }
  880. ///////////
  881. case OP_BEGIN_CLASS: {
  882. // [base]
  883. py_Name name = byte.arg;
  884. py_Type base;
  885. if(py_isnone(TOP())) {
  886. base = tp_object;
  887. } else {
  888. if(!py_checktype(TOP(), tp_type)) goto __ERROR;
  889. base = py_totype(TOP());
  890. }
  891. POP();
  892. py_Type type =
  893. pk_newtype(py_name2str(name), base, frame->module, NULL, true, false);
  894. PUSH(py_tpobject(type));
  895. self->__curr_class = TOP();
  896. DISPATCH();
  897. }
  898. case OP_END_CLASS: {
  899. // [cls or decorated]
  900. py_Name name = byte.arg;
  901. // set into f_globals
  902. py_setdict(frame->module, name, TOP());
  903. if(py_istype(TOP(), tp_type)) {
  904. // call on_end_subclass
  905. py_TypeInfo* ti = c11__at(py_TypeInfo, &self->types, py_totype(TOP()));
  906. if(ti->base != tp_object) {
  907. // PyTypeInfo* base_ti = &_all_types[ti->base];
  908. py_TypeInfo* base_ti = c11__at(py_TypeInfo, &self->types, ti->base);
  909. if(base_ti->on_end_subclass) base_ti->on_end_subclass(ti);
  910. }
  911. }
  912. POP();
  913. self->__curr_class = NULL;
  914. DISPATCH();
  915. }
  916. case OP_STORE_CLASS_ATTR: {
  917. py_Name name = byte.arg;
  918. if(py_istype(TOP(), tp_function)) {
  919. Function* ud = py_touserdata(TOP());
  920. ud->clazz = self->__curr_class->_obj;
  921. }
  922. py_setdict(self->__curr_class, name, TOP());
  923. POP();
  924. DISPATCH();
  925. }
  926. case OP_ADD_CLASS_ANNOTATION: {
  927. py_Type type = py_totype(self->__curr_class);
  928. py_TypeInfo* ti = c11__at(py_TypeInfo, &self->types, type);
  929. c11_vector__push(py_Name, &ti->annotated_fields, byte.arg);
  930. DISPATCH();
  931. }
  932. ///////////
  933. case OP_WITH_ENTER: {
  934. // [expr]
  935. py_push(TOP());
  936. if(!py_pushmethod(__enter__)) {
  937. TypeError("'%t' object does not support the context manager protocol",
  938. TOP()->type);
  939. goto __ERROR;
  940. }
  941. if(!py_vectorcall(0, 0)) goto __ERROR;
  942. PUSH(py_retval());
  943. DISPATCH();
  944. }
  945. case OP_WITH_EXIT: {
  946. // [expr]
  947. py_push(TOP());
  948. if(!py_pushmethod(__exit__)) {
  949. TypeError("'%t' object does not support the context manager protocol",
  950. TOP()->type);
  951. goto __ERROR;
  952. }
  953. if(!py_vectorcall(0, 0)) goto __ERROR;
  954. DISPATCH();
  955. }
  956. ///////////
  957. case OP_TRY_ENTER: {
  958. Frame__set_unwind_target(frame, SP());
  959. DISPATCH();
  960. }
  961. case OP_EXCEPTION_MATCH: {
  962. if(!py_checktype(TOP(), tp_type)) goto __ERROR;
  963. bool ok = py_isinstance(&self->curr_exception, py_totype(TOP()));
  964. py_newbool(TOP(), ok);
  965. DISPATCH();
  966. }
  967. case OP_RAISE: {
  968. // [exception]
  969. if(py_istype(TOP(), tp_type)) {
  970. if(!py_tpcall(py_totype(TOP()), 0, NULL)) goto __ERROR;
  971. py_assign(TOP(), py_retval());
  972. }
  973. if(!py_isinstance(TOP(), tp_BaseException)) {
  974. TypeError("exceptions must derive from BaseException");
  975. goto __ERROR;
  976. }
  977. py_raise(TOP());
  978. goto __ERROR;
  979. }
  980. case OP_RAISE_ASSERT: {
  981. if(byte.arg) {
  982. if(!py_str(TOP())) goto __ERROR;
  983. POP();
  984. py_exception(tp_AssertionError, "%s", py_tostr(py_retval()));
  985. } else {
  986. py_exception(tp_AssertionError, "");
  987. }
  988. goto __ERROR;
  989. }
  990. case OP_RE_RAISE: {
  991. assert(self->curr_exception.type);
  992. goto __ERROR_RE_RAISE;
  993. }
  994. case OP_PUSH_EXCEPTION: {
  995. assert(self->curr_exception.type);
  996. PUSH(&self->curr_exception);
  997. DISPATCH();
  998. }
  999. case OP_POP_EXCEPTION: {
  1000. assert(self->curr_exception.type);
  1001. py_clearexc(NULL);
  1002. DISPATCH();
  1003. }
  1004. //////////////////
  1005. case OP_FSTRING_EVAL: {
  1006. py_TValue* tmp = c11__at(py_TValue, &frame->co->consts, byte.arg);
  1007. const char* string = py_tostr(tmp);
  1008. // TODO: optimize this
  1009. if(!py_exec(string, "<f-string>", EVAL_MODE, frame->module)) goto __ERROR;
  1010. PUSH(py_retval());
  1011. DISPATCH();
  1012. }
  1013. case OP_FORMAT_STRING: {
  1014. py_Ref spec = c11__at(py_TValue, &frame->co->consts, byte.arg);
  1015. bool ok = format_object(TOP(), py_tosv(spec));
  1016. if(!ok) goto __ERROR;
  1017. py_assign(TOP(), py_retval());
  1018. DISPATCH();
  1019. }
  1020. default: c11__unreachedable();
  1021. }
  1022. c11__unreachedable();
  1023. __ERROR:
  1024. pk_print_stack(self, frame, (Bytecode){0});
  1025. py_BaseException__set_lineno(&self->curr_exception, Frame__lineno(frame), frame->co);
  1026. __ERROR_RE_RAISE:
  1027. do {
  1028. } while(0);
  1029. // printf("error.op: %s, line: %d\n", pk_opname(byte.op), Frame__lineno(frame));
  1030. int lineno = py_BaseException__get_lineno(&self->curr_exception, frame->co);
  1031. py_BaseException__stpush(&self->curr_exception,
  1032. frame->co->src,
  1033. lineno < 0 ? Frame__lineno(frame) : lineno,
  1034. frame->has_function ? frame->co->name->data : NULL);
  1035. int target = Frame__prepare_jump_exception_handler(frame, &self->stack);
  1036. if(target >= 0) {
  1037. // 1. Exception can be handled inside the current frame
  1038. DISPATCH_JUMP_ABSOLUTE(target);
  1039. } else {
  1040. // 2. Exception need to be propagated to the upper frame
  1041. bool is_base_frame_to_be_popped = frame == base_frame;
  1042. VM__pop_frame(self);
  1043. if(self->top_frame == NULL || is_base_frame_to_be_popped) {
  1044. // propagate to the top level
  1045. return RES_ERROR;
  1046. }
  1047. frame = self->top_frame;
  1048. goto __ERROR;
  1049. }
  1050. }
  1051. return RES_RETURN;
  1052. }
  1053. bool pk_stack_binaryop(VM* self, py_Name op, py_Name rop) {
  1054. // [a, b]
  1055. py_Ref magic = py_tpfindmagic(SECOND()->type, op);
  1056. if(magic) {
  1057. bool ok = py_call(magic, 2, SECOND());
  1058. if(!ok) return false;
  1059. if(self->last_retval.type != tp_NotImplementedType) return true;
  1060. }
  1061. // try reverse operation
  1062. if(rop) {
  1063. // [a, b] -> [b, a]
  1064. py_TValue tmp = *TOP();
  1065. *TOP() = *SECOND();
  1066. *SECOND() = tmp;
  1067. magic = py_tpfindmagic(SECOND()->type, rop);
  1068. if(magic) {
  1069. bool ok = py_call(magic, 2, SECOND());
  1070. if(!ok) return false;
  1071. if(self->last_retval.type != tp_NotImplementedType) return true;
  1072. }
  1073. }
  1074. // eq/ne op never fails
  1075. if(op == __eq__ || op == __ne__) {
  1076. bool res = py_isidentical(SECOND(), TOP());
  1077. py_newbool(py_retval(), res);
  1078. return true;
  1079. }
  1080. return TypeError("unsupported operand type(s) for '%n'", op);
  1081. }
  1082. bool py_binaryop(py_Ref lhs, py_Ref rhs, py_Name op, py_Name rop) {
  1083. VM* self = pk_current_vm;
  1084. PUSH(lhs);
  1085. PUSH(rhs);
  1086. bool ok = pk_stack_binaryop(self, op, rop);
  1087. STACK_SHRINK(2);
  1088. return ok;
  1089. }
  1090. static bool stack_unpack_sequence(VM* self, uint16_t arg) {
  1091. int length;
  1092. py_TValue* p = pk_arrayview(TOP(), &length);
  1093. if(!p) return TypeError("expected list or tuple to unpack, got '%t'", TOP()->type);
  1094. if(length != arg) return ValueError("expected %d values to unpack, got %d", arg, length);
  1095. POP();
  1096. for(int i = 0; i < length; i++) {
  1097. PUSH(p + i);
  1098. }
  1099. return true;
  1100. }
  1101. static bool format_object(py_Ref val, c11_sv spec) {
  1102. if(spec.size == 0) return py_str(val);
  1103. char type;
  1104. switch(spec.data[spec.size - 1]) {
  1105. case 'f':
  1106. case 'd':
  1107. case 's':
  1108. type = spec.data[spec.size - 1];
  1109. spec.size--; // remove last char
  1110. break;
  1111. default: type = ' '; break;
  1112. }
  1113. char pad_c = ' ';
  1114. if(strchr("0-=*#@!~", spec.data[0])) {
  1115. pad_c = spec.data[0];
  1116. spec = c11_sv__slice(spec, 1);
  1117. }
  1118. char align;
  1119. if(spec.data[0] == '^') {
  1120. align = '^';
  1121. spec = c11_sv__slice(spec, 1);
  1122. } else if(spec.data[0] == '>') {
  1123. align = '>';
  1124. spec = c11_sv__slice(spec, 1);
  1125. } else if(spec.data[0] == '<') {
  1126. align = '<';
  1127. spec = c11_sv__slice(spec, 1);
  1128. } else {
  1129. align = (py_isint(val) || py_isfloat(val)) ? '>' : '<';
  1130. }
  1131. int dot = c11_sv__index(spec, '.');
  1132. py_i64 width, precision;
  1133. if(dot >= 0) {
  1134. if(dot == 0) {
  1135. // {.2f}
  1136. width = -1;
  1137. } else {
  1138. // {10.2f}
  1139. IntParsingResult res = c11__parse_uint(c11_sv__slice2(spec, 0, dot), &width, 10);
  1140. if(res != IntParsing_SUCCESS) return ValueError("invalid format specifer");
  1141. }
  1142. IntParsingResult res = c11__parse_uint(c11_sv__slice(spec, dot + 1), &precision, 10);
  1143. if(res != IntParsing_SUCCESS) return ValueError("invalid format specifer");
  1144. } else {
  1145. // {10s}
  1146. IntParsingResult res = c11__parse_uint(spec, &width, 10);
  1147. if(res != IntParsing_SUCCESS) return ValueError("invalid format specifer");
  1148. precision = -1;
  1149. }
  1150. if(type != 'f' && dot >= 0) {
  1151. return ValueError("precision not allowed in the format specifier");
  1152. }
  1153. c11_sbuf buf;
  1154. c11_sbuf__ctor(&buf);
  1155. if(type == 'f') {
  1156. py_f64 x;
  1157. if(!py_castfloat(val, &x)) {
  1158. c11_sbuf__dtor(&buf);
  1159. return false;
  1160. }
  1161. if(precision < 0) precision = 6;
  1162. c11_sbuf__write_f64(&buf, x, precision);
  1163. } else if(type == 'd') {
  1164. if(!py_checkint(val)) {
  1165. c11_sbuf__dtor(&buf);
  1166. return false;
  1167. }
  1168. c11_sbuf__write_i64(&buf, py_toint(val));
  1169. } else if(type == 's') {
  1170. if(!py_checkstr(val)) {
  1171. c11_sbuf__dtor(&buf);
  1172. return false;
  1173. }
  1174. c11_sbuf__write_sv(&buf, py_tosv(val));
  1175. } else {
  1176. if(!py_str(val)) {
  1177. c11_sbuf__dtor(&buf);
  1178. return false;
  1179. }
  1180. c11_sbuf__write_sv(&buf, py_tosv(py_retval()));
  1181. }
  1182. c11_string* body = c11_sbuf__submit(&buf);
  1183. int length = c11_sv__u8_length(c11_string__sv(body));
  1184. c11_sbuf__ctor(&buf); // reinit sbuf
  1185. if(width != -1 && width > length) {
  1186. switch(align) {
  1187. case '>': {
  1188. c11_sbuf__write_pad(&buf, width - length, pad_c);
  1189. c11_sbuf__write_sv(&buf, c11_string__sv(body));
  1190. break;
  1191. }
  1192. case '<': {
  1193. c11_sbuf__write_sv(&buf, c11_string__sv(body));
  1194. c11_sbuf__write_pad(&buf, width - length, pad_c);
  1195. break;
  1196. }
  1197. case '^': {
  1198. int pad_left = (width - length) / 2;
  1199. int pad_right = (width - length) - pad_left;
  1200. c11_sbuf__write_pad(&buf, pad_left, pad_c);
  1201. c11_sbuf__write_sv(&buf, c11_string__sv(body));
  1202. c11_sbuf__write_pad(&buf, pad_right, pad_c);
  1203. break;
  1204. }
  1205. default: c11__unreachedable();
  1206. }
  1207. } else {
  1208. c11_sbuf__write_sv(&buf, c11_string__sv(body));
  1209. }
  1210. c11_string__delete(body);
  1211. c11_sbuf__py_submit(&buf, py_retval());
  1212. return true;
  1213. }