primitives.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  1. import time as python_time
  2. import json
  3. import sys
  4. class InterpretedFunctionFinished(Exception):
  5. """Exception to indicate the result value of an interpreted function, as a return
  6. cannot be used."""
  7. def __init__(self, value):
  8. Exception.__init__(self)
  9. self.result = value
  10. class SleepKernel(Exception):
  11. """Exception to indicate the kernel to sleep for some time."""
  12. def __init__(self, timeout, interruptable):
  13. Exception.__init__(self)
  14. self.timeout = timeout
  15. self.interruptable = interruptable
  16. # Functions annotated with __exception_return use the JIT's calling convention instead of
  17. # returnvalue is not modified.
  18. #
  19. # ### Rationale for __exception_return
  20. #
  21. # __exception_return is a useful mechanism because it allows us to have a __call_function
  22. # implementation that has O(1) state read overhead. A previous implementation of
  23. # __call_function checked if the caller's frame had been popped whenever
  24. # ModelverseKernel.execute_yield threw a StopIteration exception. However, that incurs O(n) overhead
  25. # _per call,_ where n is the number of StopIteration exceptions that are thrown during the call.
  26. # O(n) is pretty bad, but this actually becomes O(n * m) when m calls to __call_function are
  27. # nested. And that's just not acceptable.
  28. # __exception_return requires kernel support, but I think the complexity gains are well worth it;
  29. # I reckon JIT-to-interpreter switches aren't going to get a whole lot cheaper than this.
  30. EXCEPTION_RETURN_KEY = "__exception_return"
  31. """A dictionary key for functions which request that the kernel throw a InterpretedFunctionFinished
  32. exception with the return value instead of injecting the return value in the caller's frame."""
  33. def integer_subtraction(a, b, **remainder):
  34. if 'value' not in a:
  35. a['value'], = yield [("RV", [a['id']])]
  36. if 'value' not in b:
  37. b['value'], = yield [("RV", [b['id']])]
  38. yield [("RETURN", [{'value': a['value'] - b['value']}])]
  39. def integer_addition(a, b, **remainder):
  40. if 'value' not in a:
  41. a['value'], = yield [("RV", [a['id']])]
  42. if 'value' not in b:
  43. b['value'], = yield [("RV", [b['id']])]
  44. yield [("RETURN", [{'value': a['value'] + b['value']}])]
  45. def integer_multiplication(a, b, **remainder):
  46. if 'value' not in a:
  47. a['value'], = yield [("RV", [a['id']])]
  48. if 'value' not in b:
  49. b['value'], = yield [("RV", [b['id']])]
  50. yield [("RETURN", [{'value': a['value'] * b['value']}])]
  51. def integer_division(a, b, **remainder):
  52. if 'value' not in a:
  53. a['value'], = yield [("RV", [a['id']])]
  54. if 'value' not in b:
  55. b['value'], = yield [("RV", [b['id']])]
  56. yield [("RETURN", [{'value': int(a['value']) // b['value']}])]
  57. def integer_lt(a, b, **remainder):
  58. if 'value' not in a:
  59. a['value'], = yield [("RV", [a['id']])]
  60. if 'value' not in b:
  61. b['value'], = yield [("RV", [b['id']])]
  62. yield [("RETURN", [{'value': a['value'] < b['value']}])]
  63. def bool_and(a, b, **remainder):
  64. if 'value' not in a:
  65. a['value'], = yield [("RV", [a['id']])]
  66. if 'value' not in b:
  67. b['value'], = yield [("RV", [b['id']])]
  68. yield [("RETURN", [{'value': a['value'] and b['value']}])]
  69. def bool_or(a, b, **remainder):
  70. if 'value' not in a:
  71. a['value'], = yield [("RV", [a['id']])]
  72. if 'value' not in b:
  73. b['value'], = yield [("RV", [b['id']])]
  74. yield [("RETURN", [{'value': a['value'] or b['value']}])]
  75. def bool_not(a, **remainder):
  76. if 'value' not in a:
  77. a['value'], = yield [("RV", [a['id']])]
  78. yield [("RETURN", [{'value': not a['value']}])]
  79. def float_subtraction(a, b, **remainder):
  80. if 'value' not in a:
  81. a['value'], = yield [("RV", [a['id']])]
  82. if 'value' not in b:
  83. b['value'], = yield [("RV", [b['id']])]
  84. yield [("RETURN", [{'value': a['value'] - b['value']}])]
  85. def float_addition(a, b, **remainder):
  86. if 'value' not in a:
  87. a['value'], = yield [("RV", [a['id']])]
  88. if 'value' not in b:
  89. b['value'], = yield [("RV", [b['id']])]
  90. yield [("RETURN", [{'value': a['value'] + b['value']}])]
  91. def float_multiplication(a, b, **remainder):
  92. if 'value' not in a:
  93. a['value'], = yield [("RV", [a['id']])]
  94. if 'value' not in b:
  95. b['value'], = yield [("RV", [b['id']])]
  96. yield [("RETURN", [{'value': a['value'] * b['value']}])]
  97. def float_division(a, b, **remainder):
  98. if 'value' not in a:
  99. a['value'], = yield [("RV", [a['id']])]
  100. if 'value' not in b:
  101. b['value'], = yield [("RV", [b['id']])]
  102. yield [("RETURN", [{'value': float(a['value']) / b['value']}])]
  103. def float_lt(a, b, **remainder):
  104. if 'value' not in a:
  105. a['value'], = yield [("RV", [a['id']])]
  106. if 'value' not in b:
  107. b['value'], = yield [("RV", [b['id']])]
  108. yield [("RETURN", [{'value': a['value'] < b['value']}])]
  109. def string_join(a, b, **remainder):
  110. if 'value' not in a:
  111. a['value'], = yield [("RV", [a['id']])]
  112. if 'value' not in b:
  113. b['value'], = yield [("RV", [b['id']])]
  114. yield [("RETURN", [{'value': str(a['value']) + str(b['value'])}])]
  115. def string_split(a, b, **remainder):
  116. # TODO make non-primitive, though compiled
  117. if 'value' not in a:
  118. a['value'], = yield [("RV", [a['id']])]
  119. if 'value' not in b:
  120. b['value'], = yield [("RV", [b['id']])]
  121. result = a['value'].split(b['value'])
  122. elems = yield [("CN", [])] + [("CNV", [v]) for v in result]
  123. new_val = elems[0]
  124. yield [("CD", [new_val, i, v]) for i, v in enumerate(elems[1:])]
  125. yield [("RETURN", [{'id': new_val}])]
  126. def string_get(a, b, **remainder):
  127. if 'value' not in a:
  128. a['value'], = yield [("RV", [a['id']])]
  129. if 'value' not in b:
  130. b['value'], = yield [("RV", [b['id']])]
  131. yield [("RETURN", [{'value': a['value'][b['value']]}])]
  132. def string_len(a, **remainder):
  133. if 'value' not in a:
  134. a['value'], = yield [("RV", [a['id']])]
  135. yield [("RETURN", [{'value': len(a['value'])}])]
  136. def value_eq(a, b, **remainder):
  137. if 'value' not in a:
  138. a['value'], = yield [("RV", [a['id']])]
  139. if 'value' not in b:
  140. b['value'], = yield [("RV", [b['id']])]
  141. yield [("RETURN", [{'value': a['value'] == b['value']}])]
  142. def element_eq(a, b, **remainder):
  143. if "id" not in a:
  144. #print("MATERIALIZING A element_eq")
  145. a['id'], = yield [("CNV", [a['value']])]
  146. if "id" not in b:
  147. #print("MATERIALIZING B element_eq")
  148. b['id'], = yield [("CNV", [b['value']])]
  149. yield [("RETURN", [{'value': a['id'] == b['id']}])]
  150. def cast_string(a, **remainder):
  151. if 'value' not in a:
  152. a['value'], = yield [("RV", [a['id']])]
  153. if isinstance(a['value'], dict):
  154. yield [("RETURN", [{'value': str(a['value']['value'])}])]
  155. else:
  156. yield [("RETURN", [{'value': str(a['value'])}])]
  157. def cast_float(a, **remainder):
  158. if 'value' not in a:
  159. a['value'], = yield [("RV", [a['id']])]
  160. yield [("RETURN", [{'value': float(a['value'])}])]
  161. def cast_boolean(a, **remainder):
  162. if 'value' not in a:
  163. a['value'], = yield [("RV", [a['id']])]
  164. yield [("RETURN", [{'value': bool(a['value'])}])]
  165. def cast_integer(a, **remainder):
  166. if 'value' not in a:
  167. a['value'], = yield [("RV", [a['id']])]
  168. yield [("RETURN", [{'value': int(a['value'])}])]
  169. def cast_value(a, **remainder):
  170. if 'value' not in a:
  171. a['value'], = yield [("RV", [a['id']])]
  172. if isinstance(a['value'], dict):
  173. yield [("RETURN", [{'value': str(a['value']['value'])}])]
  174. else:
  175. yield [("RETURN", [{'value': json.dumps(a['value'])}])]
  176. def cast_id(a, **remainder):
  177. if "id" not in a:
  178. #print("MATERIALIZING A cast_id")
  179. a['id'], = yield [("CNV", [a['value']])]
  180. yield [("RETURN", [{'value': str(a['id'])}])]
  181. def dict_add_fast(a, b, c, **remainder):
  182. # TODO deprecate, as dict_add is now also efficient
  183. if "value" not in b:
  184. b['value'], = yield [("RV", [b['id']])]
  185. if "id" not in c:
  186. #print("MATERIALIZING C dict_add_fast")
  187. c['id'], = yield [("CNV", [c['value']])]
  188. yield [("CD", [a['id'], b['value'], c['id']])]
  189. yield [("RETURN", [a])]
  190. def dict_delete(a, b, **remainder):
  191. if "value" not in b:
  192. b['value'], = yield [("RV", [b['id']])]
  193. edge, = yield [("RDE", [a['id'], b['value']])]
  194. if edge is None:
  195. print("Failed dict_delete for value '%s'!" % b['value'])
  196. keys, = yield [("RDK", [a['id']])]
  197. keys = yield [("RV", [i]) for i in keys]
  198. print("Keys: " + str(keys))
  199. raise Exception()
  200. yield [("DE", [edge])]
  201. yield [("RETURN", [a])]
  202. def dict_delete_node(a, b, **remainder):
  203. edge, = yield [("RDNE", [a['id'], b['id']])]
  204. if edge is None:
  205. print("Failed dict_delete_node!")
  206. yield [("DE", [edge])]
  207. yield [("RETURN", [a])]
  208. def dict_read(a, b, **remainder):
  209. if "value" not in b:
  210. b['value'], = yield [("RV", [b['id']])]
  211. result, = yield [("RD", [a['id'], b['value']])]
  212. yield [("RETURN", [{'id': result}])]
  213. def dict_read_edge(a, b, **remainder):
  214. if "value" not in b:
  215. b['value'], = yield [("RV", [b['id']])]
  216. result, = yield [("RDE", [a['id'], b['value']])]
  217. yield [("RETURN", [{'id': result}])]
  218. def dict_read_node(a, b, **remainder):
  219. result, = yield [("RDN", [a['id'], b['id']])]
  220. yield [("RETURN", [{'id': result}])]
  221. def dict_in(a, b, **remainder):
  222. if "value" not in b:
  223. b['value'], = yield [("RV", [b['id']])]
  224. value, = yield [("RD", [a['id'], b['value']])]
  225. yield [("RETURN", [{'value': value is not None}])]
  226. def dict_in_node(a, b, **remainder):
  227. if "id" not in b:
  228. # Not even allocated the node, so it is certain not to be in the dictionary
  229. yield [("RETURN", [{'value': False}])]
  230. value, = yield [("RDN", [a['id'], b['id']])]
  231. yield [("RETURN", [{'value': value is not None}])]
  232. def dict_keys(a, **remainder):
  233. keys, result = yield [("RDK", [a['id']]), ("CN", [])]
  234. edges = yield [("CE", [result, result]) for _ in keys]
  235. _ = yield [("CE", [edge, key]) for edge, key in zip(edges, keys)]
  236. yield [("RETURN", [{'id': result}])]
  237. def is_physical_int(a, **remainder):
  238. if "value" not in a:
  239. a['value'], = yield [("RV", [a['id']])]
  240. try:
  241. yield [("RETURN", [{'value': isinstance(a['value'], int) or isinstance(a['value'], long)}])]
  242. except NameError:
  243. yield [("RETURN", [{'value': isinstance(a['value'], int)}])]
  244. def is_physical_string(a, **remainder):
  245. if "value" not in a:
  246. a['value'], = yield [("RV", [a['id']])]
  247. try:
  248. yield [("RETURN", [{'value': isinstance(a['value'], str) or isinstance(a['value'], unicode)}])]
  249. except NameError:
  250. yield [("RETURN", [{'value': isinstance(a['value'], str)}])]
  251. def is_physical_float(a, **remainder):
  252. if "value" not in a:
  253. a['value'], = yield [("RV", [a['id']])]
  254. yield [("RETURN", [{'value': isinstance(a['value'], float)}])]
  255. def is_physical_boolean(a, **remainder):
  256. if "value" not in a:
  257. a['value'], = yield [("RV", [a['id']])]
  258. yield [("RETURN", [{'value': isinstance(a['value'], bool)}])]
  259. def is_physical_action(a, **remainder):
  260. if "value" not in a:
  261. a['value'], = yield [("RV", [a['id']])]
  262. yield [("RETURN", [{'value': isinstance(a['value'], dict) and a['value']["value"] in ["if", "while", "assign", "call", "break", "continue", "return", "resolve", "access", "constant", "global", "declare"]}])]
  263. def is_physical_none(a, **remainder):
  264. if "value" not in a:
  265. a['value'], = yield [("RV", [a['id']])]
  266. yield [("RETURN", [{'value': isinstance(a['value'], dict) and a['value']["value"] == "none"}])]
  267. def create_node(**remainder):
  268. result, = yield [("CN", [])]
  269. yield [("RETURN", [{'id': result}])]
  270. def create_edge(a, b, **remainder):
  271. if "id" not in a:
  272. #print("MATERIALIZING A create_edge")
  273. a['id'], = yield [("CNV", [a['value']])]
  274. if "id" not in b:
  275. #print("MATERIALIZING B create_edge")
  276. b['id'], = yield [("CNV", [b['value']])]
  277. result, = yield [("CE", [a['id'], b['id']])]
  278. yield [("RETURN", [{'id': result}])]
  279. def create_value(a, **remainder):
  280. if "value" not in a:
  281. a['value'], = yield [("RV", [a['id']])]
  282. yield [("RETURN", [{'value': a['value']}])]
  283. def read_nr_out(a, **remainder):
  284. if "id" not in a:
  285. yield [("RETURN", [{'value': 0}])]
  286. else:
  287. outgoing, = yield [("RO", [a['id']])]
  288. yield [("RETURN", [{'value': len(outgoing)}])]
  289. def read_out(a, b, root, **remainder):
  290. if "id" not in a:
  291. a['id'], = yield [("CNV", [a['value']])]
  292. if "value" not in b:
  293. b['value'], = yield [("RV", [b['id']])]
  294. outgoing, = yield [("RO", [a['id']])]
  295. yield [("RETURN", [{'id': sorted(outgoing)[b['value']] if len(outgoing) > b['value'] else root}])]
  296. def read_nr_in(a, **remainder):
  297. if "id" not in a:
  298. yield [("RETURN", [{'value': 0}])]
  299. else:
  300. incoming, = yield [("RI", [a['id']])]
  301. yield [("RETURN", [{'value': len(incoming)}])]
  302. def read_in(a, b, root, **remainder):
  303. if "id" not in a:
  304. a['id'], = yield [("CNV", [a['value']])]
  305. if "value" not in b:
  306. b['value'], = yield [("RV", [b['id']])]
  307. incoming, = yield [("RI", [a['id']])]
  308. yield [("RETURN", [{'id': sorted(incoming)[b['value']] if len(incoming) > b['value'] else root}])]
  309. def read_edge_src(a, **remainder):
  310. result, = yield [("RE", [a['id']])]
  311. yield [("RETURN", [{'id': result[0]}])]
  312. def read_edge_dst(a, **remainder):
  313. result, = yield [("RE", [a['id']])]
  314. yield [("RETURN", [{'id': result[1]}])]
  315. def delete_element(a, **remainder):
  316. if "id" not in a:
  317. yield [("RETURN", [{'value': False}])]
  318. edge, = yield [("RE", [a['id']])]
  319. if edge[0] is None:
  320. # Not an edge:
  321. yield [("DN", [a['id']])]
  322. yield [("RETURN", [{'value': False}])]
  323. else:
  324. yield [("DE", [a['id']])]
  325. yield [("RETURN", [{'value': True}])]
  326. def read_root(root, **remainder):
  327. yield [("RETURN", [{'id': root}])]
  328. def is_edge(a, **remainder):
  329. if "id" not in a:
  330. yield [("RETURN", [{'value': False}])]
  331. edge, = yield [("RE", [a['id']])]
  332. yield [("RETURN", [{'value': edge[0] is not None}])]
  333. def log(a, **remainder):
  334. if "value" not in a:
  335. a['value'], = yield [("RV", [a['id']])]
  336. print("== LOG == " + str(a['value']))
  337. yield [("RETURN", [a])]
  338. def read_taskroot(task_root, **remainder):
  339. yield [("RETURN", [{'id': task_root}])]
  340. def time(**remainder):
  341. yield [("RETURN", [{'value': python_time.time()}])]
  342. def hash(a, **remainder):
  343. if "value" not in a:
  344. a['value'], = yield [("RV", [a['id']])]
  345. import hashlib
  346. try:
  347. value = hashlib.sha512(a['value']).hexdigest()
  348. except TypeError:
  349. value = hashlib.sha512(a['value'].encode()).hexdigest()
  350. yield [("RETURN", [{'value': value}])]
  351. def __sleep(a, b, **remainder):
  352. if "value" not in a:
  353. a['value'], = yield [("RV", [a['id']])]
  354. if "value" not in b:
  355. b['value'], = yield [("RV", [b['id']])]
  356. timeout = a['value']
  357. interruptable = b['value']
  358. yield [("SLEEP", [timeout, interruptable])]
  359. yield [("RETURN", [a])]
  360. def is_error(a, **remainder):
  361. if a['id'] is None:
  362. yield [("RETURN", [{'value': True}])]
  363. else:
  364. yield [("RETURN", [{'value': False}])]
  365. def list_sort(a, **remainder):
  366. elements, = yield [("RO", [a['id']])]
  367. values = yield [("RD", [a['id'], i]) for i in range(elements)]
  368. values = yield [("RV", [i]) for i in values]
  369. new_list, = yield [("CN", [])]
  370. values = yield [("CNV", [v]) for v in sorted(values))
  371. yield [("CD", [new_list, i, v]) for i, v in enumerate(values)]
  372. yield [("RETURN", [{'id': new_list}])]