├── .github └── workflows │ ├── node.js.yml │ └── npm-publish.yml ├── .gitignore ├── .npmignore ├── LICENSE ├── README.md ├── browser ├── index.html ├── index.js ├── lib │ └── styled-elements │ │ ├── index.js │ │ └── lib │ │ └── hash.js └── yulp.png ├── browser_config └── now.json ├── examples ├── ERC20.yulp ├── EmptyContract.yulp ├── SignatureGeneration.yulp ├── SimpleStore.yulp ├── another.yulp ├── cool.yulp └── example.js ├── package-lock.json ├── package.json └── src ├── index.js ├── index.test.js ├── resolve.ne ├── yul.ne └── yulplus.ne /.github/workflows/node.js.yml: -------------------------------------------------------------------------------- 1 | # This workflow will do a clean install of node dependencies, build the source code and run tests across different versions of node 2 | # For more information see: https://help.github.com/actions/language-and-framework-guides/using-nodejs-with-github-actions 3 | 4 | name: Node.js CI 5 | 6 | on: push 7 | 8 | jobs: 9 | build: 10 | 11 | runs-on: ubuntu-latest 12 | 13 | strategy: 14 | matrix: 15 | node-version: [10.x, 12.x, 14.x] 16 | 17 | steps: 18 | - uses: actions/checkout@v2 19 | - name: Use Node.js ${{ matrix.node-version }} 20 | uses: actions/setup-node@v1 21 | with: 22 | node-version: ${{ matrix.node-version }} 23 | - run: npm ci 24 | - run: npm run build --if-present 25 | - run: npm test 26 | -------------------------------------------------------------------------------- /.github/workflows/npm-publish.yml: -------------------------------------------------------------------------------- 1 | # This workflow will run tests using node and then publish a package to GitHub Packages when a release is created 2 | # For more information see: https://help.github.com/actions/language-and-framework-guides/publishing-nodejs-packages 3 | 4 | name: Node.js Package 5 | 6 | on: 7 | release: 8 | types: [created] 9 | 10 | jobs: 11 | build: 12 | runs-on: ubuntu-latest 13 | steps: 14 | - uses: actions/checkout@v2 15 | - uses: actions/setup-node@v1 16 | with: 17 | node-version: 12 18 | - run: npm ci 19 | - run: npm test 20 | 21 | publish-npm: 22 | needs: build 23 | runs-on: ubuntu-latest 24 | steps: 25 | - uses: actions/checkout@v2 26 | - uses: actions/setup-node@v1 27 | with: 28 | node-version: 12 29 | registry-url: https://registry.npmjs.org/ 30 | - run: npm ci 31 | - run: npm publish 32 | env: 33 | NODE_AUTH_TOKEN: ${{secrets.NPM_TOKEN}} 34 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | dist/ 3 | .cache/ 4 | src/gen 5 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | dist/ 3 | .cache/ 4 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2020 Fuel Labs 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Yul+ 2 | 3 | ![Node.js CI](https://github.com/FuelLabs/yulp/workflows/Node.js%20CI/badge.svg) 4 | [![npm version](https://badge.fury.io/js/yulp.svg)](https://badge.fury.io/js/yulp) 5 | 6 | A low-level, highly efficient extension to Yul, an intermediate smart-contract language for the Ethereum Virtual Machine. 7 | 8 | [Try it Now!](https://yulp.fuel.sh) 9 | 10 | ## Features 11 | - All existing Yul features 12 | - Memory structures (`mstruct`) 13 | - Enums (`enum`) 14 | - Constants (`const`) 15 | - Ethereum standard ABI signature/topic generation (`sig"function ..."`, `topic"event ...`) 16 | - Booleans (`true`, `false`) 17 | - Safe math (over/under flow protection for addition, subtraction, multiplication) 18 | - Injected methods (`mslice` and `require`) 19 | 20 | ## Coming Soon 21 | - Static typing 22 | - CLI support 23 | 24 | ## Installing 25 | 26 | ```sh 27 | npm install yulp 28 | ``` 29 | 30 | ## Building From Source 31 | 32 | ```sh 33 | npm install 34 | npm run build 35 | npm test 36 | ``` 37 | 38 | ## Library Usage 39 | 40 | ### Code Example 41 | 42 | ```js 43 | const yulp = require('../index'); 44 | const source = yulp.compile(` 45 | 46 | object "SimpleStore" { 47 | code { 48 | datacopy(0, dataoffset("Runtime"), datasize("Runtime")) 49 | return(0, datasize("Runtime")) 50 | } 51 | object "Runtime" { 52 | code { 53 | calldatacopy(0, 0, 36) // write calldata to memory 54 | 55 | mstruct StoreCalldata( // Custom addressable calldata structure 56 | sig: 4, 57 | val: 32 58 | ) 59 | 60 | switch StoreCalldata.sig(0) // select signature from memory (at position 0) 61 | 62 | case sig"function store(uint256 val)" { // new signature method 63 | sstore(0, StoreCalldata.val(0)) // sstore calldata value 64 | log2(0, 0, topic"event Store(uint256 value)", StoreCalldata.val(0)) 65 | } 66 | 67 | case sig"function get() returns (uint256)" { 68 | mstore(100, sload(0)) 69 | return (100, 32) 70 | } 71 | } 72 | } 73 | } 74 | 75 | `); 76 | 77 | console.log(yulp.print(source.results)); 78 | ``` 79 | 80 | ### Enums 81 | 82 | Here we have a fully featured `enum` identifier which acts as a constant. 83 | 84 | ```js 85 | object "contract" { 86 | code { 87 | enum Colors ( 88 | Red, 89 | Blue, 90 | Green 91 | ) 92 | 93 | log1(0, 0, Colors.Green) // logs 2 as a topic 94 | } 95 | } 96 | ``` 97 | 98 | ### Constants 99 | 100 | `const` will define a `let` variable value that cannot be re-assigned. 101 | 102 | ```js 103 | object "contract" { 104 | code { 105 | const firstVar := 0xaa 106 | const someOther := 1 107 | } 108 | } 109 | ``` 110 | 111 | ### Memory Slice 112 | 113 | `mslice(position, length)` will return a 1-32 byte value from memory. 114 | 115 | ```js 116 | object "contract" { 117 | code { 118 | mstore(30, 0xaaaa) 119 | 120 | log1(0, 0, mslice(30, 2)) // will log 0xaaaa 121 | } 122 | } 123 | ``` 124 | 125 | ### Booleans 126 | 127 | `true` and `false` are added and equate to values `0x01` and `0x00`. 128 | 129 | ```js 130 | object "contract" { 131 | code { 132 | mstore(30, true) 133 | 134 | log1(0, 0, mload(30)) // will log 0x01 135 | } 136 | } 137 | ``` 138 | 139 | ### Multi mstore sugar 140 | 141 | `mstore` can now be used as a proxy method 142 | 143 | ```js 144 | object "contract" { 145 | code { 146 | mstore(30, 1, 2, 3, 4) 147 | 148 | /* 149 | mstore(30, 1) 150 | mstore(add(30, 32), 2) 151 | mstore(add(30, 64), 3) 152 | mstore(add(30, 96), 4) 153 | */ 154 | } 155 | } 156 | ``` 157 | 158 | ### Comparison Methods 159 | 160 | `lte`, `gte`, `neq` can now be used. 161 | 162 | ``` 163 | if and(lte(1, 10), gte(5, 2)) { 164 | let k := neq(0, 1) 165 | } 166 | ``` 167 | 168 | ### MAX_UINT 169 | 170 | `MAX_UINT` literal is now available (i.e. `uint(-1)`) 171 | 172 | ``` 173 | if lt(v, MAX_UINT) { 174 | let k := 1 175 | } 176 | ``` 177 | 178 | ### Ethereum Standard ABI Signature and Topic Generation 179 | 180 | `sig" [ method abi ] "` will equate to a 4 byte method signature hex value 181 | 182 | `topic" [ event abi definition ] "` will equate to the 32 byte topic hash 183 | 184 | ```js 185 | object "contract" { 186 | code { 187 | const storeSig := sig"function store(uint256 val)" 188 | const eventSig := topic"event Store (uint256 indexed val)" 189 | 190 | log1(0, 0, storeSig) // will log 0x6057361d 191 | 192 | log1(0, 0, eventSig) // will log 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef 193 | } 194 | } 195 | ``` 196 | 197 | ### Memory Structures 198 | 199 | Memory structures enable better handling of pre-existing in-memory structures. 200 | 201 | `mstruct Identifier ( [ property, ... ] )` 202 | 203 | A structure property is defined by an identifier and length specifier (i.e. `blockProducer:32`) where the identifier is `blockProducer` and the length is `32 bytes`. 204 | 205 | In-memory array like structures are defined using a `name.length` property, followed by a `name:[array item size]` property. 206 | 207 | Note, `mstruct` properties allow for data chunk sizes up to 32 bytes only. 208 | 209 | ### Inheritance 210 | 211 | ```js 212 | object "Utils" { 213 | code { 214 | const Size := 1 215 | 216 | function someMethod() -> {} 217 | } 218 | } 219 | 220 | object "SimpleStore" is "Utils" { 221 | code { 222 | mstore(0, Size) 223 | someMethod() 224 | } 225 | } 226 | ``` 227 | 228 | ### Imports 229 | 230 | We now support basic file system usage, we don't support local path resolution just yet. 231 | 232 | The `fs` object is simply supplied at `compile`: `yulp.compile(source, fs)`. 233 | 234 | ```js 235 | import "./Utils.yulp" 236 | 237 | object "SimpleStore" is "Utils" { 238 | ... 239 | } 240 | ``` 241 | 242 | ### Error Reporting 243 | 244 | A new experimental (post v0.0.7) feature is the `error"some message"` literal. 245 | 246 | This simply utf8 encodes the message to bytes, keccak256 hashes it and returns the first 4 bytes as an error identifier. 247 | 248 | The compiler will return an `errors` property (`{ [4 byte idenfitier]: [error message], ... }`). 249 | 250 | ```js 251 | object "contract" { 252 | code { 253 | // example structure in memory of a BlockHeader starting at mem. position 400 254 | mstore(400, 0xaa) // block producer 255 | mstore(432, 0xbb) // previous block hash 256 | mstore(464, 0xcc) // block height 257 | mstore(496, 0x03) // length of anotherArray (i.e. 3 array items) 258 | mstore(554, 0xaaaabbbbcccc) // array with 3 elements, 0xaaaa, 0xbbbb, 0xcccc 259 | mstore(560, 0xdd) // Ethereum block number 260 | mstore(592, 0x01) // transaction roots array length 261 | mstore(652, 0xffffffff) // transaction roots, one 4 byte item 0xffffffff 262 | 263 | mstruct BlockHeader ( 264 | blockProducer: 32, 265 | previousBlockHash: 32, 266 | blockHeight: 32, 267 | anotherArray.length: 32, 268 | anotherArray: [2], 269 | ethereumBlockNumber: 32, 270 | roots.length: 32, 271 | roots: [4] 272 | ) 273 | 274 | BlockHeader.blockProducer(400) // will return 0xaa 275 | BlockHeader.blockProducer.size() // will return 32 276 | 277 | BlockHeader.blockHeight(400) // will return block height 0xcc 278 | BlockHeader.blockHeight.offset(400) // will return pos + length 279 | BlockHeader.blockHeight.position(400) // will return pos 280 | BlockHeader.blockHeight.size() // 32 281 | BlockHeader.blockHeight.index() // 2 282 | BlockHeader.blockHeight.keccak256(500) // keccak256 hash the block height 283 | 284 | BlockHeader.anotherArray(400, 2) // will return anotherArray item 0xcccc 285 | 286 | BlockHeader.size(400) // will return the size of the entire struct 287 | BlockHeader.offset(400) // will return entire offset position of the struct pos + length 288 | BlockHeader.keccak256(400) // keccak256 hash the entire block header 289 | } 290 | } 291 | ``` 292 | 293 | ## Helping Out 294 | 295 | There is always a lot of work to do, and will have many rules to maintain. So please help out in any way that you can: 296 | 297 | - Improve documentation. 298 | - Chime in on any open issue or pull request. 299 | - Open new issues about your ideas for making `yulp` better, and pull requests to show us how your idea works. 300 | - Add new tests to *absolutely anything*. 301 | - Create or contribute to ecosystem tools. 302 | - Spread the word! 303 | 304 | We communicate via [issues](https://github.com/fuellabs/yulp/issues) and [pull requests](https://github.com/fuellabs/yulp/pulls). 305 | 306 | ## Donating 307 | 308 | Please consider donating if you think Yul+ is helpful to you or that my work is valuable. We are happy if you can help us buy a cup of coffee. ❤️ 309 | 310 | - [Gitcoin grant page](https://gitcoin.co/grants/199/fuel-labs) 311 | 312 | Or just send us some *Dai*, *USDC* or *Ether*: 313 | 314 | - [**0x3e947a271a37Ae7B59921c57be0a3246Ee0d887C**](https://etherscan.io/address/0x3e947a271a37Ae7B59921c57be0a3246Ee0d887C) 315 | 316 | ## Coming Soon 317 | 318 | ```js 319 | mstruct BasicRecursiveStructures ( // better structure description 320 | block: BlockHeader, 321 | root: RootHeader, 322 | proof: MerkleProof, 323 | leaf: TransactionLeaf, 324 | token: 32 325 | ) 326 | 327 | mstruct SwitchStatements ( // special switch case 328 | data.switch: 1, // switch 0, 1, 2 for options below 329 | data: [InputUTXO,InputHTLC,TransactionDeposit] 330 | ) 331 | 332 | mstruct FixedLengthArrays ( // special switch case 333 | someArr: (7)[32], 334 | ) 335 | ``` 336 | 337 | -------------------------------------------------------------------------------- /browser/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | Yul+ - Low-Level Ethereum Devepment 4 | 5 | 6 | 7 | 8 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /browser/index.js: -------------------------------------------------------------------------------- 1 | import regeneratorRuntime from "regenerator-runtime"; 2 | import { h, app } from "hyperapp"; 3 | import { Link, Route, location, Switch } from "@hyperapp/router"; 4 | import axios from 'axios'; 5 | const { utils, Wallet } = require('ethers'); 6 | const { sendTransaction, balanceOf, call, Eth, onReceipt } = require('ethjs-extras'); 7 | const wrapper = require('solc/wrapper'); 8 | const solc = wrapper(window.Module); 9 | const yulp = require('../src/index'); 10 | 11 | // local packages.. 12 | const styled = require('./lib/styled-elements').default; 13 | 14 | // define initial app state 15 | const state = { 16 | location: location.state, 17 | error: null, 18 | bytecode: '', 19 | autoCompile: true, 20 | yulpResult: null, 21 | contracts: { 22 | 'input.yul': {} 23 | }, 24 | errors: [], 25 | }; 26 | 27 | var editor; 28 | 29 | // localmemory storage 30 | let localMemory = {}; 31 | 32 | // localstorage 33 | const local = window.localStorage || { 34 | setItem: (key, value) => Object.assign(localMemory, { [key]: value }), 35 | getItem: key => localMemory[key] || null, 36 | }; 37 | 38 | // define initial actions 39 | const actions = { 40 | location: location.actions, 41 | load: () => (state, actions) => { 42 | editor = ace.edit("editor"); 43 | editor.session.setMode("ace/mode/javascript"); 44 | editor.getSession().setUseWorker(false); 45 | 46 | editor.renderer.on('afterRender', actions.autoCompile); 47 | }, 48 | autoCompile: () => (state, actions) => { 49 | if (state.autoCompile) actions.compile(); 50 | }, 51 | compile: () => (state, actions) => { 52 | 53 | let yulpResult = null; 54 | let yulpError = null; 55 | 56 | try { 57 | yulpResult = yulp.print(yulp.compile(editor.getValue()).results); 58 | } catch (yulpErrors) { 59 | yulpError = [yulpErrors]; 60 | } 61 | 62 | var output = JSON.parse(solc.compile(JSON.stringify({ 63 | "language": "Yul", 64 | "sources": { "input.yul": { "content": yulpResult } }, // editor.getValue() 65 | "settings": { 66 | "outputSelection": { "*": { "*": ["*"], "": [ "*" ] } }, 67 | "optimizer": { "enabled": true, "details": { "yul": true } } 68 | } 69 | }))); 70 | 71 | local.setItem('code', editor.getValue()); 72 | 73 | actions.change({ 74 | contracts: output.contracts, 75 | yulpResult: yulpResult, 76 | errors: yulpError || output.errors, 77 | }); 78 | }, 79 | dark: () => (state, actions) => { 80 | var darky = !state.dark; 81 | actions.change({ dark: darky }); 82 | 83 | if (darky) { 84 | document.body.style.background = 'rgb(39, 40, 34)'; 85 | editor.setTheme("ace/theme/monokai"); 86 | } else { 87 | document.body.style.background = '#FFF'; 88 | editor.setTheme("ace/theme/textmate"); 89 | } 90 | }, 91 | change: obj => obj, 92 | }; 93 | 94 | // no operation 95 | const noop = () => {}; 96 | 97 | // provider 98 | let provider = window.ethereum || (window.web3 || {}).currentProvider; 99 | 100 | // provider.. 101 | const eth = Eth({ provider }); 102 | 103 | // server url 104 | const serverURL = 'https://api.nickpay.com'; 105 | 106 | // json params for axios 107 | const post = (url, data) => axios.post(serverURL + url, JSON.stringify(data)); 108 | 109 | // null token address 110 | const nullAddress = '0x0000000000000000000000000000000000000000'; 111 | 112 | // dai token address 113 | const daiTokenAddress = '0x89d24a6b4ccb1b6faa2625fe562bdd9a23260359'; 114 | 115 | // nickpay contract 116 | const nickpayAddress = '0xdacce757c5fc1df946ead943353cf9e3b69054e3'; 117 | 118 | // who will get the fee 119 | const feeRecipient = '0x0000000000000000000000000000000000000000'; 120 | 121 | // shorthand 122 | const keccak256 = utils.keccak256; 123 | const encodePacked = utils.solidityPack; 124 | const abiEncode = encodePacked; 125 | 126 | // lower case it 127 | const lower = v => String(v).toLowerCase(); 128 | 129 | // are you sure message for unload. 130 | window.onbeforeunload = function(e) { 131 | return 'Are you sure you want to close this tab. Data could be lost!'; 132 | }; 133 | 134 | // Not found page 135 | const NotFound = () => ( 136 |
137 |

