pism.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  1. import json
  2. import os
  3. import sys
  4. import codegen
  5. symbol_table = {
  6. "contract": 1,
  7. "param": 2,
  8. "start": 0,
  9. "end": 0,
  10. "witness": 2,
  11. "assert_not_small_order": 1,
  12. "fr_as_binary_le": 2,
  13. "ec_mul_const": 3,
  14. "ec_add": 3,
  15. "ec_repr": 2,
  16. "emit_ec": 1,
  17. "alloc_binary": 1,
  18. "binary_clone": 2,
  19. "binary_extend": 2,
  20. }
  21. types_map = {
  22. "U64": "u64",
  23. "Fr": "jubjub::Fr",
  24. "Point": "jubjub::SubgroupPoint",
  25. "Scalar": "bls12_381::Scalar",
  26. "Bool": "bool"
  27. }
  28. command_desc = {
  29. "witness": (
  30. ("EdwardsPoint", True),
  31. ("Point", False)
  32. ),
  33. "assert_not_small_order": (
  34. ("EdwardsPoint", False),
  35. ),
  36. "fr_as_binary_le": (
  37. ("Vec<Boolean>", True),
  38. ("Fr", False)
  39. ),
  40. "ec_mul_const": (
  41. ("EdwardsPoint", True),
  42. ("Vec<Boolean>", False),
  43. ("FixedGenerator", False)
  44. ),
  45. "ec_add": (
  46. ("EdwardsPoint", True),
  47. ("EdwardsPoint", False),
  48. ("EdwardsPoint", False),
  49. ),
  50. "ec_repr": (
  51. ("Vec<Boolean>", True),
  52. ("EdwardsPoint", False),
  53. ),
  54. "emit_ec": (
  55. ("EdwardsPoint", False),
  56. ),
  57. "alloc_binary": (
  58. ("Vec<Boolean>", True),
  59. ),
  60. "binary_clone": (
  61. ("Vec<Boolean>", True),
  62. ("Vec<Boolean>", False),
  63. ),
  64. "binary_extend": (
  65. ("Vec<Boolean>", False),
  66. ("Vec<Boolean>", False),
  67. ),
  68. }
  69. def eprint(*args):
  70. print(*args, file=sys.stderr)
  71. class Line:
  72. def __init__(self, text, line_number):
  73. self.text = text
  74. self.orig = text
  75. self.lineno = line_number
  76. self.clean()
  77. def clean(self):
  78. # Remove the comments
  79. self.text = self.text.split("#", 1)[0]
  80. # Remove whitespace
  81. self.text = self.text.strip()
  82. def is_empty(self):
  83. return bool(self.text)
  84. def __repr__(self):
  85. return "Line %s: %s" % (self.lineno, self.orig)
  86. def command(self):
  87. if not self.is_empty():
  88. return None
  89. return self.text.split(" ")[0]
  90. def args(self):
  91. if not self.is_empty():
  92. return None
  93. return self.text.split(" ")[1:]
  94. def clean(contents):
  95. # Split input into lines
  96. contents = contents.split("\n")
  97. contents = [Line(line, i) for i, line in enumerate(contents)]
  98. # Remove empty blank lines
  99. contents = [line for line in contents if line.is_empty()]
  100. return contents
  101. def make_segments(contents):
  102. constants = [line for line in contents if line.command() == "constant"]
  103. segments = []
  104. current_segment = []
  105. for line in contents:
  106. if line.command() == "contract":
  107. current_segment = []
  108. current_segment.append(line)
  109. if line.command() == "end":
  110. segments.append(current_segment)
  111. current_segment = []
  112. return constants, segments
  113. def build_constants_table(constants):
  114. table = {}
  115. for line in constants:
  116. args = line.args()
  117. if len(args) != 2:
  118. eprint("error: wrong number of args")
  119. eprint(line)
  120. return None
  121. name, type = args
  122. table[name] = type
  123. return table
  124. def extract(segment):
  125. assert segment
  126. # Does it have a declaration?
  127. if not segment[0].command() == "contract":
  128. eprint("error: missing contract declaration")
  129. eprint(segment[0])
  130. return None
  131. # Does it have an end?
  132. if not segment[-1].command() == "end":
  133. eprint("error: missing contract end")
  134. eprint(segment[-1])
  135. return None
  136. # Does it have a start?
  137. if not [line for line in segment if line.command() == "start"]:
  138. eprint("error: missing contract start")
  139. eprint(segment[0])
  140. return None
  141. for line in segment:
  142. command, args = line.command(), line.args()
  143. if symbol_table[command] != len(args):
  144. eprint("error: wrong number of args for command '%s'" % command)
  145. eprint(line)
  146. return None
  147. contract_name = segment[0].args()[0]
  148. start_index = [index for index, line in enumerate(segment)
  149. if line.command() == "start"]
  150. if len(start_index) > 1:
  151. eprint("error: multiple start statements in contract '%s'" %
  152. contract_name)
  153. for index in start_index:
  154. eprint(segment[index])
  155. eprint("Aborting.")
  156. return None
  157. assert len(start_index) == 1
  158. start_index = start_index[0]
  159. header = segment[1:start_index]
  160. code = segment[start_index + 1:-1]
  161. params = {}
  162. for param_decl in header:
  163. args = param_decl.args()
  164. assert len(args) == 2
  165. name, type = args
  166. params[name] = type
  167. program = []
  168. for line in code:
  169. command, args = line.command(), line.args()
  170. program.append((command, args, line))
  171. return Contract(contract_name, params, program)
  172. def to_initial_caps(snake_str):
  173. components = snake_str.split("_")
  174. return "".join(x.title() for x in components)
  175. class Contract:
  176. def __init__(self, name, params, program):
  177. self.name = name
  178. self.params = params
  179. self.program = program
  180. def _includes(self):
  181. return \
  182. r"""use bellman::{
  183. gadgets::{
  184. boolean,
  185. boolean::{AllocatedBit, Boolean},
  186. multipack,
  187. },
  188. groth16, Circuit, ConstraintSystem, SynthesisError,
  189. };
  190. use bls12_381::Bls12;
  191. use ff::{PrimeField, Field};
  192. use group::Curve;
  193. use zcash_proofs::circuit::ecc;
  194. """
  195. def _compile_header(self):
  196. code = "pub struct %s {\n" % to_initial_caps(self.name)
  197. for param_name, param_type in self.params.items():
  198. try:
  199. mapped_type = types_map[param_type]
  200. except KeyError:
  201. return None
  202. code += " pub %s: Option<%s>,\n" % (param_name, mapped_type)
  203. code += "}\n"
  204. return code
  205. def _compile_body(self):
  206. self.stack = {}
  207. code = "\n"
  208. #indent = " " * 8
  209. for command, args, line in self.program:
  210. if (code_text := self._compile_line(command, args, line)) is None:
  211. return None
  212. code += code_text + "\n"
  213. return code
  214. def _preprocess_args(self, args, line):
  215. nargs = []
  216. for arg in args:
  217. if not arg.startswith("param:"):
  218. nargs.append((arg, False))
  219. continue
  220. _, argname = arg.split(":", 1)
  221. if argname not in self.params:
  222. eprint("error: non-existant param referenced")
  223. eprint(line)
  224. return None
  225. nargs.append((argname, True))
  226. return nargs
  227. def type_checking(self, command, args, line):
  228. assert command in command_desc
  229. type_list = command_desc[command]
  230. if len(type_list) != len(args):
  231. eprint("error: wrong number of arguments!")
  232. eprint(line)
  233. return False
  234. for (expected_type, new_val), (argname, is_param) in \
  235. zip(type_list, args):
  236. # Only type check input arguments, not output values
  237. if new_val:
  238. continue
  239. if is_param:
  240. actual_type = self.params[argname]
  241. elif argname in self.constants:
  242. actual_type = self.constants[argname]
  243. else:
  244. # Check the stack here
  245. if argname not in self.stack:
  246. eprint("error: cannot find value '%s' on the stack!" %
  247. argname)
  248. eprint(line)
  249. return False
  250. actual_type = self.stack[argname]
  251. return True
  252. def _check_args(self, command, args, line):
  253. assert command in command_desc
  254. type_list = command_desc[command]
  255. assert len(type_list) == len(args)
  256. for (_, is_new_val), (arg, is_param) in zip(type_list, args):
  257. if is_param:
  258. continue
  259. if is_new_val:
  260. continue
  261. if arg in self.stack:
  262. continue
  263. if arg in self.constants:
  264. continue
  265. eprint("error: cannot find '%s' in the stack" % arg)
  266. eprint(line)
  267. return False
  268. return True
  269. def _compile_line(self, command, args, line):
  270. if (args := self._preprocess_args(args, line)) is None:
  271. return None
  272. if not self.type_checking(command, args, line):
  273. return None
  274. if not self._check_args(command, args, line):
  275. return None
  276. self.modify_stack(command, args)
  277. args = [self.carg(arg) for arg in args]
  278. try:
  279. codegen_method = getattr(codegen, command)
  280. except AttributeError:
  281. eprint("error: missing command '%s' does not exist" % command)
  282. eprint(line)
  283. return None
  284. return codegen_method(line, *args)
  285. def carg(self, arg):
  286. argname, is_param = arg
  287. if is_param:
  288. return "self.%s" % argname
  289. if argname in self.rename_consts:
  290. return self.rename_consts[argname]
  291. return argname
  292. def modify_stack(self, command, args):
  293. type_list = command_desc[command]
  294. assert len(type_list) == len(args)
  295. for (expected_type, new_val), (argname, is_param) in \
  296. zip(type_list, args):
  297. if is_param:
  298. assert not new_val
  299. continue
  300. # Now apply the new values to the stack
  301. if new_val:
  302. self.stack[argname] = expected_type
  303. def compile(self, constants, aux):
  304. self.constants = constants
  305. code = ""
  306. code += self._includes()
  307. self.rename_consts = {}
  308. if "constants" in aux:
  309. for const_name, value in aux["constants"].items():
  310. if "module_includes" not in value:
  311. continue
  312. if "maps_to" not in value:
  313. eprint("error: bad aux config '%s', missing maps_to" %
  314. const_name)
  315. mapped_type = value["maps_to"]
  316. code += "use %s::%s;\n" % (value["module_includes"], mapped_type)
  317. self.rename_consts[const_name] = mapped_type
  318. code += "\n"
  319. if (header := self._compile_header()) is None:
  320. return None
  321. code += header
  322. code += \
  323. r"""impl Circuit<bls12_381::Scalar> for %s {
  324. fn synthesize<CS: ConstraintSystem<bls12_381::Scalar>>(
  325. self,
  326. cs: &mut CS,
  327. ) -> Result<(), SynthesisError> {
  328. """ % to_initial_caps(self.name)
  329. if (body := self._compile_body()) is None:
  330. return None
  331. code += body
  332. code += "Ok(())\n"
  333. code += " }\n"
  334. code += "}\n"
  335. return code
  336. def process(contents, aux):
  337. contents = clean(contents)
  338. constants, segments = make_segments(contents)
  339. if (constants := build_constants_table(constants)) is None:
  340. return False
  341. codes = []
  342. for segment in segments:
  343. contract = extract(segment)
  344. if (code := contract.compile(constants, aux)) is None:
  345. return False
  346. codes.append(code)
  347. # Success! Output finished product.
  348. [print(code) for code in codes]
  349. return True
  350. def main(argv):
  351. if len(argv) != 2:
  352. eprint("pism FILENAME")
  353. return -1
  354. src_filename = argv[1]
  355. basename, _ = os.path.splitext(src_filename)
  356. aux_filename = basename + ".aux"
  357. aux = json.loads(open(aux_filename).read())
  358. contents = open(src_filename).read()
  359. if not process(contents, aux):
  360. return -2
  361. return 0
  362. if __name__ == "__main__":
  363. sys.exit(main(sys.argv))