tree_ir.py 68 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745
  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 has_result_temporary(self):
  94. """Tells if this instruction stores its result in a temporary."""
  95. return True
  96. def generate_python_def(self, code_generator):
  97. """Generates a Python statement that executes this instruction.
  98. The statement is appended immediately to the code generator."""
  99. if self.has_definition():
  100. raise NotImplementedError()
  101. else:
  102. code_generator.append_line('pass')
  103. def generate_python_use(self, code_generator):
  104. """Generates a Python expression that retrieves this instruction's
  105. result. The expression is returned as a string."""
  106. if self.has_result():
  107. return code_generator.get_result_name(self)
  108. else:
  109. return 'None'
  110. def get_children(self):
  111. """Gets this instruction's sequence of child instructions."""
  112. raise NotImplementedError()
  113. def create(self, new_children):
  114. """Creates a new instruction of this type from the given sequence of child instructions."""
  115. raise NotImplementedError()
  116. def simplify_node(self):
  117. """Applies basic simplification to this instruction only."""
  118. return self
  119. def simplify(self):
  120. """Applies basic simplification to this instruction and all of its children."""
  121. # This fairly convoluted one-liner first simplifies all children, then creates
  122. # an instruction from the simplified children, and finally simplifies that top-level
  123. # instruction.
  124. return self.create([c.simplify() for c in self.get_children()]).simplify_node()
  125. def __str__(self):
  126. code_generator = PythonGenerator()
  127. self.generate_python_def(code_generator)
  128. return str(code_generator)
  129. class PythonGenerator(object):
  130. """Generates Python code from instructions."""
  131. def __init__(self, combine_state_definitions=True):
  132. self.code = []
  133. self.state_definitions = []
  134. self.state_definition_names = set()
  135. self.indentation_string = ' ' * 4
  136. self.indentation = 0
  137. self.result_name_dict = {}
  138. self.combine_state_definitions = combine_state_definitions
  139. def append(self, text):
  140. """Appends the given string to this code generator."""
  141. self.flush_state_definitions()
  142. self.code.append(text)
  143. def append_indentation(self):
  144. """Appends indentation to the code generator."""
  145. self.append(self.indentation_string * self.indentation)
  146. def append_line(self, line=None):
  147. """Appends the indentation string followed by the given string (if any)
  148. and a newline to the code generator."""
  149. self.append_indentation()
  150. if line is not None:
  151. self.append(line)
  152. self.append('\n')
  153. def increase_indentation(self):
  154. """Increases the code generator's indentation by one indent."""
  155. self.flush_state_definitions()
  156. self.indentation += 1
  157. def decrease_indentation(self):
  158. """Decreases the code generator's indentation by one indent."""
  159. self.flush_state_definitions()
  160. self.indentation -= 1
  161. def get_result_name(self, instruction, advised_name=None):
  162. """Gets the name of the given instruction's result variable."""
  163. if instruction not in self.result_name_dict:
  164. override_name = instruction.get_result_name_override(self)
  165. if override_name is not None:
  166. self.result_name_dict[instruction] = override_name
  167. elif advised_name is not None:
  168. self.result_name_dict[instruction] = advised_name
  169. else:
  170. self.result_name_dict[instruction] = \
  171. 'tmp' + str(len(self.result_name_dict))
  172. result = self.result_name_dict[instruction]
  173. if result in self.state_definition_names:
  174. # This might mean that we're trying to access a name that is
  175. # defined by the current block of state definitions. So we need
  176. # to flush the state definitions now.
  177. self.flush_state_definitions()
  178. return result
  179. def append_definition(self, lhs, rhs):
  180. """Defines the first instruction's result variable as the second
  181. instruction's result."""
  182. self.append_line(
  183. self.get_result_name(lhs) + ' = ' + rhs.generate_python_use(self))
  184. def append_move_definition(self, lhs, rhs):
  185. """First defines the second instruction, then defines the first
  186. instruction as the result of the second."""
  187. if rhs.has_definition():
  188. # Retrieve the result name for the lhs.
  189. lhs_result_name = self.get_result_name(lhs)
  190. # Encourage the rhs to take on the same result name as the lhs.
  191. rhs_result_name = self.get_result_name(rhs, lhs_result_name)
  192. # Generate the rhs' definition.
  193. rhs.generate_python_def(self)
  194. # Only perform an assignment if it's truly necessary.
  195. if lhs_result_name != rhs_result_name or not rhs.has_result_temporary():
  196. self.append_definition(lhs, rhs)
  197. else:
  198. self.append_definition(lhs, rhs)
  199. def append_state_definition(self, lhs, opcode, args):
  200. """Appends a definition that queries the modelverse state."""
  201. result_name = self.get_result_name(lhs)
  202. request_tuple = '(%s, [%s])' % (
  203. repr(opcode),
  204. ', '.join([arg_i.generate_python_use(self) for arg_i in args]))
  205. self.state_definitions.append((result_name, request_tuple))
  206. self.state_definition_names.add(result_name)
  207. if not self.combine_state_definitions:
  208. self.flush_state_definitions()
  209. def flush_state_definitions(self):
  210. """Flushes the list of state-access definitions to the generated code."""
  211. state_defs = self.state_definitions
  212. if len(state_defs) > 0:
  213. # Clear state_definitions _before_ calling append_line, because append_line
  214. # will call flush_state_definitions. Clearing state_definitions afterward
  215. # will result in infinite recursion.
  216. self.state_definitions = []
  217. self.state_definition_names = set()
  218. if len(state_defs) == 1:
  219. self.append_line('%s, = yield [%s]' % state_defs[0])
  220. else:
  221. self.append_line(
  222. "%s = yield [%s]" % (
  223. ', '.join([name for name, _ in state_defs]),
  224. ', '.join([def_val for _, def_val in state_defs])))
  225. def __str__(self):
  226. self.flush_state_definitions()
  227. return ''.join(self.code)
  228. class VoidInstruction(Instruction):
  229. """A base class for instructions that do not return a value."""
  230. def get_result_type_impl(self):
  231. """Gets this instruction's result type."""
  232. return NO_RESULT_TYPE
  233. def get_children(self):
  234. """Gets this instruction's sequence of child instructions."""
  235. return []
  236. def create(self, new_children):
  237. """Creates a new instruction of this type from the given sequence of child instructions."""
  238. return self
  239. class EmptyInstruction(VoidInstruction):
  240. """Represents the empty instruction, which does nothing."""
  241. def has_definition_impl(self):
  242. """Tells if this instruction requires a definition."""
  243. return False
  244. def __repr__(self):
  245. return "EmptyInstruction()"
  246. class SelectInstruction(Instruction):
  247. """Represents a select-instruction: an instruction that defines one of two
  248. child instructions, and sets its result to the defined child's result."""
  249. def __init__(self, condition, if_clause, else_clause):
  250. Instruction.__init__(self)
  251. self.condition = condition
  252. self.if_clause = if_clause
  253. self.else_clause = else_clause
  254. def get_result_type_impl(self):
  255. """Gets this instruction's result type."""
  256. return result_type_intersection(
  257. self.if_clause.get_result_type(),
  258. self.else_clause.get_result_type())
  259. def simplify_node(self):
  260. """Applies basic simplification to this instruction only."""
  261. if isinstance(self.condition, LiteralInstruction):
  262. return self.if_clause if self.condition.literal else self.else_clause
  263. else:
  264. return SelectInstruction(self.condition, self.if_clause, self.else_clause)
  265. def get_children(self):
  266. """Gets this instruction's sequence of child instructions."""
  267. return [self.condition, self.if_clause, self.else_clause]
  268. def create(self, new_children):
  269. """Creates a new instruction of this type from the given sequence of child instructions."""
  270. condition, if_clause, else_clause = new_children
  271. return SelectInstruction(condition, if_clause, else_clause)
  272. def generate_python_if(self, code_generator, is_elif=False):
  273. """Generates Python code for this instruction."""
  274. if_has_result = self.has_result()
  275. if self.condition.has_definition():
  276. self.condition.generate_python_def(code_generator)
  277. code_generator.append_line(
  278. ('elif ' if is_elif else 'if ') +
  279. self.condition.generate_python_use(code_generator) + ':')
  280. code_generator.increase_indentation()
  281. if if_has_result:
  282. code_generator.append_move_definition(self, self.if_clause)
  283. else:
  284. self.if_clause.generate_python_def(code_generator)
  285. code_generator.decrease_indentation()
  286. else_has_def = self.else_clause.has_definition()
  287. if else_has_def or if_has_result:
  288. if (isinstance(self.else_clause, SelectInstruction) and
  289. not self.else_clause.condition.has_definition()):
  290. self.else_clause.generate_python_if(code_generator, True)
  291. if if_has_result:
  292. code_generator.increase_indentation()
  293. code_generator.append_definition(self, self.else_clause)
  294. code_generator.decrease_indentation()
  295. else:
  296. code_generator.append_line('else:')
  297. code_generator.increase_indentation()
  298. if if_has_result:
  299. code_generator.append_move_definition(self, self.else_clause)
  300. else:
  301. self.else_clause.generate_python_def(code_generator)
  302. code_generator.decrease_indentation()
  303. def generate_python_def(self, code_generator):
  304. """Generates Python code for this instruction."""
  305. return self.generate_python_if(code_generator)
  306. def __repr__(self):
  307. return "SelectInstruction(%r, %r, %r)" % (self.condition, self.if_clause, self.else_clause)
  308. class ReturnInstruction(VoidInstruction):
  309. """Represents a return-instruction."""
  310. def __init__(self, value):
  311. VoidInstruction.__init__(self)
  312. self.value = value
  313. def get_children(self):
  314. """Gets this instruction's sequence of child instructions."""
  315. return [self.value]
  316. def create(self, new_children):
  317. """Creates a new instruction of this type from the given sequence of child instructions."""
  318. value, = new_children
  319. return ReturnInstruction(value)
  320. def simplify_node(self):
  321. """Applies basic simplification to this instruction only."""
  322. # If we have a return whose value is a call, then we can rewrite
  323. # that as a tail call and save us a stack frame.
  324. def rewrite_call(instruction):
  325. """Rewrites the given instruction in tail-call form, or returns
  326. None."""
  327. if isinstance(instruction, RunGeneratorFunctionInstruction):
  328. return RunTailGeneratorFunctionInstruction(*instruction.get_children())
  329. elif isinstance(instruction, CompoundInstruction):
  330. snd_rewritten = rewrite_call(instruction.second)
  331. if snd_rewritten is not None:
  332. return CompoundInstruction(instruction.first, snd_rewritten)
  333. return None
  334. rewritten_value = rewrite_call(self.value)
  335. if rewritten_value is None:
  336. return self
  337. else:
  338. # We don't even need to create a return here, because tail calls terminate
  339. # the current stack frame anyway.
  340. return rewritten_value
  341. def generate_python_def(self, code_generator):
  342. """Generates Python code for this instruction."""
  343. if self.value.has_definition():
  344. self.value.generate_python_def(code_generator)
  345. code_generator.append_line(
  346. 'raise PrimitiveFinished(' +
  347. self.value.generate_python_use(code_generator) +
  348. ')')
  349. def __repr__(self):
  350. return "ReturnInstruction(%r)" % self.value
  351. class RaiseInstruction(VoidInstruction):
  352. """An instruction that raises an error."""
  353. def __init__(self, value):
  354. VoidInstruction.__init__(self)
  355. self.value = value
  356. def get_children(self):
  357. """Gets this instruction's sequence of child instructions."""
  358. return [self.value]
  359. def create(self, new_children):
  360. """Creates a new instruction of this type from the given sequence of child instructions."""
  361. value, = new_children
  362. return RaiseInstruction(value)
  363. def generate_python_def(self, code_generator):
  364. """Generates Python code for this instruction."""
  365. self.value.generate_python_def(code_generator)
  366. code_generator.append_line(
  367. 'raise ' + self.value.generate_python_use(code_generator))
  368. def __repr__(self):
  369. return "RaiseInstruction(%r)" % self.value
  370. class CallInstruction(Instruction):
  371. """An instruction that performs a simple call."""
  372. def __init__(self, target, argument_list):
  373. Instruction.__init__(self)
  374. self.target = target
  375. self.argument_list = argument_list
  376. def get_children(self):
  377. """Gets this instruction's sequence of child instructions."""
  378. return [self.target] + self.argument_list
  379. def create(self, new_children):
  380. """Creates a new instruction of this type from the given sequence of child instructions."""
  381. return CallInstruction(new_children[0], new_children[1:])
  382. def generate_python_def(self, code_generator):
  383. """Generates Python code for this instruction."""
  384. if self.target.has_definition():
  385. self.target.generate_python_def(code_generator)
  386. for arg in self.argument_list:
  387. if arg.has_definition():
  388. arg.generate_python_def(code_generator)
  389. code_generator.append_line(
  390. '%s = %s(%s)' % (
  391. code_generator.get_result_name(self),
  392. self.target.generate_python_use(code_generator),
  393. ', '.join([arg.generate_python_use(code_generator) for arg in self.argument_list])))
  394. def __repr__(self):
  395. return "CallInstruction(%r, %r)" % (self.target, self.argument_list)
  396. class PrintInstruction(VoidInstruction):
  397. """An instruction that prints a value."""
  398. def __init__(self, argument):
  399. VoidInstruction.__init__(self)
  400. self.argument = argument
  401. def get_children(self):
  402. """Gets this instruction's sequence of child instructions."""
  403. return [self.argument]
  404. def create(self, new_children):
  405. """Creates a new instruction of this type from the given sequence of child instructions."""
  406. arg, = new_children
  407. return PrintInstruction(arg)
  408. def generate_python_def(self, code_generator):
  409. """Generates Python code for this instruction."""
  410. if self.argument.has_definition():
  411. self.argument.generate_python_def(code_generator)
  412. code_generator.append_line(
  413. 'print(%s)' % (
  414. self.argument.generate_python_use(code_generator)))
  415. def __repr__(self):
  416. return "PrintInstruction(%r)" % self.argument
  417. class BinaryInstruction(Instruction):
  418. """An instruction that performs a binary operation."""
  419. def __init__(self, lhs, operator, rhs):
  420. Instruction.__init__(self)
  421. self.lhs = lhs
  422. self.operator = operator
  423. self.rhs = rhs
  424. def has_definition_impl(self):
  425. """Tells if this instruction requires a definition."""
  426. return self.lhs.has_definition() or self.rhs.has_definition()
  427. def get_children(self):
  428. """Gets this instruction's sequence of child instructions."""
  429. return [self.lhs, self.rhs]
  430. def create(self, new_children):
  431. """Creates a new instruction of this type from the given sequence of child instructions."""
  432. lhs, rhs, = new_children
  433. return BinaryInstruction(lhs, self.operator, rhs)
  434. def simplify_node(self):
  435. """Applies basic simplification to this instruction only."""
  436. if isinstance(self.lhs, LiteralInstruction) and isinstance(self.rhs, LiteralInstruction):
  437. # TODO: there's probably a better way to do this than with eval.
  438. return LiteralInstruction(
  439. eval('%s %s %s' % (repr(self.lhs.literal), self.operator, repr(self.rhs.literal))))
  440. else:
  441. return self
  442. def has_result_temporary(self):
  443. """Tells if this instruction stores its result in a temporary."""
  444. return False
  445. def generate_python_use(self, code_generator):
  446. """Generates a Python expression that retrieves this instruction's
  447. result. The expression is returned as a string."""
  448. return '(%s %s %s)' % (
  449. self.lhs.generate_python_use(code_generator),
  450. self.operator,
  451. self.rhs.generate_python_use(code_generator))
  452. def generate_python_def(self, code_generator):
  453. """Generates a Python statement that executes this instruction.
  454. The statement is appended immediately to the code generator."""
  455. lhs_has_def, rhs_has_def = self.lhs.has_definition(), self.rhs.has_definition()
  456. if lhs_has_def:
  457. self.lhs.generate_python_def(code_generator)
  458. if rhs_has_def:
  459. self.rhs.generate_python_def(code_generator)
  460. elif rhs_has_def:
  461. self.rhs.generate_python_def(code_generator)
  462. else:
  463. code_generator.append_line('pass')
  464. def __repr__(self):
  465. return "BinaryInstruction(%r, %r, %r)" % (self.lhs, self.operator, self.rhs)
  466. class UnaryInstruction(Instruction):
  467. """An instruction that performs a unary operation."""
  468. def __init__(self, operator, operand):
  469. Instruction.__init__(self)
  470. self.operator = operator
  471. self.operand = operand
  472. def has_definition_impl(self):
  473. """Tells if this instruction requires a definition."""
  474. return self.operand.has_definition()
  475. def get_children(self):
  476. """Gets this instruction's sequence of child instructions."""
  477. return [self.operand]
  478. def has_result_temporary(self):
  479. """Tells if this instruction stores its result in a temporary."""
  480. return False
  481. def create(self, new_children):
  482. """Creates a new instruction of this type from the given sequence of child instructions."""
  483. operand, = new_children
  484. return UnaryInstruction(self.operator, operand)
  485. def simplify_node(self):
  486. """Applies basic simplification to this instruction only."""
  487. if isinstance(self.operand, LiteralInstruction):
  488. # TODO: there's probably a better way to do this than with eval.
  489. return LiteralInstruction(
  490. eval('%s %s' % (self.operator, repr(self.operand.literal))))
  491. else:
  492. return self
  493. def generate_python_use(self, code_generator):
  494. """Generates a Python expression that retrieves this instruction's
  495. result. The expression is returned as a string."""
  496. return '(%s %s)' % (
  497. self.operator,
  498. self.operand.generate_python_use(code_generator))
  499. def generate_python_def(self, code_generator):
  500. """Generates a Python statement that executes this instruction.
  501. The statement is appended immediately to the code generator."""
  502. if self.operand.has_definition():
  503. self.operand.generate_python_def(code_generator)
  504. else:
  505. code_generator.append_line('pass')
  506. def __repr__(self):
  507. return "UnaryInstruction(%r, %r)" % (self.operator, self.operand)
  508. class LoopInstruction(VoidInstruction):
  509. """Represents a loop-instruction, which loops until broken."""
  510. def __init__(self, body):
  511. VoidInstruction.__init__(self)
  512. self.body = body
  513. def get_children(self):
  514. """Gets this instruction's sequence of child instructions."""
  515. return [self.body]
  516. def create(self, new_children):
  517. """Creates a new instruction of this type from the given sequence of child instructions."""
  518. body, = new_children
  519. return LoopInstruction(body)
  520. def generate_python_def(self, code_generator):
  521. """Generates Python code for this instruction."""
  522. code_generator.append_line('while 1:')
  523. code_generator.increase_indentation()
  524. self.body.generate_python_def(code_generator)
  525. code_generator.decrease_indentation()
  526. def __repr__(self):
  527. return "LoopInstruction(%r)" % self.body
  528. class BreakInstruction(VoidInstruction):
  529. """Represents a break-instruction."""
  530. def generate_python_def(self, code_generator):
  531. """Generates Python code for this instruction."""
  532. code_generator.append_line('break')
  533. def __repr__(self):
  534. return "BreakInstruction()"
  535. class ContinueInstruction(VoidInstruction):
  536. """Represents a continue-instruction."""
  537. def generate_python_def(self, code_generator):
  538. """Generates Python code for this instruction."""
  539. code_generator.append_line('continue')
  540. def __repr__(self):
  541. return "ContinueInstruction()"
  542. class IgnoreInstruction(VoidInstruction):
  543. """Represents an instruction that evaluates its operand, and then discards
  544. the result."""
  545. def __init__(self, value):
  546. VoidInstruction.__init__(self)
  547. self.value = value
  548. def has_definition_impl(self):
  549. """Tells if this instruction requires a definition."""
  550. return self.value.has_definition()
  551. def get_children(self):
  552. """Gets this instruction's sequence of child instructions."""
  553. return [self.value]
  554. def create(self, new_children):
  555. """Creates a new instruction of this type from the given sequence of child instructions."""
  556. value, = new_children
  557. return IgnoreInstruction(value)
  558. def simplify_node(self):
  559. """Applies basic simplification to this instruction and its children."""
  560. if not self.value.has_result():
  561. return self.value
  562. else:
  563. return self
  564. def generate_python_def(self, code_generator):
  565. """Generates Python code for this instruction."""
  566. self.value.generate_python_def(code_generator)
  567. def __repr__(self):
  568. return "IgnoreInstruction(%r)" % self.value
  569. class CompoundInstruction(Instruction):
  570. """Represents an instruction that evaluates two other instructions
  571. in order, and returns the second instruction's result."""
  572. def __init__(self, first, second):
  573. Instruction.__init__(self)
  574. self.first = first
  575. self.second = second
  576. def get_result_type_impl(self):
  577. """Gets this instruction's result type."""
  578. if self.second.has_result():
  579. return self.second.get_result_type()
  580. else:
  581. return self.first.get_result_type()
  582. def get_children(self):
  583. """Gets this instruction's sequence of child instructions."""
  584. return [self.first, self.second]
  585. def create(self, new_children):
  586. """Creates a new instruction of this type from the given sequence of child instructions."""
  587. first, second = new_children
  588. return CompoundInstruction(first, second)
  589. def simplify_node(self):
  590. """Applies basic simplification to this instruction and its children."""
  591. if not self.first.has_definition() and (
  592. not self.first.has_result() or self.second.has_result()):
  593. return self.second
  594. elif (not self.second.has_definition()) and (not self.second.has_result()):
  595. return self.first
  596. else:
  597. return self
  598. def generate_python_def(self, code_generator):
  599. """Generates Python code for this instruction."""
  600. if self.second.has_result():
  601. self.first.generate_python_def(code_generator)
  602. code_generator.append_move_definition(self, self.second)
  603. elif self.first.has_result():
  604. code_generator.append_move_definition(self, self.first)
  605. self.second.generate_python_def(code_generator)
  606. else:
  607. self.first.generate_python_def(code_generator)
  608. self.second.generate_python_def(code_generator)
  609. def __repr__(self):
  610. return "CompoundInstruction(%r, %r)" % (self.first, self.second)
  611. class LiteralInstruction(Instruction):
  612. """Represents an integer, floating-point, string or Boolean literal."""
  613. def __init__(self, literal):
  614. Instruction.__init__(self)
  615. self.literal = literal
  616. def has_definition_impl(self):
  617. """Tells if this instruction requires a definition."""
  618. return False
  619. def has_result_temporary(self):
  620. """Tells if this instruction stores its result in a temporary."""
  621. return False
  622. def get_children(self):
  623. """Gets this instruction's sequence of child instructions."""
  624. return []
  625. def create(self, new_children):
  626. """Creates a new instruction of this type from the given sequence of child instructions."""
  627. return self
  628. def generate_python_use(self, code_generator):
  629. """Generates a Python expression that retrieves this instruction's
  630. result. The expression is returned as a string."""
  631. return repr(self.literal)
  632. def __repr__(self):
  633. return "LiteralInstruction(%r)" % self.literal
  634. class DictionaryLiteralInstruction(Instruction):
  635. """Constructs a dictionary literal."""
  636. def __init__(self, key_value_pairs):
  637. Instruction.__init__(self)
  638. self.key_value_pairs = key_value_pairs
  639. def get_children(self):
  640. """Gets this instruction's sequence of child instructions."""
  641. return [val for _, val in self.key_value_pairs]
  642. def create(self, new_children):
  643. """Creates a new instruction of this type from the given sequence of child instructions."""
  644. keys = [k for k, _ in self.key_value_pairs]
  645. return DictionaryLiteralInstruction(zip(keys, new_children))
  646. def has_definition_impl(self):
  647. """Tells if this instruction requires a definition."""
  648. return any(
  649. [key.has_definition() or val.has_definition()
  650. for key, val in self.key_value_pairs])
  651. def has_result_temporary(self):
  652. """Tells if this instruction stores its result in a temporary."""
  653. return False
  654. def simplify(self):
  655. """Applies basic simplification to this instruction and its children."""
  656. return DictionaryLiteralInstruction(
  657. [(key.simplify(), val.simplify()) for key, val in self.key_value_pairs])
  658. def generate_python_def(self, code_generator):
  659. """Generates a Python statement that executes this instruction.
  660. The statement is appended immediately to the code generator."""
  661. for key, val in self.key_value_pairs:
  662. if key.has_definition():
  663. key.generate_python_def(code_generator)
  664. if val.has_definition():
  665. val.generate_python_def(code_generator)
  666. def generate_python_use(self, code_generator):
  667. """Generates a Python expression that retrieves this instruction's
  668. result. The expression is returned as a string."""
  669. return '{%s}' % ', '.join(
  670. ['%s : %s' % (
  671. key.generate_python_use(code_generator),
  672. val.generate_python_use(code_generator))
  673. for key, val in self.key_value_pairs])
  674. def __repr__(self):
  675. return "DictionaryLiteralInstruction(%r)" % self.key_value_pairs
  676. class ListSliceInstruction(Instruction):
  677. """Slices a list."""
  678. def __init__(self, seq, start, end, step):
  679. Instruction.__init__(self)
  680. self.seq = seq
  681. self.start = start
  682. self.end = end
  683. self.step = step
  684. def get_children(self):
  685. """Gets this instruction's sequence of child instructions."""
  686. all_items = (self.seq, self.start, self.end, self.step)
  687. return [item for item in all_items if item is not None]
  688. def create(self, new_children):
  689. """Creates a new instruction of this type from the given sequence of child instructions."""
  690. # pylint: disable=I0011,E1120
  691. args = []
  692. i = 0
  693. for old_item in (self.seq, self.start, self.end, self.step):
  694. if old_item is None:
  695. args.append(None)
  696. else:
  697. args.append(new_children[i])
  698. i += 1
  699. assert len(new_children) == i
  700. assert len(args) == 4
  701. return ListSliceInstruction(*args)
  702. def has_definition_impl(self):
  703. """Tells if this instruction requires a definition."""
  704. return any([item.has_definition() for item in self.get_children()])
  705. def has_result_temporary(self):
  706. """Tells if this instruction stores its result in a temporary."""
  707. return False
  708. def generate_python_def(self, code_generator):
  709. """Generates a Python statement that executes this instruction.
  710. The statement is appended immediately to the code generator."""
  711. for item in self.get_children():
  712. if item.has_definition():
  713. item.generate_python_def(code_generator)
  714. def generate_python_use(self, code_generator):
  715. """Generates a Python expression that retrieves this instruction's
  716. result. The expression is returned as a string."""
  717. return '%s[%s:%s:%s]' % (
  718. self.seq.generate_python_use(code_generator),
  719. '' if self.start is None else self.start.generate_python_use(code_generator),
  720. '' if self.end is None else self.end.generate_python_use(code_generator),
  721. '' if self.step is None else self.step.generate_python_use(code_generator))
  722. def __repr__(self):
  723. return "ListSliceInstruction(%r, %r, %r, %r)" % (self.seq, self.start, self.end, self.step)
  724. class StateInstruction(Instruction):
  725. """An instruction that accesses the modelverse state."""
  726. def get_result_type_impl(self):
  727. """Gets the type of value produced by this instruction."""
  728. return NODE_RESULT_TYPE
  729. def get_opcode(self):
  730. """Gets the opcode for this state instruction."""
  731. raise NotImplementedError()
  732. def get_arguments(self):
  733. """Gets this state instruction's argument list."""
  734. raise NotImplementedError()
  735. def get_children(self):
  736. """Gets this instruction's sequence of child instructions."""
  737. return self.get_arguments()
  738. def create(self, new_children):
  739. """Creates a new instruction of this type from the given sequence of child instructions."""
  740. return type(self)(*new_children)
  741. def generate_python_def(self, code_generator):
  742. """Generates a Python statement that executes this instruction.
  743. The statement is appended immediately to the code generator."""
  744. args = self.get_arguments()
  745. for arg_i in args:
  746. if arg_i.has_definition():
  747. arg_i.generate_python_def(code_generator)
  748. code_generator.append_state_definition(self, self.get_opcode(), args)
  749. def __repr__(self):
  750. return "StateInstruction(%s)" % ', '.join(map(repr, self.get_arguments()))
  751. class RunGeneratorFunctionInstruction(StateInstruction):
  752. """An instruction that runs a generator function."""
  753. def __init__(self, function, argument_dict, result_type=PRIMITIVE_RESULT_TYPE):
  754. StateInstruction.__init__(self)
  755. self.function = function
  756. self.argument_dict = argument_dict
  757. self.result_type_cache = result_type
  758. def get_opcode(self):
  759. """Gets the opcode for this state instruction."""
  760. return "CALL_KWARGS"
  761. def get_arguments(self):
  762. """Gets this state instruction's argument list."""
  763. return [self.function, self.argument_dict]
  764. def create(self, new_children):
  765. """Creates a new instruction of this type from the given sequence of child instructions."""
  766. func, arg_dict = new_children
  767. return RunGeneratorFunctionInstruction(func, arg_dict, self.get_result_type())
  768. class RunTailGeneratorFunctionInstruction(StateInstruction):
  769. """An instruction that runs a generator function."""
  770. def __init__(self, function, argument_dict):
  771. StateInstruction.__init__(self)
  772. self.function = function
  773. self.argument_dict = argument_dict
  774. def get_result_type_impl(self):
  775. """Gets the type of value produced by this instruction."""
  776. return NO_RESULT_TYPE
  777. def get_opcode(self):
  778. """Gets the opcode for this state instruction."""
  779. return "TAIL_CALL_KWARGS"
  780. def get_arguments(self):
  781. """Gets this state instruction's argument list."""
  782. return [self.function, self.argument_dict]
  783. class VariableName(object):
  784. """A data structure that unifies names across instructions that access the
  785. same variable."""
  786. def __init__(self, name):
  787. self.name = name
  788. def get_result_name_override(self, _):
  789. """Gets a value that overrides the code generator's result name for this
  790. instruction if it is not None."""
  791. return self.name
  792. def __str__(self):
  793. return self.name
  794. def __repr__(self):
  795. return 'VariableName(%r)' % self.name
  796. class VariableInstruction(Instruction):
  797. """A base class for instructions that access variables."""
  798. def __init__(self, name):
  799. Instruction.__init__(self)
  800. if isinstance(name, str) or isinstance(name, unicode) or name is None:
  801. self.name = VariableName(name)
  802. else:
  803. self.name = name
  804. def get_children(self):
  805. """Gets this instruction's sequence of child instructions."""
  806. raise NotImplementedError()
  807. def create(self, new_children):
  808. """Creates a new instruction of this type from the given sequence of child instructions."""
  809. raise NotImplementedError()
  810. def get_result_name_override(self, code_generator):
  811. """Gets a value that overrides the code generator's result name for this
  812. instruction if it is not None."""
  813. return code_generator.get_result_name(self.name)
  814. class LocalInstruction(VariableInstruction):
  815. """A base class for instructions that access local variables."""
  816. def get_children(self):
  817. """Gets this instruction's sequence of child instructions."""
  818. raise NotImplementedError()
  819. def create(self, new_children):
  820. """Creates a new instruction of this type from the given sequence of child instructions."""
  821. raise NotImplementedError()
  822. def create_load(self):
  823. """Creates an instruction that loads the variable referenced by this instruction."""
  824. return LoadLocalInstruction(self.name)
  825. def create_store(self, value):
  826. """Creates an instruction that stores the given value in the variable referenced
  827. by this instruction."""
  828. return StoreLocalInstruction(self.name, value)
  829. class StoreLocalInstruction(LocalInstruction):
  830. """An instruction that stores a value in a local variable."""
  831. def __init__(self, name, value):
  832. LocalInstruction.__init__(self, name)
  833. self.value = value
  834. def get_children(self):
  835. """Gets this instruction's sequence of child instructions."""
  836. return [self.value]
  837. def create(self, new_children):
  838. """Creates a new instruction of this type from the given sequence of child instructions."""
  839. val, = new_children
  840. return StoreLocalInstruction(self.name, val)
  841. def generate_python_def(self, code_generator):
  842. """Generates a Python statement that executes this instruction.
  843. The statement is appended immediately to the code generator."""
  844. code_generator.append_move_definition(self, self.value)
  845. def __repr__(self):
  846. return 'StoreLocalInstruction(%r, %r)' % (self.name, self.value)
  847. class TupleStoreLocalInstruction(VoidInstruction):
  848. """Assigns a number of values to a number of variables."""
  849. def __init__(self, name_value_pairs):
  850. VoidInstruction.__init__(self)
  851. self.name_value_pairs = name_value_pairs
  852. def get_children(self):
  853. """Gets this instruction's sequence of child instructions."""
  854. return [val for _, val in self.name_value_pairs]
  855. def has_result_temporary(self):
  856. """Tells if this instruction stores its result in a temporary."""
  857. return False
  858. def create(self, new_children):
  859. """Creates a new instruction of this type from the given sequence of child instructions."""
  860. new_name_value_pairs = [
  861. (name, new_value) for (name, _), new_value in zip(self.name_value_pairs, new_children)]
  862. return TupleStoreLocalInstruction(new_name_value_pairs)
  863. def generate_python_def(self, code_generator):
  864. """Generates a Python statement that executes this instruction.
  865. The statement is appended immediately to the code generator."""
  866. tuple_lhs = []
  867. tuple_rhs = []
  868. for name, value in self.name_value_pairs:
  869. if isinstance(name, str) or isinstance(name, unicode) or name is None:
  870. variable = VariableName(name)
  871. else:
  872. variable = name
  873. # Retrieve the result name for the variable.
  874. var_result_name = code_generator.get_result_name(variable)
  875. # Encourage the value to take on the same result name as the variable.
  876. value_result_name = code_generator.get_result_name(value, var_result_name)
  877. if value.has_definition():
  878. # Generate the value' definition.
  879. value.generate_python_def(code_generator)
  880. # Only perform an assignment if it's truly necessary.
  881. if var_result_name != value_result_name or not value.has_result_temporary():
  882. tuple_lhs.append(var_result_name)
  883. tuple_rhs.append(value.generate_python_use(code_generator))
  884. if len(tuple_lhs) > 0:
  885. code_generator.append_line(
  886. '%s = %s' % (', '.join(tuple_lhs), ', '.join(tuple_rhs)))
  887. def __repr__(self):
  888. return 'TupleStoreLocalInstruction(%r)' % (self.name_value_pairs)
  889. class LoadLocalInstruction(LocalInstruction):
  890. """An instruction that loads a value from a local variable."""
  891. def has_definition_impl(self):
  892. """Tells if this instruction requires a definition."""
  893. return False
  894. def get_children(self):
  895. """Gets this instruction's sequence of child instructions."""
  896. return []
  897. def create(self, new_children):
  898. """Creates a new instruction of this type from the given sequence of child instructions."""
  899. return self
  900. def __repr__(self):
  901. return 'LoadLocalInstruction(%r)' % self.name
  902. class DefineFunctionInstruction(VariableInstruction):
  903. """An instruction that defines a function."""
  904. def __init__(self, name, parameter_list, body):
  905. VariableInstruction.__init__(self, name)
  906. self.parameter_list = parameter_list
  907. self.body = body
  908. def get_children(self):
  909. """Gets this instruction's sequence of child instructions."""
  910. return [self.body]
  911. def create(self, new_children):
  912. """Creates a new instruction of this type from the given sequence of child instructions."""
  913. body, = new_children
  914. return DefineFunctionInstruction(self.name, self.parameter_list, body)
  915. def generate_python_def(self, code_generator):
  916. """Generates a Python statement that executes this instruction.
  917. The statement is appended immediately to the code generator."""
  918. code_generator.append_line('def %s(%s):' % (
  919. code_generator.get_result_name(self), ', '.join(self.parameter_list)))
  920. code_generator.increase_indentation()
  921. self.body.generate_python_def(code_generator)
  922. code_generator.decrease_indentation()
  923. def __repr__(self):
  924. return 'DefineFunctionInstruction(%r, %r, %r)' % (self.name, self.parameter_list, self.body)
  925. class LocalExistsInstruction(LocalInstruction):
  926. """An instruction that checks if a local variable exists."""
  927. def has_definition_impl(self):
  928. """Tells if this instruction requires a definition."""
  929. return False
  930. def get_children(self):
  931. """Gets this instruction's sequence of child instructions."""
  932. return []
  933. def create(self, new_children):
  934. """Creates a new instruction of this type from the given sequence of child instructions."""
  935. return self
  936. def generate_python_use(self, code_generator):
  937. """Generates a Python expression that retrieves this instruction's
  938. result. The expression is returned as a string."""
  939. return "'%s' in locals()" % self.get_result_name_override(code_generator)
  940. def __repr__(self):
  941. return 'LocalExistsInstruction(%r)' % self.name
  942. class LoadGlobalInstruction(VariableInstruction):
  943. """An instruction that loads a value from a global variable."""
  944. def has_definition_impl(self):
  945. """Tells if this instruction requires a definition."""
  946. return False
  947. def get_children(self):
  948. """Gets this instruction's sequence of child instructions."""
  949. return []
  950. def create(self, new_children):
  951. """Creates a new instruction of this type from the given sequence of child instructions."""
  952. return self
  953. def __repr__(self):
  954. return 'LoadGlobalInstruction(%r)' % self.name
  955. class LoadIndexInstruction(Instruction):
  956. """An instruction that produces a value by indexing a specified expression with
  957. a given key."""
  958. def __init__(self, indexed, key):
  959. Instruction.__init__(self)
  960. self.indexed = indexed
  961. self.key = key
  962. def has_definition_impl(self):
  963. """Tells if this instruction requires a definition."""
  964. return self.indexed.has_definition() or self.key.has_definition()
  965. def get_children(self):
  966. """Gets this instruction's sequence of child instructions."""
  967. return [self.indexed, self.key]
  968. def has_result_temporary(self):
  969. """Tells if this instruction stores its result in a temporary."""
  970. return False
  971. def create(self, new_children):
  972. """Creates a new instruction of this type from the given sequence of child instructions."""
  973. indexed, key = new_children
  974. return LoadIndexInstruction(indexed, key)
  975. def generate_python_use(self, code_generator):
  976. """Generates a Python expression that retrieves this instruction's
  977. result. The expression is returned as a string."""
  978. return "%s[%s]" % (
  979. self.indexed.generate_python_use(code_generator),
  980. self.key.generate_python_use(code_generator))
  981. def generate_python_def(self, code_generator):
  982. """Generates a Python statement that executes this instruction.
  983. The statement is appended immediately to the code generator."""
  984. indexed_has_def, key_has_def = self.indexed.has_definition(), self.key.has_definition()
  985. if indexed_has_def:
  986. self.indexed.generate_python_def(code_generator)
  987. if key_has_def:
  988. self.key.generate_python_def(code_generator)
  989. if not indexed_has_def and not key_has_def:
  990. code_generator.append_line('pass')
  991. def __repr__(self):
  992. return 'LoadIndexInstruction(%r, %r)' % (self.indexed, self.key)
  993. class LoadMemberInstruction(Instruction):
  994. """An instruction that produces a value by loading a member from a container."""
  995. def __init__(self, container, member_name):
  996. Instruction.__init__(self)
  997. self.container = container
  998. self.member_name = member_name
  999. def has_definition_impl(self):
  1000. """Tells if this instruction requires a definition."""
  1001. return self.container.has_definition()
  1002. def get_children(self):
  1003. """Gets this instruction's sequence of child instructions."""
  1004. return [self.container]
  1005. def has_result_temporary(self):
  1006. """Tells if this instruction stores its result in a temporary."""
  1007. return False
  1008. def create(self, new_children):
  1009. """Creates a new instruction of this type from the given sequence of child instructions."""
  1010. container, = new_children
  1011. return LoadMemberInstruction(container, self.member_name)
  1012. def generate_python_def(self, code_generator):
  1013. """Generates a Python statement that executes this instruction.
  1014. The statement is appended immediately to the code generator."""
  1015. self.container.generate_python_def(code_generator)
  1016. def generate_python_use(self, code_generator):
  1017. """Generates a Python expression that retrieves this instruction's
  1018. result. The expression is returned as a string."""
  1019. return "%s.%s" % (
  1020. self.container.generate_python_use(code_generator),
  1021. self.member_name)
  1022. def __repr__(self):
  1023. return 'LoadMemberInstruction(%r, %r)' % (self.container, self.member_name)
  1024. class StoreMemberInstruction(VoidInstruction):
  1025. """An instruction that stores a value in a container member."""
  1026. def __init__(self, container, member_name, value):
  1027. VoidInstruction.__init__(self)
  1028. self.container = container
  1029. self.member_name = member_name
  1030. self.value = value
  1031. def has_definition_impl(self):
  1032. """Tells if this instruction requires a definition."""
  1033. return True
  1034. def get_children(self):
  1035. """Gets this instruction's sequence of child instructions."""
  1036. return [self.container, self.value]
  1037. def create(self, new_children):
  1038. """Creates a new instruction of this type from the given sequence of child instructions."""
  1039. container, value = new_children
  1040. return StoreMemberInstruction(container, self.member_name, value)
  1041. def generate_python_def(self, code_generator):
  1042. """Generates a Python statement that executes this instruction.
  1043. The statement is appended immediately to the code generator."""
  1044. if self.container.has_definition():
  1045. self.container.generate_python_def(code_generator)
  1046. code_generator.append_line('%s.%s = %s' % (
  1047. self.container.generate_python_use(code_generator),
  1048. self.member_name,
  1049. self.value.generate_python_use(code_generator)))
  1050. def __repr__(self):
  1051. return 'StoreMemberInstruction(%r, %r, %r)' % (self.container, self.member_name, self.value)
  1052. class NopInstruction(VoidInstruction):
  1053. """A nop instruction, which allows for the kernel's thread of execution to be interrupted."""
  1054. def generate_python_def(self, code_generator):
  1055. """Generates a Python statement that executes this instruction.
  1056. The statement is appended immediately to the code generator."""
  1057. code_generator.append_line('yield %s' % repr(NOP_LITERAL))
  1058. def __repr__(self):
  1059. return 'NopInstruction()'
  1060. class ReadValueInstruction(StateInstruction):
  1061. """An instruction that reads a value from a node."""
  1062. def __init__(self, node_id):
  1063. StateInstruction.__init__(self)
  1064. self.node_id = node_id
  1065. def get_result_type_impl(self):
  1066. """Gets the type of value produced by this instruction."""
  1067. return PRIMITIVE_RESULT_TYPE
  1068. def simplify_node(self):
  1069. """Applies basic simplification to this instruction only."""
  1070. if isinstance(self.node_id, CreateNodeWithValueInstruction):
  1071. return self.node_id.value
  1072. else:
  1073. return self
  1074. def get_opcode(self):
  1075. """Gets the opcode for this state instruction."""
  1076. return "RV"
  1077. def get_arguments(self):
  1078. """Gets this state instruction's argument list."""
  1079. return [self.node_id]
  1080. class ReadDictionaryValueInstruction(StateInstruction):
  1081. """An instruction that reads a dictionary value."""
  1082. def __init__(self, node_id, key):
  1083. StateInstruction.__init__(self)
  1084. self.node_id = node_id
  1085. self.key = key
  1086. def get_opcode(self):
  1087. """Gets the opcode for this state instruction."""
  1088. return "RD"
  1089. def get_arguments(self):
  1090. """Gets this state instruction's argument list."""
  1091. return [self.node_id, self.key]
  1092. class ReadDictionaryEdgeInstruction(StateInstruction):
  1093. """An instruction that reads a dictionary edge."""
  1094. def __init__(self, node_id, key):
  1095. StateInstruction.__init__(self)
  1096. self.node_id = node_id
  1097. self.key = key
  1098. def get_opcode(self):
  1099. """Gets the opcode for this state instruction."""
  1100. return "RDE"
  1101. def get_arguments(self):
  1102. """Gets this state instruction's argument list."""
  1103. return [self.node_id, self.key]
  1104. class ReadDictionaryKeysInstruction(StateInstruction):
  1105. """An instruction that reads all keys from a dictionary."""
  1106. def __init__(self, node_id):
  1107. StateInstruction.__init__(self)
  1108. self.node_id = node_id
  1109. def get_opcode(self):
  1110. """Gets the opcode for this state instruction."""
  1111. return "RDK"
  1112. def get_arguments(self):
  1113. """Gets this state instruction's argument list."""
  1114. return [self.node_id]
  1115. class ReadEdgeInstruction(StateInstruction):
  1116. """An instruction that reads an edge."""
  1117. def __init__(self, node_id):
  1118. StateInstruction.__init__(self)
  1119. self.node_id = node_id
  1120. def get_opcode(self):
  1121. """Gets the opcode for this state instruction."""
  1122. return "RE"
  1123. def get_arguments(self):
  1124. """Gets this state instruction's argument list."""
  1125. return [self.node_id]
  1126. class ReadOutgoingEdgesInstruction(StateInstruction):
  1127. """An instruction that reads all outgoing edges for a node."""
  1128. def __init__(self, node_id):
  1129. StateInstruction.__init__(self)
  1130. self.node_id = node_id
  1131. def get_result_type_impl(self):
  1132. """Gets the type of value produced by this instruction."""
  1133. return PRIMITIVE_RESULT_TYPE
  1134. def get_opcode(self):
  1135. """Gets the opcode for this state instruction."""
  1136. return "RO"
  1137. def get_arguments(self):
  1138. """Gets this state instruction's argument list."""
  1139. return [self.node_id]
  1140. class ReadIncomingEdgesInstruction(StateInstruction):
  1141. """An instruction that reads all incoming edges for a node."""
  1142. def __init__(self, node_id):
  1143. StateInstruction.__init__(self)
  1144. self.node_id = node_id
  1145. def get_result_type_impl(self):
  1146. """Gets the type of value produced by this instruction."""
  1147. return PRIMITIVE_RESULT_TYPE
  1148. def get_opcode(self):
  1149. """Gets the opcode for this state instruction."""
  1150. return "RI"
  1151. def get_arguments(self):
  1152. """Gets this state instruction's argument list."""
  1153. return [self.node_id]
  1154. class CreateNodeInstruction(StateInstruction):
  1155. """An instruction that creates an empty node."""
  1156. def get_opcode(self):
  1157. """Gets the opcode for this state instruction."""
  1158. return "CN"
  1159. def get_arguments(self):
  1160. """Gets this state instruction's argument list."""
  1161. return []
  1162. class CreateNodeWithValueInstruction(StateInstruction):
  1163. """An instruction that creates a node with a given value."""
  1164. def __init__(self, value):
  1165. StateInstruction.__init__(self)
  1166. self.value = value
  1167. def get_opcode(self):
  1168. """Gets the opcode for this state instruction."""
  1169. return "CNV"
  1170. def get_arguments(self):
  1171. """Gets this state instruction's argument list."""
  1172. return [self.value]
  1173. class CreateEdgeInstruction(StateInstruction):
  1174. """An instruction that creates an edge."""
  1175. def __init__(self, source_id, target_id):
  1176. StateInstruction.__init__(self)
  1177. self.source_id = source_id
  1178. self.target_id = target_id
  1179. def get_opcode(self):
  1180. """Gets the opcode for this state instruction."""
  1181. return "CE"
  1182. def get_arguments(self):
  1183. """Gets this state instruction's argument list."""
  1184. return [self.source_id, self.target_id]
  1185. class CreateDictionaryEdgeInstruction(StateInstruction):
  1186. """An instruction that creates a dictionary edge."""
  1187. def __init__(self, source_id, key, target_id):
  1188. StateInstruction.__init__(self)
  1189. self.source_id = source_id
  1190. self.key = key
  1191. self.target_id = target_id
  1192. def get_opcode(self):
  1193. """Gets the opcode for this state instruction."""
  1194. return "CD"
  1195. def get_arguments(self):
  1196. """Gets this state instruction's argument list."""
  1197. return [self.source_id, self.key, self.target_id]
  1198. class DeleteNodeInstruction(StateInstruction):
  1199. """An instruction that deletes a node."""
  1200. def __init__(self, node_id):
  1201. StateInstruction.__init__(self)
  1202. self.node_id = node_id
  1203. def get_result_type_impl(self):
  1204. """Gets the type of value produced by this instruction."""
  1205. return NO_RESULT_TYPE
  1206. def get_opcode(self):
  1207. """Gets the opcode for this state instruction."""
  1208. return "DN"
  1209. def get_arguments(self):
  1210. """Gets this state instruction's argument list."""
  1211. return [self.node_id]
  1212. class DeleteEdgeInstruction(StateInstruction):
  1213. """An instruction that deletes an edge."""
  1214. def __init__(self, edge_id):
  1215. StateInstruction.__init__(self)
  1216. self.edge_id = edge_id
  1217. def get_result_type_impl(self):
  1218. """Gets the type of value produced by this instruction."""
  1219. return NO_RESULT_TYPE
  1220. def get_opcode(self):
  1221. """Gets the opcode for this state instruction."""
  1222. return "DE"
  1223. def get_arguments(self):
  1224. """Gets this state instruction's argument list."""
  1225. return [self.edge_id]
  1226. def create_block(*statements):
  1227. """Creates a block-statement from the given list of statements."""
  1228. length = len(statements)
  1229. if length == 0:
  1230. return EmptyInstruction()
  1231. elif length == 1:
  1232. return statements[0]
  1233. else:
  1234. return CompoundInstruction(
  1235. statements[0],
  1236. create_block(*statements[1:]))
  1237. def create_jit_call(target, named_arguments, kwargs):
  1238. """Creates a call that abides by the JIT's calling convention."""
  1239. # A JIT call looks like this:
  1240. #
  1241. # target = ...
  1242. # arg_dict = { ... }
  1243. # arg_dict.update(kwargs)
  1244. # result, = yield [("CALL_KWARGS", [target, arg_dict])]
  1245. results = []
  1246. if target.has_definition():
  1247. target_tmp = StoreLocalInstruction(None, target)
  1248. results.append(target_tmp)
  1249. target = target_tmp.create_load()
  1250. arg_dict = StoreLocalInstruction(
  1251. None,
  1252. DictionaryLiteralInstruction(
  1253. [(LiteralInstruction(key), val) for key, val in named_arguments]))
  1254. results.append(arg_dict)
  1255. results.append(
  1256. CallInstruction(
  1257. LoadMemberInstruction(arg_dict.create_load(), 'update'),
  1258. [kwargs]))
  1259. return CompoundInstruction(
  1260. create_block(*results),
  1261. RunGeneratorFunctionInstruction(
  1262. target, arg_dict.create_load(), NODE_RESULT_TYPE))
  1263. def evaluate_and_load(value):
  1264. """Creates a statement that evaluates the given tree, and creates
  1265. an expression that loads the result. These instructions are returned
  1266. as a pair of trees."""
  1267. if isinstance(value, (LoadLocalInstruction, LiteralInstruction)):
  1268. return EmptyInstruction(), value
  1269. else:
  1270. store = StoreLocalInstruction(None, value)
  1271. return IgnoreInstruction(store), store.create_load()
  1272. def create_new_local_node(local_variable, connected_node, edge_variable=None):
  1273. """Creates a local node that is the backing storage for a local variable.
  1274. This node is connected to a given node to make sure it's not perceived
  1275. as dead by the GC. The newly created node is stored in the given
  1276. local variable. The edge's id can also optionally be stored in a variable."""
  1277. local_store = StoreLocalInstruction(local_variable, CreateNodeInstruction())
  1278. create_edge = CreateEdgeInstruction(connected_node, local_store.create_load())
  1279. if edge_variable is not None:
  1280. create_edge = StoreLocalInstruction(edge_variable, create_edge)
  1281. return create_block(IgnoreInstruction(local_store), IgnoreInstruction(create_edge))
  1282. def map_instruction_tree_top_down(function, instruction):
  1283. """Applies the given mapping function to every instruction in the tree
  1284. that has the given instruction as root. The map is applied in a top-down
  1285. fashion."""
  1286. mapped_instruction = function(instruction)
  1287. return mapped_instruction.create(
  1288. [map_instruction_tree_top_down(function, child)
  1289. for child in mapped_instruction.get_children()])
  1290. def map_and_simplify(function, instruction):
  1291. """Applies the given mapping function to every instruction in the tree
  1292. that has the given instruction as root, and simplifies it on-the-fly.
  1293. The map is applied in a bottom-up fashion.
  1294. This is at least as powerful as first mapping and then simplifying, as
  1295. maps and simplifications are interspersed."""
  1296. return function(
  1297. instruction.create(
  1298. [map_and_simplify(function, child)
  1299. for child in instruction.get_children()])).simplify_node()
  1300. def iterate_as_stack(instruction, stack_iterator):
  1301. """Iterates over the given instruction and its children in the order in which temporaries are
  1302. 'pushed' on and 'popped' from a virtual evaluation stack."""
  1303. if isinstance(instruction, SelectInstruction):
  1304. iterate_as_stack(instruction.condition, stack_iterator)
  1305. stack_iterator.pop()
  1306. if_iterator, else_iterator = stack_iterator.branch(), stack_iterator.branch()
  1307. iterate_as_stack(instruction.if_clause, if_iterator)
  1308. iterate_as_stack(instruction.else_clause, else_iterator)
  1309. stack_iterator.merge(if_iterator, else_iterator)
  1310. elif isinstance(instruction, CompoundInstruction):
  1311. iterate_as_stack(instruction.first, stack_iterator)
  1312. if instruction.second.has_result():
  1313. stack_iterator.pop()
  1314. iterate_as_stack(instruction.second, stack_iterator)
  1315. if not instruction.second.has_result():
  1316. stack_iterator.pop()
  1317. else:
  1318. children = instruction.get_children()
  1319. for child in children:
  1320. # Push all children onto the stack.
  1321. iterate_as_stack(child, stack_iterator)
  1322. for child in children:
  1323. # Pop all children from the stack.
  1324. stack_iterator.pop()
  1325. # Push the instruction.
  1326. stack_iterator.push(instruction)
  1327. class StackIterator(object):
  1328. """A base class for stack iterators."""
  1329. def __init__(self, stack=None):
  1330. self.stack = [] if stack is None else stack
  1331. def pop(self):
  1332. """Pops an instruction from the stack."""
  1333. self.stack.pop()
  1334. def push(self, instruction):
  1335. """Pushes an instruction onto the stack."""
  1336. self.stack.append(set([instruction]))
  1337. def branch(self):
  1338. """Creates a copy of this stack iterator."""
  1339. return self.create(self.copy_stack())
  1340. def merge(self, *branches):
  1341. """Sets this stack iterator's stack to the union of the given branches."""
  1342. self.__init__(self.merge_stacks(*branches))
  1343. def copy_stack(self):
  1344. """Creates a copy of this stack iterator's stack."""
  1345. return [set(vals) for vals in self.stack]
  1346. def create(self, new_stack):
  1347. """Creates a stack iterator from the given stack"""
  1348. return type(self)(new_stack)
  1349. def merge_stacks(self, *branches):
  1350. """Computes the union of the stacks of the given branches."""
  1351. results = None
  1352. for branch in branches:
  1353. if results is None:
  1354. results = branch.copy_stack()
  1355. else:
  1356. assert len(branch.stack) == len(results)
  1357. results = [set.union(*t) for t in zip(branch.stack, results)]
  1358. return results
  1359. def protect_temporaries_from_gc(instruction, connected_node):
  1360. """Protects temporaries from the garbage collector by connecting them to the given node."""
  1361. # # The reasoning behind this function
  1362. #
  1363. # A nop instruction (`yield None`) may trigger the garbage collector, which will delete
  1364. # unreachable ("dead") vertices and edges. Now take into account that a bare temporary node
  1365. # is actually unreachable from the root node. The consequence is that temporary nodes
  1366. # may be garbage-collected if a nop instruction is executed while they are on the evaluation
  1367. # "stack." This is _never_ what we want.
  1368. #
  1369. # To counter this, we can connect temporary nodes to a node that is reachable from the root.
  1370. # However, we only want to create edges between edges and a known reachable node if we really
  1371. # have to, because creating edges incurs some overhead.
  1372. #
  1373. # We will create an edge between a temporary and the known reachable node if and only if the
  1374. # temporary is on the "stack" when either a nop or a call instruction is executed.
  1375. class GCStackIterator(StackIterator):
  1376. """A stack iterator that detects which instructions might be at risk of getting garbage
  1377. collected."""
  1378. def __init__(self, stack=None, gc_temporaries=None):
  1379. StackIterator.__init__(self, stack)
  1380. self.gc_temporaries = set() if gc_temporaries is None else gc_temporaries
  1381. def push(self, instruction):
  1382. """Pushes an instruction onto the stack."""
  1383. if isinstance(instruction, (
  1384. NopInstruction,
  1385. RunGeneratorFunctionInstruction,
  1386. RunTailGeneratorFunctionInstruction)):
  1387. # All values currently on the stack are at risk. Mark them as such.
  1388. for instruction_set in self.stack:
  1389. self.gc_temporaries.update(instruction_set)
  1390. # Proceed.
  1391. StackIterator.push(self, instruction)
  1392. def merge(self, *branches):
  1393. """Sets this stack iterator's stack to the union of the given branches."""
  1394. self.__init__(
  1395. self.merge_stacks(*branches),
  1396. set.union(*[br.gc_temporaries for br in branches]))
  1397. def create(self, new_stack):
  1398. """Creates a stack iterator from the given stack"""
  1399. return GCStackIterator(new_stack, self.gc_temporaries)
  1400. # Find out which instructions are at risk.
  1401. gc_iterator = GCStackIterator()
  1402. iterate_as_stack(instruction, gc_iterator)
  1403. # These temporaries need to be protected from the GC.
  1404. gc_temporaries = gc_iterator.gc_temporaries
  1405. def protect_result(instruction):
  1406. """Protects the given instruction's (temporary) result."""
  1407. if instruction in gc_temporaries and instruction.get_result_type() == NODE_RESULT_TYPE:
  1408. gc_temporaries.remove(instruction)
  1409. store_instr = StoreLocalInstruction(None, instruction)
  1410. return CompoundInstruction(
  1411. store_instr,
  1412. CompoundInstruction(
  1413. SelectInstruction(
  1414. BinaryInstruction(
  1415. store_instr.create_load(), 'is not', LiteralInstruction(None)),
  1416. CreateEdgeInstruction(connected_node, store_instr.create_load()),
  1417. EmptyInstruction()),
  1418. store_instr.create_load()))
  1419. else:
  1420. return instruction
  1421. return map_instruction_tree_top_down(protect_result, instruction)
  1422. if __name__ == "__main__":
  1423. example_tree = SelectInstruction(
  1424. LiteralInstruction(True),
  1425. LoopInstruction(
  1426. CompoundInstruction(
  1427. BreakInstruction(),
  1428. CompoundInstruction(
  1429. EmptyInstruction(),
  1430. ContinueInstruction()
  1431. )
  1432. )
  1433. ),
  1434. ReturnInstruction(
  1435. EmptyInstruction()))
  1436. print(example_tree.simplify())