Yulit

138 |

Hmm... Page not found

139 |
140 | ); 141 | 142 | const Code = () => (state, actions) => ( 143 |
144 |
145 |
{ 147 | local.getItem('code') || ` 148 | object "SimpleStore" { 149 | code { 150 | datacopy(0, dataoffset("Runtime"), datasize("Runtime")) 151 | return(0, datasize("Runtime")) 152 | } 153 | object "Runtime" { 154 | code { 155 | calldatacopy(0, 0, 36) 156 | 157 | mstruct Calldata( 158 | sig: 4, 159 | val: 32 160 | ) 161 | 162 | switch Calldata.sig(0) 163 | 164 | case sig"function store(uint256 val)" { 165 | sstore(0, Calldata.val(0)) 166 | } 167 | 168 | case sig"function get() returns (uint256)" { 169 | mstore(100, sload(0)) 170 | return (100, 32) 171 | } 172 | } 173 | } 174 | } 175 | `}
176 |
177 |
178 | 179 | 180 |
181 |
182 | actions.change({ autoCompile: !state.autoCompile })} /> Auto Compile 183 |
184 |
185 | actions.dark()} /> Dark 186 |
187 |
188 | 189 |
190 |
191 | 192 |

Errors

193 | {state.errors.map(v => v.formattedMessage || v.message)} 194 | 195 |

196 | 197 |

Yul Code

198 | 199 | {state.yulpResult ? ( 200 |
201 | 204 |
205 | ) : ''} 206 | 207 |

