pocketpy.h 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025
  1. #pragma once
  2. #include "vm.h"
  3. #include "compiler.h"
  4. #include "repl.h"
  5. _Code VM::compile(_Str source, _Str filename, CompileMode mode) {
  6. Compiler compiler(this, source.c_str(), filename, mode);
  7. try{
  8. return compiler.__fillCode();
  9. }catch(_Error& e){
  10. throw e;
  11. }catch(std::exception& e){
  12. throw CompileError("UnexpectedError", e.what(), compiler.getLineSnapshot());
  13. }
  14. }
  15. #define BIND_NUM_ARITH_OPT(name, op) \
  16. _vm->bindMethodMulti({"int","float"}, #name, [](VM* vm, const pkpy::ArgList& args){ \
  17. if(!vm->isIntOrFloat(args[0], args[1])) \
  18. vm->typeError("unsupported operand type(s) for " #op ); \
  19. if(args._index(0)->isType(vm->_tp_int) && args._index(1)->isType(vm->_tp_int)){ \
  20. return vm->PyInt(vm->PyInt_AS_C(args._index(0)) op vm->PyInt_AS_C(args._index(1))); \
  21. }else{ \
  22. return vm->PyFloat(vm->numToFloat(args._index(0)) op vm->numToFloat(args._index(1))); \
  23. } \
  24. });
  25. #define BIND_NUM_LOGICAL_OPT(name, op, is_eq) \
  26. _vm->bindMethodMulti({"int","float"}, #name, [](VM* vm, const pkpy::ArgList& args){ \
  27. if(!vm->isIntOrFloat(args[0], args[1])){ \
  28. if constexpr(is_eq) return vm->PyBool(args[0] == args[1]); \
  29. vm->typeError("unsupported operand type(s) for " #op ); \
  30. } \
  31. return vm->PyBool(vm->numToFloat(args._index(0)) op vm->numToFloat(args._index(1))); \
  32. });
  33. void __initializeBuiltinFunctions(VM* _vm) {
  34. BIND_NUM_ARITH_OPT(__add__, +)
  35. BIND_NUM_ARITH_OPT(__sub__, -)
  36. BIND_NUM_ARITH_OPT(__mul__, *)
  37. BIND_NUM_LOGICAL_OPT(__lt__, <, false)
  38. BIND_NUM_LOGICAL_OPT(__le__, <=, false)
  39. BIND_NUM_LOGICAL_OPT(__gt__, >, false)
  40. BIND_NUM_LOGICAL_OPT(__ge__, >=, false)
  41. BIND_NUM_LOGICAL_OPT(__eq__, ==, true)
  42. #undef BIND_NUM_ARITH_OPT
  43. #undef BIND_NUM_LOGICAL_OPT
  44. _vm->bindBuiltinFunc("__sys_stdout_write", [](VM* vm, const pkpy::ArgList& args) {
  45. vm->__checkArgSize(args, 1);
  46. (*vm->_stdout) << vm->PyStr_AS_C(args[0]);
  47. return vm->None;
  48. });
  49. _vm->bindBuiltinFunc("super", [](VM* vm, const pkpy::ArgList& args) {
  50. vm->__checkArgSize(args, 0);
  51. auto it = vm->topFrame()->f_locals.find(m_self);
  52. if(it == vm->topFrame()->f_locals.end()) vm->typeError("super() can only be called in a class method");
  53. return vm->newObject(vm->_tp_super, it->second);
  54. });
  55. _vm->bindBuiltinFunc("eval", [](VM* vm, const pkpy::ArgList& args) {
  56. vm->__checkArgSize(args, 1);
  57. const _Str& expr = vm->PyStr_AS_C(args[0]);
  58. _Code code = vm->compile(expr, "<eval>", EVAL_MODE);
  59. return vm->_exec(code, vm->topFrame()->_module, vm->topFrame()->copy_f_locals());
  60. });
  61. _vm->bindBuiltinFunc("isinstance", [](VM* vm, const pkpy::ArgList& args) {
  62. vm->__checkArgSize(args, 2);
  63. return vm->PyBool(vm->isInstance(args[0], args[1]));
  64. });
  65. _vm->bindBuiltinFunc("repr", [](VM* vm, const pkpy::ArgList& args) {
  66. vm->__checkArgSize(args, 1);
  67. return vm->asRepr(args[0]);
  68. });
  69. _vm->bindBuiltinFunc("hash", [](VM* vm, const pkpy::ArgList& args) {
  70. vm->__checkArgSize(args, 1);
  71. return vm->PyInt(vm->hash(args[0]));
  72. });
  73. _vm->bindBuiltinFunc("len", [](VM* vm, const pkpy::ArgList& args) {
  74. vm->__checkArgSize(args, 1);
  75. return vm->call(args[0], __len__, pkpy::noArg());
  76. });
  77. _vm->bindBuiltinFunc("chr", [](VM* vm, const pkpy::ArgList& args) {
  78. vm->__checkArgSize(args, 1);
  79. _Int i = vm->PyInt_AS_C(args[0]);
  80. if (i < 0 || i > 128) vm->valueError("chr() arg not in range(128)");
  81. return vm->PyStr(std::string(1, (char)i));
  82. });
  83. _vm->bindBuiltinFunc("ord", [](VM* vm, const pkpy::ArgList& args) {
  84. vm->__checkArgSize(args, 1);
  85. _Str s = vm->PyStr_AS_C(args[0]);
  86. if (s.size() != 1) vm->typeError("ord() expected an ASCII character");
  87. return vm->PyInt((_Int)s[0]);
  88. });
  89. _vm->bindBuiltinFunc("globals", [](VM* vm, const pkpy::ArgList& args) {
  90. vm->__checkArgSize(args, 0);
  91. const auto& d = vm->topFrame()->f_globals();
  92. PyVar obj = vm->call(vm->builtins->attribs["dict"]);
  93. for (const auto& [k, v] : d) {
  94. vm->call(obj, __setitem__, pkpy::twoArgs(vm->PyStr(k), v));
  95. }
  96. return obj;
  97. });
  98. _vm->bindBuiltinFunc("locals", [](VM* vm, const pkpy::ArgList& args) {
  99. vm->__checkArgSize(args, 0);
  100. const auto& d = vm->topFrame()->f_locals;
  101. PyVar obj = vm->call(vm->builtins->attribs["dict"]);
  102. for (const auto& [k, v] : d) {
  103. vm->call(obj, __setitem__, pkpy::twoArgs(vm->PyStr(k), v));
  104. }
  105. return obj;
  106. });
  107. _vm->bindBuiltinFunc("dir", [](VM* vm, const pkpy::ArgList& args) {
  108. vm->__checkArgSize(args, 1);
  109. std::vector<_Str> names;
  110. for (auto& [k, _] : args[0]->attribs) names.push_back(k);
  111. for (auto& [k, _] : args[0]->_type->attribs) {
  112. if (k.find("__") == 0) continue;
  113. if (std::find(names.begin(), names.end(), k) == names.end()) names.push_back(k);
  114. }
  115. PyVarList ret;
  116. for (const auto& name : names) ret.push_back(vm->PyStr(name));
  117. std::sort(ret.begin(), ret.end(), [vm](const PyVar& a, const PyVar& b) {
  118. return vm->PyStr_AS_C(a) < vm->PyStr_AS_C(b);
  119. });
  120. return vm->PyList(ret);
  121. });
  122. _vm->bindMethod("object", "__repr__", [](VM* vm, const pkpy::ArgList& args) {
  123. PyVar _self = args[0];
  124. _Str s = "<" + UNION_TP_NAME(_self) + " object at " + std::to_string((uintptr_t)_self.get()) + ">";
  125. return vm->PyStr(s);
  126. });
  127. _vm->bindMethod("type", "__new__", [](VM* vm, const pkpy::ArgList& args) {
  128. vm->__checkArgSize(args, 1);
  129. return args[0]->_type;
  130. });
  131. _vm->bindMethod("type", "__eq__", [](VM* vm, const pkpy::ArgList& args) {
  132. vm->__checkArgSize(args, 2, true);
  133. return vm->PyBool(args[0] == args[1]);
  134. });
  135. _vm->bindMethod("range", "__new__", [](VM* vm, const pkpy::ArgList& args) {
  136. _Range r;
  137. switch (args.size()) {
  138. case 1: r.stop = vm->PyInt_AS_C(args[0]); break;
  139. case 2: r.start = vm->PyInt_AS_C(args[0]); r.stop = vm->PyInt_AS_C(args[1]); break;
  140. case 3: r.start = vm->PyInt_AS_C(args[0]); r.stop = vm->PyInt_AS_C(args[1]); r.step = vm->PyInt_AS_C(args[2]); break;
  141. default: vm->typeError("expected 1-3 arguments, but got " + std::to_string(args.size()));
  142. }
  143. return vm->PyRange(r);
  144. });
  145. _vm->bindMethod("range", "__iter__", [](VM* vm, const pkpy::ArgList& args) {
  146. vm->__checkType(args[0], vm->_tp_range);
  147. return vm->PyIter(
  148. pkpy::make_shared<BaseIterator, RangeIterator>(vm, args[0])
  149. );
  150. });
  151. _vm->bindMethod("NoneType", "__repr__", [](VM* vm, const pkpy::ArgList& args) {
  152. return vm->PyStr("None");
  153. });
  154. _vm->bindMethod("NoneType", "__json__", [](VM* vm, const pkpy::ArgList& args) {
  155. return vm->PyStr("null");
  156. });
  157. _vm->bindMethod("NoneType", "__eq__", [](VM* vm, const pkpy::ArgList& args) {
  158. return vm->PyBool(args[0] == args[1]);
  159. });
  160. _vm->bindMethodMulti({"int", "float"}, "__truediv__", [](VM* vm, const pkpy::ArgList& args) {
  161. if(!vm->isIntOrFloat(args[0], args[1]))
  162. vm->typeError("unsupported operand type(s) for " "/" );
  163. _Float rhs = vm->numToFloat(args[1]);
  164. if (rhs == 0) vm->zeroDivisionError();
  165. return vm->PyFloat(vm->numToFloat(args[0]) / rhs);
  166. });
  167. _vm->bindMethodMulti({"int", "float"}, "__pow__", [](VM* vm, const pkpy::ArgList& args) {
  168. if(!vm->isIntOrFloat(args[0], args[1]))
  169. vm->typeError("unsupported operand type(s) for " "**" );
  170. if(args[0]->isType(vm->_tp_int) && args[1]->isType(vm->_tp_int)){
  171. return vm->PyInt((_Int)round(pow(vm->PyInt_AS_C(args[0]), vm->PyInt_AS_C(args[1]))));
  172. }else{
  173. return vm->PyFloat((_Float)pow(vm->numToFloat(args[0]), vm->numToFloat(args[1])));
  174. }
  175. });
  176. /************ PyInt ************/
  177. _vm->bindMethod("int", "__new__", [](VM* vm, const pkpy::ArgList& args) {
  178. if(args.size() == 0) return vm->PyInt(0);
  179. vm->__checkArgSize(args, 1);
  180. if (args[0]->isType(vm->_tp_int)) return args[0];
  181. if (args[0]->isType(vm->_tp_float)) return vm->PyInt((_Int)vm->PyFloat_AS_C(args[0]));
  182. if (args[0]->isType(vm->_tp_bool)) return vm->PyInt(vm->PyBool_AS_C(args[0]) ? 1 : 0);
  183. if (args[0]->isType(vm->_tp_str)) {
  184. const _Str& s = vm->PyStr_AS_C(args[0]);
  185. try{
  186. size_t parsed = 0;
  187. _Int val = std::stoll(s, &parsed, 10);
  188. if(parsed != s.size()) throw std::invalid_argument("");
  189. return vm->PyInt(val);
  190. }catch(std::invalid_argument&){
  191. vm->valueError("invalid literal for int(): '" + s + "'");
  192. }
  193. }
  194. vm->typeError("int() argument must be a int, float, bool or str");
  195. return vm->None;
  196. });
  197. _vm->bindMethod("int", "__floordiv__", [](VM* vm, const pkpy::ArgList& args) {
  198. if(!args[0]->isType(vm->_tp_int) || !args[1]->isType(vm->_tp_int))
  199. vm->typeError("unsupported operand type(s) for " "//" );
  200. _Int rhs = vm->PyInt_AS_C(args._index(1));
  201. if(rhs == 0) vm->zeroDivisionError();
  202. return vm->PyInt(vm->PyInt_AS_C(args._index(0)) / rhs);
  203. });
  204. _vm->bindMethod("int", "__mod__", [](VM* vm, const pkpy::ArgList& args) {
  205. if(!args[0]->isType(vm->_tp_int) || !args[1]->isType(vm->_tp_int))
  206. vm->typeError("unsupported operand type(s) for " "%" );
  207. _Int rhs = vm->PyInt_AS_C(args._index(1));
  208. if(rhs == 0) vm->zeroDivisionError();
  209. return vm->PyInt(vm->PyInt_AS_C(args._index(0)) % rhs);
  210. });
  211. _vm->bindMethod("int", "__repr__", [](VM* vm, const pkpy::ArgList& args) {
  212. return vm->PyStr(std::to_string(vm->PyInt_AS_C(args[0])));
  213. });
  214. _vm->bindMethod("int", "__json__", [](VM* vm, const pkpy::ArgList& args) {
  215. return vm->PyStr(std::to_string((int)vm->PyInt_AS_C(args[0])));
  216. });
  217. #define __INT_BITWISE_OP(name,op) \
  218. _vm->bindMethod("int", #name, [](VM* vm, const pkpy::ArgList& args) { \
  219. if(!args[0]->isType(vm->_tp_int) || !args[1]->isType(vm->_tp_int)) \
  220. vm->typeError("unsupported operand type(s) for " #op ); \
  221. return vm->PyInt(vm->PyInt_AS_C(args._index(0)) op vm->PyInt_AS_C(args._index(1))); \
  222. });
  223. __INT_BITWISE_OP(__lshift__, <<)
  224. __INT_BITWISE_OP(__rshift__, >>)
  225. __INT_BITWISE_OP(__and__, &)
  226. __INT_BITWISE_OP(__or__, |)
  227. __INT_BITWISE_OP(__xor__, ^)
  228. #undef __INT_BITWISE_OP
  229. /************ PyFloat ************/
  230. _vm->bindMethod("float", "__new__", [](VM* vm, const pkpy::ArgList& args) {
  231. if(args.size() == 0) return vm->PyFloat(0.0);
  232. vm->__checkArgSize(args, 1);
  233. if (args[0]->isType(vm->_tp_int)) return vm->PyFloat((_Float)vm->PyInt_AS_C(args[0]));
  234. if (args[0]->isType(vm->_tp_float)) return args[0];
  235. if (args[0]->isType(vm->_tp_bool)) return vm->PyFloat(vm->PyBool_AS_C(args[0]) ? 1.0 : 0.0);
  236. if (args[0]->isType(vm->_tp_str)) {
  237. const _Str& s = vm->PyStr_AS_C(args[0]);
  238. if(s == "inf") return vm->PyFloat(INFINITY);
  239. if(s == "-inf") return vm->PyFloat(-INFINITY);
  240. try{
  241. _Float val = std::stod(s);
  242. return vm->PyFloat(val);
  243. }catch(std::invalid_argument&){
  244. vm->valueError("invalid literal for float(): '" + s + "'");
  245. }
  246. }
  247. vm->typeError("float() argument must be a int, float, bool or str");
  248. return vm->None;
  249. });
  250. _vm->bindMethod("float", "__repr__", [](VM* vm, const pkpy::ArgList& args) {
  251. _Float val = vm->PyFloat_AS_C(args[0]);
  252. if(std::isinf(val) || std::isnan(val)) return vm->PyStr(std::to_string(val));
  253. _StrStream ss;
  254. ss << std::setprecision(std::numeric_limits<_Float>::max_digits10-1) << val;
  255. std::string s = ss.str();
  256. if(std::all_of(s.begin()+1, s.end(), isdigit)) s += ".0";
  257. return vm->PyStr(s);
  258. });
  259. _vm->bindMethod("float", "__json__", [](VM* vm, const pkpy::ArgList& args) {
  260. _Float val = vm->PyFloat_AS_C(args[0]);
  261. if(std::isinf(val) || std::isnan(val)){
  262. vm->valueError("cannot jsonify 'nan' or 'inf'");
  263. }
  264. return vm->PyStr(std::to_string(val));
  265. });
  266. /************ PyString ************/
  267. _vm->bindMethod("str", "__new__", [](VM* vm, const pkpy::ArgList& args) {
  268. vm->__checkArgSize(args, 1);
  269. return vm->asStr(args[0]);
  270. });
  271. _vm->bindMethod("str", "__add__", [](VM* vm, const pkpy::ArgList& args) {
  272. if(!args[0]->isType(vm->_tp_str) || !args[1]->isType(vm->_tp_str))
  273. vm->typeError("unsupported operand type(s) for " "+" );
  274. const _Str& lhs = vm->PyStr_AS_C(args[0]);
  275. const _Str& rhs = vm->PyStr_AS_C(args[1]);
  276. return vm->PyStr(lhs + rhs);
  277. });
  278. _vm->bindMethod("str", "__len__", [](VM* vm, const pkpy::ArgList& args) {
  279. const _Str& _self = vm->PyStr_AS_C(args[0]);
  280. return vm->PyInt(_self.u8_length());
  281. });
  282. _vm->bindMethod("str", "__contains__", [](VM* vm, const pkpy::ArgList& args) {
  283. const _Str& _self = vm->PyStr_AS_C(args[0]);
  284. const _Str& _other = vm->PyStr_AS_C(args[1]);
  285. return vm->PyBool(_self.find(_other) != _Str::npos);
  286. });
  287. _vm->bindMethod("str", "__str__", [](VM* vm, const pkpy::ArgList& args) {
  288. return args[0]; // str is immutable
  289. });
  290. _vm->bindMethod("str", "__iter__", [](VM* vm, const pkpy::ArgList& args) {
  291. return vm->PyIter(
  292. pkpy::make_shared<BaseIterator, StringIterator>(vm, args[0])
  293. );
  294. });
  295. _vm->bindMethod("str", "__repr__", [](VM* vm, const pkpy::ArgList& args) {
  296. const _Str& _self = vm->PyStr_AS_C(args[0]);
  297. return vm->PyStr(_self.__escape(true));
  298. });
  299. _vm->bindMethod("str", "__json__", [](VM* vm, const pkpy::ArgList& args) {
  300. const _Str& _self = vm->PyStr_AS_C(args[0]);
  301. return vm->PyStr(_self.__escape(false));
  302. });
  303. _vm->bindMethod("str", "__eq__", [](VM* vm, const pkpy::ArgList& args) {
  304. if(args[0]->isType(vm->_tp_str) && args[1]->isType(vm->_tp_str))
  305. return vm->PyBool(vm->PyStr_AS_C(args[0]) == vm->PyStr_AS_C(args[1]));
  306. return vm->PyBool(args[0] == args[1]); // fallback
  307. });
  308. _vm->bindMethod("str", "__getitem__", [](VM* vm, const pkpy::ArgList& args) {
  309. const _Str& _self (vm->PyStr_AS_C(args[0]));
  310. if(args[1]->isType(vm->_tp_slice)){
  311. _Slice s = vm->PySlice_AS_C(args[1]);
  312. s.normalize(_self.u8_length());
  313. return vm->PyStr(_self.u8_substr(s.start, s.stop));
  314. }
  315. int _index = (int)vm->PyInt_AS_C(args[1]);
  316. _index = vm->normalizedIndex(_index, _self.u8_length());
  317. return vm->PyStr(_self.u8_getitem(_index));
  318. });
  319. _vm->bindMethod("str", "__gt__", [](VM* vm, const pkpy::ArgList& args) {
  320. const _Str& _self (vm->PyStr_AS_C(args[0]));
  321. const _Str& _obj (vm->PyStr_AS_C(args[1]));
  322. return vm->PyBool(_self > _obj);
  323. });
  324. _vm->bindMethod("str", "__lt__", [](VM* vm, const pkpy::ArgList& args) {
  325. const _Str& _self (vm->PyStr_AS_C(args[0]));
  326. const _Str& _obj (vm->PyStr_AS_C(args[1]));
  327. return vm->PyBool(_self < _obj);
  328. });
  329. _vm->bindMethod("str", "upper", [](VM* vm, const pkpy::ArgList& args) {
  330. vm->__checkArgSize(args, 1, true);
  331. const _Str& _self (vm->PyStr_AS_C(args[0]));
  332. _StrStream ss;
  333. for(auto c : _self) ss << (char)toupper(c);
  334. return vm->PyStr(ss.str());
  335. });
  336. _vm->bindMethod("str", "lower", [](VM* vm, const pkpy::ArgList& args) {
  337. vm->__checkArgSize(args, 1, true);
  338. const _Str& _self (vm->PyStr_AS_C(args[0]));
  339. _StrStream ss;
  340. for(auto c : _self) ss << (char)tolower(c);
  341. return vm->PyStr(ss.str());
  342. });
  343. _vm->bindMethod("str", "replace", [](VM* vm, const pkpy::ArgList& args) {
  344. vm->__checkArgSize(args, 3, true);
  345. const _Str& _self = vm->PyStr_AS_C(args[0]);
  346. const _Str& _old = vm->PyStr_AS_C(args[1]);
  347. const _Str& _new = vm->PyStr_AS_C(args[2]);
  348. _Str _copy = _self;
  349. // replace all occurences of _old with _new in _copy
  350. size_t pos = 0;
  351. while ((pos = _copy.find(_old, pos)) != std::string::npos) {
  352. _copy.replace(pos, _old.length(), _new);
  353. pos += _new.length();
  354. }
  355. return vm->PyStr(_copy);
  356. });
  357. _vm->bindMethod("str", "startswith", [](VM* vm, const pkpy::ArgList& args) {
  358. vm->__checkArgSize(args, 2, true);
  359. const _Str& _self = vm->PyStr_AS_C(args[0]);
  360. const _Str& _prefix = vm->PyStr_AS_C(args[1]);
  361. return vm->PyBool(_self.find(_prefix) == 0);
  362. });
  363. _vm->bindMethod("str", "endswith", [](VM* vm, const pkpy::ArgList& args) {
  364. vm->__checkArgSize(args, 2, true);
  365. const _Str& _self = vm->PyStr_AS_C(args[0]);
  366. const _Str& _suffix = vm->PyStr_AS_C(args[1]);
  367. return vm->PyBool(_self.rfind(_suffix) == _self.length() - _suffix.length());
  368. });
  369. _vm->bindMethod("str", "join", [](VM* vm, const pkpy::ArgList& args) {
  370. vm->__checkArgSize(args, 2, true);
  371. const _Str& _self = vm->PyStr_AS_C(args[0]);
  372. PyVarList* _list;
  373. if(args[1]->isType(vm->_tp_list)){
  374. _list = &vm->PyList_AS_C(args[1]);
  375. }else if(args[1]->isType(vm->_tp_tuple)){
  376. _list = &vm->PyTuple_AS_C(args[1]);
  377. }else{
  378. vm->typeError("can only join a list or tuple");
  379. }
  380. _StrStream ss;
  381. for(int i = 0; i < _list->size(); i++){
  382. if(i > 0) ss << _self;
  383. ss << vm->PyStr_AS_C(vm->asStr(_list->operator[](i)));
  384. }
  385. return vm->PyStr(ss.str());
  386. });
  387. /************ PyList ************/
  388. _vm->bindMethod("list", "__iter__", [](VM* vm, const pkpy::ArgList& args) {
  389. vm->__checkType(args[0], vm->_tp_list);
  390. return vm->PyIter(
  391. pkpy::make_shared<BaseIterator, VectorIterator>(vm, args[0])
  392. );
  393. });
  394. _vm->bindMethod("list", "append", [](VM* vm, const pkpy::ArgList& args) {
  395. vm->__checkArgSize(args, 2, true);
  396. PyVarList& _self = vm->PyList_AS_C(args[0]);
  397. _self.push_back(args[1]);
  398. return vm->None;
  399. });
  400. _vm->bindMethod("list", "insert", [](VM* vm, const pkpy::ArgList& args) {
  401. vm->__checkArgSize(args, 3, true);
  402. PyVarList& _self = vm->PyList_AS_C(args[0]);
  403. int _index = (int)vm->PyInt_AS_C(args[1]);
  404. if(_index < 0) _index += _self.size();
  405. if(_index < 0) _index = 0;
  406. if(_index > _self.size()) _index = _self.size();
  407. _self.insert(_self.begin() + _index, args[2]);
  408. return vm->None;
  409. });
  410. _vm->bindMethod("list", "clear", [](VM* vm, const pkpy::ArgList& args) {
  411. vm->__checkArgSize(args, 1, true);
  412. vm->PyList_AS_C(args[0]).clear();
  413. return vm->None;
  414. });
  415. _vm->bindMethod("list", "copy", [](VM* vm, const pkpy::ArgList& args) {
  416. vm->__checkArgSize(args, 1, true);
  417. return vm->PyList(vm->PyList_AS_C(args[0]));
  418. });
  419. _vm->bindMethod("list", "__add__", [](VM* vm, const pkpy::ArgList& args) {
  420. const PyVarList& _self = vm->PyList_AS_C(args[0]);
  421. const PyVarList& _obj = vm->PyList_AS_C(args[1]);
  422. PyVarList _new_list = _self;
  423. _new_list.insert(_new_list.end(), _obj.begin(), _obj.end());
  424. return vm->PyList(_new_list);
  425. });
  426. _vm->bindMethod("list", "__len__", [](VM* vm, const pkpy::ArgList& args) {
  427. const PyVarList& _self = vm->PyList_AS_C(args[0]);
  428. return vm->PyInt(_self.size());
  429. });
  430. _vm->bindMethod("list", "__getitem__", [](VM* vm, const pkpy::ArgList& args) {
  431. const PyVarList& _self = vm->PyList_AS_C(args[0]);
  432. if(args[1]->isType(vm->_tp_slice)){
  433. _Slice s = vm->PySlice_AS_C(args[1]);
  434. s.normalize(_self.size());
  435. PyVarList _new_list;
  436. for(size_t i = s.start; i < s.stop; i++)
  437. _new_list.push_back(_self[i]);
  438. return vm->PyList(_new_list);
  439. }
  440. int _index = (int)vm->PyInt_AS_C(args[1]);
  441. _index = vm->normalizedIndex(_index, _self.size());
  442. return _self[_index];
  443. });
  444. _vm->bindMethod("list", "__setitem__", [](VM* vm, const pkpy::ArgList& args) {
  445. PyVarList& _self = vm->PyList_AS_C(args[0]);
  446. int _index = (int)vm->PyInt_AS_C(args[1]);
  447. _index = vm->normalizedIndex(_index, _self.size());
  448. _self[_index] = args[2];
  449. return vm->None;
  450. });
  451. _vm->bindMethod("list", "__delitem__", [](VM* vm, const pkpy::ArgList& args) {
  452. PyVarList& _self = vm->PyList_AS_C(args[0]);
  453. int _index = (int)vm->PyInt_AS_C(args[1]);
  454. _index = vm->normalizedIndex(_index, _self.size());
  455. _self.erase(_self.begin() + _index);
  456. return vm->None;
  457. });
  458. /************ PyTuple ************/
  459. _vm->bindMethod("tuple", "__new__", [](VM* vm, const pkpy::ArgList& args) {
  460. vm->__checkArgSize(args, 1);
  461. PyVarList _list = vm->PyList_AS_C(vm->call(vm->builtins->attribs["list"], args));
  462. return vm->PyTuple(_list);
  463. });
  464. _vm->bindMethod("tuple", "__iter__", [](VM* vm, const pkpy::ArgList& args) {
  465. vm->__checkType(args[0], vm->_tp_tuple);
  466. return vm->PyIter(
  467. pkpy::make_shared<BaseIterator, VectorIterator>(vm, args[0])
  468. );
  469. });
  470. _vm->bindMethod("tuple", "__len__", [](VM* vm, const pkpy::ArgList& args) {
  471. const PyVarList& _self = vm->PyTuple_AS_C(args[0]);
  472. return vm->PyInt(_self.size());
  473. });
  474. _vm->bindMethod("tuple", "__getitem__", [](VM* vm, const pkpy::ArgList& args) {
  475. const PyVarList& _self = vm->PyTuple_AS_C(args[0]);
  476. int _index = (int)vm->PyInt_AS_C(args[1]);
  477. _index = vm->normalizedIndex(_index, _self.size());
  478. return _self[_index];
  479. });
  480. /************ PyBool ************/
  481. _vm->bindMethod("bool", "__new__", [](VM* vm, const pkpy::ArgList& args) {
  482. vm->__checkArgSize(args, 1);
  483. return vm->asBool(args[0]);
  484. });
  485. _vm->bindMethod("bool", "__repr__", [](VM* vm, const pkpy::ArgList& args) {
  486. bool val = vm->PyBool_AS_C(args[0]);
  487. return vm->PyStr(val ? "True" : "False");
  488. });
  489. _vm->bindMethod("bool", "__json__", [](VM* vm, const pkpy::ArgList& args) {
  490. bool val = vm->PyBool_AS_C(args[0]);
  491. return vm->PyStr(val ? "true" : "false");
  492. });
  493. _vm->bindMethod("bool", "__eq__", [](VM* vm, const pkpy::ArgList& args) {
  494. return vm->PyBool(args[0] == args[1]);
  495. });
  496. _vm->bindMethod("bool", "__xor__", [](VM* vm, const pkpy::ArgList& args) {
  497. bool _self = vm->PyBool_AS_C(args[0]);
  498. bool _obj = vm->PyBool_AS_C(args[1]);
  499. return vm->PyBool(_self ^ _obj);
  500. });
  501. _vm->bindMethod("ellipsis", "__repr__", [](VM* vm, const pkpy::ArgList& args) {
  502. return vm->PyStr("Ellipsis");
  503. });
  504. _vm->bindMethod("_native_function", "__call__", [](VM* vm, const pkpy::ArgList& args) {
  505. const _CppFunc& _self = vm->PyNativeFunction_AS_C(args[0]);
  506. return _self(vm, args.subList(1));
  507. });
  508. _vm->bindMethod("function", "__call__", [](VM* vm, const pkpy::ArgList& args) {
  509. return vm->call(args[0], args.subList(1));
  510. });
  511. _vm->bindMethod("_bounded_method", "__call__", [](VM* vm, const pkpy::ArgList& args) {
  512. vm->__checkType(args[0], vm->_tp_bounded_method);
  513. const _BoundedMethod& _self = vm->PyBoundedMethod_AS_C(args[0]);
  514. pkpy::ArgList newArgs(args.size());
  515. newArgs[0] = _self.obj;
  516. for(int i = 1; i < args.size(); i++) newArgs[i] = args[i];
  517. return vm->call(_self.method, newArgs);
  518. });
  519. }
  520. #include "builtins.h"
  521. #ifdef _WIN32
  522. #define __EXPORT __declspec(dllexport)
  523. #elif __APPLE__
  524. #define __EXPORT __attribute__((visibility("default"))) __attribute__((used))
  525. #elif __EMSCRIPTEN__
  526. #define __EXPORT EMSCRIPTEN_KEEPALIVE
  527. #define __NO_MAIN
  528. #else
  529. #define __EXPORT
  530. #endif
  531. void __addModuleTime(VM* vm){
  532. PyVar mod = vm->newModule("time");
  533. vm->bindFunc(mod, "time", [](VM* vm, const pkpy::ArgList& args) {
  534. auto now = std::chrono::high_resolution_clock::now();
  535. return vm->PyFloat(std::chrono::duration_cast<std::chrono::microseconds>(now.time_since_epoch()).count() / 1000000.0);
  536. });
  537. vm->bindFunc(mod, "sleep", [](VM* vm, const pkpy::ArgList& args) {
  538. vm->__checkArgSize(args, 1);
  539. if(!vm->isIntOrFloat(args[0])){
  540. vm->typeError("time.sleep() argument must be int or float");
  541. }
  542. double sec = vm->numToFloat(args[0]);
  543. vm->sleepForSecs(sec);
  544. return vm->None;
  545. });
  546. }
  547. void __addModuleSys(VM* vm){
  548. PyVar mod = vm->newModule("sys");
  549. vm->bindFunc(mod, "getrefcount", [](VM* vm, const pkpy::ArgList& args) {
  550. vm->__checkArgSize(args, 1);
  551. return vm->PyInt(args[0].use_count());
  552. });
  553. vm->bindFunc(mod, "getrecursionlimit", [](VM* vm, const pkpy::ArgList& args) {
  554. vm->__checkArgSize(args, 0);
  555. return vm->PyInt(vm->maxRecursionDepth);
  556. });
  557. vm->bindFunc(mod, "setrecursionlimit", [](VM* vm, const pkpy::ArgList& args) {
  558. vm->__checkArgSize(args, 1);
  559. vm->maxRecursionDepth = (int)vm->PyInt_AS_C(args[0]);
  560. return vm->None;
  561. });
  562. vm->setAttr(mod, "version", vm->PyStr(PK_VERSION));
  563. }
  564. void __addModuleJson(VM* vm){
  565. PyVar mod = vm->newModule("json");
  566. vm->bindFunc(mod, "loads", [](VM* vm, const pkpy::ArgList& args) {
  567. vm->__checkArgSize(args, 1);
  568. const _Str& expr = vm->PyStr_AS_C(args[0]);
  569. _Code code = vm->compile(expr, "<json>", JSON_MODE);
  570. return vm->_exec(code, vm->topFrame()->_module, vm->topFrame()->copy_f_locals());
  571. });
  572. vm->bindFunc(mod, "dumps", [](VM* vm, const pkpy::ArgList& args) {
  573. vm->__checkArgSize(args, 1);
  574. return vm->asJson(args[0]);
  575. });
  576. }
  577. void __addModuleMath(VM* vm){
  578. PyVar mod = vm->newModule("math");
  579. vm->setAttr(mod, "pi", vm->PyFloat(3.1415926535897932384));
  580. vm->setAttr(mod, "e" , vm->PyFloat(2.7182818284590452354));
  581. vm->bindFunc(mod, "log", [](VM* vm, const pkpy::ArgList& args) {
  582. vm->__checkArgSize(args, 1);
  583. return vm->PyFloat(log(vm->numToFloat(args[0])));
  584. });
  585. vm->bindFunc(mod, "log10", [](VM* vm, const pkpy::ArgList& args) {
  586. vm->__checkArgSize(args, 1);
  587. return vm->PyFloat(log10(vm->numToFloat(args[0])));
  588. });
  589. vm->bindFunc(mod, "log2", [](VM* vm, const pkpy::ArgList& args) {
  590. vm->__checkArgSize(args, 1);
  591. return vm->PyFloat(log2(vm->numToFloat(args[0])));
  592. });
  593. vm->bindFunc(mod, "sin", [](VM* vm, const pkpy::ArgList& args) {
  594. vm->__checkArgSize(args, 1);
  595. return vm->PyFloat(sin(vm->numToFloat(args[0])));
  596. });
  597. vm->bindFunc(mod, "cos", [](VM* vm, const pkpy::ArgList& args) {
  598. vm->__checkArgSize(args, 1);
  599. return vm->PyFloat(cos(vm->numToFloat(args[0])));
  600. });
  601. vm->bindFunc(mod, "tan", [](VM* vm, const pkpy::ArgList& args) {
  602. vm->__checkArgSize(args, 1);
  603. return vm->PyFloat(tan(vm->numToFloat(args[0])));
  604. });
  605. vm->bindFunc(mod, "isclose", [](VM* vm, const pkpy::ArgList& args) {
  606. vm->__checkArgSize(args, 2);
  607. _Float a = vm->numToFloat(args[0]);
  608. _Float b = vm->numToFloat(args[1]);
  609. return vm->PyBool(fabs(a - b) < 1e-9);
  610. });
  611. vm->bindFunc(mod, "isnan", [](VM* vm, const pkpy::ArgList& args) {
  612. vm->__checkArgSize(args, 1);
  613. return vm->PyBool(std::isnan(vm->numToFloat(args[0])));
  614. });
  615. vm->bindFunc(mod, "isinf", [](VM* vm, const pkpy::ArgList& args) {
  616. vm->__checkArgSize(args, 1);
  617. return vm->PyBool(std::isinf(vm->numToFloat(args[0])));
  618. });
  619. }
  620. PyVar __regex_search(const _Str& pattern, const _Str& string, bool fromStart, VM* vm){
  621. std::regex re(pattern);
  622. std::smatch m;
  623. if(std::regex_search(string, m, re)){
  624. if(fromStart && m.position() != 0){
  625. return vm->None;
  626. }
  627. PyVar ret = vm->newObject(vm->_userTypes["re.Match"], (_Int)1);
  628. vm->setAttr(ret, "_start", vm->PyInt(
  629. string.__to_u8_index(m.position())
  630. ));
  631. vm->setAttr(ret, "_end", vm->PyInt(
  632. string.__to_u8_index(m.position() + m.length())
  633. ));
  634. PyVarList groups(m.size());
  635. for(size_t i = 0; i < m.size(); ++i){
  636. groups[i] = vm->PyStr(m[i].str());
  637. }
  638. vm->setAttr(ret, "_groups", vm->PyTuple(groups));
  639. return ret;
  640. }
  641. return vm->None;
  642. };
  643. void __addModuleRe(VM* vm){
  644. PyVar mod = vm->newModule("re");
  645. PyVar _tp_match = vm->newUserClassType(mod, "Match", vm->_tp_object);
  646. vm->bindMethod("re.Match", "start", [](VM* vm, const pkpy::ArgList& args) {
  647. vm->__checkArgSize(args, 1, true);
  648. PyVar self = args[0];
  649. return vm->getAttr(self, "_start");
  650. });
  651. vm->bindMethod("re.Match", "end", [](VM* vm, const pkpy::ArgList& args) {
  652. vm->__checkArgSize(args, 1, true);
  653. PyVar self = args[0];
  654. return vm->getAttr(self, "_end");
  655. });
  656. vm->bindMethod("re.Match", "span", [](VM* vm, const pkpy::ArgList& args) {
  657. vm->__checkArgSize(args, 1, true);
  658. PyVar self = args[0];
  659. PyVarList vec = { vm->getAttr(self, "_start"), vm->getAttr(self, "_end") };
  660. return vm->PyTuple(vec);
  661. });
  662. vm->bindMethod("re.Match", "group", [](VM* vm, const pkpy::ArgList& args) {
  663. vm->__checkArgSize(args, 2, true);
  664. int index = (int)vm->PyInt_AS_C(args[1]);
  665. const auto& vec = vm->PyTuple_AS_C(vm->getAttr(args[0], "_groups"));
  666. vm->normalizedIndex(index, vec.size());
  667. return vec[index];
  668. });
  669. vm->bindFunc(mod, "match", [](VM* vm, const pkpy::ArgList& args) {
  670. vm->__checkArgSize(args, 2);
  671. const _Str& pattern = vm->PyStr_AS_C(args[0]);
  672. const _Str& string = vm->PyStr_AS_C(args[1]);
  673. return __regex_search(pattern, string, true, vm);
  674. });
  675. vm->bindFunc(mod, "search", [](VM* vm, const pkpy::ArgList& args) {
  676. vm->__checkArgSize(args, 2);
  677. const _Str& pattern = vm->PyStr_AS_C(args[0]);
  678. const _Str& string = vm->PyStr_AS_C(args[1]);
  679. return __regex_search(pattern, string, false, vm);
  680. });
  681. vm->bindFunc(mod, "sub", [](VM* vm, const pkpy::ArgList& args) {
  682. vm->__checkArgSize(args, 3);
  683. const _Str& pattern = vm->PyStr_AS_C(args[0]);
  684. const _Str& repl = vm->PyStr_AS_C(args[1]);
  685. const _Str& string = vm->PyStr_AS_C(args[2]);
  686. std::regex re(pattern);
  687. return vm->PyStr(std::regex_replace(string, re, repl));
  688. });
  689. vm->bindFunc(mod, "split", [](VM* vm, const pkpy::ArgList& args) {
  690. vm->__checkArgSize(args, 2);
  691. const _Str& pattern = vm->PyStr_AS_C(args[0]);
  692. const _Str& string = vm->PyStr_AS_C(args[1]);
  693. std::regex re(pattern);
  694. std::sregex_token_iterator it(string.begin(), string.end(), re, -1);
  695. std::sregex_token_iterator end;
  696. PyVarList vec;
  697. for(; it != end; ++it){
  698. vec.push_back(vm->PyStr(it->str()));
  699. }
  700. return vm->PyList(vec);
  701. });
  702. }
  703. class _PkExported{
  704. public:
  705. virtual ~_PkExported() = default;
  706. virtual void* get() = 0;
  707. };
  708. static std::vector<_PkExported*> _pkLookupTable;
  709. template<typename T>
  710. class PkExported : public _PkExported{
  711. T* _ptr;
  712. public:
  713. template<typename... Args>
  714. PkExported(Args&&... args) {
  715. _ptr = new T(std::forward<Args>(args)...);
  716. _pkLookupTable.push_back(this);
  717. }
  718. ~PkExported() override { delete _ptr; }
  719. void* get() override { return _ptr; }
  720. operator T*() { return _ptr; }
  721. };
  722. #define pkpy_allocate(T, ...) *(new PkExported<T>(__VA_ARGS__))
  723. extern "C" {
  724. __EXPORT
  725. /// Delete a pointer allocated by `pkpy_xxx_xxx`.
  726. /// It can be `VM*`, `REPL*`, `ThreadedVM*`, `char*`, etc.
  727. ///
  728. /// !!!
  729. /// If the pointer is not allocated by `pkpy_xxx_xxx`, the behavior is undefined.
  730. /// For char*, you can also use trivial `delete` in your language.
  731. /// !!!
  732. void pkpy_delete(void* p){
  733. for(int i = 0; i < _pkLookupTable.size(); i++){
  734. if(_pkLookupTable[i]->get() == p){
  735. delete _pkLookupTable[i];
  736. _pkLookupTable.erase(_pkLookupTable.begin() + i);
  737. return;
  738. }
  739. }
  740. free(p);
  741. }
  742. __EXPORT
  743. /// Run a given source on a virtual machine.
  744. void pkpy_vm_exec(VM* vm, const char* source){
  745. vm->exec(source, "main.py", EXEC_MODE);
  746. }
  747. __EXPORT
  748. /// Get a global variable of a virtual machine.
  749. ///
  750. /// Return a json representing the result.
  751. /// If the variable is not found, return `nullptr`.
  752. char* pkpy_vm_get_global(VM* vm, const char* name){
  753. auto it = vm->_main->attribs.find(name);
  754. if(it == vm->_main->attribs.end()) return nullptr;
  755. try{
  756. _Str _json = vm->PyStr_AS_C(vm->asJson(it->second));
  757. return strdup(_json.c_str());
  758. }catch(...){
  759. return nullptr;
  760. }
  761. }
  762. __EXPORT
  763. /// Evaluate an expression.
  764. ///
  765. /// Return a json representing the result.
  766. /// If there is any error, return `nullptr`.
  767. char* pkpy_vm_eval(VM* vm, const char* source){
  768. PyVarOrNull ret = vm->exec(source, "<eval>", EVAL_MODE);
  769. if(ret == nullptr) return nullptr;
  770. try{
  771. _Str _json = vm->PyStr_AS_C(vm->asJson(ret));
  772. return strdup(_json.c_str());
  773. }catch(...){
  774. return nullptr;
  775. }
  776. }
  777. __EXPORT
  778. /// Create a REPL, using the given virtual machine as the backend.
  779. REPL* pkpy_new_repl(VM* vm){
  780. return pkpy_allocate(REPL, vm);
  781. }
  782. __EXPORT
  783. /// Input a source line to an interactive console.
  784. void pkpy_repl_input(REPL* r, const char* line){
  785. r->input(line);
  786. }
  787. __EXPORT
  788. /// Check if the REPL needs more lines.
  789. int pkpy_repl_last_input_result(REPL* r){
  790. return (int)(r->last_input_result());
  791. }
  792. __EXPORT
  793. /// Add a source module into a virtual machine.
  794. void pkpy_vm_add_module(VM* vm, const char* name, const char* source){
  795. vm->addLazyModule(name, source);
  796. }
  797. void __vm_init(VM* vm){
  798. __initializeBuiltinFunctions(vm);
  799. __addModuleSys(vm);
  800. __addModuleTime(vm);
  801. __addModuleJson(vm);
  802. __addModuleMath(vm);
  803. __addModuleRe(vm);
  804. // add builtins | no exception handler | must succeed
  805. _Code code = vm->compile(__BUILTINS_CODE, "<builtins>", EXEC_MODE);
  806. vm->_exec(code, vm->builtins, {});
  807. pkpy_vm_add_module(vm, "random", __RANDOM_CODE);
  808. pkpy_vm_add_module(vm, "os", __OS_CODE);
  809. }
  810. __EXPORT
  811. /// Create a virtual machine.
  812. VM* pkpy_new_vm(bool use_stdio){
  813. VM* vm = pkpy_allocate(VM, use_stdio);
  814. __vm_init(vm);
  815. return vm;
  816. }
  817. __EXPORT
  818. /// Create a virtual machine that supports asynchronous execution.
  819. ThreadedVM* pkpy_new_tvm(bool use_stdio){
  820. ThreadedVM* vm = pkpy_allocate(ThreadedVM, use_stdio);
  821. __vm_init(vm);
  822. return vm;
  823. }
  824. __EXPORT
  825. /// Read the standard output and standard error as string of a virtual machine.
  826. /// The `vm->use_stdio` should be `false`.
  827. /// After this operation, both stream will be cleared.
  828. ///
  829. /// Return a json representing the result.
  830. char* pkpy_vm_read_output(VM* vm){
  831. if(vm->use_stdio) return nullptr;
  832. _StrStream* s_out = (_StrStream*)(vm->_stdout);
  833. _StrStream* s_err = (_StrStream*)(vm->_stderr);
  834. _Str _stdout = s_out->str();
  835. _Str _stderr = s_err->str();
  836. _StrStream ss;
  837. ss << '{' << "\"stdout\": " << _stdout.__escape(false);
  838. ss << ", ";
  839. ss << "\"stderr\": " << _stderr.__escape(false) << '}';
  840. s_out->str("");
  841. s_err->str("");
  842. return strdup(ss.str().c_str());
  843. }
  844. __EXPORT
  845. /// Get the current state of a threaded virtual machine.
  846. ///
  847. /// Return `0` for `THREAD_READY`,
  848. /// `1` for `THREAD_RUNNING`,
  849. /// `2` for `THREAD_SUSPENDED`,
  850. /// `3` for `THREAD_FINISHED`.
  851. int pkpy_tvm_get_state(ThreadedVM* vm){
  852. return vm->getState();
  853. }
  854. __EXPORT
  855. /// Set the state of a threaded virtual machine to `THREAD_READY`.
  856. /// The current state should be `THREAD_FINISHED`.
  857. void pkpy_tvm_reset_state(ThreadedVM* vm){
  858. vm->resetState();
  859. }
  860. __EXPORT
  861. /// Read the current JSONRPC request from shared string buffer.
  862. char* pkpy_tvm_read_jsonrpc_request(ThreadedVM* vm){
  863. _Str s = vm->readJsonRpcRequest();
  864. return strdup(s.c_str());
  865. }
  866. __EXPORT
  867. /// Write a JSONRPC response to shared string buffer.
  868. void pkpy_tvm_write_jsonrpc_response(ThreadedVM* vm, const char* value){
  869. vm->writeJsonrpcResponse(value);
  870. }
  871. __EXPORT
  872. /// Emit a KeyboardInterrupt signal to stop a running threaded virtual machine.
  873. void pkpy_tvm_terminate(ThreadedVM* vm){
  874. vm->terminate();
  875. }
  876. __EXPORT
  877. /// Run a given source on a threaded virtual machine.
  878. /// The excution will be started in a new thread.
  879. void pkpy_tvm_exec_async(VM* vm, const char* source){
  880. vm->execAsync(source, "main.py", EXEC_MODE);
  881. }
  882. }