tree_ir.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562
  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. NOP_LITERAL = None
  27. """A literal that results in a nop during which execution may be interrupted
  28. when yielded."""
  29. class Instruction(object):
  30. """A base class for instructions. An instruction is essentially a syntax
  31. node that must first be defined, and can only then be used."""
  32. def __init__(self):
  33. pass
  34. def has_result(self):
  35. """Tells if this instruction computes a result."""
  36. return True
  37. def has_definition(self):
  38. """Tells if this instruction requires a definition."""
  39. return True
  40. def generate_python_def(self, code_generator):
  41. """Generates a Python statement that executes this instruction.
  42. The statement is appended immediately to the code generator."""
  43. if self.has_definition():
  44. raise NotImplementedError()
  45. else:
  46. code_generator.append_line('pass')
  47. def generate_python_use(self, code_generator):
  48. """Generates a Python expression that retrieves this instruction's
  49. result. The expression is returned as a string."""
  50. if self.has_result():
  51. return code_generator.get_result_name(self)
  52. else:
  53. return 'None'
  54. def simplify(self):
  55. """Applies basic simplification to this instruction and its children."""
  56. return self
  57. def __str__(self):
  58. code_generator = PythonGenerator()
  59. self.generate_python_def(code_generator)
  60. return code_generator.code
  61. class PythonGenerator(object):
  62. """Generates Python code from instructions."""
  63. def __init__(self):
  64. self.code = ''
  65. self.indentation_string = ' ' * 4
  66. self.indentation = 0
  67. self.result_value_dict = {}
  68. def append(self, text):
  69. """Appends the given string to this code generator."""
  70. self.code += text
  71. def append_indentation(self):
  72. """Appends indentation to the code generator."""
  73. self.append(self.indentation_string * self.indentation)
  74. def append_line(self, line=None):
  75. """Appends the indentation string followed by the given string (if any)
  76. and a newline to the code generator."""
  77. self.append_indentation()
  78. if line is not None:
  79. self.append(line)
  80. self.append('\n')
  81. def increase_indentation(self):
  82. """Increases the code generator's indentation by one indent."""
  83. self.indentation += 1
  84. def decrease_indentation(self):
  85. """Decreases the code generator's indentation by one indent."""
  86. self.indentation -= 1
  87. def get_result_name(self, instruction):
  88. """Gets the name of the given instruction's result variable."""
  89. if instruction not in self.result_value_dict:
  90. self.result_value_dict[instruction] = \
  91. 'tmp' + str(len(self.result_value_dict))
  92. return self.result_value_dict[instruction]
  93. def append_definition(self, lhs, rhs):
  94. """Defines the first instruction's result variable as the second
  95. instruction's result."""
  96. self.append_line(
  97. self.get_result_name(lhs) + ' = ' + rhs.generate_python_use(self))
  98. def append_state_definition(self, lhs, opcode, args):
  99. """Appends a definition that queries the modelverse state."""
  100. self.append_line(
  101. "%s, = yield [('%s', [%s])]" % (
  102. self.get_result_name(lhs),
  103. opcode,
  104. ', '.join([arg_i.generate_python_use(self) for arg_i in args])))
  105. class VoidInstruction(Instruction):
  106. """A base class for instructions that do not return a value."""
  107. def has_result(self):
  108. """Tells if this instruction computes a result."""
  109. return False
  110. class EmptyInstruction(VoidInstruction):
  111. """Represents the empty instruction, which does nothing."""
  112. def has_definition(self):
  113. """Tells if this instruction requires a definition."""
  114. return False
  115. class SelectInstruction(Instruction):
  116. """Represents a select-instruction: an instruction that defines one of two
  117. child instructions, and sets its result to the defined child's result."""
  118. def __init__(self, condition, if_clause, else_clause):
  119. Instruction.__init__(self)
  120. self.condition = condition
  121. self.if_clause = if_clause
  122. self.else_clause = else_clause
  123. def has_result(self):
  124. """Tells if this instruction computes a result."""
  125. return self.if_clause.has_result() or self.else_clause.has_result()
  126. def simplify(self):
  127. """Applies basic simplification to this instruction and its children."""
  128. simple_cond = self.condition.simplify()
  129. simple_if = self.if_clause.simplify()
  130. simple_else = self.else_clause.simplify()
  131. if isinstance(simple_cond, LiteralInstruction):
  132. return simple_if if simple_cond.literal else simple_else
  133. else:
  134. return SelectInstruction(simple_cond, simple_if, simple_else)
  135. def generate_python_def(self, code_generator):
  136. """Generates Python code for this instruction."""
  137. if_has_result = self.has_result()
  138. if self.condition.has_definition():
  139. self.condition.generate_python_def(code_generator)
  140. code_generator.append_line(
  141. 'if ' + self.condition.generate_python_use(code_generator) + ':')
  142. code_generator.increase_indentation()
  143. self.if_clause.generate_python_def(code_generator)
  144. if if_has_result:
  145. code_generator.append_definition(self, self.if_clause)
  146. code_generator.decrease_indentation()
  147. if self.else_clause.has_definition() or if_has_result:
  148. code_generator.append_line('else:')
  149. code_generator.increase_indentation()
  150. self.else_clause.generate_python_def(code_generator)
  151. if if_has_result:
  152. code_generator.append_definition(self, self.else_clause)
  153. code_generator.decrease_indentation()
  154. class ReturnInstruction(VoidInstruction):
  155. """Represents a return-instruction."""
  156. def __init__(self, value):
  157. VoidInstruction.__init__(self)
  158. self.value = value
  159. def simplify(self):
  160. """Applies basic simplification to this instruction and its children."""
  161. return LoopInstruction(self.value.simplify())
  162. def generate_python_def(self, code_generator):
  163. """Generates Python code for this instruction."""
  164. code_generator.append_line(
  165. 'raise PrimitiveFinished(' +
  166. self.value.generate_python_use(code_generator) +
  167. ')')
  168. class LoopInstruction(VoidInstruction):
  169. """Represents a loop-instruction, which loops until broken."""
  170. def __init__(self, body):
  171. VoidInstruction.__init__(self)
  172. self.body = body
  173. def simplify(self):
  174. """Applies basic simplification to this instruction and its children."""
  175. return LoopInstruction(self.body.simplify())
  176. def generate_python_def(self, code_generator):
  177. """Generates Python code for this instruction."""
  178. code_generator.append_line('while True:')
  179. code_generator.increase_indentation()
  180. self.body.generate_python_def(code_generator)
  181. code_generator.decrease_indentation()
  182. class BreakInstruction(VoidInstruction):
  183. """Represents a break-instruction."""
  184. def generate_python_def(self, code_generator):
  185. """Generates Python code for this instruction."""
  186. code_generator.append_line('break')
  187. class ContinueInstruction(VoidInstruction):
  188. """Represents a continue-instruction."""
  189. def generate_python_def(self, code_generator):
  190. """Generates Python code for this instruction."""
  191. code_generator.append_line('continue')
  192. class CompoundInstruction(Instruction):
  193. """Represents an instruction that evaluates two other instructions
  194. in order, and returns the second instruction's result."""
  195. def __init__(self, first, second):
  196. Instruction.__init__(self)
  197. self.first = first
  198. self.second = second
  199. def has_result(self):
  200. """Tells if this instruction has a result."""
  201. return self.second.has_result()
  202. def simplify(self):
  203. """Applies basic simplification to this instruction and its children."""
  204. simple_fst, simple_snd = self.first.simplify(), self.second.simplify()
  205. if not simple_fst.has_definition():
  206. return simple_snd
  207. elif (not simple_snd.has_definition()) and (not simple_snd.has_result()):
  208. return simple_fst
  209. else:
  210. return CompoundInstruction(simple_fst, simple_snd)
  211. def generate_python_def(self, code_generator):
  212. """Generates Python code for this instruction."""
  213. self.first.generate_python_def(code_generator)
  214. self.second.generate_python_def(code_generator)
  215. if self.has_result():
  216. code_generator.append_definition(self, self.second)
  217. class LiteralInstruction(Instruction):
  218. """Represents an integer, floating-point, string or Boolean literal."""
  219. def __init__(self, literal):
  220. Instruction.__init__(self)
  221. self.literal = literal
  222. def has_definition(self):
  223. """Tells if this instruction requires a definition."""
  224. return False
  225. def generate_python_use(self, code_generator):
  226. """Generates a Python expression that retrieves this instruction's
  227. result. The expression is returned as a string."""
  228. return repr(self.literal)
  229. class StateInstruction(Instruction):
  230. """An instruction that accesses the modelverse state."""
  231. def get_opcode(self):
  232. """Gets the opcode for this state instruction."""
  233. raise NotImplementedError()
  234. def get_arguments(self):
  235. """Gets this state instruction's argument list."""
  236. raise NotImplementedError()
  237. def generate_python_def(self, code_generator):
  238. """Generates a Python statement that executes this instruction.
  239. The statement is appended immediately to the code generator."""
  240. args = self.get_arguments()
  241. for arg_i in args:
  242. if arg_i.has_definition():
  243. arg_i.generate_python_def(code_generator)
  244. code_generator.append_state_definition(self, self.get_opcode(), args)
  245. class LocalInstruction(Instruction):
  246. """A base class for instructions that access local variables."""
  247. def __init__(self, name):
  248. Instruction.__init__(self)
  249. self.name = name
  250. def create_load(self):
  251. """Creates an instruction that loads the variable referenced by this instruction."""
  252. return LoadLocalInstruction(self.name)
  253. def generate_python_use(self, code_generator):
  254. """Generates a Python expression that retrieves this instruction's
  255. result. The expression is returned as a string."""
  256. return self.name
  257. class StoreLocalInstruction(LocalInstruction):
  258. """An instruction that stores a value in a local variable."""
  259. def __init__(self, name, value):
  260. LocalInstruction.__init__(self, name)
  261. self.value = value
  262. def simplify(self):
  263. """Applies basic simplification to this instruction and its children."""
  264. return StoreLocalInstruction(self.name, self.value.simplify())
  265. def generate_python_def(self, code_generator):
  266. """Generates a Python statement that executes this instruction.
  267. The statement is appended immediately to the code generator."""
  268. if self.value.has_definition():
  269. self.value.generate_python_def(code_generator)
  270. code_generator.append_line(
  271. '%s = %s' % (self.name, self.value.generate_python_use(code_generator)))
  272. class LoadLocalInstruction(LocalInstruction):
  273. """An instruction that loads a value from a local variable."""
  274. def has_definition(self):
  275. """Tells if this instruction requires a definition."""
  276. return False
  277. class DefineFunctionInstruction(LocalInstruction):
  278. """An instruction that defines a function."""
  279. def __init__(self, name, parameter_list, body):
  280. LocalInstruction.__init__(self, name)
  281. self.parameter_list = parameter_list
  282. self.body = body
  283. def generate_python_def(self, code_generator):
  284. """Generates a Python statement that executes this instruction.
  285. The statement is appended immediately to the code generator."""
  286. code_generator.append_line('def %s(%s):' % (self.name, ', '.join(self.parameter_list)))
  287. code_generator.increase_indentation()
  288. self.body.generate_python_def(code_generator)
  289. code_generator.decrease_indentation()
  290. class LoadIndexInstruction(Instruction):
  291. """An instruction that produces a value by indexing a specified expression with
  292. a given key."""
  293. def __init__(self, indexed, key):
  294. Instruction.__init__(self)
  295. self.indexed = indexed
  296. self.key = key
  297. def has_definition(self):
  298. """Tells if this instruction requires a definition."""
  299. return False
  300. def generate_python_use(self, code_generator):
  301. """Generates a Python expression that retrieves this instruction's
  302. result. The expression is returned as a string."""
  303. if self.indexed.has_definition():
  304. self.indexed.generate_python_def(code_generator)
  305. if self.key.has_definition():
  306. self.key.generate_python_def(code_generator)
  307. return "%s[%s]" % (
  308. self.indexed.generate_python_use(code_generator),
  309. self.key.generate_python_use(code_generator))
  310. class NopInstruction(Instruction):
  311. """A nop instruction, which allows for the kernel's thread of execution to be interrupted."""
  312. def has_result(self):
  313. """Tells if this instruction computes a result."""
  314. return False
  315. def generate_python_def(self, code_generator):
  316. """Generates a Python statement that executes this instruction.
  317. The statement is appended immediately to the code generator."""
  318. code_generator.append_line('yield %s' % repr(NOP_LITERAL))
  319. class ReadValueInstruction(StateInstruction):
  320. """An instruction that reads a value from a node."""
  321. def __init__(self, node_id):
  322. StateInstruction.__init__(self)
  323. self.node_id = node_id
  324. def simplify(self):
  325. """Applies basic simplification to this instruction and its children."""
  326. return ReadValueInstruction(self.node_id.simplify())
  327. def get_opcode(self):
  328. """Gets the opcode for this state instruction."""
  329. return "RV"
  330. def get_arguments(self):
  331. """Gets this state instruction's argument list."""
  332. return [self.node_id]
  333. class ReadDictionaryValueInstruction(StateInstruction):
  334. """An instruction that reads a dictionary value."""
  335. def __init__(self, node_id, key):
  336. StateInstruction.__init__(self)
  337. self.node_id = node_id
  338. self.key = key
  339. def simplify(self):
  340. """Applies basic simplification to this instruction and its children."""
  341. return ReadDictionaryValueInstruction(
  342. self.node_id.simplify(),
  343. self.key.simplify())
  344. def get_opcode(self):
  345. """Gets the opcode for this state instruction."""
  346. return "RD"
  347. def get_arguments(self):
  348. """Gets this state instruction's argument list."""
  349. return [self.node_id, self.key]
  350. class ReadDictionaryEdgeInstruction(StateInstruction):
  351. """An instruction that reads a dictionary edge."""
  352. def __init__(self, node_id, key):
  353. StateInstruction.__init__(self)
  354. self.node_id = node_id
  355. self.key = key
  356. def simplify(self):
  357. """Applies basic simplification to this instruction and its children."""
  358. return ReadDictionaryEdgeInstruction(
  359. self.node_id.simplify(),
  360. self.key.simplify())
  361. def get_opcode(self):
  362. """Gets the opcode for this state instruction."""
  363. return "RDE"
  364. def get_arguments(self):
  365. """Gets this state instruction's argument list."""
  366. return [self.node_id, self.key]
  367. class CreateNodeInstruction(StateInstruction):
  368. """An instruction that creates an empty node."""
  369. def get_opcode(self):
  370. """Gets the opcode for this state instruction."""
  371. return "CN"
  372. def get_arguments(self):
  373. """Gets this state instruction's argument list."""
  374. return []
  375. class CreateDictionaryEdgeInstruction(StateInstruction):
  376. """An instruction that creates a dictionary edge."""
  377. def __init__(self, source_id, key, target_id):
  378. StateInstruction.__init__(self)
  379. self.source_id = source_id
  380. self.key = key
  381. self.target_id = target_id
  382. def simplify(self):
  383. """Applies basic simplification to this instruction and its children."""
  384. return CreateDictionaryEdgeInstruction(
  385. self.source_id.simplify(),
  386. self.key.simplify(),
  387. self.target_id.simplify())
  388. def get_opcode(self):
  389. """Gets the opcode for this state instruction."""
  390. return "CD"
  391. def get_arguments(self):
  392. """Gets this state instruction's argument list."""
  393. return [self.source_id, self.key, self.target_id]
  394. class DeleteEdgeInstruction(StateInstruction):
  395. """An instruction that deletes an edge."""
  396. def __init__(self, edge_id):
  397. StateInstruction.__init__(self)
  398. self.edge_id = edge_id
  399. def simplify(self):
  400. """Applies basic simplification to this instruction and its children."""
  401. return DeleteEdgeInstruction(self.edge_id.simplify())
  402. def has_result(self):
  403. """Tells if this instruction computes a result."""
  404. return False
  405. def get_opcode(self):
  406. """Gets the opcode for this state instruction."""
  407. return "DE"
  408. def get_arguments(self):
  409. """Gets this state instruction's argument list."""
  410. return [self.edge_id]
  411. def create_block(*statements):
  412. """Creates a block-statement from the given list of statements."""
  413. length = len(statements)
  414. if length == 0:
  415. return EmptyInstruction()
  416. elif length == 1:
  417. return statements[0]
  418. else:
  419. return CompoundInstruction(
  420. statements[0],
  421. create_block(*statements[1:]))
  422. if __name__ == "__main__":
  423. example_tree = SelectInstruction(
  424. LiteralInstruction(True),
  425. LoopInstruction(
  426. CompoundInstruction(
  427. BreakInstruction(),
  428. CompoundInstruction(
  429. EmptyInstruction(),
  430. ContinueInstruction()
  431. )
  432. )
  433. ),
  434. ReturnInstruction(
  435. EmptyInstruction()))
  436. print(example_tree.simplify())