├── .eslintrc.cjs
├── .gitattributes
├── .github
├── dependabot.yml
└── workflows
│ └── ci.yml
├── .gitignore
├── COPYING
├── README.md
├── build
└── main.cjs
├── main.js
├── package-lock.json
├── package.json
├── rollup.cjs.config.js
├── src
├── codebuilder.js
├── codebuilder_wat.js
├── functionbuilder.js
├── functionbuilder_wat.js
├── modulebuilder.js
├── modulebuilder_wat.js
├── protoboard.js
└── utils.js
└── test
├── basic.js
└── protoboard.js
/.eslintrc.cjs:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | "plugins": [
3 | "mocha"
4 | ],
5 | "env": {
6 | "es6": true,
7 | "node": true,
8 | "mocha": true,
9 | "es2020": true,
10 | },
11 | "globals": {
12 | "WebAssembly": true
13 | },
14 | "parserOptions": {
15 | "ecmaVersion": 2020,
16 | "sourceType": "module"
17 | },
18 | "extends": "eslint:recommended",
19 | "rules": {
20 | "indent": [
21 | "error",
22 | 4
23 | ],
24 | "linebreak-style": [
25 | "error",
26 | "unix"
27 | ],
28 | "quotes": [
29 | "error",
30 | "double"
31 | ],
32 | "semi": [
33 | "error",
34 | "always"
35 | ],
36 | "mocha/no-exclusive-tests": "error"
37 | }
38 | };
39 |
--------------------------------------------------------------------------------
/.gitattributes:
--------------------------------------------------------------------------------
1 | # Autodetect text files
2 | * text=auto eol=lf
3 |
--------------------------------------------------------------------------------
/.github/dependabot.yml:
--------------------------------------------------------------------------------
1 | version: 2
2 | updates:
3 | # Enable version updates for npm
4 | - package-ecosystem: "npm"
5 | # Look for `package.json` and `lock` files in the `root` directory
6 | directory: "/"
7 | # Check the npm registry for updates every day (weekdays)
8 | schedule:
9 | interval: "daily"
10 |
--------------------------------------------------------------------------------
/.github/workflows/ci.yml:
--------------------------------------------------------------------------------
1 | name: Continuous Integration
2 | on: [push, pull_request]
3 |
4 | jobs:
5 | test:
6 | name: Test
7 | runs-on: ${{ matrix.os }}
8 |
9 | strategy:
10 | fail-fast: false
11 | matrix:
12 | os: [ubuntu-latest, macos-latest, windows-latest]
13 | node-version: ["12", "14", "16", "18"]
14 |
15 | steps:
16 | - name: Checkout project
17 | uses: actions/checkout@v2
18 |
19 | - name: Setup Node.js
20 | uses: actions/setup-node@v3
21 | with:
22 | node-version: ${{ matrix.node-version }}
23 | check-latest: true
24 | cache: 'npm'
25 |
26 | - name: Install dependencies
27 | run: npm ci
28 |
29 | - name: Run tests
30 | run: npm test
31 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | vk_proof.json
2 | vk_verifier.json
3 |
4 | # Logs
5 | logs
6 | *.log
7 | npm-debug.log*
8 | yarn-debug.log*
9 | yarn-error.log*
10 |
11 | # Runtime data
12 | pids
13 | *.pid
14 | *.seed
15 | *.pid.lock
16 |
17 | # Directory for instrumented libs generated by jscoverage/JSCover
18 | lib-cov
19 |
20 | # Coverage directory used by tools like istanbul
21 | coverage
22 |
23 | # nyc test coverage
24 | .nyc_output
25 |
26 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
27 | .grunt
28 |
29 | # Bower dependency directory (https://bower.io/)
30 | bower_components
31 |
32 | # node-waf configuration
33 | .lock-wscript
34 |
35 | # Compiled binary addons (https://nodejs.org/api/addons.html)
36 | build/Release
37 |
38 | # Dependency directories
39 | node_modules/
40 | jspm_packages/
41 |
42 | # Typescript v1 declaration files
43 | typings/
44 |
45 | # Optional npm cache directory
46 | .npm
47 |
48 | # Optional eslint cache
49 | .eslintcache
50 |
51 | # Optional REPL history
52 | .node_repl_history
53 |
54 | # Output of 'npm pack'
55 | *.tgz
56 |
57 | # Yarn Integrity file
58 | .yarn-integrity
59 |
60 | # dotenv environment variables file
61 | .env
62 |
63 | # next.js build output
64 | .next
65 |
66 | tmp
67 |
68 | .DS_Store
69 |
--------------------------------------------------------------------------------
/COPYING:
--------------------------------------------------------------------------------
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 | {one line to give the program's name and a brief idea of what it does.}
635 | Copyright (C) {year} {name of author}
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 | {project} Copyright (C) {year} {fullname}
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 | # wasmbuilder
2 |
3 | Javascript package that helps to build wasm code by hand.
4 |
5 |
6 | ## License
7 |
8 | WasmBuilder is part of the iden3 project copyright 2019 0KIMS association and published with GPL-3 license. Please check the COPYING file for more details.
9 |
--------------------------------------------------------------------------------
/build/main.cjs:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | Object.defineProperty(exports, '__esModule', { value: true });
4 |
5 | /*
6 | Copyright 2019 0KIMS association.
7 |
8 | This file is part of wasmbuilder
9 |
10 | wasmbuilder is a free software: you can redistribute it and/or modify it
11 | under the terms of the GNU General Public License as published by
12 | the Free Software Foundation, either version 3 of the License, or
13 | (at your option) any later version.
14 |
15 | wasmbuilder is distributed in the hope that it will be useful, but WITHOUT
16 | ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
17 | or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
18 | License for more details.
19 |
20 | You should have received a copy of the GNU General Public License
21 | along with wasmbuilder. If not, see .
22 | */
23 |
24 | function toNumber(n) {
25 | return BigInt(n);
26 | }
27 |
28 | function isNegative(n) {
29 | return n < 0n;
30 | }
31 |
32 | function isZero(n) {
33 | return n === 0n;
34 | }
35 |
36 | function bitLength(n) {
37 | if (isNegative(n)) {
38 | return n.toString(2).length - 1; // discard the - sign
39 | } else {
40 | return n.toString(2).length;
41 | }
42 | }
43 |
44 | function u32(n) {
45 | const b = [];
46 | const v = toNumber(n);
47 | b.push(Number(v & 0xFFn));
48 | b.push(Number(v >> 8n & 0xFFn));
49 | b.push(Number(v >> 16n & 0xFFn));
50 | b.push(Number(v >> 24n & 0xFFn));
51 | return b;
52 | }
53 |
54 | function toUTF8Array(str) {
55 | var utf8 = [];
56 | for (var i=0; i < str.length; i++) {
57 | var charcode = str.charCodeAt(i);
58 | if (charcode < 0x80) utf8.push(charcode);
59 | else if (charcode < 0x800) {
60 | utf8.push(0xc0 | (charcode >> 6),
61 | 0x80 | (charcode & 0x3f));
62 | }
63 | else if (charcode < 0xd800 || charcode >= 0xe000) {
64 | utf8.push(0xe0 | (charcode >> 12),
65 | 0x80 | ((charcode>>6) & 0x3f),
66 | 0x80 | (charcode & 0x3f));
67 | }
68 | // surrogate pair
69 | else {
70 | i++;
71 | // UTF-16 encodes 0x10000-0x10FFFF by
72 | // subtracting 0x10000 and splitting the
73 | // 20 bits of 0x0-0xFFFFF into two halves
74 | charcode = 0x10000 + (((charcode & 0x3ff)<<10)
75 | | (str.charCodeAt(i) & 0x3ff));
76 | utf8.push(0xf0 | (charcode >>18),
77 | 0x80 | ((charcode>>12) & 0x3f),
78 | 0x80 | ((charcode>>6) & 0x3f),
79 | 0x80 | (charcode & 0x3f));
80 | }
81 | }
82 | return utf8;
83 | }
84 |
85 | function string(str) {
86 | const bytes = toUTF8Array(str);
87 | return [ ...varuint32(bytes.length), ...bytes ];
88 | }
89 |
90 | function varuint(n) {
91 | const code = [];
92 | let v = toNumber(n);
93 | if (isNegative(v)) throw new Error("Number cannot be negative");
94 | while (!isZero(v)) {
95 | code.push(Number(v & 0x7Fn));
96 | v = v >> 7n;
97 | }
98 | if (code.length==0) code.push(0);
99 | for (let i=0; i 0xFFFFFFFFn) throw new Error("Number too big");
132 | if (v > 0x7FFFFFFFn) v = v - 0x100000000n;
133 | // bigInt("-80000000", 16) as base10
134 | if (v < -2147483648n) throw new Error("Number too small");
135 | return varint(v);
136 | }
137 |
138 | function varint64(n) {
139 | let v = toNumber(n);
140 | if (v > 0xFFFFFFFFFFFFFFFFn) throw new Error("Number too big");
141 | if (v > 0x7FFFFFFFFFFFFFFFn) v = v - 0x10000000000000000n;
142 | // bigInt("-8000000000000000", 16) as base10
143 | if (v < -9223372036854775808n) throw new Error("Number too small");
144 | return varint(v);
145 | }
146 |
147 | function varuint32(n) {
148 | let v = toNumber(n);
149 | if (v > 0xFFFFFFFFn) throw new Error("Number too big");
150 | return varuint(v);
151 | }
152 |
153 | function toHexString(byteArray) {
154 | return Array.from(byteArray, function(byte) {
155 | return ("0" + (byte & 0xFF).toString(16)).slice(-2);
156 | }).join("");
157 | }
158 |
159 | function ident(text) {
160 | if (typeof text === "string") {
161 | let lines = text.split("\n");
162 | for (let i=0; i.
191 | */
192 |
193 | class CodeBuilder {
194 | constructor(func) {
195 | this.func = func;
196 | this.functionName = func.functionName;
197 | this.module = func.module;
198 | }
199 |
200 | setLocal(localName, valCode) {
201 | const idx = this.func.localIdxByName[localName];
202 | if (idx === undefined)
203 | throw new Error(`Local Variable not defined: Function: ${this.functionName} local: ${localName} `);
204 | return [...valCode, 0x21, ...varuint32( idx )];
205 | }
206 |
207 | teeLocal(localName, valCode) {
208 | const idx = this.func.localIdxByName[localName];
209 | if (idx === undefined)
210 | throw new Error(`Local Variable not defined: Function: ${this.functionName} local: ${localName} `);
211 | return [...valCode, 0x22, ...varuint32( idx )];
212 | }
213 |
214 | getLocal(localName) {
215 | const idx = this.func.localIdxByName[localName];
216 | if (idx === undefined)
217 | throw new Error(`Local Variable not defined: Function: ${this.functionName} local: ${localName} `);
218 | return [0x20, ...varuint32( idx )];
219 | }
220 |
221 | i64_load8_s(idxCode, _offset, _align) {
222 | const offset = _offset || 0;
223 | const align = (_align === undefined) ? 0 : _align; // 8 bits alignment by default
224 | return [...idxCode, 0x30, align, ...varuint32(offset)];
225 | }
226 |
227 | i64_load8_u(idxCode, _offset, _align) {
228 | const offset = _offset || 0;
229 | const align = (_align === undefined) ? 0 : _align; // 8 bits alignment by default
230 | return [...idxCode, 0x31, align, ...varuint32(offset)];
231 | }
232 |
233 | i64_load16_s(idxCode, _offset, _align) {
234 | const offset = _offset || 0;
235 | const align = (_align === undefined) ? 1 : _align; // 16 bits alignment by default
236 | return [...idxCode, 0x32, align, ...varuint32(offset)];
237 | }
238 |
239 | i64_load16_u(idxCode, _offset, _align) {
240 | const offset = _offset || 0;
241 | const align = (_align === undefined) ? 1 : _align; // 16 bits alignment by default
242 | return [...idxCode, 0x33, align, ...varuint32(offset)];
243 | }
244 |
245 | i64_load32_s(idxCode, _offset, _align) {
246 | const offset = _offset || 0;
247 | const align = (_align === undefined) ? 2 : _align; // 32 bits alignment by default
248 | return [...idxCode, 0x34, align, ...varuint32(offset)];
249 | }
250 |
251 | i64_load32_u(idxCode, _offset, _align) {
252 | const offset = _offset || 0;
253 | const align = (_align === undefined) ? 2 : _align; // 32 bits alignment by default
254 | return [...idxCode, 0x35, align, ...varuint32(offset)];
255 | }
256 |
257 | i64_load(idxCode, _offset, _align) {
258 | const offset = _offset || 0;
259 | const align = (_align === undefined) ? 3 : _align; // 64 bits alignment by default
260 | return [...idxCode, 0x29, align, ...varuint32(offset)];
261 | }
262 |
263 |
264 | i64_store(idxCode, _offset, _align, _codeVal) {
265 | let offset, align, codeVal;
266 | if (Array.isArray(_offset)) {
267 | offset = 0;
268 | align = 3;
269 | codeVal = _offset;
270 | } else if (Array.isArray(_align)) {
271 | offset = _offset;
272 | align = 3;
273 | codeVal = _align;
274 | } else if (Array.isArray(_codeVal)) {
275 | offset = _offset;
276 | align = _align;
277 | codeVal = _codeVal;
278 | }
279 | return [...idxCode, ...codeVal, 0x37, align, ...varuint32(offset)];
280 | }
281 |
282 | i64_store32(idxCode, _offset, _align, _codeVal) {
283 | let offset, align, codeVal;
284 | if (Array.isArray(_offset)) {
285 | offset = 0;
286 | align = 2;
287 | codeVal = _offset;
288 | } else if (Array.isArray(_align)) {
289 | offset = _offset;
290 | align = 2;
291 | codeVal = _align;
292 | } else if (Array.isArray(_codeVal)) {
293 | offset = _offset;
294 | align = _align;
295 | codeVal = _codeVal;
296 | }
297 | return [...idxCode, ...codeVal, 0x3e, align, ...varuint32(offset)];
298 | }
299 |
300 |
301 | i64_store16(idxCode, _offset, _align, _codeVal) {
302 | let offset, align, codeVal;
303 | if (Array.isArray(_offset)) {
304 | offset = 0;
305 | align = 1;
306 | codeVal = _offset;
307 | } else if (Array.isArray(_align)) {
308 | offset = _offset;
309 | align = 1;
310 | codeVal = _align;
311 | } else if (Array.isArray(_codeVal)) {
312 | offset = _offset;
313 | align = _align;
314 | codeVal = _codeVal;
315 | }
316 | return [...idxCode, ...codeVal, 0x3d, align, ...varuint32(offset)];
317 | }
318 |
319 |
320 | i64_store8(idxCode, _offset, _align, _codeVal) {
321 | let offset, align, codeVal;
322 | if (Array.isArray(_offset)) {
323 | offset = 0;
324 | align = 0;
325 | codeVal = _offset;
326 | } else if (Array.isArray(_align)) {
327 | offset = _offset;
328 | align = 0;
329 | codeVal = _align;
330 | } else if (Array.isArray(_codeVal)) {
331 | offset = _offset;
332 | align = _align;
333 | codeVal = _codeVal;
334 | }
335 | return [...idxCode, ...codeVal, 0x3c, align, ...varuint32(offset)];
336 | }
337 |
338 | i32_load8_s(idxCode, _offset, _align) {
339 | const offset = _offset || 0;
340 | const align = (_align === undefined) ? 0 : _align; // 32 bits alignment by default
341 | return [...idxCode, 0x2c, align, ...varuint32(offset)];
342 | }
343 |
344 | i32_load8_u(idxCode, _offset, _align) {
345 | const offset = _offset || 0;
346 | const align = (_align === undefined) ? 0 : _align; // 32 bits alignment by default
347 | return [...idxCode, 0x2d, align, ...varuint32(offset)];
348 | }
349 |
350 | i32_load16_s(idxCode, _offset, _align) {
351 | const offset = _offset || 0;
352 | const align = (_align === undefined) ? 1 : _align; // 32 bits alignment by default
353 | return [...idxCode, 0x2e, align, ...varuint32(offset)];
354 | }
355 |
356 | i32_load16_u(idxCode, _offset, _align) {
357 | const offset = _offset || 0;
358 | const align = (_align === undefined) ? 1 : _align; // 32 bits alignment by default
359 | return [...idxCode, 0x2f, align, ...varuint32(offset)];
360 | }
361 |
362 | i32_load(idxCode, _offset, _align) {
363 | const offset = _offset || 0;
364 | const align = (_align === undefined) ? 2 : _align; // 32 bits alignment by default
365 | return [...idxCode, 0x28, align, ...varuint32(offset)];
366 | }
367 |
368 | i32_store(idxCode, _offset, _align, _codeVal) {
369 | let offset, align, codeVal;
370 | if (Array.isArray(_offset)) {
371 | offset = 0;
372 | align = 2;
373 | codeVal = _offset;
374 | } else if (Array.isArray(_align)) {
375 | offset = _offset;
376 | align = 2;
377 | codeVal = _align;
378 | } else if (Array.isArray(_codeVal)) {
379 | offset = _offset;
380 | align = _align;
381 | codeVal = _codeVal;
382 | }
383 | return [...idxCode, ...codeVal, 0x36, align, ...varuint32(offset)];
384 | }
385 |
386 |
387 | i32_store16(idxCode, _offset, _align, _codeVal) {
388 | let offset, align, codeVal;
389 | if (Array.isArray(_offset)) {
390 | offset = 0;
391 | align = 1;
392 | codeVal = _offset;
393 | } else if (Array.isArray(_align)) {
394 | offset = _offset;
395 | align = 1;
396 | codeVal = _align;
397 | } else if (Array.isArray(_codeVal)) {
398 | offset = _offset;
399 | align = _align;
400 | codeVal = _codeVal;
401 | }
402 | return [...idxCode, ...codeVal, 0x3b, align, ...varuint32(offset)];
403 | }
404 |
405 | i32_store8(idxCode, _offset, _align, _codeVal) {
406 | let offset, align, codeVal;
407 | if (Array.isArray(_offset)) {
408 | offset = 0;
409 | align = 0;
410 | codeVal = _offset;
411 | } else if (Array.isArray(_align)) {
412 | offset = _offset;
413 | align = 0;
414 | codeVal = _align;
415 | } else if (Array.isArray(_codeVal)) {
416 | offset = _offset;
417 | align = _align;
418 | codeVal = _codeVal;
419 | }
420 | return [...idxCode, ...codeVal, 0x3a, align, ...varuint32(offset)];
421 | }
422 |
423 | call(fnName, ...args) {
424 | const idx = this.module.functionIdxByName[fnName];
425 | if (idx === undefined)
426 | throw new Error(`Function not defined: Function: ${fnName}`);
427 | return [...[].concat(...args), 0x10, ...varuint32(idx)];
428 | }
429 |
430 | call_indirect(fnIdx, ...args) {
431 | return [...[].concat(...args), ...fnIdx, 0x11, 0, 0];
432 | }
433 |
434 | if(condCode, thenCode, elseCode) {
435 | if (elseCode) {
436 | return [...condCode, 0x04, 0x40, ...thenCode, 0x05, ...elseCode, 0x0b];
437 | } else {
438 | return [...condCode, 0x04, 0x40, ...thenCode, 0x0b];
439 | }
440 | }
441 |
442 | block(bCode) { return [0x02, 0x40, ...bCode, 0x0b]; }
443 | loop(...args) {
444 | return [0x03, 0x40, ...[].concat(...[...args]), 0x0b];
445 | }
446 | br_if(relPath, condCode) { return [...condCode, 0x0d, ...varuint32(relPath)]; }
447 | br(relPath) { return [0x0c, ...varuint32(relPath)]; }
448 | ret(rCode) { return [...rCode, 0x0f]; }
449 | drop(dCode) { return [...dCode, 0x1a]; }
450 |
451 | i64_const(num) { return [0x42, ...varint64(num)]; }
452 | i32_const(num) { return [0x41, ...varint32(num)]; }
453 |
454 |
455 | i64_eqz(opcode) { return [...opcode, 0x50]; }
456 | i64_eq(op1code, op2code) { return [...op1code, ...op2code, 0x51]; }
457 | i64_ne(op1code, op2code) { return [...op1code, ...op2code, 0x52]; }
458 | i64_lt_s(op1code, op2code) { return [...op1code, ...op2code, 0x53]; }
459 | i64_lt_u(op1code, op2code) { return [...op1code, ...op2code, 0x54]; }
460 | i64_gt_s(op1code, op2code) { return [...op1code, ...op2code, 0x55]; }
461 | i64_gt_u(op1code, op2code) { return [...op1code, ...op2code, 0x56]; }
462 | i64_le_s(op1code, op2code) { return [...op1code, ...op2code, 0x57]; }
463 | i64_le_u(op1code, op2code) { return [...op1code, ...op2code, 0x58]; }
464 | i64_ge_s(op1code, op2code) { return [...op1code, ...op2code, 0x59]; }
465 | i64_ge_u(op1code, op2code) { return [...op1code, ...op2code, 0x5a]; }
466 | i64_add(op1code, op2code) { return [...op1code, ...op2code, 0x7c]; }
467 | i64_sub(op1code, op2code) { return [...op1code, ...op2code, 0x7d]; }
468 | i64_mul(op1code, op2code) { return [...op1code, ...op2code, 0x7e]; }
469 | i64_div_s(op1code, op2code) { return [...op1code, ...op2code, 0x7f]; }
470 | i64_div_u(op1code, op2code) { return [...op1code, ...op2code, 0x80]; }
471 | i64_rem_s(op1code, op2code) { return [...op1code, ...op2code, 0x81]; }
472 | i64_rem_u(op1code, op2code) { return [...op1code, ...op2code, 0x82]; }
473 | i64_and(op1code, op2code) { return [...op1code, ...op2code, 0x83]; }
474 | i64_or(op1code, op2code) { return [...op1code, ...op2code, 0x84]; }
475 | i64_xor(op1code, op2code) { return [...op1code, ...op2code, 0x85]; }
476 | i64_shl(op1code, op2code) { return [...op1code, ...op2code, 0x86]; }
477 | i64_shr_s(op1code, op2code) { return [...op1code, ...op2code, 0x87]; }
478 | i64_shr_u(op1code, op2code) { return [...op1code, ...op2code, 0x88]; }
479 | i64_extend_i32_s(op1code) { return [...op1code, 0xac]; }
480 | i64_extend_i32_u(op1code) { return [...op1code, 0xad]; }
481 | i64_clz(op1code) { return [...op1code, 0x79]; }
482 | i64_ctz(op1code) { return [...op1code, 0x7a]; }
483 |
484 | i32_eqz(op1code) { return [...op1code, 0x45]; }
485 | i32_eq(op1code, op2code) { return [...op1code, ...op2code, 0x46]; }
486 | i32_ne(op1code, op2code) { return [...op1code, ...op2code, 0x47]; }
487 | i32_lt_s(op1code, op2code) { return [...op1code, ...op2code, 0x48]; }
488 | i32_lt_u(op1code, op2code) { return [...op1code, ...op2code, 0x49]; }
489 | i32_gt_s(op1code, op2code) { return [...op1code, ...op2code, 0x4a]; }
490 | i32_gt_u(op1code, op2code) { return [...op1code, ...op2code, 0x4b]; }
491 | i32_le_s(op1code, op2code) { return [...op1code, ...op2code, 0x4c]; }
492 | i32_le_u(op1code, op2code) { return [...op1code, ...op2code, 0x4d]; }
493 | i32_ge_s(op1code, op2code) { return [...op1code, ...op2code, 0x4e]; }
494 | i32_ge_u(op1code, op2code) { return [...op1code, ...op2code, 0x4f]; }
495 | i32_add(op1code, op2code) { return [...op1code, ...op2code, 0x6a]; }
496 | i32_sub(op1code, op2code) { return [...op1code, ...op2code, 0x6b]; }
497 | i32_mul(op1code, op2code) { return [...op1code, ...op2code, 0x6c]; }
498 | i32_div_s(op1code, op2code) { return [...op1code, ...op2code, 0x6d]; }
499 | i32_div_u(op1code, op2code) { return [...op1code, ...op2code, 0x6e]; }
500 | i32_rem_s(op1code, op2code) { return [...op1code, ...op2code, 0x6f]; }
501 | i32_rem_u(op1code, op2code) { return [...op1code, ...op2code, 0x70]; }
502 | i32_and(op1code, op2code) { return [...op1code, ...op2code, 0x71]; }
503 | i32_or(op1code, op2code) { return [...op1code, ...op2code, 0x72]; }
504 | i32_xor(op1code, op2code) { return [...op1code, ...op2code, 0x73]; }
505 | i32_shl(op1code, op2code) { return [...op1code, ...op2code, 0x74]; }
506 | i32_shr_s(op1code, op2code) { return [...op1code, ...op2code, 0x75]; }
507 | i32_shr_u(op1code, op2code) { return [...op1code, ...op2code, 0x76]; }
508 | i32_rotl(op1code, op2code) { return [...op1code, ...op2code, 0x77]; }
509 | i32_rotr(op1code, op2code) { return [...op1code, ...op2code, 0x78]; }
510 | i32_wrap_i64(op1code) { return [...op1code, 0xa7]; }
511 | i32_clz(op1code) { return [...op1code, 0x67]; }
512 | i32_ctz(op1code) { return [...op1code, 0x68]; }
513 |
514 | unreachable() { return [ 0x0 ]; }
515 |
516 | current_memory() { return [ 0x3f, 0]; }
517 |
518 | comment() { return []; }
519 | }
520 |
521 | /*
522 | Copyright 2019 0KIMS association.
523 |
524 | This file is part of wasmbuilder
525 |
526 | wasmbuilder is a free software: you can redistribute it and/or modify it
527 | under the terms of the GNU General Public License as published by
528 | the Free Software Foundation, either version 3 of the License, or
529 | (at your option) any later version.
530 |
531 | wasmbuilder is distributed in the hope that it will be useful, but WITHOUT
532 | ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
533 | or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
534 | License for more details.
535 |
536 | You should have received a copy of the GNU General Public License
537 | along with wasmbuilder. If not, see .
538 | */
539 |
540 | const typeCodes = {
541 | "i32": 0x7f,
542 | "i64": 0x7e,
543 | "f32": 0x7d,
544 | "f64": 0x7c,
545 | "anyfunc": 0x70,
546 | "func": 0x60,
547 | "emptyblock": 0x40
548 | };
549 |
550 |
551 | class FunctionBuilder {
552 |
553 | constructor (module, fnName, fnType, moduleName, fieldName) {
554 | if (fnType == "import") {
555 | this.fnType = "import";
556 | this.moduleName = moduleName;
557 | this.fieldName = fieldName;
558 | } else if (fnType == "internal") {
559 | this.fnType = "internal";
560 | } else {
561 | throw new Error("Invalid function fnType: " + fnType);
562 | }
563 | this.module = module;
564 | this.fnName = fnName;
565 | this.params = [];
566 | this.locals = [];
567 | this.localIdxByName = {};
568 | this.code = [];
569 | this.returnType = null;
570 | this.nextLocal =0;
571 | }
572 |
573 | addParam(paramName, paramType) {
574 | if (this.localIdxByName[paramName])
575 | throw new Error(`param already exists. Function: ${this.fnName}, Param: ${paramName} `);
576 | const idx = this.nextLocal++;
577 | this.localIdxByName[paramName] = idx;
578 | this.params.push({
579 | type: paramType
580 | });
581 | }
582 |
583 | addLocal(localName, localType, _length) {
584 | const length = _length || 1;
585 | if (this.localIdxByName[localName])
586 | throw new Error(`local already exists. Function: ${this.fnName}, Param: ${localName} `);
587 | const idx = this.nextLocal++;
588 | this.localIdxByName[localName] = idx;
589 | this.locals.push({
590 | type: localType,
591 | length: length
592 | });
593 | }
594 |
595 | setReturnType(returnType) {
596 | if (this.returnType)
597 | throw new Error(`returnType already defined. Function: ${this.fnName}`);
598 | this.returnType = returnType;
599 | }
600 |
601 | getSignature() {
602 | const params = [...varuint32(this.params.length), ...this.params.map((p) => typeCodes[p.type])];
603 | const returns = this.returnType ? [0x01, typeCodes[this.returnType]] : [0];
604 | return [0x60, ...params, ...returns];
605 | }
606 |
607 | getBody() {
608 | const locals = this.locals.map((l) => [
609 | ...varuint32(l.length),
610 | typeCodes[l.type]
611 | ]);
612 |
613 | const body = [
614 | ...varuint32(this.locals.length),
615 | ...[].concat(...locals),
616 | ...this.code,
617 | 0x0b
618 | ];
619 | return [
620 | ...varuint32(body.length),
621 | ...body
622 | ];
623 | }
624 |
625 | addCode(...code) {
626 | this.code.push(...[].concat(...[...code]));
627 | }
628 |
629 | getCodeBuilder() {
630 | return new CodeBuilder(this);
631 | }
632 | }
633 |
634 | /*
635 | Copyright 2019 0KIMS association.
636 |
637 | This file is part of wasmbuilder
638 |
639 | wasmbuilder is a free software: you can redistribute it and/or modify it
640 | under the terms of the GNU General Public License as published by
641 | the Free Software Foundation, either version 3 of the License, or
642 | (at your option) any later version.
643 |
644 | wasmbuilder is distributed in the hope that it will be useful, but WITHOUT
645 | ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
646 | or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
647 | License for more details.
648 |
649 | You should have received a copy of the GNU General Public License
650 | along with wasmbuilder. If not, see .
651 | */
652 |
653 | class ModuleBuilder {
654 |
655 | constructor() {
656 | this.functions = [];
657 | this.functionIdxByName = {};
658 | this.nImportFunctions = 0;
659 | this.nInternalFunctions =0;
660 | this.memory = {
661 | pagesSize: 1,
662 | moduleName: "env",
663 | fieldName: "memory"
664 | };
665 | this.free = 8;
666 | this.datas = [];
667 | this.modules = {};
668 | this.exports = [];
669 | this.functionsTable = [];
670 | }
671 |
672 | build() {
673 | this._setSignatures();
674 | return new Uint8Array([
675 | ...u32(0x6d736100),
676 | ...u32(1),
677 | ...this._buildType(),
678 | ...this._buildImport(),
679 | ...this._buildFunctionDeclarations(),
680 | ...this._buildFunctionsTable(),
681 | ...this._buildExports(),
682 | ...this._buildElements(),
683 | ...this._buildCode(),
684 | ...this._buildData()
685 | ]);
686 | }
687 |
688 | addFunction(fnName) {
689 | if (typeof(this.functionIdxByName[fnName]) !== "undefined")
690 | throw new Error(`Function already defined: ${fnName}`);
691 |
692 | const idx = this.functions.length;
693 | this.functionIdxByName[fnName] = idx;
694 |
695 | this.functions.push(new FunctionBuilder(this, fnName, "internal"));
696 |
697 | this.nInternalFunctions++;
698 | return this.functions[idx];
699 | }
700 |
701 | addIimportFunction(fnName, moduleName, _fieldName) {
702 | if (typeof(this.functionIdxByName[fnName]) !== "undefined")
703 | throw new Error(`Function already defined: ${fnName}`);
704 |
705 | if ( (this.functions.length>0)
706 | &&(this.functions[this.functions.length-1].type == "internal"))
707 | throw new Error(`Import functions must be declared before internal: ${fnName}`);
708 |
709 | let fieldName = _fieldName || fnName;
710 |
711 | const idx = this.functions.length;
712 | this.functionIdxByName[fnName] = idx;
713 |
714 | this.functions.push(new FunctionBuilder(this, fnName, "import", moduleName, fieldName));
715 |
716 | this.nImportFunctions ++;
717 | return this.functions[idx];
718 | }
719 |
720 | setMemory(pagesSize, moduleName, fieldName) {
721 | this.memory = {
722 | pagesSize: pagesSize,
723 | moduleName: moduleName || "env",
724 | fieldName: fieldName || "memory"
725 | };
726 | }
727 |
728 | exportFunction(fnName, _exportName) {
729 | const exportName = _exportName || fnName;
730 | if (typeof(this.functionIdxByName[fnName]) === "undefined")
731 | throw new Error(`Function not defined: ${fnName}`);
732 | const idx = this.functionIdxByName[fnName];
733 | if (exportName != fnName) {
734 | this.functionIdxByName[exportName] = idx;
735 | }
736 | this.exports.push({
737 | exportName: exportName,
738 | idx: idx
739 | });
740 | }
741 |
742 | addFunctionToTable(fnName) {
743 | const idx = this.functionIdxByName[fnName];
744 | this.functionsTable.push(idx);
745 | }
746 |
747 | addData(offset, bytes) {
748 | this.datas.push({
749 | offset: offset,
750 | bytes: bytes
751 | });
752 | }
753 |
754 | alloc(a, b) {
755 | let size;
756 | let bytes;
757 | if ((Array.isArray(a) || ArrayBuffer.isView(a)) && (typeof(b) === "undefined")) {
758 | size = a.length;
759 | bytes = a;
760 | } else {
761 | size = a;
762 | bytes = b;
763 | }
764 | size = (((size-1)>>3) +1)<<3; // Align to 64 bits.
765 | const p = this.free;
766 | this.free += size;
767 | if (bytes) {
768 | this.addData(p, bytes);
769 | }
770 | return p;
771 | }
772 |
773 | allocString(s) {
774 | const encoder = new globalThis.TextEncoder();
775 | const uint8array = encoder.encode(s);
776 | return this.alloc([...uint8array, 0]);
777 | }
778 |
779 | _setSignatures() {
780 | this.signatures = [];
781 | const signatureIdxByName = {};
782 | if (this.functionsTable.length>0) {
783 | const signature = this.functions[this.functionsTable[0]].getSignature();
784 | const signatureName = "s_"+toHexString(signature);
785 | signatureIdxByName[signatureName] = 0;
786 | this.signatures.push(signature);
787 | }
788 | for (let i=0; i.
954 | */
955 |
956 | class CodeBuilderWat {
957 | constructor(func) {
958 | this.func = func;
959 | this.functionName = func.functionName;
960 | this.module = func.module;
961 | }
962 |
963 | setLocal(localName, valCode) {
964 | const idx = this.func.localIdxByName[localName];
965 | if (idx === undefined)
966 | throw new Error(`Local Variable not defined: Function: ${this.functionName} local: ${localName} `);
967 | return [valCode, `set_local $${localName}`];
968 | }
969 |
970 | teeLocal(localName, valCode) {
971 | const idx = this.func.localIdxByName[localName];
972 | if (idx === undefined)
973 | throw new Error(`Local Variable not defined: Function: ${this.functionName} local: ${localName} `);
974 | return [valCode, `tee_local $${localName}`];
975 | }
976 |
977 | getLocal(localName) {
978 | const idx = this.func.localIdxByName[localName];
979 | if (idx === undefined)
980 | throw new Error(`Local Variable not defined: Function: ${this.functionName} local: ${localName} `);
981 | return `get_local $${localName}`;
982 | }
983 |
984 | genLoad(inst, def_align, idxCode, _offset, _align) {
985 | let S = inst;
986 | const offset = _offset || 0;
987 | if (offset>0) S += ` offset=${offset}`;
988 | const align = (_align === undefined) ? def_align : _align; // 8 bits alignment by default
989 | if (align!=def_align) S += ` align=${1 << align}`;
990 | return [idxCode, S];
991 | }
992 |
993 |
994 | genStore(inst, def_align, idxCode, _offset, _align, _codeVal) {
995 | let offset, align, codeVal;
996 | if (typeof _align === "undefined") {
997 | offset = 0;
998 | align = def_align;
999 | codeVal = _offset;
1000 | } else if (typeof _codeVal === "undefined") {
1001 | offset = _offset;
1002 | align = def_align;
1003 | codeVal = _align;
1004 | } else {
1005 | offset = _offset;
1006 | align = _align;
1007 | codeVal = _codeVal;
1008 | }
1009 | let S = inst;
1010 | if (offset>0) S += ` offset=${offset}`;
1011 | if (align!=def_align) S += ` align=${1 << align}`;
1012 | return [idxCode, codeVal, S];
1013 | }
1014 |
1015 | i64_load8_s(idxCode, _offset, _align) {
1016 | return this.genLoad("i64.load8_s", 0, idxCode, _offset, _align);
1017 | }
1018 |
1019 | i64_load8_u(idxCode, _offset, _align) {
1020 | return this.genLoad("i64.load8_u", 0, idxCode, _offset, _align);
1021 | }
1022 |
1023 | i64_load16_s(idxCode, _offset, _align) {
1024 | return this.genLoad("i64.load16_s", 1,idxCode, _offset, _align);
1025 | }
1026 |
1027 | i64_load16_u(idxCode, _offset, _align) {
1028 | return this.genLoad("i64.load16_u", 1, idxCode, _offset, _align);
1029 | }
1030 |
1031 | i64_load32_s(idxCode, _offset, _align) {
1032 | return this.genLoad("i64.load32_s", 2, idxCode, _offset, _align);
1033 | }
1034 |
1035 | i64_load32_u(idxCode, _offset, _align) {
1036 | return this.genLoad("i64.load32_u", 2, idxCode, _offset, _align);
1037 | }
1038 |
1039 | i64_load(idxCode, _offset, _align) {
1040 | return this.genLoad("i64.load", 3, idxCode, _offset, _align);
1041 | }
1042 |
1043 |
1044 | i64_store(idxCode, _offset, _align, _codeVal) {
1045 | return this.genStore("i64.store", 3, idxCode, _offset, _align, _codeVal);
1046 | }
1047 |
1048 | i64_store32(idxCode, _offset, _align, _codeVal) {
1049 | return this.genStore("i64.store32", 2, idxCode, _offset, _align, _codeVal);
1050 | }
1051 |
1052 | i64_store16(idxCode, _offset, _align, _codeVal) {
1053 | return this.genStore("i64.store16", 1, idxCode, _offset, _align, _codeVal);
1054 | }
1055 |
1056 | i64_store8(idxCode, _offset, _align, _codeVal) {
1057 | return this.genStore("i64.store8", 0, idxCode, _offset, _align, _codeVal);
1058 | }
1059 |
1060 | i32_load8_s(idxCode, _offset, _align) {
1061 | return this.genLoad("i32.load8_s", 0, idxCode, _offset, _align);
1062 | }
1063 |
1064 | i32_load8_u(idxCode, _offset, _align) {
1065 | return this.genLoad("i32.load8_u", 0, idxCode, _offset, _align);
1066 | }
1067 |
1068 | i32_load16_s(idxCode, _offset, _align) {
1069 | return this.genLoad("i32.load16_s", 1, idxCode, _offset, _align);
1070 | }
1071 |
1072 | i32_load16_u(idxCode, _offset, _align) {
1073 | return this.genLoad("i32.load16_u", 1, idxCode, _offset, _align);
1074 | }
1075 |
1076 | i32_load(idxCode, _offset, _align) {
1077 | return this.genLoad("i32.load", 2, idxCode, _offset, _align);
1078 | }
1079 |
1080 | i32_store(idxCode, _offset, _align, _codeVal) {
1081 | return this.genStore("i32.store", 2, idxCode, _offset, _align, _codeVal);
1082 | }
1083 |
1084 | i32_store16(idxCode, _offset, _align, _codeVal) {
1085 | return this.genStore("i32.store16", 1, idxCode, _offset, _align, _codeVal);
1086 | }
1087 |
1088 | i32_store8(idxCode, _offset, _align, _codeVal) {
1089 | return this.genStore("i32.store8", 0, idxCode, _offset, _align, _codeVal);
1090 | }
1091 |
1092 | call(fnName, ...args) {
1093 | const idx = this.module.functionIdxByName[fnName];
1094 | if (idx === undefined)
1095 | throw new Error(`Function not defined: Function: ${fnName}`);
1096 | return [args, `call $${fnName}`];
1097 | }
1098 |
1099 | call_indirect(fnIdx, ...args) {
1100 | return [args, fnIdx, "call_indirect (type 0)"];
1101 | }
1102 |
1103 | if(condCode, thenCode, elseCode) {
1104 | if (elseCode) {
1105 | return [condCode, "if", ident(thenCode), "else", ident(elseCode), "end"];
1106 | } else {
1107 | return [condCode, "if", ident(thenCode), "end"];
1108 | }
1109 | }
1110 |
1111 | block(bCode) { return ["block", ident(bCode), "end"]; }
1112 | loop(...args) { return ["loop", ident(args), "end"]; }
1113 | br_if(relPath, condCode) { return [condCode, `br_if ${relPath}`]; }
1114 | br(relPath) { return `br ${relPath}`; }
1115 | ret(rCode) { return [rCode, "return"]; }
1116 | drop(dCode) { return [dCode, "drop"]; }
1117 |
1118 | i64_const(num) { return `i64.const ${num}`; }
1119 | i32_const(num) { return `i32.const ${num}`; }
1120 |
1121 | i64_eqz(opcode) { return [opcode, "i64.eqz"]; }
1122 | i64_eq(op1code, op2code) { return [op1code, op2code, "i64.eq"]; }
1123 | i64_ne(op1code, op2code) { return [op1code, op2code, "i64.ne"]; }
1124 | i64_lt_s(op1code, op2code) { return [op1code, op2code, "i64.lt_s"]; }
1125 | i64_lt_u(op1code, op2code) { return [op1code, op2code, "i64.lt_u"]; }
1126 | i64_gt_s(op1code, op2code) { return [op1code, op2code, "i64.gt_s"]; }
1127 | i64_gt_u(op1code, op2code) { return [op1code, op2code, "i64.gt_u"]; }
1128 | i64_le_s(op1code, op2code) { return [op1code, op2code, "i64.le_s"]; }
1129 | i64_le_u(op1code, op2code) { return [op1code, op2code, "i64.le_u"]; }
1130 | i64_ge_s(op1code, op2code) { return [op1code, op2code, "i64.ge_s"]; }
1131 | i64_ge_u(op1code, op2code) { return [op1code, op2code, "i64.ge_u"]; }
1132 | i64_add(op1code, op2code) { return [op1code, op2code, "i64.add"]; }
1133 | i64_sub(op1code, op2code) { return [op1code, op2code, "i64.sub"]; }
1134 | i64_mul(op1code, op2code) { return [op1code, op2code, "i64.mul"]; }
1135 | i64_div_s(op1code, op2code) { return [op1code, op2code, "i64.div_s"]; }
1136 | i64_div_u(op1code, op2code) { return [op1code, op2code, "i64.div_u"]; }
1137 | i64_rem_s(op1code, op2code) { return [op1code, op2code, "i64.rem_s"]; }
1138 | i64_rem_u(op1code, op2code) { return [op1code, op2code, "i64.rem_u"]; }
1139 | i64_and(op1code, op2code) { return [op1code, op2code, "i64.and"]; }
1140 | i64_or(op1code, op2code) { return [op1code, op2code, "i64.or"]; }
1141 | i64_xor(op1code, op2code) { return [op1code, op2code, "i64.xor"]; }
1142 | i64_shl(op1code, op2code) { return [op1code, op2code, "i64.shl"]; }
1143 | i64_shr_s(op1code, op2code) { return [op1code, op2code, "i64.shr_s"]; }
1144 | i64_shr_u(op1code, op2code) { return [op1code, op2code, "i64.shr_u"]; }
1145 | i64_extend_i32_s(op1code) { return [op1code, "i64.extend_s/i32"]; }
1146 | i64_extend_i32_u(op1code) { return [op1code, "i64.extend_u/i32"]; }
1147 |
1148 |
1149 | i32_eqz(op1code) { return [op1code, "i32.eqz"]; }
1150 | i32_eq(op1code, op2code) { return [op1code, op2code, "i32.eq"]; }
1151 | i32_ne(op1code, op2code) { return [op1code, op2code, "i32.ne"]; }
1152 | i32_lt_s(op1code, op2code) { return [op1code, op2code, "i32.lt_s"]; }
1153 | i32_lt_u(op1code, op2code) { return [op1code, op2code, "i32.lt_u"]; }
1154 | i32_gt_s(op1code, op2code) { return [op1code, op2code, "i32.gt_s"]; }
1155 | i32_gt_u(op1code, op2code) { return [op1code, op2code, "i32.gt_u"]; }
1156 | i32_le_s(op1code, op2code) { return [op1code, op2code, "i32.le_s"]; }
1157 | i32_le_u(op1code, op2code) { return [op1code, op2code, "i32.le_u"]; }
1158 | i32_ge_s(op1code, op2code) { return [op1code, op2code, "i32.ge_s"]; }
1159 | i32_ge_u(op1code, op2code) { return [op1code, op2code, "i32.ge_u"]; }
1160 | i32_add(op1code, op2code) { return [op1code, op2code, "i32.add"]; }
1161 | i32_sub(op1code, op2code) { return [op1code, op2code, "i32.sub"]; }
1162 | i32_mul(op1code, op2code) { return [op1code, op2code, "i32.mul"]; }
1163 | i32_div_s(op1code, op2code) { return [op1code, op2code, "i32.div_s"]; }
1164 | i32_div_u(op1code, op2code) { return [op1code, op2code, "i32.div_u"]; }
1165 | i32_rem_s(op1code, op2code) { return [op1code, op2code, "i32.rem_s"]; }
1166 | i32_rem_u(op1code, op2code) { return [op1code, op2code, "i32.rem_u"]; }
1167 | i32_and(op1code, op2code) { return [op1code, op2code, "i32.and"]; }
1168 | i32_or(op1code, op2code) { return [op1code, op2code, "i32.or"]; }
1169 | i32_xor(op1code, op2code) { return [op1code, op2code, "i32.xor"]; }
1170 | i32_shl(op1code, op2code) { return [op1code, op2code, "i32.shl"]; }
1171 | i32_shr_s(op1code, op2code) { return [op1code, op2code, "i32.shr_s"]; }
1172 | i32_shr_u(op1code, op2code) { return [op1code, op2code, "i32.shr_u"]; }
1173 | i32_rotl(op1code, op2code) { return [op1code, op2code, "i32.rotl"]; }
1174 | i32_rotr(op1code, op2code) { return [op1code, op2code, "i32.rotr"]; }
1175 | i32_wrap_i64(op1code) { return [op1code, "i32.wrap/i64"]; }
1176 |
1177 | ureachable() { return "unreachable"; }
1178 |
1179 | current_memory() { return "current_memory"; }
1180 |
1181 | comment(c) { return ";; " + c; }
1182 |
1183 | }
1184 |
1185 | /*
1186 | Copyright 2019 0KIMS association.
1187 |
1188 | This file is part of wasmbuilder
1189 |
1190 | wasmbuilder is a free software: you can redistribute it and/or modify it
1191 | under the terms of the GNU General Public License as published by
1192 | the Free Software Foundation, either version 3 of the License, or
1193 | (at your option) any later version.
1194 |
1195 | wasmbuilder is distributed in the hope that it will be useful, but WITHOUT
1196 | ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
1197 | or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
1198 | License for more details.
1199 |
1200 | You should have received a copy of the GNU General Public License
1201 | along with wasmbuilder. If not, see .
1202 | */
1203 |
1204 | class FunctionBuilderWat {
1205 |
1206 | constructor (module, fnName, fnType, moduleName, fieldName) {
1207 | if (fnType == "import") {
1208 | this.fnType = "import";
1209 | this.moduleName = moduleName;
1210 | this.fieldName = fieldName;
1211 | } else if (fnType == "internal") {
1212 | this.fnType = "internal";
1213 | this.comment = moduleName;
1214 | } else {
1215 | throw new Error("Invalid function fnType: " + fnType);
1216 | }
1217 | this.module = module;
1218 | this.fnName = fnName;
1219 | this.params = [];
1220 | this.locals = [];
1221 | this.localIdxByName = {};
1222 | this.code = [];
1223 | this.returnType = null;
1224 | this.nextLocal =0;
1225 | }
1226 |
1227 | addParam(paramName, paramType) {
1228 | if (this.localIdxByName[paramName])
1229 | throw new Error(`param already exists. Function: ${this.fnName}, Param: ${paramName} `);
1230 | const idx = this.nextLocal++;
1231 | this.localIdxByName[paramName] = idx;
1232 | this.params.push({
1233 | type: paramType,
1234 | name: paramName
1235 | });
1236 | }
1237 |
1238 | addLocal(localName, localType, _length) {
1239 | if ((typeof _length != "undefined") && (_length != 1)) {
1240 | throw new Error("Locals greater than 1 not implemented");
1241 | }
1242 | if (this.localIdxByName[localName])
1243 | throw new Error(`local already exists. Function: ${this.fnName}, Param: ${localName} `);
1244 | const idx = this.nextLocal++;
1245 | this.localIdxByName[localName] = idx;
1246 | this.locals.push({
1247 | type: localType,
1248 | name: localName,
1249 | });
1250 | }
1251 |
1252 | setReturnType(returnType) {
1253 | if (this.returnType)
1254 | throw new Error(`returnType already defined. Function: ${this.fnName}`);
1255 | this.returnType = returnType;
1256 | }
1257 |
1258 | getSignature() {
1259 | let p = "";
1260 | for (let i=0; i.
1342 | */
1343 |
1344 | class ModuleBuilderWat {
1345 |
1346 | constructor() {
1347 | this.functions = [];
1348 | this.functionIdxByName = {};
1349 | this.nImportFunctions = 0;
1350 | this.nInternalFunctions =0;
1351 | this.memory = {
1352 | pagesSize: 1,
1353 | moduleName: "env",
1354 | fieldName: "memory"
1355 | };
1356 | this.free = 8;
1357 | this.datas = [];
1358 | this.modules = {};
1359 | this.exports = [];
1360 | this.functionsTable = [];
1361 | }
1362 |
1363 | build() {
1364 | const src = [];
1365 | this._setSignatures();
1366 | src.push(this._buildType());
1367 | src.push(this._buildImport());
1368 | if (this.functionsTable.length>0) {
1369 | src.push(this._buildFunctionsTable());
1370 | }
1371 | if (this.exports.length > 0) {
1372 | src.push(this._buildExports());
1373 | }
1374 | if (this.functionsTable.length>0) {
1375 | src.push(this._buildElements());
1376 | }
1377 | if (this.nInternalFunctions>0) {
1378 | src.push(this._buildFunctions());
1379 | }
1380 | src.push(this._buildData());
1381 | return [
1382 | "(module",
1383 | ident(src),
1384 | ")"
1385 | ];
1386 | }
1387 |
1388 | addFunction(fnName, comment) {
1389 | if (typeof(this.functionIdxByName[fnName]) !== "undefined")
1390 | throw new Error(`Function already defined: ${fnName}`);
1391 |
1392 | const idx = this.functions.length;
1393 | this.functionIdxByName[fnName] = idx;
1394 |
1395 | this.functions.push(new FunctionBuilderWat(this, fnName, "internal", comment));
1396 |
1397 | this.nInternalFunctions++;
1398 | return this.functions[idx];
1399 | }
1400 |
1401 | addIimportFunction(fnName, moduleName, _fieldName) {
1402 | if (typeof(this.functionIdxByName[fnName]) !== "undefined")
1403 | throw new Error(`Function already defined: ${fnName}`);
1404 |
1405 | if ( (this.functions.length>0)
1406 | &&(this.functions[this.functions.length-1].type == "internal"))
1407 | throw new Error(`Import functions must be declared before internal: ${fnName}`);
1408 |
1409 | let fieldName = _fieldName || fnName;
1410 |
1411 | const idx = this.functions.length;
1412 | this.functionIdxByName[fnName] = idx;
1413 |
1414 | this.functions.push(new FunctionBuilderWat(this, fnName, "import", moduleName, fieldName));
1415 |
1416 | this.nImportFunctions ++;
1417 | return this.functions[idx];
1418 | }
1419 |
1420 | setMemory(pagesSize, moduleName, fieldName) {
1421 | this.memory = {
1422 | pagesSize: pagesSize,
1423 | moduleName: moduleName || "env",
1424 | fieldName: fieldName || "memory"
1425 | };
1426 | }
1427 |
1428 | exportFunction(fnName, _exportName) {
1429 | const exportName = _exportName || fnName;
1430 | if (typeof(this.functionIdxByName[fnName]) === "undefined")
1431 | throw new Error(`Function not defined: ${fnName}`);
1432 | const idx = this.functionIdxByName[fnName];
1433 | if (exportName != fnName) {
1434 | this.functionIdxByName[exportName] = idx;
1435 | }
1436 | this.exports.push({
1437 | exportName: exportName,
1438 | idx: idx
1439 | });
1440 | }
1441 |
1442 | addFunctionToTable(fnName) {
1443 | const idx = this.functionIdxByName[fnName];
1444 | this.functionsTable.push(idx);
1445 | }
1446 |
1447 | addData(offset, bytes) {
1448 | this.datas.push({
1449 | offset: offset,
1450 | bytes: bytes
1451 | });
1452 | }
1453 |
1454 | alloc(a, b) {
1455 | let size;
1456 | let bytes;
1457 | if ((Array.isArray(a) || ArrayBuffer.isView(a)) && (typeof(b) === "undefined")) {
1458 | size = a.length;
1459 | bytes = a;
1460 | } else {
1461 | size = a;
1462 | bytes = b;
1463 | }
1464 | size = (((size-1)>>3) +1)<<3; // Align to 64 bits.
1465 | const p = this.free;
1466 | this.free += size;
1467 | if (bytes) {
1468 | this.addData(p, bytes);
1469 | }
1470 | return p;
1471 | }
1472 |
1473 | allocString(s) {
1474 | const encoder = new TextEncoder();
1475 | const uint8array = encoder.encode(s);
1476 | return this.alloc([...uint8array, 0]);
1477 | }
1478 |
1479 | _setSignatures() {
1480 | this.signatures = [];
1481 | const signatureIdxByName = {};
1482 | if (this.functionsTable.length>0) {
1483 | const signature = this.functions[this.functionsTable[0]].getSignature();
1484 | const signatureName = this.functions[this.functionsTable[0]].getSignatureName();
1485 | signatureIdxByName[signatureName] = 0;
1486 | this.signatures.push(signature);
1487 | }
1488 | for (let i=0; i126 || b[i] == 34 || b[i]==92) {
1557 | let h=b[i].toString(16);
1558 | while (h.length<2) h = "0"+h;
1559 | S += "\\" + h;
1560 | } else {
1561 | S += String.fromCharCode(b[i]);
1562 | }
1563 | }
1564 | S += "\"";
1565 | return S;
1566 | }
1567 | }
1568 |
1569 | }
1570 |
1571 | /*
1572 | Copyright 2019 0KIMS association.
1573 |
1574 | This file is part of websnark (Web Assembly zkSnark Prover).
1575 |
1576 | websnark is a free software: you can redistribute it and/or modify it
1577 | under the terms of the GNU General Public License as published by
1578 | the Free Software Foundation, either version 3 of the License, or
1579 | (at your option) any later version.
1580 |
1581 | websnark is distributed in the hope that it will be useful, but WITHOUT
1582 | ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
1583 | or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
1584 | License for more details.
1585 |
1586 | You should have received a copy of the GNU General Public License
1587 | along with websnark. If not, see .
1588 | */
1589 |
1590 | async function buildProtoboard(builder, defBytes, bitsPerBytes) {
1591 | const protoboard = new Protoboard();
1592 |
1593 | protoboard.defBytes = defBytes;
1594 | protoboard.bitsPerBytes = bitsPerBytes || 32;
1595 |
1596 | protoboard.memory = new WebAssembly.Memory({initial:20000});
1597 | protoboard.i32 = new Uint32Array(protoboard.memory.buffer);
1598 | protoboard.i8 = new Uint8Array(protoboard.memory.buffer);
1599 |
1600 | const moduleBuilder = new ModuleBuilder();
1601 |
1602 | const fLog32 = moduleBuilder.addIimportFunction("debug_log32", "debug", "log32");
1603 | fLog32.addParam("x", "i32");
1604 | const fLog64 = moduleBuilder.addIimportFunction("debug_log64", "debug", "log64");
1605 | fLog64.addParam("x", "i32");
1606 | fLog64.addParam("y", "i32");
1607 |
1608 | buildLog32(moduleBuilder);
1609 | buildLog64(moduleBuilder);
1610 |
1611 | builder(moduleBuilder, protoboard);
1612 |
1613 |
1614 | const code = moduleBuilder.build();
1615 |
1616 | const wasmModule = await WebAssembly.compile(code);
1617 |
1618 | protoboard.log = console.log;
1619 |
1620 | protoboard.instance = await WebAssembly.instantiate(wasmModule, {
1621 | env: {
1622 | "memory": protoboard.memory
1623 | },
1624 | debug: {
1625 | log32: function (c1) {
1626 | if (c1<0) c1 = 0x100000000+c1;
1627 | let s=c1.toString(16);
1628 | while (s.length<8) s = "0"+s;
1629 | protoboard.log(s + ": " + c1.toString());
1630 | },
1631 | log64: function (c1, c2) {
1632 | if (c1<0) c1 = 0x100000000+c1;
1633 | if (c2<0) c2 = 0x100000000+c2;
1634 | const n = BigInt(c1) + (BigInt(c2) << 32n);
1635 | let s=n.toString(16);
1636 | while (s.length<16) s = "0"+s;
1637 | protoboard.log(s + ": " + n.toString());
1638 | }
1639 | }
1640 | });
1641 |
1642 | Object.assign(protoboard, protoboard.instance.exports);
1643 | Object.assign(protoboard, moduleBuilder.modules);
1644 |
1645 | return protoboard;
1646 |
1647 | function buildLog32(module) {
1648 |
1649 | const f = module.addFunction("log32");
1650 | f.addParam("x", "i32");
1651 |
1652 | const c = f.getCodeBuilder();
1653 | f.addCode(c.call("debug_log32", c.getLocal("x")));
1654 | }
1655 |
1656 | function buildLog64(module) {
1657 |
1658 | const f = module.addFunction("log64");
1659 | f.addParam("x", "i64");
1660 |
1661 | const c = f.getCodeBuilder();
1662 | f.addCode(c.call(
1663 | "debug_log64",
1664 | c.i32_wrap_i64(c.getLocal("x")),
1665 | c.i32_wrap_i64(
1666 | c.i64_shr_u(
1667 | c.getLocal("x"),
1668 | c.i64_const(32)
1669 | )
1670 | )
1671 | ));
1672 | }
1673 |
1674 | }
1675 |
1676 | class Protoboard {
1677 |
1678 | constructor() {
1679 |
1680 | }
1681 |
1682 | alloc(length) {
1683 | if (typeof length === "undefined") {
1684 | length = this.defBytes;
1685 | }
1686 | length = (((length-1)>>3) +1)<<3; // Align to 64 bits.
1687 |
1688 | const res = this.i32[0];
1689 | this.i32[0] += length;
1690 | return res;
1691 | }
1692 |
1693 | set(pos, nums, nBytes) {
1694 | if (!Array.isArray(nums)) {
1695 | nums = [nums];
1696 | }
1697 | if (typeof nBytes === "undefined") {
1698 | nBytes = this.defBytes;
1699 | }
1700 |
1701 | const words = Math.floor((nBytes -1)/4)+1;
1702 | let p = pos;
1703 |
1704 | const CHUNK = 1n << BigInt(this.bitsPerBytes);
1705 |
1706 | for (let i=0; i>2] = Number(remainder);
1712 | v = quotient;
1713 | p += 4;
1714 | }
1715 | if (v !== 0n) {
1716 | throw new Error("Expected v to be 0");
1717 | }
1718 | }
1719 |
1720 | return pos;
1721 | }
1722 |
1723 | get(pos, nElements, nBytes) {
1724 | if (typeof nBytes == "undefined") {
1725 | if (typeof nElements == "undefined") {
1726 | nElements = 1;
1727 | nBytes = this.defBytes;
1728 | } else {
1729 | nElements = nBytes;
1730 | nBytes = this.defBytes;
1731 | }
1732 | }
1733 |
1734 | const words = Math.floor((nBytes -1)/4)+1;
1735 |
1736 | const CHUNK = 1n << BigInt(this.bitsPerBytes);
1737 |
1738 |
1739 | const nums = [];
1740 | for (let i=0; i=0; j--) {
1743 | acc = acc * CHUNK;
1744 | let v = this.i32[(pos>>2)+j];
1745 | if (this.bitsPerBytes <32) {
1746 | if (v&0x80000000) v = v-0x100000000;
1747 | }
1748 | acc = acc + BigInt(v);
1749 | }
1750 | nums.push(acc);
1751 | pos += words*4;
1752 | }
1753 |
1754 | if (nums.length == 1) return nums[0];
1755 | return nums;
1756 | }
1757 | }
1758 |
1759 | exports.ModuleBuilder = ModuleBuilder;
1760 | exports.ModuleBuilderWat = ModuleBuilderWat;
1761 | exports.buildProtoboard = buildProtoboard;
1762 |
--------------------------------------------------------------------------------
/main.js:
--------------------------------------------------------------------------------
1 | /*
2 | Copyright 2019 0KIMS association.
3 |
4 | This file is part of wasmbuilder
5 |
6 | wasmbuilder is a free software: you can redistribute it and/or modify it
7 | under the terms of the GNU General Public License as published by
8 | the Free Software Foundation, either version 3 of the License, or
9 | (at your option) any later version.
10 |
11 | wasmbuilder is distributed in the hope that it will be useful, but WITHOUT
12 | ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
13 | or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
14 | License for more details.
15 |
16 | You should have received a copy of the GNU General Public License
17 | along with wasmbuilder. If not, see .
18 | */
19 |
20 | export { ModuleBuilder } from "./src/modulebuilder.js";
21 | export { ModuleBuilderWat } from "./src/modulebuilder_wat.js";
22 | export { buildProtoboard } from "./src/protoboard.js";
23 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "wasmbuilder",
3 | "type": "module",
4 | "version": "0.0.16",
5 | "description": "Tool to build wasm programs by hand.",
6 | "main": "./build/main.cjs",
7 | "module": "./main.js",
8 | "exports": {
9 | "import": "./main.js",
10 | "require": "./build/main.cjs"
11 | },
12 | "scripts": {
13 | "lint": "eslint .",
14 | "pretest": "npm run lint",
15 | "test": "mocha",
16 | "build": "rollup -c rollup.cjs.config.js"
17 | },
18 | "repository": {
19 | "type": "git",
20 | "url": "https://github.com/iden3/wasmbuilder"
21 | },
22 | "keywords": [
23 | "wasm",
24 | "script",
25 | "generator"
26 | ],
27 | "author": "Jordi Baylina",
28 | "license": "GPL-3.0",
29 | "dependencies": {},
30 | "devDependencies": {
31 | "eslint": "^8.17.0",
32 | "eslint-plugin-mocha": "^10.0.5",
33 | "mocha": "^10.0.0",
34 | "rollup": "^2.38.5"
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/rollup.cjs.config.js:
--------------------------------------------------------------------------------
1 | import fs from "fs";
2 | import { builtinModules as builtin } from "module";
3 |
4 | const pkg = JSON.parse(fs.readFileSync("./package.json"));
5 |
6 | export default {
7 | input: "./main.js",
8 | output: {
9 | file: "build/main.cjs",
10 | format: "cjs",
11 | },
12 | external: [
13 | ...Object.keys(pkg.dependencies),
14 | ...builtin,
15 | ]
16 | };
17 |
--------------------------------------------------------------------------------
/src/codebuilder.js:
--------------------------------------------------------------------------------
1 | /*
2 | Copyright 2019 0KIMS association.
3 |
4 | This file is part of wasmbuilder
5 |
6 | wasmbuilder is a free software: you can redistribute it and/or modify it
7 | under the terms of the GNU General Public License as published by
8 | the Free Software Foundation, either version 3 of the License, or
9 | (at your option) any later version.
10 |
11 | wasmbuilder is distributed in the hope that it will be useful, but WITHOUT
12 | ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
13 | or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
14 | License for more details.
15 |
16 | You should have received a copy of the GNU General Public License
17 | along with wasmbuilder. If not, see .
18 | */
19 |
20 | import * as utils from "./utils.js";
21 |
22 | export class CodeBuilder {
23 | constructor(func) {
24 | this.func = func;
25 | this.functionName = func.functionName;
26 | this.module = func.module;
27 | }
28 |
29 | setLocal(localName, valCode) {
30 | const idx = this.func.localIdxByName[localName];
31 | if (idx === undefined)
32 | throw new Error(`Local Variable not defined: Function: ${this.functionName} local: ${localName} `);
33 | return [...valCode, 0x21, ...utils.varuint32( idx )];
34 | }
35 |
36 | teeLocal(localName, valCode) {
37 | const idx = this.func.localIdxByName[localName];
38 | if (idx === undefined)
39 | throw new Error(`Local Variable not defined: Function: ${this.functionName} local: ${localName} `);
40 | return [...valCode, 0x22, ...utils.varuint32( idx )];
41 | }
42 |
43 | getLocal(localName) {
44 | const idx = this.func.localIdxByName[localName];
45 | if (idx === undefined)
46 | throw new Error(`Local Variable not defined: Function: ${this.functionName} local: ${localName} `);
47 | return [0x20, ...utils.varuint32( idx )];
48 | }
49 |
50 | i64_load8_s(idxCode, _offset, _align) {
51 | const offset = _offset || 0;
52 | const align = (_align === undefined) ? 0 : _align; // 8 bits alignment by default
53 | return [...idxCode, 0x30, align, ...utils.varuint32(offset)];
54 | }
55 |
56 | i64_load8_u(idxCode, _offset, _align) {
57 | const offset = _offset || 0;
58 | const align = (_align === undefined) ? 0 : _align; // 8 bits alignment by default
59 | return [...idxCode, 0x31, align, ...utils.varuint32(offset)];
60 | }
61 |
62 | i64_load16_s(idxCode, _offset, _align) {
63 | const offset = _offset || 0;
64 | const align = (_align === undefined) ? 1 : _align; // 16 bits alignment by default
65 | return [...idxCode, 0x32, align, ...utils.varuint32(offset)];
66 | }
67 |
68 | i64_load16_u(idxCode, _offset, _align) {
69 | const offset = _offset || 0;
70 | const align = (_align === undefined) ? 1 : _align; // 16 bits alignment by default
71 | return [...idxCode, 0x33, align, ...utils.varuint32(offset)];
72 | }
73 |
74 | i64_load32_s(idxCode, _offset, _align) {
75 | const offset = _offset || 0;
76 | const align = (_align === undefined) ? 2 : _align; // 32 bits alignment by default
77 | return [...idxCode, 0x34, align, ...utils.varuint32(offset)];
78 | }
79 |
80 | i64_load32_u(idxCode, _offset, _align) {
81 | const offset = _offset || 0;
82 | const align = (_align === undefined) ? 2 : _align; // 32 bits alignment by default
83 | return [...idxCode, 0x35, align, ...utils.varuint32(offset)];
84 | }
85 |
86 | i64_load(idxCode, _offset, _align) {
87 | const offset = _offset || 0;
88 | const align = (_align === undefined) ? 3 : _align; // 64 bits alignment by default
89 | return [...idxCode, 0x29, align, ...utils.varuint32(offset)];
90 | }
91 |
92 |
93 | i64_store(idxCode, _offset, _align, _codeVal) {
94 | let offset, align, codeVal;
95 | if (Array.isArray(_offset)) {
96 | offset = 0;
97 | align = 3;
98 | codeVal = _offset;
99 | } else if (Array.isArray(_align)) {
100 | offset = _offset;
101 | align = 3;
102 | codeVal = _align;
103 | } else if (Array.isArray(_codeVal)) {
104 | offset = _offset;
105 | align = _align;
106 | codeVal = _codeVal;
107 | }
108 | return [...idxCode, ...codeVal, 0x37, align, ...utils.varuint32(offset)];
109 | }
110 |
111 | i64_store32(idxCode, _offset, _align, _codeVal) {
112 | let offset, align, codeVal;
113 | if (Array.isArray(_offset)) {
114 | offset = 0;
115 | align = 2;
116 | codeVal = _offset;
117 | } else if (Array.isArray(_align)) {
118 | offset = _offset;
119 | align = 2;
120 | codeVal = _align;
121 | } else if (Array.isArray(_codeVal)) {
122 | offset = _offset;
123 | align = _align;
124 | codeVal = _codeVal;
125 | }
126 | return [...idxCode, ...codeVal, 0x3e, align, ...utils.varuint32(offset)];
127 | }
128 |
129 |
130 | i64_store16(idxCode, _offset, _align, _codeVal) {
131 | let offset, align, codeVal;
132 | if (Array.isArray(_offset)) {
133 | offset = 0;
134 | align = 1;
135 | codeVal = _offset;
136 | } else if (Array.isArray(_align)) {
137 | offset = _offset;
138 | align = 1;
139 | codeVal = _align;
140 | } else if (Array.isArray(_codeVal)) {
141 | offset = _offset;
142 | align = _align;
143 | codeVal = _codeVal;
144 | }
145 | return [...idxCode, ...codeVal, 0x3d, align, ...utils.varuint32(offset)];
146 | }
147 |
148 |
149 | i64_store8(idxCode, _offset, _align, _codeVal) {
150 | let offset, align, codeVal;
151 | if (Array.isArray(_offset)) {
152 | offset = 0;
153 | align = 0;
154 | codeVal = _offset;
155 | } else if (Array.isArray(_align)) {
156 | offset = _offset;
157 | align = 0;
158 | codeVal = _align;
159 | } else if (Array.isArray(_codeVal)) {
160 | offset = _offset;
161 | align = _align;
162 | codeVal = _codeVal;
163 | }
164 | return [...idxCode, ...codeVal, 0x3c, align, ...utils.varuint32(offset)];
165 | }
166 |
167 | i32_load8_s(idxCode, _offset, _align) {
168 | const offset = _offset || 0;
169 | const align = (_align === undefined) ? 0 : _align; // 32 bits alignment by default
170 | return [...idxCode, 0x2c, align, ...utils.varuint32(offset)];
171 | }
172 |
173 | i32_load8_u(idxCode, _offset, _align) {
174 | const offset = _offset || 0;
175 | const align = (_align === undefined) ? 0 : _align; // 32 bits alignment by default
176 | return [...idxCode, 0x2d, align, ...utils.varuint32(offset)];
177 | }
178 |
179 | i32_load16_s(idxCode, _offset, _align) {
180 | const offset = _offset || 0;
181 | const align = (_align === undefined) ? 1 : _align; // 32 bits alignment by default
182 | return [...idxCode, 0x2e, align, ...utils.varuint32(offset)];
183 | }
184 |
185 | i32_load16_u(idxCode, _offset, _align) {
186 | const offset = _offset || 0;
187 | const align = (_align === undefined) ? 1 : _align; // 32 bits alignment by default
188 | return [...idxCode, 0x2f, align, ...utils.varuint32(offset)];
189 | }
190 |
191 | i32_load(idxCode, _offset, _align) {
192 | const offset = _offset || 0;
193 | const align = (_align === undefined) ? 2 : _align; // 32 bits alignment by default
194 | return [...idxCode, 0x28, align, ...utils.varuint32(offset)];
195 | }
196 |
197 | i32_store(idxCode, _offset, _align, _codeVal) {
198 | let offset, align, codeVal;
199 | if (Array.isArray(_offset)) {
200 | offset = 0;
201 | align = 2;
202 | codeVal = _offset;
203 | } else if (Array.isArray(_align)) {
204 | offset = _offset;
205 | align = 2;
206 | codeVal = _align;
207 | } else if (Array.isArray(_codeVal)) {
208 | offset = _offset;
209 | align = _align;
210 | codeVal = _codeVal;
211 | }
212 | return [...idxCode, ...codeVal, 0x36, align, ...utils.varuint32(offset)];
213 | }
214 |
215 |
216 | i32_store16(idxCode, _offset, _align, _codeVal) {
217 | let offset, align, codeVal;
218 | if (Array.isArray(_offset)) {
219 | offset = 0;
220 | align = 1;
221 | codeVal = _offset;
222 | } else if (Array.isArray(_align)) {
223 | offset = _offset;
224 | align = 1;
225 | codeVal = _align;
226 | } else if (Array.isArray(_codeVal)) {
227 | offset = _offset;
228 | align = _align;
229 | codeVal = _codeVal;
230 | }
231 | return [...idxCode, ...codeVal, 0x3b, align, ...utils.varuint32(offset)];
232 | }
233 |
234 | i32_store8(idxCode, _offset, _align, _codeVal) {
235 | let offset, align, codeVal;
236 | if (Array.isArray(_offset)) {
237 | offset = 0;
238 | align = 0;
239 | codeVal = _offset;
240 | } else if (Array.isArray(_align)) {
241 | offset = _offset;
242 | align = 0;
243 | codeVal = _align;
244 | } else if (Array.isArray(_codeVal)) {
245 | offset = _offset;
246 | align = _align;
247 | codeVal = _codeVal;
248 | }
249 | return [...idxCode, ...codeVal, 0x3a, align, ...utils.varuint32(offset)];
250 | }
251 |
252 | call(fnName, ...args) {
253 | const idx = this.module.functionIdxByName[fnName];
254 | if (idx === undefined)
255 | throw new Error(`Function not defined: Function: ${fnName}`);
256 | return [...[].concat(...args), 0x10, ...utils.varuint32(idx)];
257 | }
258 |
259 | call_indirect(fnIdx, ...args) {
260 | return [...[].concat(...args), ...fnIdx, 0x11, 0, 0];
261 | }
262 |
263 | if(condCode, thenCode, elseCode) {
264 | if (elseCode) {
265 | return [...condCode, 0x04, 0x40, ...thenCode, 0x05, ...elseCode, 0x0b];
266 | } else {
267 | return [...condCode, 0x04, 0x40, ...thenCode, 0x0b];
268 | }
269 | }
270 |
271 | block(bCode) { return [0x02, 0x40, ...bCode, 0x0b]; }
272 | loop(...args) {
273 | return [0x03, 0x40, ...[].concat(...[...args]), 0x0b];
274 | }
275 | br_if(relPath, condCode) { return [...condCode, 0x0d, ...utils.varuint32(relPath)]; }
276 | br(relPath) { return [0x0c, ...utils.varuint32(relPath)]; }
277 | ret(rCode) { return [...rCode, 0x0f]; }
278 | drop(dCode) { return [...dCode, 0x1a]; }
279 |
280 | i64_const(num) { return [0x42, ...utils.varint64(num)]; }
281 | i32_const(num) { return [0x41, ...utils.varint32(num)]; }
282 |
283 |
284 | i64_eqz(opcode) { return [...opcode, 0x50]; }
285 | i64_eq(op1code, op2code) { return [...op1code, ...op2code, 0x51]; }
286 | i64_ne(op1code, op2code) { return [...op1code, ...op2code, 0x52]; }
287 | i64_lt_s(op1code, op2code) { return [...op1code, ...op2code, 0x53]; }
288 | i64_lt_u(op1code, op2code) { return [...op1code, ...op2code, 0x54]; }
289 | i64_gt_s(op1code, op2code) { return [...op1code, ...op2code, 0x55]; }
290 | i64_gt_u(op1code, op2code) { return [...op1code, ...op2code, 0x56]; }
291 | i64_le_s(op1code, op2code) { return [...op1code, ...op2code, 0x57]; }
292 | i64_le_u(op1code, op2code) { return [...op1code, ...op2code, 0x58]; }
293 | i64_ge_s(op1code, op2code) { return [...op1code, ...op2code, 0x59]; }
294 | i64_ge_u(op1code, op2code) { return [...op1code, ...op2code, 0x5a]; }
295 | i64_add(op1code, op2code) { return [...op1code, ...op2code, 0x7c]; }
296 | i64_sub(op1code, op2code) { return [...op1code, ...op2code, 0x7d]; }
297 | i64_mul(op1code, op2code) { return [...op1code, ...op2code, 0x7e]; }
298 | i64_div_s(op1code, op2code) { return [...op1code, ...op2code, 0x7f]; }
299 | i64_div_u(op1code, op2code) { return [...op1code, ...op2code, 0x80]; }
300 | i64_rem_s(op1code, op2code) { return [...op1code, ...op2code, 0x81]; }
301 | i64_rem_u(op1code, op2code) { return [...op1code, ...op2code, 0x82]; }
302 | i64_and(op1code, op2code) { return [...op1code, ...op2code, 0x83]; }
303 | i64_or(op1code, op2code) { return [...op1code, ...op2code, 0x84]; }
304 | i64_xor(op1code, op2code) { return [...op1code, ...op2code, 0x85]; }
305 | i64_shl(op1code, op2code) { return [...op1code, ...op2code, 0x86]; }
306 | i64_shr_s(op1code, op2code) { return [...op1code, ...op2code, 0x87]; }
307 | i64_shr_u(op1code, op2code) { return [...op1code, ...op2code, 0x88]; }
308 | i64_extend_i32_s(op1code) { return [...op1code, 0xac]; }
309 | i64_extend_i32_u(op1code) { return [...op1code, 0xad]; }
310 | i64_clz(op1code) { return [...op1code, 0x79]; }
311 | i64_ctz(op1code) { return [...op1code, 0x7a]; }
312 |
313 | i32_eqz(op1code) { return [...op1code, 0x45]; }
314 | i32_eq(op1code, op2code) { return [...op1code, ...op2code, 0x46]; }
315 | i32_ne(op1code, op2code) { return [...op1code, ...op2code, 0x47]; }
316 | i32_lt_s(op1code, op2code) { return [...op1code, ...op2code, 0x48]; }
317 | i32_lt_u(op1code, op2code) { return [...op1code, ...op2code, 0x49]; }
318 | i32_gt_s(op1code, op2code) { return [...op1code, ...op2code, 0x4a]; }
319 | i32_gt_u(op1code, op2code) { return [...op1code, ...op2code, 0x4b]; }
320 | i32_le_s(op1code, op2code) { return [...op1code, ...op2code, 0x4c]; }
321 | i32_le_u(op1code, op2code) { return [...op1code, ...op2code, 0x4d]; }
322 | i32_ge_s(op1code, op2code) { return [...op1code, ...op2code, 0x4e]; }
323 | i32_ge_u(op1code, op2code) { return [...op1code, ...op2code, 0x4f]; }
324 | i32_add(op1code, op2code) { return [...op1code, ...op2code, 0x6a]; }
325 | i32_sub(op1code, op2code) { return [...op1code, ...op2code, 0x6b]; }
326 | i32_mul(op1code, op2code) { return [...op1code, ...op2code, 0x6c]; }
327 | i32_div_s(op1code, op2code) { return [...op1code, ...op2code, 0x6d]; }
328 | i32_div_u(op1code, op2code) { return [...op1code, ...op2code, 0x6e]; }
329 | i32_rem_s(op1code, op2code) { return [...op1code, ...op2code, 0x6f]; }
330 | i32_rem_u(op1code, op2code) { return [...op1code, ...op2code, 0x70]; }
331 | i32_and(op1code, op2code) { return [...op1code, ...op2code, 0x71]; }
332 | i32_or(op1code, op2code) { return [...op1code, ...op2code, 0x72]; }
333 | i32_xor(op1code, op2code) { return [...op1code, ...op2code, 0x73]; }
334 | i32_shl(op1code, op2code) { return [...op1code, ...op2code, 0x74]; }
335 | i32_shr_s(op1code, op2code) { return [...op1code, ...op2code, 0x75]; }
336 | i32_shr_u(op1code, op2code) { return [...op1code, ...op2code, 0x76]; }
337 | i32_rotl(op1code, op2code) { return [...op1code, ...op2code, 0x77]; }
338 | i32_rotr(op1code, op2code) { return [...op1code, ...op2code, 0x78]; }
339 | i32_wrap_i64(op1code) { return [...op1code, 0xa7]; }
340 | i32_clz(op1code) { return [...op1code, 0x67]; }
341 | i32_ctz(op1code) { return [...op1code, 0x68]; }
342 |
343 | unreachable() { return [ 0x0 ]; }
344 |
345 | current_memory() { return [ 0x3f, 0]; }
346 |
347 | comment() { return []; }
348 | }
349 |
--------------------------------------------------------------------------------
/src/codebuilder_wat.js:
--------------------------------------------------------------------------------
1 | /*
2 | Copyright 2019 0KIMS association.
3 |
4 | This file is part of wasmbuilder
5 |
6 | wasmbuilder is a free software: you can redistribute it and/or modify it
7 | under the terms of the GNU General Public License as published by
8 | the Free Software Foundation, either version 3 of the License, or
9 | (at your option) any later version.
10 |
11 | wasmbuilder is distributed in the hope that it will be useful, but WITHOUT
12 | ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
13 | or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
14 | License for more details.
15 |
16 | You should have received a copy of the GNU General Public License
17 | along with wasmbuilder. If not, see .
18 | */
19 |
20 | import * as utils from "./utils.js";
21 |
22 | export class CodeBuilderWat {
23 | constructor(func) {
24 | this.func = func;
25 | this.functionName = func.functionName;
26 | this.module = func.module;
27 | }
28 |
29 | setLocal(localName, valCode) {
30 | const idx = this.func.localIdxByName[localName];
31 | if (idx === undefined)
32 | throw new Error(`Local Variable not defined: Function: ${this.functionName} local: ${localName} `);
33 | return [valCode, `set_local $${localName}`];
34 | }
35 |
36 | teeLocal(localName, valCode) {
37 | const idx = this.func.localIdxByName[localName];
38 | if (idx === undefined)
39 | throw new Error(`Local Variable not defined: Function: ${this.functionName} local: ${localName} `);
40 | return [valCode, `tee_local $${localName}`];
41 | }
42 |
43 | getLocal(localName) {
44 | const idx = this.func.localIdxByName[localName];
45 | if (idx === undefined)
46 | throw new Error(`Local Variable not defined: Function: ${this.functionName} local: ${localName} `);
47 | return `get_local $${localName}`;
48 | }
49 |
50 | genLoad(inst, def_align, idxCode, _offset, _align) {
51 | let S = inst;
52 | const offset = _offset || 0;
53 | if (offset>0) S += ` offset=${offset}`;
54 | const align = (_align === undefined) ? def_align : _align; // 8 bits alignment by default
55 | if (align!=def_align) S += ` align=${1 << align}`;
56 | return [idxCode, S];
57 | }
58 |
59 |
60 | genStore(inst, def_align, idxCode, _offset, _align, _codeVal) {
61 | let offset, align, codeVal;
62 | if (typeof _align === "undefined") {
63 | offset = 0;
64 | align = def_align;
65 | codeVal = _offset;
66 | } else if (typeof _codeVal === "undefined") {
67 | offset = _offset;
68 | align = def_align;
69 | codeVal = _align;
70 | } else {
71 | offset = _offset;
72 | align = _align;
73 | codeVal = _codeVal;
74 | }
75 | let S = inst;
76 | if (offset>0) S += ` offset=${offset}`;
77 | if (align!=def_align) S += ` align=${1 << align}`;
78 | return [idxCode, codeVal, S];
79 | }
80 |
81 | i64_load8_s(idxCode, _offset, _align) {
82 | return this.genLoad("i64.load8_s", 0, idxCode, _offset, _align);
83 | }
84 |
85 | i64_load8_u(idxCode, _offset, _align) {
86 | return this.genLoad("i64.load8_u", 0, idxCode, _offset, _align);
87 | }
88 |
89 | i64_load16_s(idxCode, _offset, _align) {
90 | return this.genLoad("i64.load16_s", 1,idxCode, _offset, _align);
91 | }
92 |
93 | i64_load16_u(idxCode, _offset, _align) {
94 | return this.genLoad("i64.load16_u", 1, idxCode, _offset, _align);
95 | }
96 |
97 | i64_load32_s(idxCode, _offset, _align) {
98 | return this.genLoad("i64.load32_s", 2, idxCode, _offset, _align);
99 | }
100 |
101 | i64_load32_u(idxCode, _offset, _align) {
102 | return this.genLoad("i64.load32_u", 2, idxCode, _offset, _align);
103 | }
104 |
105 | i64_load(idxCode, _offset, _align) {
106 | return this.genLoad("i64.load", 3, idxCode, _offset, _align);
107 | }
108 |
109 |
110 | i64_store(idxCode, _offset, _align, _codeVal) {
111 | return this.genStore("i64.store", 3, idxCode, _offset, _align, _codeVal);
112 | }
113 |
114 | i64_store32(idxCode, _offset, _align, _codeVal) {
115 | return this.genStore("i64.store32", 2, idxCode, _offset, _align, _codeVal);
116 | }
117 |
118 | i64_store16(idxCode, _offset, _align, _codeVal) {
119 | return this.genStore("i64.store16", 1, idxCode, _offset, _align, _codeVal);
120 | }
121 |
122 | i64_store8(idxCode, _offset, _align, _codeVal) {
123 | return this.genStore("i64.store8", 0, idxCode, _offset, _align, _codeVal);
124 | }
125 |
126 | i32_load8_s(idxCode, _offset, _align) {
127 | return this.genLoad("i32.load8_s", 0, idxCode, _offset, _align);
128 | }
129 |
130 | i32_load8_u(idxCode, _offset, _align) {
131 | return this.genLoad("i32.load8_u", 0, idxCode, _offset, _align);
132 | }
133 |
134 | i32_load16_s(idxCode, _offset, _align) {
135 | return this.genLoad("i32.load16_s", 1, idxCode, _offset, _align);
136 | }
137 |
138 | i32_load16_u(idxCode, _offset, _align) {
139 | return this.genLoad("i32.load16_u", 1, idxCode, _offset, _align);
140 | }
141 |
142 | i32_load(idxCode, _offset, _align) {
143 | return this.genLoad("i32.load", 2, idxCode, _offset, _align);
144 | }
145 |
146 | i32_store(idxCode, _offset, _align, _codeVal) {
147 | return this.genStore("i32.store", 2, idxCode, _offset, _align, _codeVal);
148 | }
149 |
150 | i32_store16(idxCode, _offset, _align, _codeVal) {
151 | return this.genStore("i32.store16", 1, idxCode, _offset, _align, _codeVal);
152 | }
153 |
154 | i32_store8(idxCode, _offset, _align, _codeVal) {
155 | return this.genStore("i32.store8", 0, idxCode, _offset, _align, _codeVal);
156 | }
157 |
158 | call(fnName, ...args) {
159 | const idx = this.module.functionIdxByName[fnName];
160 | if (idx === undefined)
161 | throw new Error(`Function not defined: Function: ${fnName}`);
162 | return [args, `call $${fnName}`];
163 | }
164 |
165 | call_indirect(fnIdx, ...args) {
166 | return [args, fnIdx, "call_indirect (type 0)"];
167 | }
168 |
169 | if(condCode, thenCode, elseCode) {
170 | if (elseCode) {
171 | return [condCode, "if", utils.ident(thenCode), "else", utils.ident(elseCode), "end"];
172 | } else {
173 | return [condCode, "if", utils.ident(thenCode), "end"];
174 | }
175 | }
176 |
177 | block(bCode) { return ["block", utils.ident(bCode), "end"]; }
178 | loop(...args) { return ["loop", utils.ident(args), "end"]; }
179 | br_if(relPath, condCode) { return [condCode, `br_if ${relPath}`]; }
180 | br(relPath) { return `br ${relPath}`; }
181 | ret(rCode) { return [rCode, "return"]; }
182 | drop(dCode) { return [dCode, "drop"]; }
183 |
184 | i64_const(num) { return `i64.const ${num}`; }
185 | i32_const(num) { return `i32.const ${num}`; }
186 |
187 | i64_eqz(opcode) { return [opcode, "i64.eqz"]; }
188 | i64_eq(op1code, op2code) { return [op1code, op2code, "i64.eq"]; }
189 | i64_ne(op1code, op2code) { return [op1code, op2code, "i64.ne"]; }
190 | i64_lt_s(op1code, op2code) { return [op1code, op2code, "i64.lt_s"]; }
191 | i64_lt_u(op1code, op2code) { return [op1code, op2code, "i64.lt_u"]; }
192 | i64_gt_s(op1code, op2code) { return [op1code, op2code, "i64.gt_s"]; }
193 | i64_gt_u(op1code, op2code) { return [op1code, op2code, "i64.gt_u"]; }
194 | i64_le_s(op1code, op2code) { return [op1code, op2code, "i64.le_s"]; }
195 | i64_le_u(op1code, op2code) { return [op1code, op2code, "i64.le_u"]; }
196 | i64_ge_s(op1code, op2code) { return [op1code, op2code, "i64.ge_s"]; }
197 | i64_ge_u(op1code, op2code) { return [op1code, op2code, "i64.ge_u"]; }
198 | i64_add(op1code, op2code) { return [op1code, op2code, "i64.add"]; }
199 | i64_sub(op1code, op2code) { return [op1code, op2code, "i64.sub"]; }
200 | i64_mul(op1code, op2code) { return [op1code, op2code, "i64.mul"]; }
201 | i64_div_s(op1code, op2code) { return [op1code, op2code, "i64.div_s"]; }
202 | i64_div_u(op1code, op2code) { return [op1code, op2code, "i64.div_u"]; }
203 | i64_rem_s(op1code, op2code) { return [op1code, op2code, "i64.rem_s"]; }
204 | i64_rem_u(op1code, op2code) { return [op1code, op2code, "i64.rem_u"]; }
205 | i64_and(op1code, op2code) { return [op1code, op2code, "i64.and"]; }
206 | i64_or(op1code, op2code) { return [op1code, op2code, "i64.or"]; }
207 | i64_xor(op1code, op2code) { return [op1code, op2code, "i64.xor"]; }
208 | i64_shl(op1code, op2code) { return [op1code, op2code, "i64.shl"]; }
209 | i64_shr_s(op1code, op2code) { return [op1code, op2code, "i64.shr_s"]; }
210 | i64_shr_u(op1code, op2code) { return [op1code, op2code, "i64.shr_u"]; }
211 | i64_extend_i32_s(op1code) { return [op1code, "i64.extend_s/i32"]; }
212 | i64_extend_i32_u(op1code) { return [op1code, "i64.extend_u/i32"]; }
213 |
214 |
215 | i32_eqz(op1code) { return [op1code, "i32.eqz"]; }
216 | i32_eq(op1code, op2code) { return [op1code, op2code, "i32.eq"]; }
217 | i32_ne(op1code, op2code) { return [op1code, op2code, "i32.ne"]; }
218 | i32_lt_s(op1code, op2code) { return [op1code, op2code, "i32.lt_s"]; }
219 | i32_lt_u(op1code, op2code) { return [op1code, op2code, "i32.lt_u"]; }
220 | i32_gt_s(op1code, op2code) { return [op1code, op2code, "i32.gt_s"]; }
221 | i32_gt_u(op1code, op2code) { return [op1code, op2code, "i32.gt_u"]; }
222 | i32_le_s(op1code, op2code) { return [op1code, op2code, "i32.le_s"]; }
223 | i32_le_u(op1code, op2code) { return [op1code, op2code, "i32.le_u"]; }
224 | i32_ge_s(op1code, op2code) { return [op1code, op2code, "i32.ge_s"]; }
225 | i32_ge_u(op1code, op2code) { return [op1code, op2code, "i32.ge_u"]; }
226 | i32_add(op1code, op2code) { return [op1code, op2code, "i32.add"]; }
227 | i32_sub(op1code, op2code) { return [op1code, op2code, "i32.sub"]; }
228 | i32_mul(op1code, op2code) { return [op1code, op2code, "i32.mul"]; }
229 | i32_div_s(op1code, op2code) { return [op1code, op2code, "i32.div_s"]; }
230 | i32_div_u(op1code, op2code) { return [op1code, op2code, "i32.div_u"]; }
231 | i32_rem_s(op1code, op2code) { return [op1code, op2code, "i32.rem_s"]; }
232 | i32_rem_u(op1code, op2code) { return [op1code, op2code, "i32.rem_u"]; }
233 | i32_and(op1code, op2code) { return [op1code, op2code, "i32.and"]; }
234 | i32_or(op1code, op2code) { return [op1code, op2code, "i32.or"]; }
235 | i32_xor(op1code, op2code) { return [op1code, op2code, "i32.xor"]; }
236 | i32_shl(op1code, op2code) { return [op1code, op2code, "i32.shl"]; }
237 | i32_shr_s(op1code, op2code) { return [op1code, op2code, "i32.shr_s"]; }
238 | i32_shr_u(op1code, op2code) { return [op1code, op2code, "i32.shr_u"]; }
239 | i32_rotl(op1code, op2code) { return [op1code, op2code, "i32.rotl"]; }
240 | i32_rotr(op1code, op2code) { return [op1code, op2code, "i32.rotr"]; }
241 | i32_wrap_i64(op1code) { return [op1code, "i32.wrap/i64"]; }
242 |
243 | ureachable() { return "unreachable"; }
244 |
245 | current_memory() { return "current_memory"; }
246 |
247 | comment(c) { return ";; " + c; }
248 |
249 | }
250 |
--------------------------------------------------------------------------------
/src/functionbuilder.js:
--------------------------------------------------------------------------------
1 | /*
2 | Copyright 2019 0KIMS association.
3 |
4 | This file is part of wasmbuilder
5 |
6 | wasmbuilder is a free software: you can redistribute it and/or modify it
7 | under the terms of the GNU General Public License as published by
8 | the Free Software Foundation, either version 3 of the License, or
9 | (at your option) any later version.
10 |
11 | wasmbuilder is distributed in the hope that it will be useful, but WITHOUT
12 | ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
13 | or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
14 | License for more details.
15 |
16 | You should have received a copy of the GNU General Public License
17 | along with wasmbuilder. If not, see .
18 | */
19 |
20 | import { CodeBuilder } from "./codebuilder.js";
21 | import * as utils from "./utils.js";
22 |
23 | const typeCodes = {
24 | "i32": 0x7f,
25 | "i64": 0x7e,
26 | "f32": 0x7d,
27 | "f64": 0x7c,
28 | "anyfunc": 0x70,
29 | "func": 0x60,
30 | "emptyblock": 0x40
31 | };
32 |
33 |
34 | export class FunctionBuilder {
35 |
36 | constructor (module, fnName, fnType, moduleName, fieldName) {
37 | if (fnType == "import") {
38 | this.fnType = "import";
39 | this.moduleName = moduleName;
40 | this.fieldName = fieldName;
41 | } else if (fnType == "internal") {
42 | this.fnType = "internal";
43 | } else {
44 | throw new Error("Invalid function fnType: " + fnType);
45 | }
46 | this.module = module;
47 | this.fnName = fnName;
48 | this.params = [];
49 | this.locals = [];
50 | this.localIdxByName = {};
51 | this.code = [];
52 | this.returnType = null;
53 | this.nextLocal =0;
54 | }
55 |
56 | addParam(paramName, paramType) {
57 | if (this.localIdxByName[paramName])
58 | throw new Error(`param already exists. Function: ${this.fnName}, Param: ${paramName} `);
59 | const idx = this.nextLocal++;
60 | this.localIdxByName[paramName] = idx;
61 | this.params.push({
62 | type: paramType
63 | });
64 | }
65 |
66 | addLocal(localName, localType, _length) {
67 | const length = _length || 1;
68 | if (this.localIdxByName[localName])
69 | throw new Error(`local already exists. Function: ${this.fnName}, Param: ${localName} `);
70 | const idx = this.nextLocal++;
71 | this.localIdxByName[localName] = idx;
72 | this.locals.push({
73 | type: localType,
74 | length: length
75 | });
76 | }
77 |
78 | setReturnType(returnType) {
79 | if (this.returnType)
80 | throw new Error(`returnType already defined. Function: ${this.fnName}`);
81 | this.returnType = returnType;
82 | }
83 |
84 | getSignature() {
85 | const params = [...utils.varuint32(this.params.length), ...this.params.map((p) => typeCodes[p.type])];
86 | const returns = this.returnType ? [0x01, typeCodes[this.returnType]] : [0];
87 | return [0x60, ...params, ...returns];
88 | }
89 |
90 | getBody() {
91 | const locals = this.locals.map((l) => [
92 | ...utils.varuint32(l.length),
93 | typeCodes[l.type]
94 | ]);
95 |
96 | const body = [
97 | ...utils.varuint32(this.locals.length),
98 | ...[].concat(...locals),
99 | ...this.code,
100 | 0x0b
101 | ];
102 | return [
103 | ...utils.varuint32(body.length),
104 | ...body
105 | ];
106 | }
107 |
108 | addCode(...code) {
109 | this.code.push(...[].concat(...[...code]));
110 | }
111 |
112 | getCodeBuilder() {
113 | return new CodeBuilder(this);
114 | }
115 | }
116 |
--------------------------------------------------------------------------------
/src/functionbuilder_wat.js:
--------------------------------------------------------------------------------
1 | /*
2 | Copyright 2019 0KIMS association.
3 |
4 | This file is part of wasmbuilder
5 |
6 | wasmbuilder is a free software: you can redistribute it and/or modify it
7 | under the terms of the GNU General Public License as published by
8 | the Free Software Foundation, either version 3 of the License, or
9 | (at your option) any later version.
10 |
11 | wasmbuilder is distributed in the hope that it will be useful, but WITHOUT
12 | ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
13 | or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
14 | License for more details.
15 |
16 | You should have received a copy of the GNU General Public License
17 | along with wasmbuilder. If not, see .
18 | */
19 |
20 | import { CodeBuilderWat } from "./codebuilder_wat.js";
21 | import * as utils from "./utils.js";
22 |
23 | export class FunctionBuilderWat {
24 |
25 | constructor (module, fnName, fnType, moduleName, fieldName) {
26 | if (fnType == "import") {
27 | this.fnType = "import";
28 | this.moduleName = moduleName;
29 | this.fieldName = fieldName;
30 | } else if (fnType == "internal") {
31 | this.fnType = "internal";
32 | this.comment = moduleName;
33 | } else {
34 | throw new Error("Invalid function fnType: " + fnType);
35 | }
36 | this.module = module;
37 | this.fnName = fnName;
38 | this.params = [];
39 | this.locals = [];
40 | this.localIdxByName = {};
41 | this.code = [];
42 | this.returnType = null;
43 | this.nextLocal =0;
44 | }
45 |
46 | addParam(paramName, paramType) {
47 | if (this.localIdxByName[paramName])
48 | throw new Error(`param already exists. Function: ${this.fnName}, Param: ${paramName} `);
49 | const idx = this.nextLocal++;
50 | this.localIdxByName[paramName] = idx;
51 | this.params.push({
52 | type: paramType,
53 | name: paramName
54 | });
55 | }
56 |
57 | addLocal(localName, localType, _length) {
58 | if ((typeof _length != "undefined") && (_length != 1)) {
59 | throw new Error("Locals greater than 1 not implemented");
60 | }
61 | if (this.localIdxByName[localName])
62 | throw new Error(`local already exists. Function: ${this.fnName}, Param: ${localName} `);
63 | const idx = this.nextLocal++;
64 | this.localIdxByName[localName] = idx;
65 | this.locals.push({
66 | type: localType,
67 | name: localName,
68 | });
69 | }
70 |
71 | setReturnType(returnType) {
72 | if (this.returnType)
73 | throw new Error(`returnType already defined. Function: ${this.fnName}`);
74 | this.returnType = returnType;
75 | }
76 |
77 | getSignature() {
78 | let p = "";
79 | for (let i=0; i.
18 | */
19 |
20 |
21 | import { FunctionBuilder } from "./functionbuilder.js";
22 | import * as utils from "./utils.js";
23 |
24 | export class ModuleBuilder {
25 |
26 | constructor() {
27 | this.functions = [];
28 | this.functionIdxByName = {};
29 | this.nImportFunctions = 0;
30 | this.nInternalFunctions =0;
31 | this.memory = {
32 | pagesSize: 1,
33 | moduleName: "env",
34 | fieldName: "memory"
35 | };
36 | this.free = 8;
37 | this.datas = [];
38 | this.modules = {};
39 | this.exports = [];
40 | this.functionsTable = [];
41 | }
42 |
43 | build() {
44 | this._setSignatures();
45 | return new Uint8Array([
46 | ...utils.u32(0x6d736100),
47 | ...utils.u32(1),
48 | ...this._buildType(),
49 | ...this._buildImport(),
50 | ...this._buildFunctionDeclarations(),
51 | ...this._buildFunctionsTable(),
52 | ...this._buildExports(),
53 | ...this._buildElements(),
54 | ...this._buildCode(),
55 | ...this._buildData()
56 | ]);
57 | }
58 |
59 | addFunction(fnName) {
60 | if (typeof(this.functionIdxByName[fnName]) !== "undefined")
61 | throw new Error(`Function already defined: ${fnName}`);
62 |
63 | const idx = this.functions.length;
64 | this.functionIdxByName[fnName] = idx;
65 |
66 | this.functions.push(new FunctionBuilder(this, fnName, "internal"));
67 |
68 | this.nInternalFunctions++;
69 | return this.functions[idx];
70 | }
71 |
72 | addIimportFunction(fnName, moduleName, _fieldName) {
73 | if (typeof(this.functionIdxByName[fnName]) !== "undefined")
74 | throw new Error(`Function already defined: ${fnName}`);
75 |
76 | if ( (this.functions.length>0)
77 | &&(this.functions[this.functions.length-1].type == "internal"))
78 | throw new Error(`Import functions must be declared before internal: ${fnName}`);
79 |
80 | let fieldName = _fieldName || fnName;
81 |
82 | const idx = this.functions.length;
83 | this.functionIdxByName[fnName] = idx;
84 |
85 | this.functions.push(new FunctionBuilder(this, fnName, "import", moduleName, fieldName));
86 |
87 | this.nImportFunctions ++;
88 | return this.functions[idx];
89 | }
90 |
91 | setMemory(pagesSize, moduleName, fieldName) {
92 | this.memory = {
93 | pagesSize: pagesSize,
94 | moduleName: moduleName || "env",
95 | fieldName: fieldName || "memory"
96 | };
97 | }
98 |
99 | exportFunction(fnName, _exportName) {
100 | const exportName = _exportName || fnName;
101 | if (typeof(this.functionIdxByName[fnName]) === "undefined")
102 | throw new Error(`Function not defined: ${fnName}`);
103 | const idx = this.functionIdxByName[fnName];
104 | if (exportName != fnName) {
105 | this.functionIdxByName[exportName] = idx;
106 | }
107 | this.exports.push({
108 | exportName: exportName,
109 | idx: idx
110 | });
111 | }
112 |
113 | addFunctionToTable(fnName) {
114 | const idx = this.functionIdxByName[fnName];
115 | this.functionsTable.push(idx);
116 | }
117 |
118 | addData(offset, bytes) {
119 | this.datas.push({
120 | offset: offset,
121 | bytes: bytes
122 | });
123 | }
124 |
125 | alloc(a, b) {
126 | let size;
127 | let bytes;
128 | if ((Array.isArray(a) || ArrayBuffer.isView(a)) && (typeof(b) === "undefined")) {
129 | size = a.length;
130 | bytes = a;
131 | } else {
132 | size = a;
133 | bytes = b;
134 | }
135 | size = (((size-1)>>3) +1)<<3; // Align to 64 bits.
136 | const p = this.free;
137 | this.free += size;
138 | if (bytes) {
139 | this.addData(p, bytes);
140 | }
141 | return p;
142 | }
143 |
144 | allocString(s) {
145 | const encoder = new globalThis.TextEncoder();
146 | const uint8array = encoder.encode(s);
147 | return this.alloc([...uint8array, 0]);
148 | }
149 |
150 | _setSignatures() {
151 | this.signatures = [];
152 | const signatureIdxByName = {};
153 | if (this.functionsTable.length>0) {
154 | const signature = this.functions[this.functionsTable[0]].getSignature();
155 | const signatureName = "s_"+utils.toHexString(signature);
156 | signatureIdxByName[signatureName] = 0;
157 | this.signatures.push(signature);
158 | }
159 | for (let i=0; i.
18 | */
19 |
20 |
21 | import { FunctionBuilderWat } from "./functionbuilder_wat.js";
22 | import * as utils from "./utils.js";
23 |
24 | export class ModuleBuilderWat {
25 |
26 | constructor() {
27 | this.functions = [];
28 | this.functionIdxByName = {};
29 | this.nImportFunctions = 0;
30 | this.nInternalFunctions =0;
31 | this.memory = {
32 | pagesSize: 1,
33 | moduleName: "env",
34 | fieldName: "memory"
35 | };
36 | this.free = 8;
37 | this.datas = [];
38 | this.modules = {};
39 | this.exports = [];
40 | this.functionsTable = [];
41 | }
42 |
43 | build() {
44 | const src = [];
45 | this._setSignatures();
46 | src.push(this._buildType());
47 | src.push(this._buildImport());
48 | if (this.functionsTable.length>0) {
49 | src.push(this._buildFunctionsTable());
50 | }
51 | if (this.exports.length > 0) {
52 | src.push(this._buildExports());
53 | }
54 | if (this.functionsTable.length>0) {
55 | src.push(this._buildElements());
56 | }
57 | if (this.nInternalFunctions>0) {
58 | src.push(this._buildFunctions());
59 | }
60 | src.push(this._buildData());
61 | return [
62 | "(module",
63 | utils.ident(src),
64 | ")"
65 | ];
66 | }
67 |
68 | addFunction(fnName, comment) {
69 | if (typeof(this.functionIdxByName[fnName]) !== "undefined")
70 | throw new Error(`Function already defined: ${fnName}`);
71 |
72 | const idx = this.functions.length;
73 | this.functionIdxByName[fnName] = idx;
74 |
75 | this.functions.push(new FunctionBuilderWat(this, fnName, "internal", comment));
76 |
77 | this.nInternalFunctions++;
78 | return this.functions[idx];
79 | }
80 |
81 | addIimportFunction(fnName, moduleName, _fieldName) {
82 | if (typeof(this.functionIdxByName[fnName]) !== "undefined")
83 | throw new Error(`Function already defined: ${fnName}`);
84 |
85 | if ( (this.functions.length>0)
86 | &&(this.functions[this.functions.length-1].type == "internal"))
87 | throw new Error(`Import functions must be declared before internal: ${fnName}`);
88 |
89 | let fieldName = _fieldName || fnName;
90 |
91 | const idx = this.functions.length;
92 | this.functionIdxByName[fnName] = idx;
93 |
94 | this.functions.push(new FunctionBuilderWat(this, fnName, "import", moduleName, fieldName));
95 |
96 | this.nImportFunctions ++;
97 | return this.functions[idx];
98 | }
99 |
100 | setMemory(pagesSize, moduleName, fieldName) {
101 | this.memory = {
102 | pagesSize: pagesSize,
103 | moduleName: moduleName || "env",
104 | fieldName: fieldName || "memory"
105 | };
106 | }
107 |
108 | exportFunction(fnName, _exportName) {
109 | const exportName = _exportName || fnName;
110 | if (typeof(this.functionIdxByName[fnName]) === "undefined")
111 | throw new Error(`Function not defined: ${fnName}`);
112 | const idx = this.functionIdxByName[fnName];
113 | if (exportName != fnName) {
114 | this.functionIdxByName[exportName] = idx;
115 | }
116 | this.exports.push({
117 | exportName: exportName,
118 | idx: idx
119 | });
120 | }
121 |
122 | addFunctionToTable(fnName) {
123 | const idx = this.functionIdxByName[fnName];
124 | this.functionsTable.push(idx);
125 | }
126 |
127 | addData(offset, bytes) {
128 | this.datas.push({
129 | offset: offset,
130 | bytes: bytes
131 | });
132 | }
133 |
134 | alloc(a, b) {
135 | let size;
136 | let bytes;
137 | if ((Array.isArray(a) || ArrayBuffer.isView(a)) && (typeof(b) === "undefined")) {
138 | size = a.length;
139 | bytes = a;
140 | } else {
141 | size = a;
142 | bytes = b;
143 | }
144 | size = (((size-1)>>3) +1)<<3; // Align to 64 bits.
145 | const p = this.free;
146 | this.free += size;
147 | if (bytes) {
148 | this.addData(p, bytes);
149 | }
150 | return p;
151 | }
152 |
153 | allocString(s) {
154 | const encoder = new TextEncoder();
155 | const uint8array = encoder.encode(s);
156 | return this.alloc([...uint8array, 0]);
157 | }
158 |
159 | _setSignatures() {
160 | this.signatures = [];
161 | const signatureIdxByName = {};
162 | if (this.functionsTable.length>0) {
163 | const signature = this.functions[this.functionsTable[0]].getSignature();
164 | const signatureName = this.functions[this.functionsTable[0]].getSignatureName();
165 | signatureIdxByName[signatureName] = 0;
166 | this.signatures.push(signature);
167 | }
168 | for (let i=0; i126 || b[i] == 34 || b[i]==92) {
237 | let h=b[i].toString(16);
238 | while (h.length<2) h = "0"+h;
239 | S += "\\" + h;
240 | } else {
241 | S += String.fromCharCode(b[i]);
242 | }
243 | }
244 | S += "\"";
245 | return S;
246 | }
247 | }
248 |
249 | }
250 |
--------------------------------------------------------------------------------
/src/protoboard.js:
--------------------------------------------------------------------------------
1 | /*
2 | Copyright 2019 0KIMS association.
3 |
4 | This file is part of websnark (Web Assembly zkSnark Prover).
5 |
6 | websnark is a free software: you can redistribute it and/or modify it
7 | under the terms of the GNU General Public License as published by
8 | the Free Software Foundation, either version 3 of the License, or
9 | (at your option) any later version.
10 |
11 | websnark is distributed in the hope that it will be useful, but WITHOUT
12 | ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
13 | or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
14 | License for more details.
15 |
16 | You should have received a copy of the GNU General Public License
17 | along with websnark. If not, see .
18 | */
19 |
20 | import { ModuleBuilder } from "./modulebuilder.js";
21 |
22 | export async function buildProtoboard(builder, defBytes, bitsPerBytes) {
23 | const protoboard = new Protoboard();
24 |
25 | protoboard.defBytes = defBytes;
26 | protoboard.bitsPerBytes = bitsPerBytes || 32;
27 |
28 | protoboard.memory = new WebAssembly.Memory({initial:20000});
29 | protoboard.i32 = new Uint32Array(protoboard.memory.buffer);
30 | protoboard.i8 = new Uint8Array(protoboard.memory.buffer);
31 |
32 | const moduleBuilder = new ModuleBuilder();
33 |
34 | const fLog32 = moduleBuilder.addIimportFunction("debug_log32", "debug", "log32");
35 | fLog32.addParam("x", "i32");
36 | const fLog64 = moduleBuilder.addIimportFunction("debug_log64", "debug", "log64");
37 | fLog64.addParam("x", "i32");
38 | fLog64.addParam("y", "i32");
39 |
40 | buildLog32(moduleBuilder);
41 | buildLog64(moduleBuilder);
42 |
43 | builder(moduleBuilder, protoboard);
44 |
45 |
46 | const code = moduleBuilder.build();
47 |
48 | const wasmModule = await WebAssembly.compile(code);
49 |
50 | protoboard.log = console.log;
51 |
52 | protoboard.instance = await WebAssembly.instantiate(wasmModule, {
53 | env: {
54 | "memory": protoboard.memory
55 | },
56 | debug: {
57 | log32: function (c1) {
58 | if (c1<0) c1 = 0x100000000+c1;
59 | let s=c1.toString(16);
60 | while (s.length<8) s = "0"+s;
61 | protoboard.log(s + ": " + c1.toString());
62 | },
63 | log64: function (c1, c2) {
64 | if (c1<0) c1 = 0x100000000+c1;
65 | if (c2<0) c2 = 0x100000000+c2;
66 | const n = BigInt(c1) + (BigInt(c2) << 32n);
67 | let s=n.toString(16);
68 | while (s.length<16) s = "0"+s;
69 | protoboard.log(s + ": " + n.toString());
70 | }
71 | }
72 | });
73 |
74 | Object.assign(protoboard, protoboard.instance.exports);
75 | Object.assign(protoboard, moduleBuilder.modules);
76 |
77 | return protoboard;
78 |
79 | function buildLog32(module) {
80 |
81 | const f = module.addFunction("log32");
82 | f.addParam("x", "i32");
83 |
84 | const c = f.getCodeBuilder();
85 | f.addCode(c.call("debug_log32", c.getLocal("x")));
86 | }
87 |
88 | function buildLog64(module) {
89 |
90 | const f = module.addFunction("log64");
91 | f.addParam("x", "i64");
92 |
93 | const c = f.getCodeBuilder();
94 | f.addCode(c.call(
95 | "debug_log64",
96 | c.i32_wrap_i64(c.getLocal("x")),
97 | c.i32_wrap_i64(
98 | c.i64_shr_u(
99 | c.getLocal("x"),
100 | c.i64_const(32)
101 | )
102 | )
103 | ));
104 | }
105 |
106 | }
107 |
108 | class Protoboard {
109 |
110 | constructor() {
111 |
112 | }
113 |
114 | alloc(length) {
115 | if (typeof length === "undefined") {
116 | length = this.defBytes;
117 | }
118 | length = (((length-1)>>3) +1)<<3; // Align to 64 bits.
119 |
120 | const res = this.i32[0];
121 | this.i32[0] += length;
122 | return res;
123 | }
124 |
125 | set(pos, nums, nBytes) {
126 | if (!Array.isArray(nums)) {
127 | nums = [nums];
128 | }
129 | if (typeof nBytes === "undefined") {
130 | nBytes = this.defBytes;
131 | }
132 |
133 | const words = Math.floor((nBytes -1)/4)+1;
134 | let p = pos;
135 |
136 | const CHUNK = 1n << BigInt(this.bitsPerBytes);
137 |
138 | for (let i=0; i>2] = Number(remainder);
144 | v = quotient;
145 | p += 4;
146 | }
147 | if (v !== 0n) {
148 | throw new Error("Expected v to be 0");
149 | }
150 | }
151 |
152 | return pos;
153 | }
154 |
155 | get(pos, nElements, nBytes) {
156 | if (typeof nBytes == "undefined") {
157 | if (typeof nElements == "undefined") {
158 | nElements = 1;
159 | nBytes = this.defBytes;
160 | } else {
161 | nElements = nBytes;
162 | nBytes = this.defBytes;
163 | }
164 | }
165 |
166 | const words = Math.floor((nBytes -1)/4)+1;
167 |
168 | const CHUNK = 1n << BigInt(this.bitsPerBytes);
169 |
170 |
171 | const nums = [];
172 | for (let i=0; i=0; j--) {
175 | acc = acc * CHUNK;
176 | let v = this.i32[(pos>>2)+j];
177 | if (this.bitsPerBytes <32) {
178 | if (v&0x80000000) v = v-0x100000000;
179 | }
180 | acc = acc + BigInt(v);
181 | }
182 | nums.push(acc);
183 | pos += words*4;
184 | }
185 |
186 | if (nums.length == 1) return nums[0];
187 | return nums;
188 | }
189 | }
190 |
--------------------------------------------------------------------------------
/src/utils.js:
--------------------------------------------------------------------------------
1 | /*
2 | Copyright 2019 0KIMS association.
3 |
4 | This file is part of wasmbuilder
5 |
6 | wasmbuilder is a free software: you can redistribute it and/or modify it
7 | under the terms of the GNU General Public License as published by
8 | the Free Software Foundation, either version 3 of the License, or
9 | (at your option) any later version.
10 |
11 | wasmbuilder is distributed in the hope that it will be useful, but WITHOUT
12 | ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
13 | or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
14 | License for more details.
15 |
16 | You should have received a copy of the GNU General Public License
17 | along with wasmbuilder. If not, see .
18 | */
19 |
20 | export function toNumber(n) {
21 | return BigInt(n);
22 | }
23 |
24 | export function isNegative(n) {
25 | return n < 0n;
26 | }
27 |
28 | export function isZero(n) {
29 | return n === 0n;
30 | }
31 |
32 | export function bitLength(n) {
33 | if (isNegative(n)) {
34 | return n.toString(2).length - 1; // discard the - sign
35 | } else {
36 | return n.toString(2).length;
37 | }
38 | }
39 |
40 | export function u32(n) {
41 | const b = [];
42 | const v = toNumber(n);
43 | b.push(Number(v & 0xFFn));
44 | b.push(Number(v >> 8n & 0xFFn));
45 | b.push(Number(v >> 16n & 0xFFn));
46 | b.push(Number(v >> 24n & 0xFFn));
47 | return b;
48 | }
49 |
50 | export function u64(n) {
51 | const b = [];
52 | const v = toNumber(n);
53 | b.push(Number(v & 0xFFn));
54 | b.push(Number(v >> 8n & 0xFFn));
55 | b.push(Number(v >> 16n & 0xFFn));
56 | b.push(Number(v >> 24n & 0xFFn));
57 | b.push(Number(v >> 32n & 0xFFn));
58 | b.push(Number(v >> 40n & 0xFFn));
59 | b.push(Number(v >> 48n & 0xFFn));
60 | b.push(Number(v >> 56n & 0xFFn));
61 | return b;
62 | }
63 |
64 | export function toUTF8Array(str) {
65 | var utf8 = [];
66 | for (var i=0; i < str.length; i++) {
67 | var charcode = str.charCodeAt(i);
68 | if (charcode < 0x80) utf8.push(charcode);
69 | else if (charcode < 0x800) {
70 | utf8.push(0xc0 | (charcode >> 6),
71 | 0x80 | (charcode & 0x3f));
72 | }
73 | else if (charcode < 0xd800 || charcode >= 0xe000) {
74 | utf8.push(0xe0 | (charcode >> 12),
75 | 0x80 | ((charcode>>6) & 0x3f),
76 | 0x80 | (charcode & 0x3f));
77 | }
78 | // surrogate pair
79 | else {
80 | i++;
81 | // UTF-16 encodes 0x10000-0x10FFFF by
82 | // subtracting 0x10000 and splitting the
83 | // 20 bits of 0x0-0xFFFFF into two halves
84 | charcode = 0x10000 + (((charcode & 0x3ff)<<10)
85 | | (str.charCodeAt(i) & 0x3ff));
86 | utf8.push(0xf0 | (charcode >>18),
87 | 0x80 | ((charcode>>12) & 0x3f),
88 | 0x80 | ((charcode>>6) & 0x3f),
89 | 0x80 | (charcode & 0x3f));
90 | }
91 | }
92 | return utf8;
93 | }
94 |
95 | export function string(str) {
96 | const bytes = toUTF8Array(str);
97 | return [ ...varuint32(bytes.length), ...bytes ];
98 | }
99 |
100 | export function varuint(n) {
101 | const code = [];
102 | let v = toNumber(n);
103 | if (isNegative(v)) throw new Error("Number cannot be negative");
104 | while (!isZero(v)) {
105 | code.push(Number(v & 0x7Fn));
106 | v = v >> 7n;
107 | }
108 | if (code.length==0) code.push(0);
109 | for (let i=0; i 0xFFFFFFFFn) throw new Error("Number too big");
142 | if (v > 0x7FFFFFFFn) v = v - 0x100000000n;
143 | // bigInt("-80000000", 16) as base10
144 | if (v < -2147483648n) throw new Error("Number too small");
145 | return varint(v);
146 | }
147 |
148 | export function varint64(n) {
149 | let v = toNumber(n);
150 | if (v > 0xFFFFFFFFFFFFFFFFn) throw new Error("Number too big");
151 | if (v > 0x7FFFFFFFFFFFFFFFn) v = v - 0x10000000000000000n;
152 | // bigInt("-8000000000000000", 16) as base10
153 | if (v < -9223372036854775808n) throw new Error("Number too small");
154 | return varint(v);
155 | }
156 |
157 | export function varuint32(n) {
158 | let v = toNumber(n);
159 | if (v > 0xFFFFFFFFn) throw new Error("Number too big");
160 | return varuint(v);
161 | }
162 |
163 | export function varuint64(n) {
164 | let v = toNumber(n);
165 | if (v > 0xFFFFFFFFFFFFFFFFn) throw new Error("Number too big");
166 | return varuint(v);
167 | }
168 |
169 | export function toHexString(byteArray) {
170 | return Array.from(byteArray, function(byte) {
171 | return ("0" + (byte & 0xFF).toString(16)).slice(-2);
172 | }).join("");
173 | }
174 |
175 | export function ident(text) {
176 | if (typeof text === "string") {
177 | let lines = text.split("\n");
178 | for (let i=0; i ("00" + x.toString(16)).slice(-2)).join("");
7 | }
8 |
9 | describe("Basic tests for WasmGenerator", () => {
10 | it("Should generate a basic module", () => {
11 | const module = new ModuleBuilder();
12 |
13 | const bytes = module.build();
14 |
15 | assert.equal("0061736d01000000010100020f0103656e76066d656d6f72790200010301000701000a01000b0a010041000b0408000000",buf2hex(bytes) );
16 | });
17 | });
18 |
--------------------------------------------------------------------------------
/test/protoboard.js:
--------------------------------------------------------------------------------
1 | import assert from "assert";
2 |
3 | import { buildProtoboard } from "../main.js";
4 |
5 | describe("Basic protoboard test", () => {
6 | it("Should generate a basic protoboard", async () => {
7 | const pb = await buildProtoboard(function(module) {
8 |
9 | buildTest1();
10 | buildTest2();
11 | buildTest3();
12 |
13 | function buildTest1() {
14 | const f = module.addFunction("test1");
15 |
16 | const c = f.getCodeBuilder();
17 | f.addCode(c.call("log32", c.i32_const(44)));
18 |
19 |
20 | module.exportFunction("test1");
21 |
22 | }
23 |
24 | function buildTest2() {
25 | const f = module.addFunction("test2");
26 |
27 | const c = f.getCodeBuilder();
28 | f.addCode(c.call("log64", c.i64_const(66)));
29 |
30 |
31 | module.exportFunction("test2");
32 |
33 | }
34 |
35 | // Regression test for PR#20
36 | function buildTest3() {
37 | const f = module.addFunction("test3");
38 |
39 | const c = f.getCodeBuilder();
40 | f.addCode(c.call("log32", c.i32_const(-66)));
41 |
42 | module.exportFunction("test3");
43 | }
44 | });
45 |
46 | const logs = [];
47 | pb.log = function(S) {
48 | logs.push(S);
49 | };
50 |
51 | pb.test1();
52 | pb.test2();
53 | pb.test3();
54 |
55 | assert.equal(logs[0], "0000002c: 44");
56 | assert.equal(logs[1], "0000000000000042: 66");
57 | // Regression test for PR#20
58 | assert.equal(logs[2], "ffffffbe: 4294967230");
59 | });
60 |
61 | it("Can `alloc`, `set`, and `get` data", async() => {
62 | const n8q=48;
63 |
64 | const pb = await buildProtoboard(function() {}, n8q);
65 |
66 | const e1 = pb.alloc(n8q*2);
67 | const pos = pb.set(e1, 1n);
68 |
69 | assert.equal(pb.get(pos), 1n);
70 | });
71 | });
72 |
--------------------------------------------------------------------------------