primitives.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  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 a['id'] is None:
  265. yield [("RETURN", [{"value": True}])]
  266. if "value" not in a:
  267. a['value'], = yield [("RV", [a['id']])]
  268. elif a['value'] is None:
  269. yield [("RETURN", [{"value": True}])]
  270. yield [("RETURN", [{'value': isinstance(a['value'], dict) and a['value']["value"] == "none"}])]
  271. def create_node(**remainder):
  272. result, = yield [("CN", [])]
  273. yield [("RETURN", [{'id': result}])]
  274. def create_edge(a, b, **remainder):
  275. if "id" not in a:
  276. #print("MATERIALIZING A create_edge")
  277. a['id'], = yield [("CNV", [a['value']])]
  278. if "id" not in b:
  279. #print("MATERIALIZING B create_edge")
  280. b['id'], = yield [("CNV", [b['value']])]
  281. result, = yield [("CE", [a['id'], b['id']])]
  282. yield [("RETURN", [{'id': result}])]
  283. def create_value(a, **remainder):
  284. if "value" not in a:
  285. a['value'], = yield [("RV", [a['id']])]
  286. yield [("RETURN", [{'value': a['value']}])]
  287. def read_nr_out(a, **remainder):
  288. if "id" not in a:
  289. yield [("RETURN", [{'value': 0}])]
  290. else:
  291. outgoing, = yield [("RO", [a['id']])]
  292. yield [("RETURN", [{'value': len(outgoing)}])]
  293. def read_out(a, b, root, **remainder):
  294. if "id" not in a:
  295. a['id'], = yield [("CNV", [a['value']])]
  296. if "value" not in b:
  297. b['value'], = yield [("RV", [b['id']])]
  298. outgoing, = yield [("RO", [a['id']])]
  299. yield [("RETURN", [{'id': sorted(outgoing)[b['value']] if len(outgoing) > b['value'] else root}])]
  300. def read_nr_in(a, **remainder):
  301. if "id" not in a:
  302. yield [("RETURN", [{'value': 0}])]
  303. else:
  304. incoming, = yield [("RI", [a['id']])]
  305. yield [("RETURN", [{'value': len(incoming)}])]
  306. def read_in(a, b, root, **remainder):
  307. if "id" not in a:
  308. a['id'], = yield [("CNV", [a['value']])]
  309. if "value" not in b:
  310. b['value'], = yield [("RV", [b['id']])]
  311. incoming, = yield [("RI", [a['id']])]
  312. yield [("RETURN", [{'id': sorted(incoming)[b['value']] if len(incoming) > b['value'] else root}])]
  313. def read_edge_src(a, **remainder):
  314. result, = yield [("RE", [a['id']])]
  315. yield [("RETURN", [{'id': result[0]}])]
  316. def read_edge_dst(a, **remainder):
  317. result, = yield [("RE", [a['id']])]
  318. yield [("RETURN", [{'id': result[1]}])]
  319. def delete_element(a, **remainder):
  320. if "id" not in a:
  321. yield [("RETURN", [{'value': False}])]
  322. edge, = yield [("RE", [a['id']])]
  323. if edge[0] is None:
  324. # Not an edge:
  325. yield [("DN", [a['id']])]
  326. yield [("RETURN", [{'value': False}])]
  327. else:
  328. yield [("DE", [a['id']])]
  329. yield [("RETURN", [{'value': True}])]
  330. def read_root(root, **remainder):
  331. yield [("RETURN", [{'id': root}])]
  332. def is_edge(a, **remainder):
  333. if "id" not in a:
  334. yield [("RETURN", [{'value': False}])]
  335. edge, = yield [("RE", [a['id']])]
  336. yield [("RETURN", [{'value': edge[0] is not None}])]
  337. def log(a, **remainder):
  338. if "value" not in a:
  339. a['value'], = yield [("RV", [a['id']])]
  340. print("== LOG == " + str(a['value']))
  341. yield [("RETURN", [a])]
  342. def read_taskroot(task_root, **remainder):
  343. yield [("RETURN", [{'id': task_root}])]
  344. def time(**remainder):
  345. yield [("RETURN", [{'value': python_time.time()}])]
  346. def hash(a, **remainder):
  347. if "value" not in a:
  348. a['value'], = yield [("RV", [a['id']])]
  349. import hashlib
  350. try:
  351. value = hashlib.sha512(a['value']).hexdigest()
  352. except TypeError:
  353. value = hashlib.sha512(a['value'].encode()).hexdigest()
  354. yield [("RETURN", [{'value': value}])]
  355. def __sleep(a, b, **remainder):
  356. if "value" not in a:
  357. a['value'], = yield [("RV", [a['id']])]
  358. if "value" not in b:
  359. b['value'], = yield [("RV", [b['id']])]
  360. timeout = a['value']
  361. interruptable = b['value']
  362. yield [("SLEEP", [timeout, interruptable])]
  363. yield [("RETURN", [a])]
  364. def is_error(a, **remainder):
  365. if a['id'] is None:
  366. yield [("RETURN", [{'value': True}])]
  367. else:
  368. yield [("RETURN", [{'value': False}])]
  369. def list_sort(a, **remainder):
  370. elements, = yield [("RO", [a['id']])]
  371. values = yield [("RD", [a['id'], i]) for i in range(len(elements))]
  372. values = yield [("RV", [i]) for i in values]
  373. new_list, = yield [("CN", [])]
  374. values = yield [("CNV", [v]) for v in sorted(values)]
  375. yield [("CD", [new_list, i, v]) for i, v in enumerate(values)]
  376. yield [("RETURN", [{'id': new_list}])]