primitives.py 15 KB

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