vm.py 13 KB

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