tree_ir.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689
  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 get_result_name_override(self):
  41. """Gets a value that overrides the code generator's result name for this
  42. instruction if it is not None."""
  43. return None
  44. def generate_python_def(self, code_generator):
  45. """Generates a Python statement that executes this instruction.
  46. The statement is appended immediately to the code generator."""
  47. if self.has_definition():
  48. raise NotImplementedError()
  49. else:
  50. code_generator.append_line('pass')
  51. def generate_python_use(self, code_generator):
  52. """Generates a Python expression that retrieves this instruction's
  53. result. The expression is returned as a string."""
  54. if self.has_result():
  55. return code_generator.get_result_name(self)
  56. else:
  57. return 'None'
  58. def simplify(self):
  59. """Applies basic simplification to this instruction and its children."""
  60. return self
  61. def __str__(self):
  62. code_generator = PythonGenerator()
  63. self.generate_python_def(code_generator)
  64. return str(code_generator)
  65. class PythonGenerator(object):
  66. """Generates Python code from instructions."""
  67. def __init__(self):
  68. self.code = []
  69. self.indentation_string = ' ' * 4
  70. self.indentation = 0
  71. self.result_value_dict = {}
  72. def append(self, text):
  73. """Appends the given string to this code generator."""
  74. self.code.append(text)
  75. def append_indentation(self):
  76. """Appends indentation to the code generator."""
  77. self.append(self.indentation_string * self.indentation)
  78. def append_line(self, line=None):
  79. """Appends the indentation string followed by the given string (if any)
  80. and a newline to the code generator."""
  81. self.append_indentation()
  82. if line is not None:
  83. self.append(line)
  84. self.append('\n')
  85. def increase_indentation(self):
  86. """Increases the code generator's indentation by one indent."""
  87. self.indentation += 1
  88. def decrease_indentation(self):
  89. """Decreases the code generator's indentation by one indent."""
  90. self.indentation -= 1
  91. def get_result_name(self, instruction, advised_name=None):
  92. """Gets the name of the given instruction's result variable."""
  93. if instruction not in self.result_value_dict:
  94. override_name = instruction.get_result_name_override()
  95. if override_name is not None:
  96. self.result_value_dict[instruction] = override_name
  97. elif advised_name is not None:
  98. self.result_value_dict[instruction] = advised_name
  99. else:
  100. self.result_value_dict[instruction] = \
  101. 'tmp' + str(len(self.result_value_dict))
  102. return self.result_value_dict[instruction]
  103. def append_definition(self, lhs, rhs):
  104. """Defines the first instruction's result variable as the second
  105. instruction's result."""
  106. self.append_line(
  107. self.get_result_name(lhs) + ' = ' + rhs.generate_python_use(self))
  108. def append_move_definition(self, lhs, rhs):
  109. """First defines the second instruction, then defines the first
  110. instruction as the result of the second."""
  111. if rhs.has_definition():
  112. # Retrieve the result name for the lhs.
  113. lhs_result_name = self.get_result_name(lhs)
  114. # Encourage the rhs to take on the same result name as the lhs.
  115. rhs_result_name = self.get_result_name(rhs, lhs_result_name)
  116. # Generate the rhs' definition.
  117. rhs.generate_python_def(self)
  118. # Only perform an assignment if it's truly necessary.
  119. if lhs_result_name != rhs_result_name:
  120. self.append_definition(lhs, rhs)
  121. else:
  122. self.append_definition(lhs, rhs)
  123. def append_state_definition(self, lhs, opcode, args):
  124. """Appends a definition that queries the modelverse state."""
  125. self.append_line(
  126. "%s, = yield [('%s', [%s])]" % (
  127. self.get_result_name(lhs),
  128. opcode,
  129. ', '.join([arg_i.generate_python_use(self) for arg_i in args])))
  130. def __str__(self):
  131. return ''.join(self.code)
  132. class VoidInstruction(Instruction):
  133. """A base class for instructions that do not return a value."""
  134. def has_result(self):
  135. """Tells if this instruction computes a result."""
  136. return False
  137. class EmptyInstruction(VoidInstruction):
  138. """Represents the empty instruction, which does nothing."""
  139. def has_definition(self):
  140. """Tells if this instruction requires a definition."""
  141. return False
  142. class SelectInstruction(Instruction):
  143. """Represents a select-instruction: an instruction that defines one of two
  144. child instructions, and sets its result to the defined child's result."""
  145. def __init__(self, condition, if_clause, else_clause):
  146. Instruction.__init__(self)
  147. self.condition = condition
  148. self.if_clause = if_clause
  149. self.else_clause = else_clause
  150. def has_result(self):
  151. """Tells if this instruction computes a result."""
  152. return self.if_clause.has_result() or self.else_clause.has_result()
  153. def simplify(self):
  154. """Applies basic simplification to this instruction and its children."""
  155. simple_cond = self.condition.simplify()
  156. simple_if = self.if_clause.simplify()
  157. simple_else = self.else_clause.simplify()
  158. if isinstance(simple_cond, LiteralInstruction):
  159. return simple_if if simple_cond.literal else simple_else
  160. else:
  161. return SelectInstruction(simple_cond, simple_if, simple_else)
  162. def generate_python_def(self, code_generator):
  163. """Generates Python code for this instruction."""
  164. if_has_result = self.has_result()
  165. if self.condition.has_definition():
  166. self.condition.generate_python_def(code_generator)
  167. code_generator.append_line(
  168. 'if ' + self.condition.generate_python_use(code_generator) + ':')
  169. code_generator.increase_indentation()
  170. if if_has_result:
  171. code_generator.append_move_definition(self, self.if_clause)
  172. else:
  173. self.if_clause.generate_python_def(code_generator)
  174. code_generator.decrease_indentation()
  175. else_has_def = self.else_clause.has_definition()
  176. if else_has_def or if_has_result:
  177. code_generator.append_line('else:')
  178. code_generator.increase_indentation()
  179. if if_has_result:
  180. code_generator.append_move_definition(self, self.else_clause)
  181. else:
  182. self.else_clause.generate_python_def(code_generator)
  183. code_generator.decrease_indentation()
  184. class ReturnInstruction(VoidInstruction):
  185. """Represents a return-instruction."""
  186. def __init__(self, value):
  187. VoidInstruction.__init__(self)
  188. self.value = value
  189. def simplify(self):
  190. """Applies basic simplification to this instruction and its children."""
  191. return ReturnInstruction(self.value.simplify())
  192. def generate_python_def(self, code_generator):
  193. """Generates Python code for this instruction."""
  194. self.value.generate_python_def(code_generator)
  195. code_generator.append_line(
  196. 'raise PrimitiveFinished(' +
  197. self.value.generate_python_use(code_generator) +
  198. ')')
  199. class RaiseInstruction(VoidInstruction):
  200. """An instruction that raises an error."""
  201. def __init__(self, value):
  202. VoidInstruction.__init__(self)
  203. self.value = value
  204. def simplify(self):
  205. """Applies basic simplification to this instruction and its children."""
  206. return RaiseInstruction(self.value.simplify())
  207. def generate_python_def(self, code_generator):
  208. """Generates Python code for this instruction."""
  209. self.value.generate_python_def(code_generator)
  210. code_generator.append_line(
  211. 'raise ' + self.value.generate_python_use(code_generator))
  212. class CallInstruction(Instruction):
  213. """An instruction that performs a simple call."""
  214. def __init__(self, target, argument_list):
  215. Instruction.__init__(self)
  216. self.target = target
  217. self.argument_list = argument_list
  218. def simplify(self):
  219. """Applies basic simplification to this instruction and its children."""
  220. return CallInstruction(
  221. self.target.simplify(),
  222. [arg.simplify() for arg in self.argument_list])
  223. def generate_python_def(self, code_generator):
  224. """Generates Python code for this instruction."""
  225. if self.target.has_definition():
  226. self.target.generate_python_def(code_generator)
  227. for arg in self.argument_list:
  228. if arg.has_definition():
  229. arg.generate_python_def(code_generator)
  230. code_generator.append_line(
  231. '%s = %s(%s) ' % (
  232. code_generator.get_result_name(self),
  233. self.target.generate_python_use(code_generator),
  234. ', '.join([arg.generate_python_use(code_generator) for arg in self.argument_list])))
  235. class BinaryInstruction(Instruction):
  236. """An instruction that performs a binary operation."""
  237. def __init__(self, lhs, operator, rhs):
  238. Instruction.__init__(self)
  239. self.lhs = lhs
  240. self.operator = operator
  241. self.rhs = rhs
  242. def has_definition(self):
  243. """Tells if this instruction requires a definition."""
  244. return self.lhs.has_definition() or self.rhs.has_definition()
  245. def simplify(self):
  246. """Applies basic simplification to this instruction and its children."""
  247. simple_lhs, simple_rhs = self.lhs.simplify(), self.rhs.simplify()
  248. return BinaryInstruction(simple_lhs, self.operator, simple_rhs)
  249. def generate_python_use(self, code_generator):
  250. """Generates a Python expression that retrieves this instruction's
  251. result. The expression is returned as a string."""
  252. return '%s %s %s' % (
  253. self.lhs.generate_python_use(code_generator),
  254. self.operator,
  255. self.rhs.generate_python_use(code_generator))
  256. def generate_python_def(self, code_generator):
  257. """Generates a Python statement that executes this instruction.
  258. The statement is appended immediately to the code generator."""
  259. if self.lhs.has_definition():
  260. self.lhs.generate_python_def(code_generator)
  261. if self.rhs.has_definition():
  262. self.rhs.generate_python_def(code_generator)
  263. elif self.rhs.has_definition():
  264. self.rhs.generate_python_def(code_generator)
  265. else:
  266. code_generator.append_line('pass')
  267. class LoopInstruction(VoidInstruction):
  268. """Represents a loop-instruction, which loops until broken."""
  269. def __init__(self, body):
  270. VoidInstruction.__init__(self)
  271. self.body = body
  272. def simplify(self):
  273. """Applies basic simplification to this instruction and its children."""
  274. return LoopInstruction(self.body.simplify())
  275. def generate_python_def(self, code_generator):
  276. """Generates Python code for this instruction."""
  277. code_generator.append_line('while 1:')
  278. code_generator.increase_indentation()
  279. self.body.generate_python_def(code_generator)
  280. code_generator.decrease_indentation()
  281. class BreakInstruction(VoidInstruction):
  282. """Represents a break-instruction."""
  283. def generate_python_def(self, code_generator):
  284. """Generates Python code for this instruction."""
  285. code_generator.append_line('break')
  286. class ContinueInstruction(VoidInstruction):
  287. """Represents a continue-instruction."""
  288. def generate_python_def(self, code_generator):
  289. """Generates Python code for this instruction."""
  290. code_generator.append_line('continue')
  291. class CompoundInstruction(Instruction):
  292. """Represents an instruction that evaluates two other instructions
  293. in order, and returns the second instruction's result."""
  294. def __init__(self, first, second):
  295. Instruction.__init__(self)
  296. self.first = first
  297. self.second = second
  298. def has_result(self):
  299. """Tells if this instruction has a result."""
  300. return self.second.has_result()
  301. def simplify(self):
  302. """Applies basic simplification to this instruction and its children."""
  303. simple_fst, simple_snd = self.first.simplify(), self.second.simplify()
  304. if not simple_fst.has_definition():
  305. return simple_snd
  306. elif (not simple_snd.has_definition()) and (not simple_snd.has_result()):
  307. return simple_fst
  308. else:
  309. return CompoundInstruction(simple_fst, simple_snd)
  310. def generate_python_def(self, code_generator):
  311. """Generates Python code for this instruction."""
  312. self.first.generate_python_def(code_generator)
  313. code_generator.append_move_definition(self, self.second)
  314. class LiteralInstruction(Instruction):
  315. """Represents an integer, floating-point, string or Boolean literal."""
  316. def __init__(self, literal):
  317. Instruction.__init__(self)
  318. self.literal = literal
  319. def has_definition(self):
  320. """Tells if this instruction requires a definition."""
  321. return False
  322. def generate_python_use(self, code_generator):
  323. """Generates a Python expression that retrieves this instruction's
  324. result. The expression is returned as a string."""
  325. return repr(self.literal)
  326. class StateInstruction(Instruction):
  327. """An instruction that accesses the modelverse state."""
  328. def get_opcode(self):
  329. """Gets the opcode for this state instruction."""
  330. raise NotImplementedError()
  331. def get_arguments(self):
  332. """Gets this state instruction's argument list."""
  333. raise NotImplementedError()
  334. def generate_python_def(self, code_generator):
  335. """Generates a Python statement that executes this instruction.
  336. The statement is appended immediately to the code generator."""
  337. args = self.get_arguments()
  338. for arg_i in args:
  339. if arg_i.has_definition():
  340. arg_i.generate_python_def(code_generator)
  341. code_generator.append_state_definition(self, self.get_opcode(), args)
  342. class LocalInstruction(Instruction):
  343. """A base class for instructions that access local variables."""
  344. def __init__(self, name):
  345. Instruction.__init__(self)
  346. self.name = name
  347. def get_result_name_override(self):
  348. """Gets a value that overrides the code generator's result name for this
  349. instruction if it is not None."""
  350. return self.name
  351. def create_load(self):
  352. """Creates an instruction that loads the variable referenced by this instruction."""
  353. return LoadLocalInstruction(self.name)
  354. def create_store(self, value):
  355. """Creates an instruction that stores the given value in the variable referenced
  356. by this instruction."""
  357. return StoreLocalInstruction(self.name, value)
  358. def generate_python_use(self, code_generator):
  359. """Generates a Python expression that retrieves this instruction's
  360. result. The expression is returned as a string."""
  361. return self.name
  362. class StoreLocalInstruction(LocalInstruction):
  363. """An instruction that stores a value in a local variable."""
  364. def __init__(self, name, value):
  365. LocalInstruction.__init__(self, name)
  366. self.value = value
  367. def simplify(self):
  368. """Applies basic simplification to this instruction and its children."""
  369. return StoreLocalInstruction(self.name, self.value.simplify())
  370. def generate_python_def(self, code_generator):
  371. """Generates a Python statement that executes this instruction.
  372. The statement is appended immediately to the code generator."""
  373. code_generator.append_move_definition(self, self.value)
  374. class LoadLocalInstruction(LocalInstruction):
  375. """An instruction that loads a value from a local variable."""
  376. def has_definition(self):
  377. """Tells if this instruction requires a definition."""
  378. return False
  379. class DefineFunctionInstruction(LocalInstruction):
  380. """An instruction that defines a function."""
  381. def __init__(self, name, parameter_list, body):
  382. LocalInstruction.__init__(self, name)
  383. self.parameter_list = parameter_list
  384. self.body = body
  385. def generate_python_def(self, code_generator):
  386. """Generates a Python statement that executes this instruction.
  387. The statement is appended immediately to the code generator."""
  388. code_generator.append_line('def %s(%s):' % (self.name, ', '.join(self.parameter_list)))
  389. code_generator.increase_indentation()
  390. self.body.generate_python_def(code_generator)
  391. code_generator.decrease_indentation()
  392. class LocalExistsInstruction(LocalInstruction):
  393. """An instruction that checks if a local variable exists."""
  394. def has_definition(self):
  395. """Tells if this instruction requires a definition."""
  396. return False
  397. def generate_python_use(self, code_generator):
  398. """Generates a Python expression that retrieves this instruction's
  399. result. The expression is returned as a string."""
  400. return "'%s' in locals()" % self.name
  401. class LoadIndexInstruction(Instruction):
  402. """An instruction that produces a value by indexing a specified expression with
  403. a given key."""
  404. def __init__(self, indexed, key):
  405. Instruction.__init__(self)
  406. self.indexed = indexed
  407. self.key = key
  408. def has_definition(self):
  409. """Tells if this instruction requires a definition."""
  410. return False
  411. def generate_python_use(self, code_generator):
  412. """Generates a Python expression that retrieves this instruction's
  413. result. The expression is returned as a string."""
  414. if self.indexed.has_definition():
  415. self.indexed.generate_python_def(code_generator)
  416. if self.key.has_definition():
  417. self.key.generate_python_def(code_generator)
  418. return "%s[%s]" % (
  419. self.indexed.generate_python_use(code_generator),
  420. self.key.generate_python_use(code_generator))
  421. class NopInstruction(Instruction):
  422. """A nop instruction, which allows for the kernel's thread of execution to be interrupted."""
  423. def has_result(self):
  424. """Tells if this instruction computes a result."""
  425. return False
  426. def generate_python_def(self, code_generator):
  427. """Generates a Python statement that executes this instruction.
  428. The statement is appended immediately to the code generator."""
  429. code_generator.append_line('yield %s' % repr(NOP_LITERAL))
  430. class ReadValueInstruction(StateInstruction):
  431. """An instruction that reads a value from a node."""
  432. def __init__(self, node_id):
  433. StateInstruction.__init__(self)
  434. self.node_id = node_id
  435. def simplify(self):
  436. """Applies basic simplification to this instruction and its children."""
  437. return ReadValueInstruction(self.node_id.simplify())
  438. def get_opcode(self):
  439. """Gets the opcode for this state instruction."""
  440. return "RV"
  441. def get_arguments(self):
  442. """Gets this state instruction's argument list."""
  443. return [self.node_id]
  444. class ReadDictionaryValueInstruction(StateInstruction):
  445. """An instruction that reads a dictionary value."""
  446. def __init__(self, node_id, key):
  447. StateInstruction.__init__(self)
  448. self.node_id = node_id
  449. self.key = key
  450. def simplify(self):
  451. """Applies basic simplification to this instruction and its children."""
  452. return ReadDictionaryValueInstruction(
  453. self.node_id.simplify(),
  454. self.key.simplify())
  455. def get_opcode(self):
  456. """Gets the opcode for this state instruction."""
  457. return "RD"
  458. def get_arguments(self):
  459. """Gets this state instruction's argument list."""
  460. return [self.node_id, self.key]
  461. class ReadDictionaryEdgeInstruction(StateInstruction):
  462. """An instruction that reads a dictionary edge."""
  463. def __init__(self, node_id, key):
  464. StateInstruction.__init__(self)
  465. self.node_id = node_id
  466. self.key = key
  467. def simplify(self):
  468. """Applies basic simplification to this instruction and its children."""
  469. return ReadDictionaryEdgeInstruction(
  470. self.node_id.simplify(),
  471. self.key.simplify())
  472. def get_opcode(self):
  473. """Gets the opcode for this state instruction."""
  474. return "RDE"
  475. def get_arguments(self):
  476. """Gets this state instruction's argument list."""
  477. return [self.node_id, self.key]
  478. class CreateNodeInstruction(StateInstruction):
  479. """An instruction that creates an empty node."""
  480. def get_opcode(self):
  481. """Gets the opcode for this state instruction."""
  482. return "CN"
  483. def get_arguments(self):
  484. """Gets this state instruction's argument list."""
  485. return []
  486. class CreateDictionaryEdgeInstruction(StateInstruction):
  487. """An instruction that creates a dictionary edge."""
  488. def __init__(self, source_id, key, target_id):
  489. StateInstruction.__init__(self)
  490. self.source_id = source_id
  491. self.key = key
  492. self.target_id = target_id
  493. def simplify(self):
  494. """Applies basic simplification to this instruction and its children."""
  495. return CreateDictionaryEdgeInstruction(
  496. self.source_id.simplify(),
  497. self.key.simplify(),
  498. self.target_id.simplify())
  499. def get_opcode(self):
  500. """Gets the opcode for this state instruction."""
  501. return "CD"
  502. def get_arguments(self):
  503. """Gets this state instruction's argument list."""
  504. return [self.source_id, self.key, self.target_id]
  505. class DeleteEdgeInstruction(StateInstruction):
  506. """An instruction that deletes an edge."""
  507. def __init__(self, edge_id):
  508. StateInstruction.__init__(self)
  509. self.edge_id = edge_id
  510. def simplify(self):
  511. """Applies basic simplification to this instruction and its children."""
  512. return DeleteEdgeInstruction(self.edge_id.simplify())
  513. def has_result(self):
  514. """Tells if this instruction computes a result."""
  515. return False
  516. def get_opcode(self):
  517. """Gets the opcode for this state instruction."""
  518. return "DE"
  519. def get_arguments(self):
  520. """Gets this state instruction's argument list."""
  521. return [self.edge_id]
  522. def create_block(*statements):
  523. """Creates a block-statement from the given list of statements."""
  524. length = len(statements)
  525. if length == 0:
  526. return EmptyInstruction()
  527. elif length == 1:
  528. return statements[0]
  529. else:
  530. return CompoundInstruction(
  531. statements[0],
  532. create_block(*statements[1:]))
  533. if __name__ == "__main__":
  534. example_tree = SelectInstruction(
  535. LiteralInstruction(True),
  536. LoopInstruction(
  537. CompoundInstruction(
  538. BreakInstruction(),
  539. CompoundInstruction(
  540. EmptyInstruction(),
  541. ContinueInstruction()
  542. )
  543. )
  544. ),
  545. ReturnInstruction(
  546. EmptyInstruction()))
  547. print(example_tree.simplify())