vm.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  1. import argparse
  2. import sys
  3. from enum import Enum
  4. alloc_commands = {
  5. "param": 1,
  6. "private": 1,
  7. "public": 1,
  8. }
  9. op_commands = {
  10. "set": 2,
  11. "mul": 2,
  12. "add": 2,
  13. "sub": 2,
  14. "divide": 2,
  15. "double": 1,
  16. "square": 1,
  17. "unpack_bits": 3,
  18. "load": 2,
  19. "local": 1,
  20. }
  21. constraint_commands = {
  22. "lc0_add": 1,
  23. "lc1_add": 1,
  24. "lc2_add": 1,
  25. "lc0_sub": 1,
  26. "lc1_sub": 1,
  27. "lc2_sub": 1,
  28. "lc0_add_one": 0,
  29. "lc1_add_one": 0,
  30. "lc2_add_one": 0,
  31. "lc0_add_coeff": 2,
  32. "lc1_add_coeff": 2,
  33. "lc2_add_coeff": 2,
  34. "lc0_add_one_coeff": 1,
  35. "lc1_add_one_coeff": 1,
  36. "lc2_add_one_coeff": 1,
  37. "enforce": 0,
  38. "lc_coeff_reset": 0,
  39. "lc_coeff_double": 0,
  40. }
  41. def eprint(*args):
  42. print(*args, file=sys.stderr)
  43. class Line:
  44. def __init__(self, text, line_number):
  45. self.text = text
  46. self.orig = text
  47. self.lineno = line_number
  48. self.clean()
  49. def clean(self):
  50. # Remove the comments
  51. self.text = self.text.split("#", 1)[0]
  52. # Remove whitespace
  53. self.text = self.text.strip()
  54. def is_empty(self):
  55. return bool(self.text)
  56. def __repr__(self):
  57. return "Line %s: %s" % (self.lineno, self.orig.lstrip())
  58. def command(self):
  59. if not self.is_empty():
  60. return None
  61. return self.text.split(" ")[0]
  62. def args(self):
  63. if not self.is_empty():
  64. return None
  65. return self.text.split()[1:]
  66. def clean(contents):
  67. # Split input into lines
  68. contents = contents.split("\n")
  69. contents = [Line(line, i) for i, line in enumerate(contents)]
  70. # Remove empty blank lines
  71. contents = [line for line in contents if line.is_empty()]
  72. return contents
  73. def divide_sections(contents):
  74. state = "NOSCOPE"
  75. segments = {}
  76. current_segment = []
  77. contract_name = None
  78. for line in contents:
  79. if line.command() == "contract":
  80. if len(line.args()) != 1:
  81. eprint("error: missing contract name")
  82. eprint(line)
  83. return None
  84. contract_name = line.args()[0]
  85. if state == "NOSCOPE":
  86. assert not current_segment
  87. state = "INSCOPE"
  88. continue
  89. else:
  90. assert state == "INSCOPE"
  91. eprint("error: double contract entry violation")
  92. eprint(line)
  93. return None
  94. elif line.command() == "end":
  95. if len(line.args()) != 0:
  96. eprint("error: end takes no args")
  97. eprint(line)
  98. return None
  99. if state == "NOSCOPE":
  100. eprint("error: missing contract start for end")
  101. eprint(line)
  102. return None
  103. else:
  104. assert state == "INSCOPE"
  105. state = "NOSCOPE"
  106. segments[contract_name] = current_segment
  107. current_segment = []
  108. continue
  109. elif state == "NOSCOPE":
  110. # Ignore lines outside any contract
  111. continue
  112. current_segment.append(line)
  113. if state != "NOSCOPE":
  114. eprint("error: reached end of file with unclosed scope")
  115. return None
  116. return segments
  117. def extract_relevant_lines(contract, commands_table):
  118. relevant_lines = []
  119. for line in contract:
  120. command = line.command()
  121. if command not in commands_table.keys():
  122. continue
  123. define = commands_table[command]
  124. if len(line.args()) != define:
  125. eprint("error: wrong number of args")
  126. return None
  127. relevant_lines.append(line)
  128. return relevant_lines
  129. class VariableType(Enum):
  130. PUBLIC = 1
  131. PRIVATE = 2
  132. class Variable:
  133. def __init__(self, symbol, index, type, is_param):
  134. self.symbol = symbol
  135. self.index = index
  136. self.type = type
  137. self.is_param = is_param
  138. def __repr__(self):
  139. return "<Variable %s:%s>" % (self.symbol, self.index)
  140. def generate_alloc_table(contract):
  141. relevant_lines = extract_relevant_lines(contract, alloc_commands)
  142. alloc_table = {}
  143. for i, line in enumerate(relevant_lines):
  144. assert len(line.args()) == 1
  145. symbol = line.args()[0]
  146. command = line.command()
  147. if command == "param":
  148. type = VariableType.PRIVATE
  149. is_param = True
  150. elif command == "private":
  151. type = VariableType.PRIVATE
  152. is_param = False
  153. elif command == "public":
  154. type = VariableType.PUBLIC
  155. is_param = False
  156. else:
  157. assert False
  158. if symbol in alloc_table:
  159. eprint("error: duplicate symbol '%s'" % symbol)
  160. eprint(line)
  161. return None
  162. alloc_table[symbol] = Variable(symbol, i, type, is_param)
  163. return alloc_table
  164. class Operation:
  165. def __init__(self, line, indexes):
  166. self.command = line.command()
  167. self.args = indexes
  168. self.line = line
  169. class VariableRefType(Enum):
  170. AUX = 1
  171. LOCAL = 2
  172. CONST = 3
  173. class VariableRef:
  174. def __init__(self, type, index):
  175. self.type = type
  176. self.index = index
  177. def __repr__(self):
  178. return "%s(%s)" % (self.type.name, self.index)
  179. def symbols_list_to_refs(line, alloc, local_vars, constants):
  180. indexes = []
  181. for symbol in line.args():
  182. if symbol in alloc:
  183. # Lookup variable index
  184. index = alloc[symbol].index
  185. index = VariableRef(VariableRefType.AUX, index)
  186. elif symbol in local_vars:
  187. index = local_vars[symbol]
  188. index = VariableRef(VariableRefType.LOCAL, index)
  189. elif symbol in constants:
  190. index = constants[symbol][0]
  191. index = VariableRef(VariableRefType.CONST, index)
  192. else:
  193. eprint("error: missing unallocated symbol '%s'" % symbol)
  194. eprint(line)
  195. return None
  196. indexes.append(index)
  197. return indexes
  198. def generate_ops_table(contract, alloc, constants):
  199. relevant_lines = extract_relevant_lines(contract, op_commands)
  200. ops = []
  201. local_vars = {}
  202. for line in relevant_lines:
  203. # This is a special case which creates a new local stack value
  204. if line.command() == "local":
  205. assert len(line.args()) == 1
  206. symbol = line.args()[0]
  207. local_vars[symbol] = len(local_vars)
  208. indexes = []
  209. else:
  210. if (indexes := symbols_list_to_refs(line, alloc,
  211. local_vars, constants)) is None:
  212. return None
  213. # Handle this here directly since only the
  214. # load command deals with constants
  215. if line.command() == "load":
  216. assert len(indexes) == 2
  217. # This is the only command which uses consts
  218. if indexes[1].type != VariableRefType.CONST:
  219. eprint("error: load command takes a const argument")
  220. eprint(line)
  221. return None
  222. elif any(index.type == VariableRefType.CONST for index in indexes):
  223. eprint("error: invalid const arg")
  224. eprint(line)
  225. return None
  226. ops.append(Operation(line, indexes))
  227. return ops
  228. class Constraint:
  229. def __init__(self, line, lcargs):
  230. self.command = line.command()
  231. self.args = lcargs
  232. self.line = line
  233. def args_comment(self):
  234. return ", ".join("%s" % symbol for symbol in self.line.args())
  235. def symbols_list_to_lcargs(line, alloc, constants):
  236. lcargs = []
  237. for symbol in line.args():
  238. if symbol in alloc:
  239. # Lookup variable index
  240. index = alloc[symbol].index
  241. lcargs.append(index)
  242. elif symbol in constants:
  243. value = constants[symbol]
  244. lcargs.append(value)
  245. else:
  246. eprint("error: missing unallocated symbol '%s'" % symbol)
  247. eprint(line)
  248. return None
  249. return lcargs
  250. def generate_constraints_table(contract, alloc, constants):
  251. relevant_lines = extract_relevant_lines(contract, constraint_commands)
  252. constraints = []
  253. for line in relevant_lines:
  254. if (lcargs := symbols_list_to_lcargs(line, alloc, constants)) is None:
  255. return None
  256. constraints.append(Constraint(line, lcargs))
  257. return constraints
  258. class Contract:
  259. def __init__(self, constants, alloc, ops, constraints):
  260. self.constants = constants
  261. self.alloc = alloc
  262. self.ops = ops
  263. self.constraints = constraints
  264. def __repr__(self):
  265. repr_str = ""
  266. repr_str += "Constants:\n"
  267. for symbol, value in self.constants.items():
  268. repr_str += " // %s\n" % symbol
  269. repr_str += " %s: %s\n" % value
  270. repr_str += "Alloc table:\n"
  271. for symbol, variable in self.alloc.items():
  272. repr_str += " // %s\n" % symbol
  273. repr_str += " %s %s\n" % (variable.type, variable.index)
  274. repr_str += "Operations:\n"
  275. for op in self.ops:
  276. repr_str += " // %s\n" % op.line
  277. repr_str += " %s %s\n" % (op.command, op.args)
  278. repr_str += "Constraints:\n"
  279. for constraint in self.constraints:
  280. if constraint.args:
  281. repr_str += " // %s\n" % constraint.args_comment()
  282. repr_str += " %s %s\n" % (constraint.command, constraint.args)
  283. return repr_str
  284. def compile(contract, constants):
  285. # Allocation table
  286. # symbol: Private/Public, is_param, index
  287. if (alloc := generate_alloc_table(contract)) is None:
  288. return None
  289. # Operations lines list
  290. if (ops := generate_ops_table(contract, alloc, constants)) is None:
  291. return None
  292. # Constraint commands
  293. if (constraints := generate_constraints_table(
  294. contract, alloc, constants)) is None:
  295. return None
  296. return Contract(constants, alloc, ops, constraints)
  297. def parse_constants(contents):
  298. relevant_lines = [line for line in contents if line.command() == "constant"]
  299. constants = {}
  300. for line in relevant_lines:
  301. assert line.command() == "constant"
  302. if len(line.args()) != 2:
  303. eprint("error: wrong number of args for constant")
  304. eprint(line)
  305. return None
  306. symbol, value = line.args()
  307. try:
  308. int(value, 16)
  309. except ValueError:
  310. eprint("error: invalid constant value for '%s'" % symbol)
  311. eprint(line)
  312. return None
  313. if len(value) != 32*2 + 2 or value[:2] != "0x":
  314. eprint("error: invalid hex value for constant")
  315. eprint(line)
  316. return None
  317. # Remove 0x prefix
  318. value = value[2:]
  319. constants[symbol] = (len(constants), value)
  320. return constants
  321. def process(contents):
  322. # Remove left whitespace
  323. contents = clean(contents)
  324. # Parse all constants
  325. if (constants := parse_constants(contents)) is None:
  326. return None
  327. # Divide into contract sections
  328. if (pre_contracts := divide_sections(contents)) is None:
  329. return None
  330. # Process each contract
  331. contracts = {}
  332. for contract_name, pre_contract in pre_contracts.items():
  333. if (contract := compile(pre_contract, constants)) is None:
  334. return None
  335. contracts[contract_name] = contract
  336. return contracts
  337. def main(argv):
  338. parser = argparse.ArgumentParser()
  339. parser.add_argument("filename", help="VM PISM file: proofs/vm.pism")
  340. group = parser.add_mutually_exclusive_group()
  341. group.add_argument('--display', action='store_true',
  342. help="show the compiled code in human readable format")
  343. group.add_argument('--rust', action='store_true',
  344. help="output compiled code to rust for testing")
  345. args = parser.parse_args()
  346. src_filename = args.filename
  347. contents = open(src_filename).read()
  348. if (contracts := process(contents)) is None:
  349. return -2
  350. def default_display():
  351. for contract_name, contract in contracts.items():
  352. print("Contract:", contract_name)
  353. print(contract)
  354. if args.display:
  355. default_display()
  356. elif args.rust:
  357. import vm_export_rust
  358. for contract_name, contract in contracts.items():
  359. vm_export_rust.display(contract)
  360. else:
  361. default_display()
  362. return 0
  363. if __name__ == "__main__":
  364. sys.exit(main(sys.argv))