208 | 209 | {state.contracts ? Object.keys(state.contracts['input.yul']).map(contractName => (
210 |

{contractName} ({Math.round(state.contracts['input.yul'][contractName].evm.bytecode.object.length / 2)} bytes)

211 | 0x{state.contracts['input.yul'][contractName].evm.bytecode.object} 212 | 213 | 214 |
)) : ''} 215 | 216 |
217 | 218 | 219 | Yul Docs 220 | 221 | 222 | 223 | Yul+ Docs 224 | 225 | 226 |
227 |
228 |
229 | ); 230 | 231 | // routes for app 232 | const Routes = () => ( 233 | 234 | 235 | 236 | 237 | ); 238 | 239 | // main app 240 | const main = app( 241 | state, 242 | actions, 243 | Routes, 244 | document.body, 245 | ); 246 | 247 | // unsubscripe for routing 248 | const unsubscribe = location.subscribe(main.location); 249 | 250 | // change global style.. 251 | styled.injectGlobal` 252 | body { 253 | padding: 0px; 254 | margin: 0px; 255 | } 256 | 257 | input, button { 258 | font-family: Monaco, Menlo, Consolas, source-code-pro, monospace; 259 | } 260 | `; 261 | -------------------------------------------------------------------------------- /browser/lib/styled-elements/index.js: -------------------------------------------------------------------------------- 1 | const doHash = require('./lib/hash'); 2 | const { h } = require('hyperapp'); 3 | 4 | let theme = {}; 5 | let globalCSS = ''; 6 | export const docCSS = {}; 7 | export const dangerChars = [ 8 | /&/g, 9 | //g, 11 | /"/g, 12 | /'/g, 13 | // /\//g, 14 | ]; 15 | 16 | export function escapeChars(str) { 17 | let output = String(str); 18 | dangerChars.forEach(char => (output = output.replace(char, ''))); 19 | return output; 20 | } 21 | 22 | export function joinTemplate(strings, keys, state) { 23 | let output = ''; 24 | 25 | strings.forEach((str, index) => { 26 | if (keys.length >= index) { 27 | let keyValue = keys[index]; 28 | 29 | if (typeof keyValue === 'function') { 30 | keyValue = escapeChars(keyValue(state || {}) || ''); 31 | } 32 | 33 | if (typeof keyValue === 'string' && docCSS[keyValue.replace('class-', '')]) { 34 | const hash = keyValue.replace('class-', ''); 35 | keyValue = joinTemplate(docCSS[hash].strings, docCSS[hash].keys, state); 36 | } 37 | 38 | output += str + (keyValue || ''); 39 | } else { 40 | output += str; 41 | } 42 | }); 43 | 44 | return output; 45 | } 46 | 47 | export function buildName(hash, isKeyframes) { 48 | return isKeyframes ? `animation-${hash}` : `class-${hash}`; 49 | } 50 | 51 | function buildClass(className, rawCSS) { 52 | return rawCSS !== '' ? ` 53 | .${buildName(className)} { 54 | ${rawCSS.trim()} 55 | }` : ''; 56 | } 57 | 58 | function buildPseudo(className, rawCSS) { 59 | let output = ` 60 | ${rawCSS.trim()}`; 61 | output = output.replace('&', `.${buildName(className)}`); 62 | return output; 63 | } 64 | 65 | function buildQuery(className, rawCSS) { 66 | let output = rawCSS; 67 | 68 | const innerContent = output.substring(output.indexOf('{') + 1, output.lastIndexOf('}')); 69 | output = ` 70 | ${output.substring(0, output.indexOf('{') + 1)} 71 | ${buildCSS(className, innerContent).trim()} 72 | }`; 73 | 74 | return output; 75 | } 76 | 77 | function findRightEndBracketPosition(rawCSS, start, lastClose) { 78 | const openPos = rawCSS.indexOf('{', start); 79 | const closePos = rawCSS.indexOf('}', (lastClose || openPos) + 1); 80 | const secondOpenPos = rawCSS.indexOf('{', openPos + 1); 81 | 82 | if (secondOpenPos > closePos || secondOpenPos === -1) { 83 | return closePos; 84 | } 85 | 86 | return findRightEndBracketPosition(rawCSS, secondOpenPos, closePos); 87 | } 88 | 89 | function buildCSS(className, rawCSS) { 90 | let output = rawCSS; 91 | const rawPseudos = []; 92 | const rawQueries = []; 93 | 94 | const parsePseudos = () => { 95 | const start = output.indexOf('&'); 96 | const pseudo = output.substring(start, findRightEndBracketPosition(output, start) + 1); 97 | if (String(pseudo).indexOf('&') !== -1) { 98 | rawPseudos.push(pseudo); 99 | output = output.replace(pseudo, ''); 100 | parsePseudos(); 101 | } 102 | }; 103 | 104 | const parseQueries = () => { 105 | const start = output.indexOf('@media'); 106 | const query = output.substring(start, findRightEndBracketPosition(output, start) + 1); 107 | if (String(query).indexOf('@media') !== -1) { 108 | rawQueries.push(query); 109 | output = output.replace(query, ''); 110 | parseQueries(); 111 | } 112 | }; 113 | 114 | parseQueries(); 115 | parsePseudos(); 116 | 117 | output = buildClass(className, output.trim()); 118 | rawPseudos.forEach(pseudo => (output += buildPseudo(className, pseudo))); 119 | rawQueries.forEach(query => (output += buildQuery(className, query))); 120 | 121 | return output; 122 | } 123 | 124 | function buildKeyframes(hash, rawCSS) { 125 | return ` 126 | @-webkit-keyframes ${buildName(hash, true)} { 127 | ${rawCSS.trim()} 128 | } 129 | @keyframes ${buildName(hash, true)} { 130 | ${rawCSS.trim()} 131 | }`; 132 | } 133 | 134 | export function renderCSS() { 135 | let renderedCSS = ''; 136 | Object.keys(docCSS).forEach(classHash => (renderedCSS += docCSS[classHash].rendered)); 137 | return `${globalCSS}${renderedCSS}`; 138 | } 139 | 140 | function buildAndRenderCSS(strings, keys, state, isKeyframes) { 141 | const rawCSS = joinTemplate(strings, keys, state); 142 | const hash = doHash(rawCSS).toString(36); 143 | 144 | if (document.querySelector('#styles') === null) { 145 | const styleEl = document.createElement('style'); // eslint-disable-line 146 | styleEl.type = 'text/css'; 147 | styleEl.id = 'styles'; 148 | 149 | document.head.appendChild(styleEl); 150 | } 151 | 152 | if (!docCSS[hash]) { 153 | if (isKeyframes) { 154 | docCSS[hash] = { rendered: buildKeyframes(hash, rawCSS), strings, keys }; 155 | } else { 156 | docCSS[hash] = { rendered: buildCSS(hash, rawCSS), strings, keys }; 157 | } 158 | 159 | document.querySelector('#styles').innerHTML = renderCSS(); 160 | } 161 | 162 | return buildName(hash, isKeyframes); 163 | } 164 | 165 | function makeKeyframes(strings, ...keys) { 166 | return buildAndRenderCSS(strings, keys, { theme }, true); 167 | } 168 | 169 | function appendChildren(children, el) { 170 | children.forEach((child) => { 171 | if (typeof child === 'string' || typeof child === 'number') { 172 | el.appendChild(document.createTextNode(String(child))); // eslint-disable-line 173 | } else if (Array.isArray(child)) { 174 | appendChildren(child, el); 175 | } else { 176 | el.appendChild(child); 177 | } 178 | }); 179 | 180 | return el; 181 | } 182 | 183 | function makeElement(tag) { 184 | return (strings, ...keys) => (...inputChildren) => { 185 | const inputProps = inputChildren[0]; 186 | const notProps = (typeof inputProps !== 'object' 187 | || Array.isArray(inputProps) 188 | || inputProps.length === 0 189 | || (inputProps.tagName && true || false) 190 | || (inputProps.nodeName && true || false)); 191 | const elProps = notProps ? {} : inputProps; 192 | const specifiedProps = elProps.props || {}; 193 | let children = (notProps ? inputChildren : inputChildren.slice(1)) || []; 194 | 195 | if (Array.isArray(children[0])) { 196 | children = children[0]; 197 | } 198 | 199 | const className = buildAndRenderCSS(strings, keys, Object.assign({}, { theme }, elProps, specifiedProps)); 200 | 201 | 202 | const newProps = Object.assign(elProps, {}, { class: className }); 203 | delete newProps.children; 204 | 205 | return h(tag, newProps, children); 206 | }; 207 | } 208 | 209 | export default function styled(el) { 210 | return (strings, ...keys) => { 211 | const className = buildAndRenderCSS(strings, keys, { theme }); 212 | 213 | if (el.classList) { 214 | el.classList.add(className); 215 | } else { 216 | el.className += ` ${className}`; // eslint-disable-line 217 | } 218 | 219 | return el; 220 | }; 221 | } 222 | 223 | export const setTheme = styled.setTheme = selectedTheme => (theme = Object.assign({}, selectedTheme)); 224 | export const css = styled.css = (strings, ...keys) => buildAndRenderCSS(strings, keys, { theme }); 225 | export const injectGlobal = styled.injectGlobal = (strings, ...keys) => { 226 | globalCSS += joinTemplate(strings, keys, { theme }); 227 | }; 228 | 229 | export const tags = styled.tags = ['a', 'abbr', 'address', 'area', 'article', 'aside', 'audio', 'b', 230 | 'base', 'bdi', 'bdo', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 231 | 'cite', 'code', 'col', 'colgroup', 'command', 'datalist', 'dd', 'del', 'details', 232 | 'dfn', 'div', 'dl', 'doctype', 'dt', 'em', 'embed', 'fieldset', 'figcaption', 233 | 'figure', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 234 | 'hr', 'html', 'i', 'iframe', 'img', 'input', 'ins', 'kbd', 'keygen', 'label', 235 | 'legend', 'li', 'link', 'main', 'map', 'mark', 'menu', 'meta', 'meter', 'nav', 236 | 'noscript', 'object', 'ol', 'optgroup', 'option', 'output', 'p', 'param', 'pre', 237 | 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'script', 'section', 'select', 238 | 'small', 'source', 'span', 'strong', 'style', 'sub', 'summary', 'sup', 'table', 239 | 'tbody', 'td', 'textarea', 'tfoot', 'th', 'thead', 'time', 'title', 'tr', 'track', 240 | 'u', 'ul', 'var', 'video', 'wbr']; 241 | 242 | export const presets = styled.presets = { 243 | mobile: '(min-width: 400px)', 244 | Mobile: '@media (min-width: 400px)', 245 | phablet: '(min-width: 550px)', 246 | Phablet: '@media (min-width: 550px)', 247 | tablet: '(min-width: 750px)', 248 | Tablet: '@media (min-width: 750px)', 249 | desktop: '(min-width: 1000px)', 250 | Desktop: '@media (min-width: 1000px)', 251 | hd: '(min-width: 1200px)', 252 | Hd: '@media (min-width: 1200px)', 253 | }; 254 | 255 | styled.tags.forEach(tag => (styled[tag] = makeElement(tag))); 256 | export const keyframes = styled.keyframes = makeKeyframes; 257 | -------------------------------------------------------------------------------- /browser/lib/styled-elements/lib/hash.js: -------------------------------------------------------------------------------- 1 | function doHash(str, seed) { 2 | let m = 0x5bd1e995; 3 | let r = 24; 4 | let h = seed ^ str.length; 5 | let length = str.length; 6 | let currentIndex = 0; 7 | 8 | while (length >= 4) { 9 | let k = UInt32(str, currentIndex); 10 | 11 | k = Umul32(k, m); 12 | k ^= k >>> r; 13 | k = Umul32(k, m); 14 | 15 | h = Umul32(h, m); 16 | h ^= k; 17 | 18 | currentIndex += 4; 19 | length -= 4; 20 | } 21 | 22 | switch (length) { 23 | case 3: 24 | h ^= UInt16(str, currentIndex); 25 | h ^= str.charCodeAt(currentIndex + 2) << 16; 26 | h = Umul32(h, m); 27 | break 28 | 29 | case 2: 30 | h ^= UInt16(str, currentIndex); 31 | h = Umul32(h, m); 32 | break 33 | 34 | case 1: 35 | h ^= str.charCodeAt(currentIndex); 36 | h = Umul32(h, m); 37 | break 38 | } 39 | 40 | h ^= h >>> 13; 41 | h = Umul32(h, m); 42 | h ^= h >>> 15; 43 | 44 | return h >>> 0; 45 | } 46 | 47 | function UInt32(str, pos) { 48 | return (str.charCodeAt(pos++)) + 49 | (str.charCodeAt(pos++) << 8) + 50 | (str.charCodeAt(pos++) << 16) + 51 | (str.charCodeAt(pos) << 24); 52 | } 53 | 54 | function UInt16(str, pos) { 55 | return (str.charCodeAt(pos++)) + 56 | (str.charCodeAt(pos++) << 8); 57 | } 58 | 59 | function Umul32(n, m) { 60 | n = n | 0; 61 | m = m | 0; 62 | let nlo = n & 0xffff; 63 | let nhi = n >>> 16; 64 | let res = ((nlo * m) + (((nhi * m) & 0xffff) << 16)) | 0; 65 | return res; 66 | } 67 | 68 | module.exports = doHash; 69 | -------------------------------------------------------------------------------- /browser/yulp.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HowittColet/yulp/f7f48617b5ea463a990078ba1296ac14bd2d7831/browser/yulp.png -------------------------------------------------------------------------------- /browser_config/now.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "fuel-yulp", 3 | "version": 2, 4 | "builds": [ 5 | { "src": "./*.js", "use": "@now/static" }, 6 | { "src": "./*.map", "use": "@now/static" }, 7 | { "src": "./*.html", "use": "@now/static" }, 8 | { "src": "./*.svg", "use": "@now/static" }, 9 | { "src": "./*.png", "use": "@now/static" } 10 | ], 11 | "routes": [ 12 | { "src": "^/(.*)", "dest": "/$1"} 13 | ] 14 | } 15 | -------------------------------------------------------------------------------- /examples/ERC20.yulp: -------------------------------------------------------------------------------- 1 | object "ERC20" { 2 | code { 3 | enum Storage (balance, allowance) // storage index numbers 4 | 5 | // constructor(address owner, uint256 totalSupply) 6 | codecopy(64, sub(codesize(), 64), 64) 7 | 8 | // stipulate initial owner and total supply 9 | let owner := mload(64) 10 | let totalSupply := mload(96) 11 | 12 | // set initial owner balance at totalSupply 13 | mstore(0, owner, Storage.balance) 14 | sstore(keccak256(0, 64), totalSupply) 15 | 16 | // Goto runtime 17 | datacopy(0, dataoffset("Runtime"), datasize("Runtime")) 18 | return(0, datasize("Runtime")) 19 | } 20 | object "Runtime" { 21 | code { 22 | const _calldata := 128 // leave first 4 32 byte chunks for hashing, returns etc.. 23 | 24 | enum Storage (balance, allowance) // storage index numbers 25 | 26 | calldatacopy(_calldata, 0, calldatasize()) // copy all calldata to memory 27 | 28 | switch mslice(_calldata, 4) // 4 byte calldata signature 29 | 30 | case sig"transfer(address owner, uint256 amount) returns (bool success)" { 31 | mstruct transferCalldata(sig: 4, owner: 32, amount: 32) 32 | 33 | transferFrom(caller(), 34 | transferCalldata.owner(_calldata), 35 | transferCalldata.amount(_calldata)) 36 | } 37 | 38 | case sig"transferFrom(address source, address destination, uint amount) returns (bool success)" { 39 | mstruct transferFromCalldata(sig: 4, source: 32, destination: 32, amount: 32) 40 | 41 | transferFrom(transferFromCalldata.source(_calldata), 42 | transferFromCalldata.destination(_calldata), 43 | transferFromCalldata.amount(_calldata)) 44 | } 45 | 46 | case sig"approve(address destination, uint256 amount) returns (bool success)" { 47 | mstruct approveCalldata(sig: 4, destination: 32, amount: 32) 48 | 49 | sstore(mappingStorageKey2(caller(), 50 | approveCalldata.destination(_calldata), 51 | Storage.allowance), approveCalldata.amount(_calldata)) 52 | 53 | mstore(0, approveCalldata.amount(_calldata)) 54 | log3(0, 32, 55 | topic"event Approval(address indexed source, address indexed destination, uint256 amount)", 56 | caller(), 57 | approveCalldata.destination(_calldata)) 58 | 59 | mstore(0, true) 60 | return(0, 32) 61 | } 62 | 63 | case sig"balanceOf(address owner) returns (uint256 balance)" { 64 | mstruct balanceOfCalldata(sig: 4, owner: 32) 65 | 66 | mstore(0, sload(mappingStorageKey(balanceOfCalldata.owner(_calldata), 67 | Storage.balance))) 68 | return (0, 32) 69 | } 70 | 71 | case sig"allowance(address source, address owner) returns (uint256 allowance)" { 72 | mstruct allowanceCalldata(sig: 4, source: 32, owner: 32) 73 | 74 | mstore(0, sload(mappingStorageKey2(allowanceCalldata.source(_calldata), 75 | allowanceCalldata.owner(_calldata), 76 | Storage.allowance))) 77 | return (0, 32) 78 | } 79 | 80 | case sig"name() returns (string)" { 81 | // mstore(0, "Fake Dai Stablecoin") somethig like this, proper but w/ encoding. 82 | // return(0, 32) 83 | } 84 | case sig"symbol() returns (string)" { 85 | // mstore(0, "FDAI") 86 | // return(0, 32) 87 | } 88 | case sig"version() returns (string)" { 89 | // mstore(0, "1") 90 | // return(0, 32) 91 | } 92 | case sig"decimals() returns (string)" { 93 | // mstore(0, 18) 94 | // return(0, 32) 95 | } 96 | 97 | default { require(0) } // invalid method signature 98 | 99 | stop() // stop execution here.. 100 | 101 | function transferFrom(source, destination, amount) { 102 | let balanceOfSource := sload(mappingStorageKey(source, Storage.balance)) 103 | let allowanceOfDestination := sload(mappingStorageKey2(source, destination, Storage.balance)) 104 | let allowanceOfSourceSender := sload(mappingStorageKey2(source, caller(), Storage.allowance)) 105 | 106 | // require(balanceOf[src] >= wad, "Dai/insufficient-balance"); 107 | require(or(gt(balanceOfSource, amount), eq(balanceOfSource, amount))) 108 | 109 | // if (src != msg.sender && allowance[src][msg.sender] != uint(-1)) { 110 | if and(neq(source, caller()), neq(allowanceOfSourceSender, MAX_UINT)) { 111 | // require(allowance[src][msg.sender] >= wad, "Dai/insufficient-allowance"); 112 | require(gte(allowanceOfDestination, amount)) 113 | 114 | // allowance[src][msg.sender] = sub(allowance[src][msg.sender], wad); 115 | sstore(mappingStorageKey2(source, destination, Storage.balance), 116 | sub(allowanceOfDestination, amount)) 117 | } 118 | 119 | // balanceOf[src] = sub(balanceOf[src], wad); 120 | sstore(mappingStorageKey(source, Storage.balance), 121 | sub(balanceOfSource, amount)) 122 | 123 | // balanceOf[dst] = add(balanceOf[dst], wad); 124 | let balanceOfDestination := sload(mappingStorageKey(destination, Storage.balance)) 125 | sstore(mappingStorageKey(destination, Storage.balance), 126 | add(balanceOfDestination, amount)) 127 | 128 | mstore(0, amount) 129 | log3(0, 32, topic"event Transfer(address indexed source, address indexed destination, uint amount)", 130 | source, destination) 131 | 132 | mstore(0, true) 133 | return(0, 32) 134 | } 135 | 136 | // Solidity Style Storage Key: mapping(bytes32 => bytes32) 137 | function mappingStorageKey(key, storageIndex) -> storageKey { 138 | mstore(0, key, storageIndex) 139 | storageKey := keccak256(0, 64) 140 | } 141 | 142 | // Solidity Style Storage Key: mapping(bytes32 => mapping(bytes32 => bytes32) 143 | function mappingStorageKey2(key, key2, storageIndex) -> storageKey { 144 | mstore(0, key, storageIndex, key2) 145 | mstore(96, keccak256(0, 64)) 146 | storageKey := keccak256(64, 64) 147 | } 148 | } 149 | } 150 | } 151 | -------------------------------------------------------------------------------- /examples/EmptyContract.yulp: -------------------------------------------------------------------------------- 1 | object "EmptyContract" { 2 | code { 3 | 4 | // Your constructor code 5 | 6 | datacopy(0, dataoffset("Runtime"), datasize("Runtime")) 7 | return(0, datasize("Runtime")) 8 | } 9 | object "Runtime" { 10 | code { 11 | 12 | // Your runtime code 13 | 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /examples/SignatureGeneration.yulp: -------------------------------------------------------------------------------- 1 | object "contract" { 2 | code { 3 | const storeSig := sig"function store(uint256 val)" 4 | const eventSig := topic"event Store (uint256 indexed val)" 5 | 6 | log1(0, 0, storeSig) // will log 0x6057361d 7 | 8 | log1(0, 0, eventSig) // will log 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /examples/SimpleStore.yulp: -------------------------------------------------------------------------------- 1 | object "SimpleStore" { 2 | code { 3 | datacopy(0, dataoffset("Runtime"), datasize("Runtime")) 4 | return(0, datasize("Runtime")) 5 | } 6 | object "Runtime" { 7 | code { 8 | calldatacopy(0, 0, 36) // write calldata to memory 9 | 10 | mstruct Calldata( 11 | sig: 4, 12 | val: 32 13 | ) 14 | 15 | require(0, error"nick") 16 | require(311, error"nick") 17 | 18 | switch Calldata.sig(0) // select signature from memory 19 | 20 | case sig"function store(uint256 val)" { // new signature method 21 | sstore(0, Calldata.val(0)) // sstore calldata value 22 | require(311, error"nick") 23 | } 24 | 25 | case sig"function get() returns (uint256)" { 26 | mstore(100, sload(0)) 27 | return (100, 32) 28 | } 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /examples/another.yulp: -------------------------------------------------------------------------------- 1 | import "./cool.yulp" 2 | 3 | object "Another" is "Another3" { 4 | code { 5 | mstruct Nick2 ( 6 | cool: 10 7 | ) 8 | 9 | let boooo := Nick.cool(3) 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /examples/cool.yulp: -------------------------------------------------------------------------------- 1 | object "Another3" { 2 | code { 3 | mstruct Nick ( 4 | cool: 10 5 | ) 6 | 7 | let boooo := 1 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /examples/example.js: -------------------------------------------------------------------------------- 1 | const yulp = require('../src/index'); 2 | const fs = require('fs'); 3 | const source = yulp.compile(` 4 | import "./another.yulp" 5 | import "./cool.yulp" 6 | 7 | object "CoolBeans" { 8 | code { 9 | function yes() {} 10 | require(2, error"dd") 11 | } 12 | } 13 | 14 | object "YesSir" is "CoolBeans", "Another" { 15 | code { 16 | let b := add(yes(), Nick.cool(0)) 17 | function no() {} 18 | require(2, error"dd") 19 | } 20 | } 21 | 22 | object "SimpleStore" { 23 | code { 24 | datacopy(0, dataoffset("Runtime"), datasize("Runtime")) 25 | return(0, datasize("Runtime")) 26 | } 27 | object "Runtime" is "YesSir" { 28 | code { 29 | calldatacopy(0, 0, 36) // write calldata to memory 30 | 31 | mstruct Something( 32 | val: uint64, 33 | someArr1.length: bytes12, 34 | someArr1: [uint256], 35 | john2: address, 36 | someArr2.length: bytes12, 37 | someArr2: [10], 38 | cool1: address, 39 | someArr3.length: bytes12, 40 | someArr3: [bytes10] 41 | ) 42 | 43 | let address45 := 22 44 | 45 | Something.cool1(address()) 46 | Something.someArr3(0) 47 | 48 | require(2, error"nick") 49 | require(2, error"john") 50 | } 51 | } 52 | } 53 | `, fs, './examples'); 54 | 55 | const yulOutput = yulp.print(source.results); 56 | 57 | console.log(yulOutput); 58 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "yulp", 3 | "version": "0.2.3", 4 | "description": "A low-level highly-efficient language for the Ethereum Virtual Machine.", 5 | "main": "src/index.js", 6 | "scripts": { 7 | "start": "npm run build && node ./examples/example.js", 8 | "browser": "parcel browser/index.html", 9 | "build-browser": "parcel build browser/index.html && cp browser_config/now.json dist/now.json", 10 | "test": "npm run build && node ./src/index.test.js", 11 | "make-gen-dir": "mkdir -p src/gen", 12 | "build-resolve": "npm run make-gen-dir && nearleyc src/resolve.ne -o src/gen/resolve.js", 13 | "build-yul": "npm run make-gen-dir && nearleyc src/yul.ne -o src/gen/yul.js", 14 | "build-yulplus": "npm run make-gen-dir && nearleyc src/yulplus.ne -o src/gen/yulplus.js", 15 | "build": "npm run build-resolve && npm run build-yul && npm run build-yulplus", 16 | "prepublishOnly": "npm run build" 17 | }, 18 | "author": "Nick Dodson ", 19 | "license": "Apache-2.0", 20 | "optionalDependencies": { 21 | "@hyperapp/router": "^0.7.1", 22 | "axios": "^0.18.1", 23 | "ethjs-extras": "0.0.7", 24 | "hyperapp": "1.2.9", 25 | "regenerator-runtime": "0.13.2", 26 | "solc": "0.5.7" 27 | }, 28 | "dependencies": { 29 | "bn.js": "^5.0.0", 30 | "ethers": "^4.0.39", 31 | "moo": "^0.5.1", 32 | "nearley": "^2.19.0", 33 | "parse-es6-imports": "^1.0.1", 34 | "rfdc": "^1.1.4" 35 | }, 36 | "devDependencies": { 37 | "parcel": "^1.12.4", 38 | "zora": "^3.1.8" 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | const nearley = require("nearley"); 2 | const Resolve = require('./gen/resolve'); 3 | const Yulp = require('./gen/yulplus'); 4 | const Yul = require('./gen/yul'); 5 | const print = (v, isArr = Array.isArray(v)) => (isArr ? v : [v]) 6 | .map(v => Array.isArray(v) ? print(v) : (!v ? '' : v.value)).join(''); 7 | 8 | function flatDeep(input) { 9 | const stack = [...input]; 10 | const res = []; 11 | while(stack.length) { 12 | // pop value from stack 13 | const next = stack.pop(); 14 | if(Array.isArray(next)) { 15 | // push back array items, won't modify the original input 16 | stack.push(...next); 17 | } else { 18 | res.push(next); 19 | } 20 | } 21 | // reverse to restore input order 22 | return res.reverse(); 23 | } 24 | 25 | function __filter(arr, kind, prop = 'type', stopKind = 'Nothing') { 26 | var isStopKind = false; 27 | 28 | return flatDeep(arr, 10000000) 29 | .filter(v => { 30 | if (v[prop] === stopKind) { 31 | isStopKind = true; 32 | } 33 | 34 | if (isStopKind === true) { 35 | return false; 36 | } 37 | 38 | return v[prop] === kind; 39 | }); 40 | } 41 | 42 | function flatDeep(input) { 43 | const stack = [...input]; 44 | const res = []; 45 | while(stack.length) { 46 | // pop value from stack 47 | const next = stack.pop(); 48 | if(Array.isArray(next)) { 49 | // push back array items, won't modify the original input 50 | stack.push(...next); 51 | } else { 52 | res.push(next); 53 | } 54 | } 55 | // reverse to restore input order 56 | return res.reverse(); 57 | } 58 | 59 | function mapDeep(arr, f, d = 0) { 60 | return Array.isArray(arr) ? arr.map(v => mapDeep(v, f, d++)) : f(arr, d); 61 | } 62 | 63 | function _filter(arr, kind, stopKind = 'Nothing') { 64 | var isStopKind = false; 65 | 66 | return flatDeep(arr, 10000000) 67 | .filter(v => { 68 | if (v.type === stopKind) { 69 | isStopKind = true; 70 | } 71 | 72 | if (isStopKind === true) { 73 | return false; 74 | } 75 | 76 | return v.type === kind; 77 | }); 78 | } 79 | 80 | const unique = arr => [...(new Set(arr))]; 81 | 82 | const parseImports = require('parse-es6-imports'); 83 | 84 | // Export parser 85 | module.exports = { 86 | nearley, 87 | Yulp, 88 | compile: (source, fs, base = '') => { 89 | let result = null; 90 | const parserR = new nearley.Parser(Resolve); 91 | const parser = new nearley.Parser(Yulp); 92 | 93 | if (fs) { 94 | let resolvedFiles = []; 95 | let resolvedImports = {}; 96 | const path = require('path'); 97 | 98 | const resolveFiles = src => { 99 | const imports = parseImports(src); 100 | 101 | for (const file of imports) { 102 | if (resolvedFiles.indexOf(file.fromModule) === -1) { 103 | resolvedImports[file.fromModule] = resolveFiles(fs.readFileSync(path.join(base, file.fromModule), 'utf8')); 104 | } 105 | 106 | if (resolvedFiles.indexOf(file.fromModule) === -1) { 107 | resolvedFiles.push(file.fromModule); 108 | } 109 | } 110 | 111 | return src; 112 | }; 113 | 114 | const src = resolveFiles(source); 115 | const res = resolvedFiles.map(v => resolvedImports[v]).join('') + ' ' + src; 116 | 117 | // if error here, should return the whole section of code, 118 | // try { resolved == } catch (line than pull from res that line..) 119 | 120 | const resolved = parserR.feed(res); 121 | const target = mapDeep(_filter(resolved.results, 'BaseObject').slice(-1)[0].object, d => { 122 | if (d.type === 'ParsedObject') { 123 | d.value = print(d.d); 124 | } 125 | return d; 126 | }); 127 | 128 | // if error here, should return the whole section of code, 129 | // try { resolved == } catch (line than pull from res that line..) 130 | 131 | result = parser.feed(print(target)); 132 | } else { 133 | // no fs 134 | const resolved = parserR.feed(source); 135 | 136 | const base = _filter(resolved.results, 'BaseObject'); 137 | const target = base.length ? mapDeep(base.slice(-1)[0].object, d => { 138 | if (d.type === 'ParsedObject') { 139 | d.value = print(d.d); 140 | } 141 | return d; 142 | }) : []; 143 | result = parser.feed(print(target)); 144 | } 145 | 146 | const signatures = __filter(result.results, true, 'isSignature') 147 | .filter((v,i,a)=>a.findIndex(t=>(t.value === v.value)) === i) 148 | .map(v => ({ abi: v.signature, signature: v.value })); 149 | const errors = __filter(result.results, true, 'isError') 150 | .reduce((acc, v) => Object.assign(acc, { [v.message]: v.hash, [v.hash]: v.message }), {}); 151 | const topics = __filter(result.results, true, 'isTopic') 152 | .filter((v,i,a)=>a.findIndex(t=>(t.value === v.value))===i) 153 | .map(v => ({ abi: v.topic, topic: v.value })); 154 | 155 | result.signatures = signatures; 156 | result.topics = topics; 157 | result.errors = errors; 158 | 159 | return result; 160 | }, 161 | print, 162 | }; 163 | -------------------------------------------------------------------------------- /src/index.test.js: -------------------------------------------------------------------------------- 1 | const { test } = require('zora'); 2 | const { compile, print } = require('./index'); 3 | const solc = require('solc'); 4 | 5 | function yulToYulp(source, t) { 6 | t.equal(print(compile(source).results), source, 'yul to yulp'); 7 | } 8 | 9 | // Parse and Compile 10 | function yulCompile(source) { 11 | try { 12 | var output = JSON.parse(solc.compile(JSON.stringify({ 13 | language: 'Yul', 14 | sources: { 15 | 'Target.yul': { 16 | content: source, 17 | }, 18 | }, 19 | "settings": { 20 | "outputSelection": { "*": { "*": ["*"], "": [ "*" ] } }, 21 | "optimizer": { "enabled": false, "details": { "yul": true } } 22 | } 23 | }))); 24 | 25 | // is errors in compiling 26 | const isErrors = (output.errors || []) 27 | .filter(v => v.type !== 'Warning').length; 28 | 29 | if (isErrors) { 30 | return { errors: output.errors, bytecode: null }; 31 | } 32 | 33 | return { 34 | errors: null, 35 | bytecode: '0x' + output.contracts['Target.yul'].Target.evm.bytecode.object, 36 | }; 37 | } catch (error) { 38 | return { errors: error, bytecode: null }; 39 | } 40 | } 41 | 42 | test('yulp should be yul', t => { 43 | 44 | 45 | yulToYulp(`object "SimpleStore" {}`, t); 46 | yulToYulp(``, t); 47 | yulToYulp(`object "SimpleStore" { 48 | code { 49 | } 50 | }`, t); 51 | yulToYulp(`object "SimpleStore" { 52 | code { 53 | codecopy(0, 0, 0) 54 | } 55 | }`, t); 56 | yulToYulp(`object "HeyYa" { 57 | data "cool" hex"a2322" 58 | }`, t); 59 | yulToYulp(`object "SimpleStore" { 60 | code { 61 | // constructor code 62 | 63 | datacopy(0, dataoffset("Runtime"), datasize("Runtime")) // runtime code 64 | return(0, datasize("Runtime")) 65 | } 66 | object "Runtime" { 67 | code { 68 | calldatacopy(0, 0, 36) // copy calldata to memory 69 | 70 | switch and(shr(224, mload(0)), 0xffffffff) // 4 byte method signature 71 | 72 | case 0x6057361d { // store(uint256 val) 73 | sstore(0, mload(4)) 74 | } 75 | 76 | case 0x6d4ce63c { // get() returns (uint256) 77 | mstore(100, sload(0)) 78 | return (100, 32) 79 | } 80 | } 81 | } 82 | }`, t); 83 | 84 | t.equal(print(compile(` 85 | object "SimpleStore" { 86 | code { 87 | datacopy(0, dataoffset("Runtime"), datasize("Runtime")) 88 | return(0, datasize("Runtime")) 89 | } 90 | object "Runtime" { 91 | code { 92 | calldatacopy(0, 0, 36) // write calldata to memory 93 | 94 | mstruct Calldata( 95 | sig: 4, 96 | val: 32 97 | ) 98 | 99 | require(0, error"nick") 100 | require(311, error"nick") 101 | 102 | switch Calldata.sig(0) // select signature from memory 103 | 104 | case sig"function store(uint256 val)" { // new signature method 105 | sstore(0, Calldata.val(0)) // sstore calldata value 106 | require(311, error"nick") 107 | } 108 | 109 | case sig"function get() returns (uint256)" { 110 | mstore(100, sload(0)) 111 | return (100, 32) 112 | } 113 | } 114 | } 115 | } 116 | `).results), 117 | `object \"SimpleStore\" {\n code {\n datacopy(0, dataoffset(\"Runtime\"), datasize(\"Runtime\"))\n return(0, datasize(\"Runtime\"))\n }\n object \"Runtime\" {\n code {\nfunction require(arg, message) {\n if lt(arg, 1) {\n mstore(0, message)\n revert(0, 32)\n }\n}\n\nfunction mslice(position, length) -> result {\n result := div(mload(position), exp(2, sub(256, mul(length, 8))))\n}\n\n\nfunction Calldata.sig(pos) -> res {\n res := mslice(Calldata.sig.position(pos), 4)\n}\n\n\n\nfunction Calldata.sig.position(_pos) -> _offset {\n \n \n function Calldata.sig.position._chunk0(pos) -> __r {\n __r := 0x00\n }\n \n function Calldata.sig.position._chunk1(pos) -> __r {\n __r := pos\n }\n \n\n _offset := add(Calldata.sig.position._chunk0(_pos), add(Calldata.sig.position._chunk1(_pos), 0))\n \n}\n\n\n\nfunction Calldata.val(pos) -> res {\n res := mslice(Calldata.val.position(pos), 32)\n}\n\n\n\nfunction Calldata.val.position(_pos) -> _offset {\n \n \n function Calldata.val.position._chunk0(pos) -> __r {\n __r := 0x04\n }\n \n function Calldata.val.position._chunk1(pos) -> __r {\n __r := pos\n }\n \n\n _offset := add(Calldata.val.position._chunk0(_pos), add(Calldata.val.position._chunk1(_pos), 0))\n \n}\n\n\n calldatacopy(0, 0, 36) // write calldata to memory\n\n \n\n require(0, 0x01)\n require(311, 0x01)\n\n switch Calldata.sig(0) // select signature from memory\n\n case 0x6057361d { // new signature method\n sstore(0, Calldata.val(0)) // sstore calldata value\n require(311, 0x01)\n }\n\n case 0x6d4ce63c {\n mstore(100, sload(0))\n return (100, 32)\n }\n }\n }\n }`, 'const'); 118 | 119 | 120 | t.equal(print(compile(` 121 | 122 | object "Another3" { 123 | code { 124 | mstruct Nick ( 125 | cool: 10 126 | ) 127 | 128 | let boooo := 1 129 | } 130 | } 131 | 132 | object "Another" is "Another3" { 133 | code { 134 | mstruct Nick2 ( 135 | cool: 10 136 | ) 137 | 138 | let boooo := Nick.cool(3) 139 | } 140 | } 141 | 142 | `).results), 143 | `object \"Another\" {\n code {\nfunction mslice(position, length) -> result {\n result := div(mload(position), exp(2, sub(256, mul(length, 8))))\n}\n\n\nfunction Nick.cool(pos) -> res {\n res := mslice(Nick.cool.position(pos), 10)\n}\n\n\n\nfunction Nick.cool.position(_pos) -> _offset {\n \n \n function Nick.cool.position._chunk0(pos) -> __r {\n __r := 0x00\n }\n \n function Nick.cool.position._chunk1(pos) -> __r {\n __r := pos\n }\n \n\n _offset := add(Nick.cool.position._chunk0(_pos), add(Nick.cool.position._chunk1(_pos), 0))\n \n}\n\n\n \n\n let boooo := 1\n \n \n\n let boooo := Nick.cool(3)\n }\n }`, 'const'); 144 | 145 | 146 | t.equal(print(compile(` object "SimpleStore" { code { enum Color(red, blue, green) return (Color.blue, Color.green) } } `).results), 147 | `object \"SimpleStore\" { code { return (1, 2) } }`, 'const'); 148 | 149 | t.equal(print(compile(` object "SimpleStore" { code { const nick := 0 } } `).results), 150 | `object \"SimpleStore\" { code { } }`, 'const'); 151 | 152 | t.equal(print(compile(` object "SimpleStore" { code { const nick := unsafeAdd(1, 2) } } `).results), 153 | `object \"SimpleStore\" { code { let nick := add(1, 2) } }`, 'unsafe add'); 154 | 155 | t.equal(print(compile(` object "SimpleStore" { code { const nick := unsafeDiv(1, 2) } } `).results), 156 | `object \"SimpleStore\" { code { let nick := div(1, 2) } }`, 'unsafe div'); 157 | 158 | t.equal(print(compile(` object "SimpleStore" { code { const nick := unsafeMul(1, 2) } } `).results), 159 | `object \"SimpleStore\" { code { let nick := mul(1, 2) } }`, 'unsafe mul'); 160 | 161 | t.equal(print(compile(` object "SimpleStore" { code { const nick := unsafeSub(1, 2) } } `).results), 162 | `object \"SimpleStore\" { code { let nick := sub(1, 2) } }`, 'unsafe sub'); 163 | 164 | t.equal(print(compile(` object "SimpleStore" { code { require(0, error"nick") require(1, error"john") } } `).results), 165 | `object \"SimpleStore\" { code {\nfunction require(arg, message) {\n if lt(arg, 1) {\n mstore(0, message)\n revert(0, 32)\n }\n}\n require(0, 0x01) require(1, 0x02) } }`, 'const'); 166 | 167 | }); 168 | -------------------------------------------------------------------------------- /src/resolve.ne: -------------------------------------------------------------------------------- 1 | @{% 2 | 3 | // needs to comment out the other files 4 | 5 | const moo = require('moo') 6 | const { utils } = require('ethers'); 7 | const clone = require('rfdc')() // Returns the deep copy function 8 | 9 | const print = (v, isArr = Array.isArray(v)) => (isArr ? v : [v]) 10 | .map(v => Array.isArray(v) ? print(v) : (!v ? '' : v.value)).join(''); 11 | 12 | function flatDeep(input) { 13 | const stack = [...input]; 14 | const res = []; 15 | while(stack.length) { 16 | // pop value from stack 17 | const next = stack.pop(); 18 | if(Array.isArray(next)) { 19 | // push back array items, won't modify the original input 20 | stack.push(...next); 21 | } else { 22 | res.push(next); 23 | } 24 | } 25 | // reverse to restore input order 26 | return res.reverse(); 27 | } 28 | 29 | function mapDeep(arr, f, d = 0) { 30 | return Array.isArray(arr) ? arr.map(v => mapDeep(v, f, d++)) : f(arr, d); 31 | } 32 | 33 | function _filter(arr, kind, stopKind = 'Nothing') { 34 | var isStopKind = false; 35 | 36 | return flatDeep(arr, 10000000) 37 | .filter(v => { 38 | if (v.type === stopKind) { 39 | isStopKind = true; 40 | } 41 | 42 | if (isStopKind === true) { 43 | return false; 44 | } 45 | 46 | return v.type === kind; 47 | }); 48 | } 49 | 50 | let lexer = moo.compile({ 51 | space: { match: /\s+/, lineBreaks: true }, 52 | singleLineComment: /\/\/.*?$/, 53 | multiComment: /\/\*[\s\S]*?\*\/|(?:[^\\:]|^)\/\/.*$/, 54 | NumberLiteral: /(?!0x)[0-9]+/, 55 | HexLiteral: /(?:hex)(?:"|')[0-9a-fA-F]+(?:"|')/, 56 | HexNumber: /0[x][0-9a-fA-F]+/, 57 | StringLiteral: /"(?:\\["bfnrt\/\\]|\\u[a-fA-F0-9]{4}|[^"\\])*"/, 58 | equate: ":=", 59 | "->": "->", 60 | ",": ",", 61 | ":": ":", 62 | MAX_UINTLiteral: /(?:MAX_UINT)/, 63 | SigLiteral: /(?:sig)"(?:\\["bfnrt\/\\]|\\u[a-fA-F0-9]{4}|[^"\\])*"/, 64 | TopicLiteral: /(?:topic)"(?:\\["bfnrt\/\\]|\\u[a-fA-F0-9]{4}|[^"\\])*"/, 65 | ErrorLiteral: /(?:error)"(?:\\["bfnrt\/\\]|\\u[a-fA-F0-9]{4}|[^"\\])*"/, 66 | codeKeyword: /(?:code)(?:\s)/, 67 | objectKeyword: /(?:object)(?:\s)/, 68 | dataKeyword: /(?:data)(?:\s)/, 69 | boolean: ["true", "false"], 70 | bracket: ["{", "}", "(", ")", '[', ']'], 71 | ConstIdentifier: /(?:const)(?:\s)/, 72 | AddressInternalType: /(?:address)(?!\(|[a-zA-Z0-9])/, 73 | UintInternalType: /(?:uint)(?:[0-9]{1,3})(?!\(|[a-zA-Z])/, 74 | BytesInternalType: /(?:bytes)(?:[0-9]{1,3})(?!\(|[a-zA-Z])/, 75 | InternalType: ["memPtr"], 76 | keyword: ['code ', 'let', "for", "function", "enum", 77 | "mstruct", "if", "else", "break", "continue", "default", "switch", "case"], 78 | Identifier: /[\w.]+/, 79 | }); 80 | 81 | function typeToSize(type) { 82 | let size = 0; 83 | 84 | if (type.indexOf("address") !== -1) { 85 | return { type: 'NumberLiteral', value: "20", text: "20", toString: () => "20" }; 86 | } 87 | 88 | if (type.indexOf("uint") !== -1) { 89 | const value = String(parseInt(type.replace('uint', '').trim(), 10) / 8); 90 | return { type: 'NumberLiteral', value: value, text: value, toString: () => value }; 91 | } 92 | 93 | if (type.indexOf("bytes") !== -1) { 94 | const value = String(parseInt(type.replace('bytes', '').trim(), 10)); 95 | return { type: 'NumberLiteral', value: value, text: value, toString: () => value }; 96 | } 97 | } 98 | 99 | let objects = {}; 100 | %} 101 | 102 | @lexer lexer 103 | 104 | Page -> Yul {% function(d) { 105 | return mapDeep(d, v => { 106 | if (v.isCodeBlock) { 107 | let includes = []; 108 | objects[v.objectName] = { 109 | code: v.code, 110 | extends: v.objectExtends, 111 | }; 112 | 113 | const includeit = arr => { 114 | arr.map(a => { 115 | if (includes.indexOf(a) === -1) { 116 | includeit(objects[a].extends); 117 | 118 | if (includes.indexOf(a) === -1) { 119 | includes.push(a); 120 | } 121 | } 122 | }); 123 | }; 124 | includeit(v.objectExtends); 125 | 126 | v.value = print([{ value: '{' }].concat(includes.map(v => objects[v].code))); 127 | } 128 | 129 | return v; 130 | }); 131 | } %} 132 | Yul -> (_ Chunk):* _ {% function (d) { 133 | return d; 134 | } %} 135 | Chunk -> (ObjectDefinition | ImportStatement) {% function(d) { 136 | if (d[0][0][0]) { 137 | if (d[0][0][0].type === 'ParsedObject') { 138 | d[0][0][0].type = 'BaseObject'; 139 | } 140 | } 141 | 142 | return d; 143 | } %} 144 | Imports -> %StringLiteral (_ "," _ %StringLiteral):* {% function (d) { return d; } %} 145 | ImportStatement -> "import" _ %StringLiteral {% function(d) { 146 | const file = d[2].value.slice(1, -1); 147 | return { 148 | value: '', 149 | text: '', 150 | file, 151 | type: 'ImportStatement', 152 | }; 153 | } %} 154 | ObjectList -> %StringLiteral (_ "," _ %StringLiteral):* {% function(d) { 155 | return _filter(d, 'StringLiteral').map((v, i) => ({ 156 | type: 'ObjectExtends', 157 | value: '', 158 | text: '', 159 | name: v.value.slice(1, -1), 160 | })); 161 | } %} 162 | ObjectIs -> "is" {% 163 | function (d) { 164 | return { value: '', text: '', toString: () => {} }; 165 | } 166 | %} 167 | ObjectDefinition -> ((%objectKeyword _ %StringLiteral) 168 | | (%objectKeyword _ %StringLiteral _ ObjectIs _ ObjectList)) _ "{" ( _ objectStatement):* _ "}" {% 169 | function (d) { 170 | let obj = null; 171 | const _extends = _filter(d[0][0], 'ObjectExtends').map(v => v.name); 172 | const name = _filter(d[0][0], 'StringLiteral')[0].value.slice(1, -1); 173 | 174 | const _object = mapDeep(d, m => { 175 | if (obj === null && m.isCodeBlock) { 176 | m.objectName = name; 177 | m.objectExtends = _extends; 178 | obj = true; 179 | } 180 | 181 | return m; 182 | }); 183 | 184 | return [{ 185 | value: '', 186 | text: '', 187 | object: d, 188 | name, 189 | extends: _extends, 190 | type: 'ParsedObject', 191 | }].concat(d); 192 | } 193 | %} 194 | objectStatement -> CodeDefinition 195 | | DataDeclaration 196 | | ObjectDefinition 197 | DataDeclaration -> %dataKeyword _ %StringLiteral _ (%StringLiteral | %HexLiteral) 198 | CodeDefinition -> %codeKeyword _ Block {% 199 | function (d) { 200 | d[2][0].code = d[2].slice(1, -1); 201 | d[2][0].isCodeBlock = true; 202 | return d; 203 | } 204 | %} 205 | Block -> "{" _ Statement (_ Statement):* _ "}" 206 | | "{" _ "}" 207 | Switch -> "switch" _ Expression _ SwitchDefinitions 208 | SwitchDefinitions -> SwitchDefinition (_ SwitchDefinition):* 209 | MAX_UINT -> %MAX_UINTLiteral 210 | ErrorLiteral -> %ErrorLiteral 211 | SigLiteral -> %SigLiteral 212 | TopicLiteral -> %TopicLiteral 213 | Boolean -> %boolean 214 | EnumDeclaration -> "enum" _ %Identifier _ "(" _ ")" 215 | | "enum" _ %Identifier _ "(" _ IdentifierList _ ")" 216 | ForLoop -> "for" _ "{" (_ Statement):* _ "}" _ Expression _ "{" (_ Statement):* _ "}" _ Block 217 | BreakContinue -> "break" | "continue" 218 | SwitchDefinition -> Case | Default 219 | CaseLiteral -> Literal | %Identifier 220 | Case -> "case" _ CaseLiteral _ Block 221 | Default -> "default" _ Block 222 | Statement -> FunctionDefinition 223 | | FunctionCall 224 | | ForLoop 225 | | VariableDeclaration 226 | | ConstantDeclaration 227 | | MemoryStructDeclaration 228 | | EnumDeclaration 229 | | IfStatement 230 | | Assignment 231 | | Switch 232 | | BreakContinue 233 | | Block 234 | IfStatement -> "if" _ Expression _ Block 235 | NumericLiteral -> %NumberLiteral 236 | | %HexNumber 237 | | SigLiteral 238 | | ErrorLiteral 239 | | TopicLiteral 240 | Literal -> %StringLiteral 241 | | NumericLiteral 242 | | MAX_UINT 243 | Expression -> Literal 244 | | %Identifier 245 | | FunctionCall 246 | | Boolean 247 | InternalType -> (%AddressInternalType | %BytesInternalType | %UintInternalType) {% 248 | function (d) { 249 | return typeToSize(d[0][0].value); 250 | } 251 | %} 252 | ExpressionList -> "(" _ Expression ( _ "," _ Expression):* _ ")" 253 | FunctionCall -> %Identifier _ ExpressionList 254 | | %Identifier _ "(" _ ")" 255 | ArraySize -> InternalType | NumericLiteral 256 | ArraySpecifier -> "[" _ ArraySize _ "]" 257 | StructIdentifier -> %Identifier 258 | IdentifierList -> %Identifier (_ "," _ %Identifier):* 259 | MemoryStructIdentifier -> %Identifier _ ":" _ ( InternalType | StructIdentifier | NumericLiteral | ArraySpecifier ) 260 | MemoryStructList -> MemoryStructIdentifier (_ "," _ MemoryStructIdentifier):* 261 | MemoryStructDeclaration -> "mstruct" _ %Identifier _ "(" _ ")" 262 | | "mstruct" _ %Identifier _ "(" _ MemoryStructList _ ")" 263 | VariableDeclaration -> "let" _ IdentifierList _ ":=" _ Expression 264 | ConstantDeclaration -> %ConstIdentifier _ IdentifierList _ ":=" _ Expression 265 | Assignment -> IdentifierList _ ":=" _ Expression 266 | FunctionDefinition -> "function" _ %Identifier _ "(" _ IdentifierList _ ")" _ "->" _ IdentifierList _ Block 267 | | "function" _ %Identifier _ "(" _ ")" _ "->" _ IdentifierList _ Block 268 | | "function" _ %Identifier _ "(" _ ")" _ "->" _ "(" _ ")" _ Block 269 | | "function" _ %Identifier _ "(" _ IdentifierList _ ")" _ Block 270 | | "function" _ %Identifier _ "(" _ ")" _ Block 271 | Empty -> %space 272 | | %multiComment 273 | | %singleLineComment 274 | _ -> (Empty):* 275 | -------------------------------------------------------------------------------- /src/yul.ne: -------------------------------------------------------------------------------- 1 | @{% 2 | const moo = require('moo') 3 | const { utils } = require('ethers'); 4 | function id(x) { return x[0]; } 5 | 6 | let lexer = moo.compile({ 7 | space: { match: /\s+/, lineBreaks: true }, 8 | singleLineComment: /\/\/.*?$/, 9 | multiComment: /\/\*[\s\S]*?\*\/|(?:[^\\:]|^)\/\/.*$/, 10 | NumberLiteral: /(?!0x)[0-9]+/, 11 | HexLiteral: /(?:hex)(?:"|')[0-9a-fA-F]+(?:"|')/, 12 | HexNumber: /0[x][0-9a-fA-F]+/, 13 | StringLiteral: /"(?:\\["bfnrt\/\\]|\\u[a-fA-F0-9]{4}|[^"\\])*"/, 14 | ":=": ":=", 15 | "->": "->", 16 | ",": ",", 17 | codeKeyword: /(?:code)(?:\s)/, 18 | objectKeyword: /(?:object)(?:\s)/, 19 | dataKeyword: /(?:data)(?:\s)/, 20 | bracket: ["{", "}", "(", ")"], 21 | keyword: ['code', 'let', "for", "function", 22 | "if", "else", "break", "continue", "default", "switch", "case"], 23 | Identifier: /[\w]+/, 24 | }); 25 | 26 | function extractArray(d) { 27 | return d; 28 | } 29 | %} 30 | 31 | @lexer lexer 32 | 33 | Yul -> (_ Chunk):* _ {% function(d) { return d; } %} 34 | Chunk -> ObjectDefinition | CodeDefinition {% function(d) { return d; } %} 35 | ObjectDefinition -> %objectKeyword _ %StringLiteral _ "{" ( _ objectStatement):* _ "}" 36 | objectStatement -> CodeDefinition {% function(d) { return d[0]; } %} 37 | | DataDeclaration {% function(d) { return d[0]; } %} 38 | | ObjectDefinition {% function(d) { return d[0]; } %} 39 | DataDeclaration -> %dataKeyword _ %StringLiteral _ (%StringLiteral | %HexLiteral) 40 | CodeDefinition -> %codeKeyword _ Block 41 | Block -> "{" _ Statement (_ Statement):* _ "}" {% extractArray %} 42 | | "{" _ "}" {% extractArray %} 43 | Switch -> "switch" _ Expression _ SwitchDefinitions 44 | SwitchDefinitions -> SwitchDefinition (_ SwitchDefinition):* {% 45 | function(d) { 46 | const clean = d.filter(v => v); 47 | return d; 48 | } 49 | %} 50 | ForLoop -> "for" _ "{" (_ Statement):* _ "}" _ Expression _ "{" (_ Statement):* _ "}" _ Block 51 | BreakContinue -> "break" | "continue" 52 | SwitchDefinition -> Case | Default 53 | Case -> "case" _ Literal _ Block 54 | Default -> "default" _ Block 55 | Statement -> FunctionDefinition 56 | | FunctionCall 57 | | ForLoop 58 | | VariableDeclaration 59 | | IfStatement 60 | | Assignment 61 | | Switch 62 | | BreakContinue 63 | | Block 64 | IfStatement -> "if" _ Expression _ Block 65 | Literal -> %StringLiteral 66 | | %NumberLiteral 67 | | %HexNumber 68 | Expression -> Literal 69 | | %Identifier 70 | | FunctionCall 71 | FunctionCall -> %Identifier _ "(" _ Expression ( _ "," _ Expression):* _ ")" 72 | | %Identifier _ "(" _ ")" 73 | Assignment -> IdentifierList _ ":=" _ Expression 74 | IdentifierList -> %Identifier (_ "," _ %Identifier):* {% 75 | function (d) { 76 | return d; 77 | /* const clean = d.filter(v => v); 78 | return [d[0]].concat(d[1][0]).filter(v => v); 79 | */ 80 | } 81 | %} 82 | VariableDeclaration -> "let" _ IdentifierList _ ":=" _ Expression 83 | FunctionDefinition -> "function" _ %Identifier _ "(" _ IdentifierList _ ")" _ "->" _ IdentifierList _ Block 84 | | "function" _ %Identifier _ "(" _ ")" _ "->" _ IdentifierList _ Block 85 | | "function" _ %Identifier _ "(" _ ")" _ "->" _ "(" _ ")" _ Block 86 | | "function" _ %Identifier _ "(" _ IdentifierList _ ")" _ Block 87 | | "function" _ %Identifier _ "(" _ ")" _ Block 88 | Empty -> %space 89 | | %multiComment 90 | | %singleLineComment 91 | _ -> (Empty):* 92 | -------------------------------------------------------------------------------- /src/yulplus.ne: -------------------------------------------------------------------------------- 1 | @{% 2 | const moo = require('moo') 3 | const { utils } = require('ethers'); 4 | const clone = require('rfdc')() // Returns the deep copy function 5 | 6 | function id(x) { return x[0]; } 7 | 8 | let errorNonce = 0; 9 | let errorMap = {}; 10 | 11 | const print = (v, isArr = Array.isArray(v)) => (isArr ? v : [v]) 12 | .map(v => Array.isArray(v) ? print(v) : (!v ? '' : v.value)).join(''); 13 | 14 | let lexer = moo.compile({ 15 | space: { match: /\s+/, lineBreaks: true }, 16 | singleLineComment: /\/\/.*?$/, 17 | multiComment: /\/\*[\s\S]*?\*\/|(?:[^\\:]|^)\/\/.*$/, 18 | NumberLiteral: /(?!0x)[0-9]+/, 19 | HexLiteral: /(?:hex)(?:"|')[0-9a-fA-F]+(?:"|')/, 20 | HexNumber: /0[x][0-9a-fA-F]+/, 21 | StringLiteral: /"(?:\\["bfnrt\/\\]|\\u[a-fA-F0-9]{4}|[^"\\])*"/, 22 | equate: ":=", 23 | "->": "->", 24 | ",": ",", 25 | ":": ":", 26 | MAX_UINTLiteral: /(?:MAX_UINT)/, 27 | SigLiteral: /(?:sig)"(?:\\["bfnrt\/\\]|\\u[a-fA-F0-9]{4}|[^"\\])*"/, 28 | TopicLiteral: /(?:topic)"(?:\\["bfnrt\/\\]|\\u[a-fA-F0-9]{4}|[^"\\])*"/, 29 | ErrorLiteral: /(?:error)"(?:\\["bfnrt\/\\]|\\u[a-fA-F0-9]{4}|[^"\\])*"/, 30 | codeKeyword: /(?:code)(?:\s)/, 31 | objectKeyword: /(?:object)(?:\s)/, 32 | dataKeyword: /(?:data)(?:\s)/, 33 | boolean: ["true", "false"], 34 | bracket: ["{", "}", "(", ")", '[', ']'], 35 | ConstIdentifier: /(?:const)(?:\s)/, 36 | keyword: ['code ', 'let', "for", "function", "enum", "mstruct", "if", "else", "break", "continue", "default", "switch", "case"], 37 | Identifier: /[\w.]+/, 38 | }); 39 | 40 | function stringToSig(str) { 41 | const clean = str.trim(); 42 | 43 | if (clean.indexOf("event") === 0) { 44 | const inter = new utils.Interface([str]); 45 | return inter.events[Object.keys(inter.events)[0]].topic; 46 | } else { 47 | const inter = new utils.Interface([str]); 48 | 49 | // if constructor 50 | if (Object.keys(inter.functions).length === 0) { 51 | return '0x00'; 52 | } 53 | 54 | // if normal method 55 | return inter.functions[Object.keys(inter.functions)[0]].sighash; 56 | } 57 | } 58 | 59 | function flatDeep(input) { 60 | const stack = [...input]; 61 | const res = []; 62 | while(stack.length) { 63 | // pop value from stack 64 | const next = stack.pop(); 65 | if(Array.isArray(next)) { 66 | // push back array items, won't modify the original input 67 | stack.push(...next); 68 | } else { 69 | res.push(next); 70 | } 71 | } 72 | // reverse to restore input order 73 | return res.reverse(); 74 | } 75 | 76 | function mapDeep(arr, f, d = 0) { 77 | return Array.isArray(arr) ? arr.map(v => mapDeep(v, f, d++)) : f(arr, d); 78 | } 79 | 80 | function _filter(arr, kind, stopKind = 'Nothing') { 81 | var isStopKind = false; 82 | 83 | return flatDeep(arr, 10000000) 84 | .filter(v => { 85 | if (v.type === stopKind) { 86 | isStopKind = true; 87 | } 88 | 89 | if (isStopKind === true) { 90 | return false; 91 | } 92 | 93 | return v.type === kind; 94 | }); 95 | } 96 | 97 | function _filterKind(arr, kind, stopKind = null) { 98 | var isStopKind = false; 99 | 100 | return flatDeep(arr, 10000000) 101 | .filter(v => { 102 | if (v.kind === stopKind) { 103 | isStopKind = true; 104 | } 105 | 106 | if (isStopKind === true) { 107 | return false; 108 | } 109 | 110 | return v.kind === kind; 111 | }); 112 | } 113 | 114 | const stateKind = kind => d => { 115 | d[0].kind = kind; 116 | return d; 117 | } 118 | 119 | function functionCall(d) { 120 | d[0].type = 'FunctionCallIdentifier'; 121 | d[0].name = d[0].value; 122 | 123 | if (d[0].value === 'require' && d[2][3].length < 1) { 124 | const commaZero = { 125 | value: ', 0', 126 | text: ', 0', 127 | toString: () => ', 0', 128 | }; 129 | 130 | d[2][3] = commaZero; 131 | } 132 | 133 | // if mstore(0, x, x, x) args, than process this.. 134 | if (d[0].value === 'mstore' && d[2][3].length > 1) { 135 | // values after pos, x, [....] 136 | const secondaryValues = d[2][3].slice(1); 137 | 138 | // slice away the secondary values 139 | d[2][3] = d[2][3].slice(0, 1); 140 | 141 | // New injected mstores 142 | const firstMstoreArgument = print(d[2][2]); 143 | const additionalMstores = secondaryValues.map((v, i) => { 144 | 145 | const mstoreCopy = clone(d); 146 | const valOffset = (i + 1) * 32; 147 | mstoreCopy[2][2] = [ 148 | { type: 'FunctionCallIdentifier', noSafeMath: true, name: 'add', value: 'add', text: 'add', toString: () => 'add' }, 149 | [{ type: 'bracket', value: '(', text: '(', toString: () => '(' }, 150 | clone(d[2][2]), 151 | { type: 'comma', text: ',', value: ',', toString: () => ',' }, 152 | { type: 'NumberLiteral', value: valOffset, text: valOffset, toString: () => valOffset }, 153 | { type: 'bracket', value: ')', text: ')', toString: () => ')' }], 154 | ]; 155 | mstoreCopy[2][3][0] = v; 156 | 157 | return mstoreCopy; 158 | }); 159 | 160 | d = d.concat(additionalMstores 161 | .map(v => [{ type: 'space', text: ' ', value: ' ', toString: () => ' ' }].concat(v))); 162 | } 163 | 164 | return d; 165 | } 166 | 167 | function extractArray(d) { 168 | return d; 169 | } 170 | 171 | function functionDeclaration(d) { 172 | d[2].type = 'FunctionIdentifier'; 173 | return d; 174 | } 175 | 176 | function addValues(vals) { 177 | let cummulativeValue = utils.bigNumberify(0); 178 | let _vals = [0]; 179 | 180 | for (let i = 0; i < vals.length; i++) { 181 | const v = vals[i]; 182 | const isInt = Number.isInteger(v); 183 | 184 | if (v.type === 'HexLiteral' || v.type === 'NumberLiteral' || isInt) { 185 | if (isInt) { 186 | cummulativeValue = cummulativeValue.add(utils.bigNumberify(v)); 187 | } else { 188 | cummulativeValue = cummulativeValue.add(v.value); 189 | } 190 | } else { 191 | _vals.push(v); 192 | } 193 | } 194 | 195 | // Vals 196 | _vals[0] = { 197 | type: 'HexLiteral', 198 | value: cummulativeValue.toHexString(), 199 | text: cummulativeValue.toHexString(), 200 | toString: () => cummulativeValue.toHexString(), 201 | }; 202 | 203 | return _vals 204 | .map(v => `add(${v.value || v}, `) 205 | .concat(['0']) 206 | .concat(Array(_vals.length).fill(')')) 207 | .join(''); 208 | } 209 | 210 | 211 | function addValues2(vals, _name) { 212 | let cummulativeValue = utils.bigNumberify(0); 213 | let _vals = [0]; 214 | 215 | for (let i = 0; i < vals.length; i++) { 216 | const v = vals[i]; 217 | const isInt = Number.isInteger(v); 218 | 219 | if (v.type === 'HexLiteral' || v.type === 'NumberLiteral' || isInt) { 220 | if (isInt) { 221 | cummulativeValue = cummulativeValue.add(utils.bigNumberify(v)); 222 | } else { 223 | cummulativeValue = cummulativeValue.add(v.value); 224 | } 225 | } else { 226 | _vals.push(v); 227 | } 228 | } 229 | 230 | _vals[0] = { 231 | type: 'HexLiteral', 232 | value: cummulativeValue.toHexString(), 233 | text: cummulativeValue.toHexString(), 234 | toString: () => cummulativeValue.toHexString(), 235 | }; 236 | 237 | const chunks = _vals.map(v => v.value || v); 238 | const blobs = chunks.map((blob, b) => { 239 | for (let c = chunks.length; c >= 0; c--) { 240 | const chunk = chunks[c]; 241 | if (blob.indexOf(chunk) !== -1 && chunk !== blob) { 242 | return blob.replace(chunk, `${_name}._chunk${c}(pos)`); 243 | } 244 | } 245 | return blob; 246 | }); 247 | 248 | return ` 249 | ${blobs.map((v, i) => ` 250 | function ${_name}._chunk${i}(pos) -> __r { 251 | __r := ${v} 252 | } 253 | `).join('')} 254 | 255 | _offset := ${_vals.map((v, i) => `add(${_name}._chunk${i}(_pos), `) 256 | .concat(['0']) 257 | .concat(Array(_vals.length).fill(')')) 258 | .join('')} 259 | `; 260 | } 261 | 262 | const gte = ` 263 | function gte(x, y) -> result { 264 | result := iszero(lt(x, y)) 265 | } 266 | `; 267 | const lte = ` 268 | function lte(x, y) -> result { 269 | result := iszero(gt(x, y)) 270 | } 271 | `; 272 | const neq = ` 273 | function neq(x, y) -> result { 274 | result := iszero(eq(x, y)) 275 | } 276 | `; 277 | const sliceMethod = ` 278 | function mslice(position, length) -> result { 279 | result := div(mload(position), exp(2, sub(256, mul(length, 8)))) 280 | } 281 | `; 282 | const sliceObject = { 283 | value: sliceMethod, 284 | text: sliceMethod, 285 | type: 'MethodInjection', 286 | toString: () => sliceMethod, 287 | }; 288 | 289 | const requireMethod = ` 290 | function require(arg, message) { 291 | if iszero(arg) { 292 | mstore(0, message) 293 | revert(0, 32) 294 | } 295 | } 296 | `; 297 | 298 | // Include safe maths 299 | let identifierTree = {}; 300 | 301 | // idLiteral 302 | function idLiteral(x) { 303 | x[0].isLiteral = true; 304 | return x[0]; 305 | } 306 | 307 | function mstruct(d, stubs, prefix, startingPosition, parentName) { 308 | const name = prefix || d[2].value; 309 | const properties = _filter(d[6], 'MemoryStructIdentifier'); 310 | const structPropMap = properties 311 | .map((v, i) => ({ name: v.name, type: v.type, value: v.value, before: properties[i - 1] })) 312 | .filter(v => v.value.type === 'Identifier') 313 | .map(v => mstruct(stubs[v.value.value], stubs, name + '.' + v.name, v.before, name)) 314 | .reduce((acc, v) => ({ ...acc, [v.name]: { 315 | // size: name + '.' + v.name + '.size(pos)', // maybe add normal method with size specieir here.. 316 | dataMap: { ...v.dataMap, [v.name]: { 317 | size: `${v.name}.size(${v.name}.position(pos))`, 318 | method: '', 319 | required: [`${v.name}.size`, `${v.name}.position`], 320 | }}, 321 | } }), {}); 322 | 323 | const pos = startingPosition && parentName 324 | ? parentName + '.' + startingPosition.name + '.offset(pos)' 325 | : 'pos'; 326 | const posRequired = pos !== 'pos' ? [pos.slice(0, -5)] : []; 327 | 328 | let methodList = properties 329 | .map(v => name + '.' + v.name); 330 | 331 | // check for array length specifiers 332 | for (var p = 0; p < properties.length; p++) { 333 | const prop = properties[p]; 334 | 335 | if (prop.value.type === 'ArraySpecifier' 336 | && methodList.indexOf(name + '.' + prop.name + '.length') === -1) { 337 | throw new Error(`In memory struct "${name}", array property "${prop.name}" requires a ".length" property.`); 338 | } 339 | } 340 | 341 | let dataMap = properties 342 | .reduce((acc, v, i) => Object.assign(acc, 343 | v.value.type === 'Identifier' ? structPropMap[name + '.' + v.name].dataMap : { 344 | [name + '.' + v.name]: { 345 | size: v.value.type === 'ArraySpecifier' 346 | ? ('mul(' 347 | + acc[name + '.' + v.name + '.length'].slice 348 | + ', ' + v.value.value + ')') 349 | : v.value, 350 | offset: addValues(methodList.slice(0, i) 351 | .map(name => acc[name].size)), 352 | slice: `mslice(${addValues(['pos'].concat(methodList.slice(0, i) 353 | .map(name => acc[name].size)))}, ${v.value.value})`, 354 | method: v.value.type === 'ArraySpecifier' ? 355 | ` 356 | function ${name + '.' + v.name}(pos, i) -> res { 357 | res := mslice(add(${name + '.' + v.name}.position(pos), 358 | mul(i, ${v.value.value})), ${v.value.value}) 359 | } 360 | 361 | function ${name + '.' + v.name}.slice(pos) -> res { 362 | res := mslice(${name + '.' + v.name}.position(pos), 363 | ${name + '.' + v.name}.length(pos)) 364 | } 365 | ` 366 | : ` 367 | function ${name + '.' + v.name}(pos) -> res { 368 | res := mslice(${name + '.' + v.name}.position(pos), ${v.value.value}) 369 | } 370 | `, 371 | required: [ 372 | name + '.' + v.name + '.position' 373 | ].concat(v.value.type === 'ArraySpecifier' 374 | ? [name + '.' + v.name + '.length'] 375 | : []), 376 | }, 377 | [name + '.' + v.name + '.slice']: { 378 | method: v.value.type === 'ArraySpecifier' ? 379 | ` 380 | function ${name + '.' + v.name}.slice(pos) -> res { 381 | res := mslice(${name + '.' + v.name}.position(pos), ${name + '.' + v.name}.length(pos)) 382 | } 383 | ` : ``, 384 | required: [ 385 | name + '.' + v.name + '.position' 386 | ].concat(v.value.type === 'ArraySpecifier' 387 | ? [name + '.' + v.name + '.length'] 388 | : []), 389 | }, 390 | [name + '.' + v.name + '.keccak256']: { 391 | method: ` 392 | function ${name + '.' + v.name + '.keccak256'}(pos) -> _hash { 393 | _hash := keccak256(${name + '.' + v.name + '.position'}(pos), 394 | ${v.value.type === 'ArraySpecifier' 395 | ? `mul(${name + '.' + v.name + '.length'}(pos), 396 | ${name + '.' + v.name + '.size'}())` 397 | : `${name + '.' + v.name + '.size'}()`}) 398 | } 399 | `, 400 | required: [ 401 | name + '.' + v.name + '.position', 402 | name + '.' + v.name + '.size', 403 | ].concat(v.value.type === 'ArraySpecifier' 404 | ? [name + '.' + v.name + '.length'] 405 | : []), 406 | }, 407 | [name + '.' + v.name + '.position']: { 408 | method: ` 409 | function ${name + '.' + v.name + '.position'}(_pos) -> _offset { 410 | ${addValues2([pos].concat(methodList.slice(0, i) 411 | .map(name => acc[name].size)), name + '.' + v.name + '.position')} 412 | } 413 | `, 414 | required: posRequired.concat(...methodList.slice(0, i) 415 | .map(name => acc[name].required)), 416 | }, 417 | [name + '.' + v.name + '.offset']: { 418 | method: ` 419 | function ${name + '.' + v.name + '.offset'}(pos) -> _offset { 420 | ${v.value.type === 'ArraySpecifier' 421 | ? `_offset := add(${name + '.' + v.name + '.position(pos)'}, mul(${name + '.' + v.name + '.length(pos)'}, ${v.value.value}))` 422 | : `_offset := add(${name + '.' + v.name + '.position(pos)'}, ${v.value.value})`} 423 | } 424 | `, 425 | required: (v.value.type === 'ArraySpecifier' 426 | ? [name + '.' + v.name + '.length', name + '.' + v.name + '.length.position'] 427 | : []).concat([ 428 | name + '.' + v.name + '.position', 429 | ]), 430 | }, 431 | [name + '.' + v.name + '.index']: { 432 | method: ` 433 | function ${name + '.' + v.name + '.index'}() -> _index { 434 | _index := ${i} 435 | } 436 | `, 437 | required: [], 438 | }, 439 | [name + '.' + v.name + '.size']: { 440 | method: ` 441 | function ${name + '.' + v.name + '.size'}() -> _size { 442 | _size := ${v.value.value} 443 | } 444 | `, 445 | required: [], 446 | }, 447 | }), {}); 448 | 449 | dataMap[name + '.keccak256'] = { 450 | method: ` 451 | function ${name + '.keccak256'}(pos) -> _hash { 452 | _hash := keccak256(pos, ${name + '.size'}(pos)) 453 | } 454 | `, 455 | required: [name + '.size', name + '.offset'], 456 | }; 457 | 458 | dataMap[name + '.size'] = { 459 | method: ` 460 | function ${name + '.size'}(pos) -> _offset { 461 | _offset := sub(${name + '.offset'}(pos), pos) 462 | } 463 | `, 464 | required: [name + '.offset'], 465 | }; 466 | 467 | const lastOffset = methodList[methodList.length - 1] 468 | .slice(-7) === '.offset' ? '' : '.offset'; 469 | 470 | dataMap[name + '.offset'] = { 471 | method: ` 472 | function ${name + '.offset'}(pos) -> _offset { 473 | _offset := ${methodList.length 474 | ? methodList[methodList.length - 1] + '.offset(pos)' : '0'} 475 | } 476 | `, 477 | required: methodList.length > 0 478 | ? [methodList[methodList.length - 1] + '.offset'] 479 | .concat(dataMap[methodList[methodList.length - 1] + lastOffset].required) 480 | : [], 481 | }; 482 | 483 | dataMap[name + '.position'] = { 484 | method: ` 485 | function ${name + '.position'}(pos) -> _offset { 486 | _offset := ${pos} 487 | } 488 | `, 489 | required: [], 490 | }; 491 | 492 | return { 493 | type: 'MemoryStructDeclaration', 494 | name, 495 | dataMap, 496 | value: '', 497 | text: '', 498 | line: d[2].line, 499 | toString: () => '', 500 | }; 501 | } 502 | %} 503 | 504 | @lexer lexer 505 | 506 | Yul -> (_ Chunk):* _ {% function(d) { return d; } %} 507 | Chunk -> ObjectDefinition | CodeDefinition {% function(d) { return d; } %} 508 | ObjectList -> %StringLiteral (_ "," _ %StringLiteral):* {% extractArray %} 509 | ObjectDefinition -> ((%objectKeyword _ %StringLiteral) | (%objectKeyword _ %StringLiteral _ "is" _ ObjectList)) _ "{" ( _ objectStatement):* _ "}" 510 | objectStatement -> CodeDefinition {% function(d) { return d[0]; } %} 511 | | DataDeclaration {% function(d) { return d[0]; } %} 512 | | ObjectDefinition {% function(d) { return d[0]; } %} 513 | DataDeclaration -> %dataKeyword _ %StringLiteral _ (%StringLiteral | %HexLiteral) 514 | CodeDefinition -> %codeKeyword _ Block {% 515 | function (d) { 516 | // Inject slice method 517 | const functionCalls = _filter(d, 'FunctionCallIdentifier'); 518 | const usesSlice = functionCalls 519 | .filter(v => v.value === 'mslice' || v._includeMarker === 'mslice') 520 | .length > 0; 521 | let usesRequire = functionCalls 522 | .filter(v => v.usesRequire === true) 523 | .length > 0; 524 | const usesMath = functionCalls 525 | .filter(v => v.usesSafeMath === true) 526 | .length > 0; 527 | let __methodToInclude = {}; 528 | 529 | // gte 530 | if (functionCalls 531 | .filter(v => v.usesGTE === true) 532 | .length > 0) { 533 | __methodToInclude['gte'] = gte; 534 | } 535 | 536 | // lte 537 | if (functionCalls 538 | .filter(v => v.usesLTE === true) 539 | .length > 0) { 540 | __methodToInclude['lte'] = lte; 541 | } 542 | 543 | // NEQ 544 | if (functionCalls 545 | .filter(v => v.usesNEQ === true) 546 | .length > 0) { 547 | __methodToInclude['neq'] = neq; 548 | } 549 | 550 | if (usesMath) { 551 | usesRequire = true; 552 | __methodToInclude['safeAdd'] = ` 553 | function safeAdd(x, y) -> z { 554 | z := add(x, y) 555 | require(or(eq(z, x), gt(z, x)), 0) 556 | } 557 | `; 558 | 559 | __methodToInclude['safeSub'] = ` 560 | function safeSub(x, y) -> z { 561 | z := sub(x, y) 562 | require(or(eq(z, x), lt(z, x)), 0) 563 | } 564 | `; 565 | 566 | __methodToInclude['safeMul'] = ` 567 | function safeMul(x, y) -> z { 568 | if gt(y, 0) { 569 | z := mul(x, y) 570 | require(eq(div(z, y), x), 0) 571 | } 572 | } 573 | `; 574 | 575 | __methodToInclude['safeDiv'] = ` 576 | function safeDiv(x, y) -> z { 577 | require(gt(y, 0), 0) 578 | z := div(x, y) 579 | } 580 | `; 581 | } 582 | 583 | if (usesRequire) { 584 | __methodToInclude['require'] = requireMethod; 585 | } 586 | 587 | if (usesSlice) { 588 | d[2].splice(2, 0, sliceObject); 589 | } 590 | 591 | d[2].splice(2, 0, Object.keys(__methodToInclude) 592 | .map(key => ({ 593 | type: 'InjectedMethod', 594 | value: __methodToInclude[key], 595 | text: __methodToInclude[key], 596 | toString: () => __methodToInclude[key], 597 | }))); 598 | 599 | return d; 600 | } 601 | %} 602 | Block -> "{" _ Statement (_ Statement):* _ "}" {% function(d, l) { 603 | const blockId = d[0].line + '.' + d[0].col; 604 | const currentBlock = identifierTree[blockId] = { 605 | type: 'Block', 606 | id: blockId, 607 | value: ``, // `/* ${blockId} */`, 608 | }; 609 | 610 | // Scan for enums and constant declarations 611 | const enums = _filter(d, 'Enum') 612 | .reduce((acc, v) => Object.assign(acc, v.dataMap), {}); 613 | const constants = _filter(d, 'Constant') 614 | .reduce((acc, v) => Object.assign(acc, v.dataMap), {}); 615 | let mstructs = _filter(d, 'MemoryStructDeclaration') 616 | .reduce((acc, v) => Object.assign(acc, v.dataMap), {}); 617 | let methodToInclude = {}; 618 | let stubs = {}; 619 | const duplicateChecks = {}; 620 | let err = null; 621 | const dubcheck = (_type, v) => { 622 | if (typeof duplicateChecks[_type + v.name] === 'undefined') { 623 | duplicateChecks[_type + v.name] = v; 624 | } else { 625 | throw new Error(`${_type} already declared with the same identifier "${v.name}" on line ${duplicateChecks[_type + v.name].line} and ${v.line}. All ${_type} must have the unique names. Scoping coming soon.`); 626 | } 627 | }; 628 | let replaceLiterals = {}; 629 | 630 | let _map = mapDeep(d, v => { 631 | if (err) { throw new Error(err) } 632 | 633 | if (v.type === 'MemoryStructStub') { 634 | const struc = mstruct(v.d, stubs); 635 | v.type = 'MemoryStructDeclaration'; 636 | v.name = struc.name; 637 | v.dataMap = struc.dataMap; 638 | v.value = struc.value; 639 | v.text = struc.text; 640 | v.line = struc.line; 641 | v.toString = struc.toString; 642 | mstructs = { ...mstructs, ...v.dataMap }; 643 | stubs = { ...stubs, [v.name]: v.d }; 644 | } 645 | 646 | // We have now set within this block context, this enum to Used 647 | if (v.type === 'Enum') { 648 | v.type = 'UsedEnum'; 649 | } 650 | 651 | if (v.type === 'UsedEnum') { 652 | dubcheck('Enum', v); 653 | } 654 | 655 | // Set constants in context to used 656 | if (v.type === 'Constant') { 657 | v.type = 'UsedConstant'; 658 | 659 | if (v.__value.isLiteral) { 660 | Object.keys(v.dataMap).map(identifier => { 661 | enums[identifier] = v.__value.value; 662 | }); 663 | } 664 | } 665 | 666 | if (v.type === 'UsedConstant') { 667 | for (let vi = 0; vi < v.__itendifiers.length; vi++) { 668 | // currentBlock.identifiers.push(v.__itendifiers[vi]); 669 | 670 | dubcheck('Constant', Object.assign(v, { 671 | name: v.__itendifiers[vi], 672 | })); 673 | } 674 | } 675 | 676 | // Used now.. 677 | if (v.type === 'MemoryStructDeclaration') { 678 | v.type = 'UsedMemoryStructDeclaration'; 679 | } 680 | 681 | if (v.type === 'UsedMemoryStructDeclaration') { 682 | dubcheck('MemoryStructDeclaration', v); 683 | } 684 | 685 | // Check for constant re-assignments 686 | if (v.type === 'Assignment') { 687 | for (var i = 0; i < v._identifiers.length; i++) { 688 | if (typeof constants[v._identifiers[i].value] !== 'undefined') { 689 | throw new Error(`Constant re-assignment '${v._identifiers[i].value}' to '${print(v._value)}' at line ${v.line}`); 690 | } 691 | } 692 | } 693 | 694 | // Replace enums 695 | if (v.type === 'Identifier' 696 | && typeof enums[v.value] !== "undefined") { 697 | 698 | // Replace out enums 699 | v.type = 'Literal'; 700 | v.value = enums[v.value]; 701 | v.text = enums[v.value]; 702 | } 703 | 704 | if (v.type === 'FunctionCallIdentifier' 705 | && typeof mstructs[v.name] !== 'undefined') { 706 | methodToInclude[v.name] = "\n" + mstructs[v.name].method + "\n"; 707 | 708 | // recursive get require 709 | const getRequired = required => { 710 | // include the required methods from the struct 711 | for (var im = 0; im < required.length; im++) { 712 | const requiredMethodName = required[im]; 713 | 714 | // this has to be recursive for arrays etc.. 715 | methodToInclude[requiredMethodName] = "\n" 716 | + mstructs[requiredMethodName].method 717 | + "\n"; 718 | 719 | for (var i = 0; i < mstructs[requiredMethodName].required.length; i++) { 720 | const reqName = mstructs[requiredMethodName].required[i]; 721 | const req = methodToInclude[reqName]; 722 | if (typeof req === 'undefined') { 723 | getRequired([reqName]); 724 | } 725 | } 726 | } 727 | }; 728 | 729 | // get required.. 730 | for (var i = 0; i < mstructs[v.name].required.length; i++) { 731 | const reqName = mstructs[v.name].required[i]; 732 | const req = methodToInclude[reqName]; 733 | if (typeof req === 'undefined') { 734 | getRequired([reqName]); 735 | } 736 | } 737 | } 738 | 739 | if (v.type === 'FunctionCallIdentifier' 740 | && v.name === 'lte') { 741 | v.usesLTE = true; 742 | } 743 | 744 | if (v.type === 'FunctionCallIdentifier' 745 | && v.name === 'gte') { 746 | v.usesGTE = true; 747 | } 748 | 749 | if (v.type === 'FunctionCallIdentifier' 750 | && v.name === 'neq') { 751 | v.usesNEQ = true; 752 | } 753 | 754 | // Safe Math Multiply 755 | if (v.type === 'FunctionCallIdentifier' 756 | && v.name === 'require') { 757 | v.usesRequire = true; 758 | } 759 | 760 | if (v.type === 'FunctionCallIdentifier' 761 | && v.name === 'unsafeAdd') { 762 | v.text = 'add'; 763 | v.value = 'add'; 764 | v.toString = () => 'add'; 765 | } 766 | 767 | if (v.type === 'FunctionCallIdentifier' 768 | && v.name === 'unsafeMul') { 769 | v.text = 'mul'; 770 | v.value = 'mul'; 771 | v.toString = () => 'mul'; 772 | } 773 | 774 | if (v.type === 'FunctionCallIdentifier' 775 | && v.name === 'unsafeDiv') { 776 | v.text = 'div'; 777 | v.value = 'div'; 778 | v.toString = () => 'div'; 779 | } 780 | 781 | if (v.type === 'FunctionCallIdentifier' 782 | && v.name === 'unsafeSub') { 783 | v.text = 'sub'; 784 | v.value = 'sub'; 785 | v.toString = () => 'sub'; 786 | } 787 | 788 | if (v.type === 'FunctionCallIdentifier' 789 | && v.name === 'add' 790 | && !v.noSafeMath) { 791 | v.text = 'safeAdd'; 792 | v.value = 'safeAdd'; 793 | v.usesSafeMath = true; 794 | } 795 | 796 | if (v.type === 'FunctionCallIdentifier' 797 | && v.name === 'sub') { 798 | v.text = 'safeSub'; 799 | v.value = 'safeSub'; 800 | v.usesSafeMath = true; 801 | } 802 | 803 | if (v.type === 'FunctionCallIdentifier' 804 | && v.name === 'mul') { 805 | v.text = 'safeMul'; 806 | v.value = 'safeMul'; 807 | v.usesSafeMath = true; 808 | } 809 | 810 | if (v.type === 'FunctionCallIdentifier' 811 | && v.name === 'div') { 812 | v.text = 'safeDiv'; 813 | v.value = 'safeDiv'; 814 | v.usesSafeMath = true; 815 | } 816 | 817 | // Return object 818 | return v; 819 | }); 820 | 821 | // inject mslice if any mstruct method used. 822 | if (Object.keys(methodToInclude).length > 0) { 823 | _map.splice(2, 0, { 824 | type: 'FunctionCallIdentifier', 825 | value: '', 826 | text: '', 827 | _includeMarker: 'mslice', 828 | toString: () => '', 829 | }); 830 | } 831 | 832 | // set secondary kind of first element to Block 833 | _map.splice(0, 0, currentBlock); 834 | 835 | // add methods to include 836 | _map.splice(2, 0, Object.keys(methodToInclude) 837 | .map(key => ({ 838 | type: 'InjectedMstructMethod', 839 | value: methodToInclude[key], 840 | text: methodToInclude[key], 841 | toString: () => methodToInclude[key], 842 | }))); 843 | 844 | return _map; 845 | } %} 846 | | "{" _ "}" {% extractArray %} 847 | Switch -> "switch" _ Expression _ SwitchDefinitions 848 | SwitchDefinitions -> SwitchDefinition (_ SwitchDefinition):* {% 849 | function(d) { 850 | const clean = d.filter(v => v); 851 | return d; 852 | } 853 | %} 854 | MAX_UINT -> %MAX_UINTLiteral {% 855 | function(d) { 856 | const val = '0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'; 857 | return { type: 'HexNumber', value: val, text: val }; 858 | } 859 | %} 860 | ErrorLiteral -> %ErrorLiteral {% 861 | function(d) { 862 | const message = d[0].value.trim().slice(6).slice(0, -1); 863 | let bytes4ErrorHash = null; 864 | 865 | if (errorMap[message]) { 866 | bytes4ErrorHash = errorMap[message]; 867 | } else { 868 | errorNonce += 1; 869 | bytes4ErrorHash = utils.bigNumberify(errorNonce).toHexString(); 870 | errorMap[message] = bytes4ErrorHash; 871 | } 872 | 873 | // const bytes4ErrorHash = utils.keccak256(utils.toUtf8Bytes(message)).slice(0, 10); // remove error" and " 874 | return { type: 'HexNumber', 875 | isError: true, 876 | hash: bytes4ErrorHash, 877 | message, 878 | value: bytes4ErrorHash, 879 | text: bytes4ErrorHash, 880 | }; 881 | } 882 | %} 883 | SigLiteral -> %SigLiteral {% 884 | function(d) { 885 | const sig = stringToSig(d[0].value.trim().slice(4).slice(0, -1)); // remove sig" and " 886 | 887 | return { type: 'HexNumber', 888 | isSignature: true, 889 | signature: d[0].value.trim(), 890 | value: sig, 891 | text: sig, 892 | }; 893 | } 894 | %} 895 | TopicLiteral -> %TopicLiteral {% 896 | function(d) { 897 | const sig = stringToSig(d[0].value.trim().slice(6, -1)); 898 | return { 899 | type: 'HexNumber', 900 | isTopic: true, 901 | topic: d[0].value.trim(), 902 | value: sig, 903 | text: sig, 904 | }; 905 | } 906 | %} 907 | Boolean -> %boolean {% function(d) { 908 | if (d[0].value === "true") { 909 | return { type: 'HexNumber', value: '0x01', text: '0x01' }; 910 | } else { 911 | return { type: 'HexNumber', value: '0x00', text: '0x00' }; 912 | } 913 | } %} 914 | EnumDeclaration -> "enum" _ %Identifier _ "(" _ ")" {% 915 | function (d) { 916 | return {}; 917 | } 918 | %} 919 | | "enum" _ %Identifier _ "(" _ IdentifierList _ ")" {% 920 | function (d) { 921 | const ids = _filter(d, 'Identifier'); 922 | const name = ids[0].value; 923 | const markers = ids.slice(1); 924 | const dataMap = markers 925 | .reduce((acc, v, i) => Object.assign(acc, { 926 | [name + '.' + v]: i, 927 | }), {}); 928 | 929 | return { 930 | type: 'Enum', 931 | value: '', 932 | text: '', 933 | ids, 934 | name, 935 | markers, 936 | line: ids[0].line, 937 | toString: () => '', 938 | dataMap, 939 | }; 940 | } 941 | %} 942 | ForLoop -> "for" _ "{" (_ Statement):* _ "}" _ Expression _ "{" (_ Statement):* _ "}" _ Block 943 | BreakContinue -> "break" | "continue" 944 | SwitchDefinition -> Case | Default 945 | CaseLiteral -> Literal | %Identifier 946 | Case -> "case" _ CaseLiteral _ Block 947 | Default -> "default" _ Block 948 | Statement -> FunctionDefinition 949 | | FunctionCall 950 | | ForLoop 951 | | VariableDeclaration 952 | | ConstantDeclaration 953 | | MemoryStructDeclaration 954 | | EnumDeclaration 955 | | IfStatement 956 | | Assignment 957 | | Switch 958 | | BreakContinue 959 | | Block 960 | IfStatement -> "if" _ Expression _ Block 961 | NumericLiteral -> %NumberLiteral {% id %} 962 | | %HexNumber {% id %} 963 | | SigLiteral {% id %} 964 | | ErrorLiteral {% id %} 965 | | TopicLiteral {% id %} 966 | Literal -> %StringLiteral {% idLiteral %} 967 | | NumericLiteral {% idLiteral %} 968 | | MAX_UINT {% idLiteral %} 969 | Expression -> Literal {% id %} 970 | | %Identifier {% id %} 971 | | FunctionCall {% id %} 972 | | Boolean {% id %} 973 | ExpressionList -> "(" _ Expression ( _ "," _ Expression):* _ ")" 974 | FunctionCall -> %Identifier _ ExpressionList {% functionCall %} 975 | | %Identifier _ "(" _ ")" {% functionCall %} 976 | ArraySpecifier -> "[" _ NumericLiteral _ "]" {% 977 | function (d) { 978 | return { 979 | type: 'ArraySpecifier', 980 | value: d[2].value, 981 | text: d[2].value, 982 | }; 983 | } 984 | %} 985 | StructIdentifier -> %Identifier {% id %} 986 | IdentifierList -> %Identifier (_ "," _ %Identifier):* {% extractArray %} 987 | MemoryStructIdentifier -> %Identifier _ ":" _ ( StructIdentifier | NumericLiteral | ArraySpecifier ) {% 988 | function (d) { 989 | return { 990 | type: 'MemoryStructIdentifier', 991 | name: d[0].value, 992 | value: d[4][0], 993 | }; 994 | } 995 | %} 996 | MemoryStructList -> MemoryStructIdentifier (_ "," _ MemoryStructIdentifier):* {% extractArray %} 997 | MemoryStructDeclaration -> "mstruct" _ %Identifier _ "(" _ ")" {% function(d) { 998 | return { 999 | type: 'MemoryStructDeclaration', 1000 | name: d[2].value, 1001 | dataMap: {}, 1002 | value: '', 1003 | text: '', 1004 | line: d[2].line, 1005 | toString: () => '', 1006 | }; 1007 | } %} 1008 | | "mstruct" _ %Identifier _ "(" _ MemoryStructList _ ")" {% 1009 | function (d) { 1010 | return { 1011 | type: 'MemoryStructStub', 1012 | d, 1013 | value: '', 1014 | text: '', 1015 | line: d[2].line, 1016 | toString: () => '', 1017 | }; 1018 | } 1019 | %} 1020 | VariableDeclaration -> "let" _ IdentifierList _ ":=" _ Expression 1021 | ConstantDeclaration -> %ConstIdentifier _ IdentifierList _ ":=" _ Expression {% 1022 | function (d) { 1023 | // Change const to let 1024 | d[0].value = 'let '; 1025 | d[0].text = 'let '; 1026 | d[0].type = 'Constant'; 1027 | d[0].__itendifiers = _filter(d, 'Identifier', 'equate') 1028 | .map(v => v.value); 1029 | d[0].__value = d[6]; 1030 | d[0].dataMap = d[0].__itendifiers.reduce((acc, v) => Object.assign(acc, { 1031 | [v]: d[0].__value, 1032 | }), {}); 1033 | d.__constant = true; 1034 | 1035 | // if its a literal, we move for a global replacement block > 1036 | if (d[0].__value.isLiteral) { 1037 | d[0].value = ''; 1038 | d[0].text = ''; 1039 | return d[0]; 1040 | } 1041 | 1042 | return d; 1043 | } 1044 | %} 1045 | Assignment -> IdentifierList _ ":=" _ Expression {% 1046 | function (d) { 1047 | d[0][0]._identifiers = _filter(d[0], 'Identifier'); 1048 | d[0][0].type = 'Assignment'; 1049 | d[0][0]._value = d[4]; 1050 | return d; 1051 | } 1052 | %} 1053 | FunctionDefinition -> "function" _ %Identifier _ "(" _ IdentifierList _ ")" _ "->" _ IdentifierList _ Block {% functionDeclaration %} 1054 | | "function" _ %Identifier _ "(" _ ")" _ "->" _ IdentifierList _ Block {% functionDeclaration %} 1055 | | "function" _ %Identifier _ "(" _ ")" _ "->" _ "(" _ ")" _ Block {% functionDeclaration %} 1056 | | "function" _ %Identifier _ "(" _ IdentifierList _ ")" _ Block {% functionDeclaration %} 1057 | | "function" _ %Identifier _ "(" _ ")" _ Block {% functionDeclaration %} 1058 | Empty -> %space 1059 | | %multiComment 1060 | | %singleLineComment 1061 | _ -> (Empty):* 1062 | --------------------------------------------------------------------------------