tree_ir.py 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483
  1. # NOTE: NOP_LITERAL abuses a mechanic of the modelverse kernel. Specifically,
  2. # whenever the `ModelverseKernel.execute_yields` method returns `None`, then
  3. # the server built around it takes that as a hint that an instruction's phase
  4. # has been completed. The server interrupts the kernel's thread of execution
  5. # when it remarks that an instruction has completed a phase (i.e., when `None`
  6. # is returned by `ModelverseKernel.execute_yields`) and proceeds to check for
  7. # input and output.
  8. #
  9. # In assembly language, a nop is usually used as a point at which a thread of
  10. # execution can be terminated. It follows from the paragraph above that what
  11. # the interpreter does is more or less equivalent to placing nops after every
  12. # instruction. It is worthwhile to remark that JIT-compiled code cannot rely
  13. # on the kernel to interrupt the thread of execution automatically during a
  14. # jitted function's execution -- jitted functions are considered equivalent
  15. # to a single instruction as far as the kernel is concerned. A nop will be
  16. # inserted _after_ the function call (if it is called from interpreted code)
  17. # but that does not suffice for IO, which needs the input/output processing
  18. # to be performed during function execution.
  19. #
  20. # For this reason, the JIT must strategically interrupt the execution of the
  21. # functions it compiles. In other words, it must insert its own nops.
  22. # Here comes the interesting part: a nop is equivalent to `yield None`,
  23. # because that will persuade `ModelverseKernel.execute_yields` to relay the
  24. # `None` marker value to the server, without terminating the current
  25. # generator.
  26. # Let's just agree to disagree on map vs list comprehensions, pylint.
  27. # pylint: disable=I0011,W0141
  28. NOP_LITERAL = None
  29. """A literal that results in a nop during which execution may be interrupted
  30. when yielded."""
  31. UNKNOWN_RESULT_TYPE = 'unknown'
  32. """The result type for instructions that produce either primitive values or
  33. references to nodes."""
  34. PRIMITIVE_RESULT_TYPE = 'primitive'
  35. """The result type for instructions that produce primitive values."""
  36. NODE_RESULT_TYPE = 'node'
  37. """The result type for instructions that produce references to nodes."""
  38. NO_RESULT_TYPE = 'nothing'
  39. """The result type for instructions that no result."""
  40. def result_type_intersection(first_type, second_type):
  41. """Computes the intersection of the given result types."""
  42. if first_type == second_type:
  43. return first_type
  44. elif ((first_type == PRIMITIVE_RESULT_TYPE and second_type == UNKNOWN_RESULT_TYPE)
  45. or (first_type == UNKNOWN_RESULT_TYPE and second_type == PRIMITIVE_RESULT_TYPE)):
  46. return PRIMITIVE_RESULT_TYPE
  47. elif ((first_type == NODE_RESULT_TYPE and second_type == UNKNOWN_RESULT_TYPE)
  48. or (first_type == UNKNOWN_RESULT_TYPE and second_type == NODE_RESULT_TYPE)):
  49. return NODE_RESULT_TYPE
  50. else:
  51. return NO_RESULT_TYPE
  52. def result_type_union(first_type, second_type):
  53. """Computes the union of the given result types."""
  54. if first_type == second_type:
  55. return first_type
  56. elif ((first_type == PRIMITIVE_RESULT_TYPE and second_type == NO_RESULT_TYPE)
  57. or (first_type == NO_RESULT_TYPE and second_type == PRIMITIVE_RESULT_TYPE)):
  58. return PRIMITIVE_RESULT_TYPE
  59. elif ((first_type == NODE_RESULT_TYPE and second_type == NO_RESULT_TYPE)
  60. or (first_type == NO_RESULT_TYPE and second_type == NODE_RESULT_TYPE)):
  61. return NODE_RESULT_TYPE
  62. else:
  63. return UNKNOWN_RESULT_TYPE
  64. class Instruction(object):
  65. """A base class for instructions. An instruction is essentially a syntax
  66. node that must first be defined, and can only then be used."""
  67. def __init__(self):
  68. self.result_type_cache = None
  69. self.has_definition_cache = None
  70. def get_result_type(self):
  71. """Gets this instruction's result type."""
  72. if self.result_type_cache is None:
  73. self.result_type_cache = self.get_result_type_impl()
  74. return self.result_type_cache
  75. def has_result(self):
  76. """Tells if this instruction computes a result."""
  77. return self.get_result_type() != NO_RESULT_TYPE
  78. def has_definition(self):
  79. """Tells if this instruction requires a definition."""
  80. if self.has_definition_cache is None:
  81. self.has_definition_cache = self.has_definition_impl()
  82. return self.has_definition_cache
  83. def get_result_type_impl(self):
  84. """Gets this instruction's result type."""
  85. return PRIMITIVE_RESULT_TYPE
  86. def has_definition_impl(self):
  87. """Tells if this instruction requires a definition."""
  88. return True
  89. def get_result_name_override(self, code_generator):
  90. """Gets a value that overrides the code generator's result name for this
  91. instruction if it is not None."""
  92. return None
  93. def generate_python_def(self, code_generator):
  94. """Generates a Python statement that executes this instruction.
  95. The statement is appended immediately to the code generator."""
  96. if self.has_definition():
  97. raise NotImplementedError()
  98. else:
  99. code_generator.append_line('pass')
  100. def generate_python_use(self, code_generator):
  101. """Generates a Python expression that retrieves this instruction's
  102. result. The expression is returned as a string."""
  103. if self.has_result():
  104. return code_generator.get_result_name(self)
  105. else:
  106. return 'None'
  107. def get_children(self):
  108. """Gets this instruction's sequence of child instructions."""
  109. raise NotImplementedError()
  110. def create(self, new_children):
  111. """Creates a new instruction of this type from the given sequence of child instructions."""
  112. raise NotImplementedError()
  113. def simplify_node(self):
  114. """Applies basic simplification to this instruction only."""
  115. return self
  116. def simplify(self):
  117. """Applies basic simplification to this instruction and all of its children."""
  118. # This fairly convoluted one-liner first simplifies all children, then creates
  119. # an instruction from the simplified children, and finally simplifies that top-level
  120. # instruction.
  121. return self.create([c.simplify() for c in self.get_children()]).simplify_node()
  122. def __str__(self):
  123. code_generator = PythonGenerator()
  124. self.generate_python_def(code_generator)
  125. return str(code_generator)
  126. class PythonGenerator(object):
  127. """Generates Python code from instructions."""
  128. def __init__(self, combine_state_definitions=True):
  129. self.code = []
  130. self.state_definitions = []
  131. self.state_definition_names = set()
  132. self.indentation_string = ' ' * 4
  133. self.indentation = 0
  134. self.result_name_dict = {}
  135. self.combine_state_definitions = combine_state_definitions
  136. def append(self, text):
  137. """Appends the given string to this code generator."""
  138. self.flush_state_definitions()
  139. self.code.append(text)
  140. def append_indentation(self):
  141. """Appends indentation to the code generator."""
  142. self.append(self.indentation_string * self.indentation)
  143. def append_line(self, line=None):
  144. """Appends the indentation string followed by the given string (if any)
  145. and a newline to the code generator."""
  146. self.append_indentation()
  147. if line is not None:
  148. self.append(line)
  149. self.append('\n')
  150. def increase_indentation(self):
  151. """Increases the code generator's indentation by one indent."""
  152. self.flush_state_definitions()
  153. self.indentation += 1
  154. def decrease_indentation(self):
  155. """Decreases the code generator's indentation by one indent."""
  156. self.flush_state_definitions()
  157. self.indentation -= 1
  158. def get_result_name(self, instruction, advised_name=None):
  159. """Gets the name of the given instruction's result variable."""
  160. if instruction not in self.result_name_dict:
  161. override_name = instruction.get_result_name_override(self)
  162. if override_name is not None:
  163. self.result_name_dict[instruction] = override_name
  164. elif advised_name is not None:
  165. self.result_name_dict[instruction] = advised_name
  166. else:
  167. self.result_name_dict[instruction] = \
  168. 'tmp' + str(len(self.result_name_dict))
  169. result = self.result_name_dict[instruction]
  170. if result in self.state_definition_names:
  171. # This might mean that we're trying to access a name that is
  172. # defined by the current block of state definitions. So we need
  173. # to flush the state definitions now.
  174. self.flush_state_definitions()
  175. return result
  176. def append_definition(self, lhs, rhs):
  177. """Defines the first instruction's result variable as the second
  178. instruction's result."""
  179. self.append_line(
  180. self.get_result_name(lhs) + ' = ' + rhs.generate_python_use(self))
  181. def append_move_definition(self, lhs, rhs):
  182. """First defines the second instruction, then defines the first
  183. instruction as the result of the second."""
  184. if rhs.has_definition():
  185. # Retrieve the result name for the lhs.
  186. lhs_result_name = self.get_result_name(lhs)
  187. # Encourage the rhs to take on the same result name as the lhs.
  188. rhs_result_name = self.get_result_name(rhs, lhs_result_name)
  189. # Generate the rhs' definition.
  190. rhs.generate_python_def(self)
  191. # Only perform an assignment if it's truly necessary.
  192. if lhs_result_name != rhs_result_name:
  193. self.append_definition(lhs, rhs)
  194. else:
  195. self.append_definition(lhs, rhs)
  196. def append_state_definition(self, lhs, opcode, args):
  197. """Appends a definition that queries the modelverse state."""
  198. result_name = self.get_result_name(lhs)
  199. request_tuple = '(%s, [%s])' % (
  200. repr(opcode),
  201. ', '.join([arg_i.generate_python_use(self) for arg_i in args]))
  202. self.state_definitions.append((result_name, request_tuple))
  203. self.state_definition_names.add(result_name)
  204. if not self.combine_state_definitions:
  205. self.flush_state_definitions()
  206. def flush_state_definitions(self):
  207. """Flushes the list of state-access definitions to the generated code."""
  208. state_defs = self.state_definitions
  209. if len(state_defs) > 0:
  210. # Clear state_definitions _before_ calling append_line, because append_line
  211. # will call flush_state_definitions. Clearing state_definitions afterward
  212. # will result in infinite recursion.
  213. self.state_definitions = []
  214. self.state_definition_names = set()
  215. if len(state_defs) == 1:
  216. self.append_line('%s, = yield [%s]' % state_defs[0])
  217. else:
  218. self.append_line(
  219. "%s = yield [%s]" % (
  220. ', '.join([name for name, _ in state_defs]),
  221. ', '.join([def_val for _, def_val in state_defs])))
  222. def __str__(self):
  223. self.flush_state_definitions()
  224. return ''.join(self.code)
  225. class VoidInstruction(Instruction):
  226. """A base class for instructions that do not return a value."""
  227. def get_result_type_impl(self):
  228. """Gets this instruction's result type."""
  229. return NO_RESULT_TYPE
  230. def get_children(self):
  231. """Gets this instruction's sequence of child instructions."""
  232. return []
  233. def create(self, new_children):
  234. """Creates a new instruction of this type from the given sequence of child instructions."""
  235. return self
  236. class EmptyInstruction(VoidInstruction):
  237. """Represents the empty instruction, which does nothing."""
  238. def has_definition_impl(self):
  239. """Tells if this instruction requires a definition."""
  240. return False
  241. class SelectInstruction(Instruction):
  242. """Represents a select-instruction: an instruction that defines one of two
  243. child instructions, and sets its result to the defined child's result."""
  244. def __init__(self, condition, if_clause, else_clause):
  245. Instruction.__init__(self)
  246. self.condition = condition
  247. self.if_clause = if_clause
  248. self.else_clause = else_clause
  249. def get_result_type_impl(self):
  250. """Gets this instruction's result type."""
  251. return result_type_intersection(
  252. self.if_clause.get_result_type(),
  253. self.else_clause.get_result_type())
  254. def simplify_node(self):
  255. """Applies basic simplification to this instruction only."""
  256. if isinstance(self.condition, LiteralInstruction):
  257. return self.if_clause if self.condition.literal else self.else_clause
  258. else:
  259. return SelectInstruction(self.condition, self.if_clause, self.else_clause)
  260. def get_children(self):
  261. """Gets this instruction's sequence of child instructions."""
  262. return [self.condition, self.if_clause, self.else_clause]
  263. def create(self, new_children):
  264. """Creates a new instruction of this type from the given sequence of child instructions."""
  265. condition, if_clause, else_clause = new_children
  266. return SelectInstruction(condition, if_clause, else_clause)
  267. def generate_python_def(self, code_generator):
  268. """Generates Python code for this instruction."""
  269. if_has_result = self.has_result()
  270. if self.condition.has_definition():
  271. self.condition.generate_python_def(code_generator)
  272. code_generator.append_line(
  273. 'if ' + self.condition.generate_python_use(code_generator) + ':')
  274. code_generator.increase_indentation()
  275. if if_has_result:
  276. code_generator.append_move_definition(self, self.if_clause)
  277. else:
  278. self.if_clause.generate_python_def(code_generator)
  279. code_generator.decrease_indentation()
  280. else_has_def = self.else_clause.has_definition()
  281. if else_has_def or if_has_result:
  282. code_generator.append_line('else:')
  283. code_generator.increase_indentation()
  284. if if_has_result:
  285. code_generator.append_move_definition(self, self.else_clause)
  286. else:
  287. self.else_clause.generate_python_def(code_generator)
  288. code_generator.decrease_indentation()
  289. class ReturnInstruction(VoidInstruction):
  290. """Represents a return-instruction."""
  291. def __init__(self, value):
  292. VoidInstruction.__init__(self)
  293. self.value = value
  294. def get_children(self):
  295. """Gets this instruction's sequence of child instructions."""
  296. return [self.value]
  297. def create(self, new_children):
  298. """Creates a new instruction of this type from the given sequence of child instructions."""
  299. value, = new_children
  300. return ReturnInstruction(value)
  301. def simplify_node(self):
  302. """Applies basic simplification to this instruction only."""
  303. # If we have a return whose value is a call, then we can rewrite
  304. # that as a tail call and save us a stack frame.
  305. def rewrite_call(instruction):
  306. """Rewrites the given instruction in tail-call form, or returns
  307. None."""
  308. if isinstance(instruction, RunGeneratorFunctionInstruction):
  309. return RunTailGeneratorFunctionInstruction(*instruction.get_children())
  310. elif isinstance(instruction, CompoundInstruction):
  311. snd_rewritten = rewrite_call(instruction.second)
  312. if snd_rewritten is not None:
  313. return CompoundInstruction(instruction.first, snd_rewritten)
  314. return None
  315. rewritten_value = rewrite_call(self.value)
  316. if rewritten_value is None:
  317. return self
  318. else:
  319. # We don't even need to create a return here, because tail calls terminate
  320. # the current stack frame anyway.
  321. return rewritten_value
  322. def generate_python_def(self, code_generator):
  323. """Generates Python code for this instruction."""
  324. if self.value.has_definition():
  325. self.value.generate_python_def(code_generator)
  326. code_generator.append_line(
  327. 'raise PrimitiveFinished(' +
  328. self.value.generate_python_use(code_generator) +
  329. ')')
  330. class RaiseInstruction(VoidInstruction):
  331. """An instruction that raises an error."""
  332. def __init__(self, value):
  333. VoidInstruction.__init__(self)
  334. self.value = value
  335. def get_children(self):
  336. """Gets this instruction's sequence of child instructions."""
  337. return [self.value]
  338. def create(self, new_children):
  339. """Creates a new instruction of this type from the given sequence of child instructions."""
  340. value, = new_children
  341. return RaiseInstruction(value)
  342. def generate_python_def(self, code_generator):
  343. """Generates Python code for this instruction."""
  344. self.value.generate_python_def(code_generator)
  345. code_generator.append_line(
  346. 'raise ' + self.value.generate_python_use(code_generator))
  347. class CallInstruction(Instruction):
  348. """An instruction that performs a simple call."""
  349. def __init__(self, target, argument_list):
  350. Instruction.__init__(self)
  351. self.target = target
  352. self.argument_list = argument_list
  353. def get_children(self):
  354. """Gets this instruction's sequence of child instructions."""
  355. return [self.target] + self.argument_list
  356. def create(self, new_children):
  357. """Creates a new instruction of this type from the given sequence of child instructions."""
  358. return CallInstruction(new_children[0], new_children[1:])
  359. def generate_python_def(self, code_generator):
  360. """Generates Python code for this instruction."""
  361. if self.target.has_definition():
  362. self.target.generate_python_def(code_generator)
  363. for arg in self.argument_list:
  364. if arg.has_definition():
  365. arg.generate_python_def(code_generator)
  366. code_generator.append_line(
  367. '%s = %s(%s)' % (
  368. code_generator.get_result_name(self),
  369. self.target.generate_python_use(code_generator),
  370. ', '.join([arg.generate_python_use(code_generator) for arg in self.argument_list])))
  371. class PrintInstruction(VoidInstruction):
  372. """An instruction that prints a value."""
  373. def __init__(self, argument):
  374. VoidInstruction.__init__(self)
  375. self.argument = argument
  376. def get_children(self):
  377. """Gets this instruction's sequence of child instructions."""
  378. return [self.argument]
  379. def create(self, new_children):
  380. """Creates a new instruction of this type from the given sequence of child instructions."""
  381. arg, = new_children
  382. return PrintInstruction(arg)
  383. def generate_python_def(self, code_generator):
  384. """Generates Python code for this instruction."""
  385. if self.argument.has_definition():
  386. self.argument.generate_python_def(code_generator)
  387. code_generator.append_line(
  388. 'print(%s)' % (
  389. self.argument.generate_python_use(code_generator)))
  390. class BinaryInstruction(Instruction):
  391. """An instruction that performs a binary operation."""
  392. def __init__(self, lhs, operator, rhs):
  393. Instruction.__init__(self)
  394. self.lhs = lhs
  395. self.operator = operator
  396. self.rhs = rhs
  397. def has_definition_impl(self):
  398. """Tells if this instruction requires a definition."""
  399. return self.lhs.has_definition() or self.rhs.has_definition()
  400. def get_children(self):
  401. """Gets this instruction's sequence of child instructions."""
  402. return [self.lhs, self.rhs]
  403. def create(self, new_children):
  404. """Creates a new instruction of this type from the given sequence of child instructions."""
  405. lhs, rhs, = new_children
  406. return BinaryInstruction(lhs, self.operator, rhs)
  407. def simplify_node(self):
  408. """Applies basic simplification to this instruction only."""
  409. if isinstance(self.lhs, LiteralInstruction) and isinstance(self.rhs, LiteralInstruction):
  410. # TODO: there's probably a better way to do this than with eval.
  411. return LiteralInstruction(
  412. eval('%s %s %s' % (repr(self.lhs.literal), self.operator, repr(self.rhs.literal))))
  413. else:
  414. return self
  415. def generate_python_use(self, code_generator):
  416. """Generates a Python expression that retrieves this instruction's
  417. result. The expression is returned as a string."""
  418. return '(%s %s %s)' % (
  419. self.lhs.generate_python_use(code_generator),
  420. self.operator,
  421. self.rhs.generate_python_use(code_generator))
  422. def generate_python_def(self, code_generator):
  423. """Generates a Python statement that executes this instruction.
  424. The statement is appended immediately to the code generator."""
  425. if self.lhs.has_definition():
  426. self.lhs.generate_python_def(code_generator)
  427. if self.rhs.has_definition():
  428. self.rhs.generate_python_def(code_generator)
  429. elif self.rhs.has_definition():
  430. self.rhs.generate_python_def(code_generator)
  431. else:
  432. code_generator.append_line('pass')
  433. class UnaryInstruction(Instruction):
  434. """An instruction that performs a unary operation."""
  435. def __init__(self, operator, operand):
  436. Instruction.__init__(self)
  437. self.operator = operator
  438. self.operand = operand
  439. def has_definition_impl(self):
  440. """Tells if this instruction requires a definition."""
  441. return self.operand.has_definition()
  442. def get_children(self):
  443. """Gets this instruction's sequence of child instructions."""
  444. return [self.operand]
  445. def create(self, new_children):
  446. """Creates a new instruction of this type from the given sequence of child instructions."""
  447. operand, = new_children
  448. return UnaryInstruction(self.operator, operand)
  449. def simplify_node(self):
  450. """Applies basic simplification to this instruction only."""
  451. if isinstance(self.operand, LiteralInstruction):
  452. # TODO: there's probably a better way to do this than with eval.
  453. return LiteralInstruction(
  454. eval('%s %s' % (self.operator, repr(self.operand.literal))))
  455. else:
  456. return self
  457. def generate_python_use(self, code_generator):
  458. """Generates a Python expression that retrieves this instruction's
  459. result. The expression is returned as a string."""
  460. return '(%s %s)' % (
  461. self.operator,
  462. self.operand.generate_python_use(code_generator))
  463. def generate_python_def(self, code_generator):
  464. """Generates a Python statement that executes this instruction.
  465. The statement is appended immediately to the code generator."""
  466. if self.operand.has_definition():
  467. self.operand.generate_python_def(code_generator)
  468. else:
  469. code_generator.append_line('pass')
  470. class LoopInstruction(VoidInstruction):
  471. """Represents a loop-instruction, which loops until broken."""
  472. def __init__(self, body):
  473. VoidInstruction.__init__(self)
  474. self.body = body
  475. def get_children(self):
  476. """Gets this instruction's sequence of child instructions."""
  477. return [self.body]
  478. def create(self, new_children):
  479. """Creates a new instruction of this type from the given sequence of child instructions."""
  480. body, = new_children
  481. return LoopInstruction(body)
  482. def generate_python_def(self, code_generator):
  483. """Generates Python code for this instruction."""
  484. code_generator.append_line('while 1:')
  485. code_generator.increase_indentation()
  486. self.body.generate_python_def(code_generator)
  487. code_generator.decrease_indentation()
  488. class BreakInstruction(VoidInstruction):
  489. """Represents a break-instruction."""
  490. def generate_python_def(self, code_generator):
  491. """Generates Python code for this instruction."""
  492. code_generator.append_line('break')
  493. class ContinueInstruction(VoidInstruction):
  494. """Represents a continue-instruction."""
  495. def generate_python_def(self, code_generator):
  496. """Generates Python code for this instruction."""
  497. code_generator.append_line('continue')
  498. class CompoundInstruction(Instruction):
  499. """Represents an instruction that evaluates two other instructions
  500. in order, and returns the second instruction's result."""
  501. def __init__(self, first, second):
  502. Instruction.__init__(self)
  503. self.first = first
  504. self.second = second
  505. def get_result_type_impl(self):
  506. """Gets this instruction's result type."""
  507. if self.second.has_result():
  508. return self.second.get_result_type()
  509. else:
  510. return self.first.get_result_type()
  511. def get_children(self):
  512. """Gets this instruction's sequence of child instructions."""
  513. return [self.first, self.second]
  514. def create(self, new_children):
  515. """Creates a new instruction of this type from the given sequence of child instructions."""
  516. first, second = new_children
  517. return CompoundInstruction(first, second)
  518. def simplify_node(self):
  519. """Applies basic simplification to this instruction and its children."""
  520. if not self.first.has_definition() and (
  521. not self.first.has_result() or self.second.has_result()):
  522. return self.second
  523. elif (not self.second.has_definition()) and (not self.second.has_result()):
  524. return self.first
  525. else:
  526. return self
  527. def generate_python_def(self, code_generator):
  528. """Generates Python code for this instruction."""
  529. if self.second.has_result():
  530. self.first.generate_python_def(code_generator)
  531. code_generator.append_move_definition(self, self.second)
  532. elif self.first.has_result():
  533. code_generator.append_move_definition(self, self.first)
  534. self.second.generate_python_def(code_generator)
  535. else:
  536. self.first.generate_python_def(code_generator)
  537. self.second.generate_python_def(code_generator)
  538. class LiteralInstruction(Instruction):
  539. """Represents an integer, floating-point, string or Boolean literal."""
  540. def __init__(self, literal):
  541. Instruction.__init__(self)
  542. self.literal = literal
  543. def has_definition_impl(self):
  544. """Tells if this instruction requires a definition."""
  545. return False
  546. def get_children(self):
  547. """Gets this instruction's sequence of child instructions."""
  548. return []
  549. def create(self, new_children):
  550. """Creates a new instruction of this type from the given sequence of child instructions."""
  551. return self
  552. def generate_python_use(self, code_generator):
  553. """Generates a Python expression that retrieves this instruction's
  554. result. The expression is returned as a string."""
  555. return repr(self.literal)
  556. class DictionaryLiteralInstruction(Instruction):
  557. """Constructs a dictionary literal."""
  558. def __init__(self, key_value_pairs):
  559. Instruction.__init__(self)
  560. self.key_value_pairs = key_value_pairs
  561. def get_children(self):
  562. """Gets this instruction's sequence of child instructions."""
  563. return [val for _, val in self.key_value_pairs]
  564. def create(self, new_children):
  565. """Creates a new instruction of this type from the given sequence of child instructions."""
  566. keys = [k for k, _ in self.key_value_pairs]
  567. return DictionaryLiteralInstruction(zip(keys, new_children))
  568. def has_definition_impl(self):
  569. """Tells if this instruction requires a definition."""
  570. return any(
  571. [key.has_definition() or val.has_definition()
  572. for key, val in self.key_value_pairs])
  573. def simplify(self):
  574. """Applies basic simplification to this instruction and its children."""
  575. return DictionaryLiteralInstruction(
  576. [(key.simplify(), val.simplify()) for key, val in self.key_value_pairs])
  577. def generate_dictionary_expr(self, code_generator):
  578. """Generates an expression that creates this dictionary."""
  579. return '{%s}' % ', '.join(
  580. ['%s : %s' % (
  581. key.generate_python_use(code_generator),
  582. val.generate_python_use(code_generator))
  583. for key, val in self.key_value_pairs])
  584. def generate_python_def(self, code_generator):
  585. """Generates a Python statement that executes this instruction.
  586. The statement is appended immediately to the code generator."""
  587. if self.has_definition():
  588. for key, val in self.key_value_pairs:
  589. if key.has_definition():
  590. key.generate_python_def(code_generator)
  591. if val.has_definition():
  592. val.generate_python_def(code_generator)
  593. code_generator.append_line('%s = %s' % (
  594. code_generator.get_result_name(self),
  595. self.generate_dictionary_expr(code_generator)))
  596. else:
  597. code_generator.append_line('pass')
  598. def generate_python_use(self, code_generator):
  599. """Generates a Python expression that retrieves this instruction's
  600. result. The expression is returned as a string."""
  601. if self.has_definition():
  602. return code_generator.get_result_name(self)
  603. else:
  604. return self.generate_dictionary_expr(code_generator)
  605. class StateInstruction(Instruction):
  606. """An instruction that accesses the modelverse state."""
  607. def get_result_type_impl(self):
  608. """Gets the type of value produced by this instruction."""
  609. return NODE_RESULT_TYPE
  610. def get_opcode(self):
  611. """Gets the opcode for this state instruction."""
  612. raise NotImplementedError()
  613. def get_arguments(self):
  614. """Gets this state instruction's argument list."""
  615. raise NotImplementedError()
  616. def get_children(self):
  617. """Gets this instruction's sequence of child instructions."""
  618. return self.get_arguments()
  619. def create(self, new_children):
  620. """Creates a new instruction of this type from the given sequence of child instructions."""
  621. return type(self)(*new_children)
  622. def generate_python_def(self, code_generator):
  623. """Generates a Python statement that executes this instruction.
  624. The statement is appended immediately to the code generator."""
  625. args = self.get_arguments()
  626. for arg_i in args:
  627. if arg_i.has_definition():
  628. arg_i.generate_python_def(code_generator)
  629. code_generator.append_state_definition(self, self.get_opcode(), args)
  630. class RunGeneratorFunctionInstruction(StateInstruction):
  631. """An instruction that runs a generator function."""
  632. def __init__(self, function, argument_dict, result_type=PRIMITIVE_RESULT_TYPE):
  633. StateInstruction.__init__(self)
  634. self.function = function
  635. self.argument_dict = argument_dict
  636. self.result_type_cache = result_type
  637. def get_opcode(self):
  638. """Gets the opcode for this state instruction."""
  639. return "CALL_KWARGS"
  640. def get_arguments(self):
  641. """Gets this state instruction's argument list."""
  642. return [self.function, self.argument_dict]
  643. def create(self, new_children):
  644. """Creates a new instruction of this type from the given sequence of child instructions."""
  645. func, arg_dict = new_children
  646. return RunGeneratorFunctionInstruction(func, arg_dict, self.get_result_type())
  647. class RunTailGeneratorFunctionInstruction(StateInstruction):
  648. """An instruction that runs a generator function."""
  649. def __init__(self, function, argument_dict):
  650. StateInstruction.__init__(self)
  651. self.function = function
  652. self.argument_dict = argument_dict
  653. def get_result_type_impl(self):
  654. """Gets the type of value produced by this instruction."""
  655. return NO_RESULT_TYPE
  656. def get_opcode(self):
  657. """Gets the opcode for this state instruction."""
  658. return "TAIL_CALL_KWARGS"
  659. def get_arguments(self):
  660. """Gets this state instruction's argument list."""
  661. return [self.function, self.argument_dict]
  662. class VariableName(object):
  663. """A data structure that unifies names across instructions that access the
  664. same variable."""
  665. def __init__(self, name):
  666. self.name = name
  667. def get_result_name_override(self, _):
  668. """Gets a value that overrides the code generator's result name for this
  669. instruction if it is not None."""
  670. return self.name
  671. class VariableInstruction(Instruction):
  672. """A base class for instructions that access variables."""
  673. def __init__(self, name):
  674. Instruction.__init__(self)
  675. if isinstance(name, str) or isinstance(name, unicode) or name is None:
  676. self.name = VariableName(name)
  677. else:
  678. self.name = name
  679. def get_children(self):
  680. """Gets this instruction's sequence of child instructions."""
  681. raise NotImplementedError()
  682. def create(self, new_children):
  683. """Creates a new instruction of this type from the given sequence of child instructions."""
  684. raise NotImplementedError()
  685. def get_result_name_override(self, code_generator):
  686. """Gets a value that overrides the code generator's result name for this
  687. instruction if it is not None."""
  688. return code_generator.get_result_name(self.name)
  689. class LocalInstruction(VariableInstruction):
  690. """A base class for instructions that access local variables."""
  691. def get_children(self):
  692. """Gets this instruction's sequence of child instructions."""
  693. raise NotImplementedError()
  694. def create(self, new_children):
  695. """Creates a new instruction of this type from the given sequence of child instructions."""
  696. raise NotImplementedError()
  697. def create_load(self):
  698. """Creates an instruction that loads the variable referenced by this instruction."""
  699. return LoadLocalInstruction(self.name)
  700. def create_store(self, value):
  701. """Creates an instruction that stores the given value in the variable referenced
  702. by this instruction."""
  703. return StoreLocalInstruction(self.name, value)
  704. class StoreLocalInstruction(LocalInstruction):
  705. """An instruction that stores a value in a local variable."""
  706. def __init__(self, name, value):
  707. LocalInstruction.__init__(self, name)
  708. self.value = value
  709. def get_children(self):
  710. """Gets this instruction's sequence of child instructions."""
  711. return [self.value]
  712. def create(self, new_children):
  713. """Creates a new instruction of this type from the given sequence of child instructions."""
  714. val, = new_children
  715. return StoreLocalInstruction(self.name, val)
  716. def generate_python_def(self, code_generator):
  717. """Generates a Python statement that executes this instruction.
  718. The statement is appended immediately to the code generator."""
  719. code_generator.append_move_definition(self, self.value)
  720. class LoadLocalInstruction(LocalInstruction):
  721. """An instruction that loads a value from a local variable."""
  722. def has_definition_impl(self):
  723. """Tells if this instruction requires a definition."""
  724. return False
  725. def get_children(self):
  726. """Gets this instruction's sequence of child instructions."""
  727. return []
  728. def create(self, new_children):
  729. """Creates a new instruction of this type from the given sequence of child instructions."""
  730. return self
  731. class DefineFunctionInstruction(VariableInstruction):
  732. """An instruction that defines a function."""
  733. def __init__(self, name, parameter_list, body):
  734. VariableInstruction.__init__(self, name)
  735. self.parameter_list = parameter_list
  736. self.body = body
  737. def get_children(self):
  738. """Gets this instruction's sequence of child instructions."""
  739. return [self.body]
  740. def create(self, new_children):
  741. """Creates a new instruction of this type from the given sequence of child instructions."""
  742. body, = new_children
  743. return DefineFunctionInstruction(self.name, self.parameter_list, body)
  744. def generate_python_def(self, code_generator):
  745. """Generates a Python statement that executes this instruction.
  746. The statement is appended immediately to the code generator."""
  747. code_generator.append_line('def %s(%s):' % (
  748. code_generator.get_result_name(self), ', '.join(self.parameter_list)))
  749. code_generator.increase_indentation()
  750. self.body.generate_python_def(code_generator)
  751. code_generator.decrease_indentation()
  752. class LocalExistsInstruction(LocalInstruction):
  753. """An instruction that checks if a local variable exists."""
  754. def has_definition_impl(self):
  755. """Tells if this instruction requires a definition."""
  756. return False
  757. def get_children(self):
  758. """Gets this instruction's sequence of child instructions."""
  759. return []
  760. def create(self, new_children):
  761. """Creates a new instruction of this type from the given sequence of child instructions."""
  762. return self
  763. def generate_python_use(self, code_generator):
  764. """Generates a Python expression that retrieves this instruction's
  765. result. The expression is returned as a string."""
  766. return "'%s' in locals()" % self.get_result_name_override(code_generator)
  767. class LoadGlobalInstruction(VariableInstruction):
  768. """An instruction that loads a value from a global variable."""
  769. def has_definition_impl(self):
  770. """Tells if this instruction requires a definition."""
  771. return False
  772. def get_children(self):
  773. """Gets this instruction's sequence of child instructions."""
  774. return []
  775. def create(self, new_children):
  776. """Creates a new instruction of this type from the given sequence of child instructions."""
  777. return self
  778. class LoadIndexInstruction(Instruction):
  779. """An instruction that produces a value by indexing a specified expression with
  780. a given key."""
  781. def __init__(self, indexed, key):
  782. Instruction.__init__(self)
  783. self.indexed = indexed
  784. self.key = key
  785. def has_definition_impl(self):
  786. """Tells if this instruction requires a definition."""
  787. return False
  788. def get_children(self):
  789. """Gets this instruction's sequence of child instructions."""
  790. return [self.indexed, self.key]
  791. def create(self, new_children):
  792. """Creates a new instruction of this type from the given sequence of child instructions."""
  793. indexed, key = new_children
  794. return LoadIndexInstruction(indexed, key)
  795. def generate_python_use(self, code_generator):
  796. """Generates a Python expression that retrieves this instruction's
  797. result. The expression is returned as a string."""
  798. if self.indexed.has_definition():
  799. self.indexed.generate_python_def(code_generator)
  800. if self.key.has_definition():
  801. self.key.generate_python_def(code_generator)
  802. return "%s[%s]" % (
  803. self.indexed.generate_python_use(code_generator),
  804. self.key.generate_python_use(code_generator))
  805. class LoadMemberInstruction(Instruction):
  806. """An instruction that produces a value by loading a member from a container."""
  807. def __init__(self, container, member_name):
  808. Instruction.__init__(self)
  809. self.container = container
  810. self.member_name = member_name
  811. def has_definition_impl(self):
  812. """Tells if this instruction requires a definition."""
  813. return self.container.has_definition()
  814. def get_children(self):
  815. """Gets this instruction's sequence of child instructions."""
  816. return [self.container]
  817. def create(self, new_children):
  818. """Creates a new instruction of this type from the given sequence of child instructions."""
  819. container, = new_children
  820. return LoadMemberInstruction(container, self.member_name)
  821. def generate_python_def(self, code_generator):
  822. """Generates a Python statement that executes this instruction.
  823. The statement is appended immediately to the code generator."""
  824. self.container.generate_python_def(code_generator)
  825. def generate_python_use(self, code_generator):
  826. """Generates a Python expression that retrieves this instruction's
  827. result. The expression is returned as a string."""
  828. return "%s.%s" % (
  829. self.container.generate_python_use(code_generator),
  830. self.member_name)
  831. class StoreMemberInstruction(VoidInstruction):
  832. """An instruction that stores a value in a container member."""
  833. def __init__(self, container, member_name, value):
  834. VoidInstruction.__init__(self)
  835. self.container = container
  836. self.member_name = member_name
  837. self.value = value
  838. def has_definition_impl(self):
  839. """Tells if this instruction requires a definition."""
  840. return True
  841. def get_children(self):
  842. """Gets this instruction's sequence of child instructions."""
  843. return [self.container, self.value]
  844. def create(self, new_children):
  845. """Creates a new instruction of this type from the given sequence of child instructions."""
  846. container, value = new_children
  847. return StoreMemberInstruction(container, self.member_name, value)
  848. def generate_python_def(self, code_generator):
  849. """Generates a Python statement that executes this instruction.
  850. The statement is appended immediately to the code generator."""
  851. if self.container.has_definition():
  852. self.container.generate_python_def(code_generator)
  853. code_generator.append_line('%s.%s = %s' % (
  854. self.container.generate_python_use(code_generator),
  855. self.member_name,
  856. self.value.generate_python_use(code_generator)))
  857. class NopInstruction(VoidInstruction):
  858. """A nop instruction, which allows for the kernel's thread of execution to be interrupted."""
  859. def generate_python_def(self, code_generator):
  860. """Generates a Python statement that executes this instruction.
  861. The statement is appended immediately to the code generator."""
  862. code_generator.append_line('yield %s' % repr(NOP_LITERAL))
  863. class ReadValueInstruction(StateInstruction):
  864. """An instruction that reads a value from a node."""
  865. def __init__(self, node_id):
  866. StateInstruction.__init__(self)
  867. self.node_id = node_id
  868. def get_result_type_impl(self):
  869. """Gets the type of value produced by this instruction."""
  870. return PRIMITIVE_RESULT_TYPE
  871. def simplify_node(self):
  872. """Applies basic simplification to this instruction only."""
  873. if isinstance(self.node_id, CreateNodeWithValueInstruction):
  874. return self.node_id.value
  875. else:
  876. return self
  877. def get_opcode(self):
  878. """Gets the opcode for this state instruction."""
  879. return "RV"
  880. def get_arguments(self):
  881. """Gets this state instruction's argument list."""
  882. return [self.node_id]
  883. class ReadDictionaryValueInstruction(StateInstruction):
  884. """An instruction that reads a dictionary value."""
  885. def __init__(self, node_id, key):
  886. StateInstruction.__init__(self)
  887. self.node_id = node_id
  888. self.key = key
  889. def get_opcode(self):
  890. """Gets the opcode for this state instruction."""
  891. return "RD"
  892. def get_arguments(self):
  893. """Gets this state instruction's argument list."""
  894. return [self.node_id, self.key]
  895. class ReadDictionaryEdgeInstruction(StateInstruction):
  896. """An instruction that reads a dictionary edge."""
  897. def __init__(self, node_id, key):
  898. StateInstruction.__init__(self)
  899. self.node_id = node_id
  900. self.key = key
  901. def get_opcode(self):
  902. """Gets the opcode for this state instruction."""
  903. return "RDE"
  904. def get_arguments(self):
  905. """Gets this state instruction's argument list."""
  906. return [self.node_id, self.key]
  907. class ReadEdgeInstruction(StateInstruction):
  908. """An instruction that reads an edge."""
  909. def __init__(self, node_id):
  910. StateInstruction.__init__(self)
  911. self.node_id = node_id
  912. def get_opcode(self):
  913. """Gets the opcode for this state instruction."""
  914. return "RE"
  915. def get_arguments(self):
  916. """Gets this state instruction's argument list."""
  917. return [self.node_id]
  918. class ReadOutgoingEdgesInstruction(StateInstruction):
  919. """An instruction that reads all outgoing edges for a node."""
  920. def __init__(self, node_id):
  921. StateInstruction.__init__(self)
  922. self.node_id = node_id
  923. def get_result_type_impl(self):
  924. """Gets the type of value produced by this instruction."""
  925. return PRIMITIVE_RESULT_TYPE
  926. def get_opcode(self):
  927. """Gets the opcode for this state instruction."""
  928. return "RO"
  929. def get_arguments(self):
  930. """Gets this state instruction's argument list."""
  931. return [self.node_id]
  932. class ReadIncomingEdgesInstruction(StateInstruction):
  933. """An instruction that reads all incoming edges for a node."""
  934. def __init__(self, node_id):
  935. StateInstruction.__init__(self)
  936. self.node_id = node_id
  937. def get_result_type_impl(self):
  938. """Gets the type of value produced by this instruction."""
  939. return PRIMITIVE_RESULT_TYPE
  940. def get_opcode(self):
  941. """Gets the opcode for this state instruction."""
  942. return "RI"
  943. def get_arguments(self):
  944. """Gets this state instruction's argument list."""
  945. return [self.node_id]
  946. class CreateNodeInstruction(StateInstruction):
  947. """An instruction that creates an empty node."""
  948. def get_opcode(self):
  949. """Gets the opcode for this state instruction."""
  950. return "CN"
  951. def get_arguments(self):
  952. """Gets this state instruction's argument list."""
  953. return []
  954. class CreateNodeWithValueInstruction(StateInstruction):
  955. """An instruction that creates a node with a given value."""
  956. def __init__(self, value):
  957. StateInstruction.__init__(self)
  958. self.value = value
  959. def get_opcode(self):
  960. """Gets the opcode for this state instruction."""
  961. return "CNV"
  962. def get_arguments(self):
  963. """Gets this state instruction's argument list."""
  964. return [self.value]
  965. class CreateEdgeInstruction(StateInstruction):
  966. """An instruction that creates an edge."""
  967. def __init__(self, source_id, target_id):
  968. StateInstruction.__init__(self)
  969. self.source_id = source_id
  970. self.target_id = target_id
  971. def get_opcode(self):
  972. """Gets the opcode for this state instruction."""
  973. return "CE"
  974. def get_arguments(self):
  975. """Gets this state instruction's argument list."""
  976. return [self.source_id, self.target_id]
  977. class CreateDictionaryEdgeInstruction(StateInstruction):
  978. """An instruction that creates a dictionary edge."""
  979. def __init__(self, source_id, key, target_id):
  980. StateInstruction.__init__(self)
  981. self.source_id = source_id
  982. self.key = key
  983. self.target_id = target_id
  984. def get_opcode(self):
  985. """Gets the opcode for this state instruction."""
  986. return "CD"
  987. def get_arguments(self):
  988. """Gets this state instruction's argument list."""
  989. return [self.source_id, self.key, self.target_id]
  990. class DeleteNodeInstruction(StateInstruction):
  991. """An instruction that deletes a node."""
  992. def __init__(self, node_id):
  993. StateInstruction.__init__(self)
  994. self.node_id = node_id
  995. def get_result_type_impl(self):
  996. """Gets the type of value produced by this instruction."""
  997. return NO_RESULT_TYPE
  998. def get_opcode(self):
  999. """Gets the opcode for this state instruction."""
  1000. return "DN"
  1001. def get_arguments(self):
  1002. """Gets this state instruction's argument list."""
  1003. return [self.node_id]
  1004. class DeleteEdgeInstruction(StateInstruction):
  1005. """An instruction that deletes an edge."""
  1006. def __init__(self, edge_id):
  1007. StateInstruction.__init__(self)
  1008. self.edge_id = edge_id
  1009. def get_result_type_impl(self):
  1010. """Gets the type of value produced by this instruction."""
  1011. return NO_RESULT_TYPE
  1012. def get_opcode(self):
  1013. """Gets the opcode for this state instruction."""
  1014. return "DE"
  1015. def get_arguments(self):
  1016. """Gets this state instruction's argument list."""
  1017. return [self.edge_id]
  1018. def create_block(*statements):
  1019. """Creates a block-statement from the given list of statements."""
  1020. length = len(statements)
  1021. if length == 0:
  1022. return EmptyInstruction()
  1023. elif length == 1:
  1024. return statements[0]
  1025. else:
  1026. return CompoundInstruction(
  1027. statements[0],
  1028. create_block(*statements[1:]))
  1029. def create_jit_call(target, named_arguments, kwargs):
  1030. """Creates a call that abides by the JIT's calling convention."""
  1031. # A JIT call looks like this:
  1032. #
  1033. # target = ...
  1034. # arg_dict = { ... }
  1035. # arg_dict.update(kwargs)
  1036. # result, = yield [("CALL_KWARGS", [target, arg_dict])]
  1037. results = []
  1038. if target.has_definition():
  1039. target_tmp = StoreLocalInstruction(None, target)
  1040. results.append(target_tmp)
  1041. target = target_tmp.create_load()
  1042. arg_dict = StoreLocalInstruction(
  1043. None,
  1044. DictionaryLiteralInstruction(
  1045. [(LiteralInstruction(key), val) for key, val in named_arguments]))
  1046. results.append(arg_dict)
  1047. results.append(
  1048. CallInstruction(
  1049. LoadMemberInstruction(arg_dict.create_load(), 'update'),
  1050. [kwargs]))
  1051. return CompoundInstruction(
  1052. create_block(*results),
  1053. RunGeneratorFunctionInstruction(
  1054. target, arg_dict.create_load(), NODE_RESULT_TYPE))
  1055. def create_new_local_node(local_variable, connected_node, edge_variable=None):
  1056. """Creates a local node that is the backing storage for a local variable.
  1057. This node is connected to a given node to make sure it's not perceived
  1058. as dead by the GC. The newly created node is stored in the given
  1059. local variable. The edge's id can also optionally be stored in a variable."""
  1060. local_store = StoreLocalInstruction(local_variable, CreateNodeInstruction())
  1061. create_edge = CreateEdgeInstruction(connected_node, local_store.create_load())
  1062. if edge_variable is not None:
  1063. create_edge = StoreLocalInstruction(edge_variable, create_edge)
  1064. return create_block(local_store, create_edge)
  1065. def with_debug_info_trace(instruction, debug_info, function_name):
  1066. """Prepends the given instruction with a tracing instruction that prints
  1067. the given debug information and function name."""
  1068. if debug_info is None and function_name is None:
  1069. return instruction
  1070. else:
  1071. if debug_info is None:
  1072. debug_info = 'unknown location '
  1073. if function_name is None:
  1074. function_name = 'unknown function'
  1075. return create_block(
  1076. PrintInstruction(
  1077. LiteralInstruction('TRACE: %s(%s, JIT)' % (debug_info, function_name))),
  1078. instruction)
  1079. def map_instruction_tree_top_down(function, instruction):
  1080. """Applies the given mapping function to every instruction in the tree
  1081. that has the given instruction as root. The map is applied in a top-down
  1082. fashion."""
  1083. mapped_instruction = function(instruction)
  1084. return mapped_instruction.create(
  1085. [map_instruction_tree_top_down(function, child)
  1086. for child in mapped_instruction.get_children()])
  1087. def map_and_simplify(function, instruction):
  1088. """Applies the given mapping function to every instruction in the tree
  1089. that has the given instruction as root, and simplifies it on-the-fly.
  1090. The map is applied in a bottom-up fashion.
  1091. This is at least as powerful as first mapping and then simplifying, as
  1092. maps and simplifications are interspersed."""
  1093. return function(
  1094. instruction.create(
  1095. [map_and_simplify(function, child)
  1096. for child in instruction.get_children()])).simplify_node()
  1097. def iterate_as_stack(instruction, stack_iterator):
  1098. """Iterates over the given instruction and its children in the order in which temporaries are
  1099. 'pushed' on and 'popped' from a virtual evaluation stack."""
  1100. if isinstance(instruction, SelectInstruction):
  1101. iterate_as_stack(instruction.condition, stack_iterator)
  1102. stack_iterator.pop()
  1103. if_iterator, else_iterator = stack_iterator.branch(), stack_iterator.branch()
  1104. iterate_as_stack(instruction.if_clause, if_iterator)
  1105. iterate_as_stack(instruction.else_clause, else_iterator)
  1106. stack_iterator.merge(if_iterator, else_iterator)
  1107. elif isinstance(instruction, CompoundInstruction):
  1108. iterate_as_stack(instruction.first, stack_iterator)
  1109. if instruction.second.has_result():
  1110. stack_iterator.pop()
  1111. iterate_as_stack(instruction.second, stack_iterator)
  1112. if not instruction.second.has_result():
  1113. stack_iterator.pop()
  1114. else:
  1115. children = instruction.get_children()
  1116. for child in children:
  1117. # Push all children onto the stack.
  1118. iterate_as_stack(child, stack_iterator)
  1119. for child in children:
  1120. # Pop all children from the stack.
  1121. stack_iterator.pop()
  1122. # Push the instruction.
  1123. stack_iterator.push(instruction)
  1124. class StackIterator(object):
  1125. """A base class for stack iterators."""
  1126. def __init__(self, stack=None):
  1127. self.stack = [] if stack is None else stack
  1128. def pop(self):
  1129. """Pops an instruction from the stack."""
  1130. self.stack.pop()
  1131. def push(self, instruction):
  1132. """Pushes an instruction onto the stack."""
  1133. self.stack.append(set([instruction]))
  1134. def branch(self):
  1135. """Creates a copy of this stack iterator."""
  1136. return self.create(self.copy_stack())
  1137. def merge(self, *branches):
  1138. """Sets this stack iterator's stack to the union of the given branches."""
  1139. self.__init__(self.merge_stacks(*branches))
  1140. def copy_stack(self):
  1141. """Creates a copy of this stack iterator's stack."""
  1142. return [set(vals) for vals in self.stack]
  1143. def create(self, new_stack):
  1144. """Creates a stack iterator from the given stack"""
  1145. return type(self)(new_stack)
  1146. def merge_stacks(self, *branches):
  1147. """Computes the union of the stacks of the given branches."""
  1148. results = None
  1149. for branch in branches:
  1150. if results is None:
  1151. results = branch.copy_stack()
  1152. else:
  1153. assert len(branch.stack) == len(results)
  1154. results = [set.union(*t) for t in zip(branch.stack, results)]
  1155. return results
  1156. def protect_temporaries_from_gc(instruction, connected_node):
  1157. """Protects temporaries from the garbage collector by connecting them to the given node."""
  1158. # # The reasoning behind this function
  1159. #
  1160. # A nop instruction (`yield None`) may trigger the garbage collector, which will delete
  1161. # unreachable ("dead") vertices and edges. Now take into account that a bare temporary node
  1162. # is actually unreachable from the root node. The consequence is that temporary nodes
  1163. # may be garbage-collected if a nop instruction is executed while they are on the evaluation
  1164. # "stack." This is _never_ what we want.
  1165. #
  1166. # To counter this, we can connect temporary nodes to a node that is reachable from the root.
  1167. # However, we only want to create edges between edges and a known reachable node if we really
  1168. # have to, because creating edges incurs some overhead.
  1169. #
  1170. # We will create an edge between a temporary and the known reachable node if and only if the
  1171. # temporary is on the "stack" when either a nop or a call instruction is executed.
  1172. class GCStackIterator(StackIterator):
  1173. """A stack iterator that detects which instructions might be at risk of getting garbage
  1174. collected."""
  1175. def __init__(self, stack=None, gc_temporaries=None):
  1176. StackIterator.__init__(self, stack)
  1177. self.gc_temporaries = set() if gc_temporaries is None else gc_temporaries
  1178. def push(self, instruction):
  1179. """Pushes an instruction onto the stack."""
  1180. if isinstance(instruction, (
  1181. NopInstruction,
  1182. RunGeneratorFunctionInstruction,
  1183. RunTailGeneratorFunctionInstruction)):
  1184. # All values currently on the stack are at risk. Mark them as such.
  1185. for instruction_set in self.stack:
  1186. self.gc_temporaries.update(instruction_set)
  1187. # Proceed.
  1188. StackIterator.push(self, instruction)
  1189. def merge(self, *branches):
  1190. """Sets this stack iterator's stack to the union of the given branches."""
  1191. self.__init__(
  1192. self.merge_stacks(*branches),
  1193. set.union(*[br.gc_temporaries for br in branches]))
  1194. def create(self, new_stack):
  1195. """Creates a stack iterator from the given stack"""
  1196. return GCStackIterator(new_stack, self.gc_temporaries)
  1197. # Find out which instructions are at risk.
  1198. gc_iterator = GCStackIterator()
  1199. iterate_as_stack(instruction, gc_iterator)
  1200. # These temporaries need to be protected from the GC.
  1201. gc_temporaries = gc_iterator.gc_temporaries
  1202. def protect_result(instruction):
  1203. """Protects the given instruction's (temporary) result."""
  1204. if instruction in gc_temporaries and instruction.get_result_type() == NODE_RESULT_TYPE:
  1205. gc_temporaries.remove(instruction)
  1206. store_instr = StoreLocalInstruction(None, instruction)
  1207. return CompoundInstruction(
  1208. store_instr,
  1209. CompoundInstruction(
  1210. SelectInstruction(
  1211. BinaryInstruction(
  1212. store_instr.create_load(), 'is not', LiteralInstruction(None)),
  1213. CreateEdgeInstruction(connected_node, store_instr.create_load()),
  1214. EmptyInstruction()),
  1215. store_instr.create_load()))
  1216. else:
  1217. return instruction
  1218. return map_instruction_tree_top_down(protect_result, instruction)
  1219. if __name__ == "__main__":
  1220. example_tree = SelectInstruction(
  1221. LiteralInstruction(True),
  1222. LoopInstruction(
  1223. CompoundInstruction(
  1224. BreakInstruction(),
  1225. CompoundInstruction(
  1226. EmptyInstruction(),
  1227. ContinueInstruction()
  1228. )
  1229. )
  1230. ),
  1231. ReturnInstruction(
  1232. EmptyInstruction()))
  1233. print(example_tree.simplify())