├── .github
└── workflows
│ └── rust.yml
├── .gitignore
├── .gitmodules
├── Cargo.toml
├── LICENSE
├── README.md
├── bin
├── repl
│ ├── Cargo.toml
│ └── src
│ │ ├── main.rs
│ │ └── repl.rs
└── scribe
│ ├── Cargo.lock
│ ├── Cargo.toml
│ └── src
│ └── main.rs
├── crates
├── miden-integration-tests
│ ├── .gitignore
│ ├── Cargo.toml
│ ├── snapshots
│ │ ├── erc20__tests__parse_erc20.snap
│ │ ├── scribe__parser__tests__parse_assignment.snap
│ │ ├── scribe__parser__tests__parse_cruft.snap
│ │ ├── scribe__parser__tests__parse_fibonnaci.snap
│ │ ├── scribe__parser__tests__parse_function_call.snap
│ │ ├── scribe__parser__tests__parse_function_def.snap
│ │ ├── scribe__parser__tests__parse_function_def_with_return.snap
│ │ ├── scribe__parser__tests__parse_function_def_without_return.snap
│ │ ├── scribe__parser__tests__parse_if.snap
│ │ ├── scribe__parser__tests__parse_reference_chain.snap
│ │ ├── scribe__parser__tests__parse_switch_statement.snap
│ │ ├── scribe__parser__tests__parse_var_and_add.snap
│ │ ├── scribe__parser__tests__parse_var_declaration.snap
│ │ ├── scribe__parser__tests__parse_var_declaration_with_types.snap
│ │ └── scribe__parser__tests__snapshot_test.snap
│ ├── src
│ │ └── lib.rs
│ ├── test_output.masm
│ └── tests
│ │ ├── bugfixes.rs
│ │ ├── future.rs
│ │ ├── lib.rs
│ │ ├── lifetime.rs
│ │ ├── memory.rs
│ │ ├── optimization.rs
│ │ ├── quickcheck_tests.rs
│ │ ├── test.rs
│ │ ├── u256.rs
│ │ └── utils.rs
└── papyrus
│ ├── Cargo.toml
│ └── src
│ ├── ast_optimization.rs
│ ├── executor.rs
│ ├── grammar.pest
│ ├── lib.rs
│ ├── miden_asm
│ ├── u256gt_unsafe.masm
│ ├── u256lt_unsafe.masm
│ ├── u256shl_unsafe.masm
│ └── u256shr_unsafe.masm
│ ├── miden_generator.rs
│ ├── parser.rs
│ ├── snapshots
│ ├── papyrus__parser__tests__parse_cruft.snap
│ ├── papyrus__parser__tests__parse_fibonnaci.snap
│ ├── papyrus__parser__tests__parse_function_call.snap
│ ├── papyrus__parser__tests__parse_function_def_with_return.snap
│ ├── papyrus__parser__tests__parse_function_def_without_return.snap
│ ├── papyrus__parser__tests__parse_if.snap
│ ├── papyrus__parser__tests__parse_switch_statement.snap
│ ├── papyrus__parser__tests__parse_var_and_add.snap
│ ├── papyrus__parser__tests__parse_var_declaration.snap
│ └── papyrus__parser__tests__parse_var_declaration_with_types.snap
│ ├── type_inference.rs
│ ├── types.rs
│ └── utils.rs
├── history.txt
└── problems.md
/.github/workflows/rust.yml:
--------------------------------------------------------------------------------
1 | name: Rust
2 |
3 | on:
4 | push:
5 | branches: [ main ]
6 | pull_request:
7 | branches: [ main ]
8 |
9 | env:
10 | CARGO_TERM_COLOR: always
11 |
12 | jobs:
13 | build:
14 |
15 | runs-on: ubuntu-latest
16 |
17 | steps:
18 | - uses: actions/checkout@v2
19 | - name: Build
20 | run: cargo build --verbose
21 | - name: Check formatting
22 | run: cargo fmt --all --verbose -- --check
23 | - name: Ask Clippy for his thoughts
24 | run: cargo clippy --all-targets --all-features
25 | - name: Run tests
26 | run: cargo test --verbose
27 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | /target
2 | .DS_STORE
3 | Cargo.lock
--------------------------------------------------------------------------------
/.gitmodules:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ControlCplusControlV/Scribe/93b46212b6920c4a9c472cd0c324fb00783d562c/.gitmodules
--------------------------------------------------------------------------------
/Cargo.toml:
--------------------------------------------------------------------------------
1 | [workspace]
2 | members = [
3 | "crates/papyrus",
4 | "bin/scribe",
5 | "bin/repl",
6 | ]
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # 📜 Scribe 📜
2 | 
3 |
4 | Scribe is a compact Yul transpiler written in Rust that targets the Polygon
5 | Miden VM. Scribe works by compiling Yul down to Miden opcodes, allowing
6 | developers to write smart contracts in Yul and run them on Polygon Miden. Since
7 | Yul is the intermediate language for Solidity, Vyper and Yul+ Scribe is a great
8 | foundation for various smart contract languages to compile code to run on
9 | Polygon Miden.
10 |
11 |
12 | ## Status
13 |
14 | **WARNING:** This project is in an alpha stage. It has not been audited and may contain bugs and security flaws. This implementation is NOT ready for production use.
15 |
16 | ### Parsing
17 |
18 | All yul syntax is parsed, including the new typed identifier list syntax.
19 |
20 | Data blocks are not transpiled. Objects are naively transpiled as a series of statements.
21 |
22 | ### Types
23 |
24 | Because u256 operations are so expensive in miden, scribe will check whether
25 | variables and parameters are typed, and if they're `u32` values, then we can
26 | use the much cheaper miden u32 operations. Scribe will default to `u256`.
27 |
28 |
29 | ### Supported yul functions
30 |
31 | | Function | u32 | u256 | notes |
32 | |----------|------|-----| ---- |
33 | | add | ✅ | ✅ | |
34 | | mul | ✅ | ✅ | |
35 | | sub | ✅ | ✅ | |
36 | | div | ✅ | ❌ | |
37 | | and | ✅ | ✅ | |
38 | | or | ✅ | ✅ | |
39 | | xor | ✅ | ✅ | |
40 | | mstore | ✅ | ✅ | address must be u32 |
41 | | mload | ✅ | ✅ | address must be u32 |
42 | | iszero | ✅ | ✅ | |
43 | | eq | ✅ | ✅ | |
44 | | lt | ✅ | ✅ | |
45 | | gt | ✅ | ✅ | |
46 | | gte | ✅ | ✅ | |
47 | | lte | ✅ | ✅ | |
48 | | shl | ✅ | ❌ | |
49 | | shr | ✅ | ❌ | |
50 |
51 |
52 | ## Miden Repl
53 |
54 | Scribe features a REPL to write miden assembly. You can start the repl with:
55 |
56 | ```
57 | cargo run -- repl
58 | ```
59 |
60 | From within the repl, you can write any valid miden assembly, then check the
61 | stack with `stack`, or check your whole program with `program`. Anything that
62 | errors out will not be added to the program. You can undo the last command with `undo`.
63 |
64 | ```
65 | $ cargo run -- repl
66 |
67 | >> push.4
68 |
69 | >> push.5 push.7 mul
70 |
71 | >> stack
72 |
73 | 35 4 0 0 0 0 0 0 0 0 0 0 0 0 0 0
74 |
75 | >> program
76 |
77 | begin
78 | push.4
79 | push.5 push.7 mul
80 | end
81 |
82 | >> undo
83 | Undoing push.5 push.7 mul
84 |
85 | >> stack
86 |
87 | 4 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
88 |
89 | >> help
90 |
91 | Available commands:
92 |
93 | stack: display the stack
94 | undo: remove the last instruction
95 | program: display the program
96 | ```
97 |
98 | ## How Does it Work?
99 |
100 | Scribe is built with Rust and uses the [Pest parser](https://github.com/pest-parser/pest) to be able to recognize Yul Grammar. Scribe then translates the Yul code to the Miden VM opcodes, enabling fully functional Miden assembly can be generated from Yul. Since languages like Solidity and Vyper compile to Yul before generating EVM opcodes, in future versions of Scribe, it will be possible to transpile code written in Solidity or Vyper, into Miden assembly!
101 |
102 |
103 |
104 | **Lets take a closer look at how Scribe works under the hood.**
105 |
106 |
107 | First, Scribe reads in all of the Yul contracts in the `Scribe/contracts`
108 | directory. While Scribe can transpile entire Yul contracts, for this
109 | walkthrough we will just use a simple snippet of Yul code. We'll use u32
110 | annotations so that the output is more readable, but this example will also
111 | work with u256 values.
112 |
113 | ```js
114 |
115 | object "fib" {
116 | code {
117 | let n:u32 := 10
118 | let a:u32 := 0
119 | let b:u32 := 1
120 | let c:u32 := 0
121 |
122 | for { let i:u32 := 0 } lt(i, n) { i := add(i, 1)}
123 | {
124 | c := add(a,b)
125 | a := b
126 | b := c
127 | }
128 | b
129 | }
130 | }
131 |
132 | ```
133 |
134 | Once the Yul code is read in, Scribe converts the code into a string and passes it into the `parse_yul_syntax` function. From there, Scribe parses the string, looking for Yul grammar and generates an `Expr` for each match.
135 |
136 | ```rust
137 | pub enum Expr {
138 | Literal(ExprLiteral),
139 | FunctionDefinition(ExprFunctionDefinition),
140 | FunctionCall(ExprFunctionCall),
141 | IfStatement(ExprIfStatement),
142 | Assignment(ExprAssignment),
143 | DeclareVariable(ExprDeclareVariable),
144 | ForLoop(ExprForLoop),
145 | Block(ExprBlock),
146 | Switch(ExprSwitch),
147 | Case(ExprCase),
148 | Variable(ExprVariableReference),
149 | Repeat(ExprRepeat),
150 | Break,
151 | Continue,
152 | Leave,
153 | }
154 | ```
155 |
156 | Each `Expr` is pushed to a `Vec`, which is then passed into the
157 | `miden_generator::transpile_program()` function. This function generates the
158 | Miden opcodes and keeps track of the variables as well as open memory
159 | addresses.
160 |
161 | The transpiled code from the fibonacci example looks like this:
162 |
163 | ```nasm
164 | begin [30/1924]
165 | # Assigning to n #
166 | # u32 literal 10 #
167 | push.10
168 |
169 | # Assigning to a #
170 | # u32 literal 0 #
171 | push.0
172 |
173 | # Assigning to b #
174 | # u32 literal 1 #
175 | push.1
176 |
177 | # Assigning to c #
178 | # u32 literal 0 #
179 | push.0
180 |
181 | # Assigning to i #
182 | # u32 literal 0 #
183 | push.0
184 |
185 | # -- conditional -- #
186 | # lt() #
187 | # pushing i to the top #
188 | dup.0
189 | # pushing n to the top #
190 | dup.5
191 | lt
192 | while.true
193 | # -- interior block -- #
194 | # Assigning to c #
195 | # add() #
196 | # pushing a to the top #
197 | dup.3
198 | # pushing b to the top #
199 | dup.3
200 | add
201 | # Assigning to a #
202 | # pushing b to the top #
203 | dup.3
204 | # Assigning to b #
205 | # pushing c to the top #
206 | dup.1
207 |
208 | # -- after block -- #
209 | # Assigning to i #
210 | # add() #
211 | # pushing i to the top #
212 | dup.3
213 | # u32 literal 1 #
214 | push.1
215 |
216 | add
217 |
218 | # cleaning up after branch #
219 | # pushing n to the top #
220 | movup.8
221 | # pushing a to the top #
222 | movup.3
223 | # pushing b to the top #
224 | movup.3
225 | # pushing c to the top #
226 | movup.4
227 | # pushing i to the top #
228 | movup.4
229 |
230 | # -- conditional -- #
231 | # lt() #
232 | # pushing i to the top #
233 | dup.0
234 | # pushing n to the top #
235 | dup.5
236 | lt
237 |
238 | end
239 |
240 | # pushing b to the top #
241 | dup.2
242 | end
243 |
244 | ```
245 |
246 | Now the generated Miden code is ready to run! Scribe can test your code on the Miden VM by starting the VM, passing in the Miden code and calling the executor. Here is what the process looks like from start to finish!
247 |
248 | ```rust
249 | //Parse the Yul code
250 | let parsed_yul_code = parser::parse_yul_syntax(yul_code);
251 |
252 | //Generate Miden opcodes from the parsed Yul code
253 | let miden_code = miden_generator::transpile_program(parsed);
254 |
255 | //Execute the Miden code on the Miden VM
256 | let execution_value = executor::execute(miden_code, inputs).unwrap();
257 | let stack = execution_value.last_stack_state();
258 | let last_stack_value = stack.first().unwrap();
259 |
260 | //Print the output
261 | println!("Miden Output");
262 | println!("{}", last_stack_value);
263 | ```
264 |
265 | And here is the output!
266 |
267 | ```
268 | Miden Output
269 | 89
270 | ```
271 |
272 |
273 |
274 | ## How to transpile your own contract.
275 |
276 | To transpile and test your own contracts simple drop your own Yul Contracts inside the contracts folder then transpile then by running the transpiler crate with `cargo run`. Note that some Yul operations are still unsupported, but basic arithmatic, and control structures are supported, as well as variables.
277 |
278 | Scribe was meant to focus on real world applicability, and because of this uses Miden v0.2. Due to Miden v0.2 not being done yet certain crates of it like the zk prover are broken atm as the developers build away on the new release. So certain functionality like zk proof generation can't be done at the moment, but execution can still be tested in the zk VM environment.
279 |
280 | First clone this repo and download its submodule
281 |
282 | ```
283 | git clone https://github.com/ControlCplusControlV/Scribe
284 | cd Scribe
285 | git submodule init
286 | git submodule update
287 | ```
288 |
289 | then cd into the transpiler crate
290 |
291 | ```
292 | cd transpiler
293 | ```
294 |
295 | Then init the git submodule, and you should be good to go!
296 |
297 |
298 | ## Contributing
299 |
300 | ### Testing
301 |
302 | Scribe has unit tests and integration tests that can be run with `cargo test`
303 |
304 | Our parsing tests use the [insta](https://github.com/mitsuhiko/insta)
305 | snapshot-testing crate. After running a new test, run `cargo insta review`,
306 | verify that the generated AST looks right, then accept the output as correct.
307 | In future tests the output will be compared to this snapshot.
308 |
--------------------------------------------------------------------------------
/bin/repl/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "repl"
3 | version = "0.1.0"
4 | edition = "2021"
5 |
6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7 |
8 | [dependencies]
9 | papyrus = { path = "../../crates/papyrus"}
10 | pest = "2.0"
11 | pest_derive = "2.0"
12 | miden-assembly = { git = "http://github.com/maticnetwork/miden", branch = "next" }
13 | miden-processor = { git = "http://github.com/maticnetwork/miden", branch = "next" }
14 | miden-core = { git = "http://github.com/maticnetwork/miden", branch = "next" }
15 | hex = "0.4"
16 | colored = "2"
17 | debug_tree = "0.4.0"
18 | insta = "1.12.0"
19 | primitive-types = "0.11.1"
20 | itertools = "0.10.3"
21 | rustyline = "9.1.2"
22 | clap = {version = "3.0.14", features = ["derive"]}
23 | anyhow = "1.0.54"
24 | thiserror = "1.0.30"
25 | # TODO: can maybe delete
26 | quickcheck = "1.0.3"
27 | quickcheck_macros = "1"
28 | include_dir = "0.7.2"
29 | indoc = "1.0.6"
--------------------------------------------------------------------------------
/bin/repl/src/main.rs:
--------------------------------------------------------------------------------
1 | extern crate quickcheck_macros;
2 |
3 | extern crate insta;
4 | mod repl;
5 | use crate::repl::*;
6 |
7 | use clap::Parser;
8 |
9 | #[derive(Parser)]
10 | #[clap(version = "1.0", author = "Me")]
11 | struct Opts {
12 | #[clap(short, long)]
13 | functions_file: Option,
14 | #[clap(short, long)]
15 | stack: Option,
16 | }
17 |
18 | fn main() {
19 | let opts: Opts = Opts::parse();
20 |
21 | start_repl(opts.functions_file, opts.stack);
22 | }
23 |
--------------------------------------------------------------------------------
/bin/repl/src/repl.rs:
--------------------------------------------------------------------------------
1 | use colored::*;
2 | use papyrus::executor::execute;
3 | use papyrus::utils::load_all_procs;
4 | use rustyline::error::ReadlineError;
5 | use rustyline::Editor;
6 | use std::fs;
7 | use std::path::Path;
8 |
9 | //The Scribe Read–eval–print loop or repl for short is a Miden shell that allows for quick and easy debugging with Miden assembly!
10 | //To use the repl, simply type "scribe repl" when in the transpiler crate and the repl will launch.
11 | //Now that you have the repl launched, there are a bunch of awesome things you can do like execute any Miden instruction, use procedures,
12 | //undo executed instructions, check the stack at anytime and more! Check out the list of commands that you can use below. After exiting the
13 | // repl, a history.txt file will be saved
14 |
15 | //Miden Instructions
16 | // Any Miden instruction included in the Miden Assembly HackMD is valid. (Ex. push.0, drop, dropw, swap, cswap, shr, mem.load.n, ect.)
17 | // You can input instructions one by one or multiple instructions in one input.
18 | // Ex.
19 | // push.1
20 | // push.2
21 | // push.3
22 | // Is the same as
23 | // push.1 push.2 push.3
24 |
25 | //`stack`
26 | // Use the `stack` command to check the state of the stack at anytime. When you start the repl, the stack will be empty.
27 | // Try pushing some values and checking the stack!
28 | // Ex.
29 | // push.1 push.2 push.3
30 | // stack
31 | // >> 3 2 1 0 0 0 0 0 0 0 0 0 0 0 0 0
32 |
33 | //`undo`
34 | // Use the `undo` command at anytime to revert to the last state of the stack before a command or Miden instruction. You can use `undo`
35 | // as many times as you want to restore the state of a stack n instructions ago.
36 | // Ex. push.1 push.2 push.3
37 | // stack
38 | // >> 3 2 1 0 0 0 0 0 0 0 0 0 0 0 0 0
39 | // push.4
40 | // stack
41 | // >> 4 3 2 1 0 0 0 0 0 0 0 0 0 0 0 0
42 | // push.5
43 | // stack
44 | // >> 5 4 3 2 1 0 0 0 0 0 0 0 0 0 0 0
45 | // undo
46 | // stack
47 | // >> 4 3 2 1 0 0 0 0 0 0 0 0 0 0 0 0
48 | // undo
49 | // stack
50 | // >> 3 2 1 0 0 0 0 0 0 0 0 0 0 0 0 0
51 |
52 | //`program`
53 | // Use the `program` command at anytime to see the full Miden assembly that you have input to that point as a Miden program
54 | // Ex.
55 | // push.1
56 | // push.2
57 | // push.3
58 | // add
59 | // add
60 | // program
61 | // >>
62 | // begin
63 | // push.1
64 | // push.2
65 | // push.3
66 | // add
67 | // add
68 | // end
69 |
70 | //`help`
71 | // Use the `help` command at any time to see a list of available commands.
72 |
73 | pub fn start_repl(functions_file: Option, stack_string: Option) {
74 | let mut program_lines: Vec = Vec::new();
75 | let mut functions_miden = "".to_string();
76 | if let Some(functions_file) = functions_file {
77 | let path = Path::new(&functions_file);
78 | functions_miden = fs::read_to_string(path).expect("Something went wrong reading the file");
79 | }
80 | if let Some(stack_string) = stack_string {
81 | program_lines.push(
82 | stack_string
83 | .split(',')
84 | .map(|s| format!("push.{}", s))
85 | .collect::>()
86 | .into_iter()
87 | .rev()
88 | .collect::>()
89 | .join(" "),
90 | );
91 | }
92 | let mut rl = Editor::<()>::new();
93 | loop {
94 | let program = format!(
95 | "begin\n{}\nend",
96 | program_lines
97 | .iter()
98 | .map(|l| format!(" {}", l))
99 | .collect::>()
100 | .join("\n")
101 | );
102 | let program_with_procs = format!(
103 | "{}\n{}\n{}",
104 | functions_miden,
105 | load_all_procs(),
106 | program.clone()
107 | );
108 | let result = execute(program_with_procs, vec![]);
109 |
110 | let mut result_string = "".to_string();
111 | if !program_lines.is_empty() {
112 | match result {
113 | Ok(execution_value) => {
114 | let stack = execution_value.last_stack_state();
115 | result_string = format!(
116 | "\n{}",
117 | stack
118 | .iter()
119 | .map(|f| format!("{}", f))
120 | .collect::>()
121 | .join(" "),
122 | );
123 | }
124 | Err(e) => {
125 | result_string = format!("Error running program: {:?}", e);
126 | println!("{}", result_string);
127 | program_lines.pop();
128 | }
129 | }
130 | }
131 | println!();
132 | let readline = rl.readline(&">> ".blue());
133 | match readline {
134 | Ok(line) => {
135 | if line == "program" {
136 | println!("\n{}", program);
137 | } else if line == "help" {
138 | println!("Available commands:");
139 | println!();
140 | println!("stack: display the stack");
141 | println!("undo: remove the last instruction");
142 | println!("program: display the program");
143 | } else if line == "undo" {
144 | let last_line = program_lines.pop().unwrap();
145 | println!("Undoing {}", last_line);
146 | } else if line == "stack" || line == "res" {
147 | println!("{}", result_string);
148 | } else {
149 | rl.add_history_entry(line.clone());
150 | program_lines.push(line.clone());
151 | // println!("{}", line);
152 | }
153 | }
154 | Err(ReadlineError::Interrupted) => {
155 | println!("CTRL-C");
156 | break;
157 | }
158 | Err(ReadlineError::Eof) => {
159 | println!("CTRL-D");
160 | break;
161 | }
162 | Err(err) => {
163 | println!("Error: {:?}", err);
164 | break;
165 | }
166 | };
167 | }
168 | rl.save_history("history.txt").unwrap();
169 | }
170 |
--------------------------------------------------------------------------------
/bin/scribe/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "scribe"
3 | version = "0.1.0"
4 | edition = "2021"
5 |
6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7 |
8 | [[bin]]
9 | name = "scribe"
10 | path = "src/main.rs"
11 |
12 | [dependencies]
13 | papyrus = { path = "../../crates/papyrus" }
14 | pest = "2.0"
15 | pest_derive = "2.0"
16 | miden-assembly = { git = "http://github.com/maticnetwork/miden", branch = "next" }
17 | miden-processor = { git = "http://github.com/maticnetwork/miden", branch = "next" }
18 | miden-core = { git = "http://github.com/maticnetwork/miden", branch = "next" }
19 | hex = "0.4"
20 | colored = "2"
21 | debug_tree = "0.4.0"
22 | insta = "1.12.0"
23 | primitive-types = "0.11.1"
24 | itertools = "0.10.3"
25 | rustyline = "9.1.2"
26 | clap = {version = "3.0.14", features = ["derive"]}
27 | anyhow = "1.0.54"
28 | thiserror = "1.0.30"
29 | # TODO: can maybe delete
30 | quickcheck = "1.0.3"
31 | quickcheck_macros = "1"
32 | include_dir = "0.7.2"
33 | indoc = "1.0.6"
34 |
--------------------------------------------------------------------------------
/bin/scribe/src/main.rs:
--------------------------------------------------------------------------------
1 | use papyrus::ast_optimization::optimize_ast;
2 | use papyrus::miden_generator;
3 | use papyrus::parser;
4 | use papyrus::type_inference::infer_types;
5 |
6 | use papyrus::types::YulFile;
7 | use std::fs;
8 | extern crate quickcheck_macros;
9 |
10 | extern crate insta;
11 |
12 | pub fn write_yul_to_masm(yul_file: YulFile) {
13 | let parsed = parser::parse_yul_syntax(&yul_file.file_contents);
14 | let ast = optimize_ast(parsed);
15 | let ast = infer_types(&ast);
16 |
17 | let miden_code = miden_generator::transpile_program(ast, Default::default());
18 |
19 | fs::write(
20 | format!(
21 | "../masm/{}.masm",
22 | &yul_file.file_path.file_stem().unwrap().to_str().unwrap()
23 | ),
24 | miden_code,
25 | )
26 | .expect("Unable to write Miden to file.");
27 | }
28 |
29 | fn main() {
30 | let yul_contracts = read_yul_contracts();
31 |
32 | //For each contract in Vec of YulFile
33 | for yul_code in yul_contracts {
34 | write_yul_to_masm(yul_code)
35 | }
36 | }
37 |
38 | //Read in all of the Yul contracts from the contracts directory and return a Vec of Yul Files
39 | fn read_yul_contracts() -> Vec {
40 | let mut yul_files: Vec = Vec::new();
41 | let mut paths: Vec<_> = fs::read_dir("../contracts/")
42 | .unwrap()
43 | .map(|r| r.unwrap())
44 | .collect();
45 |
46 | //Sort the files by file name
47 | paths.sort_by_key(|dir| dir.path());
48 |
49 | //For each file, read in the contents and push a YulFile to the yul_files Vec
50 | for path in paths {
51 | let contents = fs::read_to_string(path.path())
52 | .expect("Something went wrong reading from the contracts directory");
53 |
54 | yul_files.push(YulFile {
55 | file_path: path.path(),
56 | file_contents: contents,
57 | });
58 | }
59 |
60 | //Return the yul files
61 | yul_files
62 | }
63 |
--------------------------------------------------------------------------------
/crates/miden-integration-tests/.gitignore:
--------------------------------------------------------------------------------
1 | target/
2 |
--------------------------------------------------------------------------------
/crates/miden-integration-tests/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "miden-integration-tests"
3 | version = "0.1.0"
4 | edition = "2021"
5 | # Disable automatic test target discovery. This allows us to run all the integ tests as a single binary target (lib.rs)
6 | # instead of each integ test file being its own compiled & linked binary which is the default behavior. Linking with
7 | # RocksDB is expensive so we want to minimize the amount of work on ld. This is also how other projects like diesel-rs
8 | # structure their integ tests.
9 | autotests = false
10 | autobenches = false
11 |
12 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
13 | [[test]]
14 | name = "integration_tests"
15 | path = "tests/lib.rs"
16 | harness = true
17 |
18 |
19 | [dependencies]
20 | scribe = {path = "../transpiler/"}
21 | miden-assembly = { git = "http://github.com/maticnetwork/miden", branch = "next" }
22 | miden-processor = { git = "http://github.com/maticnetwork/miden", branch = "next" }
23 | miden-core = { git = "http://github.com/maticnetwork/miden", branch = "next" }
24 | primitive-types = "0.11.1"
25 | quickcheck = "1.0.3"
26 | quickcheck_macros = "1"
27 | tokio = { version = "1.21", features = ["macros", "rt-multi-thread"] }
28 | colored = "2"
29 | indoc = "1.0.6"
30 | insta = "1.12.0"
31 | rstest = "*"
32 |
--------------------------------------------------------------------------------
/crates/miden-integration-tests/snapshots/scribe__parser__tests__parse_assignment.snap:
--------------------------------------------------------------------------------
1 | ---
2 | source: src/parser.rs
3 | assertion_line: 253
4 | expression: "parse_to_tree(\"\n i := 1\n \")"
5 |
6 | ---
7 | AST
8 | └╼ assign - i
9 | └╼ 1
10 |
--------------------------------------------------------------------------------
/crates/miden-integration-tests/snapshots/scribe__parser__tests__parse_cruft.snap:
--------------------------------------------------------------------------------
1 | ---
2 | source: src/parser.rs
3 | assertion_line: 276
4 | expression: parse_to_tree(yul)
5 |
6 | ---
7 | AST
8 |
--------------------------------------------------------------------------------
/crates/miden-integration-tests/snapshots/scribe__parser__tests__parse_fibonnaci.snap:
--------------------------------------------------------------------------------
1 | ---
2 | source: src/parser.rs
3 | assertion_line: 415
4 | expression: "parse_to_tree(\"\n let f := 1\n let s := 1\n let next\n for { let i := 0 } lt(i, 10) { i := add(i, 1)}\n {\n if lt(i, 2) {\n mstore(i, 1)\n }\n if gt(i, 1) {\n next := add(s, f)\n f := s\n s := next\n mstore(i, s)\n }\n }\")"
5 |
6 | ---
7 | AST
8 | ├╼ declare - f:u256
9 | │ └╼ 1:u256
10 | ├╼ declare - s:u256
11 | │ └╼ 1:u256
12 | ├╼ declare - next:u256
13 | └╼ for loop
14 | ├╼ init block
15 | │ └╼ declare - i:u256
16 | │ └╼ 0:u256
17 | ├╼ conditional
18 | │ └╼ lt(u256, u256): u256
19 | │ ├╼ var - i:u256
20 | │ └╼ 10:u256
21 | ├╼ after block
22 | │ └╼ assign - i:u256
23 | │ └╼ add(u256, u256): u256
24 | │ ├╼ var - i:u256
25 | │ └╼ 1:u256
26 | └╼ interior block
27 | ├╼ if statement
28 | │ └╼ conditional
29 | │ ├╼ lt(u256, u256): u256
30 | │ │ ├╼ var - i:u256
31 | │ │ └╼ 2:u256
32 | │ └╼ mstore(u256, u256): u256
33 | │ ├╼ var - i:u256
34 | │ └╼ 1:u256
35 | └╼ if statement
36 | └╼ conditional
37 | ├╼ gt(u256, u256): u256
38 | │ ├╼ var - i:u256
39 | │ └╼ 1:u256
40 | ├╼ assign - next:u256
41 | │ └╼ add(u256, u256): u256
42 | │ ├╼ var - s:u256
43 | │ └╼ var - f:u256
44 | ├╼ assign - f:u256
45 | │ └╼ var - s:u256
46 | ├╼ assign - s:u256
47 | │ └╼ var - next:u256
48 | └╼ mstore(u256, u256): u256
49 | ├╼ var - i:u256
50 | └╼ var - s:u256
51 |
--------------------------------------------------------------------------------
/crates/miden-integration-tests/snapshots/scribe__parser__tests__parse_function_call.snap:
--------------------------------------------------------------------------------
1 | ---
2 | source: src/parser.rs
3 | assertion_line: 391
4 | expression: "parse_to_tree(\"add(1,2)\")"
5 |
6 | ---
7 | AST
8 | └╼ add(u256, u256):
9 | ├╼ 1:u256
10 | └╼ 2:u256
11 |
--------------------------------------------------------------------------------
/crates/miden-integration-tests/snapshots/scribe__parser__tests__parse_function_def.snap:
--------------------------------------------------------------------------------
1 | ---
2 | source: src/parser.rs
3 | assertion_line: 453
4 | expression: "parse_to_tree(\"\n function allocate_unbounded() -> memPtr {\n memPtr := mload(64)\n }\")"
5 |
6 | ---
7 | AST
8 | └╼ function definition - allocate_unbounded
9 | ├╼ params
10 | ├╼ returns
11 | │ └╼ memPtr:u32
12 | └╼ body
13 | └╼ assign - memPtr:u32
14 | └╼ mload(u32): u32
15 | └╼ 64:u32
16 |
--------------------------------------------------------------------------------
/crates/miden-integration-tests/snapshots/scribe__parser__tests__parse_function_def_with_return.snap:
--------------------------------------------------------------------------------
1 | ---
2 | source: src/parser.rs
3 | assertion_line: 479
4 | expression: "parse_to_tree(\"\n function allocate_unbounded() -> memPtr {\n memPtr := mload(64)\n }\")"
5 |
6 | ---
7 | AST
8 | └╼ function definition - allocate_unbounded
9 | ├╼ params
10 | ├╼ returns
11 | │ └╼ memPtr:u256
12 | └╼ body
13 | └╼ assign - memPtr:u256
14 | └╼ mload(u32): u256
15 | └╼ 64:u32
16 |
--------------------------------------------------------------------------------
/crates/miden-integration-tests/snapshots/scribe__parser__tests__parse_function_def_without_return.snap:
--------------------------------------------------------------------------------
1 | ---
2 | source: src/parser.rs
3 | assertion_line: 489
4 | expression: "parse_to_tree(\"\n function allocate_unbounded() {\n let memPtr := mload(64)\n }\")"
5 |
6 | ---
7 | AST
8 | └╼ function definition - allocate_unbounded
9 | ├╼ params
10 | ├╼ returns
11 | └╼ body
12 | └╼ declare - memPtr:u256
13 | └╼ mload(u32): u256
14 | └╼ 64:u32
15 |
--------------------------------------------------------------------------------
/crates/miden-integration-tests/snapshots/scribe__parser__tests__parse_if.snap:
--------------------------------------------------------------------------------
1 | ---
2 | source: src/parser.rs
3 | assertion_line: 437
4 | expression: "parse_to_tree(\"\n if lt(i, 2) {\n mstore(i, 1)\n }\n \")"
5 |
6 | ---
7 | AST
8 | └╼ if statement
9 | └╼ conditional
10 | ├╼ lt(unknown, u256):
11 | │ ├╼ var - i:unknown
12 | │ └╼ 2:u256
13 | └╼ mstore(unknown, u256):
14 | ├╼ var - i:unknown
15 | └╼ 1:u256
16 |
--------------------------------------------------------------------------------
/crates/miden-integration-tests/snapshots/scribe__parser__tests__parse_reference_chain.snap:
--------------------------------------------------------------------------------
1 | ---
2 | source: src/parser.rs
3 | assertion_line: 477
4 | expression: "parse_to_tree(\"\n function fun__spendAllowance_564(var_owner_524, var_spender_526, var_amount_528) {\n let _110 := var_owner_524\n let expr_534 := _110\n }\")"
5 |
6 | ---
7 | AST
8 | └╼ function definition - fun__spendAllowance_564
9 | ├╼ params
10 | │ ├╼ var_owner_524:u32
11 | │ ├╼ var_spender_526:u32
12 | │ └╼ var_amount_528:u32
13 | ├╼ returns
14 | └╼ body
15 | ├╼ declare - _110:u32
16 | │ └╼ var - var_owner_524:u32
17 | └╼ declare - expr_534:u32
18 | └╼ var - _110:u32
19 |
--------------------------------------------------------------------------------
/crates/miden-integration-tests/snapshots/scribe__parser__tests__parse_switch_statement.snap:
--------------------------------------------------------------------------------
1 | ---
2 | source: src/parser.rs
3 | assertion_line: 508
4 | expression: "parse_to_tree(\"\n let x := 5\n let y := 8\n switch x\n case 3 {\n y := 5\n }\n case 5 {\n y := 12\n let z := 15\n }\n case 8 {\n y := 15\n }\n y\")"
5 |
6 | ---
7 | AST
8 | ├╼ declare - x:u256
9 | │ └╼ 5:u256
10 | ├╼ declare - y:u256
11 | │ └╼ 8:u256
12 | ├╼ switch
13 | │ ├╼ var - x:u256
14 | │ ├╼ case
15 | │ │ └╼ assign - y:u256
16 | │ │ └╼ 5:u256
17 | │ ├╼ case
18 | │ │ ├╼ assign - y:u256
19 | │ │ │ └╼ 12:u256
20 | │ │ └╼ declare - z:u256
21 | │ │ └╼ 15:u256
22 | │ └╼ case
23 | │ └╼ assign - y:u256
24 | │ └╼ 15:u256
25 | └╼ var - y:u256
26 |
--------------------------------------------------------------------------------
/crates/miden-integration-tests/snapshots/scribe__parser__tests__parse_var_and_add.snap:
--------------------------------------------------------------------------------
1 | ---
2 | source: src/parser.rs
3 | assertion_line: 396
4 | expression: "parse_to_tree(\"let x := add(1,2)\")"
5 |
6 | ---
7 | AST
8 | └╼ declare - x:u256
9 | └╼ add(u256, u256): u256
10 | ├╼ 1:u256
11 | └╼ 2:u256
12 |
--------------------------------------------------------------------------------
/crates/miden-integration-tests/snapshots/scribe__parser__tests__parse_var_declaration.snap:
--------------------------------------------------------------------------------
1 | ---
2 | source: src/parser.rs
3 | assertion_line: 373
4 | expression: "parse_to_tree(\"let x := 1\n let y := 2\")"
5 |
6 | ---
7 | AST
8 | ├╼ declare - x:u256
9 | │ └╼ 1:u256
10 | └╼ declare - y:u256
11 | └╼ 2:u256
12 |
--------------------------------------------------------------------------------
/crates/miden-integration-tests/snapshots/scribe__parser__tests__parse_var_declaration_with_types.snap:
--------------------------------------------------------------------------------
1 | ---
2 | source: src/parser.rs
3 | assertion_line: 381
4 | expression: "parse_to_tree(\"let x:u32 := 1\n let y:u256 := 2\n let z := 2\n \")"
5 |
6 | ---
7 | AST
8 | ├╼ declare - x:u32
9 | │ └╼ 1:u32
10 | ├╼ declare - y:u256
11 | │ └╼ 2:u256
12 | └╼ declare - z:u256
13 | └╼ 2:u256
14 |
--------------------------------------------------------------------------------
/crates/miden-integration-tests/snapshots/scribe__parser__tests__snapshot_test.snap:
--------------------------------------------------------------------------------
1 | ---
2 | source: src/parser.rs
3 | assertion_line: 215
4 | expression: expressions_to_tree(&parse_yul_syntax(yul))
5 |
6 | ---
7 | AST
8 | ├╼ declare - x
9 | │ └╼ 1
10 | └╼ declare - y
11 | └╼ 2
12 |
--------------------------------------------------------------------------------
/crates/miden-integration-tests/src/lib.rs:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/crates/miden-integration-tests/test_output.masm:
--------------------------------------------------------------------------------
1 | use.std::math::u256
2 |
3 |
4 | begin
5 | # and() #
6 | # u256 literal: 0 #
7 | push.0 push.0 push.0 push.0 push.0 push.0 push.0 push.0
8 |
9 | # u256 literal: 0 #
10 | push.0 push.0 push.0 push.0 push.0 push.0 push.0 push.0
11 |
12 | exec.u256::and
13 | end
--------------------------------------------------------------------------------
/crates/miden-integration-tests/tests/bugfixes.rs:
--------------------------------------------------------------------------------
1 | use crate::utils::{run_example, MidenResult};
2 |
3 | #[test]
4 | fn test_is_zero() {
5 | run_example(
6 | "
7 | let five:u32 := 5
8 | let x:u32 := iszero(five)
9 | x
10 | ",
11 | MidenResult::U32(0),
12 | );
13 | }
14 |
15 | #[test]
16 | fn test_is_zero_u256() {
17 | run_example(
18 | "
19 | let five:u256 := 1157923731619542357098500868790785326998466564056403945758400791312963995
20 | let x:u256 := iszero(five)
21 | x
22 | ",
23 | MidenResult::U32(0),
24 | );
25 | }
26 |
--------------------------------------------------------------------------------
/crates/miden-integration-tests/tests/future.rs:
--------------------------------------------------------------------------------
1 | use primitive_types::U256;
2 | use crate::utils::{run_example, MidenResult};
3 |
4 | #[ignore]
5 | #[test]
6 | fn u256_sqrt() {
7 | run_example(
8 | "
9 | let x:u256 := 100 // Find sqrt of x
10 | // Start off with z at 1.
11 | let z:u256 := 1
12 |
13 | // Used below to help find a nearby power of 2.
14 | let y:u256 := x
15 |
16 | // Find the lowest power of 2 that is at least sqrt(x).
17 | if iszero(lt(y, 0x100000000000000000000000000000000)) {
18 | y := shr(128, y) // Like dividing by 2 ** 128.
19 | z := shl(64, z)
20 | }
21 | if iszero(lt(y, 0x10000000000000000)) {
22 | y := shr(64, y) // Like dividing by 2 ** 64.
23 | z := shl(32, z)
24 | }
25 | if iszero(lt(y, 0x100000000)) {
26 | y := shr(32, y) // Like dividing by 2 ** 32.
27 | z := shl(16, z)
28 | }
29 | if iszero(lt(y, 0x10000)) {
30 | y := shr(16, y) // Like dividing by 2 ** 16.
31 | z := shl(8, z)
32 | }
33 | if iszero(lt(y, 0x100)) {
34 | y := shr(8, y) // Like dividing by 2 ** 8.
35 | z := shl(4, z)
36 | }
37 | if iszero(lt(y, 0x10)) {
38 | y := shr(4, y) // Like dividing by 2 ** 4.
39 | z := shl(2, z)
40 | }
41 | if iszero(lt(y, 0x8)) {
42 | // Equivalent to 2 ** z.
43 | z := shl(1, z)
44 | }
45 |
46 | // Shifting right by 1 is like dividing by 2.
47 | z := shr(1, add(z, div(x, z)))
48 | z := shr(1, add(z, div(x, z)))
49 | z := shr(1, add(z, div(x, z)))
50 | z := shr(1, add(z, div(x, z)))
51 | z := shr(1, add(z, div(x, z)))
52 | z := shr(1, add(z, div(x, z)))
53 | z := shr(1, add(z, div(x, z)))
54 |
55 | // Compute a rounded down version of z.
56 | let zRoundDown:u256 := div(x, z)
57 |
58 | // If zRoundDown is smaller, use it.
59 | if lt(zRoundDown, z) {
60 | z := zRoundDown
61 | }
62 | ",
63 | MidenResult::U256(U256::from_dec_str("10").unwrap()),
64 | );
65 | }
66 |
--------------------------------------------------------------------------------
/crates/miden-integration-tests/tests/lib.rs:
--------------------------------------------------------------------------------
1 | #[macro_use]
2 | extern crate quickcheck;
3 | mod future;
4 | mod milestone_1;
5 | mod milestone_2;
6 | mod quickcheck_tests;
7 | mod test;
8 | mod utils;
9 |
--------------------------------------------------------------------------------
/crates/miden-integration-tests/tests/lifetime.rs:
--------------------------------------------------------------------------------
1 | use crate::utils::compile_example;
2 | use indoc::indoc;
3 |
4 | #[test]
5 | fn variable_life() {
6 | // Will probably have to disable some optimizations for this
7 | //
8 | // When a var would have been pushed to memory, it should instead be allowed to fall out of the
9 | // addressable part of the stack, if it's no longer used
10 | compile_example(
11 | "
12 | // Test mstore and mload
13 | mstore(0x20, 67677686778768)
14 | let b:u256 := mload(0x20)
15 | let c:u256 := add(b, 1000)
16 | mstore(0x20, c)
17 | let d:u256 = mload(0x20)
18 | // assert the value of d
19 | d
20 | ",
21 | todo!(),
22 | );
23 | }
24 |
25 | #[test]
26 | fn test_folding() {
27 | compile_example(
28 | "
29 | let a:u256 := add(100, 5)
30 | let b:u256 := mul(a, 10)
31 | let c:u256 := div(b, 5)
32 | let d:u256 := sub(c, 1)
33 | // Assert this folds into a single PUSH statement
34 | ",
35 | todo!(),
36 | );
37 | }
38 |
39 | #[test]
40 | fn test_lifetime() {
41 | compile_example(
42 | "
43 | let a:u256 := 3485488493484388458349458
44 | let b:u256 := 43589348589349845838993489493
45 | let c:u256 = add(a, b)
46 | let d:u256 = add(a, c)
47 | ",
48 | todo!(),
49 | );
50 | }
51 |
--------------------------------------------------------------------------------
/crates/miden-integration-tests/tests/memory.rs:
--------------------------------------------------------------------------------
1 | use crate::utils::{run_example, MidenResult};
2 | use primitive_types::U256;
3 |
4 | #[test]
5 | fn mstore_mload_u256() {
6 | run_example(
7 | "
8 | let x:u256 := 2156795733811448305138118958686944006956945342567680366977754542899210
9 | mstore(100,x)
10 | mload(100)
11 | ",
12 | MidenResult::U256(
13 | U256::from_dec_str(
14 | "2156795733811448305138118958686944006956945342567680366977754542899210",
15 | )
16 | .unwrap(),
17 | ),
18 | );
19 | }
20 |
21 | #[test]
22 | fn mstore_mload_u32() {
23 | run_example(
24 | "
25 | let x:u32 := 700
26 | mstore(100,x)
27 | mload(100)
28 | ",
29 | MidenResult::U32(700),
30 | );
31 | }
32 |
33 | #[test]
34 | fn sum_memory_u32() {
35 | run_example(
36 | "
37 | function sum_from_memory(offset:u32,size:u32) -> b:u32 {
38 | let b:u32 := 0
39 | for { let i:u32 := offset } lt(i, add(offset, size)) { i := add(i, 1)} {
40 | b := add(b, mload(i))
41 | }
42 | b
43 | }
44 | let x:u32 := 1
45 | mstore(100,x)
46 | mstore(101,x)
47 | mstore(102,x)
48 | mstore(103,x)
49 | mstore(104,x)
50 | sum_from_memory(100, 5)
51 | ",
52 | MidenResult::U32(5),
53 | );
54 | }
55 |
56 | #[test]
57 | fn sum_memory_u256() {
58 | run_example(
59 | "
60 | function sum_from_memory(offset:u32,size:u32) -> b:u256 {
61 | let b:u256 := 0
62 | for { let i:u32 := offset } lt(i, add(offset, size)) { i := add(i, 1)} {
63 | b := add(b, mload(i))
64 | }
65 | b
66 | }
67 | let x:u256 := 1
68 | mstore(100,x)
69 | mstore(101,x)
70 | mstore(102,x)
71 | mstore(103,x)
72 | mstore(104,x)
73 | mstore(105,x)
74 | let offset:u32 := 100
75 | let size:u32 := 6
76 | sum_from_memory(offset, size)
77 | ",
78 | MidenResult::U256(U256::from(6)),
79 | );
80 | }
81 |
82 | #[test]
83 | fn memory_test() {
84 | compile_example(
85 | "
86 | // populate memory
87 | mstore(0x20, 1)
88 | mstore(0x21, 2)
89 | mstore(0x22, 3)
90 |
91 | // declare variables - we read from memory to make sure constant folding doesn't kick in
92 | let a:u256 := mload(0x20)
93 | let b:u256 := mload(0x21)
94 | let c:u256 := mload(0x22)
95 |
96 | // perform some operations with the variables
97 | b := add(b, 100)
98 | c := add(c, a)
99 | c := add(c, b)
100 | ",
101 | todo!(),
102 | );
103 | }
104 |
--------------------------------------------------------------------------------
/crates/miden-integration-tests/tests/optimization.rs:
--------------------------------------------------------------------------------
1 | use crate::utils::compile_example;
2 | use indoc::indoc;
3 |
4 | #[test]
5 | fn optimization_basic_constant_replacement() {
6 | compile_example(
7 | "
8 | let x:u32 := 10
9 | x
10 | ",
11 | indoc! {"
12 | begin
13 | push.10
14 | end
15 | "},
16 | );
17 | }
18 |
19 | #[test]
20 | fn optimization_basic_constant_replacement_2() {
21 | compile_example(
22 | "
23 | let x:u32 := 10
24 | let y:u32 := 5
25 | add(x, y)
26 | ",
27 | indoc! {"
28 | begin
29 | push.15
30 | end
31 | "},
32 | );
33 | }
34 |
35 | #[test]
36 | fn optimization_unused_var() {
37 | compile_example(
38 | "
39 | let x:u32 := 1
40 | 5
41 | ",
42 | indoc! {"
43 | begin
44 | push.5
45 | end
46 | "},
47 | );
48 | }
49 |
50 | #[test]
51 | fn optimization_last_use() {
52 | // We'll have to disable constant elimination for this one
53 | // The point is the `movup` instruction that gets outputted instead of dup, since we don't need
54 | // to keep a copy on the stack anymore
55 | compile_example(
56 | "
57 | let x:u32 := 1
58 | let y:u32 := add(x, 2)
59 | let z:u32 := add(x, 3)
60 | ",
61 | indoc! {"
62 | begin
63 | push.1
64 | dup.0
65 | push.2
66 | u32add
67 | movup.1
68 | push.3
69 | add
70 | end
71 | "},
72 | );
73 | }
74 |
75 | #[test]
76 | fn optimization_let_old_vars_die() {
77 | // Will probably have to disable some optimizations for this
78 | //
79 | // When a var would have been pushed to memory, it should instead be allowed to fall out of the
80 | // addressable part of the stack, if it's no longer used
81 | compile_example(
82 | "
83 | let x1:u32 := 1
84 | let x2:u32 := 2
85 | let x3:u32 := 3
86 | let x4:u32 := 4
87 | let x5:u32 := 5
88 | let x6:u32 := 6
89 | let x7:u32 := 7
90 | let x8:u32 := 8
91 | let x9:u32 := 9
92 | let x10:u32 := 10
93 | let x11:u32 := 11
94 | let x12:u32 := 12
95 | let x13:u32 := 13
96 | let x14:u32 := 14
97 | let x15:u32 := 15
98 | let x16:u32 := 16
99 | let x17:u32 := 17
100 | x17
101 | ",
102 | indoc! {"
103 | begin
104 | push.1
105 | push.2
106 | push.3
107 | push.4
108 | push.5
109 | push.6
110 | push.7
111 | push.8
112 | push.9
113 | push.10
114 | push.11
115 | push.12
116 | push.13
117 | push.14
118 | push.15
119 | push.16
120 | push.17
121 | end
122 | "},
123 | );
124 | }
125 |
126 | #[test]
127 | fn optimization_let_old_vars_die_v2() {
128 | // Will probably have to disable some optimizations for this
129 | //
130 | // When a var would have been pushed to memory, it should instead be allowed to fall out of the
131 | // addressable part of the stack, if it's no longer used
132 | compile_example(
133 | "
134 | let x1;u256 := 1
135 | let x2:u256 := 2
136 | let x3:u256 := 3
137 | x3
138 | ",
139 | indoc! {"
140 | begin
141 | // Assert similarly to the test above to make sure old variables die
142 | end
143 | "},
144 | );
145 | }
146 |
--------------------------------------------------------------------------------
/crates/miden-integration-tests/tests/quickcheck_tests.rs:
--------------------------------------------------------------------------------
1 | use crate::utils::{miden_to_u256, MidenResult};
2 | use miden_core::StarkField;
3 | use quickcheck::{Arbitrary, Gen, TestResult};
4 | use quickcheck_macros::quickcheck;
5 | use scribe::{
6 | executor::execute,
7 | utils::{convert_u256_to_pushes, join_u32s_to_u256, load_all_procs, split_u256_to_u32s},
8 | };
9 |
10 | #[derive(Clone, Debug)]
11 | struct U256(primitive_types::U256);
12 |
13 | // A reduced range for each u32, to make debugging easier, also tends to find failing cases more
14 | // often because it's vastly more likely that two u32 values will be the same
15 | #[derive(Clone, Debug)]
16 | struct U256Small(primitive_types::U256);
17 |
18 | impl Arbitrary for U256 {
19 | fn arbitrary(g: &mut Gen) -> U256 {
20 | let bytes = (0..32).map(|_| u8::arbitrary(g)).collect::>();
21 | U256(primitive_types::U256::from_little_endian(&bytes))
22 | }
23 | }
24 |
25 | impl Arbitrary for U256Small {
26 | fn arbitrary(g: &mut Gen) -> U256Small {
27 | let bytes = (0..32)
28 | .map(|i| if i % 4 == 0 { u8::arbitrary(g) / 64 } else { 0 })
29 | .collect::>();
30 | U256Small(primitive_types::U256::from_little_endian(&bytes))
31 | }
32 | }
33 |
34 | fn run_miden_function(
35 | proc: &str,
36 | stack: Vec,
37 | expected: MidenResult,
38 | ) -> TestResult {
39 | let program = format!(
40 | "use.std::math::u256\n{}\nbegin\n{}\n{}\nend",
41 | load_all_procs(),
42 | stack
43 | .iter()
44 | .map(convert_u256_to_pushes)
45 | .collect::>()
46 | .join("\n"),
47 | proc
48 | );
49 | println!("{}", program);
50 | let result = execute(program, vec![]);
51 | let execution_value = result.unwrap();
52 | match expected {
53 | MidenResult::U256(expected) => {
54 | let output_stack = execution_value.last_stack_state();
55 | let stack_result = miden_to_u256(execution_value);
56 | println!("Expected: {}", expected);
57 | println!("Output : {}", stack_result);
58 | println!(
59 | "O Stack : {:?}",
60 | output_stack
61 | .iter()
62 | .take(8)
63 | .map(|x| x.as_int())
64 | .collect::>()
65 | );
66 | println!("E Stack : {:?}", split_u256_to_u32s(&expected));
67 | TestResult::from_bool(stack_result == expected)
68 | }
69 | MidenResult::U32(expected) => {
70 | let stack_result = execution_value.last_stack_state().first().unwrap().as_int();
71 | println!("Expected: {}", expected);
72 | println!("Output : {}", stack_result);
73 | TestResult::from_bool(stack_result == expected.into())
74 | }
75 | }
76 | }
77 |
78 | #[ignore]
79 | #[quickcheck]
80 | fn split_and_join(x: U256) -> TestResult {
81 | let res = join_u32s_to_u256(split_u256_to_u32s(&x.0));
82 | TestResult::from_bool(x.0 == res)
83 | }
84 |
85 | #[ignore]
86 | #[quickcheck]
87 | fn addition(x: U256, y: U256) -> TestResult {
88 | let (expected, overflowed) = x.0.overflowing_add(y.0);
89 | if overflowed {
90 | return TestResult::discard();
91 | }
92 | run_miden_function(
93 | "exec.u256::add_unsafe",
94 | vec![x.0, y.0],
95 | MidenResult::U256(expected),
96 | )
97 | }
98 |
99 | #[quickcheck]
100 | fn multiplication(x: U256, y: U256) -> TestResult {
101 | let (expected, _overflowed) = (x.0).overflowing_mul(y.0);
102 | run_miden_function(
103 | "exec.u256::mul_unsafe",
104 | vec![(x.0), (y.0)],
105 | MidenResult::U256(expected),
106 | )
107 | }
108 |
109 | #[ignore]
110 | #[quickcheck]
111 | fn shl(x: U256) -> TestResult {
112 | let expected = x.0 << 1_u32;
113 | run_miden_function(
114 | "exec.u256shl_unsafe",
115 | vec![x.0],
116 | MidenResult::U256(expected),
117 | )
118 | }
119 |
120 | #[ignore]
121 | #[quickcheck]
122 | fn less_than(x: U256Small, y: U256Small) -> TestResult {
123 | let expected = x.0 < y.0;
124 | run_miden_function(
125 | "exec.u256lt_unsafe",
126 | vec![x.0, y.0],
127 | MidenResult::U32(if expected { 1 } else { 0 }),
128 | )
129 | }
130 |
131 | #[ignore]
132 | #[quickcheck]
133 | fn greater_than(x: U256Small, y: U256Small) -> TestResult {
134 | let expected = x.0 > y.0;
135 | run_miden_function(
136 | "exec.u256gt_unsafe",
137 | vec![x.0, y.0],
138 | MidenResult::U32(if expected { 1 } else { 0 }),
139 | )
140 | }
141 |
142 | #[ignore]
143 | #[quickcheck]
144 | fn less_than_or_equal_to(x: U256Small, y: U256Small) -> TestResult {
145 | let expected = x.0 <= y.0;
146 | run_miden_function(
147 | "exec.u256lte_unsafe",
148 | vec![x.0, y.0],
149 | MidenResult::U32(if expected { 1 } else { 0 }),
150 | )
151 | }
152 |
153 | #[ignore]
154 | #[quickcheck]
155 | fn greater_than_or_equal_to(x: U256Small, y: U256Small) -> TestResult {
156 | let expected = x.0 >= y.0;
157 | run_miden_function(
158 | "exec.u256gte_unsafe",
159 | vec![x.0, y.0],
160 | MidenResult::U32(if expected { 1 } else { 0 }),
161 | )
162 | }
163 |
164 | #[ignore]
165 | #[quickcheck]
166 | fn shr(x: U256) -> TestResult {
167 | let expected = x.0 >> 1_u32;
168 | run_miden_function(
169 | "exec.u256shr_unsafe",
170 | vec![x.0],
171 | MidenResult::U256(expected),
172 | )
173 | }
174 |
175 | #[ignore]
176 | #[quickcheck]
177 | fn auto_and(x: U256, y: U256) -> TestResult {
178 | let expected = x.0 & y.0;
179 | run_miden_function(
180 | "exec.u256::and",
181 | vec![x.0, y.0],
182 | MidenResult::U256(expected),
183 | )
184 | }
185 |
186 | #[ignore]
187 | #[quickcheck]
188 | fn quickcheck_subtraction(x: U256, y: U256) -> TestResult {
189 | let (expected, underflowed) = x.0.overflowing_sub(y.0);
190 | if underflowed {
191 | return TestResult::discard();
192 | }
193 | run_miden_function(
194 | "exec.u256::sub_unsafe",
195 | vec![x.0, y.0],
196 | MidenResult::U256(expected),
197 | )
198 | }
199 |
200 | #[ignore]
201 | #[quickcheck]
202 | fn quickcheck_literals(x: U256) -> TestResult {
203 | let expected = x.0;
204 | run_miden_function("", vec![x.0], MidenResult::U256(expected))
205 | }
206 |
207 | #[ignore]
208 | #[test]
209 | fn subtraction_with_addition_overflow() {
210 | let x = join_u32s_to_u256(vec![0, 0, 0, 0, 0, 4, 0, 1]);
211 | let y = join_u32s_to_u256(vec![0, 0, 0, 0, 0, 0, u32::max_value(), 2]);
212 | dbg!(x, y);
213 | let expected = x - y;
214 | dbg!(expected);
215 | let test_result = run_miden_function(
216 | "exec.u256::sub_unsafe",
217 | vec![x, y],
218 | MidenResult::U256(expected),
219 | );
220 | dbg!(&test_result);
221 | assert!(!test_result.is_failure());
222 | }
223 |
224 | #[test]
225 | fn multiplication_all_limbs() {
226 | let x = join_u32s_to_u256(vec![8, 7, 6, 5, 4, 3, 2, 1]);
227 | let y = join_u32s_to_u256(vec![1, 1, 1, 1, 1, 1, 1, 1]);
228 | dbg!(x, y);
229 | let (expected, _) = x.overflowing_mul(y);
230 | dbg!(expected);
231 | let test_result = run_miden_function(
232 | "exec.u256::mul_unsafe",
233 | vec![x, y],
234 | MidenResult::U256(expected),
235 | );
236 | dbg!(&test_result);
237 | assert!(!test_result.is_failure());
238 | }
239 |
240 | fn reverse(xs: &[T]) -> Vec {
241 | let mut rev = vec![];
242 | for x in xs {
243 | rev.insert(0, x.clone())
244 | }
245 | rev
246 | }
247 |
248 | #[quickcheck]
249 | fn double_reversal_is_identity(xs: Vec) -> bool {
250 | xs == reverse(&reverse(&xs))
251 | }
252 |
--------------------------------------------------------------------------------
/crates/miden-integration-tests/tests/test.rs:
--------------------------------------------------------------------------------
1 | use primitive_types::U256;
2 | use crate::utils::{run_example, MidenResult};
3 |
4 | #[test]
5 | fn integration_math() {
6 | run_example("add(1, 2)", MidenResult::U256(U256::from(3)));
7 | run_example("mul(2, 3)", MidenResult::U256(U256::from(6)));
8 | run_example("mul(2, 3)", MidenResult::U256(U256::from(6)));
9 | run_example("sub(4, 2)", MidenResult::U256(U256::from(2)));
10 | // run_example("div(8, 2)", MidenResult::U256(U256::from(4)));
11 | }
12 |
13 | #[test]
14 | fn integration_boolean() {
15 | run_example("lt(2, 6)", MidenResult::U32(1));
16 | run_example("lt(6, 2)", MidenResult::U32(0));
17 | run_example("eq(2, 2)", MidenResult::U32(1));
18 | run_example("eq(4, 2)", MidenResult::U32(0));
19 | run_example("or(1, 0)", MidenResult::U256(U256::from(1)));
20 | run_example("or(0, 0)", MidenResult::U256(U256::from(0)));
21 | run_example("and(1, 1)", MidenResult::U256(U256::from(1)));
22 | run_example("and(0, 1)", MidenResult::U256(U256::from(0)));
23 | run_example("and(0, 0)", MidenResult::U256(U256::from(0)));
24 | }
25 |
26 | #[test]
27 | fn integration_variables() {
28 | run_example(
29 | "
30 | let x := 2
31 | let y := 3
32 | x := 4
33 | add(x, y)
34 | ",
35 | MidenResult::U256(U256::from(7)),
36 | );
37 | }
38 |
39 | #[test]
40 | fn integration_if() {
41 | run_example(
42 | "
43 | let x := 2
44 | let y := 3
45 | if lt(x, y) {
46 | x := 5
47 | }
48 | x
49 | ",
50 | MidenResult::U256(U256::from(5)),
51 | );
52 | }
53 |
54 | #[test]
55 | fn integration_function() {
56 | run_example(
57 | "
58 | function square(a) -> b {
59 | let b := mul(a, a)
60 | }
61 | function secret() -> c {
62 | let c := 42
63 | }
64 | mul(square(3), secret())
65 | ",
66 | MidenResult::U256(U256::from(378)),
67 | );
68 | }
69 |
70 | #[test]
71 | fn integration_for() {
72 | run_example(
73 | "
74 | let x := 2
75 | for { let i := 0 } lt(i, 5) { i := add(i, 1)} {
76 | x := 3
77 | }
78 | i
79 | ",
80 | MidenResult::U256(U256::from(5)),
81 | );
82 | }
83 |
84 | #[test]
85 | fn integration_fib() {
86 | run_example(
87 | "
88 | let a:u32 := 0
89 | let b:u32 := 1
90 | let c:u32 := 0
91 |
92 | for { let i:u32 := 0 } lt(i, n) { i := add(i, 1)}
93 | {
94 | c := add(a,b)
95 | a := b
96 | b := c
97 | }
98 | b
99 | ",
100 | MidenResult::U256(U256::from(89)),
101 | );
102 | }
103 |
104 | #[test]
105 | fn integration_case() {
106 | run_example(
107 | "
108 | let y := 8
109 | let x := 5
110 | switch x
111 | case 3 {
112 | y := 5
113 | }
114 | case 5 {
115 | y := 12
116 | let z := 15
117 | }
118 | case 8 {
119 | y := 15
120 | }
121 | y
122 | ",
123 | MidenResult::U256(U256::from(12)),
124 | );
125 | }
126 |
127 | #[test]
128 | fn integration_lots_of_vars_u32() {
129 | run_example(
130 | "
131 | let x1:u32 := 1
132 | let x2:u32 := 2
133 | let x3:u32 := 3
134 | let x4:u32 := 4
135 | let x5:u32 := 5
136 | let x6:u32 := 6
137 | let x7:u32 := 7
138 | let x8:u32 := 8
139 | let x9:u32 := 9
140 | let x10:u32 := 10
141 | let x11:u32 := 11
142 | let x12:u32 := 12
143 | let x13:u32 := 13
144 | let x14:u32 := 14
145 | let x15:u32 := 15
146 | let x16:u32 := 16
147 | let x17:u32 := 17
148 | let x18:u32 := 18
149 | x1
150 | ",
151 | MidenResult::U32(1),
152 | );
153 | }
154 |
155 | #[test]
156 | fn integration_lots_of_vars() {
157 | run_example(
158 | "
159 | let x1 := 1
160 | let x2 := 2
161 | let x3 := 3
162 | let x4 := 4
163 | let x5 := 5
164 | let x6 := 6
165 | let x7 := 7
166 | let x8 := 8
167 | let x9 := 9
168 | let x10 := 10
169 | let x11 := 11
170 | let x12 := 12
171 | let x13 := 13
172 | let x14 := 14
173 | let x15 := 15
174 | let x16 := 16
175 | let x17 := 17
176 | let x18 := 18
177 | x1
178 | ",
179 | MidenResult::U256(U256::from(1)),
180 | );
181 | }
182 |
183 | #[ignore]
184 | #[test]
185 | fn integration_mstore() {
186 | run_example(
187 | "
188 | let x1:u32 := 1
189 | mstore(42, x1)
190 | mload(42)
191 | ",
192 | MidenResult::U256(U256::from(1)),
193 | );
194 | }
195 |
--------------------------------------------------------------------------------
/crates/miden-integration-tests/tests/u256.rs:
--------------------------------------------------------------------------------
1 | use crate::utils::{run_example, MidenResult};
2 | use primitive_types::U256;
3 |
4 | #[test]
5 | fn u256_hex_literal() {
6 | run_example(
7 | "
8 | let x:u256 := 0x1F6F1604415806848692A606A47
9 | x
10 | ",
11 | MidenResult::U256(U256::from_dec_str("39847239847923879823657234623047").unwrap()),
12 | );
13 | }
14 |
15 | #[test]
16 | fn u256_literal() {
17 | run_example(
18 | "
19 | let x:u256 := 39847239847923879823657234623047
20 | ",
21 | MidenResult::U256(U256::from_dec_str("39847239847923879823657234623047").unwrap()),
22 | );
23 | }
24 |
25 | #[test]
26 | fn u256_add() {
27 | run_example(
28 | // x = 10 + (20 << 32) + (30 << 64) + (40 << 96) + (50 << 128) + (60 << 160) + (70 << 192) + (80 << 224)
29 | // y = 1 + (2 << 32) + (3 << 64) + (4 << 96) + (5 << 128) + (6 << 160) + (7 << 192) + (8 << 224)
30 | "
31 | let x:u256 := 2156795733811448305138118958686944006956945342567680366977754542899210
32 | let y:u256 := 215679573381144830513811895868694400695694534256768036697775454289921
33 | add(y, x)
34 | ",
35 | MidenResult::U256(
36 | U256::from_dec_str(
37 | "2372475307192593135651930854555638407652639876824448403675529997189131",
38 | )
39 | .unwrap(),
40 | ),
41 | );
42 | }
43 |
44 | #[test]
45 | fn u256_mul() {
46 | run_example(
47 | // x = 10 + (20 << 32) + (30 << 64) + (40 << 96) + (50 << 128) + (60 << 160) + (70 << 192) + (80 << 224)
48 | // y = 1 + (2 << 32) + (3 << 64) + (4 << 96) + (5 << 128) + (6 << 160) + (7 << 192) + (8 << 224)
49 | "
50 | let x:u256 := 2156795733811448305138118958686944006956945342567680366977754542899210
51 | let y:u256 := 2
52 | mul(y, x)
53 | ",
54 | MidenResult::U256(
55 | U256::from_dec_str(
56 | "4313591467622896610276237917373888013913890685135360733955509085798420",
57 | )
58 | .unwrap(),
59 | ),
60 | );
61 | }
62 |
63 | #[test]
64 | fn u256_add_with_carry() {
65 | run_example(
66 | // x = (2 ** 32 - 1) + (20 << 32) + (30 << 64) + (40 << 96) + (50 << 128) + (60 << 160) + (70 << 192) + (80 << 224)
67 | // y = 1 + (2 << 32) + (3 << 64) + (4 << 96) + (5 << 128) + (6 << 160) + (7 << 192) + (8 << 224)
68 | "
69 | let x:u256 := 2156795733811448305138118958686944006956945342567680366977758837866495
70 | let y:u256 := 215679573381144830513811895868694400695694534256768036697775454289921
71 | add(y, x)
72 | ",
73 | MidenResult::U256(
74 | U256::from_dec_str(
75 | "2372475307192593135651930854555638407652639876824448403675534292156416",
76 | )
77 | .unwrap(),
78 | ),
79 | );
80 | }
81 |
82 | #[test]
83 | fn u256_sub() {
84 | run_example(
85 | "
86 | let x:u256 := 2156795733811448305138118958686944006956945342567680366977754542899210
87 | let y:u256 := 215679573381144830513811895868694400695694534256768036697775454289921
88 | sub(x, y)
89 | ",
90 | MidenResult::U256(
91 | U256::from_dec_str(
92 | "1941116160430303474624307062818249606261250808310912330279979088609289",
93 | )
94 | .unwrap(),
95 | ),
96 | );
97 | }
98 |
99 | #[ignore]
100 | #[test]
101 | fn u256_sub_underflow() {
102 | run_example(
103 | "
104 | let x:u256 := 2156795733811448305138118958686944006956945342567680366977754542899210
105 | let y:u256 := 215679573381144830513811895868694400695694534256768036697775454289921
106 | sub(y, x)
107 | ",
108 | MidenResult::U256(
109 | U256::from_dec_str(
110 | "115792087323159981660418150179047860122040009078026900151085826209037651279862",
111 | )
112 | .unwrap(),
113 | ),
114 | );
115 | }
116 |
117 | #[test]
118 | fn u256_and() {
119 | run_example(
120 | "
121 | let x:u256 := 2156795733811448305138118958686944006956945342567680366977754542899210
122 | let y:u256 := 215679573381144830513811895868694400695694534256768036697775454289921
123 | and(x, y)
124 | ",
125 | MidenResult::U256(
126 | U256::from_dec_str("37662610418166091132338348212060737827516158233555356352512")
127 | .unwrap(),
128 | ),
129 | );
130 | }
131 |
132 | #[test]
133 | fn u256_or() {
134 | run_example(
135 | "
136 | let x:u256 := 2156795733811448305138118958686944006956945342567680366977754542899210
137 | let y:u256 := 215679573381144830513811895868694400695694534256768036697775454289921
138 | or(x, y)
139 | ",
140 | MidenResult::U256(
141 | U256::from_dec_str(
142 | "2372475307154930525233764763423300059440579138996932245441974640836619",
143 | )
144 | .unwrap(),
145 | ),
146 | );
147 | }
148 |
149 | #[test]
150 | fn u256_xor() {
151 | run_example(
152 | "
153 | let x:u256 := 2156795733811448305138118958686944006956945342567680366977754542899210
154 | let y:u256 := 215679573381144830513811895868694400695694534256768036697775454289921
155 | xor(x, y)
156 | ",
157 | MidenResult::U256(
158 | U256::from_dec_str(
159 | "2372475307117267914815598672290961711228518401169416087208419284484107",
160 | )
161 | .unwrap(),
162 | ),
163 | );
164 | }
165 |
166 | #[test]
167 | fn u256_mixed_types() {
168 | run_example(
169 | "
170 | let x:u256 := 28948022309329048855892746252171976963317496166410141009864396001978282409984
171 | let y:u256 := 21711016731996786641919559689128982722488122124807605757398297001483711807488
172 | let z:u256 := add(x, y)
173 | let a:u32 := 4
174 | let b:u32 := 8
175 | let c := add(a, b)
176 | z
177 | ",
178 | MidenResult::U256(
179 | U256::from_dec_str("50659039041325835497812305941300959685805618291217746767262693003461994217472")
180 | .unwrap(),
181 | ),
182 | );
183 | }
184 |
185 | #[test]
186 | fn u256_stack_overflow() {
187 | run_example(
188 | "
189 | let x:u256 := 2156795733811448305138118958686944006956945342567680366977754542899210
190 | let y:u256 := 215679573381144830513811895868694400695694534256768036697775454289921
191 | let z:u256 := 215679573381144830513811895868694400695694534256768036697775454289921
192 | x
193 | ",
194 | MidenResult::U256(
195 | U256::from_dec_str(
196 | "2156795733811448305138118958686944006956945342567680366977754542899210",
197 | )
198 | .unwrap(),
199 | ),
200 | );
201 | }
202 |
203 | #[test]
204 | fn u256_less_than() {
205 | run_example(
206 | "
207 | let x:u256 := 2156795733811448305138118958686944006956945342567680366977754542899210
208 | let y:u256 := 215679573381144830513811895868694400695694534256768036697775454289921
209 | lt(x,y)
210 | ",
211 | MidenResult::U32(0),
212 | );
213 | }
214 |
215 | #[test]
216 | fn u256_match_no_default() {
217 | run_example(
218 | "
219 | let x:u256 := 31711016731996786641919559689128982722488122124807605757398297001483711807488
220 | let foo:u32 := 1
221 | switch x
222 | case 31711016731996786641919559689128982722488122124807605757398297001483711807488 {
223 | foo := 5
224 | }
225 | foo
226 | ",
227 | MidenResult::U32(5),
228 | );
229 | }
230 |
231 | #[test]
232 | fn u256_match_default_with_match() {
233 | run_example(
234 | "
235 | let x:u256 := 50
236 | let foo:u32 := 1
237 | switch x
238 | case 50 {
239 | foo := 5
240 | }
241 | default {
242 | foo := 83
243 | }
244 | foo
245 | ",
246 | MidenResult::U32(5),
247 | );
248 | }
249 |
250 | #[test]
251 | fn u256_match_default_no_match() {
252 | run_example(
253 | "
254 | let x:u256 := 80
255 | let foo:u32 := 1
256 | switch x
257 | case 50 {
258 | foo := 5
259 | }
260 | default {
261 | foo := 83
262 | }
263 | foo
264 | ",
265 | MidenResult::U32(83),
266 | );
267 | }
268 |
269 | #[test]
270 | fn u256_equality() {
271 | run_example(
272 | "
273 | let x:u256 := 31711016731996786641919559689128982722488122124807605757398297001483711807488
274 | let y:u256 := 21711016731996786641919559689128982722488122124807605757398297001483711807488
275 | let foo:u32 := 5
276 | if eq(x, y) {
277 | foo := 7
278 | }
279 | foo
280 | ",
281 | MidenResult::U32(5)
282 | );
283 | }
284 |
285 | #[test]
286 | fn u256_function() {
287 | run_example(
288 | "
289 | function add_a_lot(a:u256) -> b:u256 {
290 | let b:u256 := 100
291 | if eq(a, 100) {
292 | b := add(a, 18446744073709551616)
293 | }
294 | }
295 | let z:u256 := add_a_lot(100)
296 | let b := 4
297 | z
298 | ",
299 | MidenResult::U256(U256::from_dec_str("18446744073709551716").unwrap()),
300 | );
301 | }
302 |
303 | #[test]
304 | fn u256_sum_odds() {
305 | run_example(
306 | "
307 | let sum_odds:u256 := 0
308 | let n:u256 := 72
309 | for { let i:u256 := 1 } lt(i, n) { i := add(i, 2)} {
310 | sum_odds := add(i, sum_odds)
311 | }
312 | sum_odds
313 | ",
314 | MidenResult::U256(U256::from_dec_str("1296").unwrap()),
315 | );
316 | }
317 |
318 | #[test]
319 | fn u256_shl() {
320 | run_example(
321 | "
322 | let x:u256 := 2156795733811448305138118958686944006956945342567680366977758837866495
323 | shl(x)
324 | ",
325 | MidenResult::U256(
326 | U256::from_dec_str(
327 | "4313591467622896610276237917373888013913890685135360733955517675732990",
328 | )
329 | .unwrap(),
330 | ),
331 | );
332 | }
333 |
334 | #[test]
335 | fn u256_shr() {
336 | run_example(
337 | "
338 | let x:u256 := 2156795733811448305138118958686944006956945342567680366977758837866495
339 | shr(x)
340 | ",
341 | MidenResult::U256(
342 | U256::from_dec_str(
343 | "1078397866905724152569059479343472003478472671283840183488879418933247",
344 | )
345 | .unwrap(),
346 | ),
347 | );
348 | }
349 |
350 | #[test]
351 | fn mstore_mload_u256() {
352 | run_example(
353 | "
354 | let x:u256 := 2156795733811448305138118958686944006956945342567680366977754542899210
355 | mstore(100,x)
356 | mload(100)
357 | ",
358 | MidenResult::U256(
359 | U256::from_dec_str(
360 | "2156795733811448305138118958686944006956945342567680366977754542899210",
361 | )
362 | .unwrap(),
363 | ),
364 | );
365 | }
366 |
367 | #[test]
368 | fn mstore_mload_u32() {
369 | run_example(
370 | "
371 | let x:u32 := 700
372 | mstore(100,x)
373 | mload(100)
374 | ",
375 | MidenResult::U32(700),
376 | );
377 | }
378 |
379 | #[test]
380 | fn sum_memory_u32() {
381 | run_example(
382 | "
383 | function sum_from_memory(offset:u32,size:u32) -> b:u32 {
384 | let b:u32 := 0
385 | for { let i:u32 := offset } lt(i, add(offset, size)) { i := add(i, 1)} {
386 | b := add(b, mload(i))
387 | }
388 | b
389 | }
390 | let x:u32 := 1
391 | mstore(100,x)
392 | mstore(101,x)
393 | mstore(102,x)
394 | mstore(103,x)
395 | mstore(104,x)
396 | sum_from_memory(100, 5)
397 | ",
398 | MidenResult::U32(5),
399 | );
400 | }
401 |
402 | #[test]
403 | fn sum_memory_u256() {
404 | run_example(
405 | "
406 | function sum_from_memory(offset:u32,size:u32) -> b:u256 {
407 | let b:u256 := 0
408 | for { let i:u32 := offset } lt(i, add(offset, size)) { i := add(i, 1)} {
409 | b := add(b, mload(i))
410 | }
411 | b
412 | }
413 | let x:u256 := 1
414 | mstore(100,x)
415 | mstore(101,x)
416 | mstore(102,x)
417 | mstore(103,x)
418 | mstore(104,x)
419 | mstore(105,x)
420 | let offset:u32 := 100
421 | let size:u32 := 6
422 | sum_from_memory(offset, size)
423 | ",
424 | MidenResult::U256(U256::from(6)),
425 | );
426 | }
427 |
428 | #[ignore]
429 | #[test]
430 | fn u256_sqrt() {
431 | run_example(
432 | "
433 | let x:u256 := 100 // Find sqrt of x
434 | // Start off with z at 1.
435 | let z:u256 := 1
436 |
437 | // Used below to help find a nearby power of 2.
438 | let y:u256 := x
439 |
440 | // Find the lowest power of 2 that is at least sqrt(x).
441 | if iszero(lt(y, 0x100000000000000000000000000000000)) {
442 | y := shr(128, y) // Like dividing by 2 ** 128.
443 | z := shl(64, z)
444 | }
445 | if iszero(lt(y, 0x10000000000000000)) {
446 | y := shr(64, y) // Like dividing by 2 ** 64.
447 | z := shl(32, z)
448 | }
449 | if iszero(lt(y, 0x100000000)) {
450 | y := shr(32, y) // Like dividing by 2 ** 32.
451 | z := shl(16, z)
452 | }
453 | if iszero(lt(y, 0x10000)) {
454 | y := shr(16, y) // Like dividing by 2 ** 16.
455 | z := shl(8, z)
456 | }
457 | if iszero(lt(y, 0x100)) {
458 | y := shr(8, y) // Like dividing by 2 ** 8.
459 | z := shl(4, z)
460 | }
461 | if iszero(lt(y, 0x10)) {
462 | y := shr(4, y) // Like dividing by 2 ** 4.
463 | z := shl(2, z)
464 | }
465 | if iszero(lt(y, 0x8)) {
466 | // Equivalent to 2 ** z.
467 | z := shl(1, z)
468 | }
469 |
470 | // Shifting right by 1 is like dividing by 2.
471 | z := shr(1, add(z, div(x, z)))
472 | z := shr(1, add(z, div(x, z)))
473 | z := shr(1, add(z, div(x, z)))
474 | z := shr(1, add(z, div(x, z)))
475 | z := shr(1, add(z, div(x, z)))
476 | z := shr(1, add(z, div(x, z)))
477 | z := shr(1, add(z, div(x, z)))
478 |
479 | // Compute a rounded down version of z.
480 | let zRoundDown:u256 := div(x, z)
481 |
482 | // If zRoundDown is smaller, use it.
483 | if lt(zRoundDown, z) {
484 | z := zRoundDown
485 | }
486 | ",
487 | MidenResult::U256(U256::from_dec_str("10").unwrap()),
488 | );
489 | }
490 |
--------------------------------------------------------------------------------
/crates/miden-integration-tests/tests/utils.rs:
--------------------------------------------------------------------------------
1 | use colored::*;
2 | use miden_core::StarkField;
3 | use primitive_types::U256;
4 | use scribe::ast_optimization::optimize_ast;
5 | use scribe::executor;
6 | use scribe::miden_generator;
7 | use scribe::miden_generator::CompileOptions;
8 | use scribe::parser;
9 | use scribe::type_inference::infer_types;
10 | use scribe::types::expressions_to_tree;
11 | use scribe::types::YulFile;
12 | use std::fs;
13 | pub enum MidenResult {
14 | U256(primitive_types::U256),
15 | U32(u32),
16 | }
17 |
18 | //Function to display transpile Yul code and display each step of the transpilation process in the terminal.
19 | //This function is only used to demonstrate what Scribe does in a easy to read format.
20 | pub fn run_example(yul_code: &str, expected_output: MidenResult) {
21 | fn print_title(s: &str) {
22 | let s1 = format!("=== {} ===", s).blue().bold();
23 | println!("{}", s1);
24 | println!(" ");
25 | }
26 | println!();
27 | println!();
28 | print_title("Input Yul");
29 | println!("{}", yul_code);
30 | println!();
31 |
32 | let parsed = parser::parse_yul_syntax(yul_code);
33 |
34 | let ast = optimize_ast(parsed);
35 |
36 | let ast = infer_types(&ast);
37 | print_title("AST");
38 | println!("{}", expressions_to_tree(&ast));
39 | println!();
40 |
41 | let (transpiler, miden_code) = miden_generator::transpile_program(ast, Default::default());
42 | let mut trimmed_miden_code = miden_code
43 | .split('\n')
44 | // .skip_while(|line| *line != "# end std lib #")
45 | // .filter(|line| !line.trim().starts_with("#"))
46 | // .filter(|line| !line.trim().is_empty())
47 | .collect::>()
48 | .join("\n");
49 | print_title("Generated Miden Assembly");
50 | println!("{}", trimmed_miden_code);
51 | println!();
52 | println!("Estimated cost: {}", transpiler.cost);
53 | println!();
54 | fs::write(format!("./test_output.masm",), trimmed_miden_code)
55 | .expect("Unable to write Miden to file.");
56 |
57 | let execution_value = executor::execute(miden_code, vec![]).unwrap();
58 | let stack = execution_value.last_stack_state();
59 | let last_stack_value = stack.first().unwrap();
60 |
61 | print_title("Miden Output");
62 | match expected_output {
63 | MidenResult::U256(expected) => {
64 | let stack_value = miden_to_u256(execution_value);
65 | println!("{}", stack_value);
66 | if expected != stack_value {
67 | print_title("Miden Stack");
68 | println!("{:?}", stack);
69 | panic!("Failed, stack result not right");
70 | }
71 | }
72 | MidenResult::U32(expected) => {
73 | println!("{}", last_stack_value);
74 | if expected != last_stack_value.as_int() as u32 {
75 | print_title("Miden Stack");
76 | println!("{:?}", stack);
77 | panic!("Failed, stack result not right");
78 | }
79 | }
80 | }
81 | }
82 |
83 | pub fn compile_example(yul_code: &str, expected_output: &str) {
84 | fn print_title(s: &str) {
85 | let s1 = format!("=== {} ===", s).blue().bold();
86 | println!("{}", s1);
87 | println!(" ");
88 | }
89 |
90 | let parsed = parser::parse_yul_syntax(yul_code);
91 |
92 | let ast = optimize_ast(parsed);
93 |
94 | let ast = infer_types(&ast);
95 |
96 | let (_, miden_code) = miden_generator::transpile_program(
97 | ast,
98 | CompileOptions {
99 | comments: false,
100 | auto_indent: false,
101 | },
102 | );
103 | let mut trimmed_miden_code = miden_code
104 | .split('\n')
105 | .filter(|line| !line.contains("use std") && !line.trim().is_empty())
106 | .collect::>()
107 | .join("\n");
108 | let mut trimmed_yul_code = yul_code
109 | .split('\n')
110 | .filter(|line| !line.trim().is_empty())
111 | .collect::>()
112 | .join("\n");
113 | print_title("Input Yul");
114 | println!("{}", trimmed_yul_code);
115 | println!("");
116 | // println!();
117 | // assert_eq!(trimmed_miden_code, expected_output);
118 | if trimmed_miden_code != expected_output {
119 | print_title("Expected Output");
120 | println!("{}", expected_output);
121 | print_title("Actual Output");
122 | println!("{}", trimmed_miden_code);
123 | panic!("Incorrect output");
124 | }
125 | }
126 |
127 | // pub fn run_yul() {}
128 |
129 | //Converts the top 8 elements on the top of the stack to a U256 struct
130 | //This is used during testing to assert that the Miden output is the correct U256 value
131 | pub fn miden_to_u256(execuiton_trace: miden_processor::ExecutionTrace) -> U256 {
132 | let u256_bytes = execuiton_trace
133 | .last_stack_state()
134 | .iter()
135 | .take(8)
136 | .flat_map(|x| {
137 | let svint = x.as_int() as u32;
138 |
139 | svint.to_be_bytes()
140 | })
141 | .collect::>();
142 |
143 | U256::from_big_endian(&u256_bytes)
144 | }
145 |
--------------------------------------------------------------------------------
/crates/papyrus/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "papyrus"
3 | version = "0.1.0"
4 | edition = "2021"
5 |
6 | [dependencies]
7 | pest = "2.0"
8 | pest_derive = "2.0"
9 | miden-assembly = { git = "http://github.com/maticnetwork/miden", branch = "next" }
10 | miden-processor = { git = "http://github.com/maticnetwork/miden", branch = "next" }
11 | miden-core = { git = "http://github.com/maticnetwork/miden", branch = "next" }
12 | hex = "0.4"
13 | colored = "2"
14 | debug_tree = "0.4.0"
15 | insta = "1.12.0"
16 | primitive-types = "0.11.1"
17 | itertools = "0.10.3"
18 | rustyline = "9.1.2"
19 | clap = {version = "3.0.14", features = ["derive"]}
20 | anyhow = "1.0.54"
21 | thiserror = "1.0.30"
22 | # TODO: can maybe delete
23 | quickcheck = "1.0.3"
24 | quickcheck_macros = "1"
25 | include_dir = "0.7.2"
26 | indoc = "1.0.6"
--------------------------------------------------------------------------------
/crates/papyrus/src/ast_optimization.rs:
--------------------------------------------------------------------------------
1 | #![allow(dead_code)]
2 | use std::{collections::HashMap, vec};
3 |
4 | use crate::types::*;
5 |
6 | //TODO: Update this mod and comment the functions
7 |
8 | pub fn optimize_ast(ast: Vec) -> Vec {
9 | // let mut assignment_visitor = VariableAssignmentVisitor::default();
10 | // let ast = walk_ast(ast, &mut assignment_visitor);
11 | // let const_variables = assignment_visitor.get_const_variables();
12 | // let ast = walk_ast(ast, &mut ConstVariableVisitor { const_variables });
13 |
14 | // walk_ast(ast, &mut ForLoopToRepeatVisitor {})
15 | // TODO: fix optimizations
16 | ast
17 | }
18 |
19 | // Walks through each expression in the abstract syntax tree, optimizing the AST where possible. A new, optimized AST is returned
20 | //Which is then passed into the Miden generation logic.
21 | fn walk_ast(ast: Vec, visitor: &mut V) -> Vec {
22 | let mut new_ast = vec![];
23 | for expr in ast {
24 | if let Some(expr) = walk_expr(expr, visitor) {
25 | new_ast.push(expr);
26 | }
27 | }
28 | new_ast
29 | }
30 |
31 | trait ExpressionVisitor {
32 | fn visit_expr(&mut self, expr: Expr) -> Option;
33 | }
34 |
35 | //TODO: Keeps track of constant variables
36 | #[derive(Default)]
37 | struct ConstVariableVisitor {
38 | const_variables: HashMap,
39 | }
40 |
41 | #[derive(Default)]
42 | struct ForLoopToRepeatVisitor {}
43 |
44 | //The variable assignment visitor keeps track of variables that are reused through the code and the last assignment.
45 | //Variables that do not change can be optimized by converting them into constants.
46 | #[derive(Default)]
47 | struct VariableAssignmentVisitor {
48 | assignment_counter: HashMap,
49 | last_assignment: HashMap,
50 | }
51 |
52 | impl VariableAssignmentVisitor {
53 | // Checks for variables that are only assigned once and returns a hashmap of the variables to convert into constants.
54 | fn get_const_variables(&self) -> HashMap {
55 | self.assignment_counter
56 | .iter()
57 | .filter(|(_k, v)| **v == 1)
58 | .filter_map(|(k, _)| {
59 | if let Some(value) = self.last_assignment.get(k) {
60 | return Some((k.clone(), value.clone()));
61 | }
62 | None
63 | })
64 | .collect::>()
65 | }
66 | }
67 |
68 | // TODO: unstable for now, as it will incorrectly transform for loops that modify the iterator in
69 | // the interior block. To fix this we should have the variable assignment visitor walk the interior
70 | // block, for assignments. Also need to make sure the var isn't referenced within the for loop
71 | //
72 | // TODO: there's a lot of ways we can miss this optimization currently. Even just flipping i :=
73 | // add(i, 1) to i := add(1, i) will break this optimization. In the future we should support gt,
74 | // subtracting, etc.
75 | impl ExpressionVisitor for ForLoopToRepeatVisitor {
76 | fn visit_expr(&mut self, _expr: Expr) -> Option {
77 | todo!();
78 | // match &expr {
79 | // Expr::ForLoop(ExprForLoop {
80 | // init_block,
81 | // conditional,
82 | // after_block,
83 | // interior_block,
84 | // }) => {
85 | // let start: Option;
86 | // let iterator_identifier: Option;
87 | // if let Some(first_expr) = (*init_block.exprs).first() {
88 | // if let Expr::DeclareVariable(ExprDeclareVariable { identifier, rhs }) =
89 | // first_expr
90 | // {
91 | // if let Some(Expr::Literal(value)) = rhs.clone().map(|e| *e) {
92 | // start = Some(todo!("Need to get literal value here"));
93 | // iterator_identifier = Some(identifier.to_string());
94 | // } else {
95 | // return Some(expr);
96 | // }
97 | // } else {
98 | // return Some(expr);
99 | // }
100 | // } else {
101 | // return Some(expr);
102 | // }
103 | //
104 | // if let Some(Expr::Assignment(assignment)) = (*after_block.exprs).first() {
105 | // if *assignment
106 | // == (ExprAssignment {
107 | // typed_identifier: iterator_identifier.clone().unwrap(),
108 | // rhs: Box::new(Expr::FunctionCall(ExprFunctionCall {
109 | // function_name: "add".to_string(),
110 | // exprs: Box::new(vec![
111 | // Expr::Variable(ExprVariableReference {
112 | // identifier: iterator_identifier.clone().unwrap(),
113 | // }),
114 | // Expr::Literal(todo!("Need to get literal value here")),
115 | // ]),
116 | // })),
117 | // })
118 | // {}
119 | // } else {
120 | // return Some(expr);
121 | // }
122 | // if let Expr::FunctionCall(ExprFunctionCall {
123 | // function_name,
124 | // exprs,
125 | // }) = &**conditional
126 | // {
127 | // if function_name == "lt"
128 | // && exprs[0]
129 | // == Expr::Variable(ExprVariableReference {
130 | // identifier: iterator_identifier.unwrap(),
131 | // })
132 | // {
133 | // if let Expr::Literal(value) = exprs[1] {
134 | // return Some(Expr::Repeat(ExprRepeat {
135 | // interior_block: interior_block.clone(),
136 | // iterations: todo!("Get end value from literal"),
137 | // }));
138 | // }
139 | // }
140 | // } else {
141 | // return Some(expr);
142 | // }
143 | // }
144 | // _ => {}
145 | // }
146 | // Some(expr)
147 | }
148 | }
149 |
150 | impl ExpressionVisitor for VariableAssignmentVisitor {
151 | fn visit_expr(&mut self, _expr: Expr) -> Option {
152 | todo!();
153 | // match &expr {
154 | // Expr::DeclareVariable(ExprDeclareVariable { identifier, rhs }) => {
155 | // if let Some(Expr::Literal(literal)) = rhs.clone().map(|r| *r) {
156 | // self.last_assignment.insert(identifier.clone(), literal);
157 | // }
158 | // let count = self
159 | // .assignment_counter
160 | // .entry(identifier.clone())
161 | // .or_insert(0);
162 | // *count += 1;
163 | // }
164 | // Expr::Assignment(ExprAssignment {
165 | // typed_identifier: identifier,
166 | // rhs: _,
167 | // }) => {
168 | // let count = self
169 | // .assignment_counter
170 | // .entry(identifier.clone())
171 | // .or_insert(0);
172 | // *count += 1;
173 | // }
174 | // _ => {}
175 | // }
176 | // Some(expr)
177 | }
178 | }
179 |
180 | impl ExpressionVisitor for ConstVariableVisitor {
181 | fn visit_expr(&mut self, _expr: Expr) -> Option {
182 | todo!();
183 | // match &expr {
184 | // Expr::DeclareVariable(ExprDeclareVariable { identifier, rhs: _ }) => {
185 | // if self.const_variables.get(identifier).is_some() {
186 | // return None;
187 | // }
188 | // }
189 | // Expr::Variable(ExprVariableReference { identifier }) => {
190 | // if let Some(value) = self.const_variables.get(identifier) {
191 | // return Some(Expr::Literal(value.clone()));
192 | // }
193 | // }
194 | // _ => {}
195 | // }
196 | // Some(expr)
197 | }
198 | }
199 |
200 | // TODO: it would be nice if there wasn't so much cloning in here
201 | fn walk_expr(expr: Expr, visitor: &mut V) -> Option {
202 | let expr = visitor.visit_expr(expr);
203 | if let Some(expr) = expr {
204 | return Some(match expr {
205 | //Expr is literal
206 | Expr::Literal(ref _x) => expr,
207 |
208 | //Expr is function call
209 | Expr::FunctionCall(ExprFunctionCall {
210 | function_name,
211 | inferred_return_types,
212 | inferred_param_types,
213 | exprs,
214 | }) => Expr::FunctionCall(ExprFunctionCall {
215 | function_name,
216 | inferred_return_types,
217 | inferred_param_types,
218 | exprs: Box::new(vec![
219 | walk_expr(exprs[0].clone(), visitor).unwrap(),
220 | walk_expr(exprs[1].clone(), visitor).unwrap(),
221 | ]),
222 | }),
223 |
224 | //Expr is if statement
225 | Expr::IfStatement(ExprIfStatement {
226 | first_expr,
227 | second_expr,
228 | }) => Expr::IfStatement(ExprIfStatement {
229 | first_expr: Box::new(walk_expr(*first_expr, visitor).unwrap()),
230 | second_expr: Box::new(ExprBlock {
231 | exprs: walk_ast(second_expr.exprs, visitor),
232 | }),
233 | }),
234 |
235 | //Expr is assignment
236 | Expr::Assignment(ExprAssignment {
237 | inferred_types,
238 | identifiers,
239 | rhs,
240 | }) => Expr::Assignment(ExprAssignment {
241 | identifiers,
242 | inferred_types,
243 | rhs: Box::new(walk_expr(*rhs, visitor).unwrap()),
244 | }),
245 |
246 | //Expr is declare variable
247 | Expr::DeclareVariable(ExprDeclareVariable {
248 | typed_identifiers,
249 | rhs,
250 | }) => Expr::DeclareVariable(ExprDeclareVariable {
251 | typed_identifiers,
252 | rhs: rhs.map(|rhs| Box::new(walk_expr(*rhs, visitor).unwrap())),
253 | }),
254 |
255 | //TODO: Expr is function definition
256 | Expr::FunctionDefinition(ExprFunctionDefinition {
257 | function_name: _,
258 | params: _,
259 | returns: _,
260 | block: _,
261 | }) => todo!(),
262 |
263 | //TODO: Expr is break
264 | Expr::Break => todo!(),
265 |
266 | //TODO: Expr is continue
267 | Expr::Continue => todo!(),
268 | Expr::Leave => todo!(),
269 |
270 | //Expr is repeat
271 | Expr::Repeat(ExprRepeat {
272 | interior_block,
273 | iterations,
274 | }) => Expr::Repeat(ExprRepeat {
275 | iterations,
276 | interior_block: Box::new(ExprBlock {
277 | exprs: walk_ast(interior_block.exprs, visitor),
278 | }),
279 | }),
280 |
281 | //Expr is for loop
282 | Expr::ForLoop(ExprForLoop {
283 | init_block,
284 | conditional,
285 | after_block,
286 | interior_block,
287 | }) => Expr::ForLoop(ExprForLoop {
288 | init_block: Box::new(ExprBlock {
289 | exprs: walk_ast(init_block.exprs, visitor),
290 | }),
291 | conditional: Box::new(walk_expr(*conditional, visitor).unwrap()),
292 | after_block: Box::new(ExprBlock {
293 | exprs: walk_ast(after_block.exprs, visitor),
294 | }),
295 | interior_block: Box::new(ExprBlock {
296 | exprs: walk_ast(interior_block.exprs, visitor),
297 | }),
298 | }),
299 |
300 | //Expr is block
301 | Expr::Block(ExprBlock { exprs }) => Expr::Block(ExprBlock {
302 | exprs: walk_ast(exprs, visitor),
303 | }),
304 |
305 | //Expr is variable
306 | Expr::Variable(ExprVariableReference {
307 | identifier: _,
308 | inferred_type: _,
309 | }) => expr,
310 | Expr::Case(_) => todo!(),
311 | Expr::Switch(_) => todo!(),
312 | });
313 | }
314 | None
315 | }
316 |
--------------------------------------------------------------------------------
/crates/papyrus/src/executor.rs:
--------------------------------------------------------------------------------
1 | use miden_processor::ExecutionTrace;
2 | pub use miden_processor::{ExecutionError, MemAdviceProvider, StackInputs};
3 |
4 | //Compiles and executes a compiled Miden program, returning the stack and any Miden errors.
5 | //The program is passed in as a String, passed to the Miden Assembler, and then passed into the Miden Processor to be executed
6 | pub fn execute(program: String, _pub_inputs: Vec) -> Result {
7 | let program = miden_assembly::Assembler::default()
8 | .compile(program)
9 | .map_err(MidenError::AssemblyError)?;
10 |
11 | miden_processor::execute(&program, StackInputs::empty(), MemAdviceProvider::empty())
12 | .map_err(MidenError::ExecutionError)
13 | }
14 |
15 | //Errors that are returned from the Miden processor during execution.
16 | #[derive(Debug)]
17 | pub enum MidenError {
18 | AssemblyError(miden_assembly::AssemblyError),
19 | ExecutionError(ExecutionError),
20 | }
21 |
22 | #[ignore]
23 | #[test]
24 | fn debug_execution() {
25 | // You can put a miden program here to debug output, manually modifying it if needed
26 | let execution_value = execute(
27 | r##"
28 | begin
29 | push.5
30 | mul.5
31 | end
32 | "##
33 | .to_string(),
34 | vec![],
35 | )
36 | .unwrap();
37 |
38 | println!("Miden Output");
39 | let stack = execution_value.last_stack_state();
40 | dbg!(&stack);
41 | let _last_stack_value = stack.first().unwrap();
42 | }
43 |
--------------------------------------------------------------------------------
/crates/papyrus/src/grammar.pest:
--------------------------------------------------------------------------------
1 | file = { SOI ~ NEWLINE* ~ (object | statement*) ~ NEWLINE* ~ EOI }
2 |
3 | alpha = { 'a'..'z' | 'A'..'Z' }
4 | digit = { '0'..'9' }
5 | underscore = { "_" }
6 | WHITESPACE = _{ " " }
7 |
8 |
9 | block = { "{" ~ NEWLINE* ~ statement* ~ NEWLINE* ~ "}" }
10 | statement = { NEWLINE* ~ (for_loop | switch | if_statement | variable_declaration | assignment | block | function_definition | break_ | continue_ | leave | expr | comment) ~ NEWLINE* }
11 | function_definition = { "function" ~ identifier ~ "(" ~ typed_identifier_list ~ ")" ~ function_returns ~ block }
12 | function_returns = { ( "->" ~ typed_identifier_list)? }
13 | variable_declaration = { "let" ~ typed_identifier_list ~ (":=" ~ expr)? }
14 | assignment = { (identifier_list) ~ ":=" ~ NEWLINE * ~ expr }
15 | expr = { function_call | identifier | literal }
16 | if_statement = { "if" ~ expr ~ block}
17 | switch = { "switch" ~ expr ~ NEWLINE* ~ ((case+ ~ default?) | default) }
18 | case = { "case" ~ literal ~ block ~ NEWLINE* }
19 | default = { "default" ~ block }
20 | for_loop = { "for" ~ block ~ expr ~ block ~ (NEWLINE*) ~ block}
21 | break_ = @{ "break" }
22 | continue_ = @{ "continue" }
23 | leave = @{"leave"}
24 | function_call = { identifier ~ "(" ~ (expr ~ ( "," ~ expr)* )? ~ ")" }
25 | identifier = @{ ("_" | ASCII_ALPHA) ~ (ASCII_ALPHANUMERIC | "_" | "$")*}
26 | identifier_list = { identifier ~ ("," ~ identifier)* }
27 | type_name = { identifier }
28 | typed_identifier_list = { typed_identifier? ~ ("," ~ typed_identifier )* }
29 | typed_identifier = { (identifier ~ (":" ~ type_name)?) }
30 | literal = { (number_literal | string_literal | true_literal | false_literal | hex_literal) ~ (":" ~ type_name)? }
31 | number_literal = { hex_number | decimal_number }
32 | comment = _{"//" ~ (!NEWLINE ~ ANY)* ~ NEWLINE}
33 | string_literal = ${ "\"" ~ string_inner ~ "\"" }
34 | string_inner = @{ string_char* }
35 | string_char = {
36 | !("\"" | "\\") ~ ANY
37 | | "\\" ~ ("\"" | "\\" | "/" | "b" | "f" | "n" | "r" | "t")
38 | | "\\" ~ ("u" ~ ASCII_HEX_DIGIT{4})
39 | }
40 | true_literal = @{ "true" }
41 | false_literal = @{ "false"}
42 | hex_number = @{ "0x" ~ ('0'..'9'| 'a'..'f'|'A'..'F')+ }
43 | decimal_number = @{ digit+ }
44 | object = { "object" ~ string_literal ~ "{" ~ NEWLINE* ~ code ~ (object | data)* ~ NEWLINE* ~ "}" }
45 | code = { "code" ~ block }
46 | data = {"data" ~ string_literal ~ (hex_literal | string_literal) }
47 | hex_literal = @{ "hex" ~ ( ("\"" ~ ('0'..'9'| 'a'..'f'|'A'..'F'){2}* ~ "\"") | "\'" ~ ('0'..'9'| 'a'..'f'|'A'..'F'){2}* ~ "\'") }
48 |
--------------------------------------------------------------------------------
/crates/papyrus/src/lib.rs:
--------------------------------------------------------------------------------
1 | pub mod ast_optimization;
2 | pub mod executor;
3 | pub mod miden_generator;
4 | pub mod parser;
5 | pub mod type_inference;
6 | pub mod types;
7 | pub mod utils;
8 |
--------------------------------------------------------------------------------
/crates/papyrus/src/miden_asm/u256gt_unsafe.masm:
--------------------------------------------------------------------------------
1 | proc.u256gt_unsafe
2 | dup.8
3 | dup.1
4 | gt
5 | movup.9
6 | movup.2
7 | eq
8 |
9 | dup.9
10 | dup.3
11 | gt
12 | dup.1
13 | and
14 | movup.2
15 | or
16 | movup.9
17 | movup.3
18 | eq
19 | movup.2
20 | dup
21 | movdn.2
22 | cdrop
23 |
24 | dup.8
25 | dup.3
26 | gt
27 | dup.1
28 | and
29 | movup.2
30 | or
31 | movup.8
32 | movup.3
33 | eq
34 | movup.2
35 | dup
36 | movdn.2
37 | cdrop
38 |
39 | dup.7
40 | dup.3
41 | gt
42 | dup.1
43 | and
44 | movup.2
45 | or
46 | movup.7
47 | movup.3
48 | eq
49 | movup.2
50 | dup
51 | movdn.2
52 | cdrop
53 |
54 | dup.6
55 | dup.3
56 | gt
57 | dup.1
58 | and
59 | movup.2
60 | or
61 | movup.6
62 | movup.3
63 | eq
64 | movup.2
65 | dup
66 | movdn.2
67 | cdrop
68 |
69 | dup.5
70 | dup.3
71 | gt
72 | dup.1
73 | and
74 | movup.2
75 | or
76 | movup.5
77 | movup.3
78 | eq
79 | movup.2
80 | dup
81 | movdn.2
82 | cdrop
83 |
84 | dup.4
85 | dup.3
86 | gt
87 | dup.1
88 | and
89 | movup.2
90 | or
91 | movup.4
92 | movup.3
93 | eq
94 | movup.2
95 | dup
96 | movdn.2
97 | cdrop
98 |
99 | movup.3
100 | movup.3
101 | gt
102 | dup.1
103 | and
104 | movup.2
105 | or
106 | swap
107 | drop
108 | end
--------------------------------------------------------------------------------
/crates/papyrus/src/miden_asm/u256lt_unsafe.masm:
--------------------------------------------------------------------------------
1 | proc.u256lt_unsafe
2 | dup.8
3 | dup.1
4 | lt
5 | movup.9
6 | movup.2
7 | eq
8 |
9 | dup.9
10 | dup.3
11 | lt
12 | dup.1
13 | and
14 | movup.2
15 | or
16 | movup.9
17 | movup.3
18 | eq
19 | movup.2
20 | dup
21 | movdn.2
22 | cdrop
23 |
24 | dup.8
25 | dup.3
26 | lt
27 | dup.1
28 | and
29 | movup.2
30 | or
31 | movup.8
32 | movup.3
33 | eq
34 | movup.2
35 | dup
36 | movdn.2
37 | cdrop
38 |
39 | dup.7
40 | dup.3
41 | lt
42 | dup.1
43 | and
44 | movup.2
45 | or
46 | movup.7
47 | movup.3
48 | eq
49 | movup.2
50 | dup
51 | movdn.2
52 | cdrop
53 |
54 | dup.6
55 | dup.3
56 | lt
57 | dup.1
58 | and
59 | movup.2
60 | or
61 | movup.6
62 | movup.3
63 | eq
64 | movup.2
65 | dup
66 | movdn.2
67 | cdrop
68 |
69 | dup.5
70 | dup.3
71 | lt
72 | dup.1
73 | and
74 | movup.2
75 | or
76 | movup.5
77 | movup.3
78 | eq
79 | movup.2
80 | dup
81 | movdn.2
82 | cdrop
83 |
84 | dup.4
85 | dup.3
86 | lt
87 | dup.1
88 | and
89 | movup.2
90 | or
91 | movup.4
92 | movup.3
93 | eq
94 | movup.2
95 | dup
96 | movdn.2
97 | cdrop
98 |
99 | movup.3
100 | movup.3
101 | lt
102 | dup.1
103 | and
104 | movup.2
105 | or
106 | swap
107 | drop
108 | end
--------------------------------------------------------------------------------
/crates/papyrus/src/miden_asm/u256shl_unsafe.masm:
--------------------------------------------------------------------------------
1 | proc.u256shl_unsafe
2 | dup.7
3 | u32unchecked_shl.1
4 | movup.8
5 | u32unchecked_shr.31
6 |
7 | repeat.6
8 | dup.8
9 | u32unchecked_shl.1
10 | add
11 | movup.8
12 | u32unchecked_shr.31
13 | end
14 |
15 | movup.8
16 | u32unchecked_shl.1
17 | add
18 | end
--------------------------------------------------------------------------------
/crates/papyrus/src/miden_asm/u256shr_unsafe.masm:
--------------------------------------------------------------------------------
1 | proc.u256shr_unsafe
2 | dup
3 | u32unchecked_shr.1
4 | movdn.8
5 | u32unchecked_shl.31
6 |
7 | repeat.6
8 | dup.1
9 | u32unchecked_shr.1
10 | add
11 | movdn.8
12 | u32unchecked_shl.31
13 | end
14 |
15 | swap
16 | u32unchecked_shr.1
17 | add
18 | movdn.7
19 | end
--------------------------------------------------------------------------------
/crates/papyrus/src/parser.rs:
--------------------------------------------------------------------------------
1 | use crate::types::*;
2 | use pest::iterators::Pair;
3 | use pest::Parser;
4 | use pest_derive::Parser;
5 | use primitive_types::U256;
6 | use std::str;
7 |
8 | #[derive(Parser)]
9 | #[grammar = "./grammar.pest"]
10 | struct IdentParser;
11 | const DEFAULT_TYPE: YulType = YulType::U256;
12 |
13 | //Takes in yul code as a string and parses the grammar, returning a Struct that represents a statement or expression in Yul
14 | //Yul grammar is parsed by matching rules, which can be found in the grammar.pest file
15 | //After a rule is matched, the statement or expression is unwrapped to parse nested rules.
16 | //For example, a the grammar for a decimal_number is @{ digit+ }, and a digit is { '0'..'9' }
17 |
18 | //To see examples for each Expr, check out types.rs
19 | pub fn parse_yul_syntax(syntax: &str) -> Vec {
20 | let file = IdentParser::parse(Rule::file, syntax)
21 | .expect("unsuccessful parse")
22 | .next()
23 | .unwrap();
24 |
25 | //Parse each statement that matches a grammar pattern inside the file, add them the to Vec and return the Vec
26 | let mut expressions: Vec = vec![];
27 | for statement in file.clone().into_inner() {
28 | match statement.as_rule() {
29 | Rule::statement => {
30 | expressions.push(parse_statement(statement));
31 | }
32 |
33 | Rule::object => {
34 | // TODO: create an object type
35 | let mut parts = statement.into_inner();
36 | let object_name = parts.next().unwrap();
37 | dbg!(&object_name);
38 | let code = parts.next().unwrap();
39 | expressions.push(parse_statement(code));
40 | }
41 |
42 | Rule::EOI => (),
43 | r => {
44 | dbg!(&statement);
45 | panic!("Unreachable rule: {:?}", r);
46 | }
47 | }
48 | }
49 | expressions
50 | }
51 |
52 | //Parses a Yul statement. This function matches a grammar rule and return an Expr struct
53 | //which is later added into the Abstract Syntax Tree
54 | fn parse_statement(expression: Pair) -> Expr {
55 | let inner = expression.into_inner().next().unwrap();
56 | match inner.as_rule() {
57 | //Rule is expr
58 | Rule::expr => parse_expression(inner),
59 |
60 | //Rule is block
61 | Rule::block => Expr::Block(parse_block(inner)),
62 |
63 | // Rule is code
64 | Rule::code => Expr::Block(parse_block(inner.into_inner().next().unwrap())),
65 |
66 | //If the rule is a function definition, parse the function name, parameters, returns and then return an Expr
67 | Rule::function_definition => {
68 | let mut parts = inner.into_inner();
69 | let function_name = parts.next().unwrap().as_str();
70 |
71 | //get the typed identifiers from the function and parse each expression
72 | let params: Vec = parse_typed_identifier_list(parts.next().unwrap());
73 | let returns_rule = parts.next().unwrap();
74 | let mut returns = vec![];
75 | if let Some(inner) = returns_rule.into_inner().next() {
76 | returns = parse_typed_identifier_list(inner);
77 | }
78 |
79 | let block = parts.next().unwrap();
80 |
81 | Expr::FunctionDefinition(ExprFunctionDefinition {
82 | function_name: function_name.to_string(),
83 | params,
84 | returns,
85 | block: parse_block(block),
86 | })
87 | }
88 |
89 | //Rule is assignment
90 | Rule::assignment => {
91 | let mut parts = inner.into_inner();
92 | let identifiers = parse_identifier_list(parts.next().unwrap());
93 | let rhs = parts.next().unwrap();
94 | let rhs_expr = parse_expression(rhs);
95 | Expr::Assignment(ExprAssignment {
96 | identifiers,
97 | inferred_types: vec![],
98 | rhs: Box::new(rhs_expr),
99 | })
100 | }
101 |
102 | //Rule is if statement
103 | Rule::if_statement => {
104 | let mut inners = inner.into_inner();
105 | let first_arg = inners.next().unwrap();
106 | let second_arg = inners.next().unwrap();
107 | Expr::IfStatement(ExprIfStatement {
108 | first_expr: Box::new(parse_expression(first_arg)),
109 | second_expr: Box::new(parse_block(second_arg)),
110 | })
111 | }
112 |
113 | //Rule is switch
114 | Rule::switch => {
115 | let mut parts = inner.into_inner();
116 | let mut default_case = None;
117 | let mut cases = Vec::new();
118 | let expr = parse_expression(parts.next().unwrap());
119 | for part in parts {
120 | match part.as_rule() {
121 | Rule::case => cases.push(parse_case(part)),
122 | Rule::default => {
123 | default_case = Some(parse_block(part.into_inner().next().unwrap()))
124 | }
125 | _ => unreachable!(),
126 | }
127 | }
128 |
129 | Expr::Switch(ExprSwitch {
130 | expr: Box::new(expr),
131 | inferred_type: None,
132 | cases,
133 | default_case,
134 | })
135 | }
136 |
137 | //Rule is case
138 | Rule::case => {
139 | let mut parts = inner.into_inner();
140 | let literal = parts.next().unwrap();
141 | let block = parts.next().unwrap();
142 |
143 | Expr::Case(ExprCase {
144 | literal: parse_literal(literal),
145 | block: parse_block(block),
146 | })
147 | }
148 |
149 | //Rule is for loop
150 | Rule::for_loop => {
151 | let mut parts = inner.into_inner();
152 | let init_block = parts.next().unwrap();
153 | let conditional = parts.next().unwrap();
154 | let after_block = parts.next().unwrap();
155 | let interior_block = parts.next().unwrap();
156 |
157 | Expr::ForLoop(ExprForLoop {
158 | init_block: Box::new(parse_block(init_block)),
159 | conditional: Box::new(parse_expression(conditional)),
160 | after_block: Box::new(parse_block(after_block)),
161 | interior_block: Box::new(parse_block(interior_block)),
162 | })
163 | }
164 |
165 | //Rule is break
166 | Rule::break_ => Expr::Break,
167 |
168 | //Rule is continue
169 | Rule::continue_ => Expr::Continue,
170 |
171 | //Rule is leave
172 | Rule::leave => Expr::Leave,
173 |
174 | //Rule is variable declaration
175 | Rule::variable_declaration => {
176 | let mut parts = inner.into_inner();
177 | let typed_identifiers: Vec =
178 | parse_typed_identifier_list(parts.next().unwrap());
179 | let rhs = parts.next();
180 | let mut rhs_expr = None;
181 | if let Some(rhs) = rhs {
182 | rhs_expr = Some(parse_expression(rhs));
183 | }
184 | Expr::DeclareVariable(ExprDeclareVariable {
185 | typed_identifiers,
186 | rhs: rhs_expr.map(Box::new),
187 | })
188 | }
189 |
190 | //if rule is not defined
191 | r => {
192 | panic!("Unreachable rule: {:?}", r);
193 | }
194 | }
195 | }
196 |
197 | //Parses an identifier list for function definitions or variable declarations.
198 | //TODO: explain how this gets handled in transpilation, variables stored in a hashmap during translation
199 | fn parse_identifier_list(rule: Pair) -> Vec {
200 | let mut identifiers = Vec::new();
201 | for rule in rule.into_inner() {
202 | let identifier = rule.as_str();
203 | identifiers.push(identifier.to_string());
204 | }
205 | identifiers
206 | }
207 |
208 | //Parses a case statement into an Expr
209 | fn parse_case(rule: Pair) -> ExprCase {
210 | let mut parts = rule.into_inner();
211 | let literal = parse_literal(parts.next().unwrap());
212 | let block = parse_block(parts.next().unwrap());
213 | ExprCase { block, literal }
214 | }
215 |
216 | //Parses a typed identifier list for function definitions or variable declarations. This is later used to determine
217 | //what type of operation to use for specific instructions (ex. u256add vs u32add).
218 | //Currently the two Yul types that are supported are u32 and u256
219 | fn parse_typed_identifier_list(rule: Pair) -> Vec {
220 | let mut identifiers = Vec::new();
221 | for rules in rule.into_inner() {
222 | let mut parts = rules.into_inner();
223 | let identifier = parts.next().unwrap().as_str();
224 | let yul_type = parts
225 | .next()
226 | .map(|x| YulType::from_annotation(x.as_str()))
227 | .unwrap_or(DEFAULT_TYPE);
228 | identifiers.push(TypedIdentifier {
229 | identifier: identifier.to_string(),
230 | yul_type,
231 | })
232 | }
233 | identifiers
234 | }
235 |
236 | //Parses a literal into an Expr
237 | //Literals can be a number literal, string literal, true/false literal or a hex literal.
238 | //Literals can also have an optional type in Yul.
239 | fn parse_literal(literal: Pair) -> ExprLiteral {
240 | match parse_expression(literal.clone()) {
241 | Expr::Literal(literal) => literal,
242 | _ => unreachable!("This should only parse literals {:?}", &literal),
243 | }
244 | }
245 |
246 | //Function to parse grammar within an expression rule
247 | fn parse_expression(expression: Pair) -> Expr {
248 | let expression = expression.clone().into_inner().next().unwrap();
249 | match expression.as_rule() {
250 | Rule::literal => {
251 | // Parsing literals need to recurse because it could be a number literal
252 | Expr::Literal(parse_literal(expression))
253 | }
254 | Rule::number_literal => parse_expression(expression),
255 | Rule::hex_number => {
256 | // TODO: parse hex numbers
257 | let initial = expression.as_str();
258 | Expr::Literal(ExprLiteral::Number(ExprLiteralNumber {
259 | inferred_type: None,
260 | value: U256::from_str_radix(initial, 16).unwrap(),
261 | }))
262 | }
263 | Rule::hex_literal => {
264 | // TODO: parse hex numbers
265 | let initial = expression.as_str();
266 | Expr::Literal(ExprLiteral::Number(ExprLiteralNumber {
267 | inferred_type: None,
268 | value: U256::from_str_radix(initial, 16).unwrap(),
269 | }))
270 | }
271 | Rule::decimal_number => {
272 | let i = expression.as_str();
273 | Expr::Literal(ExprLiteral::Number(ExprLiteralNumber {
274 | inferred_type: None,
275 | value: U256::from_dec_str(i).unwrap(),
276 | }))
277 | }
278 | Rule::string_literal => {
279 | let content = expression.into_inner().next().unwrap();
280 | Expr::Literal(ExprLiteral::String(content.as_str().to_string()))
281 | }
282 |
283 | // //rule is a false literal
284 | // Rule::false_literal => Expr::Bool(false),
285 |
286 | // //rule is a true literal
287 | // Rule::true_literal => Expr::Bool(true),
288 |
289 | //if the matched rule is an identifier
290 | Rule::identifier => parse_identifier(expression),
291 |
292 | //if the matched rule is a function call
293 | Rule::function_call => {
294 | let mut inners = expression.into_inner();
295 | let function_name = inners.next().unwrap().as_str();
296 | let mut exprs: Vec = Vec::new();
297 | // for each argument in the function, parse the expression and add it to exprs
298 | for arg in inners {
299 | exprs.push(parse_expression(arg));
300 | }
301 | Expr::FunctionCall(ExprFunctionCall {
302 | function_name: function_name.to_string(),
303 | exprs: Box::new(exprs),
304 | inferred_return_types: vec![],
305 | inferred_param_types: vec![],
306 | })
307 | }
308 |
309 | //if the rule has not been defined yet
310 | r => {
311 | panic!("Unreachable rule: {:?}", r);
312 | }
313 | }
314 | }
315 |
316 | //Parses an identifier into an Expr, which gets transpiled into a variable reference.
317 | //These variables need to be kept track of during transpilation in case their value changes during runtime,
318 | // which needs to be accounted for during transpilation.
319 | fn parse_identifier(identifier: Pair) -> Expr {
320 | return Expr::Variable(ExprVariableReference {
321 | identifier: identifier.as_str().to_string(),
322 | inferred_type: None,
323 | });
324 | }
325 |
326 | //Parses a block into an Expr
327 | fn parse_block(expression: Pair) -> ExprBlock {
328 | let mut exprs: Vec = Vec::new();
329 | for statement in expression.into_inner() {
330 | if statement.clone().into_inner().next().is_some() {
331 | exprs.push(parse_statement(statement));
332 | }
333 | }
334 |
335 | ExprBlock { exprs }
336 | }
337 |
338 | // TESTS
339 | #[cfg(test)]
340 | mod tests {
341 | use crate::type_inference::infer_types;
342 |
343 | use super::*;
344 |
345 | fn parse_to_tree(yul: &str) -> String {
346 | let ast = parse_yul_syntax(yul);
347 | let ast_with_inferred_types = infer_types(&ast);
348 | expressions_to_tree(&ast_with_inferred_types)
349 | }
350 |
351 | #[test]
352 | fn parse_var_declaration() {
353 | insta::assert_snapshot!(parse_to_tree(
354 | "let x := 1
355 | let y := 2"
356 | ));
357 | }
358 |
359 | #[test]
360 | fn parse_var_declaration_with_types() {
361 | insta::assert_snapshot!(parse_to_tree(
362 | "let x:u32 := 1
363 | let y:u256 := 2
364 | let z := 2
365 | "
366 | ));
367 | }
368 |
369 | #[test]
370 | fn parse_function_call() {
371 | insta::assert_snapshot!(parse_to_tree("add(1,2)"));
372 | }
373 |
374 | #[test]
375 | fn parse_var_and_add() {
376 | insta::assert_snapshot!(parse_to_tree("let x := add(1,2)"));
377 | }
378 |
379 | #[ignore]
380 | #[test]
381 | fn parse_literals() {
382 | insta::assert_snapshot!(parse_to_tree(
383 | "
384 | \"string_literal\"
385 | true
386 | false
387 | 1
388 | 0x1
389 | "
390 | ));
391 | }
392 |
393 | #[test]
394 | fn parse_fibonnaci() {
395 | insta::assert_snapshot!(parse_to_tree(
396 | "
397 | let f := 1
398 | let s := 1
399 | let next
400 | for { let i := 0 } lt(i, 10) { i := add(i, 1)}
401 | {
402 | if lt(i, 2) {
403 | mstore(i, 1)
404 | }
405 | if gt(i, 1) {
406 | next := add(s, f)
407 | f := s
408 | s := next
409 | mstore(i, s)
410 | }
411 | }"
412 | ));
413 | }
414 |
415 | #[test]
416 | fn parse_if() {
417 | insta::assert_snapshot!(parse_to_tree(
418 | "
419 | if lt(i, 2) {
420 | mstore(i, 1)
421 | }
422 | "
423 | ));
424 | }
425 |
426 | #[test]
427 | fn parse_cruft() {
428 | let yul = r###"
429 | object "fib" {
430 | code {
431 | }
432 | }
433 |
434 | "###;
435 | insta::assert_snapshot!(parse_to_tree(yul));
436 | }
437 |
438 | //TODO: add test for parse function definition
439 |
440 | #[ignore]
441 | #[test]
442 | fn parse_break() {
443 | insta::assert_snapshot!(parse_to_tree(
444 | "for { let i := 0 } lt(i, 10) { i := add(i, 1)}
445 | {
446 | if lt(i,3){
447 | break
448 | }
449 | "
450 | ));
451 | }
452 |
453 | #[ignore]
454 | #[test]
455 | fn parse_continue() {
456 | insta::assert_snapshot!(parse_to_tree(
457 | "for { let i := 0 } lt(i, 10) { i := add(i, 1)}
458 | {
459 | if lt(i,3){
460 | continue
461 | }
462 | "
463 | ));
464 | }
465 |
466 | #[test]
467 | fn parse_function_def_with_return() {
468 | insta::assert_snapshot!(parse_to_tree(
469 | "
470 | function allocate_unbounded() -> memPtr {
471 | memPtr := mload(64)
472 | }"
473 | ));
474 | }
475 |
476 | #[test]
477 | fn parse_function_def_without_return() {
478 | insta::assert_snapshot!(parse_to_tree(
479 | "
480 | function allocate_unbounded() {
481 | let memPtr := mload(64)
482 | }"
483 | ));
484 | }
485 |
486 | #[test]
487 | fn parse_switch_statement() {
488 | insta::assert_snapshot!(parse_to_tree(
489 | "
490 | let x := 5
491 | let y := 8
492 | switch x
493 | case 3 {
494 | y := 5
495 | }
496 | case 5 {
497 | y := 12
498 | let z := 15
499 | }
500 | case 8 {
501 | y := 15
502 | }
503 | y"
504 | ));
505 | }
506 |
507 | //TODO: add test for default
508 | }
509 |
--------------------------------------------------------------------------------
/crates/papyrus/src/snapshots/papyrus__parser__tests__parse_cruft.snap:
--------------------------------------------------------------------------------
1 | ---
2 | source: crates/papyrus/src/parser.rs
3 | expression: parse_to_tree(yul)
4 | ---
5 | AST
6 |
--------------------------------------------------------------------------------
/crates/papyrus/src/snapshots/papyrus__parser__tests__parse_fibonnaci.snap:
--------------------------------------------------------------------------------
1 | ---
2 | source: crates/papyrus/src/parser.rs
3 | expression: "parse_to_tree(\"\n let f := 1\n let s := 1\n let next\n for { let i := 0 } lt(i, 10) { i := add(i, 1)}\n {\n if lt(i, 2) {\n mstore(i, 1)\n }\n if gt(i, 1) {\n next := add(s, f)\n f := s\n s := next\n mstore(i, s)\n }\n }\")"
4 | ---
5 | AST
6 | ├╼ declare - f:u256
7 | │ └╼ 1:u256
8 | ├╼ declare - s:u256
9 | │ └╼ 1:u256
10 | ├╼ declare - next:u256
11 | └╼ for loop
12 | ├╼ init block
13 | │ └╼ declare - i:u256
14 | │ └╼ 0:u256
15 | ├╼ conditional
16 | │ └╼ lt(u256, u256): u256
17 | │ ├╼ var - i:u256
18 | │ └╼ 10:u256
19 | ├╼ after block
20 | │ └╼ assign - i:u256
21 | │ └╼ add(u256, u256): u256
22 | │ ├╼ var - i:u256
23 | │ └╼ 1:u256
24 | └╼ interior block
25 | ├╼ if statement
26 | │ └╼ conditional
27 | │ ├╼ lt(u256, u256): u256
28 | │ │ ├╼ var - i:u256
29 | │ │ └╼ 2:u256
30 | │ └╼ mstore(u256, u256): u256
31 | │ ├╼ var - i:u256
32 | │ └╼ 1:u256
33 | └╼ if statement
34 | └╼ conditional
35 | ├╼ gt(u256, u256): u256
36 | │ ├╼ var - i:u256
37 | │ └╼ 1:u256
38 | ├╼ assign - next:u256
39 | │ └╼ add(u256, u256): u256
40 | │ ├╼ var - s:u256
41 | │ └╼ var - f:u256
42 | ├╼ assign - f:u256
43 | │ └╼ var - s:u256
44 | ├╼ assign - s:u256
45 | │ └╼ var - next:u256
46 | └╼ mstore(u256, u256): u256
47 | ├╼ var - i:u256
48 | └╼ var - s:u256
49 |
--------------------------------------------------------------------------------
/crates/papyrus/src/snapshots/papyrus__parser__tests__parse_function_call.snap:
--------------------------------------------------------------------------------
1 | ---
2 | source: crates/papyrus/src/parser.rs
3 | expression: "parse_to_tree(\"add(1,2)\")"
4 | ---
5 | AST
6 | └╼ add(u256, u256):
7 | ├╼ 1:u256
8 | └╼ 2:u256
9 |
--------------------------------------------------------------------------------
/crates/papyrus/src/snapshots/papyrus__parser__tests__parse_function_def_with_return.snap:
--------------------------------------------------------------------------------
1 | ---
2 | source: crates/papyrus/src/parser.rs
3 | expression: "parse_to_tree(\"\n function allocate_unbounded() -> memPtr {\n memPtr := mload(64)\n }\")"
4 | ---
5 | AST
6 | └╼ function definition - allocate_unbounded
7 | ├╼ params
8 | ├╼ returns
9 | │ └╼ memPtr:u256
10 | └╼ body
11 | └╼ assign - memPtr:u256
12 | └╼ mload(u32): u256
13 | └╼ 64:u32
14 |
--------------------------------------------------------------------------------
/crates/papyrus/src/snapshots/papyrus__parser__tests__parse_function_def_without_return.snap:
--------------------------------------------------------------------------------
1 | ---
2 | source: crates/papyrus/src/parser.rs
3 | expression: "parse_to_tree(\"\n function allocate_unbounded() {\n let memPtr := mload(64)\n }\")"
4 | ---
5 | AST
6 | └╼ function definition - allocate_unbounded
7 | ├╼ params
8 | ├╼ returns
9 | └╼ body
10 | └╼ declare - memPtr:u256
11 | └╼ mload(u32): u256
12 | └╼ 64:u32
13 |
--------------------------------------------------------------------------------
/crates/papyrus/src/snapshots/papyrus__parser__tests__parse_if.snap:
--------------------------------------------------------------------------------
1 | ---
2 | source: crates/papyrus/src/parser.rs
3 | expression: "parse_to_tree(\"\n if lt(i, 2) {\n mstore(i, 1)\n }\n \")"
4 | ---
5 | AST
6 | └╼ if statement
7 | └╼ conditional
8 | ├╼ lt(unknown, u256):
9 | │ ├╼ var - i:unknown
10 | │ └╼ 2:u256
11 | └╼ mstore(unknown, u256):
12 | ├╼ var - i:unknown
13 | └╼ 1:u256
14 |
--------------------------------------------------------------------------------
/crates/papyrus/src/snapshots/papyrus__parser__tests__parse_switch_statement.snap:
--------------------------------------------------------------------------------
1 | ---
2 | source: crates/papyrus/src/parser.rs
3 | expression: "parse_to_tree(\"\n let x := 5\n let y := 8\n switch x\n case 3 {\n y := 5\n }\n case 5 {\n y := 12\n let z := 15\n }\n case 8 {\n y := 15\n }\n y\")"
4 | ---
5 | AST
6 | ├╼ declare - x:u256
7 | │ └╼ 5:u256
8 | ├╼ declare - y:u256
9 | │ └╼ 8:u256
10 | ├╼ switch
11 | │ ├╼ var - x:u256
12 | │ ├╼ case
13 | │ │ └╼ assign - y:u256
14 | │ │ └╼ 5:u256
15 | │ ├╼ case
16 | │ │ ├╼ assign - y:u256
17 | │ │ │ └╼ 12:u256
18 | │ │ └╼ declare - z:u256
19 | │ │ └╼ 15:u256
20 | │ └╼ case
21 | │ └╼ assign - y:u256
22 | │ └╼ 15:u256
23 | └╼ var - y:u256
24 |
--------------------------------------------------------------------------------
/crates/papyrus/src/snapshots/papyrus__parser__tests__parse_var_and_add.snap:
--------------------------------------------------------------------------------
1 | ---
2 | source: crates/papyrus/src/parser.rs
3 | expression: "parse_to_tree(\"let x := add(1,2)\")"
4 | ---
5 | AST
6 | └╼ declare - x:u256
7 | └╼ add(u256, u256): u256
8 | ├╼ 1:u256
9 | └╼ 2:u256
10 |
--------------------------------------------------------------------------------
/crates/papyrus/src/snapshots/papyrus__parser__tests__parse_var_declaration.snap:
--------------------------------------------------------------------------------
1 | ---
2 | source: crates/papyrus/src/parser.rs
3 | expression: "parse_to_tree(\"let x := 1\n let y := 2\")"
4 | ---
5 | AST
6 | ├╼ declare - x:u256
7 | │ └╼ 1:u256
8 | └╼ declare - y:u256
9 | └╼ 2:u256
10 |
--------------------------------------------------------------------------------
/crates/papyrus/src/snapshots/papyrus__parser__tests__parse_var_declaration_with_types.snap:
--------------------------------------------------------------------------------
1 | ---
2 | source: crates/papyrus/src/parser.rs
3 | expression: "parse_to_tree(\"let x:u32 := 1\n let y:u256 := 2\n let z := 2\n \")"
4 | ---
5 | AST
6 | ├╼ declare - x:u32
7 | │ └╼ 1:u32
8 | ├╼ declare - y:u256
9 | │ └╼ 2:u256
10 | └╼ declare - z:u256
11 | └╼ 2:u256
12 |
--------------------------------------------------------------------------------
/crates/papyrus/src/type_inference.rs:
--------------------------------------------------------------------------------
1 | use std::{collections::HashMap, vec};
2 |
3 | use crate::types::*;
4 |
5 | //Function to
6 | pub fn infer_types(ast: &Vec) -> Vec {
7 | let mut inferrer = TypeInferrer::default();
8 | inferrer.walk_ast(ast)
9 | }
10 |
11 | #[derive(Default)]
12 | struct TypeInferrer {
13 | scoped_variables: HashMap,
14 | expected_types: Vec