tree_ir.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660
  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 ReturnInstruction(self.value.simplify())
  162. def generate_python_def(self, code_generator):
  163. """Generates Python code for this instruction."""
  164. self.value.generate_python_def(code_generator)
  165. code_generator.append_line(
  166. 'raise PrimitiveFinished(' +
  167. self.value.generate_python_use(code_generator) +
  168. ')')
  169. class RaiseInstruction(VoidInstruction):
  170. """An instruction that raises an error."""
  171. def __init__(self, value):
  172. VoidInstruction.__init__(self)
  173. self.value = value
  174. def simplify(self):
  175. """Applies basic simplification to this instruction and its children."""
  176. return RaiseInstruction(self.value.simplify())
  177. def generate_python_def(self, code_generator):
  178. """Generates Python code for this instruction."""
  179. self.value.generate_python_def(code_generator)
  180. code_generator.append_line(
  181. 'raise ' + self.value.generate_python_use(code_generator))
  182. class CallInstruction(Instruction):
  183. """An instruction that performs a simple call."""
  184. def __init__(self, target, argument_list):
  185. Instruction.__init__(self)
  186. self.target = target
  187. self.argument_list = argument_list
  188. def simplify(self):
  189. """Applies basic simplification to this instruction and its children."""
  190. return CallInstruction(
  191. self.target.simplify(),
  192. [arg.simplify() for arg in self.argument_list])
  193. def generate_python_def(self, code_generator):
  194. """Generates Python code for this instruction."""
  195. if self.target.has_definition():
  196. self.target.generate_python_def(code_generator)
  197. for arg in self.argument_list:
  198. if arg.has_definition():
  199. arg.generate_python_def(code_generator)
  200. code_generator.append_line(
  201. '%s = %s(%s) ' % (
  202. code_generator.get_result_name(self),
  203. self.target.generate_python_use(code_generator),
  204. [arg.generate_python_use(code_generator) for arg in self.argument_list]))
  205. class BinaryInstruction(Instruction):
  206. """An instruction that performs a binary operation."""
  207. def __init__(self, lhs, operator, rhs):
  208. Instruction.__init__(self)
  209. self.lhs = lhs
  210. self.operator = operator
  211. self.rhs = rhs
  212. def has_definition(self):
  213. """Tells if this instruction requires a definition."""
  214. return self.lhs.has_definition() or self.rhs.has_definition()
  215. def simplify(self):
  216. """Applies basic simplification to this instruction and its children."""
  217. simple_lhs, simple_rhs = self.lhs.simplify(), self.rhs.simplify()
  218. return BinaryInstruction(simple_lhs, self.operator, simple_rhs)
  219. def generate_python_use(self, code_generator):
  220. """Generates a Python expression that retrieves this instruction's
  221. result. The expression is returned as a string."""
  222. return '%s %s %s' % (
  223. self.lhs.generate_python_use(code_generator),
  224. self.operator,
  225. self.rhs.generate_python_use(code_generator))
  226. def generate_python_def(self, code_generator):
  227. """Generates a Python statement that executes this instruction.
  228. The statement is appended immediately to the code generator."""
  229. if self.lhs.has_definition():
  230. self.lhs.generate_python_def(code_generator)
  231. if self.rhs.has_definition():
  232. self.rhs.generate_python_def(code_generator)
  233. elif self.rhs.has_definition():
  234. self.rhs.generate_python_def(code_generator)
  235. else:
  236. code_generator.append_line('pass')
  237. class LoopInstruction(VoidInstruction):
  238. """Represents a loop-instruction, which loops until broken."""
  239. def __init__(self, body):
  240. VoidInstruction.__init__(self)
  241. self.body = body
  242. def simplify(self):
  243. """Applies basic simplification to this instruction and its children."""
  244. return LoopInstruction(self.body.simplify())
  245. def generate_python_def(self, code_generator):
  246. """Generates Python code for this instruction."""
  247. code_generator.append_line('while True:')
  248. code_generator.increase_indentation()
  249. self.body.generate_python_def(code_generator)
  250. code_generator.decrease_indentation()
  251. class BreakInstruction(VoidInstruction):
  252. """Represents a break-instruction."""
  253. def generate_python_def(self, code_generator):
  254. """Generates Python code for this instruction."""
  255. code_generator.append_line('break')
  256. class ContinueInstruction(VoidInstruction):
  257. """Represents a continue-instruction."""
  258. def generate_python_def(self, code_generator):
  259. """Generates Python code for this instruction."""
  260. code_generator.append_line('continue')
  261. class CompoundInstruction(Instruction):
  262. """Represents an instruction that evaluates two other instructions
  263. in order, and returns the second instruction's result."""
  264. def __init__(self, first, second):
  265. Instruction.__init__(self)
  266. self.first = first
  267. self.second = second
  268. def has_result(self):
  269. """Tells if this instruction has a result."""
  270. return self.second.has_result()
  271. def simplify(self):
  272. """Applies basic simplification to this instruction and its children."""
  273. simple_fst, simple_snd = self.first.simplify(), self.second.simplify()
  274. if not simple_fst.has_definition():
  275. return simple_snd
  276. elif (not simple_snd.has_definition()) and (not simple_snd.has_result()):
  277. return simple_fst
  278. else:
  279. return CompoundInstruction(simple_fst, simple_snd)
  280. def generate_python_def(self, code_generator):
  281. """Generates Python code for this instruction."""
  282. self.first.generate_python_def(code_generator)
  283. self.second.generate_python_def(code_generator)
  284. if self.has_result():
  285. code_generator.append_definition(self, self.second)
  286. class LiteralInstruction(Instruction):
  287. """Represents an integer, floating-point, string or Boolean literal."""
  288. def __init__(self, literal):
  289. Instruction.__init__(self)
  290. self.literal = literal
  291. def has_definition(self):
  292. """Tells if this instruction requires a definition."""
  293. return False
  294. def generate_python_use(self, code_generator):
  295. """Generates a Python expression that retrieves this instruction's
  296. result. The expression is returned as a string."""
  297. return repr(self.literal)
  298. class StateInstruction(Instruction):
  299. """An instruction that accesses the modelverse state."""
  300. def get_opcode(self):
  301. """Gets the opcode for this state instruction."""
  302. raise NotImplementedError()
  303. def get_arguments(self):
  304. """Gets this state instruction's argument list."""
  305. raise NotImplementedError()
  306. def generate_python_def(self, code_generator):
  307. """Generates a Python statement that executes this instruction.
  308. The statement is appended immediately to the code generator."""
  309. args = self.get_arguments()
  310. for arg_i in args:
  311. if arg_i.has_definition():
  312. arg_i.generate_python_def(code_generator)
  313. code_generator.append_state_definition(self, self.get_opcode(), args)
  314. class LocalInstruction(Instruction):
  315. """A base class for instructions that access local variables."""
  316. def __init__(self, name):
  317. Instruction.__init__(self)
  318. self.name = name
  319. def create_load(self):
  320. """Creates an instruction that loads the variable referenced by this instruction."""
  321. return LoadLocalInstruction(self.name)
  322. def create_store(self, value):
  323. """Creates an instruction that stores the given value in the variable referenced
  324. by this instruction."""
  325. return StoreLocalInstruction(self.name, value)
  326. def generate_python_use(self, code_generator):
  327. """Generates a Python expression that retrieves this instruction's
  328. result. The expression is returned as a string."""
  329. return self.name
  330. class StoreLocalInstruction(LocalInstruction):
  331. """An instruction that stores a value in a local variable."""
  332. def __init__(self, name, value):
  333. LocalInstruction.__init__(self, name)
  334. self.value = value
  335. def simplify(self):
  336. """Applies basic simplification to this instruction and its children."""
  337. return StoreLocalInstruction(self.name, self.value.simplify())
  338. def generate_python_def(self, code_generator):
  339. """Generates a Python statement that executes this instruction.
  340. The statement is appended immediately to the code generator."""
  341. if self.value.has_definition():
  342. self.value.generate_python_def(code_generator)
  343. code_generator.append_line(
  344. '%s = %s' % (self.name, self.value.generate_python_use(code_generator)))
  345. class LoadLocalInstruction(LocalInstruction):
  346. """An instruction that loads a value from a local variable."""
  347. def has_definition(self):
  348. """Tells if this instruction requires a definition."""
  349. return False
  350. class DefineFunctionInstruction(LocalInstruction):
  351. """An instruction that defines a function."""
  352. def __init__(self, name, parameter_list, body):
  353. LocalInstruction.__init__(self, name)
  354. self.parameter_list = parameter_list
  355. self.body = body
  356. def generate_python_def(self, code_generator):
  357. """Generates a Python statement that executes this instruction.
  358. The statement is appended immediately to the code generator."""
  359. code_generator.append_line('def %s(%s):' % (self.name, ', '.join(self.parameter_list)))
  360. code_generator.increase_indentation()
  361. self.body.generate_python_def(code_generator)
  362. code_generator.decrease_indentation()
  363. class LocalExistsInstruction(LocalInstruction):
  364. """An instruction that checks if a local variable exists."""
  365. def has_definition(self):
  366. """Tells if this instruction requires a definition."""
  367. return False
  368. def generate_python_use(self, code_generator):
  369. """Generates a Python expression that retrieves this instruction's
  370. result. The expression is returned as a string."""
  371. return '%s in locals()' % self.name
  372. class LoadIndexInstruction(Instruction):
  373. """An instruction that produces a value by indexing a specified expression with
  374. a given key."""
  375. def __init__(self, indexed, key):
  376. Instruction.__init__(self)
  377. self.indexed = indexed
  378. self.key = key
  379. def has_definition(self):
  380. """Tells if this instruction requires a definition."""
  381. return False
  382. def generate_python_use(self, code_generator):
  383. """Generates a Python expression that retrieves this instruction's
  384. result. The expression is returned as a string."""
  385. if self.indexed.has_definition():
  386. self.indexed.generate_python_def(code_generator)
  387. if self.key.has_definition():
  388. self.key.generate_python_def(code_generator)
  389. return "%s[%s]" % (
  390. self.indexed.generate_python_use(code_generator),
  391. self.key.generate_python_use(code_generator))
  392. class NopInstruction(Instruction):
  393. """A nop instruction, which allows for the kernel's thread of execution to be interrupted."""
  394. def has_result(self):
  395. """Tells if this instruction computes a result."""
  396. return False
  397. def generate_python_def(self, code_generator):
  398. """Generates a Python statement that executes this instruction.
  399. The statement is appended immediately to the code generator."""
  400. code_generator.append_line('yield %s' % repr(NOP_LITERAL))
  401. class ReadValueInstruction(StateInstruction):
  402. """An instruction that reads a value from a node."""
  403. def __init__(self, node_id):
  404. StateInstruction.__init__(self)
  405. self.node_id = node_id
  406. def simplify(self):
  407. """Applies basic simplification to this instruction and its children."""
  408. return ReadValueInstruction(self.node_id.simplify())
  409. def get_opcode(self):
  410. """Gets the opcode for this state instruction."""
  411. return "RV"
  412. def get_arguments(self):
  413. """Gets this state instruction's argument list."""
  414. return [self.node_id]
  415. class ReadDictionaryValueInstruction(StateInstruction):
  416. """An instruction that reads a dictionary value."""
  417. def __init__(self, node_id, key):
  418. StateInstruction.__init__(self)
  419. self.node_id = node_id
  420. self.key = key
  421. def simplify(self):
  422. """Applies basic simplification to this instruction and its children."""
  423. return ReadDictionaryValueInstruction(
  424. self.node_id.simplify(),
  425. self.key.simplify())
  426. def get_opcode(self):
  427. """Gets the opcode for this state instruction."""
  428. return "RD"
  429. def get_arguments(self):
  430. """Gets this state instruction's argument list."""
  431. return [self.node_id, self.key]
  432. class ReadDictionaryEdgeInstruction(StateInstruction):
  433. """An instruction that reads a dictionary edge."""
  434. def __init__(self, node_id, key):
  435. StateInstruction.__init__(self)
  436. self.node_id = node_id
  437. self.key = key
  438. def simplify(self):
  439. """Applies basic simplification to this instruction and its children."""
  440. return ReadDictionaryEdgeInstruction(
  441. self.node_id.simplify(),
  442. self.key.simplify())
  443. def get_opcode(self):
  444. """Gets the opcode for this state instruction."""
  445. return "RDE"
  446. def get_arguments(self):
  447. """Gets this state instruction's argument list."""
  448. return [self.node_id, self.key]
  449. class CreateNodeInstruction(StateInstruction):
  450. """An instruction that creates an empty node."""
  451. def get_opcode(self):
  452. """Gets the opcode for this state instruction."""
  453. return "CN"
  454. def get_arguments(self):
  455. """Gets this state instruction's argument list."""
  456. return []
  457. class CreateDictionaryEdgeInstruction(StateInstruction):
  458. """An instruction that creates a dictionary edge."""
  459. def __init__(self, source_id, key, target_id):
  460. StateInstruction.__init__(self)
  461. self.source_id = source_id
  462. self.key = key
  463. self.target_id = target_id
  464. def simplify(self):
  465. """Applies basic simplification to this instruction and its children."""
  466. return CreateDictionaryEdgeInstruction(
  467. self.source_id.simplify(),
  468. self.key.simplify(),
  469. self.target_id.simplify())
  470. def get_opcode(self):
  471. """Gets the opcode for this state instruction."""
  472. return "CD"
  473. def get_arguments(self):
  474. """Gets this state instruction's argument list."""
  475. return [self.source_id, self.key, self.target_id]
  476. class DeleteEdgeInstruction(StateInstruction):
  477. """An instruction that deletes an edge."""
  478. def __init__(self, edge_id):
  479. StateInstruction.__init__(self)
  480. self.edge_id = edge_id
  481. def simplify(self):
  482. """Applies basic simplification to this instruction and its children."""
  483. return DeleteEdgeInstruction(self.edge_id.simplify())
  484. def has_result(self):
  485. """Tells if this instruction computes a result."""
  486. return False
  487. def get_opcode(self):
  488. """Gets the opcode for this state instruction."""
  489. return "DE"
  490. def get_arguments(self):
  491. """Gets this state instruction's argument list."""
  492. return [self.edge_id]
  493. def create_block(*statements):
  494. """Creates a block-statement from the given list of statements."""
  495. length = len(statements)
  496. if length == 0:
  497. return EmptyInstruction()
  498. elif length == 1:
  499. return statements[0]
  500. else:
  501. return CompoundInstruction(
  502. statements[0],
  503. create_block(*statements[1:]))
  504. if __name__ == "__main__":
  505. example_tree = SelectInstruction(
  506. LiteralInstruction(True),
  507. LoopInstruction(
  508. CompoundInstruction(
  509. BreakInstruction(),
  510. CompoundInstruction(
  511. EmptyInstruction(),
  512. ContinueInstruction()
  513. )
  514. )
  515. ),
  516. ReturnInstruction(
  517. EmptyInstruction()))
  518. print(example_tree.simplify())